hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a7d1178ed445c78a9efa24ccb4d69370516664bc | 3,012 | cpp | C++ | EngineLib/Camera.cpp | annahayhurst/procedural-terrain-generator | fb110b4307007a8ffd34097148c495584db1c085 | [
"Zlib"
] | 1 | 2021-02-01T08:12:49.000Z | 2021-02-01T08:12:49.000Z | EngineLib/Camera.cpp | annahayhurst/procedural-terrain-generator | fb110b4307007a8ffd34097148c495584db1c085 | [
"Zlib"
] | 18 | 2020-05-22T14:15:01.000Z | 2020-07-16T17:52:26.000Z | EngineLib/Camera.cpp | annahayhurst/procedural-terrain-generator | fb110b4307007a8ffd34097148c495584db1c085 | [
"Zlib"
] | null | null | null | #include "Camera.h"
#include <iostream>
namespace Engine {
// Constructor with parameters
Camera::Camera(vec3 position, vec3 up, GLfloat yaw, GLfloat pitch, GLfloat moveSpeed, GLfloat turnSpeed) :
position(position), worldUp(up), front(vec3(0.0f, 0.0f, -1.0f)),
yaw(yaw), pitch(pitch),
moveSpeed(moveSpeed), turnSpeed(turnSpeed) {
calculateDirection();
}
// The view matrix translates our perspective from world-space to view-space
glm::mat4 Camera::getViewMatrix() {
// Eye position | center | up
// position + front = the target, i.e. what we are looking at
return glm::lookAt(position, position + front, up);
}
// Set the current camera position in the uniform found in the fragment shader
void Camera::updateUniformPosition(Shader* shader) {
glUniform3f(shader->getCameraPositionUL(), this->getPosition().x, this->getPosition().y, this->getPosition().z);
}
// Assign camera navigation to WASD/up-left-down-right. Makes use of dT to move at appropriate speed
void Camera::keyControl(bool* keys, GLfloat dT) {
// Speed of camera movement relative to change in time
GLfloat velocity = moveSpeed * dT;
if (keys[GLFW_KEY_W]) {
position += front * velocity; // move relative to where the "front" of the camera faces
}
if (keys[GLFW_KEY_S] || keys[GLFW_KEY_DOWN]) {
position -= front * velocity;
}
if (keys[GLFW_KEY_A] || keys[GLFW_KEY_LEFT]) {
position -= right * velocity; // move relative to where the "right" of the camera is
}
if (keys[GLFW_KEY_D] || keys[GLFW_KEY_RIGHT]) {
position += right * velocity;
}
if (keys[GLFW_KEY_SPACE] || keys[GLFW_KEY_UP]) {
position += vec3(0.f, 2.5f, 0.f) * velocity; // ascend vertically
}
if (keys[GLFW_KEY_DOWN]) {
position -= vec3(0.f, 2.5f, 0.f) * velocity; // descend vertically
}
if (keys[GLFW_KEY_Q]) {
std::cout << front.x << " " << front.y << " " << front.z << "\n";
}
}
// Allow change of angle using mouse movement - depending on turn speed
// Pitch and yaw are used to change camera directions
void Camera::mouseControl(GLdouble dX, GLdouble dY) {
dX *= turnSpeed;
dY *= turnSpeed;
yaw += (GLfloat)dX;
pitch += (GLfloat)dY;
// Restrict angles to <90 to avoid visual anomalies
if (pitch >= 90.0f) {
pitch = 89.0f;
}
else if (pitch <= -90.0f) {
pitch = -89.0f;
}
calculateDirection();
}
// Update the front, right and up vectors using current angles
void Camera::calculateDirection() {
front.x = cos(radians(yaw)) * cos(radians(pitch));
front.y = sin(radians(pitch)); // y direction doesn't depend on yaw
front.z = sin(radians(yaw)) * cos(radians(pitch));
front = glm::normalize(front); // create a unit vector from (x, y, z) to get current direction
// The right is a cross product between front (just calculated) and the reference world up
right = glm::normalize(glm::cross(front, worldUp));
// The relative up direction is a cross product between right and front
up = glm::normalize(glm::cross(right, front));
}
}
| 32.042553 | 114 | 0.677623 | [
"vector"
] |
a7d3d243b1e1945a9b378ccacc76ae0c0b65bbeb | 15,121 | cpp | C++ | LPsolver_v1.5/pgCbc/libPgCbc.cpp | aau-daisy/solvedb | 8a15559b5a08747b2217d9146e3dd122379d4de1 | [
"Apache-2.0"
] | 12 | 2017-12-06T10:39:21.000Z | 2021-02-18T13:43:35.000Z | LPsolver_v1.5/pgCbc/libPgCbc.cpp | aau-daisy/solvedb | 8a15559b5a08747b2217d9146e3dd122379d4de1 | [
"Apache-2.0"
] | 3 | 2017-05-17T13:38:36.000Z | 2020-06-27T17:50:40.000Z | LPsolver_v1.5/pgCbc/libPgCbc.cpp | aau-daisy/solvedb | 8a15559b5a08747b2217d9146e3dd122379d4de1 | [
"Apache-2.0"
] | 2 | 2020-02-16T12:47:07.000Z | 2021-02-18T13:43:36.000Z | /*
Copyright (C) 2004-2007 EPRI Corporation and others. All Rights Reserved.
This code is licensed under the terms of the Eclipse Public License (EPL).
$Id: cbc_driverC_sos.c 1902 2013-04-10 16:58:16Z stefan $
*/
/* This example shows the use of the "C" interface for CBC. */
#include "libPgCbc.h"
#include "miscadmin.h"
#include "utils/elog.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <ostream>
#include <sstream>
#include <streambuf>
#include <sstream>
#include <cmath>
#include <exception>
#include <typeinfo>
#include <stdexcept>
// Using CLP as the solver
#include "CbcOrClpParam.hpp"
#include "OsiClpSolverInterface.hpp"
#include "CbcModel.hpp"
#include "CbcSolver.hpp"
#include "CoinBuild.hpp"
#include "CbcStrategy.hpp"
#include "CbcHeuristic.hpp"
#include "CoinMessageHandler.hpp"
#include "CoinHelperFunctions.hpp"
#include "CoinError.hpp"
// For time measurements
#include <sys/time.h> /* For performance benchmarking */
/* A type of function */
typedef enum {
LPfunctionEmpty, /* Function does not containt variables */
LPfunctionFloat, /* Function contains only float variables */
LPfunctionInteger, /* Function contains only integer variables */
LPfunctionBool, /* Function contains only boolean variables */
LPfunctionMixed /* Function contains variables of mixed types */
} LPfunctionType;
// To allow stdio redirection
class SolverLP_MessageHandler : public CoinMessageHandler {
public:
virtual int print();
/** Default constructor. */
SolverLP_MessageHandler();
/** Destructor */
virtual ~SolverLP_MessageHandler();
/// Clone
virtual CoinMessageHandler * clone() const ;
};
class SolverLP_Streambuf: public std::basic_streambuf< char,std::char_traits<char> >
{
typedef std::basic_streambuf<char, std::char_traits<char> >::int_type int_type;
typedef std::char_traits<char> traits_t;
int_type overflow( int_type c )
{
//std::cerr << traits_t::to_char_type( c ) << traits_t::to_char_type( c );
appendStringInfoChar(&buf, c);
if (c == '\n') {
ErrorContextCallback * old_error_context = error_context_stack;
error_context_stack = NULL;
ereport(NOTICE, (errmsg("%s", buf.data)));
error_context_stack = old_error_context;
resetStringInfo(&buf);
}
return c;
}
public:
SolverLP_Streambuf() : std::basic_streambuf < char,std::char_traits<char> > ()
{
initStringInfo(&buf);
}
~SolverLP_Streambuf()
{
if (buf.data)
pfree(buf.data);
}
private:
StringInfoData buf;
};
/* ***************** PostgreSQL Memory Manager is not yet supported. *************** */
///* If true, CBC uses PostgreSQL memory manager. This is needed, to avoid SEGFAL during the initialization of static members of the CBC solver */
//static bool use_pg_memctx = false;
///* Override the global NEW and DELETE operators to use the Postgres's memory manager */
//inline void* operator new ( size_t size ) { if (use_pg_memctx) return palloc( size ); else return malloc(size); }
//inline void* operator new[] ( size_t size ) { if (use_pg_memctx) return palloc( size ); else return malloc(size); }
//inline void operator delete ( void* ptr ) { if (use_pg_memctx && ptr) pfree( ptr ); else free(ptr); }
//inline void operator delete[]( void* ptr ) { if (use_pg_memctx && ptr) pfree( ptr ); else free(ptr); }
/* Prototypes */
inline static LPfunctionType get_function_type(LPproblem * prob, pg_LPfunction * poly);
static CbcModel * buildCbcModel(LPproblem * prob);
static int callBack(CbcModel * model, int whereFrom);
static inline double time_diff(struct timeval *tod1, struct timeval *tod2);
extern LPsolverResult * solve_problem_cbc(LPproblem * prob, char * args, int pgLogLevel) {
LPsolverResult * result = NULL;
std::streambuf * orgbuf;
/* Set the memory context */
// use_pg_memctx = true;
/* Remembers the standard IO*/
orgbuf = std::cout.rdbuf();
try {
CbcSolverUsefulData paramData;
SolverLP_MessageHandler * msgHnd;
SolverLP_Streambuf * msgBuf;
CbcModel * model;
struct timeval start_time, end_time; /* For performance benchmarking */
/* Redirect stdout */
msgBuf = new SolverLP_Streambuf();
std::cout.rdbuf( msgBuf );
/* Build Cbc model */
model = buildCbcModel(prob);
if (model == NULL)
ereport(ERROR, (errmsg("Failed creating CBC model.")));
/* Initialize the message handler */
msgHnd = new SolverLP_MessageHandler();
model->passInMessageHandler(msgHnd);
paramData.parameters_[whichParam(CLP_PARAM_INT_LOGLEVEL, paramData.numberParameters_, paramData.parameters_)].setIntValue(5);
/* Setup default parameters */
paramData.useSignalHandler_ = false;
paramData.noPrinting_ = false;
/* Performance measurements */
gettimeofday(&start_time, NULL);
CbcMain0(*model, paramData);
/* Setup the logging level */
int logLevel = 0;
if (pgLogLevel <= INFO)
logLevel = 1;
if (pgLogLevel <= LOG)
logLevel = 2;
if (pgLogLevel <= DEBUG1)
logLevel = 3;
if (pgLogLevel <= DEBUG2)
logLevel = 4;
msgHnd->setLogLevel(logLevel);
paramData.parameters_[whichParam(CLP_PARAM_INT_LOGLEVEL, paramData.numberParameters_, paramData.parameters_)].setIntValue(logLevel);
paramData.parameters_[whichParam(CLP_PARAM_INT_SOLVERLOGLEVEL, paramData.numberParameters_, paramData.parameters_)].setIntValue(logLevel);
/* Setup the arguments */
std::vector<const char*> argv;
argv.push_back("SolverLP Interface");
if (args != NULL)
{
std::stringstream ss(args);
std::string item;
while(std::getline(ss, item, ' '))
argv.push_back(strdup(item.c_str()));
}
argv.push_back("-solve");
argv.push_back("-quit");
// if (args != NULL)
// argv.push_back(args);
CbcMain1((int) argv.size(), &argv[0], *model, callBack, paramData);
gettimeofday(&end_time, NULL);
/* Saves the solution */
const double * solution = model->bestSolution();
if (solution != NULL) {
result = new LPsolverResult();
/* CbcModel clones the solver so we need to get current copy from the CbcModel */
result->numVariables = model->solver()->getNumCols();
result->varIndices = new int[result->numVariables];
result->varValues = new double[result->numVariables];
for (int i = 0; i < result->numVariables; i++) {
result->varIndices[i] = i;
result->varValues[i] = solution[i];
}
result->solvingTime = time_diff(&end_time, &start_time);
}
delete model;
delete msgHnd;
delete msgBuf;
} catch (const std::exception &e) {
ereport(ERROR, (errmsg("%s", e.what())));
} catch (const std::string & e){
ereport(ERROR, (errmsg("%s", e.c_str())));
} catch (const CoinError&e) {
ereport(ERROR, (errmsg("%s", e.message().c_str())));
} catch (...) {
ereport(ERROR, (errmsg("Some exception occured during CBC solving.")));
}
/* Restore stdout buffer */
std::cout.rdbuf(orgbuf);
/* Restore the memory context */
// use_pg_memctx = false;
return result;
}
/* Builds Cbc Model */
static CbcModel * buildCbcModel(LPproblem * prob) {
OsiClpSolverInterface * clp;
CoinBuild * build;
int i;
int * colStart;
double * colValue;
ListCell * c;
bool is_mip;
/* Early return, on NULL problems */
if (prob == NULL || prob->numVariables <= 0)
return NULL;
// Instantiate the Clp solver
clp = new OsiClpSolverInterface();
// clp->messageHandler()->setLogLevel(0);
//clp->messageHandler()->setFilePointer();
clp->getModelPtr()->setDualBound(1e10);
// Tell solver to return fast if presolve or initial solve infeasible
// clp->getModelPtr()->setMoreSpecialOptions(3);
/* Setup objective */
clp->setObjSense(prob->objDirection == LPobjMinimize ? 1 : -1);
/* Setup columns, and the objective */
colStart = new int[prob->numVariables];
colValue = new double[prob->numVariables];
for (i = 0; i < prob->numVariables; i++)
colValue[i] = 0;
if (prob->obj != NULL)
for (i = 0; i < prob->obj->numTerms; i++) {
lpTerm * term = &prob->obj->term[i];
/* Assign the objective function value */
colValue[term->varNr] = term->factor;
}
build = new CoinBuild();
is_mip = false; /* Initialy, the problem is not MIP */
for (i = 0; i < prob->numVariables; i++) {
double columnLower = -COIN_DBL_MAX;
double columnUpper = COIN_DBL_MAX;
if (prob->varTypes[i] == LPtypeBool) {
columnLower = 0;
columnUpper = 1;
}
build->addColumn(0, NULL, NULL, columnLower, columnUpper, colValue[i]);
/* Detect if the problem is MIP */
is_mip |= (prob->varTypes[i] == LPtypeBool)
|| (prob->varTypes[i] == LPtypeInteger);
}
/* Add actual columns */
((OsiSolverInterface *) clp)->addCols(*build);
/* Set column types */
for (i = 0; i < prob->numVariables; i++) {
LPvariableType type = prob->varTypes[i];
if (type == LPtypeInteger || type == LPtypeBool)
clp->setInteger(i);
}
/* Setup rows */
delete build;
build = new CoinBuild();
i = 0;
foreach(c, prob->ctrs)
{
Sl_Ctr *ne = (Sl_Ctr*) lfirst(c);
pg_LPfunction *poly = DatumGetLPfunction(sl_ctr_get_x_val(ne));
double rowLower, rowUpper;
LPfunctionType poly_type;
double value;
int j;
Assert(poly != NULL);
/* Moves the factor0 to the value side */
value = ne->c_val - poly->factor0;
/* We treat constraints differently depending on the function type */
/* Detect the constraint type */
poly_type = get_function_type(prob, poly);
if (poly_type == LPfunctionEmpty)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg ("SolverLP: Cannot handle constraints involving no unknown variables in constraint query %d", i), errdetail("Please check your query.")));
rowLower = rowUpper = 0; /* Initial */
/* We can handle negation for booleans */
if ((poly_type == LPfunctionBool) && (ne->op == SL_CtrType_NE)) {
/* Inverse the value: glp_set_row_bnds(lp, i + 1, GLP_FX, 1 - value, 1 - value); */
rowLower = 1 - value;
rowUpper = 1 - value;
} else if ((poly_type == LPfunctionInteger)
&& (ne->op == SL_CtrType_LT)) {
/* We can handle LT AND GT for integers: glp_set_row_bnds(lp, i + 1, GLP_LO, value - 1, 0); */
rowLower = value - 1;
rowUpper = COIN_DBL_MAX;
} else if ((poly_type == LPfunctionInteger)
&& (ne->op == SL_CtrType_GT)) {
// glp_set_row_bnds(lp, i + 1, GLP_UP, 0, value + 1); // Fix from "value + 1, 0"
rowLower = -COIN_DBL_MAX;
rowUpper = value + 1;
} else
switch (ne->op) {
case SL_CtrType_EQ:
// glp_set_row_bnds(lp, i + 1, GLP_FX, value, value);
rowLower = rowUpper = value;
break;
case SL_CtrType_GE:
// glp_set_row_bnds(lp, i + 1, GLP_UP, 0, value);
rowLower = poly_type == LPfunctionBool ? 0 : -COIN_DBL_MAX;
rowUpper = value;
break;
case SL_CtrType_LE:
// glp_set_row_bnds(lp, i + 1, GLP_LO, value, 0);
rowLower = value;
rowUpper = COIN_DBL_MAX;
break;
default:
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg ("SolverLP: Invalid constraint specified in the constraint query %d", i), errdetail("The solver only supports =, >=, <= for float and mixed constraints, > and < for integer constraints, and != for boolean constraints")));
break;
}
// Setup indices and bound coefficients
for (j = 0; j < poly->numTerms; j++) {
lpTerm * term = &poly->term[j];
colStart[j] = term->varNr;
colValue[j] = term->factor;
}
i++;
build->addRow(poly->numTerms, colStart, colValue, rowLower, rowUpper);
}
/* Add actual rows */
((OsiSolverInterface *) clp)->addRows(*build);
return new CbcModel(*clp);
}
static int callBack(CbcModel * model, int whereFrom)
{
if (InterruptPending)
throw std::runtime_error("Interrupt requested");
return 0;
}
/*
* Get the type of the function
*/
inline static LPfunctionType get_function_type(LPproblem * prob, pg_LPfunction * poly)
{
int i;
LPfunctionType type = LPfunctionEmpty;
for(i = 0; i < poly->numTerms; i++)
{
LPvariableType var_type;
LPfunctionType var_typep;
int varNr = poly->term[i].varNr;
Assert(varNr>= 0 && varNr < prob->numVariables);
var_type = prob->varTypes[varNr];
var_typep = var_type == LPtypeBool ? LPfunctionBool :
var_type == LPtypeInteger ? LPfunctionInteger :
LPfunctionFloat;
if (type == LPfunctionEmpty)
type = var_typep;
else if (type != var_typep)
{
type = LPfunctionMixed;
break;
}
}
return type;
}
/* ************************* SolverLP message handler ************************* */
//-------------------------------------------------------------------
// Default Constructor
//-------------------------------------------------------------------
SolverLP_MessageHandler::SolverLP_MessageHandler () : CoinMessageHandler()
{
}
//-------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------
SolverLP_MessageHandler::~SolverLP_MessageHandler ()
{
}
//-------------------------------------------------------------------
// Clone
//-------------------------------------------------------------------
CoinMessageHandler * SolverLP_MessageHandler::clone() const
{
return new SolverLP_MessageHandler(*this);
}
int
SolverLP_MessageHandler::print()
{
/* A PostgreSQL hack to be able to print text continously */
ErrorContextCallback * old_error_context = error_context_stack;
error_context_stack = NULL;
ereport(NOTICE, (errmsg("%s", messageBuffer_)));
error_context_stack = old_error_context;
return 0;
}
static inline double time_diff(struct timeval *tod1, struct timeval *tod2)
{
long long t1, t2;
t1 = tod1->tv_sec * 1E6 + tod1->tv_usec;
t2 = tod2->tv_sec * 1E6 + tod2->tv_usec;
return ((double)(t1 - t2)) / 1E6;
}
/* Do initial solve */
// clp->setHintParam(OsiDoPresolveInInitial,true,OsiHintTry);
// clp->setHintParam(OsiDoDualInInitial,true,OsiHintTry);
// clp->setHintParam(OsiDoScale,false,OsiHintTry);
// clp->setHintParam(OsiDoDualInInitial,true,OsiHintTry);
//clp->initialSolve();
//if (clp->isProvenOptimal())
// if (is_mip) {
// // Pass the solver with the problem to be solved to CbcModel
// CbcModel model(*clp);
//
// CbcStrategyDefault strategy(true, 5, 0);
// CbcRounding heuristic(model);
// model.addHeuristic(&heuristic);
// model.setStrategy(strategy);
// model.setLogLevel(0);
//
// // Do complete search
// model.branchAndBound(0);
//
// /*
// * Saves the solution.
// * */
// const double * solution = model.bestSolution();
//
// if (solution != NULL) {
// LPsolverResult * result = new LPsolverResult();
// /* CbcModel clones the solver so we need to get current copy from the CbcModel */
// result->numVariables = model.solver()->getNumCols();
// result->varIndices = new int[result->numVariables];
// result->varValues = new double[result->numVariables];
// for (i = 0; i < result->numVariables; i++) {
// result->varIndices[i] = i;
// result->varValues[i] = solution[i];
// }
// return result;
// }
// }
| 28.801905 | 278 | 0.651147 | [
"vector",
"model"
] |
a7dfd06170b63f05e671be837a0772f8c75269bd | 4,972 | cpp | C++ | src/main.cpp | falichs/Depizelizing-Pixel-Art-on-GPUs | 1e08d156b16c0a0165ae38cabd55fc71611c7543 | [
"MIT"
] | 59 | 2017-02-27T11:59:21.000Z | 2022-02-22T08:36:26.000Z | src/main.cpp | falichs/Depizelizing-Pixel-Art-on-GPUs | 1e08d156b16c0a0165ae38cabd55fc71611c7543 | [
"MIT"
] | 2 | 2018-04-06T11:07:49.000Z | 2021-11-23T22:40:00.000Z | src/main.cpp | falichs/Depizelizing-Pixel-Art-on-GPUs | 1e08d156b16c0a0165ae38cabd55fc71611c7543 | [
"MIT"
] | 12 | 2018-04-05T13:59:19.000Z | 2021-12-13T11:55:35.000Z | // Copyright (c) 2015 Felix Kreuzer
//
// This source is subject to the MIT License.
// Please see the LICENSE.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "PixelArtRenderer.h"
#include <boost/program_options.hpp>
using namespace boost;
namespace po = boost::program_options;
#include <algorithm>
#include <iterator>
using namespace std;
/** @file main.cpp */
/**
* Prints command line options to console
*/
void printUsage() {
std::cout << "Usage is -in <infile>\n";
}
/**
* An operator function for using BOOST::PROGRAM_OPTIONS.
*/
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
return os;
}
/**
* Handles input parameters and controls the main-loop.
* Command-line parameters are parsed using BOOST::PROGRAM_OPTIONS.
* After that the PIXELARTRENDERER class gets instantiated and initialized.
* The main-loop orders the Renderer to draw frames and measures the time between them.
* The only way to break the loop is by pressing the ESC key or closing the OS-window.
* @see PixelArtRenderer
*/
int main( int argc, char* argv[] )
{
int height;
string inputPath;
string sequence_name; //if fed with sequence
int sequence_count = 0; //if fed with sequence
float sequence_fps = 1; //if fed with sequence
bool useSequence = false;
po::options_description desc("Allowed options");
try {
desc.add_options()
("help", "produce help message")
//("input-file", po::value< vector<string> >(), "input file")
("input-file,I", po::value<string>(&inputPath), "input file")
("input-sequence,S", po::value<string>(&sequence_name), "input seqence name")
("sequence-count", po::value<int>(&sequence_count), "input seqence count")
("sequence-fps", po::value<float>(&sequence_fps)->default_value(15.0f), "input seqence frames per second")
("height", po::value<int>(&height)->default_value(600),
"output vertical size in pixel")
;
po::positional_options_description p;
p.add("input-file", -1);
p.add("input-sequence", 3);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "Usage: GPUPixelArt.exe [options]\n";
cout << desc;
return 0;
} else if (vm.count("input-file"))
{
//cout << "Input files are: " << vm["input-file"].as< vector<string> >() << "\n";
cout << "INPUT: " << inputPath << "\n";
} else if (vm.count("input-sequence"))
{
//cout << "Input files are: " << vm["input-file"].as< vector<string> >() << "\n";
useSequence = true;
cout << "INPUT: sequence:" << sequence_name << ", frame count:" << sequence_count << ", fps:" << sequence_fps <<".\n";
} else {
cout << "Usage: GPUPixelArt.exe [options]\n";
cout << desc;
return 0;
}
cout << "Height is " << height << "\n";
}
catch(std::exception& e)
{
cout << e.what() << "\n";
cout << "Usage: GPUPixelArt.exe [options]\n";
cout << desc;
return 1;
}
PixelArtRenderer* renderer = PixelArtRenderer::getInstance();
int errorcode = renderer->initGraphics();
if (errorcode != 0) {
return 1;
}
renderer->resizeFun(renderer->getWindow(),0,height);
if(useSequence) {
if( !(renderer->loadPixelArtSequence(sequence_name, sequence_count, sequence_fps))) {
return 1;
}
} else {
if(!(renderer->loadPixelArt(inputPath.c_str())))
return 1;
}
if(!renderer->initConstructionContent()) {
return 1;
}
//glfwEnable(GLFW_STICKY_KEYS);
double lastTime = glfwGetTime();
int nbFrames = 0;
double sequence_last_frame_time = lastTime;
do{
// Measure speed
double currentTime = glfwGetTime();
nbFrames++;
if ( currentTime - lastTime >= 1.0 ){ // If last prinf() was more than 1 sec ago
// printf and reset timer
char title[100];
snprintf(title,100, "Depixelizing PixelArt On GPU - %f ms/frame - ", 1000.0/double(nbFrames) );
glfwSetWindowTitle(renderer->getWindow(), title);
nbFrames = 0;
lastTime += 1.0;
}
if(useSequence) {
renderer->sequenceLoadFrame(currentTime);
}
renderer->drawFrame(currentTime);
} // Check if the ESC key was pressed or the window was closed
while( !glfwWindowShouldClose(renderer->getWindow()));
// Cleanup
renderer->~PixelArtRenderer();
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
}
| 29.247059 | 121 | 0.638375 | [
"vector"
] |
a7ece1e9cc6d9518931ba55d8ff009cfe5eb8bf5 | 22,314 | cpp | C++ | PyCommon/externalLibs/BaseLib/motion/Retarget_JH/PmQm/pmPosture.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | 4 | 2018-05-14T07:27:59.000Z | 2021-12-21T04:39:21.000Z | PyCommon/externalLibs/BaseLib/motion/Retarget_JH/PmQm/pmPosture.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | null | null | null | PyCommon/externalLibs/BaseLib/motion/Retarget_JH/PmQm/pmPosture.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | 3 | 2018-01-03T06:09:21.000Z | 2021-07-26T15:13:14.000Z |
#include "pm.h"
using namespace jhm;
void
PmPosture::setScale( m_real s )
{
scale = s;
mask = mask | PM_MASK_SCALE;
}
m_real
PmPosture::getScale() const
{
return scale;
}
void
PmPosture::setTranslation( vector const& v )
{
trans = v;
mask = mask | MaskBit(PmHuman::PELVIS);
}
void
PmPosture::addTranslation( vector const& d )
{
trans += d;
}
vector
PmPosture::getTranslation() const
{
return trans;
}
void
PmPosture::addRotation( int i, vector const& d )
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
rotate[i] = rotate[i] * exp(d);
}
void
PmPosture::setRotation( int i, quater const& q )
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
rotate[i] = q;
mask = mask | MaskBit(i);
}
void
PmPosture::setRotation( int i, vector const& v )
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
rotate[i] = EulerAngle2Quater(v);
mask = mask | MaskBit(i);
}
void
PmPosture::setRotation( int i, matrix const& m )
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
rotate[i] = Matrix2Quater( m );
mask = mask | MaskBit(i);
}
quater
PmPosture::getRotation( int i ) const
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
return rotate[i];
}
void
PmPosture::setTransq( int i, transq const& t )
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
if ( i==PmHuman::PELVIS ) trans = t.translation;
rotate[i] = t.rotation;
mask = mask | MaskBit(i);
}
transq
PmPosture::getTransq( int i ) const
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
if ( i==PmHuman::PELVIS )
return transq( rotate[i], trans );
else
return transq( rotate[i], vector(0,0,0) );
}
void
PmPosture::setTransf( int i, transf const& t )
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
if ( i==PmHuman::PELVIS ) trans = t.translation();
rotate[i] = Matrix2Quater( t.affine() );
mask = mask | MaskBit(i);
}
transf
PmPosture::getTransf( int i ) const
{
assert( i>=0 && i<PM_HUMAN_NUM_LINKS );
if ( i==PmHuman::PELVIS )
return transf( Quater2Matrix(rotate[i]), trans );
else
return transf( Quater2Matrix(rotate[i]), vector(0,0,0) );
}
PmPosture&
PmPosture::interpolate( m_real d, PmPosture const& v1,
PmPosture const& v2 )
{
PmMaskType mask1 = v1.getMask();
PmMaskType mask2 = v2.getMask();
if ( mask1 & mask2 & PM_MASK_SCALE )
this->scale = (1.0 - d)*v1.scale + d*v2.scale;
if ( mask1 & mask2 & MaskBit(PmHuman::PELVIS) )
setTranslation( ::interpolate(d, v1.trans, v2.trans ) );
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( mask1 & mask2 & MaskBit(i) )
setRotation( i, ::interpolate(d, v1.rotate[i], v2.rotate[i]) );
return (*this);
}
PmPosture&
PmPosture::copyOver( PmPosture const& v )
{
if ( v.mask & PM_MASK_SCALE ) this->scale = v.scale;
if ( v.mask & MaskBit(PmHuman::PELVIS) ) this->trans = v.trans;
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( v.mask & MaskBit(i) ) this->rotate[i] = v.rotate[i];
this->mask |= v.mask;
return (*this);
}
PmPosture&
PmPosture::copyUnder( PmPosture const& v )
{
if ( v.mask & PM_MASK_SCALE & this->mask )
this->scale = v.scale;
if ( v.mask & MaskBit(PmHuman::PELVIS) & this->mask )
this->trans = v.trans;
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( v.mask & MaskBit(i) & this->mask )
this->rotate[i] = v.rotate[i];
return (*this);
}
PmPosture&
PmPosture::blend( m_real t, PmPosture const& v )
{
if ( v.mask & !PM_MASK_SCALE )
this->scale = v.scale;
else if ( v.mask & PM_MASK_SCALE )
this->scale = (1.0 - t)*this->scale + t*v.scale;
if ( v.mask & !MaskBit(PmHuman::PELVIS) )
this->trans = v.trans;
else if ( v.mask & MaskBit(PmHuman::PELVIS) )
this->trans = ::interpolate(t, this->trans, v.trans);
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
{
if ( v.mask & !MaskBit(i) )
this->rotate[i] = v.rotate[i];
else if ( v.mask & MaskBit(i) )
{
if ( this->rotate[i] % v.rotate[i] > 0 )
this->rotate[i] = ::interpolate(t, this->rotate[i], v.rotate[i]);
else
this->rotate[i] = ::interpolate(t, this->rotate[i], -v.rotate[i]);
}
}
this->mask |= v.mask;
return (*this);
}
transf
PmPosture::getGlobalTransf( int i ) const
{
transf t = getTransf(i);
while( body->getParent(i) != -1 )
{
m_real s = getScale();
t *= scale_transf(s,s,s) * body->getJointTransf(i);
// t *= translate_transf( getScale() * body->getJointPosition(i) );
i = body->getParent(i);
t *= getTransf(i);
}
return t;
}
transf
PmPosture::getBaseTransf( int i ) const
{
transf t = identity_transf;
while( body->getParent(i) != -1 )
{
m_real s = getScale();
t *= scale_transf(s,s,s) * body->getJointTransf(i);
// t *= translate_transf( getScale() * body->getJointPosition(i) );
i = body->getParent(i);
t *= getTransf(i);
}
return t;
}
vector
PmPosture::getGlobalTranslation( int i ) const
{
transf t = getTransf(i);
while( body->getParent(i) != -1 )
{
m_real s = getScale();
t *= scale_transf(s,s,s) * body->getJointTransf(i);
i = body->getParent(i);
t *= getTransf(i);
}
return t.translation();
}
position
PmPosture::getGlobalPosition( int i ) const
{
transf t = getTransf(i);
while( body->getParent(i) != -1 )
{
m_real s = getScale();
t *= scale_transf(s,s,s) * body->getJointTransf(i);
i = body->getParent(i);
t *= getTransf(i);
}
return t.getPosition();
}
quater
PmPosture::getGlobalRotation( int i ) const
{
transf t = getTransf(i);
while( body->getParent(i) != -1 )
{
m_real s = getScale();
t *= scale_transf(s,s,s) * body->getJointTransf(i);
i = body->getParent(i);
t *= getTransf(i);
}
return Matrix2Quater(t.affine());
}
//----------------------------------------------------------------------------//
PmPosture&
PmPosture::operator=( PmPosture const& v )
{
this->body = v.body;
this->mask = v.mask;
this->scale = v.scale;
this->trans = v.trans;
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
this->rotate[i] = v.rotate[i];
return (*this);
}
PmPosture&
PmPosture::operator+=( PmVector const& v )
{
#ifdef __EULER_ANGLES__
if ( this->mask & v.getMask() & MaskBit(PmHuman::PELVIS) )
setTranslation( getTranslation() + v.getLinearVector() );
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( this->mask & v.getMask() & MaskBit(i) )
{
setRotation( i, Quater2EulerAngle(getRotation(i)) +
v.getAngularVector(i) );
}
#else
if ( this->mask & v.getMask() & MaskBit(PmHuman::PELVIS) )
{
transq t = transq( exp(v.getAngularVector(0)),
v.getLinearVector() );
this->setTransq( 0, getTransq(0) * t );
};
for( int i=1; i<PM_HUMAN_NUM_LINKS; i++ )
if ( this->mask & v.getMask() & MaskBit(i) )
this->rotate[i] = this->rotate[i] * exp(v.getAngularVector(i));
#endif
return (*this);
}
void
PmPosture::addDisplacement( PmVector const& v, m_real f )
{
#ifdef __EULER_ANGLES__
if ( this->mask & v.getMask() & MaskBit(PmHuman::PELVIS) )
setTranslation( getTranslation() + f * v.getLinearVector() );
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( this->mask & v.getMask() & MaskBit(i) )
{
setRotation( i, Quater2EulerAngle(getRotation(i)) +
f * v.getAngularVector(i) );
}
#else
if ( this->mask & v.getMask() & MaskBit(PmHuman::PELVIS) )
{
transq t = transq( exp(f * v.getAngularVector(0)),
f * v.getLinearVector() );
this->setTransq( 0, getTransq(0) * t );
};
for( int i=1; i<PM_HUMAN_NUM_LINKS; i++ )
if ( this->mask & v.getMask() & MaskBit(i) )
this->rotate[i] = this->rotate[i] * exp(f * v.getAngularVector(i));
#endif
}
//----------------------------------------------------------------------------//
void
PmPosture::quater2euler()
{
vector v;
rotate[0] = EulerAngle2Quater( Quater2EulerAngle( rotate[0] ) );
for( int i=1; i<PM_HUMAN_NUM_LINKS; i++ )
if ( this->mask & MaskBit(i) )
{
v = Quater2EulerAngle( getRotation(i) );
setRotation( i, quater(0,v[0],v[1],v[2]) );
}
}
void
PmPosture::euler2quater()
{
quater q;
vector v;
for( int i=1; i<PM_HUMAN_NUM_LINKS; i++ )
if ( this->mask & MaskBit(i) )
{
q = getRotation(i);
v = vector( q.x(), q.y(), q.z() );
setRotation( i, EulerAngle2Quater(v) );
}
}
//----------------------------------------------------------------------------//
PmPosture
PmPosture::posture_stand()
{
PmPosture h;
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
h.rotate[i] = quater( 1,0,0,0 );
h.rotate[PmHuman::LOWER_RIGHT_ARM] = exp(-M_PI/48 * x_axis );
h.rotate[PmHuman::LOWER_LEFT_ARM] = exp(-M_PI/48 * x_axis );
h.rotate[PmHuman::UPPER_RIGHT_LEG] = exp(-M_PI/64 * x_axis );
h.rotate[PmHuman::UPPER_LEFT_LEG] = exp(-M_PI/64 * x_axis );
h.rotate[PmHuman::LOWER_RIGHT_LEG] = exp(M_PI/48 * x_axis );
h.rotate[PmHuman::LOWER_LEFT_LEG] = exp(M_PI/48 * x_axis );
h.copyOver( posture_hand_relax_right() );
h.copyOver( posture_hand_relax_left() );
// h.setMask( PM_MASK_ALL_JOINT );
return h;
}
PmPosture
PmPosture::posture_stand( vector const& v )
{
PmPosture h;
h.trans = v;
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
h.rotate[i] = quater( 1,0,0,0 );
h.rotate[PmHuman::LOWER_RIGHT_ARM] = exp(-M_PI/48 * x_axis );
h.rotate[PmHuman::LOWER_LEFT_ARM] = exp(-M_PI/48 * x_axis );
h.copyOver( posture_hand_relax_right() );
h.copyOver( posture_hand_relax_left() );
// h.setMask( PM_MASK_ALL_JOINT );
return h;
}
PmPosture
PmPosture::posture_hand_fist_right()
{
PmPosture h;
h.rotate[PmHuman::RIGHT_PALM] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_11] = Matrix2Quater( EulerAngle2Matrix(vector(-1.41437,-0.865949,2.30966)) );
h.rotate[PmHuman::RIGHT_FINGER_12] = exp( -1.01914/2 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_13] = exp( -1.09799/2 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_21] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_22] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_23] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_31] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_32] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_33] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_41] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_42] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_43] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_51] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_52] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_53] = exp( M_PI/4 * z_axis );
h.setMask( PM_MASK_RIGHT_HAND );
return h;
}
PmPosture
PmPosture::posture_hand_fist_left()
{
PmPosture h;
h.rotate[PmHuman::LEFT_PALM] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_11] = Matrix2Quater( EulerAngle2Matrix(vector(-1.41437,0.865949,-2.30966)) );
h.rotate[PmHuman::LEFT_FINGER_12] = exp( 1.01914/2 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_13] = exp( 1.09799/2 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_21] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_22] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_23] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_31] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_32] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_33] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_41] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_42] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_43] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_51] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_52] = exp( -M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_53] = exp( -M_PI/4 * z_axis );
h.setMask( PM_MASK_LEFT_HAND );
return h;
}
PmPosture
PmPosture::posture_hand_relax_right()
{
PmPosture h;
h.rotate[PmHuman::RIGHT_PALM] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_11] = Matrix2Quater( EulerAngle2Matrix(vector(-1.637,-0.911,1.962)) );
h.rotate[PmHuman::RIGHT_FINGER_12] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_13] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_21] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_22] = exp( M_PI/6 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_23] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_31] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_32] = exp( M_PI/5 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_33] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_41] = exp( M_PI/10 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_42] = exp( M_PI/5 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_43] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_51] = exp( M_PI/8 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_52] = exp( M_PI/4 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_53] = exp( M_PI/12 * z_axis );
h.setMask( PM_MASK_RIGHT_HAND );
return h;
}
PmPosture
PmPosture::posture_hand_relax_left()
{
PmPosture h;
h.rotate[PmHuman::LEFT_PALM] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_11] = Matrix2Quater( EulerAngle2Matrix(vector(-1.637,0.911,-1.962)) );
h.rotate[PmHuman::LEFT_FINGER_12] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_13] = exp( M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_21] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_22] = exp(-M_PI/6 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_23] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_31] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_32] = exp(-M_PI/5 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_33] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_41] = exp(-M_PI/10 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_42] = exp(-M_PI/5 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_43] = exp(-M_PI/12 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_51] = exp(-M_PI/8 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_52] = exp(-M_PI/4 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_53] = exp(-M_PI/12 * z_axis );
h.setMask( PM_MASK_LEFT_HAND );
return h;
}
PmPosture
PmPosture::posture_hand_stretch_right()
{
PmPosture h;
h.rotate[PmHuman::RIGHT_PALM] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_11] = Matrix2Quater( EulerAngle2Matrix(vector(-1.6392,-0.729895,2.00465)) );
h.rotate[PmHuman::RIGHT_FINGER_12] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_13] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_21] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_22] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_23] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_31] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_32] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_33] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_41] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_42] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_43] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_51] = quater(1,0,0,0);
h.rotate[PmHuman::RIGHT_FINGER_52] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::RIGHT_FINGER_53] = exp( M_PI/24 * z_axis );
h.setMask( PM_MASK_RIGHT_HAND );
return h;
}
PmPosture
PmPosture::posture_hand_stretch_left()
{
PmPosture h;
h.rotate[PmHuman::LEFT_PALM] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_11] = Matrix2Quater( EulerAngle2Matrix(vector(-1.6392,0.729895,-2.00465)) );
h.rotate[PmHuman::LEFT_FINGER_12] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_13] = exp( M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_21] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_22] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_23] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_31] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_32] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_33] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_41] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_42] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_43] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_51] = quater(1,0,0,0);
h.rotate[PmHuman::LEFT_FINGER_52] = exp(-M_PI/24 * z_axis );
h.rotate[PmHuman::LEFT_FINGER_53] = exp(-M_PI/24 * z_axis );
h.setMask( PM_MASK_LEFT_HAND );
return h;
}
//----------------------------------------------------------------------------//
vector
PmPosture::getRollingAxis( int BASE, int UPPER, int LOWER, int END )
{
transf reference = getGlobalTransf( BASE ).inverse();
vector end = (getGlobalTransf(END) * reference).translation();
vector upper = (getGlobalTransf(UPPER) * reference).translation();
return upper - end;
}
PmPosture&
PmPosture::applyTransf( transf const& t )
{
setTransf( 0, getTransf(0) * t );
return (*this);
}
//----------------------------------------------------------------------------//
int
PmPosture::getNumSpineLinks() const
{
if ( body ) return body->getNumSpineLinks();
return 0;
}
int
PmPosture::getDOF( int joint ) const
{
return GetDOF( joint );
}
int
PmPosture::getDOF() const
{
return GetDOF( this->getMask() );
}
void
PmPosture::addDisplacement( vectorN const& disp )
{
int i, j = 0;
vector p, v;
PmMaskType mask = getMask();
for( i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( mask & MaskBit(i) )
{
if ( getDOF(i)==6 )
{
p = vector( disp[j ], disp[j+1], disp[j+2] );
v = vector( disp[j+3], disp[j+4], disp[j+5] );
setRotation( i, getRotation(i) * exp(v) );
setTranslation( getTranslation() + p );
j += 6;
}
else if ( getDOF(i)==3 )
{
v = vector( disp[j], disp[j+1], disp[j+2] );
setRotation( i, getRotation(i) * exp(v) );
j += 3;
}
else if ( getDOF(i)==1 )
{
v = vector( disp[j], 0, 0 );
setRotation( i, getRotation(i) * exp(v) );
j ++;
}
}
if ( mask & MaskBit(PmHuman::CHEST) )
{
quater q = getRotation( PmHuman::CHEST );
for( i=0; i<getNumSpineLinks(); i++ )
setRotation( PmHuman::CHEST-i-1, q );
}
}
//----------------------------------------------------------------------------//
// Physical Properties
//----------------------------------------------------------------------------//
vector
PmPosture::getCOG( int i ) const
{
return getGlobalTranslation(i);
}
vector
PmPosture::getCOG() const
{
assert( getBody() );
m_real mass = 0.0;
vector center(0,0,0);
PmMaskType mask = getMask();
for( int i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( mask & MaskBit(i) )
{
center += getBody()->getMass(i) * getCOG(i);
mass += getBody()->getMass(i);
}
return center / mass;
}
void
PmPosture::getCOGlist( m_real* mass, vector* cog ) const
{
assert( getBody() );
PmMaskType mask = getMask();
int i;
for( i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( mask & MaskBit(i) )
{
mass[i] = getBody()->getMass(i);
cog[i] = mass[i] * getCOG(i);
}
for( i=PM_HUMAN_NUM_LINKS-1; i>=0; i-- )
if ( mask & MaskBit(i) )
{
int parent = getBody()->getParent( i );
if ( parent != -1 )
{
mass[parent] += mass[i];
cog[parent] += cog[i];
}
}
for( i=0; i<PM_HUMAN_NUM_LINKS; i++ )
if ( mask & MaskBit(i) )
{
cog[i] /= mass[i];
}
}
void
PmPosture::getSupportPolygon( PmConstraint const& c, QmPolygon2D& sp ) const
{
assert( getBody() );
int pn=0;
position points[30];
/*
//------------------------------------------------
// Viewpoint model
transf t;
m_real h = -getBody()->getAnkleHeight();
if ( c.isConstrained( PmHuman::RIGHT_FOOT ) )
{
t = getGlobalTransf( PmHuman::RIGHT_FOOT );
points[pn++] = position( 1.5,h, 7) * t;
points[pn++] = position( 1.5,h,-1) * t;
points[pn++] = position(-1.5,h,-1) * t;
points[pn++] = position(-1.5,h, 7) * t;
}
if ( c.isConstrained( PmHuman::LEFT_FOOT ) )
{
t = getGlobalTransf( PmHuman::LEFT_FOOT );
points[pn++] = position( 1.5,h, 7) * t;
points[pn++] = position( 1.5,h,-1) * t;
points[pn++] = position(-1.5,h,-1) * t;
points[pn++] = position(-1.5,h, 7) * t;
}
// Viewpoint model
//------------------------------------------------
*/
//------------------------------------------------
// ASF/AMC model
position p1, p2;
m_real d = 3.0;
if ( c.isConstrained( PmHuman::RIGHT_FOOT ) )
{
p1 = vector2position( getGlobalTranslation( PmHuman::RIGHT_FOOT ) );
p2 = vector2position( getGlobalTranslation( PmHuman::RIGHT_TOE ) );
points[pn++] = p1 + vector( d,0, d);
points[pn++] = p1 + vector(-d,0, d);
points[pn++] = p1 + vector( d,0,-d);
points[pn++] = p1 + vector(-d,0,-d);
points[pn++] = p2 + vector( d,0, d);
points[pn++] = p2 + vector(-d,0, d);
points[pn++] = p2 + vector( d,0,-d);
points[pn++] = p2 + vector(-d,0,-d);
}
if ( c.isConstrained( PmHuman::LEFT_FOOT ) )
{
p1 = vector2position( getGlobalTranslation( PmHuman::LEFT_FOOT ) );
p2 = vector2position( getGlobalTranslation( PmHuman::LEFT_TOE ) );
points[pn++] = p1 + vector( d,0, d);
points[pn++] = p1 + vector(-d,0, d);
points[pn++] = p1 + vector( d,0,-d);
points[pn++] = p1 + vector(-d,0,-d);
points[pn++] = p2 + vector( d,0, d);
points[pn++] = p2 + vector(-d,0, d);
points[pn++] = p2 + vector( d,0,-d);
points[pn++] = p2 + vector(-d,0,-d);
}
// ASF/AMC model
//------------------------------------------------
sp.convexHull( pn, points );
}
| 26.981862 | 113 | 0.58358 | [
"vector",
"model"
] |
a7ee354afccbd2769e6e316b55e17b7c6def71b3 | 3,632 | cc | C++ | optix/src/OptixLightManager.cc | Levi-Armstrong/ign-rendering | dfcf7c4a574b6b0e94419b7ba1ab3ebce64055f3 | [
"ECL-2.0",
"Apache-2.0"
] | 25 | 2020-04-15T16:59:45.000Z | 2022-02-09T00:07:34.000Z | optix/src/OptixLightManager.cc | Levi-Armstrong/ign-rendering | dfcf7c4a574b6b0e94419b7ba1ab3ebce64055f3 | [
"ECL-2.0",
"Apache-2.0"
] | 510 | 2020-04-20T23:26:31.000Z | 2022-03-31T14:33:36.000Z | optix/src/OptixLightManager.cc | srmainwaring/ign-rendering | 46dd20ae11fdf2dd2ce25d7ee93299545ef8b224 | [
"ECL-2.0",
"Apache-2.0"
] | 30 | 2020-05-22T17:41:38.000Z | 2022-02-28T17:07:19.000Z | /*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* 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 "ignition/rendering/optix/OptixLightManager.hh"
#include "ignition/rendering/optix/OptixLight.hh"
#include "ignition/rendering/optix/OptixScene.hh"
#include "ignition/rendering/optix/OptixVisual.hh"
using namespace ignition;
using namespace rendering;
//////////////////////////////////////////////////
OptixLightManager::OptixLightManager(OptixScenePtr _scene) :
scene(_scene)
{
this->CreateBuffers();
}
//////////////////////////////////////////////////
OptixLightManager::~OptixLightManager()
{
}
//////////////////////////////////////////////////
void OptixLightManager::AddDirectionalLight(OptixDirectionalLightPtr _light)
{
this->directionalData.push_back(_light->Data());
}
//////////////////////////////////////////////////
void OptixLightManager::AddPointLight(OptixPointLightPtr _light)
{
this->pointData.push_back(_light->Data());
}
//////////////////////////////////////////////////
void OptixLightManager::AddSpotLight(OptixSpotLightPtr _light)
{
this->spotData.push_back(_light->Data());
}
//////////////////////////////////////////////////
void OptixLightManager::PreRender()
{
this->WriteDirectionalBuffer();
this->WritePointBuffer();
this->WriteSpotBuffer();
}
//////////////////////////////////////////////////
void OptixLightManager::Clear()
{
directionalData.clear();
pointData.clear();
spotData.clear();
}
//////////////////////////////////////////////////
void OptixLightManager::WriteDirectionalBuffer()
{
this->WriteBuffer<OptixDirectionalLightData>(this->directionalBuffer,
this->directionalData);
}
//////////////////////////////////////////////////
void OptixLightManager::WritePointBuffer()
{
this->WriteBuffer<OptixPointLightData>(this->pointBuffer, this->pointData);
}
//////////////////////////////////////////////////
void OptixLightManager::WriteSpotBuffer()
{
this->WriteBuffer<OptixSpotLightData>(this->spotBuffer, this->spotData);
}
//////////////////////////////////////////////////
template <class T>
void OptixLightManager::WriteBuffer(optix::Buffer _buffer,
const std::vector<T> &_data)
{
_buffer->setSize(_data.size());
unsigned int memSize = sizeof(T) * _data.size();
std::memcpy(_buffer->map(), &_data[0], memSize);
_buffer->unmap();
}
//////////////////////////////////////////////////
void OptixLightManager::CreateBuffers()
{
this->directionalBuffer =
this->CreateBuffer<OptixDirectionalLightData>("directionalLights");
this->pointBuffer = this->CreateBuffer<OptixPointLightData>("pointLights");
this->spotBuffer = this->CreateBuffer<OptixSpotLightData>("spotLights");
}
//////////////////////////////////////////////////
template <class T>
optix::Buffer OptixLightManager::CreateBuffer(const std::string &_name)
{
optix::Context optixContext = this->scene->OptixContext();
optix::Buffer buffer = optixContext->createBuffer(RT_BUFFER_INPUT);
optixContext[_name]->setBuffer(buffer);
buffer->setFormat(RT_FORMAT_USER);
buffer->setElementSize(sizeof(T));
return buffer;
}
| 29.528455 | 77 | 0.619769 | [
"vector"
] |
c5068e76a12d3c91197a854e988a481dc9f5721e | 2,070 | cpp | C++ | Templates/TP_TwinStick/Source/TP_TwinStick/TP_TwinStickProjectile.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Templates/TP_TwinStick/Source/TP_TwinStick/TP_TwinStickProjectile.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Templates/TP_TwinStick/Source/TP_TwinStick/TP_TwinStickProjectile.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserve
#include "TP_TwinStickProjectile.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "Engine/StaticMesh.h"
ATP_TwinStickProjectile::ATP_TwinStickProjectile()
{
// Static reference to the mesh to use for the projectile
static ConstructorHelpers::FObjectFinder<UStaticMesh> ProjectileMeshAsset(TEXT("/Game/TwinStick/Meshes/TwinStickProjectile.TwinStickProjectile"));
// Create mesh component for the projectile sphere
ProjectileMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ProjectileMesh0"));
ProjectileMesh->SetStaticMesh(ProjectileMeshAsset.Object);
ProjectileMesh->SetupAttachment(RootComponent);
ProjectileMesh->BodyInstance.SetCollisionProfileName("Projectile");
ProjectileMesh->OnComponentHit.AddDynamic(this, &ATP_TwinStickProjectile::OnHit); // set up a notification for when this component hits something
RootComponent = ProjectileMesh;
// Use a ProjectileMovementComponent to govern this projectile's movement
ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovement0"));
ProjectileMovement->UpdatedComponent = ProjectileMesh;
ProjectileMovement->InitialSpeed = 3000.f;
ProjectileMovement->MaxSpeed = 3000.f;
ProjectileMovement->bRotationFollowsVelocity = true;
ProjectileMovement->bShouldBounce = false;
ProjectileMovement->ProjectileGravityScale = 0.f; // No gravity
// Die after 3 seconds by default
InitialLifeSpan = 3.0f;
}
void ATP_TwinStickProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
// Only add impulse and destroy projectile if we hit a physics
if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL) && OtherComp->IsSimulatingPhysics())
{
OtherComp->AddImpulseAtLocation(GetVelocity() * 20.0f, GetActorLocation());
}
Destroy();
} | 46 | 163 | 0.807246 | [
"mesh",
"object"
] |
c50ecd2cf03c4a943969927b06e9d2a3f05bf0e2 | 15,510 | cpp | C++ | consumer/src/consumer.cpp | Talank/pact-cplusplus | e6f50df28912648f3863ab47ec57dfcf973f9da0 | [
"MIT"
] | null | null | null | consumer/src/consumer.cpp | Talank/pact-cplusplus | e6f50df28912648f3863ab47ec57dfcf973f9da0 | [
"MIT"
] | null | null | null | consumer/src/consumer.cpp | Talank/pact-cplusplus | e6f50df28912648f3863ab47ec57dfcf973f9da0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <stdlib.h>
#include <sstream>
#include "consumer.h"
#include <boost/exception/diagnostic_information.hpp>
#include <nlohmann/json.hpp>
using namespace pact_mock_server_ffi;
using json = nlohmann::json;
namespace pact_consumer {
void init() {
pact_mock_server_ffi::init("LOG_LEVEL");
}
////////////////////////////////////
// Pact Class
////////////////////////////////////
Pact::Pact(const char* consumer_name, const char* provider_name) {
this->pact = pact_mock_server_ffi::new_pact(consumer_name, provider_name);
this->consumer = consumer_name;
this->provider = provider_name;
}
Interaction Pact::uponReceiving(const char* description) const {
return Interaction(this, description);
}
Interaction Pact::given(const char* provider_state) const {
return Interaction(this, "__new_interaction__").given(provider_state);
}
Interaction Pact::given(const char* provider_state, const std::unordered_map<std::string, std::string>& parameters) const {
return Interaction(this, "__new_interaction__").given(provider_state, parameters);
}
PactTestResult Pact::run_test(std::function<bool(const MockServerHandle*)> callback) const {
MockServerHandle mockServer(this->pact);
PactTestResult result;
if (mockServer.started_ok()) {
try {
bool callback_result = callback(&mockServer);
bool mock_server_result = mock_server_matched(mockServer.get_port());
if (callback_result && mock_server_result) {
auto write_result = write_pact_file(mockServer.get_port(), this->pact_directory.data());
switch (write_result) {
case 1:
result.add_state(TestResultState::PactFileError, "A general panic was caught");
break;
case 2:
result.add_state(TestResultState::PactFileError, "The pact file was not able to be written");
break;
case 3:
result.add_state(TestResultState::PactFileError, "A mock server with the provided port was not found");
break;
}
}
} catch(const std::exception& e) {
result.add_state(TestResultState::UserCodeFailed, e.what(), boost::current_exception_diagnostic_information());
} catch (...) {
result.add_state(TestResultState::UserCodeFailed);
}
if (!mock_server_matched(mockServer.get_port())) {
std::string mismatches = mock_server_mismatches(mockServer.get_port());
result.add_state(TestResultState::Mismatches, mismatches);
}
} else {
result.add_state(TestResultState::MockServerFailed);
}
if (!result.is_ok()) {
result.display_errors();
}
return result;
}
////////////////////////////////////
// Interaction Class
////////////////////////////////////
Interaction::Interaction(const Pact* parent, const char* description) {
this->pact = parent;
this->description = description;
this->interaction = pact_mock_server_ffi::new_interaction(parent->pact, description);
if (this->interaction.interaction == 0) {
throw std::string("Could not create a new interaction with description ") + description;
}
}
Interaction Interaction::uponReceiving(const char* description) const {
pact_mock_server_ffi::upon_receiving(this->interaction, description);
return *this;
}
Interaction Interaction::given(const char* provider_state) const {
pact_mock_server_ffi::given(this->interaction, provider_state);
return *this;
}
Interaction Interaction::given(const char* provider_state, const std::unordered_map<std::string, std::string>& parameters) const {
for (auto& p : parameters) {
pact_mock_server_ffi::given_with_param(this->interaction, provider_state, p.first.data(), p.second.data());
}
return *this;
}
Interaction Interaction::withRequest(const char* method, const char* path) const {
pact_mock_server_ffi::with_request(this->interaction, method, path);
return *this;
}
Interaction Interaction::withQuery(const std::unordered_map<std::string, std::vector<std::string>>& query) const {
for (auto& q : query) {
for (auto it = q.second.begin(); it != q.second.end(); it++) {
pact_mock_server_ffi::with_query_parameter(this->interaction, q.first.data(), it - q.second.begin(), it->data());
}
}
return *this;
}
Interaction Interaction::withHeaders(const std::unordered_map<std::string, std::vector<std::string>>& headers) const {
for (auto& h : headers) {
for (auto it = h.second.begin(); it != h.second.end(); it++) {
pact_mock_server_ffi::with_header(this->interaction, pact_mock_server_ffi::InteractionPart::Request, h.first.data(), it - h.second.begin(), it->data());
}
}
return *this;
}
Interaction Interaction::withBody(const std::string& body, const std::string& content_type) const {
pact_mock_server_ffi::with_body(this->interaction, pact_mock_server_ffi::InteractionPart::Request, content_type.data(), body.data());
return *this;
}
Interaction Interaction::withJsonBody(pact_consumer::matchers::IMatcher::Ptr body) const {
pact_mock_server_ffi::with_body(this->interaction, pact_mock_server_ffi::InteractionPart::Request, "application/json;charset=UTF-8",
body->getJson().data());
return *this;
}
Interaction Interaction::withBinaryFile(const std::string& content_type, const std::filesystem::path& example_file) const {
std::ifstream file (example_file, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size)) {
pact_mock_server_ffi::with_binary_file(this->interaction, pact_mock_server_ffi::InteractionPart::Request, content_type.data(),
buffer.data(), size);
return *this;
} else {
throw std::string("Could not read file contents: ") + example_file.string();
}
}
Interaction Interaction::withMultipartFileUpload(const std::string& part_name, const std::string& content_type, const std::filesystem::path& example_file) const {
auto result = pact_mock_server_ffi::with_multipart_file(this->interaction, pact_mock_server_ffi::InteractionPart::Request, content_type.data(),
example_file.string().data(), part_name.data());
if (result.tag == pact_mock_server_ffi::StringResult::Tag::Failed) {
std::string error = result.failed._0;
pact_mock_server_ffi::free_string(result.failed._0);
BOOST_THROW_EXCEPTION(std::runtime_error(error));
}
return *this;
}
Interaction Interaction::willRespondWith(size_t status) const {
pact_mock_server_ffi::response_status(this->interaction, status);
return *this;
}
Interaction Interaction::withResponseHeaders(const std::unordered_map<std::string, std::vector<std::string>>& headers) const {
for (auto h : headers) {
for (auto it = h.second.begin(); it != h.second.end(); it++) {
pact_mock_server_ffi::with_header(this->interaction, pact_mock_server_ffi::InteractionPart::Response, h.first.data(), it - h.second.begin(), it->data());
}
}
return *this;
}
Interaction Interaction::withResponseBody(const std::string& body, const std::string& content_type) const {
pact_mock_server_ffi::with_body(this->interaction, pact_mock_server_ffi::InteractionPart::Response, content_type.data(),
body.data());
return *this;
}
Interaction Interaction::withResponseJsonBody(pact_consumer::matchers::IMatcher::Ptr body) const {
pact_mock_server_ffi::with_body(this->interaction, pact_mock_server_ffi::InteractionPart::Response, "application/json;charset=UTF-8",
body->getJson().data());
return *this;
}
Interaction Interaction::withResponseBinaryFile(const std::string& content_type, const std::filesystem::path& example_file) const {
std::ifstream file (example_file, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size)) {
pact_mock_server_ffi::with_binary_file(this->interaction, pact_mock_server_ffi::InteractionPart::Response, content_type.data(),
buffer.data(), size);
return *this;
} else {
throw std::string("Could not read file contents: ") + example_file.string();
}
}
Interaction Interaction::withResponseMultipartFileUpload(const std::string& part_name, const std::string& content_type, const std::filesystem::path& example_file) const {
auto result = pact_mock_server_ffi::with_multipart_file(this->interaction, pact_mock_server_ffi::InteractionPart::Response, content_type.data(),
example_file.string().data(), part_name.data());
if (result.tag == pact_mock_server_ffi::StringResult::Tag::Failed) {
std::string error = result.failed._0;
pact_mock_server_ffi::free_string(result.failed._0);
BOOST_THROW_EXCEPTION(std::runtime_error(error));
}
return *this;
}
////////////////////////////////////
// Mock Server Class
////////////////////////////////////
MockServerHandle::MockServerHandle(pact_mock_server_ffi::PactHandle pact) {
this->port = pact_mock_server_ffi::create_mock_server_for_pact(pact, "127.0.0.1:0", false);
}
MockServerHandle::~MockServerHandle() {
pact_mock_server_ffi::cleanup_mock_server(this->port);
}
bool MockServerHandle::started_ok() const {
return this->port > 0;
}
std::string MockServerHandle::get_url() const {
std::ostringstream out;
out << "http://127.0.0.1:" << this->port;
return out.str();
}
int32_t MockServerHandle::get_port() const {
return this->port;
}
////////////////////////////////////
// Pact Test Result Class
////////////////////////////////////
PactTestResult::PactTestResult() {
this->messages.resize(TestResultState::MockServerFailed + 1);
}
void PactTestResult::add_state(TestResultState state) {
this->status |= state;
}
void PactTestResult::add_state(TestResultState state, std::string message) {
this->status |= state;
this->messages[state] = message;
}
void PactTestResult::add_state(TestResultState state, std::string message, std::string ex) {
this->status |= state;
this->messages[state] = message;
this->ex = ex;
}
bool PactTestResult::is_ok() const {
return this->status == 0;
}
void PactTestResult::display_errors() {
if (this->status != 0) {
std::cout << "\nThe test failed for the following reasons:\n\n";
if (this->status & TestResultState::Mismatches) {
if (this->messages[TestResultState::Mismatches].empty()) {
std::cout << " * Not all the requests matched\n\n";
} else {
std::cout << " * The following mismatches occurred:\n\n";
auto mismatches_str = this->messages[TestResultState::Mismatches];
auto j = json::parse(mismatches_str);
int i = 1;
for (json::iterator it = j.begin(); it != j.end(); ++it, i++) {
auto mismatch = *it;
std::string type = mismatch["type"];
if (type == "request-not-found") {
std::cout << " " << i << ") An unexpected request was received: " << mismatch["method"] << " " << mismatch["path"] << "\n\n";
} else if (type == "missing-request") {
std::cout << " " << i << ") An expected request was not received: " << mismatch["method"] << " " << mismatch["path"] << "\n\n";
} else if (type == "request-mismatch") {
std::cout << " " << i << ") Mismatched request was received: " << mismatch["method"] << " " << mismatch["path"] << "\n\n";
auto mismatches = mismatch["mismatches"];
int m = 1;
for (json::iterator it = mismatches.begin(); it != mismatches.end(); ++it, m++) {
auto mismatch_details = *it;
std::string mismatch_type = mismatch_details["type"];
if (mismatch_type == "MethodMismatch") {
std::string expected = mismatch_details["expected"];
std::string actual = mismatch_details["actual"];
std::cout << " " << i << "." << m << ") Method: Expected " << expected << " but was " << actual << "\n";
} else if (mismatch_type == "PathMismatch") {
std::string mismatch = mismatch_details["mismatch"];
std::cout << " " << i << "." << m << ") Path: " << mismatch << "\n";
} else if (mismatch_type == "StatusMismatch") {
std::string expected = mismatch_details["expected"];
std::string actual = mismatch_details["actual"];
std::cout << " " << i << "." << m << ") Status: Expected " << expected << " but was " << actual << "\n";
} else if (mismatch_type == "QueryMismatch") {
std::string mismatch = mismatch_details["mismatch"];
std::cout << " " << i << "." << m << ") Query Parameter: " << mismatch << "\n";
} else if (mismatch_type == "HeaderMismatch") {
std::string mismatch = mismatch_details["mismatch"];
std::cout << " " << i << "." << m << ") Header: " << mismatch << "\n";
} else if (mismatch_type == "BodyTypeMismatch") {
std::string expected = mismatch_details["expected"];
std::string actual = mismatch_details["actual"];
std::cout << " " << i << "." << m << ") Body Type: Expected " << expected << " but was " << actual << "\n";
} else if (mismatch_type == "BodyMismatch") {
std::string path = mismatch_details["path"];
std::string mismatch = mismatch_details["mismatch"];
std::cout << " " << i << "." << m << ") Body: " << path << " - " << mismatch << "\n";
} else {
std::cout << " " << i << "." << m << ") An unknown type of mismatch occurred: " << mismatch_type << "\n";
}
}
}
}
}
}
if (this->status & TestResultState::UserCodeFailed) {
auto message = this->messages[TestResultState::UserCodeFailed];
if (message.empty()) {
std::cout << " * Test callback failed with an exception\n\n";
} else {
std::cout << " * Test callback failed with an exception: " << message << "\n\n";
}
if (ex.has_value()) {
std::cout << " " << ex.value() << "\n";
}
}
if (this->status & TestResultState::PactFileError) {
auto message = this->messages[TestResultState::PactFileError];
if (message.empty()) {
std::cout << " * Failed to write the Pact file\n";
} else {
std::cout << " * Failed to write the Pact file: " << message << "\n";
}
}
if (this->status & TestResultState::MockServerFailed) {
auto message = this->messages[TestResultState::MockServerFailed];
if (message.empty()) {
std::cout << " * Mock server failed to start\n";
} else {
std::cout << " * Mock server failed to start: " << message << "\n";
}
}
}
std::cout << "\n";
}
}
| 42.60989 | 172 | 0.61225 | [
"vector"
] |
c5126033cdd1a27d09b64d183b6a7b7d893efde3 | 9,292 | cpp | C++ | passes/caml_alloc_inliner.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 2 | 2019-03-02T20:48:18.000Z | 2019-05-08T21:18:00.000Z | passes/caml_alloc_inliner.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | null | null | null | passes/caml_alloc_inliner.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 1 | 2019-11-18T20:20:34.000Z | 2019-11-18T20:20:34.000Z | // This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#include "core/cast.h"
#include "core/block.h"
#include "core/prog.h"
#include "core/func.h"
#include "core/insts.h"
#include "passes/caml_alloc_inliner.h"
// -----------------------------------------------------------------------------
const char *CamlAllocInlinerPass::kPassID = "caml-alloc-inliner";
// -----------------------------------------------------------------------------
static void InlineCall(CallSite *call, Block *cont, Block *raise)
{
Block *block = call->getParent();
Func *func = block->getParent();
Prog *prog = func->getParent();
// Identify calls to globals.
auto movInst = ::cast_or_null<MovInst>(call->GetCallee());
if (!movInst) {
return;
}
auto movGlobal = ::cast_or_null<Global>(movInst->GetArg());
if (!movGlobal) {
return;
}
// Call must receive two arguments: Caml_state and Caml_state->young_ptr.
Ref<Inst> statePtr = call->arg(0);
Ref<Inst> youngPtr = call->arg(1);
Ref<Inst> youngLimit = call->arg_size() > 2 ? call->arg(2) : nullptr;
Ref<Inst> exnPtr = call->arg_size() > 3 ? call->arg(3) : nullptr;
// Find the byte adjustment to insert.
std::optional<unsigned> bytes;
if (movGlobal->getName() == "caml_alloc1") {
bytes = 16;
} else if (movGlobal->getName() == "caml_alloc2") {
bytes = 24;
} else if (movGlobal->getName() == "caml_alloc3") {
bytes = 32;
} else if (movGlobal->getName() == "caml_allocN") {
bytes = {};
} else {
return;
}
// Insert the byte adjustment at the end of the call block.
if (bytes) {
auto *constInst = new MovInst(Type::I64, new ConstantInt(*bytes), {});
block->AddInst(constInst);
auto *addInst = new SubInst(Type::I64, youngPtr, constInst, {});
block->AddInst(addInst);
youngPtr = addInst;
}
// Prepare phis in the no-collection branch.
//
//
// Originally, a call looks like:
//
// call.caml_alloc.i64.i64 $state, $ptr, fn, $old_state, $old_ptr, .L
//.L:
// ... use $state, $ptr ...
//
// The call is changed into:
//
//.Lsrc:
// add.i64 $new_ptr, $old_ptr
// ld.i64 $young_limit, [$state_ptr + 8]
// cmp.uge.i8 $flag, $new_ptr, $young_limit
// jcc $flag, .L, .Lgc
//.L:
// phi.i64 $state_ptr_phi, .Lsrc, $state_ptr, .Lgc, $state_ptr_gc
// phi.i64 $young_ptr_phi, .Lsrc, $new_ptr, .Lgc, $young_ptr_gc
// ... use phis ...
//
//.Lgc:
// mov.i64 $fn, caml_call_gc
// call.caml_gc $state_ptr_gc, $young_ptr_gc, $fn, $state_ptr, $new_ptr, .L
Block *noGcBlock;
PhiInst *statePtrPhi;
PhiInst *youngPtrPhi;
PhiInst *youngLimitPhi = nullptr;
PhiInst *exnPtrPhi = nullptr;
if (!cont) {
std::vector<Ref<Inst>> phis;
noGcBlock = new Block(block->getName());
func->insertAfter(std::next(block->getIterator()), noGcBlock);
statePtrPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(statePtrPhi);
phis.push_back(statePtrPhi);
youngPtrPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(youngPtrPhi);
phis.push_back(youngPtrPhi);
if (youngLimit) {
youngLimitPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(youngLimitPhi);
phis.push_back(youngLimitPhi);
}
if (exnPtr) {
exnPtrPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(exnPtrPhi);
phis.push_back(exnPtrPhi);
}
ReturnInst *retInst = new ReturnInst(phis, {});
noGcBlock->AddInst(retInst);
assert(call->use_empty() && "tail call has uses");
} else {
std::vector<Ref<Inst>> phis;
if (cont->pred_size() == 1) {
noGcBlock = cont;
} else {
noGcBlock = new Block((block->getName() + "no_gc").str());
func->insertAfter(std::next(block->getIterator()), noGcBlock);
JumpInst *jump = new JumpInst(noGcBlock, {});
noGcBlock->AddInst(jump);
}
statePtrPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(statePtrPhi, &*noGcBlock->begin());
phis.push_back(statePtrPhi);
youngPtrPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(youngPtrPhi, &*noGcBlock->begin());
phis.push_back(youngPtrPhi);
if (youngLimit) {
youngLimitPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(youngLimitPhi, &*noGcBlock->begin());
phis.push_back(youngLimitPhi);
}
if (exnPtr) {
exnPtrPhi = new PhiInst(Type::I64);
noGcBlock->AddInst(exnPtrPhi, &*noGcBlock->begin());
phis.push_back(exnPtrPhi);
}
call->replaceAllUsesWith(phis);
}
AnnotSet annot = call->GetAnnots();
call->eraseFromParent();
std::vector<Type> callType;
statePtrPhi->Add(block, statePtr);
callType.push_back(Type::I64);
youngPtrPhi->Add(block, youngPtr);
callType.push_back(Type::I64);
if (youngLimit) {
youngLimitPhi->Add(block, youngLimit);
callType.push_back(Type::I64);
}
if (exnPtr) {
exnPtrPhi->Add(block, exnPtr);
callType.push_back(Type::I64);
}
// Create the GC block.
Block *gcBlock = new Block((block->getName() + "gc").str());
{
func->AddBlock(gcBlock);
Global *gcFunc = prog->GetGlobalOrExtern("caml_call_gc");
MovInst *gcName = new MovInst(Type::I64, gcFunc, {});
gcBlock->AddInst(gcName);
Inst *gcCall;
std::vector<Ref<Inst>> gcArgs;
gcArgs.push_back(statePtr);
gcArgs.push_back(youngPtr);
if (youngLimit) {
gcArgs.push_back(youngLimit);
}
if (exnPtr) {
gcArgs.push_back(exnPtr);
}
if (raise) {
gcCall = new InvokeInst(
callType,
gcName,
gcArgs,
std::vector<TypeFlag>(gcArgs.size(), TypeFlag::GetNone()),
CallingConv::CAML_GC,
std::nullopt,
noGcBlock,
raise,
std::move(annot)
);
for (PhiInst &phi : raise->phis()) {
Ref<Inst> val = phi.GetValue(block);
phi.Remove(block);
phi.Add(gcBlock, val);
}
} else {
gcCall = new CallInst(
callType,
gcName,
gcArgs,
std::vector<TypeFlag>(gcArgs.size(), TypeFlag::GetNone()),
CallingConv::CAML_GC,
std::nullopt,
noGcBlock,
std::move(annot)
);
}
gcBlock->AddInst(gcCall);
statePtrPhi->Add(gcBlock, gcCall->GetSubValue(0));
youngPtrPhi->Add(gcBlock, gcCall->GetSubValue(1));
if (youngLimit) {
youngLimitPhi->Add(gcBlock, gcCall->GetSubValue(2));
}
if (exnPtr) {
exnPtrPhi->Add(gcBlock, gcCall->GetSubValue(3));
}
}
// Either use the cached limit or load it from the state.
Ref<Inst> youngLimitVal;
if (youngLimitPhi) {
youngLimitVal = youngLimit;
} else {
MovInst *offInst = new MovInst(Type::I64, new ConstantInt(8), {});
block->AddInst(offInst);
AddInst *addInst = new AddInst(Type::I64, statePtr, offInst, {});
block->AddInst(addInst);
LoadInst *loadInst = new LoadInst(Type::I64, addInst, {});
block->AddInst(loadInst);
youngLimitVal = loadInst;
}
// Add the comparison dispatching either to the gc or no gc blocks.
CmpInst *cmpInst = new CmpInst(
Type::I8,
youngPtr,
youngLimitVal,
Cond::UGE,
{}
);
block->AddInst(cmpInst);
JumpCondInst *jccInst = new JumpCondInst(cmpInst, noGcBlock, gcBlock, {});
jccInst->SetAnnot<Probability>(1, 1);
block->AddInst(jccInst);
}
// -----------------------------------------------------------------------------
bool CamlAllocInlinerPass::Run(Prog &prog)
{
bool changed = false;
for (Func &func : prog) {
if (func.GetCallingConv() != CallingConv::CAML) {
continue;
}
for (auto bt = func.begin(); bt != func.end(); ) {
auto *term = (bt++)->GetTerminator();
switch (term->GetKind()) {
case Inst::Kind::CALL: {
auto *call = static_cast<CallInst *>(term);
if (call->GetCallingConv() != CallingConv::CAML_ALLOC) {
continue;
}
InlineCall(call, call->GetCont(), nullptr);
changed = true;
continue;
}
case Inst::Kind::TAIL_CALL: {
auto *call = static_cast<TailCallInst *>(term);
if (call->GetCallingConv() != CallingConv::CAML_ALLOC) {
continue;
}
InlineCall(call, nullptr, nullptr);
changed = true;
continue;
}
case Inst::Kind::INVOKE: {
auto *call = static_cast<InvokeInst *>(term);
if (call->GetCallingConv() != CallingConv::CAML_ALLOC) {
continue;
}
InlineCall(call, call->GetCont(), call->GetThrow());
changed = true;
continue;
}
case Inst::Kind::RETURN:
case Inst::Kind::JUMP_COND:
case Inst::Kind::JUMP:
case Inst::Kind::SWITCH:
case Inst::Kind::TRAP:
case Inst::Kind::DEBUG_TRAP:
case Inst::Kind::RAISE: {
continue;
}
default: {
llvm_unreachable("not a terminator");
}
}
}
}
return changed;
}
// -----------------------------------------------------------------------------
const char *CamlAllocInlinerPass::GetPassName() const
{
return "OCaml allocation inlining";
}
| 28.94704 | 80 | 0.579746 | [
"vector"
] |
78a10bcf5b65d8fb1f6dee5d903f060e8e805f9c | 38,781 | cpp | C++ | src/ETISS.cpp | Samanti-Das/etiss_new | b3f3e80e36bed0c162c6d6e6b0d47d77e21e32a2 | [
"BSD-3-Clause"
] | null | null | null | src/ETISS.cpp | Samanti-Das/etiss_new | b3f3e80e36bed0c162c6d6e6b0d47d77e21e32a2 | [
"BSD-3-Clause"
] | 14 | 2021-03-17T13:18:56.000Z | 2021-06-08T17:21:16.000Z | src/ETISS.cpp | Samanti-Das/etiss_new | b3f3e80e36bed0c162c6d6e6b0d47d77e21e32a2 | [
"BSD-3-Clause"
] | 1 | 2021-09-14T12:29:46.000Z | 2021-09-14T12:29:46.000Z | /**
@copyright
<pre>
Copyright 2018 Infineon Technologies AG
This file is part of ETISS tool, see <https://github.com/tum-ei-eda/etiss>.
The initial version of this software has been created with the funding support by the German Federal
Ministry of Education and Research (BMBF) in the project EffektiV under grant 01IS13022.
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.
</pre>
@author Marc Greim <marc.greim@mytum.de>, Chair of Electronic Design Automation, TUM
@date July 29, 2014
@version 0.1
*/
/**
@file ETISS.cpp
@brief Implementation of etiss/ETISS.h except for
etiss::preloadLibraries
@detail
*/
#include "etiss/ETISS.h"
#include "etiss/fault/Stressor.h"
#include <csignal>
#include <cstring>
#include <fstream>
#include <functional>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/algorithm/string.hpp>
#if ETISS_USE_DLSYM
#include <dlfcn.h>
#endif
using namespace etiss;
std::string etiss_defaultjit_;
std::list<std::shared_ptr<etiss::LibraryInterface>> etiss_libraries_;
std::recursive_mutex etiss_libraries_mu_;
boost::program_options::variables_map vm;
std::vector<std::string> pluginOptions = {"plugin.logger.logaddr", "plugin.logger.logmask", "plugin.gdbserver.port"};
std::set<std::string> etiss::listCPUArchs()
{
std::set<std::string> ret;
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
if ((*iter).get() != 0)
{
if (!(*iter)->isEmpty())
{
for (unsigned i = 0; i < (*iter)->countCPUArchs(); i++)
{
std::string jit = (*iter)->nameCPUArch(i);
if (ret.find(jit) != ret.end())
{
etiss::log(etiss::ERROR, "CPUArch provided by multiple libraries: \"" + jit + "\"");
}
else
{
ret.insert(jit);
}
}
}
}
}
return ret;
}
std::set<std::string> etiss::listJITs()
{
std::set<std::string> ret;
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
if ((*iter).get() != 0)
{
if (!(*iter)->isEmpty())
{
for (unsigned i = 0; i < (*iter)->countJITs(); i++)
{
std::string jit = (*iter)->nameJIT(i);
if (ret.find(jit) != ret.end())
{
etiss::log(etiss::ERROR, "JIT provided by multiple libraries: \"" + jit + "\"");
}
else
{
ret.insert(jit);
}
}
}
}
}
return ret;
}
std::set<std::string> etiss::listPlugins()
{
std::set<std::string> ret;
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
if ((*iter).get() != 0)
{
if (!(*iter)->isEmpty())
{
for (unsigned i = 0; i < (*iter)->countPlugins(); i++)
{
std::string jit = (*iter)->namePlugin(i);
if (ret.find(jit) != ret.end())
{
etiss::log(etiss::ERROR, "JIT provided by multiple libraries: \"" + jit + "\"");
}
else
{
ret.insert(jit);
}
}
}
}
}
return ret;
}
std::shared_ptr<JIT> etiss::getJIT(std::string name, std::map<std::string, std::string> options)
{
std::shared_ptr<JIT> jit;
std::string ujit;
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
std::shared_ptr<LibraryInterface> lib = *iter;
if (lib.get() != 0)
{
if (!lib->isEmpty())
{
for (unsigned i = 0; i < lib->countJITs(); i++)
{
if (lib->nameJIT(i) == name)
{
if (jit.get() != 0)
{
etiss::log(etiss::ERROR, "JIT provided by multiple libraries: using \"" + name +
"\" from library \"" + ujit +
"\" [also provided by library \"" + lib->getName() + "\"]");
}
else
{
etiss::JIT *ca = lib->createJIT(i, options);
if (ca == 0)
{
etiss::log(etiss::ERROR,
"Failed to create JIT via library interface \"" + lib->getName() + "\"");
}
else
{
jit = std::shared_ptr<JIT>(ca, [lib](JIT *j) { lib->deleteJIT(j); });
ujit = lib->getName();
}
}
}
}
}
}
}
return jit;
}
std::shared_ptr<CPUArch> etiss::getCPUArch(std::string name, std::map<std::string, std::string> options)
{
std::shared_ptr<CPUArch> arch;
std::string uarch;
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
std::shared_ptr<LibraryInterface> lib = *iter;
if (lib.get() != 0)
{
if (!lib->isEmpty())
{
for (unsigned i = 0; i < lib->countCPUArchs(); i++)
{
if (lib->nameCPUArch(i) == name)
{
if (arch.get() != 0)
{
etiss::log(etiss::ERROR, "CPU Architecture provided by multiple libraries: using \"" +
name + "\" from library \"" + uarch +
"\" [also provided by library \"" + lib->getName() + "\"]");
}
else
{
etiss::CPUArch *ca = lib->createCPUArch(i, options);
if (ca == 0)
{
etiss::log(etiss::ERROR,
"Failed to create CPUArch via library interface \"" + lib->getName() + "\"");
}
else
{
arch = std::shared_ptr<CPUArch>(ca, [lib](CPUArch *a) { lib->deleteCPUArch(a); });
uarch = lib->getName();
}
}
}
}
}
}
}
return arch;
}
std::shared_ptr<Plugin> etiss::getPlugin(std::string name, std::map<std::string, std::string> options)
{
std::shared_ptr<Plugin> ptrPlugin;
std::string strPluginName;
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
std::shared_ptr<LibraryInterface> lib = *iter;
if (lib.get() != 0)
{
if (!lib->isEmpty())
{
for (unsigned i = 0; i < lib->countPlugins(); i++)
{
if (lib->namePlugin(i) == name)
{
if (ptrPlugin.get() != 0)
{
etiss::log(etiss::ERROR, "Plugin provided by multiple libraries: using \"" + name +
"\" from library \"" + strPluginName +
"\" [also provided by library \"" + lib->getName() + "\"]");
}
else
{
etiss::Plugin *ca = lib->createPlugin(i, options);
if (ca == 0)
{
etiss::log(etiss::ERROR,
"Failed to create Plugin via library interface \"" + lib->getName() + "\"");
}
else
{
ptrPlugin = std::shared_ptr<Plugin>(ca, [lib](Plugin *p) { lib->deletePlugin(p); });
strPluginName = lib->getName();
etiss::log(etiss::INFO, "Plugin \"" + name + "\" loaded via library interface \"" +
strPluginName + "\"\n");
}
}
break;
}
}
}
}
}
return ptrPlugin;
}
bool etiss::loadLibrary(std::string path, std::string name)
{
auto lib = etiss::LibraryInterface::openSharedLibrary(path, name);
if (lib.get())
{
addLibrary(lib);
return true;
}
return false;
}
void etiss::addLibrary(std::shared_ptr<etiss::LibraryInterface> libInterface)
{
etiss::LibraryInterface *lif = libInterface.get();
if (lif == 0)
{
return;
}
etiss::forceInitialization();
{
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
etiss_libraries_.push_back(libInterface);
}
// if no default jit is present, try to use one from this library
for (unsigned i = 0; (etiss_defaultjit_.size() <= 0) && (i < libInterface->countJITs()); i++)
{
etiss_defaultjit_ = libInterface->nameJIT(i);
}
}
std::set<std::string> etiss::listLibraries()
{
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
std::set<std::string> ret;
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
ret.insert((*iter)->getName() + "[" + (*iter)->versionInfo() + "]");
}
return ret;
}
std::set<std::string> etiss::listLibraryPrefixes()
{
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
std::set<std::string> ret;
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
ret.insert((*iter)->getName());
}
return ret;
}
std::shared_ptr<etiss::JIT> etiss::getDefaultJIT()
{
return getJIT(etiss_defaultjit_);
}
// transfer controll to etiss console on SIGINT
void (*etiss_prev_SIGINT_handler)(int) = 0;
bool etiss_SIGINT_handler_enabled = false;
void etiss_SIGINT_handler(int sig)
{
if (sig == SIGINT)
{
std::cout << std::endl << "\033[0;31m" << std::endl;
/// TODO etiss::transferCMDControll();
std::cout << std::endl << "\033[0m" << std::endl;
}
else
{ // false handler assignment
signal(sig, SIG_DFL);
raise(sig);
return;
}
}
//__attribute__((destructor))
static void etiss_remove_SIGINT()
{
if (etiss_SIGINT_handler_enabled)
{
etiss_prev_SIGINT_handler = signal(SIGINT, etiss_prev_SIGINT_handler);
etiss_SIGINT_handler_enabled = false;
}
}
/// replaces __attribute__((destructor)) in a portable way
static class helper_class_etiss_2
{
public:
~helper_class_etiss_2() { etiss_remove_SIGINT(); }
} helper_class_etiss_2;
// initialize
CSimpleIniA *po_simpleIni;
void etiss_loadIni(std::string fileName)
{
if (po_simpleIni == NULL)
po_simpleIni = new CSimpleIniA(true, true, true);
SI_Error rc = po_simpleIni->LoadFile(fileName.c_str());
if (rc < 0)
std::cout << "Initializer::loadIni(): Failed to load Ini: " << fileName << std::endl;
else
std::cout << "Initializer::loadIni(): Ini sucessfully loaded " << fileName << std::endl;
}
void etiss::Initializer::loadIni(std::list<std::string> *files)
{
std::cout << " Load ini file." << std::endl;
// create ini parser
if (po_simpleIni == NULL)
po_simpleIni = new CSimpleIniA(true, true, true);
else
std::cout << "Info: simpleIni already exists!" << std::endl;
// load file
for (auto it_files : *files)
{
// the check above is sufficient no need for this / checked for previous cases false and last true gives true not the case based on files structure
etiss_loadIni(it_files);
}
}
void etiss_loadIniConfigs()
{
if (!po_simpleIni) // no .ini files were given.
{
return;
}
std::cout << " Load Configs from .ini files:" << std::endl;
// preload loglevel
if (!etiss::cfg().isSet("etiss.loglevel"))
{
etiss::cfg().set<int>("etiss.loglevel", po_simpleIni->GetLongValue("IntConfigurations", "etiss.loglevel", etiss::WARNING));
}
{
int ll = cfg().get<int>("etiss.loglevel", etiss::WARNING);
if (ll >= 0 && ll <= etiss::VERBOSE)
{ // valid log level
// dnm
// etiss::verbosity() = etiss::VERBOSE;
etiss::verbosity() = (Verbosity)ll;
etiss::log(etiss::VERBOSE, "Log level set to VERBOSE");
}
else
{
etiss::verbosity() = etiss::WARNING;
etiss::log(etiss::ERROR, "Specified log level is not valid. must range between 0 (= "
"silent) and 5 (= verbose)");
}
}
// get all sections
CSimpleIniA::TNamesDepend sections;
po_simpleIni->GetAllSections(sections);
for (auto iter_section : sections)
{
// only load config sections
if (std::string(iter_section.pItem) != "StringConfigurations" &&
std::string(iter_section.pItem) != "BoolConfigurations" &&
std::string(iter_section.pItem) != "IntConfigurations")
{
continue;
}
etiss::log(etiss::INFO, std::string(" [") + iter_section.pItem + ']');
// get all keys in a section
CSimpleIniA::TNamesDepend keys;
po_simpleIni->GetAllKeys(iter_section.pItem, keys);
for (auto iter_key : keys)
{
std::stringstream message;
bool warning = false;
// skip loglevel
if (std::string(iter_key.pItem) == "etiss.loglevel")
continue;
// check if cfg is already set
if (etiss::cfg().isSet(iter_key.pItem))
{
message << " cfg already set on command line. ";
message << " " << iter_key.pItem << "=";
const ::std::type_info& type = vm[std::string(iter_key.pItem)].value().type() ;
if (type == typeid(::std::string))
message << vm[std::string(iter_key.pItem)].as<std::string>() << ",";
else if (type == typeid(int))
message << vm[std::string(iter_key.pItem)].as<int>() << ",";
else if (type == typeid(bool))
message << std::boolalpha << vm[std::string(iter_key.pItem)].as<bool>() << ",";
warning = true;
}
else
{
// write key (=option) to message.
message << " " << iter_key.pItem << "=";
// get all values of a key with multiple values
CSimpleIniA::TNamesDepend values;
po_simpleIni->GetAllValues(iter_section.pItem, iter_key.pItem, values);
for (auto iter_value : values)
{
// Handle configurations
if (std::string(iter_section.pItem) == "StringConfigurations")
{
etiss::cfg().set<std::string>(iter_key.pItem, iter_value.pItem);
}
else if (std::string(iter_section.pItem) == "BoolConfigurations")
{
std::string itemval = iter_value.pItem;
boost::algorithm::to_lower(itemval); // converts itemval to lower case string
bool val;
if ((itemval == "true") | (itemval == "yes") | (itemval == "1") | (itemval == "T"))val = true;
else if ((itemval == "false") | (itemval == "no") | (itemval == "0") | (itemval == "F"))val = false;
else etiss::log(etiss::FATALERROR, "Configuration value name could not be parsed as a boolean");
etiss::cfg().set<bool>(iter_key.pItem, val);
}
else if (std::string(iter_section.pItem) == "IntConfigurations") // already load!
{
std::string itemval = iter_value.pItem;
std::size_t sz = 0;
long long val;
try{
val = std::stoll(itemval, &sz, 0);
}
// catch invalid_argument exception.
catch(const std::invalid_argument){
etiss::log(etiss::FATALERROR, "Configuration value name could not be parsed as an integer");
}
etiss::cfg().set<long long>(iter_key.pItem, val);
// we use double, as long could have only 32 Bit (e.g. on Windows)
// and long long is not offered by the ini library
}
else
// we don't add a DoubleConfigurations section, as converting them
// to and from strings could provoke accuracy issues.
// To support double, a Configuration::get<double>() has to be
// added to Misc.cpp
{
message << " Section not found for Value:";
warning = true;
}
// write item (=option value) to message.
message << iter_value.pItem << ",";
}
// check if more than one value is set in the ini file
if (values.size() > 1)
{
warning = true;
message << " Multi values. Take only LAST one!";
}
}
// add message to etiss log.
etiss::log(warning ? etiss::WARNING : etiss::INFO, message.str());
}
}
}
void etiss::Initializer::loadIniPlugins(std::shared_ptr<etiss::CPUCore> cpu)
{
std::map<std::string, std::string> options;
for (auto iter = pluginOptions.begin(); iter != pluginOptions.end(); iter++)
{
if (etiss::cfg().isSet(*iter))
{
options[*iter] = std::string(vm[std::string(*iter)].as<std::string>());
etiss::log(etiss::INFO, *iter + " written from command line\n" + " options[" +
std::string(*iter) +
"] = " + std::string(vm[std::string(*iter)].as<std::string>()) + "\n");
}
}
if (vm.count("pluginToLoad"))
{
const std::vector<std::string> pluginList = vm["pluginToLoad"].as<std::vector<std::string>>();
for (auto pluginName = pluginList.begin(); pluginName != pluginList.end(); pluginName++)
{
std::string::size_type pos = std::string(*pluginName).length();
bool pluginAlreadyPresent = false;
for (auto iter : *cpu->getPlugins())
{
std::string pluginNamecpu = iter->getPluginName();
if (pos != std::string::npos)
{
pluginNamecpu = pluginNamecpu.substr(0, pos);
}
if (pluginNamecpu == *pluginName)
{
pluginAlreadyPresent = true;
break;
}
}
if (pluginAlreadyPresent)
{
etiss::log(etiss::WARNING, " Warning: Plugin already present. Skipping it: " + *pluginName + "\n");
continue;
}
etiss::log(etiss::INFO, " Adding Plugin " + *pluginName + "\n");
cpu->addPlugin(etiss::getPlugin(*pluginName, options));
}
}
if (!po_simpleIni)
{
etiss::log(etiss::WARNING, "Ini file not loaded. Can't load plugins from simpleIni!");
return;
}
// get all sections
CSimpleIniA::TNamesDepend sections;
po_simpleIni->GetAllSections(sections);
for (auto iter_section : sections)
{
// only load Plugin sections
if (std::string(iter_section.pItem).substr(0, 6) != std::string("Plugin"))
continue;
std::string pluginName = std::string(iter_section.pItem).substr(7);
std::string::size_type pos = pluginName.length();
// check if Plugin is already present
bool pluginAlreadyPresent = false;
for (auto iter : *cpu->getPlugins())
{
std::string pluginNamecpu = iter->getPluginName();
if (pos != std::string::npos)
{
pluginNamecpu = pluginNamecpu.substr(0, pos);
}
if (pluginNamecpu == pluginName)
{
pluginAlreadyPresent = true;
break;
}
}
if (pluginAlreadyPresent)
{
etiss::log(etiss::WARNING, " Warning: Plugin already present. Skipping it: " + pluginName + "\n");
continue;
}
etiss::log(etiss::INFO, " Adding Plugin " + pluginName + "\n");
// get all keys in a section = plugin option
CSimpleIniA::TNamesDepend keys;
po_simpleIni->GetAllKeys(iter_section.pItem, keys);
for (auto iter_key : keys)
{
// get all values of a key with multiple values = value of option
CSimpleIniA::TNamesDepend values;
po_simpleIni->GetAllValues(iter_section.pItem, iter_key.pItem, values);
if (!etiss::cfg().isSet(iter_key.pItem))
{
std::stringstream ss;
ss << iter_key.pItem << " not set on the command line. Checking in .ini file.";
etiss::log(etiss::INFO, ss.str());
for (auto iter_value : values)
{
options[iter_key.pItem] = iter_value.pItem;
etiss::log(etiss::INFO,
" options[" + std::string(iter_key.pItem) + "] = " + std::string(iter_value.pItem) + "\n\n");
}
// check if more than one value is set in the ini file
if (values.size() > 1)
etiss::log(etiss::WARNING, "Multiple values for option. Took only last one!");
}
}
cpu->addPlugin(etiss::getPlugin(pluginName, options));
}
}
void etiss::Initializer::loadIniJIT(std::shared_ptr<etiss::CPUCore> cpu)
{
// check if JIT is set
if (!etiss::cfg().isSet("jit.type"))
{
etiss::log(etiss::INFO, "No JIT configured. Will use default JIT. \n");
cpu->set(etiss::getDefaultJIT());
return;
}
if (cpu->getJITName() != "")
{
etiss::log(etiss::WARNING,
"etiss::Initializer::loadIniJIT:" + std::string(" JIT already present. Overwriting it."));
}
etiss::log(etiss::INFO, " Adding JIT \"" + cfg().get<std::string>("jit.type", "") + '\"');
cpu->set(getJIT(cfg().get<std::string>("jit.type", "")));
}
std::pair<std::string, std::string> inifileload(const std::string& s)
{
if (s.find("-i") == 0)
{
std::string inifile;
inifile = s.substr(2);
etiss_loadIni(inifile);
}
return make_pair(std::string(), std::string());
}
void etiss_initialize(const std::vector<std::string>& args, bool forced = false)
{
static std::mutex mu_;
static bool initialized_(false);
{
std::lock_guard<std::mutex> lock(mu_);
if (initialized_)
{
if (!forced)
{
etiss::log(etiss::WARNING, "Multiple calls to etiss::initialize");
}
else
{
return;
}
}
else
{
if (forced)
{
etiss::log(etiss::WARNING, "etiss::initialize has not been called before using ETISS library "
"functions. Please add the line \'etiss::initialize(argc,argv);\' "
"at the beginning of \'int main(int argc, char**argv);\'");
}
}
initialized_ = true;
}
{
namespace po = boost::program_options;
try
{
po::options_description desc("Allowed options");
desc.add_options()
("help", "Produce a help message that lists all supported options.")
("arch.cpu", po::value<std::string>(), "The CPU Architecture to simulate.")
("arch.or1k.ignore_sr_iee", po::value<bool>(), "Ignore exception on OpenRISC.")
("arch.or1k.if_stall_cycles", po::value<int>(), "Add instruction stall cycles on OpenRISC.")
("arch.cpu_cycle_time_ps", po::value<int>(), "Sets CPU cycles time on OpenRISC and ARM.")
("etiss.enable_dmi", po::value<bool>(), "Enables the Direct Memory Interface feature of SystemC to speed up memory accesses. This needs to be disabled for memory tracing.")
("etiss.log_pc", po::value<bool>(), "Enables logging of the program counter.")
("etiss.max_block_size", po::value<int>(), "Sets maximum amount of instructions in a block.")
("etiss.output_path_prefix", po::value<std::string>(), "Path prefix to use when writing output files.")
("etiss.loglevel", po::value<int>(), "Verbosity of logging output.")
("jit.gcc.cleanup", po::value<bool>(), "Cleans up temporary files in GCCJIT. ")
("jit.verify", po::value<bool>(), "Run some basic checks to verify the functionality of the JIT engine.")
("jit.debug", po::value<bool>(), "Causes the JIT Engines to compile in debug mode.")
("jit.type", po::value<std::string>(), "The JIT compiler to use.")
("jit.external_headers", po::value<std::string>(), "List of semicolon-separated paths to headers for the JIT to include.")
("jit.external_libs", po::value<std::string>(), "List of semicolon-separated library names for the JIT to link.")
("jit.external_header_paths", po::value<std::string>(), "List of semicolon-separated headers paths for the JIT.")
("jit.external_lib_paths", po::value<std::string>(), "List of semicolon-separated library paths for the JIT.")
("vp.sw_binary_ram", po::value<std::string>(), "Path to binary file to be loaded into RAM.")
("vp.sw_binary_rom", po::value<std::string>(), "Path to binary file to be loaded into ROM.")
("vp.elf_file", po::value<std::string>(), "Load ELF file.")
("vp.stats_file_path", po::value<std::string>(), "Path where the output json file gets stored after bare processor is run.")
("simple_mem_system.print_dbus_access", po::value<bool>(), "Traces accesses to the data bus.")
("simple_mem_system.print_ibus_access", po::value<bool>(), "Traces accesses to the instruction bus.")
("simple_mem_system.print_dbgbus_access", po::value<bool>(), "Traces accesses to the debug bus.")
("simple_mem_system.print_to_file", po::value<bool>(), "Write all tracing to a file instead of the terminal. The file will be located at etiss.output_path_prefix.")
("plugin.logger.logaddr", po::value<std::string>(), "Provides the compare address that is used to check for memory accesses that are redirected to the logger.")
("plugin.logger.logmask", po::value<std::string>(), "Provides the mask that is used to check for memory accesses that are redirected to the logger.")
("plugin.gdbserver.port", po::value<std::string>(), "Option for gdbserver")
("pluginToLoad,p", po::value<std::vector<std::string>>()->multitoken(), "List of plugins to be loaded.")
;
po::command_line_parser parser{args};
po::command_line_parser iniparser{args};
iniparser.options(desc).allow_unregistered().extra_parser(inifileload).run();
parser.options(desc).allow_unregistered().extra_parser(etiss::Configuration::set_cmd_line_boost);
po::parsed_options parsed_options = parser.run();
po::store(parsed_options, vm);
if (vm.count("help"))
{
std::cout << "\nPlease begin all options with --\n\n";
std::cout << desc << "\n";
etiss::log(etiss::FATALERROR, std::string("Please choose the right configurations from the list and re-run.\n"));
}
auto unregistered = po::collect_unrecognized(parsed_options.options, po::include_positional);
for (auto iter_unreg : unregistered)
{
if (iter_unreg.find("-i") != 0 && iter_unreg.find("-p"))
{
etiss::log(etiss::FATALERROR, std::string("Unrecognised option ") + iter_unreg +
"\n\t Please use --help to list all recognised options. \n");
}
}
for (po::variables_map::iterator i = vm.begin() ; i != vm.end() ; ++ i)
{
const po::variable_value& v = i->second;
if (!v.empty())
{
const ::std::type_info& type = v.value().type();
if (type == typeid(::std::string))
{
const ::std::string& val = v.as<::std::string>() ;
etiss::cfg().set<std::string>(std::string(i->first), val);
}
else if (type == typeid(int))
{
int val = v.as<int>();
etiss::cfg().set<int>(std::string(i->first), val);
}
else if (type == typeid(bool))
{
bool val = v.as<bool>();
etiss::cfg().set<bool>(std::string(i->first), val);
}
}
}
}
catch(std::exception& e)
{
etiss::log(etiss::FATALERROR, std::string(e.what()) +
"\n\t Please use --help to list all recognised options. \n");
}
}
etiss_loadIniConfigs();
// log level
{
int ll = cfg().get<int>("etiss.loglevel", etiss::WARNING);
if (ll >= 0 && ll <= etiss::VERBOSE)
{ // valid log level
// dnm
// etiss::verbosity() = etiss::VERBOSE;
etiss::verbosity() = (Verbosity)ll;
etiss::log(etiss::VERBOSE, "Log level set to VERBOSE");
}
else
{
etiss::verbosity() = etiss::WARNING;
etiss::log(etiss::ERROR, "Specified log level is not valid. must range between 0 (= "
"silent) and 5 (= verbose)");
}
}
etiss::py::init(); // init python
etiss_remove_SIGINT();
preloadLibraries();
// load integrated library
if (cfg().get<bool>("etiss.load_integrated_libraries", true))
{
etiss::addLibrary(LibraryInterface::openIntegratedLibrary());
}
// check if some required files can be found
{
std::string path = etiss::installDir();
std::vector<std::string> requiredFiles;
// required files
requiredFiles.push_back(path + "/include/jit/etiss/jit/CPU.h");
// check
for (auto iter = requiredFiles.begin(); iter != requiredFiles.end(); iter++)
{
std::ifstream f(iter->c_str());
if (!f)
{
etiss::log(etiss::WARNING, std::string("Could not find file: ") + *iter + "\n" +
"\t The installation seems broken");
}
}
}
// load fault files
{
std::string faults = cfg().get<std::string>("faults.xml", "");
if (!faults.empty())
{
std::list<std::string> ffs = etiss::split(faults, ';');
for (auto ff : ffs)
{
etiss::fault::Stressor::loadXML(ff);
}
}
}
}
void etiss::initialize(std::vector<std::string>& args)
{
etiss_initialize(args, false);
}
void etiss::forceInitialization()
{
std::vector<std::string> args{};
etiss_initialize(args, true);
}
//__attribute__((destructor))
static void etiss_shutdown()
{
etiss::shutdown(); // TODO: verify with spec. assuming shared library close
// after __attribute__((destructor)) functions have been
// called
// force close open libraries
//{
// std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
// etiss_libraries_.clear();
//}
}
/// replaces __attribute__((destructor)) in a portable way
static class helper_class_etiss_1
{
public:
~helper_class_etiss_1() { etiss_shutdown(); }
} helper_class_etiss_1;
bool etiss_shutdownOk = false;
void etiss::shutdown()
{
if (etiss_shutdownOk) // only on shutdown
return;
etiss_shutdownOk = true;
etiss::fault::Stressor::clear();
// unload libraries
{
std::list<std::weak_ptr<LibraryInterface>> libraries_weak;
{
std::lock_guard<std::recursive_mutex> lock(etiss_libraries_mu_);
for (auto iter = etiss_libraries_.begin(); iter != etiss_libraries_.end(); iter++)
{
libraries_weak.push_back(std::weak_ptr<LibraryInterface>(*iter));
}
etiss_libraries_.clear();
}
for (auto iter = libraries_weak.begin(); iter != libraries_weak.end(); iter++)
{
std::shared_ptr<LibraryInterface> li = iter->lock();
if (li.get() != 0)
{
std::stringstream ss;
ss << "Failed to unload library \"" << li.get()->getName() << "\": ";
ss << li.use_count() - 1 << " references " << std::endl;
etiss::log(etiss::ERROR, ss.str());
}
}
}
// check for existing cpu core instances
{
std::list<std::string> cores = CPUCore::list();
if (cores.size() > 0)
{
for (auto iter = cores.begin(); iter != cores.end(); iter++)
{
etiss::log(etiss::ERROR, std::string("CPU core has not been deleted before "
"etiss::shutdown() call: ") +
*iter);
}
}
}
etiss::py::shutdown();
}
/**
@brief check if etiss::shutdown() was called before exiting main.
*/
//__attribute__((destructor))
static void etiss_check_shutdown()
{
if (!etiss_shutdownOk)
{
etiss::log(etiss::ERROR, "To prevent segmentation faults it is neccessary to call "
"\"etiss::shutdown();\" at the end of main and free any "
"resource acquired through ETISS.");
}
}
/// replaces __attribute__((destructor)) in a portable way
static class helper_class_etiss_3
{
public:
~helper_class_etiss_3() { etiss_check_shutdown(); }
} helper_class_etiss_3;
etiss::Initializer::~Initializer()
{
if (po_simpleIni)
delete po_simpleIni;
etiss::shutdown();
}
std::string etiss::errorMessage(etiss::int32 code, CPUArch *arch)
{
if (code <= 0)
{ // global code
const char *msg = etiss::RETURNCODE::getErrorMessages()[code];
if (msg == 0)
return std::string();
return std::string(msg);
}
else
{ // cpu arch dependent code
if (arch != 0)
{
std::string ret = arch->getName() + ": ";
/// TODO: cpu arch error message function
return ret;
}
else
{
return "Unknown CPU architecture dependent error code.";
}
}
} | 38.549702 | 184 | 0.512055 | [
"vector"
] |
78a6aa8326299bd805daff3e3c6253dab22d8688 | 3,277 | cpp | C++ | modules/task_2/kryukov_s_sparse_mat_omp/main.cpp | egorshul/pp_2021_spring_engineers | 833868c757648149a152ff0913c5e3905cd56176 | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/kryukov_s_sparse_mat_omp/main.cpp | egorshul/pp_2021_spring_engineers | 833868c757648149a152ff0913c5e3905cd56176 | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/kryukov_s_sparse_mat_omp/main.cpp | egorshul/pp_2021_spring_engineers | 833868c757648149a152ff0913c5e3905cd56176 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T17:58:16.000Z | 2022-03-22T17:58:16.000Z | // Copyright 2021 Kryukov Sergey
#include <gtest/gtest.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include "./sparsemat_omp.h"
TEST(omp_version, correct_transpose_mat) {
int size = 3;
std::vector<std::complex<double>> standartMat = {
{0, 0}, {0, 2}, {0, 0},
{0, 1}, {0, 0}, {0, 0},
{0, 0}, {0, 1}, {0, 0}
};
crs_mat TransponationMat, sparseMat;
sparseMat = createSparseMat(size, standartMat);
TransponationMat = transposeMatrixGustavson(sparseMat);
std::vector<int> rightRowNum = { 0, 1, 3, 3 };
ASSERT_EQ(TransponationMat.rowNum, rightRowNum);
}
TEST(omp_version, correct_transpose_mat2) {
int size = 4;
std::vector<std::complex<double>> standartMat = {
{0, 0}, {0, 2}, {0, 0}, {0, 0},
{0, 1}, {0, 0}, {0, 0}, {0, 3},
{0, 0}, {0, 1}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}
};
crs_mat TransponationMat, sparseMat;
sparseMat = createSparseMat(size, standartMat);
TransponationMat = transposeMatrixGustavson(sparseMat);
std::vector<int> rightRowNum = { 0, 1, 3, 3, 4 };
ASSERT_EQ(TransponationMat.rowNum, rightRowNum);
}
TEST(omp_version, check_multiplic) {
int size = 2;
std::vector<std::complex<double>> standartMat1 = {
{0, 0}, {2, 0},
{1, 0}, {0, 0}
};
std::vector<std::complex<double>> standartMat2 = {
{0, 0}, {2, 0},
{2, 0}, {0, 0}
};
crs_mat SparseMat1, SparseMat2, SparseMatResult;
SparseMat1 = createSparseMat(size, standartMat1);
SparseMat2 = createSparseMat(size, standartMat2);
SparseMatResult = multiplicateMatrix(SparseMat1, SparseMat2);
std::vector<std::complex<double>> rightVal = { {4, 0}, {2, 0} };
ASSERT_EQ(SparseMatResult.val, rightVal);
}
TEST(omp_version, check_multiplic2) {
int size = 2;
std::vector<std::complex<double>> standartMat1 = {
{0, 0}, {0, 0},
{0, 0}, {0, 0}
};
std::vector<std::complex<double>> standartMat2 = {
{0, 0}, {2, 0},
{2, 0}, {0, 0}
};
crs_mat SparseMat1, SparseMat2, SparseMatResult;
SparseMat1 = createSparseMat(size, standartMat1);
SparseMat2 = createSparseMat(size, standartMat2);
SparseMatResult = multiplicateMatrix(SparseMat1, SparseMat2);
std::vector<std::complex<double>> rightVal = {};
ASSERT_EQ(SparseMatResult.val, rightVal);
}
TEST(omp_version, check_multiplic_time) {
int size = 500;
double begin, end;
crs_mat SparseMat1 = genDiagonalSparseMat(size);
crs_mat SparseMat2 = genDiagonalSparseMat(size);
begin = omp_get_wtime();
crs_mat SparseMatResult = multiplicateMatrix(SparseMat1, SparseMat2);
end = omp_get_wtime();
std::cout << "Seq time = " << end - begin << "\n";
begin = omp_get_wtime();
crs_mat SparseMatResult_omp = omp_multiplicateMatrix(SparseMat1,
SparseMat2);
end = omp_get_wtime();
std::cout << "OMP time = " << end - begin << "\n";
EXPECT_EQ(SparseMatResult.val, SparseMatResult_omp.val);
EXPECT_EQ(SparseMatResult.rowNum, SparseMatResult_omp.rowNum);
EXPECT_EQ(SparseMatResult.colNum, SparseMatResult_omp.colNum);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 32.77 | 73 | 0.629234 | [
"vector"
] |
78adac5a3300c6a9a3e2d58dff1e7c31da3c1e2b | 3,026 | hpp | C++ | src/cmd_result.hpp | LordAro/ury-playd | dad5458bb7ae9b21e939c17c25e11b685848c081 | [
"BSL-1.0",
"MIT"
] | null | null | null | src/cmd_result.hpp | LordAro/ury-playd | dad5458bb7ae9b21e939c17c25e11b685848c081 | [
"BSL-1.0",
"MIT"
] | null | null | null | src/cmd_result.hpp | LordAro/ury-playd | dad5458bb7ae9b21e939c17c25e11b685848c081 | [
"BSL-1.0",
"MIT"
] | null | null | null | // This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Declaration of the CommandResult class.
*/
#ifndef PLAYD_CMD_RESULT
#define PLAYD_CMD_RESULT
#include <cstdint>
#include <string>
#include <vector>
#include "response.hpp"
/**
* A result from a command (an 'ACK' response).
*
* Commands may either succeed (with no failure message), or fail (with a
* failure message). The success (or not) of a command may be checked with
* CommandResult::IsSuccess.
*/
class CommandResult
{
public:
/**
* Enumeration of possible command result types.
* To be elaborated on pending specification.
* @note If you're adding new ack-codes here, update STRINGS.
* @see CommandResult::STRINGS
*/
enum class Code : std::uint8_t {
OK, ///< Request was valid and produced an answer.
WHAT, ///< Request was invalid/user error.
FAIL ///< Error, pointing blame at environment.
};
/**
* Shortcut for constructing a successful CommandResult.
* @return A CommandResult denoting success.
*/
static CommandResult Success();
/**
* Shortcut for constructing an invalid-response CommandResult.
* @param msg The failure message. See CommandResult().
* @return A CommandResult denoting an invalid response.
*/
static CommandResult Invalid(const std::string &msg);
/**
* Shortcut for constructing a failed CommandResult.
* @param msg The failure message. See CommandResult().
* @return A CommandResult denoting failure.
*/
static CommandResult Failure(const std::string &msg);
/**
* Constructs a CommandResult.
* @param type The type of command result.
* @param msg A message providing more information about the result.
* The message will be copied into the CommandResult.
*/
CommandResult(CommandResult::Code type, const std::string &msg);
/**
* Determines whether this CommandResult was successful.
* @return True if the result was a success; false otherwise.
*/
bool IsSuccess() const;
/**
* Sends a response to a ResponseSink about this CommandResult.
*
* If the CommandResult was a success, then the response is 'OK cmd',
* where 'cmd' is the parameter named as such. Otherwise, the response
* is 'X msg', where 'msg' is the result message and 'X' is whichever
* response code is most appropriate for the failure.
*
* @param sink The ResponseSink to which the response will be sent.
* @param cmd The original command that created this CommandResult.
* @param id The connection ID in the sink to which the response will
* be sent. Defaults to 0 (broadcast).
*/
void Emit(const ResponseSink &sink, const std::vector<std::string> &cmd,
size_t id = 0) const;
private:
/**
* A map from CommandResult::Code codes to their string equivalents.
* @see CommandResult::Code
*/
static const std::string STRINGS[];
std::string msg; ///< The command result's message.
CommandResult::Code type; ///< The command result's ack code.
};
#endif // PLAYD_CMD_RESULT
| 29.960396 | 75 | 0.705552 | [
"vector"
] |
78b3d1338b4ad122883dfbba9fd89c64ac87a9c3 | 8,478 | cpp | C++ | xplat/Sonar/SonarWebSocketImpl.cpp | minikin/Sonar | f7d487dd7607226858ecb3380b889969d5e9a073 | [
"MIT"
] | null | null | null | xplat/Sonar/SonarWebSocketImpl.cpp | minikin/Sonar | f7d487dd7607226858ecb3380b889969d5e9a073 | [
"MIT"
] | null | null | null | xplat/Sonar/SonarWebSocketImpl.cpp | minikin/Sonar | f7d487dd7607226858ecb3380b889969d5e9a073 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
*/
#include "SonarWebSocketImpl.h"
#include <folly/String.h>
#include <folly/futures/Future.h>
#include <folly/io/async/SSLContext.h>
#include <folly/json.h>
#include <rsocket/Payload.h>
#include <rsocket/RSocket.h>
#include <rsocket/transports/tcp/TcpConnectionFactory.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fstream>
#include <iostream>
#include <thread>
#include "CertificateUtils.h"
#ifdef __ANDROID__
#include <android/log.h>
#define SONAR_LOG(message) \
__android_log_print(ANDROID_LOG_INFO, "sonar", "sonar: %s", message)
#else
#define SONAR_LOG(message) printf("sonar: %s", message)
#endif
#define CSR_FILE_NAME "app.csr"
#define SONAR_CA_FILE_NAME "sonarCA.crt"
#define CLIENT_CERT_FILE_NAME "device.crt"
#define PRIVATE_KEY_FILE "privateKey.pem"
static constexpr int reconnectIntervalSeconds = 2;
static constexpr int connectionKeepaliveSeconds = 10;
static constexpr int securePort = 8088;
static constexpr int insecurePort = 8089;
namespace facebook {
namespace sonar {
class ConnectionEvents : public rsocket::RSocketConnectionEvents {
private:
SonarWebSocketImpl* websocket_;
public:
ConnectionEvents(SonarWebSocketImpl* websocket) : websocket_(websocket) {}
void onConnected() {
websocket_->isOpen_ = true;
if (websocket_->connectionIsTrusted_) {
websocket_->callbacks_->onConnected();
}
}
void onDisconnected(const folly::exception_wrapper&) {
if (!websocket_->isOpen_)
return;
websocket_->isOpen_ = false;
websocket_->connectionIsTrusted_ = false;
if (websocket_->connectionIsTrusted_) {
websocket_->callbacks_->onDisconnected();
}
websocket_->reconnect();
}
void onClosed(const folly::exception_wrapper& e) {
onDisconnected(e);
}
};
class Responder : public rsocket::RSocketResponder {
private:
SonarWebSocketImpl* websocket_;
public:
Responder(SonarWebSocketImpl* websocket) : websocket_(websocket) {}
void handleFireAndForget(
rsocket::Payload request,
rsocket::StreamId streamId) {
const auto payload = request.moveDataToString();
websocket_->callbacks_->onMessageReceived(folly::parseJson(payload));
}
};
SonarWebSocketImpl::SonarWebSocketImpl(SonarInitConfig config)
: deviceData_(config.deviceData), worker_(config.worker) {}
SonarWebSocketImpl::~SonarWebSocketImpl() {
stop();
}
void SonarWebSocketImpl::start() {
folly::makeFuture()
.via(worker_->getEventBase())
.delayedUnsafe(std::chrono::milliseconds(0))
.then([this]() { startSync(); });
}
void SonarWebSocketImpl::startSync() {
if (isOpen()) {
SONAR_LOG("Already connected");
return;
}
try {
if (isCertificateExchangeNeeded()) {
doCertificateExchange();
return;
}
connectSecurely();
} catch (const std::exception&) {
failedConnectionAttempts_++;
reconnect();
}
}
void SonarWebSocketImpl::doCertificateExchange() {
rsocket::SetupParameters parameters;
folly::SocketAddress address;
parameters.payload = rsocket::Payload(
folly::toJson(folly::dynamic::object("os", deviceData_.os)));
address.setFromHostPort(deviceData_.host, insecurePort);
connectionIsTrusted_ = false;
client_ =
rsocket::RSocket::createConnectedClient(
std::make_unique<rsocket::TcpConnectionFactory>(
*worker_->getEventBase(), std::move(address)),
std::move(parameters),
nullptr,
std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval
nullptr, // stats
std::make_shared<ConnectionEvents>(this))
.get();
ensureSonarDirExists();
requestSignedCertFromSonar();
}
void SonarWebSocketImpl::connectSecurely() {
rsocket::SetupParameters parameters;
folly::SocketAddress address;
parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object(
"os", deviceData_.os)("device", deviceData_.device)(
"device_id", deviceData_.deviceId)("app", deviceData_.app)));
address.setFromHostPort(deviceData_.host, securePort);
std::shared_ptr<folly::SSLContext> sslContext =
std::make_shared<folly::SSLContext>();
sslContext->loadTrustedCertificates(
absoluteFilePath(SONAR_CA_FILE_NAME).c_str());
sslContext->setVerificationOption(
folly::SSLContext::SSLVerifyPeerEnum::VERIFY);
sslContext->loadCertKeyPairFromFiles(
absoluteFilePath(CLIENT_CERT_FILE_NAME).c_str(),
absoluteFilePath(PRIVATE_KEY_FILE).c_str());
sslContext->authenticate(true, false);
connectionIsTrusted_ = true;
client_ =
rsocket::RSocket::createConnectedClient(
std::make_unique<rsocket::TcpConnectionFactory>(
*worker_->getEventBase(),
std::move(address),
std::move(sslContext)),
std::move(parameters),
std::make_shared<Responder>(this),
std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval
nullptr, // stats
std::make_shared<ConnectionEvents>(this))
.get();
failedConnectionAttempts_ = 0;
}
void SonarWebSocketImpl::reconnect() {
folly::makeFuture()
.via(worker_->getEventBase())
.delayedUnsafe(std::chrono::seconds(reconnectIntervalSeconds))
.then([this]() { startSync(); });
}
void SonarWebSocketImpl::stop() {
client_->disconnect();
client_ = nullptr;
}
bool SonarWebSocketImpl::isOpen() const {
return isOpen_ && connectionIsTrusted_;
}
void SonarWebSocketImpl::setCallbacks(Callbacks* callbacks) {
callbacks_ = callbacks;
}
void SonarWebSocketImpl::sendMessage(const folly::dynamic& message) {
worker_->add([this, message]() {
if (client_) {
client_->getRequester()
->fireAndForget(rsocket::Payload(folly::toJson(message)))
->subscribe([]() {});
}
});
}
bool SonarWebSocketImpl::isCertificateExchangeNeeded() {
if (failedConnectionAttempts_ >= 2) {
return true;
}
std::string caCert = loadStringFromFile(absoluteFilePath(SONAR_CA_FILE_NAME));
std::string clientCert =
loadStringFromFile(absoluteFilePath(CLIENT_CERT_FILE_NAME));
std::string privateKey =
loadStringFromFile(absoluteFilePath(PRIVATE_KEY_FILE));
if (caCert == "" || clientCert == "" || privateKey == "") {
return true;
}
return false;
}
void SonarWebSocketImpl::requestSignedCertFromSonar() {
std::string csr = loadStringFromFile(absoluteFilePath(CSR_FILE_NAME));
if (csr == "") {
generateCertSigningRequest(
deviceData_.appId.c_str(),
absoluteFilePath(CSR_FILE_NAME).c_str(),
absoluteFilePath(PRIVATE_KEY_FILE).c_str());
csr = loadStringFromFile(absoluteFilePath(CSR_FILE_NAME));
}
// Send CSR to Sonar desktop
folly::dynamic message = folly::dynamic::object("method", "signCertificate")(
"csr", csr.c_str())("destination", absoluteFilePath("").c_str());
worker_->add([this, message]() {
client_->getRequester()
->fireAndForget(rsocket::Payload(folly::toJson(message)))
->subscribe([this]() {
// Disconnect after message sending is complete.
// This will trigger a reconnect which should use the secure channel.
client_ = nullptr;
});
});
failedConnectionAttempts_ = 0;
}
std::string SonarWebSocketImpl::loadStringFromFile(std::string fileName) {
std::stringstream buffer;
std::ifstream stream;
std::string line;
stream.open(fileName.c_str());
if (!stream) {
SONAR_LOG(
std::string("ERROR: Unable to open ifstream: " + fileName).c_str());
return "";
}
buffer << stream.rdbuf();
std::string s = buffer.str();
return s;
}
std::string SonarWebSocketImpl::absoluteFilePath(const char* filename) {
return std::string(deviceData_.privateAppDirectory + "/sonar/" + filename);
}
bool SonarWebSocketImpl::ensureSonarDirExists() {
std::string dirPath = absoluteFilePath("");
struct stat info;
if (stat(dirPath.c_str(), &info) != 0) {
int ret = mkdir(dirPath.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
return ret == 0;
} else if (info.st_mode & S_IFDIR) {
return true;
} else {
SONAR_LOG(std::string(
"ERROR: Sonar path exists but is not a directory: " + dirPath)
.c_str());
return false;
}
}
} // namespace sonar
} // namespace facebook
| 29.134021 | 80 | 0.691791 | [
"object"
] |
78b4b83611dfcceb5388290893f49e04a3fb42a9 | 7,681 | hpp | C++ | sources/compute/SplaApplyMask.hpp | JetBrains-Research/spla | 9b353d68420bc69c322023d239f8bb0977308b9c | [
"MIT"
] | 10 | 2021-09-24T03:48:31.000Z | 2022-02-07T09:09:01.000Z | sources/compute/SplaApplyMask.hpp | JetBrains-Research/spla | 88308176e4555756d2ca81a5c05b60e240bd4d8e | [
"MIT"
] | 78 | 2021-09-11T09:39:04.000Z | 2022-02-11T19:50:07.000Z | sources/compute/SplaApplyMask.hpp | JetBrains-Research/spla | 88308176e4555756d2ca81a5c05b60e240bd4d8e | [
"MIT"
] | 3 | 2021-09-20T15:43:54.000Z | 2022-02-15T11:29:52.000Z | /**********************************************************************************/
/* This file is part of spla project */
/* https://github.com/JetBrains-Research/spla */
/**********************************************************************************/
/* MIT License */
/* */
/* Copyright (c) 2021 JetBrains-Research */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#ifndef SPLA_SPLAAPPLYMASK_HPP
#define SPLA_SPLAAPPLYMASK_HPP
#include <boost/compute/command_queue.hpp>
#include <boost/compute/container/vector.hpp>
#include <compute/SplaGather.hpp>
#include <compute/SplaMaskByKey.hpp>
namespace spla {
/**
* @addtogroup Internal
* @{
*/
/**
* @brief Apply mask to coo vector.
*
* @param mask Mask indices
* @param inputRows Row indices
* @param inputVals Values
* @param outputRows Result row indices; resized automatically
* @param outputVals Result values; resized automatically
* @param byteSize Size of values; if 0, apply only indices mask
* @param complement Pass true to apply inverse (complementary mask)
* @param queue Command queue to perform operation
*/
inline void ApplyMask(const boost::compute::vector<unsigned int> &mask,
const boost::compute::vector<unsigned int> &inputRows,
const boost::compute::vector<unsigned char> &inputVals,
boost::compute::vector<unsigned int> &outputRows,
boost::compute::vector<unsigned char> &outputVals,
std::size_t byteSize,
bool complement,
boost::compute::command_queue &queue) {
using namespace boost;
if (mask.empty() || inputRows.empty())
return;
auto ctx = queue.get_context();
auto typeHasValues = byteSize != 0;
auto nnz = inputRows.size();
compute::vector<unsigned int> perm(ctx);
if (typeHasValues) {
// Fill permutation to link value to indices
perm.resize(nnz, queue);
compute::copy_n(compute::make_counting_iterator(0), nnz, perm.begin(), queue);
}
if (typeHasValues) {
// Mask with new permutation buffer
compute::vector<unsigned int> outputPerm(ctx);
MaskByKeys(mask,
inputRows, perm,
outputRows, outputPerm,
complement,
queue);
std::swap(perm, outputPerm);
} else
MaskKeys(mask, inputRows, outputRows, complement, queue);
if (typeHasValues) {
// Copy output values using indices buffer
outputVals.resize(outputRows.size() * byteSize, queue);
Gather(perm.begin(), perm.end(), inputVals.begin(), outputVals.begin(), byteSize, queue);
}
}
/**
* @brief Apply mask to coo matrix.
*
* @param maskRows Mask indices of rows
* @param maskCols Mask indices of cols
* @param inputRows Row indices
* @param inputCols Col indices
* @param inputVals Values
* @param outputRows Result row indices; resized automatically
* @param outputCols Result col indices; resized automatically
* @param outputVals Result values; resized automatically
* @param byteSize Size of values; if 0, apply only indices mask
* @param complement If mask is a complement
* @param queue Command queue to perform operation
*/
inline void ApplyMask(const boost::compute::vector<unsigned int> &maskRows,
const boost::compute::vector<unsigned int> &maskCols,
const boost::compute::vector<unsigned int> &inputRows,
const boost::compute::vector<unsigned int> &inputCols,
const boost::compute::vector<unsigned char> &inputVals,
boost::compute::vector<unsigned int> &outputRows,
boost::compute::vector<unsigned int> &outputCols,
boost::compute::vector<unsigned char> &outputVals,
std::size_t byteSize,
bool complement,
boost::compute::command_queue &queue) {
using namespace boost;
assert(maskRows.size() == maskCols.size());
assert(inputRows.size() == inputCols.size());
if (maskRows.empty() || inputRows.empty())
return;
auto ctx = queue.get_context();
auto typeHasValues = byteSize != 0;
auto nnz = inputRows.size();
compute::vector<unsigned int> perm(ctx);
if (typeHasValues) {
// Fill permutation to link value to indices
perm.resize(nnz, queue);
compute::copy_n(compute::make_counting_iterator(0), nnz, perm.begin(), queue);
}
if (typeHasValues) {
// Mask with new permutation buffer
compute::vector<unsigned int> outputPerm(ctx);
MaskByPairKeys(maskRows, maskCols,
inputRows, inputCols, perm,
outputRows, outputCols, outputPerm,
complement,
queue);
std::swap(perm, outputPerm);
} else {
MaskPairKeys(maskRows, maskCols, inputRows, inputCols, outputRows, outputCols, complement, queue);
}
if (typeHasValues) {
// Copy output values using indices buffer
outputVals.resize(outputRows.size() * byteSize, queue);
Gather(perm.begin(), perm.end(), inputVals.begin(), outputVals.begin(), byteSize, queue);
}
}
/**
* @}
*/
}// namespace spla
#endif//SPLA_SPLAAPPLYMASK_HPP
| 45.182353 | 110 | 0.529098 | [
"vector"
] |
78b5305c8a1ec5cef831f8325740fdbca96b093c | 4,898 | cpp | C++ | mlir/lib/Dialect/Linalg/Transforms/PadOpInterchange.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/PadOpInterchange.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/PadOpInterchange.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | //===- PadOpInterchange.cpp - Interchange pad operation with Generic ops --===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements patterns that intechanges a generic op -> pad_tensor
// pattern into extract_slice -> generic_op.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
using namespace mlir;
using namespace mlir::linalg;
namespace {
/// A sequence of operations
///
/// ```mlir
/// %0 = linalg. ...
/// %1 = linalg.pad_tensor %0 ...
/// ```
///
/// can be replaced with
///
/// ```mlir
/// %0 = linalg.fill
/// %1 = tensor.extract_slice %0 ...
/// %2 = linalg. .... outs(..., %1, ....) ....
/// %3 = tensor.insert_slice %2 into %1 ...
/// ```
///
/// if the `linalg.generic` has all parallel iterator types.
struct FusePadOp : OpRewritePattern<tensor::PadOp> {
using OpRewritePattern<tensor::PadOp>::OpRewritePattern;
LogicalResult matchAndRewrite(tensor::PadOp padOp,
PatternRewriter &rewriter) const override {
// Only works on padding op that sets the padded value to a constant.
Value padValue = padOp.getConstantPaddingValue();
if (!padValue)
return rewriter.notifyMatchFailure(padOp, "non constant padding");
// This pattern could work for any Linalg op. For now restrict it to generic
// ops.
Value source = padOp.source();
auto linalgOp = source.getDefiningOp<GenericOp>();
if (!linalgOp) {
return rewriter.notifyMatchFailure(
padOp, "expected source to be linalg.generic op");
}
// All iterator types need to be parallel.
if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops()) {
return rewriter.notifyMatchFailure(
padOp, "only supported for ops with all parallel iterator types");
}
ReifiedRankedShapedTypeDims resultShape;
ReifyRankedShapedTypeOpInterface reifyShapedTypeInterface =
dyn_cast<ReifyRankedShapedTypeOpInterface>(padOp.getOperation());
if (failed(reifyShapedTypeInterface.reifyResultShapes(rewriter,
resultShape)) ||
resultShape.size() != 1) {
return rewriter.notifyMatchFailure(
padOp, "failed to get shape of pad op result");
}
Location loc = padOp.getLoc();
// Create the tensor of same size as output of the pad op.
RankedTensorType padResultType = padOp.getResultType();
auto resultSizes = getAsOpFoldResult(resultShape[0]);
auto initTensor = rewriter.create<InitTensorOp>(
loc, resultSizes, padResultType.getElementType());
// Fill the tensor with the pad value.
// TODO: There is an option to fill only the boundaries. For now just
// filling the whole tensor.
auto fillTensor =
rewriter.create<FillOp>(loc, padValue, initTensor.getResult());
// Construct a slice of the fill result that is to be replaced with the
// result of the generic op. The low pad values are the offsets, the size of
// the source is the size of the slice.
// TODO: This insert/extract could be potentially made a utility method.
unsigned resultNumber = source.cast<OpResult>().getResultNumber();
SmallVector<OpFoldResult> offsets = padOp.getMixedLowPad();
SmallVector<OpFoldResult> sizes;
sizes.reserve(offsets.size());
for (const auto &shape : llvm::enumerate(
source.getType().cast<RankedTensorType>().getShape())) {
if (ShapedType::isDynamic(shape.value())) {
sizes.push_back(
rewriter.create<tensor::DimOp>(loc, source, shape.index())
.getResult());
} else {
sizes.push_back(rewriter.getIndexAttr(shape.value()));
}
}
SmallVector<OpFoldResult> strides(offsets.size(), rewriter.getIndexAttr(1));
auto slice = rewriter.create<tensor::ExtractSliceOp>(
loc, fillTensor.getResult(0), offsets, sizes, strides);
// Clone the generic op.
auto clonedOp = cast<GenericOp>(rewriter.clone(*linalgOp.getOperation()));
clonedOp.setOutputOperand(resultNumber, slice.getResult());
// Insert it back into the result of the fill.
rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
padOp, clonedOp.getResult(resultNumber), fillTensor.getResult(0),
offsets, sizes, strides);
return success();
}
};
} // namespace
void mlir::linalg::populateFusePadTensorWithProducerLinalgOpPatterns(
RewritePatternSet &patterns) {
patterns.add<FusePadOp>(patterns.getContext());
}
| 38.873016 | 80 | 0.654553 | [
"shape"
] |
78b5f74fd33abe16afcc4a7080cf42fad53086d6 | 2,775 | cpp | C++ | c++/0115-distinct-subsequences.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | 2 | 2019-04-13T09:55:04.000Z | 2019-05-16T12:47:40.000Z | c++/0115-distinct-subsequences.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | c++/0115-distinct-subsequences.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | // 115. Distinct Subsequences [Hard]
// Given a string S and a string T, count the number of distinct subsequences of S which equals T.
// A subsequence of a string is a new string which is formed from the original string by deleting
// some (can be none) of the characters without disturbing the relative positions of the remaining
// characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
// Example 1:
// Input: S = "rabbbit", T = "rabbit"
// Output: 3
// Explanation:
// As shown below, there are 3 ways you can generate "rabbit" from S.
// (The caret symbol ^ means the chosen letters)
// rabbbit
// ^^^^ ^^
// rabbbit
// ^^ ^^^^
// rabbbit
// ^^^ ^^^
// Example 2:
// Input: S = "babgbag", T = "bag"
// Output: 5
// Explanation:
// As shown below, there are 5 ways you can generate "bag" from S.
// (The caret symbol ^ means the chosen letters)
// babgbag
// ^^ ^
// babgbag
// ^^ ^
// babgbag
// ^ ^^
// babgbag
// ^ ^^
// babgbag
// ^^^
// dynamic programming
// let dp[i][j] be number of distinct ways for first j characters in T to appear in first i characters in S
// dp[i][j] = dp[i-1][j] + (s[i-1] == t[j-1]) * dp[i-1][j-1]
// dp[i][0] = 1 for any i
class DynamicProgrammingSolution
{
public:
int numDistinct(string s, string t)
{
int m = s.size(), n = t.size();
if (m <= n) return s == t;
vector<vector<long>> dp(m+1, vector<long>(n+1));
for (int i = 0; i <= m; ++i) {
dp[i][0] = 1;
for (int j = 1; j <= std::min(n, i); ++j)
dp[i][j] = dp[i-1][j] + (s[i-1] == t[j-1]) * dp[i-1][j-1];
}
return dp[m][n];
}
};
// a memory-efficient translation of DynamicProgrammingSolution
class MemoryEfficientSolution
{
public:
int numDistinct(string s, string t)
{
int m = s.size(), n = t.size();
if (m <= n) return s == t;
vector<long> prev(n+1), curr(n+1);
for (int i = 0; i <= m; ++i) {
curr[0] = 1;
for (int j = 1; j <= std::min(n, i); ++j)
curr[j] = prev[j] + (s[i-1] == t[j-1]) * prev[j-1];
std::swap(prev, curr);
}
return prev[n];
}
};
// GOOD
// 10000
// G 11000
// O 11100
// O 11210
// D 11211
// G 12211
// O 12431
// D 12434
// combine 2 swapping vectors into 1 and thus even more memory, by counting from back to front of T
// dp[i]: number of distinct ways of first i characters of T to appear in S
class Solution
{
public:
int numDistinct(string s, string t)
{
int n = t.size();
vector<long> dp(n+1); dp[0] = 1;
for (auto c : s)
for (int i = n; i >= 1; --i)
if (t[i-1] == c)
dp[i] += dp[i-1];
return dp.back();
}
};
| 26.941748 | 107 | 0.536937 | [
"vector"
] |
78b847d01b3049e8473bc791c46a379a907ae351 | 1,160 | cpp | C++ | ccpca/ccpca_wrap.cpp | takanori-fujiwara/ccpca | e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110 | [
"BSD-3-Clause"
] | 14 | 2019-07-16T03:29:29.000Z | 2022-02-19T14:59:11.000Z | ccpca/ccpca_wrap.cpp | takanori-fujiwara/ccpca | e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110 | [
"BSD-3-Clause"
] | null | null | null | ccpca/ccpca_wrap.cpp | takanori-fujiwara/ccpca | e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110 | [
"BSD-3-Clause"
] | 7 | 2019-07-16T03:35:58.000Z | 2022-01-30T05:41:07.000Z | #include "ccpca.hpp"
#include <pybind11/eigen.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
PYBIND11_MODULE(ccpca_cpp, m) {
m.doc() = "ccPCA wrapped with pybind11";
py::class_<CCPCA>(m, "CCPCA")
.def(py::init<Eigen::Index const, bool const>())
// fitTransform has some bug probably related to using pybind11
// .def("fit_transform", &CCPCA::fitTransform)
.def("fit", &CCPCA::fit)
.def("transform", &CCPCA::transform)
.def("best_alpha", &CCPCA::bestAlpha)
.def("get_feat_contribs", &CCPCA::getFeatContribs)
.def("get_scaled_feat_contribs", &CCPCA::getScaledFeatContribs)
.def("get_components", &CCPCA::getComponents)
.def("get_component", &CCPCA::getComponent)
.def("get_eigenvalues", &CCPCA::getEigenvalues)
.def("get_eigenvalue", &CCPCA::getEigenvalue)
.def("get_loadings", &CCPCA::getLoadings)
.def("get_loading", &CCPCA::getLoading)
.def("get_first_component", &CCPCA::getFirstComponent)
.def("get_best_alpha", &CCPCA::getBestAlpha)
.def("get_reports", &CCPCA::getReports);
}
| 37.419355 | 69 | 0.673276 | [
"transform"
] |
78bab7463d5ad19368967c8579cd14fa6e6b512a | 12,016 | cpp | C++ | simulator/project.cpp | MScieburakoADVA/mstp-lib | 768f9323abd3e81fb770d04b5502e6e51e8ee476 | [
"Apache-2.0"
] | 21 | 2018-10-16T18:05:32.000Z | 2022-01-11T10:57:24.000Z | simulator/project.cpp | MScieburakoADVA/mstp-lib | 768f9323abd3e81fb770d04b5502e6e51e8ee476 | [
"Apache-2.0"
] | 34 | 2018-03-06T10:04:57.000Z | 2021-05-26T13:37:03.000Z | simulator/project.cpp | MScieburakoADVA/mstp-lib | 768f9323abd3e81fb770d04b5502e6e51e8ee476 | [
"Apache-2.0"
] | 13 | 2019-04-09T07:56:48.000Z | 2022-01-11T11:00:12.000Z |
// This file is part of the mstp-lib library, available at https://github.com/adigostin/mstp-lib
// Copyright (c) 2011-2020 Adi Gostin, distributed under Apache License v2.0.
#include "pch.h"
#include "simulator.h"
#include "wire.h"
#include "bridge.h"
#include "port.h"
#include "win32/xml_serializer.h"
static const _bstr_t NextMacAddressString = "NextMacAddress";
class project : public edge::object, public project_i
{
using base = edge::object;
std::wstring _path;
std::vector<std::unique_ptr<bridge>> _bridges;
std::vector<std::unique_ptr<wire>> _wires;
mac_address _next_mac_address = next_mac_address_property.default_value.value();
bool _simulationPaused = false;
bool _changedFlag = false;
public:
virtual const std::vector<std::unique_ptr<bridge>>& bridges() const override final { return _bridges; }
virtual void insert_bridge (size_t index, std::unique_ptr<bridge>&& bridge) override final
{
assert (index <= _bridges.size());
assert (bridge->_project == nullptr);
auto b = bridge.get();
property_change_args args = { &bridges_property, index, collection_property_change_type::insert };
this->on_property_changing(args);
_bridges.insert (_bridges.begin() + index, std::move(bridge));
static_cast<project_child*>(b)->on_added_to_project(this);
this->on_property_changed(args);
b->invalidated().add_handler (&on_project_child_invalidated, this);
b->packet_transmit().add_handler (&on_packet_transmit, this);
this->event_invoker<invalidate_e>()(this);
}
virtual std::unique_ptr<bridge> remove_bridge(size_t index) override final
{
assert (index < _bridges.size());
bridge* b = _bridges[index].get();
assert (b->_project == this);
if (std::any_of (_wires.begin(), _wires.end(), [b, this](const std::unique_ptr<wire>& w) {
return any_of (w->points().begin(), w->points().end(), [b, this] (wire_end p) {
return std::holds_alternative<connected_wire_end>(p) && (std::get<connected_wire_end>(p)->bridge() == b);
});
}))
assert(false); // can't remove a connected bridge
b->packet_transmit().remove_handler (&on_packet_transmit, this);
b->invalidated().remove_handler (&on_project_child_invalidated, this);
property_change_args args = { &bridges_property, index, collection_property_change_type::remove };
this->on_property_changing(args);
static_cast<project_child*>(b)->on_removing_from_project(this);
auto result = std::move(_bridges[index]);
_bridges.erase (_bridges.begin() + index);
this->on_property_changed(args);
this->event_invoker<invalidate_e>()(this);
return result;
}
virtual const std::vector<std::unique_ptr<wire>>& wires() const override final { return _wires; }
virtual void insert_wire (size_t index, std::unique_ptr<wire>&& wire) override final
{
assert (index <= _wires.size());
assert (wire->_project == nullptr);
auto w = wire.get();
property_change_args args = { &wires_property, index, collection_property_change_type::insert };
this->on_property_changing(args);
_wires.insert (_wires.begin() + index, std::move(wire));
static_cast<project_child*>(w)->on_added_to_project(this);
this->on_property_changed(args);
w->invalidated().add_handler (&on_project_child_invalidated, this);
this->event_invoker<invalidate_e>()(this);
}
virtual std::unique_ptr<wire> remove_wire (size_t index) override final
{
assert (index < _wires.size());
wire* w = _wires[index].get();
assert(w->_project == this);
_wires[index]->invalidated().remove_handler (&on_project_child_invalidated, this);
property_change_args args = { &wires_property, index, collection_property_change_type::remove };
this->on_property_changing (args);
static_cast<project_child*>(w)->on_removing_from_project(this);
auto result = std::move(_wires[index]);
_wires.erase (_wires.begin() + index);
this->on_property_changed (args);
this->event_invoker<invalidate_e>()(this);
return result;
}
static void on_packet_transmit (void* callbackArg, bridge* bridge, size_t txPortIndex, packet_t&& pi)
{
auto project = static_cast<class project*>(callbackArg);
auto tx_port = bridge->ports().at(txPortIndex).get();
auto rx_port = project->find_connected_port(tx_port);
if (rx_port != nullptr)
rx_port->bridge()->enqueue_received_packet(std::move(pi), rx_port->port_index());
}
static void on_project_child_invalidated (void* callbackArg, renderable_object* object)
{
auto project = static_cast<class project*>(callbackArg);
project->event_invoker<invalidate_e>()(project);
}
virtual invalidate_e::subscriber invalidated() override final { return invalidate_e::subscriber(this); }
virtual loaded_e::subscriber GetLoadedEvent() override final { return loaded_e::subscriber(this); }
virtual bool IsWireForwarding (wire* wire, unsigned int vlanNumber, _Out_opt_ bool* hasLoop) const override final
{
if (!std::holds_alternative<connected_wire_end>(wire->p0()) || !std::holds_alternative<connected_wire_end>(wire->p1()))
return false;
auto portA = std::get<connected_wire_end>(wire->p0());
auto portB = std::get<connected_wire_end>(wire->p1());
bool portAFw = portA->IsForwarding(vlanNumber);
bool portBFw = portB->IsForwarding(vlanNumber);
if (!portAFw || !portBFw)
return false;
if (hasLoop != nullptr)
{
std::unordered_set<port*> txPorts;
std::function<bool(port* txPort)> transmitsTo = [this, vlanNumber, &txPorts, &transmitsTo, targetPort=portA](port* txPort) -> bool
{
if (txPort->IsForwarding(vlanNumber))
{
auto rx = find_connected_port(txPort);
if ((rx != nullptr) && rx->IsForwarding(vlanNumber))
{
txPorts.insert(txPort);
for (unsigned int i = 0; i < (unsigned int) rx->bridge()->ports().size(); i++)
{
if ((i != rx->port_index()) && rx->IsForwarding(vlanNumber))
{
port* otherTxPort = rx->bridge()->ports()[i].get();
if (otherTxPort == targetPort)
return true;
if (txPorts.find(otherTxPort) != txPorts.end())
return false;
if (transmitsTo(otherTxPort))
return true;
}
}
}
}
return false;
};
*hasLoop = transmitsTo(portA);
}
return true;
}
virtual mac_address alloc_mac_address_range (size_t count) override final
{
if (count >= 128)
throw std::range_error("count must be lower than 128.");
auto result = _next_mac_address;
_next_mac_address[5] += (uint8_t)count;
if (_next_mac_address[5] < count)
{
_next_mac_address[4]++;
if (_next_mac_address[4] == 0)
assert(false); // not implemented
}
return result;
}
virtual const std::wstring& file_path() const override final { return _path; }
virtual HRESULT save (const wchar_t* filePath) override final
{
com_ptr<IXMLDOMDocument3> doc;
HRESULT hr = CoCreateInstance (CLSID_DOMDocument60, nullptr, CLSCTX_INPROC_SERVER, __uuidof(doc), (void**) &doc);
if (FAILED(hr))
return hr;
auto project_element = serialize (doc, this, true);
hr = doc->appendChild (project_element, nullptr);
if (FAILED(hr))
return hr;
hr = format_and_save_to_file (doc, filePath);
if (FAILED(hr))
return hr;
_path = filePath;
return S_OK;
}
static std::span<const concrete_type* const> known_types();
virtual HRESULT load (const wchar_t* filePath) override final
{
com_ptr<IXMLDOMDocument3> doc;
HRESULT hr = CoCreateInstance (CLSID_DOMDocument60, nullptr, CLSCTX_INPROC_SERVER, __uuidof(doc), (void**) &doc); if (FAILED(hr)) return hr;
if (!PathFileExists(filePath))
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
VARIANT_BOOL isSuccessful;
hr = doc->load(_variant_t(filePath), &isSuccessful); if (FAILED(hr)) return hr;
if (isSuccessful != VARIANT_TRUE)
return E_FAIL;
com_ptr<IXMLDOMNode> xmlDeclarationNode;
hr = doc->get_firstChild(&xmlDeclarationNode); if (FAILED(hr)) return hr;
_bstr_t nodeName;
hr = xmlDeclarationNode->get_nodeName(nodeName.GetAddress()); if (FAILED(hr)) return hr;
if (_wcsicmp (nodeName.GetBSTR(), L"xml") != 0)
return E_FAIL;
com_ptr<IXMLDOMNode> projectNode;
hr = xmlDeclarationNode->get_nextSibling(&projectNode); assert(SUCCEEDED(hr));
hr = projectNode->get_nodeName(nodeName.GetAddress()); assert(SUCCEEDED(hr));
if (_wcsicmp (nodeName.GetBSTR(), L"Project") != 0)
return E_FAIL;
com_ptr<IXMLDOMElement> projectElement = projectNode;
deserialize_to (projectElement, this, known_types());
_path = filePath;
this->event_invoker<loaded_e>()(this);
return S_OK;
}
virtual void pause_simulation() override final
{
_simulationPaused = true;
this->event_invoker<invalidate_e>()(this);
}
virtual void resume_simulation() override final
{
_simulationPaused = false;
this->event_invoker<invalidate_e>()(this);
}
virtual bool simulation_paused() const override final { return _simulationPaused; }
virtual bool GetChangedFlag() const override final { return _changedFlag; }
virtual void SetChangedFlag (bool changedFlag) override final
{
if (changedFlag)
{
this->event_invoker<ChangedEvent>()(this);
this->event_invoker<invalidate_e>()(this);
}
if (_changedFlag != changedFlag)
{
_changedFlag = changedFlag;
this->event_invoker<ChangedFlagChangedEvent>()(this);
}
}
virtual ChangedFlagChangedEvent::subscriber GetChangedFlagChangedEvent() override final { return ChangedFlagChangedEvent::subscriber(this); }
virtual ChangedEvent::subscriber GetChangedEvent() override final { return ChangedEvent::subscriber(this); }
virtual const object_collection_property* bridges_prop() const override final { return &bridges_property; }
virtual const object_collection_property* wires_prop() const override final { return &wires_property; }
virtual property_changing_e::subscriber property_changing() override final { return property_changing_e::subscriber(this); }
virtual property_changed_e::subscriber property_changed() override final { return property_changed_e::subscriber(this); }
mac_address next_mac_address() const { return _next_mac_address; }
void set_next_mac_address (mac_address value)
{
if (_next_mac_address != value)
{
this->on_property_changing(&next_mac_address_property);
_next_mac_address = value;
this->on_property_changed(&next_mac_address_property);
}
}
static constexpr mac_address_p next_mac_address_property = {
"NextMacAddress", nullptr, nullptr, ui_visible::yes,
&next_mac_address,
&set_next_mac_address,
mac_address{ 0x00, 0xAA, 0x55, 0xAA, 0x55, 0x80 },
};
size_t bridge_count() const { return _bridges.size(); }
bridge* bridge_at(size_t index) const { return _bridges[index].get(); }
size_t wire_count() const { return _wires.size(); }
wire* wire_at(size_t index) const { return _wires[index].get(); }
static const typed_object_collection_property<class project, bridge> bridges_property;
static const typed_object_collection_property<class project, wire> wires_property;
static const property* const _properties[];
static const xtype<project> _type;
virtual const concrete_type* type() const { return &_type; }
};
//static
std::span<const concrete_type* const> project::known_types()
{
static const concrete_type* const types[] =
{ &project::_type, &bridge::_type, &bridge_tree::_type, &port::_type, &port_tree::_type, &wire::_type };
return types;
}
const typed_object_collection_property<project, bridge> project::bridges_property = {
"Bridges", nullptr, nullptr, ui_visible::no,
&bridge_count, &bridge_at, &insert_bridge, &remove_bridge
};
const typed_object_collection_property<project, wire> project::wires_property {
"Wires", nullptr, nullptr, ui_visible::no,
&wire_count, &wire_at, &insert_wire, &remove_wire
};
const property* const project::_properties[] = { &next_mac_address_property, &bridges_property, &wires_property };
const xtype<project> project::_type = { "Project", &base::_type, _properties, nullptr };
extern const project_factory_t project_factory = []() -> std::shared_ptr<project_i> { return std::make_shared<project>(); };
| 34.03966 | 142 | 0.726698 | [
"object",
"vector"
] |
78c918b408c854cebe3c2dd071a02c248ded00fa | 455 | hpp | C++ | RBF/src/rbf.hpp | jesuswr/RBF | 0d11d763ccc75616f7e08ed9822ac3968f2533fe | [
"MIT"
] | null | null | null | RBF/src/rbf.hpp | jesuswr/RBF | 0d11d763ccc75616f7e08ed9822ac3968f2533fe | [
"MIT"
] | null | null | null | RBF/src/rbf.hpp | jesuswr/RBF | 0d11d763ccc75616f7e08ed9822ac3968f2533fe | [
"MIT"
] | null | null | null | #ifndef _RBF_HPP
#define _RBF_HPP
#include <armadillo>
#include <vector>
#include <math.h>
using namespace arma;
using namespace std;
class rbf {
double sigma;
vector<double> w;
vector<double> g;
public:
rbf(vector<double> &x, vector<double> &y,
double lambda);
double gaussian(double xi, double xj);
double get_output(double x);
vector<double> test(const vector<double> &x);
};
#endif | 13.382353 | 49 | 0.632967 | [
"vector"
] |
78d1cd2e1be6bf9b1d2d93fa74e370f175d7bffa | 529 | hpp | C++ | src/syntax/symbols/sentinel.hpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | 2 | 2018-03-19T20:19:01.000Z | 2018-10-22T23:41:12.000Z | src/syntax/symbols/sentinel.hpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | 1 | 2017-01-18T20:45:33.000Z | 2017-01-21T20:57:37.000Z | src/syntax/symbols/sentinel.hpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | null | null | null | /// Copyright 2017 Lucas Saldyt
#pragma once
#include "symbol.hpp"
namespace syntax
{
using namespace tools;
/**
* Signal symbol for some hacky uses... (i.e. seperators, AST-transform matrix edge indicators)
*/
struct SentinelSymbol : public Symbol
{
string name() override;
string abstract(int indent=0) override;
string tag = "__none__";
string val = "__none__";
SentinelSymbol(string set_tag, string set_val="__none__");
SentinelSymbol();
};
}
| 23 | 100 | 0.63138 | [
"transform"
] |
78d660ae3ddf5c11428ed5f7f1c4e63bbf67bd2c | 30,944 | cpp | C++ | Granite/application/platforms/application_android.cpp | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | null | null | null | Granite/application/platforms/application_android.cpp | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | null | null | null | Granite/application/platforms/application_android.cpp | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | null | null | null | /* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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 "android_native_app_glue.h"
#include "util.hpp"
#include "application.hpp"
#include "application_events.hpp"
#include "application_wsi.hpp"
#include "context.hpp"
#include <jni.h>
#include <android/sensor.h>
#include "android.hpp"
#include "os_filesystem.hpp"
#include "rapidjson_wrapper.hpp"
#include "muglm/muglm_impl.hpp"
#ifdef AUDIO_HAVE_OPENSL
#include "audio_opensl.hpp"
#endif
#ifdef AUDIO_HAVE_OBOE
#include "audio_oboe.hpp"
#endif
using namespace std;
using namespace Vulkan;
#define SENSOR_GAME_ROTATION_VECTOR 15
namespace Granite
{
uint32_t android_api_version;
void application_dummy()
{
}
struct GlobalState
{
android_app *app;
int32_t base_width;
int32_t base_height;
int display_rotation;
int surface_orientation;
bool has_window;
bool active;
bool content_rect_changed;
};
struct JNI
{
JNIEnv *env;
jclass granite;
jmethodID finishFromThread;
jmethodID getDisplayRotation;
jmethodID getAudioNativeSampleRate;
jmethodID getAudioNativeBlockFrames;
jmethodID getCommandLineArgument;
jmethodID getCurrentOrientation;
jclass classLoaderClass;
jobject classLoader;
jmethodID getVendorId;
jmethodID getProductId;
jmethodID getDeviceName;
jmethodID getDevice;
jclass inputDeviceClass;
ASensorEventQueue *sensor_queue;
const ASensor *rotation_sensor;
};
static GlobalState global_state;
static JNI jni;
static void on_content_rect_changed(ANativeActivity *, const ARect *rect)
{
global_state.base_width = rect->right - rect->left;
global_state.base_height = rect->bottom - rect->top;
global_state.content_rect_changed = true;
LOGI("Got content rect: %d x %d\n", global_state.base_width, global_state.base_height);
}
namespace App
{
static void finishFromThread()
{
jni.env->CallVoidMethod(global_state.app->activity->clazz, jni.finishFromThread);
}
static string getCommandLine()
{
string result;
jstring key = jni.env->NewStringUTF("granite");
jstring str = static_cast<jstring>(jni.env->CallObjectMethod(global_state.app->activity->clazz,
jni.getCommandLineArgument,
key));
if (str)
{
const char *data = jni.env->GetStringUTFChars(str, nullptr);
if (data)
{
result = data;
jni.env->ReleaseStringUTFChars(str, data);
}
else
LOGE("Failed to get JNI string data.\n");
}
else
LOGE("Failed to get JNI string from getCommandLine().\n");
return result;
}
#ifdef HAVE_GRANITE_AUDIO
static int getAudioNativeSampleRate()
{
int ret = jni.env->CallIntMethod(global_state.app->activity->clazz, jni.getAudioNativeSampleRate);
return ret;
}
static int getAudioNativeBlockFrames()
{
int ret = jni.env->CallIntMethod(global_state.app->activity->clazz, jni.getAudioNativeBlockFrames);
return ret;
}
#endif
static int getCurrentOrientation()
{
int ret = jni.env->CallIntMethod(global_state.app->activity->clazz, jni.getCurrentOrientation);
return ret;
}
static int getDisplayRotation()
{
int ret = jni.env->CallIntMethod(global_state.app->activity->clazz, jni.getDisplayRotation);
return ret;
}
}
struct WSIPlatformAndroid : Granite::GraniteWSIPlatform
{
bool init(unsigned width_, unsigned height_)
{
width = width_;
height = height_;
if (!Vulkan::Context::init_loader(nullptr))
{
LOGE("Failed to init Vulkan loader.\n");
return false;
}
get_input_tracker().set_touch_resolution(width, height);
has_window = global_state.has_window;
active = global_state.active;
for (auto &id : gamepad_ids)
id = -1;
return true;
}
void event_swapchain_created(Device *device_, unsigned width_, unsigned height_, float aspect_, size_t count_, VkFormat format_, VkSurfaceTransformFlagBitsKHR transform_) override
{
Granite::GraniteWSIPlatform::event_swapchain_created(device_, width_, height_, aspect_, count_, format_, transform_);
if (transform_ & (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR))
{
swap(width_, height_);
}
get_input_tracker().set_touch_resolution(width_, height_);
}
void update_orientation();
bool alive(Vulkan::WSI &wsi) override;
void poll_input() override;
vector<const char *> get_instance_extensions() override
{
return { "VK_KHR_surface", "VK_KHR_android_surface" };
}
uint32_t get_surface_width() override
{
return width;
}
uint32_t get_surface_height() override
{
return height;
}
float get_aspect_ratio() override
{
return float(global_state.base_width) / global_state.base_height;
}
struct GamepadInfo
{
string name;
int vid = 0;
int pid = 0;
void init_remap_table(JoypadRemapper &remapper);
};
void query_gamepad_info(unsigned index, int32_t id)
{
auto &info = gamepad_info[index];
jobject device = jni.env->CallStaticObjectMethod(jni.inputDeviceClass, jni.getDevice, id);
if (device)
{
jstring name = static_cast<jstring>(jni.env->CallObjectMethod(device, jni.getDeviceName));
if (name)
{
const char *str = jni.env->GetStringUTFChars(name, nullptr);
if (str)
{
info.name = str;
jni.env->ReleaseStringUTFChars(name, str);
}
}
info.vid = jni.env->CallIntMethod(device, jni.getVendorId);
info.pid = jni.env->CallIntMethod(device, jni.getProductId);
}
LOGI("Found gamepad: %s (VID: 0x%x, PID: 0x%x)\n",
info.name.c_str(), info.vid, info.pid);
info.init_remap_table(get_input_tracker().get_joypad_remapper(index));
}
unsigned register_gamepad_id(int32_t id)
{
for (unsigned i = 0; i < InputTracker::Joypads; i++)
{
if (gamepad_ids[i] == -1)
{
get_input_tracker().enable_joypad(i);
gamepad_ids[i] = id;
query_gamepad_info(i, id);
return i;
}
else if (gamepad_ids[i] == id)
return i;
}
// Fallback to gamepad 0.
return 0;
}
VkSurfaceKHR create_surface(VkInstance instance, VkPhysicalDevice) override;
unsigned width, height;
Application *app = nullptr;
Vulkan::WSI *app_wsi = nullptr;
bool active = false;
bool has_window = true;
bool wsi_idle = false;
bool pending_native_window_init = false;
bool pending_native_window_term = false;
bool pending_config_change = false;
int32_t gamepad_ids[InputTracker::Joypads];
GamepadInfo gamepad_info[InputTracker::Joypads];
};
void WSIPlatformAndroid::GamepadInfo::init_remap_table(JoypadRemapper &remapper)
{
remapper.reset();
// TODO: Make this data-driven.
if (vid == 0x54c && pid == 0x9cc)
{
name = "PlayStation 4 Controller - Wireless";
LOGI("Autodetected joypad: %s\n", name.c_str());
remapper.register_button(AKEYCODE_BUTTON_A, JoypadKey::West, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_B, JoypadKey::South, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_C, JoypadKey::East, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_X, JoypadKey::North, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_Y, JoypadKey::LeftShoulder, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_START, JoypadKey::RightThumb, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_Z, JoypadKey::RightShoulder, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_SELECT, JoypadKey::LeftThumb, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_R2, JoypadKey::Start, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_L2, JoypadKey::Select, JoypadAxis::Unknown);
remapper.register_button(AKEYCODE_BUTTON_L1, JoypadKey::Unknown, JoypadAxis::LeftTrigger);
remapper.register_button(AKEYCODE_BUTTON_R1, JoypadKey::Unknown, JoypadAxis::RightTrigger);
remapper.register_axis(AMOTION_EVENT_AXIS_X, JoypadAxis::LeftX, 1.0f, JoypadKey::Unknown,
JoypadKey::Unknown);
remapper.register_axis(AMOTION_EVENT_AXIS_Y, JoypadAxis::LeftY, 1.0f, JoypadKey::Unknown,
JoypadKey::Unknown);
remapper.register_axis(AMOTION_EVENT_AXIS_Z, JoypadAxis::RightX, 1.0f, JoypadKey::Unknown,
JoypadKey::Unknown);
remapper.register_axis(AMOTION_EVENT_AXIS_RZ, JoypadAxis::RightY, 1.0f, JoypadKey::Unknown,
JoypadKey::Unknown);
remapper.register_axis(AMOTION_EVENT_AXIS_HAT_X, JoypadAxis::Unknown, 1.0f, JoypadKey::Left,
JoypadKey::Right);
remapper.register_axis(AMOTION_EVENT_AXIS_HAT_Y, JoypadAxis::Unknown, 1.0f, JoypadKey::Up,
JoypadKey::Down);
}
}
static VkSurfaceKHR create_surface_from_native_window(VkInstance instance, ANativeWindow *window)
{
VkSurfaceKHR surface = VK_NULL_HANDLE;
VkAndroidSurfaceCreateInfoKHR create_info = { VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR };
create_info.window = window;
if (vkCreateAndroidSurfaceKHR(instance, &create_info, nullptr, &surface) != VK_SUCCESS)
return VK_NULL_HANDLE;
return surface;
}
static void enable_sensors()
{
if (!jni.rotation_sensor || !jni.sensor_queue)
return;
int min_delay = ASensor_getMinDelay(jni.rotation_sensor);
ASensorEventQueue_enableSensor(jni.sensor_queue, jni.rotation_sensor);
if (ASensorEventQueue_setEventRate(jni.sensor_queue, jni.rotation_sensor, std::max(8000, min_delay)) < 0)
LOGE("Failed to set event rate.\n");
}
static void disable_sensors()
{
if (!jni.rotation_sensor || !jni.sensor_queue)
return;
ASensorEventQueue_disableSensor(jni.sensor_queue, jni.rotation_sensor);
}
static void handle_sensors()
{
if (!global_state.app->userData)
return;
auto &state = *static_cast<WSIPlatformAndroid *>(global_state.app->userData);
if (!ASensorEventQueue_hasEvents(jni.sensor_queue))
return;
ASensorEvent events[64];
for (;;)
{
int count = ASensorEventQueue_getEvents(jni.sensor_queue, events, 64);
if (count <= 0)
return;
for (int i = 0; i < count; i++)
{
auto &event = events[i];
if (event.type == SENSOR_GAME_ROTATION_VECTOR)
{
quat q(event.data[3], -event.data[0], -event.data[1], -event.data[2]);
if (global_state.display_rotation == 1)
{
// Compensate for different display rotation.
swap(q.x, q.y);
q.x = -q.x;
}
else if (global_state.display_rotation == 2 || global_state.display_rotation == 3)
{
//LOGE("Untested orientation %u!\n", global_state.display_rotation);
}
static const quat landscape(muglm::one_over_root_two<float>(), muglm::one_over_root_two<float>(), 0.0f, 0.0f);
q = conjugate(normalize(q * landscape));
state.get_input_tracker().orientation_event(q);
}
}
}
}
static int32_t engine_handle_input(android_app *app, AInputEvent *event)
{
if (!app->userData)
return 0;
auto &state = *static_cast<WSIPlatformAndroid *>(app->userData);
bool handled = false;
auto type = AInputEvent_getType(event);
auto source = AInputEvent_getSource(event);
auto device_id = AInputEvent_getDeviceId(event);
//auto source_class = source & AINPUT_SOURCE_CLASS_MASK;
source &= AINPUT_SOURCE_ANY;
switch (type)
{
case AINPUT_EVENT_TYPE_KEY:
{
if (source & AINPUT_SOURCE_GAMEPAD)
{
auto action = AKeyEvent_getAction(event);
auto code = AKeyEvent_getKeyCode(event);
bool pressed = action == AKEY_EVENT_ACTION_DOWN;
bool released = action == AKEY_EVENT_ACTION_UP;
if (pressed || released)
{
unsigned joypad_index = state.register_gamepad_id(device_id);
auto &tracker = state.get_input_tracker();
tracker.joypad_key_state_raw(joypad_index, code, pressed);
}
handled = true;
}
break;
}
case AINPUT_EVENT_TYPE_MOTION:
{
auto pointer = AMotionEvent_getAction(event);
auto action = pointer & AMOTION_EVENT_ACTION_MASK;
auto index = (pointer & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
if (source & AINPUT_SOURCE_JOYSTICK)
{
if (action == AMOTION_EVENT_ACTION_MOVE)
{
unsigned joypad_index = state.register_gamepad_id(device_id);
auto &tracker = state.get_input_tracker();
static const int axes[] = {
AMOTION_EVENT_AXIS_X,
AMOTION_EVENT_AXIS_Y,
AMOTION_EVENT_AXIS_Z,
AMOTION_EVENT_AXIS_RZ,
AMOTION_EVENT_AXIS_HAT_X,
AMOTION_EVENT_AXIS_HAT_Y,
AMOTION_EVENT_AXIS_LTRIGGER,
AMOTION_EVENT_AXIS_RTRIGGER,
AMOTION_EVENT_AXIS_GAS,
AMOTION_EVENT_AXIS_BRAKE,
};
for (int ax : axes)
tracker.joyaxis_state_raw(joypad_index, ax, AMotionEvent_getAxisValue(event, ax, index));
handled = true;
}
}
else if (source & AINPUT_SOURCE_TOUCHSCREEN)
{
switch (action)
{
case AMOTION_EVENT_ACTION_DOWN:
case AMOTION_EVENT_ACTION_POINTER_DOWN:
{
auto x = AMotionEvent_getX(event, index) / global_state.base_width;
auto y = AMotionEvent_getY(event, index) / global_state.base_height;
int id = AMotionEvent_getPointerId(event, index);
state.get_input_tracker().on_touch_down(id, x, y);
handled = true;
break;
}
case AMOTION_EVENT_ACTION_MOVE:
{
size_t count = AMotionEvent_getPointerCount(event);
for (size_t i = 0; i < count; i++)
{
auto x = AMotionEvent_getX(event, i) / global_state.base_width;
auto y = AMotionEvent_getY(event, i) / global_state.base_height;
int id = AMotionEvent_getPointerId(event, i);
state.get_input_tracker().on_touch_move(id, x, y);
}
state.get_input_tracker().dispatch_touch_gesture();
handled = true;
break;
}
case AMOTION_EVENT_ACTION_UP:
case AMOTION_EVENT_ACTION_POINTER_UP:
{
auto x = AMotionEvent_getX(event, index) / global_state.base_width;
auto y = AMotionEvent_getY(event, index) / global_state.base_height;
int id = AMotionEvent_getPointerId(event, index);
state.get_input_tracker().on_touch_up(id, x, y);
handled = true;
break;
}
default:
break;
}
}
break;
}
default:
break;
}
return handled ? 1 : 0;
}
static void engine_handle_cmd_init(android_app *app, int32_t cmd)
{
switch (cmd)
{
case APP_CMD_RESUME:
{
LOGI("Lifecycle resume\n");
enable_sensors();
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Running);
global_state.active = true;
Granite::Global::start_audio_system();
break;
}
case APP_CMD_PAUSE:
{
LOGI("Lifecycle pause\n");
disable_sensors();
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused);
global_state.active = false;
Granite::Global::stop_audio_system();
break;
}
case APP_CMD_START:
{
LOGI("Lifecycle start\n");
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused);
break;
}
case APP_CMD_STOP:
{
LOGI("Lifecycle stop\n");
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped);
break;
}
case APP_CMD_INIT_WINDOW:
{
global_state.has_window = app->window != nullptr;
if (app->window)
{
LOGI("Init window\n");
global_state.base_width = ANativeWindow_getWidth(app->window);
global_state.base_height = ANativeWindow_getHeight(app->window);
}
global_state.display_rotation = jni.env->CallIntMethod(app->activity->clazz, jni.getDisplayRotation);
break;
}
default:
break;
}
}
static void engine_handle_cmd(android_app *app, int32_t cmd)
{
if (!app->userData)
return;
auto &state = *static_cast<WSIPlatformAndroid *>(app->userData);
switch (cmd)
{
case APP_CMD_RESUME:
{
LOGI("Lifecycle resume\n");
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Running);
enable_sensors();
Granite::Global::start_audio_system();
state.active = true;
if (state.wsi_idle)
{
state.get_frame_timer().leave_idle();
state.wsi_idle = false;
}
break;
}
case APP_CMD_PAUSE:
{
LOGI("Lifecycle pause\n");
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused);
disable_sensors();
Granite::Global::stop_audio_system();
state.active = false;
state.get_frame_timer().enter_idle();
state.wsi_idle = true;
break;
}
case APP_CMD_START:
{
LOGI("Lifecycle start\n");
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused);
break;
}
case APP_CMD_STOP:
{
LOGI("Lifecycle stop\n");
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped);
break;
}
case APP_CMD_INIT_WINDOW:
if (app->window != nullptr)
{
state.has_window = true;
LOGI("New window size %d x %d\n", global_state.base_width, global_state.base_height);
global_state.base_width = ANativeWindow_getWidth(app->window);
global_state.base_height = ANativeWindow_getHeight(app->window);
global_state.content_rect_changed = false;
if (state.app_wsi)
{
LOGI("Lifecycle init window.\n");
auto surface = create_surface_from_native_window(state.app_wsi->get_context().get_instance(), app->window);
state.app_wsi->init_surface_and_swapchain(surface);
}
else
{
LOGI("Pending init window.\n");
state.pending_native_window_init = true;
}
}
break;
case APP_CMD_TERM_WINDOW:
state.has_window = false;
if (state.app_wsi)
{
LOGI("Lifecycle deinit window.\n");
state.app_wsi->deinit_surface_and_swapchain();
}
else
{
LOGI("Pending deinit window.\n");
state.pending_native_window_term = true;
}
break;
default:
break;
}
}
VkSurfaceKHR WSIPlatformAndroid::create_surface(VkInstance instance, VkPhysicalDevice)
{
return create_surface_from_native_window(instance, global_state.app->window);
}
void WSIPlatformAndroid::update_orientation()
{
// Apparently, AConfiguration_getOrientation is broken in latest Android versions.
// Gotta use JNI. Sigh ........
global_state.surface_orientation = App::getCurrentOrientation();
global_state.display_rotation = App::getDisplayRotation();
LOGI("Got new orientation: %d\n", global_state.surface_orientation);
LOGI("Got new rotation: %d\n", global_state.display_rotation);
LOGI("Got new resolution: %d x %d\n", global_state.base_width, global_state.base_height);
pending_config_change = true;
}
void WSIPlatformAndroid::poll_input()
{
int events;
int ident;
android_poll_source *source;
app_wsi = nullptr;
while ((ident = ALooper_pollAll(1, nullptr, &events, reinterpret_cast<void **>(&source))) >= 0)
{
if (source)
source->process(global_state.app, source);
if (ident == LOOPER_ID_USER)
handle_sensors();
if (global_state.app->destroyRequested)
return;
}
get_input_tracker().dispatch_current_state(get_frame_timer().get_frame_time());
}
bool WSIPlatformAndroid::alive(Vulkan::WSI &wsi)
{
auto &state = *static_cast<WSIPlatformAndroid *>(global_state.app->userData);
int events;
int ident;
android_poll_source *source;
state.app_wsi = &wsi;
if (global_state.app->destroyRequested)
return false;
bool once = false;
if (global_state.content_rect_changed)
{
update_orientation();
global_state.content_rect_changed = false;
}
if (state.pending_config_change)
{
state.pending_native_window_term = true;
state.pending_native_window_init = true;
state.pending_config_change = false;
}
const auto flush_pending = [&]() {
if (state.pending_native_window_term)
{
LOGI("Pending native window term\n");
wsi.deinit_surface_and_swapchain();
state.pending_native_window_term = false;
}
if (state.pending_native_window_init)
{
LOGI("Pending native window init\n");
auto surface = create_surface_from_native_window(wsi.get_context().get_instance(), global_state.app->window);
wsi.init_surface_and_swapchain(surface);
state.pending_native_window_init = false;
}
};
flush_pending();
while (!once || !state.active || !state.has_window)
{
while ((ident = ALooper_pollAll((state.has_window && state.active) ? 0 : -1,
nullptr, &events, reinterpret_cast<void **>(&source))) >= 0)
{
if (source)
source->process(global_state.app, source);
if (ident == LOOPER_ID_USER)
handle_sensors();
if (global_state.app->destroyRequested)
return false;
}
once = true;
}
flush_pending();
return true;
}
static void deinit_jni()
{
if (jni.env && global_state.app)
{
global_state.app->activity->vm->DetachCurrentThread();
jni.env = nullptr;
}
}
static void init_jni()
{
auto *app = global_state.app;
app->activity->vm->AttachCurrentThread(&jni.env, nullptr);
jclass clazz = jni.env->GetObjectClass(app->activity->clazz);
jmethodID getApplication = jni.env->GetMethodID(clazz, "getApplication", "()Landroid/app/Application;");
jobject application = jni.env->CallObjectMethod(app->activity->clazz, getApplication);
jclass applicationClass = jni.env->GetObjectClass(application);
jmethodID getApplicationContext = jni.env->GetMethodID(applicationClass, "getApplicationContext", "()Landroid/content/Context;");
jobject context = jni.env->CallObjectMethod(application, getApplicationContext);
jclass contextClass = jni.env->GetObjectClass(context);
jmethodID getClassLoader = jni.env->GetMethodID(contextClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
jni.classLoader = jni.env->CallObjectMethod(context, getClassLoader);
jni.classLoaderClass = jni.env->GetObjectClass(jni.classLoader);
jmethodID loadClass = jni.env->GetMethodID(jni.classLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jstring granite_str = jni.env->NewStringUTF("net.themaister.granite.GraniteActivity");
jni.granite = static_cast<jclass>(jni.env->CallObjectMethod(jni.classLoader, loadClass, granite_str));
jni.inputDeviceClass = jni.env->FindClass("android/view/InputDevice");
jni.finishFromThread = jni.env->GetMethodID(jni.granite, "finishFromThread", "()V");
jni.getDisplayRotation = jni.env->GetMethodID(jni.granite, "getDisplayRotation", "()I");
jni.getAudioNativeSampleRate = jni.env->GetMethodID(jni.granite, "getAudioNativeSampleRate", "()I");
jni.getAudioNativeBlockFrames = jni.env->GetMethodID(jni.granite, "getAudioNativeBlockFrames", "()I");
jni.getCurrentOrientation = jni.env->GetMethodID(jni.granite, "getCurrentOrientation", "()I");
jni.getCommandLineArgument = jni.env->GetMethodID(jni.granite, "getCommandLineArgument", "(Ljava/lang/String;)Ljava/lang/String;");
if (jni.inputDeviceClass)
{
jni.getDevice = jni.env->GetStaticMethodID(jni.inputDeviceClass, "getDevice",
"(I)Landroid/view/InputDevice;");
jni.getDeviceName = jni.env->GetMethodID(jni.inputDeviceClass, "getName",
"()Ljava/lang/String;");
jni.getVendorId = jni.env->GetMethodID(jni.inputDeviceClass, "getVendorId",
"()I");
jni.getProductId = jni.env->GetMethodID(jni.inputDeviceClass, "getProductId",
"()I");
}
#ifdef HAVE_GRANITE_AUDIO
int sample_rate = App::getAudioNativeSampleRate();
int block_frames = App::getAudioNativeBlockFrames();
#ifdef AUDIO_HAVE_OPENSL
Granite::Audio::set_opensl_low_latency_parameters(sample_rate, block_frames);
#endif
#ifdef AUDIO_HAVE_OBOE
Granite::Audio::set_oboe_low_latency_parameters(sample_rate, block_frames);
#endif
#endif
}
static void init_sensors()
{
#if __ANDROID_API__ >= 26
auto *manager = ASensorManager_getInstanceForPackage("net.themaister.GraniteActivity");
#else
auto *manager = ASensorManager_getInstance();
#endif
if (!manager)
return;
jni.rotation_sensor = ASensorManager_getDefaultSensor(manager, SENSOR_GAME_ROTATION_VECTOR);
if (!jni.rotation_sensor)
return;
LOGI("Game Sensor name: %s\n", ASensor_getName(jni.rotation_sensor));
jni.sensor_queue = ASensorManager_createEventQueue(manager, ALooper_forThread(), LOOPER_ID_USER, nullptr, nullptr);
if (!jni.sensor_queue)
return;
}
}
using namespace Granite;
static void wait_for_complete_teardown(android_app *app)
{
// If we requested to be torn down with App::finishFromThread(),
// at least make sure we observe and pump through all takedown events,
// or we get a deadlock.
while (!app->destroyRequested)
{
android_poll_source *source = nullptr;
int events = 0;
if (ALooper_pollAll(-1, nullptr, &events, reinterpret_cast<void **>(&source)) >= 0)
{
if (source)
source->process(app, source);
}
}
assert(app->activityState == APP_CMD_STOP);
}
void android_main(android_app *app)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
app_dummy();
#pragma GCC diagnostic pop
// Native glue does not implement this.
app->activity->callbacks->onContentRectChanged = on_content_rect_changed;
android_api_version = uint32_t(app->activity->sdkVersion);
// Statics on Android might not be cleared out.
global_state = {};
jni = {};
global_state.app = app;
init_jni();
Global::init();
LOGI("Starting Granite!\n");
#ifdef ANDROID_APK_FILESYSTEM
#ifndef ANDROID_BUILTIN_ASSET_PATH
#define ANDROID_BUILTIN_ASSET_PATH ""
#endif
#ifndef ANDROID_ASSET_PATH
#define ANDROID_ASSET_PATH ""
#endif
Global::filesystem()->register_protocol("builtin", make_unique<AssetManagerFilesystem>(ANDROID_BUILTIN_ASSET_PATH, app->activity->assetManager));
Global::filesystem()->register_protocol("assets", make_unique<AssetManagerFilesystem>(ANDROID_ASSET_PATH, app->activity->assetManager));
Global::filesystem()->register_protocol("cache", make_unique<OSFilesystem>(app->activity->internalDataPath));
#endif
app->onAppCmd = engine_handle_cmd_init;
app->onInputEvent = engine_handle_input;
app->userData = nullptr;
init_sensors();
Granite::Global::event_manager()->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped);
for (;;)
{
int events;
int ident;
android_poll_source *source;
while ((ident = ALooper_pollAll(-1, nullptr, &events, reinterpret_cast<void **>(&source))) >= 0)
{
if (source)
source->process(app, source);
if (app->destroyRequested)
{
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
Global::deinit();
deinit_jni();
return;
}
if (ident == LOOPER_ID_USER)
handle_sensors();
if (Granite::global_state.has_window && Granite::global_state.content_rect_changed)
{
Granite::global_state.content_rect_changed = false;
global_state.surface_orientation = AConfiguration_getOrientation(app->config);
LOGI("Get initial orientation: %d\n", global_state.surface_orientation);
app->onAppCmd = Granite::engine_handle_cmd;
try
{
vector<const char *> argv;
argv.push_back("granite");
string cli_arguments = App::getCommandLine();
vector<string> arguments;
LOGI("Intent arguments: %s\n", cli_arguments.c_str());
if (!cli_arguments.empty())
{
arguments = Util::split_no_empty(cli_arguments, " ");
for (auto &arg : arguments)
{
LOGI("Command line argument: %s\n", arg.c_str());
argv.push_back(arg.c_str());
}
}
argv.push_back(nullptr);
auto app_handle = unique_ptr<Granite::Application>(
Granite::application_create(int(argv.size()) - 1,
const_cast<char **>(argv.data())));
int ret;
if (app_handle)
{
// TODO: Configurable.
app_handle->get_wsi().set_support_prerotate(false);
unsigned width = app_handle->get_default_width();
unsigned height = app_handle->get_default_height();
{
string android_config;
Global::filesystem()->read_file_to_string("assets://android.json", android_config);
if (!android_config.empty())
{
rapidjson::Document doc;
doc.Parse(android_config);
if (doc.HasMember("width"))
width = doc["width"].GetUint();
if (doc.HasMember("height"))
height = doc["height"].GetUint();
}
}
LOGI("Using resolution: %u x %u\n", width, height);
auto platform = make_unique<Granite::WSIPlatformAndroid>();
if (platform->init(width, height))
{
global_state.app->userData = platform.get();
if (!app_handle->init_wsi(move(platform)))
ret = 1;
else
{
while (app_handle->poll())
app_handle->run_frame();
ret = 0;
}
}
else
ret = 1;
}
else
{
global_state.app->userData = nullptr;
ret = 1;
}
LOGI("Application returned %d.\n", ret);
Granite::Global::event_manager()->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id());
App::finishFromThread();
wait_for_complete_teardown(global_state.app);
app_handle.reset();
Global::deinit();
deinit_jni();
return;
}
catch (const std::exception &e)
{
LOGE("Application threw exception: %s\n", e.what());
deinit_jni();
exit(1);
}
}
}
}
}
| 29.164939 | 180 | 0.721529 | [
"vector"
] |
78dd36d18786e08cbeaecc870432dbf8c0f3d50e | 2,868 | cc | C++ | Chapter13/cloud_classify/server/main.cc | bdonkey/Hands-On-Machine-Learning-with-CPP | d2b17abeb48db3d45369fdb1be806682ab9819ed | [
"MIT"
] | 201 | 2020-05-13T12:50:50.000Z | 2022-03-27T20:56:11.000Z | Chapter13/cloud_classify/server/main.cc | bdonkey/Hands-On-Machine-Learning-with-CPP | d2b17abeb48db3d45369fdb1be806682ab9819ed | [
"MIT"
] | 1 | 2021-05-12T10:01:40.000Z | 2021-05-14T19:35:05.000Z | Chapter13/cloud_classify/server/main.cc | bdonkey/Hands-On-Machine-Learning-with-CPP | d2b17abeb48db3d45369fdb1be806682ab9819ed | [
"MIT"
] | 63 | 2020-06-05T15:03:39.000Z | 2022-02-22T02:07:09.000Z | #include <torch/script.h>
#include "network.h"
#include <httplib/httplib.h>
#include "utils.h"
int main(int argc, char** argv) {
try {
std::string snapshoot_path;
std::string synset_path;
std::string www_path;
std::string host = "localhost";
int port = 8080;
if (argc >= 4) {
snapshoot_path = argv[1];
synset_path = argv[2];
www_path = argv[3];
if (argc >= 5)
host = argv[4];
if (argc >= 6)
port = std::stoi(argv[5]);
std::cout << "Starting server:\n";
std::cout << "Model path: " << snapshoot_path << "\n";
std::cout << "Synset path: " << synset_path << "\n";
std::cout << "WWW path: " << www_path << "\n";
std::cout << "Host: " << host << "\n";
std::cout << "Port: " << port << std::endl;
torch::DeviceType device_type = torch::cuda::is_available()
? torch::DeviceType::CUDA
: torch::DeviceType::CPU;
Network network(snapshoot_path, synset_path, device_type);
std::cout << "Model initialized" << std::endl;
httplib::Server server;
server.set_base_dir(www_path.c_str());
server.set_logger([](const auto& req, const auto& /*res*/) {
std::cout << req.method << "\n" << req.path << std::endl;
});
server.set_error_handler([](const auto& /*req*/, auto& res) {
std::stringstream buf;
buf << "<p>Error Status: <span style='color:red;'>";
buf << res.status;
buf << "</span></p>";
res.set_content(buf.str(), "text/html");
});
server.Post("/multipart", [&](const auto& req, auto& res) {
std::string response_string;
for (auto& file : req.files) {
auto body = file.second.content;
std::cout << file.second.filename << std::endl;
std::cout << file.second.content_type << std::endl;
try {
auto img = ReadMemoryImageTensor(body, 224, 224);
auto class_name = network.Classify(img);
response_string += "; " + class_name;
} catch (...) {
response_string += "; Classification failed";
}
}
res.set_content(response_string.c_str(), "text/html");
});
std::cout << "Server starting ..." << std::endl;
if (!server.listen(host.c_str(), port)) {
std::cerr << "Failed to start server\n";
}
std::cout << "Server finished" << std::endl;
} else {
std::cout << "usage: " << argv[0]
<< " <model snapshoot path> <synset file path> <www "
"dir=../../client> "
"[host=localhost] [port=8080]\n";
}
} catch (const std::exception& err) {
std::cerr << err.what();
} catch (...) {
std::cerr << "Unhandled exception";
}
return 1;
}
| 32.224719 | 69 | 0.514644 | [
"model"
] |
78e02fbbb63b3e3c657fecae6379afbbcdfea4de | 17,815 | cpp | C++ | interfaces/innerkits/permission_standard/distributedpermission/main/cpp/src/distributed_permission_manager_client.cpp | openharmony-gitee-mirror/security_permission | dd482838bfe697dad1dd40531aa8fca2bd4d6883 | [
"Apache-2.0"
] | null | null | null | interfaces/innerkits/permission_standard/distributedpermission/main/cpp/src/distributed_permission_manager_client.cpp | openharmony-gitee-mirror/security_permission | dd482838bfe697dad1dd40531aa8fca2bd4d6883 | [
"Apache-2.0"
] | null | null | null | interfaces/innerkits/permission_standard/distributedpermission/main/cpp/src/distributed_permission_manager_client.cpp | openharmony-gitee-mirror/security_permission | dd482838bfe697dad1dd40531aa8fca2bd4d6883 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Device 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 "distributed_permission_manager_client.h"
#include "distributed_permission_death_recipient.h"
#include "permission_log.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "ipc_skeleton.h"
#include "distributed_permission_kit.h"
#include "permission/permission_kit.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
LOG_CORE, SECURITY_DOMAIN_PERMISSION, "DistributedPermissionManagerClient"};
}
const int32_t ERROR = -1;
DistributedPermissionManagerClient &DistributedPermissionManagerClient::GetInstance()
{
static DistributedPermissionManagerClient instance;
return instance;
}
int32_t DistributedPermissionManagerClient::AllocateDuid(const std::string &nodeId, const int32_t rUid)
{
PERMISSION_LOG_INFO(LABEL, "nodeId = %{public}s, rUid = %{public}d", Constant::EncryptDevId(nodeId).c_str(), rUid);
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->AllocateDuid(nodeId, rUid);
}
int32_t DistributedPermissionManagerClient::QueryDuid(const std::string &deviceId, int32_t rUid)
{
PERMISSION_LOG_INFO(
LABEL, "deviceId = %{public}s, rUid = %{public}d", Constant::EncryptDevId(deviceId).c_str(), rUid);
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->QueryDuid(deviceId, rUid);
}
int32_t DistributedPermissionManagerClient::CheckDPermission(int32_t dUid, const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "dUid = %{public}d, permissionName = %{public}s", dUid, permissionName.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->CheckDPermission(dUid, permissionName);
}
int32_t DistributedPermissionManagerClient::CheckPermission(const std::string &permissionName,
const std::string &appIdInfo)
{
PERMISSION_LOG_INFO(
LABEL, "permissionName = %{public}s, appIdInfo = %{public}s", permissionName.c_str(), appIdInfo.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->CheckPermission(permissionName, appIdInfo);
}
bool DistributedPermissionManagerClient::IsPermissionNameValid(const std::string &permissionName)
{
return !permissionName.empty() && (permissionName.length() <= MAX_LENGTH);
}
int32_t DistributedPermissionManagerClient::CheckSelfPermission(const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "permissionName = %{public}s", permissionName.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
if (!DistributedPermissionManagerClient::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "CheckSelfPermission::permissionName is not valid");
return Constant::PERMISSION_DENIED;
}
// CheckSelfPermission is used by applications to check whether they have certain permissions,
// so the IPC package is used to get the process id and uid of the call source.
pid_t pid = IPCSkeleton::GetCallingPid();
pid_t uid = IPCSkeleton::GetCallingUid();
AppIdInfo appIdInfoObj;
std::string appIdInfo = DistributedPermissionKit::AppIdInfoHelper::CreateAppIdInfo(pid, uid, "");
return distributedPermissionProxy_->CheckPermission(permissionName, appIdInfo);
}
int32_t DistributedPermissionManagerClient::CheckCallingPermission(const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "permissionName = %{public}s", permissionName.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
if (!DistributedPermissionManagerClient::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "CheckCallingPermission::permissionName is not valid");
return Constant::PERMISSION_DENIED;
}
// Only used to check the permissions of the caller.
pid_t pid = IPCSkeleton::GetCallingPid();
pid_t uid = IPCSkeleton::GetCallingUid();
std::string deviceId = IPCSkeleton::GetCallingDeviceID();
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
if ((pid == getpid()) && (uid == (pid_t) getuid()) && (deviceId == localDeviceId)) {
return Constant::PERMISSION_DENIED;
}
std::string appIdInfo = DistributedPermissionKit::AppIdInfoHelper::CreateAppIdInfo(pid, uid, deviceId);
return distributedPermissionProxy_->CheckPermission(permissionName, appIdInfo);
}
int32_t DistributedPermissionManagerClient::CheckCallingOrSelfPermission(const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "permissionName = %{public}s", permissionName.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
if (!DistributedPermissionManagerClient::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "CheckCallingOrSelfPermission::permissionName is not valid");
return Constant::PERMISSION_DENIED;
}
// Check the permission of its own application or caller application.
pid_t pid = IPCSkeleton::GetCallingPid();
pid_t uid = IPCSkeleton::GetCallingUid();
std::string deviceId = IPCSkeleton::GetCallingDeviceID();
std::string appIdInfo = DistributedPermissionKit::AppIdInfoHelper::CreateAppIdInfo(pid, uid, deviceId);
return distributedPermissionProxy_->CheckPermission(permissionName, appIdInfo);
}
int32_t DistributedPermissionManagerClient::CheckCallerPermission(const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "permissionName = %{public}s", permissionName.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return CheckCallingOrSelfPermission(permissionName);
}
bool DistributedPermissionManagerClient::IsRestrictedPermission(const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "permissionName = %{public}s", permissionName.c_str());
if (!DistributedPermissionManagerClient::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "PermissionName data invalid");
return false;
}
std::unique_ptr<PmsAdapter> pmsAdapter = std::make_unique<PmsAdapter>();
if (iPermissionManager_ == nullptr) {
iPermissionManager_ = pmsAdapter->GetPermissionManager();
}
PermissionDefParcel permissionDefResult;
int ret = iPermissionManager_->GetDefPermission(permissionName, permissionDefResult);
if (ret != 0) {
PERMISSION_LOG_ERROR(LABEL, "get permission def failed");
return false;
}
if (permissionDefResult.permissionDef.availableScope == Permission::AvailableScope::AVAILABLE_SCOPE_RESTRICTED) {
return true;
}
return false;
}
int32_t DistributedPermissionManagerClient::VerifyPermissionFromRemote(
const std::string &permission, const std::string &nodeId, const std::string &appIdInfo)
{
PERMISSION_LOG_INFO(LABEL, "permission = %{public}s, nodeId = %{public}s, appIdInfo = %{public}s",
permission.c_str(), Constant::EncryptDevId(nodeId).c_str(), appIdInfo.c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->VerifyPermissionFromRemote(permission, nodeId, appIdInfo);
}
int32_t DistributedPermissionManagerClient::VerifySelfPermissionFromRemote(
const std::string &permissionName, const std::string &nodeId)
{
PERMISSION_LOG_INFO(LABEL,
"permissionName = %{public}s, nodeId = %{public}s",
permissionName.c_str(),
Constant::EncryptDevId(nodeId).c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->VerifySelfPermissionFromRemote(permissionName, nodeId);
}
bool DistributedPermissionManagerClient::CanRequestPermissionFromRemote(
const std::string &permissionName, const std::string &nodeId)
{
PERMISSION_LOG_INFO(LABEL,
"permissionName = %{public}s, nodeId = %{public}s",
permissionName.c_str(),
Constant::EncryptDevId(nodeId).c_str());
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->CanRequestPermissionFromRemote(permissionName, nodeId);
}
void DistributedPermissionManagerClient::RequestPermissionsFromRemote(const std::vector<std::string> permissions,
const sptr<OnRequestPermissionsResult> &callback, const std::string &nodeId, const std::string &bundleName,
int32_t reasonResId)
{
if (callback == nullptr) {
PERMISSION_LOG_INFO(LABEL, "RequestPermissionsFromRemote param callback is null!");
return;
}
PERMISSION_LOG_INFO(LABEL,
"bundleName = %{public}s, nodeId = %{public}s",
bundleName.c_str(),
Constant::EncryptDevId(nodeId).c_str());
if (!GetDistributedPermissionProxy()) {
return;
}
return distributedPermissionProxy_->RequestPermissionsFromRemote(
permissions, callback, nodeId, bundleName, reasonResId);
}
void DistributedPermissionManagerClient::GrantSensitivePermissionToRemoteApp(
const std::string &permissionName, const std::string &nodeId, int32_t ruid)
{
PERMISSION_LOG_INFO(LABEL,
"permissionName = %{public}s, nodeId = %{public}s, ruid = %{public}d",
permissionName.c_str(),
Constant::EncryptDevId(nodeId).c_str(),
ruid);
if (!GetDistributedPermissionProxy()) {
return;
}
return distributedPermissionProxy_->GrantSensitivePermissionToRemoteApp(permissionName, nodeId, ruid);
}
int32_t DistributedPermissionManagerClient::RegisterUsingPermissionReminder(
const sptr<OnUsingPermissionReminder> &callback)
{
PERMISSION_LOG_INFO(LABEL, "enter RegisterUsingPermissionReminder");
if (callback == nullptr) {
return ERROR;
}
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->RegisterUsingPermissionReminder(callback);
}
int32_t DistributedPermissionManagerClient::UnregisterUsingPermissionReminder(
const sptr<OnUsingPermissionReminder> &callback)
{
PERMISSION_LOG_INFO(LABEL, "enter UnregisterUsingPermissionReminder");
if (callback == nullptr) {
return ERROR;
}
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->UnregisterUsingPermissionReminder(callback);
}
int32_t DistributedPermissionManagerClient::CheckPermissionAndStartUsing(
const std::string &permissionName, const std::string &appIdInfo)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s: called!", __func__);
if (permissionName.empty() || appIdInfo.empty()) {
return ERROR;
}
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
return distributedPermissionProxy_->CheckPermissionAndStartUsing(permissionName, appIdInfo);
}
int32_t DistributedPermissionManagerClient::CheckCallerPermissionAndStartUsing(const std::string &permissionName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s: called!", __func__);
if (permissionName.empty()) {
return ERROR;
}
if (!GetDistributedPermissionProxy()) {
return ERROR;
}
pid_t pid = IPCSkeleton::GetCallingPid();
uid_t uid = IPCSkeleton::GetCallingUid();
char deviceId[Constant::DEVICE_UUID_LENGTH] = {0};
GetDevUdid(deviceId, Constant::DEVICE_UUID_LENGTH);
std::string appIdInfo = DistributedPermissionKit::AppIdInfoHelper::CreateAppIdInfo(pid, uid, deviceId);
PERMISSION_LOG_INFO(LABEL,
"CheckCallerPermissionAndStartUsing::calling pid: %{public}d, uid: %{public}d, deviceId: %{private}s",
pid,
uid,
Constant::EncryptDevId(deviceId).c_str());
return CheckPermissionAndStartUsing(permissionName, appIdInfo);
}
void DistributedPermissionManagerClient::StartUsingPermission(const std::string &permName, const std::string &appIdInfo)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s: called!", __func__);
if (permName.empty() || appIdInfo.empty()) {
PERMISSION_LOG_INFO(LABEL, "checkresult : Param Empty");
return;
}
if (!GetDistributedPermissionProxy()) {
return;
}
return distributedPermissionProxy_->StartUsingPermission(permName, appIdInfo);
}
void DistributedPermissionManagerClient::StopUsingPermission(const std::string &permName, const std::string &appIdInfo)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s: called!", __func__);
if (permName.empty() || appIdInfo.empty()) {
PERMISSION_LOG_INFO(LABEL, "checkresult : Param Empty");
return;
}
if (!GetDistributedPermissionProxy()) {
return;
}
return distributedPermissionProxy_->StopUsingPermission(permName, appIdInfo);
}
void DistributedPermissionManagerClient::ResetDistributedPermissionProxy()
{
std::lock_guard<std::mutex> lock(mutex_);
if ((distributedPermissionProxy_ != nullptr) && (distributedPermissionProxy_->AsObject() != nullptr)) {
distributedPermissionProxy_->AsObject()->RemoveDeathRecipient(recipient_);
}
distributedPermissionProxy_ = nullptr;
}
void DistributedPermissionManagerClient::AddPermissionUsedRecord(
const std::string &permissionName, const std::string &appIdInfo, const int32_t sucCount, const int32_t failCount)
{
PERMISSION_LOG_INFO(LABEL, "enter");
PERMISSION_LOG_INFO(LABEL,
"permissionName = %{public}s, appIdInfo = %{public}s, sucCount = "
"%{public}d, failCount = %{public}d",
permissionName.c_str(),
appIdInfo.c_str(),
sucCount,
failCount);
if (permissionName.empty()) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s permissionName invalid", __func__);
return;
}
if (!GetDistributedPermissionProxy()) {
return;
}
distributedPermissionProxy_->AddPermissionsRecord(permissionName, appIdInfo, sucCount, failCount);
}
int32_t DistributedPermissionManagerClient::GetPermissionUsedRecords(const QueryPermissionUsedRequest &request,
QueryPermissionUsedResult &result)
{
if (!GetDistributedPermissionProxy()) {
return Constant::FAILURE_DPMS;
}
nlohmann::json jsonObj = request.to_json(request);
std::string queryJsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::replace);
std::string queryGzipStr;
if (ZipUtils::CompressString(queryJsonStr, queryGzipStr) != ZipUtils::OK) {
return Constant::FAILURE;
}
std::string resultGzipStr;
int32_t ret = distributedPermissionProxy_->GetPermissionRecords(queryGzipStr, resultGzipStr);
std::string resultJsonStr;
if (ZipUtils::DecompressString(resultGzipStr, resultJsonStr) != ZipUtils::OK) {
return Constant::FAILURE;
}
nlohmann::json jsonRes = nlohmann::json::parse(resultJsonStr, nullptr, false);
result.from_json(jsonRes, result);
return ret;
}
int32_t DistributedPermissionManagerClient::GetPermissionUsedRecords(const QueryPermissionUsedRequest &request,
const sptr<OnPermissionUsedRecord> &callback)
{
if (!GetDistributedPermissionProxy()) {
return Constant::FAILURE_DPMS;
}
nlohmann::json jsonObj = request.to_json(request);
std::string queryJsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::replace);
std::string queryGzipStr;
if (ZipUtils::CompressString(queryJsonStr, queryGzipStr) != ZipUtils::OK) {
return Constant::FAILURE;
}
int32_t ret = distributedPermissionProxy_->GetPermissionRecords(queryGzipStr, callback);
return ret;
}
bool DistributedPermissionManagerClient::GetDistributedPermissionProxy()
{
if (!distributedPermissionProxy_) {
std::lock_guard<std::mutex> lock(mutex_);
if (!distributedPermissionProxy_) {
sptr<ISystemAbilityManager> systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!systemAbilityManager) {
PERMISSION_LOG_ERROR(LABEL, "failed to get systemAbilityManager.");
return false;
}
sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(
IDistributedPermission::SA_ID_DISTRIBUTED_PERMISSION_MANAGER_SERVICE);
if (!remoteObject) {
PERMISSION_LOG_ERROR(LABEL, "failed to get remoteObject.");
return false;
}
distributedPermissionProxy_ = iface_cast<IDistributedPermission>(remoteObject);
if ((!distributedPermissionProxy_) || (!distributedPermissionProxy_->AsObject())) {
PERMISSION_LOG_ERROR(LABEL, "failed to get distributedPermissionProxy_.");
return false;
}
recipient_ = new (std::nothrow) DistributedPermissionDeathRecipient();
if (!recipient_) {
PERMISSION_LOG_ERROR(LABEL, "failed to new recipient_.");
return false;
}
distributedPermissionProxy_->AsObject()->AddDeathRecipient(recipient_);
}
}
return true;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS | 38.229614 | 120 | 0.723211 | [
"vector"
] |
78e525f8b73ebe9439c28aa004f0ce0904d5071e | 7,898 | hxx | C++ | opencascade/BRepAlgoAPI_Section.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/BRepAlgoAPI_Section.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/BRepAlgoAPI_Section.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1994-02-18
// Created by: Remi LEQUETTE
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepAlgoAPI_Section_HeaderFile
#define _BRepAlgoAPI_Section_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <BRepAlgoAPI_BooleanOperation.hxx>
class BOPAlgo_PaveFiller;
class TopoDS_Shape;
class gp_Pln;
class Geom_Surface;
//! The algorithm is to build a Section operation between arguments and tools.
//! The result of Section operation consists of vertices and edges.
//! The result of Section operation contains:
//! 1. new vertices that are subjects of V/V, E/E, E/F, F/F interferences
//! 2. vertices that are subjects of V/E, V/F interferences
//! 3. new edges that are subjects of F/F interferences
//! 4. edges that are Common Blocks
class BRepAlgoAPI_Section : public BRepAlgoAPI_BooleanOperation
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT BRepAlgoAPI_Section();
Standard_EXPORT virtual ~BRepAlgoAPI_Section();
//! Empty constructor
//! <PF> - PaveFiller object that is carried out
Standard_EXPORT BRepAlgoAPI_Section(const BOPAlgo_PaveFiller& PF);
//! Constructor with two shapes
//! <S1> -argument
//! <S2> -tool
//! <PerformNow> - the flag:
//! if <PerformNow>=True - the algorithm is performed immediately
//! Obsolete
Standard_EXPORT BRepAlgoAPI_Section(const TopoDS_Shape& S1, const TopoDS_Shape& S2, const Standard_Boolean PerformNow = Standard_True);
//! Constructor with two shapes
//! <S1> -argument
//! <S2> -tool
//! <PF> - PaveFiller object that is carried out
//! <PerformNow> - the flag:
//! if <PerformNow>=True - the algorithm is performed immediately
//! Obsolete
Standard_EXPORT BRepAlgoAPI_Section(const TopoDS_Shape& S1, const TopoDS_Shape& S2, const BOPAlgo_PaveFiller& aDSF, const Standard_Boolean PerformNow = Standard_True);
//! Constructor with two shapes
//! <S1> - argument
//! <Pl> - tool
//! <PerformNow> - the flag:
//! if <PerformNow>=True - the algorithm is performed immediately
//! Obsolete
Standard_EXPORT BRepAlgoAPI_Section(const TopoDS_Shape& S1, const gp_Pln& Pl, const Standard_Boolean PerformNow = Standard_True);
//! Constructor with two shapes
//! <S1> - argument
//! <Sf> - tool
//! <PerformNow> - the flag:
//! if <PerformNow>=True - the algorithm is performed immediately
//! Obsolete
Standard_EXPORT BRepAlgoAPI_Section(const TopoDS_Shape& S1, const Handle(Geom_Surface)& Sf, const Standard_Boolean PerformNow = Standard_True);
//! Constructor with two shapes
//! <Sf> - argument
//! <S2> - tool
//! <PerformNow> - the flag:
//! if <PerformNow>=True - the algorithm is performed immediately
//! Obsolete
Standard_EXPORT BRepAlgoAPI_Section(const Handle(Geom_Surface)& Sf, const TopoDS_Shape& S2, const Standard_Boolean PerformNow = Standard_True);
//! Constructor with two shapes
//! <Sf1> - argument
//! <Sf2> - tool
//! <PerformNow> - the flag:
//! if <PerformNow>=True - the algorithm is performed immediately
//! Obsolete
Standard_EXPORT BRepAlgoAPI_Section(const Handle(Geom_Surface)& Sf1, const Handle(Geom_Surface)& Sf2, const Standard_Boolean PerformNow = Standard_True);
//! initialize the argument
//! <S1> - argument
//! Obsolete
Standard_EXPORT void Init1 (const TopoDS_Shape& S1);
//! initialize the argument
//! <Pl> - argument
//! Obsolete
Standard_EXPORT void Init1 (const gp_Pln& Pl);
//! initialize the argument
//! <Sf> - argument
//! Obsolete
Standard_EXPORT void Init1 (const Handle(Geom_Surface)& Sf);
//! initialize the tool
//! <S2> - tool
//! Obsolete
Standard_EXPORT void Init2 (const TopoDS_Shape& S2);
//! initialize the tool
//! <Pl> - tool
//! Obsolete
Standard_EXPORT void Init2 (const gp_Pln& Pl);
//! initialize the tool
//! <Sf> - tool
//! Obsolete
Standard_EXPORT void Init2 (const Handle(Geom_Surface)& Sf);
Standard_EXPORT void Approximation (const Standard_Boolean B);
//! Indicates whether the P-Curve should be (or not)
//! performed on the argument.
//! By default, no parametric 2D curve (pcurve) is defined for the
//! edges of the result.
//! If ComputePCurve1 equals true, further computations performed
//! to attach an P-Curve in the parametric space of the argument
//! to the constructed edges.
//! Obsolete
Standard_EXPORT void ComputePCurveOn1 (const Standard_Boolean B);
//! Indicates whether the P-Curve should be (or not)
//! performed on the tool.
//! By default, no parametric 2D curve (pcurve) is defined for the
//! edges of the result.
//! If ComputePCurve1 equals true, further computations performed
//! to attach an P-Curve in the parametric space of the tool
//! to the constructed edges.
//! Obsolete
Standard_EXPORT void ComputePCurveOn2 (const Standard_Boolean B);
//! Performs the algorithm
//! Filling interference Data Structure (if it is necessary)
//! Building the result of the operation.
Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
//! get the face of the first part giving section edge <E>.
//! Returns True on the 3 following conditions :
//! 1/ <E> is an edge returned by the Shape() metwod.
//! 2/ First part of section performed is a shape.
//! 3/ <E> is built on a intersection curve (i.e <E>
//! is not the result of common edges)
//! When False, F remains untouched.
//! Obsolete
Standard_EXPORT Standard_Boolean HasAncestorFaceOn1 (const TopoDS_Shape& E, TopoDS_Shape& F) const;
//! Identifies the ancestor faces of
//! the intersection edge E resulting from the last
//! computation performed in this framework, that is, the faces of
//! the two original shapes on which the edge E lies:
//! - HasAncestorFaceOn1 gives the ancestor face in the first shape, and
//! - HasAncestorFaceOn2 gives the ancestor face in the second shape.
//! These functions return true if an ancestor face F is found, or false if not.
//! An ancestor face is identifiable for the edge E if the following
//! conditions are satisfied:
//! - the first part on which this algorithm performed its
//! last computation is a shape, that is, it was not given as
//! a surface or a plane at the time of construction of this
//! algorithm or at a later time by the Init1 function,
//! - E is one of the elementary edges built by the
//! last computation of this section algorithm.
//! To use these functions properly, you have to test the returned
//! Boolean value before using the ancestor face: F is significant
//! only if the returned Boolean value equals true.
//! Obsolete
Standard_EXPORT Standard_Boolean HasAncestorFaceOn2 (const TopoDS_Shape& E, TopoDS_Shape& F) const;
protected:
Standard_EXPORT void Init (const Standard_Boolean PerformNow);
Standard_EXPORT virtual void SetAttributes() Standard_OVERRIDE;
private:
Standard_Boolean myApprox;
Standard_Boolean myComputePCurve1;
Standard_Boolean myComputePCurve2;
};
#endif // _BRepAlgoAPI_Section_HeaderFile
| 37.079812 | 169 | 0.723854 | [
"object",
"shape"
] |
78ee037ae2ea73766c2eb95bece2a384fb898c45 | 11,319 | hpp | C++ | or-tools_Ubuntu-18.04-64bit_v7.4.7247/include/coin/CbcNode.hpp | rajiff/docker-google-or-tools | b7a6c730639c5b47857925de9cf673b456cb4390 | [
"Apache-2.0"
] | 7 | 2020-07-04T01:50:12.000Z | 2021-06-03T21:54:52.000Z | PO_class/assignment_2/or-tools/include/coin/CbcNode.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | null | null | null | PO_class/assignment_2/or-tools/include/coin/CbcNode.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | null | null | null | /* $Id$ */
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef CbcNode_H
#define CbcNode_H
#include <string>
#include <vector>
#include "CoinWarmStartBasis.hpp"
#include "CoinSearchTree.hpp"
#include "CbcBranchBase.hpp"
#include "CbcNodeInfo.hpp"
#include "CbcFullNodeInfo.hpp"
#include "CbcPartialNodeInfo.hpp"
class OsiSolverInterface;
class OsiSolverBranch;
class OsiCuts;
class OsiRowCut;
class OsiRowCutDebugger;
class CoinWarmStartBasis;
class CbcCountRowCut;
class CbcModel;
class CbcNode;
class CbcSubProblem;
class CbcGeneralBranchingObject;
/** Information required while the node is live
When a subproblem is initially created, it is represented by an CbcNode
object and an attached CbcNodeInfo object.
The CbcNode contains information (depth, branching instructions), that's
needed while the subproblem remains `live', <i>i.e.</i>, while the
subproblem is not fathomed and there are branch arms still be be
evaluated. The CbcNode is deleted when the last branch arm has been
evaluated.
The CbcNodeInfo object contains the information needed to maintain the
search tree and recreate the subproblem for the node. It remains in
existence until there are no nodes remaining in the subtree rooted at this
node.
*/
class CbcNode : public CoinTreeNode {
public:
/// Default Constructor
CbcNode();
/// Construct and increment parent reference count
CbcNode(CbcModel *model, CbcNode *lastNode);
/// Copy constructor
CbcNode(const CbcNode &);
/// Assignment operator
CbcNode &operator=(const CbcNode &rhs);
/// Destructor
~CbcNode();
/** Create a description of the subproblem at this node
The CbcNodeInfo structure holds the information (basis & variable bounds)
required to recreate the subproblem for this node. It also links the node
to its parent (via the parent's CbcNodeInfo object).
If lastNode == NULL, a CbcFullNodeInfo object will be created. All
parameters except \p model are unused.
If lastNode != NULL, a CbcPartialNodeInfo object will be created. Basis and
bounds information will be stored in the form of differences between the
parent subproblem and this subproblem.
(More precisely, \p lastws, \p lastUpper, \p lastLower,
\p numberOldActiveCuts, and \p numberNewCuts are used.)
*/
void
createInfo(CbcModel *model,
CbcNode *lastNode,
const CoinWarmStartBasis *lastws,
const double *lastLower, const double *lastUpper,
int numberOldActiveCuts, int numberNewCuts);
/** Create a branching object for the node
The routine scans the object list of the model and selects a set of
unsatisfied objects as candidates for branching. The candidates are
evaluated, and an appropriate branch object is installed.
The numberPassesLeft is decremented to stop fixing one variable each time
and going on and on (e.g. for stock cutting, air crew scheduling)
If evaluation determines that an object is monotone or infeasible,
the routine returns immediately. In the case of a monotone object,
the branch object has already been called to modify the model.
Return value:
<ul>
<li> 0: A branching object has been installed
<li> -1: A monotone object was discovered
<li> -2: An infeasible object was discovered
</ul>
*/
int chooseBranch(CbcModel *model,
CbcNode *lastNode,
int numberPassesLeft);
/** Create a branching object for the node - when dynamic pseudo costs
The routine scans the object list of the model and selects a set of
unsatisfied objects as candidates for branching. The candidates are
evaluated, and an appropriate branch object is installed.
This version gives preference in evaluation to variables which
have not been evaluated many times. It also uses numberStrong
to say give up if last few tries have not changed incumbent.
See Achterberg, Koch and Martin.
The numberPassesLeft is decremented to stop fixing one variable each time
and going on and on (e.g. for stock cutting, air crew scheduling)
If evaluation determines that an object is monotone or infeasible,
the routine returns immediately. In the case of a monotone object,
the branch object has already been called to modify the model.
Return value:
<ul>
<li> 0: A branching object has been installed
<li> -1: A monotone object was discovered
<li> -2: An infeasible object was discovered
<li> >0: Number of quich branching objects (and branches will be non NULL)
</ul>
*/
int chooseDynamicBranch(CbcModel *model,
CbcNode *lastNode,
OsiSolverBranch *&branches,
int numberPassesLeft);
/** Create a branching object for the node
The routine scans the object list of the model and selects a set of
unsatisfied objects as candidates for branching. The candidates are
evaluated, and an appropriate branch object is installed.
The numberPassesLeft is decremented to stop fixing one variable each time
and going on and on (e.g. for stock cutting, air crew scheduling)
If evaluation determines that an object is monotone or infeasible,
the routine returns immediately. In the case of a monotone object,
the branch object has already been called to modify the model.
Return value:
<ul>
<li> 0: A branching object has been installed
<li> -1: A monotone object was discovered
<li> -2: An infeasible object was discovered
</ul>
Branch state:
<ul>
<li> -1: start
<li> -1: A monotone object was discovered
<li> -2: An infeasible object was discovered
</ul>
*/
int chooseOsiBranch(CbcModel *model,
CbcNode *lastNode,
OsiBranchingInformation *usefulInfo,
int branchState);
/** Create a branching object for the node
The routine scans the object list of the model and selects a set of
unsatisfied objects as candidates for branching. It then solves a
series of problems and a CbcGeneral branch object is installed.
If evaluation determines that an object is infeasible,
the routine returns immediately.
Return value:
<ul>
<li> 0: A branching object has been installed
<li> -2: An infeasible object was discovered
</ul>
*/
int chooseClpBranch(CbcModel *model,
CbcNode *lastNode);
int analyze(CbcModel *model, double *results);
/// Decrement active cut counts
void decrementCuts(int change = 1);
/// Decrement all active cut counts in chain starting at parent
void decrementParentCuts(CbcModel *model, int change = 1);
/// Nulls out node info
void nullNodeInfo();
/** Initialize reference counts in attached CbcNodeInfo
This is a convenience routine, which will initialize the reference counts
in the attached CbcNodeInfo object based on the attached
OsiBranchingObject.
\sa CbcNodeInfo::initializeInfo(int).
*/
void initializeInfo();
/// Does next branch and updates state
int branch(OsiSolverInterface *solver);
/** Double checks in case node can change its mind!
Returns objective value
Can change objective etc */
double checkIsCutoff(double cutoff);
// Information to make basis and bounds
inline CbcNodeInfo *nodeInfo() const
{
return nodeInfo_;
}
// Objective value
inline double objectiveValue() const
{
return objectiveValue_;
}
inline void setObjectiveValue(double value)
{
objectiveValue_ = value;
}
/// Number of arms defined for the attached OsiBranchingObject.
inline int numberBranches() const
{
if (branch_)
return (branch_->numberBranches());
else
return (-1);
}
/* Active arm of the attached OsiBranchingObject.
In the simplest instance, coded -1 for the down arm of the branch, +1 for
the up arm. But see OsiBranchingObject::way()
Use nodeInfo--.numberBranchesLeft_ to see how active
*/
int way() const;
/// Depth in branch-and-cut search tree
inline int depth() const
{
return depth_;
}
/// Set depth in branch-and-cut search tree
inline void setDepth(int value)
{
depth_ = value;
}
/// Get the number of objects unsatisfied at this node.
inline int numberUnsatisfied() const
{
return numberUnsatisfied_;
}
/// Set the number of objects unsatisfied at this node.
inline void setNumberUnsatisfied(int value)
{
numberUnsatisfied_ = value;
}
/// Get sum of "infeasibilities" reported by each object
inline double sumInfeasibilities() const
{
return sumInfeasibilities_;
}
/// Set sum of "infeasibilities" reported by each object
inline void setSumInfeasibilities(double value)
{
sumInfeasibilities_ = value;
}
// Guessed objective value (for solution)
inline double guessedObjectiveValue() const
{
return guessedObjectiveValue_;
}
inline void setGuessedObjectiveValue(double value)
{
guessedObjectiveValue_ = value;
}
/// Branching object for this node
inline const OsiBranchingObject *branchingObject() const
{
return branch_;
}
/// Modifiable branching object for this node
inline OsiBranchingObject *modifiableBranchingObject() const
{
return branch_;
}
/// Set branching object for this node (takes ownership)
inline void setBranchingObject(OsiBranchingObject *branchingObject)
{
branch_ = branchingObject;
}
/// The node number
inline int nodeNumber() const
{
return nodeNumber_;
}
inline void setNodeNumber(int node)
{
nodeNumber_ = node;
}
/// Returns true if on tree
inline bool onTree() const
{
return (state_ & 1) != 0;
}
/// Sets true if on tree
inline void setOnTree(bool yesNo)
{
if (yesNo)
state_ |= 1;
else
state_ &= ~1;
}
/// Returns true if active
inline bool active() const
{
return (state_ & 2) != 0;
}
/// Sets true if active
inline void setActive(bool yesNo)
{
if (yesNo)
state_ |= 2;
else
state_ &= ~2;
}
/// Get state (really for debug)
inline int getState() const
{
return state_;
}
/// Set state (really for debug)
inline void setState(int value)
{
state_ = value;
}
/// Print
void print() const;
/// Debug
inline void checkInfo() const
{
assert(nodeInfo_->numberBranchesLeft() == branch_->numberBranchesLeft());
}
private:
// Data
/// Information to make basis and bounds
CbcNodeInfo *nodeInfo_;
/// Objective value
double objectiveValue_;
/// Guessed satisfied Objective value
double guessedObjectiveValue_;
/// Sum of "infeasibilities" reported by each object
double sumInfeasibilities_;
/// Branching object for this node
OsiBranchingObject *branch_;
/// Depth of the node in the search tree
int depth_;
/// The number of objects unsatisfied at this node.
int numberUnsatisfied_;
/// The node number
int nodeNumber_;
/** State
1 - on tree
2 - active
*/
int state_;
};
#endif
/* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
*/
| 29.708661 | 82 | 0.699443 | [
"object",
"vector",
"model"
] |
78f1bfe4f2ad08363a79dce22f9a10eb847b2076 | 3,146 | cpp | C++ | NFServer/NFGameServerPlugin/NFCPropertyConfigModule.cpp | sosan/NoahGameFrame | 38c54014c5c4620b784b2c1d2cab256f42bae186 | [
"Apache-2.0"
] | null | null | null | NFServer/NFGameServerPlugin/NFCPropertyConfigModule.cpp | sosan/NoahGameFrame | 38c54014c5c4620b784b2c1d2cab256f42bae186 | [
"Apache-2.0"
] | null | null | null | NFServer/NFGameServerPlugin/NFCPropertyConfigModule.cpp | sosan/NoahGameFrame | 38c54014c5c4620b784b2c1d2cab256f42bae186 | [
"Apache-2.0"
] | 1 | 2020-04-23T21:57:32.000Z | 2020-04-23T21:57:32.000Z | // -------------------------------------------------------------------------
// @FileName : NFCPropertyConfigModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-09-30
// @Module : NFCPropertyConfigModule
//
// -------------------------------------------------------------------------
#include "NFCPropertyConfigModule.h"
#include "NFComm/NFPluginModule/NFIPluginManager.h"
bool NFCPropertyConfigModule::Init()
{
return true;
}
bool NFCPropertyConfigModule::Shut()
{
return true;
}
bool NFCPropertyConfigModule::Execute()
{
return true;
}
bool NFCPropertyConfigModule::AfterInit()
{
m_pClassModule = pPluginManager->FindModule<NFIClassModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
Load();
return true;
}
int NFCPropertyConfigModule::CalculateBaseValue(const int nJob, const int nLevel, const std::string& strProperty)
{
NF_SHARE_PTR <NFMapEx<int, std::string> > xPropertyMap = mhtCoefficienData.GetElement(nJob);
if (xPropertyMap)
{
NF_SHARE_PTR<std::string> xRefPropertyIDName = xPropertyMap->GetElement(nLevel);
if (xRefPropertyIDName)
{
return m_pElementModule->GetPropertyInt(*xRefPropertyIDName, strProperty);
}
}
return 0;
}
void NFCPropertyConfigModule::Load()
{
NF_SHARE_PTR<NFIClass> xLogicClass = m_pClassModule->GetElement(NFrame::InitProperty::ThisName());
if (xLogicClass)
{
const std::vector<std::string>& strIdList = xLogicClass->GetIDList();
for (int i = 0; i < strIdList.size(); ++i)
{
const std::string& strId = strIdList[i];
NF_SHARE_PTR<NFIPropertyManager> pPropertyManager = m_pElementModule->GetPropertyManager(strId);
if (pPropertyManager)
{
int nJob = m_pElementModule->GetPropertyInt(strId, NFrame::InitProperty::Job());
int nLevel = m_pElementModule->GetPropertyInt(strId, NFrame::InitProperty::Level());
std::string strEffectData = m_pElementModule->GetPropertyString(strId, NFrame::InitProperty::EffectData());
NF_SHARE_PTR <NFMapEx<int, std::string> > xPropertyMap = mhtCoefficienData.GetElement(nJob);
if (!xPropertyMap)
{
xPropertyMap = NF_SHARE_PTR<NFMapEx<int, std::string>>(NF_NEW NFMapEx<int, std::string>());
mhtCoefficienData.AddElement(nJob, xPropertyMap);
NF_SHARE_PTR<std::string> xRefPropertyIDName = xPropertyMap->GetElement(nLevel);
if (!xRefPropertyIDName)
{
xRefPropertyIDName = NF_SHARE_PTR<std::string>(NF_NEW std::string(strEffectData));
xPropertyMap->AddElement(nLevel, xRefPropertyIDName);
}
}
}
}
}
}
bool NFCPropertyConfigModule::LegalLevel(const int nJob, const int nLevel)
{
NF_SHARE_PTR <NFMapEx<int, std::string> > xPropertyMap = mhtCoefficienData.GetElement(nJob);
if (xPropertyMap)
{
NF_SHARE_PTR<std::string> xRefPropertyIDName = xPropertyMap->GetElement(nLevel);
if (xRefPropertyIDName)
{
return true;
}
}
return false;
}
| 30.843137 | 124 | 0.636364 | [
"vector"
] |
78f44efecc5df0cf516bcbdedb30507b788e9c41 | 15,012 | inl | C++ | src/common/datatypes/PathOps.inl | tom-chensf/nebula-common | a1158b9430a66d5f3a28591282d83adca11b37f4 | [
"Apache-2.0"
] | null | null | null | src/common/datatypes/PathOps.inl | tom-chensf/nebula-common | a1158b9430a66d5f3a28591282d83adca11b37f4 | [
"Apache-2.0"
] | null | null | null | src/common/datatypes/PathOps.inl | tom-chensf/nebula-common | a1158b9430a66d5f3a28591282d83adca11b37f4 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* obj source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#ifndef COMMON_DATATYPES_PATHOPS_H_
#define COMMON_DATATYPES_PATHOPS_H_
#include "common/base/Base.h"
#include <thrift/lib/cpp2/GeneratedSerializationCodeHelper.h>
#include <thrift/lib/cpp2/gen/module_types_tcc.h>
#include <thrift/lib/cpp2/protocol/ProtocolReaderStructReadState.h>
#include "common/datatypes/Path.h"
namespace apache {
namespace thrift {
/**************************************
*
* Ops for class Step
*
*************************************/
namespace detail {
template<>
struct TccStructTraits<nebula::Step> {
static void translateFieldName(
MAYBE_UNUSED folly::StringPiece _fname,
MAYBE_UNUSED int16_t& fid,
MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) {
if (_fname == "dst") {
fid = 1;
_ftype = apache::thrift::protocol::T_STRUCT;
} else if (_fname == "type") {
fid = 2;
_ftype = apache::thrift::protocol::T_I32;
} else if (_fname == "name") {
fid = 3;
_ftype = apache::thrift::protocol::T_STRING;
} else if (_fname == "ranking") {
fid = 4;
_ftype = apache::thrift::protocol::T_I64;
} else if (_fname == "props") {
fid = 5;
_ftype = apache::thrift::protocol::T_MAP;
}
}
};
} // namespace detail
template<>
inline void Cpp2Ops<nebula::Step>::clear(nebula::Step* obj) {
return obj->clear();
}
template<>
inline constexpr protocol::TType Cpp2Ops<nebula::Step>::thriftType() {
return apache::thrift::protocol::T_STRUCT;
}
template<>
template<class Protocol>
uint32_t Cpp2Ops<nebula::Step>::write(Protocol* proto, nebula::Step const* obj) {
uint32_t xfer = 0;
xfer += proto->writeStructBegin("Step");
xfer += proto->writeFieldBegin("dst", apache::thrift::protocol::T_STRUCT, 1);
xfer += ::apache::thrift::Cpp2Ops< nebula::Vertex>::write(proto, &obj->dst);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldBegin("type", apache::thrift::protocol::T_I32, 2);
// NOTICE: The original id will be transformed to +1/-1, to indicate the edge direction.
auto type = obj->type;
if (type != 0) {
type > 0 ? type = 1 : type = -1;
}
xfer += detail::pm::protocol_methods<type_class::integral, nebula::EdgeType>
::write(*proto, type);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldBegin("name", apache::thrift::protocol::T_STRING, 3);
xfer += proto->writeBinary(obj->name);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldBegin("ranking", apache::thrift::protocol::T_I64, 4);
xfer += detail::pm::protocol_methods<type_class::integral, nebula::EdgeRanking>
::write(*proto, obj->ranking);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldBegin("props", apache::thrift::protocol::T_MAP, 5);
xfer += detail::pm::protocol_methods<
type_class::map<type_class::binary, type_class::structure>,
std::unordered_map<std::string, nebula::Value>
>::write(*proto, obj->props);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldStop();
xfer += proto->writeStructEnd();
return xfer;
}
template<>
template<class Protocol>
void Cpp2Ops<nebula::Step>::read(Protocol* proto, nebula::Step* obj) {
apache::thrift::detail::ProtocolReaderStructReadState<Protocol> readState;
readState.readStructBegin(proto);
using apache::thrift::protocol::TProtocolException;
if (UNLIKELY(!readState.advanceToNextField(proto, 0, 1, protocol::T_STRUCT))) {
goto _loop;
}
_readField_dst:
{
Cpp2Ops<nebula::Vertex>::read(proto, &obj->dst);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 1, 2, protocol::T_I32))) {
goto _loop;
}
_readField_type:
{
detail::pm::protocol_methods<type_class::integral, nebula::EdgeType>
::read(*proto, obj->type);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 2, 3, protocol::T_STRING))) {
goto _loop;
}
_readField_name:
{
proto->readBinary(obj->name);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 3, 4, protocol::T_I64))) {
goto _loop;
}
_readField_ranking:
{
detail::pm::protocol_methods<type_class::integral, nebula::EdgeRanking>
::read(*proto, obj->ranking);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 4, 5, protocol::T_MAP))) {
goto _loop;
}
_readField_props:
{
obj->props = std::unordered_map<std::string, nebula::Value>();
detail::pm::protocol_methods<
type_class::map<type_class::binary, type_class::structure>,
std::unordered_map<std::string, nebula::Value>
>::read(*proto, obj->props);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 5, 0, protocol::T_STOP))) {
goto _loop;
}
_end:
readState.readStructEnd(proto);
return;
_loop:
if (readState.fieldType == apache::thrift::protocol::T_STOP) {
goto _end;
}
if (proto->kUsesFieldNames()) {
detail::TccStructTraits<nebula::Step>::translateFieldName(readState.fieldName(),
readState.fieldId,
readState.fieldType);
}
switch (readState.fieldId) {
case 1:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_STRUCT)) {
goto _readField_dst;
} else {
goto _skip;
}
}
case 2:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_I32)) {
goto _readField_type;
} else {
goto _skip;
}
}
case 3:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_STRING)) {
goto _readField_name;
} else {
goto _skip;
}
}
case 4:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_I64)) {
goto _readField_ranking;
} else {
goto _skip;
}
}
case 5:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_MAP)) {
goto _readField_props;
} else {
goto _skip;
}
}
default:
{
_skip:
proto->skip(readState.fieldType);
readState.readFieldEnd(proto);
readState.readFieldBeginNoInline(proto);
goto _loop;
}
}
}
template<>
template<class Protocol>
uint32_t Cpp2Ops<nebula::Step>::serializedSize(Protocol const* proto,
nebula::Step const* obj) {
uint32_t xfer = 0;
xfer += proto->serializedStructSize("Step");
xfer += proto->serializedFieldSize("dst", apache::thrift::protocol::T_STRUCT, 1);
xfer += Cpp2Ops<nebula::Vertex>::serializedSize(proto, &obj->dst);
xfer += proto->serializedFieldSize("type", apache::thrift::protocol::T_I32, 2);
xfer += detail::pm::protocol_methods<type_class::integral, nebula::EdgeType>
::serializedSize<false>(*proto, obj->type);
xfer += proto->serializedFieldSize("name", apache::thrift::protocol::T_STRING, 3);
xfer += proto->serializedSizeBinary(obj->name);
xfer += proto->serializedFieldSize("ranking", apache::thrift::protocol::T_I64, 4);
xfer += detail::pm::protocol_methods<type_class::integral, nebula::EdgeRanking>
::serializedSize<false>(*proto, obj->ranking);
xfer += proto->serializedFieldSize("props", apache::thrift::protocol::T_MAP, 5);
xfer += detail::pm::protocol_methods<
type_class::map<type_class::binary, type_class::structure>,
std::unordered_map<std::string, nebula::Value>
>::serializedSize<false>(*proto, obj->props);
xfer += proto->serializedSizeStop();
return xfer;
}
template<>
template<class Protocol>
uint32_t Cpp2Ops<nebula::Step>::serializedSizeZC(Protocol const* proto,
nebula::Step const* obj) {
uint32_t xfer = 0;
xfer += proto->serializedStructSize("Step");
xfer += proto->serializedFieldSize("dst", apache::thrift::protocol::T_STRUCT, 1);
xfer += Cpp2Ops<nebula::Vertex>::serializedSizeZC(proto, &obj->dst);
xfer += proto->serializedFieldSize("type", apache::thrift::protocol::T_I32, 2);
xfer += detail::pm::protocol_methods<type_class::integral, nebula::EdgeType>
::serializedSize<false>(*proto, obj->type);
xfer += proto->serializedFieldSize("name", apache::thrift::protocol::T_STRING, 3);
xfer += proto->serializedSizeZCBinary(obj->name);
xfer += proto->serializedFieldSize("ranking", apache::thrift::protocol::T_I64, 4);
xfer += detail::pm::protocol_methods<type_class::integral, nebula::EdgeRanking>
::serializedSize<false>(*proto, obj->ranking);
xfer += proto->serializedFieldSize("props", apache::thrift::protocol::T_MAP, 5);
xfer += detail::pm::protocol_methods<
type_class::map<type_class::binary, type_class::structure>,
std::unordered_map<std::string, nebula::Value>
>::serializedSize<false>(*proto, obj->props);
xfer += proto->serializedSizeStop();
return xfer;
}
/**************************************
*
* Ops for class Path
*
*************************************/
namespace detail {
template<>
struct TccStructTraits<nebula::Path> {
static void translateFieldName(
MAYBE_UNUSED folly::StringPiece _fname,
MAYBE_UNUSED int16_t& fid,
MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) {
if (_fname == "src") {
fid = 1;
_ftype = apache::thrift::protocol::T_STRUCT;
} else if (_fname == "steps") {
fid = 2;
_ftype = apache::thrift::protocol::T_LIST;
}
}
};
} // namespace detail
template<>
inline void Cpp2Ops<nebula::Path>::clear(nebula::Path* obj) {
return obj->clear();
}
template<>
inline constexpr protocol::TType Cpp2Ops<nebula::Path>::thriftType() {
return apache::thrift::protocol::T_STRUCT;
}
template<>
template<class Protocol>
uint32_t Cpp2Ops<nebula::Path>::write(Protocol* proto, nebula::Path const* obj) {
uint32_t xfer = 0;
xfer += proto->writeStructBegin("Path");
xfer += proto->writeFieldBegin("src", apache::thrift::protocol::T_STRUCT, 1);
xfer += Cpp2Ops< nebula::Vertex>::write(proto, &obj->src);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldBegin("steps", apache::thrift::protocol::T_LIST, 2);
xfer += detail::pm::protocol_methods<
type_class::list<type_class::structure>,
std::vector<nebula::Step>
>::write(*proto, obj->steps);
xfer += proto->writeFieldEnd();
xfer += proto->writeFieldStop();
xfer += proto->writeStructEnd();
return xfer;
}
template<>
template<class Protocol>
void Cpp2Ops<nebula::Path>::read(Protocol* proto, nebula::Path* obj) {
detail::ProtocolReaderStructReadState<Protocol> readState;
readState.readStructBegin(proto);
using apache::thrift::protocol::TProtocolException;
if (UNLIKELY(!readState.advanceToNextField(proto, 0, 1, protocol::T_STRUCT))) {
goto _loop;
}
_readField_src:
{
Cpp2Ops<nebula::Vertex>::read(proto, &obj->src);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 1, 2, protocol::T_LIST))) {
goto _loop;
}
_readField_steps:
{
obj->steps = std::vector<nebula::Step>();
detail::pm::protocol_methods<
type_class::list<type_class::structure>,
std::vector<nebula::Step>
>::read(*proto, obj->steps);
}
if (UNLIKELY(!readState.advanceToNextField(proto, 2, 0, protocol::T_STOP))) {
goto _loop;
}
_end:
readState.readStructEnd(proto);
return;
_loop:
if (readState.fieldType == apache::thrift::protocol::T_STOP) {
goto _end;
}
if (proto->kUsesFieldNames()) {
detail::TccStructTraits<nebula::Path>::translateFieldName(readState.fieldName(),
readState.fieldId,
readState.fieldType);
}
switch (readState.fieldId) {
case 1:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_STRUCT)) {
goto _readField_src;
} else {
goto _skip;
}
}
case 2:
{
if (LIKELY(readState.fieldType == apache::thrift::protocol::T_LIST)) {
goto _readField_steps;
} else {
goto _skip;
}
}
default:
{
_skip:
proto->skip(readState.fieldType);
readState.readFieldEnd(proto);
readState.readFieldBeginNoInline(proto);
goto _loop;
}
}
}
template<>
template<class Protocol>
uint32_t Cpp2Ops<nebula::Path>::serializedSize(Protocol const* proto,
nebula::Path const* obj) {
uint32_t xfer = 0;
xfer += proto->serializedStructSize("Path");
xfer += proto->serializedFieldSize("src", apache::thrift::protocol::T_STRUCT, 1);
xfer += Cpp2Ops<nebula::Vertex>::serializedSize(proto, &obj->src);
xfer += proto->serializedFieldSize("steps", apache::thrift::protocol::T_LIST, 2);
xfer += detail::pm::protocol_methods<
type_class::list<type_class::structure>,
std::vector<nebula::Step>
>::serializedSize<false>(*proto, obj->steps);
xfer += proto->serializedSizeStop();
return xfer;
}
template<>
template<class Protocol>
uint32_t Cpp2Ops<nebula::Path>::serializedSizeZC(Protocol const* proto,
nebula::Path const* obj) {
uint32_t xfer = 0;
xfer += proto->serializedStructSize("Path");
xfer += proto->serializedFieldSize("src", apache::thrift::protocol::T_STRUCT, 1);
xfer += Cpp2Ops<nebula::Vertex>::serializedSizeZC(proto, &obj->src);
xfer += proto->serializedFieldSize("steps", apache::thrift::protocol::T_LIST, 2);
xfer += detail::pm::protocol_methods<
type_class::list<type_class::structure>,
std::vector<nebula::Step>
>::serializedSize<false>(*proto, obj->steps);
xfer += proto->serializedSizeStop();
return xfer;
}
} // namespace thrift
} // namespace apache
#endif // COMMON_DATATYPES_PATHOPS_H_
| 30.512195 | 92 | 0.591727 | [
"vector"
] |
78f87f1a495d4da6fa5422cfc9b85a8bedc49645 | 9,076 | cpp | C++ | src/mlpack/methods/local_coordinate_coding/local_coordinate_coding_main.cpp | 17minutes/mlpack | 8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-09-22T18:12:40.000Z | 2021-11-17T10:39:58.000Z | src/mlpack/methods/local_coordinate_coding/local_coordinate_coding_main.cpp | kosmaz/Mlpack | 62100ddca45880a57e7abb0432df72d285e5728b | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/local_coordinate_coding/local_coordinate_coding_main.cpp | kosmaz/Mlpack | 62100ddca45880a57e7abb0432df72d285e5728b | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file lcc_main.cpp
* @author Nishant Mehta
*
* Executable for Local Coordinate Coding.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/cli.hpp>
#include "lcc.hpp"
using namespace arma;
using namespace std;
using namespace mlpack;
using namespace mlpack::math;
using namespace mlpack::lcc;
using namespace mlpack::sparse_coding; // For NothingInitializer.
PROGRAM_INFO("Local Coordinate Coding",
"An implementation of Local Coordinate Coding (LCC), which "
"codes data that approximately lives on a manifold using a variation of l1-"
"norm regularized sparse coding. Given a dense data matrix X with n points"
" and d dimensions, LCC seeks to find a dense dictionary matrix D with k "
"atoms in d dimensions, and a coding matrix Z with n points in k "
"dimensions. Because of the regularization method used, the atoms in D "
"should lie close to the manifold on which the data points lie."
"\n\n"
"The original data matrix X can then be reconstructed as D * Z. Therefore,"
" this program finds a representation of each point in X as a sparse linear"
" combination of atoms in the dictionary D."
"\n\n"
"The coding is found with an algorithm which alternates between a "
"dictionary step, which updates the dictionary D, and a coding step, which "
"updates the coding matrix Z."
"\n\n"
"To run this program, the input matrix X must be specified (with -i), along"
" with the number of atoms in the dictionary (-k). An initial dictionary "
"may also be specified with the --initial_dictionary option. The l1-norm "
"regularization parameter is specified with -l. For example, to run LCC on"
" the dataset in data.csv using 200 atoms and an l1-regularization "
"parameter of 0.1, saving the dictionary into dict.csv and the codes into "
"codes.csv, use "
"\n\n"
"$ local_coordinate_coding -i data.csv -k 200 -l 0.1 -d dict.csv -c "
"codes.csv"
"\n\n"
"The maximum number of iterations may be specified with the -n option. "
"Optionally, the input data matrix X can be normalized before coding with "
"the -N option.");
// Training parameters.
PARAM_MATRIX_IN("training", "Matrix of training data (X).", "t");
PARAM_INT_IN("atoms", "Number of atoms in the dictionary.", "k", 0);
PARAM_DOUBLE_IN("lambda", "Weighted l1-norm regularization parameter.", "l",
0.0);
PARAM_INT_IN("max_iterations", "Maximum number of iterations for LCC (0 "
"indicates no limit).", "n", 0);
PARAM_MATRIX_IN("initial_dictionary", "Optional initial dictionary.", "i");
PARAM_FLAG("normalize", "If set, the input data matrix will be normalized "
"before coding.", "N");
PARAM_DOUBLE_IN("tolerance", "Tolerance for objective function.", "o", 0.01);
// Load/save a model.
PARAM_MODEL_IN(LocalCoordinateCoding, "input_model", "Input LCC model.", "m");
PARAM_MODEL_OUT(LocalCoordinateCoding, "output_model", "Output for trained LCC "
"model.", "M");
// Test on another dataset.
PARAM_MATRIX_IN("test", "Test points to encode.", "T");
PARAM_MATRIX_OUT("dictionary", "Output dictionary matrix.", "d");
PARAM_MATRIX_OUT("codes", "Output codes matrix.", "c");
PARAM_INT_IN("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
int main(int argc, char* argv[])
{
CLI::ParseCommandLine(argc, argv);
if (CLI::GetParam<int>("seed") != 0)
RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
RandomSeed((size_t) std::time(NULL));
// Check for parameter validity.
if (CLI::HasParam("input_model") && CLI::HasParam("initial_dictionary"))
Log::Fatal << "Cannot specify both --input_model_file (-m) and "
<< "--initial_dictionary_file (-i)!" << endl;
if (CLI::HasParam("training") && !CLI::HasParam("atoms"))
Log::Fatal << "If --training_file is specified, the number of atoms in the "
<< "dictionary must be specified with --atoms (-k)!" << endl;
if (!CLI::HasParam("training") && !CLI::HasParam("input_model"))
Log::Fatal << "One of --training_file (-t) or --input_model_file (-m) must "
<< "be specified!" << endl;
if (!CLI::HasParam("codes") && !CLI::HasParam("dictionary") &&
!CLI::HasParam("output_model"))
Log::Warn << "Neither --codes_file (-c), --dictionary_file (-d), nor "
<< "--output_model_file (-M) are specified; no output will be saved."
<< endl;
if (CLI::HasParam("codes") && !CLI::HasParam("test"))
Log::Fatal << "--codes_file (-c) is specified, but no test matrix ("
<< "specified with --test_file or -T) is given to encode!" << endl;
if (!CLI::HasParam("training"))
{
if (CLI::HasParam("atoms"))
Log::Warn << "--atoms (-k) ignored because --training_file (-t) is not "
<< "specified." << endl;
if (CLI::HasParam("lambda"))
Log::Warn << "--lambda (-l) ignored because --training_file (-t) is not "
<< "specified." << endl;
if (CLI::HasParam("initial_dictionary"))
Log::Warn << "--initial_dictionary_file (-i) ignored because "
<< "--training_file (-t) is not specified." << endl;
if (CLI::HasParam("max_iterations"))
Log::Warn << "--max_iterations (-n) ignored because --training_file (-t) "
<< "is not specified." << endl;
if (CLI::HasParam("normalize"))
Log::Warn << "--normalize (-N) ignored because --training_file (-t) is "
<< "not specified." << endl;
if (CLI::HasParam("tolerance"))
Log::Warn << "--tolerance (-o) ignored because --training_file (-t) is "
<< "not specified." << endl;
}
// Do we have an existing model?
LocalCoordinateCoding lcc(0, 0.0);
if (CLI::HasParam("input_model"))
lcc = std::move(CLI::GetParam<LocalCoordinateCoding>("input_model"));
if (CLI::HasParam("training"))
{
mat matX = std::move(CLI::GetParam<mat>("training"));
// Normalize each point if the user asked for it.
if (CLI::HasParam("normalize"))
{
Log::Info << "Normalizing data before coding..." << endl;
for (size_t i = 0; i < matX.n_cols; ++i)
matX.col(i) /= norm(matX.col(i), 2);
}
lcc.Lambda() = CLI::GetParam<double>("lambda");
lcc.Atoms() = (size_t) CLI::GetParam<int>("atoms");
lcc.MaxIterations() = (size_t) CLI::GetParam<int>("max_iterations");
lcc.Tolerance() = CLI::GetParam<double>("tolerance");
// Inform the user if we are overwriting their model.
if (CLI::HasParam("input_model"))
{
Log::Info << "Using dictionary from existing model in '"
<< CLI::GetUnmappedParam<string>("input_model") << "' as initial "
<< "dictionary for training." << endl;
lcc.Train<NothingInitializer>(matX);
}
else if (CLI::HasParam("initial_dictionary"))
{
// Load initial dictionary directly into LCC object.
lcc.Dictionary() = std::move(CLI::GetParam<mat>("initial_dictionary"));
// Validate the size of the initial dictionary.
if (lcc.Dictionary().n_cols != lcc.Atoms())
{
Log::Fatal << "The initial dictionary has " << lcc.Dictionary().n_cols
<< " atoms, but the number of atoms was specified to be "
<< lcc.Atoms() << "!" << endl;
}
if (lcc.Dictionary().n_rows != matX.n_rows)
{
Log::Fatal << "The initial dictionary has " << lcc.Dictionary().n_rows
<< " dimensions, but the data has " << matX.n_rows << " dimensions!"
<< endl;
}
// Train the model.
lcc.Train<NothingInitializer>(matX);
}
else
{
// Run with the default initialization.
lcc.Train(matX);
}
}
// Now, do we have any matrix to encode?
if (CLI::HasParam("test"))
{
mat matY = std::move(CLI::GetParam<mat>("test"));
if (matY.n_rows != lcc.Dictionary().n_rows)
Log::Fatal << "Model was trained with a dimensionality of "
<< lcc.Dictionary().n_rows << ", but data in test file "
<< CLI::GetUnmappedParam<mat>("test") << " has a dimensionality of "
<< matY.n_rows << "!" << endl;
// Normalize each point if the user asked for it.
if (CLI::HasParam("normalize"))
{
Log::Info << "Normalizing test data before coding..." << endl;
for (size_t i = 0; i < matY.n_cols; ++i)
matY.col(i) /= norm(matY.col(i), 2);
}
mat codes;
lcc.Encode(matY, codes);
if (CLI::HasParam("codes"))
CLI::GetParam<mat>("codes") = std::move(codes);
}
// Did the user want to save the dictionary?
if (CLI::HasParam("dictionary"))
CLI::GetParam<mat>("dictionary") = std::move(lcc.Dictionary());
// Did the user want to save the model?
if (CLI::HasParam("output_model"))
CLI::GetParam<LocalCoordinateCoding>("output_model") = std::move(lcc);
CLI::Destroy();
}
| 39.633188 | 80 | 0.63431 | [
"object",
"model"
] |
78fc06b4a66012e7d02112e32572306a3e900370 | 1,720 | cpp | C++ | coj.uci.cu/RubTask.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 6 | 2016-09-10T03:16:34.000Z | 2020-04-07T14:45:32.000Z | coj.uci.cu/RubTask.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | null | null | null | coj.uci.cu/RubTask.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 2 | 2018-08-11T20:55:35.000Z | 2020-01-15T23:23:11.000Z | /*
By: facug91
From: http://coj.uci.cu/24h/problem.xhtml?pid=2191
Name: Rub Task
Date: 12/03/2015
*/
#include <bits/stdc++.h>
#define EPS 1e-9
#define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000007ll
//#define MAXN 1000005
using namespace std;
typedef long long ll;
typedef pair<int, int> ii; typedef pair<int, ii> iii;
typedef vector<int> vi; typedef vector<ii> vii;
int n, m, mat[105][105], dis[10500];
bool vis[10500];
vii adj[10500];
void make_graph () {
int i, j, d, dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}, x, y;
for (i=0; i<n*m; i++) adj[i].clear();
for (i=0; i<n; i++) {
for (j=0; j<m; j++) {
for (d=0; d<4; d++) {
x = i + dx[d];
y = j + dy[d];
if (x >= 0 && x < n && y >= 0 && y < m) adj[i*m+j].push_back(ii(x*m+y, mat[x][y]));
}
}
}
}
void dijkstra () {
ii act; int u, v, i;
for (i=0; i<n*m; i++) dis[i] = INF, vis[i] = false;
dis[0] = 0;
priority_queue<ii, vii, greater<ii> > q; q.push(ii(0, 0));
while (q.size()) {
act = q.top(); q.pop();
u = act.second;
if (vis[u]) continue;
if (u == n*m-1) return;
vis[u] = true;
for (i=0; i<adj[u].size(); i++) {
v = adj[u][i].first;
if (dis[v] > dis[u]+adj[u][i].second) {
dis[v] = dis[u]+adj[u][i].second;
q.push(ii(dis[v], v));
}
}
}
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int i, j;
cin>>n>>m; m+=2;
for (i=0; i<n; i++) mat[i][0] = mat[i][m-1] = 0;
for (i=0; i<n; i++) for (j=1; j<m-1; j++) cin>>mat[i][j];
make_graph();
dijkstra();
cout<<dis[n*m-1]<<"\n";
return 0;
}
| 23.243243 | 88 | 0.486628 | [
"vector"
] |
78fecd6f115dc1793ee50047e6e1299a1b227b45 | 1,671 | hpp | C++ | include/game_states.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | 5 | 2021-01-02T19:06:37.000Z | 2022-03-11T23:56:03.000Z | include/game_states.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | null | null | null | include/game_states.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <map>
#include <memory>
#include <stdexcept>
#include "key_defines.hpp"
#include "tetromino.hpp"
namespace nestris_x86 {
template <int W = 10, int H = 20>
// clang-format off
struct GameState {
GameState()
: grid{},
das_counter{},
gravity_counter{},
entry_delay_counter{},
spawn_new_tetromino{},
level{},
lines{},
lines_until_next_level{},
active_tetromino{},
next_tetromino{},
score{},
high_score{},
topped_out{},
paused{} {}
// clang-format on
using Grid = std::array<std::array<int, H>, W>;
Grid grid;
int gravity_counter;
int das_counter;
int entry_delay_counter;
bool spawn_new_tetromino;
int level;
int lines;
int lines_until_next_level;
TetrominoState active_tetromino;
Tetromino next_tetromino;
int score;
int high_score;
bool topped_out;
bool paused;
bool press_down_lock;
int press_down_counter;
int viz_wall_charge_frame_count;
};
inline bool entryDelay(const GameState<>& state) {
return state.entry_delay_counter > 0;
}
struct LineClearAnimationInfo {
std::vector<int> rows;
int animation_frame{};
};
enum class StatisticsMode { Classic, TreyVision };
inline StatisticsMode statisticsModeFromString(const std::string& statistics_mode) {
if (statistics_mode == "NES") {
return StatisticsMode::Classic;
} else if (statistics_mode == "TREY V") {
return StatisticsMode::TreyVision;
} else {
throw std::runtime_error("Invalid statistics mode `" + statistics_mode + "`.");
}
return StatisticsMode::Classic;
}
} // namespace nestris_x86
| 21.986842 | 84 | 0.678037 | [
"vector"
] |
60003f4cf1d83639ac002d3649f0792f9259c4a7 | 367 | cpp | C++ | find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | 1 | 2022-02-14T07:57:07.000Z | 2022-02-14T07:57:07.000Z | find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | null | null | null | find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
unordered_map<int, int> mp;
for(int i=0; i<nums.size(); i++)
{
mp[nums[i]]++;
}
vector<int> ans;
for(auto m : mp)
{
if(m.second==2)
ans.push_back(m.first);
}
return ans;
}
}; | 21.588235 | 51 | 0.435967 | [
"vector"
] |
6000bc4406c5d5248fd6da9b9730521fbdb4dede | 2,679 | cc | C++ | test/3d/mpi/test_poisson.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 9 | 2018-03-07T19:15:27.000Z | 2019-02-22T20:10:23.000Z | test/3d/mpi/test_poisson.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 5 | 2018-11-13T19:59:46.000Z | 2020-04-09T19:31:25.000Z | test/3d/mpi/test_poisson.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 2 | 2018-07-20T01:06:48.000Z | 2019-11-25T12:15:16.000Z | #include <gtest/gtest.h>
#include <mpi.h>
#include <cedar/types.h>
#include <cedar/3d/mpi/grid_func.h>
#include <cedar/3d/util/topo.h>
#include <cedar/3d/mpi/gallery.h>
#include <cedar/3d/mpi/solver.h>
static void set_problem(cedar::cdr3::mpi::grid_func & b)
{
using namespace cedar;
using namespace cedar::cdr3;
const double pi = M_PI;
auto rhs = [pi](real_t x, real_t y, real_t z) {
return 12*(pi*pi)*sin(2*pi*x)*sin(2*pi*y)*sin(2*pi*z);
};
auto & topo = b.grid();
b.set(0);
real_t igs = topo.is(0);
real_t jgs = topo.is(1);
real_t kgs = topo.is(2);
real_t hx = 1.0 / (topo.nglobal(0) - 1);
real_t hy = 1.0 / (topo.nglobal(1) - 1);
real_t hz = 1.0 / (topo.nglobal(2) - 1);
real_t h2 = hx*hy*hz;
real_t nlx = topo.nlocal(0) - 2;
real_t nly = topo.nlocal(1) - 2;
real_t nlz = topo.nlocal(2) - 2;
real_t i1 = nlx + 1;
real_t j1 = nly + 1;
real_t k1 = nlz + 1;
for (auto k : range<len_t>(1, k1)) {
for (auto j : range<len_t>(1, j1)) {
for (auto i : range<len_t>(1, i1)) {
len_t is = igs + i;
len_t js = jgs + j;
len_t ks = kgs + k;
real_t x = (is-1)*hx;
real_t y = (js-1)*hy;
real_t z = (ks-1)*hz;
b(i,j,k) = rhs(x, y, z) * h2;
}
}
}
}
static void set_solution(cedar::cdr3::mpi::grid_func & q)
{
using namespace cedar;
const double pi = M_PI;
auto sol = [pi](real_t x, real_t y, real_t z) {
return sin(2*pi*x)*sin(2*pi*y)*sin(2*pi*z);
};
auto & topo = q.grid();
real_t igs = topo.is(0);
real_t jgs = topo.is(1);
real_t kgs = topo.is(2);
real_t hx = 1.0 / (topo.nglobal(0) - 1);
real_t hy = 1.0 / (topo.nglobal(1) - 1);
real_t hz = 1.0 / (topo.nglobal(2) - 1);
for (auto k : q.range(2)) {
for (auto j : q.range(1)) {
for (auto i : q.range(0)) {
len_t is = igs + i;
len_t js = jgs + j;
len_t ks = kgs + k;
real_t x = (is-1)*hx;
real_t y = (js-1)*hy;
real_t z = (ks-1)*hz;
q(i,j,k) = sol(x,y,z);
}
}
}
}
TEST(MPIPoisson3, Isotropic) {
using namespace cedar;
using namespace cedar::cdr3;
auto nx = 200;
auto ny = nx;
auto nz = nx;
auto grid = util::create_topo_global(MPI_COMM_WORLD, nx, ny, nz);
auto so = mpi::gallery::poisson(grid);
mpi::grid_func b(grid);
set_problem(b);
auto conf = std::make_shared<config>("");
log::init(*conf);
conf->set("solver.relaxation", "point");
conf->set("solver.cg-solver", "LU");
mpi::solver<seven_pt> bmg(so, conf);
auto sol = bmg.solve(b);
ASSERT_LT(std::abs(bmg.levels.template get<seven_pt>(0).res.lp_norm<2>()),
1e-8);
mpi::grid_func exact_sol(grid);
set_solution(exact_sol);
auto diff = exact_sol - sol;
ASSERT_LT(std::abs(diff.inf_norm()),
1e-4);
}
| 19.844444 | 75 | 0.588652 | [
"3d"
] |
601451bc26ee8efd83abf5eeccecdae1e9ef2d7a | 15,395 | cpp | C++ | test/unit/module/bessel/cyl_bessel_jn.cpp | HadrienG2/eve | 3afdcfb524f88c0b88df9b54e25bbb9b33f518ec | [
"MIT"
] | null | null | null | test/unit/module/bessel/cyl_bessel_jn.cpp | HadrienG2/eve | 3afdcfb524f88c0b88df9b54e25bbb9b33f518ec | [
"MIT"
] | null | null | null | test/unit/module/bessel/cyl_bessel_jn.cpp | HadrienG2/eve | 3afdcfb524f88c0b88df9b54e25bbb9b33f518ec | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/module/bessel.hpp>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/bessel_prime.hpp>
//==================================================================================================
//== Types tests
//==================================================================================================
EVE_TEST_TYPES( "Check return types of cyl_bessel_jn"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
using v_t = eve::element_type_t<T>;
using i_t = eve::as_integer_t<v_t>;
using I_t = eve::wide<i_t, eve::cardinal_t<T>>;
TTS_EXPR_IS( eve::cyl_bessel_jn(T(), T()) , T);
TTS_EXPR_IS( eve::cyl_bessel_jn(v_t(),v_t()), v_t);
TTS_EXPR_IS( eve::cyl_bessel_jn(i_t(),T()), T);
TTS_EXPR_IS( eve::cyl_bessel_jn(I_t(),T()), T);
TTS_EXPR_IS( eve::cyl_bessel_jn(i_t(),v_t()), v_t);
TTS_EXPR_IS( eve::cyl_bessel_jn(I_t(),v_t()), T);
};
//==================================================================================================
//== integral orders
//==================================================================================================
EVE_TEST( "Check behavior of cyl_bessel_jn on wide with integral order"
, eve::test::simd::ieee_reals
, eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 20000.0))
)
<typename T>(T n, T a0)
{
using v_t = eve::element_type_t<T>;
auto eve__cyl_bessel_jn = [](auto n, auto x) { return eve::cyl_bessel_jn(n, x); };
auto std__cyl_bessel_jn = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_j(double(n), double(x)); };
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(0, eve::minf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, eve::inf(eve::as<v_t>())), v_t(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);
}
//scalar large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, v_t(1500)), std__cyl_bessel_jn(3, v_t(1500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, v_t(500)), std__cyl_bessel_jn(2, v_t(500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(-3, v_t(1500)), std__cyl_bessel_jn(-3, v_t(1500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(-2, v_t(500)), std__cyl_bessel_jn(-2, v_t(500)), 2.0);
//scalar forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, v_t(10)), std__cyl_bessel_jn(2, v_t(10)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, v_t(5)), std__cyl_bessel_jn(3, v_t(5)) , 2.0);
//scalar serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, v_t(0.1)), std__cyl_bessel_jn(2, v_t(0.1)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, v_t(0.2)), std__cyl_bessel_jn(3, v_t(0.2)) , 2.0);
//scalar besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, v_t(8)), std__cyl_bessel_jn(10, v_t(8)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, v_t(8)), std__cyl_bessel_jn(10, v_t(8)) , 2.0);
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(0, eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, eve::inf(eve::as<T>())), T(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
}
//scalar large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, T(1500)), T(std__cyl_bessel_jn(3, v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, T(500)), T(std__cyl_bessel_jn(2, v_t(500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(-3, T(1500)), T(std__cyl_bessel_jn(-3, v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(-2, T(500)), T(std__cyl_bessel_jn(-2, v_t(500))), 2.0);
//scalar forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, T(10)), T(std__cyl_bessel_jn(2, v_t(10))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, T(5)), T(std__cyl_bessel_jn(3, v_t(5))) , 2.0);
//scalar serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, T(0.1)), T(std__cyl_bessel_jn(2, v_t(0.1))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, T(0.2)), T(std__cyl_bessel_jn(3, v_t(0.2))) , 2.0);
//scalar besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, T(8)), T(std__cyl_bessel_jn(10, v_t(8))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, T(8)), T(std__cyl_bessel_jn(10, v_t(8))) , 2.0);
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(0), eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), eve::inf(eve::as<T>())), T(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
}
// large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), T(1500)), T(std__cyl_bessel_jn(3, v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), T(500)), T(std__cyl_bessel_jn(2, v_t(500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3), T(1500)), T(std__cyl_bessel_jn(-3, v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2), T(500)), T(std__cyl_bessel_jn(-2, v_t(500))), 2.0);
// forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), T(10)), T(std__cyl_bessel_jn(2, v_t(10))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), T(5)), T(std__cyl_bessel_jn(3, v_t(5))) , 2.0);
// serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), T(0.1)), T(std__cyl_bessel_jn(2, v_t(0.1))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), T(0.2)), T(std__cyl_bessel_jn(3, v_t(0.2))) , 2.0);
// besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10), T(8)), T(std__cyl_bessel_jn(10, v_t(8))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10), T(8)), T(std__cyl_bessel_jn(10, v_t(8))) , 2.0);
using i_t = eve::as_integer_t<v_t>;
using I_t = eve::wide<i_t, eve::cardinal_t<T>>;
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(0), eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), eve::inf(eve::as<T>())), T(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
}
// large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), T(1500)), T(std__cyl_bessel_jn(3, v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), T(500)), T(std__cyl_bessel_jn(2, v_t(500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(-3), T(1500)), T(std__cyl_bessel_jn(-3, v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(-2), T(500)), T(std__cyl_bessel_jn(-2, v_t(500))), 2.0);
// forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), T(10)), T(std__cyl_bessel_jn(2, v_t(10))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), T(5)), T(std__cyl_bessel_jn(3, v_t(5))) , 2.0);
// serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), T(0.1)), T(std__cyl_bessel_jn(2, v_t(0.1))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), T(0.2)), T(std__cyl_bessel_jn(3, v_t(0.2))) , 2.0);
// besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(10), T(8)), T(std__cyl_bessel_jn(10, v_t(8))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(10), T(8)), T(std__cyl_bessel_jn(10, v_t(8))) , 2.0);
TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(n, a0), map(std__cyl_bessel_jn, n, a0) , 0.0015);
TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(n, -a0), map(std__cyl_bessel_jn, n, -a0) , 0.0015);
TTS_RELATIVE_EQUAL(map(eve__cyl_bessel_jn, n, -a0), map(std__cyl_bessel_jn, n, -a0) , 0.0015);
};
//==================================================================================================
//== non integral orders
//==================================================================================================
EVE_TEST( "Check behavior of cyl_bessel_jn on wide with non integral order"
, eve::test::simd::ieee_reals
, eve::test::generate(eve::test::randoms(0.0, 10.0)
, eve::test::randoms(0.0, 2000.0))
)
<typename T>(T n, T a0)
{
using v_t = eve::element_type_t<T>;
auto eve__cyl_bessel_jn = [](auto n, auto x) { return eve::cyl_bessel_jn(n, x); };
auto std__cyl_bessel_jn = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_j(double(n), double(x)); };
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(0.5), eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), eve::inf(eve::as<v_t>())), v_t(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);
}
//scalar large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), v_t(1500)), std__cyl_bessel_jn(v_t(3.5), v_t(1500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), v_t( 500)), std__cyl_bessel_jn(v_t(2.5), v_t( 500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(1500)), std__cyl_bessel_jn(v_t(-3.5), v_t(1500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t( 500)), std__cyl_bessel_jn(v_t(-2.5), v_t(500)), 2.0);
//scalar forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), v_t(10)), std__cyl_bessel_jn(v_t(2.5), v_t(10)) , 5.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), v_t(5)), std__cyl_bessel_jn(v_t(3.5), v_t(5)) , 2.0);
//scalar serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), v_t(0.1)), std__cyl_bessel_jn(v_t(2.5), v_t(0.1)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), v_t(0.2)), std__cyl_bessel_jn(v_t(3.5), v_t(0.2)) , 2.0);
//scalar besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), v_t(8)), std__cyl_bessel_jn(v_t(10.5), v_t(8)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), v_t(8)), std__cyl_bessel_jn(v_t(10.5), v_t(8)) , 2.0);
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), eve::inf(eve::as<T>())), T(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
}
//scalar large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), T(1500)), T(std__cyl_bessel_jn(v_t(3.5), v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), T(500)), T(std__cyl_bessel_jn(v_t(2.5), v_t(500))), 2.0);
//scalar forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), T(10)), T(std__cyl_bessel_jn(v_t(2.5), v_t(10))) , 5.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), T(5)), T(std__cyl_bessel_jn(v_t(3.5), v_t(5))) , 2.0);
//scalar serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), T(0.1)), T(std__cyl_bessel_jn(v_t(2.5), v_t(0.1))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), T(0.2)), T(std__cyl_bessel_jn(v_t(3.5), v_t(0.2))) , 2.5);
//scalar besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), T(8)), T(std__cyl_bessel_jn(v_t(10.5), v_t(8))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), T(8)), T(std__cyl_bessel_jn(v_t(10.5), v_t(8))) , 2.0);
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), eve::inf(eve::as<T>())), T(0), 0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
}
// large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), T(1500)), T(std__cyl_bessel_jn(v_t(3.5), v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), T(500)), T(std__cyl_bessel_jn(v_t(2.5), v_t(500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(1500)), T(std__cyl_bessel_jn(v_t(-3.5), v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(500)), T(std__cyl_bessel_jn(v_t(-2.5), v_t( 500))), 2.0);
// forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), T(10)), T(std__cyl_bessel_jn(v_t(2.5), v_t(10))) , 5.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), T(5)), T(std__cyl_bessel_jn(v_t(3.5), v_t(5))) , 2.0);
// serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), T(0.1)), T(std__cyl_bessel_jn(v_t(2.5), v_t(0.1))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), T(0.2)), T(std__cyl_bessel_jn(v_t(3.5), v_t(0.2))) , 2.5);
// besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10.5), T(8)), T(std__cyl_bessel_jn(v_t(10.5), v_t(8))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10.5), T(8)), T(std__cyl_bessel_jn(v_t(10.5), v_t(8))) , 2.0);
TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(n, a0), map(std__cyl_bessel_jn, n, a0) , 0.001);
//scalar large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(1500)), std__cyl_bessel_jn(v_t(-3.5), v_t(1500)), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t(500)), std__cyl_bessel_jn(v_t(-2.5), v_t(500)), 2.0);
//scalar forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t(10)), std__cyl_bessel_jn(v_t(-2.5), v_t(10)) , 6.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(5)), std__cyl_bessel_jn(v_t(-3.5), v_t(5)) , 35.0);
//scalar serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t(0.1)), std__cyl_bessel_jn(v_t(-2.5), v_t(0.1)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(0.2)), std__cyl_bessel_jn(v_t(-3.5), v_t(0.2)) , 2.0);
//scalar besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-10.5), v_t(8)), std__cyl_bessel_jn(v_t(-10.5), v_t(8)) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-10.5), v_t(8)), std__cyl_bessel_jn(v_t(-10.5), v_t(8)) , 2.0);
// large x
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(1500)), T(std__cyl_bessel_jn(v_t(-3.5), v_t(1500))), 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(500)), T(std__cyl_bessel_jn(v_t(-2.5), v_t(500))), 2.0);
// forward
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(10)), T(std__cyl_bessel_jn(v_t(-2.5), v_t(10))) , 6.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(5)), T(std__cyl_bessel_jn(v_t(-3.5), v_t(5))) , 35.0);
// serie
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(0.1)), T(std__cyl_bessel_jn(v_t(-2.5), v_t(0.1))) , 2.0);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(0.2)), T(std__cyl_bessel_jn(v_t(-3.5), v_t(0.2))) , 2.5);
// besseljy
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-10.5), T(8)), T(std__cyl_bessel_jn(v_t(-10.5), v_t(8))) , 2.5);
TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-10.5), T(8)), T(std__cyl_bessel_jn(v_t(-10.5), v_t(8))) , 2.5);
TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(-n, a0), map(std__cyl_bessel_jn, -n, a0) , 0.001);
};
EVE_TEST( "Check behavior of diff(cyl_bessel_jn) on wide"
, eve::test::simd::ieee_reals
, eve::test::generate( eve::test::randoms(0.0, 10.0)
, eve::test::randoms(0.0, 60.0))
)
<typename T>(T n, T a0 )
{
using v_t = eve::element_type_t<T>;
auto eve__diff_bessel_jn = [](auto n, auto x) { return eve::diff(eve::cyl_bessel_jn)(n, x); };
auto std__diff_bessel_jn = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_j_prime(double(n), double(x)); };
TTS_RELATIVE_EQUAL(eve__diff_bessel_jn(n, a0), map(std__diff_bessel_jn, n, a0), 1.0e-3);
auto nn = eve::trunc(n);
TTS_RELATIVE_EQUAL(eve__diff_bessel_jn(nn, a0), map(std__diff_bessel_jn, nn, a0), 2.0e-3);
};
| 59.211538 | 120 | 0.6228 | [
"vector"
] |
60146456889bf4e5094d5adbfa36dcd3388619bb | 13,390 | cpp | C++ | demos/terrain/terrain.cpp | ShamylZakariya/MarchingCubes | 27f375d5d25df2246095d65c11127aac82a24211 | [
"MIT"
] | 2 | 2019-12-03T05:52:57.000Z | 2021-05-21T18:17:52.000Z | demos/terrain/terrain.cpp | ShamylZakariya/MarchingCubes | 27f375d5d25df2246095d65c11127aac82a24211 | [
"MIT"
] | null | null | null | demos/terrain/terrain.cpp | ShamylZakariya/MarchingCubes | 27f375d5d25df2246095d65c11127aac82a24211 | [
"MIT"
] | null | null | null | #include "terrain.hpp"
#include <glm/ext.hpp>
#include <glm/gtc/noise.hpp>
#include "materials.hpp"
#include "terrain_samplers.hpp"
using namespace glm;
namespace {
vec4 rainbow(float dist)
{
using namespace mc::util::color;
const hsv hC { 360 * dist, 0.6F, 1.0F };
const auto rgbC = Hsv2Rgb(hC);
return vec4(rgbC.r, rgbC.g, rgbC.b, 1);
}
vec4 nodeColor(int atDepth)
{
return rainbow((atDepth % 8) / 8.0F);
}
}
TerrainChunk::TerrainChunk(int size, mc::util::unowned_ptr<TerrainSampler::SampleSource> terrain)
: _index(0, 0)
, _size(size)
, _maxHeight(terrain->maxHeight())
, _threadPool(std::thread::hardware_concurrency(), true)
, _terrainSampleSource(terrain)
{
std::vector<mc::util::unowned_ptr<mc::TriangleConsumer<mc::Vertex>>> unownedTriangleConsumers;
for (size_t i = 0, N = _threadPool.size(); i < N; i++) {
_triangles.push_back(std::make_unique<mc::TriangleConsumer<mc::Vertex>>());
unownedTriangleConsumers.push_back(_triangles.back().get());
}
const int minNodeSize = 4;
const float fuzziness = 2.0F;
_volume = std::make_unique<mc::OctreeVolume>(size, fuzziness, minNodeSize, &_threadPool, unownedTriangleConsumers);
}
void TerrainChunk::setIndex(ivec2 index)
{
_needsMarch = true;
_index = index;
_volume->clear();
for (auto& tc : _triangles) {
tc->clear();
}
const auto xzOffset = getXZOffset();
const auto size = vec3(_volume->getSize());
const auto sampleOffset = vec3(xzOffset.x, 0, xzOffset.y);
// bounds are in world not local space
_bounds = AABB(sampleOffset, sampleOffset + size);
_groundSampler = _volume->add(std::make_unique<TerrainSampler>(_terrainSampleSource, sampleOffset));
// Build a debug frame to show our volume
const auto segmentColor = rainbow(static_cast<float>((_index.x * 50 + _index.y) % 10) / 10.0F);
_boundingLineBuffer.clear();
_boundingLineBuffer.add(AABB(vec3 { 0.0F }, size).inset(1), segmentColor);
}
void TerrainChunk::march(std::function<void()> onComplete)
{
const double startTime = glfwGetTime();
_aabbLineBuffer.clear();
const auto nodeObserver = [this](mc::OctreeVolume::Node* node) {
{
// update the occupied aabb display
auto bounds = node->bounds;
bounds.inset(node->depth * 0.005F);
_aabbLineBuffer.add(bounds, nodeColor(node->depth));
}
};
const auto onMarchComplete = [this, startTime, onComplete]() {
_lastMarchDurationSeconds = glfwGetTime() - startTime;
onComplete();
_isMarching = false;
_needsMarch = false;
};
_isMarching = true;
_volume->marchAsync(onMarchComplete, nodeObserver);
}
///////////////////////////////////////////////////////////////////////////////
namespace {
int makeOdd(int v)
{
if (v % 2)
return v;
return v + 1;
}
}
TerrainGrid::TerrainGrid(int gridSize, int chunkSize,
std::unique_ptr<TerrainSampler::SampleSource>&& terrainSampleSource,
std::unique_ptr<GreebleSource>&& greebleSource)
: _gridSize(makeOdd(gridSize))
, _chunkSize(chunkSize)
, _terrainSampleSource(std::move(terrainSampleSource))
, _greebleSource(std::move(greebleSource))
{
_grid.resize(_gridSize * _gridSize);
for (int i = 0; i < _gridSize; i++) {
for (int j = 0; j < _gridSize; j++) {
int k = i * _gridSize + j;
_grid[k] = std::make_unique<TerrainChunk>(chunkSize, _terrainSampleSource.get());
_grid[k]->setIndex(ivec2(j - _gridSize / 2, i - _gridSize / 2));
}
}
_centerOffset = (_gridSize * _gridSize) / 2;
}
glm::ivec2 TerrainGrid::worldToIndex(const glm::vec3& world) const
{
auto idx = ivec2(world.x / _chunkSize, world.z / _chunkSize);
if (world.x < 0)
idx.x--;
if (world.z < 0)
idx.y--;
return idx;
}
mc::util::unowned_ptr<TerrainChunk> TerrainGrid::getTerrainChunkContaining(const glm::vec3& world) const
{
const ivec2 idx0 = _grid[0]->getIndex();
const ivec2 targetIdx = worldToIndex(world);
const ivec2 delta = targetIdx - idx0;
if (delta.x >= 0 && delta.x < _gridSize && delta.y >= 0 && delta.y < _gridSize) {
return _grid[delta.y * _gridSize + delta.x];
}
return nullptr;
}
void TerrainGrid::shift(glm::ivec2 by)
{
// shift dx
int dx = by.x;
while (dx != 0) {
if (dx > 0) {
// shift contents to right, recycling rightmost column to left
for (int y = 0; y < _gridSize; y++) {
int rowOffset = y * _gridSize;
for (int x = _gridSize - 1; x > 0; x--) {
std::swap(_grid[rowOffset + x], _grid[rowOffset + x - 1]);
}
_grid[rowOffset]->setIndex(_grid[rowOffset + 1]->getIndex() + ivec2(-1, 0));
}
dx--;
} else {
// WORKS
// shift contents to left, recycling elements at left side of each row to right
for (int y = 0; y < _gridSize; y++) {
int rowOffset = y * _gridSize;
for (int x = 0; x < _gridSize - 1; x++) {
std::swap(_grid[rowOffset + x], _grid[rowOffset + x + 1]);
}
_grid[rowOffset + _gridSize - 1]->setIndex(_grid[rowOffset + _gridSize - 2]->getIndex() + ivec2(+1, 0));
}
dx++;
}
}
// shift dy
int dy = by.y;
while (dy != 0) {
if (dy > 0) {
// shift contents down, recycling elements at bottom to top
for (int x = 0; x < _gridSize; x++) {
for (int y = _gridSize - 1; y > 0; y--) {
std::swap(_grid[y * _gridSize + x], _grid[((y - 1) * _gridSize) + x]);
}
_grid[x]->setIndex(_grid[_gridSize + x]->getIndex() + ivec2(0, -1));
}
dy--;
} else {
// shift contents up, recycling elements at top to bottom
for (int x = 0; x < _gridSize; x++) {
for (int y = 0; y < _gridSize - 1; y++) {
std::swap(_grid[y * _gridSize + x], _grid[(y + 1) * _gridSize + x]);
}
_grid[(_gridSize - 1) * _gridSize + x]->setIndex(_grid[(_gridSize - 2) * _gridSize + x]->getIndex() + ivec2(0, 1));
}
dy++;
}
}
}
void TerrainGrid::print()
{
std::cout << "TerrainGrid::print\n";
for (int i = 0; i < _gridSize; i++) {
for (int j = 0; j < _gridSize; j++) {
int k = i * _gridSize + j;
std::cout << "\tidx:" << k << "\t" << glm::to_string(_grid[k]->getIndex()) << std::endl;
}
std::cout << "\n";
}
std::cout << std::endl;
}
void TerrainGrid::march(const glm::vec3& viewPos, const glm::vec3& viewDir)
{
// collect all TerrainChunk instances which need to be marched, and aren't being marched
_dirtyChunks.clear();
for (const auto& chunk : _grid) {
if (chunk->needsMarch() && !chunk->isWorking()) {
_dirtyChunks.push_back(chunk.get());
}
}
// sort such that the elements most in front of view are at end of vector
std::sort(_dirtyChunks.begin(), _dirtyChunks.end(), [&viewPos, &viewDir](TerrainChunk* a, TerrainChunk* b) -> bool {
vec3 vToA = normalize(a->getBounds().center() - viewPos);
vec3 vToB = normalize(b->getBounds().center() - viewPos);
float da = dot(vToA, viewDir);
float db = dot(vToB, viewDir);
return da < db;
});
// now march the queue serially from back to front
if (!_dirtyChunks.empty()) {
_isMarching = true;
updateGreebling();
marchSerially();
}
}
namespace {
const float kIsoThreshold = 0.001F;
vec3 normalAt(mc::OctreeVolume::Node* node, glm::vec3 p)
{
mc::MaterialState _;
const float d = 0.05f;
vec3 gradient(
node->valueAt(p + vec3(d, 0, 0), 1, _, false) - node->valueAt(p + vec3(-d, 0, 0), 1, _, false),
node->valueAt(p + vec3(0, d, 0), 1, _, false) - node->valueAt(p + vec3(0, -d, 0), 1, _, false),
node->valueAt(p + vec3(0, 0, d), 1, _, false) - node->valueAt(p + vec3(0, 0, -d), 1, _, false));
return -normalize(gradient);
}
}
TerrainGrid::RaycastResult TerrainGrid::rayCast(const glm::vec3& origin, const glm::vec3& dir,
float stepSize, float maxLength,
bool computeNormal, RaycastEdgeBehavior edgeBehavior) const
{
const float maxLength2 = maxLength * maxLength;
const float minStepSize = stepSize * pow<float>(0.5, 6);
const bool clamp = edgeBehavior == RaycastEdgeBehavior::Clamp;
mc::util::unowned_ptr<TerrainChunk> currentChunk = getTerrainChunkContaining(origin);
mc::util::unowned_ptr<TerrainChunk> lastChunk = getTerrainChunkContaining(origin + dir * maxLength);
const bool crossesChunks = lastChunk != currentChunk;
vec3 samplePoint = origin;
mc::MaterialState _;
bool firstStep = true;
bool forward = true;
bool wasInsideVolume = false;
while (distance2(samplePoint, origin) < maxLength2) {
auto volume = currentChunk->getVolume();
auto chunkWorldOrigin = currentChunk->getWorldOrigin();
vec3 localSamplePoint = samplePoint - chunkWorldOrigin;
if (clamp) {
localSamplePoint = volume->getBounds().clamp(localSamplePoint);
}
auto node = volume->findNode(localSamplePoint);
if (node != nullptr) {
float value = node->valueAt(localSamplePoint, 1, _, false);
if (firstStep && value > 0.5F + kIsoThreshold) {
// the raycast origin is inside the volume. Reverse raycast to find exit point.
forward = false;
wasInsideVolume = true;
stepSize *= -1;
}
// we landed right on the iso surface boundary, we're done.
if (std::abs(value - 0.5F) < kIsoThreshold) {
RaycastResult result;
result.isHit = true;
result.distance = glm::distance(samplePoint, origin) * (wasInsideVolume ? -1 : 1);
result.position = samplePoint;
if (computeNormal) {
result.normal = normalAt(node, localSamplePoint);
}
}
if (forward) {
if (value > 0.5F) {
forward = false;
stepSize *= -0.5F;
}
} else {
if (value < 0.5F) {
forward = true;
stepSize *= -0.5F;
}
}
}
if (std::abs(stepSize) <= minStepSize) {
// we've been binary searching about the threshold; this is good enough.
RaycastResult result;
result.isHit = true;
result.position = samplePoint;
result.distance = glm::distance(samplePoint, origin) * (wasInsideVolume ? -1 : 1);
if (computeNormal) {
result.normal = normalAt(node, localSamplePoint);
}
return result;
}
samplePoint += dir * stepSize;
firstStep = false;
if (crossesChunks) {
currentChunk = getTerrainChunkContaining(samplePoint);
if (!currentChunk) {
return RaycastResult::none();
}
}
}
std::cout << "Done - exceeded max raycast distance" << std::endl;
return RaycastResult::none();
}
bool TerrainGrid::samplerIntersects(mc::IVolumeSampler* sampler, const vec3& samplerChunkWorldOrigin, const AABB worldBounds)
{
const auto relativeOrigin = worldBounds.min - samplerChunkWorldOrigin;
const auto relativeBounds = AABB { relativeOrigin, relativeOrigin + worldBounds.size() };
return sampler->intersects(relativeBounds);
}
namespace {
float snap(float v, int step)
{
int x = v / step;
return x * step;
}
}
void TerrainGrid::updateGreebling()
{
if (!_greebleSource)
return;
const int step = _greebleSource->sampleStepSize();
for (const auto& chunk : _dirtyChunks) {
const auto chunkBounds = chunk->getBounds();
const auto extent = chunkBounds.size();
const auto range = AABB(
vec3(snap(chunkBounds.min.x - extent.x, step), chunkBounds.min.y, snap(chunkBounds.min.z - extent.z, step)),
vec3(snap(chunkBounds.max.x + extent.x, step), chunkBounds.max.y, snap(chunkBounds.max.z + extent.z, step)));
for (float x = range.min.x; x <= range.max.x; x += step) {
for (float z = range.min.z; z <= range.max.z; z += step) {
const vec3 world(x, 0, z);
const GreebleSource::Sample sample = _greebleSource->sample(world);
const vec3 local(world.x - chunkBounds.min.x, 0, world.z - chunkBounds.min.z);
std::unique_ptr<mc::IVolumeSampler> greeble = _greebleSource->evaluate(sample, local);
if (greeble) {
chunk->getVolume()->add(std::move(greeble));
}
}
}
}
}
void TerrainGrid::marchSerially()
{
_dirtyChunks.back()->march([this]() {
_dirtyChunks.pop_back();
if (!_dirtyChunks.empty()) {
marchSerially();
} else {
_isMarching = false;
}
});
}
| 33.813131 | 131 | 0.571397 | [
"vector"
] |
6017233ea519a3d6e05b5cccc3ff2772fe081760 | 9,970 | hpp | C++ | libcaf_core/caf/intrusive/lifo_inbox.hpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | 4 | 2019-05-03T05:38:15.000Z | 2020-08-25T15:23:19.000Z | libcaf_core/caf/intrusive/lifo_inbox.hpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2021-11-26T13:14:47.000Z | 2021-11-26T16:29:58.000Z | libcaf_core/caf/intrusive/lifo_inbox.hpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | 3 | 2020-05-21T20:54:58.000Z | 2020-06-17T13:44:13.000Z | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include "caf/config.hpp"
#include "caf/intrusive/inbox_result.hpp"
namespace caf::intrusive {
/// An intrusive, thread-safe LIFO queue implementation for a single reader
/// with any number of writers.
template <class Policy>
class lifo_inbox {
public:
// -- member types -----------------------------------------------------------
using policy_type = Policy;
using value_type = typename policy_type::mapped_type;
using pointer = value_type*;
using node_type = typename value_type::node_type;
using node_pointer = node_type*;
using unique_pointer = typename policy_type::unique_pointer;
using deleter_type = typename unique_pointer::deleter_type;
// -- static utility functions -----------------------------------------------
/// Casts a node type to its value type.
static pointer promote(node_pointer ptr) noexcept {
return static_cast<pointer>(ptr);
}
// -- modifiers --------------------------------------------------------------
/// Tries to enqueue a new element to the inbox.
/// @threadsafe
inbox_result push_front(pointer new_element) noexcept {
CAF_ASSERT(new_element != nullptr);
pointer e = stack_.load();
auto eof = stack_closed_tag();
auto blk = reader_blocked_tag();
while (e != eof) {
// A tag is never part of a non-empty list.
new_element->next = e != blk ? e : nullptr;
if (stack_.compare_exchange_strong(e, new_element))
return e == reader_blocked_tag() ? inbox_result::unblocked_reader
: inbox_result::success;
// Continue with new value of `e`.
}
// The queue has been closed, drop messages.
deleter_type d;
d(new_element);
return inbox_result::queue_closed;
}
/// Tries to enqueue a new element to the inbox.
/// @threadsafe
inbox_result push_front(unique_pointer x) noexcept {
return push_front(x.release());
}
/// Tries to enqueue a new element to the mailbox.
/// @threadsafe
template <class... Ts>
inbox_result emplace_front(Ts&&... xs) {
return push_front(new value_type(std::forward<Ts>(xs)...));
}
/// Queries whether this queue is empty.
/// @pre `!closed() && !blocked()`
bool empty() const noexcept {
CAF_ASSERT(!closed());
CAF_ASSERT(!blocked());
return stack_.load() == stack_empty_tag();
}
/// Queries whether this has been closed.
bool closed() const noexcept {
return stack_.load() == stack_closed_tag();
}
/// Queries whether this has been marked as blocked, i.e.,
/// the owner of the list is waiting for new data.
bool blocked() const noexcept {
return stack_.load() == reader_blocked_tag();
}
/// Tries to set this queue from `empty` to `blocked`.
bool try_block() noexcept {
auto e = stack_empty_tag();
return stack_.compare_exchange_strong(e, reader_blocked_tag());
}
/// Tries to set this queue from `blocked` to `empty`.
bool try_unblock() noexcept {
auto e = reader_blocked_tag();
return stack_.compare_exchange_strong(e, stack_empty_tag());
}
/// Sets the head to `new_head` and returns the previous head if the queue
/// was not empty.
pointer take_head(pointer new_head) noexcept {
// This member function should only be used to transition to closed or
// empty.
CAF_ASSERT(new_head == stack_closed_tag() || new_head == stack_empty_tag());
pointer e = stack_.load();
// Must not be called on a closed queue.
CAF_ASSERT(e != stack_closed_tag());
// Must not be called on a blocked queue unless for setting it to closed,
// because that would mean an actor accesses its mailbox after blocking its
// mailbox but before receiving anything.
CAF_ASSERT(e != reader_blocked_tag() || new_head == stack_closed_tag());
// We don't assert these conditions again since only the owner is allowed
// to call this member function, i.e., there's never a race on `take_head`.
while (e != new_head) {
if (stack_.compare_exchange_weak(e, new_head)) {
CAF_ASSERT(e != stack_closed_tag());
if (is_empty_or_blocked_tag(e)) {
// Sanity check: going from empty/blocked to closed.
CAF_ASSERT(new_head == stack_closed_tag());
return nullptr;
}
return e;
}
// Next iteration.
}
return nullptr;
}
/// Sets the head to `stack_empty_tag()` and returns the previous head if
/// the queue was not empty.
pointer take_head() noexcept {
return take_head(stack_empty_tag());
}
/// Closes this queue and deletes all remaining elements.
/// @warning Call only from the reader (owner).
void close() noexcept {
deleter_type d;
// We assume the node destructor to never throw. However, the following
// static assert fails. Unfortunately, std::default_delete's apply operator
// is not noexcept (event for types that have a noexcept destructor).
// static_assert(noexcept(d(std::declval<pointer>())),
// "deleter is not noexcept");
close(d);
}
/// Closes this queue and applies `f` to each pointer. The function object
/// `f` must take ownership of the passed pointer.
/// @warning Call only from the reader (owner).
template <class F>
void close(F& f) noexcept(noexcept(f(std::declval<pointer>()))) {
node_pointer ptr = take_head(stack_closed_tag());
while (ptr != nullptr) {
auto next = ptr->next;
f(promote(ptr));
ptr = next;
}
}
lifo_inbox() noexcept {
stack_ = stack_empty_tag();
}
~lifo_inbox() noexcept {
if (!closed())
close();
}
// -- synchronized access ---------------------------------------------------
template <class Mutex, class CondVar>
bool synchronized_push_front(Mutex& mtx, CondVar& cv, pointer ptr) {
switch (push_front(ptr)) {
default:
// enqueued message to a running actor's mailbox
return true;
case inbox_result::unblocked_reader: {
std::unique_lock<Mutex> guard(mtx);
cv.notify_one();
return true;
}
case inbox_result::queue_closed:
// actor no longer alive
return false;
}
}
template <class Mutex, class CondVar>
bool synchronized_push_front(Mutex& mtx, CondVar& cv, unique_pointer ptr) {
return synchronized_push_front(mtx, cv, ptr.release());
}
template <class Mutex, class CondVar, class... Ts>
bool synchronized_emplace_front(Mutex& mtx, CondVar& cv, Ts&&... xs) {
return synchronized_push_front(mtx, cv,
new value_type(std::forward<Ts>(xs)...));
}
template <class Mutex, class CondVar>
void synchronized_await(Mutex& mtx, CondVar& cv) {
CAF_ASSERT(!closed());
if (try_block()) {
std::unique_lock<Mutex> guard(mtx);
while (blocked())
cv.wait(guard);
}
}
template <class Mutex, class CondVar, class TimePoint>
bool synchronized_await(Mutex& mtx, CondVar& cv, const TimePoint& timeout) {
CAF_ASSERT(!closed());
if (try_block()) {
std::unique_lock<Mutex> guard(mtx);
while (blocked()) {
if (cv.wait_until(guard, timeout) == std::cv_status::timeout) {
// if we're unable to set the queue from blocked to empty,
// than there's a new element in the list
return !try_unblock();
}
}
}
return true;
}
private:
static constexpr pointer stack_empty_tag() {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator whether this queue is empty or not.
return static_cast<pointer>(nullptr);
}
pointer stack_closed_tag() const noexcept {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator whether this queue is closed or not.
return reinterpret_cast<pointer>(reinterpret_cast<intptr_t>(this) + 1);
}
pointer reader_blocked_tag() const noexcept {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator whether the owner of the queue is currently waiting for
// new messages.
return reinterpret_cast<pointer>(const_cast<lifo_inbox*>(this));
}
bool is_empty_or_blocked_tag(pointer x) const noexcept {
return x == stack_empty_tag() || x == reader_blocked_tag();
}
// -- member variables ------------------------------------------------------
std::atomic<pointer> stack_;
};
} // namespace caf::intrusive
| 35.229682 | 80 | 0.585456 | [
"object"
] |
601828a5ad0a0ad9959a735a14510a7ecbd5691d | 3,585 | cpp | C++ | openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateMeter.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateMeter.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateMeter.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2013, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <energyplus/ForwardTranslator.hpp>
#include <model/Model.hpp>
#include <model/Meter.hpp>
#include <model/Meter_Impl.hpp>
#include <utilities/idd/Output_Meter_FieldEnums.hxx>
#include <utilities/idd/Output_Meter_Cumulative_FieldEnums.hxx>
#include <utilities/idd/Output_Meter_MeterFileOnly_FieldEnums.hxx>
#include <utilities/idd/Output_Meter_Cumulative_MeterFileOnly_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
using namespace openstudio::model;
using namespace std;
namespace openstudio {
namespace energyplus {
boost::optional<IdfObject> ForwardTranslator::translateMeter( Meter & modelObject )
{
boost::optional<IdfObject> idfObject;
QString name = toQString(modelObject.name()).replace(QString("FuelOil_"), QString("FuelOil#"));
if (modelObject.meterFileOnly() && modelObject.cumulative()){
idfObject = IdfObject (openstudio::IddObjectType::Output_Meter_Cumulative_MeterFileOnly);
m_idfObjects.push_back(*idfObject);
idfObject->setString(Output_Meter_Cumulative_MeterFileOnlyFields::Name, toString(name));
if (!modelObject.isReportingFrequencyDefaulted()){
idfObject->setString(Output_Meter_Cumulative_MeterFileOnlyFields::ReportingFrequency, modelObject.reportingFrequency());
}
}else if (modelObject.meterFileOnly()){
idfObject = IdfObject (openstudio::IddObjectType::Output_Meter_MeterFileOnly);
m_idfObjects.push_back(*idfObject);
idfObject->setString(Output_Meter_MeterFileOnlyFields::Name, toString(name));
if (!modelObject.isReportingFrequencyDefaulted()){
idfObject->setString(Output_Meter_MeterFileOnlyFields::ReportingFrequency, modelObject.reportingFrequency());
}
}else if (modelObject.cumulative()){
idfObject = IdfObject (openstudio::IddObjectType::Output_Meter_Cumulative);
m_idfObjects.push_back(*idfObject);
idfObject->setString(Output_Meter_CumulativeFields::Name, toString(name));
if (!modelObject.isReportingFrequencyDefaulted()){
idfObject->setString(Output_Meter_CumulativeFields::ReportingFrequency, modelObject.reportingFrequency());
}
}else{
idfObject = IdfObject (openstudio::IddObjectType::Output_Meter);
m_idfObjects.push_back(*idfObject);
idfObject->setString(Output_MeterFields::Name, toString(name));
if (!modelObject.isReportingFrequencyDefaulted()){
idfObject->setString(Output_MeterFields::ReportingFrequency, modelObject.reportingFrequency());
}
}
return idfObject;
}
} // energyplus
} // openstudio
| 37.736842 | 127 | 0.718271 | [
"model"
] |
60189bb761f86f6993a7f4dcc5bd96f092d95dd6 | 5,113 | hpp | C++ | util/include/throughput.hpp | cloudnoize/concord-bft | f87f424dd5b93a4d6946158bf0d476caf559db0a | [
"Apache-2.0"
] | 340 | 2018-08-27T16:30:45.000Z | 2022-03-28T14:31:44.000Z | util/include/throughput.hpp | cloudnoize/concord-bft | f87f424dd5b93a4d6946158bf0d476caf559db0a | [
"Apache-2.0"
] | 706 | 2018-09-02T17:50:32.000Z | 2022-03-31T13:03:15.000Z | util/include/throughput.hpp | glevkovich/concord-bft | a1b7b57472f5375230428d16c613a760b33233fa | [
"Apache-2.0"
] | 153 | 2018-08-29T05:37:25.000Z | 2022-03-23T14:08:45.000Z | // Concord
//
// Copyright (c) 2018-2020 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the subcomponent's license, as noted in the LICENSE
// file.
#pragma once
#include <stdint.h>
#include <chrono>
#include "assertUtils.hpp"
namespace concord::util {
/** A Duration Tracker allows to track the sum of multiple none-continues time intervals (durations).
* This is done by calling start() / pause() multiple times.
* If the last call to the tracker is start(): call totalDuration() to get the sum of intervals, including current
* still running interval.
* If the last call to a tracker is pause(): you may get the sum of intervals from pause() returned
* value or call totalDuration() explicitly.
* To reset (re-use) the tracker, call reset() and then start().
*/
template <typename T>
class DurationTracker {
public:
void start() {
ConcordAssert(!running_);
start_time_ = std::chrono::steady_clock::now();
running_ = true;
}
uint64_t pause() {
if (running_)
total_duration_ += std::chrono::duration_cast<T>(std::chrono::steady_clock::now() - start_time_).count();
running_ = false;
return total_duration_;
}
void reset() {
total_duration_ = 0;
running_ = false;
}
uint64_t totalDuration(bool doReset = false) {
uint64_t ret = total_duration_;
if (running_) {
total_duration_ = pause();
ret = total_duration_;
if (doReset) {
reset();
} else
start();
}
return ret;
};
private:
uint64_t total_duration_ = 0;
std::chrono::time_point<std::chrono::steady_clock> start_time_;
bool running_ = false;
}; // class DurationTracker
/**
* A Throughput object is used to calculate the number of items processed in a time unit.
* After construction, it must be started by calling start().
* It can be paused by calling pause() and resumed by calling resume(). While paused, reports cannot be made.
* To continue call resume().
* To end the current measurements, call end().After ending, pause and resume are not allowed, only start() can be
* called to re-use the object.
* In order to get meaningful statistics, user should report periodically to the object on the processing
* progress by calling report().
*
* If the user supplies a window_size > 0:
* 1) User may call all member functions prefixed with getPrevWin*.
* 2) Last window throughput is calculated and saved.
* 3) Overall and last window calculations are based on the window's end time.
* 4) report() returns true when the window's end reached.
*
* To get overall and/or last window statistics, the user has 2 options:
* 1) If window_size > 0, it should waits until report() returns true and then it may call getOverallResults()
* and/or getPrevWinResults().
* 2) If window_size is 0, user can call at any time for getOverallResults(). Calling report() to continue collecting
* statistics is still possible after.
*/
class Throughput {
public:
Throughput(uint32_t window_size = 0ul) : num_reports_per_window_(window_size) {}
Throughput() = delete;
// Reset all statistics and record starting time
void start();
bool isStarted() { return started_; }
// Reset all statistics, and set started_ to false. Call a again start() to re-use object
void end();
// pause timer. reporting is not allowed.
void pause();
// continue timer after pause was called()
void resume();
// Report amount of items processed since last report.
// If window_size > 0: returns true if reached the end of a summary window, and started a new window
// trigger_calc_throughput is true: manually trigger end of window
bool report(uint64_t items_processed = 1, bool trigger_calc_throughput = false);
struct Results {
uint64_t elapsed_time_ms_ = 0ull;
uint64_t throughput_ = 0ull; // items per sec
uint64_t num_processed_items_ = 0ull;
};
// Get overall Results: total number of items processed, and throughput from time elapsed_time_ms_
const Results& getOverallResults();
// Get previous window's results. Can be called only if report() returned true.
const Results& getPrevWinResults() const;
// Get previous window's index. Can be called only if report() returned true.
uint64_t getPrevWinIndex() const;
protected:
struct Stats {
DurationTracker<std::chrono::milliseconds> total_duration_;
Results results_;
void restart();
void reset();
void calcThroughput(); // in Items/sec
};
const uint32_t num_reports_per_window_;
bool started_ = false;
bool prev_win_calculated_ = false;
Stats overall_stats_;
Stats current_window_stats_;
Stats previous_window_stats_;
uint64_t previous_window_index_;
uint64_t reports_counter_ = 0;
}; // class Throughput
} // namespace concord::util
| 34.315436 | 117 | 0.717191 | [
"object"
] |
e7440c5b32fccb411a9b10b6d797c70f5577812a | 53,781 | cpp | C++ | libnd4j/include/ops/declarable/generic/recurrent/sru.cpp | nutonchain/Deeplearning | 20f222c1eff95205c6c9c9b666b04402405e4442 | [
"Apache-2.0"
] | 2 | 2018-11-26T15:30:37.000Z | 2018-11-26T15:30:39.000Z | libnd4j/include/ops/declarable/generic/recurrent/sru.cpp | nutonchain/Deeplearning | 20f222c1eff95205c6c9c9b666b04402405e4442 | [
"Apache-2.0"
] | 16 | 2018-12-03T11:37:19.000Z | 2018-12-03T19:47:25.000Z | libnd4j/include/ops/declarable/generic/recurrent/sru.cpp | nutonchain/Deeplearning | 20f222c1eff95205c6c9c9b666b04402405e4442 | [
"Apache-2.0"
] | 2 | 2021-03-01T07:46:24.000Z | 2021-09-26T17:08:40.000Z | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// implementation of operations for Simple Recurrent Unit: arXiv:1709.02755v2 [cs.CL] 12 Sep 2017
//
//@author Yurii Shyrma
//
#include <op_boilerplate.h>
#if NOT_EXCLUDED(OP_sru)
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/sru.h>
#include <MmulHelper.h>
namespace nd4j {
namespace ops {
// return 2d array evaluated though last dimension interval t1-t2
template <typename T>
NDArray<T>* timestep(const NDArray<T>* const arr, const int t1, const int t2) {
IndicesList list({ NDIndex::all(), NDIndex::all(), NDIndex::interval(t1,t2)});
NDArray<T>* result = arr->subarray(list);
result->reshapei(result->ordering(), {arr->shapeOf()[0], arr->shapeOf()[1]} );
return result;
}
template <typename T>
NDArray<T> _sigmoid(const NDArray<T>& arr) {
NDArray<T> result(arr.getShapeInfo(), arr.getWorkspace());
(const_cast<NDArray<T>&>(arr)).template applyTransform<simdOps::Sigmoid<T>>(&result);
return result;
}
/////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru_logic, 5, 2, false, 0, 0) {
NDArray<T>* input = INPUT_VARIABLE(0); // X, input 3d tensor [bS x K x N], N - number of time steps, bS - batch size, K - number of features
NDArray<T>* weights = INPUT_VARIABLE(1); // W, 2d tensor of weights [3K x K]
NDArray<T>* bias = INPUT_VARIABLE(2); // B, row of biases with twice length [1 × 2*K]
NDArray<T>* init = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x K] at time t=0
NDArray<T>* mask = nullptr; // optional, 2d tensor of dropout mask [bS x K]
bool applyMask = false;
if (block.width() > 4) {
mask = INPUT_VARIABLE(4);
applyMask = true;
}
NDArray<T>* output = OUTPUT_VARIABLE(0); // h_t, [bS x K x N]
NDArray<T>* state = OUTPUT_VARIABLE(1); // c_t, [bS x K x N]
const int bS = input->shapeOf()[0]; // bS - batch size
const int K = input->shapeOf()[1]; // K - number of features
const int N = input->shapeOf()[2]; // N - number of time steps
const NDArray<T> wi = mmul(*weights, *input); // U [bS x 3K x N]
const NDArray<T> bF = (*bias)({0,0, 0, K}); // biases for forget gate [1 x K]
const NDArray<T> bR = (*bias)({0,0, K,2*K}); // biases for reset gate [1 x K]
NDArray<T> xt(block.getWorkspace());
NDArray<T> zt(block.getWorkspace());
NDArray<T> ft(block.getWorkspace());
NDArray<T> rt(block.getWorkspace());
NDArray<T> ht(block.getWorkspace());
NDArray<T> ct = *init;
NDArray<T> gct(state->ordering(), {bS, K}, block.getWorkspace());
NDArray<T> xmt = *input;
// input = input * mask
if(applyMask)
xmt.template applyBroadcast<simdOps::Multiply<T>>({0, 1}, mask, &xmt, nullptr);
for (int t = 0; t < N; ++t) {
xt = xmt({0,0, 0,0, t,t+1}); xt.reshapei(xt.ordering(), {bS, K}); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
zt = wi({0,0, 0, K, t,t+1}); zt.reshapei(zt.ordering(), {bS, K}); // [bS x 3K x N] -> [bS x K x 1] -> [bS x K]
ft = wi({0,0, K, 2*K, t,t+1}); ft.reshapei(ft.ordering(), {bS, K}); // [bS x 3K x N] -> [bS x K x 1] -> [bS x K]
rt = wi({0,0, 2*K,3*K, t,t+1}); rt.reshapei(rt.ordering(), {bS, K}); // [bS x 3K x N] -> [bS x K x 1] -> [bS x K]
ft = _sigmoid(ft + bF);
rt = _sigmoid(rt + bR);
ct = ft * (ct - zt) + zt;
// TODO T val = (activation_type == 1) ? tanh(cur) : ((activation_type == 2) ? reluf(cur) : cur );
ct.template applyTransform<simdOps::Tanh<T>>(&gct);
ht = rt * (gct - xt) + xt;
// save results
output->assign(ht, {{}, {}, {t,t+1}} );
state->assign (ct, {{}, {}, {t,t+1}} );
}
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(sru_logic) {
auto inShape = inputShape->at(0); // [bS x K x N]
int rank = inShape[0]; // = 3
int size = rank*2 + 4;
int bS = inShape[1];
int K = inShape[2];
int N = inShape[3];
char order = (char)(inShape[size-1]);
Nd4jLong* newShapeInfo1 = nullptr;
Nd4jLong* newShapeInfo2 = nullptr;
ALLOCATE(newShapeInfo1, block.getWorkspace(), size, Nd4jLong);
ALLOCATE(newShapeInfo2, block.getWorkspace(), size, Nd4jLong);
newShapeInfo1[0] = rank;
newShapeInfo1[1] = bS;
newShapeInfo1[2] = K;
newShapeInfo1[3] = N;
shape::updateStrides(newShapeInfo1, order);
memcpy(newShapeInfo2, newShapeInfo1, shape::shapeInfoByteLength(newShapeInfo1));
return SHAPELIST(newShapeInfo1, newShapeInfo2);
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru_old, 5, 2, false, 0, 0) {
NDArray<T>* x = INPUT_VARIABLE(0); // X, input 3d tensor [bS x inSize x time], time - number of time steps, bS - batch size, inSize - number of features
NDArray<T>* w = INPUT_VARIABLE(1); // W, 2d tensor of weights [3K x inSize]
NDArray<T>* b = INPUT_VARIABLE(2); // B, row of biases with twice length [1 × 2*inSize]
NDArray<T>* c0 = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x inSize] at time t=0
NDArray<T>* mask = nullptr; // optional, 2d tensor of dropout mask [bS x inSize]
bool applyMask = false;
if (block.width() > 4) {
mask = INPUT_VARIABLE(4);
applyMask = true;
}
NDArray<T>* h = OUTPUT_VARIABLE(0); // h_t, [bS x inSize x time]
NDArray<T>* state = OUTPUT_VARIABLE(1); // c_t, [bS x inSize x time]
const int bS = x->shapeOf()[0]; // bS - batch size
const int inSize = x->shapeOf()[1]; // inSize - number of features
const int time = x->shapeOf()[2]; // time - number of time steps
// multiplication matrix = matmul(w,x)
NDArray<T>* wi = MmulHelper<T>::mmul(w, x, nullptr, (T)1., (T)0.); // U [bS x 3K x time]
// wi.printShapeInfo();
NDArray<T>* wiZ = wi->subarray( { NDIndex::all(), NDIndex::interval(0,inSize), NDIndex::all() } ); // [bS x inSize x time]
NDArray<T>* wiF = wi->subarray( { NDIndex::all(), NDIndex::interval(inSize,2*inSize), NDIndex::all() } ); // forget gate [bS x inSize x time]
NDArray<T>* wiR = wi->subarray( { NDIndex::all(), NDIndex::interval(2*inSize,3*inSize), NDIndex::all() } ); // reset gate [bS x inSize x time]
NDArray<T>* bF = b->subarray( { NDIndex::all(), NDIndex::interval(0,inSize) } ); // biases for forget gate [1 x inSize]
NDArray<T>* bR = b->subarray( { NDIndex::all(), NDIndex::interval(inSize,2*inSize)} ); // biases for reset gate [1 x inSize]
NDArray<T>* xt(nullptr), *zt(nullptr), *ft(nullptr), *rt(nullptr), *ct(nullptr), *ht(nullptr);
NDArray<T>* ct_1 = c0->dup(c0->ordering());
NDArray<T>* gct = new NDArray<T>(state->ordering(), {bS, inSize});
NDArray<T>* xmt = x->dup(x->ordering());
// x = x * mask
if(applyMask)
xmt->template applyBroadcast<simdOps::Multiply<T>>({0, 1}, mask, xmt, nullptr); // apply mask
for (int t = 0; t < time; ++t) {
xt = timestep(xmt, t, t+1); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
zt = timestep(wiZ, t, t+1); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
ft = timestep(wiF, t, t+1); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
rt = timestep(wiR, t, t+1); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
ct = timestep(state, t, t+1); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
ht = timestep(h, t, t+1); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
// ft = sigmoid(ft + bf), rt = sigmoid(rt + bR)
ft->addRowVector(bF, ft);
rt->addRowVector(bR, rt);
ft->template applyTransform<simdOps::Sigmoid<T>>();
rt->template applyTransform<simdOps::Sigmoid<T>>();
// ct = ft * c_t-1 + (1 - ft) * zt,
ft->template applyPairwiseTransform<simdOps::Multiply<T>>(ct_1, ct, nullptr);
ft->template applyTransform<simdOps::OneMinus<T>>(ft);
ft->template applyPairwiseTransform<simdOps::Multiply<T>>(zt, nullptr);
ct->template applyPairwiseTransform<simdOps::Add<T>>(ft, nullptr);
// TODO T val = (activation_type == 1) ? tanh(cur) : ((activation_type == 2) ? reluf(cur) : cur );
ct->template applyTransform<simdOps::Tanh<T>>(gct);
// ht = rt * gct + (1 - rt) * xt
rt->template applyPairwiseTransform<simdOps::Multiply<T>>(gct, ht, nullptr);
rt->template applyTransform<simdOps::OneMinus<T>>(rt);
rt->template applyPairwiseTransform<simdOps::Multiply<T>>(xt, nullptr);
ht->template applyPairwiseTransform<simdOps::Add<T>>(rt, nullptr);
delete xt; delete zt; delete ft; delete rt; delete ht; delete ct_1;
ct_1 = ct;
}
delete wiZ; delete wiF; delete wiR; delete wi; delete bF; delete bR; delete ct_1; delete gct; delete xmt;
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(sru_old) {
auto inShape = inputShape->at(0); // [bS x inSize x time]
int rank = inShape[0]; // = 3
int size = rank*2 + 4;
auto bS = inShape[1];
auto inSize = inShape[2];
int time = inShape[3];
char order = (char)(inShape[size-1]);
Nd4jLong* newShapeInfo1 = nullptr;
Nd4jLong* newShapeInfo2 = nullptr;
ALLOCATE(newShapeInfo1, block.getWorkspace(), size, Nd4jLong);
ALLOCATE(newShapeInfo2, block.getWorkspace(), size, Nd4jLong);
newShapeInfo1[0] = rank;
newShapeInfo1[1] = bS;
newShapeInfo1[2] = inSize;
newShapeInfo1[3] = time;
shape::updateStrides(newShapeInfo1, order);
memcpy(newShapeInfo2, newShapeInfo1, shape::shapeInfoByteLength(newShapeInfo1));
return SHAPELIST(newShapeInfo1, newShapeInfo2);
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru, 5, 2, false, 0, 0) {
NDArray<T>* x = INPUT_VARIABLE(0); // X, input 3d tensor [bS x inSize x time], time - number of time steps, bS - batch size, inSize - number of features
NDArray<T>* w = INPUT_VARIABLE(1); // W, 2d tensor of weights [3*inSize x inSize]
NDArray<T>* b = INPUT_VARIABLE(2); // B, row of biases with twice length [2*inSize]
NDArray<T>* c0 = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x inSize] at time t=0
NDArray<T>* mask = block.width() > 4 ? INPUT_VARIABLE(4) : nullptr; // optional, 2d tensor of dropout mask [bS x inSize]
NDArray<T>* h = OUTPUT_VARIABLE(0); // cell outputs, [bS x inSize x time]
NDArray<T>* c = OUTPUT_VARIABLE(1); // cell states, [bS x inSize x time]
const int rank = x->rankOf(); // = 3
const int bS = x->sizeAt(0);
const int inSize = x->sizeAt(1);
const int time = x->sizeAt(2);
// input shapes validation
REQUIRE_TRUE(w->rankOf() == rank-1, 0, "SRU operation: wrong rank of weights array, expected is %i, but got %i instead !", rank-1, w->rankOf());
REQUIRE_TRUE(b->rankOf() == 1, 0, "SRU operation: wrong rank of biases array, expected is %i, but got %i instead !", 1, b->rankOf());
REQUIRE_TRUE(c0->rankOf() == rank-1, 0, "SRU operation: wrong rank of initial state array, expected is %i, but got %i instead !", rank-1, c0->rankOf());
if(mask)
REQUIRE_TRUE(mask->rankOf() == rank-1, 0, "SRU operation: wrong rank of mask array, expected is %i, but got %i instead !", rank-1, mask->rankOf());
const std::string wShape = ShapeUtils<T>::shapeAsString(w);
const std::string wCorrectShape = ShapeUtils<T>::shapeAsString({3*inSize, inSize});
const std::string bShape = ShapeUtils<T>::shapeAsString(b);
const std::string bCorrectShape = ShapeUtils<T>::shapeAsString({2*inSize});
const std::string c0Shape = ShapeUtils<T>::shapeAsString(c0);
const std::string c0CorrectShape = ShapeUtils<T>::shapeAsString({bS, inSize});
REQUIRE_TRUE(wShape == wCorrectShape, 0, "SRU operation: wrong shape of weights array, expected is %s, but got %s instead !", wCorrectShape.c_str(), wShape.c_str());
REQUIRE_TRUE(bShape == bCorrectShape, 0, "SRU operation: wrong shape of biases array, expected is %s, but got %s instead !", bCorrectShape.c_str(), bShape.c_str());
REQUIRE_TRUE(c0Shape == c0CorrectShape, 0, "SRU operation: wrong shape of initial state array, expected is %s, but got %s instead !", c0CorrectShape.c_str(), c0Shape.c_str());
if(mask) {
const std::string maskShape = ShapeUtils<T>::shapeAsString(mask);
REQUIRE_TRUE(maskShape == c0CorrectShape, 0, "SRU operation: wrong shape of mask array, expected is %s, but got %s instead !", c0CorrectShape.c_str(), maskShape.c_str());
}
// xm = x * mask
NDArray<T>* xm = x;
if(mask) {
xm = new NDArray<T>(x->getShapeInfo(), true, block.getWorkspace());
x->template applyBroadcast<simdOps::Multiply<T>>({0, 1}, mask, xm, nullptr);
}
// time loop
helpers::sruTimeLoop<T>({xm, c0, w, b}, {h, c});
if(mask)
delete xm;
return Status::OK();
}
DECLARE_SHAPE_FN(sru) {
auto xShapeInfo = inputShape->at(0); // X, input 3d tensor [bS x inSize x time], time - number of time steps, bS - batch size, inSize - number of features
auto wShapeInfo = inputShape->at(1); // W, 2d tensor of weights [3*inSize x inSize]
auto bShapeInfo = inputShape->at(2); // B, row of biases with twice length [2*inSize]
auto c0ShapeInfo = inputShape->at(3); // C_{0}, 2d tensor of initial state [bS x inSize] at time t=0
Nd4jLong* maskShapeInfo = block.width() > 4 ? inputShape->at(4) : nullptr; // optional, 2d tensor of dropout mask [bS x inSize]
const int rank = xShapeInfo[0]; // = 3
const int bS = xShapeInfo[1];
const int inSize = xShapeInfo[2];
const int time = xShapeInfo[3];
// input shapes validation
REQUIRE_TRUE(wShapeInfo[0] == rank-1, 0, "SRU operation: wrong rank of weights array, expected is %i, but got %i instead !", rank-1, wShapeInfo[0]);
REQUIRE_TRUE(bShapeInfo[0] == 1, 0, "SRU operation: wrong rank of biases array, expected is %i, but got %i instead !", 1, bShapeInfo[0]);
REQUIRE_TRUE(c0ShapeInfo[0] == rank-1, 0, "SRU operation: wrong rank of initial state array, expected is %i, but got %i instead !", rank-1, c0ShapeInfo[0]);
if(maskShapeInfo)
REQUIRE_TRUE(maskShapeInfo[0] == rank-1, 0, "SRU operation: wrong rank of mask array, expected is %i, but got %i instead !", rank-1, maskShapeInfo[0]);
const std::string wShape = ShapeUtils<T>::shapeAsString(wShapeInfo);
const std::string wCorrectShape = ShapeUtils<T>::shapeAsString({3*inSize, inSize});
const std::string bShape = ShapeUtils<T>::shapeAsString(bShapeInfo);
const std::string bCorrectShape = ShapeUtils<T>::shapeAsString({2*inSize});
const std::string c0Shape = ShapeUtils<T>::shapeAsString(c0ShapeInfo);
const std::string c0CorrectShape = ShapeUtils<T>::shapeAsString({bS, inSize});
REQUIRE_TRUE(wShape == wCorrectShape, 0, "SRU operation: wrong shape of weights array, expected is %s, but got %s instead !", wCorrectShape.c_str(), wShape.c_str());
REQUIRE_TRUE(bShape == bCorrectShape, 0, "SRU operation: wrong shape of biases array, expected is %s, but got %s instead !", bCorrectShape.c_str(), bShape.c_str());
REQUIRE_TRUE(c0Shape == c0CorrectShape, 0, "SRU operation: wrong shape of initial state array, expected is %s, but got %s instead !", c0CorrectShape.c_str(), c0Shape.c_str());
if(maskShapeInfo) {
const std::string maskShape = ShapeUtils<T>::shapeAsString(maskShapeInfo);
REQUIRE_TRUE(maskShape == c0CorrectShape, 0, "SRU operation: wrong shape of mask array, expected is %s, but got %s instead !", c0CorrectShape.c_str(), maskShape.c_str());
}
Nd4jLong* newShapeInfo1 = nullptr;
Nd4jLong* newShapeInfo2 = nullptr;
ALLOCATE(newShapeInfo1, block.getWorkspace(), shape::shapeInfoLength(rank), Nd4jLong); // [bS x inSize x time]
ALLOCATE(newShapeInfo2, block.getWorkspace(), shape::shapeInfoLength(rank), Nd4jLong); // [bS x inSize x time]
newShapeInfo1[0] = rank;
newShapeInfo1[1] = bS;
newShapeInfo1[2] = inSize;
newShapeInfo1[3] = time;
shape::updateStrides(newShapeInfo1, shape::order(xShapeInfo));
memcpy(newShapeInfo2, newShapeInfo1, shape::shapeInfoByteLength(newShapeInfo1));
return SHAPELIST(newShapeInfo1, newShapeInfo2);
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru_bp, 8, 4, true, 0, 0) {
NDArray<T>* x = INPUT_VARIABLE(0); // X, input 3d tensor [bS x K x N], N - number of time steps, bS - batch size, K - number of features
NDArray<T>* w = INPUT_VARIABLE(1); // W, 2d tensor of weights [3K x K]
NDArray<T>* b = INPUT_VARIABLE(2); // B, row of biases with twice length [1 × 2*K]
NDArray<T>* c0 = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x K] at time t=0
NDArray<T>* c = INPUT_VARIABLE(4); // C, [bS x K x N]
NDArray<T>* inGradCt = INPUT_VARIABLE(5); // [bS x K]
NDArray<T>* inGradH = INPUT_VARIABLE(6); // [bS x K x N]
NDArray<T>* mask = nullptr; // optional, 2d tensor of dropout mask [bS x K]
bool applyMask = false;
if (block.width() > 7) {
mask = INPUT_VARIABLE(7);
applyMask = true;
}
NDArray<T>* gradX = OUTPUT_VARIABLE(0); // [bS x K x N]
NDArray<T>* gradW = OUTPUT_VARIABLE(1); // [bS x 3K x K]
NDArray<T>* gradB = OUTPUT_VARIABLE(2); // [1 x 2K]
NDArray<T>* gradInit = OUTPUT_VARIABLE(3); // [bS x K]
const int bS = x->shapeOf()[0];
const int K = x->shapeOf()[1];
const int N = x->shapeOf()[2]; // N - number of time steps
NDArray<T>* gradBias = new NDArray<T>(x->ordering(), {bS, 2*K, N});
NDArray<T>* gradU = new NDArray<T>(x->ordering(), {bS, 3*K, N});
NDArray<T>* gradHX = new NDArray<T>(x->ordering(), {bS, K, N});
NDArray<T>* gct = new NDArray<T>(c->ordering(), {bS, K});
NDArray<T>* gradTanh = new NDArray<T>(c->ordering(), {bS, K});
NDArray<T>* gradCt = new NDArray<T>(c->ordering(), {bS, K});
NDArray<T>* ftMinus = new NDArray<T>(c->ordering(), {bS, K});
NDArray<T>* rtMinus = new NDArray<T>(c->ordering(), {bS, K});
NDArray<T>* temp1 = new NDArray<T>(c->ordering(), {bS, K});
NDArray<T>* temp2 = new NDArray<T>(c->ordering(), {bS, K});
// x = x * mask
if(applyMask)
x->template applyBroadcast<simdOps::Multiply<T>>({0, 1}, mask, x, nullptr); // apply mask
// multiplication matrix wi = matmul(w,x), U = WX
NDArray<T>* wi = MmulHelper<T>::mmul(w, x, nullptr, (T)1., (T)0.); // U [bS x 3K x N]
NDArray<T>* wiZ = wi->subarray( { NDIndex::all(), NDIndex::interval(0,K), NDIndex::all() } ); // [bS x K x N]
NDArray<T>* wiF = wi->subarray( { NDIndex::all(), NDIndex::interval(K,2*K), NDIndex::all() } ); // forget gate [bS x K x N]
NDArray<T>* wiR = wi->subarray( { NDIndex::all(), NDIndex::interval(2*K,3*K), NDIndex::all() } ); // reset gate [bS x K x N]
NDArray<T>* bF = b->subarray( { NDIndex::all(), NDIndex::interval(0,K) } ); // biases for forget gate [1 x K]
NDArray<T>* bR = b->subarray( { NDIndex::all(), NDIndex::interval(K,2*K)} ); // biases for reset gate [1 x K]
NDArray<T>* gradBF = gradBias->subarray( { NDIndex::all(), NDIndex::interval(0,K), NDIndex::all() } ); // [bS x K x N]
NDArray<T>* gradBR = gradBias->subarray( { NDIndex::all(), NDIndex::interval(K,2*K), NDIndex::all() } ); // [bS x K x N]
NDArray<T>* gradUZ = gradU->subarray( { NDIndex::all(), NDIndex::interval(0,K), NDIndex::all() } ); // [bS x K x N]
NDArray<T>* gradUF = gradU->subarray( { NDIndex::all(), NDIndex::interval(K,2*K), NDIndex::all() } ); // [bS x K x N]
NDArray<T>* gradUR = gradU->subarray( { NDIndex::all(), NDIndex::interval(2*K,3*K), NDIndex::all() } ); // [bS x K x N]
NDArray<T>* xt(nullptr), *zt(nullptr), *ft(nullptr), *rt(nullptr), *ct(nullptr), *inGradHt(nullptr), *gradBFt(nullptr),
*gradBRt(nullptr), *ct_1(nullptr), *gradHXt(nullptr), *gradURt(nullptr), *gradUFt(nullptr), *gradUZt(nullptr);
for (int t = N-1; t >=0 ; --t) {
// initialization
xt = timestep(x, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
zt = timestep(wiZ, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
ft = timestep(wiF, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
rt = timestep(wiR, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
ct = timestep(c, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
inGradHt = timestep(inGradH, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
gradBRt = timestep(gradBR, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
gradBFt = timestep(gradBF, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
gradHXt = timestep(gradHX, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
gradUZt = timestep(gradUZ, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
gradUFt = timestep(gradUF, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
gradURt = timestep(gradUR, t, t+1); // [bS x K x N] -> [bS x K x 1] -> [bS x K]
if(t != 0)
ct_1 = timestep(c, t-1, t); // previous c_{t-1}
else
ct_1 = c0->dup(c0->ordering());
///////////////// forward
// ft = sigmoid(ft + bf), rt = sigmoid(rt + bR)
ft->addRowVector(bF, ft);
rt->addRowVector(bR, rt);
ft->template applyTransform<simdOps::Sigmoid<T>>();
rt->template applyTransform<simdOps::Sigmoid<T>>();
// TODO T val = (activation_type == 1) ? tanh(cur) : ((activation_type == 2) ? reluf(cur) : cur );
ct->template applyTransform<simdOps::Tanh<T>>(gct);
// ftMinus = 1-ft, rtMinus = 1-rt
ft->template applyTransform<simdOps::OneMinus<T>>(ftMinus);
rt->template applyTransform<simdOps::OneMinus<T>>(rtMinus);
///////////////// backward
// bR, *grad_brt_ptr = inGradHt * (g_ct - xt) * (1.0f - rt) * rt;
gct->template applyPairwiseTransform<simdOps::Subtract<T>>(xt, temp1, nullptr); // temp1 = (g_ct - xt)
rtMinus->template applyPairwiseTransform<simdOps::Multiply<T>>(rt, temp2, nullptr); // temp2 = (1.0f - rt) * rt;
temp1->template applyPairwiseTransform<simdOps::Multiply<T>>(temp2, nullptr); // temp1 = (g_ct - xt) * (1.0f - rt) * rt;
inGradHt->template applyPairwiseTransform<simdOps::Multiply<T>>(temp1, gradBRt, nullptr); // = inGradHt * (g_ct - xt) * (1.0f - rt) * rt;
// bF, TODO - tanh
// gradTanh = (1.0f - g_ct * g_ct);
gct->template applyPairwiseTransform<simdOps::Multiply<T>>(gct, gradTanh, nullptr); // gradTanh = g_ct * g_ct
gradTanh->template applyTransform<simdOps::OneMinus<T>>(gradTanh); // gradTanh = (1.0f - g_ct * g_ct)
// gradCt = inGradHt * rt * gradTanh
rt->template applyPairwiseTransform<simdOps::Multiply<T>>(gradTanh, gradCt, nullptr); // gradCt = rt * gradTanh
inGradHt->template applyPairwiseTransform<simdOps::Multiply<T>>(gradCt, gradCt, nullptr); // gradCt = inGradHt * rt * gradTanh
// gradBFt = (gradCt + inGradCt) * (ct_1 - zt) * (1 - ft) * ft;
gradCt->template applyPairwiseTransform<simdOps::Add<T>>(inGradCt, temp1, nullptr); // temp1 = (gradCt + inGradCt)
ct_1->template applyPairwiseTransform<simdOps::Subtract<T>>(zt, temp2, nullptr); // temp2 = (ct_1 - zt)
temp1->template applyPairwiseTransform<simdOps::Multiply<T>>(ftMinus, temp1, nullptr); // temp1 = (gradCt + inGradCt)*(1-ft)
temp1->template applyPairwiseTransform<simdOps::Multiply<T>>(ft, temp1, nullptr); // temp1 = (gradCt + inGradCt)*(1-ft)*ft
temp1->template applyPairwiseTransform<simdOps::Multiply<T>>(temp2, gradBFt, nullptr); // gradBFt = (gradCt + inGradCt) * (ct_1 - zt) * (1 - ft) * ft;
// x_t (highway connection), gradHXt = inGradHt * (1.0f - rt);
inGradHt->template applyPairwiseTransform<simdOps::Multiply<T>>(rtMinus, gradHXt, nullptr);
// U_t, gradUZt = (inGradHt * rt * grad_tanh + inGradCt) * (1.0f - ft);
rt->template applyPairwiseTransform<simdOps::Multiply<T>>(gradTanh, temp1, nullptr); // temp1 = rt * grad_tanh
inGradHt->template applyPairwiseTransform<simdOps::Multiply<T>>(temp1, temp1, nullptr); // temp1 = inGradHt * rt * grad_tanh
temp1->template applyPairwiseTransform<simdOps::Add<T>>(inGradCt, temp1, nullptr); // temp1 = inGradHt * rt * grad_tanh + inGradCt
temp1->template applyPairwiseTransform<simdOps::Multiply<T>>(ftMinus, gradUZt, nullptr); // gradUZt = (inGradHt * rt * grad_tanh + inGradCt) * (1.0f - ft);
gradUFt->assign(gradBFt);
gradURt->assign(gradBRt);
// c_{t-1}, inGradCt = (gradCt + inGradCt) * ft;
gradCt->template applyPairwiseTransform<simdOps::Add<T>>(inGradCt, temp1, nullptr); // temp1 = (gradCt + inGradCt)
temp1->template applyPairwiseTransform<simdOps::Multiply<T>>(ft, inGradCt, nullptr); // inGradCt = (gradCt + inGradCt) * ft;
delete xt; delete zt; delete ft; delete rt; delete ct; delete inGradHt; delete ct_1; delete gradBRt;
delete gradBFt; delete gradHXt; delete gradUZt; delete gradUFt; delete gradURt;
}
// gradInit
gradInit->assign(inGradCt);
// gradX
NDArray<T>* weightsT = w->transpose(); // [K x 3K]
MmulHelper<T>::mmul(weightsT, gradU, gradX, (T)1., (T)0.); // [bS x K x N]
gradX->template applyPairwiseTransform<simdOps::Add<T>>(gradHX, gradX, nullptr); // + grad_highway_x
if(applyMask)
gradX->template applyBroadcast<simdOps::Multiply<T>>({0,1}, mask, gradX, nullptr); // apply mask
// gradB
NDArray<T>* temp3 = gradBias->template reduceAlongDimension<simdOps::Sum<T>>({0,2}, false, true); // [1 x 2K]
gradB->assign(temp3);
// gradW [bS x 3K x K]
x->permutei({0, 2, 1}); // [bS x N x K]
MmulHelper<T>::mmul(gradU, x, gradW, (T)1., (T)0.); // [bS x 3K x K]
delete gradUR; delete gradBF; delete gradUZ; delete gradUF; delete gradBR;
delete gct; delete gradU; delete gradHX; delete wiZ; delete wiF; delete wiR; delete bF; delete bR;
delete temp1; delete temp2; delete temp3; delete gradCt; delete wi;
delete gradTanh; delete ftMinus; delete rtMinus; delete weightsT; delete gradBias;
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(sru_bp) {
auto inShape = inputShape->at(0); // [bS x inSize x time]
auto bS = inShape[1];
auto inSize = inShape[2];
auto time = inShape[3];
char order = (char)(inShape[9]);
Nd4jLong *newShapeInfo1(nullptr), *newShapeInfo2(nullptr), *newShapeInfo3(nullptr), *newShapeInfo4(nullptr);
ALLOCATE(newShapeInfo1, block.getWorkspace(), 10, Nd4jLong);
ALLOCATE(newShapeInfo2, block.getWorkspace(), 10, Nd4jLong);
ALLOCATE(newShapeInfo3, block.getWorkspace(), 8, Nd4jLong);
ALLOCATE(newShapeInfo4, block.getWorkspace(), 8, Nd4jLong);
newShapeInfo1[0] = 3;
newShapeInfo1[1] = bS;
newShapeInfo1[2] = inSize;
newShapeInfo1[3] = time;
shape::updateStrides(newShapeInfo1, order);
newShapeInfo2[0] = 3;
newShapeInfo2[1] = bS;
newShapeInfo2[2] = 3*inSize;
newShapeInfo2[3] = inSize;
shape::updateStrides(newShapeInfo2, order);
newShapeInfo3[0] = 2;
newShapeInfo3[1] = 1;
newShapeInfo3[2] = 2*inSize;
shape::updateStrides(newShapeInfo3, order);
newShapeInfo4[0] = 2;
newShapeInfo4[1] = bS;
newShapeInfo4[2] = inSize;
shape::updateStrides(newShapeInfo4, order);
return SHAPELIST(newShapeInfo1, newShapeInfo2, newShapeInfo3, newShapeInfo4);
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru_bp_logic, 8, 4, true, 0, 0) {
NDArray<T>* x = INPUT_VARIABLE(0); // X, input 3d tensor [bS x inSize x time], time - number of time steps, bS - batch size, inSize - number of features
NDArray<T>* w = INPUT_VARIABLE(1); // W, 2d tensor of weights [3*inSize x inSize]
NDArray<T>* b = INPUT_VARIABLE(2); // B, row of biases with twice length [1 × 2*inSize]
NDArray<T>* c0 = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x inSize] at time t=0
NDArray<T>* c = INPUT_VARIABLE(4); // C, [bS x inSize x time]
NDArray<T>* inGradCt = INPUT_VARIABLE(5); // [bS x inSize]
NDArray<T>* inGradH = INPUT_VARIABLE(6); // [bS x inSize x time]
NDArray<T>* mask = block.width() > 7 ? INPUT_VARIABLE(7) : nullptr; // optional, 2d tensor of dropout mask [bS x inSize]
NDArray<T>* gradX = OUTPUT_VARIABLE(0); // [bS x inSize x time]
NDArray<T>* gradW = OUTPUT_VARIABLE(1); // [bS x 3*inSize x inSize]
NDArray<T>* gradB = OUTPUT_VARIABLE(2); // [2*inSize]
NDArray<T>* gradInit = OUTPUT_VARIABLE(3); // [bS x inSize]
// input shapes validation
const int rank = 3;
REQUIRE_TRUE(x->rankOf() == rank, 0, "SRU_BP operation: wrong rank of input array, expected is %i, but got %i instead !", rank, x->rankOf());
REQUIRE_TRUE(w->rankOf() == rank-1, 0, "SRU_BP operation: wrong rank of weights array, expected is %i, but got %i instead !", rank-1, w->rankOf());
REQUIRE_TRUE(b->rankOf() <= 2, 0, "SRU_BP operation: wrong rank of biases array, expected is <=2, but got %i instead !", b->rankOf());
REQUIRE_TRUE(c0->rankOf() == rank-1, 0, "SRU_BP operation: wrong rank of initial state array, expected is %i, but got %i instead !", rank-1, c0->rankOf());
REQUIRE_TRUE(c->rankOf() == rank, 0, "SRU_BP operation: wrong rank of cell states array, expected is %i, but got %i instead !", rank, c->rankOf());
REQUIRE_TRUE(inGradCt->rankOf() == rank-1, 0, "SRU_BP operation: wrong rank of array of cell state gradient, expected is %i, but got %i instead !", rank-1, inGradCt->rankOf());
REQUIRE_TRUE(inGradH->rankOf() == rank, 0, "SRU_BP operation: wrong rank of array of cell outputs gradients, expected is %i, but got %i instead !", rank, inGradH->rankOf());
if(mask)
REQUIRE_TRUE(mask->rankOf() == rank-1, 0, "SRU_BP operation: wrong rank of mask array, expected is %i, but got %i instead !", rank-1, mask->rankOf());
const int bS = x->shapeOf()[0];
const int inSize = x->shapeOf()[1];
const int time = x->shapeOf()[2]; // time - number of time steps
const std::string wShape = ShapeUtils<T>::shapeAsString(w);
const std::string wCorrectShape = ShapeUtils<T>::shapeAsString({3*inSize, inSize});
// const std::string bShape = ShapeUtils<T>::shapeAsString(b);
// const std::string bCorrectShape = ShapeUtils<T>::shapeAsString({2*inSize});
const std::string c0Shape = ShapeUtils<T>::shapeAsString(c0);
const std::string c0CorrectShape = ShapeUtils<T>::shapeAsString({bS, inSize});
const std::string cShape = ShapeUtils<T>::shapeAsString(c);
const std::string cCorrectShape = ShapeUtils<T>::shapeAsString({bS, inSize, time});
const std::string inGradCtShape = ShapeUtils<T>::shapeAsString(inGradCt);
const std::string inGradCtCorrectShape = ShapeUtils<T>::shapeAsString({bS, inSize});
const std::string inGradHShape = ShapeUtils<T>::shapeAsString(inGradH);
const std::string inGradHCorrectShape = ShapeUtils<T>::shapeAsString({bS, inSize, time});
REQUIRE_TRUE(wShape == wCorrectShape, 0, "SRU_BP operation: wrong shape of weights array, expected is %s, but got %s instead !", wCorrectShape.c_str(), wShape.c_str());
// REQUIRE_TRUE(bShape == bCorrectShape, 0, "SRU_BP operation: wrong shape of biases array, expected is %s, but got %s instead !", bCorrectShape.c_str(), bShape.c_str());
REQUIRE_TRUE(c0Shape == c0CorrectShape, 0, "SRU_BP operation: wrong shape of initial state array, expected is %s, but got %s instead !", c0CorrectShape.c_str(), c0Shape.c_str());
REQUIRE_TRUE(cShape == cCorrectShape, 0, "SRU_BP operation: wrong shape of cell states array, expected is %s, but got %s instead !", cCorrectShape.c_str(), cShape.c_str());
REQUIRE_TRUE(inGradCtShape == inGradCtCorrectShape, 0, "SRU_BP operation: wrong shape of array of cell state gradient, expected is %s, but got %s instead !", inGradCtCorrectShape.c_str(), inGradCtShape.c_str());
REQUIRE_TRUE(inGradHShape == inGradHCorrectShape, 0, "SRU_BP operation: wrong shape of array of cell outputs gradients, expected is %s, but got %s instead !", inGradHCorrectShape.c_str(), inGradHShape.c_str());
if(mask) {
const std::string maskShape = ShapeUtils<T>::shapeAsString(mask);
REQUIRE_TRUE(maskShape == c0CorrectShape, 0, "SRU_BP operation: wrong shape of mask array, expected is %s, but got %s instead !", c0CorrectShape.c_str(), maskShape.c_str());
}
const NDArray<T> bF = (*b)({0,0, 0, inSize}); // biases for forget gate [1 x inSize]
const NDArray<T> bR = (*b)({0,0, inSize,2*inSize}); // biases for reset gate [1 x inSize]
NDArray<T> gradBias(x->ordering(), {bS, 2*inSize, time}, block.getWorkspace());
NDArray<T> gradU (x->ordering(), {bS, 3*inSize, time}, block.getWorkspace());
NDArray<T> gradHX (x->ordering(), {bS, inSize, time}, block.getWorkspace());
NDArray<T> gct (c->ordering(), {bS, inSize}, block.getWorkspace());
// x = x * mask
if(mask)
x->template applyBroadcast<simdOps::Multiply<T>>({0, 1}, mask, x, nullptr); // apply mask
// multiplication matrix wi = matmul(w,x), U = WX
const NDArray<T> wi = mmul(*w, *x); // U [bS x 3K x time]
for (int t = time-1; t >=0 ; --t) {
// initialization
NDArray<T> xt = (*x)({0,0, 0,0, t,t+1}); xt.reshapei(xt.ordering(), {bS, inSize}); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
NDArray<T> zt = wi({0,0, 0, inSize, t,t+1}); zt.reshapei(zt.ordering(), {bS, inSize}); // [bS x 3K x time] -> [bS x inSize x 1] -> [bS x inSize]
NDArray<T> ft = wi({0,0, inSize, 2*inSize, t,t+1}); ft.reshapei(ft.ordering(), {bS, inSize}); // [bS x 3K x time] -> [bS x inSize x 1] -> [bS x inSize]
NDArray<T> rt = wi({0,0, 2*inSize,3*inSize, t,t+1}); rt.reshapei(rt.ordering(), {bS, inSize}); // [bS x 3K x time] -> [bS x inSize x 1] -> [bS x inSize]
NDArray<T> ct = (*c)({0,0, 0,0, t,t+1}); ct.reshapei(ct.ordering(), {bS, inSize}); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
NDArray<T> inGradHt = (*inGradH)({ 0,0, 0,0, t,t+1}); inGradHt.reshapei(xt.ordering(), {bS, inSize}); // [bS x inSize x time] -> [bS x inSize x 1] -> [bS x inSize]
NDArray<T> ct_1 = t ? (*c)({ 0,0, 0,0, t-1,t}) : *c0; // previous c_{t-1}
///////////////// forward
// ft = sigmoid(ft + bf), rt = sigmoid(rt + bR)
ft = _sigmoid(ft + bF);
rt = _sigmoid(rt + bR);
// TODO T val = (activation_type == 1) ? tanh(cur) : ((activation_type == 2) ? reluf(cur) : cur );
ct.template applyTransform<simdOps::Tanh<T>>(&gct);
///////////////// backward
// bR, *grad_brt_ptr = inGradHt * (g_ct - xt) * (1.0f - rt) * rt;
// ftMinus = -ft + (T)1.;
NDArray<T> ftMinus = (T)1. - ft;
NDArray<T> rtMinus = (T)1. - rt;
NDArray<T> gradBRt = inGradHt * (gct - xt) * rtMinus * rt;
// bF, TODO - tanh
NDArray<T> gradTanh = (T)1. - gct * gct;
NDArray<T> gradCt = inGradHt * rt * gradTanh;
NDArray<T> gradBFt = (gradCt + *inGradCt) * (ct_1 - zt) * ftMinus * ft;
// x_t (highway connection), gradHXt = inGradHt * (1.0f - rt);
NDArray<T> gradHXt = inGradHt * rtMinus;
// U_t, gradUZt = (inGradHt * rt * grad_tanh + inGradCt) * (1.0f - ft);
NDArray<T> gradUZt = (inGradHt * rt * gradTanh + *inGradCt) * ftMinus;
// c_{t-1}, inGradCt = (gradCt + inGradCt) * ft;
*inGradCt = (gradCt + *inGradCt) * ft;
// save results
gradBias.assign(gradBFt, {{}, {0, inSize}, {t,t+1}} );
gradBias.assign(gradBRt, {{}, {inSize, 2*inSize}, {t,t+1}} );
gradU.assign(gradUZt, {{}, {0, inSize}, {t,t+1}} );
gradU.assign(gradBFt, {{}, {inSize, 2*inSize}, {t,t+1}} );
gradU.assign(gradBRt, {{}, {2*inSize, 3*inSize}, {t,t+1}} );
gradHX.assign(gradHXt, {{}, { }, {t,t+1}} );
}
// gradInit
gradInit->assign(inGradCt);
// gradX
w->transposei(); // [inSize x 3K]
gradX->assign( mmul(*w, gradU) + gradHX);
if(mask)
gradX->template applyBroadcast<simdOps::Multiply<T>>({0,1}, mask, gradX, nullptr); // apply mask
// gradB
gradBias.template reduceAlongDimension<simdOps::Sum<T>>(gradB, {0,2}, false, true); // [1 x 2K]
// gradW [bS x 3K x inSize]
x->permutei({0, 2, 1}); // [bS x time x inSize]
gradW->assign( mmul(gradU, *x) );
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(sru_bp_logic) {
auto inShape = inputShape->at(0); // [bS x inSize x time]
auto bS = inShape[1];
auto inSize = inShape[2];
auto time = inShape[3];
char order = shape::order(inShape);
Nd4jLong *newShapeInfo1(nullptr), *newShapeInfo2(nullptr), *newShapeInfo3(nullptr), *newShapeInfo4(nullptr);
ALLOCATE(newShapeInfo1, block.getWorkspace(), 10, Nd4jLong);
ALLOCATE(newShapeInfo2, block.getWorkspace(), 10, Nd4jLong);
ALLOCATE(newShapeInfo3, block.getWorkspace(), 8, Nd4jLong);
ALLOCATE(newShapeInfo4, block.getWorkspace(), 8, Nd4jLong);
newShapeInfo1[0] = 3;
newShapeInfo1[1] = bS;
newShapeInfo1[2] = inSize;
newShapeInfo1[3] = time;
shape::updateStrides(newShapeInfo1, order);
newShapeInfo2[0] = 3;
newShapeInfo2[1] = bS;
newShapeInfo2[2] = 3*inSize;
newShapeInfo2[3] = inSize;
shape::updateStrides(newShapeInfo2, order);
newShapeInfo3[0] = 2;
newShapeInfo3[1] = 1;
newShapeInfo3[2] = 2*inSize;
shape::updateStrides(newShapeInfo3, order);
newShapeInfo4[0] = 2;
newShapeInfo4[1] = bS;
newShapeInfo4[2] = inSize;
shape::updateStrides(newShapeInfo4, order);
return SHAPELIST(newShapeInfo1, newShapeInfo2, newShapeInfo3, newShapeInfo4);
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru_bi, 5, 2, true, 0, 0) {
NDArray<T>* x = INPUT_VARIABLE(0); // X, input 3d tensor [time x bS x 2K], time - number of time steps, bS - batch size, inSize - number of features
NDArray<T>* w = INPUT_VARIABLE(1); // W, 2d tensor of weights [2K x 6K]
NDArray<T>* b = INPUT_VARIABLE(2); // B, row of biases with twice length [1 × 4K]
NDArray<T>* c0 = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x 2K] at time t=0
NDArray<T>* mask = nullptr; // optional, 2d tensor of dropout mask [bS x 2K]
bool applyMask = false;
if (block.width() > 4) {
mask = INPUT_VARIABLE(4);
applyMask = true;
}
NDArray<T>* ht = OUTPUT_VARIABLE(0); // h_t, [time x bS x 2K]
NDArray<T>* state = OUTPUT_VARIABLE(1); // c_t, [time x bS x 2K]
const int time = x->shapeOf()[0]; // time - number of time steps
const int bS = x->shapeOf()[1]; // bS - batch size
const int inSize = x->shapeOf()[2] / 2; // inSize - number of features
// x = x * mask
if(applyMask)
x->template applyBroadcast<simdOps::Multiply<T>>({1, 2}, mask, x, nullptr); // apply mask
// U = x * w
NDArray<T> wi = mmul(*x, *w); // U [time x bS x 6K]
const int d2 = 2*inSize;
const int ncols = bS*d2;
const int ncolsWi = 3*ncols;
T* const pInput = x->getBuffer();
T* const pWi = wi.getBuffer();
T* const pBias = b->getBuffer();
T* const pInit = c0->getBuffer();
T* const pMask = mask->getBuffer();
T* const pOutput = ht->getBuffer();
T* const pState = state->getBuffer();
int ncolsRev, ncolsWiRev; // for reverse direction
T maskVal, cur, bF, bR, ft, rt, val;
T *pInputVal(nullptr), *pWiVal(nullptr), *pOutputVal(nullptr), *pStateVal(nullptr);
bool flip = false;
for (int col = 0; col < ncols; ++col) {
flip = (col%d2) >= inSize;
maskVal = applyMask ? *(pMask + col) : (T)1.;
cur = *(pInit + col);
bF = *(pBias + col%d2);
bR = *(pBias + col%d2 + d2);
pWiVal = pWi + 3*col;
pInputVal = pInput + col;
pOutputVal = pOutput + col;
pStateVal = pState + col;
if (flip) {
pInputVal += (time-1)*ncols;
pWiVal += (time-1)*ncolsWi;
pOutputVal += (time-1)*ncols;
pStateVal += (time-1)*ncols;
}
ncolsRev = flip ? -ncols : ncols;
ncolsWiRev = flip ? -ncolsWi : ncolsWi;
for (int t = 0; t < time; ++t) {
// evaluate sigmoids
ft = ((T)1.)/((T)1. + nd4j::math::nd4j_exp<T>(-(*(pWiVal + 1) + bF)));
rt = ((T)1.)/((T)1. + nd4j::math::nd4j_exp<T>(-(*(pWiVal + 2) + bR)));
cur = (cur - *pWiVal)*ft + *pWiVal;
*pStateVal = cur;
val = nd4j::math::nd4j_tanh<T>(cur);
*pOutputVal = (val*maskVal - *pInputVal)*rt + *pInputVal;
pInputVal += ncolsRev;
pWiVal += ncolsWiRev;
pStateVal += ncolsRev;
pOutputVal += ncolsRev;
}
}
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(sru_bi) {
auto inShape = inputShape->at(0); // [time x bS x 2K ]
auto rank = inShape[0]; // = 3
auto size = rank*2 + 4;
auto time = inShape[1];
auto bS = inShape[2];
auto inSize = inShape[3] / 2;
char order = shape::order(inShape);
Nd4jLong* newShapeInfo1 = nullptr;
Nd4jLong* newShapeInfo2 = nullptr;
ALLOCATE(newShapeInfo1, block.getWorkspace(), size, Nd4jLong);
ALLOCATE(newShapeInfo2, block.getWorkspace(), size, Nd4jLong);
newShapeInfo1[0] = rank;
newShapeInfo1[1] = time;
newShapeInfo1[2] = bS;
newShapeInfo1[3] = 2*inSize;
// FIXME: remove memcpy
shape::updateStrides(newShapeInfo1, order);
memcpy(newShapeInfo2, newShapeInfo1, shape::shapeInfoByteLength(newShapeInfo1));
return SHAPELIST(newShapeInfo1, newShapeInfo2);
}
//////////////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(sru_bi_bp, 8, 4, true, 0, 0) {
NDArray<T>* x = INPUT_VARIABLE(0); // X, input 3d tensor [time x bS x 2K], time - number of time steps, bS - batch size, inSize - number of features
NDArray<T>* w = INPUT_VARIABLE(1); // W, 2d tensor of weights [2K x 6K]
NDArray<T>* b = INPUT_VARIABLE(2); // B, row of biases with twice length [1 × 4K]
NDArray<T>* c0 = INPUT_VARIABLE(3); // C_{0}, 2d tensor of initial state [bS x 2K] at time t=0
NDArray<T>* state = INPUT_VARIABLE(4); // C, [time x bS x 2K]
NDArray<T>* inGradCt = INPUT_VARIABLE(5); // [bS x 2K]
NDArray<T>* inGradH = INPUT_VARIABLE(6); // [time x bS x 2K]
NDArray<T>* mask = nullptr; // optional, 2d tensor of dropout mask [bS x 2K]
bool applyMask = false;
if (block.width() > 7) {
mask = INPUT_VARIABLE(7);
applyMask = true;
}
NDArray<T>* gradInput = OUTPUT_VARIABLE(0); // [time x bS x 2K]
NDArray<T>* gradWeights = OUTPUT_VARIABLE(1); // [time x 2K x 6K]
NDArray<T>* gradB = OUTPUT_VARIABLE(2); // [1 x 4K]
NDArray<T>* gradInit = OUTPUT_VARIABLE(3); // [bS x 2K]
const int time = x->shapeOf()[0]; // time - number of time steps
const int bS = x->shapeOf()[1];
const int inSize = x->shapeOf()[2] / 2;
// x = x * mask
if(applyMask)
x->template applyBroadcast<simdOps::Multiply<T>>({1, 2}, mask, x, nullptr); // apply mask
// U = x * w
NDArray<T> wi = mmul(*x, *w); // [time x bS x 2K] * [2K x 6K] = [time x bS x 6K]
NDArray<T> gradBias(x->ordering(), {bS, 4*inSize}, block.getWorkspace());
NDArray<T> gradWi (x->ordering(), {time, bS, 6*inSize}, block.getWorkspace());
const int d2 = 2*inSize;
const int ncols = bS*d2;
const int ncolsWi = 3*ncols;
T* const pInput = x->getBuffer();
T* const pWi = wi.getBuffer();
T* const pBias = b->getBuffer();
T* const pInit = c0->getBuffer();
T* const pMask = mask->getBuffer();
T* const pState = state->getBuffer();
T* const pInGradCt = inGradCt->getBuffer();
T* const pInGradH = inGradH->getBuffer();
T* const pGradWi = gradWi.getBuffer();
T* const pGradInput = gradInput->getBuffer();
T* const pGradBias = gradBias.getBuffer();
T* const pGradInit = gradInit->getBuffer();
int ncolsRev, ncolsWiRev; // for reverse direction
T gbF, gbR, cur, maskVal, bF, bR, ft, rt, val, prevVal, gft, grt, gradSateVal;
bool flip = false;
T *pInputVal(nullptr), *pWiVal(nullptr), *pStateVal(nullptr), *pInGradHVal(nullptr), *pGradWiVal(nullptr), *pGradInputVal(nullptr);
for (int col = 0; col < ncols; ++col) {
gbF = gbR = (T)0.;
flip = (col%d2) >= inSize;
maskVal = applyMask ? *(pMask + col) : (T)1.;
cur = *(pInGradCt + col);
bF = *(pBias + col%d2);
bR = *(pBias + col%d2 + d2);
pWiVal = pWi + 3*col;
pInputVal = pInput + col;
pStateVal = pState + col;
pInGradHVal = pInGradH + col;
pGradWiVal = pGradWi + 3*col;
pGradInputVal = pGradInput + col;
if (!flip) {
pInputVal += (time-1)*ncols;
pWiVal += (time-1)*ncolsWi;
pStateVal += (time-1)*ncols;
pInGradHVal += (time-1)*ncols;
pGradWiVal += (time-1)*ncolsWi;
pGradInputVal += (time-1)*ncols;
}
ncolsRev = flip ? -ncols : ncols;
ncolsWiRev = flip ? -ncolsWi : ncolsWi;
for (int t = 0; t < time; ++t) {
// evaluate sigmoids
ft = ((T)1.)/((T)1. + nd4j::math::nd4j_exp<T>(-(*(pWiVal + 1) + bF)));
rt = ((T)1.)/((T)1. + nd4j::math::nd4j_exp<T>(-(*(pWiVal + 2) + bR)));
val = nd4j::math::nd4j_tanh<T>(*pStateVal);
prevVal = (t < time-1) ? (*(pStateVal - ncolsRev)) : (*(pInit + col));
// grad wrt input
*pGradInputVal = *pInGradHVal - (*pInGradHVal)*rt ;
// grad wrt rt, wiR and bR
grt = (*pInGradHVal) * (val*maskVal - *pInputVal) * (rt - rt*rt);
*(pGradWiVal + 2) = grt;
gbR += grt;
// grad wrt state
gradSateVal = (*pInGradHVal) * maskVal * (rt - rt*val*val) + cur;
// grad wrt wi0
*pGradWiVal = gradSateVal - gradSateVal*ft;
// grad wrt ft, wi1, and bF
gft = gradSateVal * (prevVal - *pWiVal) * (ft - ft*ft);
*(pGradWiVal + 1) = gft;
gbF += gft;
// grad wrt c_previous
cur = gradSateVal * ft;
pInputVal -= ncolsRev;
pWiVal -= ncolsWiRev;
pStateVal -= ncolsRev;
pGradWiVal -= ncolsWiRev;
pGradInputVal -= ncolsRev;
pInGradHVal -= ncolsRev;
}
*(pGradBias + col) = gbF;
*(pGradBias + col + ncols) = gbR;
*(pGradInit + col) = cur;
}
// gradB
gradBias.template reduceAlongDimension<simdOps::Sum<T>>(gradB, {0}, false, true); // [1 x 4K]
// gradWeights
x->permutei({0, 2, 1}); // [time x bS x 2K] -> [time x 2K x bS]
*gradWeights = mmul(*x, gradWi); // [time x 2K x bS ] * [time x bS x 6K] = [time x 2K x 6K]
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(sru_bi_bp) {
auto inShape = inputShape->at(0); // [time x bS x 2K]
auto time = inShape[1];
auto bS = inShape[2];
auto inSize = inShape[3] / 2;
char order = shape::order(inShape);
Nd4jLong *newShapeInfo1(nullptr), *newShapeInfo2(nullptr), *newShapeInfo3(nullptr), *newShapeInfo4(nullptr);
ALLOCATE(newShapeInfo1, block.getWorkspace(), 10, Nd4jLong);
ALLOCATE(newShapeInfo2, block.getWorkspace(), 10, Nd4jLong);
ALLOCATE(newShapeInfo3, block.getWorkspace(), 8, Nd4jLong);
ALLOCATE(newShapeInfo4, block.getWorkspace(), 8, Nd4jLong);
// gradInput
newShapeInfo1[0] = 3;
newShapeInfo1[1] = time;
newShapeInfo1[2] = bS;
newShapeInfo1[3] = 2*inSize;
shape::updateStrides(newShapeInfo1, order);
// gradWeights
newShapeInfo2[0] = 3;
newShapeInfo2[1] = time;
newShapeInfo2[2] = 2*inSize;
newShapeInfo2[3] = 6*inSize;
shape::updateStrides(newShapeInfo2, order);
// gradB
newShapeInfo3[0] = 2;
newShapeInfo3[1] = 1;
newShapeInfo3[2] = 4*inSize;
shape::updateStrides(newShapeInfo3, order);
// gradInit
newShapeInfo4[0] = 2;
newShapeInfo4[1] = bS;
newShapeInfo4[2] = 2*inSize;
shape::updateStrides(newShapeInfo4, order);
return SHAPELIST(newShapeInfo1, newShapeInfo2, newShapeInfo3, newShapeInfo4);
}
}
}
#endif | 53.248515 | 215 | 0.551236 | [
"shape",
"3d"
] |
e74832813946d94e6095ae9f3079a34aa3f4e967 | 52,288 | cc | C++ | third_party/blink/renderer/platform/graphics/canvas_resource.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/platform/graphics/canvas_resource.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/platform/graphics/canvas_resource.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 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/graphics/canvas_resource.h"
#include <utility>
#include "base/callback_helpers.h"
#include "base/memory/read_only_shared_memory_region.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/viz/common/resources/bitmap_allocation.h"
#include "components/viz/common/resources/resource_format_utils.h"
#include "components/viz/common/resources/transferable_resource.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gpu_memory_buffer_manager.h"
#include "gpu/command_buffer/client/raster_interface.h"
#include "gpu/command_buffer/client/shared_image_interface.h"
#include "gpu/command_buffer/client/webgpu_interface.h"
#include "gpu/command_buffer/common/capabilities.h"
#include "gpu/command_buffer/common/gpu_memory_buffer_support.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "gpu/command_buffer/common/sync_token.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/color_space.h"
namespace blink {
CanvasResource::CanvasResource(base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
const SkColorInfo& info)
: owning_thread_ref_(base::PlatformThread::CurrentRef()),
owning_thread_task_runner_(Thread::Current()->GetTaskRunner()),
provider_(std::move(provider)),
info_(info),
filter_quality_(filter_quality) {}
CanvasResource::~CanvasResource() {
#if DCHECK_IS_ON()
DCHECK(did_call_on_destroy_);
#endif
}
void CanvasResource::OnDestroy() {
if (is_cross_thread()) {
// Destroyed on wrong thread. This can happen when the thread of origin was
// torn down, in which case the GPU context owning any underlying resources
// no longer exists.
Abandon();
} else {
if (provider_)
provider_->OnDestroyResource();
TearDown();
}
#if DCHECK_IS_ON()
did_call_on_destroy_ = true;
#endif
}
gpu::InterfaceBase* CanvasResource::InterfaceBase() const {
if (!ContextProviderWrapper())
return nullptr;
return ContextProviderWrapper()->ContextProvider()->InterfaceBase();
}
gpu::gles2::GLES2Interface* CanvasResource::ContextGL() const {
if (!ContextProviderWrapper())
return nullptr;
return ContextProviderWrapper()->ContextProvider()->ContextGL();
}
gpu::raster::RasterInterface* CanvasResource::RasterInterface() const {
if (!ContextProviderWrapper())
return nullptr;
return ContextProviderWrapper()->ContextProvider()->RasterInterface();
}
gpu::webgpu::WebGPUInterface* CanvasResource::WebGPUInterface() const {
if (!ContextProviderWrapper())
return nullptr;
return ContextProviderWrapper()->ContextProvider()->WebGPUInterface();
}
void CanvasResource::WaitSyncToken(const gpu::SyncToken& sync_token) {
if (sync_token.HasData()) {
if (auto* interface_base = InterfaceBase())
interface_base->WaitSyncTokenCHROMIUM(sync_token.GetConstData());
}
}
static void ReleaseFrameResources(
base::WeakPtr<CanvasResourceProvider> resource_provider,
scoped_refptr<CanvasResource> resource,
const gpu::SyncToken& sync_token,
bool lost_resource) {
resource->WaitSyncToken(sync_token);
if (resource_provider)
resource_provider->NotifyTexParamsModified(resource.get());
// TODO(khushalsagar): If multiple readers had access to this resource, losing
// it once should make sure subsequent releases don't try to recycle this
// resource.
if (lost_resource)
resource->NotifyResourceLost();
if (resource_provider && !lost_resource && resource->IsRecycleable())
resource_provider->RecycleResource(std::move(resource));
}
bool CanvasResource::PrepareTransferableResource(
viz::TransferableResource* out_resource,
viz::ReleaseCallback* out_callback,
MailboxSyncMode sync_mode) {
DCHECK(IsValid());
DCHECK(out_callback);
*out_callback =
WTF::Bind(&ReleaseFrameResources, provider_, base::WrapRefCounted(this));
if (!out_resource)
return true;
if (SupportsAcceleratedCompositing())
return PrepareAcceleratedTransferableResource(out_resource, sync_mode);
return PrepareUnacceleratedTransferableResource(out_resource);
}
bool CanvasResource::PrepareAcceleratedTransferableResource(
viz::TransferableResource* out_resource,
MailboxSyncMode sync_mode) {
TRACE_EVENT0("blink",
"CanvasResource::PrepareAcceleratedTransferableResource");
// Gpu compositing is a prerequisite for compositing an accelerated resource
DCHECK(SharedGpuContext::IsGpuCompositingEnabled());
if (!ContextProviderWrapper())
return false;
const gpu::Mailbox& mailbox = GetOrCreateGpuMailbox(sync_mode);
if (mailbox.IsZero())
return false;
*out_resource = viz::TransferableResource::MakeGL(
mailbox, GLFilter(), TextureTarget(), GetSyncToken(), Size(),
IsOverlayCandidate());
out_resource->color_space = GetColorSpace();
out_resource->format = GetResourceFormat();
out_resource->read_lock_fences_enabled = NeedsReadLockFences();
return true;
}
bool CanvasResource::PrepareUnacceleratedTransferableResource(
viz::TransferableResource* out_resource) {
TRACE_EVENT0("blink",
"CanvasResource::PrepareUnacceleratedTransferableResource");
const gpu::Mailbox& mailbox = GetOrCreateGpuMailbox(kVerifiedSyncToken);
if (mailbox.IsZero())
return false;
// For software compositing, the display compositor assumes an N32 format for
// the resource type and completely ignores the format set on the
// TransferableResource. Clients are expected to render in N32 format but use
// RGBA as the tagged format on resources.
*out_resource =
viz::TransferableResource::MakeSoftware(mailbox, Size(), viz::RGBA_8888);
out_resource->color_space = GetColorSpace();
return true;
}
GrDirectContext* CanvasResource::GetGrContext() const {
if (!ContextProviderWrapper())
return nullptr;
return ContextProviderWrapper()->ContextProvider()->GetGrContext();
}
SkImageInfo CanvasResource::CreateSkImageInfo() const {
return SkImageInfo::Make(SkISize::Make(Size().width(), Size().height()),
info_);
}
GLenum CanvasResource::GLFilter() const {
return filter_quality_ == cc::PaintFlags::FilterQuality::kNone ? GL_NEAREST
: GL_LINEAR;
}
viz::ResourceFormat CanvasResource::GetResourceFormat() const {
return viz::SkColorTypeToResourceFormat(info_.colorType());
}
gfx::BufferFormat CanvasResource::GetBufferFormat() const {
return viz::BufferFormat(GetResourceFormat());
}
gfx::ColorSpace CanvasResource::GetColorSpace() const {
SkColorSpace* color_space = info_.colorSpace();
return color_space ? gfx::ColorSpace(*color_space)
: gfx::ColorSpace::CreateSRGB();
}
// CanvasResourceSharedBitmap
//==============================================================================
CanvasResourceSharedBitmap::CanvasResourceSharedBitmap(
const SkImageInfo& info,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality)
: CanvasResource(std::move(provider), filter_quality, info.colorInfo()),
size_(info.width(), info.height()) {
// Software compositing lazily uses RGBA_8888 as the resource format
// everywhere but the content is expected to be rendered in N32 format.
base::MappedReadOnlyRegion shm =
viz::bitmap_allocation::AllocateSharedBitmap(Size(), viz::RGBA_8888);
if (!shm.IsValid())
return;
shared_mapping_ = std::move(shm.mapping);
shared_bitmap_id_ = viz::SharedBitmap::GenerateId();
CanvasResourceDispatcher* resource_dispatcher =
Provider() ? Provider()->ResourceDispatcher() : nullptr;
if (resource_dispatcher) {
resource_dispatcher->DidAllocateSharedBitmap(std::move(shm.region),
shared_bitmap_id_);
}
}
CanvasResourceSharedBitmap::~CanvasResourceSharedBitmap() {
OnDestroy();
}
bool CanvasResourceSharedBitmap::IsValid() const {
return shared_mapping_.IsValid();
}
gfx::Size CanvasResourceSharedBitmap::Size() const {
return size_;
}
scoped_refptr<StaticBitmapImage> CanvasResourceSharedBitmap::Bitmap() {
if (!IsValid())
return nullptr;
// Construct an SkImage that references the shared memory buffer.
// The release callback holds a reference to |this| to ensure that the
// canvas resource that owns the shared memory stays alive at least until
// the SkImage is destroyed.
SkImageInfo image_info = SkImageInfo::Make(
SkISize::Make(Size().width(), Size().height()), GetSkColorInfo());
SkPixmap pixmap(image_info, shared_mapping_.memory(),
image_info.minRowBytes());
AddRef();
sk_sp<SkImage> sk_image = SkImage::MakeFromRaster(
pixmap,
[](const void*, SkImage::ReleaseContext resource_to_unref) {
static_cast<CanvasResourceSharedBitmap*>(resource_to_unref)->Release();
},
this);
auto image = UnacceleratedStaticBitmapImage::Create(sk_image);
image->SetOriginClean(is_origin_clean_);
return image;
}
scoped_refptr<CanvasResourceSharedBitmap> CanvasResourceSharedBitmap::Create(
const SkImageInfo& info,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality) {
auto resource = AdoptRef(new CanvasResourceSharedBitmap(
info, std::move(provider), filter_quality));
return resource->IsValid() ? resource : nullptr;
}
void CanvasResourceSharedBitmap::TearDown() {
CanvasResourceDispatcher* resource_dispatcher =
Provider() ? Provider()->ResourceDispatcher() : nullptr;
if (resource_dispatcher && !shared_bitmap_id_.IsZero())
resource_dispatcher->DidDeleteSharedBitmap(shared_bitmap_id_);
shared_mapping_ = {};
}
void CanvasResourceSharedBitmap::Abandon() {
shared_mapping_ = {};
}
void CanvasResourceSharedBitmap::NotifyResourceLost() {
// Release our reference to the shared memory mapping since the resource can
// no longer be safely recycled and this memory is needed for copy-on-write.
shared_mapping_ = {};
}
const gpu::Mailbox& CanvasResourceSharedBitmap::GetOrCreateGpuMailbox(
MailboxSyncMode sync_mode) {
return shared_bitmap_id_;
}
bool CanvasResourceSharedBitmap::HasGpuMailbox() const {
return !shared_bitmap_id_.IsZero();
}
void CanvasResourceSharedBitmap::TakeSkImage(sk_sp<SkImage> image) {
SkImageInfo image_info = SkImageInfo::Make(
SkISize::Make(Size().width(), Size().height()), GetSkColorInfo());
bool read_pixels_successful = image->readPixels(
image_info, shared_mapping_.memory(), image_info.minRowBytes(), 0, 0);
DCHECK(read_pixels_successful);
}
// CanvasResourceSharedImage
//==============================================================================
CanvasResourceSharedImage::CanvasResourceSharedImage(
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
const SkColorInfo& info)
: CanvasResource(provider, filter_quality, info) {}
// CanvasResourceRasterSharedImage
//==============================================================================
CanvasResourceRasterSharedImage::CanvasResourceRasterSharedImage(
const SkImageInfo& info,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
bool is_origin_top_left,
bool is_accelerated,
uint32_t shared_image_usage_flags)
: CanvasResourceSharedImage(std::move(provider),
filter_quality,
info.colorInfo()),
context_provider_wrapper_(std::move(context_provider_wrapper)),
size_(info.width(), info.height()),
is_origin_top_left_(is_origin_top_left),
is_accelerated_(is_accelerated),
#if defined(OS_MAC)
// On Mac, WebGPU usage is always backed by an IOSurface which should
// should also use the GL_TEXTURE_RECTANGLE target instead of
// GL_TEXTURE_2D. Setting |is_overlay_candidate_| both allows overlays,
// and causes |texture_target_| to take the value returned from
// gpu::GetBufferTextureTarget.
is_overlay_candidate_(
shared_image_usage_flags &
(gpu::SHARED_IMAGE_USAGE_SCANOUT | gpu::SHARED_IMAGE_USAGE_WEBGPU)),
#else
is_overlay_candidate_(shared_image_usage_flags &
gpu::SHARED_IMAGE_USAGE_SCANOUT),
#endif
texture_target_(is_overlay_candidate_
? gpu::GetBufferTextureTarget(
gfx::BufferUsage::SCANOUT,
GetBufferFormat(),
context_provider_wrapper_->ContextProvider()
->GetCapabilities())
: GL_TEXTURE_2D),
use_oop_rasterization_(is_accelerated &&
context_provider_wrapper_->ContextProvider()
->GetCapabilities()
.supports_oop_raster) {
auto* gpu_memory_buffer_manager =
Platform::Current()->GetGpuMemoryBufferManager();
if (!is_accelerated_) {
DCHECK(gpu_memory_buffer_manager);
DCHECK(shared_image_usage_flags & gpu::SHARED_IMAGE_USAGE_DISPLAY);
gpu_memory_buffer_ = gpu_memory_buffer_manager->CreateGpuMemoryBuffer(
Size(), GetBufferFormat(), gfx::BufferUsage::SCANOUT_CPU_READ_WRITE,
gpu::kNullSurfaceHandle, nullptr);
if (!gpu_memory_buffer_)
return;
gpu_memory_buffer_->SetColorSpace(GetColorSpace());
}
auto* shared_image_interface =
context_provider_wrapper_->ContextProvider()->SharedImageInterface();
DCHECK(shared_image_interface);
// The GLES2 flag is needed for rendering via GL using a GrContext.
if (use_oop_rasterization_) {
// TODO(crbug.com/1050845): Ideally we'd like to get rid of the GLES2 usage
// flags. Adding them for now to isolate other errors/prepare for field
// trials.
shared_image_usage_flags = shared_image_usage_flags |
gpu::SHARED_IMAGE_USAGE_RASTER |
gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION |
gpu::SHARED_IMAGE_USAGE_GLES2 |
gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT;
} else {
shared_image_usage_flags = shared_image_usage_flags |
gpu::SHARED_IMAGE_USAGE_GLES2 |
gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT;
}
GrSurfaceOrigin surface_origin = is_origin_top_left_
? kTopLeft_GrSurfaceOrigin
: kBottomLeft_GrSurfaceOrigin;
SkAlphaType surface_alpha_type = GetSkColorInfo().alphaType();
gpu::Mailbox shared_image_mailbox;
if (gpu_memory_buffer_) {
shared_image_mailbox = shared_image_interface->CreateSharedImage(
gpu_memory_buffer_.get(), gpu_memory_buffer_manager, GetColorSpace(),
surface_origin, surface_alpha_type, shared_image_usage_flags);
} else {
shared_image_mailbox = shared_image_interface->CreateSharedImage(
GetResourceFormat(), Size(), GetColorSpace(), surface_origin,
surface_alpha_type, shared_image_usage_flags, gpu::kNullSurfaceHandle);
}
// Wait for the mailbox to be ready to be used.
WaitSyncToken(shared_image_interface->GenUnverifiedSyncToken());
auto* raster_interface = RasterInterface();
DCHECK(raster_interface);
owning_thread_data().shared_image_mailbox = shared_image_mailbox;
if (use_oop_rasterization_)
return;
// For the non-accelerated case, writes are done on the CPU. So we don't need
// a texture for reads or writes.
if (!is_accelerated_)
return;
owning_thread_data().texture_id_for_read_access =
raster_interface->CreateAndConsumeForGpuRaster(shared_image_mailbox);
if (shared_image_usage_flags &
gpu::SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE) {
owning_thread_data().texture_id_for_write_access =
raster_interface->CreateAndConsumeForGpuRaster(shared_image_mailbox);
} else {
owning_thread_data().texture_id_for_write_access =
owning_thread_data().texture_id_for_read_access;
}
}
scoped_refptr<CanvasResourceRasterSharedImage>
CanvasResourceRasterSharedImage::Create(
const SkImageInfo& info,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
bool is_origin_top_left,
bool is_accelerated,
uint32_t shared_image_usage_flags) {
TRACE_EVENT0("blink", "CanvasResourceRasterSharedImage::Create");
auto resource = base::AdoptRef(new CanvasResourceRasterSharedImage(
info, std::move(context_provider_wrapper), std::move(provider),
filter_quality, is_origin_top_left, is_accelerated,
shared_image_usage_flags));
return resource->IsValid() ? resource : nullptr;
}
bool CanvasResourceRasterSharedImage::IsValid() const {
return !mailbox().IsZero();
}
void CanvasResourceRasterSharedImage::BeginReadAccess() {
RasterInterface()->BeginSharedImageAccessDirectCHROMIUM(
GetTextureIdForReadAccess(), GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM);
}
void CanvasResourceRasterSharedImage::EndReadAccess() {
RasterInterface()->EndSharedImageAccessDirectCHROMIUM(
GetTextureIdForReadAccess());
}
void CanvasResourceRasterSharedImage::BeginWriteAccess() {
RasterInterface()->BeginSharedImageAccessDirectCHROMIUM(
GetTextureIdForWriteAccess(),
GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM);
}
void CanvasResourceRasterSharedImage::EndWriteAccess() {
RasterInterface()->EndSharedImageAccessDirectCHROMIUM(
GetTextureIdForWriteAccess());
}
GrBackendTexture CanvasResourceRasterSharedImage::CreateGrTexture() const {
GrGLTextureInfo texture_info = {};
texture_info.fID = GetTextureIdForWriteAccess();
texture_info.fTarget = TextureTarget();
texture_info.fFormat = viz::TextureStorageFormat(GetResourceFormat());
return GrBackendTexture(Size().width(), Size().height(), GrMipMapped::kNo,
texture_info);
}
CanvasResourceRasterSharedImage::~CanvasResourceRasterSharedImage() {
OnDestroy();
}
void CanvasResourceRasterSharedImage::TearDown() {
DCHECK(!is_cross_thread());
// The context deletes all shared images on destruction which means no
// cleanup is needed if the context was lost.
if (ContextProviderWrapper()) {
auto* raster_interface = RasterInterface();
auto* shared_image_interface =
ContextProviderWrapper()->ContextProvider()->SharedImageInterface();
if (raster_interface && shared_image_interface) {
gpu::SyncToken shared_image_sync_token;
raster_interface->GenUnverifiedSyncTokenCHROMIUM(
shared_image_sync_token.GetData());
shared_image_interface->DestroySharedImage(shared_image_sync_token,
mailbox());
}
if (raster_interface) {
if (owning_thread_data().texture_id_for_read_access) {
raster_interface->DeleteGpuRasterTexture(
owning_thread_data().texture_id_for_read_access);
}
if (owning_thread_data().texture_id_for_write_access &&
owning_thread_data().texture_id_for_write_access !=
owning_thread_data().texture_id_for_read_access) {
raster_interface->DeleteGpuRasterTexture(
owning_thread_data().texture_id_for_write_access);
}
}
}
owning_thread_data().texture_id_for_read_access = 0u;
owning_thread_data().texture_id_for_write_access = 0u;
}
void CanvasResourceRasterSharedImage::Abandon() {
// Called when the owning thread has been torn down which will destroy the
// context on which the shared image was created so no cleanup is necessary.
}
void CanvasResourceRasterSharedImage::WillDraw() {
DCHECK(!is_cross_thread())
<< "Write access is only allowed on the owning thread";
// Sync token for software mode is generated from SharedImageInterface each
// time the GMB is updated.
if (!is_accelerated_)
return;
owning_thread_data().mailbox_needs_new_sync_token = true;
}
// static
void CanvasResourceRasterSharedImage::OnBitmapImageDestroyed(
scoped_refptr<CanvasResourceRasterSharedImage> resource,
bool has_read_ref_on_texture,
const gpu::SyncToken& sync_token,
bool is_lost) {
DCHECK(!resource->is_cross_thread());
if (has_read_ref_on_texture) {
DCHECK(!resource->use_oop_rasterization_);
DCHECK_GT(resource->owning_thread_data().bitmap_image_read_refs, 0u);
resource->owning_thread_data().bitmap_image_read_refs--;
if (resource->owning_thread_data().bitmap_image_read_refs == 0u &&
resource->RasterInterface()) {
resource->RasterInterface()->EndSharedImageAccessDirectCHROMIUM(
resource->owning_thread_data().texture_id_for_read_access);
}
}
auto weak_provider = resource->WeakProvider();
ReleaseFrameResources(std::move(weak_provider), std::move(resource),
sync_token, is_lost);
}
void CanvasResourceRasterSharedImage::Transfer() {
if (is_cross_thread() || !ContextProviderWrapper())
return;
// TODO(khushalsagar): This is for consistency with MailboxTextureHolder
// transfer path. Its unclear why the verification can not be deferred until
// the resource needs to be transferred cross-process.
owning_thread_data().mailbox_sync_mode = kVerifiedSyncToken;
GetSyncToken();
}
scoped_refptr<StaticBitmapImage> CanvasResourceRasterSharedImage::Bitmap() {
TRACE_EVENT0("blink", "CanvasResourceRasterSharedImage::Bitmap");
SkImageInfo image_info = CreateSkImageInfo();
if (!is_accelerated_) {
if (!gpu_memory_buffer_->Map())
return nullptr;
SkPixmap pixmap(CreateSkImageInfo(), gpu_memory_buffer_->memory(0),
gpu_memory_buffer_->stride(0));
auto sk_image = SkImage::MakeRasterCopy(pixmap);
gpu_memory_buffer_->Unmap();
return sk_image ? UnacceleratedStaticBitmapImage::Create(sk_image)
: nullptr;
}
// In order to avoid creating multiple representations for this shared image
// on the same context, the AcceleratedStaticBitmapImage uses the texture id
// of the resource here. We keep a count of pending shared image releases to
// correctly scope the read lock for this texture.
// If this resource is accessed across threads, or the
// AcceleratedStaticBitmapImage is accessed on a different thread after being
// created here, the image will create a new representation from the mailbox
// rather than referring to the shared image's texture ID if it was provided
// below.
const bool has_read_ref_on_texture =
!is_cross_thread() && !use_oop_rasterization_;
GLuint texture_id_for_image = 0u;
if (has_read_ref_on_texture) {
texture_id_for_image = owning_thread_data().texture_id_for_read_access;
owning_thread_data().bitmap_image_read_refs++;
if (owning_thread_data().bitmap_image_read_refs == 1u &&
RasterInterface()) {
RasterInterface()->BeginSharedImageAccessDirectCHROMIUM(
texture_id_for_image, GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM);
}
}
// The |release_callback| keeps a ref on this resource to ensure the backing
// shared image is kept alive until the lifetime of the image.
// Note that the code in CanvasResourceProvider::RecycleResource also uses the
// ref-count on the resource as a proxy for a read lock to allow recycling the
// resource once all refs have been released.
auto release_callback =
base::BindOnce(&OnBitmapImageDestroyed,
scoped_refptr<CanvasResourceRasterSharedImage>(this),
has_read_ref_on_texture);
scoped_refptr<StaticBitmapImage> image;
// If its cross thread, then the sync token was already verified.
if (!is_cross_thread()) {
owning_thread_data().mailbox_sync_mode = kUnverifiedSyncToken;
}
image = AcceleratedStaticBitmapImage::CreateFromCanvasMailbox(
mailbox(), GetSyncToken(), texture_id_for_image, image_info, texture_target_,
is_origin_top_left_, context_provider_wrapper_, owning_thread_ref_,
owning_thread_task_runner_, std::move(release_callback));
DCHECK(image);
return image;
}
void CanvasResourceRasterSharedImage::CopyRenderingResultsToGpuMemoryBuffer(
const sk_sp<SkImage>& image) {
DCHECK(!is_cross_thread());
if (!ContextProviderWrapper() || !gpu_memory_buffer_->Map())
return;
auto surface = SkSurface::MakeRasterDirect(CreateSkImageInfo(),
gpu_memory_buffer_->memory(0),
gpu_memory_buffer_->stride(0));
surface->getCanvas()->drawImage(image, 0, 0);
auto* sii =
ContextProviderWrapper()->ContextProvider()->SharedImageInterface();
gpu_memory_buffer_->Unmap();
sii->UpdateSharedImage(gpu::SyncToken(), mailbox());
owning_thread_data().sync_token = sii->GenUnverifiedSyncToken();
}
const gpu::Mailbox& CanvasResourceRasterSharedImage::GetOrCreateGpuMailbox(
MailboxSyncMode sync_mode) {
if (!is_cross_thread()) {
owning_thread_data().mailbox_sync_mode = sync_mode;
}
return mailbox();
}
bool CanvasResourceRasterSharedImage::HasGpuMailbox() const {
return !mailbox().IsZero();
}
const gpu::SyncToken CanvasResourceRasterSharedImage::GetSyncToken() {
if (is_cross_thread()) {
// Sync token should be generated at Transfer time, which must always be
// called before cross-thread usage. And since we don't allow writes on
// another thread, the sync token generated at Transfer time shouldn't
// have been invalidated.
DCHECK(!mailbox_needs_new_sync_token());
DCHECK(sync_token().verified_flush());
return sync_token();
}
if (mailbox_needs_new_sync_token()) {
auto* raster_interface = RasterInterface();
DCHECK(raster_interface); // caller should already have early exited if
// !raster_interface.
raster_interface->GenUnverifiedSyncTokenCHROMIUM(
owning_thread_data().sync_token.GetData());
owning_thread_data().mailbox_needs_new_sync_token = false;
}
if (owning_thread_data().mailbox_sync_mode == kVerifiedSyncToken &&
!owning_thread_data().sync_token.verified_flush()) {
int8_t* token_data = owning_thread_data().sync_token.GetData();
auto* raster_interface = RasterInterface();
raster_interface->ShallowFlushCHROMIUM();
raster_interface->VerifySyncTokensCHROMIUM(&token_data, 1);
owning_thread_data().sync_token.SetVerifyFlush();
}
return sync_token();
}
void CanvasResourceRasterSharedImage::NotifyResourceLost() {
owning_thread_data().is_lost = true;
if (WeakProvider())
Provider()->NotifyTexParamsModified(this);
}
base::WeakPtr<WebGraphicsContext3DProviderWrapper>
CanvasResourceRasterSharedImage::ContextProviderWrapper() const {
DCHECK(!is_cross_thread());
return context_provider_wrapper_;
}
// CanvasResourceSkiaDawnSharedImage
//==============================================================================
#if BUILDFLAG(SKIA_USE_DAWN)
CanvasResourceSkiaDawnSharedImage::CanvasResourceSkiaDawnSharedImage(
const SkImageInfo& info,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
bool is_origin_top_left,
uint32_t shared_image_usage_flags)
: CanvasResourceSharedImage(std::move(provider),
filter_quality,
info.colorInfo()),
context_provider_wrapper_(std::move(context_provider_wrapper)),
size_(info.width(), info.height()),
owning_thread_task_runner_(Thread::Current()->GetTaskRunner()),
is_origin_top_left_(is_origin_top_left) {
if (!context_provider_wrapper_)
return;
auto* shared_image_interface =
context_provider_wrapper_->ContextProvider()->SharedImageInterface();
DCHECK(shared_image_interface);
shared_image_usage_flags =
shared_image_usage_flags | gpu::SHARED_IMAGE_USAGE_WEBGPU;
GrSurfaceOrigin surface_origin = is_origin_top_left_
? kTopLeft_GrSurfaceOrigin
: kBottomLeft_GrSurfaceOrigin;
gpu::Mailbox shared_image_mailbox;
shared_image_mailbox = shared_image_interface->CreateSharedImage(
GetResourceFormat(), size_, GetColorSpace(), surface_origin,
GetSkColorInfo().alphaType(), shared_image_usage_flags,
gpu::kNullSurfaceHandle);
auto* webgpu = WebGPUInterface();
// Wait for the mailbox to be ready to be used.
WaitSyncToken(shared_image_interface->GenUnverifiedSyncToken());
// Ensure Dawn wire is initialized.
webgpu->RequestAdapterAsync(gpu::webgpu::PowerPreference::kHighPerformance,
/*force_fallback_adapter*/ false,
base::DoNothing());
WGPUDeviceProperties properties{};
webgpu->RequestDeviceAsync(0, properties, base::DoNothing());
owning_thread_data().shared_image_mailbox = shared_image_mailbox;
}
scoped_refptr<CanvasResourceSkiaDawnSharedImage>
CanvasResourceSkiaDawnSharedImage::Create(
const SkImageInfo& info,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
bool is_origin_top_left,
uint32_t shared_image_usage_flags) {
TRACE_EVENT0("blink", "CanvasResourceSkiaDawnSharedImage::Create");
auto resource = base::AdoptRef(new CanvasResourceSkiaDawnSharedImage(
info, std::move(context_provider_wrapper), std::move(provider),
filter_quality, is_origin_top_left, shared_image_usage_flags));
return resource->IsValid() ? resource : nullptr;
}
bool CanvasResourceSkiaDawnSharedImage::IsValid() const {
return !mailbox().IsZero();
}
GLenum CanvasResourceSkiaDawnSharedImage::TextureTarget() const {
#if defined(OS_MAC)
return GL_TEXTURE_RECTANGLE_ARB;
#else
return GL_TEXTURE_2D;
#endif
}
CanvasResourceSkiaDawnSharedImage::~CanvasResourceSkiaDawnSharedImage() {
OnDestroy();
}
void CanvasResourceSkiaDawnSharedImage::TearDown() {
DCHECK(!is_cross_thread());
if (ContextProviderWrapper()) {
auto* webgpu = WebGPUInterface();
auto* shared_image_interface =
ContextProviderWrapper()->ContextProvider()->SharedImageInterface();
if (webgpu && shared_image_interface) {
gpu::SyncToken shared_image_sync_token;
webgpu->GenUnverifiedSyncTokenCHROMIUM(shared_image_sync_token.GetData());
shared_image_interface->DestroySharedImage(shared_image_sync_token,
mailbox());
}
}
}
void CanvasResourceSkiaDawnSharedImage::Abandon() {
if (auto context_provider = SharedGpuContext::ContextProviderWrapper()) {
auto* sii = context_provider->ContextProvider()->SharedImageInterface();
if (sii)
sii->DestroySharedImage(gpu::SyncToken(), mailbox());
}
}
void CanvasResourceSkiaDawnSharedImage::WillDraw() {
DCHECK(!is_cross_thread())
<< "Write access is only allowed on the owning thread";
owning_thread_data().mailbox_needs_new_sync_token = true;
}
void CanvasResourceSkiaDawnSharedImage::BeginAccess() {
auto* webgpu = WebGPUInterface();
// TODO(senorblanco): create an actual passed-in Device, rather than this
// default hacky one. http://crbug.com/1078775
gpu::webgpu::ReservedTexture reservation =
webgpu->ReserveTexture(webgpu->DeprecatedEnsureDefaultDeviceSync());
DCHECK(reservation.texture);
owning_thread_data().texture = wgpu::Texture(reservation.texture);
owning_thread_data().id = reservation.id;
owning_thread_data().generation = reservation.generation;
webgpu->FlushCommands();
webgpu->AssociateMailbox(
reservation.deviceId, reservation.deviceGeneration,
owning_thread_data().id, owning_thread_data().generation,
WGPUTextureUsage_TextureBinding | WGPUTextureUsage_RenderAttachment,
reinterpret_cast<GLbyte*>(&owning_thread_data().shared_image_mailbox));
}
void CanvasResourceSkiaDawnSharedImage::EndAccess() {
auto* webgpu = WebGPUInterface();
webgpu->FlushCommands();
webgpu->DissociateMailbox(owning_thread_data().id,
owning_thread_data().generation);
owning_thread_data().texture = nullptr;
owning_thread_data().id = 0;
owning_thread_data().generation = 0;
}
GrBackendTexture CanvasResourceSkiaDawnSharedImage::CreateGrTexture() const {
GrDawnTextureInfo info = {};
info.fTexture = texture();
#if defined(OS_MAC)
info.fFormat = wgpu::TextureFormat::BGRA8Unorm;
#else
info.fFormat = wgpu::TextureFormat::RGBA8Unorm;
#endif
info.fLevelCount = 1;
return GrBackendTexture(Size().width(), Size().height(), info);
}
void CanvasResourceSkiaDawnSharedImage::CopyRenderingResultsToGpuMemoryBuffer(
const sk_sp<SkImage>&) {
DCHECK(false);
}
// static
void CanvasResourceSkiaDawnSharedImage::OnBitmapImageDestroyed(
scoped_refptr<CanvasResourceSkiaDawnSharedImage> resource,
bool has_read_ref_on_texture,
const gpu::SyncToken& sync_token,
bool is_lost) {
if (resource->is_cross_thread()) {
auto& task_runner = *resource->owning_thread_task_runner_;
PostCrossThreadTask(
task_runner, FROM_HERE,
CrossThreadBindOnce(
&CanvasResourceSkiaDawnSharedImage::OnBitmapImageDestroyed,
std::move(resource), has_read_ref_on_texture, sync_token, is_lost));
return;
}
if (has_read_ref_on_texture) {
DCHECK_GT(resource->owning_thread_data().bitmap_image_read_refs, 0u);
resource->owning_thread_data().bitmap_image_read_refs--;
}
// The StaticBitmapImage is used for readbacks which may modify the texture
// params. Note that this is racy, since the modification and resetting of the
// param is not atomic so the display may draw with incorrect params, but its
// a good enough fix for now.
resource->owning_thread_data().needs_gl_filter_reset = true;
auto weak_provider = resource->WeakProvider();
ReleaseFrameResources(std::move(weak_provider), std::move(resource),
sync_token, is_lost);
}
void CanvasResourceSkiaDawnSharedImage::Transfer() {
if (is_cross_thread() || !ContextProviderWrapper())
return;
// TODO(khushalsagar): This is for consistency with MailboxTextureHolder
// transfer path. Its unclear why the verification can not be deferred until
// the resource needs to be transferred cross-process.
owning_thread_data().mailbox_sync_mode = kVerifiedSyncToken;
GetSyncToken();
}
scoped_refptr<StaticBitmapImage> CanvasResourceSkiaDawnSharedImage::Bitmap() {
TRACE_EVENT0("blink", "CanvasResourceSkiaDawnSharedImage::Bitmap");
SkImageInfo image_info = CreateSkImageInfo();
// In order to avoid creating multiple representations for this shared image
// on the same context, the AcceleratedStaticBitmapImage uses the texture id
// of the resource here. We keep a count of pending shared image releases to
// correctly scope the read lock for this texture.
// If this resource is accessed across threads, or the
// AcceleratedStaticBitmapImage is accessed on a different thread after being
// created here, the image will create a new representation from the mailbox
// rather than referring to the shared image's texture ID if it was provided
// below.
const bool has_read_ref_on_texture = !is_cross_thread();
if (has_read_ref_on_texture) {
owning_thread_data().bitmap_image_read_refs++;
if (owning_thread_data().bitmap_image_read_refs == 1u) {
BeginAccess();
}
}
// The |release_callback| keeps a ref on this resource to ensure the backing
// shared image is kept alive until the lifetime of the image.
// Note that the code in CanvasResourceProvider::RecycleResource also uses the
// ref-count on the resource as a proxy for a read lock to allow recycling the
// resource once all refs have been released.
auto release_callback =
base::BindOnce(&OnBitmapImageDestroyed,
scoped_refptr<CanvasResourceSkiaDawnSharedImage>(this),
has_read_ref_on_texture);
scoped_refptr<StaticBitmapImage> image;
// If its cross thread, then the sync token was already verified.
if (!is_cross_thread()) {
owning_thread_data().mailbox_sync_mode = kUnverifiedSyncToken;
}
image = AcceleratedStaticBitmapImage::CreateFromCanvasMailbox(
mailbox(), GetSyncToken(), 0, image_info, GL_TEXTURE_2D,
is_origin_top_left_, context_provider_wrapper_, owning_thread_ref_,
owning_thread_task_runner_, std::move(release_callback));
DCHECK(image);
return image;
}
const gpu::Mailbox& CanvasResourceSkiaDawnSharedImage::GetOrCreateGpuMailbox(
MailboxSyncMode sync_mode) {
if (!is_cross_thread()) {
owning_thread_data().mailbox_sync_mode = sync_mode;
}
return mailbox();
}
bool CanvasResourceSkiaDawnSharedImage::HasGpuMailbox() const {
return !mailbox().IsZero();
}
const gpu::SyncToken CanvasResourceSkiaDawnSharedImage::GetSyncToken() {
if (is_cross_thread()) {
// Sync token should be generated at Transfer time, which must always be
// called before cross-thread usage. And since we don't allow writes on
// another thread, the sync token generated at Transfer time shouldn't
// have been invalidated.
DCHECK(!mailbox_needs_new_sync_token());
DCHECK(sync_token().verified_flush());
return sync_token();
}
if (mailbox_needs_new_sync_token()) {
auto* webgpu = WebGPUInterface();
DCHECK(webgpu); // caller should already have early exited if !gl.
webgpu->GenUnverifiedSyncTokenCHROMIUM(
owning_thread_data().sync_token.GetData());
owning_thread_data().mailbox_needs_new_sync_token = false;
}
if (owning_thread_data().mailbox_sync_mode == kVerifiedSyncToken &&
!owning_thread_data().sync_token.verified_flush()) {
int8_t* token_data = owning_thread_data().sync_token.GetData();
auto* webgpu = WebGPUInterface();
webgpu->VerifySyncTokensCHROMIUM(&token_data, 1);
owning_thread_data().sync_token.SetVerifyFlush();
}
return sync_token();
}
void CanvasResourceSkiaDawnSharedImage::NotifyResourceLost() {
owning_thread_data().is_lost = true;
// Since the texture params are in an unknown state, reset the cached tex
// params state for the resource.
owning_thread_data().needs_gl_filter_reset = true;
if (WeakProvider())
Provider()->NotifyTexParamsModified(this);
}
base::WeakPtr<WebGraphicsContext3DProviderWrapper>
CanvasResourceSkiaDawnSharedImage::ContextProviderWrapper() const {
DCHECK(!is_cross_thread());
return context_provider_wrapper_;
}
#endif
// ExternalCanvasResource
//==============================================================================
scoped_refptr<ExternalCanvasResource> ExternalCanvasResource::Create(
const gpu::Mailbox& mailbox,
viz::ReleaseCallback release_callback,
gpu::SyncToken sync_token,
const SkImageInfo& info,
GLenum texture_target,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
bool is_origin_top_left,
bool is_overlay_candidate) {
TRACE_EVENT0("blink", "ExternalCanvasResource::Create");
auto resource = AdoptRef(new ExternalCanvasResource(
mailbox, std::move(release_callback), sync_token, info, texture_target,
std::move(context_provider_wrapper), std::move(provider), filter_quality,
is_origin_top_left, is_overlay_candidate));
return resource->IsValid() ? resource : nullptr;
}
ExternalCanvasResource::~ExternalCanvasResource() {
OnDestroy();
}
bool ExternalCanvasResource::IsValid() const {
return context_provider_wrapper_ && HasGpuMailbox();
}
void ExternalCanvasResource::Abandon() {
// We don't need to destroy the shared image mailbox since we don't own it.
}
void ExternalCanvasResource::TakeSkImage(sk_sp<SkImage> image) {
NOTREACHED();
}
scoped_refptr<StaticBitmapImage> ExternalCanvasResource::Bitmap() {
TRACE_EVENT0("blink", "ExternalCanvasResource::Bitmap");
if (!IsValid())
return nullptr;
// The |release_callback| keeps a ref on this resource to ensure the backing
// shared image is kept alive until the lifetime of the image.
auto release_callback = base::BindOnce(
[](scoped_refptr<ExternalCanvasResource> resource,
const gpu::SyncToken& sync_token, bool is_lost) {
// Do nothing but hold onto the refptr.
},
base::RetainedRef(this));
return AcceleratedStaticBitmapImage::CreateFromCanvasMailbox(
mailbox_, GetSyncToken(), /*shared_image_texture_id=*/0u,
CreateSkImageInfo(), texture_target_, is_origin_top_left_,
context_provider_wrapper_, owning_thread_ref_, owning_thread_task_runner_,
std::move(release_callback));
}
void ExternalCanvasResource::TearDown() {
if (release_callback_)
std::move(release_callback_).Run(GetSyncToken(), resource_is_lost_);
Abandon();
}
const gpu::Mailbox& ExternalCanvasResource::GetOrCreateGpuMailbox(
MailboxSyncMode sync_mode) {
TRACE_EVENT0("blink", "ExternalCanvasResource::GetOrCreateGpuMailbox");
DCHECK_EQ(sync_mode, kVerifiedSyncToken);
return mailbox_;
}
bool ExternalCanvasResource::HasGpuMailbox() const {
return !mailbox_.IsZero();
}
const gpu::SyncToken ExternalCanvasResource::GetSyncToken() {
TRACE_EVENT0("blink", "ExternalCanvasResource::GetSyncToken");
// This method is expected to be used both in WebGL and WebGPU, that's why it
// uses InterfaceBase.
if (!sync_token_.HasData()) {
auto* interface = InterfaceBase();
if (interface)
interface->GenSyncTokenCHROMIUM(sync_token_.GetData());
} else if (!sync_token_.verified_flush()) {
// The offscreencanvas usage needs the sync_token to be verified in order to
// be able to use it by the compositor.
int8_t* token_data = sync_token_.GetData();
auto* interface = InterfaceBase();
DCHECK(interface);
interface->ShallowFlushCHROMIUM();
interface->VerifySyncTokensCHROMIUM(&token_data, 1);
sync_token_.SetVerifyFlush();
}
return sync_token_;
}
base::WeakPtr<WebGraphicsContext3DProviderWrapper>
ExternalCanvasResource::ContextProviderWrapper() const {
return context_provider_wrapper_;
}
ExternalCanvasResource::ExternalCanvasResource(
const gpu::Mailbox& mailbox,
viz::ReleaseCallback out_callback,
gpu::SyncToken sync_token,
const SkImageInfo& info,
GLenum texture_target,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality,
bool is_origin_top_left,
bool is_overlay_candidate)
: CanvasResource(std::move(provider), filter_quality, info.colorInfo()),
context_provider_wrapper_(std::move(context_provider_wrapper)),
size_(info.width(), info.height()),
mailbox_(mailbox),
texture_target_(texture_target),
release_callback_(std::move(out_callback)),
sync_token_(sync_token),
is_origin_top_left_(is_origin_top_left),
is_overlay_candidate_(is_overlay_candidate) {
DCHECK(!release_callback_ || sync_token_.HasData());
}
// CanvasResourceSwapChain
//==============================================================================
scoped_refptr<CanvasResourceSwapChain> CanvasResourceSwapChain::Create(
const SkImageInfo& info,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality) {
TRACE_EVENT0("blink", "CanvasResourceSwapChain::Create");
auto resource = AdoptRef(
new CanvasResourceSwapChain(info, std::move(context_provider_wrapper),
std::move(provider), filter_quality));
return resource->IsValid() ? resource : nullptr;
}
CanvasResourceSwapChain::~CanvasResourceSwapChain() {
OnDestroy();
}
bool CanvasResourceSwapChain::IsValid() const {
return context_provider_wrapper_ && HasGpuMailbox();
}
void CanvasResourceSwapChain::TakeSkImage(sk_sp<SkImage> image) {
NOTREACHED();
}
scoped_refptr<StaticBitmapImage> CanvasResourceSwapChain::Bitmap() {
SkImageInfo image_info = SkImageInfo::Make(
SkISize::Make(Size().width(), Size().height()), GetSkColorInfo());
// It's safe to share the back buffer texture id if we're on the same thread
// since the |release_callback| ensures this resource will be alive.
GLuint shared_texture_id = !is_cross_thread() ? back_buffer_texture_id_ : 0u;
// The |release_callback| keeps a ref on this resource to ensure the backing
// shared image is kept alive until the lifetime of the image.
auto release_callback = base::BindOnce(
[](scoped_refptr<CanvasResourceSwapChain>, const gpu::SyncToken&, bool) {
// Do nothing but hold onto the refptr.
},
base::RetainedRef(this));
return AcceleratedStaticBitmapImage::CreateFromCanvasMailbox(
back_buffer_mailbox_, GetSyncToken(), shared_texture_id, image_info,
GL_TEXTURE_2D, true /*is_origin_top_left*/, context_provider_wrapper_,
owning_thread_ref_, owning_thread_task_runner_,
std::move(release_callback));
}
void CanvasResourceSwapChain::Abandon() {
// Called when the owning thread has been torn down which will destroy the
// context on which the shared image was created so no cleanup is necessary.
}
void CanvasResourceSwapChain::TearDown() {
// The context deletes all shared images on destruction which means no
// cleanup is needed if the context was lost.
if (!context_provider_wrapper_)
return;
if (!use_oop_rasterization_) {
auto* raster_interface =
context_provider_wrapper_->ContextProvider()->RasterInterface();
DCHECK(raster_interface);
raster_interface->EndSharedImageAccessDirectCHROMIUM(
back_buffer_texture_id_);
raster_interface->DeleteGpuRasterTexture(back_buffer_texture_id_);
}
// No synchronization is needed here because the GL SharedImageRepresentation
// will keep the backing alive on the service until the textures are deleted.
auto* sii =
context_provider_wrapper_->ContextProvider()->SharedImageInterface();
DCHECK(sii);
sii->DestroySharedImage(gpu::SyncToken(), front_buffer_mailbox_);
sii->DestroySharedImage(gpu::SyncToken(), back_buffer_mailbox_);
}
const gpu::Mailbox& CanvasResourceSwapChain::GetOrCreateGpuMailbox(
MailboxSyncMode sync_mode) {
DCHECK_EQ(sync_mode, kVerifiedSyncToken);
return front_buffer_mailbox_;
}
bool CanvasResourceSwapChain::HasGpuMailbox() const {
return !front_buffer_mailbox_.IsZero();
}
const gpu::SyncToken CanvasResourceSwapChain::GetSyncToken() {
DCHECK(sync_token_.verified_flush());
return sync_token_;
}
void CanvasResourceSwapChain::PresentSwapChain() {
DCHECK(!is_cross_thread());
DCHECK(context_provider_wrapper_);
TRACE_EVENT0("blink", "CanvasResourceSwapChain::PresentSwapChain");
auto* raster_interface =
context_provider_wrapper_->ContextProvider()->RasterInterface();
DCHECK(raster_interface);
auto* sii =
context_provider_wrapper_->ContextProvider()->SharedImageInterface();
DCHECK(sii);
// Synchronize presentation and rendering.
raster_interface->GenUnverifiedSyncTokenCHROMIUM(sync_token_.GetData());
sii->PresentSwapChain(sync_token_, back_buffer_mailbox_);
// This only gets called via the CanvasResourceDispatcher export path so a
// verified sync token will be needed ultimately.
sync_token_ = sii->GenVerifiedSyncToken();
raster_interface->WaitSyncTokenCHROMIUM(sync_token_.GetData());
// PresentSwapChain() flips the front and back buffers, but the mailboxes
// still refer to the current front and back buffer after present. So the
// front buffer contains the content we just rendered, and it needs to be
// copied into the back buffer to support a retained mode like canvas expects.
// The wait sync token ensure that the present executes before we do the copy.
raster_interface->CopySubTexture(front_buffer_mailbox_, back_buffer_mailbox_,
GL_TEXTURE_2D, 0, 0, 0, 0, size_.width(),
size_.height(), false /* unpack_flip_y */,
false /* unpack_premultiply_alpha */);
// Don't generate sync token here so that the copy is not on critical path.
}
base::WeakPtr<WebGraphicsContext3DProviderWrapper>
CanvasResourceSwapChain::ContextProviderWrapper() const {
return context_provider_wrapper_;
}
CanvasResourceSwapChain::CanvasResourceSwapChain(
const SkImageInfo& info,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
base::WeakPtr<CanvasResourceProvider> provider,
cc::PaintFlags::FilterQuality filter_quality)
: CanvasResource(std::move(provider), filter_quality, info.colorInfo()),
context_provider_wrapper_(std::move(context_provider_wrapper)),
size_(info.width(), info.height()),
use_oop_rasterization_(context_provider_wrapper_->ContextProvider()
->GetCapabilities()
.supports_oop_raster) {
if (!context_provider_wrapper_)
return;
uint32_t usage = gpu::SHARED_IMAGE_USAGE_DISPLAY |
gpu::SHARED_IMAGE_USAGE_GLES2 |
gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT |
gpu::SHARED_IMAGE_USAGE_SCANOUT;
if (use_oop_rasterization_) {
usage = usage | gpu::SHARED_IMAGE_USAGE_RASTER |
gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION;
}
auto* sii =
context_provider_wrapper_->ContextProvider()->SharedImageInterface();
DCHECK(sii);
gpu::SharedImageInterface::SwapChainMailboxes mailboxes =
sii->CreateSwapChain(GetResourceFormat(), Size(), GetColorSpace(),
kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType,
usage);
back_buffer_mailbox_ = mailboxes.back_buffer;
front_buffer_mailbox_ = mailboxes.front_buffer;
sync_token_ = sii->GenVerifiedSyncToken();
// Wait for the mailboxes to be ready to be used.
auto* raster_interface =
context_provider_wrapper_->ContextProvider()->RasterInterface();
DCHECK(raster_interface);
raster_interface->WaitSyncTokenCHROMIUM(sync_token_.GetData());
// In OOPR mode we use mailboxes directly. We early out here because
// we don't need a texture id, as access is managed in the gpu process.
if (use_oop_rasterization_)
return;
back_buffer_texture_id_ =
raster_interface->CreateAndConsumeForGpuRaster(back_buffer_mailbox_);
raster_interface->BeginSharedImageAccessDirectCHROMIUM(
back_buffer_texture_id_, GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM);
}
} // namespace blink
| 38.731852 | 91 | 0.731066 | [
"render"
] |
e749862b273507c0a3ebadccc8b8ea7eceb901d8 | 4,839 | hpp | C++ | tenncor/layr/layer.hpp | mingkaic/tenncor | f2fa9652e55e9ca206de5e9741fe41bde43791c1 | [
"BSL-1.0",
"MIT"
] | 1 | 2020-12-29T20:38:08.000Z | 2020-12-29T20:38:08.000Z | tenncor/layr/layer.hpp | mingkaic/tenncor | f2fa9652e55e9ca206de5e9741fe41bde43791c1 | [
"BSL-1.0",
"MIT"
] | 16 | 2018-01-28T04:20:19.000Z | 2021-01-23T09:38:52.000Z | tenncor/layr/layer.hpp | mingkaic/tenncor | f2fa9652e55e9ca206de5e9741fe41bde43791c1 | [
"BSL-1.0",
"MIT"
] | null | null | null | ///
/// api.hpp
/// layr
///
/// Purpose:
/// Utility APIs for creating layers
///
#ifndef LAYR_LAYER_HPP
#define LAYR_LAYER_HPP
#include "tenncor/layr/init.hpp"
namespace layr
{
const std::string weight_label = "weight";
const std::string bias_label = "bias";
const std::string input_label = "input";
const std::string bind_name = "_UNARY_BIND";
const std::string link_name = "_LINK";
const std::string dense_name = "_DENSE_LAYER";
const std::string conv_name = "_CONV_LAYER";
const std::string rnn_name = "_RNN_LAYER";
const std::string lstm_name = "_LSTM_LAYER";
const std::string gru_name = "_GRU_LAYER";
static inline teq::TensMapT<std::string> replace_targets (
const teq::OwnMapT& inputs)
{
teq::TensMapT<std::string> targets;
for (auto& inp : inputs)
{
targets.emplace(inp.first, "target");
}
return targets;
}
teq::Shape gen_rshape (teq::DimsT runcoms,
teq::Shape left, eigen::PairVecT<teq::RankT> lrdims);
teq::TensptrT make_layer (teq::TensptrT root,
const std::string& layername, teq::TensptrT input);
eteq::ETensor get_input (const eteq::ETensor& root);
/// Copy everything from input.first to root, except replacing input.first with input.second
eteq::ETensor trail (const eteq::ETensor& root, const teq::OwnMapT& inputs);
eteq::ETensor connect (const eteq::ETensor& root, const eteq::ETensor& input);
eteq::ETensor deep_clone (const eteq::ETensor& root);
struct Trailer final : public teq::iOnceTraveler
{
Trailer (const teq::OwnMapT& inputs) :
trailed_(inputs), pfinder_(replace_targets(inputs)) {}
teq::OwnMapT trailed_;
private:
/// Implementation of iOnceTraveler
void visit_leaf (teq::iLeaf&) override {}
/// Implementation of iOnceTraveler
void visit_func (teq::iFunctor& func) override
{
if (estd::has(trailed_, &func))
{
return;
}
func.accept(pfinder_);
if (false == estd::has(pfinder_.roadmap_, &func))
{
return;
}
auto& target_dir = pfinder_.roadmap_.at(&func).at("target");
marsh::Maps dup_attrs;
marsh::get_attrs(dup_attrs, func);
auto& attr_directions = target_dir.attrs_;
for (const std::string& attr : attr_directions)
{
auto ref = static_cast<const teq::TensorRef*>(func.get_attr(attr));
auto ctens = ref->get_tensor();
ctens->accept(*this);
teq::TensptrT trailed;
if (estd::get(trailed, trailed_, ctens.get()))
{
dup_attrs.rm_attr(attr);
dup_attrs.add_attr(attr, marsh::ObjptrT(
ref->copynreplace(trailed)));
}
}
auto& child_directions = target_dir.args_;
teq::TensptrsT children = func.get_args();
for (size_t i : child_directions)
{
auto child = children[i];
child->accept(*this);
children[i] = trailed_.at(child.get());
}
auto opcode = (egen::_GENERATED_OPCODE) func.get_opcode().code_;
auto fcpy = eteq::make_funcattr(opcode, children, dup_attrs);
trailed_.emplace(&func, fcpy);
}
teq::PathFinder pfinder_;
};
struct BreadthStat final : public teq::iOnceTraveler
{
teq::TensMapT<size_t> breadth_;
private:
void visit_leaf (teq::iLeaf& leaf) override
{
breadth_.emplace(&leaf, breadth_.size());
}
void visit_func (teq::iFunctor& func) override
{
auto deps = func.get_args();
teq::multi_visit(*this, deps);
breadth_.emplace(&func, breadth_.size());
}
};
// Inorder traversal for mutable leaves
struct VarExtract final : public teq::iOnceTraveler
{
VarExtract (teq::TensSetT term = {}) : term_(term) {}
teq::LeafsT variables_;
teq::TensSetT term_;
private:
void visit_leaf (teq::iLeaf& leaf) override
{
if (estd::has(term_, &leaf))
{
return;
}
if (teq::Usage::IMMUTABLE != leaf.get_usage())
{
variables_.push_back(&leaf);
}
}
void visit_func (teq::iFunctor& func) override
{
if (estd::has(term_, &func))
{
return;
}
auto deps = func.get_args();
teq::multi_visit(*this, deps);
}
};
template <typename T>
eteq::VarptrsT<T> get_storage (const eteq::ETensor& root)
{
teq::RefMapT owner = teq::track_ownrefs(teq::TensptrsT{root});
auto intens = get_input(root).get();
VarExtract extra({intens});
root->accept(extra);
eteq::VarptrsT<T> vars;
vars.reserve(extra.variables_.size());
for (auto leaf : extra.variables_)
{
if (auto var = std::dynamic_pointer_cast<
eteq::Variable<T>>(owner.at(leaf).lock()))
{
vars.push_back(var);
}
}
return vars;
}
template <typename T>
struct RBMLayer final
{
RBMLayer<T> deep_clone (void) const
{
return RBMLayer<T>{
::layr::deep_clone(fwd_),
::layr::deep_clone(bwd_)
};
}
eteq::ETensor connect (const eteq::ETensor& input) const
{
return ::layr::connect(fwd_, input);
}
eteq::ETensor backward_connect (const eteq::ETensor& output) const
{
return ::layr::connect(bwd_, output);
}
eteq::ETensor fwd_;
eteq::ETensor bwd_;
};
using UnaryF = std::function<eteq::ETensor(const eteq::ETensor&)>;
}
#endif // LAYR_LAYER_HPP
| 21.411504 | 92 | 0.689812 | [
"shape"
] |
e74aa8e641e6a3aee8b16e04afec19fa09a2a1eb | 7,633 | cpp | C++ | Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T12:39:24.000Z | 2021-07-20T12:39:24.000Z | Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Source/Framework/ScriptCanvasTestFixture.h>
#include <Source/Framework/ScriptCanvasTestUtilities.h>
#include <ScriptCanvas/Core/NodeFunctionGeneric.h>
#pragma warning( push )
#pragma warning( disable : 5046) //'function' : Symbol involving type with internal linkage not defined
using namespace ScriptCanvasTests;
namespace
{
AZ_INLINE void ArgsNoReturn(float)
{
UnitTestEventsBus::Broadcast(&UnitTestEvents::SideEffect, "ArgsNoReturn SideFX");
}
AZ_INLINE std::tuple<AZStd::string, bool> ArgsReturnMulti(double input)
{
// compile test
return input >= 0.0
? std::make_tuple("positive", true)
: std::make_tuple("negative", false);
}
AZ_INLINE void NoArgsNoReturn()
{
UnitTestEventsBus::Broadcast(&UnitTestEvents::SideEffect, "NoArgsNoReturn SideFX");
}
AZ_INLINE float NoArgsReturn()
{
UnitTestEventsBus::Broadcast(&UnitTestEvents::SideEffect, "NoArgsReturn SideFX");
return 0.0f;
}
AZ_INLINE std::tuple<AZStd::string, bool> NoArgsReturnMulti()
{
return std::make_tuple("no-args", false);
}
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(ArgsNoReturn, "UnitTests", "{980E4400-288B-4DA2-8C5C-BBC5164CA2AB}", "", "One Arg");
SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(ArgsReturnMulti, "UnitTests", "{D7475558-BD14-4588-BC3A-6B4BD1ACF3B4}", "", "input:One Arg", "output:string", "output:bool");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(NoArgsNoReturn, "UnitTests", "{18BC4E04-7D97-4379-8A36-877881633AA9}", "");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(NoArgsReturn, "UnitTests", "{08E6535A-FCE0-4953-BA3E-59CF5A10073B}", "");
SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(NoArgsReturnMulti, "UnitTests", "{A73262FA-2756-40D6-A25C-8B98A64348F2}", "", "output:string", "output:bool");
// generic types that passed around by reference/pointer should behavior just like the value types
int MaxReturnByValueInteger(int lhs, int rhs)
{
return lhs >= rhs ? lhs : rhs;
}
const int* MaxReturnByPointerInteger(const int* lhs, const int* rhs)
{
return (lhs && rhs && (*lhs) >= (*rhs)) ? lhs : rhs;
}
const int& MaxReturnByReferenceInteger(const int& lhs, const int& rhs)
{
return lhs >= rhs ? lhs : rhs;
}
std::tuple<TestBehaviorContextObject, int> MaxReturnByValueMulti(TestBehaviorContextObject lhs, TestBehaviorContextObject rhs, int lhsInt, int rhsInt)
{
return std::make_tuple
(lhs.GetValue() >= rhs.GetValue() ? lhs : rhs
, lhsInt >= rhsInt ? lhsInt : rhsInt);
}
std::tuple<const TestBehaviorContextObject*, const int*> MaxReturnByPointerMulti(const TestBehaviorContextObject* lhs, const TestBehaviorContextObject* rhs, const int* lhsInt, const int* rhsInt)
{
return std::make_tuple
((lhs && rhs && (lhs->GetValue() >= rhs->GetValue())) ? lhs : rhs
, lhsInt && rhsInt && *lhsInt >= *rhsInt ? lhsInt : rhsInt);
}
std::tuple<const TestBehaviorContextObject&, const int&> MaxReturnByReferenceMulti(const TestBehaviorContextObject& lhs, const TestBehaviorContextObject& rhs, const int& lhsInt, const int& rhsInt)
{
return std::forward_as_tuple
(lhs.GetValue() >= rhs.GetValue() ? lhs : rhs
, lhsInt >= rhsInt ? lhsInt : rhsInt);
}
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MaxReturnByValue, "UnitTests", "{60C054C6-8A07-4D41-A9E4-E3BB0D20F098}", "", "0", "1");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MaxReturnByPointer, "UnitTests", "{16AFDE59-31B5-4B49-999F-8B486FC91371}", "", "0", "1");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MaxReturnByReference, "UnitTests", "{0A1FD51A-1D53-46FC-9A2F-DF711F62FDE9}", "", "0", "1");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MaxReturnByValueInteger, "UnitTests", "{5165F1BA-248F-434F-9227-B6AC2102D4B5}", "", "0", "1");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MaxReturnByPointerInteger, "UnitTests", "{BE658D24-8AB0-463B-979D-C829985E96EF}", "", "0", "1");
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MaxReturnByReferenceInteger, "UnitTests", "{8DE10FF6-9628-4015-A149-4276BF98D2AB}", "", "0", "1");
SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(MaxReturnByValueMulti, "UnitTests", "{5BE8F2C8-C036-4C82-A7C1-4DCBAC2FA6FC}", "", "0", "1", "0", "1", "Result", "Result");
SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(MaxReturnByPointerMulti, "UnitTests", "{339BDAB0-BB80-4BFE-B377-12FD08278A8E}", "", "0", "1", "0", "1", "Result", "Result");
SCRIPT_CANVAS_GENERIC_FUNCTION_MULTI_RESULTS_NODE(MaxReturnByReferenceMulti, "UnitTests", "{7FECD272-4348-463C-80CC-45D0C77378A6}", "", "0", "1", "0", "1", "Result", "Result");
} // namespace
namespace ScriptCanvas
{
AZ_INLINE AZ::Vector3 NormalizeWithDefault(const AZ::Vector3& source, const Data::NumberType tolerance, [[maybe_unused]] const Data::BooleanType fakeValueForTestingDefault)
{
AZ_TracePrintf("SC", "The fake value for testing default is %s\n", fakeValueForTestingDefault ? "True" : "False");
return source.GetNormalizedSafe(tolerance);
}
void NormalizeWithDefaultInputOverrides(Node& node) { SetDefaultValuesByIndex< 1, 2 >::_(node, 3.3, true); }
SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(NormalizeWithDefault, NormalizeWithDefaultInputOverrides, "Math/Vector3", "{1A56B08E-7E48-4240-878A-397A912519B6}", "description placeholder", "Vector", "Tolerance", "Fake Testing Default Value");
}
TEST_F(ScriptCanvasTestFixture, NodeGenerics)
{
using namespace ScriptCanvasEditor;
RegisterComponentDescriptor<ArgsNoReturnNode>();
RegisterComponentDescriptor<ArgsReturnMultiNode>();
RegisterComponentDescriptor<NoArgsNoReturnNode>();
RegisterComponentDescriptor<NoArgsReturnNode>();
RegisterComponentDescriptor<NoArgsReturnMultiNode>();
RegisterComponentDescriptor<NormalizeWithDefaultNode>();
UnitTestEventsHandler unitTestHandler;
unitTestHandler.BusConnect();
ScriptCanvas::Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const ScriptCanvasId& graphUniqueId = graph->GetScriptCanvasId();
AZ::EntityId startID;
CreateTestNode<ScriptCanvas::Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId noArgsNoReturnNodeID;
CreateTestNode<NoArgsNoReturnNode>(graphUniqueId, noArgsNoReturnNodeID);
AZ::EntityId argsNoReturnNodeID;
CreateTestNode<ArgsNoReturnNode>(graphUniqueId, argsNoReturnNodeID);
AZ::EntityId noArgsReturnNodeID;
CreateTestNode<NoArgsReturnNode>(graphUniqueId, noArgsReturnNodeID);
AZ::EntityId normalizeWithDefaultNodeID;
CreateTestNode<NormalizeWithDefaultNode>(graphUniqueId, normalizeWithDefaultNodeID);
AZ::EntityId unused0, unused1;
CreateTestNode<ArgsReturnMultiNode>(graphUniqueId, unused0);
CreateTestNode<NoArgsReturnMultiNode>(graphUniqueId, unused1);
EXPECT_TRUE(Connect(*graph, startID, "Out", noArgsNoReturnNodeID, "In"));
EXPECT_TRUE(Connect(*graph, noArgsNoReturnNodeID, "Out", argsNoReturnNodeID, "In"));
EXPECT_TRUE(Connect(*graph, argsNoReturnNodeID, "Out", noArgsReturnNodeID, "In"));
EXPECT_TRUE(Connect(*graph, noArgsReturnNodeID, "Out", normalizeWithDefaultNodeID, "In"));
delete graph->GetEntity();
}
#pragma warning( pop )
| 45.434524 | 250 | 0.723176 | [
"vector",
"3d"
] |
e74cd6f720c8cc24abf5e14614a33cb65af81e1b | 814 | cpp | C++ | src/ali_longest-continuous-increasing-subsequence/solution.cpp | hustzxd/leetcode | 83828602183e4709a6f20f163951e10b66f26935 | [
"MIT"
] | null | null | null | src/ali_longest-continuous-increasing-subsequence/solution.cpp | hustzxd/leetcode | 83828602183e4709a6f20f163951e10b66f26935 | [
"MIT"
] | null | null | null | src/ali_longest-continuous-increasing-subsequence/solution.cpp | hustzxd/leetcode | 83828602183e4709a6f20f163951e10b66f26935 | [
"MIT"
] | null | null | null | #include "../../include/solution.h"
int findLengthOfLCIS(vector<int> &nums) {
int n = nums.size();
int cur = 1;
int res = 1;
for (int i = 1; i < n; i++) {
if (nums[i] > nums[i - 1]) {
cur++;
} else {
res = max(res, cur);
cur = 1;
}
}
res = max(res, cur);
return res;
}
int main() {
int n;
cin >> n;
vector<int> A(n, 0);
vector<int> B(n, 0);
unordered_map<int, int> idx; //
for (int i = 0; i < n; ++i) {
cin >> A[i];
}
for (int i = 0; i < n; ++i) {
cin >> B[i];
idx[B[i]] = i;
}
for (int i = 0; i < n; ++i) {
A[i] = idx[A[i]];
// cout << A[i] << " ";
}
int len = findLengthOfLCIS(A);
cout << n - len << endl;
return 0;
}
| 20.35 | 41 | 0.385749 | [
"vector"
] |
e74e4dc4084e95e24e05ff9f7223b44d1d2ba01a | 10,978 | cpp | C++ | src/video_streamer.cpp | KivApple/video_streamer | f9f70a7d2f6663153cc086806e5b1403294ca559 | [
"MIT"
] | null | null | null | src/video_streamer.cpp | KivApple/video_streamer | f9f70a7d2f6663153cc086806e5b1403294ca559 | [
"MIT"
] | null | null | null | src/video_streamer.cpp | KivApple/video_streamer | f9f70a7d2f6663153cc086806e5b1403294ca559 | [
"MIT"
] | null | null | null | #include <sys/select.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <easylogging++.h>
#include <atomic>
#include "video_streamer.h"
#include "v4l2_device.h"
namespace video_streamer {
class heap_image_buffer_releaser: public image_buffer_releaser {
public:
void release(image_buffer &buffer) override {
delete[] buffer.data();
}
};
}
static video_streamer::heap_image_buffer_releaser _heap_image_buffer_releaser;
video_streamer::image_buffer::image_buffer(size_t size): video_streamer::image_buffer::image_buffer(
new uint8_t[size], size, &_heap_image_buffer_releaser
) {
}
video_streamer::stream_server::stream_server(
std::vector<std::string> server_addresses, int send_buffer_size
): std::thread(&stream_server::run, this), m_send_buffer_size(send_buffer_size) {
std::unique_lock<std::mutex> lock(m_client_sockets_mutex);
int one = 1;
for (auto &address : server_addresses) {
size_t dot_pos = address.rfind(':');
if (dot_pos == std::string::npos) {
throw stream_server_exception("Port number is missing in " + address);
}
if (dot_pos == 0) {
throw stream_server_exception("Hostname or IP address is missing in " + address);
}
size_t address_start = 0;
size_t address_end = dot_pos;
if (address[address_start] == '[' && address[address_end - 1] == ']') {
address_start++;
address_end--;
}
std::string host(address, address_start, address_end - address_start);
std::string port(address, dot_pos + 1);
addrinfo hints = {};
hints.ai_socktype = SOCK_STREAM;
addrinfo *result;
int error = getaddrinfo(host.data(), port.data(), &hints, &result);
if (error != 0) {
if (error == EAI_SYSTEM) {
LOG(ERROR) << "getaddrinfo() failed for host=" << host << ", port=" << port << ": " << strerror(errno);
} else {
LOG(ERROR) << "getaddrinfo() failed for host=" << host << ", port=" << port << ": " << gai_strerror(errno);
}
throw stream_server_exception("getaddrinfo() failed for host=" + host + ", port=" + port);
}
posix::unique_fd socket = posix::unique_fd(::socket(
result->ai_family, result->ai_socktype, result->ai_protocol
));
if (socket < 0) {
LOG(ERROR) << "socket() failed for host=" << host << ", port=" << port << ": " << strerror(errno);
throw stream_server_exception(std::string("Unable to create a socket: ") + strerror(errno));
}
if (setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)) < 0) {
LOG(WARNING) << "setsockopt(SO_REUSEADDR) failed: "<< strerror(errno);
}
if (bind(socket, result->ai_addr, result->ai_addrlen) != 0) {
LOG(ERROR) << "bind() failed for host=" << host << ", port=" << port << ": " << strerror(errno);
throw stream_server_exception(std::string("Unable to bind a socket: ") + strerror(errno));
}
if (listen(socket, 5) != 0) {
LOG(ERROR) << "listen() failed for host=" << host << ", port=" << port << ": " << strerror(errno);
throw stream_server_exception(std::string("Unable to listen a socket: ") + strerror(errno));
}
freeaddrinfo(result);
LOG(INFO) << "Listening on address " << host << ", port " << port;
m_server_sockets.push_back(std::move(socket));
}
}
video_streamer::stream_server::~stream_server() {
if (joinable()) {
m_quit = true;
join();
}
}
void video_streamer::stream_server::send(const void *data, size_t data_size) {
std::unique_lock<std::mutex> lock(m_client_sockets_mutex);
auto it = m_client_sockets.begin();
while (it != m_client_sockets.end()) {
errno = 0;
size_t offset = 0;
while (offset < data_size) {
ssize_t r = ::send(*it, (const char*) data + offset, data_size - offset, MSG_NOSIGNAL);
if (r <= 0) {
break;
}
offset += r;
}
if (offset < data_size) {
LOG(INFO) << "The client disconnected: " << strerror(errno);
it = m_client_sockets.erase(it);
} else {
++it;
}
}
}
void video_streamer::stream_server::send(const image_buffer &buffer) {
send(buffer.data(), buffer.size());
}
void video_streamer::stream_server::send(const frame &frame) {
send(frame.buffer());
}
void video_streamer::stream_server::accept_client(posix::unique_fd &server_socket) {
sockaddr_storage socket_addr = {};
socklen_t socket_addr_len = sizeof(socket_addr);
posix::unique_fd socket = accept(server_socket, (sockaddr*) &socket_addr, &socket_addr_len);
if (socket < 0) {
LOG(ERROR) << "accept() failed: " << strerror(errno);
throw stream_server_exception("accept() failed");
}
char address_buffer[std::max(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
const char *address = inet_ntop(
socket_addr.ss_family,
socket_addr.ss_family == AF_INET6 ?
(void*) &((sockaddr_in6*) &socket_addr)->sin6_addr :
(void*) &((sockaddr_in*) &socket_addr)->sin_addr,
address_buffer,
sizeof(address_buffer)
);
uint16_t port = ntohs(
socket_addr.ss_family == AF_INET6 ?
((sockaddr_in6*) &socket_addr)->sin6_port :
((sockaddr_in*) &socket_addr)->sin_port
);
LOG(INFO) << "New client connected from " << address << ", port " << port;
if (m_send_buffer_size > 0) {
if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &m_send_buffer_size, sizeof(int)) < 0) {
LOG(WARNING) << "Unable to update socket send buffer size";
}
}
std::unique_lock<std::mutex> lock(m_client_sockets_mutex);
m_client_sockets.push_back(std::move(socket));
}
void video_streamer::stream_server::run() {
usleep(100);
while (!m_quit) {
fd_set read_fds;
FD_ZERO(&read_fds);
int max_fd = -1;
{
std::unique_lock<std::mutex> lock(m_server_sockets_mutex);
for (auto &&socket : m_server_sockets) {
FD_SET(socket, &read_fds);
if (socket > max_fd) {
max_fd = socket;
}
}
}
timeval timeout { .tv_sec = 1, .tv_usec = 0 };
int r = select(max_fd + 1, &read_fds, nullptr, nullptr, &timeout);
if (r < 0) {
LOG(ERROR) << "select() failed: " << strerror(errno);
throw stream_server_exception("select() failed");
}
if (r == 0) continue;
std::unique_lock<std::mutex> lock(m_server_sockets_mutex);
for (auto &&server_socket : m_server_sockets) {
if (!FD_ISSET(server_socket, &read_fds)) continue;
accept_client(server_socket);
}
}
m_quit = false;
LOG(INFO) << "Stopped listening for incoming connections";
}
static void configure_loggers(const char *config_file_name, bool traceLibJpeg) {
el::Configurations conf;
conf.setGlobally(el::ConfigurationType::Filename, "video_streamer.log");
conf.setGlobally(
el::ConfigurationType::Format,
"%datetime{%Y-%M-%d %H:%m:%s.%g} [%level] [%logger] %msg"
);
if (config_file_name) {
conf.parseFromFile(config_file_name);
}
el::Loggers::setDefaultConfigurations(conf, true);
if (!traceLibJpeg) {
conf.set(el::Level::Trace, el::ConfigurationType::Enabled, "false");
el::Loggers::reconfigureLogger("libjpeg", conf);
}
}
volatile bool running = true;
struct sigaction prev_sigint_handler;
static void sigint_handler(int sig) {
if (running) {
running = false;
LOG(INFO) << "Received SIGINT";
} else {
prev_sigint_handler.sa_handler(sig);
}
}
static void setup_signal_handlers() {
struct sigaction sigint_action = {};
sigint_action.sa_handler = sigint_handler;
sigaction(SIGINT, &sigint_action, &prev_sigint_handler);
/* sigint_action.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sigint_action, nullptr); */
}
static std::atomic<int> frame_counter, byte_counter, jpeg_quality(80);
int video_streamer::main(int argc, char **argv, std::function<uncompressed_frame(uncompressed_frame)> frame_processor) {
std::vector<std::string> listen_addresses;
std::string capture_device_path = "/dev/video0";
int capture_frame_width = -1;
int capture_frame_height = -1;
bool show_stats = false;
const char *log_config_file = nullptr;
bool trace_libjpeg = false;
int target_bitrate = -1;
int send_buffer_size = -1;
for (auto i = 0; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "--listen" && i < argc - 1) {
listen_addresses.emplace_back(argv[++i]);
} else if (arg == "--device" && i < argc - 1) {
capture_device_path = argv[++i];
} else if (arg == "--width" && i < argc - 1) {
capture_frame_width = atoi(argv[++i]);
} else if (arg == "--height" && i < argc - 1) {
capture_frame_height = atoi(argv[++i]);
} else if (arg == "--stats") {
show_stats = true;
} else if (arg == "--log-config" && i < argc - 1) {
log_config_file = argv[++i];
} else if (arg == "--trace-libjpeg") {
trace_libjpeg = true;
} else if (arg == "--target-bitrate") {
target_bitrate = atoi(argv[++i]);
} else if (arg == "--send-buffer" && i < argc - 1) {
send_buffer_size = atoi(argv[++i]);
} else if (!arg.empty()) {
std::cerr << "Invalid command line argument: " << arg << std::endl;
}
}
if (listen_addresses.empty()) {
std::cerr << "Usage: " << argv[0] << " --device /dev/video0 --listen 127.0.0.1:1234 ..." << std::endl;
std::cerr << "\t" << "--width NNN" << std::endl;
std::cerr << "\t" << "--height NNN" << std::endl;
std::cerr << "\t" << "--stats" << std::endl;
std::cerr << "\t" << "--log-config FILE-NAME" << std::endl;
std::cerr << "\t" << "--trace-libjpeg" << std::endl;
std::cerr << "\t" << "--bitrate NNN" << std::endl;
std::cerr << "\t" << "--send-buffer NNN" << std::endl;
return EXIT_SUCCESS;
}
configure_loggers(log_config_file, trace_libjpeg);
video_streamer::v4l2::capture_device device(capture_device_path);
device.set_format(capture_frame_width, capture_frame_height, video_streamer::v4l2::format::MJPEG);
LOG(INFO) << "Capture size is " << device.frame_width() << "x" << device.frame_height();
LOG(INFO) << "Capture pixel format is " << device.pixel_format();
video_streamer::stream_server server(listen_addresses, send_buffer_size);
std::vector<std::thread> stream_threads;
stream_threads.reserve(std::thread::hardware_concurrency());
for (auto i = 0; i < std::thread::hardware_concurrency(); i++) {
stream_threads.emplace_back([&device, &server, &frame_processor] {
while (running) {
try {
auto frame = device.read_jpeg();
if (frame_processor) {
auto processed_frame = frame_processor(frame.uncompress(JCS_RGB, 3));
auto compressed_frame = jpeg_frame(
processed_frame, JCS_RGB, 3, jpeg_quality
);
server.send(compressed_frame);
byte_counter += (int) compressed_frame.buffer().size();
} else {
// TODO: Recompress JPEG if the frame is exceed target bitrate
server.send(frame);
byte_counter += (int) frame.buffer().size();
}
// TODO: Adjust quality if it is exceed target bitrate
frame_counter++;
} catch (const video_streamer::libjpeg_exception &e) {
LOG(WARNING) << "libjpeg error: " << e.what();
}
}
});
}
setup_signal_handlers();
while (running) {
sleep(1);
if (show_stats) {
LOG(DEBUG) << "Processed " << frame_counter.exchange(0) << " frames (" <<
(8 * byte_counter.exchange(0) / (1024 * 1024)) << " MBit/s)";
}
}
for (auto &&thread : stream_threads) {
thread.join();
}
return EXIT_SUCCESS;
}
| 33.882716 | 120 | 0.662234 | [
"vector"
] |
e74e5681f11056de9900d09196bd027c95d484f3 | 4,362 | cpp | C++ | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/phosphor-snmp/0.1+gitAUTOINC+52b3ad2a60-r1/git/snmp_notification.cpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/phosphor-snmp/0.1+gitAUTOINC+52b3ad2a60-r1/git/snmp_notification.cpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/phosphor-snmp/0.1+gitAUTOINC+52b3ad2a60-r1/git/snmp_notification.cpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | #include "snmp_notification.hpp"
#include "snmp_util.hpp"
#include "xyz/openbmc_project/Common/error.hpp"
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
namespace phosphor
{
namespace network
{
namespace snmp
{
namespace variant_ns = sdbusplus::message::variant_ns;
using namespace phosphor::logging;
using namespace sdbusplus::xyz::openbmc_project::Common::Error;
using snmpSessionPtr =
std::unique_ptr<netsnmp_session, decltype(&::snmp_close)>;
bool Notification::addPDUVar(netsnmp_pdu& pdu, const OID& objID,
size_t objIDLen, u_char type, Value val)
{
netsnmp_variable_list* varList = nullptr;
switch (type)
{
case ASN_INTEGER:
{
auto ltmp = variant_ns::get<int32_t>(val);
varList = snmp_pdu_add_variable(&pdu, objID.data(), objIDLen, type,
<mp, sizeof(ltmp));
}
break;
case ASN_UNSIGNED:
{
auto ltmp = variant_ns::get<uint32_t>(val);
varList = snmp_pdu_add_variable(&pdu, objID.data(), objIDLen, type,
<mp, sizeof(ltmp));
}
break;
case ASN_OPAQUE_U64:
{
auto ltmp = variant_ns::get<uint64_t>(val);
varList = snmp_pdu_add_variable(&pdu, objID.data(), objIDLen, type,
<mp, sizeof(ltmp));
}
break;
case ASN_OCTET_STR:
{
const auto& value = variant_ns::get<std::string>(val);
varList = snmp_pdu_add_variable(&pdu, objID.data(), objIDLen, type,
value.c_str(), value.length());
}
break;
}
return (varList == nullptr ? false : true);
}
void Notification::sendTrap()
{
constexpr auto comm = "public";
netsnmp_session session{0};
snmp_sess_init(&session);
init_snmp("snmpapp");
// TODO: https://github.com/openbmc/openbmc/issues/3145
session.version = SNMP_VERSION_2c;
session.community = (u_char*)comm;
session.community_len = strlen(comm);
session.callback = nullptr;
session.callback_magic = nullptr;
auto mgrs = getManagers();
for (auto& mgr : mgrs)
{
session.peername = const_cast<char*>(mgr.c_str());
// create the session
auto ss = snmp_add(
&session,
netsnmp_transport_open_client("snmptrap", session.peername),
nullptr, nullptr);
if (!ss)
{
log<level::ERR>("Unable to get the snmp session.",
entry("SNMPMANAGER=%s", mgr.c_str()));
elog<InternalFailure>();
}
// Wrap the raw pointer in RAII
snmpSessionPtr sessionPtr(ss, &::snmp_close);
ss = nullptr;
auto pdu = snmp_pdu_create(SNMP_MSG_TRAP2);
if (!pdu)
{
log<level::ERR>("Failed to create notification PDU");
elog<InternalFailure>();
}
pdu->trap_type = SNMP_TRAP_ENTERPRISESPECIFIC;
auto trapInfo = getTrapOID();
if (!snmp_pdu_add_variable(pdu, SNMPTrapOID,
sizeof(SNMPTrapOID) / sizeof(oid),
ASN_OBJECT_ID, trapInfo.first.data(),
trapInfo.second * sizeof(oid)))
{
log<level::ERR>("Failed to add the SNMP var(trapID)");
snmp_free_pdu(pdu);
elog<InternalFailure>();
}
auto objectList = getFieldOIDList();
for (const auto& object : objectList)
{
if (!addPDUVar(*pdu, std::get<0>(object), std::get<1>(object),
std::get<2>(object), std::get<3>(object)))
{
log<level::ERR>("Failed to add the SNMP var");
snmp_free_pdu(pdu);
elog<InternalFailure>();
}
}
// pdu is freed by snmp_send
if (!snmp_send(sessionPtr.get(), pdu))
{
log<level::ERR>("Failed to send the snmp trap.");
elog<InternalFailure>();
}
log<level::DEBUG>("Sent SNMP Trap", entry("MGR=%s", mgr.c_str()));
}
}
} // namespace snmp
} // namespace network
} // namespace phosphor
| 29.876712 | 79 | 0.544017 | [
"object"
] |
e752a4f63c461f168255701a7cad7ce39cd63750 | 36,075 | cxx | C++ | inetsrv/iis/iisrearc/core/ap/was/dll/applicationstore.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/iisrearc/core/ap/was/dll/applicationstore.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/iisrearc/core/ap/was/dll/applicationstore.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1998-2000 Microsoft Corporation
Module Name:
applicationstore.cxx
Abstract:
Reads application configuration
Author:
Bilal Alam (balam) 27-May-2001
Revision History:
--*/
#include "precomp.h"
HRESULT
APPLICATION_DATA_OBJECT::SetFromMetabaseData(
METADATA_GETALL_RECORD * pProperties,
DWORD cProperties,
BYTE * pbBase
)
/*++
Routine Description:
Setup a application data object from metabase properties
Arguments:
pProperties - Array of metadata properties
cProperties - Count of metadata properties
pbBase - Base of offsets in metadata properties
Return Value:
HRESULT
--*/
{
DWORD dwCounter;
PVOID pvDataPointer;
METADATA_GETALL_RECORD* pCurrentRecord;
HRESULT hr;
if ( pProperties == NULL || pbBase == NULL )
{
DBG_ASSERT ( pProperties != NULL && pbBase != NULL );
return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
}
//
// for each property evaluate what it tells us.
//
for ( dwCounter = 0;
dwCounter < cProperties;
dwCounter++ )
{
pCurrentRecord = &(pProperties[ dwCounter ]);
pvDataPointer = (PVOID) ( pbBase + pCurrentRecord->dwMDDataOffset );
switch ( pCurrentRecord->dwMDIdentifier )
{
case MD_APP_APPPOOL_ID:
hr = _strAppPoolId.Copy( (WCHAR*) pvDataPointer );
if ( FAILED( hr ) )
{
return hr;
}
break;
}
}
return NO_ERROR;
}
VOID
APPLICATION_DATA_OBJECT::Compare(
DATA_OBJECT * pDataObject
)
/*++
Routine Description:
Compare a given application object with this one. This routine sets the
changed flags as appropriate
Arguments:
pDataObject - New object to compare to
Return Value:
None
--*/
{
APPLICATION_DATA_OBJECT * pApplicationObject;
if ( pDataObject == NULL )
{
DBG_ASSERT ( pDataObject != NULL );
return;
}
pApplicationObject = (APPLICATION_DATA_OBJECT*) pDataObject;
DBG_ASSERT( pApplicationObject->CheckSignature() );
//
// If the application is not in WAS then assume that all the
// values have changed, because WAS will want to know about all
// of them.
//
if ( pApplicationObject->QueryInWas() )
{
//
// if we are in BC mode, or if the app pool id is the same, mark
// this application as if the app pool id has not changed.
//
if ( GetWebAdminService()->IsBackwardCompatibilityEnabled() ||
_strAppPoolId.EqualsNoCase ( pApplicationObject->_strAppPoolId ) )
{
_fAppPoolIdChanged = FALSE;
}
}
}
const WCHAR *
APPLICATION_DATA_OBJECT::QueryAppPoolId(
)
/*++
Routine Description:
Get the app pool id for the application object.
Arguments:
None
Return Value:
const WCHAR * pointing to the app pool id for the app.
--*/
{
// On any action we may need to look up the pool id.
if ( GetWebAdminService()->
IsBackwardCompatibilityEnabled() )
{
return &wszDEFAULT_APP_POOL;
}
else
{
return _strAppPoolId.QueryStr();
}
}
BOOL
APPLICATION_DATA_OBJECT::QueryHasChanged(
VOID
) const
/*++
Routine Description:
Has anything in this object changed
Arguments:
None
Return Value:
TRUE if something has changed (duh!)
--*/
{
return _fAppPoolIdChanged;
}
DATA_OBJECT *
APPLICATION_DATA_OBJECT::Clone(
VOID
)
/*++
Routine Description:
Clone application object
Arguments:
None
Return Value:
DATA_OBJECT *
--*/
{
APPLICATION_DATA_OBJECT * pClone;
HRESULT hr;
pClone = new APPLICATION_DATA_OBJECT;
if ( pClone == NULL )
{
return NULL;
}
hr = pClone->_strAppPoolId.Copy( _strAppPoolId );
if ( FAILED( hr ) )
{
delete pClone;
return NULL;
}
hr = pClone->_applicationKey.Create( _applicationKey.QueryApplicationUrl(),
_applicationKey.QuerySiteId() );
if ( FAILED( hr ) )
{
delete pClone;
return NULL;
}
pClone->_fAppPoolIdChanged = _fAppPoolIdChanged;
CloneBasics ( pClone );
return pClone;
}
VOID
APPLICATION_DATA_OBJECT::SelfValidate(
VOID
)
/*++
Routine Description:
Check this object's internal validity
Arguments:
None
Return Value:
None
--*/
{
//
// never bother validating if we are deleting
//
if ( !QueryWillWasKnowAboutObject() )
{
return;
}
//
// To have a valid keys these should not be able
// to happen, if they do we will investigate how
// and decide if we should log or not.
//
DBG_ASSERT ( QuerySiteId() > 0 );
DBG_ASSERT ( QueryApplicationUrl() != NULL &&
*(QueryApplicationUrl()) != L'\0' );
//
// Resonably this should also not be able to happen
// unless someone sets the AppPoolId to "" specifically
//
if ( _strAppPoolId.IsEmpty() )
{
GetWebAdminService()->
GetWMSLogger()->
LogApplicationAppPoolIdEmpty( QuerySiteId(),
QueryApplicationUrl(),
QueryInWas() );
SetSelfValid( FALSE );
}
}
HRESULT
APPLICATION_DATA_OBJECT_TABLE::ReadFromMetabase(
IMSAdminBase * pAdminBase
)
/*++
Routine Description:
Read all the applications from the metabase and build up a table
Arguments:
pAdminBase - ABO pointer
Return Value:
HRESULT
--*/
{
return ReadFromMetabasePath( pAdminBase, L"/LM/W3SVC", TRUE );
}
HRESULT
APPLICATION_DATA_OBJECT_TABLE::ReadFromMetabasePath(
IMSAdminBase * pAdminBase,
WCHAR * pszMetaPath,
BOOL fMultiThreaded
)
/*++
Routine Description:
Read all the applications from the metabase and build up a table
Arguments:
pAdminBase - ABO pointer
pszMetaPath - Metabase path
fMultiThreaded - whether or not to do this multithreaded
Return Value:
HRESULT
--*/
{
MB mb( pAdminBase );
BOOL fRet;
STACK_BUFFER( bufPaths, 2048 );
fRet = mb.Open( pszMetaPath, METADATA_PERMISSION_READ );
if ( !fRet )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
fRet = mb.GetDataPaths( L"",
MD_APP_APPPOOL_ID,
STRING_METADATA,
&bufPaths );
if ( !fRet )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
MULTIPLE_THREAD_READER reader;
return reader.DoWork(this, &mb, (LPWSTR) bufPaths.QueryPtr(), fMultiThreaded);
}
HRESULT
APPLICATION_DATA_OBJECT_TABLE::DoThreadWork(
LPWSTR pszString,
LPVOID pContext
)
/*++
Routine Description:
Read one application from the metabase and build up a table entry
Arguments:
pszString - Application to read
pContext - MB pointer opened to w3svc node
Return Value:
HRESULT
--*/
{
BOOL fRet;
WCHAR * pszPaths = NULL;
APPLICATION_DATA_OBJECT * pApplicationObject = NULL;
HRESULT hr = S_OK;
STACK_BUFFER( bufProperties, 512 );
DWORD cProperties;
DWORD dwDataSetNumber;
DWORD dwSiteId = 0;
WCHAR * pszEnd = NULL;
LK_RETCODE lkrc;
MB * mb = (MB*) pContext;
pszPaths = pszString;
DBG_ASSERT(pContext && pszString);
//
// We only care about rooted application paths
// (/LM/W3SVC/<n>/ROOT/*)
//
if ( pszPaths[ 0 ] == L'/' &&
pszPaths[ 1 ] == L'\0' )
{
goto exit;
}
//
// Check for <n>
//
dwSiteId = wcstoul( pszPaths + 1, &pszEnd, 10 );
if ( dwSiteId == 0 )
{
//
// This isn't a site at all. Therefore we don't care about
// this application.
//
goto exit;
}
//
// Check for the /ROOT/ and skip past if we found it
//
if ( _wcsnicmp( pszEnd, L"/ROOT/", 6 ) != 0 )
{
goto exit;
}
//
// Skip past the "/ROOT"
//
pszEnd += 5;
//
// We have an application
//
fRet = mb->GetAll( pszPaths,
METADATA_INHERIT | METADATA_PARTIAL_PATH | METADATA_NON_SECURE_ONLY,
IIS_MD_UT_SERVER,
&bufProperties,
&cProperties,
&dwDataSetNumber );
if ( !fRet )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto exit;
}
//
// Create and initialize object
//
pApplicationObject = new APPLICATION_DATA_OBJECT();
if ( pApplicationObject == NULL )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto exit;
}
hr = pApplicationObject->Create( pszEnd, dwSiteId );
if ( FAILED( hr ) )
{
goto exit;
}
hr = pApplicationObject->SetFromMetabaseData(
( METADATA_GETALL_RECORD * ) bufProperties.QueryPtr(),
cProperties,
( PBYTE ) bufProperties.QueryPtr() );
if ( FAILED( hr ) )
{
goto exit;
}
IF_DEBUG( WEB_ADMIN_SERVICE_WMS )
{
DBGPRINTF(( DBG_CONTEXT,
" Inserting Site '%d''s Application '%S' from the metadata tables \n",
pApplicationObject->QuerySiteId(),
pApplicationObject->QueryApplicationUrl()));
}
//
// Insert into hash table
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// General rule about inserting into tables:
//
// For Initial Processing and Complete processing caused by
// a change notification, we will always ignore inserting a
// object if we fine an object all ready in the table. This is because
// during a change notification if a record was added by the change
// notification code, it will be more correct ( like knowing if ServerCommand
// actually changed ), then the new generic record that was read because
// of a change to a hire node. Also during initial read we should
// not have to make this decision so we can still ignore if we do see it.
//
// For Change Processing we will need to evaluate the change that
// all ready exists and compare it with the new change to decide
// what change we should make.
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lkrc = InsertRecord( (DATA_OBJECT*) pApplicationObject );
if ( lkrc != LK_SUCCESS && lkrc != LK_KEY_EXISTS )
{
hr = HRESULT_FROM_WIN32( lkrc );
goto exit;
}
hr = S_OK;
exit:
if ( pApplicationObject )
{
pApplicationObject->DereferenceDataObject();
pApplicationObject = NULL;
}
return hr;
}
HRESULT
APPLICATION_DATA_OBJECT_TABLE::ReadFromMetabaseChangeNotification(
IMSAdminBase * pAdminBase,
MD_CHANGE_OBJECT pcoChangeList[],
DWORD dwMDNumElements,
DATA_OBJECT_TABLE* pMasterTable
)
/*++
Routine Description:
Change change notification by building a new table
Arguments:
pAdminBase - ABO pointer
pcoChangeList - Properties which have changed
dwMDNumElements - Number of properties which have changed
Return Value:
HRESULT
--*/
{
HRESULT hr = S_OK;
DWORD i;
WCHAR * pszPath = NULL;
WCHAR * pszPathEnd = NULL;
APPLICATION_DATA_OBJECT * pApplicationObject = NULL;
MB mb( pAdminBase );
LK_RETCODE lkrc;
BOOL fRet;
DWORD dwSiteId;
STACK_STRU( strAppPoolId, 256 );
BOOL fReadAllObjects = FALSE;
APPLICATION_DATA_OBJECT_TABLE* pMasterAppTable = ( APPLICATION_DATA_OBJECT_TABLE* ) pMasterTable;
for ( i = 0; i < dwMDNumElements; i++ )
{
//
// We only care about W3SVC properties
//
IF_DEBUG( WEB_ADMIN_SERVICE_WMS )
{
DBGPRINTF(( DBG_CONTEXT,
" Evaluation change notification for %S to see if applications care about it \n",
pcoChangeList[ i ].pszMDPath ));
}
if( _wcsnicmp( pcoChangeList[ i ].pszMDPath,
DATA_STORE_SERVER_MB_PATH,
DATA_STORE_SERVER_MB_PATH_CCH ) != 0 )
{
continue;
}
//
// If a property changed at the W3SVC level, then we need to
// re-evaluate all the apps (i.e. read all the metabase props) once
//
if ( wcslen( pcoChangeList[ i ].pszMDPath ) ==
DATA_STORE_SERVER_MB_PATH_CCH )
{
fReadAllObjects = TRUE;
continue;
}
//
// Evaluate which site changed
//
pszPath = pcoChangeList[ i ].pszMDPath + DATA_STORE_SERVER_MB_PATH_CCH;
DBG_ASSERT( *pszPath != L'\0' );
dwSiteId = wcstoul( pszPath, &pszPathEnd, 10 );
//
// We only care about sites
//
if ( dwSiteId == 0 )
{
continue;
}
DBG_ASSERT ( pszPathEnd );
//
// If not at least as deep as root, then ignore
//
if ( _wcsnicmp( pszPathEnd, L"/ROOT/", 6 ) != 0 )
{
// at this point it might be a deletion on a site. if it is
// then we want to delete all the applications that point to
// this site.
if ( pcoChangeList[ i ].dwMDChangeType & MD_CHANGE_TYPE_DELETE_OBJECT &&
( ( pszPathEnd[0] == L'\0' ) ||
( pszPathEnd[0] == L'/' &&
pszPathEnd[1] == L'\0') ) )
{
// if we are deleting a site, then we need to delete
// all applications beneath it as well.
// first change all entries in this table for this app to a delete.
hr = DeleteSubApplications( NULL, dwSiteId, NULL, FALSE );
if ( FAILED ( hr ) )
{
goto exit;
}
// then add deletion references for any references in the master table.
hr = DeleteSubApplications( pMasterAppTable, dwSiteId, NULL, FALSE );
if ( FAILED ( hr ) )
{
goto exit;
}
} // end of if we are on a real site being deleted
continue;
}
//
// Skip past /ROOT
//
pszPathEnd += 5;
//
// If this was a delete, then we're OK to add a row with it
//
BOOL fDeleteOnlyThisUrl = FALSE;
//
// If we are being told to delete a property on the application
// we need to make sure that the property is not the AppPoolId. If
// it is then we are basically being told to delete the object.
//
if ( pcoChangeList[ i ].dwMDChangeType & MD_CHANGE_TYPE_DELETE_DATA )
{
for ( DWORD j = 0; j < pcoChangeList[ i ].dwMDNumDataIDs; j++ )
{
if ( pcoChangeList[ i ].pdwMDDataIDs[ j ] == MD_APP_APPPOOL_ID )
{
// We are basically just deleting the object so change the
// change action to show this.
pcoChangeList[ i ].dwMDChangeType = pcoChangeList[ i ].dwMDChangeType |
MD_CHANGE_TYPE_DELETE_OBJECT;
fDeleteOnlyThisUrl = TRUE;
}
}
}
//
// Now if we are removing this application, let's get to it.
//
if ( pcoChangeList[ i ].dwMDChangeType & MD_CHANGE_TYPE_DELETE_OBJECT )
{
// if we are deleting an application, then we need to delete
// all applications beneath it as well.
// first change all entries in this table for this app to a delete.
hr = DeleteSubApplications( NULL, dwSiteId, pszPathEnd, fDeleteOnlyThisUrl );
if ( FAILED ( hr ) )
{
goto exit;
}
// then add deletion references for any references in the master table.
hr = DeleteSubApplications( pMasterAppTable, dwSiteId, pszPathEnd, fDeleteOnlyThisUrl );
if ( FAILED ( hr ) )
{
goto exit;
}
}
else
{
//
// If this is an insert/update, we need to first check whether
// there is an actual application at the path in question
//
fRet = mb.Open( pcoChangeList[ i ].pszMDPath,
METADATA_PERMISSION_READ );
if ( !fRet )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
// if we can not find the key then a delete
// for the object is on it's way, so we can
// ignore this change notification.
if ( hr == HRESULT_FROM_WIN32( ERROR_PATH_NOT_FOUND ) )
{
hr = S_OK;
continue;
}
goto exit;
}
fRet = mb.GetStr( L"",
MD_APP_APPPOOL_ID,
IIS_MD_UT_SERVER,
&strAppPoolId,
0 );
// close the metabase so that we can get
// the next item in the loop if we need to
// without this call we can get told the path
// is not found.
mb.Close();
if ( fRet )
{
//
// We have an application here!
//
pApplicationObject = new APPLICATION_DATA_OBJECT;
if ( pApplicationObject == NULL )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto exit;
}
hr = pApplicationObject->Create( pszPathEnd,
dwSiteId );
if ( FAILED( hr ) )
{
goto exit;
}
IF_DEBUG( WEB_ADMIN_SERVICE_WMS )
{
DBGPRINTF(( DBG_CONTEXT,
"AppPoolId = '%S' \n ",
strAppPoolId.QueryStr() ));
}
hr = pApplicationObject->SetAppPoolId( strAppPoolId.QueryStr() );
if ( FAILED( hr ) )
{
goto exit;
}
IF_DEBUG( WEB_ADMIN_SERVICE_WMS )
{
DBGPRINTF(( DBG_CONTEXT,
"AppPoolId = '%S' \n ",
pApplicationObject->QueryAppPoolId() ));
}
IF_DEBUG( WEB_ADMIN_SERVICE_WMS )
{
DBGPRINTF(( DBG_CONTEXT,
" Inserting Site '%d''s Application '%S' from the metadata tables \n",
pApplicationObject->QuerySiteId(),
pApplicationObject->QueryApplicationUrl()));
}
//
// Insert into the table
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// General rule about inserting into tables:
//
// For Initial Processing and Complete processing caused by
// a change notification, we will always ignore inserting a
// object if we fine an object all ready in the table. This is because
// during a change notification if a record was added by the change
// notification code, it will be more correct ( like knowing if ServerCommand
// actually changed ), then the new generic record that was read because
// of a change to a hire node. Also during initial read we should
// not have to make this decision so we can still ignore if we do see it.
//
// For Change Processing we will need to evaluate the change that
// all ready exists and compare it with the new change to decide
// what change we should make.
//
// For the case of application since it doesn't have any special property like
// ServerCommand or AppPoolCommand that we need to know that it has changed
// we can always just take the second record regardless of what is happening.
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lkrc = InsertRecord( (DATA_OBJECT*) pApplicationObject, TRUE );
if ( lkrc != LK_SUCCESS )
{
hr = HRESULT_FROM_WIN32( lkrc );
goto exit;
}
pApplicationObject->DereferenceDataObject();
pApplicationObject = NULL;
}
}
} // end of loop.
//
// if we saw something along the way that is going to cause us to need
// to re-read all the objects, now is the time to do it.
//
if ( fReadAllObjects )
{
hr = ReadFromMetabasePath( pAdminBase, L"/LM/W3SVC", TRUE);
if ( FAILED( hr ) )
{
goto exit;
}
}
exit:
if ( pApplicationObject )
{
pApplicationObject->DereferenceDataObject();
pApplicationObject = NULL;
}
return hr;
}
//static
LK_ACTION
APPLICATION_DATA_OBJECT_TABLE::CreateWASObjectsAction(
IN DATA_OBJECT * pObject,
IN LPVOID
)
/*++
Routine Description:
Handles determining if the application data object
should be created in WAS's known apps
Arguments:
IN DATA_OBJECT* pObject = the app to decide about
IN LPVOID pTableVoid = pointer back to the table the
pObject is from
Return Value:
LK_ACTION
--*/
{
DBG_ASSERT ( pObject );
APPLICATION_DATA_OBJECT* pAppObject = (APPLICATION_DATA_OBJECT*) pObject;
DBG_ASSERT( pAppObject->CheckSignature() );
//
// For both Inserts and Updates we call Modify application
// this is because we allow WAS to determine if the application
// exists or not. It could exist if it is the root app and was
// created for us.
//
if ( pAppObject->QueryShouldWasInsert() )
{
GetWebAdminService()->
GetUlAndWorkerManager()->
ModifyApplication( pAppObject );
}
return LKA_SUCCEEDED;
}
//static
LK_ACTION
APPLICATION_DATA_OBJECT_TABLE::UpdateWASObjectsAction(
IN DATA_OBJECT * pObject,
IN LPVOID
)
/*++
Routine Description:
Handles determining if the application data object
should be updated in WAS's known apps
Arguments:
IN DATA_OBJECT* pObject = the app to decide about
IN LPVOID pTableVoid = pointer back to the table the
pObject is from
Return Value:
LK_ACTION
--*/
{
DBG_ASSERT ( pObject );
APPLICATION_DATA_OBJECT* pAppObject = (APPLICATION_DATA_OBJECT*) pObject;
DBG_ASSERT( pAppObject->CheckSignature() );
if ( pAppObject->QueryShouldWasUpdate() )
{
GetWebAdminService()->
GetUlAndWorkerManager()->
ModifyApplication( pAppObject );
}
return LKA_SUCCEEDED;
}
//static
LK_ACTION
APPLICATION_DATA_OBJECT_TABLE::DeleteWASObjectsAction(
IN DATA_OBJECT * pObject,
IN LPVOID
)
/*++
Routine Description:
Handles determining if the application data object
should be deleted from WAS's known apps
Arguments:
IN DATA_OBJECT* pObject = the app to decide about
IN LPVOID pTableVoid = pointer back to the table the
pObject is from
Return Value:
LK_ACTION
--*/
{
DBG_ASSERT ( pObject );
APPLICATION_DATA_OBJECT* pAppObject = (APPLICATION_DATA_OBJECT*) pObject;
DBG_ASSERT( pAppObject->CheckSignature() );
if ( pAppObject->QueryShouldWasDelete() )
{
GetWebAdminService()->
GetUlAndWorkerManager()->
DeleteApplication( pAppObject->QueryApplicationUrl(),
pAppObject->QuerySiteId() );
}
return LKA_SUCCEEDED;
}
HRESULT
APPLICATION_DATA_OBJECT_TABLE::DeleteSubApplications(
IN APPLICATION_DATA_OBJECT_TABLE* pTableToFindObjectsIn,
IN DWORD dwSiteId,
IN LPWSTR pwszAppUrl,
IN BOOL fDeleteOnlyThisUrl
)
/*++
Routine Description:
Deletes applications that exist under sites or other
applications that are being deleted.
Arguments:
IN APPLICATION_DATA_OBJECT_TABLE* pTableToFindObjectsIn = If null delete from current table.
IN DWORD dwSiteId = Site Id of applications being deleted
IN LPWSTR pwszAppUrl = AppUrl that must be contained in app to cause deletion ( if NULL, delete
all applications for the site ).
IN BOOL fDeleteOnlyThisUrl = Only applies if a specific URL is given. If it is TRUE we will only
delete the exact URL and none below it.
Return Value:
HRESULT
--*/
{
HRESULT hr = S_OK;
APPLICATION_DATA_OBJECT_TABLE* pTableToSearch = pTableToFindObjectsIn;
APPLICATION_DATA_OBJECT* pOrigAppObject = NULL;
// number of characters in the app url not counting the null
DWORD cchInAppUrl = ( pwszAppUrl == NULL ) ? 0 : (DWORD) wcslen( pwszAppUrl );
// remove the ending slash from the equation.
if ( cchInAppUrl > 0 &&
pwszAppUrl[cchInAppUrl-1] == '/' )
{
// Don't worry about the final '/'
cchInAppUrl = cchInAppUrl - 1;
}
// If we were passed in a NULL for the table to search than we
// really want to search the same table we are updating.
//
if ( pTableToSearch == NULL )
{
pTableToSearch = this;
}
// Now walk through the table and identify if the record we find
// is actually this record.
for ( APPLICATION_DATA_OBJECT_TABLE::iterator appiter = pTableToSearch->begin();
appiter != end();
++appiter )
{
pOrigAppObject = (APPLICATION_DATA_OBJECT*) appiter.Record();
DBG_ASSERT( pOrigAppObject->CheckSignature() );
// Found an application who's site matches the one being deleted
if ( pOrigAppObject->QuerySiteId() == dwSiteId )
{
// if we are deleting the site, then delete this one
// or if we are deleting the root application, then delete
// all applications below it.
if ( pwszAppUrl == NULL || cchInAppUrl == 0 )
{
// delete it.
hr = DeleteThisURLFromTable( pOrigAppObject, pTableToFindObjectsIn );
if ( FAILED ( hr ) )
{
goto exit;
}
}
else
{
//
// we have all ready removed the '/' from the length above, so
// now we just need to make sure that if we find a match, it is
// ended with either a null or a slash.
//
DBG_ASSERT ( cchInAppUrl > 0 );
if ( wcsncmp ( pwszAppUrl, pOrigAppObject->QueryApplicationUrl(), cchInAppUrl ) == 0 )
{
// do we want to only delete the specific url, or do we want to delete
// all urls under it as well.
if ( fDeleteOnlyThisUrl )
{
//
// so if either the one we are comparing to is null terminated or
// null terminated directly after the trailing slash, then we can
// delete it.
//
if ( pOrigAppObject->QueryApplicationUrl()[cchInAppUrl] == '\0' ||
( pOrigAppObject->QueryApplicationUrl()[cchInAppUrl] == '/' &&
pOrigAppObject->QueryApplicationUrl()[cchInAppUrl+1] == '\0' ) )
{
// delete it.
hr = DeleteThisURLFromTable( pOrigAppObject, pTableToFindObjectsIn );
if ( FAILED ( hr ) )
{
goto exit;
}
}
}
else
{
//
// if the string we found ends with either a null or a slash then
// we should delete it. We know this string has enough characters
// because it passed the above check.
//
if ( pOrigAppObject->QueryApplicationUrl()[cchInAppUrl] == '\0' ||
pOrigAppObject->QueryApplicationUrl()[cchInAppUrl] == '/' )
{
// delete it.
hr = DeleteThisURLFromTable( pOrigAppObject, pTableToFindObjectsIn );
if ( FAILED ( hr ) )
{
goto exit;
}
}
}
}
else
{
// the url does not match so we don't need to do anything
// but move on.
}
} // end of URL specific check
} // end of site id matching
} // end of loop walking applications looking for site.
exit:
return hr;
}
HRESULT
APPLICATION_DATA_OBJECT_TABLE::DeleteThisURLFromTable(
IN APPLICATION_DATA_OBJECT* pOrigAppObject,
IN APPLICATION_DATA_OBJECT_TABLE* pTableFoundIn
)
/*++
Routine Description:
Adds an entry to delete a specific application from
a table.
Arguments:
IN APPLICATION_DATA_OBJECT* pOrigAppObject = The object that we want deleted
IN APPLICATION_DATA_OBJECT_TABLE* pTableFoundIn = The table we were looking in. If it is null then
we are looking in this table and the object is from
the same table that we are trying to alter, so we
don't have to clone and add.
Return Value:
HRESULT
--*/
{
HRESULT hr = S_OK;
APPLICATION_DATA_OBJECT * pApplicationObject = NULL;
LK_RETCODE lkrc;
DBG_ASSERT ( pOrigAppObject );
IF_DEBUG( WEB_ADMIN_SERVICE_WMS )
{
DBGPRINTF(( DBG_CONTEXT,
" Deleting Site '%d''s Application '%S' from the metadata tables \n",
pOrigAppObject->QuerySiteId(),
pOrigAppObject->QueryApplicationUrl()));
}
// If the table found in is null then we are working on the same table
// and all we have to do is change the DeleteWhenDone on the object.
if ( pTableFoundIn == NULL )
{
pOrigAppObject->SetDeleteWhenDone( TRUE );
}
else
{
// We are putting an entry into a table that doesn't have an entry
// yet, so we need to clone the object and insert it.
pApplicationObject = ( APPLICATION_DATA_OBJECT* ) pOrigAppObject->Clone();
if ( pApplicationObject == NULL )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto exit;
}
pApplicationObject->SetDeleteWhenDone( TRUE );
//
// Insert into the table
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// General rule about inserting into tables:
//
// For Initial Processing and Complete processing caused by
// a change notification, we will always ignore inserting a
// object if we find an object all ready in the table. This is because
// during a change notification if a record was added by the change
// notification code, it will be more correct ( like knowing if ServerCommand
// actually changed ), then the new generic record that was read because
// of a change to a hire node. Also during initial read we should
// not have to make this decision so we can still ignore if we do see it.
//
// For Change Processing we will need to evaluate the change that
// all ready exists and compare it with the new change to decide
// what change we should make.
//
// For the case of application since it doesn't have any special property like
// ServerCommand or AppPoolCommand that we need to know that it has changed
// we can always just take the second record regardless of what is happening.
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lkrc = InsertRecord( (DATA_OBJECT*) pApplicationObject, TRUE );
if ( lkrc != LK_SUCCESS )
{
hr = HRESULT_FROM_WIN32( lkrc );
goto exit;
}
}
exit:
if ( pApplicationObject )
{
pApplicationObject->DereferenceDataObject();
pApplicationObject = NULL;
}
return hr;
}
| 28.427896 | 106 | 0.507055 | [
"object"
] |
e7533de588160c80e1167647613cb7022267cd00 | 10,498 | cc | C++ | mindspore/ccsrc/runtime/device/ascend/ge_runtime/runtime_model.cc | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | 2 | 2021-07-08T13:10:42.000Z | 2021-11-08T02:48:57.000Z | mindspore/ccsrc/runtime/device/ascend/ge_runtime/runtime_model.cc | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/runtime/device/ascend/ge_runtime/runtime_model.cc | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019-2020 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 "runtime/device/ascend/ge_runtime/runtime_model.h"
#include <set>
#include "runtime/kernel.h"
#include "runtime/rt_model.h"
#include "graphengine/inc/external/runtime/rt_error_codes.h"
#include "runtime/device/ascend/ge_runtime/model_context.h"
#include "runtime/device/ascend/ge_runtime/task/task.h"
#include "runtime/device/ascend/ge_runtime/task/task_factory.h"
#include "mindspore/core/utils/log_adapter.h"
namespace mindspore::ge::model_runner {
RuntimeModel::~RuntimeModel() {
MS_LOG(INFO) << "RuntimeModel destructor start.";
// Unbind rtModel from all task related streams
RtModelUnbindStream();
// Release task first, hccl task hold stream
task_list_.clear();
// Release all task related streams
RtStreamDestory();
// Release rtlabel resource
RtLabelDestory();
// Release rtEvent resourece
RtEventDestory();
MS_LOG(INFO) << "Do RtModelDestroy";
// Release all rt_model
RtModelDestory();
}
void RuntimeModel::InitStream(const std::shared_ptr<DavinciModel> &davinci_model) {
MS_EXCEPTION_IF_NULL(davinci_model);
std::set<int64_t> wait_active_streams;
std::set<int64_t> force_copy_streams;
for (const auto &stream_id : davinci_model->GetWaitActiveStreams()) {
MS_LOG(INFO) << "Stream id " << stream_id << " is wait active stream.";
(void)wait_active_streams.insert(stream_id);
}
for (const auto &stream_id : davinci_model->GetForceCopyStreams()) {
MS_LOG(INFO) << "Stream id " << stream_id << " is force copy stream.";
(void)force_copy_streams.insert(stream_id);
}
MS_LOG(INFO) << "Total stream num " << davinci_model->GetStreamNum();
for (uint32_t i = 0; i < davinci_model->GetStreamNum(); ++i) {
rtStream_t stream = nullptr;
uint32_t flag = (force_copy_streams.find(i) != force_copy_streams.end())
? (RT_STREAM_PERSISTENT | RT_STREAM_FORCE_COPY)
: (RT_STREAM_PERSISTENT);
rtError_t rt_ret = rtStreamCreateWithFlags(&stream, davinci_model->GetPriority(), flag);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtStreamCreate failed, ret: " << std::hex << rt_ret;
}
MS_LOG(INFO) << "rtStreamCreateWithFlags end.";
stream_list_.emplace_back(stream);
// Bind rt_model_handle_ to all task related streams
flag = (wait_active_streams.find(i) != wait_active_streams.end()) ? (static_cast<uint32_t>(RT_INVALID_FLAG))
: (static_cast<uint32_t>(RT_HEAD_STREAM));
rt_ret = rtModelBindStream(rt_model_handle_, stream, flag);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtModelBindStream failed, ret: " << std::hex << rt_ret;
}
MS_LOG(INFO) << "stream index: " << i << ", stream: " << std::hex << stream;
}
}
void RuntimeModel::InitEvent(uint32_t event_num) {
MS_LOG(INFO) << "Event number: " << event_num;
for (uint32_t i = 0; i < event_num; ++i) {
rtEvent_t rt_event;
rtError_t rt_ret = rtEventCreate(&rt_event);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtEventCreate failed, ret: " << std::hex << rt_ret;
}
event_list_.push_back(rt_event);
}
}
void RuntimeModel::InitLabel(const std::shared_ptr<DavinciModel> &davinci_model) {
MS_LOG(INFO) << "Label number: " << davinci_model->GetBatchNum();
label_list_.resize(davinci_model->GetBatchNum());
for (auto &task_info : davinci_model->GetTaskInfoList()) {
MS_EXCEPTION_IF_NULL(task_info);
if (task_info->type() != TaskInfoType::LABEL_SET) {
continue;
}
auto label_set_task_info = std::static_pointer_cast<LabelSetTaskInfo>(task_info);
if (label_set_task_info->stream_id() >= stream_list_.size()) {
MS_LOG(EXCEPTION) << "Invalid stream id " << label_set_task_info->stream_id() << " total stream num "
<< stream_list_.size();
}
rtLabel_t rt_label = nullptr;
rtError_t rt_ret = rtLabelCreateEx(&rt_label, stream_list_[label_set_task_info->stream_id()]);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtLabelCreate failed, ret: " << std::hex << rt_ret;
}
label_list_[label_set_task_info->label_id()] = rt_label;
}
}
void RuntimeModel::InitResource(const std::shared_ptr<DavinciModel> &davinci_model) {
MS_LOG(INFO) << "InitResource start";
MS_EXCEPTION_IF_NULL(davinci_model);
rtError_t rt_ret = rtModelCreate(&rt_model_handle_, 0);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtModelCreate failed, ret: " << std::hex << rt_ret;
}
// Create rtStream for rt_model_handle_
rt_ret = rtStreamCreate(&rt_model_stream_, davinci_model->GetPriority());
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtStreamCreate failed, ret: " << std::hex << rt_ret;
}
MS_LOG(INFO) << "rtStreamCreate end";
InitStream(davinci_model);
InitEvent(davinci_model->GetEventNum());
InitLabel(davinci_model);
MS_LOG(INFO) << "InitResource success";
}
void RuntimeModel::GenerateTask(uint32_t device_id, uint64_t session_id,
const std::shared_ptr<DavinciModel> &davinci_model) {
MS_LOG(INFO) << "GenerateTask start.";
MS_EXCEPTION_IF_NULL(davinci_model);
auto task_infos = davinci_model->GetTaskInfoList();
ModelContext model_context(device_id, session_id, davinci_model->GetPriority(), rt_model_handle_, rt_model_stream_,
stream_list_, label_list_, event_list_);
for (auto &task_info : task_infos) {
auto task = TaskFactory::GetInstance().Create(model_context, task_info);
task_list_.push_back(task);
}
MS_LOG(INFO) << "GenerateTask success.";
}
void RuntimeModel::LoadComplete() {
uint32_t task_id = 0;
uint32_t stream_id = 0;
auto rt_ret = rtModelGetTaskId(rt_model_handle_, &task_id, &stream_id);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtModelGetTaskId failed, ret: " << std::hex << rt_ret;
}
task_id_list_.push_back(task_id);
stream_id_list_.push_back(stream_id);
rt_ret = rtModelLoadComplete(rt_model_handle_);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtModelLoadComplete failed, ret: " << std::hex << rt_ret;
}
}
void RuntimeModel::Load(uint32_t device_id, uint64_t session_id, const std::shared_ptr<DavinciModel> &davinci_model) {
InitResource(davinci_model);
GenerateTask(device_id, session_id, davinci_model);
}
void RuntimeModel::DistributeTask() {
MS_LOG(INFO) << "DistributeTask start.";
for (auto &task : task_list_) {
MS_EXCEPTION_IF_NULL(task);
task->Distribute();
uint32_t task_id = 0;
uint32_t stream_id = 0;
rtError_t rt_ret = rtModelGetTaskId(rt_model_handle_, &task_id, &stream_id);
if (rt_ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtModelGetTaskId failed, ret: " << std::hex << rt_ret;
}
task_id_list_.push_back(task_id);
stream_id_list_.push_back(stream_id);
if (task->Args() != nullptr) {
std::shared_ptr<RuntimeInfo> runtime_tuple = std::make_shared<RuntimeInfo>(task_id, stream_id, task->Args());
auto emplace_ret = runtime_info_map_.emplace(task->task_name(), runtime_tuple);
if (!emplace_ret.second) {
MS_LOG(WARNING) << "Task name exist: " << task->task_name();
}
}
}
if (task_list_.empty()) {
MS_LOG(EXCEPTION) << "Task list is empty";
}
MS_LOG(INFO) << "DistributeTask success.";
}
void RuntimeModel::Run() {
MS_LOG(INFO) << "Davinci task run start.";
rtError_t ret = rtModelExecute(rt_model_handle_, rt_model_stream_, 0);
if (ret != RT_ERROR_NONE) {
MS_LOG(EXCEPTION) << "Call rt api rtModelLoadComplete failed, ret: " << std::hex << ret;
}
MS_LOG(INFO) << "Run rtModelExecute success, start to rtStreamSynchronize.";
ret = rtStreamSynchronize(rt_model_stream_);
if (ret != RT_ERROR_NONE) {
if (ret == ACL_ERROR_RT_END_OF_SEQUENCE) {
MS_LOG(INFO) << "Model stream ACL_ERROR_RT_END_OF_SEQUENCE signal received.";
return;
}
MS_LOG(EXCEPTION) << "Call rt api rtStreamSynchronize failed, ret: " << std::hex << ret;
}
MS_LOG(INFO) << "Davinci task run success.";
}
void RuntimeModel::RtModelUnbindStream() noexcept {
for (size_t i = 0; i < stream_list_.size(); i++) {
if (rtModelUnbindStream(rt_model_handle_, stream_list_[i]) != RT_ERROR_NONE) {
MS_LOG(ERROR) << "Unbind stream from model failed! Index: " << i;
return;
}
}
}
void RuntimeModel::RtStreamDestory() noexcept {
if (rtStreamDestroy(rt_model_stream_) != RT_ERROR_NONE) {
MS_LOG(ERROR) << "Destroy stream for rt_model failed!";
return;
}
for (size_t i = 0; i < stream_list_.size(); i++) {
if (rtStreamDestroy(stream_list_[i]) != RT_ERROR_NONE) {
MS_LOG(ERROR) << "Destroy stream failed! Index: " << i;
return;
}
}
}
void RuntimeModel::RtLabelDestory() noexcept {
for (size_t i = 0; i < label_list_.size(); i++) {
if (label_list_[i] == nullptr) {
continue;
}
if (rtLabelDestroy(label_list_[i]) != RT_ERROR_NONE) {
MS_LOG(ERROR) << "Destroy label failed! Index: " << i;
return;
}
}
}
void RuntimeModel::RtModelDestory() noexcept {
rtError_t ret = rtModelDestroy(rt_model_handle_);
if (ret != RT_ERROR_NONE) {
MS_LOG(ERROR) << "Call rt api rtModelDestroy failed, ret: " << std::hex << ret;
return;
}
}
void RuntimeModel::RtEventDestory() noexcept {
for (size_t i = 0; i < event_list_.size(); i++) {
if (rtEventDestroy(event_list_[i]) != RT_ERROR_NONE) {
MS_LOG(ERROR) << "Destroy event failed! Index: " << i;
return;
}
}
}
const std::vector<uint32_t> &RuntimeModel::GetTaskIdList() const { return task_id_list_; }
const std::vector<uint32_t> &RuntimeModel::GetStreamIdList() const { return stream_id_list_; }
} // namespace mindspore::ge::model_runner
| 35.829352 | 118 | 0.684607 | [
"vector",
"model"
] |
e754d589dd827cf7638e9203443f81aafbb10759 | 7,162 | cpp | C++ | applications/createEVENT/MultipleSimCenterEvents.cpp | fmckenna/EE-UQ | a1fe96fd000aec933430bda5829c82b5743338c3 | [
"BSD-2-Clause"
] | 1 | 2019-04-30T19:38:17.000Z | 2019-04-30T19:38:17.000Z | applications/createEVENT/MultipleSimCenterEvents.cpp | s-m-amin-ghasemi/EE-UQ | 7eb42d09b59b42fd1256c6d8693cfe46e0b8034b | [
"BSD-2-Clause"
] | 2 | 2018-09-11T01:32:27.000Z | 2018-09-11T23:08:06.000Z | applications/createEVENT/MultipleSimCenterEvents.cpp | s-m-amin-ghasemi/EE-UQ | 7eb42d09b59b42fd1256c6d8693cfe46e0b8034b | [
"BSD-2-Clause"
] | 6 | 2018-05-14T21:45:24.000Z | 2018-10-04T18:13:42.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>
using namespace std;
#include <jansson.h> // for Json
void addEvent(const char *fileNameEvent, json_t *obj, double factor);
void addEvent(const char *fileNameEvent, json_t *obj);
int main(int argc, char **argv)
{
// StandardEarthquakeEDP --filenameBIM file --filenameEVENT file? <--getRV>
char *filenameBIM = argv[2];
char *filenameEVENT = argv[4];
// create output JSON object for EVENT file and create events array
json_t *rootEvent = json_object();
json_t *newEventArray = json_array();
// load INPUT file
json_error_t error;
json_t *rootINPUT = json_load_file(filenameBIM, 0, &error);
json_t *eventsArray = json_object_get(rootINPUT,"Events");
if (argc == 6) {
//
// if --getRV we want to set EVENT file with random variables and events that just contain name
//
// output jsonObject for any Random Variables
json_t *rvArray=json_array();
//
// parse each event in input:
// 1. make sure earthquake
// 2. add responses
//
int index;
json_t *value;
int numEDP = 0;
json_array_foreach(eventsArray, index, value) {
// check earthquake
json_t *type = json_object_get(value,"type");
const char *eventType = json_string_value(type);
if (strcmp(eventType,"ExistingSimCenterEvents") != 0) {
json_array_append(newEventArray, value); // copy event for next event app to parse
} else {
json_t *eventObj = json_object();
json_object_set(eventObj,"type", json_string("Seismic"));
json_object_set(eventObj,"subtype", json_string("MultipleSimCenterEvent"));
json_t *existingEventsArray = json_object_get(value,"Events");
int numExisting = json_array_size(existingEventsArray);
if (numExisting > 1) {
json_t *randomVar = json_object();
json_object_set(randomVar, "distribution",json_string("discrete_design_set_string"));
json_object_set(randomVar, "name",json_string("MultipleEvent"));
json_object_set(randomVar, "value",json_string("RV.MultipleEvent"));
json_t *theMultipleEvents = json_array();
json_t *existingEvent = 0;
json_array_foreach(existingEventsArray, index, existingEvent) {
json_array_append(theMultipleEvents, json_object_get(existingEvent,"name"));
}
json_object_set(randomVar, "elements", theMultipleEvents);
json_array_append(rvArray, randomVar);
json_object_set(eventObj, "index", json_string("RV.MultipleEvent"));
} else {
json_object_set(eventObj, "index", json_integer(0));
}
//add first event to event
json_t *firstEvent = json_array_get(existingEventsArray, 0);
json_t *fileValue = json_object_get(firstEvent, "fileName");
if (fileValue != NULL) {
const char *fileName = json_string_value(fileValue);
addEvent(fileName, eventObj);
}
json_array_append(newEventArray, eventObj);
}
}
// write the variables & events
json_object_set(rootEvent,"randomVariables",rvArray);
json_object_set(rootEvent,"Events",newEventArray);
// dump the event file
json_dump_file(rootEvent,filenameEVENT,0);
} else { // if not --getRV we want to copy file to EVENT fileName
//
// need to open up EVENT file and process to see which of EVENTS to use
// need to open up INPUT file to see the name of this file (it should be in dir,
// then copy file to replace EVENT
//
json_t *rootINPUT = json_load_file(filenameBIM, 0, &error);
json_t *rootEVENT = json_load_file(filenameEVENT, 0, &error);
// load INPUT file
json_error_t error;
json_t *inputEventsArray = json_object_get(rootINPUT,"Events");
json_t *eventsEventsArray = json_object_get(rootEVENT,"Events");
int count;
json_t *value;
int numEDP = 0;
json_array_foreach(eventsEventsArray, count, value) {
// check earthquake
json_t *type = json_object_get(value,"type");
const char *eventType = json_string_value(type);
if (strcmp(eventType,"Seismic") == 0) {
json_t *subType = json_object_get(value,"subtype");
if ((subType != NULL) && (strcmp("MultipleSimCenterEvent",json_string_value(subType)) ==0)) {
json_t *index = json_object_get(value,"index");
if (index != NULL) {
if (json_is_integer(index) == false) {
const char *eventName = json_string_value(index);
// we need to replace the EVENT with another event
json_t *inputEvent = json_array_get(inputEventsArray,count);
json_t *events = json_object_get(inputEvent,"Events");
for (int i=0; i<json_array_size(events); i++) {
json_t *theEvent = json_array_get(events, i);
const char * name = json_string_value(json_object_get(theEvent,"name"));
json_t *factorValue = json_object_get(theEvent,"factor");
double factor = json_number_value(json_object_get(theEvent,"factor"));
if (strcmp(eventName, name) == 0) {
const char *fileName = json_string_value(json_object_get(theEvent,"fileName"));
addEvent(fileName, value, factor);
i = json_array_size(events);
}
}
} else {
//
// we need to go get factor from input file and set it in the event
//
json_t *inputEvent = json_array_get(inputEventsArray,count);
json_t *events = json_object_get(inputEvent,"Events");
json_t *theEvent = json_array_get(events, 0);
double factor = json_number_value(json_object_get(theEvent,"factor"));
/* ********************************************* KEEPING AROUND JUST IN CASE
// add factor to timSeries
json_t *seriesArray = json_object_get(value,"timeSeries");
int countSeries = 0;
json_t *seriesValue;
json_array_foreach(seriesArray, count, seriesValue) {
json_object_set(seriesValue,"factor",json_real(factor));
}
***************************************************************************/
json_object_set(value,"factor",json_real(factor));
}
} else {
;
}
}
}
}
// write rootEvent
json_dump_file(rootEVENT,filenameEVENT,0);
}
return 0;
}
//
// procedure to open an existing event file, take first event and "UPDATE"
// the passed obj with the contents of this first event
//
void addEvent(const char *fileName, json_t *obj) {
// open file and get the first event
json_error_t error;
json_t *rootEVENT = json_load_file(fileName, 0, &error);
json_t *eventsArray = json_object_get(rootEVENT,"Events");
json_t *eventToCopy = json_array_get(eventsArray,0);
// update the object
json_object_update(obj, eventToCopy);
}
void addEvent(const char *fileName, json_t *obj, double factor) {
// open file and get the first event
json_error_t error;
json_t *rootEVENT = json_load_file(fileName, 0, &error);
json_t *eventsArray = json_object_get(rootEVENT,"Events");
json_t *eventToCopy = json_array_get(eventsArray,0);
json_object_set(eventToCopy,"factor",json_real(factor));
// update the object
json_object_update(obj, eventToCopy);
}
| 31.275109 | 99 | 0.672019 | [
"object"
] |
e75d15607daecb2de69c4dc8dede53f5c75fd5f6 | 36,708 | cpp | C++ | dali/internal/adaptor/common/adaptor-impl.cpp | Coquinho/dali-adaptor | a8006aea66b316a5eb710e634db30f566acda144 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | dali/internal/adaptor/common/adaptor-impl.cpp | Coquinho/dali-adaptor | a8006aea66b316a5eb710e634db30f566acda144 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-10-19T13:45:40.000Z | 2020-12-10T20:21:03.000Z | dali/internal/adaptor/common/adaptor-impl.cpp | expertisesolutions/dali-adaptor | 810bf4dea833ea7dfbd2a0c82193bc0b3b155011 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 Samsung Electronics 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.
*
*/
// CLASS HEADER
#include <dali/internal/adaptor/common/adaptor-impl.h>
#include <dali/internal/addons/common/addon-manager-impl.h>
#include <dali/internal/addons/common/addon-manager-factory.h>
#include <dali/internal/adaptor/common/adaptor-builder-impl.h>
// EXTERNAL INCLUDES
#include <errno.h>
#include <sys/stat.h>
#include <dali/public-api/actors/layer.h>
#include <dali/public-api/object/any.h>
#include <dali/public-api/object/object-registry.h>
#include <dali/public-api/events/wheel-event.h>
#include <dali/devel-api/actors/actor-devel.h>
#include <dali/integration-api/debug.h>
#include <dali/integration-api/core.h>
#include <dali/integration-api/context-notifier.h>
#include <dali/integration-api/profiling.h>
#include <dali/integration-api/input-options.h>
#include <dali/integration-api/events/key-event-integ.h>
#include <dali/integration-api/events/touch-event-integ.h>
#include <dali/integration-api/events/wheel-event-integ.h>
#include <dali/integration-api/processor-interface.h>
#include <dali/integration-api/addon-manager.h>
// INTERNAL INCLUDES
#include <dali/public-api/dali-adaptor-common.h>
#include <dali/internal/system/common/thread-controller.h>
#include <dali/internal/system/common/performance-interface-factory.h>
#include <dali/internal/adaptor/common/lifecycle-observer.h>
#include <dali/internal/adaptor/common/thread-controller-interface.h>
#include <dali/internal/graphics/gles/egl-graphics-factory.h>
#include <dali/internal/graphics/gles/egl-graphics.h> // Temporary until Core is abstracted
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/internal/system/common/callback-manager.h>
#include <dali/internal/accessibility/common/tts-player-impl.h>
#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
#include <dali/internal/window-system/common/event-handler.h>
#include <dali/internal/graphics/gles/gl-proxy-implementation.h>
#include <dali/internal/graphics/gles/gl-implementation.h>
#include <dali/internal/graphics/gles/egl-sync-implementation.h>
#include <dali/internal/graphics/common/egl-image-extensions.h>
#include <dali/internal/clipboard/common/clipboard-impl.h>
#include <dali/internal/system/common/object-profiler.h>
#include <dali/internal/window-system/common/display-connection.h>
#include <dali/internal/window-system/common/display-utils.h> // For Utils::MakeUnique
#include <dali/internal/window-system/common/window-impl.h>
#include <dali/internal/window-system/common/window-render-surface.h>
#include <dali/internal/system/common/logging.h>
#include <dali/internal/system/common/locale-utils.h>
#include <dali/internal/imaging/common/image-loader-plugin-proxy.h>
#include <dali/internal/imaging/common/image-loader.h>
#include <dali/internal/system/common/configuration-manager.h>
#include <dali/internal/system/common/environment-variables.h>
using Dali::TextAbstraction::FontClient;
extern std::string GetSystemCachePath();
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
thread_local Adaptor* gThreadLocalAdaptor = NULL; // raw thread specific pointer to allow Adaptor::Get
} // unnamed namespace
Dali::Adaptor* Adaptor::New( Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface *surface, EnvironmentOptions* environmentOptions, ThreadMode threadMode )
{
Dali::Adaptor* adaptor = new Dali::Adaptor;
Adaptor* impl = new Adaptor( window, *adaptor, surface, environmentOptions, threadMode );
adaptor->mImpl = impl;
Dali::Internal::Adaptor::AdaptorBuilder* mAdaptorBuilder = new AdaptorBuilder();
auto graphicsFactory = mAdaptorBuilder->GetGraphicsFactory();
impl->Initialize( graphicsFactory );
delete mAdaptorBuilder; // Not needed anymore as the graphics interface has now been created
return adaptor;
}
Dali::Adaptor* Adaptor::New( Dali::Integration::SceneHolder window, EnvironmentOptions* environmentOptions )
{
Internal::Adaptor::SceneHolder& windowImpl = Dali::GetImplementation( window );
Dali::Adaptor* adaptor = New( window, windowImpl.GetSurface(), environmentOptions, ThreadMode::NORMAL );
windowImpl.SetAdaptor( *adaptor );
return adaptor;
}
Dali::Adaptor* Adaptor::New( GraphicsFactory& graphicsFactory, Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface *surface, EnvironmentOptions* environmentOptions, ThreadMode threadMode )
{
Dali::Adaptor* adaptor = new Dali::Adaptor; // Public adaptor
Adaptor* impl = new Adaptor( window, *adaptor, surface, environmentOptions, threadMode ); // Impl adaptor
adaptor->mImpl = impl;
impl->Initialize( graphicsFactory );
return adaptor;
} // Called second
Dali::Adaptor* Adaptor::New( GraphicsFactory& graphicsFactory, Dali::Integration::SceneHolder window, EnvironmentOptions* environmentOptions )
{
Internal::Adaptor::SceneHolder& windowImpl = Dali::GetImplementation( window );
Dali::Adaptor* adaptor = New( graphicsFactory, window, windowImpl.GetSurface(), environmentOptions, ThreadMode::NORMAL );
windowImpl.SetAdaptor( *adaptor );
return adaptor;
} // Called first
void Adaptor::Initialize( GraphicsFactory& graphicsFactory )
{
// all threads here (event, update, and render) will send their logs to TIZEN Platform's LogMessage handler.
Dali::Integration::Log::LogFunction logFunction( Dali::TizenPlatform::LogMessage );
mEnvironmentOptions->SetLogFunction( logFunction );
mEnvironmentOptions->InstallLogFunction(); // install logging for main thread
mPlatformAbstraction = new TizenPlatform::TizenPlatformAbstraction;
std::string path;
GetDataStoragePath( path );
mPlatformAbstraction->SetDataStoragePath( path );
if( mEnvironmentOptions->PerformanceServerRequired() )
{
mPerformanceInterface = PerformanceInterfaceFactory::CreateInterface( *this, *mEnvironmentOptions );
}
mEnvironmentOptions->CreateTraceManager( mPerformanceInterface );
mEnvironmentOptions->InstallTraceFunction(); // install tracing for main thread
mCallbackManager = CallbackManager::New();
Dali::Internal::Adaptor::SceneHolder* defaultWindow = mWindows.front();
DALI_ASSERT_DEBUG( defaultWindow->GetSurface() && "Surface not initialized" );
mGraphics = std::unique_ptr< GraphicsInterface >( &graphicsFactory.Create() );
mGraphics->Initialize( mEnvironmentOptions );
GraphicsInterface* graphics = mGraphics.get(); // This interface is temporary until Core has been updated to match
auto eglGraphics = static_cast<EglGraphics *>( graphics );
// This will only be created once
eglGraphics->Create();
GlImplementation& mGLES = eglGraphics->GetGlesInterface();
EglSyncImplementation& eglSyncImpl = eglGraphics->GetSyncImplementation();
EglContextHelperImplementation& eglContextHelperImpl = eglGraphics->GetContextHelperImplementation();
// Create the AddOnManager
mAddOnManager.reset( Dali::Internal::AddOnManagerFactory::CreateAddOnManager() );
mCore = Integration::Core::New( *this,
*mPlatformAbstraction,
mGLES,
eglSyncImpl,
eglContextHelperImpl,
( 0u != mEnvironmentOptions->GetRenderToFboInterval() ) ? Integration::RenderToFrameBuffer::TRUE : Integration::RenderToFrameBuffer::FALSE,
mGraphics->GetDepthBufferRequired(),
mGraphics->GetStencilBufferRequired(),
mGraphics->GetPartialUpdateRequired() );
defaultWindow->SetAdaptor( Get() );
Dali::Integration::SceneHolder defaultSceneHolder( defaultWindow );
mWindowCreatedSignal.Emit( defaultSceneHolder );
const unsigned int timeInterval = mEnvironmentOptions->GetObjectProfilerInterval();
if( 0u < timeInterval )
{
mObjectProfiler = new ObjectProfiler( mCore->GetObjectRegistry(), timeInterval );
}
mNotificationTrigger = TriggerEventFactory::CreateTriggerEvent( MakeCallback( this, &Adaptor::ProcessCoreEvents ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER);
mDisplayConnection = Dali::DisplayConnection::New( *mGraphics, defaultWindow->GetSurface()->GetSurfaceType() );
mThreadController = new ThreadController( *this, *mEnvironmentOptions, mThreadMode );
// Should be called after Core creation
if( mEnvironmentOptions->GetPanGestureLoggingLevel() )
{
Integration::EnableProfiling( Dali::Integration::PROFILING_TYPE_PAN_GESTURE );
}
if( mEnvironmentOptions->GetPanGesturePredictionMode() >= 0 )
{
Integration::SetPanGesturePredictionMode(mEnvironmentOptions->GetPanGesturePredictionMode());
}
if( mEnvironmentOptions->GetPanGesturePredictionAmount() >= 0 )
{
Integration::SetPanGesturePredictionAmount(mEnvironmentOptions->GetPanGesturePredictionAmount());
}
if( mEnvironmentOptions->GetPanGestureMaximumPredictionAmount() >= 0 )
{
Integration::SetPanGestureMaximumPredictionAmount(mEnvironmentOptions->GetPanGestureMaximumPredictionAmount());
}
if( mEnvironmentOptions->GetPanGestureMinimumPredictionAmount() >= 0 )
{
Integration::SetPanGestureMinimumPredictionAmount(mEnvironmentOptions->GetPanGestureMinimumPredictionAmount());
}
if( mEnvironmentOptions->GetPanGesturePredictionAmountAdjustment() >= 0 )
{
Integration::SetPanGesturePredictionAmountAdjustment(mEnvironmentOptions->GetPanGesturePredictionAmountAdjustment());
}
if( mEnvironmentOptions->GetPanGestureSmoothingMode() >= 0 )
{
Integration::SetPanGestureSmoothingMode(mEnvironmentOptions->GetPanGestureSmoothingMode());
}
if( mEnvironmentOptions->GetPanGestureSmoothingAmount() >= 0.0f )
{
Integration::SetPanGestureSmoothingAmount(mEnvironmentOptions->GetPanGestureSmoothingAmount());
}
if( mEnvironmentOptions->GetPanGestureUseActualTimes() >= 0 )
{
Integration::SetPanGestureUseActualTimes( mEnvironmentOptions->GetPanGestureUseActualTimes() == 0 ? true : false );
}
if( mEnvironmentOptions->GetPanGestureInterpolationTimeRange() >= 0 )
{
Integration::SetPanGestureInterpolationTimeRange( mEnvironmentOptions->GetPanGestureInterpolationTimeRange() );
}
if( mEnvironmentOptions->GetPanGestureScalarOnlyPredictionEnabled() >= 0 )
{
Integration::SetPanGestureScalarOnlyPredictionEnabled( mEnvironmentOptions->GetPanGestureScalarOnlyPredictionEnabled() == 0 ? true : false );
}
if( mEnvironmentOptions->GetPanGestureTwoPointPredictionEnabled() >= 0 )
{
Integration::SetPanGestureTwoPointPredictionEnabled( mEnvironmentOptions->GetPanGestureTwoPointPredictionEnabled() == 0 ? true : false );
}
if( mEnvironmentOptions->GetPanGestureTwoPointInterpolatePastTime() >= 0 )
{
Integration::SetPanGestureTwoPointInterpolatePastTime( mEnvironmentOptions->GetPanGestureTwoPointInterpolatePastTime() );
}
if( mEnvironmentOptions->GetPanGestureTwoPointVelocityBias() >= 0.0f )
{
Integration::SetPanGestureTwoPointVelocityBias( mEnvironmentOptions->GetPanGestureTwoPointVelocityBias() );
}
if( mEnvironmentOptions->GetPanGestureTwoPointAccelerationBias() >= 0.0f )
{
Integration::SetPanGestureTwoPointAccelerationBias( mEnvironmentOptions->GetPanGestureTwoPointAccelerationBias() );
}
if( mEnvironmentOptions->GetPanGestureMultitapSmoothingRange() >= 0 )
{
Integration::SetPanGestureMultitapSmoothingRange( mEnvironmentOptions->GetPanGestureMultitapSmoothingRange() );
}
if( mEnvironmentOptions->GetMinimumPanDistance() >= 0 )
{
Integration::SetPanGestureMinimumDistance( mEnvironmentOptions->GetMinimumPanDistance() );
}
if( mEnvironmentOptions->GetMinimumPanEvents() >= 0 )
{
Integration::SetPanGestureMinimumPanEvents( mEnvironmentOptions->GetMinimumPanEvents() );
}
if( mEnvironmentOptions->GetMinimumPinchDistance() >= 0 )
{
Integration::SetPinchGestureMinimumDistance( mEnvironmentOptions->GetMinimumPinchDistance() );
}
if( mEnvironmentOptions->GetMinimumPinchTouchEvents() >= 0 )
{
Integration::SetPinchGestureMinimumTouchEvents( mEnvironmentOptions->GetMinimumPinchTouchEvents() );
}
if( mEnvironmentOptions->GetMinimumPinchTouchEventsAfterStart() >= 0 )
{
Integration::SetPinchGestureMinimumTouchEventsAfterStart( mEnvironmentOptions->GetMinimumPinchTouchEventsAfterStart() );
}
if( mEnvironmentOptions->GetMinimumRotationTouchEvents() >= 0 )
{
Integration::SetRotationGestureMinimumTouchEvents( mEnvironmentOptions->GetMinimumRotationTouchEvents() );
}
if( mEnvironmentOptions->GetMinimumRotationTouchEventsAfterStart() >= 0 )
{
Integration::SetRotationGestureMinimumTouchEventsAfterStart( mEnvironmentOptions->GetMinimumRotationTouchEventsAfterStart() );
}
if( mEnvironmentOptions->GetLongPressMinimumHoldingTime() >= 0 )
{
Integration::SetLongPressMinimumHoldingTime( mEnvironmentOptions->GetLongPressMinimumHoldingTime() );
}
std::string systemCachePath = GetSystemCachePath();
if( ! systemCachePath.empty() )
{
const int dir_err = mkdir( systemCachePath.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH );
if ( 0 != dir_err && errno != EEXIST )
{
DALI_LOG_ERROR( "Error creating system cache directory: %s!\n", systemCachePath.c_str() );
exit( 1 );
}
}
mConfigurationManager = Utils::MakeUnique<ConfigurationManager>( systemCachePath, eglGraphics, mThreadController );
}
Adaptor::~Adaptor()
{
// Ensure stop status
Stop();
// set to NULL first as we do not want any access to Adaptor as it is being destroyed.
gThreadLocalAdaptor = NULL;
for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
{
(*iter)->OnDestroy();
}
// Clear out all the handles to Windows
mWindows.clear();
delete mThreadController; // this will shutdown render thread, which will call Core::ContextDestroyed before exit
delete mObjectProfiler;
delete mCore;
delete mDisplayConnection;
delete mPlatformAbstraction;
delete mCallbackManager;
delete mPerformanceInterface;
mGraphics->Destroy();
// uninstall it on this thread (main actor thread)
Dali::Integration::Log::UninstallLogFunction();
// Delete environment options if we own it
if( mEnvironmentOptionsOwned )
{
delete mEnvironmentOptions;
}
}
void Adaptor::Start()
{
// It doesn't support restart after stop at this moment to support restarting, need more testing
if( READY != mState )
{
return;
}
mCore->Initialize();
SetupSystemInformation();
// Start the callback manager
mCallbackManager->Start();
Dali::Internal::Adaptor::SceneHolder* defaultWindow = mWindows.front();
unsigned int dpiHor, dpiVer;
dpiHor = dpiVer = 0;
defaultWindow->GetSurface()->GetDpi( dpiHor, dpiVer );
// set the DPI value for font rendering
FontClient fontClient = FontClient::Get();
fontClient.SetDpi( dpiHor, dpiVer );
// Initialize the thread controller
mThreadController->Initialize();
// Set max texture size
if( mEnvironmentOptions->GetMaxTextureSize() > 0 )
{
Dali::TizenPlatform::ImageLoader::SetMaxTextureSize( mEnvironmentOptions->GetMaxTextureSize() );
}
else
{
unsigned int maxTextureSize = mConfigurationManager->GetMaxTextureSize();
Dali::TizenPlatform::ImageLoader::SetMaxTextureSize( maxTextureSize );
}
ProcessCoreEvents(); // Ensure any startup messages are processed.
// Initialize the image loader plugin
Internal::Adaptor::ImageLoaderPluginProxy::Initialize();
for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
{
(*iter)->OnStart();
}
if (mAddOnManager)
{
mAddOnManager->Start();
}
}
// Dali::Internal::Adaptor::Adaptor::Pause
void Adaptor::Pause()
{
// Only pause the adaptor if we're actually running.
if( RUNNING == mState )
{
// Inform observers that we are about to be paused.
for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
{
(*iter)->OnPause();
}
// Extensions
if (mAddOnManager)
{
mAddOnManager->Pause();
}
// Pause all windows event handlers when adaptor paused
for( auto window : mWindows )
{
window->Pause();
}
mThreadController->Pause();
mState = PAUSED;
// Ensure any messages queued during pause callbacks are processed by doing another update.
RequestUpdateOnce();
DALI_LOG_RELEASE_INFO( "Adaptor::Pause: Paused\n" );
}
else
{
DALI_LOG_RELEASE_INFO( "Adaptor::Pause: Not paused [%d]\n", mState );
}
}
// Dali::Internal::Adaptor::Adaptor::Resume
void Adaptor::Resume()
{
// Only resume the adaptor if we are in the suspended state.
if( PAUSED == mState )
{
mState = RUNNING;
// Reset the event handlers when adaptor resumed
for( auto window : mWindows )
{
window->Resume();
}
// Resume AddOnManager
if (mAddOnManager)
{
mAddOnManager->Resume();
}
// Inform observers that we have resumed.
for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
{
(*iter)->OnResume();
}
// Trigger processing of events queued up while paused
mCore->ProcessEvents();
// Do at end to ensure our first update/render after resumption includes the processed messages as well
mThreadController->Resume();
DALI_LOG_RELEASE_INFO( "Adaptor::Resume: Resumed\n");
}
else
{
DALI_LOG_RELEASE_INFO( "Adaptor::Resume: Not resumed [%d]\n", mState );
}
}
void Adaptor::Stop()
{
if( RUNNING == mState ||
PAUSED == mState ||
PAUSED_WHILE_HIDDEN == mState )
{
for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
{
(*iter)->OnStop();
}
if (mAddOnManager)
{
mAddOnManager->Stop();
}
mThreadController->Stop();
// Delete the TTS player
for( int i =0; i < Dali::TtsPlayer::MODE_NUM; i++ )
{
if( mTtsPlayers[i] )
{
mTtsPlayers[i].Reset();
}
}
// Destroy the image loader plugin
Internal::Adaptor::ImageLoaderPluginProxy::Destroy();
delete mNotificationTrigger;
mNotificationTrigger = NULL;
mCallbackManager->Stop();
mState = STOPPED;
DALI_LOG_RELEASE_INFO( "Adaptor::Stop\n" );
}
}
void Adaptor::ContextLost()
{
mCore->GetContextNotifier()->NotifyContextLost(); // Inform stage
}
void Adaptor::ContextRegained()
{
// Inform core, so that texture resources can be reloaded
mCore->RecoverFromContextLoss();
mCore->GetContextNotifier()->NotifyContextRegained(); // Inform stage
}
void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp )
{
Integration::Point convertedPoint( point );
mWindows.front()->FeedTouchPoint( convertedPoint, timeStamp );
}
void Adaptor::FeedWheelEvent( Dali::WheelEvent& wheelEvent )
{
Integration::WheelEvent event( static_cast< Integration::WheelEvent::Type >( wheelEvent.GetType() ), wheelEvent.GetDirection(), wheelEvent.GetModifiers(), wheelEvent.GetPoint(), wheelEvent.GetDelta(), wheelEvent.GetTime() );
mWindows.front()->FeedWheelEvent( event );
}
void Adaptor::FeedKeyEvent( Dali::KeyEvent& keyEvent )
{
Integration::KeyEvent convertedEvent( keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast< Integration::KeyEvent::State >( keyEvent.GetState() ), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass() );
mWindows.front()->FeedKeyEvent( convertedEvent );
}
void Adaptor::ReplaceSurface( Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& newSurface )
{
Internal::Adaptor::SceneHolder* windowImpl = &Dali::GetImplementation( window );
for( auto windowPtr : mWindows )
{
if( windowPtr == windowImpl ) // the window is not deleted
{
mResizedSignal.Emit( mAdaptor );
windowImpl->SetSurface( &newSurface );
// Flush the event queue to give the update-render thread chance
// to start processing messages for new camera setup etc as soon as possible
ProcessCoreEvents();
// This method blocks until the render thread has completed the replace.
mThreadController->ReplaceSurface( &newSurface );
break;
}
}
}
void Adaptor::DeleteSurface( Dali::RenderSurfaceInterface& surface )
{
// Flush the event queue to give the update-render thread chance
// to start processing messages for new camera setup etc as soon as possible
ProcessCoreEvents();
// This method blocks until the render thread has finished rendering the current surface.
mThreadController->DeleteSurface( &surface );
}
Dali::RenderSurfaceInterface& Adaptor::GetSurface() const
{
return *mWindows.front()->GetSurface();
}
void Adaptor::ReleaseSurfaceLock()
{
mWindows.front()->GetSurface()->ReleaseLock();
}
Dali::TtsPlayer Adaptor::GetTtsPlayer(Dali::TtsPlayer::Mode mode)
{
if( !mTtsPlayers[mode] )
{
// Create the TTS player when it needed, because it can reduce launching time.
mTtsPlayers[mode] = TtsPlayer::New(mode);
}
return mTtsPlayers[mode];
}
bool Adaptor::AddIdle( CallbackBase* callback, bool hasReturnValue, bool forceAdd )
{
bool idleAdded(false);
// Only add an idle if the Adaptor is actually running
if( RUNNING == mState || READY == mState || forceAdd )
{
idleAdded = mCallbackManager->AddIdleCallback( callback, hasReturnValue );
}
return idleAdded;
}
void Adaptor::RemoveIdle( CallbackBase* callback )
{
mCallbackManager->RemoveIdleCallback( callback );
}
void Adaptor::ProcessIdle()
{
bool idleProcessed = mCallbackManager->ProcessIdle();
mNotificationOnIdleInstalled = mNotificationOnIdleInstalled && !idleProcessed;
}
void Adaptor::SetPreRenderCallback( CallbackBase* callback )
{
mThreadController->SetPreRenderCallback( callback );
}
bool Adaptor::AddWindow( Dali::Integration::SceneHolder childWindow )
{
Internal::Adaptor::SceneHolder& windowImpl = Dali::GetImplementation( childWindow );
windowImpl.SetAdaptor( Get() );
// ChildWindow is set to the layout direction of the default window.
windowImpl.GetRootLayer().SetProperty( Dali::Actor::Property::LAYOUT_DIRECTION, mRootLayoutDirection );
// Add the new Window to the container - the order is not important
mWindows.push_back( &windowImpl );
Dali::RenderSurfaceInterface* surface = windowImpl.GetSurface();
mThreadController->AddSurface( surface );
mWindowCreatedSignal.Emit( childWindow );
return true;
}
bool Adaptor::RemoveWindow( Dali::Integration::SceneHolder* childWindow )
{
Internal::Adaptor::SceneHolder& windowImpl = Dali::GetImplementation( *childWindow );
for ( WindowContainer::iterator iter = mWindows.begin(); iter != mWindows.end(); ++iter )
{
if( *iter == &windowImpl )
{
mWindows.erase( iter );
return true;
}
}
return false;
}
bool Adaptor::RemoveWindow( std::string childWindowName )
{
for ( WindowContainer::iterator iter = mWindows.begin(); iter != mWindows.end(); ++iter )
{
if( ( *iter )->GetName() == childWindowName )
{
mWindows.erase( iter );
return true;
}
}
return false;
}
bool Adaptor::RemoveWindow( Internal::Adaptor::SceneHolder* childWindow )
{
for ( WindowContainer::iterator iter = mWindows.begin(); iter != mWindows.end(); ++iter )
{
if( ( *iter )->GetId() == childWindow->GetId() )
{
mWindows.erase( iter );
return true;
}
}
return false;
}
Dali::Adaptor& Adaptor::Get()
{
DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" );
return gThreadLocalAdaptor->mAdaptor;
}
bool Adaptor::IsAvailable()
{
return gThreadLocalAdaptor != NULL;
}
void Adaptor::SceneCreated()
{
mCore->SceneCreated();
}
Dali::Integration::Core& Adaptor::GetCore()
{
return *mCore;
}
void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender )
{
mThreadController->SetRenderRefreshRate( numberOfVSyncsPerRender );
}
Dali::DisplayConnection& Adaptor::GetDisplayConnectionInterface()
{
DALI_ASSERT_DEBUG( mDisplayConnection && "Display connection not created" );
return *mDisplayConnection;
}
GraphicsInterface& Adaptor::GetGraphicsInterface()
{
DALI_ASSERT_DEBUG( mGraphics && "Graphics interface not created" );
return *( mGraphics.get() );
}
Dali::Integration::PlatformAbstraction& Adaptor::GetPlatformAbstractionInterface()
{
return *mPlatformAbstraction;
}
TriggerEventInterface& Adaptor::GetProcessCoreEventsTrigger()
{
return *mNotificationTrigger;
}
SocketFactoryInterface& Adaptor::GetSocketFactoryInterface()
{
return mSocketFactory;
}
Dali::RenderSurfaceInterface* Adaptor::GetRenderSurfaceInterface()
{
if( !mWindows.empty() )
{
return mWindows.front()->GetSurface();
}
return nullptr;
}
TraceInterface& Adaptor::GetKernelTraceInterface()
{
return mKernelTracer;
}
TraceInterface& Adaptor::GetSystemTraceInterface()
{
return mSystemTracer;
}
PerformanceInterface* Adaptor::GetPerformanceInterface()
{
return mPerformanceInterface;
}
Integration::PlatformAbstraction& Adaptor::GetPlatformAbstraction() const
{
DALI_ASSERT_DEBUG( mPlatformAbstraction && "PlatformAbstraction not created" );
return *mPlatformAbstraction;
}
void Adaptor::GetWindowContainerInterface( WindowContainer& windows )
{
windows = mWindows;
}
void Adaptor::DestroyTtsPlayer(Dali::TtsPlayer::Mode mode)
{
if( mTtsPlayers[mode] )
{
mTtsPlayers[mode].Reset();
}
}
Any Adaptor::GetNativeWindowHandle()
{
return mWindows.front()->GetNativeHandle();
}
Any Adaptor::GetNativeWindowHandle( Dali::Actor actor )
{
Any nativeWindowHandle;
Dali::Integration::Scene scene = Dali::Integration::Scene::Get( actor );
for( auto sceneHolder : mWindows )
{
if ( scene == sceneHolder->GetScene() )
{
nativeWindowHandle = sceneHolder->GetNativeHandle();
break;
}
}
return nativeWindowHandle;
}
Any Adaptor::GetGraphicsDisplay()
{
Any display;
if (mGraphics)
{
GraphicsInterface* graphics = mGraphics.get(); // This interface is temporary until Core has been updated to match
auto eglGraphics = static_cast<EglGraphics *>( graphics );
EglImplementation& eglImpl = eglGraphics->GetEglImplementation();
display = eglImpl.GetDisplay();
}
return display;
}
void Adaptor::SetUseRemoteSurface(bool useRemoteSurface)
{
mUseRemoteSurface = useRemoteSurface;
}
void Adaptor::AddObserver( LifeCycleObserver& observer )
{
ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) );
if ( match == mObservers.end() )
{
mObservers.push_back( &observer );
}
}
void Adaptor::RemoveObserver( LifeCycleObserver& observer )
{
ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) );
if ( match != mObservers.end() )
{
mObservers.erase( match );
}
}
void Adaptor::QueueCoreEvent(const Dali::Integration::Event& event)
{
if( mCore )
{
mCore->QueueEvent(event);
}
}
void Adaptor::ProcessCoreEvents()
{
if( mCore )
{
if( mPerformanceInterface )
{
mPerformanceInterface->AddMarker( PerformanceInterface::PROCESS_EVENTS_START );
}
mCore->ProcessEvents();
if( mPerformanceInterface )
{
mPerformanceInterface->AddMarker( PerformanceInterface::PROCESS_EVENTS_END );
}
}
}
void Adaptor::RequestUpdate( bool forceUpdate )
{
switch( mState )
{
case RUNNING:
{
mThreadController->RequestUpdate();
break;
}
case PAUSED:
case PAUSED_WHILE_HIDDEN:
{
if( forceUpdate )
{
// Update (and resource upload) without rendering
mThreadController->RequestUpdateOnce( UpdateMode::SKIP_RENDER );
}
break;
}
default:
{
// Do nothing
break;
}
}
}
void Adaptor::RequestProcessEventsOnIdle( bool forceProcess )
{
// Only request a notification if the Adaptor is actually running
// and we haven't installed the idle notification
if( ( ! mNotificationOnIdleInstalled ) && ( RUNNING == mState || READY == mState || forceProcess ) )
{
mNotificationOnIdleInstalled = AddIdleEnterer( MakeCallback( this, &Adaptor::ProcessCoreEventsFromIdle ), forceProcess );
}
}
void Adaptor::OnWindowShown()
{
if( PAUSED_WHILE_HIDDEN == mState )
{
// Adaptor can now be resumed
mState = PAUSED;
Resume();
// Force a render task
RequestUpdateOnce();
}
else if( RUNNING == mState )
{
// Force a render task
RequestUpdateOnce();
DALI_LOG_RELEASE_INFO( "Adaptor::OnWindowShown: Update requested.\n" );
}
else if( PAUSED_WHILE_INITIALIZING == mState )
{
// Change the state to READY again. It will be changed to RUNNING after the adaptor is started.
mState = READY;
}
else
{
DALI_LOG_RELEASE_INFO( "Adaptor::OnWindowShown: Adaptor is not paused state.[%d]\n", mState );
}
}
void Adaptor::OnWindowHidden()
{
if( RUNNING == mState || READY == mState )
{
bool allWindowsHidden = true;
for( auto window : mWindows )
{
if ( window->IsVisible() )
{
allWindowsHidden = false;
break;
}
}
// Only pause the adaptor when all the windows are hidden
if( allWindowsHidden )
{
if( mState == RUNNING )
{
Pause();
// Adaptor cannot be resumed until any window is shown
mState = PAUSED_WHILE_HIDDEN;
}
else // mState is READY
{
// Pause the adaptor after the state gets RUNNING
mState = PAUSED_WHILE_INITIALIZING;
}
}
else
{
DALI_LOG_RELEASE_INFO( "Adaptor::OnWindowHidden: Some windows are shown. Don't pause adaptor.\n" );
}
}
else
{
DALI_LOG_RELEASE_INFO( "Adaptor::OnWindowHidden: Adaptor is not running state.[%d]\n", mState );
}
}
// Dali::Internal::Adaptor::Adaptor::OnDamaged
void Adaptor::OnDamaged( const DamageArea& area )
{
// This is needed for the case where Dali window is partially obscured
RequestUpdate( false );
}
void Adaptor::SurfaceResizePrepare( Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize )
{
mResizedSignal.Emit( mAdaptor );
}
void Adaptor::SurfaceResizeComplete( Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize )
{
// Nofify surface resizing before flushing event queue
mThreadController->ResizeSurface();
// Flush the event queue to give the update-render thread chance
// to start processing messages for new camera setup etc as soon as possible
ProcessCoreEvents();
}
void Adaptor::NotifySceneCreated()
{
GetCore().SceneCreated();
// Flush the event queue to give the update-render thread chance
// to start processing messages for new camera setup etc as soon as possible
ProcessCoreEvents();
// Start thread controller after the scene has been created
mThreadController->Start();
// Process after surface is created (registering to remote surface provider if required)
SurfaceInitialized();
if( mState != PAUSED_WHILE_INITIALIZING )
{
mState = RUNNING;
DALI_LOG_RELEASE_INFO( "Adaptor::NotifySceneCreated: Adaptor is running\n" );
}
else
{
mState = RUNNING;
Pause();
mState = PAUSED_WHILE_HIDDEN;
DALI_LOG_RELEASE_INFO( "Adaptor::NotifySceneCreated: Adaptor is paused\n" );
}
}
void Adaptor::NotifyLanguageChanged()
{
mLanguageChangedSignal.Emit( mAdaptor );
}
void Adaptor::RenderOnce()
{
if( mThreadController )
{
UpdateMode updateMode;
if( mThreadMode == ThreadMode::NORMAL )
{
updateMode = UpdateMode::NORMAL;
}
else
{
updateMode = UpdateMode::FORCE_RENDER;
ProcessCoreEvents();
}
mThreadController->RequestUpdateOnce( updateMode );
}
}
const LogFactoryInterface& Adaptor::GetLogFactory()
{
return *mEnvironmentOptions;
}
void Adaptor::RegisterProcessor( Integration::Processor& processor )
{
GetCore().RegisterProcessor(processor);
}
void Adaptor::UnregisterProcessor( Integration::Processor& processor )
{
GetCore().UnregisterProcessor(processor);
}
bool Adaptor::IsMultipleWindowSupported() const
{
return mConfigurationManager->IsMultipleWindowSupported();
}
void Adaptor::RequestUpdateOnce()
{
if( mThreadController )
{
mThreadController->RequestUpdateOnce( UpdateMode::NORMAL );
}
}
bool Adaptor::ProcessCoreEventsFromIdle()
{
ProcessCoreEvents();
// the idle handle automatically un-installs itself
mNotificationOnIdleInstalled = false;
return false;
}
Dali::Internal::Adaptor::SceneHolder* Adaptor::GetWindow( Dali::Actor& actor )
{
Dali::Integration::Scene scene = Dali::Integration::Scene::Get( actor );
for( auto window : mWindows )
{
if ( scene == window->GetScene() )
{
return window;
}
}
return nullptr;
}
Dali::WindowContainer Adaptor::GetWindows() const
{
Dali::WindowContainer windows;
for ( auto iter = mWindows.begin(); iter != mWindows.end(); ++iter )
{
// Downcast to Dali::Window
Dali::Window window( dynamic_cast<Dali::Internal::Adaptor::Window*>( *iter ) );
if ( window )
{
windows.push_back( window );
}
}
return windows;
}
Dali::SceneHolderList Adaptor::GetSceneHolders() const
{
Dali::SceneHolderList sceneHolderList;
for( auto iter = mWindows.begin(); iter != mWindows.end(); ++iter )
{
sceneHolderList.push_back( Dali::Integration::SceneHolder( *iter ) );
}
return sceneHolderList;
}
Dali::ObjectRegistry Adaptor::GetObjectRegistry() const
{
Dali::ObjectRegistry registry;
if( mCore )
{
registry = mCore->GetObjectRegistry();
}
return registry;
}
Adaptor::Adaptor(Dali::Integration::SceneHolder window, Dali::Adaptor& adaptor, Dali::RenderSurfaceInterface* surface, EnvironmentOptions* environmentOptions, ThreadMode threadMode )
: mResizedSignal(),
mLanguageChangedSignal(),
mWindowCreatedSignal(),
mAdaptor( adaptor ),
mState( READY ),
mCore( nullptr ),
mThreadController( nullptr ),
mGraphics( nullptr ),
mDisplayConnection( nullptr ),
mWindows(),
mConfigurationManager( nullptr ),
mPlatformAbstraction( nullptr ),
mCallbackManager( nullptr ),
mNotificationOnIdleInstalled( false ),
mNotificationTrigger( nullptr ),
mDaliFeedbackPlugin(),
mFeedbackController( nullptr ),
mTtsPlayers(),
mObservers(),
mEnvironmentOptions( environmentOptions ? environmentOptions : new EnvironmentOptions /* Create the options if not provided */),
mPerformanceInterface( nullptr ),
mKernelTracer(),
mSystemTracer(),
mObjectProfiler( nullptr ),
mSocketFactory(),
mThreadMode( threadMode ),
mEnvironmentOptionsOwned( environmentOptions ? false : true /* If not provided then we own the object */ ),
mUseRemoteSurface( false ),
mRootLayoutDirection( Dali::LayoutDirection::LEFT_TO_RIGHT )
{
DALI_ASSERT_ALWAYS( !IsAvailable() && "Cannot create more than one Adaptor per thread" );
mWindows.insert( mWindows.begin(), &Dali::GetImplementation( window ) );
gThreadLocalAdaptor = this;
}
void Adaptor::SetRootLayoutDirection( std::string locale )
{
mRootLayoutDirection = static_cast< LayoutDirection::Type >( Internal::Adaptor::Locale::GetDirection( std::string( locale ) ) );
for ( auto& window : mWindows )
{
Dali::Actor root = window->GetRootLayer();
root.SetProperty( Dali::Actor::Property::LAYOUT_DIRECTION, mRootLayoutDirection );
}
}
bool Adaptor::AddIdleEnterer( CallbackBase* callback, bool forceAdd )
{
bool idleAdded( false );
// Only add an idle if the Adaptor is actually running
if( RUNNING == mState || READY == mState || forceAdd )
{
idleAdded = mCallbackManager->AddIdleEntererCallback( callback );
}
if( !idleAdded )
{
// Delete callback
delete callback;
}
return idleAdded;
}
void Adaptor::RemoveIdleEnterer( CallbackBase* callback )
{
mCallbackManager->RemoveIdleEntererCallback( callback );
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
| 29.226115 | 359 | 0.72333 | [
"render",
"object"
] |
e7645f3261966a103e687f6ba99d99a18f932b2e | 3,821 | cpp | C++ | aws-cpp-sdk-ssm/source/model/StepExecutionFilterKey.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2020-07-16T19:03:13.000Z | 2020-07-16T19:03:13.000Z | aws-cpp-sdk-ssm/source/model/StepExecutionFilterKey.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-ssm/source/model/StepExecutionFilterKey.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2019-10-31T11:19:50.000Z | 2019-10-31T11:19:50.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/ssm/model/StepExecutionFilterKey.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace SSM
{
namespace Model
{
namespace StepExecutionFilterKeyMapper
{
static const int StartTimeBefore_HASH = HashingUtils::HashString("StartTimeBefore");
static const int StartTimeAfter_HASH = HashingUtils::HashString("StartTimeAfter");
static const int StepExecutionStatus_HASH = HashingUtils::HashString("StepExecutionStatus");
static const int StepExecutionId_HASH = HashingUtils::HashString("StepExecutionId");
static const int StepName_HASH = HashingUtils::HashString("StepName");
static const int Action_HASH = HashingUtils::HashString("Action");
StepExecutionFilterKey GetStepExecutionFilterKeyForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == StartTimeBefore_HASH)
{
return StepExecutionFilterKey::StartTimeBefore;
}
else if (hashCode == StartTimeAfter_HASH)
{
return StepExecutionFilterKey::StartTimeAfter;
}
else if (hashCode == StepExecutionStatus_HASH)
{
return StepExecutionFilterKey::StepExecutionStatus;
}
else if (hashCode == StepExecutionId_HASH)
{
return StepExecutionFilterKey::StepExecutionId;
}
else if (hashCode == StepName_HASH)
{
return StepExecutionFilterKey::StepName;
}
else if (hashCode == Action_HASH)
{
return StepExecutionFilterKey::Action;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<StepExecutionFilterKey>(hashCode);
}
return StepExecutionFilterKey::NOT_SET;
}
Aws::String GetNameForStepExecutionFilterKey(StepExecutionFilterKey enumValue)
{
switch(enumValue)
{
case StepExecutionFilterKey::StartTimeBefore:
return "StartTimeBefore";
case StepExecutionFilterKey::StartTimeAfter:
return "StartTimeAfter";
case StepExecutionFilterKey::StepExecutionStatus:
return "StepExecutionStatus";
case StepExecutionFilterKey::StepExecutionId:
return "StepExecutionId";
case StepExecutionFilterKey::StepName:
return "StepName";
case StepExecutionFilterKey::Action:
return "Action";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace StepExecutionFilterKeyMapper
} // namespace Model
} // namespace SSM
} // namespace Aws
| 35.055046 | 100 | 0.653756 | [
"model"
] |
e7677ba884196e0d47e4bf48b08d09cb56eeb93e | 10,865 | cpp | C++ | tools/Vitis-AI-Library/centerpoint/src/preprocess.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | tools/Vitis-AI-Library/centerpoint/src/preprocess.cpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | tools/Vitis-AI-Library/centerpoint/src/preprocess.cpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* 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 <memory>
#include <thread>
#include <cmath>
#include <cstring>
#include <iostream>
#include <fstream>
#include <vitis/ai/env_config.hpp>
#include <vitis/ai/profiling.hpp>
#include "./preprocess.hpp"
DEF_ENV_PARAM(DEBUG_CENTERPOINT, "0");
DEF_ENV_PARAM(DEBUG_VOXELIZE, "0");
DEF_ENV_PARAM(DEBUG_PERMUTE, "0");
DEF_ENV_PARAM(DEBUG_NEON, "0");
DEF_ENV_PARAM(USE_OLD_VOXELIZE, "0");
namespace vitis { namespace ai {
namespace centerpoint {
//constexpr uint32_t POINTS_DIM = 4;
template<typename T>
static void writefile_(string& filename, vector<T>& data) {
ofstream output_file(filename);
for(size_t i = 0; i < data.size(); i++)
output_file << data[i] << endl;
}
static void dynamic_voxelize_kernel2(const vector<float> &points,
vector<int> &coors, // [n, 3]
const std::vector<float> voxel_size,
const std::vector<float> coors_range,
const std::vector<int> grid_size,
const int num_points, const int num_features,
const int NDim) {
const int ndim_minus_1 = NDim - 1;
bool failed = false;
int coor[NDim];
int c;
for (int i = 0; i < num_points; ++i) {
failed = false;
for (int j = 0; j < NDim; ++j) {
// c = floor((points[i][j] - coors_range[j]) / voxel_size[j]);
//LOG_IF(ERROR, ENV_PARAM(DEBUG_CENTERPOINT))
// << "i: " << i << ", j: " << j;
c = std::floor((points[i * num_features + j] - coors_range[j]) / voxel_size[j]);
// necessary to rm points out of range
if ((c < 0 || c >= grid_size[j])) {
failed = true;
break;
}
coor[ndim_minus_1 - j] = c;
}
for (int k = 0; k < NDim; ++k) {
if (failed)
//coors[i][k] = -1;
coors[i * 3 + k] = -1;
else
//coors[i][k] = coor[k];
coors[i * 3 + k] = coor[k];
}
}
return;
}
static void hard_voxelize_kernel3(const vector<float> &points,
//DataContainer<float> &voxels,
//vector<float> &voxels, //(40000, 64, 4)
int8_t * voxels,
std::vector<float> &means,
std::vector<float> &scales,
vector<int> &coors,// (n, 4)
int coors_dim,
vector<int> &num_points_per_voxel,
//vector<vector<vector<int>>> &coor_to_voxelidx,
vector<int> &coor_to_voxelidx, // 1, 400, 400
int& voxel_num, const std::vector<float> voxel_size,
const std::vector<float> coors_range,
const std::vector<int> grid_size,
const int max_points, const int max_voxels,
const int num_points, const int num_features,
const int NDim) {
__TIC__(TEMP_COORS_INIT)
//vector<vector<int>> temp_coors(num_points);
//for (auto i = 0; i < num_points; ++i) {
// temp_coors[i].resize(3);
// memset(temp_coors[i].data(), 0, 3);
//}
vector<int> temp_coors(num_points * 3, 0);
LOG_IF(INFO, ENV_PARAM(DEBUG_CENTERPOINT))
<< "temp_coors size:" << temp_coors.size();
__TOC__(TEMP_COORS_INIT)
// First use dynamic voxelization to get coors,
// then check max points/voxels constraints
//dynamic_voxelize_kernel<T, int>(points, temp_coors.accessor<int, 2>(),
__TIC__(DYNAMIC_VOXELIZE_KERNEL2)
dynamic_voxelize_kernel2(points, temp_coors,
voxel_size, coors_range, grid_size,
num_points, num_features, NDim);
//auto o = std::ofstream("./temp_coors_2.txt");
//for (auto i = 0; i < num_points; ++i) {
// o << temp_coors[i * 3] << " "
// << temp_coors[i * 3 + 1] << " "
// << temp_coors[i * 3 + 2] << std::endl;
//}
//o.close();
__TOC__(DYNAMIC_VOXELIZE_KERNEL2)
int voxelidx, num;
//auto coor = temp_coors.accessor<int, 2>();
// note : need copy?
__TIC__(SELECT_VOXELS)
//vector<vector<int>> coor = temp_coors;
vector<int> coor = temp_coors;
for (int i = 0; i < num_points; ++i) {
//if (coor[i][0] == -1) continue;
if (coor[i * 3] == -1) continue;
//voxelidx = coor_to_voxelidx[coor[i][0]][coor[i][1]][coor[i][2]];
auto idx = coor[i * 3] * 400 * 400 + coor[i * 3 + 1] * 400 + coor[i * 3 + 2];
voxelidx = coor_to_voxelidx[idx];
// record voxel
if (voxelidx == -1) {
voxelidx = voxel_num;
if (max_voxels != -1 && voxel_num >= max_voxels) break;
voxel_num += 1;
//coor_to_voxelidx[coor[i][0]][coor[i][1]][coor[i][2]] = voxelidx;
//coor_to_voxelidx[coor[i * 3]][coor[i * 3 + 1]][coor[i * 3 + 2]] = voxelidx;
coor_to_voxelidx[idx] = voxelidx;
for (int k = 0; k < NDim; ++k) {
//coors[voxelidx][k + 1] = coor[i * 3 + k];
coors[voxelidx * coors_dim + k + 1] = coor[i * 3 + k];
}
}
// put points into voxel
num = num_points_per_voxel[voxelidx];
if (max_points == -1 || num < max_points) {
auto final_idx = voxelidx * 40 * num_features + num * num_features; // 64 need to read from tensor
//if (ENV_PARAM(DEBUG_NEON)) {
// set_input_neon_channel(points.data() + i * 4, 4, voxels + final_idx, scales);
//} else {
for (int k = 0; k < num_features; ++k) {
//voxels[voxelidx][num][k] = points[i][k];
//voxels.at({voxelidx,num,k}) = points[i][k];
//voxels.at({voxelidx,num,k}) = points[i * 4 + k];
//voxels[voxelidx * 64 *4 + num * 4 + k] = points[i * 4 + k];
//voxels[final_idx + k] = (int)(points[i * 4 + k] * scales[k]);
//voxels[final_idx + k] = (int)((points[i * num_features + k] - means[k]) * scales[k]);
voxels[final_idx + k] = std::round((points[i * num_features + k] - means[k]) * scales[k]);
}
//}
num_points_per_voxel[voxelidx] += 1;
}
}
__TOC__(SELECT_VOXELS)
return;
}
static int hard_voxelize_cpu3(const vector<float>& points,
//vector<float>& voxels, // (40000, 64, 4)
int points_dim,
int8_t * voxels,
std::vector<float> &means,
std::vector<float> &scales,
vector<int>& coors, // (n, 4)
int coors_dim,
vector<int>& num_points_per_voxel,
const std::vector<float> voxel_size,
const std::vector<float> coors_range,
const int max_points, const int max_voxels,
const int NDim = 3) { // coors_range dim
std::vector<int> grid_size(NDim);
const int num_points = points.size() / points_dim;
LOG_IF(INFO, ENV_PARAM(DEBUG_CENTERPOINT)) << "num_points:" << num_points;
//const int num_features = points.size(1);
const int num_features = points_dim; // points dim
LOG_IF(INFO, ENV_PARAM(DEBUG_CENTERPOINT)) << "num_features:" << num_features;
for (int i = 0; i < NDim; ++i) {
grid_size[i] =
round((coors_range[NDim + i] - coors_range[i]) / voxel_size[i]);
LOG_IF(INFO, ENV_PARAM(DEBUG_CENTERPOINT))
<< "grid_size[" << i << "]:" << grid_size[i];
}
// coors, num_points_per_voxel, coor_to_voxelidx are int Tensor
// printf("cpu coor_to_voxelidx size: [%d, %d, %d]\n", grid_size[2],
// grid_size[1], grid_size[0]);
// at::Tensor coor_to_voxelidx =
// -at::ones({grid_size[2], grid_size[1], grid_size[0]}, coors.options());
vector<int> coor_to_voxelidx(grid_size[2] * grid_size[1] * grid_size[0], -1);
LOG_IF(INFO, ENV_PARAM(DEBUG_CENTERPOINT))
<< " coor_to_voxelidx size:" << coor_to_voxelidx.size();
int voxel_num = 0;
__TIC__(HARD_VOXELIZE_KERNEL2)
hard_voxelize_kernel3(
points, voxels, means, scales, coors, coors_dim, num_points_per_voxel,
coor_to_voxelidx, voxel_num, voxel_size,
coors_range, grid_size, max_points, max_voxels, num_points,
num_features, NDim);
//LOG(ERROR) << "HELLO";
__TOC__(HARD_VOXELIZE_KERNEL2)
return voxel_num;
}
static int voxelize_input(const std::vector<float> &points,
int dim,
std::vector<int> &coors,
int8_t *input_tensor_ptr,
std::vector<float> means,
std::vector<float> scales) {
//const int dim = 4;
const int coors_dim = 4; // 3 and padding
coors.resize(2560 * coors_dim);
std::vector<float> voxels_size{0.2, 0.2, 14};
//std::vector<float> coors_range{-50, -50, -5, 50, 50, 3};
std::vector<float> coors_range{0, -40, -6, 80, 40, 8};
__TIC__(VOXELIZE_RESULT_INIT)
vector<int> num_points(MAX_VOXELS_NUM, 0);
__TOC__(VOXELIZE_RESULT_INIT)
__TIC__(HARD_VOXELIZE_CPU)
int voxel_num = 0;
voxel_num = hard_voxelize_cpu3(points, dim, input_tensor_ptr, means, scales, coors, coors_dim, num_points,
voxels_size, coors_range, MAX_POINTS_NUM, MAX_VOXELS_NUM);
//for (auto i = 0u; i < coors.size(); ++i) {
// memcpy(result.coors.data.data() + i * coors_dim, coors[i].data(), coors_dim * sizeof(int));
//}
__TOC__(HARD_VOXELIZE_CPU)
LOG_IF(INFO, ENV_PARAM(DEBUG_CENTERPOINT))
<< " voxel num:" << voxel_num;
coors.resize(voxel_num * 4);
return voxel_num;
}
std::vector<int> preprocess3(const std::vector<float> &points, int dim,
const std::vector<float> &input_mean,
const std::vector<float> &input_scale,
int8_t *input_tensor_ptr) {
__TIC__(VOXELIZE_INPUT)
// 1. voxelize
std::vector<int> coors;
//auto input_scale = std::vector<float>{1.0/50, 1.0/50, 1.0/5, 1.0/0.5}; // read from config
//for (auto i = 0u; i < input_scale.size(); ++i) {
// input_scale[i] *= input_tensor_scale;
//}
voxelize_input(points, dim, coors, input_tensor_ptr, input_mean, input_scale); // tuple: voxels, num_points, coors
__TOC__(VOXELIZE_INPUT)
return std::move(coors);
}
}
}}
| 38.392226 | 116 | 0.570179 | [
"vector"
] |
e76804867d17652bf8ca52da5a2d2c17c37a19b2 | 3,858 | cc | C++ | ext/dsent/model/optical_graph/OpticalNode.cc | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 765 | 2015-01-14T16:17:04.000Z | 2022-03-28T07:46:28.000Z | ext/dsent/model/optical_graph/OpticalNode.cc | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 148 | 2018-07-20T00:58:36.000Z | 2021-11-16T01:52:33.000Z | ext/dsent/model/optical_graph/OpticalNode.cc | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 807 | 2015-01-06T09:55:38.000Z | 2022-03-30T10:23:36.000Z | /* Copyright (c) 2012 Massachusetts Institute of Technology
*
* 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 "model/optical_graph/OpticalNode.h"
namespace DSENT
{
// Set the optical node initial visited num
const int OpticalNode::OPTICAL_NODE_INIT_VISITED_NUM = 0;
OpticalNode::OpticalNode(Type type_, const String& instance_name_, OpticalModel* model_, const WavelengthGroup& wavelengths_)
:m_type_(type_), m_instance_name_(instance_name_), m_model_(model_), m_wavelengths_(wavelengths_)
{
m_loss_ = 0.0;
setVisitedNum(OpticalNode::OPTICAL_NODE_INIT_VISITED_NUM);
m_downstream_nodes_ = new vector<OpticalNode*>;
}
OpticalNode::~OpticalNode()
{
}
OpticalNode::Type OpticalNode::getType() const
{
return m_type_;
}
vector<OpticalNode*>* OpticalNode::getDownstreamNodes() const
{
return m_downstream_nodes_;
}
const String& OpticalNode::getInstanceName() const
{
return m_instance_name_;
}
OpticalModel* OpticalNode::getModel()
{
return m_model_;
}
const OpticalModel* OpticalNode::getModel() const
{
return (const OpticalModel*) m_model_;
}
void OpticalNode::addDownstreamNode(OpticalNode* node_)
{
ASSERT(node_->isExpected(getWavelengths()), "[Error] " + getInstanceName() +
" -> Downstream node not expecting a superset of the current wavelengths");
m_downstream_nodes_->push_back(node_);
}
WavelengthGroup OpticalNode::getWavelengths() const
{
return m_wavelengths_;
}
bool OpticalNode::isExpected(const WavelengthGroup& wavelengths_) const
{
// Check that the lower limits are within bounds
bool lower_match = (wavelengths_.first >= getWavelengths().first);
// Check that the upper limits are within bounds
bool upper_match = (wavelengths_.second <= getWavelengths().second);
// Assert that there are no misalignments
ASSERT(lower_match == upper_match, "[Error] " + getInstanceName() +
" -> Wavelength group misalignment!");
// Both upper and lower bounds must match
return (upper_match && lower_match);
}
//-------------------------------------------------------------------------
void OpticalNode::setLoss(double loss_)
{
m_loss_ = loss_;
}
double OpticalNode::getLoss() const
{
return m_loss_;
}
void OpticalNode::setVisitedNum(int visited_num_)
{
m_visited_num_ = visited_num_;
}
int OpticalNode::getVisitedNum() const
{
return m_visited_num_;
}
//-------------------------------------------------------------------------
} // namespace DSENT
| 32.694915 | 129 | 0.65267 | [
"vector",
"model"
] |
e76822d04fb3f381bbcb80d127fe8ac69b14a4f1 | 1,703 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/main_menu_screen/MainMenuPresenter.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/main_menu_screen/MainMenuPresenter.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/main_menu_screen/MainMenuPresenter.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
#include <gui/main_menu_screen/MainMenuPresenter.hpp>
#include <gui/main_menu_screen/MainMenuView.hpp>
MainMenuPresenter::MainMenuPresenter(MainMenuView& v) :
DemoPresenter(v),
view(v)
{
}
void MainMenuPresenter::activate()
{
}
void MainMenuPresenter::deactivate()
{
}
void MainMenuPresenter::setSelectedDemoScreen(Defines::DemoID elementIndex)
{
model->setSelectedDemoScreen(elementIndex);
}
void MainMenuPresenter::setPreviousSelectedMenuType(Defines::MainMenuType menuType)
{
model->setPreviousSelectedMainMenuType(menuType);
}
Defines::DemoID MainMenuPresenter::getSelectedDemoScreen()
{
return model->getSelectedDemoScreen();
}
Defines::MainMenuType MainMenuPresenter::getPreviousSelectedMenuType()
{
return model->getPreviousSelectedMainMenuType();
}
void MainMenuPresenter::screenSaverMinorTick()
{
view.screenSaverMinorTick();
}
void MainMenuPresenter::gotoSTMenu()
{
// TODO Goto ST menu
#ifndef SIMULATOR
__HAL_RCC_RTC_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_RCC_BKPSRAM_CLK_ENABLE();
HAL_PWR_EnableBkUpAccess();
*(uint32_t *)(0x40024000) = 0x5AA55BBB;
NVIC_SystemReset();
#endif
}
| 21.833333 | 83 | 0.675866 | [
"model"
] |
e76dcade17edc44c58d1e19eada1a1ca18ac8709 | 1,960 | cc | C++ | net/dcsctp/packet/parameter/parameter_test.cc | c0der88/webrtc | a4da76a880d31f012038ac721ac4abc7ea3ffa2d | [
"BSD-3-Clause"
] | 2 | 2021-11-29T08:00:33.000Z | 2022-02-18T06:14:08.000Z | net/dcsctp/packet/parameter/parameter_test.cc | c0der88/webrtc | a4da76a880d31f012038ac721ac4abc7ea3ffa2d | [
"BSD-3-Clause"
] | 10 | 2020-07-13T14:49:36.000Z | 2020-10-14T15:43:13.000Z | net/dcsctp/packet/parameter/parameter_test.cc | c0der88/webrtc | a4da76a880d31f012038ac721ac4abc7ea3ffa2d | [
"BSD-3-Clause"
] | 1 | 2020-10-30T07:02:56.000Z | 2020-10-30T07:02:56.000Z | /*
* Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "net/dcsctp/packet/parameter/parameter.h"
#include <cstdint>
#include <type_traits>
#include <vector>
#include "api/array_view.h"
#include "net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.h"
#include "net/dcsctp/packet/tlv_trait.h"
#include "net/dcsctp/testing/testing_macros.h"
#include "rtc_base/gunit.h"
#include "test/gmock.h"
namespace dcsctp {
namespace {
using ::testing::ElementsAre;
using ::testing::SizeIs;
TEST(ParameterTest, SerializeDeserializeParameter) {
Parameters parameters =
Parameters::Builder()
.Add(OutgoingSSNResetRequestParameter(ReconfigRequestSN(123),
ReconfigResponseSN(456),
TSN(789), {StreamID(42)}))
.Build();
rtc::ArrayView<const uint8_t> serialized = parameters.data();
ASSERT_HAS_VALUE_AND_ASSIGN(Parameters parsed, Parameters::Parse(serialized));
auto descriptors = parsed.descriptors();
ASSERT_THAT(descriptors, SizeIs(1));
EXPECT_THAT(descriptors[0].type, OutgoingSSNResetRequestParameter::kType);
ASSERT_HAS_VALUE_AND_ASSIGN(
OutgoingSSNResetRequestParameter parsed_param,
OutgoingSSNResetRequestParameter::Parse(descriptors[0].data));
EXPECT_EQ(*parsed_param.request_sequence_number(), 123u);
EXPECT_EQ(*parsed_param.response_sequence_number(), 456u);
EXPECT_EQ(*parsed_param.sender_last_assigned_tsn(), 789u);
EXPECT_THAT(parsed_param.stream_ids(), ElementsAre(StreamID(42)));
}
} // namespace
} // namespace dcsctp
| 36.296296 | 80 | 0.72449 | [
"vector"
] |
e77012f45b0fba694a8968b5ce34abf71d92f6a1 | 5,307 | hpp | C++ | include/codegen/include/OnlineServices/LevelScoreUploader.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/OnlineServices/LevelScoreUploader.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/OnlineServices/LevelScoreUploader.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:36 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: System.Int32
#include "System/Int32.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OnlineServices
namespace OnlineServices {
// Forward declaring type: PlatformOnlineServicesAvailabilityModel
class PlatformOnlineServicesAvailabilityModel;
// Forward declaring type: LevelScoreResultsData
struct LevelScoreResultsData;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: System::Threading
namespace System::Threading {
// Forward declaring type: CancellationTokenSource
class CancellationTokenSource;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: HTTPLeaderboardsModel
class HTTPLeaderboardsModel;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace: OnlineServices
namespace OnlineServices {
// Autogenerated type: OnlineServices.LevelScoreUploader
class LevelScoreUploader : public ::Il2CppObject {
public:
// Nested type: OnlineServices::LevelScoreUploader::LevelScoreResultsDataUploadInfo
class LevelScoreResultsDataUploadInfo;
// Nested type: OnlineServices::LevelScoreUploader::$SendLevelScoreResultAsync$d__13
struct $SendLevelScoreResultAsync$d__13;
// private System.Action`1<System.String> scoreForLeaderboardDidUploadEvent
// Offset: 0x10
System::Action_1<::Il2CppString*>* scoreForLeaderboardDidUploadEvent;
// static field const value: static private System.Int32 kMaxUploadAttempts
static constexpr const int kMaxUploadAttempts = 3;
// Get static field: static private System.Int32 kMaxUploadAttempts
static int _get_kMaxUploadAttempts();
// Set static field: static private System.Int32 kMaxUploadAttempts
static void _set_kMaxUploadAttempts(int value);
// private System.Threading.CancellationTokenSource _cancellationTokenSource
// Offset: 0x18
System::Threading::CancellationTokenSource* cancellationTokenSource;
// private HTTPLeaderboardsModel _leaderboardsModel
// Offset: 0x20
GlobalNamespace::HTTPLeaderboardsModel* leaderboardsModel;
// private System.Collections.Generic.List`1<OnlineServices.LevelScoreUploader/LevelScoreResultsDataUploadInfo> _unsuccessfullySentLevelScoreResultsDataUploadInfos
// Offset: 0x28
System::Collections::Generic::List_1<OnlineServices::LevelScoreUploader::LevelScoreResultsDataUploadInfo*>* unsuccessfullySentLevelScoreResultsDataUploadInfos;
// private System.Collections.Generic.List`1<OnlineServices.LevelScoreUploader/LevelScoreResultsDataUploadInfo> _levelScoreResultsDataUploadInfos
// Offset: 0x30
System::Collections::Generic::List_1<OnlineServices::LevelScoreUploader::LevelScoreResultsDataUploadInfo*>* levelScoreResultsDataUploadInfos;
// private OnlineServices.PlatformOnlineServicesAvailabilityModel _platformOnlineServicesAvailabilityModel
// Offset: 0x38
OnlineServices::PlatformOnlineServicesAvailabilityModel* platformOnlineServicesAvailabilityModel;
// public System.Void add_scoreForLeaderboardDidUploadEvent(System.Action`1<System.String> value)
// Offset: 0xBB830C
void add_scoreForLeaderboardDidUploadEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void remove_scoreForLeaderboardDidUploadEvent(System.Action`1<System.String> value)
// Offset: 0xBB83B0
void remove_scoreForLeaderboardDidUploadEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void .ctor(HTTPLeaderboardsModel leaderboardsModel, OnlineServices.PlatformOnlineServicesAvailabilityModel platformOnlineServicesAvailabilityModel)
// Offset: 0xBB8454
static LevelScoreUploader* New_ctor(GlobalNamespace::HTTPLeaderboardsModel* leaderboardsModel, OnlineServices::PlatformOnlineServicesAvailabilityModel* platformOnlineServicesAvailabilityModel);
// public System.Void SendLevelScoreResult(OnlineServices.LevelScoreResultsData levelScoreResultsData)
// Offset: 0xBB852C
void SendLevelScoreResult(OnlineServices::LevelScoreResultsData levelScoreResultsData);
// public System.Void TrySendPreviouslyUnsuccessfullySentResults()
// Offset: 0xBB871C
void TrySendPreviouslyUnsuccessfullySentResults();
// private System.Void SendLevelScoreResultAsync()
// Offset: 0xBB864C
void SendLevelScoreResultAsync();
// private System.Void AddUnsuccessfullySentResults()
// Offset: 0xBB8740
void AddUnsuccessfullySentResults();
// protected System.Void OnDestroy()
// Offset: 0xBB87B4
void OnDestroy();
}; // OnlineServices.LevelScoreUploader
}
DEFINE_IL2CPP_ARG_TYPE(OnlineServices::LevelScoreUploader*, "OnlineServices", "LevelScoreUploader");
#pragma pack(pop)
| 50.066038 | 197 | 0.791219 | [
"object"
] |
e772e73c4c9ff52e40cdfbf1c900b67614cc4ddd | 16,115 | cc | C++ | src/commands/GlobalCommandController.cc | D15C0DE/openMSX | 5119a9657de4b82115c745f670cdc55dc7363133 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 7 | 2019-10-11T21:47:05.000Z | 2021-10-05T19:58:18.000Z | src/commands/GlobalCommandController.cc | D15C0DE/openMSX | 5119a9657de4b82115c745f670cdc55dc7363133 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2019-05-25T21:08:47.000Z | 2019-05-25T21:10:35.000Z | src/commands/GlobalCommandController.cc | D15C0DE/openMSX | 5119a9657de4b82115c745f670cdc55dc7363133 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | #include "GlobalCommandController.hh"
#include "Reactor.hh"
#include "Setting.hh"
#include "ProxyCommand.hh"
#include "ProxySetting.hh"
#include "LocalFileReference.hh"
#include "GlobalCliComm.hh"
#include "CliConnection.hh"
#include "CommandException.hh"
#include "SettingsManager.hh"
#include "TclObject.hh"
#include "Version.hh"
#include "ScopedAssign.hh"
#include "join.hh"
#include "outer.hh"
#include "ranges.hh"
#include "stl.hh"
#include "StringOp.hh"
#include "view.hh"
#include "xrange.hh"
#include "build-info.hh"
#include <cassert>
#include <memory>
using std::string;
using std::string_view;
using std::vector;
namespace openmsx {
GlobalCommandController::GlobalCommandController(
EventDistributor& eventDistributor,
GlobalCliComm& cliComm_, Reactor& reactor_)
: cliComm(cliComm_)
, connection(nullptr)
, reactor(reactor_)
, openMSXInfoCommand(*this, "openmsx_info")
, hotKey(reactor.getRTScheduler(), *this, eventDistributor)
, settingsConfig(*this, hotKey)
, helpCmd(*this)
, tabCompletionCmd(*this)
, updateCmd(*this)
, platformInfo(getOpenMSXInfoCommand())
, versionInfo (getOpenMSXInfoCommand())
, romInfoTopic(getOpenMSXInfoCommand())
{
}
GlobalCommandController::~GlobalCommandController() = default;
GlobalCommandControllerBase::~GlobalCommandControllerBase()
{
// GlobalCommandController destructor must have run before
// we can check this.
#ifdef DEBUG
assert(commands.empty());
#endif
assert(commandCompleters.empty());
}
void GlobalCommandController::registerProxyCommand(std::string_view name)
{
auto it = proxyCommandMap.find(name);
if (it == end(proxyCommandMap)) {
it = proxyCommandMap.emplace_noDuplicateCheck(
0, std::make_unique<ProxyCmd>(reactor, name));
}
++it->first;
}
void GlobalCommandController::unregisterProxyCommand(string_view name)
{
auto it = proxyCommandMap.find(name);
assert(it != end(proxyCommandMap));
assert(it->first > 0);
--it->first;
if (it->first == 0) {
proxyCommandMap.erase(it);
}
}
GlobalCommandController::ProxySettings::iterator
GlobalCommandController::findProxySetting(string_view name)
{
return ranges::find_if(proxySettings, [&](auto& v) {
return v.first->getFullName() == name;
});
}
void GlobalCommandController::registerProxySetting(Setting& setting)
{
const auto& name = setting.getBaseNameObj();
auto it = findProxySetting(name.getString());
if (it == end(proxySettings)) {
// first occurrence
auto proxy = std::make_unique<ProxySetting>(reactor, name);
getSettingsManager().registerSetting(*proxy);
getInterpreter().registerSetting(*proxy);
proxySettings.emplace_back(std::move(proxy), 1);
} else {
// was already registered
++(it->second);
}
}
void GlobalCommandController::unregisterProxySetting(Setting& setting)
{
auto it = findProxySetting(setting.getBaseName());
assert(it != end(proxySettings));
assert(it->second);
--(it->second);
if (it->second == 0) {
auto& proxy = *it->first;
getInterpreter().unregisterSetting(proxy);
getSettingsManager().unregisterSetting(proxy);
move_pop_back(proxySettings, it);
}
}
CliComm& GlobalCommandController::getCliComm()
{
return cliComm;
}
Interpreter& GlobalCommandController::getInterpreter()
{
return interpreter;
}
void GlobalCommandController::registerCommand(
Command& command, zstring_view str)
{
#ifdef DEBUG
assert(!commands.contains(str));
commands.emplace_noDuplicateCheck(str, &command);
#endif
interpreter.registerCommand(str, command);
}
void GlobalCommandController::unregisterCommand(
Command& command, string_view str)
{
(void)str;
#ifdef DEBUG
assert(commands.contains(str));
assert(commands[str] == &command);
commands.erase(str);
#endif
interpreter.unregisterCommand(command);
}
void GlobalCommandController::registerCompleter(
CommandCompleter& completer, string_view str)
{
if (StringOp::startsWith(str, "::")) str.remove_prefix(2); // drop leading ::
assert(!commandCompleters.contains(str));
commandCompleters.emplace_noDuplicateCheck(str, &completer);
}
void GlobalCommandController::unregisterCompleter(
CommandCompleter& completer, string_view str)
{
if (StringOp::startsWith(str, "::")) str.remove_prefix(2); // drop leading ::
assert(commandCompleters.contains(str));
assert(commandCompleters[str] == &completer); (void)completer;
commandCompleters.erase(str);
}
void GlobalCommandController::registerSetting(Setting& setting)
{
getSettingsManager().registerSetting(setting);
interpreter.registerSetting(setting);
}
void GlobalCommandController::unregisterSetting(Setting& setting)
{
interpreter.unregisterSetting(setting);
getSettingsManager().unregisterSetting(setting);
}
static vector<string> split(string_view str, const char delimiter)
{
vector<string> tokens;
enum ParseState {Alpha, BackSlash, Quote};
ParseState state = Alpha;
for (auto chr : str) {
switch (state) {
case Alpha:
if (tokens.empty()) {
tokens.emplace_back();
}
if (chr == delimiter) {
// token done, start new token
tokens.emplace_back();
} else {
tokens.back() += chr;
if (chr == '\\') {
state = BackSlash;
} else if (chr == '"') {
state = Quote;
}
}
break;
case Quote:
tokens.back() += chr;
if (chr == '"') {
state = Alpha;
}
break;
case BackSlash:
tokens.back() += chr;
state = Alpha;
break;
}
}
return tokens;
}
static string removeEscaping(const string& str)
{
enum ParseState {Alpha, BackSlash, Quote};
ParseState state = Alpha;
string result;
for (auto chr : str) {
switch (state) {
case Alpha:
if (chr == '\\') {
state = BackSlash;
} else if (chr == '"') {
state = Quote;
} else {
result += chr;
}
break;
case Quote:
if (chr == '"') {
state = Alpha;
} else {
result += chr;
}
break;
case BackSlash:
result += chr;
state = Alpha;
break;
}
}
return result;
}
static vector<string> removeEscaping(const vector<string>& input, bool keepLastIfEmpty)
{
vector<string> result;
for (const auto& s : input) {
if (!s.empty()) {
result.push_back(removeEscaping(s));
}
}
if (keepLastIfEmpty && (input.empty() || input.back().empty())) {
result.emplace_back();
}
return result;
}
static string escapeChars(const string& str, string_view chars)
{
string result;
for (auto chr : str) {
if (chars.find(chr) != string::npos) {
result += '\\';
}
result += chr;
}
return result;
}
static string addEscaping(const string& str, bool quote, bool finished)
{
if (str.empty() && finished) {
quote = true;
}
string result = escapeChars(str, "$[]");
if (quote) {
result.insert(result.begin(), '"');
if (finished) {
result += '"';
}
} else {
result = escapeChars(result, " ");
}
return result;
}
bool GlobalCommandController::isComplete(zstring_view command)
{
return interpreter.isComplete(command);
}
TclObject GlobalCommandController::executeCommand(
zstring_view command, CliConnection* connection_)
{
ScopedAssign sa(connection, connection_);
return interpreter.execute(command);
}
void GlobalCommandController::source(const string& script)
{
try {
LocalFileReference file(script);
interpreter.executeFile(file.getFilename());
} catch (CommandException& e) {
getCliComm().printWarning(
"While executing ", script, ": ", e.getMessage());
}
}
string GlobalCommandController::tabCompletion(string_view command)
{
// split on 'active' command (the command that should actually be
// completed). Some examples:
// if {[debug rea<tab> <-- should complete the 'debug' command
// instead of the 'if' command
// bind F6 { cycl<tab> <-- should complete 'cycle' instead of 'bind'
TclParser parser = interpreter.parse(command);
int last = parser.getLast();
string_view pre = command.substr(0, last);
string_view post = command.substr(last);
// split command string in tokens
vector<string> originalTokens = split(post, ' ');
if (originalTokens.empty()) {
originalTokens.emplace_back();
}
// complete last token
auto tokens = removeEscaping(originalTokens, true);
auto oldNum = tokens.size();
tabCompletion(tokens);
auto newNum = tokens.size();
bool tokenFinished = oldNum != newNum;
// replace last token
string& original = originalTokens.back();
string& completed = tokens[oldNum - 1];
if (!completed.empty()) {
bool quote = !original.empty() && (original[0] == '"');
original = addEscaping(completed, quote, tokenFinished);
}
if (tokenFinished) {
assert(newNum == (oldNum + 1));
assert(tokens.back().empty());
originalTokens.emplace_back();
}
// rebuild command string
return strCat(pre, join(originalTokens, ' '));
}
void GlobalCommandController::tabCompletion(vector<string>& tokens)
{
if (tokens.empty()) {
// nothing typed yet
return;
}
if (tokens.size() == 1) {
string_view cmd = tokens[0];
string_view leadingNs;
// remove leading ::
if (StringOp::startsWith(cmd, "::")) {
cmd.remove_prefix(2);
leadingNs = "::";
}
// get current (typed) namespace
auto p1 = cmd.rfind("::");
string_view ns = (p1 == string_view::npos) ? cmd : cmd.substr(0, p1 + 2);
// build a list of all command strings
TclObject names = interpreter.getCommandNames();
vector<string> names2;
names2.reserve(names.size());
for (string_view n1 : names) {
// remove leading ::
if (StringOp::startsWith(n1, "::")) n1.remove_prefix(2);
// initial namespace part must match
if (!StringOp::startsWith(n1, ns)) continue;
// the part following the initial namespace
string_view n2 = n1.substr(ns.size());
// only keep upto the next namespace portion,
auto p2 = n2.find("::");
auto n3 = (p2 == string_view::npos) ? n1 : n1.substr(0, ns.size() + p2 + 2);
// don't care about adding the same string multiple times
names2.push_back(strCat(leadingNs, n3));
}
Completer::completeString(tokens, names2);
} else {
string_view cmd = tokens.front();
if (StringOp::startsWith(cmd, "::")) cmd.remove_prefix(2); // drop leading ::
if (auto* v = lookup(commandCompleters, cmd)) {
(*v)->tabCompletion(tokens);
} else {
TclObject command = makeTclList("openmsx::tabcompletion");
command.addListElements(tokens);
try {
TclObject list = command.executeCommand(interpreter);
bool sensitive = true;
auto begin = list.begin();
auto end = list.end();
if (begin != end) {
auto it2 = end; --it2;
auto back = *it2;
if (back == "false") {
end = it2;
sensitive = false;
} else if (back == "true") {
end = it2;
sensitive = true;
}
}
Completer::completeString(tokens, begin, end, sensitive);
} catch (CommandException& e) {
cliComm.printWarning(
"Error while executing tab-completion "
"proc: ", e.getMessage());
}
}
}
}
// Help Command
GlobalCommandController::HelpCmd::HelpCmd(GlobalCommandController& controller_)
: Command(controller_, "help")
{
}
void GlobalCommandController::HelpCmd::execute(
span<const TclObject> tokens, TclObject& result)
{
auto& controller = OUTER(GlobalCommandController, helpCmd);
switch (tokens.size()) {
case 1: {
string text =
"Use 'help [command]' to get help for a specific command\n"
"The following commands exist:\n";
auto cmds = concat<string_view>(
view::keys(controller.commandCompleters),
getInterpreter().execute("openmsx::all_command_names_with_help"));
cmds.erase(ranges::remove_if(cmds, [](const auto& c) {
return c.find("::") != std::string_view::npos; }),
cmds.end());
ranges::sort(cmds);
for (auto& line : formatListInColumns(cmds)) {
strAppend(text, line, '\n');
}
result = text;
break;
}
default: {
if (const auto* v = lookup(controller.commandCompleters, tokens[1].getString())) {
auto tokens2 = to_vector(view::transform(
view::drop(tokens, 1),
[](auto& t) { return string(t.getString()); }));
result = (*v)->help(tokens2);
} else {
TclObject command = makeTclList("openmsx::help");
command.addListElements(view::drop(tokens, 1));
result = command.executeCommand(getInterpreter());
}
break;
}
}
}
string GlobalCommandController::HelpCmd::help(const vector<string>& /*tokens*/) const
{
return "prints help information for commands\n";
}
void GlobalCommandController::HelpCmd::tabCompletion(vector<string>& tokens) const
{
string front = std::move(tokens.front());
tokens.erase(begin(tokens));
auto& controller = OUTER(GlobalCommandController, helpCmd);
controller.tabCompletion(tokens);
tokens.insert(begin(tokens), std::move(front));
}
// TabCompletionCmd Command
GlobalCommandController::TabCompletionCmd::TabCompletionCmd(
GlobalCommandController& controller_)
: Command(controller_, "tabcompletion")
{
}
void GlobalCommandController::TabCompletionCmd::execute(
span<const TclObject> tokens, TclObject& result)
{
checkNumArgs(tokens, 2, "commandstring");
// TODO this prints list of possible completions in the console
auto& controller = OUTER(GlobalCommandController, tabCompletionCmd);
result = controller.tabCompletion(tokens[1].getString());
}
string GlobalCommandController::TabCompletionCmd::help(const vector<string>& /*tokens*/) const
{
return "!!! This command will change in the future !!!\n"
"Tries to completes the given argument as if it were typed in "
"the console. This command is only useful to provide "
"tabcompletion to external console interfaces.";
}
// class UpdateCmd
GlobalCommandController::UpdateCmd::UpdateCmd(CommandController& commandController_)
: Command(commandController_, "openmsx_update")
{
}
static GlobalCliComm::UpdateType getType(const TclObject& name)
{
auto updateStr = CliComm::getUpdateStrings();
for (auto i : xrange(updateStr.size())) {
if (updateStr[i] == name) {
return static_cast<CliComm::UpdateType>(i);
}
}
throw CommandException("No such update type: ", name.getString());
}
CliConnection& GlobalCommandController::UpdateCmd::getConnection()
{
auto& controller = OUTER(GlobalCommandController, updateCmd);
if (auto* c = controller.getConnection()) {
return *c;
}
throw CommandException("This command only makes sense when "
"it's used from an external application.");
}
void GlobalCommandController::UpdateCmd::execute(
span<const TclObject> tokens, TclObject& /*result*/)
{
checkNumArgs(tokens, 3, Prefix{1}, "enable|disable type");
if (tokens[1] == "enable") {
getConnection().setUpdateEnable(getType(tokens[2]), true);
} else if (tokens[1] == "disable") {
getConnection().setUpdateEnable(getType(tokens[2]), false);
} else {
throw SyntaxError();
}
}
string GlobalCommandController::UpdateCmd::help(const vector<string>& /*tokens*/) const
{
return "Enable or disable update events for external applications. See doc/openmsx-control-xml.txt.";
}
void GlobalCommandController::UpdateCmd::tabCompletion(vector<string>& tokens) const
{
switch (tokens.size()) {
case 2: {
using namespace std::literals;
static constexpr std::array ops = {"enable"sv, "disable"sv};
completeString(tokens, ops);
break;
}
case 3:
completeString(tokens, CliComm::getUpdateStrings());
break;
}
}
// Platform info
GlobalCommandController::PlatformInfo::PlatformInfo(InfoCommand& openMSXInfoCommand_)
: InfoTopic(openMSXInfoCommand_, "platform")
{
}
void GlobalCommandController::PlatformInfo::execute(
span<const TclObject> /*tokens*/, TclObject& result) const
{
result = TARGET_PLATFORM;
}
string GlobalCommandController::PlatformInfo::help(const vector<string>& /*tokens*/) const
{
return "Prints openMSX platform.";
}
// Version info
GlobalCommandController::VersionInfo::VersionInfo(InfoCommand& openMSXInfoCommand_)
: InfoTopic(openMSXInfoCommand_, "version")
{
}
void GlobalCommandController::VersionInfo::execute(
span<const TclObject> /*tokens*/, TclObject& result) const
{
result = Version::full();
}
string GlobalCommandController::VersionInfo::help(const vector<string>& /*tokens*/) const
{
return "Prints openMSX version.";
}
} // namespace openmsx
| 25.991935 | 102 | 0.698728 | [
"vector",
"transform"
] |
e77664c2fcf65b0f80a9f05e83b99f463317dc41 | 10,683 | cpp | C++ | DerivedSources/WebCore/JSNodeList.cpp | VincentWei/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | DerivedSources/WebCore/JSNodeList.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | null | null | null | DerivedSources/WebCore/JSNodeList.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
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 "JSNodeList.h"
#include "ExceptionCode.h"
#include "JSDOMBinding.h"
#include "JSNode.h"
#include "Node.h"
#include "NodeList.h"
#include "wtf/text/AtomicString.h"
#include <runtime/Error.h>
#include <runtime/JSNumberCell.h>
#include <runtime/PropertyNameArray.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSNodeList);
/* Hash table */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSNodeListTableValues[3] =
{
{ "length", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsNodeListLength), (intptr_t)0 THUNK_GENERATOR(0) },
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsNodeListConstructor), (intptr_t)0 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSNodeListTable = { 5, 3, JSNodeListTableValues, 0 };
/* Hash table for constructor */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSNodeListConstructorTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSNodeListConstructorTable = { 1, 0, JSNodeListConstructorTableValues, 0 };
class JSNodeListConstructor : public DOMConstructorObject {
public:
JSNodeListConstructor(JSC::ExecState*, JSDOMGlobalObject*);
virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);
virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);
static const JSC::ClassInfo s_info;
static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
{
return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
protected:
static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};
const ClassInfo JSNodeListConstructor::s_info = { "NodeListConstructor", &DOMConstructorObject::s_info, &JSNodeListConstructorTable, 0 };
JSNodeListConstructor::JSNodeListConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSNodeListConstructor::createStructure(globalObject->globalData(), globalObject->objectPrototype()), globalObject)
{
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSNodeListPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSNodeListConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSNodeListConstructor, DOMObject>(exec, &JSNodeListConstructorTable, this, propertyName, slot);
}
bool JSNodeListConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSNodeListConstructor, DOMObject>(exec, &JSNodeListConstructorTable, this, propertyName, descriptor);
}
/* Hash table for prototype */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSNodeListPrototypeTableValues[2] =
{
{ "item", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsNodeListPrototypeFunctionItem), (intptr_t)1 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSNodeListPrototypeTable = { 2, 1, JSNodeListPrototypeTableValues, 0 };
const ClassInfo JSNodeListPrototype::s_info = { "NodeListPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSNodeListPrototypeTable, 0 };
JSObject* JSNodeListPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSNodeList>(exec, globalObject);
}
bool JSNodeListPrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticFunctionSlot<JSObject>(exec, &JSNodeListPrototypeTable, this, propertyName, slot);
}
bool JSNodeListPrototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticFunctionDescriptor<JSObject>(exec, &JSNodeListPrototypeTable, this, propertyName, descriptor);
}
const ClassInfo JSNodeList::s_info = { "NodeList", &DOMObjectWithGlobalPointer::s_info, &JSNodeListTable, 0 };
JSNodeList::JSNodeList(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<NodeList> impl)
: DOMObjectWithGlobalPointer(structure, globalObject)
, m_impl(impl)
{
ASSERT(inherits(&s_info));
}
JSObject* JSNodeList::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSNodeListPrototype(globalObject, JSNodeListPrototype::createStructure(globalObject->globalData(), globalObject->objectPrototype()));
}
bool JSNodeList::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
const HashEntry* entry = JSNodeListTable.entry(exec, propertyName);
if (entry) {
slot.setCustom(this, entry->propertyGetter());
return true;
}
bool ok;
unsigned index = propertyName.toUInt32(ok);
if (ok && index < static_cast<NodeList*>(impl())->length()) {
slot.setCustomIndex(this, index, indexGetter);
return true;
}
if (canGetItemsForName(exec, static_cast<NodeList*>(impl()), propertyName)) {
slot.setCustom(this, nameGetter);
return true;
}
return getStaticValueSlot<JSNodeList, Base>(exec, &JSNodeListTable, this, propertyName, slot);
}
bool JSNodeList::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
const HashEntry* entry = JSNodeListTable.entry(exec, propertyName);
if (entry) {
PropertySlot slot;
slot.setCustom(this, entry->propertyGetter());
descriptor.setDescriptor(slot.getValue(exec, propertyName), entry->attributes());
return true;
}
bool ok;
unsigned index = propertyName.toUInt32(ok);
if (ok && index < static_cast<NodeList*>(impl())->length()) {
PropertySlot slot;
slot.setCustomIndex(this, index, indexGetter);
descriptor.setDescriptor(slot.getValue(exec, propertyName), DontDelete | ReadOnly);
return true;
}
if (canGetItemsForName(exec, static_cast<NodeList*>(impl()), propertyName)) {
PropertySlot slot;
slot.setCustom(this, nameGetter);
descriptor.setDescriptor(slot.getValue(exec, propertyName), ReadOnly | DontDelete | DontEnum);
return true;
}
return getStaticValueDescriptor<JSNodeList, Base>(exec, &JSNodeListTable, this, propertyName, descriptor);
}
bool JSNodeList::getOwnPropertySlot(ExecState* exec, unsigned propertyName, PropertySlot& slot)
{
if (propertyName < static_cast<NodeList*>(impl())->length()) {
slot.setCustomIndex(this, propertyName, indexGetter);
return true;
}
return getOwnPropertySlot(exec, Identifier::from(exec, propertyName), slot);
}
JSValue jsNodeListLength(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSNodeList* castedThis = static_cast<JSNodeList*>(asObject(slotBase));
UNUSED_PARAM(exec);
NodeList* imp = static_cast<NodeList*>(castedThis->impl());
JSValue result = jsNumber(imp->length());
return result;
}
JSValue jsNodeListConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSNodeList* domObject = static_cast<JSNodeList*>(asObject(slotBase));
return JSNodeList::getConstructor(exec, domObject->globalObject());
}
void JSNodeList::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
{
for (unsigned i = 0; i < static_cast<NodeList*>(impl())->length(); ++i)
propertyNames.add(Identifier::from(exec, i));
Base::getOwnPropertyNames(exec, propertyNames, mode);
}
JSValue JSNodeList::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSNodeListConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
EncodedJSValue JSC_HOST_CALL jsNodeListPrototypeFunctionItem(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSNodeList::s_info))
return throwVMTypeError(exec);
JSNodeList* castedThis = static_cast<JSNodeList*>(asObject(thisValue));
NodeList* imp = static_cast<NodeList*>(castedThis->impl());
int index(exec->argument(0).toUInt32(exec));
if (index < 0) {
setDOMException(exec, INDEX_SIZE_ERR);
return JSValue::encode(jsUndefined());
}
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->item(index)));
return JSValue::encode(result);
}
JSValue JSNodeList::indexGetter(ExecState* exec, JSValue slotBase, unsigned index)
{
JSNodeList* thisObj = static_cast<JSNodeList*>(asObject(slotBase));
return toJS(exec, thisObj->globalObject(), static_cast<NodeList*>(thisObj->impl())->item(index));
}
JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, NodeList* object)
{
return getDOMObjectWrapper<JSNodeList>(exec, globalObject, object);
}
NodeList* toNodeList(JSC::JSValue value)
{
return value.inherits(&JSNodeList::s_info) ? static_cast<JSNodeList*>(asObject(value))->impl() : 0;
}
}
| 39.713755 | 155 | 0.750257 | [
"object"
] |
e7780817ed6ebc515d236c1ac97589c378bf05be | 2,601 | cpp | C++ | src/services/hardwareFileSystem/object.cpp | patrick-lafferty/saturn | 6dc36adb42ad9b647704dd19247423a522eeb551 | [
"BSD-3-Clause"
] | 26 | 2018-03-19T15:59:46.000Z | 2021-08-06T16:13:16.000Z | src/services/hardwareFileSystem/object.cpp | patrick-lafferty/saturn | 6dc36adb42ad9b647704dd19247423a522eeb551 | [
"BSD-3-Clause"
] | 34 | 2018-01-21T17:43:29.000Z | 2020-06-27T02:00:53.000Z | src/services/hardwareFileSystem/object.cpp | patrick-lafferty/saturn | 6dc36adb42ad9b647704dd19247423a522eeb551 | [
"BSD-3-Clause"
] | 3 | 2019-12-08T22:26:35.000Z | 2021-06-25T17:05:57.000Z | /*
Copyright (c) 2017, Patrick Lafferty
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "object.h"
#include <services/virtualFileSystem/virtualFileSystem.h>
using namespace VirtualFileSystem;
using namespace Vostok;
namespace HardwareFileSystem {
void replyWriteSucceeded(uint32_t requesterTaskId, uint32_t requestId, bool success, bool expectReadResult) {
WriteResult result;
result.requestId = requestId;
result.success = success;
result.recipientId = requesterTaskId;
result.expectReadResult = expectReadResult;
send(IPC::RecipientType::TaskId, &result);
}
int HardwareObject::getFunction(std::string_view) {
return -1;
}
void HardwareObject::readFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId) {
describeFunction(requesterTaskId, requestId, functionId);
}
void HardwareObject::writeFunction(uint32_t, uint32_t, uint32_t, ArgBuffer&) {
}
void HardwareObject::describeFunction(uint32_t, uint32_t, uint32_t) {
}
Object* HardwareObject::getNestedObject(std::string_view) {
return nullptr;
}
} | 42.639344 | 113 | 0.762399 | [
"object"
] |
e77a6be124c6781c11b349f04492ceb4c9950465 | 15,780 | cpp | C++ | paso/src/SystemMatrix.cpp | markendr/esys-escript.github.io | 0023eab09cd71f830ab098cb3a468e6139191e8d | [
"Apache-2.0"
] | null | null | null | paso/src/SystemMatrix.cpp | markendr/esys-escript.github.io | 0023eab09cd71f830ab098cb3a468e6139191e8d | [
"Apache-2.0"
] | null | null | null | paso/src/SystemMatrix.cpp | markendr/esys-escript.github.io | 0023eab09cd71f830ab098cb3a468e6139191e8d | [
"Apache-2.0"
] | null | null | null |
/*****************************************************************************
*
* Copyright (c) 2003-2018 by The University of Queensland
* http://www.uq.edu.au
*
* Primary Business: Queensland, Australia
* Licensed under the Apache License, version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Development until 2012 by Earth Systems Science Computational Center (ESSCC)
* Development 2012-2013 by School of Earth Sciences
* Development from 2014 by Centre for Geoscience Computing (GeoComp)
*
*****************************************************************************/
/****************************************************************************/
/* Paso: SystemMatrix */
/****************************************************************************/
/* Author: Lutz Gross, l.gross@uq.edu.au */
/****************************************************************************/
#include "SystemMatrix.h"
#include "Options.h"
#include "PasoException.h"
#include "Preconditioner.h"
#include "Solver.h"
#include <escript/Data.h>
#include <cstring> // memcpy
#include <vector>
namespace paso {
template <>
void SystemMatrix<double>::setPreconditioner(Options* options)
{
if (!solver_p) {
SystemMatrix_ptr<double> mat(boost::dynamic_pointer_cast<SystemMatrix>(getPtr()));
solver_p = Preconditioner_alloc(mat, options);
}
}
template <>
void SystemMatrix<double>::solvePreconditioner(double* x, double* b)
{
Preconditioner* prec=(Preconditioner*)solver_p;
SystemMatrix_ptr<double> mat(boost::dynamic_pointer_cast<SystemMatrix>(getPtr()));
Preconditioner_solve(prec, mat, x, b);
}
template <>
void SystemMatrix<double>::freePreconditioner()
{
Preconditioner* prec = (Preconditioner*) solver_p;
Preconditioner_free(prec);
solver_p = NULL;
}
template <>
double SystemMatrix<double>::getGlobalSize() const
{
double global_size=0;
double my_size = mainBlock->getSize() + col_coupleBlock->getSize();
if (mpi_info->size > 1) {
#ifdef ESYS_MPI
MPI_Allreduce(&my_size, &global_size, 1, MPI_DOUBLE, MPI_SUM, mpi_info->comm);
#else
global_size = my_size;
#endif
} else {
global_size = my_size;
}
return global_size;
}
template <>
index_t* SystemMatrix<double>::borrowMainDiagonalPointer() const
{
int fail=0;
index_t* out = mainBlock->borrowMainDiagonalPointer();
if (out==NULL) fail=1;
#ifdef ESYS_MPI
int fail_loc = fail;
MPI_Allreduce(&fail_loc, &fail, 1, MPI_INT, MPI_MAX, mpi_info->comm);
#endif
if (fail>0)
throw PasoException("SystemMatrix::borrowMainDiagonalPointer: no main diagonal");
return out;
}
template <>
void SystemMatrix<double>::makeZeroRowSums(double* left_over)
{
const dim_t n = pattern->getNumOutput();
const dim_t nblk = block_size;
const dim_t blk = row_block_size;
const index_t* main_ptr = borrowMainDiagonalPointer();
rowSum(left_over);
// left_over now holds the row sum
#pragma omp parallel for
for (index_t ir=0; ir<n; ir++) {
for (index_t ib=0; ib<blk; ib++) {
const index_t irow = ib+blk*ir;
const double rtmp2 = mainBlock->val[main_ptr[ir]*nblk+ib+blk*ib];
const double rtmp1 = rtmp2-left_over[irow];
mainBlock->val[main_ptr[ir]*nblk+ib+blk*ib] = rtmp1;
left_over[irow]=rtmp2-rtmp1;
}
}
}
template <>
void SystemMatrix<double>::nullifyRows(double* mask_row, double main_diagonal_value)
{
if (type & MATRIX_FORMAT_CSC) {
throw PasoException("SystemMatrix::nullifyRows: Only CSR format is supported.");
}
if (col_block_size==1 && row_block_size==1) {
startRowCollect(mask_row);
mainBlock->nullifyRows_CSR_BLK1(mask_row, main_diagonal_value);
col_coupleBlock->nullifyRows_CSR_BLK1(mask_row, 0.);
double* remote_values = finishRowCollect();
row_coupleBlock->nullifyRows_CSR_BLK1(remote_values, 0.);
} else {
startRowCollect(mask_row);
mainBlock->nullifyRows_CSR(mask_row, main_diagonal_value);
col_coupleBlock->nullifyRows_CSR(mask_row, 0.);
double* remote_values = finishRowCollect();
row_coupleBlock->nullifyRows_CSR(remote_values, 0.);
}
}
template <>
void SystemMatrix<double>::copyColCoupleBlock()
{
if (mpi_info->size == 1) {
// nothing to do
return;
} else if (!row_coupleBlock) {
throw PasoException("SystemMatrix::copyColCoupleBlock: "
"creation of row_coupleBlock pattern not supported yet.");
} else if (row_coupler->in_use) {
throw PasoException("SystemMatrix::copyColCoupleBlock: Coupler in use.");
}
const dim_t numNeighboursSend = row_coupler->connector->send->neighbour.size();
const dim_t numNeighboursRecv = row_coupler->connector->recv->neighbour.size();
// start receiving
for (dim_t p = 0; p < numNeighboursRecv; p++) {
#ifdef ESYS_MPI
const index_t irow1 = row_coupler->connector->recv->offsetInShared[p];
const index_t irow2 = row_coupler->connector->recv->offsetInShared[p+1];
const index_t a = row_coupleBlock->pattern->ptr[irow1];
const index_t b = row_coupleBlock->pattern->ptr[irow2];
MPI_Irecv(&row_coupleBlock->val[a*block_size], (b-a) * block_size,
MPI_DOUBLE, row_coupler->connector->recv->neighbour[p],
mpi_info->counter()+row_coupler->connector->recv->neighbour[p],
mpi_info->comm, &row_coupler->mpi_requests[p]);
#endif
}
// start sending
index_t z0 = 0;
double* send_buffer = new double[col_coupleBlock->len];
const size_t block_size_size = block_size*sizeof(double);
for (dim_t p = 0; p < numNeighboursSend; p++) {
// j_min, j_max defines the range of columns to be sent to processor p
const index_t j_min = col_coupler->connector->recv->offsetInShared[p];
const index_t j_max = col_coupler->connector->recv->offsetInShared[p+1];
index_t z = z0;
// run over the rows to be connected to processor p
for (index_t rPtr=row_coupler->connector->send->offsetInShared[p];
rPtr < row_coupler->connector->send->offsetInShared[p+1]; ++rPtr) {
const index_t row = row_coupler->connector->send->shared[rPtr];
// collect the entries in the col couple block referring to
// columns on processor p
for (index_t iPtr=col_coupleBlock->pattern->ptr[row];
iPtr < col_coupleBlock->pattern->ptr[row+1]; ++iPtr) {
const index_t j = col_coupleBlock->pattern->index[iPtr];
if (j_min <= j && j < j_max) {
memcpy(&send_buffer[z],
&col_coupleBlock->val[block_size*iPtr],
block_size_size);
z+=block_size;
}
}
}
#ifdef ESYS_MPI
MPI_Issend(&send_buffer[z0], z-z0, MPI_DOUBLE,
row_coupler->connector->send->neighbour[p],
mpi_info->counter()+mpi_info->rank,
mpi_info->comm,
&row_coupler->mpi_requests[p+numNeighboursRecv]);
#endif
z0 = z;
}
// wait until everything is done
#ifdef ESYS_MPI
mpi_info->incCounter(mpi_info->size);
MPI_Waitall(numNeighboursSend+numNeighboursRecv, row_coupler->mpi_requests,
row_coupler->mpi_stati);
#endif
delete[] send_buffer;
}
template <>
void SystemMatrix<double>::applyBalanceInPlace(double* x, const bool RHS) const
{
if (is_balanced) {
if (RHS) {
const dim_t nrow = getTotalNumRows();
#pragma omp parallel for
for (index_t i=0; i<nrow; ++i) {
x[i] *= balance_vector[i];
}
} else {
const dim_t ncol = getTotalNumCols();
#pragma omp parallel for
for (index_t i=0; i<ncol; ++i) {
x[i] *= balance_vector[i];
}
}
}
}
template <>
void SystemMatrix<double>::applyBalance(double* x_out, const double* x, bool RHS) const
{
if (is_balanced) {
if (RHS) {
const dim_t nrow = getTotalNumRows();
#pragma omp parallel for
for (index_t i=0; i<nrow; ++i) {
x_out[i] = x[i] * balance_vector[i];
}
} else {
const dim_t ncol = getTotalNumCols();
#pragma omp parallel for
for (index_t i=0; i<ncol; ++i) {
x_out[i] = x[i] * balance_vector[i];
}
}
}
}
template <>
void SystemMatrix<double>::balance()
{
const dim_t nrow = getTotalNumRows();
if (!is_balanced) {
if ((type & MATRIX_FORMAT_CSC) || (type & MATRIX_FORMAT_OFFSET1)) {
throw PasoException("SystemMatrix_balance: No normalization "
"available for compressed sparse column or index offset 1.");
}
if (getGlobalNumRows() != getGlobalNumCols() ||
row_block_size != col_block_size) {
throw PasoException("SystemMatrix::balance: matrix needs to be a square matrix.");
}
// calculate absolute max value over each row
#pragma omp parallel for
for (dim_t irow=0; irow<nrow; ++irow) {
balance_vector[irow]=0;
}
mainBlock->maxAbsRow_CSR_OFFSET0(balance_vector);
if (col_coupleBlock->pattern->ptr != NULL) {
col_coupleBlock->maxAbsRow_CSR_OFFSET0(balance_vector);
}
// set balancing vector
#pragma omp parallel for
for (dim_t irow=0; irow<nrow; ++irow) {
const double fac = balance_vector[irow];
if (fac > 0) {
balance_vector[irow]=sqrt(1./fac);
} else {
balance_vector[irow]=1.;
}
}
///// rescale matrix /////
// start exchange
startCollect(balance_vector);
// process main block
mainBlock->applyDiagonal_CSR_OFFSET0(balance_vector, balance_vector);
// finish exchange
double* remote_values = finishCollect();
// process couple block
if (col_coupleBlock->pattern->ptr != NULL) {
col_coupleBlock->applyDiagonal_CSR_OFFSET0(balance_vector, remote_values);
}
if (row_coupleBlock->pattern->ptr != NULL) {
row_coupleBlock->applyDiagonal_CSR_OFFSET0(remote_values, balance_vector);
}
is_balanced = true;
}
}
template <>
SparseMatrix_ptr<double> SystemMatrix<double>::mergeSystemMatrix() const
{
const index_t n = mainBlock->numRows;
if (mpi_info->size == 1) {
index_t* ptr = new index_t[n];
#pragma omp parallel for
for (index_t i=0; i<n; i++)
ptr[i] = i;
SparseMatrix_ptr<double> out(mainBlock->getSubmatrix(n, n, ptr, ptr));
delete[] ptr;
return out;
}
#ifdef ESYS_MPI
const index_t size=mpi_info->size;
const index_t rank=mpi_info->rank;
// Merge main block and couple block to get the complete column entries
// for each row allocated to current rank. Output (ptr, idx, val)
// contains all info needed from current rank to merge a system matrix
index_t *ptr, *idx;
double *val;
mergeMainAndCouple(&ptr, &idx, &val);
std::vector<MPI_Request> mpi_requests(size*2);
std::vector<MPI_Status> mpi_stati(size*2);
// Now, pass all info to rank 0 and merge them into one sparse matrix
if (rank == 0) {
// First, copy local ptr values into ptr_global
const index_t global_n = getGlobalNumRows();
index_t* ptr_global = new index_t[global_n+1];
memcpy(ptr_global, ptr, (n+1)*sizeof(index_t));
delete[] ptr;
index_t iptr = n+1;
index_t* temp_n = new index_t[size];
index_t* temp_len = new index_t[size];
temp_n[0] = iptr;
// Second, receive ptr values from other ranks
for (index_t i=1; i<size; i++) {
const index_t remote_n = row_distribution->first_component[i+1] -
row_distribution->first_component[i];
MPI_Irecv(&ptr_global[iptr], remote_n, MPI_INT, i,
mpi_info->counter()+i, mpi_info->comm,
&mpi_requests[i]);
temp_n[i] = remote_n;
iptr += remote_n;
}
mpi_info->incCounter(size);
MPI_Waitall(size-1, &mpi_requests[1], &mpi_stati[0]);
// Then, prepare to receive idx and val from other ranks
index_t len = 0;
index_t offset = -1;
for (index_t i=0; i<size; i++) {
if (temp_n[i] > 0) {
offset += temp_n[i];
len += ptr_global[offset];
temp_len[i] = ptr_global[offset];
} else
temp_len[i] = 0;
}
index_t* idx_global = new index_t[len];
iptr = temp_len[0];
offset = n+1;
for (index_t i=1; i<size; i++) {
len = temp_len[i];
MPI_Irecv(&idx_global[iptr], len, MPI_INT, i,
mpi_info->counter()+i,
mpi_info->comm, &mpi_requests[i]);
const index_t remote_n = temp_n[i];
for (index_t j=0; j<remote_n; j++) {
ptr_global[j+offset] = ptr_global[j+offset] + iptr;
}
offset += remote_n;
iptr += len;
}
memcpy(idx_global, idx, temp_len[0]*sizeof(index_t));
delete[] idx;
MPI_Waitall(size-1, &mpi_requests[1], &mpi_stati[0]);
mpi_info->incCounter(size);
delete[] temp_n;
// Then generate the sparse matrix
const index_t rowBlockSize = mainBlock->row_block_size;
const index_t colBlockSize = mainBlock->col_block_size;
Pattern_ptr pat(new Pattern(mainBlock->pattern->type,
global_n, global_n, ptr_global, idx_global));
SparseMatrix_ptr<double> out(new SparseMatrix<double>(mainBlock->type, pat,
rowBlockSize, colBlockSize, false));
// Finally, receive and copy the values
iptr = temp_len[0] * block_size;
for (index_t i=1; i<size; i++) {
len = temp_len[i];
MPI_Irecv(&out->val[iptr], len * block_size, MPI_DOUBLE, i,
mpi_info->counter()+i, mpi_info->comm,
&mpi_requests[i]);
iptr += len*block_size;
}
memcpy(out->val, val, temp_len[0] * sizeof(double) * block_size);
delete[] val;
mpi_info->incCounter(size);
MPI_Waitall(size-1, &mpi_requests[1], &mpi_stati[0]);
delete[] temp_len;
return out;
} else { // it's not rank 0
// First, send out the local ptr
index_t tag = mpi_info->counter()+rank;
MPI_Issend(&ptr[1], n, MPI_INT, 0, tag, mpi_info->comm,
&mpi_requests[0]);
// Next, send out the local idx
index_t len = ptr[n];
tag += size;
MPI_Issend(idx, len, MPI_INT, 0, tag, mpi_info->comm,
&mpi_requests[1]);
// At last, send out the local val
len *= block_size;
tag += size;
MPI_Issend(val, len, MPI_DOUBLE, 0, tag, mpi_info->comm,
&mpi_requests[2]);
MPI_Waitall(3, &mpi_requests[0], &mpi_stati[0]);
mpi_info->setCounter(tag + size - rank);
delete[] ptr;
delete[] idx;
delete[] val;
} // rank
#endif
return SparseMatrix_ptr<double>();
}
template <>
SparseMatrix_ptr<cplx_t> SystemMatrix<cplx_t>::mergeSystemMatrix() const
{
throw PasoException("SystemMatrix::mergeSystemMatrix(): complex not implemented.");
}
} // namespace paso
| 34.082073 | 94 | 0.587389 | [
"vector"
] |
e77d2fcf4e5ba0500ac9e252d0a6bee31118e5b2 | 4,569 | cpp | C++ | source/supreme/tool_eraser.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 24 | 2019-05-12T12:03:21.000Z | 2022-03-30T01:05:46.000Z | source/supreme/tool_eraser.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 6 | 2019-05-12T11:54:54.000Z | 2022-02-26T11:47:20.000Z | source/supreme/tool_eraser.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 12 | 2019-05-12T13:48:57.000Z | 2022-02-25T15:25:24.000Z | #include "tool_eraser.h"
#include "dialogbits.h"
#include "editor.h"
#include "terrainedit.h"
EraserTool::EraserTool(void)
{
brush=0;
lastX=-1;
lastY=-1;
eraseFlag=EF_ITEM|EF_BADGUY|EF_SPECIAL;
}
EraserTool::~EraserTool(void)
{
}
void EraserTool::Update(int msx,int msy)
{
if(msx<380 || msy<400 || msx>639 || msy>479)
return;
if(GetDisplayMGL()->MouseTap())
{
if(PointInRect(msx,msy,397-15,442-15,397+16,442+16))
{
brush++;
if(brush>13)
brush=0;
}
if(PointInRect(msx,msy,520,402,520+100,402+14))
eraseFlag^=EF_ITEM;
if(PointInRect(msx,msy,520,417,520+100,417+14))
eraseFlag^=EF_BADGUY;
if(PointInRect(msx,msy,520,432,520+100,432+14))
eraseFlag^=EF_SPECIAL;
if(PointInRect(msx,msy,520,447,520+100,447+14))
eraseFlag^=EF_WALL;
if(PointInRect(msx,msy,520,462,520+100,462+14))
eraseFlag^=EF_LIGHT;
}
if(GetDisplayMGL()->RMouseTap())
{
if(PointInRect(msx,msy,397-15,442-15,397+16,442+16))
{
brush--;
if(brush>13)
brush=13;
}
}
}
void EraserTool::Render(int msx,int msy)
{
int minusBrush,plusBrush;
if(PointInRect(msx,msy,520,402,520+100,402+14))
RenderCheckbox(1,520,402,CHECK_ON*((eraseFlag&EF_ITEM)!=0),"Items",GetDisplayMGL());
else
RenderCheckbox(0,520,402,CHECK_ON*((eraseFlag&EF_ITEM)!=0),"Items",GetDisplayMGL());
if(PointInRect(msx,msy,520,417,520+100,417+14))
RenderCheckbox(1,520,417,CHECK_ON*((eraseFlag&EF_BADGUY)!=0),"Badguys",GetDisplayMGL());
else
RenderCheckbox(0,520,417,CHECK_ON*((eraseFlag&EF_BADGUY)!=0),"Badguys",GetDisplayMGL());
if(PointInRect(msx,msy,520,432,520+100,432+14))
RenderCheckbox(1,520,432,CHECK_ON*((eraseFlag&EF_SPECIAL)!=0),"Specials",GetDisplayMGL());
else
RenderCheckbox(0,520,432,CHECK_ON*((eraseFlag&EF_SPECIAL)!=0),"Specials",GetDisplayMGL());
if(PointInRect(msx,msy,520,447,520+100,447+14))
RenderCheckbox(1,520,447,CHECK_ON*((eraseFlag&EF_WALL)!=0),"Walls",GetDisplayMGL());
else
RenderCheckbox(0,520,447,CHECK_ON*((eraseFlag&EF_WALL)!=0),"Walls",GetDisplayMGL());
if(PointInRect(msx,msy,520,462,520+100,462+14))
RenderCheckbox(1,520,462,CHECK_ON*((eraseFlag&EF_LIGHT)!=0),"Light",GetDisplayMGL());
else
RenderCheckbox(0,520,462,CHECK_ON*((eraseFlag&EF_LIGHT)!=0),"Light",GetDisplayMGL());
// brush size
minusBrush=brush;
plusBrush=brush+1;
if(PointInRect(msx,msy,397-15,442-15,397+16,442+16))
DrawFillBox(397-15,442-15,397+16,442+16,8+32*1);
DrawBox(397-15,442-15,397+16,442+16,31);
DrawFillBox(397-(minusBrush),
442-(minusBrush),
397+(plusBrush),
442+(plusBrush),24);
Print(397-15,442-26,"Brush",0,1);
}
void EraserTool::SetInk(void)
{
}
void EraserTool::StartPlop(void)
{
lastX=-1;
lastY=-1;
Plop();
}
void EraserTool::PlopOne(int x,int y)
{
Map *m;
m=EditorGetMap();
if(x>=0 && y>=0 && x<m->width && y<m->height && m->map[x+y*m->width].select)
{
if(eraseFlag&EF_LIGHT)
m->map[x+y*m->width].light=0;
if(eraseFlag&EF_WALL)
m->map[x+y*m->width].wall=0;
if(eraseFlag&EF_ITEM)
m->map[x+y*m->width].item=0;
if(eraseFlag&EF_BADGUY)
{
int i;
for(i=0;i<MAX_MAPMONS;i++)
if((m->badguy[i].type) && (m->badguy[i].x==x) && (m->badguy[i].y==y))
m->badguy[i].type=0;
}
if(eraseFlag&EF_SPECIAL)
{
int i;
for(i=0;i<MAX_SPECIAL;i++)
{
if(m->special[i].x==x && m->special[i].y==y)
{
m->special[i].x=255;
}
}
}
}
}
void EraserTool::Plop(void)
{
Map *m;
int x,y;
int i,j,minusBrush,plusBrush;
EditorGetTileXY(&x,&y);
m=EditorGetMap();
if(x!=lastX || y!=lastY)
{
minusBrush=brush/2;
plusBrush=(brush+1)/2;
for(j=y-minusBrush;j<=y+plusBrush;j++)
for(i=x-minusBrush;i<=x+plusBrush;i++)
PlopOne(i,j);
MakeNormalSound(SND_MENUCLICK);
lastX=x;
lastY=y;
AddMapGuys(m);
}
}
void EraserTool::ShowTarget(void)
{
int x1,x2,y1,y2,cx,cy;
static byte col=0;
int tileX,tileY;
int tileX2,tileY2,minusBrush,plusBrush;
col=255-col;
GetCamera(&cx,&cy);
EditorGetTileXY(&tileX,&tileY);
minusBrush=brush/2;
plusBrush=(brush+1)/2;
tileX2=tileX+plusBrush;
tileY2=tileY+plusBrush;
tileX-=minusBrush;
tileY-=minusBrush;
x1=tileX*TILE_WIDTH-(cx-320);
y1=tileY*TILE_HEIGHT-(cy-240);
x2=tileX2*TILE_WIDTH-(cx-320)+TILE_WIDTH-1;
y2=tileY2*TILE_HEIGHT-(cy-240)+TILE_HEIGHT-1;
DrawBox(x1,y1,x2,y1,col);
DrawBox(x1,y2,x2,y2,col);
DrawBox(x1,y1,x1,y2,col);
DrawBox(x2,y1,x2,y2,col);
}
void EraserTool::SuckUp(int x,int y)
{
}
void EraserTool::BrushUp(void)
{
brush++;
if(brush>13)
brush=0;
}
void EraserTool::StartErase(void)
{
StartPlop();
}
void EraserTool::Erase(void)
{
Plop();
}
| 20.488789 | 92 | 0.669731 | [
"render"
] |
e77ed9525baa3ebc344a0c8658b01dc9841586d9 | 2,169 | cpp | C++ | LeetCode/Problems/Algorithms/#315_CountOfSmallerNumbersAfterSelf_sol6_segment_tree_on_compressed_values_O(NlogN)_time_O(N)_extra_space.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#315_CountOfSmallerNumbersAfterSelf_sol6_segment_tree_on_compressed_values_O(NlogN)_time_O(N)_extra_space.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#315_CountOfSmallerNumbersAfterSelf_sol6_segment_tree_on_compressed_values_O(NlogN)_time_O(N)_extra_space.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class SegmentTree{
private:
const int N;
vector<int> tree;
void add(int node, int l, int r, const int& POS, const int& VAL){
if(l == r){
tree[node] += VAL;
}else{
int mid = (l + r) / 2;
if(POS <= mid){
add(2 * node + 1, l, mid, POS, VAL);
}else{
add(2 * node + 2, mid + 1, r, POS, VAL);
}
tree[node] = tree[2 * node + 1] + tree[2 * node + 2];
}
}
int query(int node, int l, int r, const int& L, const int& R){
if(r < L || R < l){
return 0;
}
if(L <= l && r <= R){
return tree[node];
}
int mid = (l + r) / 2;
return query(2 * node + 1, l, mid, L, R) +
query(2 * node + 2, mid + 1, r, L, R);
}
public:
SegmentTree(const int& N): N(N){
int minLeaves = 1;
while(minLeaves < N){
minLeaves *= 2;
}
tree.resize(2 * minLeaves, 0);
}
void add(const int& POS, const int& VAL){
add(0, 0, N - 1, POS, VAL);
}
int query(const int& L, const int& R){
if(L <= R){
return query(0, 0, N - 1, L, R);
}
return 0;
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
const int N = nums.size();
vector<int> count(N);
// coordinate/value compression
set<int> uniqueNums(nums.begin(), nums.end());
unordered_map<int, int> originalToCompressed;
int idx = -1;
for(int num: uniqueNums){
idx += 1;
originalToCompressed[num] = idx;
}
// segment tree on compressed coordinates/values
const int M = originalToCompressed.size();
SegmentTree segmentTree(M);
for(int i = N - 1; i >= 0; --i){
count[i] = segmentTree.query(0, originalToCompressed[nums[i]] - 1);
segmentTree.add(originalToCompressed[nums[i]], 1);
}
return count;
}
}; | 27.807692 | 80 | 0.437529 | [
"vector"
] |
e78326b386d88ec09c967bc7bc8c92474701f0b7 | 6,362 | cpp | C++ | other/EscripturaArbresCelula.cpp | albertsgrc/practica-pro2 | d1029c09832080bd805d36408f1dcc2c0bdfc5fd | [
"MIT"
] | null | null | null | other/EscripturaArbresCelula.cpp | albertsgrc/practica-pro2 | d1029c09832080bd805d36408f1dcc2c0bdfc5fd | [
"MIT"
] | null | null | null | other/EscripturaArbresCelula.cpp | albertsgrc/practica-pro2 | d1029c09832080bd805d36408f1dcc2c0bdfc5fd | [
"MIT"
] | null | null | null | #include <cmath>
#include <vector>
/***********INDICACIONS*************
*Canviar "***Organisme***" pel nom de la vostra classe organisme
*Canviar "***Celula***" pel nom de la vostra classe o estructura de dades que representa una cèlula (ej.: pair<int, bool> o simplement Celula)
*Canviar la resta de elements entre estrelles pel que s'indica en cada cas
************************************/
/***********DECLARACIONS HPP***************/
static void altura_arb(Arbre<***Celula***>&a, int&h);
static void conv_a_matriu(Arbre<***Celula***>&a, vector< vector<***Celula***> >&m, int h, vector<int> &ultimpos, int hmax);
static void escriu_elem(const ***Celula*** &elem);
static void escriure_arbre(const vector< vector<***Celula***> >&m);
static void escriure_arbre_gran(const vector< vector<***Celula***> >&m);
static void escriure_arbcelula_visual(const Arbre<***Celula***>&a);
static bool es_buida(const ***Celula***&c);
static bool es_activa(const ***Celula***&c);
static int id(const ***Celula***&c);
static ***Celula*** celvacia();
/******************************************/
void ***Organisme***::altura_arb(Arbre<***Celula***>&a, int&h) {
if (a.es_buit()) h = 0;
else if (not a.es_buit()) {
int h2, h3;
Arbre<***Celula***> a1, a2;
***Celula*** c = a.arrel();
a.fills(a1, a2);
altura_arb(a1, h2);
altura_arb(a2, h3);
h = max(h2, h3) + 1;
a.plantar(c, a1, a2);
}
}
void ***Organisme***::conv_a_matriu(Arbre<***Celula***>&a, vector< vector<***Celula***> >&m, int h, vector<int>&ultimpos, int hmax) {
if (not a.es_buit()) {
***Celula*** c = a.arrel();
m[h][ultimpos[h]] = c;
++ultimpos[h];
Arbre<***Celula***> a1, a2;
a.fills(a1, a2);
conv_a_matriu(a1, m, h+1, ultimpos, hmax);
conv_a_matriu(a2, m, h+1, ultimpos, hmax);
a.plantar(c, a1, a2);
}
else {
++ultimpos[h];
++h;
int espais = 2;
while (h < hmax) {
ultimpos[h] += espais;
espais *= 2;
++h;
}
}
}
void espais(int n) {
for (int i = 0; i < n; ++i) cout << ' ';
}
bool ***Organisme***::es_buida(const ***Celula***&c) {
return ***c.es_buida()***; // Canviar per la vostra funció o paràmetre (indica si l'id de la cèlula és 0)
}
bool ***Organisme***::es_activa(const ***Celula***&c) {
return ***c.es_activa()***; // Canviar per la vostra funció o paràmetre (indica si la cèlula és activa)
}
int ***Organisme***::id(const ***Celula***&c) {
return ***c.consul_id()***; // Canviar per la vostra funció o paràmetre (retorna l'identificador de la cèlula)
}
***Celula*** ***Organisme***::celvacia() { // Funció que retorna una cèlula buida (amb id = 0)
return Celula(); // Canviar per la vostra funció o conjunt d'instruccions que retornin una cèlula amb identificador 0
// Exemple amb struct:
// Celula c;
// c.id = 0;
// c.activa = false;
// return c;
}
void ***Organisme***::escriu_elem(const ***Celula***&elem) {
if (not es_buida(elem)) {
if (not es_activa(elem)) cout << '!';
cout << id(elem);
}
else cout << ' ';
}
int ndigits(bool es_activa, int n) {
if (n < 10 and es_activa) return 1;
else if (n < 10) return 2;
else return 1 + ndigits(es_activa, n/10);
}
void ***Organisme***::escriure_arbre(const vector< vector<***Celula***> >&m) {
int n = m.size() - 1;
int espaientreelements = 3*pow(2, n - 1);
int espaiinicial = espaientreelements/2;
int espaientrebarres = espaiinicial/2;
int espaientrebranques = 3*espaientrebarres;
int strideespaiinicial = espaientrebarres/2;
for (int i = 0; i < n; ++i) {
if (n - i == 3) espaiinicial = 6;
else if (n - i == 2) espaiinicial = 3;
else if (n - i == 1) espaiinicial = 1;
espais(espaiinicial - 1);
espaiinicial -= strideespaiinicial;
for (int j = 0; j < m[i].size(); ++j) {
escriu_elem(m[i][j]);
int sumadigits = 0;
if (j%2 == 0 and not es_buida(m[i][j])) {
sumadigits += ndigits(es_activa(m[i][j]), id(m[i][j])) - 1;
if (j+1 < m[i].size()) {
sumadigits += ndigits(es_activa(m[i][j+1]), id(m[i][j+1])) - 1;
}
}
if (n - i == 1) {
if (j%2 == 0) espaientreelements = 4;
else espaientreelements = 2;
}
espais(espaientreelements - 1 - sumadigits);
}
cout << endl;
if (n - i == 3) espaiinicial = 4;
else if (n - i == 2) espaiinicial = 2;
espais(espaiinicial - 1);
espaiinicial -= strideespaiinicial;
int j = 0;
for (int k = 0; k < m[i].size(); ++k) {
if (not es_buida(m[i + 1][j])) cout << '/';
else cout << ' ';
++j;
if (n - i == 2) espaientrebarres = 2;
else if (n - i == 3) espaientrebarres = 4;
espais(espaientrebarres - 1);
if (not es_buida(m[i + 1][j])) cout << '\\';
else cout << ' ';
++j;
if (n - i == 3) espaientrebranques = 8;
else if (n - i == 2) espaientrebranques = 4;
espais(espaientrebranques - 1);
}
cout << endl;
strideespaiinicial /= 2;
espaientrebarres /= 2;
espaientrebranques /= 2;
espaientreelements /= 2;
}
}
void ***Organisme***::escriure_arbcelula_visual(const Arbre<***Celula***>&arb) { // Es passa const i es fa una còpia per tal que la gent que tingui la funció de la classe declarada com a const no tingui errors al compilar
cout << endl << "----Arbre de celules----" << endl << endl;
int h;
Arbre<***Celula***> a = arb;
altura_arb(a, h);
vector< vector<***Celula***> > m(h + 1, vector<***Celula***>());
int pot = 1;
for (int i = 0; i <= h; ++i) {
m[i] = vector<***Celula***>(pot, celvacia());
pot *= 2;
}
vector<int> ultimpos(h + 1, 0);
int haux = 0;
conv_a_matriu(a, m, haux, ultimpos, h);
escriure_arbre(m);
cout << "------------------------" << endl;
}
| 36.774566 | 222 | 0.510531 | [
"vector"
] |
e7838424694655f1278ffdce7b8241397999d991 | 2,978 | cpp | C++ | dkk_plg_default/src/XTCReader.cpp | mjf-89/DistributedKernelKmeans | ca6daa81cd51a0f2400a111c5d10a9ef144f1574 | [
"MIT"
] | null | null | null | dkk_plg_default/src/XTCReader.cpp | mjf-89/DistributedKernelKmeans | ca6daa81cd51a0f2400a111c5d10a9ef144f1574 | [
"MIT"
] | null | null | null | dkk_plg_default/src/XTCReader.cpp | mjf-89/DistributedKernelKmeans | ca6daa81cd51a0f2400a111c5d10a9ef144f1574 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include "Exception.h"
#include "XTCReader.h"
#include "xdrfile.h"
#include "xdrfile_xtc.h"
#include "FileUtils.h"
namespace DKK{
const std::string &XTCReader::getName()
{
static std::string name = "XTCReader";
return name;
}
const std::vector<std::string> &XTCReader::getReqPrmNames()
{
//stupid fix to avoid c++ 11 init lists
static std::string reqPrmNamesA[] = {
"IN",
"ATOMS"
};
static std::vector<std::string> reqPrmNames(reqPrmNamesA, reqPrmNamesA+2);
return reqPrmNames;
}
const std::vector<std::string> &XTCReader::getReqPrimitiveNames()
{
static std::vector<std::string> reqPrimitiveNames;
return reqPrimitiveNames;
}
void XTCReader::init()
{
fin=NULL;
//open input file
getParameter("IN", fin_name);
openFile();
//read number of atoms per frame
read_xtc_natoms(fin_name.c_str(), &n_atoms);
coord = (rvec*) malloc(n_atoms*sizeof(rvec));
//get the atom indexes to be considered
getParameter("ATOMS", atoms);
if(atoms.size()%2)
throw Exception("ATOMS parameter should specify couples of values as index bounds.");
//find the actual dimensionality of the dataset
D = 0;
for(int i=0; i<atoms.size(); i++)
if(i%2)
D += atoms[i]-atoms[i-1]+1;
D *= 3;
createFrameIndex();
N=frameIndex.size();
}
void XTCReader::createFrameIndex()
{
frameIndex.clear();
DKK_TYPE_OFF offset=0;
while(true){
frameIndex.push_back(offset);
try{
offset = skipFrame();
}catch(Exception &e){
break;
}
}
frameIndex.pop_back();
goTo(0);
}
void XTCReader::goTo(const int &idx)
{
dkk_fseek(xdrfile_get_cfile(fin), frameIndex[idx], 0);
}
void XTCReader::openFile()
{
if(fin!=NULL)
xdrfile_close(fin);
fin=xdrfile_open(fin_name.c_str(), "r");
}
DKK_TYPE_OFF XTCReader::skipFrame()
{
DKK_TYPE_OFF offset=0;
int data_length=0;
int BYTES_PER_XDR_UNIT=4;
//retrive current file offset
offset = dkk_ftell(xdrfile_get_cfile(fin));
//skip header: skip 3int,1float
offset += 16;
//skip box: skip 9float
offset += 36;
//skip header-data
offset += 36;
//seek file
dkk_fseek(xdrfile_get_cfile(fin), offset, 0);
if(ferror(xdrfile_get_cfile(fin)))
return 0;
//get frame data length
if(!xdrfile_read_int(&data_length, 1, fin))
throw Exception("IO XTC error, cannot read data length.");
offset += 4;
//round the number of bytes to fill xdr units
int rndup = data_length % BYTES_PER_XDR_UNIT;
rndup = rndup > 0 ? BYTES_PER_XDR_UNIT - rndup : 0;
//skip frame data
offset += (data_length + rndup);
//seek file
fseek(xdrfile_get_cfile(fin), offset, 0);
return offset;
}
int XTCReader::getDimensionality()
{
return D;
}
int XTCReader::getLength()
{
return N;
}
int XTCReader::read(int idx, DKK_TYPE_REAL* data)
{
goTo(idx);
read_xtc(fin, n_atoms, &step, &time, box, coord, &prec);
int k = 0;
for(int i=0; i<atoms.size(); i+=2){
for(int j=atoms[i]-1; j<atoms[i+1]; j++){
data[k++] = coord[j][0];
data[k++] = coord[j][1];
data[k++] = coord[j][2];
}
}
return k;
}
}
| 18.72956 | 87 | 0.680658 | [
"vector"
] |
e7890903d57d52359377a332ecbe11640bbb2258 | 6,217 | cc | C++ | src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc | samotarnik/grpc | 3278bdceda8030d5aa130f12765e5f07263c860d | [
"Apache-2.0"
] | 36,552 | 2015-02-26T17:30:13.000Z | 2022-03-31T22:41:33.000Z | src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc | SanjanaSingh897/grpc | 2d858866eb95ce5de8ccc8c35189a12733d8ca79 | [
"Apache-2.0"
] | 23,536 | 2015-02-26T17:50:56.000Z | 2022-03-31T23:39:42.000Z | src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc | SanjanaSingh897/grpc | 2d858866eb95ce5de8ccc8c35189a12733d8ca79 | [
"Apache-2.0"
] | 11,050 | 2015-02-26T17:22:10.000Z | 2022-03-31T10:12:35.000Z | /*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h"
#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
/* Privacy-integrity alts_grpc_record_protocol object uses the same struct
* defined in alts_grpc_record_protocol_common.h. */
/* --- alts_grpc_record_protocol methods implementation. --- */
static tsi_result alts_grpc_privacy_integrity_protect(
alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
grpc_slice_buffer* protected_slices) {
/* Input sanity check. */
if (rp == nullptr || unprotected_slices == nullptr ||
protected_slices == nullptr) {
gpr_log(GPR_ERROR,
"Invalid nullptr arguments to alts_grpc_record_protocol protect.");
return TSI_INVALID_ARGUMENT;
}
/* Allocates memory for output frame. In privacy-integrity protect, the
* protected frame is stored in a newly allocated buffer. */
size_t protected_frame_size =
unprotected_slices->length + rp->header_length +
alts_iovec_record_protocol_get_tag_length(rp->iovec_rp);
grpc_slice protected_slice = GRPC_SLICE_MALLOC(protected_frame_size);
iovec_t protected_iovec = {GRPC_SLICE_START_PTR(protected_slice),
GRPC_SLICE_LENGTH(protected_slice)};
/* Calls alts_iovec_record_protocol protect. */
char* error_details = nullptr;
alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp,
unprotected_slices);
grpc_status_code status =
alts_iovec_record_protocol_privacy_integrity_protect(
rp->iovec_rp, rp->iovec_buf, unprotected_slices->count,
protected_iovec, &error_details);
if (status != GRPC_STATUS_OK) {
gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
gpr_free(error_details);
grpc_slice_unref_internal(protected_slice);
return TSI_INTERNAL_ERROR;
}
grpc_slice_buffer_add(protected_slices, protected_slice);
grpc_slice_buffer_reset_and_unref_internal(unprotected_slices);
return TSI_OK;
}
static tsi_result alts_grpc_privacy_integrity_unprotect(
alts_grpc_record_protocol* rp, grpc_slice_buffer* protected_slices,
grpc_slice_buffer* unprotected_slices) {
/* Input sanity check. */
if (rp == nullptr || protected_slices == nullptr ||
unprotected_slices == nullptr) {
gpr_log(
GPR_ERROR,
"Invalid nullptr arguments to alts_grpc_record_protocol unprotect.");
return TSI_INVALID_ARGUMENT;
}
/* Allocates memory for output frame. In privacy-integrity unprotect, the
* unprotected data are stored in a newly allocated buffer. */
if (protected_slices->length < rp->header_length + rp->tag_length) {
gpr_log(GPR_ERROR, "Protected slices do not have sufficient data.");
return TSI_INVALID_ARGUMENT;
}
size_t unprotected_frame_size =
protected_slices->length - rp->header_length - rp->tag_length;
grpc_slice unprotected_slice = GRPC_SLICE_MALLOC(unprotected_frame_size);
iovec_t unprotected_iovec = {GRPC_SLICE_START_PTR(unprotected_slice),
GRPC_SLICE_LENGTH(unprotected_slice)};
/* Strips frame header from protected slices. */
grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
grpc_slice_buffer_move_first(protected_slices, rp->header_length,
&rp->header_sb);
iovec_t header_iovec = alts_grpc_record_protocol_get_header_iovec(rp);
/* Calls alts_iovec_record_protocol unprotect. */
char* error_details = nullptr;
alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp, protected_slices);
grpc_status_code status =
alts_iovec_record_protocol_privacy_integrity_unprotect(
rp->iovec_rp, header_iovec, rp->iovec_buf, protected_slices->count,
unprotected_iovec, &error_details);
if (status != GRPC_STATUS_OK) {
gpr_log(GPR_ERROR, "Failed to unprotect, %s", error_details);
gpr_free(error_details);
grpc_slice_unref_internal(unprotected_slice);
return TSI_INTERNAL_ERROR;
}
grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
grpc_slice_buffer_reset_and_unref_internal(protected_slices);
grpc_slice_buffer_add(unprotected_slices, unprotected_slice);
return TSI_OK;
}
static const alts_grpc_record_protocol_vtable
alts_grpc_privacy_integrity_record_protocol_vtable = {
alts_grpc_privacy_integrity_protect,
alts_grpc_privacy_integrity_unprotect, nullptr};
tsi_result alts_grpc_privacy_integrity_record_protocol_create(
gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
bool is_protect, alts_grpc_record_protocol** rp) {
if (crypter == nullptr || rp == nullptr) {
gpr_log(GPR_ERROR,
"Invalid nullptr arguments to alts_grpc_record_protocol create.");
return TSI_INVALID_ARGUMENT;
}
auto* impl = static_cast<alts_grpc_record_protocol*>(
gpr_zalloc(sizeof(alts_grpc_record_protocol)));
/* Calls alts_grpc_record_protocol init. */
tsi_result result =
alts_grpc_record_protocol_init(impl, crypter, overflow_size, is_client,
/*is_integrity_only=*/false, is_protect);
if (result != TSI_OK) {
gpr_free(impl);
return result;
}
impl->vtable = &alts_grpc_privacy_integrity_record_protocol_vtable;
*rp = impl;
return TSI_OK;
}
| 42.875862 | 100 | 0.747627 | [
"object"
] |
e78949933a22b8ffe8ed3f31977560e06403d2af | 3,974 | cc | C++ | tensorflow/compiler/xla/python/distributed/client_server_test.cc | joshz123/tensorflow | 7841ca029060ab78e221e757d4b1ee6e3e0ffaa4 | [
"Apache-2.0"
] | 57 | 2017-09-03T07:08:31.000Z | 2022-02-28T04:33:42.000Z | tensorflow/compiler/xla/python/distributed/client_server_test.cc | joshz123/tensorflow | 7841ca029060ab78e221e757d4b1ee6e3e0ffaa4 | [
"Apache-2.0"
] | 47 | 2020-05-15T11:30:04.000Z | 2021-08-11T16:51:08.000Z | tensorflow/compiler/xla/python/distributed/client_server_test.cc | joshz123/tensorflow | 7841ca029060ab78e221e757d4b1ee6e3e0ffaa4 | [
"Apache-2.0"
] | 66 | 2020-05-15T10:05:12.000Z | 2022-02-14T07:28:18.000Z | /* Copyright 2020 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 "grpcpp/security/server_credentials.h"
#include "absl/time/time.h"
#include "tensorflow/compiler/xla/protobuf_util.h"
#include "tensorflow/compiler/xla/python/distributed/client.h"
#include "tensorflow/compiler/xla/python/distributed/protocol.pb.h"
#include "tensorflow/compiler/xla/python/distributed/service.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/threadpool.h"
namespace xla {
namespace {
TEST(ClientServerTest, ConnectToServer) {
DistributedRuntimeServiceImpl service(/*num_nodes=*/2);
::grpc::ServerBuilder builder;
builder.RegisterService(&service);
auto server = builder.BuildAndStart();
std::vector<LocalTopologyProto> locals(2);
locals[0].set_node_id(0);
locals[1].set_node_id(1);
DeviceProto* d0 = locals[0].add_devices();
d0->set_local_device_ordinal(0);
DeviceProto* d1 = locals[0].add_devices();
d1->set_local_device_ordinal(0);
DeviceProto* d2 = locals[0].add_devices();
d2->set_local_device_ordinal(707);
DeviceProto* d3 = locals[1].add_devices();
d3->set_local_device_ordinal(1);
GlobalTopologyProto expected_topology;
auto* node0 = expected_topology.add_nodes();
auto* node1 = expected_topology.add_nodes();
*node0 = locals[0];
node0->mutable_devices(0)->set_global_device_id(0);
node0->mutable_devices(1)->set_global_device_id(1);
node0->mutable_devices(2)->set_global_device_id(2);
*node1 = locals[1];
node1->mutable_devices(0)->set_global_device_id(3);
auto thread0_fn = [&]() -> xla::Status {
DistributedRuntimeClient client(
server->InProcessChannel(::grpc::ChannelArguments()));
GlobalTopologyProto topology;
TF_RETURN_IF_ERROR(client.Connect(locals[0], &topology));
TF_RET_CHECK(
xla::protobuf_util::ProtobufEquals(topology, expected_topology));
TF_RETURN_IF_ERROR(client.KeyValueSet("key1", "value1"));
TF_ASSIGN_OR_RETURN(
std::string value,
client.BlockingKeyValueGet("key2", absl::InfiniteDuration()));
TF_RET_CHECK(value == "value2");
return xla::Status::OK();
};
auto thread1_fn = [&]() -> xla::Status {
DistributedRuntimeClient client(
server->InProcessChannel(::grpc::ChannelArguments()));
GlobalTopologyProto topology;
TF_RETURN_IF_ERROR(client.Connect(locals[1], &topology));
TF_RET_CHECK(
xla::protobuf_util::ProtobufEquals(topology, expected_topology));
TF_ASSIGN_OR_RETURN(
std::string value,
client.BlockingKeyValueGet("key1", absl::InfiniteDuration()));
TF_RET_CHECK(value == "value1");
TF_RETURN_IF_ERROR(client.KeyValueSet("key2", "value2"));
return xla::Status::OK();
};
std::vector<std::function<xla::Status()>> functions = {thread0_fn,
thread1_fn};
std::vector<xla::Status> statuses(functions.size());
{
tensorflow::thread::ThreadPool thread_pool(
tensorflow::Env::Default(), "test_threads", functions.size());
for (int i = 0; i < functions.size(); ++i) {
thread_pool.Schedule([&, i]() { statuses[i] = functions[i](); });
}
}
TF_EXPECT_OK(statuses[0]);
TF_EXPECT_OK(statuses[1]);
}
} // namespace
} // namespace xla
| 38.582524 | 80 | 0.701309 | [
"vector"
] |
e78a88ebbc1bea5409a33f955c17ffe6470398a6 | 32,449 | cpp | C++ | src/vlGraphics/Text.cpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | 1 | 2017-06-29T18:25:11.000Z | 2017-06-29T18:25:11.000Z | src/vlGraphics/Text.cpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | null | null | null | src/vlGraphics/Text.cpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | 1 | 2021-01-01T10:43:33.000Z | 2021-01-01T10:43:33.000Z | /**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2017, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include <vlGraphics/Text.hpp>
#include <vlGraphics/OpenGLContext.hpp>
#include <vlGraphics/Actor.hpp>
#include <vlCore/Log.hpp>
#include "ft2build.h"
#include FT_FREETYPE_H
using namespace vl;
//-----------------------------------------------------------------------------
void Text::render_Implementation(const Actor* actor, const Shader*, const Camera* camera, OpenGLContext* gl_context) const
{
gl_context->bindVAS(NULL, false, false);
VL_CHECK(font())
if (!font() || !font()->mFT_Face)
return;
if ( text().empty() )
return;
// Lighting can be enabled or disabled.
// glDisable(GL_LIGHTING);
// Blending must be enabled explicity by the vl::Shader, also to perform z-sort.
// glEnable(GL_BLEND);
// Trucchetto che usiamo per evitare z-fighting:
// Pass #1 - fill color and stencil
// - disable depth write mask
// - depth test can be enabled or not by the user
// - depth func can be choosen by the user
// - render in the order: background, border, shadow, outline, text
// Pass #2 - fill z-buffer
// - enable depth write mask
// - disable color mask
// - disable stencil
// - drawing background and border
// Pass #1
// disable z-writing
GLboolean depth_mask=0;
glGetBooleanv(GL_DEPTH_WRITEMASK, &depth_mask);
glDepthMask(GL_FALSE);
// background
if (backgroundEnabled())
renderBackground( actor, camera );
// border
if (borderEnabled())
renderBorder( actor, camera );
// to have the most correct results we should render the text twice one for color and stencil, the other for the z-buffer
// shadow render
if (shadowEnabled())
renderText( actor, camera, shadowColor(), shadowVector() );
// outline render
if (outlineEnabled())
{
renderText( actor, camera, outlineColor(), fvec2(-1,0) );
renderText( actor, camera, outlineColor(), fvec2(+1,0) );
renderText( actor, camera, outlineColor(), fvec2(0,-1) );
renderText( actor, camera, outlineColor(), fvec2(0,+1) );
}
// text render
renderText( actor, camera, color(), fvec2(0,0) );
// Pass #2
// fills the z-buffer (not the stencil buffer): approximated to the text bbox
// restores depth mask
glDepthMask(depth_mask);
if (depth_mask)
{
// disables writing to the color buffer
GLboolean color_mask[4];
glGetBooleanv(GL_COLOR_WRITEMASK, color_mask);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
// disable writing to the stencil buffer
int stencil_front_mask=0;
glGetIntegerv(GL_STENCIL_WRITEMASK, &stencil_front_mask);
int stencil_back_mask=0;
if (Has_GL_Version_2_0)
glGetIntegerv(GL_STENCIL_BACK_WRITEMASK, &stencil_back_mask);
glStencilMask(0);
// background
renderBackground( actor, camera );
// border
renderBorder( actor, camera );
// restores color writing
glColorMask(color_mask[0],color_mask[1],color_mask[2],color_mask[3]);
// restore the stencil masks
glStencilMask(stencil_front_mask);
if (Has_GL_Version_2_0)
glStencilMaskSeparate(GL_BACK, stencil_back_mask);
}
// restore the right color and normal since we changed them
glColor4fv( gl_context->color().ptr() );
glNormal3fv( gl_context->normal().ptr() );
}
//-----------------------------------------------------------------------------
void Text::renderText(const Actor* actor, const Camera* camera, const fvec4& color, const fvec2& offset) const
{
if(!mFont)
{
Log::error("Text::renderText() error: no Font assigned to the Text object.\n");
VL_TRAP()
return;
}
if (!font()->mFT_Face)
{
Log::error("Text::renderText() error: invalid FT_Face: probably you tried to load an unsupported font format.\n");
VL_TRAP()
return;
}
int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() };
if (viewport[2] < 1) viewport[2] = 1;
if (viewport[3] < 1) viewport[3] = 1;
// note that we only save and restore the server side states
if (mode() == Text2D)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
VL_CHECK_OGL();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
// glLoadIdentity();
// gluOrtho2D( -0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f );
// clever trick part #1
fmat4 mat = fmat4::getOrtho(-0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f, -1, +1);
mat.e(2,2) = 1.0f; // preserve the z value from the incoming vertex.
mat.e(2,3) = 0.0f;
glLoadMatrixf(mat.ptr());
VL_CHECK_OGL();
}
AABB rbbox = rawboundingRect( text() ); // for text alignment
VL_CHECK(rbbox.maxCorner().z() == 0)
VL_CHECK(rbbox.minCorner().z() == 0)
AABB bbox = rbbox;
int applied_margin = backgroundEnabled() || borderEnabled() ? margin() : 0;
bbox.setMaxCorner( bbox.maxCorner() + vec3(2.0f*applied_margin,2.0f*applied_margin,0) );
VL_CHECK(bbox.maxCorner().z() == 0)
VL_CHECK(bbox.minCorner().z() == 0)
// basic render states
fvec2 pen(0,0);
float texc[] = { 0,0, 0,0, 0,0, 0,0 };
VL_glActiveTexture( GL_TEXTURE0 );
glEnable(GL_TEXTURE_2D);
VL_glClientActiveTexture( GL_TEXTURE0 );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glTexCoordPointer(2, GL_FLOAT, 0, texc);
// Constant color
glColor4f( color.r(), color.g(), color.b(), color.a() );
// Constant normal
glNormal3f( 0, 0, 1 );
fvec3 vect[4];
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer(3, GL_FLOAT, 0, vect[0].ptr());
FT_Long has_kerning = FT_HAS_KERNING( font()->mFT_Face );
FT_UInt previous = 0;
// viewport alignment
fmat4 m = mMatrix;
int w = camera->viewport()->width();
int h = camera->viewport()->height();
if (w < 1) w = 1;
if (h < 1) h = 1;
if ( !(actor && actor->transform()) && mode() == Text2D )
{
if (viewportAlignment() & AlignHCenter)
{
VL_CHECK( !(viewportAlignment() & AlignRight) )
VL_CHECK( !(viewportAlignment() & AlignLeft) )
// vect[i].x() += int((viewport[2]-1.0f) / 2.0f);
m.translate( (float)int((w-1.0f) / 2.0f), 0, 0);
}
if (viewportAlignment() & AlignRight)
{
VL_CHECK( !(viewportAlignment() & AlignHCenter) )
VL_CHECK( !(viewportAlignment() & AlignLeft) )
// vect[i].x() += int(viewport[2]-1.0f);
m.translate( (float)int(w-1.0f), 0, 0);
}
if (viewportAlignment() & AlignTop)
{
VL_CHECK( !(viewportAlignment() & AlignBottom) )
VL_CHECK( !(viewportAlignment() & AlignVCenter) )
// vect[i].y() += int(viewport[3]-1.0f);
m.translate( 0, (float)int(h-1.0f), 0);
}
if (viewportAlignment() & AlignVCenter)
{
VL_CHECK( !(viewportAlignment() & AlignTop) )
VL_CHECK( !(viewportAlignment() & AlignBottom) )
// vect[i].y() += int((viewport[3]-1.0f) / 2.0f);
m.translate( 0, (float)int((h-1.0f) / 2.0f), 0);
}
}
// split the text in different lines
VL_CHECK(text().length())
std::vector< String > lines;
lines.push_back( String() );
for(int i=0; i<text().length(); ++i)
{
if (text()[i] == '\n')
{
// start new line
lines.push_back( String() );
}
else
lines.back() += text()[i];
}
for(unsigned iline=0; iline<lines.size(); iline++)
{
// strip spaces at the beginning and at the end of the line
if (textAlignment() == TextAlignJustify)
lines[iline].trim();
AABB linebox = rawboundingRect( lines[iline] );
int displace = 0;
int just_space = 0;
int just_remained_space = 0;
int space_count = 0;
for(int c=0; c<(int)lines[iline].length(); c++)
if ( lines[iline][c] == ' ' )
space_count++;
if (space_count && textAlignment() == TextAlignJustify)
{
just_space = int(rbbox.width() - linebox.width()) / space_count;
just_remained_space = int(rbbox.width() - linebox.width()) % space_count;
}
if (layout() == RightToLeftText)
{
if (textAlignment() == TextAlignRight)
displace = 0;
else
if (textAlignment() == TextAlignLeft)
displace = - int(rbbox.width() - linebox.width());
else
if (textAlignment() == TextAlignCenter)
displace = - int((rbbox.width() - linebox.width()) / 2.0f);
}
if (layout() == LeftToRightText)
{
if (textAlignment() == TextAlignRight)
displace = int(rbbox.width() - linebox.width());
else
if (textAlignment() == TextAlignLeft)
displace = 0;
else
if (textAlignment() == TextAlignCenter)
displace = + int((rbbox.width() - linebox.width()) / 2.0f);
}
// this is needed so that empty strings generate empty lines
// note that puttig '\n\n\n\n' at the beginning of a text generates
// a wrong rendering (see it with background box activated).
if (iline != 0 && !lines[iline].length())
{
pen.y() -= mFont->mHeight;
pen.x() = 0;
}
else
for(int c=0; c<(int)lines[iline].length(); c++)
{
if (c == 0 && iline != 0)
{
pen.y() -= mFont->mHeight;
pen.x() = 0;
}
const Glyph* glyph = mFont->glyph( lines[iline][c] );
if (!glyph)
continue;
if ( kerningEnabled() && has_kerning && previous && glyph->glyphIndex() )
{
FT_Vector delta; delta.y = 0;
if (layout() == LeftToRightText)
{
FT_Get_Kerning( font()->mFT_Face, previous, glyph->glyphIndex(), FT_KERNING_DEFAULT, &delta );
pen.x() += delta.x / 64.0f;
}
else
if (layout() == RightToLeftText)
{
FT_Get_Kerning( font()->mFT_Face, glyph->glyphIndex(), previous, FT_KERNING_DEFAULT, &delta );
pen.x() -= delta.x / 64.0f;
}
pen.y() += delta.y / 64.0f;
}
previous = glyph->glyphIndex();
if (glyph->textureHandle())
{
glBindTexture( GL_TEXTURE_2D, glyph->textureHandle() );
texc[0] = glyph->s0();
texc[1] = glyph->t1();
texc[2] = glyph->s1();
texc[3] = glyph->t1();
texc[4] = glyph->s1();
texc[5] = glyph->t0();
texc[6] = glyph->s0();
texc[7] = glyph->t0();
int left = layout() == RightToLeftText ? -glyph->left() : +glyph->left();
// triangle strip layout
vect[0].x() = pen.x() + glyph->width()*0 + left -1;
vect[0].y() = pen.y() + glyph->height()*0 + glyph->top() - glyph->height() -1;
vect[1].x() = pen.x() + glyph->width()*1 + left +1;
vect[1].y() = pen.y() + glyph->height()*0 + glyph->top() - glyph->height() -1;
vect[2].x() = pen.x() + glyph->width()*1 + left +1;
vect[2].y() = pen.y() + glyph->height()*1 + glyph->top() - glyph->height() +1;
vect[3].x() = pen.x() + glyph->width()*0 + left -1;
vect[3].y() = pen.y() + glyph->height()*1 + glyph->top() - glyph->height() +1;
if (layout() == RightToLeftText)
{
#if (1)
vect[0].x() -= glyph->width()-1 +2;
vect[1].x() -= glyph->width()-1 +2;
vect[2].x() -= glyph->width()-1 +2;
vect[3].x() -= glyph->width()-1 +2;
#endif
}
vect[0].y() -= mFont->mHeight;
vect[1].y() -= mFont->mHeight;
vect[2].y() -= mFont->mHeight;
vect[3].y() -= mFont->mHeight;
#if (1)
// normalize coordinate orgin to the bottom/left corner
vect[0] -= (fvec3)bbox.minCorner();
vect[1] -= (fvec3)bbox.minCorner();
vect[2] -= (fvec3)bbox.minCorner();
vect[3] -= (fvec3)bbox.minCorner();
#endif
#if (1)
vect[0].x() += applied_margin + displace;
vect[1].x() += applied_margin + displace;
vect[2].x() += applied_margin + displace;
vect[3].x() += applied_margin + displace;
vect[0].y() += applied_margin;
vect[1].y() += applied_margin;
vect[2].y() += applied_margin;
vect[3].y() += applied_margin;
#endif
// apply offset for outline rendering
vect[0].x() += offset.x();
vect[0].y() += offset.y();
vect[1].x() += offset.x();
vect[1].y() += offset.y();
vect[2].x() += offset.x();
vect[2].y() += offset.y();
vect[3].x() += offset.x();
vect[3].y() += offset.y();
// alignment
for(int i=0; i<4; ++i)
{
if (alignment() & AlignHCenter)
{
VL_CHECK( !(alignment() & AlignRight) )
VL_CHECK( !(alignment() & AlignLeft) )
vect[i].x() -= (int)(bbox.width() / 2.0f);
}
if (alignment() & AlignRight)
{
VL_CHECK( !(alignment() & AlignHCenter) )
VL_CHECK( !(alignment() & AlignLeft) )
vect[i].x() -= (int)bbox.width();
}
if (alignment() & AlignTop)
{
VL_CHECK( !(alignment() & AlignBottom) )
VL_CHECK( !(alignment() & AlignVCenter) )
vect[i].y() -= (int)bbox.height();
}
if (alignment() & AlignVCenter)
{
VL_CHECK( !(alignment() & AlignTop) )
VL_CHECK( !(alignment() & AlignBottom) )
vect[i].y() -= int(bbox.height() / 2.0);
}
}
// apply text transform
vect[0] = m * vect[0];
vect[1] = m * vect[1];
vect[2] = m * vect[2];
vect[3] = m * vect[3];
// actor's transform following in Text2D
if ( actor->transform() && mode() == Text2D )
{
vec4 v(0,0,0,1);
v = actor->transform()->worldMatrix() * v;
camera->project(v,v);
// from screen space to viewport space
v.x() -= viewport[0];
v.y() -= viewport[1];
v.x() = (float)int(v.x());
v.y() = (float)int(v.y());
vect[0].x() += (float)v.x();
vect[0].y() += (float)v.y();
vect[1].x() += (float)v.x();
vect[1].y() += (float)v.y();
vect[2].x() += (float)v.x();
vect[2].y() += (float)v.y();
vect[3].x() += (float)v.x();
vect[3].y() += (float)v.y();
// clever trick part #2
vect[0].z() =
vect[1].z() =
vect[2].z() =
vect[3].z() = float((v.z() - 0.5f) / 0.5f);
}
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); VL_CHECK_OGL();
#if (0)
glDisable(GL_TEXTURE_2D);
glColor3fv(vec3(1,0,0).ptr());
glDrawArrays(GL_LINE_LOOP, 0, 4);
glColor4fv(color.ptr());
glEnable(GL_TEXTURE_2D);
#endif
}
if (just_space && lines[iline][c] == ' ' && iline != lines.size()-1)
{
if (layout() == LeftToRightText)
{
pen.x() += just_space + (just_remained_space?1:0);
// pen.y() += glyph->advance().y();
}
else
if (layout() == RightToLeftText)
{
pen.x() -= just_space + (just_remained_space?1:0);
// pen.y() -= glyph->advance().y();
}
if(just_remained_space)
just_remained_space--;
}
if (layout() == LeftToRightText)
{
pen.x() += glyph->advance().x();
// pen.y() += glyph->advance().y();
}
else
if (layout() == RightToLeftText)
{
pen.x() -= glyph->advance().x();
// pen.y() -= glyph->advance().y();
}
}
}
glDisableClientState( GL_VERTEX_ARRAY ); VL_CHECK_OGL();
glDisableClientState( GL_TEXTURE_COORD_ARRAY ); VL_CHECK_OGL();
VL_CHECK_OGL();
if (mode() == Text2D)
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix(); VL_CHECK_OGL()
glMatrixMode(GL_PROJECTION);
glPopMatrix(); VL_CHECK_OGL()
}
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,0);
}
//-----------------------------------------------------------------------------
// returns the raw bounding box of the string, i.e. without alignment, margin and matrix transform.
AABB Text::rawboundingRect(const String& text) const
{
AABB aabb;
if(!font())
{
Log::error("Text::rawboundingRect() error: no Font assigned to the Text object.\n");
VL_TRAP()
return aabb;
}
if (!font()->mFT_Face)
{
Log::error("Text::rawboundingRect() error: invalid FT_Face: probably you tried to load an unsupported font format.\n");
VL_TRAP()
return aabb;
}
fvec2 pen(0,0);
fvec3 vect[4];
FT_Long has_kerning = FT_HAS_KERNING( font()->mFT_Face );
FT_UInt previous = 0;
for(int c=0; c<(int)text.length(); c++)
{
if (text[c] == '\n')
{
pen.y() -= mFont->mHeight ? mFont->mHeight : mFont->mSize;
pen.x() = 0;
continue;
}
const ref<Glyph>& glyph = mFont->glyph(text[c]);
// if glyph == NULL there was an error during its creation...
if (glyph.get() == NULL)
continue;
if ( kerningEnabled() && has_kerning && previous && glyph->glyphIndex())
{
FT_Vector delta; delta.y = 0;
if (layout() == LeftToRightText)
{
FT_Get_Kerning( font()->mFT_Face, previous, glyph->glyphIndex(), FT_KERNING_DEFAULT, &delta );
pen.x() += delta.x / 64.0f;
}
else
if (layout() == RightToLeftText)
{
FT_Get_Kerning( font()->mFT_Face, glyph->glyphIndex(), previous, FT_KERNING_DEFAULT, &delta );
pen.x() -= delta.x / 64.0f;
}
pen.y() += delta.y / 64.0f;
}
previous = glyph->glyphIndex();
if ( glyph->textureHandle() )
{
int left = layout() == RightToLeftText ? -glyph->left() : +glyph->left();
vect[0].x() = pen.x() + glyph->width()*0 + left -1;
vect[0].y() = pen.y() + glyph->height()*0 + glyph->top() - glyph->height() -1;
vect[1].x() = pen.x() + glyph->width()*1 + left +1;
vect[1].y() = pen.y() + glyph->height()*0 + glyph->top() - glyph->height() -1;
vect[2].x() = pen.x() + glyph->width()*1 + left +1;
vect[2].y() = pen.y() + glyph->height()*1 + glyph->top() - glyph->height() +1;
vect[3].x() = pen.x() + glyph->width()*0 + left -1;
vect[3].y() = pen.y() + glyph->height()*1 + glyph->top() - glyph->height() +1;
if (layout() == RightToLeftText)
{
#if (1)
vect[0].x() -= glyph->width()-1 +2;
vect[1].x() -= glyph->width()-1 +2;
vect[2].x() -= glyph->width()-1 +2;
vect[3].x() -= glyph->width()-1 +2;
#endif
}
vect[0].y() -= mFont->mHeight;
vect[1].y() -= mFont->mHeight;
vect[2].y() -= mFont->mHeight;
vect[3].y() -= mFont->mHeight;
#if(0)
// apply margin
//if (layout() == LeftToRightText)
//{
vect[0].x() += margin();
vect[1].x() += margin();
vect[2].x() += margin();
vect[3].x() += margin();
//}
//else
//if (layout() == RightToLeftText)
//{
// vect[0].x() -= margin();
// vect[1].x() -= margin();
// vect[2].x() -= margin();
// vect[3].x() -= margin();
//}
vect[0].y() += margin();
vect[1].y() += margin();
vect[2].y() += margin();
vect[3].y() += margin();
#endif
}
aabb.addPoint( (vec3)vect[0] );
aabb.addPoint( (vec3)vect[1] );
aabb.addPoint( (vec3)vect[2] );
aabb.addPoint( (vec3)vect[3] );
if (layout() == LeftToRightText)
pen += glyph->advance();
else
if (layout() == RightToLeftText)
pen -= glyph->advance();
}
return aabb;
}
//-----------------------------------------------------------------------------
void Text::renderBackground(const Actor* actor, const Camera* camera) const
{
int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() };
if (viewport[2] < 1) viewport[2] = 1;
if (viewport[3] < 1) viewport[3] = 1;
if (mode() == Text2D)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
VL_CHECK_OGL();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
//glLoadIdentity();
//gluOrtho2D( -0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f );
// clever trick part #1
fmat4 mat = fmat4::getOrtho(-0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f, -1, +1);
mat.e(2,2) = 1.0f;
mat.e(2,3) = 0.0f;
glLoadMatrixf(mat.ptr());
VL_CHECK_OGL();
}
// Constant color
glColor4f(mBackgroundColor.r(),mBackgroundColor.g(), mBackgroundColor.b(), mBackgroundColor.a()); VL_CHECK_OGL()
// Constant normal
glNormal3f(0, 0, 1); VL_CHECK_OGL()
vec3 a, b, c, d;
boundingRectTransformed( a, b, c, d, camera, mode() == Text2D ? actor : NULL );
fvec3 vect[] = { (fvec3)a, (fvec3)b, (fvec3)c, (fvec3)d };
glEnableClientState( GL_VERTEX_ARRAY ); VL_CHECK_OGL()
glVertexPointer(3, GL_FLOAT, 0, vect); VL_CHECK_OGL()
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); VL_CHECK_OGL()
glDisableClientState( GL_VERTEX_ARRAY ); VL_CHECK_OGL()
if (mode() == Text2D)
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix(); VL_CHECK_OGL()
glMatrixMode(GL_PROJECTION);
glPopMatrix(); VL_CHECK_OGL()
}
}
//-----------------------------------------------------------------------------
void Text::renderBorder(const Actor* actor, const Camera* camera) const
{
int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() };
if (viewport[2] < 1) viewport[2] = 1;
if (viewport[3] < 1) viewport[3] = 1;
if (mode() == Text2D)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
VL_CHECK_OGL();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
//glLoadIdentity();
//gluOrtho2D( -0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f );
// clever trick part #1
fmat4 mat = fmat4::getOrtho(-0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f, -1, +1);
mat.e(2,2) = 1.0f;
mat.e(2,3) = 0.0f;
glLoadMatrixf(mat.ptr());
VL_CHECK_OGL();
}
// Constant color
glColor4f(mBorderColor.r(), mBorderColor.g(), mBorderColor.b(), mBorderColor.a());
// Constant normal
glNormal3f( 0, 0, 1 );
vec3 a,b,c,d;
boundingRectTransformed( a, b, c, d, camera, mode() == Text2D ? actor : NULL );
fvec3 vect[] = { (fvec3)a, (fvec3)b, (fvec3)c, (fvec3)d };
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer(3, GL_FLOAT, 0, vect);
glDrawArrays(GL_LINE_LOOP, 0, 4);
glDisableClientState( GL_VERTEX_ARRAY );
if (mode() == Text2D)
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix(); VL_CHECK_OGL()
glMatrixMode(GL_PROJECTION);
glPopMatrix(); VL_CHECK_OGL()
}
}
//-----------------------------------------------------------------------------
//! Returns the plain 2D bounding box of the text, without taking into consideration
//! the Text's matrix transform and the eventual actor's transform
AABB Text::boundingRect() const
{
return boundingRect(text());
}
//-----------------------------------------------------------------------------
AABB Text::boundingRect(const String& text) const
{
int applied_margin = backgroundEnabled() || borderEnabled() ? margin() : 0;
AABB bbox = rawboundingRect( text );
bbox.setMaxCorner( bbox.maxCorner() + vec3(2.0f*applied_margin,2.0f*applied_margin,0) );
// normalize coordinate orgin to the bottom/left corner
vec3 min = bbox.minCorner() - bbox.minCorner();
vec3 max = bbox.maxCorner() - bbox.minCorner();
// normalize coordinate orgin to the bottom/left corner
// alignment
if (alignment() & AlignHCenter)
{
VL_CHECK( !(alignment() & AlignRight) )
VL_CHECK( !(alignment() & AlignLeft) )
min.x() -= int(bbox.width() / 2.0);
max.x() -= int(bbox.width() / 2.0);
}
if (alignment() & AlignRight)
{
VL_CHECK( !(alignment() & AlignHCenter) )
VL_CHECK( !(alignment() & AlignLeft) )
min.x() -= (int)bbox.width();
max.x() -= (int)bbox.width();
}
if (alignment() & AlignTop)
{
VL_CHECK( !(alignment() & AlignBottom) )
VL_CHECK( !(alignment() & AlignVCenter) )
min.y() -= (int)bbox.height();
max.y() -= (int)bbox.height();
}
if (alignment() & AlignVCenter)
{
VL_CHECK( !(alignment() & AlignTop) )
VL_CHECK( !(alignment() & AlignBottom) )
min.y() -= int(bbox.height() / 2.0);
max.y() -= int(bbox.height() / 2.0);
}
// no matrix transform applied
// ...
// no actor's transform applied
// ...
AABB aabb;
aabb.setMinCorner(min);
aabb.setMaxCorner(max);
return aabb;
}
//-----------------------------------------------------------------------------
//! Returns the fully transformed bounding box.
//! \p actor is needed only if you are using the actor's transform with the Text2D
//! to make the Text2D text follow the actor on the screen or you are using the Text3D to make the text
//! follow the actor's transform in 3D.
//!
//! The layout of the a, b, c and d points is the following:\n
//! \n
//! d---------c\n
//! | |\n
//! | |\n
//! a---------b\n
//! \n
//! Of course the above layout can be scaled, flipped, rotated and so on according to the given Text's matrix.
AABB Text::boundingRectTransformed(const Camera* camera, const Actor* actor) const
{
vec3 a, b, c, d;
return boundingRectTransformed(a, b, c, d, camera, actor);
}
//-----------------------------------------------------------------------------
AABB Text::boundingRectTransformed(vec3& a, vec3& b, vec3& c, vec3& d, const Camera* camera, const Actor* actor) const
{
AABB bbox = boundingRect();
a = bbox.minCorner();
b.x() = (float)bbox.maxCorner().x();
b.y() = (float)bbox.minCorner().y();
c = bbox.maxCorner();
d.x() = (float)bbox.minCorner().x();
d.y() = (float)bbox.maxCorner().y();
// set z to 0
a.z() = b.z() = c.z() = d.z() = 0;
// viewport alignment
fmat4 m = mMatrix;
int w = camera->viewport()->width();
int h = camera->viewport()->height();
if (w < 1) w = 1;
if (h < 1) h = 1;
if ( !(actor && actor->transform()) && mode() == Text2D )
{
if (viewportAlignment() & AlignHCenter)
{
VL_CHECK( !(viewportAlignment() & AlignRight) )
VL_CHECK( !(viewportAlignment() & AlignLeft) )
// vect[i].x() += int((viewport[2]-1.0f) / 2.0f);
m.translate( (float)int((w-1.0f) / 2.0f), 0, 0);
}
if (viewportAlignment() & AlignRight)
{
VL_CHECK( !(viewportAlignment() & AlignHCenter) )
VL_CHECK( !(viewportAlignment() & AlignLeft) )
// vect[i].x() += int(viewport[2]-1.0f);
m.translate( (float)int(w-1.0f), 0, 0);
}
if (viewportAlignment() & AlignTop)
{
VL_CHECK( !(viewportAlignment() & AlignBottom) )
VL_CHECK( !(viewportAlignment() & AlignVCenter) )
// vect[i].y() += int(viewport[3]-1.0f);
m.translate( 0, (float)int(h-1.0f), 0);
}
if (viewportAlignment() & AlignVCenter)
{
VL_CHECK( !(viewportAlignment() & AlignTop) )
VL_CHECK( !(viewportAlignment() & AlignBottom) )
// vect[i].y() += int((viewport[3]-1.0f) / 2.0f);
m.translate( 0, (float)int((h-1.0f) / 2.0f), 0);
}
}
// ??? mix fixme: remove all these castings!
// apply matrix transform
a = (mat4)m * a;
b = (mat4)m * b;
c = (mat4)m * c;
d = (mat4)m * d;
// apply actor's transform
if ( actor && actor->transform() )
{
if ( mode() == Text3D )
{
a = actor->transform()->worldMatrix() * a;
b = actor->transform()->worldMatrix() * b;
c = actor->transform()->worldMatrix() * c;
d = actor->transform()->worldMatrix() * d;
}
else
if ( mode() == Text2D )
{
// transform v
vec4 v(0,0,0,1);
v = actor->transform()->worldMatrix() * v;
// project to screen
camera->project(v,v);
// from screen space to viewport space
int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() };
v.x() -= viewport[0];
v.y() -= viewport[1];
v.x() = (float)int(v.x());
v.y() = (float)int(v.y());
a += v.xyz();
b += v.xyz();
c += v.xyz();
d += v.xyz();
// clever trick part #2
a.z() =
b.z() =
c.z() =
d.z() = (v.z() - 0.5f) / 0.5f;
}
}
bbox.setNull();
bbox.addPoint(a);
bbox.addPoint(b);
bbox.addPoint(c);
bbox.addPoint(d);
return bbox;
}
//-----------------------------------------------------------------------------
void Text::translate(float x, float y, float z)
{
mMatrix.translate(x,y,z);
}
//-----------------------------------------------------------------------------
void Text::rotate(float degrees, float x, float y, float z)
{
mMatrix.rotate(degrees,x,y,z);
}
//-----------------------------------------------------------------------------
void Text::resetMatrix()
{
mMatrix.setIdentity();
}
//-----------------------------------------------------------------------------
| 31.750489 | 136 | 0.515794 | [
"render",
"object",
"vector",
"transform",
"3d"
] |
e78f76cf12cc7f4cb5c8673c7e888e608b99f96a | 1,686 | cpp | C++ | data-tool/src/render.cpp | flamesman/TK7DATATOOL | 5b3988424e5f6e2d5dd8b138d3cd3311a5d9fc14 | [
"MIT"
] | 1 | 2021-10-17T13:54:58.000Z | 2021-10-17T13:54:58.000Z | data-tool/src/render.cpp | flamesman/TK7DATATOOL | 5b3988424e5f6e2d5dd8b138d3cd3311a5d9fc14 | [
"MIT"
] | null | null | null | data-tool/src/render.cpp | flamesman/TK7DATATOOL | 5b3988424e5f6e2d5dd8b138d3cd3311a5d9fc14 | [
"MIT"
] | null | null | null | #include "render.h"
bool bMaximizeMenu = true;
bool bPlayerData = false;
bool bEnemyData = false;
bool bAdvantage = false;
bool bIsLocked = false;
unsigned int menu_x = 0;
unsigned int menu_y = 0;
#define SIZE_CONSTANT 25
#define MENU_HEIGHT 50
#define MENU_WIDTH 200
#define N_ITEMS 4
ImVec2 vecWindowSizeDefault{MENU_WIDTH, MENU_HEIGHT + N_ITEMS * SIZE_CONSTANT};
ImVec2 vecWindowSizeMinimized{MENU_WIDTH, MENU_HEIGHT};
ImVec4 color_Hint{0x5F, 0xFF, 0xFF, 0xFF};
void Render::MainUI(void)
{
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
//////////////////////////////////////
//////////////// Begin ///////////////
//////////////////////////////////////
if (bIsLocked)
ImGui::Begin("TK7 Data-Tool (locked)");
else
ImGui::Begin("TK7 Data-Tool (unlocked)");
// Set Attributes
// Disable drag
// Disable Click
if (bMaximizeMenu)
{
// Size & Position
ImGui::SetWindowPos(ImVec2(menu_x, menu_y), 0);
ImGui::SetWindowSize(vecWindowSizeDefault, 0);
// Contents
ImGui::TextColored(color_Hint, "Press END to minimize menu");
ImGui::Checkbox("F1: Lock Menu", &bIsLocked);
ImGui::Checkbox("F2: Player Data", &bPlayerData);
ImGui::Checkbox("F3: Enemy Data", &bEnemyData);
ImGui::Checkbox("F4: Advantage", &bAdvantage);
}
else
{
// Size & Position
ImGui::SetWindowSize(vecWindowSizeMinimized, 0);
ImGui::SetWindowPos(ImVec2(menu_x, menu_y), 0);
// Contents
ImGui::TextColored(color_Hint, "Press END to maximize menu");
}
ImGui::End();
//////////////////////////////////////
//////////////// End ///////////////
//////////////////////////////////////
ImGui::Render();
}
| 24.085714 | 79 | 0.607948 | [
"render"
] |
e7902e136607ff0454bf5e0b62bb0c41a5dd3c32 | 9,881 | cc | C++ | module/imgproc/edge_util.cc | garyzhao/Sketch3DToolkit | 4f69320bcf2aac05849cc00fa50635ac4b335b6e | [
"MIT"
] | 27 | 2017-08-08T15:15:55.000Z | 2021-10-04T05:26:04.000Z | module/imgproc/edge_util.cc | garyzhao/Sketch3DToolkit | 4f69320bcf2aac05849cc00fa50635ac4b335b6e | [
"MIT"
] | 1 | 2019-07-08T06:20:31.000Z | 2019-07-10T01:36:05.000Z | module/imgproc/edge_util.cc | garyzhao/Sketch3DToolkit | 4f69320bcf2aac05849cc00fa50635ac4b335b6e | [
"MIT"
] | 9 | 2016-09-21T14:06:29.000Z | 2020-06-26T06:40:01.000Z | /*
* edge_util.cc
*/
#include "edge_util.h"
#include <iostream>
using namespace cv;
using namespace std;
/**
* Code for thinning a binary image using Zhang-Suen algorithm.
*
* Perform one thinning iteration.
* Normally you wouldn't call this function directly from your code.
*
* @param im Binary image with range = 0-1
* @param iter 0 = even, 1 = odd
*/
void thinningZhangSuenIteration(cv::Mat& im, int iter)
{
cv::Mat marker = cv::Mat::zeros(im.size(), CV_8UC1);
for (int i = 1; i < im.rows - 1; i++)
{
for (int j = 1; j < im.cols - 1; j++)
{
uchar p2 = im.at<uchar>(i - 1, j);
uchar p3 = im.at<uchar>(i - 1, j + 1);
uchar p4 = im.at<uchar>(i, j + 1);
uchar p5 = im.at<uchar>(i + 1, j + 1);
uchar p6 = im.at<uchar>(i + 1, j);
uchar p7 = im.at<uchar>(i + 1, j - 1);
uchar p8 = im.at<uchar>(i, j - 1);
uchar p9 = im.at<uchar>(i - 1, j - 1);
int A = (p2 == 0 && p3 == 1) + (p3 == 0 && p4 == 1) +
(p4 == 0 && p5 == 1) + (p5 == 0 && p6 == 1) +
(p6 == 0 && p7 == 1) + (p7 == 0 && p8 == 1) +
(p8 == 0 && p9 == 1) + (p9 == 0 && p2 == 1);
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = iter == 0 ? (p2 * p4 * p6) : (p2 * p4 * p8);
int m2 = iter == 0 ? (p4 * p6 * p8) : (p2 * p6 * p8);
if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0)
marker.at<uchar>(i, j) = 1;
}
}
im &= ~marker;
}
/**
* Function for thinning the given binary image
*
* @param im Binary image with range = 0-255
*/
void edgeThinningZhangSuen(cv::Mat& im)
{
im /= 255;
cv::Mat prev = cv::Mat::zeros(im.size(), CV_8UC1);
cv::Mat diff;
static int i = 0;
do {
thinningZhangSuenIteration(im, 0);
thinningZhangSuenIteration(im, 1);
cv::absdiff(im, prev, diff);
im.copyTo(prev);
cout << "Edge thinning ZhangSuen iter#" << ++i * 2 << endl;
} while (cv::countNonZero(diff) > 0);
im *= 255;
}
/**
* Code for thinning a binary image using Guo-Hall algorithm.
*
* Perform one thinning iteration.
* Normally you wouldn't call this function directly from your code.
*
* @param im Binary image with range = 0-1
* @param iter 0 = even, 1 = odd
*/
void thinningGuoHallIteration(cv::Mat& im, int iter)
{
cv::Mat marker = cv::Mat::zeros(im.size(), CV_8UC1);
for (int i = 1; i < im.rows - 1; i++)
{
for (int j = 1; j < im.cols - 1; j++)
{
uchar p2 = im.at<uchar>(i - 1, j);
uchar p3 = im.at<uchar>(i - 1, j + 1);
uchar p4 = im.at<uchar>(i, j + 1);
uchar p5 = im.at<uchar>(i + 1, j + 1);
uchar p6 = im.at<uchar>(i + 1, j);
uchar p7 = im.at<uchar>(i + 1, j - 1);
uchar p8 = im.at<uchar>(i, j - 1);
uchar p9 = im.at<uchar>(i - 1, j - 1);
int C = (!p2 & (p3 | p4)) + (!p4 & (p5 | p6)) +
(!p6 & (p7 | p8)) + (!p8 & (p9 | p2));
int N1 = (p9 | p2) + (p3 | p4) + (p5 | p6) + (p7 | p8);
int N2 = (p2 | p3) + (p4 | p5) + (p6 | p7) + (p8 | p9);
int N = N1 < N2 ? N1 : N2;
int m = iter == 0 ? ((p6 | p7 | !p9) & p8) : ((p2 | p3 | !p5) & p4);
if (C == 1 && (N >= 2 && N <= 3) && m == 0)
marker.at<uchar>(i, j) = 1;
}
}
im &= ~marker;
}
/**
* Function for thinning the given binary image
*
* @param im Binary image with range = 0-255
*/
void edgeThinningGuoHall(cv::Mat& im)
{
im /= 255;
cv::Mat prev = cv::Mat::zeros(im.size(), CV_8UC1);
cv::Mat diff;
static int i = 0;
do {
thinningGuoHallIteration(im, 0);
thinningGuoHallIteration(im, 1);
cv::absdiff(im, prev, diff);
im.copyTo(prev);
cout << "Edge thinning GuoHall iter#" << ++i * 2 << endl;
} while (cv::countNonZero(diff) > 0);
im *= 255;
}
Mat paddingImage(const Mat& src, int borderLen) {
Mat dst = src;
int w = src.cols, h = src.rows;
int top = 0, bottom = 0, left = 0, right = 0;
int d = w - h;
if (d > 0) {
top = d / 2;
bottom = d - top;
} if (d < 0) {
left = -d / 2;
right = -d - left;
}
top += borderLen;
bottom += borderLen;
left += borderLen;
right += borderLen;
copyMakeBorder(src, dst, top, bottom, left, right, BORDER_CONSTANT);
assert(dst.cols == dst.rows);
return dst;
}
void computeSobelOrientation(const Mat& im_gray, Mat& im_dst) {
Mat grad_x, grad_y;
Sobel(im_gray, grad_x, CV_32F, 1, 0, 3);
Sobel(im_gray, grad_y, CV_32F, 0, 1, 3);
phase(grad_x, grad_y, im_dst);
}
void clusterImageEdge(
const Mat& E, const Mat& O,
int& _segCnt, Mat& _segIds,
vector<float>& meanX, vector<float>& meanY, vector<float>& meanO,
vector<float>& _segMag,
vector<int>& _segR, vector<int>& _segC,
vector<vector<float>>& _segAff, vector<vector<int>>& _segAffIdx,
float _edgeMinMag, float _edgeMergeThr, float _clusterMinMag, float _gamma) {
int c, r, cd, rd, i, j;
int h = E.rows, w = E.cols;
_segIds.create(h, w, CV_32SC1);
_segCnt = 1;
// greedily merge connected edge pixels into clusters
for (c = 0; c < w; c++) {
for (r = 0; r < h; r++) {
if (c == 0 || r == 0 || c == w - 1 || r == h - 1 || E.at<float>(r, c) <= _edgeMinMag)
_segIds.at<int>(r, c) = -1;
else
_segIds.at<int>(r, c) = 0;
}
}
for (c = 1; c < w - 1; c++) {
for (r = 1; r < h - 1; r++) {
if (_segIds.at<int>(r, c) != 0) continue;
float sumv = 0; int c0 = c, r0 = r;
vector<float> vs;
vector<int> cs, rs;
while (sumv < _edgeMergeThr) {
_segIds.at<int>(r0, c0) = _segCnt;
float o0 = O.at<float>(r0, c0), o1, v;
bool found;
for (cd = -1; cd <= 1; cd++) {
for (rd = -1; rd <= 1; rd++) {
if (_segIds.at<int>(r0 + rd, c0 + cd) != 0) continue; found = false;
for (i = 0; i < cs.size(); i++)
if (cs[i] == c0 + cd && rs[i] == r0 + rd) { found = true; break; }
if (found) continue;
o1 = O.at<float>(r0 + rd, c0 + cd);
v = fabs(o1 - o0) / CV_PI;
if (v > .5) v = 1 - v;
vs.push_back(v); cs.push_back(c0 + cd); rs.push_back(r0 + rd);
}
}
float minv = 1000; j = 0;
for (i = 0; i < vs.size(); i++) {
if (vs[i] < minv) {
minv = vs[i]; c0 = cs[i]; r0 = rs[i]; j = i;
}
}
sumv += minv; if (minv < 1000) vs[j] = 1000;
}
_segCnt++;
}
}
// merge or remove small segments
_segMag.resize(_segCnt, 0);
for (c = 1; c < w - 1; c++) {
for (r = 1; r< h - 1; r++) {
if ((j = _segIds.at<int>(r, c)) > 0) _segMag[j] += E.at<float>(r, c);
}
}
for (c = 1; c < w - 1; c++) {
for (r = 1; r < h - 1; r++) {
if ((j = _segIds.at<int>(r, c)) > 0 && _segMag[j] <= _clusterMinMag) _segIds.at<int>(r, c) = 0;
}
}
i = 1;
while (i > 0) {
i = 0;
for (c = 1; c < w - 1; c++) {
for (r = 1; r< h - 1; r++) {
if (_segIds.at<int>(r, c) != 0) continue;
float o0 = O.at<float>(r, c), o1, v, minv = 1000;
j = 0;
for (cd = -1; cd <= 1; cd++) {
for (rd = -1; rd <= 1; rd++) {
if (_segIds.at<int>(r + rd, c + cd) <= 0) continue;
o1 = O.at<float>(r + rd, c + cd);
v = fabs(o1 - o0) / CV_PI;
if (v > .5) v = 1 - v;
if (v < minv) { minv = v; j = _segIds.at<int>(r + rd, c + cd); }
}
}
_segIds.at<int>(r, c) = j;
if (j > 0) i++;
}
}
}
// compactify representation
_segMag.assign(_segCnt, 0);
vector<int> map(_segCnt, 0); _segCnt = 1;
for (c = 1; c < w - 1; c++) for (r = 1; r < h - 1; r++) if ((j = _segIds.at<int>(r, c)) > 0) _segMag[j] += E.at<float>(r, c);
for (i = 0; i < _segMag.size(); i++) if (_segMag[i] > 0) map[i] = _segCnt++;
for (c = 1; c < w - 1; c++) for (r = 1; r < h - 1; r++) if ((j = _segIds.at<int>(r, c)) > 0) _segIds.at<int>(r, c) = map[j];
// compute positional means and recompute _segMag
_segMag.assign(_segCnt, 0);
vector<float> meanOx(_segCnt, 0), meanOy(_segCnt, 0);
meanX.assign(_segCnt, 0), meanY.assign(_segCnt, 0);
meanO.assign(_segCnt, 0);
for (c = 1; c < w - 1; c++) {
for (r = 1; r < h - 1; r++) {
j = _segIds.at<int>(r, c); if (j <= 0) continue;
float m = E.at<float>(r, c), o = O.at<float>(r, c); _segMag[j] += m;
meanOx[j] += m * cos(2 * o); meanOy[j] += m * sin(2 * o);
meanX[j] += m * c; meanY[j] += m * r;
}
}
for (i = 0; i < _segCnt; i++) {
if (_segMag[i] > 0) {
float m = _segMag[i]; meanX[i] /= m; meanY[i] /= m;
meanO[i] = atan2(meanOy[i] / m, meanOx[i] / m) / 2;
}
}
// compute segment affinities
_segAff.resize(_segCnt); _segAffIdx.resize(_segCnt);
for (i = 0; i < _segCnt; i++) _segAff[i].resize(0);
for (i = 0; i < _segCnt; i++) _segAffIdx[i].resize(0);
const int rad = 2;
for (c = rad; c < w - rad; c++) {
for (r = rad; r < h - rad; r++) {
int s0 = _segIds.at<int>(r, c);
if (s0 <= 0) continue;
for (cd = -rad; cd <= rad; cd++) {
for (rd = -rad; rd <= rad; rd++) {
int s1 = _segIds.at<int>(r + rd, c + cd);
if (s1 <= s0) continue;
bool found = false;
for (i = 0; i < _segAffIdx[s0].size(); i++) if (_segAffIdx[s0][i] == s1) { found = true; break; }
if (found) continue;
float o = atan2(meanY[s0] - meanY[s1], meanX[s0] - meanX[s1]) + CV_PI / 2;
float a = fabs(cos(meanO[s0] - o) * cos(meanO[s1] - o)); a = pow(a, _gamma);
_segAff[s0].push_back(a); _segAffIdx[s0].push_back(s1);
_segAff[s1].push_back(a); _segAffIdx[s1].push_back(s0);
}
}
}
}
// compute _segC and _segR
_segC.resize(_segCnt); _segR.resize(_segCnt);
for (c = 1; c < w - 1; c++) for (r = 1; r < h - 1; r++) if ((j = _segIds.at<int>(r, c)) > 0) { _segC[j] = c; _segR[j] = r; }
}
vector<Point2f> detectHarrisKeyPoints(const Mat& im_gray, int max_points,
double quality_level, double min_distance, int block_size, double k) {
vector<Point2f> points;
goodFeaturesToTrack(im_gray, points, max_points, quality_level, min_distance, Mat(), block_size, true, k);
return points;
} | 28.557803 | 127 | 0.509665 | [
"vector"
] |
e799cf82d911a73c9aa354a6cf0fc17c7a594c41 | 5,923 | hpp | C++ | matlab/external/src/OpenCVWrapper/sift.hpp | Childhoo/benchmark-orientation | d3a4086e8249e74da980752a7117030703e4db44 | [
"ImageMagick"
] | null | null | null | matlab/external/src/OpenCVWrapper/sift.hpp | Childhoo/benchmark-orientation | d3a4086e8249e74da980752a7117030703e4db44 | [
"ImageMagick"
] | null | null | null | matlab/external/src/OpenCVWrapper/sift.hpp | Childhoo/benchmark-orientation | d3a4086e8249e74da980752a7117030703e4db44 | [
"ImageMagick"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
// NOTICE: The original code is from the opencv library. The code has
// been modified by stripping off the unecessary components and simply
// keeping the SIFT related funcitons.
#ifndef __SIFT_HPP__
#define __SIFT_HPP__
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/opencv_modules.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <opencv2/highgui/highgui.hpp>
//Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"
extern "C" {
void recomputeOrientation(const void *indatav, const int rowcount, const int colcount,
const void *x, const void *y, const void *octave,
const void *response, const void *size, const void *angle,
const int numKey, void *out_angle, void *out_histogram = NULL, int bSingleOrientation = 0);
// indatav : data of the mat (should be gray image, uint8, ie CV_8U1)
// rowcount : number of rows
// colcount : number of cols
// x : list of pt.x in doubles
// y : list of pt.y in doubles
// octave : int array of octaves
// response : double array of response
// size : double array of sizes
// angle : double array of angles
// numKey : int number of keypoints
// out_angle : double array of the re-computed orientations
// out_histogram : double array for the histogram (NULL if not wanted)
}
void unpackOctave(const cv::KeyPoint & kpt, int &octave, int &layer, float &scale);
cv::Mat createInitialImage(const cv::Mat & img, bool doubleImageSize, float sigma);
void buildGaussianPyramid(const cv::Mat & base, std::vector < cv::Mat > &pyr, int nOctaves);
void buildDoGPyramid(const std::vector < cv::Mat > &gpyr, std::vector < cv::Mat > &dogpyr);
void funcRecomputeOrientation(const std::vector < cv::Mat > &gauss_pyr,
const std::vector < cv::Mat > &dog_pyr, std::vector < cv::KeyPoint > &keypoints,
std::vector < double* > &hists, int bSingleOrientation);
// #define DEBUG_VERBOSE
// #define NOTIFY_DIFFERENT
// /*!// SIFT implementation.// The class implements SIFT algorithm by
// D. Lowe.// */// class CV_EXPORTS_W SIFT : public Feature2D// {//
// public:// CV_WRAP explicit SIFT( int nfeatures=0, int
// nOctaveLayers=3,// double contrastThreshold=0.04, double
// edgeThreshold=10,// double sigma=1.6);// //! returns the descriptor
// size in floats (128)// CV_WRAP int descriptorSize() const;// //!
// returns the descriptor type// CV_WRAP int descriptorType() const;//
// //! finds the keypoints using SIFT algorithm// void
// operator()(InputArray img, InputArray mask,// vector<KeyPoint>&
// keypoints) const;// //! finds the keypoints and computes
// descriptors for them using SIFT algorithm.// //! Optionally it can
// compute descriptors for the user-provided keypoints// void
// operator()(InputArray img, InputArray mask,// vector<KeyPoint>&
// keypoints,// OutputArray descriptors,// bool
// useProvidedKeypoints=false) const;// AlgorithmInfo* info() const;//
// void buildGaussianPyramid( const Mat& base, vector<Mat>& pyr, int
// nOctaves ) const;// void buildDoGPyramid( const vector<Mat>& pyr,
// vector<Mat>& dogpyr ) const;// void findScaleSpaceExtrema( const
// vector<Mat>& gauss_pyr, const vector<Mat>& dog_pyr,//
// vector<KeyPoint>& keypoints ) const;// protected:// void
// detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const
// Mat& mask=Mat() ) const;// void computeImpl( const Mat& image,
// vector<KeyPoint>& keypoints, Mat& descriptors ) const;// CV_PROP_RW
// int nfeatures;// CV_PROP_RW int nOctaveLayers;// CV_PROP_RW double
// contrastThreshold;// CV_PROP_RW double edgeThreshold;// CV_PROP_RW
// double sigma;// };// typedef SIFT SiftFeatureDetector;// typedef
// SIFT SiftDescriptorExtractor;
#endif
/* End of file. */
| 49.358333 | 99 | 0.719737 | [
"vector"
] |
e7a5018b4edc13ea1af80cc3daa78fedb3b7336a | 978 | hpp | C++ | ros/src/computing/perception/detection/lib/image/dpm_ttic/include/dpm_ttic/dpm_ttic.hpp | izeki/Autoware | 21dcd18c4166331c290bd573733e0b881ca29ad7 | [
"BSD-3-Clause"
] | 64 | 2018-11-19T02:34:05.000Z | 2021-12-27T06:19:48.000Z | ros/src/computing/perception/detection/vision_detector/libs/dpm_ttic/include/libdpm_ttic/dpm_ttic.hpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 18 | 2019-04-08T16:09:37.000Z | 2019-06-05T15:24:40.000Z | ros/src/computing/perception/detection/vision_detector/libs/dpm_ttic/include/libdpm_ttic/dpm_ttic.hpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 34 | 2018-11-27T08:57:32.000Z | 2022-02-18T08:06:04.000Z | #ifndef _DPM_TTIC_H_
#define _DPM_TTIC_H_
#include <string>
#include <vector>
#include <opencv/cv.h>
extern void dpm_ttic_gpu_init_cuda(const std::string& cubin_path);
extern void dpm_ttic_gpu_cleanup_cuda();
struct DPMTTICResult {
int num;
std::vector<int> corner_points;
std::vector<int> type;
std::vector<float> score;
};
struct DPMTTICParam {
double threshold;
double overlap;
double lambda;
double num_cells;
DPMTTICParam() = default;
};
struct MODEL;
class DPMTTIC {
private:
MODEL *model_;
public:
DPMTTIC(const char *com_csv, const char *root_csv, const char *part_csv);
~DPMTTIC();
DPMTTICResult detect_objects(IplImage *image, const DPMTTICParam& param);
};
struct GPUModel;
class DPMTTICGPU {
private:
GPUModel *model_;
double RATIO;
public:
DPMTTICGPU(const char *com_csv, const char *root_csv, const char *part_csv);
~DPMTTICGPU();
DPMTTICResult detect_objects(IplImage *image, const DPMTTICParam& param);
};
#endif /* _DPM_TTIC_H_ */
| 18.45283 | 77 | 0.751534 | [
"vector",
"model"
] |
e7b0fe09dfd425ea2937cad20cb644aac89a510a | 3,638 | hpp | C++ | snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/inverse.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | null | null | null | snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/inverse.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | null | null | null | snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/inverse.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | 1 | 2021-09-15T20:27:27.000Z | 2021-09-15T20:27:27.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//---------------------------------------------------------------------------//
#ifndef BOOST_MULTIPRECISION_INVERSE_HPP
#define BOOST_MULTIPRECISION_INVERSE_HPP
#include <boost/container/vector.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <nil/crypto3/multiprecision/cpp_int.hpp>
#include <nil/crypto3/multiprecision/cpp_int/cpp_int_config.hpp>
#include <nil/crypto3/multiprecision/modular/modular_adaptor.hpp>
#include <nil/crypto3/multiprecision/modular/inverse.hpp>
namespace nil {
namespace crypto3 {
namespace multiprecision {
template<typename Backend, expression_template_option ExpressionTemplates>
constexpr number<Backend, ExpressionTemplates>
inverse_extended_euclidean_algorithm(const number<Backend, ExpressionTemplates>& n,
const number<Backend, ExpressionTemplates>& mod) {
return number<Backend, ExpressionTemplates>(
backends::eval_inverse_extended_euclidean_algorithm(n.backend(), mod.backend()));
}
template<typename Backend, expression_template_option ExpressionTemplates>
constexpr number<modular_adaptor<Backend>, ExpressionTemplates> inverse_extended_euclidean_algorithm(
const number<modular_adaptor<Backend>, ExpressionTemplates>& modular) {
number<Backend, ExpressionTemplates> new_base, res;
number<modular_adaptor<Backend>, ExpressionTemplates> res_mod;
modular.backend().mod_data().adjust_regular(new_base.backend(), modular.backend().base_data());
res = backends::eval_inverse_extended_euclidean_algorithm(
new_base.backend(), modular.backend().mod_data().get_mod().backend());
assign_components(res_mod.backend(), res.backend(), modular.backend().mod_data().get_mod().backend());
return res_mod;
}
template<typename Backend, expression_template_option ExpressionTemplates>
constexpr number<Backend, ExpressionTemplates>
monty_inverse(const number<Backend, ExpressionTemplates>& a,
const number<Backend, ExpressionTemplates>& p,
const number<Backend, ExpressionTemplates>& k) {
number<Backend, ExpressionTemplates> res;
backends::eval_monty_inverse(res.backend(), a.backend(), p.backend(), k.backend());
return res;
}
/*
template <typename IntegerType, typename = typename boost::enable_if<typename
is_trivial_cpp_int<IntegerType>::value>::type> IntegerType monty_inverse(const IntegerType& a)
{
return eval_monty_inverse(a);
}
*/
/*
template <typename IntegerType, typename = typename boost::enable_if<!typename
is_trivial_cpp_int<IntegerType>::value>::type> IntegerType monty_inverse(const IntegerType& a)
{
IntegerType res;
eval_monty_inverse(res.backend(), a.backend());
return res;
}
*/
} // namespace multiprecision
} // namespace crypto3
} // namespace nil
#endif
| 45.475 | 118 | 0.614623 | [
"vector"
] |
e7b3af4d6a23c7d670eed6ad23675b8048171689 | 14,138 | cpp | C++ | src/Features/Speedrun/Rules.cpp | soni801/SourceAutoRecord | 4bd9fde988eac425f86db050354db490dd3ed69b | [
"MIT"
] | null | null | null | src/Features/Speedrun/Rules.cpp | soni801/SourceAutoRecord | 4bd9fde988eac425f86db050354db490dd3ed69b | [
"MIT"
] | null | null | null | src/Features/Speedrun/Rules.cpp | soni801/SourceAutoRecord | 4bd9fde988eac425f86db050354db490dd3ed69b | [
"MIT"
] | null | null | null | #include "Rules.hpp"
#include "Categories.hpp"
#include "Features/EntityList.hpp"
#include "Features/OverlayRender.hpp"
#include "Features/Session.hpp"
#include "Modules/Client.hpp"
#include "Modules/Console.hpp"
#include "Modules/Engine.hpp"
#include "Modules/Scheme.hpp"
#include "Modules/Server.hpp"
#include "Modules/Surface.hpp"
#define TAU 6.28318530718
template <typename V>
static inline V *lookupMap(std::map<std::string, V> &m, std::string k) {
auto search = m.find(k);
if (search == m.end()) {
return nullptr;
}
return &search->second;
}
bool EntityInputRule::Test(std::string targetname, std::string classname, std::string inputname, std::string parameter) {
if ((this->typeMask & ENTRULE_TARGETNAME) && targetname != this->targetname) return false;
if ((this->typeMask & ENTRULE_CLASSNAME) && classname != this->classname) return false;
if (inputname != this->inputname) return false;
if ((this->typeMask & ENTRULE_PARAMETER) && parameter != this->parameter) return false;
return true;
}
std::optional<SpeedrunRule> EntityInputRule::Create(std::map<std::string, std::string> params) {
std::string *targetname = lookupMap(params, "targetname");
std::string *classname = lookupMap(params, "classname");
std::string *inputname = lookupMap(params, "inputname");
std::string *parameter = lookupMap(params, "parameter");
EntityInputRule rule = {0};
if (targetname) {
rule.targetname = *targetname;
rule.typeMask |= ENTRULE_TARGETNAME;
}
if (classname) {
rule.classname = *classname;
rule.typeMask |= ENTRULE_CLASSNAME;
}
if (!inputname) {
console->Print("inputname not specified\n");
return {};
}
rule.inputname = *inputname;
if (parameter) {
rule.parameter = *parameter;
rule.typeMask |= ENTRULE_PARAMETER;
}
return SpeedrunRule(RuleAction::START, "", rule);
}
static bool pointInBox(Vector point, Vector center, Vector size, double rotation) {
// Recenter point
point -= center;
// Rotate point
// We rotate it by -rotation to simulate rotating the collision box
// by rotation
double s = sin(-rotation);
double c = cos(-rotation);
double x = point.x;
double y = point.y;
point.x = x * c - y * s;
point.y = x * s + y * c;
// Is final point within the bounding box?
bool inX = abs(point.x) < size.x / 2;
bool inY = abs(point.y) < size.y / 2;
bool inZ = abs(point.z) < size.z / 2;
return inX && inY && inZ;
}
bool ZoneTriggerRule::Test(Vector pos) {
return pointInBox(pos, this->center, this->size, this->rotation);
}
void ZoneTriggerRule::DrawInWorld() {
OverlayRender::addBox(
this->center,
-this->size / 2,
this->size / 2,
{0, (float)(this->rotation * 360.0f / TAU), 0},
{ 140, 6, 195, 100 }
);
}
void ZoneTriggerRule::OverlayInfo(SpeedrunRule *rule) {
auto font = scheme->GetDefaultFont();
auto height = surface->GetFontHeight(font);
int n = 0;
OverlayRender::addText(this->center, 0, n++*height, "type: zone", font);
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("center: %.2f, %.2f, %.2f", this->center.x, this->center.y, this->center.z), font);
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("size: %.2f, %.2f, %.2f", this->size.x, this->size.y, this->size.z), font);
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("angle: %.2f", this->rotation * 360.0f / TAU));
if (rule->slot) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("player: %d", *rule->slot), font);
}
if (rule->cycle) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("cycle: %d,%d", rule->cycle->first, rule->cycle->second), font);
}
if (rule->onlyAfter) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("after: %s", rule->onlyAfter->c_str()), font);
}
}
std::optional<SpeedrunRule> ZoneTriggerRule::Create(std::map<std::string, std::string> params) {
std::string *posStr = lookupMap(params, "center");
std::string *sizeStr = lookupMap(params, "size");
std::string *angleStr = lookupMap(params, "angle");
if (!posStr || !sizeStr || !angleStr) {
console->Print("center, size, and angle must all be specified\n");
return {};
}
Vector pos;
Vector size;
double angle;
sscanf(posStr->c_str(), "%f,%f,%f", &pos.x, &pos.y, &pos.z);
sscanf(sizeStr->c_str(), "%f,%f,%f", &size.x, &size.y, &size.z);
sscanf(angleStr->c_str(), "%lf", &angle);
ZoneTriggerRule rule{
pos,
size,
angle / 360.0f * TAU,
};
return SpeedrunRule(RuleAction::START, "", rule);
}
bool PortalPlacementRule::Test(Vector pos, PortalColor portal) {
if (this->portal && portal != this->portal) return false;
return pointInBox(pos, this->center, this->size, this->rotation);
}
void PortalPlacementRule::DrawInWorld() {
int r = 255, g = 0, b = 0;
if (this->portal) {
switch (*this->portal) {
case PortalColor::BLUE:
r = 0;
g = 28;
b = 188;
break;
case PortalColor::ORANGE:
r = 218;
g = 64;
b = 3;
break;
}
}
OverlayRender::addBox(
this->center,
-this->size / 2,
this->size / 2,
{0, (float)(this->rotation * 360.0f / TAU), 0},
{ r, g, b, 100 }
);
}
void PortalPlacementRule::OverlayInfo(SpeedrunRule *rule) {
auto font = scheme->GetDefaultFont();
auto height = surface->GetFontHeight(font);
int n = 0;
OverlayRender::addText(this->center, 0, n++*height, "type: portal", font);
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("center: %.2f, %.2f, %.2f", this->center.x, this->center.y, this->center.z), font);
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("size: %.2f, %.2f, %.2f", this->size.x, this->size.y, this->size.z), font);
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("angle: %.2f", this->rotation * 360.0f / TAU), font);
if (rule->slot) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("player: %d", *rule->slot), font);
}
if (this->portal) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("portal: %s", *this->portal == PortalColor::BLUE ? "blue (primary)" : "orange (secondary)"), font);
}
if (rule->cycle) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("cycle: %d,%d", rule->cycle->first, rule->cycle->second), font);
}
if (rule->onlyAfter) {
OverlayRender::addText(this->center, 0, n++*height, Utils::ssprintf("after: %s", rule->onlyAfter->c_str()), font);
}
}
std::optional<SpeedrunRule> PortalPlacementRule::Create(std::map<std::string, std::string> params) {
std::string *posStr = lookupMap(params, "center");
std::string *sizeStr = lookupMap(params, "size");
std::string *angleStr = lookupMap(params, "angle");
std::string *portalStr = lookupMap(params, "portal");
if (!posStr || !sizeStr || !angleStr) {
console->Print("center, size, and angle must all be specified\n");
return {};
}
Vector pos;
Vector size;
double angle;
sscanf(posStr->c_str(), "%f,%f,%f", &pos.x, &pos.y, &pos.z);
sscanf(sizeStr->c_str(), "%f,%f,%f", &size.x, &size.y, &size.z);
sscanf(angleStr->c_str(), "%lf", &angle);
std::optional<PortalColor> portal;
if (portalStr) {
if (*portalStr == "blue") {
portal = PortalColor::BLUE;
} else if (*portalStr == "orange") {
portal = PortalColor::ORANGE;
} else {
console->Print("Invalid portal color '%s'\n", portalStr->c_str());
return {};
}
}
PortalPlacementRule rule{
pos,
size,
angle / 360.0f * TAU,
portal,
};
return SpeedrunRule(RuleAction::START, "", rule);
}
std::optional<SpeedrunRule> ChallengeFlagsRule::Create(std::map<std::string, std::string> params) {
return SpeedrunRule(RuleAction::START, "", ChallengeFlagsRule{});
}
bool ChallengeFlagsRule::Test() {
return true;
}
std::optional<SpeedrunRule> MapLoadRule::Create(std::map<std::string, std::string> params) {
return SpeedrunRule(RuleAction::START, "", MapLoadRule{});
}
bool MapLoadRule::Test() {
return true;
}
std::optional<SpeedrunRule> MapEndRule::Create(std::map<std::string, std::string> params) {
return SpeedrunRule(RuleAction::START, "", MapEndRule{});
}
bool MapEndRule::Test() {
return true;
}
std::optional<SpeedrunRule> CrouchFlyRule::Create(std::map<std::string, std::string> params) {
return SpeedrunRule(RuleAction::START, "", CrouchFlyRule{});
}
bool CrouchFlyRule::Test() {
return true;
}
bool SpeedrunRule::TestGeneral(std::optional<int> slot) {
if (this->fired && this->action != RuleAction::FORCE_START) return false;
if (this->onlyAfter) {
auto prereq = SpeedrunTimer::GetRule(*this->onlyAfter);
if (!prereq || !prereq->fired) return false;
}
if (engine->GetCurrentMapName() != this->map) return false;
if (this->slot) {
if (this->slot != slot) return false;
}
return true;
}
// Describe {{{
static const char *printRuleAction(RuleAction action) {
switch (action) {
case RuleAction::START:
return "start";
case RuleAction::FORCE_START:
return "force_start";
case RuleAction::STOP:
return "stop";
case RuleAction::SPLIT:
return "split";
case RuleAction::PAUSE:
return "pause";
case RuleAction::RESUME:
return "resume";
}
return "(unknown)";
}
std::string SpeedrunRule::Describe() {
std::string s = std::string("action=") + printRuleAction(this->action);
s += " map=" + this->map;
if (this->cycle) {
s += Utils::ssprintf(" cycle=%d,%d", this->cycle->first, this->cycle->second);
}
if (this->onlyAfter) {
s += " after=" + *this->onlyAfter;
}
if (this->slot) {
s += " player=" + std::to_string(*this->slot);
}
switch (this->rule.index()) {
case 0: { // EntityInputRule
s = std::string("[entity] ") + s;
EntityInputRule entRule = std::get<EntityInputRule>(this->rule);
if (entRule.typeMask & ENTRULE_TARGETNAME) {
s += " targetname=" + entRule.targetname;
}
if (entRule.typeMask & ENTRULE_CLASSNAME) {
s += " classname=" + entRule.classname;
}
s += " inputname=" + entRule.inputname;
if (entRule.typeMask & ENTRULE_PARAMETER) {
s += " parameter=" + entRule.parameter;
}
break;
}
case 1: { // ZoneTriggerRule
s = std::string("[zone] ") + s;
ZoneTriggerRule zoneRule = std::get<ZoneTriggerRule>(this->rule);
char buf[128];
snprintf(buf, sizeof buf, " center=%f,%f,%f", zoneRule.center.x, zoneRule.center.y, zoneRule.center.z);
s += buf;
snprintf(buf, sizeof buf, " size=%f,%f,%f", zoneRule.size.x, zoneRule.size.y, zoneRule.size.z);
s += buf;
s += std::string(" angle=") + std::to_string(zoneRule.rotation);
break;
}
case 2: { // PortalPlacementRule
s = std::string("[portal] ") + s;
PortalPlacementRule portalRule = std::get<PortalPlacementRule>(this->rule);
char buf[128];
snprintf(buf, sizeof buf, " center=%f,%f,%f", portalRule.center.x, portalRule.center.y, portalRule.center.z);
s += buf;
snprintf(buf, sizeof buf, " size=%f,%f,%f", portalRule.size.x, portalRule.size.y, portalRule.size.z);
s += buf;
s += std::string(" angle=") + std::to_string(portalRule.rotation);
if (portalRule.portal) {
s += " portal=";
s += *portalRule.portal == PortalColor::BLUE ? "blue" : "orange";
}
break;
}
case 3: { // ChallengeFlagsRule
s = std::string("[flags] ") + s;
break;
}
case 4: { // MapLoadRule
s = std::string("[load] ") + s;
break;
}
case 5: { // MapEndRule
s = std::string("[end] ") + s;
break;
}
case 6: { // CrouchFlyRule
s = std::string("[fly] ") + s;
break;
}
}
return s;
}
// }}}
void SpeedrunTimer::TickRules() {
const int MAX_SPLITSCREEN = 2; // HACK: we can't use MAX_SPLITSCREEN_PLAYERS since it's not a compile-time constant
static std::optional<Vector> portalPositions[MAX_SPLITSCREEN][2];
for (int slot = 0; slot < MAX_SPLITSCREEN; ++slot) {
{
void *clPlayer = client->GetPlayer(slot + 1);
if (clPlayer) {
SpeedrunTimer::TestZoneRules(client->GetAbsOrigin(clPlayer), slot);
}
}
void *player = server->GetPlayer(slot + 1);
if (!player) {
portalPositions[slot][0] = {};
portalPositions[slot][1] = {};
continue;
}
auto m_hActiveWeapon = *(CBaseHandle *)((uintptr_t)player + Offsets::m_hActiveWeapon);
auto portalGun = entityList->LookupEntity(m_hActiveWeapon);
if (!portalGun) {
portalPositions[slot][0] = {};
portalPositions[slot][1] = {};
continue;
}
auto m_hPrimaryPortal = *(CBaseHandle *)((uintptr_t)portalGun + Offsets::m_hPrimaryPortal);
auto m_hSecondaryPortal = *(CBaseHandle *)((uintptr_t)portalGun + Offsets::m_hSecondaryPortal);
auto bluePortal = entityList->LookupEntity(m_hPrimaryPortal);
auto orangePortal = entityList->LookupEntity(m_hSecondaryPortal);
for (int i = 0; i < 2; ++i) {
auto portal = i == 0 ? bluePortal : orangePortal;
if (!portal) {
portalPositions[slot][i] = {};
continue;
}
bool m_bActivated = *(bool *)((uintptr_t)portal + Offsets::m_bActivated);
if (!m_bActivated) {
portalPositions[slot][i] = {};
continue;
}
Vector pos = server->GetAbsOrigin(portal);
if (pos != portalPositions[slot][i]) {
// Portal position changed
SpeedrunTimer::TestPortalRules(pos, slot, i ? PortalColor::ORANGE : PortalColor::BLUE);
portalPositions[slot][i] = pos;
if (engine->demorecorder->isRecordingDemo) {
// Record in demo
char data[15];
data[0] = 0x05;
data[1] = slot;
data[2] = i;
*(float *)(data + 3) = pos.x;
*(float *)(data + 7) = pos.y;
*(float *)(data + 11) = pos.z;
engine->demorecorder->RecordData(data, sizeof data);
}
}
}
}
static bool flyStates[MAX_SPLITSCREEN];
for (int slot = 0; slot < MAX_SPLITSCREEN; ++slot) {
void *player = server->GetPlayer(slot + 1);
if (!player) {
flyStates[slot] = false;
continue;
}
auto portalLocal = server->GetPortalLocal(player);
int m_nTractorBeamCount = portalLocal.m_nTractorBeamCount;
uint32_t m_hTractorBeam = portalLocal.m_hTractorBeam;
bool fly = m_nTractorBeamCount > 0 && m_hTractorBeam == Offsets::INVALID_EHANDLE_INDEX;
if (fly && !flyStates[slot]) {
if (engine->demorecorder->isRecordingDemo) {
char data[2] = {0x07, (char)slot};
engine->demorecorder->RecordData(data, sizeof data);
}
SpeedrunTimer::TestFlyRules(slot);
}
flyStates[slot] = fly;
}
}
| 28.794297 | 169 | 0.65667 | [
"vector"
] |
e7b505a80b506727aef7427f99cdd6e06373fc3a | 1,587 | cpp | C++ | src/cmd/loginspect/dbscan.cpp | lslersch/zero | ab779235f3c3bf58d6a3aa9d2a0a5296578ee498 | [
"Spencer-94"
] | null | null | null | src/cmd/loginspect/dbscan.cpp | lslersch/zero | ab779235f3c3bf58d6a3aa9d2a0a5296578ee498 | [
"Spencer-94"
] | null | null | null | src/cmd/loginspect/dbscan.cpp | lslersch/zero | ab779235f3c3bf58d6a3aa9d2a0a5296578ee498 | [
"Spencer-94"
] | null | null | null | #include "dbscan.h"
#include "allocator.h"
void DBScan::setupOptions()
{
boost::program_options::options_description opt("DBScan Options");
opt.add_options()
("dbfile,d", po::value<string>(&dbfile)->required(),
"Path to DB file")
;
options.add(opt);
}
void DBScan::handlePage(PageID pid, const generic_page& page, vol_t* vol)
{
cout << "PID: " << pid;
if (vol->is_allocated_page(pid)) {
// CS TODO
// w_assert0(pid == page.pid);
if (pid == page.pid) {
cout << " Store: " << page.store
<< " LSN: " << page.lsn;
}
else {
cout << " MISMATCHED_PID_" << page.pid;
}
}
else {
cout << " unallocated";
}
cout << endl;
}
void DBScan::run()
{
static constexpr size_t BUFSIZE = 1024;
_options.set_string_option("sm_dbfile", dbfile);
// CS TODO: manage SM sub-components with shared_ptr
// auto vol = make_shared<vol_t>(_options);
vol_t* vol = new vol_t(_options);
smlevel_0::vol = vol;
vol->build_caches(false);
vector<generic_page, memalign_allocator<generic_page>> buffer(BUFSIZE);
PageID pid = 0;
PageID lastPID = vol->get_last_allocated_pid();
while (pid <= lastPID) {
size_t count = BUFSIZE;
if (pid + count > lastPID) { count = lastPID - pid + 1; }
W_COERCE(vol->read_many_pages(pid, &buffer[0], count));
for (size_t i = 0; i < count; i++) {
handlePage(pid++, buffer[i], vol);
}
}
vol->shutdown(false);
delete vol;
}
| 24.415385 | 75 | 0.563327 | [
"vector"
] |
e7b56e073e1ae89012942a35261f31504f827997 | 12,616 | cpp | C++ | mqtt-plugin/src/configuration/Topic.cpp | DEWETRON/OXYGEN-SDK-MQTT | 989027ab9cf636847a9984a3d5bac943b9652653 | [
"MIT"
] | null | null | null | mqtt-plugin/src/configuration/Topic.cpp | DEWETRON/OXYGEN-SDK-MQTT | 989027ab9cf636847a9984a3d5bac943b9652653 | [
"MIT"
] | null | null | null | mqtt-plugin/src/configuration/Topic.cpp | DEWETRON/OXYGEN-SDK-MQTT | 989027ab9cf636847a9984a3d5bac943b9652653 | [
"MIT"
] | null | null | null | #include "configuration/Topic.h"
#include "subscription/decoding/TextJsonDecoder.h"
#include "subscription/decoding/TextPlainDecoder.h"
#include "subscription/decoding/CborSyncDecoder.h"
#include "resampling/StreamClock.h"
//
#include "fmt/core.h"
#include "uuid.h"
using namespace plugin::mqtt;
using namespace plugin::mqtt::config;
Topic::OxygenOutputChannelMap &Topic::getOxygenOutputChannelMap()
{
return m_output_channel_map;
}
Subscription::Pointer Topic::getSubscription()
{
return m_subscription;
}
Publish::Pointer Topic::getPublisher()
{
return m_publish;
}
Operation Topic::getOperation()
{
return m_operation;
}
namespace
{
inline void traverseJsonSchemaChannels(json &j, Topic::OxygenOutputChannelMap &map, json::json_pointer &pointer, Subscription::Pointer subscription)
{
for (auto &[key, value] : j.items())
{
if (value["type"] != "object")
{
// The datatype of this channel
auto datatype = value["type"].get<Datatype>();
std::string uuid;
if (value.count("__uuid") > 0)
{
uuid = value["__uuid"].get<std::string>();
}
else
{
auto generator = uuids::uuid_system_generator{}();
uuid = uuids::to_string(generator);
value["__uuid"] = uuid;
}
// Channel Range
Range range;
if (value.contains("range"))
{
range.min = value["range"]["min"].get<double>();
range.max = value["range"]["max"].get<double>();
if (value["range"].contains("unit"))
{
range.unit = value["range"]["unit"].get<std::string>();
}
}
// Create a channel and its interpreter
Channel::Configuration configuration;
configuration.name = key;
configuration.uuid = uuid;
configuration.datatype = datatype;
configuration.range = range;
configuration.local_channel_id = INVALID_LOCAL_ID;
// Append the key to the json-path
pointer.push_back(key);
// Create Decoder
configuration.decoder = std::make_shared<TextJsonDecoder>(pointer, datatype);
// Reset JSON-Pointer
pointer.pop_back();
// Create channel and add to subscription
auto channel = std::make_shared<Channel>(std::move(configuration));
subscription->addChannel(channel);
// add to channels of current group
map.channels.push_back(channel);
}
else if (value["type"] == "object")
{
// The current key defines the new group and path in the incoming JSON payload as well as a subgroup for the oxygen-channels
auto &sub_map = map.group_channels[key];
pointer.push_back(key);
traverseJsonSchemaChannels(value["properties"], sub_map, pointer, subscription);
// Remove instances
pointer.pop_back();
}
}
}
inline void loadOutputChannelsFromJsonSchema(const std::string &path, json &j, Topic::OxygenOutputChannelMap &root, Subscription::Pointer subscription)
{
// All Schema-Channels are mapped to the path of this topic
auto &group = root.group_channels[path];
// The JSON-Pointer is relative to the schema object and will be used by the decoder
json::json_pointer pointer("");
// Walk/traverse through the schema, create all channels and add them to the subscription as well as the Oxygen Output Channel Map
traverseJsonSchemaChannels(j, group, pointer, subscription);
}
inline std::string insertOrGetUuidFromSchema(json &schema)
{
std::string uuid;
if (schema.contains("__uuid"))
{
uuid = schema.at("__uuid").get<std::string>();
}
else
{
auto generator = uuids::uuid_system_generator{}();
uuid = uuids::to_string(generator);
schema["__uuid"] = uuid;
}
return uuid;
}
}
void Topic::fromJson(json &d, Topics &topics)
{
if (!d.contains("topics"))
{
return;
}
std::map<std::string, StreamClock::Pointer> stream_clocks;
// Load Topics, filter for subscriptions
for (auto &[path, item] : d["topics"].items())
{
// MQTT Protocol Settings
int QoS = 0;
if (item.contains("QoS"))
{
QoS = item["QoS"].get<int>();
}
if (item.contains("subscribe"))
{
auto topic = std::make_shared<Topic>();
topic->m_operation = Operation::Subscribe;
// Sampling
Subscription::Sampling sampling;
sampling.mode = item["/subscribe/sampling/type"_json_pointer].get<SamplingModes>();
std::string clock_domain = "";
if (item["/subscribe/sampling"_json_pointer].contains("clock"))
{
clock_domain = item["/subscribe/sampling/clock"_json_pointer].get<std::string>();
}
if (sampling.mode == SamplingModes::Sync)
{
sampling.sample_rate = item["/subscribe/sampling/sample-rate"_json_pointer].get<double>();
}
// The underlying Subscription object
auto subscription = std::make_shared<Subscription>(std::move(sampling), path, QoS);
topic->m_subscription = subscription;
auto &payload = item["/subscribe/payload"_json_pointer];
// Payload - Different Interpreters
if (payload.contains("text/plain"))
{
auto &schema = payload["/text~1plain/schema"_json_pointer];
// The Unique-Identifier of this channel (get or create)
auto uuid = insertOrGetUuidFromSchema(schema);
// The Datatype of this channel
auto datatype = schema["type"].get<Datatype>();
// The range of the channel
Range range;
if (schema.contains("range"))
{
range.min = schema["range"]["min"].get<double>();
range.max = schema["range"]["max"].get<double>();
if (schema["range"].contains("unit"))
{
range.unit = schema["range"]["unit"].get<std::string>();
}
}
Channel::Configuration configuration;
configuration.name = path;
configuration.uuid = uuid;
configuration.datatype = datatype;
configuration.decoder = std::make_shared<TextPlainDecoder>(datatype);
configuration.range = range;
configuration.local_channel_id = INVALID_LOCAL_ID;
// Create a channel and add it to the subscription
auto channel = std::make_shared<Channel>(std::move(configuration));
subscription->addChannel(channel);
// Append Channel to the Oxygen Output Channel Map as a Root-Level Channel
topic->m_output_channel_map.channels.push_back(channel);
}
else if (payload.contains("text/json"))
{
// Load all Channels from the Configuration-Schema
auto &schema = payload["/text~1json/schema"_json_pointer];
loadOutputChannelsFromJsonSchema(path, schema, topic->m_output_channel_map, subscription);
}
else if (payload.contains("cbor/json/sync"))
{
auto &schema = payload["/cbor~1json~1sync/schema"_json_pointer];
// The Unique-Identifier of this channel (get or create)
auto uuid = insertOrGetUuidFromSchema(schema);
// The Datatype of this channel
auto datatype = schema["type"].get<Datatype>();
// Create or get the Stream-Clock for this subscription
StreamClock::Pointer clock;
if (clock_domain.empty())
{
// The stream does not share a clock domain
clock = std::make_shared<StreamClock>();
}
else
{
if (stream_clocks.count(clock_domain))
{
clock = stream_clocks[clock_domain];
}
else
{
clock = std::make_shared<StreamClock>();
stream_clocks[clock_domain] = clock;
}
}
// Channel Range
Range range;
if (schema.contains("range"))
{
range.min = schema["range"]["min"].get<double>();
range.max = schema["range"]["max"].get<double>();
if (schema["range"].contains("unit"))
{
range.unit = schema["range"]["unit"].get<std::string>();
}
}
Channel::Configuration configuration;
configuration.name = path;
configuration.uuid = uuid;
configuration.datatype = datatype;
configuration.decoder = std::make_shared<CborSyncDecoder>(datatype, sampling.sample_rate.value(), clock);
configuration.range = range;
configuration.local_channel_id = INVALID_LOCAL_ID;
// Create a channel and add it to the subscription
auto channel = std::make_shared<Channel>(std::move(configuration));
subscription->addChannel(channel);
// Cbor-Sync requires sampling to be of mode sync!
if (sampling.mode != SamplingModes::Sync)
{
throw std::invalid_argument(fmt::format("Sampling mode of {} must be of type sync when using cbor/json/sync payload decoder.", path));
}
// Append Channel to the Oxygen Output Channel Map as a Root-Level Channel
topic->m_output_channel_map.channels.push_back(channel);
}
// Finally append to topics
topics.push_back(std::move(topic));
}
else if (item.contains("publish"))
{
auto topic = std::make_shared<Topic>();
topic->m_operation = Operation::Publish;
// Sampling
Publish::Sampling sampling;
auto &s = item["/publish/sampling"_json_pointer];
sampling.mode = s["type"].get<SamplingModes>();
sampling.downsampling_factor = 1;
if (s.contains("downsampling-factor"))
{
sampling.downsampling_factor = s["downsampling-factor"].get<int>();
}
auto &p = item["/publish/payload"_json_pointer];
auto datatype = p["type"].get<Datatype>();
int packet_size = 10;
if (p.contains("samples-per-packet"))
{
packet_size = p["samples-per-packet"].get<int>();
}
// Oxygen Channel ID and UUID
std::string uuid = "";
std::string oxygen_channel = "";
if (item.contains("__channel"))
{
auto &c = item["__channel"];
if (c.contains("__uuid"))
{
uuid = c["__uuid"].get<std::string>();
}
else
{
auto generator = uuids::uuid_system_generator{}();
uuid = uuids::to_string(generator);
c["__uuid"] = uuid;
}
}
else
{
auto generator = uuids::uuid_system_generator{}();
uuid = uuids::to_string(generator);
item["__channel"]["__uuid"] = uuid;
}
auto publish = std::make_shared<Publish>(path, uuid, sampling, datatype, packet_size, QoS);
topic->m_publish = publish;
topics.push_back(std::move(topic));
}
}
}
| 35.840909 | 155 | 0.522987 | [
"object"
] |
e7b81999c7f2412e6189a6a0a1b45da9db5ed9c5 | 5,172 | cpp | C++ | src/Sources/colors.cpp | davidpypysp/gl-renderer | 0ce9b0d918775cd3fdc865cd51a51cdd3a149688 | [
"Unlicense",
"MIT"
] | null | null | null | src/Sources/colors.cpp | davidpypysp/gl-renderer | 0ce9b0d918775cd3fdc865cd51a51cdd3a149688 | [
"Unlicense",
"MIT"
] | null | null | null | src/Sources/colors.cpp | davidpypysp/gl-renderer | 0ce9b0d918775cd3fdc865cd51a51cdd3a149688 | [
"Unlicense",
"MIT"
] | null | null | null | #include "glitter.hpp"
namespace gl_examples
{
int ColorsProgram()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
GLFWwindow *window = glfwCreateWindow(mWidth, mHeight, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
// tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// configure global opengl state
// -----------------------------
glEnable(GL_DEPTH_TEST);
Shader lightingShader("1.colors.vert", "1.colors.frag");
Shader lightCubeShader("1.colors.vert", "1.light_cube.frag");
float vertices[] = {
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f};
unsigned int VBO, cubeVAO;
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(cubeVAO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
unsigned int lightCubeVAO;
glGenVertexArrays(1, &lightCubeVAO);
glBindVertexArray(lightCubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
while (!glfwWindowShouldClose(window))
{
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
processInput(window);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
lightingShader.use();
lightingShader.setVec3("objectColor", 1.0f, 0.5f, 0.31f);
lightingShader.setVec3("lightColor", 1.0f, 1.0f, 1.0f);
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)mWidth / (float)mHeight, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
lightingShader.setMat4("projection", projection);
lightingShader.setMat4("view", view);
glm::mat4 model = glm::mat4(1.0f);
lightingShader.setMat4("model", model);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
lightCubeShader.use();
lightCubeShader.setMat4("projection", projection);
lightCubeShader.setMat4("view", view);
model = glm::mat4(1.0f);
model = glm::translate(model, lightPos);
model = glm::scale(model, glm::vec3(0.2f));
lightCubeShader.setMat4("model", model);
glBindVertexArray(lightCubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightCubeVAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
} // namespace gl_examples | 31.730061 | 125 | 0.527649 | [
"model"
] |
e7bb72f60ce656c37b9c05ca2b6d9665eab52e17 | 10,786 | cpp | C++ | VoiceBridge/VoiceBridge/mitlm/Vocab.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 18 | 2018-02-15T03:14:32.000Z | 2021-07-06T08:21:13.000Z | VoiceBridge/VoiceBridge/mitlm/Vocab.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 3 | 2020-10-25T16:35:55.000Z | 2020-10-26T04:59:46.000Z | VoiceBridge/VoiceBridge/mitlm/Vocab.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 7 | 2018-09-16T20:40:17.000Z | 2021-07-06T08:21:14.000Z | /*
Copyright 2017-present Zoltan Somogyi (AI-TOOLKIT), All Rights Reserved
You may use this file only if you agree to the software license:
AI-TOOLKIT Open Source Software License - Version 2.1 - February 22, 2018:
https://ai-toolkit.blogspot.com/p/ai-toolkit-open-source-software-license.html.
Also included with the source code distribution in AI-TOOLKIT-LICENSE.txt.
Based on: see below
*/
////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, Massachusetts Institute of Technology //
// Copyright (c) 2013, Giulio Paci <giuliopaci@gmail.com> //
// All rights reserved. //
// //
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions are //
// met: //
// //
// * Redistributions of source code must retain the above copyright //
// notice, this list of conditions and the following disclaimer. //
// //
// * Redistributions in binary form must reproduce the above //
// copyright notice, this list of conditions and the following //
// disclaimer in the documentation and/or other materials provided //
// with the distribution. //
// //
// * Neither the name of the Massachusetts Institute of Technology //
// nor the names of its contributors may be used to endorse or //
// promote products derived from this software without specific //
// prior written permission. //
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR //
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT //
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, //
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT //
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, //
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY //
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //
////////////////////////////////////////////////////////////////////////////
#include <cassert>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include "util/FastIO.h"
#include "util/constants.h"
#include "Vocab.h"
namespace mitlm {
////////////////////////////////////////////////////////////////////////////////
struct VocabIndexCompare
{
const Vocab &_vocab;
VocabIndexCompare(const Vocab &vocab) : _vocab(vocab) { }
bool operator()(int i, int j) { return strcmp(_vocab[i], _vocab[j]) < 0; }
};
////////////////////////////////////////////////////////////////////////////////
const VocabIndex Vocab::Invalid = (VocabIndex)-1;
const VocabIndex Vocab::EndOfSentence = (VocabIndex)0;
////////////////////////////////////////////////////////////////////////////////
// Create Vocab with specified capacity.
Vocab::Vocab(size_t capacity) : _length(0), _fixedVocab(false),
_unkIndex(Invalid) {
Reserve(capacity);
Add("</s>");
}
void
Vocab::SetFixedVocab(bool fixedVocab) {
_fixedVocab = fixedVocab;
}
void
Vocab::UseUnknown() {
assert(!_fixedVocab); // Call UseUnknown() before SetReadOnly().
if (_unkIndex == Invalid) {
_unkIndex = Add("<unk>");
assert(_unkIndex == 1);
}
}
// Return associated index of the word, or Invalid if not found.
// In case of collision, apply quadratic probing.
VocabIndex
Vocab::Find(const char *word, size_t len) const {
if (len == 3 && strcmp(word, "<s>") == 0)
return EndOfSentence;
size_t skip = 0;
VocabIndex pos = (int)(StringHash(word, len) & _hashMask); //@+zso (int)
VocabIndex index;
while ((index = _indices[pos]) != Invalid &&
!(wordlen(index)==len && strncmp(operator[](index), word, len)==0)) {
pos = (int)((pos + ++skip) & _hashMask); //@+zso (int)
}
return (index == Invalid) ? _unkIndex : index;
}
// Add word to the vocab and return the associated index.
// If word already exists, return the existing index.
VocabIndex
Vocab::Add(const char *word, size_t len) {
if (len == 3 && strcmp(word, "<s>") == 0)
return EndOfSentence;
VocabIndex *pIndex = _FindIndex(word, len);
if (*pIndex == Invalid && !_fixedVocab) {
// Increase index table size as needed.
if (size() >= _offsetLens.length()) {
Reserve(std::max((size_t)1<<16, _offsetLens.length()*2));
pIndex = _FindIndex(word, len);
}
*pIndex = (int)_length; //@+zso (int)
_offsetLens[_length++] = OffsetLen((mitlm::uint)_buffer.size(), (mitlm::uint)len); //@+zso (mitlm::uint)
_buffer.append(word, len + 1); // Include terminating NULL.
}
return (*pIndex == Invalid) ? _unkIndex : *pIndex;
}
void
Vocab::Reserve(size_t capacity) {
// Reserve index table and value vector with specified capacity.
if (capacity != _offsetLens.length()) {
_Reindex(nextPowerOf2((unsigned long)(capacity + capacity/4))); //@+zso (unsigned long)
_offsetLens.resize(capacity);
}
}
// Sort the vocabulary and output the mapping from original to new index.
bool
Vocab::Sort(VocabVector &sortMap) {
// Sort indices using vocab index comparison function.
// - Skip the first two words: </s> (and optionally <unk>).
int numFixedWords = (_unkIndex == Invalid) ? 1 : 2;
VocabIndexCompare compare(*this);
VocabVector sortIndices = Range(size());
if (!sortIndices[Range(numFixedWords, size())].sort(compare)) {
sortMap = Range(size());
return false;
}
// Build new string buffer for the sorted words.
// Change offsets to refer to new string buffer.
// Build sort mapping that maps old to new indices.
std::string newBuffer;
OffsetLenVector newOffsetLens(size());
newBuffer.reserve(_buffer.size());
sortMap.reset(size());
for (VocabIndex i = 0; i < (VocabIndex)size(); ++i) {
const OffsetLen &offsetLen = _offsetLens[sortIndices[i]];
newOffsetLens[i] = OffsetLen((mitlm::uint)newBuffer.length(), offsetLen.Len); //@+zso (mitlm::uint)
newBuffer.append(&_buffer[offsetLen.Offset], offsetLen.Len + 1);
sortMap[sortIndices[i]] = i;
}
_buffer.swap(newBuffer);
_offsetLens.swap(newOffsetLens);
// Rebuild index map by applying sortMap.
MaskAssign(_indices != Invalid, sortMap[_indices], _indices);
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Loads vocabulary from file where each word appears on a non-# line.
void
Vocab::LoadVocab(ZFile &vocabFile) {
uint64_t v = !MITLMv1;
try {
v = ReadUInt64(vocabFile);
} catch(std::runtime_error e) {
}
if (v == MITLMv1) {
Deserialize(vocabFile);
} else {
vocabFile.ReOpen();
char line[mitlm::kMaxLineLength];
int len = 0;
while (!feof(vocabFile)) {
getline(vocabFile, line, mitlm::kMaxLineLength, &len);
if (len > 0 && line[0] != '#')
Add(line, len);
}
}
}
// Saves vocabulary to file with each word on its own line.
void
Vocab::SaveVocab(ZFile &vocabFile, bool asBinary) const {
if (asBinary) {
WriteUInt64(vocabFile, MITLMv1);
Serialize(vocabFile);
} else {
for (const OffsetLen *p = _offsetLens.begin();
p !=_offsetLens.begin() + _length; ++p) {
fputs(&_buffer[p->Offset], vocabFile);
fputc('\n', vocabFile);
}
}
}
////////////////////////////////////////////////////////////////////////////////
void
Vocab::Serialize(FILE *outFile) const {
WriteHeader(outFile, "Vocab");
WriteString(outFile, _buffer);
}
void
Vocab::Deserialize(FILE *inFile) {
VerifyHeader(inFile, "Vocab");
ReadString(inFile, _buffer);
// Count the number of words.
_length = 0;
for (size_t i = 0; i < _buffer.capacity(); ++i)
if (_buffer[i] == '\0') ++_length;
_offsetLens.resize(_length);
// Rebuild _offsetLens and _indices.
mitlm::uint offset = 0; //@+zso mitlm::uint
_length = 0;
for (mitlm::uint i = 0; i < (mitlm::uint)_buffer.capacity(); ++i) { //@+zso (mitlm::uint) x2
if (_buffer[i] == '\0') {
_offsetLens[_length++] = OffsetLen(offset, i - offset);
offset = i + 1;
}
}
_Reindex(nextPowerOf2((unsigned long)(_length + _length/4))); //@+zso (unsigned long)
}
////////////////////////////////////////////////////////////////////////////////
// Return the iterator to the position of the word.
// If word is not found, return the position to insert the word.
// In case of collision, apply quadratic probing.
// NOTE: This function assumes the index table is not full.
VocabIndex *
Vocab::_FindIndex(const char *word, size_t len) {
size_t skip = 0;
VocabIndex pos = (int)StringHash(word, len) & _hashMask; //@+zso (int)
VocabIndex index;
while ((index = _indices[pos]) != Invalid &&
!(wordlen(index)==len && strncmp(operator[](index), word, len)==0)) {
pos = (int)((pos + ++skip) & _hashMask); //@+zso (int)
}
return &_indices[pos];
}
// Resize index table to the specified capacity.
void
Vocab::_Reindex(size_t indexSize) {
assert(indexSize > size() && isPowerOf2((unsigned long)indexSize)); //@+zso (unsigned long)
_indices.reset(indexSize, Invalid);
_hashMask = indexSize - 1;
OffsetLen *p = _offsetLens.begin();
for (VocabIndex i = 0; i < (VocabIndex)size(); ++i, ++p) {
size_t skip = 0;
VocabIndex pos = (int)(StringHash(&_buffer[p->Offset], p->Len) & _hashMask); //@+zso (int)
while (_indices[pos] != Invalid)
pos = (int)((pos + ++skip) & _hashMask); //@+zso (int)
_indices[pos] = i;
}
}
}
| 38.659498 | 112 | 0.560449 | [
"vector"
] |
e7bd4dc4dfee7b5b43adc1a37756a8c252cb5ad0 | 9,647 | cpp | C++ | src/zinc/zinc.cpp | rokups/zinc | 7b0d27ee885d14b061fe94ce631552ff7295e9c3 | [
"MIT"
] | 47 | 2017-07-22T08:02:09.000Z | 2021-12-24T02:41:35.000Z | src/zinc/zinc.cpp | rokups/zinc | 7b0d27ee885d14b061fe94ce631552ff7295e9c3 | [
"MIT"
] | 1 | 2019-01-12T13:51:29.000Z | 2019-01-12T17:15:02.000Z | src/zinc/zinc.cpp | rokups/zinc | 7b0d27ee885d14b061fe94ce631552ff7295e9c3 | [
"MIT"
] | 4 | 2018-01-22T05:20:42.000Z | 2020-02-13T23:34:20.000Z | /*
* MIT License
*
* Copyright (c) 2018 Rokas Kupstys
*
* 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 <zinc/zinc.h>
#include <json.hpp>
#include <CLI11.hpp>
#if !_WIN32
# include <unistd.h>
#endif
using json = nlohmann::json;
#if _WIN32
#include <windows.h>
std::wstring to_wstring(const std::string &str)
{
std::wstring result;
auto needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), 0, 0);
if (needed > 0)
{
result.resize(needed);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), &result.front(), needed);
}
return result;
}
int truncate(const char *file_path, int64_t file_size)
{
std::wstring wfile_path = to_wstring(file_path);
std::replace(wfile_path.begin(), wfile_path.end(), '/', '\\');
HANDLE hFile = CreateFileW(wfile_path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (!hFile || hFile == INVALID_HANDLE_VALUE)
return (int)GetLastError();
LARGE_INTEGER distance;
distance.QuadPart = file_size;
if (!SetFilePointerEx(hFile, distance, 0, FILE_BEGIN))
{
CloseHandle(hFile);
return INVALID_SET_FILE_POINTER;
}
if (!SetEndOfFile(hFile))
{
auto error = GetLastError();
CloseHandle(hFile);
return (int)error;
}
CloseHandle(hFile);
return ERROR_SUCCESS;
}
#endif
void print_progressbar(int progress)
{
const auto length = 40;
auto completed = static_cast<size_t>((float)length / 100 * progress);
std::cout << "\r[" << std::string(completed, '#') << std::string(length - completed, ' ') << "]" << std::flush;
}
bool intersects(const zinc::Boundary& a, const zinc::Boundary& b)
{
auto a_end = a.start + a.length;
auto b_end = b.start + b.length;
return (a.start >= b.start && a.start < b_end) || (a_end >= b.start && a_end < b_end);
}
#if _DEBUG
/// Ensure that offsets are not overwritten before they are read.
void verify_operations_list(zinc::SyncOperationList& delta)
{
for (auto i = 0UL; i < delta.size(); i++)
{
const auto& a = delta[i]; // earlier spot, source of local data
for (auto j = i + 1; j < delta.size(); j++)
{
const auto& b = delta[j]; // later operation that might copy from earlier spot
if (b.local != nullptr)
{
assert(!intersects(*b.local, *a.remote));
}
}
}
}
#endif
int main(int argc, char* argv[])
{
std::string input_file;
std::string output_file;
std::string local_file;
std::string remote_url;
std::atomic<int64_t> bytes_done{0};
int64_t bytes_total = 0;
CLI::App parser{"File synchronization utility."};
auto* hash_command = parser.add_subcommand("hash", "Build file hashes instead of synchronizing files.");
hash_command->add_option("input", input_file, "Input file (binary).")->check(CLI::ExistingFile);
hash_command->add_option("output", output_file, "Output file (json).");
auto* sync_command = parser.add_subcommand("sync", "Synchronize local file with remote file.");
sync_command->add_option("local_file", local_file, "Local file (binary).")->check(CLI::ExistingFile);
sync_command->add_option("remote_url", remote_url, "Remote file url.")->check(CLI::ExistingFile);
CLI11_PARSE(parser, argc, argv);
if (hash_command->parsed())
{
if (output_file.empty())
output_file = input_file + ".json";
FILE* in = fopen(input_file.c_str(), "rb");
auto boundary_future = zinc::partition_file(in, 0, &bytes_done, &bytes_total);
auto percent_per_byte = 100.f / bytes_total;
while (bytes_done < bytes_total)
print_progressbar(static_cast<int>(percent_per_byte * bytes_done));
print_progressbar(100);
auto boundaries = boundary_future.get();
json doc;
for (const auto& block : boundaries)
{
doc.push_back({
{"start", block.start},
{"length", block.length},
{"fingerprint", block.fingerprint},
{"hash", block.hash},
});
}
std::ofstream out(output_file);
out << doc.dump(4) << std::endl;
fclose(in);
}
else if (sync_command->parsed())
{
zinc::BoundaryList local_hashes;
zinc::BoundaryList remote_hashes;
// Hash local file
FILE* local = fopen(local_file.c_str(), "rb");
auto boundary_future = zinc::partition_file(local, 0, &bytes_done, &bytes_total);
// Print progress
auto percent_per_byte = 100.f / bytes_total;
while (bytes_done < bytes_total)
print_progressbar(static_cast<int>(percent_per_byte * bytes_done));
print_progressbar(100);
local_hashes = boundary_future.get();
fclose(local);
// Get remote file hashes
json doc = json::parse(std::ifstream(remote_url + ".json"));
remote_hashes.reserve(doc.size());
for (auto& value : doc)
{
remote_hashes.emplace_back(zinc::Boundary{
.start = value["start"].get<int64_t>(),
.fingerprint = value["fingerprint"].get<uint64_t>(),
.hash = value["hash"].get<uint64_t>(),
.length = value["length"].get<int64_t>(),
});
}
// Calculate delta
auto delta = zinc::compare_files(local_hashes, remote_hashes);
#if _DEBUG
verify_operations_list(delta);
#endif
std::ifstream in(remote_url.c_str(), std::ios::binary | std::ios::in);
std::fstream out(local_file.c_str(), std::ios::binary | std::ios::in | std::ios::out);
if (!in.is_open() || !out.is_open())
{
std::cerr << "Failed to open file\n";
return -1;
}
std::vector<char> buffer;
#if _DEBUG
std::vector<char> buffer2;
for (const auto& op : delta)
{
if (op.local != nullptr)
{
if (buffer.size() < static_cast<size_t>(op.remote->length))
buffer.resize(op.local->length);
out.seekg(op.local->start, std::ios_base::beg);
out.read(&buffer.front(), op.local->length);
assert(zinc::detail::fnv64a((uint8_t*)&buffer[0], op.local->length) == op.remote->hash);
}
}
#endif
int64_t bytes_downloaded = 0;
int64_t bytes_copied = 0;
for (auto i = 0UL; i < delta.size(); i++)
{
auto& op = delta[i];
if (op.local == nullptr)
{
// Download operation
if (buffer.size() < static_cast<size_t>(op.remote->length))
buffer.resize(op.remote->length);
in.seekg(op.remote->start, std::ios_base::beg);
in.read(&buffer.front(), op.remote->length);
bytes_downloaded += op.remote->length;
#if _DEBUG
assert(zinc::detail::fnv64a((uint8_t*)&buffer[0], op.remote->length) == op.remote->hash);
#endif
}
else
{
// Copy operation
if (buffer.size() < static_cast<size_t>(op.remote->length))
buffer.resize(op.local->length);
out.seekg(op.local->start, std::ios_base::beg);
out.read(&buffer.front(), op.local->length);
bytes_copied += op.remote->length;
#if _DEBUG
assert(op.local->length == op.remote->length);
if (buffer2.size() < static_cast<size_t>(op.remote->length))
buffer2.resize(op.remote->length);
in.seekg(op.remote->start, std::ios_base::beg);
in.read(&buffer2.front(), op.remote->length);
assert(memcmp(&buffer[0], &buffer2[0], op.remote->length) == 0);
#endif
}
out.seekp(op.remote->start, std::ios_base::beg);
out.write(&buffer.front(), op.remote->length);
}
in.close();
out.close();
auto file_size = remote_hashes.back().start + remote_hashes.back().length;
truncate(local_file.c_str(), file_size);
std::cout << std::endl;
std::cout << "Copied bytes: " << bytes_copied << "\n";
std::cout << "Downloaded bytes: " << bytes_downloaded << "\n";
std::cout << "Download savings: " << 100 - int(100.0 / file_size * bytes_downloaded) << "%\n";
}
else
std::cout << parser.help();
return 0;
}
| 34.453571 | 115 | 0.59065 | [
"vector"
] |
e7be95848402cd663a776c8408dbffce16f569d4 | 8,284 | cpp | C++ | src/QMCDrivers/BranchIO.cpp | kryczko/qmcpack | 92f4885eac810b5aa7bece4b30a03395d74f5598 | [
"NCSA"
] | null | null | null | src/QMCDrivers/BranchIO.cpp | kryczko/qmcpack | 92f4885eac810b5aa7bece4b30a03395d74f5598 | [
"NCSA"
] | null | null | null | src/QMCDrivers/BranchIO.cpp | kryczko/qmcpack | 92f4885eac810b5aa7bece4b30a03395d74f5598 | [
"NCSA"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
// Cynthia Gu, zg1@ornl.gov, Oak Ridge National Laboratory
// Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
// Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
//
// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
#include "BranchIO.h"
#include "hdf/HDFVersion.h"
#include "Message/CommOperators.h"
#include "hdf/hdf_archive.h"
#if defined(HAVE_LIBBOOST)
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#endif
//#include <boost/archive/text_oarchive.hpp>
//
namespace qmcplusplus
{
#if defined(HAVE_LIBBOOST)
template<typename T>
inline void put_histogram(std::string name, accumulator_set<T> a, boost::property_tree::ptree& pt)
{
pt.put(name + ".value", a.properties[0]);
pt.put(name + ".value_squared", a.properties[1]);
pt.put(name + ".weight", a.properties[2]);
}
template<typename T>
inline void get_histogram(std::string name, accumulator_set<T>& a, boost::property_tree::ptree& pt)
{
a.properties[0] = pt.get<T>(name + ".value");
a.properties[1] = pt.get<T>(name + ".value_squared");
a.properties[2] = pt.get<T>(name + ".weight");
}
#endif
template<typename T>
struct h5data_proxy<accumulator_set<T>> : public h5_space_type<T, 1>
{
enum
{
CAPACITY = accumulator_set<T>::CAPACITY
};
using h5_space_type<T, 1>::dims;
using h5_space_type<T, 1>::get_address;
typedef accumulator_set<T> data_type;
data_type& ref_;
inline h5data_proxy(data_type& a) : ref_(a) { dims[0] = CAPACITY; }
inline bool read(hid_t grp, const std::string& aname, hid_t xfer_plist = H5P_DEFAULT)
{
return h5d_read(grp, aname, get_address(ref_.properties), xfer_plist);
}
inline bool write(hid_t grp, const std::string& aname, hid_t xfer_plist = H5P_DEFAULT)
{
return h5d_write(grp, aname.c_str(), this->size(), dims, get_address(ref_.properties), xfer_plist);
}
/** return the start address */
inline T* begin() { return ref_.properties; }
/** return the end address */
inline T* end() { return ref_.properties + CAPACITY; }
};
template<class SFNB>
std::vector<std::string> BranchIO<SFNB>::vParamName;
template<class SFNB>
std::vector<std::string> BranchIO<SFNB>::iParamName;
template<class SFNB>
void BranchIO<SFNB>::initAttributes()
{
if (vParamName.size())
return;
vParamName.resize(10);
vParamName[0] = "tau";
vParamName[1] = "taueff";
vParamName[2] = "etrial";
vParamName[3] = "eref";
vParamName[4] = "branchmax";
vParamName[5] = "branchcutoff";
vParamName[6] = "branchfilter";
vParamName[7] = "sigma";
vParamName[8] = "acc_energy";
vParamName[9] = "acc_samples";
iParamName.resize(7);
iParamName[0] = "warmupsteps";
iParamName[1] = "energyupdateinterval";
iParamName[2] = "counter";
iParamName[3] = "targetwalkers";
iParamName[4] = "maxwalkers";
iParamName[5] = "minwalkers";
iParamName[6] = "brnachinterval";
}
template<class SFNB>
bool BranchIO<SFNB>::write(const std::string& fname)
{
if (myComm->rank())
return true;
#if defined(HAVE_LIBBOOST)
initAttributes();
using boost::property_tree::ptree;
ptree pt;
// Put log filename in property tree
pt.put("state.branchmode", ref.BranchMode);
auto it_vparam = ref.vParam.begin();
for (auto& name : vParamName)
pt.put("state.vparam." + name, *(it_vparam++));
for (int i = 0; i < iParamName.size(); ++i)
pt.put("state.iparam." + iParamName[i], ref.iParam[i]);
put_histogram("state.energy", ref.EnergyHist, pt);
put_histogram("state.variance", ref.VarianceHist, pt);
put_histogram("state.r2accepted", ref.R2Accepted, pt);
put_histogram("state.r2proposed", ref.R2Proposed, pt);
std::string xname = fname + ".qmc.xml";
write_xml(xname, pt);
#else
//append .qmc.h5 if missing
std::string h5name(fname);
if (fname.find("qmc.h5") >= fname.size())
h5name.append(".qmc.h5");
hdf_archive dump(myComm);
hid_t fid = dump.create(h5name);
dump.push(hdf::main_state);
dump.push(hdf::qmc_status);
std::string v_header("tau:taueff:etrial:eref:branchmax:branchcutoff:branchfilter:sigma:acc_energy:acc_samples");
std::string i_header("warmupsteps:energyupdateinterval:counter:targetwalkers:maxwalkers:minwalkers:branchinterval");
dump.write(v_header, "vparam_def");
dump.write(i_header, "iparam_def");
dump.write(ref.vParam, "vparam");
dump.write(ref.iParam, "iparam");
dump.write(ref.BranchMode, "branchmode");
dump.push("histogram");
dump.write(ref.EnergyHist, "energy");
dump.write(ref.VarianceHist, "variance");
dump.write(ref.R2Accepted, "r2accepted");
dump.write(ref.R2Proposed, "r2proposed");
//PopHist is not being used in 2010-10-19
//if(ref.BranchMode[SimpleFixedNodeBranch::B_DMC])
//{
// dump.push("population");
// dump.write(ref.PopHist.myData,"histogram");
//}
#endif
return true;
}
template<class SFNB>
bool BranchIO<SFNB>::read(const std::string& fname)
{
int found_config = 0;
if (myComm->rank() == 0)
{
initAttributes();
using boost::property_tree::ptree;
ptree pt;
std::string xname = fname + ".qmc.xml";
read_xml(xname, pt);
if (!pt.empty())
{
ref.BranchMode = pt.get<BranchModeType>("state.branchmode");
get_histogram("state.energy", ref.EnergyHist, pt);
get_histogram("state.variance", ref.VarianceHist, pt);
get_histogram("state.r2accepted", ref.R2Accepted, pt);
get_histogram("state.r2proposed", ref.R2Proposed, pt);
int i = 0;
BOOST_FOREACH (const ptree::value_type& v, pt.get_child("state.iparam"))
{
ref.iParam[i++] = v.second.get_value<int>();
}
auto it_vparam = ref.vParam.begin();
BOOST_FOREACH (const ptree::value_type& v, pt.get_child("state.vparam"))
{
*(it_vparam++) = v.second.get_value<double>();
}
found_config = 1;
}
}
myComm->bcast(found_config);
if (!found_config)
return false;
bcast_state();
return true;
}
template<class SFNB>
void BranchIO<SFNB>::bcast_state()
{
int n = ref.vParam.size() + ref.iParam.size();
std::vector<RealType> pdata(n + 1 + 16, -1);
if (myComm->rank() == 0)
{
copy(ref.vParam.begin(), ref.vParam.end(), pdata.begin());
copy(ref.iParam.begin(), ref.iParam.end(), pdata.begin() + ref.vParam.size());
int offset = n;
pdata[offset++] = ref.BranchMode.to_ulong();
copy(ref.EnergyHist.properties, ref.EnergyHist.properties + 4, pdata.begin() + offset);
offset += 4;
copy(ref.VarianceHist.properties, ref.VarianceHist.properties + 4, pdata.begin() + offset);
offset += 4;
copy(ref.R2Accepted.properties, ref.R2Accepted.properties + 4, pdata.begin() + offset);
offset += 4;
copy(ref.R2Proposed.properties, ref.R2Proposed.properties + 4, pdata.begin() + offset);
}
//broadcast to the nodes : need to add a namespace mpi::
myComm->bcast(pdata);
if (myComm->rank())
{
int ii = 0;
for (auto& vpar : ref.vParam)
vpar = pdata[ii++];
for (int i = 0; i < ref.iParam.size(); ++i, ++ii)
ref.iParam[i] = static_cast<int>(pdata[ii]);
ref.BranchMode = static_cast<unsigned long>(pdata[ii]);
}
{
//update historgram
int ii = n + 1;
ref.EnergyHist.reset(pdata[ii], pdata[ii + 1], pdata[ii + 2]);
ii += 4;
ref.VarianceHist.reset(pdata[ii], pdata[ii + 1], pdata[ii + 2]);
ii += 4;
ref.R2Accepted.reset(pdata[ii], pdata[ii + 1], pdata[ii + 2]);
ii += 4;
ref.R2Proposed.reset(pdata[ii], pdata[ii + 1], pdata[ii + 2]);
}
}
template class BranchIO<SimpleFixedNodeBranch>;
template class BranchIO<SFNBranch>;
} // namespace qmcplusplus
| 31.498099 | 118 | 0.658257 | [
"vector"
] |
e7bf12f9e4f5e582a8de81b1b1e27f28bcbcb4ae | 712 | cpp | C++ | test/StatefulTest.cpp | jerryzhenleicai/Streams | e699eb1767bc96a50098a148eafe4fc09a559d51 | [
"MIT"
] | 494 | 2015-01-06T14:56:51.000Z | 2022-01-31T23:09:30.000Z | test/StatefulTest.cpp | jerryzhenleicai/Streams | e699eb1767bc96a50098a148eafe4fc09a559d51 | [
"MIT"
] | 9 | 2015-04-07T15:27:41.000Z | 2017-01-11T05:54:40.000Z | test/StatefulTest.cpp | jerryzhenleicai/Streams | e699eb1767bc96a50098a148eafe4fc09a559d51 | [
"MIT"
] | 54 | 2018-07-06T02:09:27.000Z | 2021-11-10T08:42:50.000Z | #include <Stream.h>
#include <gmock/gmock.h>
using namespace testing;
using namespace stream;
using namespace stream::op;
TEST(StatefulTest, StatePoint) {
std::vector<int> result;
MakeStream::range(0, 5)
| peek([&](int x) { result.push_back(x); })
| state_point()
| filter()
| sum();
EXPECT_THAT(result, ElementsAre(0, 1, 2, 3, 4));
}
TEST(StatefulTest, Sort) {
EXPECT_THAT(MakeStream::from({1, 0, 3, 5, 8, 7, 9}) | sort() | to_vector(),
ElementsAre(0, 1, 3, 5, 7, 8, 9));
}
TEST(StatefulTest, Distinct) {
EXPECT_THAT(MakeStream::from({1, 2, 1, 3, 3, 8, 5, 2, 8}) | distinct() | to_vector(),
ElementsAre(1, 2, 3, 5, 8));
}
| 25.428571 | 89 | 0.571629 | [
"vector"
] |
b10cb5cddc70dcffd14f3b562c22097c676231ca | 2,066 | hpp | C++ | SignalPublisher.hpp | ddribin/verilatest | f407b2f74580d7c535a1240c4ca071046c0ec67f | [
"MIT"
] | null | null | null | SignalPublisher.hpp | ddribin/verilatest | f407b2f74580d7c535a1240c4ca071046c0ec67f | [
"MIT"
] | null | null | null | SignalPublisher.hpp | ddribin/verilatest | f407b2f74580d7c535a1240c4ca071046c0ec67f | [
"MIT"
] | null | null | null | #ifndef VERILATEST_SIGNAL_PUBLISHER_H
#define VERILATEST_SIGNAL_PUBLISHER_H
#include <vector>
#include <tuple>
#include <queue>
#include <iostream>
#include <algorithm>
#include <functional>
#include "Signal.hpp"
template <typename T, class Core>
class SignalPublisher : public SignalInput<Core>
{
public:
typedef std::tuple<uint64_t, T> ChangeTuple;
typedef std::vector<ChangeTuple> ChangeVector;
SignalPublisher(T Core::* signal) : _signal(signal) { }
SignalPublisher(T Core::* signal, Component<Core>& component) :
_signal(signal)
{
component.addInput(*this);
}
virtual ~SignalPublisher() { }
void addInput(const ChangeTuple &input)
{
_changes.push(input);
}
void addInputs(const ChangeVector &inputs)
{
for (auto i : inputs) {
_changes.push(i);
}
}
std::function<void (uint64_t, Core& core)> inputHook()
{
auto hook = [=](uint64_t tickCount, Core& core) {
this->updateSignal(tickCount, core);
};
return hook;
}
private:
T Core::* _signal;
struct EventCompare
{
bool operator() (ChangeTuple left, ChangeTuple right) {
return std::get<0>(left) > std::get<0>(right);
}
};
std::priority_queue<ChangeTuple, ChangeVector, EventCompare> _changes;
void updateSignal(uint64_t time, Core& core)
{
if (_changes.size() == 0) {
return;
}
ChangeTuple t = _changes.top();
if (std::get<0>(t) == time) {
core.*_signal = std::get<1>(t);
_changes.pop();
}
}
};
template <typename T, class Core>
SignalPublisher<T, Core> makePublisher(T Core:: *signal)
{
SignalPublisher<T, Core> observer(signal);
return observer;
}
template <typename T, class Core>
SignalPublisher<T, Core> makePublisher(T Core:: *signal, const std::vector<std::tuple<uint64_t, T>> &inputs)
{
SignalPublisher<T, Core> observer(signal);
observer.addInputs(inputs);
return observer;
}
#endif
| 23.213483 | 108 | 0.619555 | [
"vector"
] |
b11968bc6678d1c7fb0da400a4d7d542e7060129 | 6,133 | hpp | C++ | include/GlobalNamespace/MulticolorAvatarPartPropertyBlockSetter_ColorData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/MulticolorAvatarPartPropertyBlockSetter_ColorData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/MulticolorAvatarPartPropertyBlockSetter_ColorData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: MulticolorAvatarPartPropertyBlockSetter
#include "GlobalNamespace/MulticolorAvatarPartPropertyBlockSetter.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*, "", "MulticolorAvatarPartPropertyBlockSetter/ColorData");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: MulticolorAvatarPartPropertyBlockSetter/ColorData
// [TokenAttribute] Offset: FFFFFFFF
class MulticolorAvatarPartPropertyBlockSetter::ColorData : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private UnityEngine.Color _defaultColor
// Size: 0x10
// Offset: 0x10
::UnityEngine::Color defaultColor;
// Field size check
static_assert(sizeof(::UnityEngine::Color) == 0x10);
// private System.Single _darkerColorMultiplier
// Size: 0x4
// Offset: 0x20
float darkerColorMultiplier;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _whiteBoost
// Size: 0x4
// Offset: 0x24
float whiteBoost;
// Field size check
static_assert(sizeof(float) == 0x4);
public:
// Get instance field reference: private UnityEngine.Color _defaultColor
::UnityEngine::Color& dyn__defaultColor();
// Get instance field reference: private System.Single _darkerColorMultiplier
float& dyn__darkerColorMultiplier();
// Get instance field reference: private System.Single _whiteBoost
float& dyn__whiteBoost();
// public UnityEngine.Color get_defaultColor()
// Offset: 0x13CB3D0
::UnityEngine::Color get_defaultColor();
// public System.Single get_darkerColorMultiplier()
// Offset: 0x13CB3DC
float get_darkerColorMultiplier();
// public System.Single get_whiteBoost()
// Offset: 0x13CB3E4
float get_whiteBoost();
// public System.Void .ctor()
// Offset: 0x13CB3EC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MulticolorAvatarPartPropertyBlockSetter::ColorData* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MulticolorAvatarPartPropertyBlockSetter::ColorData*, creationType>()));
}
}; // MulticolorAvatarPartPropertyBlockSetter/ColorData
#pragma pack(pop)
static check_size<sizeof(MulticolorAvatarPartPropertyBlockSetter::ColorData), 36 + sizeof(float)> __GlobalNamespace_MulticolorAvatarPartPropertyBlockSetter_ColorDataSizeCheck;
static_assert(sizeof(MulticolorAvatarPartPropertyBlockSetter::ColorData) == 0x28);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_defaultColor
// Il2CppName: get_defaultColor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Color (GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::*)()>(&GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_defaultColor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*), "get_defaultColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_darkerColorMultiplier
// Il2CppName: get_darkerColorMultiplier
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::*)()>(&GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_darkerColorMultiplier)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*), "get_darkerColorMultiplier", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_whiteBoost
// Il2CppName: get_whiteBoost
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::*)()>(&GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::get_whiteBoost)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData*), "get_whiteBoost", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MulticolorAvatarPartPropertyBlockSetter::ColorData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 53.798246 | 257 | 0.7564 | [
"object",
"vector"
] |
b11f0f205c4d202a92fdd4dfddd30b3c8ec27a1a | 6,569 | cpp | C++ | hphp/runtime/vm/jit/vasm-simplify-x64.cpp | simonwelsh/hhvm | d4f2f960f29fc66e0ed615b8fa7746a42aafb173 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2021-06-19T23:31:58.000Z | 2021-06-19T23:31:58.000Z | hphp/runtime/vm/jit/vasm-simplify-x64.cpp | alisha/hhvm | 523dc33b444bd5b59695eff2b64056629b0ed523 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/vasm-simplify-x64.cpp | alisha/hhvm | 523dc33b444bd5b59695eff2b64056629b0ed523 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/vasm-simplify-internal.h"
#include "hphp/runtime/vm/jit/vasm.h"
#include "hphp/runtime/vm/jit/vasm-gen.h"
#include "hphp/runtime/vm/jit/vasm-instr.h"
#include "hphp/runtime/vm/jit/vasm-unit.h"
#include "hphp/runtime/vm/jit/vasm-util.h"
#include "hphp/runtime/vm/jit/vasm-visit.h"
namespace HPHP { namespace jit { namespace x64 {
namespace {
///////////////////////////////////////////////////////////////////////////////
template <typename Inst>
bool simplify(Env&, const Inst& /*inst*/, Vlabel /*b*/, size_t /*i*/) {
return false;
}
///////////////////////////////////////////////////////////////////////////////
bool simplify(Env& env, const andqi& vandqi, Vlabel b, size_t i) {
return simplify_impl(env, b, i, [&] (Vout& v) {
if (env.use_counts[vandqi.sf] == 0 && vandqi.s0.q() == 0xff) {
// andqi{0xff, s, d} -> movzbq{s, d}
auto const tmp = v.makeReg();
v << movtqb{vandqi.s1, tmp};
v << movzbq{tmp, vandqi.d};
return 1;
}
return 0;
});
}
////////////////////////////////////////////////////////////////////////////////
/*
* Simplify equal/not-equal comparisons against zero into test instructions.
*
* Only perform this simplification if the comparison is immediately followed
* by an instruction which uses the flag result with an equals or not-equals
* condition code. Furthermore, that must be the only usage of that flag
* result.
*/
/*
* Check if an instruction uses a particular flag register and contains an equal
* or not-equal condition code.
*
* If more than one condition code or flag register is used, we don't match
* against the instruction. This is preferred over maintaining an explicit
* list of allowed instructions.
*/
struct CmpUseChecker {
explicit CmpUseChecker(VregSF target) : target{target} {}
void imm(ConditionCode cc) {
cc_result = !cc_result ? (cc == CC_E || cc == CC_NE) : false;
}
void use(VregSF sf) {
use_result = !use_result ? (sf == target) : false;
}
template<class H> void useHint(VregSF sf, H) { use(sf); }
void across(VregSF sf) { use(sf); }
template<class T> void imm(const T&) {}
template<class T> void def(T) {}
template <class T, class H>
void defHint(T /*r*/, H) {}
template<class T> void use(T) {}
template <class T, class H>
void useHint(T /*r*/, H) {}
template <class T>
void across(T /*r*/) {}
VregSF target;
folly::Optional<bool> cc_result;
folly::Optional<bool> use_result;
};
/*
* Transform a cmp* instruction into a test* instruction if all the above
* conditions are met.
*/
template <typename Out, typename In, typename Reg>
bool cmp_zero_impl(Env& env, const In& inst, Reg r, Vlabel b, size_t i) {
if (env.use_counts[inst.sf] != 1) return false;
auto const suitable_use = [&]{
auto const& code = env.unit.blocks[b].code;
if (i + 1 >= code.size()) return false;
CmpUseChecker c{inst.sf};
visitOperands(code[i+1], c);
return c.cc_result == true && c.use_result == true;
}();
if (!suitable_use) return false;
return simplify_impl(env, b, i, [&] (Vout& v) {
v << Out{r, r, inst.sf};
return 1;
});
}
/*
* Determine if either register in the instruction represents a constant zero
* and return it. Returns an invalid register if neither does.
*/
template <typename In>
auto get_cmp_zero_reg(Env& env, const In& inst) -> decltype(inst.s0) {
auto const& consts = env.unit.regToConst;
auto const s0_it = consts.find(inst.s0);
auto const s1_it = consts.find(inst.s1);
if (s0_it != consts.end() && s0_it->second.val == 0) {
return inst.s1;
} else if (s1_it != consts.end() && s1_it->second.val == 0) {
return inst.s0;
} else {
return decltype(inst.s0){Vreg::kInvalidReg};
}
}
/*
* Comparisons against another register.
*/
bool simplify(Env& env, const cmpb& inst, Vlabel b, size_t i) {
auto const reg = get_cmp_zero_reg(env, inst);
return reg.isValid() ? cmp_zero_impl<testb>(env, inst, reg, b, i) : false;
}
bool simplify(Env& env, const cmpw& inst, Vlabel b, size_t i) {
auto const reg = get_cmp_zero_reg(env, inst);
return reg.isValid() ? cmp_zero_impl<testw>(env, inst, reg, b, i) : false;
}
bool simplify(Env& env, const cmpl& inst, Vlabel b, size_t i) {
auto const reg = get_cmp_zero_reg(env, inst);
return reg.isValid() ? cmp_zero_impl<testl>(env, inst, reg, b, i) : false;
}
bool simplify(Env& env, const cmpq& inst, Vlabel b, size_t i) {
auto const reg = get_cmp_zero_reg(env, inst);
return reg.isValid() ? cmp_zero_impl<testq>(env, inst, reg, b, i) : false;
}
/*
* Comparisons against literals.
*/
bool simplify(Env& env, const cmpbi& inst, Vlabel b, size_t i) {
return (inst.s0.q() == 0)
? cmp_zero_impl<testb>(env, inst, inst.s1, b, i) : false;
}
bool simplify(Env& env, const cmpli& inst, Vlabel b, size_t i) {
return (inst.s0.q() == 0)
? cmp_zero_impl<testl>(env, inst, inst.s1, b, i) : false;
}
bool simplify(Env& env, const cmpqi& inst, Vlabel b, size_t i) {
return (inst.s0.q() == 0)
? cmp_zero_impl<testq>(env, inst, inst.s1, b, i) : false;
}
///////////////////////////////////////////////////////////////////////////////
}
bool simplify(Env& env, Vlabel b, size_t i) {
assertx(i <= env.unit.blocks[b].code.size());
auto const& inst = env.unit.blocks[b].code[i];
switch (inst.op) {
#define O(name, ...) \
case Vinstr::name: \
return simplify(env, inst.name##_, b, i); \
VASM_OPCODES
#undef O
}
not_reached();
}
///////////////////////////////////////////////////////////////////////////////
}}}
| 32.519802 | 80 | 0.572842 | [
"transform"
] |
b1220e3686dea19b586e42e8a8377bda5d8be892 | 1,989 | hpp | C++ | sample/include/utility.hpp | isabella232/ros2_openvino_toolkit | 9d48916423bb1559a792c356cdf6fdcd5ba48f85 | [
"Apache-2.0"
] | null | null | null | sample/include/utility.hpp | isabella232/ros2_openvino_toolkit | 9d48916423bb1559a792c356cdf6fdcd5ba48f85 | [
"Apache-2.0"
] | 1 | 2021-02-24T10:19:46.000Z | 2021-02-24T10:19:46.000Z | sample/include/utility.hpp | isabella232/ros2_openvino_toolkit | 9d48916423bb1559a792c356cdf6fdcd5ba48f85 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018 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.
#ifndef UTILITY_HPP_
#define UTILITY_HPP_
#include <gflags/gflags.h>
#include <string>
#include <vector>
#include <iostream>
#ifdef _WIN32
#include <os/windows/w_dirent.h>
#else
#include <dirent.h>
#endif
/// @brief message for help argument
static const char help_message[] = "Print a usage message.";
/// @brief message absolute path of parameter config file
static const char parameter_file_message[] = "Absolute path of parameter config file.";
/// \brief Define flag for showing help message <br>
DEFINE_bool(h, false, help_message);
/// @brief Absolute path to yaml-format configuration file <br>
/// It is a optional parameter
DEFINE_string(config, "", parameter_file_message);
/**
* \brief This function show a help message
*/
static void showUsageForParam(const std::string prog)
{
std::cout << std::endl;
std::cout << prog <<" [OPTION]" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << std::endl;
std::cout << " -h " << help_message << std::endl;
std::cout << " -config \"<path>\" " << parameter_file_message << std::endl;
}
static std::string getConfigPath(int argc, char * argv[])
{
for(int i = 1; i < argc - 1; i++){
std::string arg = argv[i];
if(arg == "-config" || arg == "--config"){
return argv[i+1];
}
}
showUsageForParam(argv[0]);
return "";
}
#endif // UTILITY_HPP_
| 28.414286 | 88 | 0.675214 | [
"vector"
] |
b128f3a3a4d0c72a9a19941e8808a8b490c6e3f9 | 26,171 | cpp | C++ | Source/ThirdParty/ANGLE/src/libANGLE/validationES31.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/ThirdParty/ANGLE/src/libANGLE/validationES31.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/ThirdParty/ANGLE/src/libANGLE/validationES31.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (c) 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// validationES31.cpp: Validation functions for OpenGL ES 3.1 entry point parameters
#include "libANGLE/validationES31.h"
#include "libANGLE/Context.h"
#include "libANGLE/Framebuffer.h"
#include "libANGLE/validationES.h"
#include "libANGLE/validationES3.h"
#include "libANGLE/VertexArray.h"
#include "common/utilities.h"
using namespace angle;
namespace gl
{
namespace
{
bool ValidateNamedProgramInterface(GLenum programInterface)
{
switch (programInterface)
{
case GL_UNIFORM:
case GL_UNIFORM_BLOCK:
case GL_PROGRAM_INPUT:
case GL_PROGRAM_OUTPUT:
case GL_TRANSFORM_FEEDBACK_VARYING:
case GL_BUFFER_VARIABLE:
case GL_SHADER_STORAGE_BLOCK:
return true;
default:
return false;
}
}
bool ValidateProgramResourceIndex(const Program *programObject,
GLenum programInterface,
GLuint index)
{
switch (programInterface)
{
case GL_PROGRAM_INPUT:
return (index < static_cast<GLuint>(programObject->getActiveAttributeCount()));
case GL_PROGRAM_OUTPUT:
return (index < static_cast<GLuint>(programObject->getOutputResourceCount()));
// TODO(Jie): more interfaces.
case GL_UNIFORM:
case GL_UNIFORM_BLOCK:
case GL_TRANSFORM_FEEDBACK_VARYING:
case GL_BUFFER_VARIABLE:
case GL_SHADER_STORAGE_BLOCK:
UNIMPLEMENTED();
return false;
default:
UNREACHABLE();
return false;
}
}
} // anonymous namespace
bool ValidateGetBooleani_v(Context *context, GLenum target, GLuint index, GLboolean *data)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1"));
return false;
}
if (!ValidateIndexedStateQuery(context, target, index, nullptr))
{
return false;
}
return true;
}
bool ValidateGetBooleani_vRobustANGLE(Context *context,
GLenum target,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLboolean *data)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1"));
return false;
}
if (!ValidateRobustEntryPoint(context, bufSize))
{
return false;
}
if (!ValidateIndexedStateQuery(context, target, index, length))
{
return false;
}
if (!ValidateRobustBufferSize(context, bufSize, *length))
{
return false;
}
return true;
}
bool ValidateDrawIndirectBase(Context *context, GLenum mode, const GLvoid *indirect)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1"));
return false;
}
// Here the third parameter 1 is only to pass the count validation.
if (!ValidateDrawBase(context, mode, 1))
{
return false;
}
const State &state = context->getGLState();
// An INVALID_OPERATION error is generated if zero is bound to VERTEX_ARRAY_BINDING,
// DRAW_INDIRECT_BUFFER or to any enabled vertex array.
if (!state.getVertexArrayId())
{
context->handleError(Error(GL_INVALID_OPERATION, "zero is bound to VERTEX_ARRAY_BINDING"));
return false;
}
gl::Buffer *drawIndirectBuffer = state.getDrawIndirectBuffer();
if (!drawIndirectBuffer)
{
context->handleError(Error(GL_INVALID_OPERATION, "zero is bound to DRAW_INDIRECT_BUFFER"));
return false;
}
// An INVALID_VALUE error is generated if indirect is not a multiple of the size, in basic
// machine units, of uint.
GLint64 offset = reinterpret_cast<GLint64>(indirect);
if ((static_cast<GLuint>(offset) % sizeof(GLuint)) != 0)
{
context->handleError(
Error(GL_INVALID_VALUE,
"indirect is not a multiple of the size, in basic machine units, of uint"));
return false;
}
return true;
}
bool ValidateDrawArraysIndirect(Context *context, GLenum mode, const GLvoid *indirect)
{
const State &state = context->getGLState();
gl::TransformFeedback *curTransformFeedback = state.getCurrentTransformFeedback();
if (curTransformFeedback && curTransformFeedback->isActive() &&
!curTransformFeedback->isPaused())
{
// An INVALID_OPERATION error is generated if transform feedback is active and not paused.
context->handleError(
Error(GL_INVALID_OPERATION, "transform feedback is active and not paused."));
return false;
}
if (!ValidateDrawIndirectBase(context, mode, indirect))
return false;
gl::Buffer *drawIndirectBuffer = state.getDrawIndirectBuffer();
CheckedNumeric<size_t> checkedOffset(reinterpret_cast<size_t>(indirect));
// In OpenGL ES3.1 spec, session 10.5, it defines the struct of DrawArraysIndirectCommand
// which's size is 4 * sizeof(uint).
auto checkedSum = checkedOffset + 4 * sizeof(GLuint);
if (!checkedSum.IsValid() ||
checkedSum.ValueOrDie() > static_cast<size_t>(drawIndirectBuffer->getSize()))
{
context->handleError(
Error(GL_INVALID_OPERATION,
"the command would source data beyond the end of the buffer object."));
return false;
}
return true;
}
bool ValidateDrawElementsIndirect(Context *context,
GLenum mode,
GLenum type,
const GLvoid *indirect)
{
if (!ValidateDrawElementsBase(context, type))
return false;
const State &state = context->getGLState();
const VertexArray *vao = state.getVertexArray();
gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer().get();
if (!elementArrayBuffer)
{
context->handleError(Error(GL_INVALID_OPERATION, "zero is bound to ELEMENT_ARRAY_BUFFER"));
return false;
}
if (!ValidateDrawIndirectBase(context, mode, indirect))
return false;
gl::Buffer *drawIndirectBuffer = state.getDrawIndirectBuffer();
CheckedNumeric<size_t> checkedOffset(reinterpret_cast<size_t>(indirect));
// In OpenGL ES3.1 spec, session 10.5, it defines the struct of DrawElementsIndirectCommand
// which's size is 5 * sizeof(uint).
auto checkedSum = checkedOffset + 5 * sizeof(GLuint);
if (!checkedSum.IsValid() ||
checkedSum.ValueOrDie() > static_cast<size_t>(drawIndirectBuffer->getSize()))
{
context->handleError(
Error(GL_INVALID_OPERATION,
"the command would source data beyond the end of the buffer object."));
return false;
}
return true;
}
bool ValidateGetTexLevelParameterBase(Context *context,
GLenum target,
GLint level,
GLenum pname,
GLsizei *length)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1"));
return false;
}
if (length)
{
*length = 0;
}
if (!ValidTexLevelDestinationTarget(context, target))
{
context->handleError(Error(GL_INVALID_ENUM, "Invalid texture target"));
return false;
}
if (context->getTargetTexture(IsCubeMapTextureTarget(target) ? GL_TEXTURE_CUBE_MAP : target) ==
nullptr)
{
context->handleError(Error(GL_INVALID_ENUM, "No texture bound."));
return false;
}
if (!ValidMipLevel(context, target, level))
{
context->handleError(Error(GL_INVALID_VALUE));
return false;
}
switch (pname)
{
case GL_TEXTURE_RED_TYPE:
case GL_TEXTURE_GREEN_TYPE:
case GL_TEXTURE_BLUE_TYPE:
case GL_TEXTURE_ALPHA_TYPE:
case GL_TEXTURE_DEPTH_TYPE:
break;
case GL_TEXTURE_RED_SIZE:
case GL_TEXTURE_GREEN_SIZE:
case GL_TEXTURE_BLUE_SIZE:
case GL_TEXTURE_ALPHA_SIZE:
case GL_TEXTURE_DEPTH_SIZE:
case GL_TEXTURE_STENCIL_SIZE:
case GL_TEXTURE_SHARED_SIZE:
break;
case GL_TEXTURE_INTERNAL_FORMAT:
case GL_TEXTURE_WIDTH:
case GL_TEXTURE_HEIGHT:
case GL_TEXTURE_DEPTH:
break;
case GL_TEXTURE_SAMPLES:
case GL_TEXTURE_FIXED_SAMPLE_LOCATIONS:
break;
case GL_TEXTURE_COMPRESSED:
break;
default:
context->handleError(Error(GL_INVALID_ENUM, "Unknown pname."));
return false;
}
if (length)
{
*length = 1;
}
return true;
}
bool ValidateGetTexLevelParameterfv(Context *context,
GLenum target,
GLint level,
GLenum pname,
GLfloat *params)
{
return ValidateGetTexLevelParameterBase(context, target, level, pname, nullptr);
}
bool ValidateGetTexLevelParameteriv(Context *context,
GLenum target,
GLint level,
GLenum pname,
GLint *params)
{
return ValidateGetTexLevelParameterBase(context, target, level, pname, nullptr);
}
bool ValidateTexStorage2DMultiSample(Context *context,
GLenum target,
GLsizei samples,
GLint internalFormat,
GLsizei width,
GLsizei height,
GLboolean fixedSampleLocations)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
if (target != GL_TEXTURE_2D_MULTISAMPLE)
{
context->handleError(Error(GL_INVALID_ENUM, "Target must be TEXTURE_2D_MULTISAMPLE."));
return false;
}
if (width < 1 || height < 1)
{
context->handleError(Error(GL_INVALID_VALUE, "Width and height must be positive."));
return false;
}
const Caps &caps = context->getCaps();
if (static_cast<GLuint>(width) > caps.max2DTextureSize ||
static_cast<GLuint>(height) > caps.max2DTextureSize)
{
context->handleError(
Error(GL_INVALID_VALUE,
"Width and height must be less than or equal to GL_MAX_TEXTURE_SIZE."));
return false;
}
if (samples == 0)
{
context->handleError(Error(GL_INVALID_VALUE, "Samples may not be zero."));
return false;
}
const TextureCaps &formatCaps = context->getTextureCaps().get(internalFormat);
if (!formatCaps.renderable)
{
context->handleError(
Error(GL_INVALID_ENUM,
"SizedInternalformat must be color-renderable, depth-renderable, "
"or stencil-renderable."));
return false;
}
// The ES3.1 spec(section 8.8) states that an INVALID_ENUM error is generated if internalformat
// is one of the unsized base internalformats listed in table 8.11.
const gl::InternalFormat &formatInfo = gl::GetInternalFormatInfo(internalFormat);
if (formatInfo.pixelBytes == 0)
{
context->handleError(
Error(GL_INVALID_ENUM,
"Internalformat is one of the unsupported unsized base internalformats."));
return false;
}
if (static_cast<GLuint>(samples) > formatCaps.getMaxSamples())
{
context->handleError(
Error(GL_INVALID_OPERATION,
"Samples must not be greater than maximum supported value for the format."));
return false;
}
Texture *texture = context->getTargetTexture(target);
if (!texture || texture->id() == 0)
{
context->handleError(Error(GL_INVALID_OPERATION, "Zero is bound to target."));
return false;
}
if (texture->getImmutableFormat())
{
context->handleError(
Error(GL_INVALID_OPERATION,
"The value of TEXTURE_IMMUTABLE_FORMAT for the texture "
"currently bound to target on the active texture unit is true."));
return false;
}
return true;
}
bool ValidateGetMultisamplefv(Context *context, GLenum pname, GLuint index, GLfloat *val)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
if (pname != GL_SAMPLE_POSITION)
{
context->handleError(Error(GL_INVALID_ENUM, "Pname must be SAMPLE_POSITION."));
return false;
}
GLint maxSamples = context->getCaps().maxSamples;
if (index >= static_cast<GLuint>(maxSamples))
{
context->handleError(
Error(GL_INVALID_VALUE, "Index must be less than the value of SAMPLES."));
return false;
}
return true;
}
bool ValidationFramebufferParameteri(Context *context, GLenum target, GLenum pname, GLint param)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
if (!ValidFramebufferTarget(target))
{
context->handleError(Error(GL_INVALID_ENUM, "Invalid framebuffer target."));
return false;
}
switch (pname)
{
case GL_FRAMEBUFFER_DEFAULT_WIDTH:
{
GLint maxWidth = context->getCaps().maxFramebufferWidth;
if (param < 0 || param > maxWidth)
{
context->handleError(
Error(GL_INVALID_VALUE,
"Params less than 0 or greater than GL_MAX_FRAMEBUFFER_WIDTH."));
return false;
}
break;
}
case GL_FRAMEBUFFER_DEFAULT_HEIGHT:
{
GLint maxHeight = context->getCaps().maxFramebufferHeight;
if (param < 0 || param > maxHeight)
{
context->handleError(
Error(GL_INVALID_VALUE,
"Params less than 0 or greater than GL_MAX_FRAMEBUFFER_HEIGHT."));
return false;
}
break;
}
case GL_FRAMEBUFFER_DEFAULT_SAMPLES:
{
GLint maxSamples = context->getCaps().maxFramebufferSamples;
if (param < 0 || param > maxSamples)
{
context->handleError(
Error(GL_INVALID_VALUE,
"Params less than 0 or greater than GL_MAX_FRAMEBUFFER_SAMPLES."));
return false;
}
break;
}
case GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS:
{
break;
}
default:
{
context->handleError(Error(GL_INVALID_ENUM, "Invalid pname: 0x%X", pname));
return false;
}
}
const Framebuffer *framebuffer = context->getGLState().getTargetFramebuffer(target);
ASSERT(framebuffer);
if (framebuffer->id() == 0)
{
context->handleError(
Error(GL_INVALID_OPERATION, "Default framebuffer is bound to target."));
return false;
}
return true;
}
bool ValidationGetFramebufferParameteri(Context *context,
GLenum target,
GLenum pname,
GLint *params)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
if (!ValidFramebufferTarget(target))
{
context->handleError(Error(GL_INVALID_ENUM, "Invalid framebuffer target."));
return false;
}
switch (pname)
{
case GL_FRAMEBUFFER_DEFAULT_WIDTH:
case GL_FRAMEBUFFER_DEFAULT_HEIGHT:
case GL_FRAMEBUFFER_DEFAULT_SAMPLES:
case GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS:
break;
default:
context->handleError(Error(GL_INVALID_ENUM, "Invalid pname: 0x%X", pname));
return false;
}
const Framebuffer *framebuffer = context->getGLState().getTargetFramebuffer(target);
ASSERT(framebuffer);
if (framebuffer->id() == 0)
{
context->handleError(
Error(GL_INVALID_OPERATION, "Default framebuffer is bound to target."));
return false;
}
return true;
}
bool ValidateGetProgramResourceIndex(Context *context,
GLuint program,
GLenum programInterface,
const GLchar *name)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES 3.1."));
return false;
}
Program *programObject = GetValidProgram(context, program);
if (programObject == nullptr)
{
return false;
}
if (!ValidateNamedProgramInterface(programInterface))
{
context->handleError(
Error(GL_INVALID_ENUM, "Invalid program interface: 0x%X", programInterface));
return false;
}
return true;
}
bool ValidateBindVertexBuffer(ValidationContext *context,
GLuint bindingIndex,
GLuint buffer,
GLintptr offset,
GLsizei stride)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
if (!context->isBufferGenerated(buffer))
{
context->handleError(Error(GL_INVALID_OPERATION, "Buffer is not generated."));
return false;
}
const Caps &caps = context->getCaps();
if (bindingIndex >= caps.maxVertexAttribBindings)
{
context->handleError(Error(
GL_INVALID_VALUE, "bindingindex must be smaller than MAX_VERTEX_ATTRIB_BINDINGS."));
return false;
}
if (offset < 0)
{
context->handleError(Error(GL_INVALID_VALUE, "offset cannot be negative."));
return false;
}
if (stride < 0 || stride > caps.maxVertexAttribStride)
{
context->handleError(
Error(GL_INVALID_VALUE, "stride must be between 0 and MAX_VERTEX_ATTRIB_STRIDE."));
return false;
}
// [OpenGL ES 3.1] Section 10.3.1 page 244:
// An INVALID_OPERATION error is generated if the default vertex array object is bound.
if (context->getGLState().getVertexArrayId() == 0)
{
context->handleError(Error(GL_INVALID_OPERATION, "Default vertex array buffer is bound."));
return false;
}
return true;
}
bool ValidateVertexBindingDivisor(ValidationContext *context, GLuint bindingIndex, GLuint divisor)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
const Caps &caps = context->getCaps();
if (bindingIndex >= caps.maxVertexAttribBindings)
{
context->handleError(Error(
GL_INVALID_VALUE, "bindingindex must be smaller than MAX_VERTEX_ATTRIB_BINDINGS."));
return false;
}
// [OpenGL ES 3.1] Section 10.3.1 page 243:
// An INVALID_OPERATION error is generated if the default vertex array object is bound.
if (context->getGLState().getVertexArrayId() == 0)
{
context->handleError(Error(GL_INVALID_OPERATION, "Default vertex array object is bound."));
return false;
}
return true;
}
bool ValidateVertexAttribFormat(ValidationContext *context,
GLuint attribIndex,
GLint size,
GLenum type,
GLuint relativeOffset,
GLboolean pureInteger)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
const Caps &caps = context->getCaps();
if (relativeOffset > static_cast<GLuint>(caps.maxVertexAttribRelativeOffset))
{
context->handleError(
Error(GL_INVALID_VALUE,
"relativeOffset cannot be greater than MAX_VERTEX_ATTRIB_RELATIVE_OFFSET."));
return false;
}
// [OpenGL ES 3.1] Section 10.3.1 page 243:
// An INVALID_OPERATION error is generated if the default vertex array object is bound.
if (context->getGLState().getVertexArrayId() == 0)
{
context->handleError(Error(GL_INVALID_OPERATION, "Default vertex array object is bound."));
return false;
}
return ValidateVertexFormatBase(context, attribIndex, size, type, pureInteger);
}
bool ValidateVertexAttribBinding(ValidationContext *context,
GLuint attribIndex,
GLuint bindingIndex)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
// [OpenGL ES 3.1] Section 10.3.1 page 243:
// An INVALID_OPERATION error is generated if the default vertex array object is bound.
if (context->getGLState().getVertexArrayId() == 0)
{
context->handleError(Error(GL_INVALID_OPERATION, "Default vertex array object is bound."));
return false;
}
const Caps &caps = context->getCaps();
if (attribIndex >= caps.maxVertexAttributes)
{
context->handleError(
Error(GL_INVALID_VALUE, "attribindex must be smaller than MAX_VERTEX_ATTRIBS."));
return false;
}
if (bindingIndex >= caps.maxVertexAttribBindings)
{
context->handleError(Error(GL_INVALID_VALUE,
"bindingindex must be smaller than MAX_VERTEX_ATTRIB_BINDINGS"));
return false;
}
return true;
}
bool ValidateGetProgramResourceName(Context *context,
GLuint program,
GLenum programInterface,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLchar *name)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
Program *programObject = GetValidProgram(context, program);
if (programObject == nullptr)
{
return false;
}
if (!ValidateNamedProgramInterface(programInterface))
{
context->handleError(
Error(GL_INVALID_ENUM, "Invalid program interface: 0x%X", programInterface));
return false;
}
if (!ValidateProgramResourceIndex(programObject, programInterface, index))
{
context->handleError(Error(GL_INVALID_VALUE, "Invalid index: %d", index));
return false;
}
if (bufSize < 0)
{
context->handleError(Error(GL_INVALID_VALUE, "Invalid bufSize: %d", bufSize));
return false;
}
return true;
}
bool ValidateDispatchCompute(Context *context,
GLuint numGroupsX,
GLuint numGroupsY,
GLuint numGroupsZ)
{
if (context->getClientVersion() < ES_3_1)
{
context->handleError(Error(GL_INVALID_OPERATION, "Context does not support GLES3.1."));
return false;
}
const State &state = context->getGLState();
Program *program = state.getProgram();
if (program == nullptr)
{
context->handleError(
Error(GL_INVALID_OPERATION, "No active program object for the compute shader stage."));
return false;
}
if (program->isLinked() == false || program->getAttachedComputeShader() == nullptr)
{
context->handleError(Error(
GL_INVALID_OPERATION,
"Program has not been successfully linked, or program contains no compute shaders."));
return false;
}
const Caps &caps = context->getCaps();
if (numGroupsX > caps.maxComputeWorkGroupCount[0])
{
context->handleError(
Error(GL_INVALID_VALUE,
"num_groups_x cannot be greater than MAX_COMPUTE_WORK_GROUP_COUNT[0](%u).",
caps.maxComputeWorkGroupCount[0]));
return false;
}
if (numGroupsY > caps.maxComputeWorkGroupCount[1])
{
context->handleError(
Error(GL_INVALID_VALUE,
"num_groups_y cannot be greater than MAX_COMPUTE_WORK_GROUP_COUNT[1](%u).",
caps.maxComputeWorkGroupCount[1]));
return false;
}
if (numGroupsZ > caps.maxComputeWorkGroupCount[2])
{
context->handleError(
Error(GL_INVALID_VALUE,
"num_groups_z cannot be greater than MAX_COMPUTE_WORK_GROUP_COUNT[2](%u).",
caps.maxComputeWorkGroupCount[2]));
return false;
}
return true;
}
} // namespace gl
| 31.493381 | 100 | 0.598525 | [
"object",
"transform"
] |
b12943b79b2f3a692d042899b3909f17c6328ea4 | 10,997 | cpp | C++ | Sources/UnitTests/MouCaGraphicLibraryTests/source/UT_Animation.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/UnitTests/MouCaGraphicLibraryTests/source/UT_Animation.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/UnitTests/MouCaGraphicLibraryTests/source/UT_Animation.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | #include "Dependancies.h"
#include <LibRT/include/RTAnimationBones.h>
#include <LibRT/include/RTCameraComportement.h>
#include <LibRT/include/RTGeometry.h>
#include <LibRT/include/RTImage.h>
#include <LibRT/include/RTLight.h>
#include <LibRT/include/RTScene.h>
#include <LibVulkan/interface/IRendererDeferred.h> // MEGA STUPID ---> Need to remove !!!
#include <MouCaCore/interface/ILoaderManager.h>
#include <MouCa3DVulkanEngine/include/Renderable/AnimatedGeometry.h>
#include <MouCa3DEngine/interface/IRendererManager.h>
#include <MouCa3DEngine/interface/ISceneSynchronizer.h>
#include <include/MouCa3DEngineTest.h>
namespace MouCa3DEngine
{
struct VertexComponent
{
float _vertex[3];
float _texCoord[2];
float _color[3];
float _normal[3];
float _tangent[3];
float _weight[4];
int _ID[4];
};
class AnimationTest : public MouCa3DDeferredTest
{
protected:
RT::Scene _scene; ///< Main scene.
RT::RenderDialogWPtr _window; ///< Weak link to window.
RT::AnimationImporterSPtr _animation;
std::array<RT::AnimatedGeometrySPtr, 100> _geometries;
public:
AnimationTest() = default;
~AnimationTest() override
{
_scene.release();
}
void SetUp() override
{
MouCa3DDeferredTest::SetUp();
_env3D._camera->computePerspectiveCamera(_env3D._resolution);
// Give ownership to scene
_scene.addCamera(_env3D._camera);
createRenderer();
// Build scene
makeScene(MouCaEnvironment::getInputPath());
}
void TearDown() override
{
_animation.reset();
//Release
for( auto& geometry : _geometries )
{
geometry.reset();
}
//_eventManager->release(); // NEED TO FIX event manager as a SPtr (need a weak ?).
_env3D.releaseRenderingSystem(_gameEnv);
MouCa3DDeferredTest::TearDown();
}
///------------------------------------------------------------------------
/// \brief Replace default renderer by deferred.
///
void createRenderer()
{
BT_PRE_CONDITION(!_scene.getCameras().empty());
auto renderingSystem = _env3D.setupRenderingSystem(_gameEnv, u8"Animation", MouCa3DDeferredEnvironment::getMode()).lock();
ASSERT_TRUE(renderingSystem.get() != nullptr);
// Allocate renderer
auto renderer = renderingSystem->buildRenderer(MouCa3DEngine::IRenderingSystem::Deferred, _env3D._resolution.getSize());
// Change renderer properties
auto currentRenderer = renderer.lock();
// MEGA STUPID ---> Need to remove !!!
dynamic_cast<Vulkan::IRendererDeferred*>( currentRenderer->getProperties() )->setGlobalAmbiantFactor(0.5f);
// MEGA STUPID ---> Need to remove !!!
ASSERT_NO_THROW(_env3D._eventManager->setRenderer(currentRenderer));
renderingSystem->linkRenderingSupport(renderer, MouCa3DEngine::IRenderingSystem::Plane);
}
///------------------------------------------------------------------------
/// \brief Build scene
///
void makeScene(const BT::Path& mainFolder)
{
auto& resources = _gameEnv.getCore()->getResourceManager();
auto& loader = _gameEnv.getCore()->getLoaderManager();
// Load images/mesh
auto mesh = resources.openMeshImport(mainFolder / L"mesh" / L"goblin.dae", AnimatedGeometry::getMeshAnimationDescriptor(), RT::MeshImport::SpecialExport);
auto imageColorMap = resources.openImage( mainFolder / L"textures"/ L"goblin.ktx");
_animation = resources.openAnimation( mainFolder / L"mesh" / L"goblin.dae");
MouCaCore::LoadingItems items =
{
MouCaCore::LoadingItem(mesh, MouCaCore::LoadingItem::Deferred),
MouCaCore::LoadingItem(imageColorMap, MouCaCore::LoadingItem::Deferred),
MouCaCore::LoadingItem(_animation, MouCaCore::LoadingItem::Deferred)
};
// Demand loading
ASSERT_NO_THROW(loader.loadResources(items));
// Prepare scene: Light
const std::vector<RT::LightSPtr> lights =
{
std::make_shared<RT::Light>(RT::Light::Form::Point, RT::Point3(1.0f), 15.0f * 0.25f), // White
std::make_shared<RT::Light>(RT::Light::Form::Point, RT::Point3(0.7f, 0.0f, 0.0f), 15.0f), // Red
std::make_shared<RT::Light>(RT::Light::Form::Point, RT::Point3(0.0f, 0.0f, 0.8f), 2.0f), // Blue
std::make_shared<RT::Light>(RT::Light::Form::Point, RT::Point3(1.0f, 1.0f, 0.0f), 5.0f), // Yellow
std::make_shared<RT::Light>(RT::Light::Form::Point, RT::Point3(0.0f, 1.0f, 0.2f), 5.0f), // Green
std::make_shared<RT::Light>(RT::Light::Form::Point, RT::Point3(1.0f, 0.7f, 0.3f), 25.0f) // Yellow
};
lights[0]->getOrientation().setPosition(RT::Point3(0.0f, 5.0f, 2.0f));
lights[1]->getOrientation().setPosition(RT::Point3(-2.0f, 0.0f, 0.0f));
lights[2]->getOrientation().setPosition(RT::Point3(2.0f, 1.0f, 0.0f));
lights[3]->getOrientation().setPosition(RT::Point3(0.0f, 0.9f, 0.5f));
lights[4]->getOrientation().setPosition(RT::Point3(0.0f, 0.5f, 0.0f));
lights[5]->getOrientation().setPosition(RT::Point3(0.0f, 1.0f, 0.0f));
// Add into scene
for( auto light : lights )
{
_scene.addLight(light);
}
ASSERT_NO_THROW(loader.synchronize());
BT::uint32 idGob = 0;
for( auto& geometry : _geometries )
{
const float distance = 30.0f;
RT::BoundingBox bbox;
geometry = std::make_shared<RT::AnimatedGeometry>();
geometry->getOrientation().setQuaternion(glm::rotate(glm::quat(), -BT::Maths::PI<float> * 0.5f, glm::vec3(1, 0, 0)));
geometry->getOrientation().setHomothetie(RT::Point3(0.01f, 0.01f, 0.01f));
geometry->getOrientation().setPosition(RT::Point3(( idGob % 10) * distance, 0.0f, (idGob / 10) * distance));
geometry->setLabel("GoblinAnimated "+std::to_string(idGob));
geometry->initialize(mesh, bbox);
geometry->setBones(&_animation->getAnimation()._hierarchy);
geometry->addImage(imageColorMap->getImage());
_scene.addObjectRenderable(geometry);
++idGob;
}
RT::CameraTrackBall* trackball = dynamic_cast<RT::CameraTrackBall*>( _env3D._trackball->getComportement() );
trackball->attachSupport(_geometries[55]);
}
};
// cppcheck-suppress syntaxError
TEST_F(AnimationTest, show)
{
auto renderingSystem = _env3D.getRenderingSystem().lock();
// Change camera
RT::CameraTrackBall* trackball = dynamic_cast<RT::CameraTrackBall*>( _env3D._trackball->getComportement() );
ASSERT_TRUE(trackball != nullptr);
trackball->setDepthRange(50.0f, 1000.0f);
trackball->moveTo({ 0.3f, 0.3f, 200.0f });
double animationTime = 0.0;
// Prepare data to show
for( auto& geometry : _geometries )
{
_animation->getAnimation().updateAnimation(*geometry, 0, animationTime);
}
renderingSystem->getSynchronizer(MouCa3DEngine::IRenderingSystem::Deferred).synchronizeScene(_scene, MouCa3DEngine::ISceneSynchronizer::All);
// Sync device (now data and all are ready to render)
renderingSystem->synchronizeDevice();
_env3D._eventManager->synchronizeCamera();
#ifdef VULKAN_USER
renderingSystem->enableRender();
// Build thread to update agent position
bool threadEnd = false;
auto demo = [&]()
{
try
{
const size_t frameMax = 0;
std::chrono::time_point<std::chrono::system_clock> timeStart, timeEnd;
timeStart = std::chrono::system_clock::now();
while( !threadEnd )
{
timeEnd = std::chrono::system_clock::now();
size_t elapse = std::chrono::duration_cast<std::chrono::milliseconds>( timeEnd - timeStart ).count();
if( elapse > frameMax )
{
// World to scene (build/delete missing data)
trackball->refresh();
_env3D._eventManager->synchronizeCamera();
animationTime += elapse * 0.001;
// Prepare data to show
for( auto& geometry : _geometries )
{
_animation->getAnimation().updateAnimation(*geometry, 0, animationTime);
}
renderingSystem->getSynchronizer(MouCa3DEngine::IRenderingSystem::Deferred).synchronizeScene(_scene, MouCa3DEngine::ISceneSynchronizer::All);
std::swap(timeStart, timeEnd);
}
else // Sleep if too quick
std::this_thread::sleep_for(std::chrono::milliseconds(frameMax - elapse));
}
}
catch( const BT::Exception& e )
{
std::cout << e.read(0).getLibraryLabel() << u8" " << e.read(0).getErrorLabel() << std::endl;
}
catch( ... )
{
std::cout << u8"Unknown error caught !" << std::endl;
}
};
std::thread animation(demo);
// Launch event loop
_gameEnv.get3DEngine().loopEvent();
// Finish animation
threadEnd = true;
animation.join();
// Stop rendering
renderingSystem->disableRender();
#else
takeScreenshot(BT::Path(u8"animation_0s.png"));
// Change Time: +2s
// Prepare data to show
for( auto& geometry : _geometries )
{
_animation->getAnimation().updateAnimation(*geometry, 0, 2.0);
}
renderingSystem->getSynchronizer(IRenderingSystem::Deferred).synchronizeScene(_scene, ISceneSynchronizer::All);
takeScreenshot(BT::Path(u8"animation_2s.png"));
#endif
}
TEST_F(AnimationTest, PERFORMANCE_animation_2000)
{
auto renderingSystem = _env3D.getRenderingSystem().lock();
// Compute many frames: 20
for( double animationTime = 0.0; animationTime < 2.0; animationTime += 0.1 )
{
// For all characters: 100
for( auto& geometry : _geometries )
{
_animation->getAnimation().updateAnimation(*geometry, 0, animationTime);
}
// Sync GPU
renderingSystem->getSynchronizer(IRenderingSystem::Deferred).synchronizeScene(_scene, ISceneSynchronizer::All);
}
}
} | 37.277966 | 178 | 0.579522 | [
"mesh",
"geometry",
"render",
"vector"
] |
b12a4098ca1914e7fc835d64604d87db7dbe3f31 | 5,246 | cpp | C++ | tc 160+/CirclesCountry.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/CirclesCountry.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/CirclesCountry.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
vector<int> X, Y, R;
inline int dist_sqr(int x, int y, int xc, int yc) {
return (x-xc)*(x-xc) + (y-yc)*(y-yc);
}
inline bool inside(int x, int y, int xc, int yc, int r) {
return dist_sqr(x, y, xc, yc) < r*r;
}
inline bool inside(int i, int j) {
return inside(X[i], Y[i], X[j], Y[j], R[j]);
}
int n;
bool v[50];
int P[50];
int get_circ(int x, int y) {
for (int i=0; i<n; ++i) {
if (inside(x, y, X[i], Y[i], R[i])) {
return i;
}
}
return n;
}
int dfs(int c) {
if (c==n || v[c]) {
return c;
} else {
v[c] = true;
return dfs(P[c]);
}
}
int depth(int c, int p) {
return (c==p ? 0 : 1 + depth(P[c], p));
}
class CirclesCountry {
public:
int leastBorders(vector <int> X_, vector <int> Y_, vector <int> R_, int x1, int y1, int x2, int y2) {
X = X_;
Y = Y_;
R = R_;
n = X.size();
for (int i=0; i<n; ++i) {
for (int j=i+1; j<n; ++j) {
if (R[i] > R[j]) {
swap(R[i], R[j]);
swap(X[i], X[j]);
swap(Y[i], Y[j]);
}
}
}
for (int i=0; i<n; ++i) {
P[i] = n;
for (int j=i+1; j<n; ++j) {
if (inside(i, j)) {
P[i] = j;
break;
}
}
}
int c1 = get_circ(x1, y1);
int c2 = get_circ(x2, y2);
memset(v, 0, sizeof v);
dfs(c1);
int p = dfs(c2);
return depth(c1, p) + depth(c2, p);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = -5; int Arg4 = 1; int Arg5 = 5; int Arg6 = 1; int Arg7 = 0; verify_case(0, Arg7, leastBorders(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)); }
void test_case_1() { int Arr0[] = {0,-6,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,1,2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2,2,2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = -5; int Arg4 = 1; int Arg5 = 5; int Arg6 = 1; int Arg7 = 2; verify_case(1, Arg7, leastBorders(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)); }
void test_case_2() { int Arr0[] = {1,-3,2,5,-4,12,12}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,-1,2,5,5,1,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {8,1,2,1,1,1,2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = -5; int Arg4 = 1; int Arg5 = 12; int Arg6 = 1; int Arg7 = 3; verify_case(2, Arg7, leastBorders(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)); }
void test_case_3() { int Arr0[] = {-3,2,2,0,-4,12,12,12}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {-1,2,3,1,5,1,1,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1,3,1,7,1,1,2,3}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; int Arg4 = 3; int Arg5 = 13; int Arg6 = 2; int Arg7 = 5; verify_case(3, Arg7, leastBorders(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)); }
void test_case_4() { int Arr0[] = {-107,-38,140,148,-198,172,-179,148,176,153,-56,-187}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {175,-115,23,-2,-49,-151,-52,42,0,68,109,-174}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {135,42,70,39,89,39,43,150,10,120,16,8}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 102; int Arg4 = 16; int Arg5 = 19; int Arg6 = -108; int Arg7 = 3; verify_case(4, Arg7, leastBorders(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
CirclesCountry ___test;
___test.run_test(-1);
}
// END CUT HERE
| 47.690909 | 560 | 0.521159 | [
"vector"
] |
b12a6b36c604c13140a092a0d0f46da87f562e3e | 20,827 | cpp | C++ | _blackscholes/src/blackscholes.cpp | huxuan0307/riscv-vectorized-benchmark-suite | 766d98b72c1900a278e9cede43df8d186f3071ba | [
"BSD-3-Clause"
] | 1 | 2021-05-26T06:38:03.000Z | 2021-05-26T06:38:03.000Z | _blackscholes/src/blackscholes.cpp | huxuan0307/riscv-vectorized-benchmark-suite | 766d98b72c1900a278e9cede43df8d186f3071ba | [
"BSD-3-Clause"
] | null | null | null | _blackscholes/src/blackscholes.cpp | huxuan0307/riscv-vectorized-benchmark-suite | 766d98b72c1900a278e9cede43df8d186f3071ba | [
"BSD-3-Clause"
] | 1 | 2021-05-26T06:38:06.000Z | 2021-05-26T06:38:06.000Z | // Copyright (c) 2007 Intel Corp.
// Black-Scholes
// Analytical method for calculating European Options
//
//
// Reference Source: Options, Futures, and Other Derivatives, 3rd Edition, Prentice
// Hall, John C. Hull,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
// RISC-V VECTOR Version by Cristóbal Ramírez Lazo, "Barcelona 2019"
#ifdef USE_RISCV_VECTOR
#include "../../common/vector_defines.h"
#endif
#ifdef ENABLE_PARSEC_HOOKS
#include <hooks.h>
#endif
// Multi-threaded pthreads header
#ifdef ENABLE_THREADS
// Add the following line so that icc 9.0 is compatible with pthread lib.
#define __thread __threadp
MAIN_ENV
#undef __thread
#endif
// Multi-threaded OpenMP header
#ifdef ENABLE_OPENMP
#include <omp.h>
#endif
#ifdef ENABLE_TBB
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/task_scheduler_init.h"
#include "tbb/tick_count.h"
using namespace std;
using namespace tbb;
#endif //ENABLE_TBB
// Multi-threaded header for Windows
#ifdef WIN32
#pragma warning(disable : 4305)
#pragma warning(disable : 4244)
#include <windows.h>
#endif
//Precision to use for calculations
#define fptype float
#define NUM_RUNS 100
typedef struct OptionData_ {
fptype s; // spot price
fptype strike; // strike price
fptype r; // risk-free interest rate
fptype divq; // dividend rate
fptype v; // volatility
fptype t; // time to maturity or option expiration in years
// (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc)
char OptionType; // Option type. "P"=PUT, "C"=CALL
fptype divs; // dividend vals (not used in this test)
fptype DGrefval; // DerivaGem Reference Value
} OptionData;
OptionData* data;
fptype* prices;
int numOptions;
int * otype;
fptype * sptprice;
fptype * strike;
fptype * rate;
fptype * volatility;
fptype * otime;
int numError = 0;
int nThreads;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Cumulative Normal Distribution Function
// See Hull, Section 11.8, P.243-244
#define inv_sqrt_2xPI 0.39894228040143270286
#ifdef USE_RISCV_VECTOR
_MMR_f32 CNDF_SIMD (_MMR_f32 xInput ,unsigned long int gvl)
{
_MMR_f32 xNPrimeofX;
_MMR_f32 xK2;
_MMR_f32 xK2_2;
_MMR_f32 xK2_3;
_MMR_f32 xK2_4;
_MMR_f32 xK2_5;
_MMR_f32 xLocal;
_MMR_f32 xLocal_1;
_MMR_f32 xLocal_2;
_MMR_f32 xLocal_3;
_MMR_f32 xVLocal_2;
_MMR_MASK_i32 xMask;
_MMR_f32 expValues;
_MMR_f32 xOne = _MM_SET_f32(1.0,gvl);
xVLocal_2 = _MM_SET_f32(0.0,gvl);
xMask = _MM_VFLT_f32(xInput,xVLocal_2,gvl); //_MM_VFLT_f32(src2,src1)
xInput = _MM_VFSGNJX_f32(xInput,xInput,gvl); //_MM_VFSGNJX_f32(src2,src1)
expValues = _MM_MUL_f32(xInput, xInput,gvl);
expValues = _MM_MUL_f32(expValues, _MM_SET_f32(-0.5,gvl),gvl);
xNPrimeofX = _MM_EXP_f32(expValues ,gvl);
FENCE();
xNPrimeofX = _MM_MUL_f32(xNPrimeofX, _MM_SET_f32(inv_sqrt_2xPI,gvl),gvl);
//xK2 = _MM_MUL_f32(_MM_SET_f32(0.2316419,gvl), xInput,gvl);
//xK2 = _MM_ADD_f32(xK2, xOne,gvl);
xK2 = _MM_SET_f32(0.2316419,gvl);
xK2 = _MM_MADD_f32(xK2,xInput,xOne,gvl);
xK2 = _MM_DIV_f32(xOne,xK2,gvl);
xK2_2 = _MM_MUL_f32(xK2, xK2,gvl);
xK2_3 = _MM_MUL_f32(xK2_2, xK2,gvl);
xK2_4 = _MM_MUL_f32(xK2_3, xK2,gvl);
xK2_5 = _MM_MUL_f32(xK2_4, xK2,gvl);
xLocal_1 = _MM_MUL_f32(xK2, _MM_SET_f32(0.319381530,gvl),gvl);
xLocal_2 = _MM_MUL_f32(xK2_2, _MM_SET_f32(-0.356563782,gvl),gvl);
xLocal_3 = _MM_MUL_f32(xK2_3, _MM_SET_f32(1.781477937,gvl),gvl);
xLocal_2 = _MM_ADD_f32(xLocal_2, xLocal_3,gvl);
//xLocal_2 = _MM_MACC_f32(xLocal_2,xK2_3,_MM_SET_f32(1.781477937,gvl),gvl);
//xLocal_3 = _MM_MUL_f32(xK2_4, _MM_SET_f32(-1.821255978,gvl),gvl);
//xLocal_2 = _MM_ADD_f32(xLocal_2, xLocal_3,gvl);
xLocal_2 = _MM_MACC_f32(xLocal_2,xK2_4,_MM_SET_f32(-1.821255978,gvl),gvl);
xLocal_3 = _MM_MUL_f32(xK2_5, _MM_SET_f32(1.330274429,gvl),gvl);
xLocal_2 = _MM_ADD_f32(xLocal_2, xLocal_3,gvl);
//xLocal_2 = _MM_MACC_f32(xLocal_2,xK2_5,_MM_SET_f32(1.330274429,gvl),gvl);
xLocal_1 = _MM_ADD_f32(xLocal_2, xLocal_1,gvl);
xLocal = _MM_MUL_f32(xLocal_1, xNPrimeofX,gvl);
xLocal = _MM_SUB_f32(xOne,xLocal,gvl);
//xLocal = _MM_NMSUB_f32(xLocal,xNPrimeofX,xOne,gvl);
xLocal = _MM_SUB_f32_MASK(xLocal,xOne,xLocal,xMask,gvl); //sub(vs2,vs1)
return xLocal;
}
void BlkSchlsEqEuroNoDiv_vector (fptype * OptionPrice, int numOptions, fptype * sptprice,
fptype * strike, fptype * rate, fptype * volatility,
fptype * time, int * otype/*,long int * otype_d*/, float timet ,unsigned long int gvl)
{
// local private working variables for the calculation
_MMR_f32 xStockPrice;
_MMR_f32 xStrikePrice;
_MMR_f32 xRiskFreeRate;
_MMR_f32 xVolatility;
_MMR_f32 xTime;
_MMR_f32 xSqrtTime;
_MMR_f32 xLogTerm;
_MMR_f32 xD1, xD2;
_MMR_f32 xPowerTerm;
_MMR_f32 xDen;
_MMR_f32 xRatexTime;
_MMR_f32 xFutureValueX;
_MMR_MASK_i32 xMask;
_MMR_i32 xOtype;
_MMR_i32 xZero;
_MMR_f32 xOptionPrice;
_MMR_f32 xOptionPrice1;
_MMR_f32 xOptionPrice2;
_MMR_f32 xfXd1;
_MMR_f32 xfXd2;
FENCE();
xStrikePrice = _MM_LOAD_f32(strike,gvl);
xStockPrice = _MM_LOAD_f32(sptprice,gvl);
xStrikePrice = _MM_DIV_f32(xStockPrice,xStrikePrice,gvl);
xLogTerm = _MM_LOG_f32(xStrikePrice,gvl);
//FENCE();
xRiskFreeRate = _MM_LOAD_f32(rate,gvl);
xVolatility = _MM_LOAD_f32(volatility,gvl);
xTime = _MM_LOAD_f32(time,gvl);
xSqrtTime = _MM_SQRT_f32(xTime,gvl);
xRatexTime = _MM_MUL_f32(xRiskFreeRate, xTime,gvl);
xRatexTime = _MM_VFSGNJN_f32(xRatexTime, xRatexTime,gvl);
xFutureValueX = _MM_EXP_f32(xRatexTime,gvl);
FENCE();
xPowerTerm = _MM_MUL_f32(xVolatility, xVolatility,gvl);
xPowerTerm = _MM_MUL_f32(xPowerTerm, _MM_SET_f32(0.5,gvl),gvl);
xD1 = _MM_ADD_f32( xRiskFreeRate , xPowerTerm,gvl);
//xD1 = _MM_MUL_f32(xD1, xTime,gvl);
//xD1 = _MM_ADD_f32(xD1,xLogTerm,gvl);
xD1 = _MM_MADD_f32(xD1,xTime,xLogTerm,gvl);
xDen = _MM_MUL_f32(xVolatility, xSqrtTime,gvl);
xD1 = _MM_DIV_f32(xD1,xDen,gvl);
xD2 = _MM_SUB_f32(xD1,xDen ,gvl);
xfXd1 = CNDF_SIMD( xD1 ,gvl);
xfXd2 = CNDF_SIMD( xD2 ,gvl);
xStrikePrice = _MM_LOAD_f32(strike,gvl);
FENCE();
xFutureValueX = _MM_MUL_f32(xFutureValueX, xStrikePrice,gvl);
xOtype = _MM_LOAD_i32(otype,gvl);
xZero = _MM_SET_i32(0,gvl);
xMask = _MM_VMSEQ_i32(xZero,xOtype,gvl);
xfXd1 = _MM_MERGE_f32(_MM_SUB_f32(_MM_SET_f32(1.0,gvl),xfXd1,gvl),xfXd1, xMask,gvl);
xStockPrice = _MM_LOAD_f32(sptprice,gvl);
xOptionPrice1 = _MM_MUL_f32(xStockPrice, xfXd1,gvl);
FENCE();
xfXd2 = _MM_MERGE_f32(_MM_SUB_f32(_MM_SET_f32(1.0,gvl),xfXd2,gvl),xfXd2, xMask,gvl);
xOptionPrice2 = _MM_MUL_f32(xFutureValueX, xfXd2,gvl);
xOptionPrice = _MM_SUB_f32(xOptionPrice2,xOptionPrice1,gvl);
xOptionPrice = _MM_VFSGNJX_f32(xOptionPrice,xOptionPrice,gvl);
_MM_STORE_f32(OptionPrice, xOptionPrice,gvl);
FENCE();
}
#endif // USE_RISCV_VECTOR
fptype CNDF ( fptype InputX )
{
int sign;
fptype OutputX;
fptype xInput;
fptype xNPrimeofX;
fptype expValues;
fptype xK2;
fptype xK2_2, xK2_3;
fptype xK2_4, xK2_5;
fptype xLocal, xLocal_1;
fptype xLocal_2, xLocal_3;
// Check for negative value of InputX
if (InputX < 0.0) {
InputX = -InputX;
sign = 1;
} else
sign = 0;
xInput = InputX;
// Compute NPrimeX term common to both four & six decimal accuracy calcs
expValues = exp(-0.5f * InputX * InputX);
xNPrimeofX = expValues;
xNPrimeofX = xNPrimeofX * inv_sqrt_2xPI;
xK2 = 0.2316419 * xInput;
xK2 = 1.0 + xK2;
xK2 = 1.0 / xK2;
xK2_2 = xK2 * xK2;
xK2_3 = xK2_2 * xK2;
xK2_4 = xK2_3 * xK2;
xK2_5 = xK2_4 * xK2;
xLocal_1 = xK2 * 0.319381530;
xLocal_2 = xK2_2 * (-0.356563782);
xLocal_3 = xK2_3 * 1.781477937;
xLocal_2 = xLocal_2 + xLocal_3;
xLocal_3 = xK2_4 * (-1.821255978);
xLocal_2 = xLocal_2 + xLocal_3;
xLocal_3 = xK2_5 * 1.330274429;
xLocal_2 = xLocal_2 + xLocal_3;
xLocal_1 = xLocal_2 + xLocal_1;
xLocal = xLocal_1 * xNPrimeofX;
xLocal = 1.0 - xLocal;
OutputX = xLocal;
if (sign) {
OutputX = 1.0 - OutputX;
}
return OutputX;
}
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
fptype BlkSchlsEqEuroNoDiv( fptype sptprice,
fptype strike, fptype rate, fptype volatility,
fptype time, int otype, float timet )
{
fptype OptionPrice;
// local private working variables for the calculation
fptype xStockPrice;
fptype xStrikePrice;
fptype xRiskFreeRate;
fptype xVolatility;
fptype xTime;
fptype xSqrtTime;
fptype logValues;
fptype xLogTerm;
fptype xD1;
fptype xD2;
fptype xPowerTerm;
fptype xDen;
fptype d1;
fptype d2;
fptype FutureValueX;
fptype NofXd1;
fptype NofXd2;
fptype NegNofXd1;
fptype NegNofXd2;
xStockPrice = sptprice;
xStrikePrice = strike;
xRiskFreeRate = rate;
xVolatility = volatility;
xTime = time;
xSqrtTime = sqrt(xTime);
logValues = log( sptprice / strike );
xLogTerm = logValues;
xPowerTerm = xVolatility * xVolatility;
xPowerTerm = xPowerTerm * 0.5;
xD1 = xRiskFreeRate + xPowerTerm;
xD1 = xD1 * xTime;
xD1 = xD1 + xLogTerm;
xDen = xVolatility * xSqrtTime;
xD1 = xD1 / xDen;
xD2 = xD1 - xDen;
d1 = xD1;
d2 = xD2;
NofXd1 = CNDF( d1 );
NofXd2 = CNDF( d2 );
FutureValueX = strike * ( exp( -(rate)*(time) ) );
if (otype == 0) {
OptionPrice = (sptprice * NofXd1) - (FutureValueX * NofXd2);
} else {
NegNofXd1 = (1.0 - NofXd1);
NegNofXd2 = (1.0 - NofXd2);
OptionPrice = (FutureValueX * NegNofXd2) - (sptprice * NegNofXd1);
}
return OptionPrice;
}
#ifdef ENABLE_TBB
struct mainWork {
mainWork(){}
mainWork(mainWork &w, tbb::split){}
void operator()(const tbb::blocked_range<int> &range) const {
fptype price;
int begin = range.begin();
int end = range.end();
for (int i=begin; i!=end; i++) {
/* Calling main function to calculate option value based on
* Black & Scholes's equation.
*/
price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i],
rate[i], volatility[i], otime[i],
otype[i], 0);
prices[i] = price;
#ifdef ERR_CHK
fptype priceDelta = data[i].DGrefval - price;
if( fabs(priceDelta) >= 1e-5 ){
fprintf(stderr,"Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n",
i, price, data[i].DGrefval, priceDelta);
numError ++;
}
#endif
}
}
};
#endif // ENABLE_TBB
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
#ifdef ENABLE_TBB
int bs_thread(void *tid_ptr) {
int j;
tbb::affinity_partitioner a;
mainWork doall;
for (j=0; j<NUM_RUNS; j++) {
tbb::parallel_for(tbb::blocked_range<int>(0, numOptions), doall, a);
}
return 0;
}
#else // !ENABLE_TBB
#ifdef WIN32
DWORD WINAPI bs_thread(LPVOID tid_ptr){
#else
int bs_thread(void *tid_ptr) {
#endif
#ifdef USE_RISCV_VECTOR
int i, j, k;
fptype priceDelta;
int tid = *(int *)tid_ptr;
int start = tid * (numOptions / nThreads);
int end = start + (numOptions / nThreads);
// unsigned long int gvl = __builtin_epi_vsetvl(end, __epi_e32, __epi_m1);
unsigned long int gvl = vsetvl_e32m1(end); //PLCT
fptype* price;
price = (fptype*)malloc(gvl*sizeof(fptype));
//price = aligned_alloc(64, gvl*sizeof(fptype));
#ifdef ENABLE_PARSEC_HOOKS
__parsec_thread_begin();
#endif
for (j=0; j<NUM_RUNS; j++) {
#ifdef ENABLE_OPENMP
#pragma omp parallel for private(i, price, priceDelta)
for (i=0; i<numOptions; i += gvl) {
#else //ENABLE_OPENMP
for (i=start; i<end; i += gvl) {
#endif //ENABLE_OPENMP
// Calling main function to calculate option value based on Black & Scholes's
// equation.
// gvl = __builtin_epi_vsetvl(end-i, __epi_e32, __epi_m1);
gvl = vsetvl_e32m1(end-i); //PLCT
BlkSchlsEqEuroNoDiv_vector( price, gvl, &(sptprice[i]), &(strike[i]),
&(rate[i]), &(volatility[i]), &(otime[i]), &(otype[i])/*,&(otype_d[i])*/, 0,gvl);
for (k=0; k<gvl; k++) {
prices[i+k] = price[k];
}
#ifdef ERR_CHK
for (k=0; k<gvl; k++) {
priceDelta = data[i+k].DGrefval - price[k];
if (fabs(priceDelta) >= 1e-4) {
printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n",
i + k, price[k], data[i+k].DGrefval, priceDelta);
numError ++;
}
}
#endif
}
}
#ifdef ENABLE_PARSEC_HOOKS
__parsec_thread_end();
#endif
return 0;
}
#else // ! USE_RISCV_VECTOR
int i, j;
fptype price;
fptype priceDelta;
int tid = *(int *)tid_ptr;
int start = tid * (numOptions / nThreads);
int end = start + (numOptions / nThreads);
for (j=0; j<NUM_RUNS; j++) {
#ifdef ENABLE_OPENMP
#pragma omp parallel for private(i, price, priceDelta)
for (i=0; i<numOptions; i++) {
#else //ENABLE_OPENMP
for (i=start; i<end; i++) {
#endif //ENABLE_OPENMP
/* Calling main function to calculate option value based on
* Black & Scholes's equation.
*/
price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i],
rate[i], volatility[i], otime[i],
otype[i], 0);
prices[i] = price;
#ifdef ERR_CHK
priceDelta = data[i].DGrefval - price;
if( fabs(priceDelta) >= 1e-4 ){
printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n",
i, price, data[i].DGrefval, priceDelta);
numError ++;
}
#endif
}
}
return 0;
}
#endif // USE_RISCV_VECTOR
#endif //ENABLE_TBB
int main (int argc, char **argv)
{
FILE *file;
int i;
int loopnum;
fptype * buffer;
int * buffer2;
int rv;
//#ifdef USE_RISCV_VECTOR
struct timeval tv1_0, tv2_0;
struct timezone tz_0;
double elapsed0=0.0;
gettimeofday(&tv1_0, &tz_0);
//#endif
#ifdef PARSEC_VERSION
#define __PARSEC_STRING(x) #x
#define __PARSEC_XSTRING(x) __PARSEC_STRING(x)
printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n");
fflush(NULL);
#else
printf("PARSEC Benchmark Suite\n");
fflush(NULL);
#endif //PARSEC_VERSION
#ifdef ENABLE_PARSEC_HOOKS
__parsec_bench_begin(__parsec_blackscholes);
#endif
if (argc != 4)
{
printf("Usage:\n\t%s <nthreads> <inputFile> <outputFile>\n", argv[0]);
exit(1);
}
nThreads = atoi(argv[1]);
char *inputFile = argv[2];
char *outputFile = argv[3];
//Read input data from file
file = fopen(inputFile, "r");
if(file == NULL) {
printf("ERROR: Unable to open file `%s'.\n", inputFile);
exit(1);
}
rv = fscanf(file, "%i", &numOptions);
if(rv != 1) {
printf("ERROR: Unable to read from file `%s'.\n", inputFile);
fclose(file);
exit(1);
}
#if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP) && !defined(ENABLE_TBB)
if(nThreads != 1) {
printf("Error: <nthreads> must be 1 (serial version)\n");
exit(1);
}
#endif
data = (OptionData*)malloc(numOptions*sizeof(OptionData));
prices = (fptype*)malloc(numOptions*sizeof(fptype));
for ( loopnum = 0; loopnum < numOptions; ++ loopnum )
{
rv = fscanf(file, "%f %f %f %f %f %f %c %f %f", &data[loopnum].s, &data[loopnum].strike, &data[loopnum].r, &data[loopnum].divq, &data[loopnum].v, &data[loopnum].t, &data[loopnum].OptionType, &data[loopnum].divs, &data[loopnum].DGrefval);
if(rv != 9) {
printf("ERROR: Unable to read from file `%s'.\n", inputFile);
fclose(file);
exit(1);
}
}
rv = fclose(file);
if(rv != 0) {
printf("ERROR: Unable to close file `%s'.\n", inputFile);
exit(1);
}
#ifdef ENABLE_THREADS
MAIN_INITENV(,8000000,nThreads);
#endif
printf("Num of Options: %d\n", numOptions);
printf("Num of Runs: %d\n", NUM_RUNS);
#define PAD 256
#define LINESIZE 64
buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD);
sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1));
strike = sptprice + numOptions;
rate = strike + numOptions;
volatility = rate + numOptions;
otime = volatility + numOptions;
buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD);
otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1));
for (i=0; i<numOptions; i++) {
otype[i] = (data[i].OptionType == 'P') ? 1 : 0;
sptprice[i] = data[i].s;
strike[i] = data[i].strike;
rate[i] = data[i].r;
volatility[i] = data[i].v;
otime[i] = data[i].t;
}
printf("Size of data: %lu\n", numOptions * (sizeof(OptionData) + sizeof(int)));
//#ifdef USE_RISCV_VECTOR
gettimeofday(&tv2_0, &tz_0);
elapsed0 = (double) (tv2_0.tv_sec-tv1_0.tv_sec) + (double) (tv2_0.tv_usec-tv1_0.tv_usec) * 1.e-6;
printf("\n\nBlackScholes Initialization took %8.8lf secs \n", elapsed0 );
//#endif
//#ifdef USE_RISCV_VECTOR
struct timeval tv1, tv2;
struct timezone tz;
double elapsed1=0.0;
gettimeofday(&tv1, &tz);
//#endif
#ifdef ENABLE_PARSEC_HOOKS
__parsec_roi_begin();
#endif
#ifdef ENABLE_THREADS
#ifdef WIN32
HANDLE *threads;
int *nums;
threads = (HANDLE *) malloc (nThreads * sizeof(HANDLE));
nums = (int *) malloc (nThreads * sizeof(int));
for(i=0; i<nThreads; i++) {
nums[i] = i;
threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0);
}
WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE);
free(threads);
free(nums);
#else
int *tids;
tids = (int *) malloc (nThreads * sizeof(int));
for(i=0; i<nThreads; i++) {
tids[i]=i;
CREATE_WITH_ARG(bs_thread, &tids[i]);
}
WAIT_FOR_END(nThreads);
free(tids);
#endif //WIN32
#else //ENABLE_THREADS
#ifdef ENABLE_OPENMP
{
int tid=0;
omp_set_num_threads(nThreads);
bs_thread(&tid);
}
#else //ENABLE_OPENMP
#ifdef ENABLE_TBB
tbb::task_scheduler_init init(nThreads);
int tid=0;
bs_thread(&tid);
#else //ENABLE_TBB
//serial version
int tid=0;
bs_thread(&tid);
#endif //ENABLE_TBB
#endif //ENABLE_OPENMP
#endif //ENABLE_THREADS
#ifdef ENABLE_PARSEC_HOOKS
__parsec_roi_end();
#endif
//#ifdef USE_RISCV_VECTOR
gettimeofday(&tv2, &tz);
elapsed1 = (double) (tv2.tv_sec-tv1.tv_sec) + (double) (tv2.tv_usec-tv1.tv_usec) * 1.e-6;
printf("\n\nBlackScholes Kernel took %8.8lf secs \n", elapsed1 );
//#endif
//Write prices to output file
file = fopen(outputFile, "w");
if(file == NULL) {
printf("ERROR: Unable to open file `%s'.\n", outputFile);
exit(1);
}
rv = fprintf(file, "%i\n", numOptions);
if(rv < 0) {
printf("ERROR: Unable to write to file `%s'.\n", outputFile);
fclose(file);
exit(1);
}
for(i=0; i<numOptions; i++) {
rv = fprintf(file, "%.18f\n", prices[i]);
if(rv < 0) {
printf("ERROR: Unable to write to file `%s'.\n", outputFile);
fclose(file);
exit(1);
}
}
rv = fclose(file);
if(rv != 0) {
printf("ERROR: Unable to close file `%s'.\n", outputFile);
exit(1);
}
#ifdef ERR_CHK
printf("Num Errors: %d\n", numError);
#endif
free(data);
free(prices);
#ifdef ENABLE_PARSEC_HOOKS
__parsec_bench_end();
#endif
return 0;
}
| 27.658699 | 245 | 0.59759 | [
"vector"
] |
b132cc1e515ce62e35a3bf6c25f120e48b49f4dd | 12,098 | cc | C++ | google/cloud/secretmanager/internal/secret_manager_connection_impl.cc | sydney-munro/google-cloud-cpp | 374b52e5cec78962358bdd5913d4118a47af1952 | [
"Apache-2.0"
] | 80 | 2017-11-24T00:19:45.000Z | 2019-01-25T10:24:33.000Z | google/cloud/secretmanager/internal/secret_manager_connection_impl.cc | sydney-munro/google-cloud-cpp | 374b52e5cec78962358bdd5913d4118a47af1952 | [
"Apache-2.0"
] | 1,579 | 2017-11-24T01:01:21.000Z | 2019-01-28T23:41:21.000Z | google/cloud/secretmanager/internal/secret_manager_connection_impl.cc | sydney-munro/google-cloud-cpp | 374b52e5cec78962358bdd5913d4118a47af1952 | [
"Apache-2.0"
] | 51 | 2017-11-24T00:56:11.000Z | 2019-01-18T20:35:02.000Z | // 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
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/secretmanager/v1/service.proto
#include "google/cloud/secretmanager/internal/secret_manager_connection_impl.h"
#include "google/cloud/secretmanager/internal/secret_manager_option_defaults.h"
#include "google/cloud/background_threads.h"
#include "google/cloud/common_options.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/pagination_range.h"
#include "google/cloud/internal/retry_loop.h"
#include <memory>
namespace google {
namespace cloud {
namespace secretmanager_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
SecretManagerServiceConnectionImpl::SecretManagerServiceConnectionImpl(
std::unique_ptr<google::cloud::BackgroundThreads> background,
std::shared_ptr<secretmanager_internal::SecretManagerServiceStub> stub,
Options options)
: background_(std::move(background)),
stub_(std::move(stub)),
options_(internal::MergeOptions(
std::move(options),
secretmanager_internal::SecretManagerServiceDefaultOptions(
SecretManagerServiceConnection::options()))) {}
StreamRange<google::cloud::secretmanager::v1::Secret>
SecretManagerServiceConnectionImpl::ListSecrets(
google::cloud::secretmanager::v1::ListSecretsRequest request) {
request.clear_page_token();
auto stub = stub_;
auto retry =
std::shared_ptr<secretmanager::SecretManagerServiceRetryPolicy const>(
retry_policy());
auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy());
auto idempotency = idempotency_policy()->ListSecrets(request);
char const* function_name = __func__;
return google::cloud::internal::MakePaginationRange<
StreamRange<google::cloud::secretmanager::v1::Secret>>(
std::move(request),
[stub, retry, backoff, idempotency, function_name](
google::cloud::secretmanager::v1::ListSecretsRequest const& r) {
return google::cloud::internal::RetryLoop(
retry->clone(), backoff->clone(), idempotency,
[stub](grpc::ClientContext& context,
google::cloud::secretmanager::v1::ListSecretsRequest const&
request) { return stub->ListSecrets(context, request); },
r, function_name);
},
[](google::cloud::secretmanager::v1::ListSecretsResponse r) {
std::vector<google::cloud::secretmanager::v1::Secret> result(
r.secrets().size());
auto& messages = *r.mutable_secrets();
std::move(messages.begin(), messages.end(), result.begin());
return result;
});
}
StatusOr<google::cloud::secretmanager::v1::Secret>
SecretManagerServiceConnectionImpl::CreateSecret(
google::cloud::secretmanager::v1::CreateSecretRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->CreateSecret(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::CreateSecretRequest const&
request) { return stub_->CreateSecret(context, request); },
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::SecretVersion>
SecretManagerServiceConnectionImpl::AddSecretVersion(
google::cloud::secretmanager::v1::AddSecretVersionRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->AddSecretVersion(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::AddSecretVersionRequest const&
request) { return stub_->AddSecretVersion(context, request); },
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::Secret>
SecretManagerServiceConnectionImpl::GetSecret(
google::cloud::secretmanager::v1::GetSecretRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->GetSecret(request),
[this](
grpc::ClientContext& context,
google::cloud::secretmanager::v1::GetSecretRequest const& request) {
return stub_->GetSecret(context, request);
},
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::Secret>
SecretManagerServiceConnectionImpl::UpdateSecret(
google::cloud::secretmanager::v1::UpdateSecretRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->UpdateSecret(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::UpdateSecretRequest const&
request) { return stub_->UpdateSecret(context, request); },
request, __func__);
}
Status SecretManagerServiceConnectionImpl::DeleteSecret(
google::cloud::secretmanager::v1::DeleteSecretRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->DeleteSecret(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::DeleteSecretRequest const&
request) { return stub_->DeleteSecret(context, request); },
request, __func__);
}
StreamRange<google::cloud::secretmanager::v1::SecretVersion>
SecretManagerServiceConnectionImpl::ListSecretVersions(
google::cloud::secretmanager::v1::ListSecretVersionsRequest request) {
request.clear_page_token();
auto stub = stub_;
auto retry =
std::shared_ptr<secretmanager::SecretManagerServiceRetryPolicy const>(
retry_policy());
auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy());
auto idempotency = idempotency_policy()->ListSecretVersions(request);
char const* function_name = __func__;
return google::cloud::internal::MakePaginationRange<
StreamRange<google::cloud::secretmanager::v1::SecretVersion>>(
std::move(request),
[stub, retry, backoff, idempotency, function_name](
google::cloud::secretmanager::v1::ListSecretVersionsRequest const&
r) {
return google::cloud::internal::RetryLoop(
retry->clone(), backoff->clone(), idempotency,
[stub](grpc::ClientContext& context,
google::cloud::secretmanager::v1::
ListSecretVersionsRequest const& request) {
return stub->ListSecretVersions(context, request);
},
r, function_name);
},
[](google::cloud::secretmanager::v1::ListSecretVersionsResponse r) {
std::vector<google::cloud::secretmanager::v1::SecretVersion> result(
r.versions().size());
auto& messages = *r.mutable_versions();
std::move(messages.begin(), messages.end(), result.begin());
return result;
});
}
StatusOr<google::cloud::secretmanager::v1::SecretVersion>
SecretManagerServiceConnectionImpl::GetSecretVersion(
google::cloud::secretmanager::v1::GetSecretVersionRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->GetSecretVersion(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::GetSecretVersionRequest const&
request) { return stub_->GetSecretVersion(context, request); },
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::AccessSecretVersionResponse>
SecretManagerServiceConnectionImpl::AccessSecretVersion(
google::cloud::secretmanager::v1::AccessSecretVersionRequest const&
request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->AccessSecretVersion(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::AccessSecretVersionRequest const&
request) {
return stub_->AccessSecretVersion(context, request);
},
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::SecretVersion>
SecretManagerServiceConnectionImpl::DisableSecretVersion(
google::cloud::secretmanager::v1::DisableSecretVersionRequest const&
request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->DisableSecretVersion(request),
[this](
grpc::ClientContext& context,
google::cloud::secretmanager::v1::DisableSecretVersionRequest const&
request) {
return stub_->DisableSecretVersion(context, request);
},
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::SecretVersion>
SecretManagerServiceConnectionImpl::EnableSecretVersion(
google::cloud::secretmanager::v1::EnableSecretVersionRequest const&
request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->EnableSecretVersion(request),
[this](grpc::ClientContext& context,
google::cloud::secretmanager::v1::EnableSecretVersionRequest const&
request) {
return stub_->EnableSecretVersion(context, request);
},
request, __func__);
}
StatusOr<google::cloud::secretmanager::v1::SecretVersion>
SecretManagerServiceConnectionImpl::DestroySecretVersion(
google::cloud::secretmanager::v1::DestroySecretVersionRequest const&
request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->DestroySecretVersion(request),
[this](
grpc::ClientContext& context,
google::cloud::secretmanager::v1::DestroySecretVersionRequest const&
request) {
return stub_->DestroySecretVersion(context, request);
},
request, __func__);
}
StatusOr<google::iam::v1::Policy>
SecretManagerServiceConnectionImpl::SetIamPolicy(
google::iam::v1::SetIamPolicyRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->SetIamPolicy(request),
[this](grpc::ClientContext& context,
google::iam::v1::SetIamPolicyRequest const& request) {
return stub_->SetIamPolicy(context, request);
},
request, __func__);
}
StatusOr<google::iam::v1::Policy>
SecretManagerServiceConnectionImpl::GetIamPolicy(
google::iam::v1::GetIamPolicyRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->GetIamPolicy(request),
[this](grpc::ClientContext& context,
google::iam::v1::GetIamPolicyRequest const& request) {
return stub_->GetIamPolicy(context, request);
},
request, __func__);
}
StatusOr<google::iam::v1::TestIamPermissionsResponse>
SecretManagerServiceConnectionImpl::TestIamPermissions(
google::iam::v1::TestIamPermissionsRequest const& request) {
return google::cloud::internal::RetryLoop(
retry_policy(), backoff_policy(),
idempotency_policy()->TestIamPermissions(request),
[this](grpc::ClientContext& context,
google::iam::v1::TestIamPermissionsRequest const& request) {
return stub_->TestIamPermissions(context, request);
},
request, __func__);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace secretmanager_internal
} // namespace cloud
} // namespace google
| 41.861592 | 80 | 0.701356 | [
"vector"
] |
b134293d546de7c5096ac68350c14a4f61893cd6 | 833 | cpp | C++ | lab07/1.3_find_max_ex/find_max_ex_test/FindMaxTest.cpp | AlexanderFadeev/oop | 62ea584b2c49dea5457b9e520866bfd7a0d883c7 | [
"MIT"
] | null | null | null | lab07/1.3_find_max_ex/find_max_ex_test/FindMaxTest.cpp | AlexanderFadeev/oop | 62ea584b2c49dea5457b9e520866bfd7a0d883c7 | [
"MIT"
] | 18 | 2018-02-07T07:10:18.000Z | 2018-05-23T08:11:28.000Z | lab07/1.3_find_max_ex/find_max_ex_test/FindMaxTest.cpp | AlexanderFadeev/oop | 62ea584b2c49dea5457b9e520866bfd7a0d883c7 | [
"MIT"
] | null | null | null | #include "FindMax.hpp"
#include "catch.hpp"
template <typename T, typename Less = std::less<T>>
void CheckFindMax(std::vector<T> vec, const T& expectedMax, const Less& less = Less())
{
auto max = T();
CHECK(FindMax(vec, max, less));
CHECK(max == expectedMax);
}
template <typename T>
void CheckFindMaxFail(std::vector<T> vec)
{
auto max = T();
CHECK_FALSE(FindMax(vec, max));
CHECK(max == T());
}
TEST_CASE("Empty vector")
{
CheckFindMaxFail<int>({});
}
TEST_CASE("Various types")
{
CheckFindMax<int>({ 1, 5, 2, 3, 4 }, 5);
CheckFindMax<double>({ 3.141592, 2.71829, 0.5, 42.0 }, 42.0);
CheckFindMax<char>({ 'a', 'd', 'e', 'q' }, 'q');
CheckFindMax<std::string>({ "abc", "foo", "zebra" }, "zebra");
}
TEST_CASE("Custom predicate")
{
CheckFindMax<int, std::greater<int>>({ 1, 5, 2, 3, 4 }, 1, std::greater<int>());
} | 21.921053 | 86 | 0.62545 | [
"vector"
] |
b138fd62117fbcf33a9668ab9bd337ab3a1a31bd | 1,418 | cpp | C++ | examples/alternatives.cpp | GerHobbelt/clipp | 0b3124d010753909fbccc63e217a763cd336b906 | [
"MIT"
] | 2 | 2022-01-19T01:22:36.000Z | 2022-03-17T07:38:54.000Z | examples/alternatives.cpp | GerHobbelt/clipp | 0b3124d010753909fbccc63e217a763cd336b906 | [
"MIT"
] | null | null | null | examples/alternatives.cpp | GerHobbelt/clipp | 0b3124d010753909fbccc63e217a763cd336b906 | [
"MIT"
] | null | null | null | /*****************************************************************************
*
* demo program - part of CLIPP (command line interfaces for modern C++)
*
* released under MIT license
*
* (c) 2017-2018 André Müller; foss@andremueller-online.de
*
*****************************************************************************/
#include <iostream>
#include <string>
#include <vector>
#include <clipp.h>
#include "monolithic_examples.h"
#if defined(BUILD_MONOLITHIC)
#define main(cnt, arr) clipp_alternatives_main(cnt, arr)
#endif
int main(int argc, const char** argv)
{
using namespace clipp;
using std::cout;
std::vector<std::string> files;
std::string expr;
bool ifany = false, ifall = false;
auto cli = (
values("file", files) % "input filenames",
(required("-s") & value("expr", expr)) % "string to look for",
option("any").set(ifany) % "report as soon as any matches" |
option("all").set(ifall) % "report only if all match"
);
if(parse(argc, argv, cli)) {
cout << "find '" << expr << "' in files: ";
for(const auto& f : files) { cout << "'" << f << "' "; } cout << '\n';
if(ifany) cout << "using 'any' mode\n";
if(ifall) cout << "using 'all' mode\n";
}
else {
cout << make_man_page(cli, argv[0]) << '\n';
}
return EXIT_SUCCESS;
}
| 26.754717 | 82 | 0.497884 | [
"vector"
] |
b13a468eae07c23b6bd5ba3c2986557bad3464ed | 4,114 | cpp | C++ | cpu_version/tools/query.cpp | takanokage/Product-Quantization-Tree | 2651ba871100ff4c0ccef42ba57e871fbc6181f8 | [
"MIT"
] | 98 | 2016-07-18T07:38:07.000Z | 2022-02-02T15:28:01.000Z | cpu_version/tools/query.cpp | takanokage/Product-Quantization-Tree | 2651ba871100ff4c0ccef42ba57e871fbc6181f8 | [
"MIT"
] | 14 | 2016-08-03T08:43:36.000Z | 2017-11-02T14:39:41.000Z | cpu_version/tools/query.cpp | takanokage/Product-Quantization-Tree | 2651ba871100ff4c0ccef42ba57e871fbc6181f8 | [
"MIT"
] | 36 | 2016-07-27T13:47:12.000Z | 2020-07-13T14:34:46.000Z | #include <iostream>
#include <string>
#include "../helper.hpp"
#include "../timer.hpp"
#include "../iterator/memiterator.hpp"
#include "../iterator/iterator.hpp"
#include "../quantizer/treequantizer.hpp"
const uint D = 128; // dimension of vector
const uint P = 2; // number of parts
const uint C1 = 16; // number of clusters in 1st level per part
const uint C2 = 8; // number of refinements
const uint H1 = 4;
const uint RE = 32;
uint ListLen = 8192;
typedef float T;
void recall(
iterator<T, D> &iter_query,
iterator<int, 100> &iter_truth,
treequantizer<T, D, C1, C2, P, H1, RE> &Q,
uint num) {
typedef std::pair< uint, T > bin_t;
// r = 1,10,100,1000,10000,100000
const int H = 6;
uint Rs[7] = {1, 10, 100, 1000, 10000, 100000, 1000000};
uint good[7] = {0};
double avg_candlist_len = 0;
double avg_binlist_len = 0;
for (int i = 0, i_e = num; i < i_e; ++i) {
// extract correct groundtruth id from dataset
const uint correctId = iter_truth[i](0, 0);
// compute requirements
std::vector<std::pair<uint, T>> vectorCandidates; // proposed vectors (ordered)
Q.query(20000,500, iter_query[i], vectorCandidates);
// avg_binlist_len += binCandidates.size();
avg_candlist_len += vectorCandidates.size();
// get statistics
bool found = false;
uint s = 0;
const uint s_e = min(vectorCandidates.size(), (uint)100000);
for (; s < s_e; ++s) {
if (vectorCandidates[s].first == correctId) {
found = true;
break;
}
}
if (found) {
if (s < 1)
++good[0];
if (s < 10)
++good[1];
if (s < 100)
++good[2];
if (s < 1000)
++good[3];
if (s < 10000)
++good[4];
if (s < 100000)
++good[5];
if (s < 1000000)
++good[6];
}
}
std::cout << "candidate list: " << avg_candlist_len / static_cast<double>(num) << std::endl;
std::cout << "bin list: " << avg_binlist_len / static_cast<double>(num) << std::endl;
for (int r = 0; r < H; ++r) {
std::cout << "@R" << Rs[r] << ": " << good[r] / static_cast<T>(num) << std::endl;
}
}
int main(int argc, char const *argv[]) {
UNUSED(argc);
UNUSED(argv);
ListLen = 20000;
std::string path = "/graphics/projects/scratch/ANNSIFTDB/ANN_SIFT1M/";
std::string query = path + "query.umem";
std::string truth = path + "groundtruth.imem";
// load query set
memiterator<float, uint8_t> query_set;
query_set.open(query.c_str());
std::cout << "query-set " << query << std::endl;
std::cout << "dim: " << query_set.dim() << std::endl;
std::cout << "num: " << query_set.num() << std::endl;
iterator<float, 128> iter_query;
float *query_data = query_set.all();
iter_query.insertBatch(query_data, query_set.num());
// load groundtruth set
memiterator<int, int> truth_set;
truth_set.open(truth.c_str());
std::cout << "truth-set " << truth << std::endl;
std::cout << "dim: " << truth_set.dim() << std::endl;
std::cout << "num: " << truth_set.num() << std::endl;
iterator<int, 100> iter_truth;
int *truth_data = truth_set.all();
iter_truth.insertBatch(truth_data, truth_set.num());
treequantizer<T, D, C1, C2, P, H1, RE> Q;
Q.loadTree("tree.tree");
Q.loadBins("tree.bins");
const uint countQueryVecs = iter_query.num();
// query vectors
timer<> t;
recall( iter_query, iter_truth, Q, countQueryVecs);
t.stop();
std::cout << "avg. query time " << t.elapsed() / static_cast<float>(countQueryVecs) << "ms" << std::endl;
std::cout << "total. query time " << t.elapsed<std::chrono::seconds>() << "s" << std::endl;
return 0;
}
| 28.372414 | 111 | 0.529898 | [
"vector"
] |
b13e0c63974a6f45da613f376032f2ec354d91c6 | 6,712 | cc | C++ | content/services/shared_storage_worklet/unnamed_operation_handler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | content/services/shared_storage_worklet/unnamed_operation_handler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | content/services/shared_storage_worklet/unnamed_operation_handler.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // 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 "content/services/shared_storage_worklet/unnamed_operation_handler.h"
#include "content/services/shared_storage_worklet/worklet_v8_helper.h"
#include "gin/arguments.h"
#include "gin/function_template.h"
#include "v8/include/v8-context.h"
#include "v8/include/v8-function.h"
#include "v8/include/v8-object.h"
#include "v8/include/v8-promise.h"
#include "v8/include/v8-value-serializer.h"
namespace shared_storage_worklet {
struct UnnamedOperationHandler::PendingRequest {
explicit PendingRequest(
mojom::SharedStorageWorkletService::RunOperationCallback callback);
~PendingRequest();
mojom::SharedStorageWorkletService::RunOperationCallback callback;
};
UnnamedOperationHandler::PendingRequest::PendingRequest(
mojom::SharedStorageWorkletService::RunOperationCallback callback)
: callback(std::move(callback)) {}
UnnamedOperationHandler::PendingRequest::~PendingRequest() = default;
UnnamedOperationHandler::UnnamedOperationHandler() = default;
UnnamedOperationHandler::~UnnamedOperationHandler() = default;
void UnnamedOperationHandler::RegisterOperation(gin::Arguments* args) {
std::string name;
if (!args->GetNext(&name)) {
args->ThrowTypeError("Missing \"name\" argument in operation registration");
return;
}
if (name.empty()) {
args->ThrowTypeError("Operation name cannot be empty");
return;
}
if (operation_definition_map_.count(name)) {
args->ThrowTypeError("Operation name already registered");
return;
}
v8::Local<v8::Object> class_definition;
if (!args->GetNext(&class_definition)) {
args->ThrowTypeError(
"Missing class name argument in operation registration");
return;
}
if (!class_definition->IsConstructor()) {
args->ThrowTypeError("Unexpected class argument: not a constructor");
return;
}
v8::Isolate* isolate = args->isolate();
v8::Local<v8::Context> context = args->GetHolderCreationContext();
v8::Local<v8::Value> class_prototype =
class_definition->Get(context, gin::StringToV8(isolate, "prototype"))
.ToLocalChecked();
v8::Local<v8::Value> run_function =
class_prototype.As<v8::Object>()
->Get(context, gin::StringToV8(isolate, "run"))
.ToLocalChecked();
if (run_function->IsUndefined() || !run_function->IsFunction()) {
args->ThrowTypeError("Missing \"run()\" function in the class");
return;
}
operation_definition_map_.emplace(
name, v8::Global<v8::Function>(isolate, run_function.As<v8::Function>()));
}
void UnnamedOperationHandler::RunOperation(
v8::Local<v8::Context> context,
const std::string& name,
const std::vector<uint8_t>& serialized_data,
mojom::SharedStorageWorkletService::RunOperationCallback callback) {
auto it = operation_definition_map_.find(name);
if (it == operation_definition_map_.end()) {
std::move(callback).Run(/*success=*/false, "Cannot find operation name.");
return;
}
v8::Isolate* isolate = context->GetIsolate();
v8::Context::Scope context_scope(context);
v8::Local<v8::Function> run_function = it->second.Get(isolate);
v8::Local<v8::Object> js_data;
if (serialized_data.empty()) {
js_data = v8::Object::New(isolate);
} else {
v8::ValueDeserializer deserializer(isolate, serialized_data.data(),
serialized_data.size());
v8::Local<v8::Value> value =
deserializer.ReadValue(context).ToLocalChecked();
js_data = value->ToObject(context).ToLocalChecked();
}
std::vector<v8::Local<v8::Value>> args{js_data};
std::string error_message;
v8::MaybeLocal<v8::Value> result = WorkletV8Helper::InvokeFunction(
context, run_function, args, &error_message);
if (result.IsEmpty()) {
std::move(callback).Run(
/*success=*/false, error_message);
return;
}
if (!result.ToLocalChecked()->IsPromise()) {
std::move(callback).Run(/*success=*/false,
"run() did not return a promise.");
return;
}
v8::Local<v8::Promise> result_promise =
result.ToLocalChecked().As<v8::Promise>();
// If the promise is already completed, retrieve and handle the result
// directly.
if (result_promise->State() == v8::Promise::PromiseState::kFulfilled) {
std::move(callback).Run(/*success=*/true, /*error_message=*/{});
return;
}
if (result_promise->State() == v8::Promise::PromiseState::kRejected) {
error_message = gin::V8ToString(
isolate,
result_promise->Result()->ToDetailString(context).ToLocalChecked());
std::move(callback).Run(
/*success=*/false, error_message);
return;
}
// If the promise is pending, install callback functions that will be
// triggered when it completes.
auto pending_request = std::make_unique<PendingRequest>(std::move(callback));
PendingRequest* pending_request_raw = pending_request.get();
pending_requests_.emplace(pending_request_raw, std::move(pending_request));
v8::Local<v8::Function> fulfilled_callback =
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(
&UnnamedOperationHandler::OnPromiseFulfilled,
weak_ptr_factory_.GetWeakPtr(), pending_request_raw))
->GetFunction(context)
.ToLocalChecked();
v8::Local<v8::Function> rejected_callback =
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(
&UnnamedOperationHandler::OnPromiseRejected,
weak_ptr_factory_.GetWeakPtr(), pending_request_raw))
->GetFunction(context)
.ToLocalChecked();
result_promise->Then(context, fulfilled_callback, rejected_callback)
.ToLocalChecked();
}
void UnnamedOperationHandler::OnPromiseFulfilled(PendingRequest* request,
gin::Arguments* args) {
std::move(request->callback).Run(/*success=*/true, /*error_message=*/{});
pending_requests_.erase(request);
}
void UnnamedOperationHandler::OnPromiseRejected(PendingRequest* request,
gin::Arguments* args) {
std::string error_message;
if (!args->GetNext(&error_message)) {
std::move(request->callback)
.Run(/*success=*/false,
"Promise is rejected without an explicit error message.");
pending_requests_.erase(request);
return;
}
std::move(request->callback).Run(/*success=*/false, error_message);
pending_requests_.erase(request);
}
} // namespace shared_storage_worklet
| 33.064039 | 80 | 0.684744 | [
"object",
"vector"
] |
b143a2fccfb087ae4d14fe9a1e1c7d967ce01137 | 1,231 | cpp | C++ | ComponentFramework/EntityBag.cpp | autious/kravall_entity_component_framework | a4380ea9135c2ad7aac444c0d52837eb1a43319d | [
"MIT"
] | 7 | 2015-06-21T20:23:12.000Z | 2020-01-04T20:20:56.000Z | ComponentFramework/EntityBag.cpp | autious/kravall_entity_component_framework | a4380ea9135c2ad7aac444c0d52837eb1a43319d | [
"MIT"
] | null | null | null | ComponentFramework/EntityBag.cpp | autious/kravall_entity_component_framework | a4380ea9135c2ad7aac444c0d52837eb1a43319d | [
"MIT"
] | null | null | null | #include "EntityBag.hpp"
#include "SystemTypes.hpp"
#include <cassert>
namespace Core
{
EntityBag::EntityBag( Aspect inclusive, Aspect exclusive )
{
m_inclusive = inclusive;
m_exclusive = exclusive;
}
void EntityBag::ChangedEntity( Entity id, Aspect old_asp, Aspect new_asp )
{
//Remove if old matches
if( AspectMatch( old_asp ) )
{
bool found = false;
std::vector<Entity>::iterator it;
for (it = m_entities.begin();
it != m_entities.end() && found == false;
)
{
if( *it == id )
{
found = true;
}
else
{
it++;
}
}
if ( found )
m_entities.erase(it);
assert( m_inclusive == 0 || found );
}
//Add if new matches
if( AspectMatch( new_asp ) && new_asp != 0ULL )
{
m_entities.push_back( id );
}
}
bool EntityBag::AspectMatch( Aspect asp )
{
return ((m_inclusive & asp) == m_inclusive) && ((m_exclusive & asp) == 0 );
}
}
| 23.226415 | 83 | 0.447604 | [
"vector"
] |
b1499670973845934c1974cddc17d7535394f030 | 56,375 | cpp | C++ | source/Tools/Fusion2/FUSIONView.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 3 | 2020-04-29T03:17:50.000Z | 2021-05-26T19:53:46.000Z | source/Tools/Fusion2/FUSIONView.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 1 | 2020-04-29T03:12:47.000Z | 2020-04-29T03:12:47.000Z | source/Tools/Fusion2/FUSIONView.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | null | null | null | /****************************************************************************************/
/* FusionView.cpp */
/* */
/* Author: Jim Mischel, Ken Baird, Jeff Lomax, John Moore */
/* Description: MFC view stuff... Alot of the editor UI functionality is here */
/* */
/* The contents of this file are subject to the Genesis3D Public License */
/* Version 1.01 (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.genesis3d.com */
/* */
/* Software distributed under the License is distributed on an "AS IS" */
/* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See */
/* the License for the specific language governing rights and limitations */
/* under the License. */
/* */
/* The Original Code is Genesis3D, released March 25, 1999. */
/*Genesis3D Version 1.1 released November 15, 1999 */
/* Copyright (C) 1999 WildTangent, Inc. All Rights Reserved */
/* */
/****************************************************************************************/
#include "stdafx.h"
#include "FUSIONView.h"
#include "FUSIONDoc.h"
#include "KeyEditDlg.h"
#include <assert.h>
#include "FusionTabControls.h"
#include "BrushEntityDialog.h"
#include "units.h"
#include "face.h"
#include "ram.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define AXIS_X 0x1
#define AXIS_Y 0x2
#define AXIS_Z 0x4
#define MAX_PIXEL_DRAG_START_DIST (12.0f)
int CFusionView::mCY_DRAG = 2 ;
int CFusionView::mCX_DRAG = 2 ;
IMPLEMENT_DYNCREATE(CFusionView, CView)
BEGIN_MESSAGE_MAP(CFusionView, CView)
ON_MESSAGE(WM_USER_COMPILE_MSG, OnCompileMessage)
ON_MESSAGE(WM_USER_COMPILE_ERR, OnCompileError)
ON_MESSAGE(WM_USER_COMPILE_DONE, OnCompileDone)
//{{AFX_MSG_MAP(CFusionView)
ON_WM_SIZE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
ON_COMMAND(ID_TOOLS_CAMERA, OnToolsCamera)
ON_UPDATE_COMMAND_UI(ID_TOOLS_CAMERA, OnUpdateToolsCamera)
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONUP()
ON_COMMAND(ID_AXIS_X, OnAxisX)
ON_UPDATE_COMMAND_UI(ID_AXIS_X, OnUpdateAxisX)
ON_COMMAND(ID_AXIS_Y, OnAxisY)
ON_UPDATE_COMMAND_UI(ID_AXIS_Y, OnUpdateAxisY)
ON_COMMAND(ID_AXIS_Z, OnAxisZ)
ON_UPDATE_COMMAND_UI(ID_AXIS_Z, OnUpdateAxisZ)
ON_COMMAND(ID_TOOLS_BRUSH_MOVEROTATEBRUSH, OnToolsBrushMoverotatebrush)
ON_UPDATE_COMMAND_UI(ID_TOOLS_BRUSH_MOVEROTATEBRUSH, OnUpdateToolsBrushMoverotatebrush)
ON_COMMAND(ID_TOOLS_BRUSH_SCALEBRUSH, OnToolsBrushScalebrush)
ON_UPDATE_COMMAND_UI(ID_TOOLS_BRUSH_SCALEBRUSH, OnUpdateToolsBrushScalebrush)
ON_COMMAND(ID_TOOLS_BRUSH_SHOWBRUSH, OnToolsBrushShowbrush)
ON_UPDATE_COMMAND_UI(ID_TOOLS_BRUSH_SHOWBRUSH, OnUpdateToolsBrushShowbrush)
ON_WM_ERASEBKGND()
ON_COMMAND(ID_TOOLS_BRUSH_SHEARBRUSH, OnToolsBrushShearbrush)
ON_UPDATE_COMMAND_UI(ID_TOOLS_BRUSH_SHEARBRUSH, OnUpdateToolsBrushShearbrush)
ON_UPDATE_COMMAND_UI(ID_GROUPS_MAKENEWGROUP, OnUpdateBrushGroupsMakenewgroup)
ON_UPDATE_COMMAND_UI(ID_BRUSH_GROUPS_ADDTOGROUP, OnUpdateBrushGroupsAddtogroup)
ON_COMMAND(ID_TOOLS_BRUSH_ROTATE90, OnToolsBrushRotate45)
ON_COMMAND(ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES, OnToolsBrushMoveselectedbrushes)
ON_UPDATE_COMMAND_UI(ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES, OnUpdateToolsBrushMoveselectedbrushes)
ON_COMMAND(ID_TOOLS_TEMPLATE, OnToolsTemplate)
ON_UPDATE_COMMAND_UI(ID_TOOLS_TEMPLATE, OnUpdateToolsTemplate)
ON_UPDATE_COMMAND_UI(ID_TOOLS_BRUSH_ROTATE90, OnUpdateToolsBrushRotate45)
ON_COMMAND(ID_BRUSH_REMOVESELECTEDFROMGROUP, OnBrushRemoveselectedfromgroup)
ON_UPDATE_COMMAND_UI(ID_BRUSH_REMOVESELECTEDFROMGROUP, OnUpdateBrushRemoveselectedfromgroup)
ON_COMMAND(ID_BRUSH_GROUPS_ADDTOGROUP, OnBrushGroupsAddtogroup)
ON_COMMAND(ID_DESELECTALL, OnDeselectall)
ON_UPDATE_COMMAND_UI(ID_DESELECTALL, OnUpdateDeselectall)
ON_COMMAND(ID_SELECTALL, OnSelectall)
ON_UPDATE_COMMAND_UI(ID_SELECTALL, OnUpdateSelectall)
ON_COMMAND(ID_TOOLS_SCALEWORLD, OnToolsScaleworld)
ON_COMMAND(ID_TOOLS_BRUSH_MAKENEWEST, OnToolsBrushMakenewest)
ON_COMMAND(ID_TOOLS_SETTEXTURESCALE, OnToolsSettexturescale)
ON_COMMAND(ID_TOOLS_NEXTBRUSH, OnToolsNextbrush)
ON_COMMAND(ID_TOOLS_PREVBRUSH, OnToolsPrevbrush)
ON_COMMAND(ID_TOOLS_ADDTOLEVEL, OnToolsAddtolevel)
ON_UPDATE_COMMAND_UI(ID_TOOLS_ADDTOLEVEL, OnUpdateToolsAddtolevel)
ON_COMMAND(ID_VIEW_ZOOMIN, OnViewZoomin)
ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOMIN, OnUpdateViewZoomin)
ON_COMMAND(ID_VIEW_ZOOMOUT, OnViewZoomout)
ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOMOUT, OnUpdateViewZoomout)
ON_COMMAND(ID_CENTERTHING, OnCenterthing)
ON_WM_MBUTTONUP()
ON_UPDATE_COMMAND_UI(ID_CENTERTHING, OnUpdateCenterthing)
//}}AFX_MSG_MAP
ON_COMMAND_RANGE( ID_VIEW_3DWIREFRAME, ID_VIEW_TEXTUREVIEW, OnViewType)
ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_3DWIREFRAME, ID_VIEW_TEXTUREVIEW, OnViewTypeCmdUi)
END_MESSAGE_MAP()
#define SIDE_LEFT 1
#define SIDE_RIGHT 2
#define SIDE_TOP 4
#define SIDE_BOTTOM 8
void CFusionView::OnUpdateCenterthing(CCmdUI* pCmdUI)
{
CFusionDoc *pDoc = GetDocument ();
if ((pDoc->mModeTool == ID_TOOLS_TEMPLATE) &&
((mViewType == ID_VIEW_TOPVIEW) || (mViewType == ID_VIEW_SIDEVIEW) || (mViewType == ID_VIEW_FRONTVIEW)))
{
pCmdUI->Enable (TRUE);
}
else
{
pCmdUI->Enable (FALSE);
}
}
// Center the template brush or entity in the selected view.
// Doesn't work for 3d views...
void CFusionView::OnCenterthing()
{
CFusionDoc *pDoc = GetDocument ();
// only works on templates
if ((pDoc->mModeTool != ID_TOOLS_TEMPLATE) ||
((mViewType != ID_VIEW_TOPVIEW) && (mViewType != ID_VIEW_SIDEVIEW) && (mViewType != ID_VIEW_FRONTVIEW)))
{
return;
}
geVec3d NewWorldPos = Render_GetViewCenter (VCam);
// Get the current thing's position...
geVec3d CurrentThingPos;
if (pDoc->TempEnt)
{
CurrentThingPos = pDoc->mRegularEntity.mOrigin;
}
else
{
if (pDoc->CurBrush == NULL)
{
return;
}
Brush_Center (pDoc->CurBrush, &CurrentThingPos);
}
// Compute delta required to get thing to NewWorldPos.
// One dimension won't be changed (i.e. in the top view, the Y won't be modified)
geVec3d MoveDelta;
geVec3d_Subtract (&NewWorldPos, &CurrentThingPos, &MoveDelta);
switch (mViewType)
{
case ID_VIEW_TOPVIEW :
MoveDelta.Y = 0.0f;
break;
case ID_VIEW_SIDEVIEW :
MoveDelta.X = 0.0f;
break;
case ID_VIEW_FRONTVIEW :
MoveDelta.Z = 0.0f;
break;
default :
// don't do nothin!
assert (0);
}
// We've computed the delta, so move the thing...
pDoc->MoveTemplateBrush (&MoveDelta);
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL );
}
static geBoolean IsKeyDown (int Key)
{
int KeyState;
KeyState = ::GetAsyncKeyState (Key);
return (KeyState & 0x8000);
}
// Prevent axis movement. View space clipping.
void CFusionView::LockAxisView (int *dx, int *dy)
{
CFusionDoc *pDoc = GetDocument ();
int mLockAxis = pDoc->GetLockAxis ();
switch (mViewType)
{
case ID_VIEW_TOPVIEW :
if (mLockAxis & AXIS_X) *dx = 0;
if (mLockAxis & AXIS_Z) *dy = 0;
break;
case ID_VIEW_SIDEVIEW :
if (mLockAxis & AXIS_X) *dx = 0;
if (mLockAxis & AXIS_Y) *dy = 0;
break;
case ID_VIEW_FRONTVIEW :
if (mLockAxis & AXIS_Z) *dx = 0;
if (mLockAxis & AXIS_Y) *dy = 0;
break;
}
}
// Prevent axis movement. World space clipping.
void CFusionView::LockAxis( geVec3d * pWP )
{
int mLockAxis ;
CFusionDoc* pDoc = GetDocument();
mLockAxis = pDoc->GetLockAxis() ;
if( mLockAxis & AXIS_X ) pWP->X = 0.0f ;
if( mLockAxis & AXIS_Y ) pWP->Y = 0.0f ;
if( mLockAxis & AXIS_Z ) pWP->Z = 0.0f ;
}/* CFusionView::LockAxis */
void CFusionView::OnToolsBrushRotate45()
{
geVec3d rp;
CFusionDoc* pDoc = GetDocument();
geVec3d_Clear (&rp);
switch (mViewType)
{
case ID_VIEW_TOPVIEW:
rp.Y = -(M_PI/4.0f);
break;
case ID_VIEW_FRONTVIEW :
rp.Z = -(M_PI/4.0f);
break;
case ID_VIEW_SIDEVIEW:
rp.X = (M_PI/4.0f);
break;
default :
return;
}
if(GetModeTool()!=ID_GENERALSELECT)
{
pDoc->RotateTemplateBrush(&rp);
pDoc->UpdateSelected();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
else
{
pDoc->RotateSelectedBrushesDirect (&rp);
pDoc->UpdateAllViews(UAV_ALL3DVIEWS | REBUILD_QUICK, NULL);
}
}
int CFusionView::GetCursorBoxPos (const POINT *ptMousePos)
{
CFusionDoc *pDoc;
const Box3d *pBrushBox;
POINT ptMin, ptMax;
int dx, dy;
int x, y;
int horiz, vert;
int lookup[4] = {1, 2, 2, 3};
/*
Split the box up into 3 sections vertically and 3 horizontally.
The center sections are 1/2 the width and height, and the end sections are
each 1/4 of width and height.
What we're creating is:
0 1 2 3 4
------------------------
| | | |
5 | 6 | 7 | 8 | 9
------------------------
| | | |
| | | |
10 | 11 | 12 | 13 | 14
| | | |
------------------------
| | | |
15 | 16 | 17 | 18 | 19
------------------------
20 21 22 23 24
Then we determine which of the sections the cursor is closest to,
and return that index.
*/
pDoc = GetDocument ();
pBrushBox = Brush_GetBoundingBox (pDoc->CurBrush);
// obtain screen coordinates for bounding box min and max points
ptMin = Render_OrthoWorldToView (VCam, &pBrushBox->Min);
ptMax = Render_OrthoWorldToView (VCam, &pBrushBox->Max);
// make sure the min and max points are correct...
if (ptMin.x > ptMax.x)
{
int temp;
temp = ptMin.x;
ptMin.x = ptMax.x;
ptMax.x = temp;
}
if (ptMin.y > ptMax.y)
{
int temp;
temp = ptMin.y;
ptMin.y = ptMax.y;
ptMax.y = temp;
}
// compute horizontal first
x = ptMousePos->x - ptMin.x;
dx = (ptMax.x - ptMin.x);
if (dx == 0) horiz = 0; else horiz = (4*x) / dx;
if (horiz < 0) horiz = 0;
else if (horiz > 3) horiz = 4;
else horiz = lookup[horiz];
// and vertical
y = ptMousePos->y - ptMin.y;
dy = (ptMax.y - ptMin.y);
if (dy == 0) vert = 0; else vert = (4*y)/dy;
if (vert < 0) vert = 0;
else if (vert > 3) vert = 3;
else vert = lookup[vert];
// return index...
return (vert * 5) + horiz;
}
void CFusionView::SetEditCursor (int Tool, const POINT *pMousePos)
{
//for sizing stuff
static const char *SizeCursors[25]=
{
IDC_SIZENWSE, IDC_SIZENWSE, IDC_SIZENS, IDC_SIZENESW, IDC_SIZENESW,
IDC_SIZENWSE, IDC_SIZENWSE, IDC_SIZENS, IDC_SIZENESW, IDC_SIZENESW,
IDC_SIZEWE, IDC_SIZEWE, IDC_NO, IDC_SIZEWE, IDC_SIZEWE,
IDC_SIZENESW, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZENWSE,
IDC_SIZENESW, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZENWSE
};
static const char *ShearCursors[25]=
{
IDC_NO, IDC_SIZEWE, IDC_SIZEWE, IDC_SIZEWE, IDC_NO,
IDC_SIZENS, IDC_NO, IDC_SIZEWE, IDC_NO, IDC_SIZENS,
IDC_SIZENS, IDC_SIZENS, IDC_NO, IDC_SIZENS, IDC_SIZENS,
IDC_SIZENS, IDC_NO, IDC_SIZEWE, IDC_NO, IDC_SIZENS,
IDC_NO, IDC_SIZEWE, IDC_SIZEWE, IDC_SIZEWE, IDC_NO
};
const char *WhichCursor = NULL;
int CursorIndex;
assert ((Tool == ID_TOOLS_BRUSH_SCALEBRUSH) || (Tool == ID_TOOLS_BRUSH_SHEARBRUSH));
// Determine where the cursor is on the box surrounding the selected brush,
// and set the appropriate cursor.
if (pMousePos->x < 0 || pMousePos->y < 0)
{
return;
}
CursorIndex = GetCursorBoxPos (pMousePos);
switch (Tool)
{
case ID_TOOLS_BRUSH_SCALEBRUSH :
// Scaling it's just a simple lookup
WhichCursor = SizeCursors [CursorIndex];
break;
case ID_TOOLS_BRUSH_SHEARBRUSH :
WhichCursor = ShearCursors[CursorIndex];
break;
default :
assert (0);
break;
}
SetCursor (AfxGetApp()->LoadStandardCursor (WhichCursor));
}
void CFusionView::Pan
(
CFusionDoc *pDoc,
int dx, int dy,
const geVec3d *dv,
BOOL LButtonIsDown,
BOOL RButtonIsDown
)
{
if(mViewIs3d)
{
geVec3d MoveVec;
if(LButtonIsDown && RButtonIsDown)
{
geVec3d_Set (&MoveVec, (float)-dx, (float)-dy, 0.0f);
Render_MoveCamPos( VCam, &MoveVec ) ;
pDoc->UpdateCameraEntity( VCam ) ;
}
else if (LButtonIsDown)
{
geVec3d_Set (&MoveVec, 0.0f, 0.0f, (float)-dy);
Render_MoveCamPos( VCam, &MoveVec ) ;
if (Render_UpIsDown (VCam))
{
Render_IncrementYaw (VCam, (float)(-dx));
}
else
{
Render_IncrementYaw(VCam, (float)dx);
}
pDoc->UpdateCameraEntity( VCam ) ;
}
else if (RButtonIsDown)
{
if (Render_UpIsDown (VCam))
{
Render_IncrementYaw (VCam, (float)(-dx));
}
else
{
Render_IncrementYaw(VCam, (float)dx);
}
Render_IncrementPitch(VCam, (float)dy);
pDoc->UpdateCameraEntity( VCam ) ;
}
}
else
{
geVec3d dcamv;
geVec3d_Scale (dv, -1.0f, &dcamv);
if (LButtonIsDown)
{
Render_MoveCamPosOrtho(VCam, &dcamv);
}
else if (RButtonIsDown)
{
Render_ZoomChange(VCam, -(((float)dy) * 0.001f));
pDoc->UpdateGridInformation ();
}
}
}
void CFusionView::ScaleSelected (CFusionDoc *pDoc, int dx, int dy)
{
//smooth out the zoom scale curve with a scalar
float ZoomInv =Render_GetZoom(VCam);
ZoomInv =(ZoomInv > .5)? 0.5f / ZoomInv : 1.0f;
// negated here because Brush_Resize is still thinking weird
pDoc->ResizeSelected (-(((float)dx)*ZoomInv), -(((float)dy)*ZoomInv), sides, Render_GetInidx(VCam));
}
void CFusionView::ShearSelected (CFusionDoc *pDoc, int dx, int dy)
{
//smooth out the zoom scale curve with a scalar
float ZoomInv =Render_GetZoom(VCam);
ZoomInv =(ZoomInv > .5)? 0.5f / ZoomInv : 1.0f;
pDoc->ShearSelected(-(((float)dy)*ZoomInv), -(((float)dx)*ZoomInv), sides, Render_GetInidx(VCam));
}
#pragma warning (disable:4100)
void CFusionView::OnMouseMove (UINT nFlags, CPoint point)
{
int dx, dy;
geVec3d sp, wp, dv;
CFusionDoc *pDoc;
geBoolean ShiftHeld;
geBoolean ControlHeld;
geBoolean LButtonIsDown, RButtonIsDown;
geBoolean SpaceHeld;
BOOL ThisIsCaptured;
int ModeTool, Tool;
fdocAdjustEnum AdjustMode;
BOOL DoRedraw = TRUE;
POINT RealCursorPosition;
pDoc =GetDocument();
ThisIsCaptured = (this == GetCapture ());
ModeTool = GetModeTool ();
Tool = GetTool ();
AdjustMode = GetAdjustMode ();
/*
You'll notice here that we don't use the nFlags parameter to get these
settings. Those flags tell what the state of things was when the
MouseMove message was received, which could have been several seconds
ago (due to delays caused by a mashed key, for example). What we're
really interested is the current state, so we can throw out old messages.
*/
ShiftHeld = IsKeyDown (VK_SHIFT);
ControlHeld = IsKeyDown (VK_CONTROL);
LButtonIsDown = IsKeyDown (VK_LBUTTON);
RButtonIsDown = IsKeyDown (VK_RBUTTON);
SpaceHeld = IsKeyDown (VK_SPACE);
IsPanning =((SpaceHeld || IsPanning) &&
(LButtonIsDown | RButtonIsDown) && ThisIsCaptured);
if (!ThisIsCaptured)
{
// Mouse isn't captured. So we're just moving the mouse around
// in this view. If we're not in camera mode and not panning,
// then set the cursor accordingly and exit.
if(!((ModeTool == ID_TOOLS_CAMERA) || IsPanning))
{
int Tool;
Tool = GetTool ();
if (mViewIs3d)
{
if (ShiftHeld)
{
SetCursor (AfxGetApp()->LoadCursor (IDC_EYEDROPPER));
}
else
{
SetCursor (AfxGetApp()->LoadStandardCursor (IDC_ARROW));
}
}
else if ((Tool == ID_TOOLS_BRUSH_SCALEBRUSH) || (Tool == ID_TOOLS_BRUSH_SHEARBRUSH))
{
SetEditCursor (Tool, &point);
}
}
return;
}
if(this==GetParentFrame()->GetActiveView())
{
pDoc->mActiveView =mViewType;
}
/*
The point parameter to this message gives us the mouse position when the
message was received. That could be old. We really want the *current*
position, so we get it here and convert it to client coordinates. This
prevents the panning runaway bug that plauged us for so long.
*/
::GetCursorPos (&RealCursorPosition);
ScreenToClient (&RealCursorPosition);
dx = (RealCursorPosition.x - mStartPoint.x);
dy = (RealCursorPosition.y - mStartPoint.y);
if ((dx == 0) && (dy == 0)) // don't do anything if no delta
{
return;
}
Render_ViewToWorld(VCam, mStartPoint.x, mStartPoint.y, &sp);
Render_ViewToWorld(VCam, RealCursorPosition.x, RealCursorPosition.y, &wp);
geVec3d_Subtract(&wp, &sp, &dv); // delta in world space
//camera and space hold panning
if ((ModeTool == ID_TOOLS_CAMERA)||IsPanning)
{
Pan (pDoc, dx, dy, &dv, LButtonIsDown, RButtonIsDown);
}
else if (!mViewIs3d)
// none of this stuff should be available in the 3d view.
{
switch (ModeTool)
{
case ID_GENERALSELECT :
switch (Tool)
{
case CURTOOL_NONE :
// no tool selected. We're doing a drag select or clone operation
if (AdjustMode == ADJUST_MODE_BRUSH)
{
// drag select or cloning
if( IsDragging )
{
mDragCurrentPoint.x += (long)dx ;
mDragCurrentPoint.y += (long)dy ;
}
else if( !IsCopying && !ShiftHeld && !RButtonIsDown )
{
#pragma message ("Logic flawed here when space being held. Don't know exactly what.")
if((abs(dx) > mCX_DRAG) || (abs(dy) > mCY_DRAG))
{
mDragCurrentPoint = RealCursorPosition;
IsDragging = TRUE ;
}
}// Drag Select
else
{ // Begin a copy operation
if((LButtonIsDown && ShiftHeld)&&(!IsCopying))
{
IsCopying =TRUE;
pDoc->CopySelectedBrushes();
if (SelBrushList_GetSize (pDoc->pSelBrushes) > 0)
{
// make current brush point to first brush in list
// so we can snap correctly.
pDoc->CurBrush = SelBrushList_GetBrush (pDoc->pSelBrushes, 0);
}
}
if(IsCopying)
{
LockAxis( &dv ) ;
if(LButtonIsDown)
{
pDoc->MoveSelectedClone(&dv);
}
SetTool(CURTOOL_NONE);
}
}// Not Drag Select
}
break;
case ID_TOOLS_BRUSH_MOVEROTATEBRUSH :
// moving/rotating brushes and entities
SetTool(ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES);
if (LButtonIsDown)
{
LockAxis( &dv ) ;
pDoc->MoveSelectedBrushes(&dv);
}// LButtonDown
if (RButtonIsDown)
{
if( pDoc->GetSelState() == ONEENTITYONLY ) // Angle,Arc,Radius control
{
if( !ShiftHeld && !ControlHeld )
{
pDoc->AdjustEntityAngle( VCam, (float)dx ) ;
}
else if( ShiftHeld && !ControlHeld )
{
pDoc->AdjustEntityArc( VCam, (float)dx ) ;
}
else if( !ShiftHeld && ControlHeld )
{
pDoc->AdjustEntityRadius( &dv ) ;
}
}
else
{
Render_ViewDeltaToRotation (VCam, (float)dx, &dv);
pDoc->RotateSelectedBrushes(&dv);
}
}// RButtonDown
SetTool(ID_TOOLS_BRUSH_MOVEROTATEBRUSH);
break;
case ID_TOOLS_BRUSH_SCALEBRUSH :
if (LButtonIsDown)
{
LockAxisView (&dx, &dy);
ScaleSelected (pDoc, dx, dy);
}
break;
case ID_TOOLS_BRUSH_SHEARBRUSH :
if (LButtonIsDown)
{
LockAxisView (&dx, &dy);
ShearSelected (pDoc, dx, dy);
}
break;
default :
DoRedraw = FALSE;
break;
}
break;
case ID_TOOLS_TEMPLATE :
switch (Tool)
{
case ID_TOOLS_BRUSH_MOVEROTATEBRUSH :
if (LButtonIsDown)
{
LockAxis (&dv);
pDoc->MoveTemplateBrush(&dv);
}
else if (RButtonIsDown)
{
Render_ViewDeltaToRotation (VCam, (float)dx, &dv);
pDoc->RotateTemplateBrush(&dv);
}
break;
case ID_TOOLS_BRUSH_SCALEBRUSH :
if (LButtonIsDown)
{
LockAxisView (&dx, &dy);
ScaleSelected (pDoc, dx, dy);
}
break;
case ID_TOOLS_BRUSH_SHEARBRUSH :
if (LButtonIsDown)
{
LockAxisView (&dx, &dy);
ShearSelected (pDoc, dx, dy);
}
break;
default :
DoRedraw = FALSE;
break;
}
break;
default :
DoRedraw = FALSE;
break;
} // Mode Tool
}// Ortho Views
if (DoRedraw)
{
RedrawWindow();
}
POINT pt = mStartPoint; // The position works on the delta mStartPoint...
ClientToScreen( &pt ) ;
SetCursorPos( pt.x, pt.y );
}
#pragma warning (default:4100)
// Snaps the closest edge to SnapSize.
static float ComputeSnap (float Cur, float Delta, float SnapSize)
{
float Target;
float SnapDelta;
float Remainder;
Target = Cur + Delta;
Remainder = (float)fmod (Target, SnapSize);
if (fabs (Remainder) < (SnapSize / 2.0f))
{
SnapDelta = -Remainder;
}
else
{
if (Target < 0.0f)
{
SnapDelta = -(SnapSize + Remainder);
}
else
{
SnapDelta = SnapSize - Remainder;
}
}
return SnapDelta;
}
static float SnapSide (float CurMin, float CurMax, float Delta, float SnapSize)
{
float MinDelta, MaxDelta;
MinDelta = ComputeSnap (CurMin, Delta, SnapSize);
MaxDelta = ComputeSnap (CurMax, Delta, SnapSize);
return (fabs (MinDelta) < fabs (MaxDelta)) ? MinDelta : MaxDelta;
}
void CFusionView::DoneMovingBrushes ()
{
CFusionDoc *pDoc = GetDocument ();
int ModeTool = GetModeTool ();
if (SelBrushList_GetSize (pDoc->pSelBrushes) > 0 || ModeTool == ID_TOOLS_TEMPLATE)
{
geFloat fSnapSize ;
const geVec3d *vMin, *vMax;
const Box3d *pBox;
geVec3d SnapDelta;
geBoolean SnapX, SnapY, SnapZ;
fSnapSize = 1.0f;
if (Level_UseGrid (pDoc->pLevel))
{
fSnapSize = Level_GetGridSnapSize (pDoc->pLevel);
}
// do the snap thing...
pBox = Brush_GetBoundingBox (pDoc->CurBrush);
vMin = Box3d_GetMin (pBox);
vMax = Box3d_GetMax (pBox);
geVec3d_Clear (&SnapDelta);
/*
In template mode, the brush is moved directly, so we have to snap to
the current position, not current position plus delta. Since we
clear the delta before computing the snap, we have to save these
flags.
*/
SnapX = (pDoc->FinalPos.X != 0.0f);
SnapY = (pDoc->FinalPos.Y != 0.0f);
SnapZ = (pDoc->FinalPos.Z != 0.0f);
if ((ModeTool == ID_TOOLS_TEMPLATE) || IsCopying)
{
geVec3d_Clear (&pDoc->FinalPos);
}
if (SnapX)
{
SnapDelta.X = ::SnapSide (vMin->X, vMax->X, pDoc->FinalPos.X, fSnapSize);
}
if (SnapY)
{
SnapDelta.Y = ::SnapSide (vMin->Y, vMax->Y, pDoc->FinalPos.Y, fSnapSize);
}
if (SnapZ)
{
SnapDelta.Z = ::SnapSide (vMin->Z, vMax->Z, pDoc->FinalPos.Z, fSnapSize);
}
if (ModeTool == ID_TOOLS_TEMPLATE)
{
pDoc->FinalPos = SnapDelta;
}
else
{
geVec3d_Add (&pDoc->FinalPos, &SnapDelta, &pDoc->FinalPos);
}
}
pDoc->DoneMove ();
pDoc->UpdateSelected();
if ((ModeTool == ID_TOOLS_TEMPLATE) ||
((pDoc->GetSelState() & ANYENTITY) && (!(pDoc->GetSelState() & ANYBRUSH))) )
{
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL );
}
else
{
pDoc->UpdateAllViews( UAV_ALL3DVIEWS | REBUILD_QUICK, NULL );
}
}
#pragma warning (disable:4100)
void CFusionView::OnLButtonUp(UINT nFlags, CPoint point)
{
BOOL bWasCaptured = FALSE ;
CFusionDoc* pDoc;
int ModeTool;
int Tool;
fdocAdjustEnum AdjustMode;
ModeTool = GetModeTool ();
Tool = GetTool ();
pDoc = GetDocument ();
AdjustMode = GetAdjustMode ();
LMouseButtonDown = GE_FALSE;
if (!RMouseButtonDown)
{
// right mouse button isn't down
if(this == GetCapture ())
{
bWasCaptured = TRUE ;
ReleaseCapture();
}
if (IsKeyDown (VK_SPACE) || IsPanning || ModeTool == ID_TOOLS_CAMERA)
{
/*
Ok, here's the scoop.
If we're in the middle of a move/rotate and the user mashes the space bar,
we all of a sudden end up in panning mode with no context information to
tell us that we were previously moving/rotating. So we end up with the
original brushes in the world, and the temporary brushes that are selected
and being moved also in the world. So here we do a TempDeleteSelected to
remove those temporary brushes. Otherwise they'd hang around forever.
Ideally, the move/rotate would be separated from the panning so that we could
move and pan at the same time. Of course, I'd like to get rid of the whole
temp selected thing, too, but that'll have to wait...
*/
pDoc->TempDeleteSelected();
IsPanning = FALSE;
ShowTheCursor ();
RedrawWindow();
return;
}
if (mViewIs3d)
{
if(ModeTool==ID_TOOLS_TEMPLATE && pDoc->TempEnt)
{
pDoc->PlaceTemplateEntity3D(point, VCam);
}
else if (IsKeyDown (VK_SHIFT))
{
pDoc->SelectTextureFromFace3D (point, VCam);
}
else
{
switch (AdjustMode)
{
case ADJUST_MODE_BRUSH :
case ADJUST_MODE_FACE :
pDoc->SelectRay (point, VCam);
pDoc->UpdateAllViews (UAV_ALL3DVIEWS, NULL);
break;
default :
break;
}
}
}
else
{
switch (Tool)
{
case CURTOOL_NONE :
if (AdjustMode == ADJUST_MODE_BRUSH)
{
if( IsDragging )
{
pDoc->SelectOrthoRect( mDragStartPoint, mDragCurrentPoint, VCam );
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
IsDragging = FALSE ;
}
else if(IsCopying)
{
DoneMovingBrushes ();
IsCopying = FALSE;
}
else
{
pDoc->SelectOrtho(point, VCam);
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL );
}
}
else
{
MessageBeep ((UINT)(-1));
}
break;
case ID_TOOLS_BRUSH_MOVEROTATEBRUSH :
case ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES :
DoneMovingBrushes ();
break;
case ID_TOOLS_BRUSH_SCALEBRUSH :
SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
pDoc->SnapScaleNearest(sides, Render_GetInidx(VCam), VCam);
if(pDoc->mLastOp == BRUSH_SCALE)
{
pDoc->DoneResize(sides, Render_GetInidx(VCam));
}
pDoc->UpdateSelected();
if((ModeTool == ID_TOOLS_TEMPLATE) ||
((pDoc->GetSelState() & ANYENTITY) && (!(pDoc->GetSelState() & ANYBRUSH))) )
{
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL );
}
else
{
pDoc->UpdateAllViews( UAV_ALL3DVIEWS | REBUILD_QUICK, NULL );
}
break;
case ID_TOOLS_BRUSH_SHEARBRUSH :
SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
if(pDoc->mLastOp==BRUSH_SHEAR)
pDoc->DoneShear(sides, Render_GetInidx(VCam));
pDoc->UpdateSelected();
if((ModeTool == ID_TOOLS_TEMPLATE) ||
((pDoc->GetSelState() & ANYENTITY) && (!(pDoc->GetSelState() & ANYBRUSH))) )
{
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL );
}
else
{
pDoc->UpdateAllViews( UAV_ALL3DVIEWS | REBUILD_QUICK, NULL );
}
break;
default :
break;
}
}
if( bWasCaptured )
{
ClientToScreen( &mStartPoint ) ;
SetCursorPos( mStartPoint.x, mStartPoint.y ) ;
}
ShowTheCursor ();
}
assert( IsCopying == FALSE ) ;
}
#pragma warning (default:4100)
#pragma warning (disable:4100)
void CFusionView::OnLButtonDown(UINT nFlags, CPoint point)
{
/*
These tables convert the index values returned by GetCursorBoxPos
into the bitmapped values expected by the brush routines (the "sides" values).
These sides values are encode the cursor's position in relation to the box
using this:
4
----------
| |
1 | | 2
| |
| |
----------
8
So the cursor in the top-left corner of the box will be 5 (left+top = 1+4 = 5).
*/
static const int SideLookup[25] =
{
5, 5, 4, 6, 6,
5, 5, 4, 6, 6,
1, 1, 0, 2, 2,
9, 9, 8, 10, 10,
9, 9, 8, 10, 10
};
static const int SideLookupShear[25] =
{
0, 4, 4, 4, 0,
1, 0, 4, 0, 2,
1, 1, 0, 2, 2,
1, 0, 8, 0, 2,
0, 8, 8, 8, 0
};
int Tool = GetTool ();
int ModeTool = GetModeTool ();
// int AdjustMode = GetAdjustMode ();
CFusionDoc* pDoc = GetDocument();
LMouseButtonDown = GE_TRUE;
geBoolean SpaceIsDown = IsKeyDown (VK_SPACE);
assert( IsCopying == FALSE ) ;
if (!RMouseButtonDown)
{
/*
if ((mViewIs3d == FALSE) && (AdjustMode == ADJUST_MODE_FACE))
{
::MessageBeep( (uint32)-1 ) ;
return ;
}
*/
SetCapture();
HideTheCursor ();
mStartPoint = point;
if (mViewIs3d || IsPanning || SpaceIsDown)
return ;
if ((Tool == CURTOOL_NONE))// && (ModeTool == ID_GENERALSELECT) && (AdjustMode == ADJUST_MODE_BRUSH))
{
mDragStartPoint = point ; // Drag mode is initiated in MouseMove
mDragCurrentPoint = point ;
}// Drag Select
else if (mViewIs3d == FALSE)
{
int CursorSide;
CursorSide = GetCursorBoxPos (&point);
if (Tool == ID_TOOLS_BRUSH_SHEARBRUSH)
{
sides = SideLookupShear[CursorSide];
}
else
{
sides = SideLookup[CursorSide];
}
if(Tool == ID_TOOLS_BRUSH_SCALEBRUSH)
{
pDoc->ScaleNum =0;
geVec3d_Set (&pDoc->FinalScale, 1.0f, 1.0f, 1.0f);
pDoc->TempCopySelectedBrushes();
}
else if(Tool == ID_TOOLS_BRUSH_SHEARBRUSH)
{
pDoc->ScaleNum =0;
geVec3d_Clear (&pDoc->FinalScale);
if (ModeTool == ID_TOOLS_TEMPLATE)
{
pDoc->TempShearTemplate =Brush_Clone(pDoc->CurBrush);
}
else
{
pDoc->TempCopySelectedBrushes();
}
}
else if ((Tool == ID_TOOLS_BRUSH_MOVEROTATEBRUSH) || (Tool == ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES))
{
geVec3d_Clear (&pDoc->FinalPos);
pDoc->TempCopySelectedBrushes();
}
}// Not Drag-select
}// LButtonDown only
}
#pragma warning (default:4100)
#pragma warning (disable:4100)
void CFusionView::OnRButtonDown(UINT nFlags, CPoint point)
{
CFusionDoc* pDoc = GetDocument();
geBoolean SpaceIsDown = IsKeyDown (VK_SPACE);
RMouseButtonDown = GE_TRUE;
if (!LMouseButtonDown)
{
int Tool;
SetCapture();
HideTheCursor ();
mStartPoint = point;
if (mViewIs3d || IsPanning || SpaceIsDown)
return ;
Tool = GetTool ();
if ((Tool == ID_TOOLS_BRUSH_MOVEROTATEBRUSH) || (Tool == ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES))
{
geVec3d_Set (&(pDoc->FinalRot), 0.0f, 0.0f, 0.0f);
pDoc->TempCopySelectedBrushes();
}
}
}
#pragma warning (default:4100)
#pragma warning (disable:4100)
void CFusionView::OnRButtonUp(UINT nFlags, CPoint point)
{
int Tool = GetTool ();
RMouseButtonDown = GE_FALSE;
if (!LMouseButtonDown)
{
CFusionDoc* pDoc = GetDocument();
if(this==GetCapture())
{
ReleaseCapture();
}
if((IsKeyDown (VK_SPACE)) || IsPanning || GetModeTool()==ID_TOOLS_CAMERA)
{
pDoc->TempDeleteSelected();
IsPanning =FALSE;
ShowTheCursor ();
RedrawWindow();
return;
}
ShowTheCursor ();
if (!mViewIs3d)
{
if ((Tool == ID_TOOLS_BRUSH_MOVEROTATEBRUSH) || (Tool == ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES))
{
pDoc->UpdateSelected();
if (GetModeTool () == ID_GENERALSELECT)
{
pDoc->DoneRotate ();
}
}
if (SelBrushList_GetSize (pDoc->pSelBrushes) != 0)
pDoc->UpdateAllViews(UAV_ALL3DVIEWS | REBUILD_QUICK, NULL);
else
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
}
assert( IsCopying == FALSE ) ;
}
#pragma warning (disable:4100)
void CFusionView::OnDraw(CDC *c)
{
CFusionDoc* pDoc = GetDocument();
switch(mViewType)
{
case ID_VIEW_TEXTUREVIEW:
case ID_VIEW_3DWIREFRAME:
//don't draw before texinfos are valid
if(Render_GetWadSizes(VCam))
{
pDoc->RenderWorld(VCam, c);
}
if(pDoc->IsLeakFileLoaded() && pDoc->bShowLeakFinder())
{
DrawLeakPoints3D(c->m_hDC, pDoc->GetLeakPoints(), pDoc->GetNumLeakPoints());
}
break;
case ID_VIEW_TOPVIEW:
case ID_VIEW_SIDEVIEW:
case ID_VIEW_FRONTVIEW:
pDoc->RenderOrthoView(VCam, c);
if(pDoc->IsLeakFileLoaded() && pDoc->bShowLeakFinder())
{
DrawLeakPoints(c->m_hDC, pDoc->GetLeakPoints(), pDoc->GetNumLeakPoints());
}
break;
}
int bkMode=c->GetBkMode();
int oldColor;
c->SetBkMode(TRANSPARENT);
if(this==GetParentFrame()->GetActiveView())
{
RECT r ;
GetClientRect( &r ) ; // This seemed to be more accurate, it shouldn't be...
CBrush RedBrush( RGB(255,0,0) ) ;
c->FrameRect( &r, &RedBrush );
oldColor=c->SetTextColor(RGB(255,255,255));
}
else
{
oldColor=c->SetTextColor(RGB(205,205,205));
}
switch( mViewType ) {
case ID_VIEW_TEXTUREVIEW:
c->TextOut(4,4,"Textured",8);
break;
case ID_VIEW_3DWIREFRAME:
c->TextOut(4,4,"Wireframe",9);
break;
case ID_VIEW_TOPVIEW:
c->TextOut(4,4,"Top",3);
break;
case ID_VIEW_SIDEVIEW:
c->TextOut(4,4,"Side",4);
break;
case ID_VIEW_FRONTVIEW:
c->TextOut(4,4,"Front",5);
break;
}
c->SetBkMode(bkMode);
c->SetTextColor(oldColor);
if( IsDragging && this==GetCapture() )
{
// DrawDragRect here just didn't show up against our grid...
CBrush SelBrush ;
SelBrush.CreateSolidBrush( RGB(0,255,255) );
CRect NewRect(mDragStartPoint, mDragCurrentPoint );
NewRect.NormalizeRect();
c->FrameRect( &NewRect, &SelBrush ) ;
}
}
void CFusionView::OnInitialUpdate()
{
RECT r;
CFusionDoc* pDoc = (CFusionDoc*) GetDocument();
SizeInfo *WadSizeInfos = Level_GetWadSizeInfos (pDoc->pLevel);
int iView;
CView::OnInitialUpdate();
GetClientRect(&r);
if(WadSizeInfos)
{
Render_SetWadSizes(VCam, WadSizeInfos);
Render_ResetSettings(VCam, r.right, r.bottom);
}
switch(mViewType)
{
case ID_VIEW_TEXTUREVIEW:
Render_SetViewType(VCam, VIEWTEXTURE);
iView = 0;
break;
case ID_VIEW_3DWIREFRAME:
Render_SetViewType(VCam, VIEWWIRE);
iView = 0;
break;
case ID_VIEW_TOPVIEW:
Render_SetViewType(VCam, VIEWTOP);
iView = 1;
break;
case ID_VIEW_SIDEVIEW:
Render_SetViewType(VCam, VIEWSIDE);
iView = 3;
break;
case ID_VIEW_FRONTVIEW:
Render_SetViewType(VCam, VIEWFRONT);
iView = 2;
break;
default :
iView = -1;
break;
}
GetParentFrame()->SetWindowText(pDoc->GetTitle());
if (iView != -1)
{
// Update view state information that was saved in level
ViewStateInfo *pViewStateInfo;
pViewStateInfo = Level_GetViewStateInfo (pDoc->pLevel, iView);
if (pViewStateInfo->IsValid)
{
Render_SetZoom (VCam, pViewStateInfo->ZoomFactor);
Render_SetPitchRollYaw (VCam, &pViewStateInfo->PitchRollYaw);
Render_SetCameraPos (VCam, &pViewStateInfo->CameraPos);
}
}
pDoc->UpdateGridInformation ();
// pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL );
}
/////////////////////////////////////////////////////////////////////////////
// CFusionView construction/destruction
CFusionView::CFusionView()
{
VCam =Render_AllocViewVars();
Render_SetWadSizes(VCam, NULL);
mStartPoint.x=mStartPoint.y=0;
mViewType = ID_VIEW_NEW;
IsDragging = IsCopying = IsPanning = FALSE;
LMouseButtonDown = GE_FALSE;
RMouseButtonDown = GE_FALSE;
mCY_DRAG = ::GetSystemMetrics( SM_CYDRAG ) ;
mCX_DRAG = ::GetSystemMetrics( SM_CXDRAG ) ;
}
CFusionView::~CFusionView()
{
Render_FreeViewVars(VCam);
if (VCam != NULL)
{
geRam_Free (VCam);
}
}
BOOL CFusionView::PreCreateWindow(CREATESTRUCT& cs)
{
//get rid of default cursor
cs.lpszClass = AfxRegisterWndClass( CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW,
NULL, (HBRUSH)GetStockObject(GRAY_BRUSH));
return CView::PreCreateWindow(cs);
}
CFusionDoc* CFusionView::GetDocument()
{
CFusionDoc *pDoc;
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFusionDoc)));
pDoc = (CFusionDoc *)m_pDocument;
ASSERT_VALID (pDoc);
return pDoc;
}
void CFusionView::OnSize(UINT nType, int cx, int cy)
{
CFusionDoc* pDoc = GetDocument();
SizeInfo *WadSizeInfos = Level_GetWadSizeInfos (pDoc->pLevel);
// call our oldself
CView::OnSize(nType, cx, cy);
// make sure that our camera knows our current size
if(WadSizeInfos)
{
Render_SetWadSizes(VCam, WadSizeInfos);
Render_ResizeView (VCam, cx, cy);
}
}
void CFusionView::OnToolsCamera()
{
CFusionDoc* pDoc = GetDocument();
SetModeTool(ID_TOOLS_CAMERA);
pDoc->ConfigureCurrentTool();
pDoc->mpMainFrame->m_wndTabControls->m_pBrushEntityDialog->Update(pDoc);
}
void CFusionView::OnUpdateToolsCamera(CCmdUI* pCmdUI)
{
if( GetModeTool() == ID_TOOLS_CAMERA )
pCmdUI->SetCheck();
else
pCmdUI->SetCheck(0);
}
void CFusionView::OnAxisX()
{
CFusionDoc* pDoc = GetDocument();
pDoc->SetLockAxis( pDoc->GetLockAxis() ^ AXIS_X ) ;
}
void CFusionView::OnUpdateAxisX(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
if( pDoc->GetLockAxis() & AXIS_X )
pCmdUI->SetCheck();
else
pCmdUI->SetCheck(0);
}
void CFusionView::OnAxisY()
{
CFusionDoc* pDoc = GetDocument();
pDoc->SetLockAxis( pDoc->GetLockAxis() ^ AXIS_Y ) ;
}
void CFusionView::OnUpdateAxisY(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
if( pDoc->GetLockAxis() & AXIS_Y )
pCmdUI->SetCheck();
else
pCmdUI->SetCheck(0);
}
void CFusionView::OnAxisZ()
{
CFusionDoc* pDoc = GetDocument();
pDoc->SetLockAxis( pDoc->GetLockAxis() ^ AXIS_Z ) ;
}
void CFusionView::OnUpdateAxisZ(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
if( pDoc->GetLockAxis() & AXIS_Z )
pCmdUI->SetCheck();
else
pCmdUI->SetCheck(0);
}
void CFusionView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView)
{
CFusionDoc* pDoc = GetDocument();
CView::OnActivateView(bActivate, pActivateView, pDeactiveView);
// set our title
GetParentFrame()->SetWindowText(pDoc->GetTitle());
// make sure the bar is updated for our doc.
CMainFrame* pFrame = (CMainFrame*)AfxGetMainWnd();
// If the application terminates after running a command line
// request, we don't want to update this combo box...
if( pFrame->IsDestroyingApp )
pFrame->LoadComboBox();
}
void CFusionView::OnToolsBrushMoverotatebrush()
{
CFusionDoc* pDoc = GetDocument();
int mode=GetModeTool();
if(mode==ID_TOOLS_TEMPLATE)
{
SetTool( ID_TOOLS_BRUSH_MOVEROTATEBRUSH );
pDoc->ConfigureCurrentTool();
}
else
{
if(GetTool()==ID_TOOLS_BRUSH_MOVEROTATEBRUSH)
{
SetTool(CURTOOL_NONE);
SetAdjustMode (ADJUST_MODE_BRUSH);
}
else
{
SetTool(ID_TOOLS_BRUSH_MOVEROTATEBRUSH);
}
pDoc->ConfigureCurrentTool();
}
}
void CFusionView::OnUpdateToolsBrushMoverotatebrush(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
//that's a pretty big if
if(GetModeTool()==ID_TOOLS_TEMPLATE ||
(GetModeTool()==ID_GENERALSELECT &&
GetAdjustMode()==ADJUST_MODE_BRUSH &&
pDoc->GetSelState()!=NOSELECTIONS))
{
pCmdUI->Enable();
if(GetTool()==ID_TOOLS_BRUSH_MOVEROTATEBRUSH)
{
pCmdUI->SetCheck();
}
else
{
pCmdUI->SetCheck(0);
}
}
else
{
pCmdUI->Enable(0);
pCmdUI->SetCheck(0);
}
}
void CFusionView::OnToolsBrushScalebrush()
{
CFusionDoc* pDoc = GetDocument();
int mode=GetModeTool();
if(mode==ID_TOOLS_TEMPLATE)
{
SetTool(ID_TOOLS_BRUSH_SCALEBRUSH);
pDoc->ConfigureCurrentTool();
}
else
{
if(GetTool()==ID_TOOLS_BRUSH_SCALEBRUSH)
{
SetTool(CURTOOL_NONE);
SetAdjustMode (ADJUST_MODE_BRUSH);
}
else
{
SetTool(ID_TOOLS_BRUSH_SCALEBRUSH);
}
pDoc->ConfigureCurrentTool();
}
}
void CFusionView::OnUpdateToolsBrushScalebrush(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
//that's a very big if
if((GetModeTool()==ID_TOOLS_TEMPLATE && !pDoc->TempEnt) ||
(GetModeTool()==ID_GENERALSELECT &&
GetAdjustMode ()==ADJUST_MODE_BRUSH &&
#pragma message ("Can't do multiple brush scaling due to Brush_Resize implementation.")
// SelBrushList_GetSize (pDoc->pSelBrushes) > 0))
SelBrushList_GetSize (pDoc->pSelBrushes) == 1))
{
pCmdUI->Enable();
if(GetTool()==ID_TOOLS_BRUSH_SCALEBRUSH)
{
pCmdUI->SetCheck();
}
else
{
pCmdUI->SetCheck(0);
}
}
else
{
pCmdUI->Enable(0);
pCmdUI->SetCheck(0);
}
}
void CFusionView::OnToolsBrushShowbrush()
{
CFusionDoc* pDoc = GetDocument();
// toggle brush
pDoc->mShowBrush ^= 1;
// redraw the screen
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
void CFusionView::OnUpdateToolsBrushShowbrush(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
pCmdUI->SetCheck (pDoc->mShowBrush);
}
BOOL CFusionView::OnEraseBkgnd(CDC* pDC)
{
CRect rect ;
// CFusionDoc* pDoc = GetDocument();
// if(!pDoc->mWorldBsp || (mViewType != ID_VIEW_TEXTUREVIEW))
if ((mViewType == ID_VIEW_TOPVIEW) || (mViewType == ID_VIEW_SIDEVIEW) || (mViewType == ID_VIEW_FRONTVIEW))
{
GetClientRect( &rect ) ;
pDC->FillSolidRect( &rect, Prefs_GetBackgroundColor (((CFusionApp *)AfxGetApp ())->GetPreferences ()));
}
return TRUE;
}
// This is the range handler for the types of view that we have
// make sure when we add more view types that we update this.
void CFusionView::OnViewType(UINT nID)
{
CFusionDoc *pDoc =GetDocument();
mViewType =nID;
SizeInfo *WadSizeInfos = Level_GetWadSizeInfos (pDoc->pLevel);
if(WadSizeInfos)
{
geVec3d SaveCameraPos;
geVec3d SaveOrientation;
geFloat ZoomFactor;
int Width, Height;
ZoomFactor = Render_GetZoom (VCam);
Render_GetCameraPos (VCam, &SaveCameraPos);
Render_GetPitchRollYaw (VCam, &SaveOrientation);
Width = Render_GetWidth (VCam);
Height = Render_GetHeight (VCam);
Render_SetWadSizes(VCam, WadSizeInfos);
Render_ResetSettings(VCam, Render_GetWidth(VCam), Render_GetHeight(VCam));
Render_ResizeView (VCam, Width, Height);
Render_SetCameraPos (VCam, &SaveCameraPos);
Render_SetPitchRollYaw (VCam, &SaveOrientation);
if (ZoomFactor != 0.0f)
{
Render_SetZoom (VCam, ZoomFactor);
}
}
switch(mViewType)
{
case ID_VIEW_TEXTUREVIEW:
Render_SetViewType(VCam, VIEWTEXTURE);
mViewIs3d = TRUE ;
break;
case ID_VIEW_3DWIREFRAME:
Render_SetViewType(VCam, VIEWWIRE);
mViewIs3d = TRUE ;
break;
case ID_VIEW_TOPVIEW:
Render_SetViewType(VCam, VIEWTOP);
mViewIs3d = FALSE ;
break;
case ID_VIEW_SIDEVIEW:
Render_SetViewType(VCam, VIEWSIDE);
mViewIs3d = FALSE ;
break;
case ID_VIEW_FRONTVIEW:
Render_SetViewType(VCam, VIEWFRONT);
mViewIs3d = FALSE ;
break;
}
pDoc->UpdateGridInformation ();
RedrawWindow();
GetParentFrame()->SetWindowText(pDoc->GetTitle());
}
void CFusionView::OnViewTypeCmdUi(CCmdUI* pCmdUI)
{
BOOL bEnable = TRUE ;
if( !mViewIs3d ) // If this is an otho view, don't allow mutate to rendered
{
if( pCmdUI->m_nID == ID_VIEW_TEXTUREVIEW ||
pCmdUI->m_nID == ID_VIEW_3DWIREFRAME )
bEnable = FALSE ;
}
else // If this is a rendered view, don't allow mutate to ortho
{
if( pCmdUI->m_nID == ID_VIEW_TOPVIEW ||
pCmdUI->m_nID == ID_VIEW_SIDEVIEW ||
pCmdUI->m_nID == ID_VIEW_FRONTVIEW )
bEnable = FALSE ;
}
if( mViewType == pCmdUI->m_nID )
pCmdUI->SetCheck();
else
pCmdUI->SetCheck(0);
pCmdUI->Enable( bEnable ) ;
}
void CFusionView::SetTitle()
{
switch(mViewType)
{
case ID_VIEW_NEW:
GetParentFrame()->SetWindowText("-Creating New View-");
break;
case ID_VIEW_3DWIREFRAME:
GetParentFrame()->SetWindowText("-3D Wireframe-");
break;
case ID_VIEW_TEXTUREVIEW:
GetParentFrame()->SetWindowText("-Texture View-");
break;
case ID_VIEW_TOPVIEW:
GetParentFrame()->SetWindowText("-Top View-");
break;
case ID_VIEW_FRONTVIEW:
GetParentFrame()->SetWindowText("-Front View-");
break;
case ID_VIEW_SIDEVIEW:
GetParentFrame()->SetWindowText("-Side View-");
break;
}
}
void CFusionView::OnToolsBrushShearbrush()
{
CFusionDoc* pDoc = GetDocument();
int mode=GetModeTool();
if(mode==ID_TOOLS_TEMPLATE)
{
SetTool( ID_TOOLS_BRUSH_SHEARBRUSH);
pDoc->ConfigureCurrentTool();
}
else
{
if(GetTool()==ID_TOOLS_BRUSH_SHEARBRUSH)
{
SetTool(CURTOOL_NONE);
SetAdjustMode (ADJUST_MODE_BRUSH);
}
else
{
SetTool(ID_TOOLS_BRUSH_SHEARBRUSH);
}
pDoc->ConfigureCurrentTool();
}
}
void CFusionView::OnUpdateToolsBrushShearbrush(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
//that's a very big if
if((GetModeTool()==ID_TOOLS_TEMPLATE && !pDoc->TempEnt) ||
(GetModeTool()==ID_GENERALSELECT &&
GetAdjustMode()==ADJUST_MODE_BRUSH &&
#pragma message ("Can't do multiple brush shear due to Brush_Shear implementation.")
SelBrushList_GetSize (pDoc->pSelBrushes) == 1))
// SelBrushList_GetSize (pDoc->pSelBrushes) > 0))
{
pCmdUI->Enable();
if(GetTool()==ID_TOOLS_BRUSH_SHEARBRUSH)
{
pCmdUI->SetCheck();
}
else
{
pCmdUI->SetCheck(0);
}
}
else
{
pCmdUI->Enable(0);
pCmdUI->SetCheck(0);
}
}
int CFusionView::GetTool(void)
{
CFusionDoc* pDoc = GetDocument();
return pDoc->mCurrentTool;
}
fdocAdjustEnum CFusionView::GetAdjustMode(void)
{
CFusionDoc* pDoc = GetDocument();
return pDoc->mAdjustMode;
}
int CFusionView::GetModeTool(void)
{
CFusionDoc* pDoc = GetDocument();
return pDoc->mModeTool;
}
void CFusionView::SetTool(int Tool)
{
CFusionDoc* pDoc = GetDocument();
pDoc->mCurrentTool = Tool;
}
void CFusionView::SetAdjustMode(fdocAdjustEnum Mode)
{
CFusionDoc* pDoc = GetDocument();
pDoc->mAdjustMode = Mode;
}
void CFusionView::SetModeTool(int Tool)
{
CFusionDoc* pDoc = GetDocument();
pDoc->mModeTool = Tool;
}
void CFusionView::OnUpdateBrushGroupsMakenewgroup(CCmdUI* pCmdUI)
{
pCmdUI->Enable();
}
void CFusionView::OnBrushGroupsAddtogroup()
{
CFusionDoc* pDoc = GetDocument();
pDoc->AddSelToGroup() ;
pDoc->mpMainFrame->UpdateActiveDoc() ;
}
void CFusionView::OnUpdateBrushGroupsAddtogroup(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
pCmdUI->Enable (!(pDoc->GetSelState() == NOSELECTIONS));
}
void CFusionView::OnBrushRemoveselectedfromgroup()
{
CFusionDoc* pDoc = GetDocument();
pDoc->RemovesSelFromGroup() ;
pDoc->mpMainFrame->UpdateActiveDoc() ;
}/* CFusionView::OnBrushRemoveselectedfromgroup */
void CFusionView::OnUpdateBrushRemoveselectedfromgroup(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
if( (pDoc->mCurrentGroup == 0) || (pDoc->GetSelState() == NOSELECTIONS) )
pCmdUI->Enable( FALSE ) ;
else
pCmdUI->Enable( TRUE ) ;
}
void CFusionView::OnToolsBrushMoveselectedbrushes()
{
SetTool(ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES);
CFusionDoc* pDoc = GetDocument();
pDoc->ConfigureCurrentTool();
}
void CFusionView::OnUpdateToolsBrushMoveselectedbrushes(CCmdUI* pCmdUI)
{
if(GetModeTool()!=ID_TOOLS_CAMERA)
{
pCmdUI->Enable();
pCmdUI->SetCheck (GetTool () == ID_TOOLS_BRUSH_MOVESELECTEDBRUSHES);
}
else
{
pCmdUI->Enable(0);
pCmdUI->SetCheck(0);
}
}
void CFusionView::OnToolsTemplate()
{
CFusionDoc* pDoc = GetDocument();
pDoc->ResetAllSelectedEntities();
pDoc->ResetAllSelectedFaces();
pDoc->ResetAllSelectedBrushes();
SetModeTool(ID_TOOLS_TEMPLATE);
if(pDoc->TempEnt)
{
SetTool( ID_TOOLS_BRUSH_MOVEROTATEBRUSH );
}
else
{
SetTool(ID_TOOLS_BRUSH_SCALEBRUSH);
}
pDoc->SetAdjustmentMode( ADJUST_MODE_BRUSH ) ;
pDoc->ConfigureCurrentTool();
pDoc->mpMainFrame->m_wndTabControls->m_pBrushEntityDialog->Update(pDoc);
}
void CFusionView::OnUpdateToolsTemplate(CCmdUI* pCmdUI)
{
if( GetModeTool() == ID_TOOLS_TEMPLATE ) pCmdUI->SetCheck();
else pCmdUI->SetCheck(0);
}
void CFusionView::OnUpdateToolsBrushRotate45(CCmdUI* pCmdUI)
{
CFusionDoc* pDoc = GetDocument();
//that's a pretty big if
if((GetModeTool()==ID_TOOLS_TEMPLATE && !pDoc->TempEnt) ||
(GetModeTool()==ID_GENERALSELECT &&
GetAdjustMode()==ADJUST_MODE_BRUSH &&
pDoc->GetSelState()!=NOSELECTIONS))
{
pCmdUI->Enable();
}
else
{
pCmdUI->Enable(0);
}
}
void CFusionView::DrawLeakPoints(HDC ViewDC, geVec3d *LeakPoints, int NumLeakPoints)
{
POINT pnt = {0,0};
POINT nullpnt;
int i;
CPen PenRed(PS_SOLID, 1, RGB(255,0,0));
HPEN oldpen;
assert(LeakPoints != NULL);
assert(NumLeakPoints > 0);
oldpen =(HPEN)SelectObject(ViewDC, (HPEN)PenRed);
for(i=0;i < NumLeakPoints-1;i++)
{
pnt =Render_OrthoWorldToView(VCam, &LeakPoints[i]);
MoveToEx(ViewDC, pnt.x, pnt.y, &nullpnt);
pnt =Render_OrthoWorldToView(VCam, &LeakPoints[i+1]);
LineTo(ViewDC, pnt.x, pnt.y);
}
LineTo(ViewDC, pnt.x, pnt.y);
SelectObject(ViewDC, oldpen);
}
void CFusionView::DrawLeakPoints3D(HDC ViewDC, geVec3d *LeakPoints, int NumLeakPoints)
{
POINT nullpnt;
int i;
CPen PenRed(PS_SOLID, 1, RGB(255,0,0));
HPEN oldpen;
geVec3d pnt3;
assert(LeakPoints != NULL);
assert(NumLeakPoints > 0);
oldpen =(HPEN)SelectObject(ViewDC, (HPEN)PenRed);
geVec3d_Clear (&pnt3);
for(i=0;i < NumLeakPoints-1;i++)
{
pnt3 =Render_XFormVert(VCam, &LeakPoints[i]);
if(pnt3.Z < 0.0f)
continue;
MoveToEx(ViewDC, Units_Round(pnt3.X), Units_Round(pnt3.Y), &nullpnt);
pnt3 =Render_XFormVert(VCam, &LeakPoints[i+1]);
LineTo(ViewDC, Units_Round(pnt3.X), Units_Round(pnt3.Y));
}
if(pnt3.Z > 1.0f)
LineTo(ViewDC, Units_Round(pnt3.X), Units_Round(pnt3.Y));
SelectObject(ViewDC, oldpen);
}
void CFusionView::OnDeselectall()
{
CFusionDoc* pDoc = GetDocument();
pDoc->ResetAllSelections() ;
pDoc->UpdateSelected();
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL ) ;
}
void CFusionView::OnUpdateDeselectall(CCmdUI* pCmdUI)
{
BOOL bEnable ;
CFusionDoc* pDoc = GetDocument();
bEnable = ( pDoc->GetSelState() == NOSELECTIONS ) ? FALSE : TRUE ;
pCmdUI->Enable( bEnable ) ;
}
void CFusionView::OnSelectall()
{
CFusionDoc* pDoc = GetDocument();
pDoc->SelectAll () ;
pDoc->UpdateAllViews( UAV_ALL3DVIEWS, NULL ) ;
}
void CFusionView::OnUpdateSelectall(CCmdUI* pCmdUI)
{
pCmdUI->Enable( TRUE ) ;
}
LRESULT CFusionView::OnCompileMessage (WPARAM wParam, LPARAM lParam)
{
if (wParam == COMPILER_PROCESSID)
{
char *msg;
msg = (char *)lParam;
ConPrintf ("%s", msg);
geRam_Free (msg);
}
return 0;
}
LRESULT CFusionView::OnCompileError (WPARAM wParam, LPARAM lParam)
{
if (wParam == COMPILER_PROCESSID)
{
char *msg;
msg = (char *)lParam;
ConError ("%s", msg);
geRam_Free (msg);
}
return 0;
}
LRESULT CFusionView::OnCompileDone (WPARAM wParam, LPARAM lParam)
{
if (wParam == COMPILER_PROCESSID)
{
CFusionDoc *pDoc;
pDoc = GetDocument ();
if (pDoc != NULL)
{
pDoc->CompileDone ((CompilerErrorEnum)lParam);
}
}
return 0;
}
void CFusionView::OnToolsScaleworld()
{
CString szKey = "Enter world scale factor";
CString szVal;
int ModalResult;
CDialog *pEditDialog;
float scf;
CFusionDoc* pDoc = GetDocument();
pEditDialog = new CFloatKeyEditDlg(this, szKey, &szVal);
if (pEditDialog != NULL)
{
ModalResult = pEditDialog->DoModal();
delete pEditDialog;
if(ModalResult == IDOK)
{
sscanf((LPCSTR)szVal, "%f", &scf);
pDoc->ScaleWorld(scf);
}
}
}
void CFusionView::OnToolsBrushMakenewest()
{
CFusionDoc *pDoc = GetDocument ();
pDoc->MakeSelectedBrushNewest();
}
void CFusionView::OnToolsSettexturescale()
{
CFusionDoc* pDoc = GetDocument();
float scf;
CString szKey, szVal;
int ModalResult;
CDialog *pEditDialog;
szKey = "Enter texture scale for selected brushes";
szVal = "1.0";
pEditDialog = new CFloatKeyEditDlg(this, szKey, &szVal);
if (pEditDialog != NULL)
{
ModalResult = pEditDialog->DoModal();
delete pEditDialog;
if(ModalResult == IDOK)
{
sscanf((LPCSTR)szVal, "%f", &scf);
pDoc->SetAllFacesTextureScale(scf);
}
}
}
void CFusionView::OnToolsNextbrush()
{
CFusionDoc *pDoc = GetDocument ();
BrushList *BList = Level_GetBrushes (pDoc->pLevel);
if(GetModeTool()==ID_GENERALSELECT && !pDoc->IsSelectionLocked())
{
switch (pDoc->mAdjustMode)
{
case ADJUST_MODE_FACE :
{
int nSelectedFaces = SelFaceList_GetSize (pDoc->pSelFaces);
Face *pFace;
if (nSelectedFaces == 0)
{
BrushIterator bi;
pDoc->CurBrush = BrushList_GetFirst (BList, &bi);
pFace = Brush_SelectFirstFace (pDoc->CurBrush);
SelBrushList_Add (pDoc->pSelBrushes, pDoc->CurBrush);
}
else
{
Brush *pBrush;
// get first selected face
pFace = SelFaceList_GetFace (pDoc->pSelFaces, nSelectedFaces-1);
// Remove all face selections
pDoc->ResetAllSelectedFaces ();
Face_SetSelected (pFace, GE_TRUE);
pBrush = BrushList_FindTopLevelFaceParent (Level_GetBrushes (pDoc->pLevel), pFace);
// select next face
if(!Brush_SetNextSelectedFace(pBrush))
{
pFace = Brush_SelectFirstFace(pBrush);
}
else
{
pFace = Brush_GetSelectedFace (pBrush);
}
}
SelFaceList_Add (pDoc->pSelFaces, pFace);
pDoc->UpdateSelected ();
pDoc->UpdateFaceAttributesDlg ();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
break;
}
case ADJUST_MODE_BRUSH :
if(pDoc->GetSelState()&ONEBRUSH)
{
SelBrushList_RemoveAll (pDoc->pSelBrushes);
SelBrushList_Add (pDoc->pSelBrushes, Brush_GetNextBrush(pDoc->CurBrush, BList));
pDoc->UpdateSelected();
//update the brush attributes dialog...
pDoc->UpdateBrushAttributesDlg ();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
else if(!(pDoc->GetSelState() & ANYBRUSH))
{
Brush *pBrush;
BrushIterator bi;
pBrush = BrushList_GetFirst (BList, &bi);
if(pBrush != NULL)
{
SelBrushList_Add (pDoc->pSelBrushes, pBrush);
pDoc->UpdateSelected();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
}
break;
default :
assert (0); // bad adjust mode
break;
}
}
}
void CFusionView::OnToolsPrevbrush()
{
CFusionDoc *pDoc = GetDocument ();
BrushList *BList = Level_GetBrushes (pDoc->pLevel);
if(GetModeTool()==ID_GENERALSELECT && !pDoc->IsSelectionLocked())
{
switch (pDoc->mAdjustMode)
{
case ADJUST_MODE_FACE :
{
int nSelectedFaces = SelFaceList_GetSize (pDoc->pSelFaces);
Face *pFace;
if (nSelectedFaces == 0)
{
BrushIterator bi;
pDoc->CurBrush = BrushList_GetFirst (BList, &bi);
pFace = Brush_SelectFirstFace (pDoc->CurBrush);
SelBrushList_Add (pDoc->pSelBrushes, pDoc->CurBrush);
}
else
{
Brush *pBrush;
// get the last selected face
pFace = SelFaceList_GetFace (pDoc->pSelFaces, 0);
// Remove all face selections
pDoc->ResetAllSelectedFaces ();
// Select the next face in order, using selected brush list...
pBrush = BrushList_FindTopLevelFaceParent (Level_GetBrushes (pDoc->pLevel), pFace);
Face_SetSelected (pFace, GE_TRUE);
// select next face
if(!Brush_SetPrevSelectedFace(pBrush))
{
pFace = Brush_SelectLastFace(pBrush);
}
else
{
pFace = Brush_GetSelectedFace (pBrush);
}
}
SelFaceList_Add (pDoc->pSelFaces, pFace);
pDoc->UpdateSelected ();
pDoc->UpdateFaceAttributesDlg ();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
break;
}
case ADJUST_MODE_BRUSH :
if(pDoc->GetSelState()&ONEBRUSH)
{
SelBrushList_RemoveAll (pDoc->pSelBrushes);
SelBrushList_Add (pDoc->pSelBrushes, Brush_GetPrevBrush(pDoc->CurBrush, BList));
pDoc->UpdateSelected();
//update the brush attributes dialog...
pDoc->UpdateBrushAttributesDlg ();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
else if(!(pDoc->GetSelState() & ANYBRUSH))
{
Brush *pBrush;
BrushIterator bi;
pBrush = BrushList_GetLast(BList, &bi);
if (pBrush != NULL)
{
SelBrushList_Add (pDoc->pSelBrushes, pBrush);
pDoc->UpdateSelected();
pDoc->UpdateAllViews(UAV_ALL3DVIEWS, NULL);
}
}
break;
default :
assert (0); // bad adjust mode
break;
}
}
}
void CFusionView::OnToolsAddtolevel()
{
CFusionDoc *pDoc = GetDocument ();
if(GetModeTool()==ID_TOOLS_TEMPLATE)
pDoc->AddBrushToWorld();
}
void CFusionView::OnUpdateToolsAddtolevel(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
}
void CFusionView::DoZoom (float ZoomInc)
{
if (!mViewIs3d)
{
CFusionDoc *pDoc = GetDocument ();
Render_ZoomChange( VCam, ZoomInc);
pDoc->UpdateGridInformation ();
RedrawWindow();
}
}
void CFusionView::OnViewZoomin()
{
DoZoom (0.1f);
}
void CFusionView::OnUpdateViewZoomin(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
}
void CFusionView::OnViewZoomout()
{
DoZoom (-0.1f);
}
void CFusionView::OnUpdateViewZoomout(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
}
void CFusionView::HideTheCursor (void)
{
while (ShowCursor (FALSE) >= 0)
{
;
}
}
void CFusionView::ShowTheCursor (void)
{
while (ShowCursor (TRUE) < 0)
{
;
}
}
| 23.343685 | 109 | 0.664213 | [
"3d"
] |
b14b9a5b3b17a27608e36f18928b7c7e1a6395ea | 1,142 | cpp | C++ | ngraph/test/visitors/op/normalize_l2.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2022-02-10T08:05:09.000Z | 2022-02-10T08:05:09.000Z | ngraph/test/visitors/op/normalize_l2.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 40 | 2020-12-04T07:46:57.000Z | 2022-02-21T13:04:40.000Z | ngraph/test/visitors/op/normalize_l2.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2021-08-18T14:29:37.000Z | 2021-08-18T14:29:37.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/op/util/attr_types.hpp"
#include "ngraph/opsets/opset1.hpp"
#include "ngraph/opsets/opset3.hpp"
#include "ngraph/opsets/opset4.hpp"
#include "ngraph/opsets/opset5.hpp"
#include "util/visitor.hpp"
using namespace std;
using namespace ngraph;
using ngraph::test::NodeBuilder;
using ngraph::test::ValueMap;
TEST(attributes, normalize_l2_op)
{
NodeBuilder::get_ops().register_factory<opset1::NormalizeL2>();
auto data = make_shared<op::Parameter>(element::i32, Shape{1});
const auto axes = make_shared<op::Constant>(element::i32, Shape{}, vector<int32_t>{0});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize_l2 = make_shared<opset1::NormalizeL2>(data, axes, eps, eps_mode);
NodeBuilder builder(normalize_l2);
auto g_normalize_l2 = as_type_ptr<opset1::NormalizeL2>(builder.create());
EXPECT_EQ(g_normalize_l2->get_eps(), normalize_l2->get_eps());
EXPECT_EQ(g_normalize_l2->get_eps_mode(), normalize_l2->get_eps_mode());
}
| 30.864865 | 91 | 0.734676 | [
"shape",
"vector"
] |
b14bcba07bda19c9ea4301fb15bda7bc11e85d16 | 749 | cpp | C++ | aws-cpp-sdk-ivs/source/model/PutMetadataRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-ivs/source/model/PutMetadataRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ivs/source/model/PutMetadataRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ivs/model/PutMetadataRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::IVS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
PutMetadataRequest::PutMetadataRequest() :
m_channelArnHasBeenSet(false),
m_metadataHasBeenSet(false)
{
}
Aws::String PutMetadataRequest::SerializePayload() const
{
JsonValue payload;
if(m_channelArnHasBeenSet)
{
payload.WithString("channelArn", m_channelArn);
}
if(m_metadataHasBeenSet)
{
payload.WithString("metadata", m_metadata);
}
return payload.View().WriteReadable();
}
| 17.418605 | 69 | 0.728972 | [
"model"
] |
b150b218164b3e7451d74fa3cf1481bd77290dbb | 33,150 | cpp | C++ | sta-src/Astro-Core/date.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 6 | 2018-09-05T12:41:59.000Z | 2021-07-01T05:34:23.000Z | sta-src/Astro-Core/date.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-02-07T19:09:21.000Z | 2015-08-14T03:15:42.000Z | sta-src/Astro-Core/date.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-03-25T15:50:31.000Z | 2017-12-06T12:16:47.000Z | /*
This program is free software; you can redistribute it and/or modify it under
the terms of the European Union Public Licence - EUPL v.1.1 as published by
the European Commission.
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 European Union Public Licence - EUPL v.1.1
for more details.
You should have received a copy of the European Union Public Licence - EUPL v.1.1
along with this program.
Further information about the European Union Public Licence - EUPL v.1.1 can
also be found on the world wide web at http://ec.europa.eu/idabc/eupl
*/
/*
------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----
*/
/*
------------------ Author: Chris Laurel -------------------------------------------------
------------------ E-mail: (claurel@gmail.com) ----------------------------
// Patched by Guillermo June 12 2009 to modify how STA inteprets the dates (all now as UTC)
// Patched by Guillermo to correct the conversion to modified Julian Dates
//Patched by Ana Raposo to include Mission Elapsed Time, Time from Epoch, transformations between a calendar date and JulianDate and Day of the Year;
There is now a function to check for leap years.
*/
#include "Astro-Core/date.h"
#include "Astro-Core/calendarTOjulian.h"
#include <cmath>
#include <QDebug>
#include "constants.h"
#include <vector>
#include <map>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <cassert>
using namespace sta;
/*! While any event in recorded human history can be written as a positive
* Julian day number, when working with contemporary events all those digits
* can be cumbersome. A Modified Julian Day (MJD) is created by subtracting 2400000.5
* from a Julian day number, and thus represents the number of days elapsed
* since midnight (00:00) Universal Time on November 17, 1858.
* Modified Julian Days are widely used to specify the epoch in tables of orbital
* elements of artificial Earth satellites. Since no such objects existed prior to
* October 4, 1957, all satellite-related MJDs are positive.
*/
double sta::MJDBase = 2400000.5;
double sta::J2000 = 2451545.0;
/*! Convert a Qt4 date-time object to a Julian date.
*
* TODO: leap seconds are not handled by Qt4 yet.
*/
double sta::CalendarToJd(const QDateTime& calendarDate)
{
Q_ASSERT(calendarDate.isValid());
QDate d = calendarDate.date();
QTime t = calendarDate.time();
return calendarTOjulian(d.year(), d.month(), d.day(), t.hour(), t.minute(), t.second()) + secsToDays(t.msec() / 1000.0);
}
/*! Convert a Julian date to a Qt4 date-time object. The returned QDateTime
* object will use the UTC timespec.
*
* @param(jd): A Julian date greater than or equal to zero.
*
* TODO: leap seconds are not handled by Qt4 yet!
*/
QDateTime sta::JdToCalendar(double jd)
{
Q_ASSERT(jd >= 0.0);
int a = (int) floor(jd + 0.5);
double c;
if (a < 2299161)
{
c = (double) (a + 1524);
}
else
{
double b = (double) ((int) floor((a - 1867216.25) / 36524.25));
c = a + b - (int) floor(b / 4) + 1525;
}
int d = (int) floor((c - 122.1) / 365.25);
int e = (int) floor(365.25 * d);
int f = (int) floor((c - e) / 30.6001);
double dday = c - e - (int) floor(30.6001 * f) + ((jd + 0.5) - a);
// This following used to be 14.0, but gcc was computing it incorrectly, so
// it was changed to 14
int month = (int) (f - 1 - 12 * (int) (f / 14));
int year = (int) (d - 4715 - (int) ((7.0 + month) / 10.0));
int day = (int) dday;
double dhour = (dday - day) * 24;
int hour = (int) dhour;
double dminute = (dhour - hour) * 60;
int minute = (int) dminute;
double dsecond = (dminute - minute) * 60;
int second = (int) dsecond;
int msec = (int) ((dsecond - second) * 1000);
return QDateTime(QDate(year, month, day), QTime(hour, minute, second, msec), Qt::UTC);
}
/*! Convert a modified Julian date (day offset from JD 2400000.0) to a
* standard Julian date.
*/
double sta::MjdToJd(double mjd)
{
return mjd + sta::MJDBase;
}
/*! Convert a standard Julian date to a modified Julian date (day offset
* from JD 2400000.0.)
*/
double sta::JdToMjd(double jd)
{
return jd - MJDBase;
}
/** Convert a modified Julian date (day offset from JD240000.0) to a
* time offset in seconds since J2000.0. This function is provided because
* toolkits such as SPICE and VESTA use seconds from J2000 as their basic
* time parameter.
*/
double sta::MjdToSecJ2000(double mjd)
{
return sta::daysToSecs(mjd + (MJDBase - sta::J2000));
}
/** Convert a time offset in seconds since J2000.0 to a modified Julian
* date (day offset from JD240000.0). This function is provided because
* toolkits such as SPICE and VESTA use seconds from J2000 as their
* basic time parameter.
*/
double sta::SecJ2000ToMjd(double sec)
{
return sta::secsToDays(sec) - (MJDBase - sta::J2000);
}
/** Convert a Julian date to a time offset in seconds since J2000.0.
* This function is provided because some toolkits (such as SPICE and VESTA)
* use seconds from J2000 as their basic time parameter.
*/
double sta::JdToSecJ2000(double jd)
{
return sta::daysToSecs(jd - sta::J2000);
}
/** Convert a time offset in seconds since J2000.0 to a Julian date.
* This function is provided because toolkits such as SPICE and VESTA
* use seconds from J2000 as their basic time parameter.
*/
double sta::SecJ2000ToJd(double sec)
{
return sta::J2000 + sta::secsToDays(sec);
}
/*! functions added by Ana Raposo to fulfill some Analysis Module requirements*/
bool sta::CheckIfLeapYear(int year)
{
/*
checks if the year in the input is a leap year, and returns true, if yes, and false if not
*/
if((year%4==0)&&(year%100!=0))
{
return (true);
}
if((year%4==0)&&(year%100==0)&&(year%400)!=0)
{
return(false);
}
if((year%4==0)&&(year%100==0)&&(year%400)==0)
{
return(true);
}
return(false);
}
double sta::DateTimeTOjulian(QDateTime DateTime)
{
/*
Transforms a date and time in the QdateTime format into Julian Date format; returns the date in JD
*/
int Year=DateTime.date().year();
int Month=DateTime.date().month();
int Day=DateTime.date().day();
int Hour=DateTime.time().hour();
int Minute=DateTime.time().minute();
int Second=DateTime.time().second();
double JulianDate=calendarTOjulian(Year,Month,Day,Hour,Minute,Second);
return JulianDate;
}
QString sta::calendarToDayOfYear(QDateTime DateTime)
{
/*
transforms a date and time in QDateTime format into a string containg the day of the year
*/
int DaysInMonths=0;
int Days=0;
int DayOfYear=0;
int MonthsLength[12];
MonthsLength[0]=MonthsLength[2]=MonthsLength[4]=MonthsLength[6]=MonthsLength[7]=MonthsLength[9]=MonthsLength[11]=31;
MonthsLength[3]=MonthsLength[5]=MonthsLength[8]=MonthsLength[10]=30;
MonthsLength[1]=28;
if(sta::CheckIfLeapYear(DateTime.date().year()))
{
MonthsLength[1]=29;
}
//if(DateTime.date().month()!=1)
{
for(int i=0;i<DateTime.date().month()-1;i++)
{
DaysInMonths=DaysInMonths+MonthsLength[i];
}
}
Days=DateTime.date().day();
DayOfYear=DaysInMonths+Days;
QString DayInYear;
DayInYear.sprintf("%1d",DayOfYear);
QString DDD;
for(int i=0;i<(3-DayInYear.size());i++)
{
DDD.append("0");
}
DDD.append(DayInYear);
return DDD;
}
QString sta::MissionElapsedTime(double Date, double StartEpoch)
{
/*
Description: calculates the elapsed time between two dates, in terms of days, hours, minutes, and seconds.
Inputs: Date- each time step, in MJD, StartEpoch-point from which the elapsed time is calculated
Outputs: string with the elapsed time in the format day/hh:mm::ss
*/
QString ETime;
double ElapsedTime=Date-StartEpoch+0.00001;
double DayJD=calendarTOjulian(1858,11,18,0,0,0); //convert 1day into MJD
double DayMJD=sta::JdToMjd(DayJD);
double ElapsedTimeDays=ElapsedTime/DayMJD;
double HourJD=calendarTOjulian(1858,11,17,1,0,0); //convert 1hour into MJD
double HourMJD=sta::JdToMjd(HourJD);
double ElapsedTimeHours=ElapsedTime/HourMJD;
double MinuteJD=calendarTOjulian(1858,11,17,0,1,0); //convert 1minute into MJD
double MinuteMJD=sta::JdToMjd(MinuteJD);
double ElapsedTimeMinutes=ElapsedTime/MinuteMJD;
double SecondJD=calendarTOjulian(1858,11,17,0,0,1);//convert 1second into MJD
double SecondMJD=sta::JdToMjd(SecondJD);
double ElapsedTimeSeconds=ElapsedTime/SecondMJD;
double Dayfractpart, Dayintpart;
Dayfractpart = modf (ElapsedTimeDays , &Dayintpart);
int day=(int)Dayintpart; //number of days
double NumberOfHours=Dayfractpart*ElapsedTimeHours/ElapsedTimeDays;
double Hourfractpart, Hourintpart;
Hourfractpart = modf (NumberOfHours , &Hourintpart);
int hour=(int)Hourintpart; //number of hours
double NumberOfMinutes=Hourfractpart*ElapsedTimeMinutes/ElapsedTimeHours;
double Minutefractpart, Minuteintpart;
Minutefractpart = modf (NumberOfMinutes , &Minuteintpart);
int minute=(int)Minuteintpart; //number of minutes
double NumberOfSeconds=Minutefractpart*ElapsedTimeSeconds/ElapsedTimeMinutes;
double Secondfractpart, Secondintpart;
Secondfractpart = modf (NumberOfSeconds , &Secondintpart);
int second=(int)Secondintpart; //number of minutes
QString STime;
QString Hour;
Hour.sprintf("%1d",hour);
(STime.append(Hour)).append(".");
QString Minute;
Minute.sprintf("%1d",minute);
(STime.append(Minute)).append(".");
QString Second;
Second.sprintf("%1d",second);
STime.append(Second);
QTime Time = QTime::fromString(STime, "h.m.s");
QString ToTime=Time.toString(Qt::TextDate);
QString DayToTime;
DayToTime.sprintf("%1d",day);
ETime.append(DayToTime);
ETime.append("/");
ETime.append(ToTime);
return ETime;
}
double sta::MjdToFromEpoch(double StartEpoch, double mjd, QString Units)
{
/*
Description: transforms a certain time into the elapsed time from the beginning of the start epoch; the elapsed time can be calculated in terms of hours, minutes, seconds, or days, according to the Units input.
Inputs: StartEpoch- beginning of propagation, mjd- considered time, Units- units in which the elapsed time shall be calculated
*/
double ElapsedTime=mjd-StartEpoch;
if(Units=="Seconds")
{
double SecondJD=calendarTOjulian(1858,11,17,0,0,1);//convert 1second into MJD
double Second=sta::JdToMjd(SecondJD);
double ElapsedTimeSeconds=ElapsedTime/Second;
return(ElapsedTimeSeconds);
}
if(Units=="Minutes")
{
double MinuteJD=calendarTOjulian(1858,11,17,0,1,0); //convert 1minute into MJD
double MinuteMJD=sta::JdToMjd(MinuteJD);
double ElapsedTimeMinutes=ElapsedTime/MinuteMJD;
return(ElapsedTimeMinutes);
}
if(Units=="Hours")
{
double HourJD=calendarTOjulian(1858,11,17,1,0,0); //convert 1hour into MJD
double HourMJD=sta::JdToMjd(HourJD);
double ElapsedTimeHours=ElapsedTime/HourMJD;
return(ElapsedTimeHours);
}
if(Units=="Days")
{
double DayJD=calendarTOjulian(1858,11,18,0,0,0); //convert 1day into MJD
double DayMJD=sta::JdToMjd(DayJD);
double ElapsedTimeDays=ElapsedTime/DayMJD;
return(ElapsedTimeDays);
}
}
QList<QString> sta::TimeLayout(int day, int month)
{
/*
Description: writes day and month with 2 digits, adding a zero whenever the values only have one digit;
example: day 1-> day 01
Inputs:day and month
Outputs: QList Output, day and month with 2 digits, Output[0] is day and Output[1] is month
*/
QString Day;
Day.sprintf("%1d",day);
QString ToDay;
for(int i=0;i<(2-Day.size());i++)
{
ToDay.append("0");
}
ToDay.append(Day);
QString Month;
Month.sprintf("%1d",month);
QString ToMonth;
for(int i=0;i<(2-Month.size());i++)
{
ToMonth.append("0");
}
ToMonth.append(Month);
QList<QString>Date;
Date.append(ToDay);
Date.append(ToMonth);
return Date;
}
QList<double> sta::DayOfYearToDDD(double DayOfYear)
{
/*
Description: returns the day of the year with 3 digits in the integer part, adding zeros when the input has only 1 or 2 digits in the integer part.
Inputs: day of the year to transform
Outputs: day of year with 3 digits in the integer part
*/
double fractpartDay;
double intpartDay;
fractpartDay = modf (DayOfYear , &intpartDay);
int IntDay=(int) intpartDay;
QList<double> DDD;
QString Day;
Day.sprintf("%1d",IntDay);
for(int i=0;i<(3-Day.size());i++)
{
DDD.append(0);
}
DDD.append(DayOfYear);
return DDD;
}
//----------------------------------------------------
/* The following code is extracted from GregorianDate.cpp
of Vesta*/
using namespace std;
static const unsigned int DaysPerMonth[] =
{
0,
31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31,
};
static const unsigned int DaysBeforeMonth[] =
{
0,
0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334,
};
// Difference in seconds between International Atomic Time (TAI) and
// Terrestrial Time (TT): TT = TAI + DeltaTAI
static const double DeltaTAI = 32.184;
static const int DeltaGPS = 19;
// Constant values taken from SPICE leap second kernel naif0008.tls
static const double TDB_K = 1.657e-3;
static const double TDB_EB = 1.671e-2;
static const double TDB_M0 = 6.239996;
static const double TDB_M1 = 1.99096871e-7;
// Convert from Terrestrial Time to Barycentric Dynamical Time. The argument and return
// value are both the number of seconds since J2000.0.
double convertTTtoTDB(double ttSec)
{
return ttSec + TDB_K * sin(TDB_M0 + TDB_M1 * ttSec + TDB_EB * sin(TDB_M0 + TDB_M1 * ttSec));
}
//Convert from Barycentric Dynamical Time to Terrestrial Time. The argument and return
//value are both the number of seconds since J2000.0.
double convertTDBtoTT(double tdbSec)
{
// We need to invert the expression in convertTTtoTDB. We'll approximate
// a solution by iterating three times (which is what SPICE does). Note that
// the maximum difference between the TT and TDB time scales is under two
// milliseconds for any date within 1000 years of J2000.
double ttSec = tdbSec;
for (unsigned int i = 0; i < 3; ++i)
{
ttSec = tdbSec - TDB_K * sin(TDB_M0 + TDB_M1 * ttSec + TDB_EB * sin(TDB_M0 + TDB_M1 * ttSec));
}
return ttSec;
}
double convertTAItoTT(double taiSec)
{
return taiSec + DeltaTAI;
}
double convertTTtoTAI(double ttSec)
{
return ttSec - DeltaTAI;
}
double convertTAItoTDB(double taiSec)
{
return convertTTtoTDB(convertTAItoTT(taiSec));
}
double convertTDBtoTAI(double tdbSec)
{
return convertTTtoTAI(convertTDBtoTT(tdbSec));
}
double convertTDBtoGPS(double tdbSec)
{
return convertTDBtoTAI(tdbSec)-DeltaGPS;
}
// Convert a uniform time from a Julian Date to a count of seconds since
// J2000.0 (12:00:00 1-Jan-2000)
static double convertJDToSec(double jd)
{
return (jd - 2451545.0) * 86400.0;
}
static double convertSecToJD(double sec)
{
return sec / 86400.0 + 2451545.0;
}
/** Convert two times in seconds from one uniform time scale
* to another.
*/
static double convertUniformSec(double fromTime, TimeConversions::TimeScale fromScale, TimeConversions::TimeScale toScale)
{
if (fromScale == toScale)
{
return fromTime;
}
// Convert to TAI
double tai = 0.0;
switch (fromScale)
{
case TimeConversions::TimeScale_TAI:
tai = fromTime;
break;
case TimeConversions::TimeScale_TDB:
tai = convertTDBtoTAI(fromTime);
break;
case TimeConversions::TimeScale_TT:
tai = convertTTtoTAI(fromTime);
break;
default:
assert(0);
}
switch (toScale)
{
case TimeConversions::TimeScale_TAI:
return tai;
case TimeConversions::TimeScale_TDB:
return convertTAItoTDB(tai);
case TimeConversions::TimeScale_TT:
return convertTAItoTT(tai);
default:
assert(0);
return 0.0;
}
}
/** Convert a Julian day number from one uniform time scale
* to another.
*/
static double convertUniformJD(double fromTime, TimeConversions::TimeScale fromScale, TimeConversions::TimeScale toScale)
{
return convertSecToJD(convertUniformSec(convertJDToSec(fromTime), fromScale, toScale));
}
// Get the Julian day number at noon on the specified Gregorian calendar date.
// If a date before 15 Oct 1582 is given, the Julian calendar is assumed. Conversion
// algorithm in from Meeus, _Astronomical Algorithms_.
static int julianDayNumber(int year, unsigned int month, unsigned int day)
{
if (month <= 2)
{
year -= 1;
month += 12;
}
int b;
if (year > 1582 || (year == 1582 && (month > 10 || (month == 10 && day >= 15))))
{
b = 2 - (year / 100) + (year / 100) / 4;
}
else
{
// The specified day is in the before the Gregorian calendar
// transition in October 1582.
b = 0;
}
return int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + day + b - 1524;
}
// Convert a uniform calendar date to a Julian day number in the same uniform time scale
static double UniformCalendarToJD(int year, unsigned int month, unsigned int day,
unsigned int hour, unsigned int minute, double second)
{
int dayNumber = julianDayNumber(year, month, day);
// -0.5 is required because julianDayNumber returns the Julian day number at noon.
return double(dayNumber) + (hour + (minute + second / 60.0) / 60.0) / 24.0 - 0.5;
}
static void JDToCalendar(double jd,
int& year, unsigned int& month, unsigned int& day,
unsigned int& hour, unsigned int& minute, double& second)
{
int a = int(floor(jd + 0.5));
double c;
if (a < 2299161)
{
c = double(a + 1524);
}
else
{
double b = double(int(floor((a - 1867216.25) / 36524.25)));
c = a + b - int(floor(b / 4)) + 1525;
}
int d = int(floor((c - 122.1) / 365.25));
int e = int(floor(365.25 * d));
int f = int(floor((c - e) / 30.6001));
double fracDay = c - e - floor(30.6001 * f) + jd + 0.5 - a;
month = f - 1 - 12 * (f / 14);
year = d - 4715 - (7 + month) / 10;
day = int(fracDay);
double fracHour = (fracDay - day) * 24.0;
hour = int(fracHour);
double fracMinute = (fracHour - hour) * 60.0;
minute = int(fracMinute);
second = (fracMinute - minute) * 60.0;
}
// Return true if the specified year is a leap year
static bool checkLeapYear(int y)
{
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
// Get the number of days in the specified month of the specified
// year.
static unsigned int daysInMonth(int y, int m)
{
if (m == 2 && checkLeapYear(y))
{
return DaysPerMonth[m] + 1;
}
else
{
return DaysPerMonth[m];
}
}
namespace TimeConversions
{
struct LeapSecond
{
int taiOffset;
int year;
unsigned int month;
unsigned int day;
};
static const LeapSecond DefaultLeapSecondList[] =
{
{ 10, 1972, 1, 1 },
{ 11, 1972, 7, 1 },
{ 12, 1973, 1, 1 },
{ 13, 1974, 1, 1 },
{ 14, 1975, 1, 1 },
{ 15, 1976, 1, 1 },
{ 16, 1977, 1, 1 },
{ 17, 1978, 1, 1 },
{ 18, 1979, 1, 1 },
{ 19, 1980, 1, 1 },
{ 20, 1981, 7, 1 },
{ 21, 1982, 7, 1 },
{ 22, 1983, 7, 1 },
{ 23, 1985, 7, 1 },
{ 24, 1988, 1, 1 },
{ 25, 1990, 1, 1 },
{ 26, 1991, 1, 1 },
{ 27, 1992, 7, 1 },
{ 28, 1993, 7, 1 },
{ 29, 1994, 7, 1 },
{ 30, 1996, 1, 1 },
{ 31, 1997, 7, 1 },
{ 32, 1999, 1, 1 },
{ 33, 2006, 1, 1 },
{ 34, 2009, 1, 1 },
};
// Get a unique value for the day that can be used to lookup in the leap
// second table.
static unsigned int dateHash(int year, unsigned int month, unsigned int day)
{
return day + 100 * (month + 100 * year);
}
struct UTCDifferenceRecord
{
double tai;
double diffSec;
};
bool operator<(const UTCDifferenceRecord& t0, const UTCDifferenceRecord& t1)
{
return t0.tai < t1.tai;
}
bool operator<(const LeapSecond& ls0, const LeapSecond& ls1)
{
if (ls0.year < ls1.year)
{
return true;
}
else if (ls0.year > ls1.year)
{
return false;
}
else
{
if (ls0.month < ls1.month)
{
return true;
}
else if (ls0.month > ls1.month)
{
return false;
}
else
{
return ls0.day < ls1.day;
}
}
}
/** LeapSecondTable is an internal class used to calculate the difference
* between UTC and TAI at some instant in time. This class will eventually
* be exposed so that VESTA users can install custom leap second tables.
*/
class LeapSecondTable
{
public:
LeapSecondTable(const LeapSecond leapSeconds[], unsigned int leapSecondCount)
{
for (unsigned int i = 0; i < leapSecondCount; ++i)
{
const LeapSecond& ls = leapSeconds[i];
m_leapSeconds.push_back(ls);
m_calendarOffsets[dateHash(ls.year, ls.month, ls.day)] = ls.taiOffset;
UTCDifferenceRecord utcDiff;
utcDiff.diffSec = ls.taiOffset;
utcDiff.tai = UniformCalendarToJD(ls.year, ls.month, ls.day, 0, 0, 0);
m_utcDiffs.push_back(utcDiff);
}
}
bool dateHasLeapSecond(const GregorianDate& d)
{
// The leap year offset table stores days *after* the ones
// containing leap seconds. Advance one day to check the table
// for a leap second...
unsigned int year = d.year();
unsigned int month = d.month();
unsigned int day = d.day();
if (d.day() == daysInMonth(year, month))
{
if (month == 12)
{
month = 1;
year++;
}
else
{
month++;
}
day = 1;
}
else
{
day++;
}
return m_calendarOffsets.find(dateHash(year, month, day)) != m_calendarOffsets.end();
}
// Get the difference betweeen UTC and TAI at the specified instant
// in the TAI time scale.
double utcDifference(double taijd)
{
if (m_utcDiffs.empty())
{
return 0.0;
}
UTCDifferenceRecord comp;
comp.tai = taijd;
comp.diffSec = 0.0;
vector<UTCDifferenceRecord>::const_iterator iter = lower_bound(m_utcDiffs.begin(), m_utcDiffs.end(), comp);
if (iter == m_utcDiffs.end())
{
return m_utcDiffs.back().diffSec;
}
else if (taijd < iter->tai)
{
if (iter == m_utcDiffs.begin())
{
return 0.0;
}
else
{
--iter;
return iter->diffSec;
}
}
else
{
return iter->diffSec;
}
}
// Get the difference betweeen UTC and TAI at the specified UTC
// calendar day.
double utcDifference(int year, unsigned int month, unsigned int day)
{
if (m_utcDiffs.empty())
{
return 0.0;
}
LeapSecond ls;
ls.year = year;
ls.month = month;
ls.day = day;
vector<LeapSecond>::const_iterator iter = lower_bound(m_leapSeconds.begin(), m_leapSeconds.end(), ls);
if (iter == m_leapSeconds.end())
{
return m_leapSeconds.back().taiOffset;
}
else if (ls < *iter)
{
if (iter == m_leapSeconds.begin())
{
return 0.0;
}
else
{
--iter;
return iter->taiOffset;
}
}
else
{
return iter->taiOffset;
}
}
private:
vector<LeapSecond> m_leapSeconds;
map<unsigned int, unsigned int> m_calendarOffsets;
vector<UTCDifferenceRecord> m_utcDiffs;
};
}
TimeConversions::LeapSecondTable* TimeConversions::GregorianDate::s_DefaultLeapSecondTable =
new TimeConversions::LeapSecondTable(DefaultLeapSecondList,
sizeof(DefaultLeapSecondList) / sizeof(DefaultLeapSecondList[0]));
/** Default constructor creates a date representing the instant at midnight, 1 January 2000 UTC.
*/
TimeConversions::GregorianDate::GregorianDate() :
m_year(2000),
m_month(1),
m_day(1),
m_hour(0),
m_minute(0),
m_second(0),
m_usec(0),
m_timeScale(TimeConversions::TimeScale_UTC)
{
}
/** Copy constructor.
*/
TimeConversions::GregorianDate::GregorianDate(const GregorianDate& other) :
m_year(other.m_year),
m_month(other.m_month),
m_day(other.m_day),
m_hour(other.m_hour),
m_minute(other.m_minute),
m_second(other.m_second),
m_usec(other.m_usec),
m_timeScale(other.m_timeScale)
{
}
/** Construct a new calendar date.
*
* The time of day and time scale are optional. If they are omitted, the time is set to midnight
* and the time scale to UTC.
*
* \param year astronomical year number (for year < 1, year 0 = 1 BCE, year -1 = 2 BCE, etc.)
* \param month month number (1 - 12)
* \param day day number (1 - 31)
* \param hour hour number (0 - 23)
* \param minute minute number (0 - 59)
* \param second second number (0 - 59, 60 allowed for leap seconds in UTC time scale)
* \param usec microseconds (0 - 999999)
*/
TimeConversions::GregorianDate::GregorianDate(int year, unsigned int month, unsigned int day,
unsigned int hour, unsigned int minute, unsigned int second, unsigned int usec,
TimeConversions::TimeScale timeScale) :
m_year(year),
m_month(month),
m_day(day),
m_hour(hour),
m_minute(minute),
m_second(second),
m_usec(usec),
m_timeScale(timeScale)
{
}
/** Assignment operator.
*/
TimeConversions::GregorianDate& TimeConversions::GregorianDate::operator=(const TimeConversions::GregorianDate& other)
{
m_year = other.m_year;
m_month = other.m_month;
m_day = other.m_day;
m_hour = other.m_hour;
m_minute = other.m_minute;
m_second = other.m_second;
m_usec = other.m_usec;
m_timeScale = other.m_timeScale;
return *this;
}
/** Return true if this calendar date names a real instant in time.
*/
bool
TimeConversions::GregorianDate::isValid() const
{
unsigned int monthLength = m_month <= 12 ? DaysPerMonth[m_month] : 0;
if (isLeapYear() && m_month == 2)
{
monthLength++;
}
unsigned int minuteLength = 60;
if (s_DefaultLeapSecondTable->dateHasLeapSecond(*this) && m_timeScale == TimeConversions::TimeScale_UTC)
{
// TODO: Handle negative leap seconds so that the code doesn't break in the
// event that one is ever added.
minuteLength = 61;
}
if (m_year == 1582 && m_month == 10 && m_day > 4 && m_day < 15)
{
// Skipped days during the Julian to Gregorian calendar
// transition.
return false;
}
else
{
return (m_month > 0 && m_month <= 12) &&
(m_day > 0 && m_day <= monthLength) &&
m_hour < 24 &&
m_minute < 60 &&
m_second < minuteLength &&
m_usec < 1000000;
}
}
/** Return true if the date falls within a leap year.
*/
bool
TimeConversions::GregorianDate::isLeapYear() const
{
return checkLeapYear(m_year);
}
/** Return the day number within the year. This will be a value
* from 1 -- 365 (or 366 during a leap year.)
*/
unsigned int
TimeConversions::GregorianDate::dayOfYear() const
{
unsigned int daysBefore = DaysBeforeMonth[m_month];
if (m_month > 2 && isLeapYear())
{
++daysBefore;
}
return daysBefore + m_day;
}
/** Returns the day of the week as an integer between 1 and 7.
*/
unsigned int
TimeConversions::GregorianDate::dayOfWeek() const
{
return (julianDay() + 1) % 7 + 1;
}
/** Return the number of days in the month: 28, 29, 30, or 31 depending
* on the month and whether the year is a leap year.
*/
unsigned int
TimeConversions::GregorianDate::daysInMonth() const
{
return ::daysInMonth(m_year, m_month);
}
/** Get the Julian day number (days since 1 Nov 4713 BCE) of this
* date.
*/
int
TimeConversions::GregorianDate::julianDay() const
{
return julianDayNumber(m_year, m_month, m_day);
}
/** Convert the date to a Julian day number in the TDB time scale.
*/
double
TimeConversions::GregorianDate::toTDBJD() const
{
return convertSecToJD(toTDBSec());
}
/** Convert the date to a Julian day number in the TAI time scale.
*/
double
TimeConversions::GregorianDate::toTAIJD() const
{
double second = m_second + m_usec * 1.0e-6;
double uniformTime = UniformCalendarToJD(m_year, m_month, m_day, m_hour, m_minute, second);
TimeConversions::TimeScale timeScale = m_timeScale;
if (m_timeScale == TimeConversions::TimeScale_UTC)
{
double utcOffset = s_DefaultLeapSecondTable->utcDifference(m_year, m_month, m_day);
uniformTime += secsToDays(utcOffset);
timeScale = TimeConversions::TimeScale_TAI;
}
return convertUniformJD(uniformTime, timeScale, TimeConversions::TimeScale_TAI);
}
/** Convert the date to a Julian day number in the TT time scale.
*/
double
TimeConversions::GregorianDate::toTTJD() const
{
return toTAIJD() + secsToDays(DeltaTAI);
}
/** Convert the date to a number of seconds since J2000.0 in the TDB
* (Barycentric Dynamical Time) time scale.
*/
double
TimeConversions::GregorianDate::toTDBSec() const
{
return convertTAItoTDB(convertJDToSec(toTAIJD()));
}
/** Convert the date to a number of seconds since J2000.0 in the TT
* (Terrestrial Time) time scale.
*/
double
TimeConversions::GregorianDate::toTTSec() const
{
return convertTAItoTT(convertJDToSec(toTAIJD()));
}
/** Construct a UTC calendar date from a Julian day number in the TDB time scale.
*/
TimeConversions::GregorianDate
TimeConversions::GregorianDate::UTCDateFromTDBJD(double tdbjd)
{
int year = 0;
unsigned int month = 1;
unsigned int day = 1;
unsigned int hour = 0;
unsigned int minute = 0;
double second = 0;
double tai = tdbjd - DeltaTAI / 86400.0;
tai -= s_DefaultLeapSecondTable->utcDifference(tai) / 86400.0;
JDToCalendar(tai, year, month, day, hour, minute, second);
unsigned int s = unsigned(second);
unsigned int usec = unsigned((second - s) * 1.0e6);
return GregorianDate(year, month, day, hour, minute, s, usec, TimeScale_UTC);
}
/** Construct a TDB calendar date from a Julian day number in the TDB time scale.
*/
TimeConversions::GregorianDate
TimeConversions::GregorianDate::TDBDateFromTDBJD(double tdbjd)
{
int year = 0;
unsigned int month = 1;
unsigned int day = 1;
unsigned int hour = 0;
unsigned int minute = 0;
double second = 0;
JDToCalendar(tdbjd, year, month, day, hour, minute, second);
unsigned int s = unsigned(second);
unsigned int usec = unsigned((second - s) * 1.0e6);
return GregorianDate(year, month, day, hour, minute, s, usec, TimeScale_TDB);
}
TimeConversions::GregorianDate
TimeConversions::GregorianDate::UTCDateFromTDBSec(double tdbsec)
{
return UTCDateFromTDBJD(convertSecToJD(tdbsec));
}
/** Construct a TDB calendar date from a Julian day number in the TDB time scale.
*/
TimeConversions::GregorianDate
TimeConversions::GregorianDate::TDBDateFromTDBSec(double tdbsec)
{
return TDBDateFromTDBJD(convertSecToJD(tdbsec));
}
/** Convert the date to a string with the specified format.
*/
string
TimeConversions::GregorianDate::toString(Format format) const
{
if (format == ISO8601_Combined)
{
ostringstream str;
str << year() << '-'
<< setw(2) << setfill('0') << month() << '-'
<< setw(2) << setfill('0') << day() << 'T'
<< setw(2) << setfill('0') << hour() << ':'
<< setw(2) << setfill('0') << minute() << ':'
<< setw(2) << setfill('0') << second();
switch (m_timeScale)
{
case TimeScale_TDB:
str << " TDB";
break;
case TimeScale_TT:
str << " TT";
break;
case TimeScale_TAI:
str << " TAI";
break;
case TimeScale_UTC:
str << " UTC";
break;
}
return str.str();
}
else
{
return "";
}
}
| 26.95122 | 210 | 0.631161 | [
"object",
"vector",
"transform"
] |
b159caa5faf4b3fa5447da45b82c967322270a61 | 1,880 | cc | C++ | sensei/read_data.cc | rbnx/sensei | 0be283b604c7f0505850fefd880fe9bf985212b5 | [
"Apache-2.0"
] | 60 | 2015-05-29T19:33:50.000Z | 2022-03-24T04:14:13.000Z | sensei/read_data.cc | rbnx/sensei | 0be283b604c7f0505850fefd880fe9bf985212b5 | [
"Apache-2.0"
] | 1 | 2022-03-19T05:52:01.000Z | 2022-03-19T05:52:01.000Z | sensei/read_data.cc | rbnx/sensei | 0be283b604c7f0505850fefd880fe9bf985212b5 | [
"Apache-2.0"
] | 20 | 2015-07-03T09:07:31.000Z | 2022-03-19T05:51:51.000Z | /*
* Copyright 2015 Google Inc. 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 "sensei/read_data.h"
#include "sensei/config.h"
#include "sensei/config.pb.h"
#include "sensei/data_reader.h"
#include "sensei/model.h"
#include "sensei/world.h"
namespace sensei {
ReadData::ReadData(World* world) : world_(world) {}
void ReadData::RunCommand(const config::ReadData& config) {
if (config.has_data_reader()) {
DataReader(config.data_reader());
return;
}
if (config.has_set()) {
Set(config.set());
return;
}
LOG(FATAL) << "Unknown ReadData subcommand: " << config.DebugString();
}
void ReadData::DataReader(const config::DataReader& config) {
config::DataReader copy(config);
// Read data and fill world_->feature_map()
MultiDataReader(copy, set_, world_).Run();
world_->feature_map()->LogStats();
world_->product_map()->LogStats();
world_->data()->LogStats();
CHECK_GE(world_->product_map()->Size(), world_->model()->GetSize());
world_->model()->InitPerShards(
world_->data()->GetTraining().GetStats().RowCount(),
world_->data()->GetHoldout().GetStats().RowCount());
world_->optimizer()->SetData(*world_->data());
world_->sgd()->SetData(*world_->data());
}
void ReadData::Set(const config::ReadData::Set& config) {
set_.MergeFrom(config);
}
} // namespace sensei
| 28.059701 | 75 | 0.695213 | [
"model"
] |
b15a00a26a2735916299aebebb0c7f5e2fa10692 | 445 | cpp | C++ | cpp/linux/new_arch/model_infer.cpp | zjykzj/onnx | d4c0557df19787d7cd16abb38755ac61412b11bf | [
"Apache-2.0"
] | null | null | null | cpp/linux/new_arch/model_infer.cpp | zjykzj/onnx | d4c0557df19787d7cd16abb38755ac61412b11bf | [
"Apache-2.0"
] | null | null | null | cpp/linux/new_arch/model_infer.cpp | zjykzj/onnx | d4c0557df19787d7cd16abb38755ac61412b11bf | [
"Apache-2.0"
] | null | null | null | //
// Created by zj on 2021/8/23.
//
#include "model_infer.h"
bool ModelInfer::create(const char *model_path) {
std::cout << "ModelInfer::create()" << std::endl;
return true;
}
bool ModelInfer::release() {
std::cout << "ModelInfer::release()" << std::endl;
return true;
}
bool ModelInfer::infer(const cv::Mat &img, std::vector<float> &output_values) {
std::cout << "ModelInfer::infer()" << std::endl;
return true;
}
| 20.227273 | 79 | 0.624719 | [
"vector"
] |
b15b6ab47194c1b35fbde329bad9be868e954104 | 26,849 | cc | C++ | src/headers/16/node_sockaddr.cc | baptistejamin/cWS | 74d3ef58da257603ab0e56bab6f768854147bb37 | [
"MIT"
] | null | null | null | src/headers/16/node_sockaddr.cc | baptistejamin/cWS | 74d3ef58da257603ab0e56bab6f768854147bb37 | [
"MIT"
] | null | null | null | src/headers/16/node_sockaddr.cc | baptistejamin/cWS | 74d3ef58da257603ab0e56bab6f768854147bb37 | [
"MIT"
] | null | null | null | #include "node_sockaddr-inl.h" // NOLINT(build/include)
#include "env-inl.h"
#include "base64-inl.h"
#include "base_object-inl.h"
#include "memory_tracker-inl.h"
#include "node_errors.h"
#include "uv.h"
#include <memory>
#include <string>
#include <vector>
namespace node {
using v8::Array;
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Int32;
using v8::Local;
using v8::MaybeLocal;
using v8::Object;
using v8::Uint32;
using v8::Value;
namespace {
template <typename T, typename F>
SocketAddress FromUVHandle(F fn, const T& handle) {
SocketAddress addr;
int len = sizeof(sockaddr_storage);
if (fn(&handle, addr.storage(), &len) == 0)
CHECK_EQ(static_cast<size_t>(len), addr.length());
else
addr.storage()->sa_family = 0;
return addr;
}
} // namespace
bool SocketAddress::ToSockAddr(
int32_t family,
const char* host,
uint32_t port,
sockaddr_storage* addr) {
switch (family) {
case AF_INET:
return uv_ip4_addr(
host,
port,
reinterpret_cast<sockaddr_in*>(addr)) == 0;
case AF_INET6:
return uv_ip6_addr(
host,
port,
reinterpret_cast<sockaddr_in6*>(addr)) == 0;
default:
UNREACHABLE();
}
}
bool SocketAddress::New(
const char* host,
uint32_t port,
SocketAddress* addr) {
return New(AF_INET, host, port, addr) || New(AF_INET6, host, port, addr);
}
bool SocketAddress::New(
int32_t family,
const char* host,
uint32_t port,
SocketAddress* addr) {
return ToSockAddr(family, host, port,
reinterpret_cast<sockaddr_storage*>(addr->storage()));
}
size_t SocketAddress::Hash::operator()(const SocketAddress& addr) const {
size_t hash = 0;
switch (addr.family()) {
case AF_INET: {
const sockaddr_in* ipv4 =
reinterpret_cast<const sockaddr_in*>(addr.raw());
hash_combine(&hash, ipv4->sin_port, ipv4->sin_addr.s_addr);
break;
}
case AF_INET6: {
const sockaddr_in6* ipv6 =
reinterpret_cast<const sockaddr_in6*>(addr.raw());
const uint64_t* a =
reinterpret_cast<const uint64_t*>(&ipv6->sin6_addr);
hash_combine(&hash, ipv6->sin6_port, a[0], a[1]);
break;
}
default:
UNREACHABLE();
}
return hash;
}
SocketAddress SocketAddress::FromSockName(const uv_tcp_t& handle) {
return FromUVHandle(uv_tcp_getsockname, handle);
}
SocketAddress SocketAddress::FromSockName(const uv_udp_t& handle) {
return FromUVHandle(uv_udp_getsockname, handle);
}
SocketAddress SocketAddress::FromPeerName(const uv_tcp_t& handle) {
return FromUVHandle(uv_tcp_getpeername, handle);
}
SocketAddress SocketAddress::FromPeerName(const uv_udp_t& handle) {
return FromUVHandle(uv_udp_getpeername, handle);
}
namespace {
constexpr uint8_t mask[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
bool is_match_ipv4(
const SocketAddress& one,
const SocketAddress& two) {
const sockaddr_in* one_in =
reinterpret_cast<const sockaddr_in*>(one.data());
const sockaddr_in* two_in =
reinterpret_cast<const sockaddr_in*>(two.data());
return memcmp(&one_in->sin_addr, &two_in->sin_addr, sizeof(uint32_t)) == 0;
}
bool is_match_ipv6(
const SocketAddress& one,
const SocketAddress& two) {
const sockaddr_in6* one_in =
reinterpret_cast<const sockaddr_in6*>(one.data());
const sockaddr_in6* two_in =
reinterpret_cast<const sockaddr_in6*>(two.data());
return memcmp(&one_in->sin6_addr, &two_in->sin6_addr, 16) == 0;
}
bool is_match_ipv4_ipv6(
const SocketAddress& ipv4,
const SocketAddress& ipv6) {
const sockaddr_in* check_ipv4 =
reinterpret_cast<const sockaddr_in*>(ipv4.data());
const sockaddr_in6* check_ipv6 =
reinterpret_cast<const sockaddr_in6*>(ipv6.data());
const uint8_t* ptr =
reinterpret_cast<const uint8_t*>(&check_ipv6->sin6_addr);
return memcmp(ptr, mask, sizeof(mask)) == 0 &&
memcmp(ptr + sizeof(mask),
&check_ipv4->sin_addr,
sizeof(uint32_t)) == 0;
}
SocketAddress::CompareResult compare_ipv4(
const SocketAddress& one,
const SocketAddress& two) {
const sockaddr_in* one_in =
reinterpret_cast<const sockaddr_in*>(one.data());
const sockaddr_in* two_in =
reinterpret_cast<const sockaddr_in*>(two.data());
if (one_in->sin_addr.s_addr < two_in->sin_addr.s_addr)
return SocketAddress::CompareResult::LESS_THAN;
else if (one_in->sin_addr.s_addr == two_in->sin_addr.s_addr)
return SocketAddress::CompareResult::SAME;
else
return SocketAddress::CompareResult::GREATER_THAN;
}
SocketAddress::CompareResult compare_ipv6(
const SocketAddress& one,
const SocketAddress& two) {
const sockaddr_in6* one_in =
reinterpret_cast<const sockaddr_in6*>(one.data());
const sockaddr_in6* two_in =
reinterpret_cast<const sockaddr_in6*>(two.data());
int ret = memcmp(&one_in->sin6_addr, &two_in->sin6_addr, 16);
if (ret < 0)
return SocketAddress::CompareResult::LESS_THAN;
else if (ret > 0)
return SocketAddress::CompareResult::GREATER_THAN;
return SocketAddress::CompareResult::SAME;
}
SocketAddress::CompareResult compare_ipv4_ipv6(
const SocketAddress& ipv4,
const SocketAddress& ipv6) {
const sockaddr_in* ipv4_in =
reinterpret_cast<const sockaddr_in*>(ipv4.data());
const sockaddr_in6 * ipv6_in =
reinterpret_cast<const sockaddr_in6*>(ipv6.data());
const uint8_t* ptr =
reinterpret_cast<const uint8_t*>(&ipv6_in->sin6_addr);
if (memcmp(ptr, mask, sizeof(mask)) != 0)
return SocketAddress::CompareResult::NOT_COMPARABLE;
int ret = memcmp(
&ipv4_in->sin_addr,
ptr + sizeof(mask),
sizeof(uint32_t));
if (ret < 0)
return SocketAddress::CompareResult::LESS_THAN;
else if (ret > 0)
return SocketAddress::CompareResult::GREATER_THAN;
return SocketAddress::CompareResult::SAME;
}
bool in_network_ipv4(
const SocketAddress& ip,
const SocketAddress& net,
int prefix) {
uint32_t mask = ((1 << prefix) - 1) << (32 - prefix);
const sockaddr_in* ip_in =
reinterpret_cast<const sockaddr_in*>(ip.data());
const sockaddr_in* net_in =
reinterpret_cast<const sockaddr_in*>(net.data());
return (htonl(ip_in->sin_addr.s_addr) & mask) ==
(htonl(net_in->sin_addr.s_addr) & mask);
}
bool in_network_ipv6(
const SocketAddress& ip,
const SocketAddress& net,
int prefix) {
// Special case, if prefix == 128, then just do a
// straight comparison.
if (prefix == 128)
return compare_ipv6(ip, net) == SocketAddress::CompareResult::SAME;
uint8_t r = prefix % 8;
int len = (prefix - r) / 8;
uint8_t mask = ((1 << r) - 1) << (8 - r);
const sockaddr_in6* ip_in =
reinterpret_cast<const sockaddr_in6*>(ip.data());
const sockaddr_in6* net_in =
reinterpret_cast<const sockaddr_in6*>(net.data());
if (memcmp(&ip_in->sin6_addr, &net_in->sin6_addr, len) != 0)
return false;
const uint8_t* p1 = reinterpret_cast<const uint8_t*>(
ip_in->sin6_addr.s6_addr);
const uint8_t* p2 = reinterpret_cast<const uint8_t*>(
net_in->sin6_addr.s6_addr);
return (p1[len] & mask) == (p2[len] & mask);
}
bool in_network_ipv4_ipv6(
const SocketAddress& ip,
const SocketAddress& net,
int prefix) {
if (prefix == 128)
return compare_ipv4_ipv6(ip, net) == SocketAddress::CompareResult::SAME;
uint8_t r = prefix % 8;
int len = (prefix - r) / 8;
uint8_t mask = ((1 << r) - 1) << (8 - r);
const sockaddr_in* ip_in =
reinterpret_cast<const sockaddr_in*>(ip.data());
const sockaddr_in6* net_in =
reinterpret_cast<const sockaddr_in6*>(net.data());
uint8_t ip_mask[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0};
uint8_t* ptr = ip_mask;
memcpy(ptr + 12, &ip_in->sin_addr, 4);
if (memcmp(ptr, &net_in->sin6_addr, len) != 0)
return false;
ptr += len;
const uint8_t* p2 = reinterpret_cast<const uint8_t*>(
net_in->sin6_addr.s6_addr);
return (ptr[0] & mask) == (p2[len] & mask);
}
bool in_network_ipv6_ipv4(
const SocketAddress& ip,
const SocketAddress& net,
int prefix) {
if (prefix == 32)
return compare_ipv4_ipv6(net, ip) == SocketAddress::CompareResult::SAME;
uint32_t m = ((1 << prefix) - 1) << (32 - prefix);
const sockaddr_in6* ip_in =
reinterpret_cast<const sockaddr_in6*>(ip.data());
const sockaddr_in* net_in =
reinterpret_cast<const sockaddr_in*>(net.data());
const uint8_t* ptr =
reinterpret_cast<const uint8_t*>(&ip_in->sin6_addr);
if (memcmp(ptr, mask, sizeof(mask)) != 0)
return false;
ptr += sizeof(mask);
uint32_t check = ReadUint32BE(ptr);
return (check & m) == (htonl(net_in->sin_addr.s_addr) & m);
}
} // namespace
// TODO(@jasnell): The implementations of is_match, compare, and
// is_in_network have not been performance optimized and could
// likely benefit from work on more performant approaches.
bool SocketAddress::is_match(const SocketAddress& other) const {
switch (family()) {
case AF_INET:
switch (other.family()) {
case AF_INET: return is_match_ipv4(*this, other);
case AF_INET6: return is_match_ipv4_ipv6(*this, other);
}
break;
case AF_INET6:
switch (other.family()) {
case AF_INET: return is_match_ipv4_ipv6(other, *this);
case AF_INET6: return is_match_ipv6(*this, other);
}
break;
}
return false;
}
SocketAddress::CompareResult SocketAddress::compare(
const SocketAddress& other) const {
switch (family()) {
case AF_INET:
switch (other.family()) {
case AF_INET: return compare_ipv4(*this, other);
case AF_INET6: return compare_ipv4_ipv6(*this, other);
}
break;
case AF_INET6:
switch (other.family()) {
case AF_INET: {
CompareResult c = compare_ipv4_ipv6(other, *this);
switch (c) {
case SocketAddress::CompareResult::NOT_COMPARABLE:
// Fall through
case SocketAddress::CompareResult::SAME:
return c;
case SocketAddress::CompareResult::GREATER_THAN:
return SocketAddress::CompareResult::LESS_THAN;
case SocketAddress::CompareResult::LESS_THAN:
return SocketAddress::CompareResult::GREATER_THAN;
}
break;
}
case AF_INET6: return compare_ipv6(*this, other);
}
break;
}
return SocketAddress::CompareResult::NOT_COMPARABLE;
}
bool SocketAddress::is_in_network(
const SocketAddress& other,
int prefix) const {
switch (family()) {
case AF_INET:
switch (other.family()) {
case AF_INET: return in_network_ipv4(*this, other, prefix);
case AF_INET6: return in_network_ipv4_ipv6(*this, other, prefix);
}
break;
case AF_INET6:
switch (other.family()) {
case AF_INET: return in_network_ipv6_ipv4(*this, other, prefix);
case AF_INET6: return in_network_ipv6(*this, other, prefix);
}
break;
}
return false;
}
SocketAddressBlockList::SocketAddressBlockList(
std::shared_ptr<SocketAddressBlockList> parent)
: parent_(parent) {}
void SocketAddressBlockList::AddSocketAddress(
const std::shared_ptr<SocketAddress>& address) {
Mutex::ScopedLock lock(mutex_);
std::unique_ptr<Rule> rule =
std::make_unique<SocketAddressRule>(address);
rules_.emplace_front(std::move(rule));
address_rules_[*address.get()] = rules_.begin();
}
void SocketAddressBlockList::RemoveSocketAddress(
const std::shared_ptr<SocketAddress>& address) {
Mutex::ScopedLock lock(mutex_);
auto it = address_rules_.find(*address.get());
if (it != std::end(address_rules_)) {
rules_.erase(it->second);
address_rules_.erase(it);
}
}
void SocketAddressBlockList::AddSocketAddressRange(
const std::shared_ptr<SocketAddress>& start,
const std::shared_ptr<SocketAddress>& end) {
Mutex::ScopedLock lock(mutex_);
std::unique_ptr<Rule> rule =
std::make_unique<SocketAddressRangeRule>(start, end);
rules_.emplace_front(std::move(rule));
}
void SocketAddressBlockList::AddSocketAddressMask(
const std::shared_ptr<SocketAddress>& network,
int prefix) {
Mutex::ScopedLock lock(mutex_);
std::unique_ptr<Rule> rule =
std::make_unique<SocketAddressMaskRule>(network, prefix);
rules_.emplace_front(std::move(rule));
}
bool SocketAddressBlockList::Apply(
const std::shared_ptr<SocketAddress>& address) {
Mutex::ScopedLock lock(mutex_);
for (const auto& rule : rules_) {
if (rule->Apply(address))
return true;
}
return parent_ ? parent_->Apply(address) : false;
}
SocketAddressBlockList::SocketAddressRule::SocketAddressRule(
const std::shared_ptr<SocketAddress>& address_)
: address(address_) {}
SocketAddressBlockList::SocketAddressRangeRule::SocketAddressRangeRule(
const std::shared_ptr<SocketAddress>& start_,
const std::shared_ptr<SocketAddress>& end_)
: start(start_),
end(end_) {}
SocketAddressBlockList::SocketAddressMaskRule::SocketAddressMaskRule(
const std::shared_ptr<SocketAddress>& network_,
int prefix_)
: network(network_),
prefix(prefix_) {}
bool SocketAddressBlockList::SocketAddressRule::Apply(
const std::shared_ptr<SocketAddress>& address) {
return this->address->is_match(*address.get());
}
std::string SocketAddressBlockList::SocketAddressRule::ToString() {
std::string ret = "Address: ";
ret += address->family() == AF_INET ? "IPv4" : "IPv6";
ret += " ";
ret += address->address();
return ret;
}
bool SocketAddressBlockList::SocketAddressRangeRule::Apply(
const std::shared_ptr<SocketAddress>& address) {
return *address.get() >= *start.get() &&
*address.get() <= *end.get();
}
std::string SocketAddressBlockList::SocketAddressRangeRule::ToString() {
std::string ret = "Range: ";
ret += start->family() == AF_INET ? "IPv4" : "IPv6";
ret += " ";
ret += start->address();
ret += "-";
ret += end->address();
return ret;
}
bool SocketAddressBlockList::SocketAddressMaskRule::Apply(
const std::shared_ptr<SocketAddress>& address) {
return address->is_in_network(*network.get(), prefix);
}
std::string SocketAddressBlockList::SocketAddressMaskRule::ToString() {
std::string ret = "Subnet: ";
ret += network->family() == AF_INET ? "IPv4" : "IPv6";
ret += " ";
ret += network->address();
ret += "/" + std::to_string(prefix);
return ret;
}
MaybeLocal<Array> SocketAddressBlockList::ListRules(Environment* env) {
Mutex::ScopedLock lock(mutex_);
std::vector<Local<Value>> rules;
if (!ListRules(env, &rules))
return MaybeLocal<Array>();
return Array::New(env->isolate(), rules.data(), rules.size());
}
bool SocketAddressBlockList::ListRules(
Environment* env,
std::vector<v8::Local<v8::Value>>* rules) {
if (parent_ && !parent_->ListRules(env, rules))
return false;
for (const auto& rule : rules_) {
Local<Value> str;
if (!rule->ToV8String(env).ToLocal(&str))
return false;
rules->push_back(str);
}
return true;
}
void SocketAddressBlockList::MemoryInfo(node::MemoryTracker* tracker) const {
tracker->TrackField("rules", rules_);
}
void SocketAddressBlockList::SocketAddressRule::MemoryInfo(
node::MemoryTracker* tracker) const {
tracker->TrackField("address", address);
}
void SocketAddressBlockList::SocketAddressRangeRule::MemoryInfo(
node::MemoryTracker* tracker) const {
tracker->TrackField("start", start);
tracker->TrackField("end", end);
}
void SocketAddressBlockList::SocketAddressMaskRule::MemoryInfo(
node::MemoryTracker* tracker) const {
tracker->TrackField("network", network);
}
SocketAddressBlockListWrap::SocketAddressBlockListWrap(
Environment* env,
Local<Object> wrap,
std::shared_ptr<SocketAddressBlockList> blocklist)
: BaseObject(env, wrap),
blocklist_(std::move(blocklist)) {
MakeWeak();
}
BaseObjectPtr<SocketAddressBlockListWrap> SocketAddressBlockListWrap::New(
Environment* env) {
Local<Object> obj;
if (!env->blocklist_constructor_template()
->InstanceTemplate()
->NewInstance(env->context()).ToLocal(&obj)) {
return BaseObjectPtr<SocketAddressBlockListWrap>();
}
BaseObjectPtr<SocketAddressBlockListWrap> wrap =
MakeBaseObject<SocketAddressBlockListWrap>(env, obj);
CHECK(wrap);
return wrap;
}
BaseObjectPtr<SocketAddressBlockListWrap> SocketAddressBlockListWrap::New(
Environment* env,
std::shared_ptr<SocketAddressBlockList> blocklist) {
Local<Object> obj;
if (!env->blocklist_constructor_template()
->InstanceTemplate()
->NewInstance(env->context()).ToLocal(&obj)) {
return BaseObjectPtr<SocketAddressBlockListWrap>();
}
BaseObjectPtr<SocketAddressBlockListWrap> wrap =
MakeBaseObject<SocketAddressBlockListWrap>(
env,
obj,
std::move(blocklist));
CHECK(wrap);
return wrap;
}
void SocketAddressBlockListWrap::New(
const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
new SocketAddressBlockListWrap(env, args.This());
}
void SocketAddressBlockListWrap::AddAddress(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SocketAddressBlockListWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
CHECK(SocketAddressBase::HasInstance(env, args[0]));
SocketAddressBase* addr;
ASSIGN_OR_RETURN_UNWRAP(&addr, args[0]);
wrap->blocklist_->AddSocketAddress(addr->address());
args.GetReturnValue().Set(true);
}
void SocketAddressBlockListWrap::AddRange(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SocketAddressBlockListWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
CHECK(SocketAddressBase::HasInstance(env, args[0]));
CHECK(SocketAddressBase::HasInstance(env, args[1]));
SocketAddressBase* start_addr;
SocketAddressBase* end_addr;
ASSIGN_OR_RETURN_UNWRAP(&start_addr, args[0]);
ASSIGN_OR_RETURN_UNWRAP(&end_addr, args[1]);
// Starting address must come before the end address
if (*start_addr->address().get() > *end_addr->address().get())
return args.GetReturnValue().Set(false);
wrap->blocklist_->AddSocketAddressRange(
start_addr->address(),
end_addr->address());
args.GetReturnValue().Set(true);
}
void SocketAddressBlockListWrap::AddSubnet(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SocketAddressBlockListWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
CHECK(SocketAddressBase::HasInstance(env, args[0]));
CHECK(args[1]->IsInt32());
SocketAddressBase* addr;
ASSIGN_OR_RETURN_UNWRAP(&addr, args[0]);
int32_t prefix;
if (!args[1]->Int32Value(env->context()).To(&prefix)) {
return;
}
CHECK_IMPLIES(addr->address()->family() == AF_INET, prefix <= 32);
CHECK_IMPLIES(addr->address()->family() == AF_INET6, prefix <= 128);
CHECK_GE(prefix, 0);
wrap->blocklist_->AddSocketAddressMask(addr->address(), prefix);
args.GetReturnValue().Set(true);
}
void SocketAddressBlockListWrap::Check(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SocketAddressBlockListWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
CHECK(SocketAddressBase::HasInstance(env, args[0]));
SocketAddressBase* addr;
ASSIGN_OR_RETURN_UNWRAP(&addr, args[0]);
args.GetReturnValue().Set(wrap->blocklist_->Apply(addr->address()));
}
void SocketAddressBlockListWrap::GetRules(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SocketAddressBlockListWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
Local<Array> rules;
if (wrap->blocklist_->ListRules(env).ToLocal(&rules))
args.GetReturnValue().Set(rules);
}
void SocketAddressBlockListWrap::MemoryInfo(MemoryTracker* tracker) const {
blocklist_->MemoryInfo(tracker);
}
std::unique_ptr<worker::TransferData>
SocketAddressBlockListWrap::CloneForMessaging() const {
return std::make_unique<TransferData>(this);
}
bool SocketAddressBlockListWrap::HasInstance(
Environment* env,
Local<Value> value) {
return GetConstructorTemplate(env)->HasInstance(value);
}
Local<FunctionTemplate> SocketAddressBlockListWrap::GetConstructorTemplate(
Environment* env) {
Local<FunctionTemplate> tmpl = env->blocklist_constructor_template();
if (tmpl.IsEmpty()) {
tmpl = env->NewFunctionTemplate(SocketAddressBlockListWrap::New);
tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BlockList"));
tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
tmpl->InstanceTemplate()->SetInternalFieldCount(kInternalFieldCount);
env->SetProtoMethod(tmpl, "addAddress", AddAddress);
env->SetProtoMethod(tmpl, "addRange", AddRange);
env->SetProtoMethod(tmpl, "addSubnet", AddSubnet);
env->SetProtoMethod(tmpl, "check", Check);
env->SetProtoMethod(tmpl, "getRules", GetRules);
env->set_blocklist_constructor_template(tmpl);
}
return tmpl;
}
void SocketAddressBlockListWrap::Initialize(
Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
Environment* env = Environment::GetCurrent(context);
env->SetConstructorFunction(
target,
"BlockList",
GetConstructorTemplate(env),
Environment::SetConstructorFunctionFlag::NONE);
SocketAddressBase::Initialize(env, target);
NODE_DEFINE_CONSTANT(target, AF_INET);
NODE_DEFINE_CONSTANT(target, AF_INET6);
}
BaseObjectPtr<BaseObject> SocketAddressBlockListWrap::TransferData::Deserialize(
Environment* env,
Local<Context> context,
std::unique_ptr<worker::TransferData> self) {
return New(env, std::move(blocklist_));
}
void SocketAddressBlockListWrap::TransferData::MemoryInfo(
MemoryTracker* tracker) const {
blocklist_->MemoryInfo(tracker);
}
bool SocketAddressBase::HasInstance(Environment* env, Local<Value> value) {
return GetConstructorTemplate(env)->HasInstance(value);
}
Local<FunctionTemplate> SocketAddressBase::GetConstructorTemplate(
Environment* env) {
Local<FunctionTemplate> tmpl = env->socketaddress_constructor_template();
if (tmpl.IsEmpty()) {
tmpl = env->NewFunctionTemplate(New);
tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SocketAddress"));
tmpl->InstanceTemplate()->SetInternalFieldCount(
SocketAddressBase::kInternalFieldCount);
tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
env->SetProtoMethod(tmpl, "detail", Detail);
env->SetProtoMethod(tmpl, "legacyDetail", LegacyDetail);
env->SetProtoMethodNoSideEffect(tmpl, "flowlabel", GetFlowLabel);
env->set_socketaddress_constructor_template(tmpl);
}
return tmpl;
}
void SocketAddressBase::Initialize(Environment* env, Local<Object> target) {
env->SetConstructorFunction(
target,
"SocketAddress",
GetConstructorTemplate(env),
Environment::SetConstructorFunctionFlag::NONE);
}
BaseObjectPtr<SocketAddressBase> SocketAddressBase::Create(
Environment* env,
std::shared_ptr<SocketAddress> address) {
Local<Object> obj;
if (!GetConstructorTemplate(env)
->InstanceTemplate()
->NewInstance(env->context()).ToLocal(&obj)) {
return BaseObjectPtr<SocketAddressBase>();
}
return MakeBaseObject<SocketAddressBase>(env, obj, std::move(address));
}
void SocketAddressBase::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(args.IsConstructCall());
CHECK(args[0]->IsString()); // address
CHECK(args[1]->IsInt32()); // port
CHECK(args[2]->IsInt32()); // family
CHECK(args[3]->IsUint32()); // flow label
Utf8Value address(env->isolate(), args[0]);
int32_t port = args[1].As<Int32>()->Value();
int32_t family = args[2].As<Int32>()->Value();
uint32_t flow_label = args[3].As<Uint32>()->Value();
std::shared_ptr<SocketAddress> addr = std::make_shared<SocketAddress>();
if (!SocketAddress::New(family, *address, port, addr.get()))
return THROW_ERR_INVALID_ADDRESS(env);
addr->set_flow_label(flow_label);
new SocketAddressBase(env, args.This(), std::move(addr));
}
void SocketAddressBase::Detail(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(args[0]->IsObject());
Local<Object> detail = args[0].As<Object>();
SocketAddressBase* base;
ASSIGN_OR_RETURN_UNWRAP(&base, args.Holder());
Local<Value> address;
if (!ToV8Value(env->context(), base->address_->address()).ToLocal(&address))
return;
if (detail->Set(env->context(), env->address_string(), address).IsJust() &&
detail->Set(
env->context(),
env->port_string(),
Int32::New(env->isolate(), base->address_->port())).IsJust() &&
detail->Set(
env->context(),
env->family_string(),
Int32::New(env->isolate(), base->address_->family())).IsJust() &&
detail->Set(
env->context(),
env->flowlabel_string(),
Uint32::New(env->isolate(), base->address_->flow_label()))
.IsJust()) {
args.GetReturnValue().Set(detail);
}
}
void SocketAddressBase::GetFlowLabel(const FunctionCallbackInfo<Value>& args) {
SocketAddressBase* base;
ASSIGN_OR_RETURN_UNWRAP(&base, args.Holder());
args.GetReturnValue().Set(base->address_->flow_label());
}
void SocketAddressBase::LegacyDetail(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SocketAddressBase* base;
ASSIGN_OR_RETURN_UNWRAP(&base, args.Holder());
args.GetReturnValue().Set(base->address_->ToJS(env));
}
SocketAddressBase::SocketAddressBase(
Environment* env,
Local<Object> wrap,
std::shared_ptr<SocketAddress> address)
: BaseObject(env, wrap),
address_(std::move(address)) {
MakeWeak();
}
void SocketAddressBase::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("address", address_);
}
std::unique_ptr<worker::TransferData>
SocketAddressBase::CloneForMessaging() const {
return std::make_unique<TransferData>(this);
}
void SocketAddressBase::TransferData::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("address", address_);
}
BaseObjectPtr<BaseObject> SocketAddressBase::TransferData::Deserialize(
Environment* env,
v8::Local<v8::Context> context,
std::unique_ptr<worker::TransferData> self) {
return SocketAddressBase::Create(env, std::move(address_));
}
} // namespace node
NODE_MODULE_CONTEXT_AWARE_INTERNAL(
block_list,
node::SocketAddressBlockListWrap::Initialize)
| 30.337853 | 80 | 0.694923 | [
"object",
"vector"
] |
b15e35e23d36c4479a5d62a1cadf5fc7b2958f47 | 9,220 | cpp | C++ | src/Equations/viscoelastic2/Model/Setup.cpp | ivotron/SeisSol | 51c2935566998480f948caf2b66b27b80df4b2c4 | [
"BSD-3-Clause"
] | null | null | null | src/Equations/viscoelastic2/Model/Setup.cpp | ivotron/SeisSol | 51c2935566998480f948caf2b66b27b80df4b2c4 | [
"BSD-3-Clause"
] | null | null | null | src/Equations/viscoelastic2/Model/Setup.cpp | ivotron/SeisSol | 51c2935566998480f948caf2b66b27b80df4b2c4 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file
* This file is part of SeisSol.
*
* @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)
*
* @section LICENSE
* Copyright (c) 2015, SeisSol Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
**/
#include <Model/Setup.h>
#include <Model/common.hpp>
#include <Kernels/common.hpp>
#include <Numerical_aux/Transformation.h>
#include <yateto/TensorView.h>
#include <generated_code/init.h>
template<typename T>
void getTransposedViscoelasticCoefficientMatrix( real i_omega,
unsigned i_dim,
unsigned mech,
T& o_M )
{
unsigned col = 9 + mech * 6;
switch (i_dim)
{
case 0:
o_M(6, col) = -i_omega;
o_M(7, col + 3) = -0.5 * i_omega;
o_M(8, col + 5) = -0.5 * i_omega;
break;
case 1:
o_M(7, col + 1) = -i_omega;
o_M(6, col + 3) = -0.5 * i_omega;
o_M(8, col + 4) = -0.5 * i_omega;
break;
case 2:
o_M(8, col + 2) = -i_omega;
o_M(7, col + 4) = -0.5 * i_omega;
o_M(6, col + 5) = -0.5 * i_omega;
break;
}
}
template<typename T>
void getTransposedSourceCoefficientTensor( seissol::model::Material const& material, T& E )
{
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
real const* theta = material.theta[mech];
E(0, mech, 0) = theta[0];
E(1, mech, 0) = theta[1];
E(2, mech, 0) = theta[1];
E(0, mech, 1) = theta[1];
E(1, mech, 1) = theta[0];
E(2, mech, 1) = theta[1];
E(0, mech, 2) = theta[1];
E(1, mech, 2) = theta[1];
E(2, mech, 2) = theta[0];
E(3, mech, 3) = theta[2];
E(4, mech, 4) = theta[2];
E(5, mech, 5) = theta[2];
}
}
void seissol::model::getTransposedCoefficientMatrix( Material const& i_material,
unsigned i_dim,
init::star::view<0>::type& AT )
{
seissol::model::getTransposedElasticCoefficientMatrix(i_material, i_dim, AT);
getTransposedViscoelasticCoefficientMatrix( 1.0, i_dim, 0, AT );
}
void seissol::model::getPlaneWaveOperator( Material const& material,
double const n[3],
std::complex<real> Mdata[NUMBER_OF_QUANTITIES*NUMBER_OF_QUANTITIES] )
{
yateto::DenseTensorView<2,std::complex<real>> M(Mdata, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});
M.setZero();
real data[NUMBER_OF_QUANTITIES * NUMBER_OF_QUANTITIES];
yateto::DenseTensorView<2,real> Coeff(data, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});
for (unsigned d = 0; d < 3; ++d) {
Coeff.setZero();
getTransposedElasticCoefficientMatrix(material, d, Coeff);
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
getTransposedViscoelasticCoefficientMatrix( material.omega[mech],
d,
mech,
Coeff );
}
for (unsigned i = 0; i < NUMBER_OF_QUANTITIES; ++i) {
for (unsigned j = 0; j < NUMBER_OF_QUANTITIES; ++j) {
M(i,j) += n[d] * Coeff(j,i);
}
}
}
real Edata[NUMBER_OF_QUANTITIES * NUMBER_OF_QUANTITIES];
yateto::DenseTensorView<3,real> E(Edata, tensor::E::Shape);
E.setZero();
getTransposedSourceCoefficientTensor(material, E);
Coeff.setZero();
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
unsigned offset = 9 + mech * 6;
for (unsigned i = 0; i < tensor::E::Shape[0]; ++i) {
for (unsigned j = 0; j < tensor::E::Shape[2]; ++j) {
Coeff(offset + i, j) = E(i, mech, j);
}
}
}
// E' = diag(-omega_1 I, ..., -omega_L I)
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
unsigned offset = 9 + 6*mech;
yateto::DenseTensorView<2,real> ETblock(data + offset + offset * NUMBER_OF_QUANTITIES, {NUMBER_OF_QUANTITIES, 6});
for (unsigned i = 0; i < 6; ++i) {
ETblock(i, i) = -material.omega[mech];
}
}
for (unsigned i = 0; i < NUMBER_OF_QUANTITIES; ++i) {
for (unsigned j = 0; j < NUMBER_OF_QUANTITIES; ++j) {
M(i,j) -= std::complex<real>(0.0, Coeff(j,i));
}
}
}
void seissol::model::getTransposedGodunovState( Material const& local,
Material const& neighbor,
enum ::faceType faceType,
init::QgodLocal::view::type& QgodLocal,
init::QgodNeighbor::view::type& QgodNeighbor )
{
seissol::model::getTransposedElasticGodunovState(local, neighbor, faceType, QgodLocal, QgodNeighbor);
}
void seissol::model::setMaterial( double* i_materialVal,
int i_numMaterialVals,
seissol::model::Material* o_material )
{
assert(i_numMaterialVals == 3 + NUMBER_OF_RELAXATION_MECHANISMS * 4);
o_material->rho = i_materialVal[0];
o_material->mu = i_materialVal[1];
o_material->lambda = i_materialVal[2];
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
o_material->omega[mech] = i_materialVal[3 + 4*mech];
for (unsigned i = 1; i < 4; ++i) {
o_material->theta[mech][i-1] = i_materialVal[3 + 4*mech + i];
}
}
}
void seissol::model::getFaceRotationMatrix( VrtxCoords const i_normal,
VrtxCoords const i_tangent1,
VrtxCoords const i_tangent2,
init::T::view::type& o_T,
init::Tinv::view::type& o_Tinv )
{
o_T.setZero();
o_Tinv.setZero();
seissol::transformations::symmetricTensor2RotationMatrix(i_normal, i_tangent1, i_tangent2, o_T);
seissol::transformations::inverseSymmetricTensor2RotationMatrix(i_normal, i_tangent1, i_tangent2, o_Tinv);
seissol::transformations::tensor1RotationMatrix(i_normal, i_tangent1, i_tangent2, o_T, 6, 6);
seissol::transformations::inverseTensor1RotationMatrix(i_normal, i_tangent1, i_tangent2, o_Tinv, 6, 6);
seissol::transformations::symmetricTensor2RotationMatrix(i_normal, i_tangent1, i_tangent2, o_T, 9, 9);
}
void seissol::model::initializeSpecificLocalData( seissol::model::Material const& material,
seissol::model::LocalData* localData )
{
auto E = init::E::view::create(localData->E);
E.setZero();
getTransposedSourceCoefficientTensor(material, E);
auto w = init::w::view::create(localData->w);
auto W = init::W::view::create(localData->W);
W.setZero();
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
w(mech) = material.omega[mech];
W(mech,mech) = -material.omega[mech];
}
}
void seissol::model::initializeSpecificNeighborData( seissol::model::Material const& localMaterial,
seissol::model::Material const (&)[4],
seissol::model::NeighborData* neighborData )
{
// We only need the local omegas
auto w = init::w::view::create(neighborData->w);
for (unsigned mech = 0; mech < NUMBER_OF_RELAXATION_MECHANISMS; ++mech) {
w(mech) = localMaterial.omega[mech];
}
}
| 39.234043 | 118 | 0.59577 | [
"shape",
"model"
] |
b15fd76873f4a232624f6b3f276b4b0f472ad884 | 1,603 | cpp | C++ | aws-cpp-sdk-redshift/source/model/CopyClusterSnapshotRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-redshift/source/model/CopyClusterSnapshotRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-redshift/source/model/CopyClusterSnapshotRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/redshift/model/CopyClusterSnapshotRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::Redshift::Model;
using namespace Aws::Utils;
CopyClusterSnapshotRequest::CopyClusterSnapshotRequest() :
m_sourceSnapshotIdentifierHasBeenSet(false),
m_sourceSnapshotClusterIdentifierHasBeenSet(false),
m_targetSnapshotIdentifierHasBeenSet(false),
m_manualSnapshotRetentionPeriod(0),
m_manualSnapshotRetentionPeriodHasBeenSet(false)
{
}
Aws::String CopyClusterSnapshotRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=CopyClusterSnapshot&";
if(m_sourceSnapshotIdentifierHasBeenSet)
{
ss << "SourceSnapshotIdentifier=" << StringUtils::URLEncode(m_sourceSnapshotIdentifier.c_str()) << "&";
}
if(m_sourceSnapshotClusterIdentifierHasBeenSet)
{
ss << "SourceSnapshotClusterIdentifier=" << StringUtils::URLEncode(m_sourceSnapshotClusterIdentifier.c_str()) << "&";
}
if(m_targetSnapshotIdentifierHasBeenSet)
{
ss << "TargetSnapshotIdentifier=" << StringUtils::URLEncode(m_targetSnapshotIdentifier.c_str()) << "&";
}
if(m_manualSnapshotRetentionPeriodHasBeenSet)
{
ss << "ManualSnapshotRetentionPeriod=" << m_manualSnapshotRetentionPeriod << "&";
}
ss << "Version=2012-12-01";
return ss.str();
}
void CopyClusterSnapshotRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
uri.SetQueryString(SerializePayload());
}
| 29.145455 | 121 | 0.756082 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.