hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f165ee0e0575b3f9551ca222649b17959275ae2 | 316 | hpp | C++ | src/libpanacea/entropy/entropy_terms/entropy_term_common.hpp | lanl/PANACEA | 9779bdb6dcc3be41ea7b286ae55a21bb269e0339 | [
"BSD-3-Clause"
] | null | null | null | src/libpanacea/entropy/entropy_terms/entropy_term_common.hpp | lanl/PANACEA | 9779bdb6dcc3be41ea7b286ae55a21bb269e0339 | [
"BSD-3-Clause"
] | null | null | null | src/libpanacea/entropy/entropy_terms/entropy_term_common.hpp | lanl/PANACEA | 9779bdb6dcc3be41ea7b286ae55a21bb269e0339 | [
"BSD-3-Clause"
] | null | null | null |
#ifndef PANACEA_PRIVATE_ENTROPYTERMCOMMON_H
#define PANACEA_PRIVATE_ENTROPYTERMCOMMON_H
#pragma once
namespace panacea {
/**
* Common functions used by entropy terms.
**/
bool is_neg_inf(const double val);
bool is_pos_inf(const double val);
} // namespace panacea
#endif // PANACEA_PRIVATE_ENTROPYTERMCOMMON_H
| 19.75 | 45 | 0.800633 | lanl |
4f16d39e7f1386337a63339050e2b5ad800d088c | 2,438 | cxx | C++ | Readers/FDEM/FDEMCrackJoint.cxx | ObjectivitySRC/PVGPlugins | 5e24150262af751159d719cc810620d1770f2872 | [
"BSD-2-Clause"
] | 4 | 2016-01-21T21:45:43.000Z | 2021-07-31T19:24:09.000Z | Readers/FDEM/FDEMCrackJoint.cxx | ObjectivitySRC/PVGPlugins | 5e24150262af751159d719cc810620d1770f2872 | [
"BSD-2-Clause"
] | null | null | null | Readers/FDEM/FDEMCrackJoint.cxx | ObjectivitySRC/PVGPlugins | 5e24150262af751159d719cc810620d1770f2872 | [
"BSD-2-Clause"
] | 6 | 2015-08-31T06:21:03.000Z | 2021-07-31T19:24:10.000Z |
#include "FDEMCrackJoint.h"
#include "vtkDoubleArray.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkPolyData.h"
#define ZLEVEL 0.00001
#define MODE_CRACK 0
#define MODE_JOINT 1
// --------------------------------------
FDEMCrackJoint::FDEMCrackJoint( char* Name, int mode, double NormCoord)
{
this->HasData = false;
this->Mode = mode;
this->Name = Name;
this->NormCoord = NormCoord;
}
// --------------------------------------
void FDEMCrackJoint::Add( double block[100] )
{
const vtkIdType size = 4; //joints have 4
vtkIdType *Id = new vtkIdType[size] ;
float x[size], y[size], z=ZLEVEL; //2nd image, dont need more than 1 z
float damage;
//read in the info for the cracks / joints
for(int i=0; i<size; i++)
{
x[i] =(float)block[3+i] * this->NormCoord;
y[i] =(float)block[7+i] * this->NormCoord;
}
//grab the damage entry for this crack or joint
damage = (float) block[11];
if ( damage < 0.0 )
{
//change null values to -1
damage = -1;
}
else if ( damage > 0.0)
{
//calcualte out the damage, and make sure it falls in the range
//of -1 to 1
damage = ( (float)block[11] + (float)block[13] ) * 0.5;
if (damage > 1.0)
{
damage = 1.0;
}
else if (damage < -1.0)
{
damage = -1.0;
}
}
//set the points and cells
if ( ( damage < 0.0 && this->Mode == MODE_CRACK ) || ( damage > 0.0 && this->Mode >= MODE_JOINT ) )
{
this->HasData = true; //only place we really know the block is damaged
for (int i=0; i < size; i++)
{
Id[i] = this->Points->InsertNextPoint(x[i], y[i], z);
}
for (int i=0; i < 4; i+=2)
{
this->Cells->InsertNextCell(2); //drawing lines
this->Cells->InsertCellPoint(Id[i]);
this->Cells->InsertCellPoint(Id[i+1]);
this->Properties->AddDamage( damage );
}
}
}
// --------------------------------------
void FDEMCrackJoint::AddProperties( double block[100] )
{
//not used in this class
}
// --------------------------------------
vtkPolyData* FDEMCrackJoint::GetOutput()
{
this->Output->SetPoints( this->Points );
this->Output->SetLines( this->Cells );
this->Properties->PushToObject( this->Output->GetCellData() );
return this->Output;
}
#undef ZLEVL | 24.38 | 104 | 0.535275 | ObjectivitySRC |
4f18301d62686a2f2440f28f518dccc5a53ae6d8 | 1,989 | inl | C++ | blast/include/html/components.inl | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | blast/include/html/components.inl | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | blast/include/html/components.inl | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | #if defined(HTML___COMPONENTS__HPP) && !defined(HTML___COMPONENTS__INL)
#define HTML___COMPONENTS__INL
/* $Id: components.inl 176066 2009-11-13 19:01:39Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
*/
inline COptionDescription::COptionDescription(void)
{
return;
}
inline COptionDescription::COptionDescription(const string& value)
: m_Value(value)
{
return;
}
inline COptionDescription::COptionDescription(const string& value,
const string& label)
: m_Value(value), m_Label(label)
{
return;
}
inline void CSelectDescription::Add(int value)
{
Add(NStr::IntToString(value));
}
#endif /* def HTML___COMPONENTS__HPP && ndef HTML___COMPONENTS__INL */
| 33.15 | 78 | 0.656109 | mycolab |
4f1a3b0a9da6e509f700595b59c4698cbb8f870c | 1,145 | cpp | C++ | src/gl/glshaderprogram.cpp | helloer/polybobin | 63b2cea40d3afcfc9d6f62f49acbfacf6a8783e1 | [
"MIT"
] | 8 | 2016-10-06T11:49:14.000Z | 2021-11-06T21:06:36.000Z | src/gl/glshaderprogram.cpp | helloer/polybobin | 63b2cea40d3afcfc9d6f62f49acbfacf6a8783e1 | [
"MIT"
] | 20 | 2017-04-25T14:23:02.000Z | 2018-12-04T22:46:04.000Z | src/gl/glshaderprogram.cpp | helloer/polybobin | 63b2cea40d3afcfc9d6f62f49acbfacf6a8783e1 | [
"MIT"
] | 4 | 2016-11-22T16:06:18.000Z | 2021-05-28T21:53:52.000Z | #include "glshaderprogram.hpp"
#include <system_error>
void GLShaderProgram::AddShader(GLenum type, const GLchar *code)
{
GLShader shader(type, code);
m_shaders.push_back(shader);
}
GLuint GLShaderProgram::GetUniformLocation(const GLchar *name)
{
return glGetUniformLocation(m_id, name);
}
void GLShaderProgram::Init()
{
for (auto &shader : m_shaders)
{
shader.Create();
shader.Compile();
}
m_id = glCreateProgram();
for (auto &shader : m_shaders)
{
glAttachShader(m_id, shader.GetId());
}
Link();
for (auto &shader : m_shaders)
{
shader.Delete();
}
}
void GLShaderProgram::StopUse()
{
glUseProgram(0);
}
void GLShaderProgram::Use()
{
glUseProgram(m_id);
}
void GLShaderProgram::Link()
{
GLint success;
char infoLog[512];
glLinkProgram(m_id);
glGetProgramiv(m_id, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(m_id, sizeof(infoLog), NULL, infoLog);
throw std::runtime_error("An error occurred when linking an OpenGL shader program : \n" + std::string(infoLog));
}
} | 19.083333 | 120 | 0.639301 | helloer |
4f1c1d15af31499388f3c0bdcaddce6b925fcabf | 1,327 | cpp | C++ | src/rulah_navigation_goals.cpp | yorgosk/ugv_navigation_goals | 87bc8eaf926c53de8e9451748da11b2ddc2f04f5 | [
"MIT"
] | 2 | 2021-08-16T09:17:06.000Z | 2022-03-10T21:59:20.000Z | src/rulah_navigation_goals.cpp | yorgosk/ugv_navigation_goals | 87bc8eaf926c53de8e9451748da11b2ddc2f04f5 | [
"MIT"
] | null | null | null | src/rulah_navigation_goals.cpp | yorgosk/ugv_navigation_goals | 87bc8eaf926c53de8e9451748da11b2ddc2f04f5 | [
"MIT"
] | 3 | 2019-04-20T07:32:25.000Z | 2021-05-30T11:43:06.000Z | /* computer & execution parameters -- in this file and not header file for faster compilation */
// #define TEST_BEZIER
// #define TEST_CALCULATIONS
// #define EVOLUTIONARY_ALGORITHM_GENERATION
// #define N_BEST_GENERATION
// #define NAIVE_GENERATION
#include "header.hpp"
#ifdef TEST_BEZIER
/* Test Bezier curve's core functions */
int main(int argc, char *argv[]) {
bezierTest(argc, argv);
return 0;
}
#elif defined( TEST_CALCULATIONS )
/* Test calculations core functions */
int main(int argc, char *argv[]) {
calculationsTest(argc, argv);
return 0;
}
#elif defined( NAIVE_GENERATION )
/* An naive waypoint generation algorithm implementation */
int main(int argc, char *argv[]) {
naiveGenerator(argc, argv);
return 0;
}
#elif defined( EVOLUTIONARY_ALGORITHM_GENERATION )
/* An Evolutionary-algorithm based waypoint generation implementation */
int main(int argc, char *argv[]) {
evolutionaryAlgorithmGenerator(argc, argv);
return 0;
}
#elif defined( N_BEST_GENERATION )
/* An N-best based waypoint generation implementation */
int main(int argc, char *argv[]) {
nBestGenerator(argc, argv);
return 0;
}
#else
/* A Hill-climbing based waypoint generation implementation */
int main(int argc, char *argv[]) {
hillClimbingGenerator(argc, argv);
return 0;
}
#endif
| 22.491525 | 96 | 0.717408 | yorgosk |
b7b32fe5a300abac022f1640868e17edeed95bde | 3,658 | hpp | C++ | warpcoil/cpp/generate/generate_type.hpp | TyRoXx/warpcoil | e0454a7880fa644dfb6e77968a37f8547590c15f | [
"MIT"
] | 2 | 2018-06-04T06:44:00.000Z | 2018-09-14T09:45:12.000Z | warpcoil/cpp/generate/generate_type.hpp | TyRoXx/warpcoil | e0454a7880fa644dfb6e77968a37f8547590c15f | [
"MIT"
] | 40 | 2016-05-01T12:51:47.000Z | 2016-09-04T14:21:51.000Z | warpcoil/cpp/generate/generate_type.hpp | TyRoXx/warpcoil | e0454a7880fa644dfb6e77968a37f8547590c15f | [
"MIT"
] | 2 | 2018-06-04T06:44:06.000Z | 2018-09-14T09:45:19.000Z | #pragma once
#include <warpcoil/cpp/generate/shared_code_generator.hpp>
#include <warpcoil/comma_separator.hpp>
#include <warpcoil/cpp/generate/generate_name_for_structure.hpp>
#include <silicium/sink/ptr_sink.hpp>
namespace warpcoil
{
namespace cpp
{
inline Si::memory_range find_suitable_uint_cpp_type(types::integer range)
{
if (range.maximum <= 0xffu)
{
return Si::make_c_str_range("std::uint8_t");
}
if (range.maximum <= 0xffffu)
{
return Si::make_c_str_range("std::uint16_t");
}
if (range.maximum <= 0xffffffffu)
{
return Si::make_c_str_range("std::uint32_t");
}
return Si::make_c_str_range("std::uint64_t");
}
template <class CharSink1, class CharSink2>
type_emptiness generate_type(CharSink1 &&code, shared_code_generator<CharSink2> &shared,
types::type const &root)
{
return Si::visit<type_emptiness>(
root,
[&code](types::integer range)
{
Si::append(code, find_suitable_uint_cpp_type(range));
return type_emptiness::non_empty;
},
[&](std::unique_ptr<types::variant> const &root)
{
assert(root);
Si::append(code, "Si::variant<");
auto comma = make_comma_separator(Si::ref_sink(code));
for (types::type const &element : root->elements)
{
comma.add_element();
generate_type(code, shared, element);
}
Si::append(code, ">");
return root->elements.empty() ? type_emptiness::empty
: type_emptiness::non_empty;
},
[&](std::unique_ptr<types::tuple> const &root)
{
assert(root);
Si::append(code, "std::tuple<");
auto comma = make_comma_separator(Si::ref_sink(code));
for (types::type const &element : root->elements)
{
comma.add_element();
generate_type(code, shared, element);
}
Si::append(code, ">");
return root->elements.empty() ? type_emptiness::empty
: type_emptiness::non_empty;
},
[&](std::unique_ptr<types::vector> const &root)
{
assert(root);
Si::append(code, "std::vector<");
generate_type(code, shared, root->element);
Si::append(code, ">");
return type_emptiness::non_empty;
},
[&code](types::utf8)
{
Si::append(code, "std::string");
return type_emptiness::non_empty;
},
[&](std::unique_ptr<types::structure> const &root) -> type_emptiness
{
assert(root);
shared.require_structure(*root);
generate_name_for_structure(code, *root);
return (root->elements.empty() ? type_emptiness::empty
: type_emptiness::non_empty);
});
}
}
}
| 39.76087 | 96 | 0.45134 | TyRoXx |
b7b767f3dc8042bb09e74f3acd7217f1c93de2b6 | 12,939 | cc | C++ | projects/S0009D/code/object.cc | Syrdni/S0009D | b159b3c73cc975885a7ce204c3d60f6d776f8654 | [
"MIT"
] | null | null | null | projects/S0009D/code/object.cc | Syrdni/S0009D | b159b3c73cc975885a7ce204c3d60f6d776f8654 | [
"MIT"
] | null | null | null | projects/S0009D/code/object.cc | Syrdni/S0009D | b159b3c73cc975885a7ce204c3d60f6d776f8654 | [
"MIT"
] | null | null | null | #include "object.h"
Object::Object(){}
Object::Object(MeshResource* mr, ShaderObject* so, TextureResource* tr, LightingNode* ln, Vector4D& cameraPos, std::string texturePath, Vector4D scale, float mass, bool unmovable)
{
this->scale = scale;
setupGraphicsNode(mr, so, tr, ln, cameraPos, texturePath);
rb = Rigidbody(originalAABB, mass, totalRotation, getReferenceToPosition(), unmovable);
setScaleMatrix(Matrix4D::getScaleMatrix(scale));
}
Object::~Object(){}
void Object::setupGraphicsNode(MeshResource* mr, ShaderObject* so, TextureResource* tr, LightingNode* ln, Vector4D& cameraPos, std::string texturePath)
{
graphicsNode.setMeshResource(mr);
graphicsNode.setShaderObject(so);
graphicsNode.setTextureResource(tr);
graphicsNode.setlightingNode(ln);
graphicsNode.setCameraPosition(cameraPos);
graphicsNode.loadTexture(texturePath.c_str());
graphicsNode.preDrawSetup();
setupFirstAABB(graphicsNode.getMeshResource()->getVertexBuffer());
}
void Object::setViewMatrix(Matrix4D viewmatrix)
{
this->viewmatrix = viewmatrix;
}
void Object::setupFirstAABB(std::vector<Vertex> vertices)
{
//Create the original AABB with mesh data
for (int i = 0; i < vertices.size(); i++)
{
if (vertices[i].pos[0] > originalAABB.maxPoint[0])
originalAABB.maxPoint[0] = vertices[i].pos[0];
else if (vertices[i].pos[0] < originalAABB.minPoint[0])
originalAABB.minPoint[0] = vertices[i].pos[0];
if (vertices[i].pos[1] > originalAABB.maxPoint[1])
originalAABB.maxPoint[1] = vertices[i].pos[1];
else if (vertices[i].pos[1] < originalAABB.minPoint[1])
originalAABB.minPoint[1] = vertices[i].pos[1];
if (vertices[i].pos[2] > originalAABB.maxPoint[2])
originalAABB.maxPoint[2] = vertices[i].pos[2];
else if (vertices[i].pos[2] < originalAABB.minPoint[2])
originalAABB.minPoint[2] = vertices[i].pos[2];
}
//Convert to worldspace
originalAABB.minPoint[0] += position[0];
originalAABB.minPoint[1] += position[1];
originalAABB.minPoint[2] += position[2];
originalAABB.maxPoint[0] += position[0];
originalAABB.maxPoint[1] += position[1];
originalAABB.maxPoint[2] += position[2];
originalAABB.maxPoint = Matrix4D::getScaleMatrix(scale) * originalAABB.maxPoint;
originalAABB.minPoint = Matrix4D::getScaleMatrix(scale) * originalAABB.minPoint;
//Set current AABB to the original
currentAABB = originalAABB;
//Debug things
Vector4D dimentions = Vector4D(originalAABB.maxPoint[0]-originalAABB.minPoint[0], originalAABB.maxPoint[1]-originalAABB.minPoint[1], originalAABB.maxPoint[2]-originalAABB.minPoint[2], 1);
Vector4D pos = Vector4D(originalAABB.minPoint[0] + (dimentions[0]/2),
originalAABB.minPoint[1] + (dimentions[1]/2),
originalAABB.minPoint[2] + (dimentions[2]/2),
1);
//DebugManager::getInstance()->createSingleFrameCube(pos, dimentions[0], dimentions[1], dimentions[2], colorOnAABB, true);
}
void Object::updateAABB()
{
//Reset AABB
currentAABB.maxPoint = Vector4D(-99999, -99999, -99999, 1);
currentAABB.minPoint = Vector4D(99999, 99999, 99999, 1);
//Create a vector that will contain all the points for the AABB
std::vector<Vector4D> pointVector;
//Create the combinedMatrix with rotation and scale
Matrix4D combinedMatrix = totalRotation;
//Apply the matrix to the original AABB and add the new points to the vector
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.maxPoint[0], originalAABB.maxPoint[1], originalAABB.maxPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.maxPoint[0], originalAABB.minPoint[1], originalAABB.maxPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.minPoint[0], originalAABB.minPoint[1], originalAABB.maxPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.minPoint[0], originalAABB.maxPoint[1], originalAABB.maxPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.maxPoint[0], originalAABB.maxPoint[1], originalAABB.minPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.maxPoint[0], originalAABB.minPoint[1], originalAABB.minPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.minPoint[0], originalAABB.minPoint[1], originalAABB.minPoint[2], 1));
pointVector.push_back(combinedMatrix * Vector4D(originalAABB.minPoint[0], originalAABB.maxPoint[1], originalAABB.minPoint[2], 1));
//Find the min and max
for (int i = 0; i < pointVector.size(); i++)
{
if (pointVector[i][0] >= currentAABB.maxPoint[0]) currentAABB.maxPoint[0] = pointVector[i][0];
if (pointVector[i][1] >= currentAABB.maxPoint[1]) currentAABB.maxPoint[1] = pointVector[i][1];
if (pointVector[i][2] >= currentAABB.maxPoint[2]) currentAABB.maxPoint[2] = pointVector[i][2];
if (pointVector[i][0] <= currentAABB.minPoint[0]) currentAABB.minPoint[0] = pointVector[i][0];
if (pointVector[i][1] <= currentAABB.minPoint[1]) currentAABB.minPoint[1] = pointVector[i][1];
if (pointVector[i][2] <= currentAABB.minPoint[2]) currentAABB.minPoint[2] = pointVector[i][2];
}
//Apply position matrix to the new AABB
currentAABB.minPoint = Matrix4D::getPositionMatrix(position) * currentAABB.minPoint;
currentAABB.maxPoint = Matrix4D::getPositionMatrix(position) * currentAABB.maxPoint;
//Debug thingy
Vector4D dimentions = Vector4D(currentAABB.maxPoint[0]-currentAABB.minPoint[0], currentAABB.maxPoint[1]-currentAABB.minPoint[1], currentAABB.maxPoint[2]-currentAABB.minPoint[2], 1);
Vector4D pos = Vector4D(currentAABB.minPoint[0] + (dimentions[0]/2),
currentAABB.minPoint[1] + (dimentions[1]/2),
currentAABB.minPoint[2] + (dimentions[2]/2),
1);
//DebugManager::getInstance()->createSingleFrameCube(pos, dimentions[0], dimentions[1], dimentions[2], colorOnAABB, true);
}
void Object::draw()
{
//Debug thiny for AABB
Vector4D dimentions = Vector4D(currentAABB.maxPoint[0]-currentAABB.minPoint[0], currentAABB.maxPoint[1]-currentAABB.minPoint[1], currentAABB.maxPoint[2]-currentAABB.minPoint[2], 1);
Vector4D pos = Vector4D(currentAABB.minPoint[0] + (dimentions[0]/2),
currentAABB.minPoint[1] + (dimentions[1]/2),
currentAABB.minPoint[2] + (dimentions[2]/2),
1);
//DebugManager::getInstance()->createSingleFrameCube(pos, dimentions[0], dimentions[1], dimentions[2], colorOnAABB, true);
colorOnAABB = Vector4D(0, 0, 1, 0);
Matrix4D rotationX = Matrix4D::rotX(rotation[0]);
Matrix4D rotationY = Matrix4D::rotY(rotation[1]);
Matrix4D rotationZ = Matrix4D::rotZ(rotation[2]);
totalRotation = rb.getRotation();
Vector4D center = rb.getCenterPoint();
Vector4D mcenter = center * -1;
totalRotation = Matrix4D::getPositionMatrix(center) * totalRotation * Matrix4D::getPositionMatrix(mcenter);
// graphicsNode.setTransform(viewmatrix * Matrix4D::getPositionMatrix(position) * totalRotation * Matrix4D::getScaleMatrix(scale));
// graphicsNode.setPosition(Matrix4D::getPositionMatrix(position) * totalRotation * Matrix4D::getScaleMatrix(scale));
graphicsNode.setTransform(viewmatrix * rb.worldTransform);
graphicsNode.setPosition(rb.worldTransform);
graphicsNode.draw();
}
void Object::update()
{
position = rb.getPosition();
totalRotation = rb.getRotation();
rb.update();
updateAABB();
draw();
}
AABB Object::getAABB()
{
return currentAABB;
}
PointAndDistance Object::checkIfRayIntersects(Ray ray)
{
if (rb.unmovable)
{
return PointAndDistance(Vector4D(0, 0, 0, -1), -1, {});
}
std::vector<PointAndDistance> intersectionPoints;
Vector4D normal1, normal2, normal3;
//Get the combined matrix of scale and rotation
Matrix4D combinedMatrix = rb.worldTransform;// Matrix4D::getPositionMatrix(position) * totalRotation * Matrix4D::getScaleMatrix(scale);
//Get the Vertex and index buffer
std::vector<Vertex> vertBuffer = graphicsNode.getMeshResource()->getVertexBuffer();
std::vector<int> indBuffer = graphicsNode.getMeshResource()->getIndexBuffer();
//Save origin for so we can use it to calculate distance
Vector4D originOriginal = ray.getOrigin();
//Convert the ray into the localspace of the model
ray.setOrigin(Vector4D(ray.getOrigin()[0], ray.getOrigin()[1], ray.getOrigin()[2], 1)); //Set 4 coord to 1 or else...
ray.setOrigin(Matrix4D::inverse(combinedMatrix) * ray.getOrigin());
ray.setDirection(Matrix4D::inverse(combinedMatrix) * ray.getDirection());
ray.setDirection(Vector4D(ray.getDirection()[0], ray.getDirection()[1], ray.getDirection()[2], 0)); //Same here
//Loop through all the triangles
for (int i = 0; i < indBuffer.size(); i += 3)
{
//Calculate the normal for the triangle
Vector4D pos1, pos2, pos3;
pos1[0] = vertBuffer[indBuffer[i]].pos[0]; pos1[1] = vertBuffer[indBuffer[i]].pos[1]; pos1[2] = vertBuffer[indBuffer[i]].pos[2];
pos2[0] = vertBuffer[indBuffer[i+1]].pos[0]; pos2[1] = vertBuffer[indBuffer[i+1]].pos[1]; pos2[2] = vertBuffer[indBuffer[i+1]].pos[2];
pos3[0] = vertBuffer[indBuffer[i+2]].pos[0]; pos3[1] = vertBuffer[indBuffer[i+2]].pos[1]; pos3[2] = vertBuffer[indBuffer[i+2]].pos[2];
Vector4D normal = (pos2 - pos1).crossProduct(pos3 - pos1);
normal = normal.normalize();
//Cehck if we hit the triangle
if (Vector4D::dotProduct(normal, ray.getDirection()) < 0)
{
//Construct the vectors we need to check if our point is inside the plane
Vector4D v2v1 = pos2-pos1; Vector4D v3v2 = pos3-pos2; Vector4D v1v3 = pos1-pos3;
//Find the point where we intersected with the plane
PointAndDistance temp = ray.intersect(mPlane((pos1 + pos2 + pos3)*(1.0/3.0), normal));
if (temp.distance == -1)
continue;
temp.point[3] = 1;
//Calculate vetors towards the point from all corners of the triangle
Vector4D PV0 = temp.point - pos1; Vector4D PV1 = temp.point - pos2; Vector4D PV2 = temp.point - pos3;
//Check if we are inside the triangle
if (Vector4D::dotProduct(normal, v2v1.crossProduct(PV0)) > 0 &&
Vector4D::dotProduct(normal, v3v2.crossProduct(PV1)) > 0 &&
Vector4D::dotProduct(normal, v1v3.crossProduct(PV2)) > 0)
{
//DebugManager::getInstance()->createCube((combinedMatrix * temp.point), 0.5, 0.5, 0.5, Vector4D(1, 0, 0, 1));
//Add the intersection point to the vector
intersectionPoints.push_back(PointAndDistance(combinedMatrix * temp.point, temp.distance, temp.normal));
}
}
}
//If we didnt intersect with the mesh return with distance of -1
if (intersectionPoints.size() <= 0)
return PointAndDistance(Vector4D(0, 0, 0, -1), -1, {});
//Else find the closest point of intersection and return it
PointAndDistance closest = PointAndDistance(Vector4D(0, 0, 0, -1), 999999, {});
for (int i = 0; i < intersectionPoints.size(); i++)
{
if (closest.distance > intersectionPoints[i].distance)
closest = intersectionPoints[i];
}
return closest;
}
Vector4D& Object::getReferenceToPosition()
{
return rb.getPosition();
}
Vector4D& Object::getReferenceToRotation()
{
return rotation;
}
Vector4D& Object::getReferenceToScale()
{
return scale;
}
Rigidbody& Object::getReferenceToRigidbody()
{
return rb;
}
AABB& Object::getReferenceToAABB()
{
return currentAABB;
}
GraphicsNode Object::getGraphicsNode()
{
return graphicsNode;
}
Matrix4D Object::getRotation()
{
return totalRotation;
}
Vector4D Object::indexOfFurthestPoint(Vector4D direction)
{
int index = 0;
std::vector<Vertex> vertexBuffer = graphicsNode.getMeshResource()->getVertexBuffer();
float maxProduct = direction.dotProduct(rb.worldTransform * Vector4D(vertexBuffer[0].pos, 1));
float product = 0;
for (int i = 1; i < vertexBuffer.size(); i++)
{
product = direction.dotProduct(rb.worldTransform * Vector4D(vertexBuffer[i].pos, 1));
if (product > maxProduct)
{
maxProduct = product;
index = i;
}
}
return rb.worldTransform * Vector4D(vertexBuffer[index].pos, 1);
}
void Object::setScaleMatrix(Matrix4D scale)
{
rb.scale = scale;
rb.worldTransform = rb.worldTransform * scale;
} | 41.471154 | 191 | 0.668831 | Syrdni |
b7b8a9c852a994ca9dcc143ca4e916c78569a5be | 7,859 | cpp | C++ | Source Code/AsTeRICS/ARE/components/sensor.eyetracker/src/main/c++/posit/posit.cpp | EliKabasele/openHAB_MyUI | f6c66a42cca24a484c2bd4013b20b05edaa88161 | [
"Apache-2.0"
] | 2 | 2016-06-30T14:32:51.000Z | 2017-09-12T18:09:18.000Z | Source Code/AsTeRICS/ARE/components/sensor.eyetracker/src/main/c++/posit/posit.cpp | EliKabasele/openHAB_MyUI | f6c66a42cca24a484c2bd4013b20b05edaa88161 | [
"Apache-2.0"
] | null | null | null | Source Code/AsTeRICS/ARE/components/sensor.eyetracker/src/main/c++/posit/posit.cpp | EliKabasele/openHAB_MyUI | f6c66a42cca24a484c2bd4013b20b05edaa88161 | [
"Apache-2.0"
] | null | null | null | /*
* AsTeRICS - Assistive Technology Rapid Integration and Construction Set
*
*
* d8888 88888888888 8888888b. 8888888 .d8888b. .d8888b.
* d88888 888 888 Y88b 888 d88P Y88b d88P Y88b
* d88P888 888 888 888 888 888 888 Y88b.
* d88P 888 .d8888b 888 .d88b. 888 d88P 888 888 "Y888b.
* d88P 888 88K 888 d8P Y8b 8888888P" 888 888 "Y88b.
* d88P 888 "Y8888b. 888 88888888 888 T88b 888 888 888 "888
* d8888888888 X88 888 Y8b. 888 T88b 888 Y88b d88P Y88b d88P
* d88P 888 88888P' 888 "Y8888 888 T88b 8888888 "Y8888P" "Y8888P"
*
*
* homepage: http://www.asterics.org
*
* This project has been funded by the European Commission,
* Grant Agreement Number 247730
*
*
* Dual License: MIT or GPL v3.0 with "CLASSPATH" exception
* (please refer to the folder LICENSE)
*
*/
#include <jni.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <windows.h>
#include <fstream>
#include "posit.h"
#include "opencv_includes.h"
#include "posit_impl.h"
HANDLE InfoWindowHandle = 0;
DWORD dwPositThreadId;
CPOSIT* ptr_positObj;
int threadMode = 0;
int screenResWidth = 1680, screenResHeight = 1050;
DWORD WINAPI InfoWindowProc(LPVOID lpv)
{
int cntEvalCycle;
int nextEvalPoint;
int evalPointInterval = 30; //equals ~ 3 seconds between each eval point
int cntEvalCol, cntEvalRow, crossPosX, crossPosY;
int evalHDistance, evalVDistance;
int actThreadMode = 1;
threadMode = 1;
std::string string_buf;
string_buf.reserve(15);
cv::Mat dst = cv::Mat::zeros(cv::Size(RESWIDTH, RESHEIGHT), CV_8UC3);
cv::Mat fsimg;
cv::namedWindow("Info",CV_WINDOW_AUTOSIZE);
cv::waitKey(1);
//thread Modes: 0=off, 1=run Info Window, 2 = run Evaluation of Accuracy
while(threadMode != 0)
{
//Mode 1: show info window
if (threadMode == 1)
{
ptr_positObj->getDebugImage(dst);
cv::imshow("Info", dst);
actThreadMode = 1;
cv::waitKey(33);
}
//Mode 2: Evaluate Accuracy
//Info window will not be updated in this mode
if (threadMode == 2)
{
//if last mode was mode 1 or mode 2: open Eval window
if(actThreadMode == 1)
{
ptr_positObj->clearEvalVectors();
fsimg = cv::Mat::zeros(cv::Size(screenResWidth, screenResHeight), CV_8UC3);
cntEvalCycle = 0;
nextEvalPoint = 0;
cntEvalCol = 0;
cntEvalRow = 0;
crossPosX = 0;
crossPosY = 0;
cv::namedWindow("EvalAccuracy",CV_WINDOW_NORMAL);
cv::waitKey(1);
cv::setWindowProperty("EvalAccuracy",CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
cv::waitKey(1);
cv::imshow("EvalAccuracy",fsimg);
evalHDistance = (screenResWidth-40) / 2;
evalVDistance = (screenResHeight-40) / 2;
}
actThreadMode = threadMode;
//create sequence for each evaluation point
if (cntEvalCycle == nextEvalPoint)
{
if (nextEvalPoint !=0)
{
ptr_positObj->copyTempEyeVal();
ptr_positObj->copyTRVal();
}
if (cntEvalCycle >= (9*evalPointInterval))
{
printf("write file!\n");
ptr_positObj->writeEvalFile();
ptr_positObj->setThreadMode(1);
cntEvalCycle = 0;
}
else
{
crossPosX = 20 + cntEvalCol * evalHDistance;
crossPosY = 20 + cntEvalRow * evalVDistance;
if (cntEvalCol >= 2)
{
cntEvalCol = 0;
cntEvalRow++;
}
else cntEvalCol++;
ptr_positObj->getEvalImage(screenResWidth, screenResHeight, crossPosX, crossPosY, fsimg);
nextEvalPoint += evalPointInterval;
cntEvalCycle++;
}
cv::imshow("EvalAccuracy", fsimg);
}
else cntEvalCycle++;
cv::waitKey(100); //wait ~100ms
}
threadMode = ptr_positObj->getThreadMode();
//close no longer required windows
if (threadMode == 1 && actThreadMode == 2)
{
cv::destroyWindow("EvalAccuracy");
cv::waitKey(1);
}
}
cv::destroyAllWindows();
cv::waitKey(1);
return(1);
}
//called when the start or resume buttton of the ACS is pressed
JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_eyetracker_jni_BridgePOSIT_activate
(JNIEnv *env, jobject obj)
{
ptr_positObj = new CPOSIT;
ptr_positObj->init();
return 1;
}
//called when the stop or pause button of the ACS is pressed
JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_eyetracker_jni_BridgePOSIT_deactivate
(JNIEnv *env, jobject obj)
{
int mode = ptr_positObj->getThreadMode();
if (mode)
{
ptr_positObj->setThreadMode(0);
DWORD wait = WaitForSingleObject(InfoWindowHandle,1000);
CloseHandle(InfoWindowHandle);
InfoWindowHandle = 0;
}
delete ptr_positObj;
return 1;
}
JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_eyetracker_jni_BridgePOSIT_runPOSIT
(JNIEnv *env, jobject obj, jint x1, jint y1, jint x2, jint y2, jint x3, jint y3, jint x4, jint y4)
{
jclass cls = env->GetObjectClass(obj);
jmethodID mid;
float tmpx, tmpy, tmpz;
ptr_positObj->runPOSIT((int)x1, (int)y1, (int)x2, (int)y2, (int)x3, (int)y3, (int)x4, (int)y4);
if (ptr_positObj->getThreadMode()!=0)
ptr_positObj->createDebugInfo();
//callback into Java: pass rotation and translation vector back to Java
ptr_positObj->getRVrad(tmpx, tmpy, tmpz);
mid = env->GetMethodID(cls, "newRotationVector_callback", "(FFF)V");
if (mid == 0) //no method attached
return -1;
env->CallVoidMethod(obj, mid, (jfloat) tmpx, (jfloat) tmpy, (jfloat) tmpz);
ptr_positObj->getTV(tmpx, tmpy, tmpz);
mid = env->GetMethodID(cls, "newTranslationVector_callback", "(FFF)V");
if (mid == 0) //no method attached
return -1;
env->CallVoidMethod(obj, mid, (jfloat) tmpx, (jfloat) tmpy, (jfloat) tmpz);
return 1;
}
JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_eyetracker_jni_BridgePOSIT_togglePoseInfoWindow
(JNIEnv *env, jobject obj)
{
threadMode = ptr_positObj->getThreadMode();
if (threadMode == 0)
{
ptr_positObj->setThreadMode(1);
InfoWindowHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) InfoWindowProc, (LPVOID) NULL, 0, &dwPositThreadId);
if (InfoWindowHandle == NULL) { printf("CreateThread for Info Window failed\n"); return(0); }
}
if (threadMode >= 1)
{
ptr_positObj->setThreadMode(0);
DWORD wait = WaitForSingleObject(InfoWindowHandle,1000);
CloseHandle(InfoWindowHandle);
InfoWindowHandle = 0;
}
return 1;
}
JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_eyetracker_jni_BridgePOSIT_startEval
(JNIEnv *env, jobject obj, jint screenX, jint screenY)
{
screenResWidth = screenX;
screenResHeight = screenY;
threadMode = ptr_positObj->getThreadMode();
if (threadMode == 0)
{
ptr_positObj->setThreadMode(2);
InfoWindowHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) InfoWindowProc, (LPVOID) NULL, 0, &dwPositThreadId);
if (InfoWindowHandle == NULL) { printf("CreateThread for Info Window + Start Eval failed\n"); return(0); }
}
if (threadMode == 1)
{
ptr_positObj->setThreadMode(2);
}
return 1;
}
//this method receives the values send by the JVM
JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_eyetracker_jni_BridgePOSIT_sendEvalParams
(JNIEnv *env, jobject obj, jint rawX, jint rawY, jint actX, jint actY)
{
int tempMode = ptr_positObj->getThreadMode();
if (tempMode == 2)
ptr_positObj->setTempEyeVal((int)rawX, (int)rawY, (int)actX, (int)actY);
else
{//callback to stop sending the eye coordinates
jclass cls = env->GetObjectClass(obj);
jmethodID mid;
mid = env->GetMethodID(cls, "stopSendEyeCoordinates_callback", "()V");
if (mid == 0) //no method attached
return -1;
env->CallVoidMethod(obj, mid);
//printf("native Code: call to stop sending eye coordinates\n");
}
//printf("received eval values from JVM\n");
return 1;
} | 27.868794 | 120 | 0.680239 | EliKabasele |
b7babcfe588e74cd23e0dc673d1100756a6ecaa4 | 20,579 | cpp | C++ | cpp/KineticGas.cpp | vegardjervell/Kineticgas | 5897dceb767802c4ec08b975fec216fe498aaf6e | [
"MIT"
] | 1 | 2022-01-28T16:14:06.000Z | 2022-01-28T16:14:06.000Z | cpp/KineticGas.cpp | vegardjervell/Kineticgas | 5897dceb767802c4ec08b975fec216fe498aaf6e | [
"MIT"
] | null | null | null | cpp/KineticGas.cpp | vegardjervell/Kineticgas | 5897dceb767802c4ec08b975fec216fe498aaf6e | [
"MIT"
] | null | null | null | /*
Author : Vegard Gjeldvik Jervell
Contains :
Major base-functions for KineticGas. These functions are required for all versions, regardless of what
potential model they use. Contains summational expressions for the bracket integrals, and iterfaces to
get the matrices and vectors required to evaluate diffusion coefficients.
*/
#include "KineticGas.h"
#include <vector>
#include <algorithm>
#include <thread>
#include <functional>
#include <math.h>
#include <iostream>
#include "pybind11/pybind11.h"
#include <chrono>
#ifdef DEBUG
#define _LIBCPP_DEBUG 1
#endif
#define pprintf(flt) std::printf("%f", flt); std::printf("\n")
#define pprinti(i) std::printf("%i", i); std::printf("\n")
#pragma region // Global helper functions
int min(int a, int b){
if (a <= b){
return a;
}
return b;
}
double min(double a, double b){
if (a <= b){
return a;
}
return b;
}
int max(int a, int b){
if (a >= b){
return a;
}
return b;
}
double max(double a, double b){
if (a >= b){
return a;
}
return b;
}
int delta(int i, int j){ // Kronecker delta
if (i == j){
return 1;
}
return 0;
}
std::vector<double> logspace(const double& lmin, const double& lmax, const int& N_gridpoints){
std::vector<double> grid(N_gridpoints);
double dx = (lmax - lmin) / (N_gridpoints - 1);
// Making a logarithmic grid
// List is inverted when going from lin to log (so that numbers are more closely spaced at the start)
// Therefore: Count "backwards" to invert the list again so that the smallest r is at r_grid[0]
// Take a linear grid on (a, b), take log(grid) to get logarithmically spaced grid on (log(a), log(b))
// Make a linear map from (log(a), log(b)) to (b, a). Because spacing is bigger at the start of the log-grid
// Map the points on (log(a), log(b)) to (b, a), count backwards such that smaller numbers come first in the returned list
double A = (lmin - lmax) / log(lmax / lmin);
double B = lmin - A * log(lmax);
for (int i = 0; i < N_gridpoints; i++){
double x = log(lmax - dx * i); // Counting backwards linearly, mapping linear grid to logspace
grid[i] = A * x + B; // Using linear map from log
}
return grid;
}
double erfspace_func(const double& x, const double& lmin, const double& lmax, const double& a, const double& b){
double r = erf(a * (pow(x, b) - pow(lmin, b)) / (pow(lmax, b) - pow(lmin, b)));
return r;
}
std::vector<double> erfspace(const double& lmin, const double& lmax, const int& N_gridpoints, double& a, double& b){
std::vector<double> grid(N_gridpoints);
double dx = (lmax - lmin) / (N_gridpoints - 1);
// Making a f(x) grid where f(x) = erf(A * (x^b - lmin) / (lmax^b - lmin))
double A = (lmin - lmax) / (erfspace_func(lmax, lmin, lmax, a, b) - erfspace_func(lmin, lmin, lmax, a, b));
double B = lmin - A * erfspace_func(lmax, lmin, lmax, a, b);
for (int i = 0; i < N_gridpoints; i++){
double x = lmax - dx * i; // Counting backwards linearly (making linear grid)
double f = erfspace_func(x, lmin, lmax, a, b); // Mapping linear grid to f-space
grid[i] = A * f + B; // Linear map from f to lin
}
return grid;
}
#pragma endregion
#pragma endregion
#pragma region // Constructor
KineticGas::KineticGas(std::vector<double> init_mole_weights,
std::vector<std::vector<double>> init_sigmaij,
std::vector<std::vector<double>> init_epsij,
std::vector<std::vector<double>> init_la,
std::vector<std::vector<double>> init_lr,
int potential_mode)
: mole_weights{init_mole_weights},
sigmaij{init_sigmaij},
epsij{init_epsij},
la_ij{init_la},
lr_ij{init_lr},
m0{0.0},
potential_mode{potential_mode}
{
#ifdef DEBUG
std::printf("This is a Debug build!\nWith %i, %E, %E\n\n", potential_mode, mole_weights[0], mole_weights[1]);
#endif
for (int i = 0; i < sigmaij.size(); i++){
sigma.push_back(sigmaij[i][i]);
m0 += mole_weights[i];
}
sigma1 = sigma[0];
sigma2 = sigma[1];
sigma12 = sigmaij[0][1];
sigma_map[1] = sigma1;
sigma_map[2] = sigma2;
sigma_map[12] = sigma12;
sigma_map[21] = sigma12;
eps1 = epsij[0][0];
eps2 = epsij[1][1];
eps12 = epsij[0][1];
eps_map[1] = eps1;
eps_map[2] = eps2;
eps_map[12] = eps12;
eps_map[21] = eps12;
la1 = la_ij[0][0];
la2 = la_ij[1][1];
la12 = la_ij[0][1];
la_map[1] = la1;
la_map[2] = la2;
la_map[12] = la12;
la_map[21] = la12;
lr1 = lr_ij[0][0];
lr2 = lr_ij[1][1];
lr12 = lr_ij[0][1];
lr_map[1] = lr1;
lr_map[2] = lr2;
lr_map[12] = lr12;
lr_map[21] = lr12;
C1 = (lr1 / (lr1 - la1)) * pow(lr1 / la1, (la1 / (lr1 - la1)));
C2 = (lr2 / (lr2 - la2)) * pow(lr2 / la2, (la2 / (lr2 - la2)));
C12 = (lr12 / (lr12 - la12)) * pow(lr12 / la12, (la12 / (lr12 - la12)));
C_map[1] = C1;
C_map[2] = C2;
C_map[12] = C12;
C_map[21] = C12;
m1 = mole_weights[0];
m2 = mole_weights[1];
M1 = mole_weights[0] / m0;
M2 = mole_weights[1] / m0;
w_spherical_integrand_export = std::bind(&KineticGas::w_spherical_integrand, this,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5, std::placeholders::_6);
switch (potential_mode)
{
case HS_potential_idx:
w_p = &KineticGas::w_HS;
potential_p = &KineticGas::HS_potential;
p_potential_derivative_r = &KineticGas::HS_potential_derivative;
p_potential_dblderivative_rr = &KineticGas::HS_potential_dblderivative_rr;
break;
case mie_potential_idx:
w_p = &KineticGas::w_spherical;
potential_p = &KineticGas::mie_potential;
p_potential_derivative_r = &KineticGas::mie_potential_derivative;
p_potential_dblderivative_rr = &KineticGas::mie_potential_dblderivative_rr;
break;
default:
throw "Invalid potential mode!";
}
}
KineticGas::KineticGas(std::vector<double> init_mole_weights,
std::vector<std::vector<double>> init_sigmaij,
std::vector<std::vector<double>> init_epsij,
std::vector<std::vector<double>> init_la,
std::vector<std::vector<double>> init_lr,
int potential_mode,
std::vector<std::vector<int>> omega_points,
std::vector<double> omega_vals)
: KineticGas(init_mole_weights, init_sigmaij, init_epsij, init_la, init_lr, potential_mode)
{
std::vector<double>::iterator v_it = omega_vals.begin();
for (std::vector<std::vector<int>>::iterator k_it = omega_points.begin();
k_it != omega_points.end();
k_it++, v_it++){
omega_map[OmegaPoint(*k_it)] = *v_it;
}
#ifdef DEBUG
std::printf("Initialized with omega_db\n");
for (std::map<OmegaPoint, double>::iterator it = omega_map.begin(); it != omega_map.end(); it++){
std::printf("ij = %i, r = %i, l = %i, T_cK = %i, omega = %E\n", it->first.ij, it->first.r, it->first.l, it->first.T_dK, it->second);
}
std::printf("\n");
#endif
}
#pragma endregion
#pragma region // Helper functions
std::vector<std::vector<double>> KineticGas::get_A_matrix(
const double& T,
const std::vector<double>& mole_fracs,
const int& N)
{
std::vector<std::vector<double>> A_matrix(2 * N + 1, std::vector<double>(2 * N + 1));
// fill_A_matrix(T, mole_fracs, N, A_matrix);
// std::thread t1(&KineticGas::fill_A_matrix_14, this, std::ref(T), std::ref(mole_fracs), std::ref(N), std::ref(A_matrix));
// std::thread t2(&KineticGas::fill_A_matrix_24, this, std::ref(T), std::ref(mole_fracs), std::ref(N), std::ref(A_matrix));
// std::thread t3(&KineticGas::fill_A_matrix_34, this, std::ref(T), std::ref(mole_fracs), std::ref(N), std::ref(A_matrix));
// fill_A_matrix_44(T, mole_fracs, N, A_matrix);
// t1.join(); t2.join(); t3.join();
std::thread t1(&KineticGas::fill_A_matrix_12, this, std::ref(T), std::ref(mole_fracs), std::ref(N), std::ref(A_matrix));
fill_A_matrix_22(T, mole_fracs, N, A_matrix);
t1.join();
return A_matrix;
}
void KineticGas::fill_A_matrix( // Fill entire A_matrix
const double& T,
const std::vector<double>& mole_fracs,
const int& N,
std::vector<std::vector<double>>& A_matrix){
for (int p = - N; p <= N; p++){
for (int q = - N; q <= p; q++){
A_matrix[p + N][q + N] = a(p, q, T, mole_fracs);
A_matrix[q + N][p + N] = A_matrix[p + N][q + N];
}
}
}
void KineticGas::fill_A_matrix_12( // Fill part of the A-matrix (as indicated by crosses), used in combination with *_22
const double& T, // x - - - -
const std::vector<double>& mole_fracs, // x x - - -
const int& N, // x x x - -
std::vector<std::vector<double>>& A_matrix){ // x x - - -
// x - - - -
for (int p = - N; p <= N; p++){
for (int q = - N; q <= - abs(p); q++){
A_matrix[p + N][q + N] = a(p, q, T, mole_fracs);
A_matrix[q + N][p + N] = A_matrix[p + N][q + N]; // Matrix is symmetric
}
}
}
void KineticGas::fill_A_matrix_22( // Fill part of the A-matrix (as indicated by crosses), used in combination with *_12
const double& T, // - - - - -
const std::vector<double>& mole_fracs, // - - - - -
const int& N, // - - - - -
std::vector<std::vector<double>>& A_matrix){ // - - x x -
// - x x x x
for (int p = 1 ; p <= N; p++){
for (int q = - p + 1 ; q <= p; q++){
A_matrix[p + N][q + N] = a(p, q, T, mole_fracs);
A_matrix[q + N][p + N] = A_matrix[p + N][q + N]; // Matrix is symmetric
}
}
}
void KineticGas::fill_A_matrix_14( // Fill part of the A-matrix (as indicated by crosses), used in combination with *_24, *_34 and *_44
const double& T, // x - - - -
const std::vector<double>& mole_fracs, // x x - - -
const int& N, // - - - - -
std::vector<std::vector<double>>& A_matrix){ // - - - - -
// - - - - -
for (int p = - N; p < 0; p++){
for (int q = - N; q <= - abs(p); q++){
A_matrix[p + N][q + N] = a(p, q, T, mole_fracs);
A_matrix[q + N][p + N] = A_matrix[p + N][q + N]; // Matrix is symmetric
}
}
}
void KineticGas::fill_A_matrix_24( // Fill part of the A-matrix (as indicated by crosses), used in combination with *_14, *_34 and *_44
const double& T, // - - - - -
const std::vector<double>& mole_fracs, // - - - - -
const int& N, // x x x - -
std::vector<std::vector<double>>& A_matrix){ // x x - - -
// x - - - -
for (int p = 0; p <= N; p++){
for (int q = - N; q <= - abs(p); q++){
double val = a(p, q, T, mole_fracs);
A_matrix[p + N][q + N] = val;
A_matrix[q + N][p + N] = A_matrix[p + N][q + N]; // Matrix is symmetric
}
}
}
void KineticGas::fill_A_matrix_34( // Fill part of the A-matrix (as indicated by crosses), used in combination with *_14, *_24 and *_44
const double& T, // - - - - -
const std::vector<double>& mole_fracs, // - - - - -
const int& N, // - - - - -
std::vector<std::vector<double>>& A_matrix){ // - - x - -
// - x x - -
for (int p = 1; p <= N; p++){
for (int q = - p + 1; q < 0; q++){
A_matrix[p + N][q + N] = a(p, q, T, mole_fracs);
A_matrix[q + N][p + N] = A_matrix[p + N][q + N]; // Matrix is symmetric
}
}
}
void KineticGas::fill_A_matrix_44( // Fill part of the A-matrix (as indicated by crosses), used in combination with *_14, *_24 and *_34
const double& T, // - - - - -
const std::vector<double>& mole_fracs, // - - - - -
const int& N, // - - - - -
std::vector<std::vector<double>>& A_matrix){ // - - - x -
// - - - x x
for (int p = 1; p <= N; p++){
for (int q = 0; q <= p; q++){
A_matrix[p + N][q + N] = a(p, q, T, mole_fracs);
A_matrix[q + N][p + N] = A_matrix[p + N][q + N];
}
}
}
std::vector<double> KineticGas::get_delta_vector(
const double& T,
const double& particle_density,
const int& N)
{
std::vector<double> delta_vector(2 * N + 1);
delta_vector[N] = (3.0 / (particle_density * 2.0)) * sqrt(2 * BOLTZMANN * T / m0);
return delta_vector;
}
std::vector<std::vector<double>> KineticGas::get_reduced_A_matrix(
const double& T,
const std::vector<double>& mole_fracs,
const int& N)
{
// Get A-matrix, exluding central row and column, where (p == 0 or q == 0)
std::vector<std::vector<double>> reduced_A(2*N, std::vector<double>(2 * N));
// Upper left block
for (int p = - N; p < 0; p++){
for (int q = - N; q <= p; q++){
reduced_A[p + N][q + N] = a(p, q, T, mole_fracs);
reduced_A[q + N][p + N] = reduced_A[p + N][q + N]; // Matrix is symmetric
}
}
//Lower left block (and upper right by symmetry)
for (int p = 1; p <= N; p++){
for (int q = - N; q < 0; q++){
reduced_A[p + N - 1][q + N] = a(p, q, T, mole_fracs);
reduced_A[q + N][p + N - 1] = reduced_A[p + N - 1][q + N]; // Matrix is symmetric
}
}
//Lower right block
for (int p = 1; p <= N; p++){
for (int q = 1; q <= p; q++){
reduced_A[p + N - 1][q + N - 1] = a(p, q, T, mole_fracs);
reduced_A[q + N - 1][p + N - 1] = reduced_A[p + N - 1][q + N - 1]; // Matrix is symmetric
}
}
return reduced_A;
}
std::vector<double> KineticGas::get_alpha_vector(
const double& T,
const double& particle_density,
const std::vector<double>& in_mole_fracs,
const int& N)
{
std::vector<double> alpha_vector(2 * N);
alpha_vector[N - 1] = - (15.0 / 4.0) * (in_mole_fracs[1] / particle_density) * sqrt(2 * BOLTZMANN * T / m2);
alpha_vector[N] = - (15.0 / 4.0) * (in_mole_fracs[0] / particle_density) * sqrt(2 * BOLTZMANN * T / m1);
return alpha_vector;
}
#pragma endregion
#pragma region // A-functions
double KineticGas::A(const int& p, const int& q, const int& r, const int& l){
double value{0.0};
int max_i = min(min(p, q), min(r, p + q + 1 - r));
for (int i = l - 1; i <= max_i; i++){
value += ((ipow(8, i) * Fac(p + q - 2 * i) * ipow(-1, l + r + i) * Fac(r + 1) * Fac(2 * (p + q + 2 - i)) * ipow(4, r)) /
(Fac(p - i) * Fac(q - i) * Fac(l) * Fac(i + 1 - l) * Fac(r - i) * Fac(p + q + 1 - i - r) * Fac(2 * r + 2)
* Fac(p + q + 2 - i) * ipow(4, p + q + 1))) * ((i + 1 - l) * (p + q + 1 - i - r) - l * (r - i));
}
return value;
}
double KineticGas::A_prime(const int& p, const int& q, const int& r, const int& l,
const double& tmp_M1, const double& tmp_M2){
double F = (pow(tmp_M1, 2) + pow(tmp_M2, 2)) / (2 * tmp_M1 * tmp_M2);
double G = (tmp_M1 - tmp_M2) / tmp_M2;
int max_i = min(p, min(q, min(r, p + q + 1 - r)));
int max_k;
int max_w;
Product p1{1}, p2{1};
double value{0.0};
for (int i = l - 1; i <= max_i; i++ ){
max_w = min(p, min(q, p + q + 1 - r)) - i;
max_k = min(l, i);
for (int k = l - 1; k <= max_k; k++){
for (int w = 0; w <= max_w; w++){
p1 = ((ipow(8, i) * Fac(p + q - 2 * i - w) * ipow(-1, r + i) * Fac(r + 1) * Fac(2 * (p + q + 2 - i - w)) * ipow(2, 2 * r) * pow(F, i - k) * pow(G, w)
* ((ipow(2, 2 * w - 1) * pow(tmp_M1, i) * pow(tmp_M2, p + q - i - w)) * 2)
* (tmp_M1 * (p + q + 1 - i - r - w) * delta(k, l) - tmp_M2 * (r - i) * delta(k, l - 1))
));
p2 = (Fac(p - i - w) * Fac(q - i - w) * Fac(r - i) * Fac(p + q + 1 - i - r - w) * Fac(2 * r + 2) * Fac(p + q + 2 - i - w) * ipow(4, p + q + 1) * Fac(k) * Fac(i - k) * Fac(w));
value += p1 / p2; // NB: Gives Bus error if unless v1 and v2 are initialized before adding to value... pls help
}
}
}
return value;
}
double KineticGas::A_trippleprime(const int& p, const int& q, const int& r, const int& l){
if (p * q == 0 || l % 2 ){
return 0.0;
}
double value{0.0};
int max_i = min(p, min(q, min(r, p + q + 1 - r)));
for (int i = l - 1; i <= max_i; i++){
value += ((ipow(8, i) * Fac(p + q - (2 * i)) * 2 * ipow(-1, r + i) * Fac(r + 1) * Fac(2 * (p + q + 2 - i)) * ipow(2, 2 * r) * (((i + 1 - l) * (p + q + 1 - i - r)) - l * (r - i))) /
(Fac(p - i) * Fac(q - i) * Fac(l) * Fac(i + 1 - l) * Fac(r - i) * Fac(p + q + 1 - i - r) * Fac(2 * r + 2) * Fac(p + q + 2 - i) * ipow(4, p + q + 1)));
}
value *= pow(0.5, p + q + 1);
return value;
}
#pragma endregion
#pragma region // H-integrals and a(p, q)
double KineticGas::H_ij(const int& p, const int& q, const int& ij, const double& T){
double tmp_M1{M1}, tmp_M2{M2};
if (ij == 21){ // swap indices
tmp_M1 = M2;
tmp_M2 = M1;
}
double value{0.0};
int max_l = min(p, q) + 1;
int max_r;
for (int l = 1; l <= max_l; l++){
max_r = p + q + 2 - l;
for (int r = l; r <= max_r; r++){
value += A(p, q, r, l) * omega(12, l, r, T);
}
}
value *= 8 * pow(tmp_M2, p + 0.5) * pow(tmp_M1, q + 0.5);
return value;
}
double KineticGas::H_i(const int& p, const int& q, const int& ij, const double& T){
double tmp_M1{M1}, tmp_M2{M2};
if (ij == 21){ // swap indices
tmp_M1 = M2;
tmp_M2 = M1;
}
double value{0.0};
int max_l = min(p, q) + 1;
int max_r;
for (int l = 1; l <= max_l; l++){
max_r = p + q + 2 - l;
for (int r = l; r <= max_r; r++){
value += A_prime(p, q, r, l, tmp_M1, tmp_M2) * omega(12, l, r, T);
}
}
value *= 8;
return value;
}
double KineticGas::H_simple(const int& p, const int& q, const int& i, const double& T){
double value{0.0};
int max_l = min(p,q) + 1;
int max_r;
for (int l = 2; l <= max_l; l += 2){
max_r = p + q + 2 - l;
for (int r = l; r <= max_r; r++){
value += A_trippleprime(p, q, r, l) * omega(i, l, r, T);
}
}
value *= 8;
return value;
}
double KineticGas::a(const int& p, const int& q, const double& T, const std::vector<double>& mole_fracs){
double x1{mole_fracs[0]}, x2{mole_fracs[1]};
if (p == 0 || q == 0){
if (p > 0) return pow(M1, 0.5) * x1 * x2 * H_i(p, q, 12, T);
else if (p < 0) return - pow(M2, 0.5) * x1 * x2 * H_i(-p, q, 21, T);
else if (q > 0) return pow(M1, 0.5) * x1 * x2 * H_i(p, q, 12, T);
else if (q < 0) return - pow(M2, 0.5) * x1 * x2 * H_i(p, -q, 21, T);
else{ // p == 0 and q == 0
return M1 * x1 * x2 * H_i(p, q, 12, T);
}
}
else if (p > 0 and q > 0) return pow(x1, 2) * (H_simple(p, q, 1, T)) + x1 * x2 * H_i(p, q, 12, T);
else if (p > 0 and q < 0) return x1 * x2 * H_ij(p, -q, 12, T);
else if (p < 0 and q > 0) return x1 * x2 * H_ij(-p, q, 21, T);
else{ // p < 0 and q < 0
return pow(x2, 2) * H_simple(-p, -q, 2, T) + x1 * x2 * H_i(-p, -q, 21, T);
}
}
#pragma endregion
| 37.690476 | 191 | 0.501093 | vegardjervell |
b7bb33a392540db3d08fa93fb9aa4ae7bdf78059 | 1,772 | cpp | C++ | KEngine/Internal/KRenderDocCapture.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 13 | 2019-10-19T17:41:19.000Z | 2021-11-04T18:50:03.000Z | KEngine/Internal/KRenderDocCapture.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 3 | 2019-12-09T06:22:43.000Z | 2020-05-28T09:33:44.000Z | KEngine/Internal/KRenderDocCapture.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | null | null | null | #include "KRenderDocCapture.h"
#include "KBase/Publish/KSystem.h"
#include "KBase/Publish/KFileTool.h"
#include "KBase/Interface/IKLog.h"
#include <assert.h>
#ifdef _WIN32
#include <Windows.h>
#endif
KRenderDocCapture::KRenderDocCapture()
: m_Module(nullptr),
m_rdoc_api(nullptr)
{
}
KRenderDocCapture::~KRenderDocCapture()
{
ASSERT_RESULT(m_Module == NULL);
ASSERT_RESULT(m_rdoc_api == nullptr);
}
bool KRenderDocCapture::Init()
{
UnInit();
#ifdef _WIN32
std::string renderDocPath;
if (KSystem::QueryRegistryKey("SOFTWARE\\Classes\\RenderDoc.RDCCapture.1\\DefaultIcon\\", "", renderDocPath))
{
std::string renderDocFolder;
ASSERT_RESULT(KFileTool::ParentFolder(renderDocPath, renderDocFolder));
std::string renderDocDLL;
ASSERT_RESULT(KFileTool::PathJoin(renderDocFolder, "renderdoc.dll", renderDocDLL));
m_Module = LoadLibraryA(renderDocDLL.c_str());
if (GetModuleHandleA(renderDocDLL.c_str()))
{
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress((HMODULE)m_Module, "RENDERDOC_GetAPI");
int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_4_1, (void**)&m_rdoc_api);
if (ret == 0)
{
m_rdoc_api = nullptr;
}
if (m_rdoc_api)
{
m_rdoc_api->MaskOverlayBits(eRENDERDOC_Overlay_None, eRENDERDOC_Overlay_None);
int MajorVersion(0), MinorVersion(0), PatchVersion(0);
m_rdoc_api->GetAPIVersion(&MajorVersion, &MinorVersion, &PatchVersion);
KG_LOGD(LM_RENDER, "RenderDoc Capture Init %d.%d.%d", MajorVersion, MinorVersion, PatchVersion);
}
}
}
#endif
return m_rdoc_api != nullptr;
}
bool KRenderDocCapture::UnInit()
{
#ifdef _WIN32
if (m_Module != NULL)
{
FreeLibrary((HMODULE)m_Module);
m_Module = nullptr;
}
#endif
m_Module = nullptr;
m_rdoc_api = nullptr;
return true;
} | 25.681159 | 113 | 0.740971 | King19931229 |
b7bbf23d8de0122178f3f6bfb9419e4dafbddaea | 2,900 | cpp | C++ | GlNddiDisplay.cpp | dave-estes-UNC/nddi | 4b38e8155bd29201152f8fa8d356e97371c60d90 | [
"Apache-2.0"
] | null | null | null | GlNddiDisplay.cpp | dave-estes-UNC/nddi | 4b38e8155bd29201152f8fa8d356e97371c60d90 | [
"Apache-2.0"
] | null | null | null | GlNddiDisplay.cpp | dave-estes-UNC/nddi | 4b38e8155bd29201152f8fa8d356e97371c60d90 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <sys/time.h>
#include "Features.h"
#include "GlNddiDisplay.h"
// public
GlNddiDisplay::GlNddiDisplay(vector<unsigned int> &frameVolumeDimensionalSizes,
unsigned int numCoefficientPlanes, unsigned int inputVectorSize,
bool headless, unsigned char logcosts, bool fixed8x8Macroblocks, bool useSingleCoefficientPlane) {
texture_ = 0;
GlNddiDisplay(frameVolumeDimensionalSizes, 320, 240, numCoefficientPlanes, inputVectorSize);
}
GlNddiDisplay::GlNddiDisplay(vector<unsigned int> &frameVolumeDimensionalSizes,
unsigned int displayWidth, unsigned int displayHeight,
unsigned int numCoefficientPlanes, unsigned int inputVectorSize,
bool headless, unsigned char logcosts, bool fixed8x8Macroblocks, bool useSingleCoefficientPlane)
: SimpleNddiDisplay(frameVolumeDimensionalSizes, displayWidth, displayHeight, numCoefficientPlanes, inputVectorSize, headless, logcosts, fixed8x8Macroblocks, useSingleCoefficientPlane) {
// allocate a texture name
glGenTextures( 1, &texture_ );
}
// TODO(CDE): Why is the destructor for GlNddiDisplay being called when we're using a ClNddiDisplay?
GlNddiDisplay::~GlNddiDisplay() {
glDeleteTextures(1, &texture_);
}
// Private
GLuint GlNddiDisplay::GetFrameBufferTex() {
return GetFrameBufferTex(0, 0, displayWidth_, displayHeight_);
}
GLuint GlNddiDisplay::GetFrameBufferTex(unsigned int sub_x, unsigned int sub_y, unsigned int sub_w, unsigned int sub_h) {
#ifdef SUPRESS_EXCESS_RENDERING
if (changed_)
Render(sub_x, sub_y, sub_w, sub_h);
#endif
// TODO(CDE): Temporarily putting this here until GlNddiDisplay and ClNddiDisplay
// are using the exact same kind of GL textures
#ifndef USE_CL
// select our current texture
glBindTexture( GL_TEXTURE_2D, texture_ );
// select modulate to mix texture with color for shading
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_NEAREST );
// when texture area is large, bilinear filter the first mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// if wrap is true, the texture wraps over at the edges (repeat)
// ... false, the texture ends at the edges (clamp)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP );
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, displayWidth_, displayHeight_,
GL_RGBA, GL_UNSIGNED_BYTE, frameBuffer_ );
#endif
return texture_;
}
| 39.189189 | 186 | 0.713793 | dave-estes-UNC |
b7bf6c77995df451e0600e946a9fafccab530e6f | 413 | hpp | C++ | include/lug/Graphics/Vulkan/Builder/Texture.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 275 | 2016-10-08T15:33:17.000Z | 2022-03-30T06:11:56.000Z | include/lug/Graphics/Vulkan/Builder/Texture.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 24 | 2016-09-29T20:51:20.000Z | 2018-05-09T21:41:36.000Z | include/lug/Graphics/Vulkan/Builder/Texture.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 37 | 2017-02-25T05:03:48.000Z | 2021-05-10T19:06:29.000Z | #pragma once
#include <lug/Graphics/Render/Texture.hpp>
#include <lug/Graphics/Resource.hpp>
namespace lug {
namespace Graphics {
namespace Builder {
class Texture;
} // Builder
namespace Vulkan {
namespace Builder {
namespace Texture {
Resource::SharedPtr<lug::Graphics::Render::Texture> build(const ::lug::Graphics::Builder::Texture& builder);
} // Texture
} // Builder
} // Vulkan
} // Graphics
} // lug
| 17.208333 | 108 | 0.72155 | Lugdunum3D |
b7c29be2afd91b746cc69d39d0e9fde9e25bf38c | 1,850 | cpp | C++ | lib/iri/test/iri_gen_test.cpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | 5 | 2016-04-07T19:49:39.000Z | 2021-08-03T05:24:11.000Z | lib/iri/test/iri_gen_test.cpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | null | null | null | lib/iri/test/iri_gen_test.cpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | 1 | 2020-12-27T11:47:31.000Z | 2020-12-27T11:47:31.000Z | /*
* iri_gen_test.cpp
*
* Created on: Aug 19, 2015
* Author: zmij
*/
#include "grammar/grammar_gen_test.hpp"
#include <tip/iri/grammar/iri_generate.hpp>
namespace gen = tip::iri::grammar::gen;
GRAMMAR_GEN_TEST(gen::sub_delims_grammar, SubDelims, char,
::testing::Values(
GenerateSubDelims::make_test_data('!', "!"),
GenerateSubDelims::make_test_data('$', "$")
)
);
GRAMMAR_GEN_TEST(gen::gen_delims_grammar, GenDelims, char,
::testing::Values(
GenerateSubDelims::make_test_data(':', ":"),
GenerateSubDelims::make_test_data('?', "?")
)
);
GRAMMAR_GEN_TEST(gen::reserved_grammar, Reserved, char,
::testing::Values(
GenerateReserved::make_test_data('!', "!"),
GenerateReserved::make_test_data('$', "$"),
GenerateReserved::make_test_data(':', ":"),
GenerateReserved::make_test_data('?', "?")
)
);
GRAMMAR_GEN_TEST(gen::unreserved_grammar, Unreserved, std::string,
::testing::Values(
GenerateUnreserved::make_test_data("a", "a"),
GenerateUnreserved::make_test_data("0", "0"),
GenerateUnreserved::make_test_data("-", "-")
)
);
GRAMMAR_GEN_TEST(gen::pct_encoded_grammar, PCT, char,
::testing::Values(
GeneratePCT::make_test_data( ' ', "%20" ),
GeneratePCT::make_test_data( '~', "%7e" ),
GeneratePCT::make_test_data( 9, "%09" )
)
);
GRAMMAR_GEN_TEST(gen::iunreserved_grammar, IUnreserved, std::string,
::testing::Values(
GenerateUnreserved::make_test_data("a", "a"),
GenerateUnreserved::make_test_data("0", "0"),
GenerateUnreserved::make_test_data("-", "-"),
GenerateUnreserved::make_test_data("%xa0", "%xa0")
)
);
GRAMMAR_GEN_TEST(gen::ipath_grammar, Path, tip::iri::path,
::testing::Values(
GeneratePath::make_test_data( {false, { "foo", "bar" }}, "foo/bar" ),
GeneratePath::make_test_data( {true, { "foo", "bar" }}, "/foo/bar" ),
GeneratePath::make_test_data( {true}, "/" )
)
);
| 26.811594 | 71 | 0.681622 | zmij |
b7c3b9cdef4002b8b538298e2973aad88e6f5a94 | 3,790 | hpp | C++ | include/saci/tree/model/branch_impl.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | 1 | 2020-07-29T20:42:58.000Z | 2020-07-29T20:42:58.000Z | include/saci/tree/model/branch_impl.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | null | null | null | include/saci/tree/model/branch_impl.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include "saci/tree/model/detail/apply_node_impl.hpp"
#include "saci/tree/model/detail/node_impl_fwd.hpp"
#include "saci/tree/model/detail/visibility.hpp"
#include "saci/tree/model/node_base.hpp"
#include <boost/fusion/include/as_vector.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>
#include <coruja/observer_class.hpp>
#include <type_traits>
namespace saci { namespace tree {
namespace detail {
template<typename Self>
struct sync_with_domain_t;
template<typename Parent>
struct update_parent_ptr;
}
template<typename T,
typename CheckPolicy,
typename Children,
typename Parent,
typename EnableIfChildren = void>
struct branch_impl;
template<typename T,
typename CheckPolicy,
typename Children,
typename Parent>
struct branch_impl<
T,
CheckPolicy,
Children,
Parent,
typename std::enable_if<boost::mpl::size<Children>::value >= 2>::type
> : coruja::observer_class<
branch_impl<T, CheckPolicy, Children, Parent>,
node_base<T, CheckPolicy, detail::Expandable, Parent>
>
{
using base = coruja::observer_class<
branch_impl,
node_base<T, CheckPolicy, detail::Expandable, Parent>>;
using ctx_t = void;
using children_t = typename boost::fusion::result_of::as_vector<
typename boost::mpl::transform<
Children, detail::apply_node_impl<branch_impl>>::type
>::type;
branch_impl() = default;
branch_impl(typename base::type& o, Parent& p) : base(o, p)
{
boost::fusion::for_each(children, detail::sync_with_domain_t<branch_impl>{*this});
}
branch_impl(branch_impl&&) = delete;
branch_impl& operator=(branch_impl&& rhs) {
base::operator=(std::move(rhs));
children = std::move(rhs.children);
boost::fusion::for_each
(children, detail::update_parent_ptr<branch_impl>{*this});
return *this;
}
void update_parent_ptr(Parent& p) {
base::update_parent_ptr(p);
boost::fusion::for_each
(children, detail::update_parent_ptr<branch_impl>{*this});
}
children_t children;
};
template<typename T,
typename CheckPolicy,
typename Children,
typename Parent>
struct branch_impl<
T,
CheckPolicy,
Children,
Parent,
typename std::enable_if<boost::mpl::size<Children>::value == 1>::type
> : coruja::observer_class<
branch_impl<T, CheckPolicy, Children, Parent>,
node_base<T, CheckPolicy, detail::Expandable, Parent>
>
{
using base = coruja::observer_class<
branch_impl,
node_base<T, CheckPolicy, detail::Expandable, Parent>>;
using ctx_t = void;
using children_t = typename detail::node_impl<
branch_impl, typename boost::mpl::front<Children>::type
>::type;
branch_impl() = default;
branch_impl(typename base::type& o, Parent& p) : base(o, p)
{
detail::sync_with_domain_t<branch_impl>{*this}(children);
}
branch_impl(branch_impl&&) = delete;
branch_impl& operator=(branch_impl&& rhs) {
base::operator=(std::move(rhs));
children = std::move(rhs.children);
detail::update_parent_ptr<branch_impl>{*this}(children);
return *this;
}
void update_parent_ptr(Parent& p) {
base::update_parent_ptr(p);
detail::update_parent_ptr<branch_impl>{*this}(children);
}
children_t children;
};
}}
#include "saci/tree/model/detail/branch.hpp"
#include "saci/tree/model/detail/update_parent_ptr.hpp"
#include "saci/tree/model/detail/sync_with_domain.hpp"
| 26.879433 | 90 | 0.656201 | ricardocosme |
b7c3c039334d9b923f1e737af3dd25ea9d5ff85a | 909 | ipp | C++ | implement/oalplus/context.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 459 | 2016-03-16T04:11:37.000Z | 2022-03-31T08:05:21.000Z | implement/oalplus/context.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 4 | 2015-08-21T02:29:15.000Z | 2020-05-02T13:50:36.000Z | implement/oalplus/context.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 47 | 2016-05-31T15:55:52.000Z | 2022-03-28T14:49:40.000Z | /**
* @file oalplus/context.ipp
* @brief Implementation of Context functions
*
* @author Matus Chochlik
*
* Copyright 2010-2014 Matus Chochlik. 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)
*/
namespace oalplus {
OALPLUS_LIB_FUNC
ContextOps ContextOps::
Current(void)
{
::ALCcontext* context = OALPLUS_ALFUNC(alc,GetCurrentContext)();
OALPLUS_HANDLE_ERROR_IF(
!context,
ALC_INVALID_CONTEXT,
"Failed to get current AL context",
Error,
ALLib("alc").
ALFunc("GetCurrentContext")
);
::ALCdevice* device = OALPLUS_ALFUNC(alc,GetContextsDevice)(context);
OALPLUS_HANDLE_ERROR_IF(
!device,
ALC_INVALID_DEVICE,
"Failed to get AL context's device",
Error,
ALLib("alc").
ALFunc("GetContextsDevice")
);
return ContextOps(device, context);
}
} // namespace oalplus
| 21.642857 | 70 | 0.728273 | Extrunder |
b7c4cc1029ec3ce05380092ae644a9095ba94d95 | 95 | cpp | C++ | Society2.0/Society2.0/CityGroup.cpp | simsim314/Society2.0 | a95e42122e2541b7544dd641247681996f1e625a | [
"Unlicense"
] | 1 | 2019-07-11T13:10:43.000Z | 2019-07-11T13:10:43.000Z | Society2.0/Society2.0/CityGroup.cpp | mdheller/Society2.0 | a95e42122e2541b7544dd641247681996f1e625a | [
"Unlicense"
] | 1 | 2019-02-19T12:32:52.000Z | 2019-03-07T20:49:50.000Z | Society2.0/Society2.0/CityGroup.cpp | mdheller/Society2.0 | a95e42122e2541b7544dd641247681996f1e625a | [
"Unlicense"
] | 1 | 2020-01-10T12:37:30.000Z | 2020-01-10T12:37:30.000Z | #include "CityGroup.h"
CityGroup::CityGroup()
{
}
CityGroup::~CityGroup()
{
}
| 7.307692 | 24 | 0.557895 | simsim314 |
b7c763c2ff0d1fa284137d82f57e42af6a7ce245 | 75,437 | cpp | C++ | MultiPlane/lens_halos.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 2 | 2017-03-22T13:18:32.000Z | 2021-05-01T01:54:31.000Z | MultiPlane/lens_halos.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 49 | 2016-10-05T03:08:38.000Z | 2020-11-03T15:39:26.000Z | MultiPlane/lens_halos.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 1 | 2017-07-10T08:52:53.000Z | 2017-07-10T08:52:53.000Z | /*
* lens_halos.cpp
*
* Created on: 06.05.2013
* Author: mpetkova
*/
#include "slsimlib.h"
using namespace std;
/// Shell constructor
LensHalo::LensHalo(){
rscale = 1.0;
mass = Rsize = Rmax = xmax = posHalo[0] = posHalo[1] = 0.0;
stars_implanted = false;
elliptical_flag = false;
Dist = -1;
stars_N =0.0;
zlens = 0.0;
}
LensHalo::LensHalo(PosType z,const COSMOLOGY &cosmo){
rscale = 1.0;
mass = Rsize = Rmax = xmax = posHalo[0] = posHalo[1] = 0.0;
stars_implanted = false;
elliptical_flag = false;
Dist = cosmo.angDist(z);
stars_N =0.0;
zlens = z;
}
//LensHalo::LensHalo(InputParams& params,COSMOLOGY &cosmo,bool needRsize){
// Dist = -1;
// assignParams(params,needRsize);
// stars_implanted = false;
// posHalo[0] = posHalo[1] = 0.0;
// elliptical_flag = false;
// setDist(cosmo);
//}
//LensHalo::LensHalo(InputParams& params,bool needRsize){
// Dist = -1;
// assignParams(params,needRsize);
// stars_implanted = false;
// posHalo[0] = posHalo[1] = 0.0;
// elliptical_flag = false;
//}
LensHalo::LensHalo(const LensHalo &h){
idnumber = h.idnumber; /// Identification number of halo. It is not always used.
Dist = h.Dist;
posHalo[0] = h.posHalo[0]; posHalo[1] = h.posHalo[1];
zlens = h. zlens;
mass = h.mass;
Rsize = h.Rsize;
mnorm = h.mnorm;
Rmax = h.Rmax;
stars_index = h.stars_index;
stars_xp = h.stars_xp;
stars_N = h.stars_N;
star_theta_force = h.star_theta_force;
if(stars_N > 1){
star_tree = new TreeQuadParticles<StarType>(stars_xp.data(),stars_N
,false,false,0,4,star_theta_force);
}else{
star_tree = nullptr;
}
star_massscale = h.star_massscale;
star_fstars = h.star_fstars;
star_Nregions = h.star_Nregions;
star_region = h.star_region;
beta = h.beta;
Rmax_to_Rsize_ratio = h.Rmax_to_Rsize_ratio;
rscale = h.rscale;
stars_implanted = h.stars_implanted;
main_stars_imf_type = h.main_stars_imf_type;
main_stars_min_mass = h. main_stars_min_mass;
main_stars_max_mass = h.main_stars_max_mass;
main_ellip_method = h.main_ellip_method;
bend_mstar =h.bend_mstar;
lo_mass_slope = h.lo_mass_slope;
hi_mass_slope = h.hi_mass_slope;
star_Sigma = h.star_Sigma;
star_xdisk = h.star_xdisk;
xmax = h.xmax;
mass_norm_factor = h.mass_norm_factor;
pa = h.pa;
fratio = h.fratio;
elliptical_flag = h.elliptical_flag;
switch_flag = h.switch_flag;
//Nmod = h.Nmod;
};
LensHalo & LensHalo::operator=(LensHalo &&h){
if (this != &h){
idnumber = h.idnumber; /// Identification number of halo. It is not always used.
Dist = h.Dist;
posHalo[0] = h.posHalo[0]; posHalo[1] = h.posHalo[1];
zlens = h. zlens;
mass = h.mass;
Rsize = h.Rsize;
mnorm = h.mnorm;
Rmax = h.Rmax;
stars_index = h.stars_index;
stars_xp = h.stars_xp;
stars_N = h.stars_N;
star_theta_force = h.star_theta_force;
delete star_tree;
star_tree = h.star_tree;
h.star_tree = nullptr;
star_massscale = h.star_massscale;
star_fstars = h.star_fstars;
star_Nregions = h.star_Nregions;
star_region = h.star_region;
beta = h.beta;
Rmax_to_Rsize_ratio = h.Rmax_to_Rsize_ratio;
rscale = h.rscale;
stars_implanted = h.stars_implanted;
main_stars_imf_type = h.main_stars_imf_type;
main_stars_min_mass = h. main_stars_min_mass;
main_stars_max_mass = h.main_stars_max_mass;
main_ellip_method = h.main_ellip_method;
bend_mstar =h.bend_mstar;
lo_mass_slope = h.lo_mass_slope;
hi_mass_slope = h.hi_mass_slope;
star_Sigma = h.star_Sigma;
star_xdisk = h.star_xdisk;
xmax = h.xmax;
mass_norm_factor = h.mass_norm_factor;
pa = h.pa;
fratio = h.fratio;
elliptical_flag = h.elliptical_flag;
switch_flag = h.switch_flag;
//Nmod = h.Nmod;
}
return *this;
};
LensHalo & LensHalo::operator=(const LensHalo &h){
if(this == &h) return *this;
idnumber = h.idnumber; /// Identification number of halo. It is not always used.
Dist = h.Dist;
posHalo[0] = h.posHalo[0]; posHalo[1] = h.posHalo[1];
zlens = h. zlens;
mass = h.mass;
Rsize = h.Rsize;
mnorm = h.mnorm;
Rmax = h.Rmax;
stars_index = h.stars_index;
stars_xp = h.stars_xp;
stars_N = h.stars_N;
star_theta_force = h.star_theta_force;
if(stars_N > 1){
star_tree = new TreeQuadParticles<StarType>(stars_xp.data(),stars_N
,false,false,0,4,star_theta_force);
}else{
star_tree = nullptr;
}
star_massscale = h.star_massscale;
star_fstars = h.star_fstars;
star_Nregions = h.star_Nregions;
star_region = h.star_region;
beta = h.beta;
Rmax_to_Rsize_ratio = h.Rmax_to_Rsize_ratio;
rscale = h.rscale;
stars_implanted = h.stars_implanted;
main_stars_imf_type = h.main_stars_imf_type;
main_stars_min_mass = h. main_stars_min_mass;
main_stars_max_mass = h.main_stars_max_mass;
main_ellip_method = h.main_ellip_method;
bend_mstar =h.bend_mstar;
lo_mass_slope = h.lo_mass_slope;
hi_mass_slope = h.hi_mass_slope;
star_Sigma = h.star_Sigma;
star_xdisk = h.star_xdisk;
xmax = h.xmax;
mass_norm_factor = h.mass_norm_factor;
pa = h.pa;
fratio = h.fratio;
elliptical_flag = h.elliptical_flag;
switch_flag = h.switch_flag;
//Nmod = h.Nmod;
return *this;
};
void LensHalo::initFromMassFunc(float my_mass, float my_Rsize, float my_rscale
, PosType my_slope, long *seed){
mass = my_mass;
Rsize = my_Rsize;
rscale = my_rscale;
xmax = Rsize/rscale;
}
void LensHalo::error_message1(std::string parameter,std::string file){
ERROR_MESSAGE();
std::cout << "Parameter " << parameter << " is needed to construct a LensHalo. It needs to be set in parameter file " << file << "!" << std::endl;
throw std::runtime_error(parameter);
}
void LensHalo::assignParams(InputParams& params,bool needRsize){
if(!params.get("main_mass",mass)) error_message1("main_mass",params.filename());
if(needRsize){ // this might not be required for lenses like NSIE
if(!params.get("main_Rsize",Rsize)) error_message1("main_Rsize",params.filename());
}
if(!params.get("main_zlens",zlens)) error_message1("main_zlens",params.filename());
}
void LensHalo::PrintStars(bool show_stars)
{
std::cout << std::endl << "Nstars "<<stars_N << std::endl << std::endl;
if(stars_N>0){
if(star_Nregions > 0)
std::cout << "stars_Nregions "<<star_Nregions << std::endl;
std::cout << "stars_massscale "<<star_massscale << std::endl;
std::cout << "stars_fstars "<<star_fstars << std::endl;
std::cout << "stars_theta_force "<<star_theta_force << std::endl;
if(show_stars){
if(stars_implanted){
for(int i=0 ; i < stars_N ; ++i) std::cout << " x["<<i<<"]="
<< stars_xp[i][0] << " " << stars_xp[i][1] << std::endl;
}else std::cout << "stars are not implanted yet" << std::endl;
}
}
}
PixelMap LensHalo::map_variables(
LensingVariable lensvar /// lensing variable - KAPPA, ALPHA1, ALPHA2, GAMMA1, GAMMA2 or PHI
,size_t Nx
,size_t Ny
,double res /// resolution in physical Mpc on the lens plane
){
Point_2d center;
PixelMap map(center.data(),Nx,Ny,res);
Point_2d x,alpha;
size_t N = Nx*Ny;
KappaType kappa,phi,gamma[3];
for(size_t i = 0 ; i < N ; ++i){
map.find_position(x.data(),i);
force_halo(alpha.data(),&kappa,gamma,&phi,x.data());
switch (lensvar) {
case ALPHA1:
map[i] = alpha[0];
break;
case ALPHA2:
map[i] = alpha[1];
break;
case GAMMA1:
map[i] = gamma[0];
break;
case GAMMA2:
map[i] = gamma[1];
break;
case KAPPA:
map[i] = kappa;
break;
case PHI:
map[i] = phi;
break;
default:
break;
}
}
return map;
}
/// calculates the deflection etc. caused by stars alone
void LensHalo::force_stars(
PosType *alpha /// mass/Mpc
,KappaType *kappa
,KappaType *gamma
,PosType const *xcm /// physical position on lens plane
)
{
PosType alpha_tmp[2];
KappaType gamma_tmp[3], tmp = 0;
KappaType phi;
gamma_tmp[0] = gamma_tmp[1] = gamma_tmp[2] = 0.0;
alpha_tmp[0] = alpha_tmp[1] = 0.0;
substract_stars_disks(xcm,alpha,kappa,gamma);
// do stars with tree code
star_tree->force2D_recur(xcm,alpha_tmp,&tmp,gamma_tmp,&phi);
alpha[0] -= star_massscale*alpha_tmp[0];
alpha[1] -= star_massscale*alpha_tmp[1];
{
*kappa += star_massscale*tmp;
gamma[0] -= star_massscale*gamma_tmp[0];
gamma[1] -= star_massscale*gamma_tmp[1];
}
}
LensHalo::~LensHalo()
{
}
const long LensHaloNFW::NTABLE = 10000;
const PosType LensHaloNFW::maxrm = 100.0;
int LensHaloNFW::count = 0;
PosType* LensHaloNFW::xtable = NULL;
PosType* LensHaloNFW::ftable = NULL;
PosType* LensHaloNFW::gtable = NULL;
PosType* LensHaloNFW::g2table = NULL;
PosType* LensHaloNFW::htable = NULL;
PosType* LensHaloNFW::xgtable = NULL;
PosType*** LensHaloNFW::modtable= NULL; // was used for Ansatz IV
LensHaloNFW::LensHaloNFW()
: LensHalo(), gmax(0)
{
LensHalo::setRsize(1.0);
Rmax = LensHalo::getRsize();
LensHalo::setMass(0.0);
LensHalo::setZlens(0,COSMOLOGY(Planck18));
LensHalo::Dist = -1; // to be set later
fratio=1;
pa = stars_N = 0;
stars_implanted = false;
rscale = LensHalo::getRsize()/5;
xmax = LensHalo::getRsize()/rscale;
make_tables();
gmax = InterpolateFromTable(gtable, xmax);
set_flag_elliptical(false);
}
LensHaloNFW::LensHaloNFW(float my_mass,float my_Rsize,PosType my_zlens,float my_concentration
,float my_fratio,float my_pa,int my_stars_N,const COSMOLOGY &cosmo
,EllipMethod my_ellip_method
){
LensHalo::setRsize(my_Rsize);
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
fratio=my_fratio, pa=my_pa, stars_N=my_stars_N, main_ellip_method=my_ellip_method;
stars_implanted = false;
rscale = LensHalo::getRsize()/my_concentration;
xmax = LensHalo::getRsize()/rscale;
make_tables();
gmax = InterpolateFromTable(gtable, xmax);
set_slope(1);
/// If the axis ratio given in the parameter file is set to 1 all ellipticizing routines are skipped.
if(fratio!=1){
Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
if(getEllipMethod()==Fourier){
std::cout << "NFW constructor: slope set to " << get_slope() << std::endl;
calcModes(fratio, get_slope(), pa, mod); // to ellipticize potential instead of kappa take calcModes(fratio, 2-get_slope(), pa, mod);
std::cout << "NFW constructor: Fourier modes computed" << std::endl;
for(int i=1;i<Nmod;i++){
if(mod[i]!=0){set_flag_elliptical(true);};
}
}else set_flag_elliptical(true);
if (getEllipMethod()==Pseudo or getEllipMethod()==Fourier){
set_norm_factor();
set_switch_flag(true);
}
}else{
set_flag_elliptical(false);
Rmax = LensHalo::getRsize();
}
}
/* LensHalo::LensHalo(mass,Rsize,zlens, // base
rscale,fratio,pa,stars_N, //NFW,Hernquist, Jaffe
rscale,fratio,pa,beta // Pseudo NFW
rscale,fratio,pa,sigma,rcore // NSIE
zlens,stars_N // dummy
){
stars_implanted = false;
posHalo[0] = posHalo[1] = 0.0;
}*/
//LensHaloNFW::LensHaloNFW(InputParams& params):LensHalo(params)
//{
// assignParams(params);
// make_tables();
// gmax = InterpolateFromTable(gtable, xmax);
//
// mnorm = renormalization(LensHalo::getRsize());
//
// std::cout << "mass normalization: " << mnorm << std::endl;
//
// // If the 2nd argument in calcModes(fratio, slope, pa, mod), the slope, is set to 1 it yields an elliptical kappa contour of given axis ratio (fratio) at the radius where the slope of the 3D density profile is -2, which is defined as the scale radius for the NFW profile. To ellipticize the potential instead of the convergence use calcModes(fratio, 2-get_slope(), pa, mod), this produces also an ellipse in the convergence map, but at the radius where the slope is 2-get_slope().
// set_slope(1);
// // If the axis ratio given in the parameter file is set to 1 all ellipticizing routines are skipped.
// if(fratio!=1){
// Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
// //std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
// if(getEllipMethod()==Fourier){
// std::cout << "NFW constructor: slope set to " << get_slope() << std::endl;
// //for(int i=1;i<20;i++){
// // calcModes(fratio, 0.1*i, pa, mod);
// //}
// //calcModes(fratio, get_slope()-0.5, pa, mod); // to ellipticize potential instead of kappa take calcModes(fratio, 2-get_slope(), pa, mod);
// calcModes(fratio, get_slope(), pa, mod); // to ellipticize potential instead of kappa take calcModes(fratio, 2-get_slope(), pa, mod);
// //calcModes(fratio, get_slope()+0.5, pa, mod); // to ellipticize potential instead of kappa take calcModes(fratio, 2-get_slope(), pa, mod);
//
// for(int i=1;i<Nmod;i++){
// if(mod[i]!=0){set_flag_elliptical(true);};
// }
// }else set_flag_elliptical(true);
// if (getEllipMethod()==Pseudo){
// set_norm_factor();
// }
// }else{
// set_flag_elliptical(false);
// Rmax = LensHalo::getRsize();
// }
//}
void LensHaloNFW::make_tables(){
if(count == 0){
int i;
//struct Ig_func g(*this);
PosType x, dx = maxrm/(PosType)NTABLE;
xtable = new PosType[NTABLE];
ftable = new PosType[NTABLE];
gtable = new PosType[NTABLE];
g2table = new PosType[NTABLE];
htable = new PosType[NTABLE];
xgtable = new PosType[NTABLE];
for(i = 0 ; i< NTABLE; i++){
x = i*dx;
xtable[i] = x;
ftable[i] = ffunction(x);
gtable[i] = gfunction(x);
g2table[i] = g2function(x);
htable[i] = hfunction(x);
if(i==0){xgtable[i]=0;}
if(i!=0){
xgtable[i] = alpha_int(x);
//Utilities::nintegrate<Ig_func>(g,1E-4,x,dx/10.);
}
}
// modtable[axis ratio 100][potential slope beta 1000][Nmods 32] for Ansatz IV
int j;
modtable = new PosType**[100];
for(i = 0; i < 100; i++){
modtable[i] = new PosType*[200];
for(j = 0; j< 200; j++){
modtable[i][j] = new PosType[Nmod];
}
}
/*
for(i = 0; i<99; i++){
std::cout<< i << std::endl;
PosType iq=0.01*(i+1);
for(j = 0; j< 200; j++){
PosType beta_r=0.01*(j+1);
calcModesC(beta_r, iq, pa, mod);
for(k=0;k<Nmod;k++){
modtable[i][j][k]=mod[k];
}
}
}
*/
}
count++;
}
// InterpolateModes was used for Ansatz IV and is an efficient way to calculate the Fourier modes used for elliptisizing the isotropic profiles before the program starts
PosType LensHaloNFW::InterpolateModes(int whichmod, PosType q, PosType b){
PosType x1,x2,y1,y2,f11,f12,f21,f22;
int i,j,k;
int NTABLEB=200;
int NTABLEQ=99;
PosType const maxb=2.0;
PosType const maxq=0.99;
k=whichmod;
j=(int)(b/maxb*NTABLEB);
i=(int)(q/maxq*NTABLEQ);
f11=modtable[i][j][k];
f12=modtable[i][j+1][k];
f21=modtable[i+1][j][k];
f22=modtable[i+1][j+1][k];
x1=i*maxq/NTABLEQ;
x2=(i+1)*maxq/NTABLEQ;
y1=j*maxb/NTABLEB;
y2=(j+1)*maxb/NTABLEB;
//std::cout << "x12y12: " << q << " " << x1 << " " << x2 << " "<< b << " " << y1 << " " << y2 << " " << std::endl;
//std::cout << "IM: " << f11 << " " << f12 << " " << f21 << " " << f22 << " " << res << std::endl;
return 1.0/(x2-x1)/(y2-y1)*(f11*(x2-q)*(y2-b)+f21*(q-x1)*(y2-b)+f12*(x2-q)*(b-y1)+f22*(q-x1)*(b-y1));
}
PosType LensHaloNFW::InterpolateFromTable(PosType *table, PosType y) const{
int j;
j=(int)(y/maxrm*NTABLE);
//std::cout << "Interp: " << std::setprecision(7) << y-0.95 << " " << std::setprecision(7) << xtable[j]-0.95 << " " << xtable[j+1] <<std::endl;
assert(y>=xtable[j] && y<=xtable[j+1]);
if (j==0)
{
if (table==ftable) return ffunction(y);
if (table==gtable) return gfunction(y);
if (table==g2table) return g2function(y);
if (table==htable) return hfunction(y);
if (table==xgtable) return alpha_int(y);
}
return (table[j+1]-table[j])/(xtable[j+1]-xtable[j])*(y-xtable[j]) + table[j];
}
void LensHaloNFW::assignParams(InputParams& params){
PosType tmp;
if(!params.get("main_zlens",tmp)) error_message1("main_zlens",params.filename());
if(!params.get("main_concentration",rscale)) error_message1("main_concentration",params.filename());
if(!params.get("main_axis_ratio",fratio)){fratio=1; std::cout << "main_axis_ratio not defined in file " << params.filename() << ", hence set to 1." << std::endl;};
if(!params.get("main_pos_angle",pa)){pa=0; std::cout << "main_pos_angle not defined in file " << params.filename() << ", hence set to 0." << std::endl;};
if(!params.get("main_ellip_method",main_ellip_method)){if(fratio!=1){main_ellip_method=Pseudo;std::cout << "main_ellip_method is not defined in file " << params.filename() << ", hence set to Pseudo." << endl;};};
rscale = LensHalo::getRsize()/rscale; // was the concentration
xmax = LensHalo::getRsize()/rscale;
}
LensHaloNFW::~LensHaloNFW(){
--count;
if(count == 0){
delete[] xtable;
delete[] gtable;
delete[] ftable;
delete[] g2table;
delete[] htable;
delete[] xgtable;
// was used for Ansatz IV
for(int i=0; i<99; i++){
for(int j=0; j<200; j++){
delete[] modtable[i][j];
}
delete[] modtable[i];
}
delete[] modtable;
}
}
/// Sets the profile to match the mass, Vmax and R_halfmass
void LensHaloNFW::initFromFile(float my_mass, long *seed, float vmax, float r_halfmass){
LensHalo::setMass(my_mass);
NFW_Utility nfw_util;
// Find the NFW profile with the same mass, Vmax and R_halfmass
nfw_util.match_nfw(vmax,r_halfmass,LensHalo::get_mass(),&rscale,&Rmax);
LensHalo::setRsize(Rmax);
rscale = LensHalo::getRsize()/rscale; // Was the concentration
xmax = LensHalo::getRsize()/rscale;
gmax = InterpolateFromTable(gtable,xmax);
// std::cout << Rmax_halo << " " << LensHalo::getRsize() << std::endl;
}
void LensHaloNFW::initFromMassFunc(float my_mass, float my_Rsize, float my_rscale, PosType my_slope, long* seed)
{
LensHalo::initFromMassFunc(my_mass, my_Rsize, my_rscale, my_slope, seed);
gmax = InterpolateFromTable(gtable,xmax);
}
const long LensHaloPseudoNFW::NTABLE = 10000;
const PosType LensHaloPseudoNFW::maxrm = 100.0;
int LensHaloPseudoNFW::count = 0;
PosType* LensHaloPseudoNFW::xtable = NULL;
PosType* LensHaloPseudoNFW::mhattable = NULL;
LensHaloPseudoNFW::LensHaloPseudoNFW()
: LensHalo()
{
}
/// constructor
LensHaloPseudoNFW::LensHaloPseudoNFW(
float my_mass /// mass in solar masses
,float my_Rsize /// maximum radius in Mpc
,PosType my_zlens /// redshift
,float my_concentration /// Rsize/rscale
,PosType my_beta /// large r slope, see class description
,float my_fratio /// axis ratio
,float my_pa /// position angle
,int my_stars_N /// number of stars, not yet implanted
,const COSMOLOGY &cosmo
,EllipMethod my_ellip_method /// ellipticizing method
)
{
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
LensHalo::setRsize(my_Rsize);
beta = my_beta;
fratio = my_fratio;
pa = my_pa;
stars_N = my_stars_N;
stars_implanted = false;
rscale = LensHalo::getRsize()/my_concentration;
xmax = LensHalo::getRsize()/rscale;
make_tables();
if(fratio!=1){
Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
if(getEllipMethod()==Fourier){
std::cout << "Note: Fourier modes set to ellipticize kappa at slope main_slope+0.5, i.e. "<< get_slope()+0.5 << std::endl;
calcModes(fratio, get_slope()+0.5, pa, mod);
for(int i=1;i<Nmod;i++){
if(mod[i]!=0){set_flag_elliptical(true);};
}
}else set_flag_elliptical(true);
if (getEllipMethod()==Pseudo){
set_norm_factor();
}
}else{
set_flag_elliptical(false);
Rmax = LensHalo::getRsize();
}
}
// The Fourier modes set to ellipticize kappa at slope main_slope+0.5, i.e. e.g. 1.5 for main_slope = 1. Note that set_slope is overridden for PseudoNFW to recalculate tables for different beta. But only fixed values of beta, i.e. 1,2 and >=3 are allowed!
//LensHaloPseudoNFW::LensHaloPseudoNFW(InputParams& params):LensHalo(params)
//{
// assignParams(params);
// make_tables();
// if(fratio!=1){
// Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
// //std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
// if(getEllipMethod()==Fourier){
// std::cout << "Note: Fourier modes set to ellipticize kappa at slope main_slope+0.5, i.e. "<< get_slope()+0.5 << std::endl;
// calcModes(fratio, get_slope()+0.5, pa, mod);
// for(int i=1;i<Nmod;i++){
// //std::cout << mod[i] << std::endl;
// if(mod[i]!=0){set_flag_elliptical(true);};
// }
// }else set_flag_elliptical(true);
// if (getEllipMethod()==Pseudo){
// set_norm_factor();
// }
// }else{
// set_flag_elliptical(false);
// Rmax = LensHalo::getRsize();
// }
//}
/// Auxiliary function for PseudoNFW profile
// previously defined in tables.cpp
PosType LensHaloPseudoNFW::mhat(PosType y, PosType beta) const{
if(y==0) y=1e-5;
if(beta == 1.0) return y - log(1+y);
if(beta == 2.0) return log(1+y) - y/(1+y);
if(beta>=3.0) return ( (1 - beta)*y + pow(1+y,beta-1) - 1)/(beta-2)/(beta-1)/pow(1+y,beta-1);
ERROR_MESSAGE();
std::cout << "Only beta ==1, ==2 and >=3 are valid" << std::endl;
exit(1);
return 0.0;
}
void LensHaloPseudoNFW::make_tables(){
if(count == 0){
int i;
PosType x, dx = maxrm/(PosType)NTABLE;
xtable = new PosType[NTABLE];
mhattable = new PosType[NTABLE];
for(i = 0 ; i< NTABLE; i++){
x = i*dx;
xtable[i] = x;
mhattable[i] = mhat(x,beta);
}
count++;
}
}
PosType LensHaloPseudoNFW::gfunction(PosType y) const{
int j;
j=(int)(y/maxrm*NTABLE);
assert(y>=xtable[j] && y<=xtable[j+1]);
if (j==0) return mhat(y,beta);
return ((mhattable[j+1]-mhattable[j])/(xtable[j+1]-xtable[j])*(y-xtable[j]) + mhattable[j]);
}
PosType LensHaloPseudoNFW::InterpolateFromTable(PosType y) const{
int j;
j=(int)(y/maxrm*NTABLE);
assert(y>=xtable[j] && y<=xtable[j+1]);
if (j==0) return mhat(y,beta);
return (mhattable[j+1]-mhattable[j])/(xtable[j+1]-xtable[j])*(y-xtable[j]) + mhattable[j];
}
void LensHaloPseudoNFW::initFromMassFunc(float my_mass, float my_Rsize, float my_rscale, PosType my_slope, long *seed){
LensHalo::initFromMassFunc(my_mass,my_Rsize,my_rscale,my_slope,seed);
beta = my_slope;
xmax = my_Rsize/my_rscale;
make_tables();
}
void LensHaloPseudoNFW::assignParams(InputParams& params){
if(!params.get("main_concentration",rscale)) error_message1("main_concentration",params.filename());
if(!params.get("main_slope",beta)) error_message1("main_slope",params.filename());
if(!params.get("main_axis_ratio",fratio)){fratio=1; std::cout << "main_axis_ratio not defined in file " << params.filename() << ", hence set to 1." << std::endl;};
if(!params.get("main_pos_angle",pa)){pa=0; std::cout << "main_pos_angle not defined in file " << params.filename() << ", hence set to 0." << std::endl;};
if(!params.get("main_ellip_method",main_ellip_method)){if(fratio!=1){main_ellip_method=Pseudo;std::cout << "main_ellip_method is not defined in file " << params.filename() << ", hence set to Pseudo. CAUTION: Ellipticizing methods have not been tested with PseudoNFW yet!" << endl;};};
rscale = LensHalo::getRsize()/rscale; // was the concentration
xmax = LensHalo::getRsize()/rscale;
}
LensHaloPseudoNFW::~LensHaloPseudoNFW(){
--count;
if(count == 0){
delete[] xtable;
delete[] mhattable;
}
}
LensHaloPowerLaw::LensHaloPowerLaw() : LensHalo(){
beta = 1;
fratio = 1;
rscale = xmax = 1.0;
}
/// constructor
LensHaloPowerLaw::LensHaloPowerLaw(
float my_mass /// mass of halo in solar masses
,float my_Rsize /// maximum radius of halo in Mpc
,PosType my_zlens /// redshift of halo
,PosType my_beta /// logarithmic slop of surface density, kappa \propto r^{-beta}
,float my_fratio /// axis ratio in asymetric case
,float my_pa /// position angle
,int my_stars_N /// number of stars, not yet implanted
,const COSMOLOGY &cosmo
,EllipMethod my_ellip_method /// ellipticizing method
){
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
LensHalo::setRsize(my_Rsize);
beta=my_beta;
fratio=my_fratio, pa=my_pa, main_ellip_method=my_ellip_method, stars_N=my_stars_N;
stars_implanted = false;
rscale = 1;
xmax = LensHalo::getRsize()/rscale ; /// xmax needs to be in initialized before the mass_norm_factor for Pseudo ellip method is calculated via set_norm_factor()
//mnorm = renormalization(get_Rmax());
//std::cout << "PA in PowerLawConstructor: " << pa << std::endl;
if(fratio!=1){
Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
if(getEllipMethod()==Fourier){
calcModes(fratio, beta, pa, mod);
for(int i=1;i<Nmod;i++){
//std::cout << i << " " << mod[i] << std::endl;
if(mod[i]!=0){set_flag_elliptical(true);};
}
}else set_flag_elliptical(true);
if (getEllipMethod()==Pseudo){
fratio=0.00890632+0.99209115*pow(fratio,0.33697702); /// translate fratio's needed for kappa into fratio used for potential
//std::cout << "Pseudo-elliptical method requires fratio transformation, new fratio=" << fratio << std::endl;
set_norm_factor();
}
}else{
set_flag_elliptical(false);
Rmax = LensHalo::getRsize();
}
}
//LensHaloPowerLaw::LensHaloPowerLaw(InputParams& params):LensHalo(params)
//{
// assignParams(params);
// /// If the 2nd argument in calcModes(fratio, slope, pa, mod), the slope, is set to 1 it yields an elliptical kappa contour of given axis ratio (fratio) at the radius where the slope of the 3D density profile is -2, which is defined as the scale radius for the NFW profile. To ellipticize the potential instead of the convergence use calcModes(fratio, 2-get_slope(), pa, mod), this produces also an ellipse in the convergence map, but at the radius where the slope is 2-get_slope().
// /// If the axis ratio given in the parameter file is set to 1 all ellipticizing routines are skipped.
//
// // rscale = xmax = 1.0; // Commented in order to have a correct computation of the potential term in the time delay.
// // Replacing it by :
// rscale = 1;
// xmax = LensHalo::getRsize()/rscale;
//
// if(fratio!=1){
// Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//
// //std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
// if(getEllipMethod()==Fourier){
// calcModes(fratio, beta, pa, mod);
// for(int i=1;i<Nmod;i++){
// //std::cout << i << " " << mod[i] << " " << fratio << " " << beta << " " << pa << " " << std::endl;
// if(mod[i]!=0){set_flag_elliptical(true);};
// }
// }else set_flag_elliptical(true);
// if (getEllipMethod()==Pseudo){
// set_norm_factor();
// }
// }else{
// set_flag_elliptical(false);
// Rmax = LensHalo::getRsize();
// }
// // rscale = xmax = 1.0;
// // mnorm = renormalization(get_Rmax());
// mnorm = 1.;
//}
void LensHaloPowerLaw::initFromMassFunc(float my_mass, float my_Rsize, float my_rscale, PosType my_slope, long *seed){
LensHalo::initFromMassFunc(my_mass,my_Rsize,my_rscale,my_slope,seed);
beta = my_slope;
xmax = my_Rsize/my_rscale;
}
void LensHaloPowerLaw::assignParams(InputParams& params){
if(!params.get("main_slope",beta)) error_message1("main_slope, example 1",params.filename());
//if(beta>=2.0) error_message1("main_slope < 2",params.filename());
if(!params.get("main_axis_ratio",fratio)){fratio=1; std::cout << "main_axis_ratio not defined in file " << params.filename() << ", hence set to 1." << std::endl;};
if(!params.get("main_pos_angle",pa)){pa=0.0; std::cout << "main_pos_angle not defined in file " << params.filename() << ", hence set to 0." << std::endl;};
if(!params.get("main_ellip_method",main_ellip_method)){if(fratio!=1){main_ellip_method=Pseudo;std::cout << "main_ellip_method is not defined in file " << params.filename() << ", hence set to Pseudo." << endl;};};
if(!params.get("main_stars_N",stars_N)) error_message1("main_stars_N",params.filename());
else if(stars_N){
assignParams_stars(params);
}
}
LensHaloPowerLaw::~LensHaloPowerLaw(){
}
LensHaloTNSIE::LensHaloTNSIE(
float my_mass
,PosType my_zlens
,float my_sigma
,float my_rcore
,float my_fratio
,float my_pa
,const COSMOLOGY &cosmo
,float f)
:LensHalo(),sigma(my_sigma),fratio(my_fratio)
,pa(PI/2 - my_pa),rcore(my_rcore)
{
rscale=1.0;
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
if(fratio > 1.0 || fratio < 0.01) throw std::invalid_argument("invalid fratio");
units = sigma*sigma/lightspeed/lightspeed/Grav;///sqrt(fratio); // mass/distance(physical);
rtrunc = my_mass*sqrt(my_fratio)/units/PI + rcore;
Rmax = f * rtrunc;
LensHalo::setRsize(Rmax);
}
void LensHaloTNSIE::force_halo(
PosType *alpha
,KappaType *kappa
,KappaType *gamma
,KappaType *phi
,PosType const *xcm
,bool subtract_point /// if true contribution from a point mass is subtracted
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
)
{
PosType rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
if(rcm2 < 1e-20) rcm2 = 1e-20;
if(rcm2 < Rmax*Rmax){
PosType tmp[2]={0,0};
alphaNSIE(tmp,xcm,fratio,rcore,pa);
alpha[0] += units*tmp[0];
alpha[1] += units*tmp[1];
alphaNSIE(tmp,xcm,fratio,rtrunc,pa);
alpha[0] -= units*tmp[0];
alpha[1] -= units*tmp[1];
{
KappaType tmp[2]={0,0};
*kappa += units*(kappaNSIE(xcm,fratio,rcore,pa) - kappaNSIE(xcm,fratio,rtrunc,pa) );
gammaNSIE(tmp,xcm,fratio,rcore,pa);
gamma[0] += units*tmp[0];
gamma[1] += units*tmp[1];
gammaNSIE(tmp,xcm,fratio,rtrunc,pa);
gamma[0] -= units*tmp[0];
gamma[1] -= units*tmp[1];
}
if(subtract_point)
{
PosType fac = screening*LensHalo::get_mass()/rcm2/PI;
alpha[0] += fac*xcm[0];
alpha[1] += fac*xcm[1];
{
fac = 2.0*fac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*fac;
gamma[1] += xcm[0]*xcm[1]*fac;
}
}
}
else
{
// outside of the halo
if (subtract_point == false)
{
PosType prefac = LensHalo::get_mass()/rcm2/PI;
alpha[0] += -1.0*prefac*xcm[0];
alpha[1] += -1.0*prefac*xcm[1];
{
PosType tmp = -2.0*prefac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
}
}
}
return;
}
/*
LensHaloRealNSIE::LensHaloRealNSIE(float my_mass,float my_Rsize,PosType my_zlens,float my_rscale,float my_sigma
, float my_rcore,float my_fratio,float my_pa,int my_stars_N){
mass=my_mass, Rsize=my_Rsize, zlens=my_zlens, rscale=my_rscale;
sigma=my_sigma, rcore=my_rcore;
fratio=my_fratio, pa=my_pa, stars_N=my_stars_N;
stars_implanted = false;
Rsize = rmaxNSIE(sigma,mass,fratio,rcore);
Rsize = MAX(1.0,1.0/fratio)*Rsize; // redefine
assert(Rmax >= Rsize);
}
*/
size_t LensHaloRealNSIE::objectCount = 0;
std::vector<double> LensHaloRealNSIE::q_table;
std::vector<double> LensHaloRealNSIE::Fofq_table;
LensHaloRealNSIE::LensHaloRealNSIE(
float my_mass /// mass, sets truncation radius
,PosType my_zlens /// redshift
,float my_sigma /// in km/s
,float my_rcore /// core radius
,float my_fratio /// axis ratio
,float my_pa /// postion angle
,int my_stars_N
,const COSMOLOGY &cosmo)
:LensHalo(){
rscale=1.0;
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
sigma=my_sigma, rcore=my_rcore;
fratio=my_fratio, pa = PI/2 - my_pa, stars_N=my_stars_N;
stars_implanted = false;
if(fratio != 1.0) elliptical_flag = true;
else elliptical_flag = false;
++objectCount;
if(objectCount == 1){ // make table for calculating elliptical integrale
construct_ellip_tables();
}
LensHalo::setRsize(rmax_calc());
//std::cout << "NSIE " << Rsize << std::endl;
Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
if(fratio > 1.0 || fratio < 0.01) throw std::invalid_argument("invalid fratio");
if(rcore > 0.0){
LensHalo::setMass(MassBy1DIntegation(LensHalo::getRsize()));
}
units = pow(sigma/lightspeed,2)/Grav;///sqrt(fratio); // mass/distance(physical);
}
//LensHaloRealNSIE::LensHaloRealNSIE(InputParams& params):LensHalo(params,false){
// sigma = 0.;
// fratio = 0.;
// pa = 0.;
// rcore = 0.;
//
// assignParams(params);
//
// if(fratio != 1.0) elliptical_flag = true;
// else elliptical_flag = false;
// ++objectCount;
// if(objectCount == 1){ // make table for calculating elliptical integrale
// construct_ellip_tables();
// }
// //Rsize = rmaxNSIE(sigma,mass,fratio,rcore);
// //Rmax = MAX(1.0,1.0/fratio)*Rsize; // redefine
// LensHalo::setRsize(rmax_calc());
// Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//
// if(fratio > 1.0 || fratio < 0.01) throw std::invalid_argument("invalid fratio");
//
// if(rcore > 0.0){
// LensHalo::setMass(MassBy1DIntegation(LensHalo::getRsize()) );
// }
//
// units = pow(sigma/lightspeed,2)/Grav;///sqrt(fratio); // mass/distance(physical)
//}
void LensHaloRealNSIE::assignParams(InputParams& params){
if(!params.get("main_sigma",sigma)) error_message1("main_sigma",params.filename());
if(!params.get("main_core",rcore)) error_message1("main_core",params.filename());
if(!params.get("main_axis_ratio",fratio)) error_message1("main_axis_ratio",params.filename());
else if(fratio > 1){
ERROR_MESSAGE();
std::cout << "parameter main_axis_ratio must be < 1 in file " << params.filename() << ". Use main_pos_angle to rotate the halo." << std::endl;
exit(1);
}
if(!params.get("main_pos_angle",pa)) error_message1("main_pos_angle",params.filename());
if(params.get("main_ellip_method",main_ellip_method)){std::cout << "main_ellip_method is NOT needed in file " << params.filename() << ". RealNSIE produces parametric ellipses!" << endl;};
if(!params.get("main_stars_N",stars_N)) error_message1("main_stars_N",params.filename());
else if(stars_N){
assignParams_stars(params);
}
}
LensHaloRealNSIE::~LensHaloRealNSIE(){
--objectCount;
if(objectCount == 0){
q_table.resize(0);
Fofq_table.resize(0);
}
}
void LensHaloRealNSIE::construct_ellip_tables(){
int N = 200;
q_table.resize(N);
Fofq_table.resize(N);
q_table[0] = 0.01;
NormFuncer funcer(q_table[0]);
Fofq_table[0] = Utilities::nintegrate<NormFuncer,double>(funcer,0.0,PI/2,1.0e-6)*2/PI;
for(int i=1 ; i < N-1 ; ++i){
q_table[i] = i*1.0/(N-1) + 0.;
NormFuncer funcer(q_table[i]);
Fofq_table[i] = Utilities::nintegrate<NormFuncer,double>(funcer,0.0,PI/2,1.0e-6)*2/PI;
}
q_table.back() = 1.0;
Fofq_table.back() = 1.0;
}
PosType LensHaloRealNSIE::rmax_calc(){
if(fratio == 1.0 || rcore > 0.0)
return sqrt( pow( LensHalo::get_mass()*Grav*lightspeed*lightspeed
*sqrt(fratio)/PI/sigma/sigma + rcore,2)
- rcore*rcore );
// This is because there is no easy way of finding the circular Rmax for a fixed mass when rcore != 0
//if(rcore > 0.0) throw std::runtime_error("rcore must be zero for this constructor");
// asymmetric case
//NormFuncer funcer(fratio);
//double ellipticint = Utilities::nintegrate<NormFuncer,double>(funcer,0.0,PI/2,1.0e-6)*2/PI;
double ellipticint = Utilities::InterpolateYvec(q_table,Fofq_table,fratio)*sqrt(fratio);
return LensHalo::get_mass()*Grav*lightspeed*lightspeed/PI/sigma/sigma/ellipticint;
}
/*
void LensHaloRealNSIE::initFromMass(float my_mass, long *seed){
mass = my_mass;
rcore = 0.0;
sigma = 126*pow(mass/1.0e10,0.25); // From Tully-Fisher and Bell & de Jong 2001
//std::cout << "Warning: All galaxies are spherical" << std::endl;
fratio = (ran2(seed)+1)*0.5; //TODO: Ben change this! This is a kluge.
pa = 2*pi*ran2(seed); //TODO: This is a kluge.
Rsize = rmaxNSIE(sigma,mass,fratio,rcore);
Rmax = MAX(1.0,1.0/fratio)*Rsize; // redefine
assert(Rmax >= Rsize);
}
void LensHaloRealNSIE::initFromFile(float my_mass, long *seed, float vmax, float r_halfmass){
initFromMass(my_mass,seed);
}
void LensHaloRealNSIE::initFromMassFunc(float my_mass, float my_Rmax, float my_rscale, PosType my_slope, long *seed){
initFromMass(my_mass,seed);
}
*/
/** \brief returns the lensing quantities of a ray in center of mass coordinates.
*
* Warning: This adds to input value of alpha, kappa, gamma, and phi. They need
* to be zeroed out if the contribution of just this halo is wanted.
*/
void LensHalo::force_halo(
PosType *alpha /// deflection solar mass/Mpc
,KappaType *kappa /// surface density in Msun/Mpc^2 (?)
,KappaType *gamma /// three components of shear
,KappaType *phi /// potential in solar masses
,PosType const *xcm /// position relative to center (Mpc?)
,bool subtract_point /// if true contribution from a point mass is subtracted
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
)
{
if (elliptical_flag){
force_halo_asym(alpha,kappa,gamma,phi,xcm,subtract_point,screening);
//assert(!isinf(*kappa) );
}else{
force_halo_sym(alpha,kappa,gamma,phi,xcm,subtract_point,screening);
//assert(!isinf(*kappa) );
}
}
/** \brief returns the lensing quantities of a ray in center of mass coordinates for a symmetric halo
*
* phi is defined here in such a way that it differs from alpha by a sign (as we should have alpha = \nabla_x phi)
* but alpha agrees with the rest of the lensing quantities (kappa and gammas).
* Warning : Be careful, the sign of alpha is changed in LensPlaneSingular::force !
*
*/
void LensHalo::force_halo_sym(
PosType *alpha /// solar mass/Mpc
,KappaType *kappa /// convergence
,KappaType *gamma /// three components of shear
,KappaType *phi /// potential solar masses
,PosType const *xcm /// position relative to center (Mpc)
,bool subtract_point /// if true contribution from a point mass is subtracted
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
)
{
PosType rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
if(rcm2 < 1e-20) rcm2 = 1e-20;
/// intersecting, subtract the point particle
if(rcm2 < Rmax*Rmax)
{
PosType prefac = mass/rcm2/PI;
PosType x = sqrt(rcm2)/rscale;
// PosType xmax = Rmax/rscale;
PosType tmp = (alpha_h(x) + 1.0*subtract_point)*prefac;
alpha[0] += tmp*xcm[0];
alpha[1] += tmp*xcm[1];
*kappa += kappa_h(x)*prefac;
tmp = (gamma_h(x) + 2.0*subtract_point) * prefac / rcm2; // ;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
*phi += phi_h(x) * mass / PI ;
if(subtract_point) *phi -= 0.5 * log(rcm2) * mass / PI;
}
else // the point particle is not subtracted
{
if (subtract_point == false)
{
PosType prefac = screening*mass/rcm2/PI;
alpha[0] += -1.0 * prefac * xcm[0];
alpha[1] += -1.0 * prefac * xcm[1];
//std::cout << "rcm2 = " << rcm2 << std::endl;
//std::cout << "prefac = " << prefac << std::endl;
//std::cout << "xcm = " << xcm[0] << " " << xcm[1] << std::endl;
PosType tmp = -2.0*prefac/rcm2;
// kappa is equal to 0 in the point mass case.
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
*phi += 0.5 * log(rcm2) * mass / PI ;
}
}
/// add stars for microlensing
if(stars_N > 0 && stars_implanted)
{
force_stars(alpha,kappa,gamma,xcm);
}
//(alpha[0] == alpha[0] && alpha[1] == alpha[1]);
return;
}
// TODO: put in some comments about the units used
void LensHalo::force_halo_asym(
PosType *alpha /// mass/Mpc
,KappaType *kappa
,KappaType *gamma
,KappaType *phi /// potential solar masses
,PosType const *xcm
,bool subtract_point /// if true contribution from a point mass is subtracted
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
){
//float r_size=get_rsize()*Rmax;
//Rmax=r_size*1.2;
PosType rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
PosType alpha_tmp[2],kappa_tmp,gamma_tmp[2],phi_tmp;
if(rcm2 < 1e-20) rcm2 = 1e-20;
//std::cout << "rsize , rmax, mass_norm =" << Rsize << " , " << Rmax << " , " << mass_norm_factor << std::endl;
//std::cout << subtract_point << std::endl;
/// intersecting, subtract the point particle
if(rcm2 < Rmax*Rmax){
double r = sqrt(rcm2); // devision by rscale for isotropic halos (see above) here taken out because not used for any halo. it should be taken out for the isotropic case too, if others not affected / make use of it ;
double theta;
if(xcm[0] == 0.0 && xcm[1] == 0.0) theta = 0.0;
else theta=atan2(xcm[1],xcm[0]);
if(rcm2 > LensHalo::getRsize()*LensHalo::getRsize()){
PosType alpha_iso[2],alpha_ellip[2];
alpha_ellip[0] = alpha_ellip[1] = 0;
if(main_ellip_method==Pseudo){alphakappagamma_asym(LensHalo::getRsize(),theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
if(main_ellip_method==Fourier){alphakappagamma1asym(LensHalo::getRsize(),theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
if(main_ellip_method==Schramm){alphakappagamma2asym(LensHalo::getRsize(),theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
if(main_ellip_method==Keeton){alphakappagamma3asym(LensHalo::getRsize(),theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
alpha_ellip[0]=alpha_tmp[0]*mass_norm_factor;
alpha_ellip[1]=alpha_tmp[1]*mass_norm_factor;
double f1 = (Rmax - r)/(Rmax - LensHalo::getRsize()),f2 = (r - LensHalo::getRsize())/(Rmax - LensHalo::getRsize());
// PosType tmp = mass/Rmax/PI/r;
PosType tmp = mass/rcm2/PI;
alpha_iso[0] = -1.0*tmp*xcm[0];
alpha_iso[1] = -1.0*tmp*xcm[1];
alpha[0] += alpha_iso[0]*f2 + alpha_ellip[0]*f1;
alpha[1] += alpha_iso[1]*f2 + alpha_ellip[1]*f1;
{
PosType tmp = -2.0*mass/rcm2/PI/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
//gamma[0] += 0.5*gamma_tmp[0]*mass_norm_factor;
//gamma[1] += 0.5*gamma_tmp[1]*mass_norm_factor;
*phi += phi_tmp;
}
}else{
if(main_ellip_method==Pseudo){alphakappagamma_asym(r,theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
if(main_ellip_method==Fourier){alphakappagamma1asym(r,theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
if(main_ellip_method==Schramm){alphakappagamma2asym(r,theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
if(main_ellip_method==Keeton){alphakappagamma3asym(r,theta, alpha_tmp,&kappa_tmp,gamma_tmp,&phi_tmp);}
alpha[0] += alpha_tmp[0]*mass_norm_factor;//-1.0*subtract_point*mass/rcm2/PI*xcm[0];
alpha[1] += alpha_tmp[1]*mass_norm_factor;//-1.0*subtract_point*mass/rcm2/PI*xcm[1];
if(get_switch_flag()==true){ /// case distinction used for elliptical NFWs (true) only (get_switch_flag==true)
*kappa += kappa_tmp*mass_norm_factor*mass_norm_factor;
gamma[0] += 0.5*gamma_tmp[0]*mass_norm_factor*mass_norm_factor;
gamma[1] += 0.5*gamma_tmp[1]*mass_norm_factor*mass_norm_factor;
}else{
*kappa += kappa_tmp*mass_norm_factor;
gamma[0] += 0.5*gamma_tmp[0]*mass_norm_factor;//+1.0*subtract_point*mass/rcm2/PI/rcm2*0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1]);
gamma[1] += 0.5*gamma_tmp[1]*mass_norm_factor;//-1.0*subtract_point*mass/rcm2/PI/rcm2*(xcm[0]*xcm[1]);
//if(theta < 0.660 && theta> 0.659){
//assert(mass_norm_factor==1);
//std::cout << theta << " , " << 0.5*gamma_tmp[0]*mass_norm_factor << " , " << 0.5*gamma_tmp[1]*mass_norm_factor << " , " << kappa_tmp*mass_norm_factor << " , " << alpha_tmp[0]*mass_norm_factor << " , " << alpha_tmp[1]*mass_norm_factor << std::endl;
//}
}
/*if (rcm2 < 1E-6){
std::cout << kappa_tmp*mass_norm_factor << " " << 0.5*gamma_tmp[0]*mass_norm_factor<< " " << 0.5*gamma_tmp[1]*mass_norm_factor << " " <<rcm2 << " " << alpha_tmp[0]*mass_norm_factor << " " << alpha_tmp[1]*mass_norm_factor << std::endl;
}
*/
*phi += phi_tmp;
}
if(subtract_point){
//std::cout << "DO WE EVEN GET HERE??" << std::endl;
PosType tmp = screening*mass/PI/rcm2; // *mass_norm_factor
alpha[0] += tmp*xcm[0];
alpha[1] += tmp*xcm[1];
tmp = 2.0*tmp/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
*phi -= 0.5 * log(rcm2) * mass / PI ; // *mass_norm_factor
}
}
else // the point particle is not subtracted
{
if (subtract_point == false)
{
PosType prefac = mass/rcm2/PI;
alpha[0] += -1.0 * prefac * xcm[0];
alpha[1] += -1.0 * prefac * xcm[1];
//if(rcm2==1.125){
//std::cout << "rcm2 = " << rcm2 << std::endl;
//std::cout << "prefac = " << prefac << std::endl;
//std::cout << "xcm = " << xcm[0] << " " << xcm[1] << std::endl;
//}
PosType tmp = -2.0*prefac/rcm2;
// kappa is equal to 0 in the point mass case.
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
*phi += 0.5 * log(rcm2) * mass / PI ;
}
}
/// add stars for microlensing
if(stars_N > 0 && stars_implanted)
{
force_stars(alpha,kappa,gamma,xcm);
}
//assert(alpha[0] == alpha[0] && alpha[1] == alpha[1]);
return;
}
/* *
void LensHaloRealNSIE::force_halo(
PosType *alpha
,KappaType *kappa
,KappaType *gamma
,KappaType *phi
,PosType const *xcm
,bool subtract_point /// if true contribution from a point mass is subtracted
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
){
PosType rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
if(rcm2 < 1e-20) rcm2 = 1e-20;
// **** test line
if(rcm2 < Rmax*Rmax){
PosType ellipR = ellipticRadiusNSIE(xcm,fratio,pa);
if(ellipR > LensHalo::getRsize()){
// This is the case when the ray is within the NSIE's circular region of influence but outside its elliptical truncation
PosType alpha_out[2],alpha_in[2],rin,x_in[2];
PosType prefac = -1.0*mass/Rmax/PI;
PosType r = sqrt(rcm2);
float units = pow(sigma/lightspeed,2)/Grav/sqrt(fratio); // mass/distance(physical)
alpha_in[0] = alpha_in[1] = 0;
rin = r*LensHalo::getRsize()/ellipR;
alpha_out[0] = prefac*xcm[0]/r;
alpha_out[1] = prefac*xcm[1]/r;
x_in[0] = rin*xcm[0]/r;
x_in[1] = rin*xcm[1]/r;
alphaNSIE(alpha_in,x_in,fratio,rcore,pa);
alpha_in[0] *= units; // minus sign removed because already included in alphaNSIE
alpha_in[1] *= units;
alpha[0] += (r - rin)*(alpha_out[0] - alpha_in[0])/(Rmax - rin) + alpha_in[0];
alpha[1] += (r - rin)*(alpha_out[1] - alpha_in[1])/(Rmax - rin) + alpha_in[1];
//alpha[0] -= (r - rin)*(alpha_out[0] - alpha_in[0])/(Rmax - rin) + alpha_in[0];
//alpha[1] -= (r - rin)*(alpha_out[1] - alpha_in[1])/(Rmax - rin) + alpha_in[1];
{
// TODO: this makes the kappa and gamma disagree with the alpha as calculated above
KappaType tmp[2]={0,0};
PosType xt[2]={0,0};
float units = pow(sigma/lightspeed,2)/Grav/sqrt(fratio); // mass/distance(physical)
xt[0]=xcm[0];
xt[1]=xcm[1];
*kappa += units*kappaNSIE(xt,fratio,rcore,pa);
gammaNSIE(tmp,xt,fratio,rcore,pa);
gamma[0] += units*tmp[0];
gamma[1] += units*tmp[1];
}
}else{
PosType xt[2]={0,0},tmp[2]={0,0};
float units = pow(sigma/lightspeed,2)/Grav/sqrt(fratio); // mass/distance(physical)
xt[0]=xcm[0];
xt[1]=xcm[1];
alphaNSIE(tmp,xt,fratio,rcore,pa);
//alpha[0] = units*tmp[0]; // minus sign removed because already included in alphaNSIE
//alpha[1] = units*tmp[1]; // Why was the "+=" removed?
alpha[0] += units*tmp[0];
alpha[1] += units*tmp[1];
{
KappaType tmp[2]={0,0};
*kappa += units*kappaNSIE(xt,fratio,rcore,pa);
gammaNSIE(tmp,xt,fratio,rcore,pa);
gamma[0] += units*tmp[0];
gamma[1] += units*tmp[1];
}
}
}
else
{
if (subtract_point == false)
{
PosType prefac = mass/rcm2/PI;
alpha[0] += -1.0*prefac*xcm[0];
alpha[1] += -1.0*prefac*xcm[1];
// can turn off kappa and gamma calculations to save times
{
PosType tmp = -2.0*prefac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
}
}
}
if(subtract_point){
PosType fac = mass/rcm2/PI;
alpha[0] += fac*xcm[0];
alpha[1] += fac*xcm[1];
// can turn off kappa and gamma calculations to save times
{
fac = 2.0*fac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*fac;
gamma[1] += xcm[0]*xcm[1]*fac;
}
}
// add stars for microlensing
if(stars_N > 0 && stars_implanted){
force_stars(alpha,kappa,gamma,xcm);
}
return;
}
*/
void LensHaloRealNSIE::force_halo(
PosType *alpha
,KappaType *kappa
,KappaType *gamma
,KappaType *phi
,PosType const *xcm
,bool subtract_point /// if true contribution from a point mass is subtracted
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
)
{
PosType rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
if(rcm2 < 1e-20) rcm2 = 1e-20;
if(rcm2 < Rmax*Rmax){
//PosType ellipR = ellipticRadiusNSIE(xcm,fratio,pa);
// std::cout << "rsize , rmax, mass_norm =" << LensHalo::getRsize() << " , " << Rmax << " , " << mass_norm_factor << std::endl;
if(rcm2 > LensHalo::getRsize()*LensHalo::getRsize())
//if(ellipR > LensHalo::getRsize()*LensHalo::getRsize())
{
// This is the case when the ray is within the NSIE's circular region of influence but outside its elliptical truncation
PosType alpha_iso[2],alpha_ellip[2];
//PosType prefac = -1.0*mass/Rmax/PI;
PosType r = sqrt(rcm2);
//double Rin = sqrt(rcm2)*LensHalo::getRsize()/ellipR;
//std::cout << Rmax << " " << LensHalo::getRsize() << " " << Rmax/LensHalo::getRsize() << std::endl;
double f1 = (Rmax - r)/(Rmax - LensHalo::getRsize()),f2 = (r - LensHalo::getRsize())/(Rmax - LensHalo::getRsize());
//double f1 = (Rmax - r)/(Rmax - Rin),f2 = (r - Rin)/(Rmax - Rin);
// SIE solution
alpha_ellip[0] = alpha_ellip[1] = 0;
alphaNSIE(alpha_ellip,xcm,fratio,rcore,pa);
alpha_ellip[0] *= units;
alpha_ellip[1] *= units;
// SIS solution
//alpha_iso[0] = alpha_iso[1] = 0;
//alphaNSIE(alpha_iso,xcm,1,rcore,pa);
//alpha_iso[0] *= units;
//alpha_iso[1] *= units;
//
// point mass solution
// PosType tmp = mass/rcm2/PI;
PosType tmp = LensHalo::get_mass()/rcm2/PI;
alpha_iso[0] = -1.0*tmp*xcm[0];
alpha_iso[1] = -1.0*tmp*xcm[1];
alpha[0] += alpha_iso[0]*f2 + alpha_ellip[0]*f1;
alpha[1] += alpha_iso[1]*f2 + alpha_ellip[1]*f1;
{
PosType tmp = -2.0*LensHalo::get_mass()/rcm2/PI/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
}
}else{
PosType xt[2]={0,0},tmp[2]={0,0};
xt[0]=xcm[0];
xt[1]=xcm[1];
alphaNSIE(tmp,xt,fratio,rcore,pa);
//alpha[0] = units*tmp[0]; // minus sign removed because already included in alphaNSIE
//alpha[1] = units*tmp[1]; // Why was the "+=" removed?
alpha[0] += units*tmp[0];//*sqrt(fratio);
alpha[1] += units*tmp[1];//*sqrt(fratio);
{
KappaType tmp[2]={0,0};
*kappa += units*kappaNSIE(xt,fratio,rcore,pa);///sqrt(fratio);
gammaNSIE(tmp,xt,fratio,rcore,pa);
gamma[0] += units*tmp[0];
gamma[1] += units*tmp[1];
}
}
if(subtract_point)
{
PosType fac = screening*LensHalo::get_mass()/rcm2/PI;
alpha[0] += fac*xcm[0];
alpha[1] += fac*xcm[1];
{
fac = 2.0*fac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*fac;
gamma[1] += xcm[0]*xcm[1]*fac;
}
}
}
else
{
// outside of the halo
if (subtract_point == false)
{
PosType prefac = LensHalo::get_mass()/rcm2/PI;
alpha[0] += -1.0*prefac*xcm[0];
alpha[1] += -1.0*prefac*xcm[1];
{
PosType tmp = -2.0*prefac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
}
}
}
// add stars for microlensing
if(stars_N > 0 && stars_implanted)
{
force_stars(alpha,kappa,gamma,xcm);
}
//assert(alpha[0] == alpha[0] && alpha[1] == alpha[1]);
return;
}
/**/
const long LensHaloHernquist::NTABLE = 100000;
const PosType LensHaloHernquist::maxrm = 100.0;
int LensHaloHernquist::count = 0;
PosType* LensHaloHernquist::xtable = NULL;
PosType* LensHaloHernquist::ftable = NULL;
PosType* LensHaloHernquist::gtable = NULL;
PosType* LensHaloHernquist::g2table = NULL;
PosType* LensHaloHernquist::htable = NULL;
PosType* LensHaloHernquist::xgtable = NULL;
/*
LensHaloHernquist::LensHaloHernquist()
: LensHalo(), gmax(0)
{
make_tables();
gmax = InterpolateFromTable(gtable,xmax);
}
*/
LensHaloHernquist::LensHaloHernquist(float my_mass,float my_Rsize,PosType my_zlens,float my_rscale,float my_fratio,float my_pa,int my_stars_N,const COSMOLOGY &cosmo, EllipMethod my_ellip_method){
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
LensHalo::setRsize(my_Rsize);
rscale=my_rscale;
fratio=my_fratio, pa=my_pa, stars_N=my_stars_N;
stars_implanted = false;
xmax = LensHalo::getRsize()/rscale;
make_tables();
gmax = InterpolateFromTable(gtable,xmax);
set_slope(1);
/// If the axis ratio given in the parameter file is set to 1 all ellipticizing routines are skipped.
if(fratio!=1){
Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
if(getEllipMethod()==Fourier){
//std::cout << "Hernquist constructor: slope set to " << get_slope() << std::endl;
calcModes(fratio, get_slope(), pa, mod); // to ellipticize potential instead of kappa use (fratio, get_slope()-2, pa, mod)
for(int i=1;i<Nmod;i++){
if(mod[i]!=0){set_flag_elliptical(true);};
}
}else set_flag_elliptical(true);
if (getEllipMethod()==Pseudo){
fratio=0.00890632+0.99209115*pow(fratio,0.33697702);
set_norm_factor();
}
}else{
set_flag_elliptical(false);
Rmax = LensHalo::getRsize();
}
}
//LensHaloHernquist::LensHaloHernquist(InputParams& params): LensHalo(params)
//{
// assignParams(params);
// make_tables();
// gmax = InterpolateFromTable(gtable,xmax);
//
// set_slope(1);
// /// If the axis ratio given in the parameter file is set to 1 all ellipticizing routines are skipped.
// if(fratio!=1){
// //std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
// if(getEllipMethod()==Fourier){
// std::cout << "Hernquist constructor: slope set to " << get_slope() << std::endl;
// calcModes(fratio, get_slope(), pa, mod); // to ellipticize potential instead of kappa use (fratio, get_slope()-2, pa, mod)
// for(int i=1;i<Nmod;i++){
// if(mod[i]!=0){set_flag_elliptical(true);};
// }
// }else set_flag_elliptical(true);
// if (getEllipMethod()==Pseudo){
// set_norm_factor();
// }
// }else set_flag_elliptical(false);
//}
void LensHaloHernquist::make_tables(){
if(count == 0){
int i;
PosType x, dx = maxrm/(PosType)NTABLE;
xtable = new PosType[NTABLE];
ftable = new PosType[NTABLE];
gtable = new PosType[NTABLE];
htable = new PosType[NTABLE];
g2table = new PosType[NTABLE];
xgtable = new PosType[NTABLE];
for(i = 0 ; i< NTABLE; i++){
x = i*dx;
xtable[i] = x;
ftable[i] = ffunction(x);
gtable[i] = gfunction(x);
htable[i] = hfunction(x);
g2table[i] = g2function(x);
if(i==0){xgtable[i]=0;}
if(i!=0){
xgtable[i] = alpha_int(x);
}
}
}
count++;
}
PosType LensHaloHernquist::InterpolateFromTable(PosType *table, PosType y) const{
int j;
j=(int)(y/maxrm*NTABLE);
assert(y>=xtable[j] && y<=xtable[j+1]);
if (j==0)
{
if (table==ftable) return ffunction(y);
if (table==gtable) return gfunction(y);
if (table==g2table) return g2function(y);
if (table==htable) return hfunction(y);
if (table==xgtable) return alpha_int(y);
}
return (table[j+1]-table[j])/(xtable[j+1]-xtable[j])*(y-xtable[j]) + table[j];
}
void LensHaloHernquist::assignParams(InputParams& params){
if(!params.get("main_rscale",rscale)) error_message1("main_rscale",params.filename());
xmax = LensHalo::getRsize()/rscale;
if(!params.get("main_axis_ratio",fratio)){fratio=1; std::cout << "main_axis_ratio not defined in file " << params.filename() << ", hence set to 1." << std::endl;};
if(!params.get("main_pos_angle",pa)){pa=0; std::cout << "main_pos_angle not defined in file " << params.filename() << ", hence set to 0." << std::endl;};
if(!params.get("main_ellip_method",main_ellip_method)){if(fratio!=1){main_ellip_method=Pseudo;std::cout << "main_ellip_method is not defined in file " << params.filename() << ", hence set to Pseudo." << endl;};};
if(!params.get("main_stars_N",stars_N)) error_message1("main_stars_N",params.filename());
else if(stars_N){
assignParams_stars(params);
std::cout << "LensHalo::getRsize() " << LensHalo::getRsize() <<std::endl;
}
}
LensHaloHernquist::~LensHaloHernquist(){
--count;
if(count == 0){
delete[] xtable;
delete[] gtable;
delete[] ftable;
delete[] htable;
delete[] g2table;
delete[] xgtable;
}
}
const long LensHaloJaffe::NTABLE = 100000;
const PosType LensHaloJaffe::maxrm = 100.0;
int LensHaloJaffe::count = 0;
PosType* LensHaloJaffe::xtable = NULL;
PosType* LensHaloJaffe::ftable = NULL;
PosType* LensHaloJaffe::gtable = NULL;
PosType* LensHaloJaffe::g2table = NULL;
PosType* LensHaloJaffe::xgtable = NULL;
//PosType* LensHaloJaffe::htable = NULL;
/*
LensHaloJaffe::LensHaloJaffe()
: LensHalo(), gmax(0)
{
make_tables();
gmax = InterpolateFromTable(gtable,xmax);
}
*/
LensHaloJaffe::LensHaloJaffe(float my_mass,float my_Rsize,PosType my_zlens,float my_rscale,float my_fratio,float my_pa,int my_stars_N,const COSMOLOGY &cosmo, EllipMethod my_ellip_method){
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
LensHalo::setRsize(my_Rsize);
rscale=my_rscale;
fratio=my_fratio, pa=my_pa, stars_N=my_stars_N;
stars_implanted = false;
xmax = LensHalo::getRsize()/rscale;
make_tables();
gmax = InterpolateFromTable(gtable,xmax);
set_slope(1);
if(fratio!=1){
Rmax = Rmax_to_Rsize_ratio*LensHalo::getRsize();
//std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
if(getEllipMethod()==Fourier){
//std::cout << "Jaffe constructor: slope set to " << get_slope() << std::endl;
calcModes(fratio, get_slope(), pa, mod);
for(int i=1;i<Nmod;i++){
if(mod[i]!=0){set_flag_elliptical(true);};
}
}else set_flag_elliptical(true);
if (getEllipMethod()==Pseudo){
fratio=0.00890632+0.99209115*pow(fratio,0.33697702);
set_norm_factor();
}
}else{
set_flag_elliptical(false);
Rmax = LensHalo::getRsize();
}
}
//LensHaloJaffe::LensHaloJaffe(InputParams& params): LensHalo(params)
//{
// assignParams(params);
// make_tables();
// gmax = InterpolateFromTable(gtable,xmax);
//
// set_slope(1);
//
// /// If the axis ratio given in the parameter file is set to 1 all ellipticizing routines are skipped.
// if(fratio!=1){
// //std::cout << getEllipMethod() << " method to ellipticise" << std::endl;
// if(getEllipMethod()==Fourier){
// std::cout << "Jaffe constructor: slope set to " << get_slope() << std::endl;
// calcModes(fratio, get_slope(), pa, mod);
// for(int i=1;i<Nmod;i++){
// if(mod[i]!=0){set_flag_elliptical(true);};
// }
// }else set_flag_elliptical(true);
// if (getEllipMethod()==Pseudo){
// set_norm_factor();
// }
// }else set_flag_elliptical(false);
//}
void LensHaloJaffe::make_tables(){
if(count == 0){
int i;
PosType x, dx = maxrm/(PosType)NTABLE;
xtable = new PosType[NTABLE];
ftable = new PosType[NTABLE];
gtable = new PosType[NTABLE];
g2table = new PosType[NTABLE];
xgtable = new PosType[NTABLE];
for(i = 0 ; i< NTABLE; i++){
x = i*dx;
xtable[i] = x;
ftable[i] = ffunction(x);
gtable[i] = gfunction(x);
g2table[i] = g2function(x);
if(i==0){xgtable[i]=0;}
if(i!=0){
xgtable[i] = alpha_int(x);
}
}
}
count++;
}
PosType LensHaloJaffe::InterpolateFromTable(PosType *table, PosType y) const{
int j;
j=(int)(y/maxrm*NTABLE);
assert(y>=xtable[j] && y<=xtable[j+1]);
if (j==0)
{
if (table==ftable) return ffunction(y);
if (table==gtable) return gfunction(y);
if (table==g2table) return g2function(y);
if (table==xgtable) return alpha_int(y);
}
return (table[j+1]-table[j])/(xtable[j+1]-xtable[j])*(y-xtable[j]) + table[j];
}
void LensHaloJaffe::assignParams(InputParams& params){
if(!params.get("main_rscale",rscale)) error_message1("main_rscale",params.filename());
xmax = LensHalo::getRsize()/rscale;
if(!params.get("main_axis_ratio",fratio)){fratio=1; std::cout << "main_axis_ratio not defined in file " << params.filename() << ", hence set to 1." << std::endl;};
if(!params.get("main_pos_angle",pa)){pa=0; std::cout << "main_pos_angle not defined in file " << params.filename() << ", hence set to 0." << std::endl;};
if(!params.get("main_ellip_method",main_ellip_method)){if(fratio!=1){main_ellip_method=Pseudo;std::cout << "main_ellip_method is not defined in file " << params.filename() << ", hence set to Pseudo." << endl;};};
if(!params.get("main_stars_N",stars_N)) error_message1("main_stars_N",params.filename());
else if(stars_N){
assignParams_stars(params);
}
}
LensHaloJaffe::~LensHaloJaffe(){
--count;
if(count == 0){
delete[] xtable;
delete[] gtable;
delete[] ftable;
delete[] g2table;
delete[] xgtable;
}
}
LensHaloDummy::LensHaloDummy()
: LensHalo()
{
// mass = 0.;
}
LensHaloDummy::LensHaloDummy(float my_mass,float my_Rsize,PosType my_zlens,float my_rscale, int my_stars_N,const COSMOLOGY &cosmo){
LensHalo::setMass(my_mass);
LensHalo::setZlens(my_zlens,cosmo);
LensHalo::setRsize(my_Rsize);
rscale=my_rscale;
stars_N=my_stars_N;
stars_implanted = false;
setTheta(0.0,0.0);
}
//LensHaloDummy::LensHaloDummy(InputParams& params): LensHalo(params)
//{
// assignParams(params);
// // mass = 0.;
//}
void LensHaloDummy::initFromMassFunc(float my_mass, float my_Rsize, float my_rscale, PosType my_slope, long *seed){
LensHalo::setMass(1.e-10);
LensHalo::setRsize(my_Rsize);
rscale = my_rscale;
xmax = LensHalo::getRsize()/rscale;
Rmax = LensHalo::getRsize();
}
void LensHaloDummy::force_halo(PosType *alpha
,KappaType *kappa
,KappaType *gamma
,KappaType *phi
,PosType const *xcm
,bool subtract_point
,PosType screening /// the factor by which to scale the mass for screening of the point mass subtraction
)
{
PosType rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
PosType prefac = LensHalo::get_mass()/rcm2/PI;
PosType tmp = subtract_point*prefac;
alpha[0] += tmp*xcm[0];
alpha[1] += tmp*xcm[1];
// intersecting, subtract the point particle
if(subtract_point)
{
PosType x = screening*sqrt(rcm2)/rscale;
*kappa += kappa_h(x)*prefac;
tmp = (gamma_h(x) + 2.0*subtract_point)*prefac/rcm2;
gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
gamma[1] += xcm[0]*xcm[1]*tmp;
*phi += phi_h(x);
}
// add stars for microlensing
if(stars_N > 0 && stars_implanted)
{
force_stars(alpha,kappa,gamma,xcm);
}
//assert(alpha[0] == alpha[0] && alpha[1] == alpha[1]);
}
void LensHaloDummy::assignParams(InputParams& params)
{
if(params.get("main_ellip_method",main_ellip_method)){std::cout << "main_ellip_method is NOT needed in file " << params.filename() << ". LensHaloDummy does not require ellipticity!" << endl;};
}
std::size_t LensHalo::Nparams() const
{
return 0;
}
PosType LensHalo::getParam(std::size_t p) const
{
switch(p)
{
default:
throw std::invalid_argument("bad parameter index for getParam()");
}
}
PosType LensHalo::setParam(std::size_t p, PosType val)
{
switch(p)
{
default:
throw std::invalid_argument("bad parameter index for setParam()");
}
}
void LensHalo::printCSV(std::ostream&, bool header) const
{
const std::type_info& type = typeid(*this);
std::cerr << "LensHalo subclass " << type.name() << " does not implement printCSV()" << std::endl;
std::exit(1);
}
/// calculates the mass within radius R by integating kappa in theta and R, used only for testing
PosType LensHalo::MassBy2DIntegation(PosType R){
LensHalo::DMDR dmdr(this);
return Utilities::nintegrate<LensHalo::DMDR,PosType>(dmdr,-12,log(R),1.0e-5);
}
/// calculates the mass within radius R by integating alpha on a ring and using Gauss' law, used only for testing
PosType LensHalo::MassBy1DIntegation(PosType R){
LensHalo::DMDTHETA dmdtheta(R,this);
return R*Utilities::nintegrate<LensHalo::DMDTHETA,PosType>(dmdtheta, 0, 2*PI, 1.0e-6)/2;
}
/// calculates the average gamma_t for LensHalo::test()
double LensHalo::test_average_gt(PosType R){
struct test_gt_func f(R,this);
return Utilities::nintegrate<test_gt_func>(f,0.0,2.*PI,1.0e-3);
}
// returns <kappa> x 2PI on a ring at R
double LensHalo::test_average_kappa(PosType R){
struct test_kappa_func f(R,this);
return Utilities::nintegrate<test_kappa_func>(f,0.0,2.*PI,1.0e-3);
}
/// Three tests: 1st - Mass via 1D integration vs mass via 2D integration. 2nd: gamma_t=alpha/r - kappa(R) which can be used for spherical distributions. Deviations are expected for axis ratios <1. For the latter case we use the next test. 3rd: The average along a circular aperture of gamma_t should be equal to <kappa(<R)> minus the average along a circular aperture over kappa. Note that also alpha/r - kappa is checked for consistency with kappa(<R)-<kappa(R)>. For axis ratios < 1 the factor between the two is expected to be of order O(10%).
bool LensHalo::test(){
std::cout << "test alpha's consistance with kappa by comparing mass interior to a radius by 1D integration and Gauss' law and by 2D integration" << std::endl << " The total internal mass is " << mass << std::endl;
std::cout << "R/Rmax R/Rsize Mass 1 D (from alpha) Mass 2 D (m1 - m2)/m1 m2/m1" << std::endl;
int N=25;
PosType m1,m2;
for(int i=1;i<N;++i){
m1 = MassBy1DIntegation(LensHalo::getRsize()*i/(N-4));
m2 = MassBy2DIntegation(LensHalo::getRsize()*i/(N-4));
std::cout << i*1./(N-4) << " " << i/(N-4) << " " << m1 << " "
<< m2 << " "<< (m1-m2)/m1 << " " << m2/m1 << std::endl;
}
PosType r;
std::cout << "test gamma_t's consistance with kappa and alpha by comparing gamma_t to alpha/r - kappa along the x-axis" << std::endl
<< "Not expected to be equal for asymmetric cases."<< std::endl;
std::cout << std::endl <<"R/Rmax R/Rsize gamma_t alpha/r - kappa alpha/r kappa delta/gt " << std::endl;
for(int i=1;i<N;++i){
r = Rsize*i/(N-2);
PosType alpha[2] = {0,0},x[2] = {0,0};
KappaType kappa = 0,gamma[3] = {0,0,0} ,phi=0;
x[0] = r;
x[1] = 0;
force_halo(alpha,&kappa,gamma,&phi,x);
std::cout << r/Rmax << " " << r/Rsize << " " << -gamma[0] << " " << -alpha[0]/r - kappa << " " << -alpha[0]/r << " " << kappa << " " << (alpha[0]/r + kappa)/gamma[0] <<std::endl;
}
std::cout << "test average tangential shear's, gamma_t's, consistance with the average convergence at a radius, kappa(r) and average kappa within a radius calculated using alpha and Gauss' law. gamma_t should be equal to <kappa>_R - kappa(R)" << std::endl;
std::cout << std::endl <<"R/Rmax R/Rsize gamma_t <kappa>_R-kappa(R) <kappa>_R kappa(R) [<kappa>_R-kappa(R)]/gt " << std::endl;
for(int i=1;i<N;++i){
r = Rsize*i/(N-2);
//integrate over t
PosType average_gt, average_kappa;
average_gt=test_average_gt(r)/2/PI;
average_kappa=test_average_kappa(r)/2/PI;
m1 = MassBy1DIntegation(r)/PI/r/r;
std::cout << r/Rmax << " " << r/Rsize << " " << -1.0*average_gt << " " << m1-average_kappa << " " << m1 << " " << average_kappa << " " << -1.0*(m1-average_kappa)/average_gt << std::endl;
PosType alpha[2] = {0,0},x[2] = {0,0};
KappaType kappa = 0,gamma[3] = {0,0,0} ,phi=0;
x[0] = r;
x[1] = 0;
force_halo(alpha,&kappa,gamma,&phi,x);
/*
assert( abs(-1.0*(m1-average_kappa)/average_gt-1.) < 1e-2 ); // <g_t> = <k(<R)>-<kappa(R)> test
if(!elliptical_flag){
assert( abs(abs(-alpha[0]/r)/m1-1.) < 1e-1 ); // alpha/r ~ <kappa(R)>
assert( abs(abs(alpha[0]/r + kappa)/gamma[0])-1.0 < 1e-2); // g_t = alpha/r - kappa test
}
*/
// This is a list of possible assertion test that can be made
//if(!elliptical_flag){
//std::cout << abs(abs(-alpha[0]/r)/m1-1.) << std::endl;
//assert( abs(abs(-alpha[0]/r)/m1-1.) < 1e-1 ); // alpha/r ~ <kappa(R)>
//std::cout << abs(abs(alpha[0]/r + kappa)/gamma[0])-1.0 << std::endl;
//assert( abs(abs(alpha[0]/r + kappa)/gamma[0])-1.0 < 1e-2); // g_t = alpha/r - kappa test
//}
//std::cout << abs(-1.0*(m1-average_kappa)/average_gt-1.) << std::endl;
//std::cout << abs( -alpha[0]/r - kappa ) / abs(m1-average_kappa ) -1. << std::endl;
//assert( abs( -alpha[0]/r - kappa ) / abs(m1-average_kappa ) -1. < 1 ); // alpha/r ~ <kappa(R)>
}
return true;
};
/// The following functions calculate the integrands of the Schramm 1990 method to obtain elliptical halos
PosType LensHalo::DALPHAXDM::operator()(PosType m){
double ap = m*m*a2 + lambda,bp = m*m*b2 + lambda;
double p2 = x[0]*x[0]/ap/ap/ap/ap + x[1]*x[1]/bp/bp/bp/bp; // actually the inverse of equation (5) in Schramm 1990
PosType tmp = m*(isohalo->getRsize());
KappaType kappa=0;
double xiso=tmp/isohalo->rscale;
//PosType alpha[2]={0,0},tm[2] = {m*(isohalo->getRsize()),0};
//KappaType kappam=0,gamma[2]={0,0},phi;
kappa=isohalo->kappa_h(xiso)/PI/xiso/xiso*isohalo->mass;
//isohalo->force_halo_sym(alpha,&kappam,gamma,&phi,tm);
//std::cout << "kappa: " << kappa << " " << kappam << " " << kappa/kappam << std::endl;
assert(kappa >= 0.0);
std::cout << "output x: " << m << " " << m*kappa/(ap*ap*ap*bp*p2) << std::endl;
return m*kappa/(ap*ap*ap*bp*p2); // integrand of equation (28) in Schramm 1990
}
PosType LensHalo::DALPHAYDM::operator()(PosType m){
double ap = m*m*a2 + lambda,bp = m*m*b2 + lambda;
double p2 = x[0]*x[0]/ap/ap/ap/ap + x[1]*x[1]/bp/bp/bp/bp; // actually the inverse of equation (5) in Schramm 1990
PosType tmp = m*(isohalo->getRsize());
KappaType kappa=0;
double xiso=tmp/isohalo->rscale;
//PosType alpha[2]={0,0},tm[2] = {m*(isohalo->getRsize()),0};
//KappaType kappam=0,gamma[2]={0,0},phi;
kappa=isohalo->kappa_h(xiso)/PI/xiso/xiso*isohalo->mass;
//isohalo->force_halo_sym(alpha,&kappam,gamma,&phi,tm);
//std::cout << "kappa: " << kappa << " " << kappam << " " << kappa/kappam << std::endl;
assert(kappa >= 0.0);
return m*kappa/(ap*bp*bp*bp*p2); // integrand of equation (29) in Schramm 1990
}
//bool LensHaloZcompare(LensHalo *lh1,LensHalo *lh2){return (lh1->getZlens() < lh2->getZlens());}
//bool compare(LensHalo *lh1,LensHalo *lh2){return (lh1->getZlens() < lh2->getZlens());}
| 34.072719 | 548 | 0.610973 | glenco |
b7cc0d9b469bff0ae0c501c7300849fefcb3d237 | 122,267 | cpp | C++ | ios/Classes/Native/Bulk_System_2.cpp | ShearerAWS/mini-mafia-release | 1a97656538fe24c015efbfc7954a66065139c34a | [
"MIT"
] | 149 | 2017-06-25T04:03:31.000Z | 2022-02-24T19:31:06.000Z | ios/Classes/Native/Bulk_System_2.cpp | ShearerAWS/mini-mafia-release | 1a97656538fe24c015efbfc7954a66065139c34a | [
"MIT"
] | 9 | 2017-06-24T23:23:11.000Z | 2019-01-16T15:22:13.000Z | ios/Classes/Native/Bulk_System_2.cpp | ShearerAWS/mini-mafia-release | 1a97656538fe24c015efbfc7954a66065139c34a | [
"MIT"
] | 29 | 2017-06-28T17:57:06.000Z | 2021-06-27T12:26:44.000Z | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
template <typename T1, typename T2>
struct VirtActionInvoker2
{
typedef void (*Action)(void*, T1, T2, const RuntimeMethod*);
static inline void Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1, T2 p2)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj);
((Action)invokeData.methodPtr)(obj, p1, p2, invokeData.method);
}
};
template <typename R, typename T1>
struct VirtFuncInvoker1
{
typedef R (*Func)(void*, T1, const RuntimeMethod*);
static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj);
return ((Func)invokeData.methodPtr)(obj, p1, invokeData.method);
}
};
// System.Byte[]
struct ByteU5BU5D_t4116647657;
// System.Char[]
struct CharU5BU5D_t3528271667;
// System.Collections.ArrayList
struct ArrayList_t2718874744;
// System.Collections.Generic.Dictionary`2<System.Int32,System.Int32>
struct Dictionary_2_t1839659084;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32>
struct Dictionary_2_t2736202052;
// System.Collections.Hashtable
struct Hashtable_t1853889766;
// System.Collections.Hashtable/HashKeys
struct HashKeys_t1568156503;
// System.Collections.Hashtable/HashValues
struct HashValues_t618387445;
// System.Collections.Hashtable/Slot[]
struct SlotU5BU5D_t2994659099;
// System.Collections.IComparer
struct IComparer_t1540313114;
// System.Collections.IDictionary
struct IDictionary_t1363984059;
// System.Collections.IEqualityComparer
struct IEqualityComparer_t1493878338;
// System.Collections.IHashCodeProvider
struct IHashCodeProvider_t267601189;
// System.DefaultUriParser
struct DefaultUriParser_t95882050;
// System.Exception
struct Exception_t;
// System.FormatException
struct FormatException_t154580423;
// System.Globalization.Calendar
struct Calendar_t1661121569;
// System.Globalization.Calendar[]
struct CalendarU5BU5D_t3985046076;
// System.Globalization.CompareInfo
struct CompareInfo_t1092934962;
// System.Globalization.CultureInfo
struct CultureInfo_t4157843068;
// System.Globalization.DateTimeFormatInfo
struct DateTimeFormatInfo_t2405853701;
// System.Globalization.NumberFormatInfo
struct NumberFormatInfo_t435877138;
// System.Globalization.TextInfo
struct TextInfo_t3810425522;
// System.Int32
struct Int32_t2950945753;
// System.Int32[]
struct Int32U5BU5D_t385246372;
// System.IntPtr[]
struct IntPtrU5BU5D_t4013366056;
// System.Runtime.Serialization.IFormatterConverter
struct IFormatterConverter_t2171992254;
// System.Runtime.Serialization.SerializationInfo
struct SerializationInfo_t950877179;
// System.String
struct String_t;
// System.String[]
struct StringU5BU5D_t1281789340;
// System.Text.RegularExpressions.FactoryCache
struct FactoryCache_t2327118887;
// System.Text.RegularExpressions.IMachineFactory
struct IMachineFactory_t1209798546;
// System.Text.RegularExpressions.Regex
struct Regex_t3657309853;
// System.Uri
struct Uri_t100236324;
// System.Uri/UriScheme[]
struct UriSchemeU5BU5D_t2082808316;
// System.UriFormatException
struct UriFormatException_t953270471;
// System.UriParser
struct UriParser_t3890150400;
// System.Void
struct Void_t1185182177;
extern RuntimeClass* CultureInfo_t4157843068_il2cpp_TypeInfo_var;
extern RuntimeClass* DefaultUriParser_t95882050_il2cpp_TypeInfo_var;
extern RuntimeClass* GenericUriParser_t1141496137_il2cpp_TypeInfo_var;
extern RuntimeClass* Hashtable_t1853889766_il2cpp_TypeInfo_var;
extern RuntimeClass* Regex_t3657309853_il2cpp_TypeInfo_var;
extern RuntimeClass* RuntimeObject_il2cpp_TypeInfo_var;
extern RuntimeClass* String_t_il2cpp_TypeInfo_var;
extern RuntimeClass* UriFormatException_t953270471_il2cpp_TypeInfo_var;
extern RuntimeClass* UriParser_t3890150400_il2cpp_TypeInfo_var;
extern RuntimeClass* Uri_t100236324_il2cpp_TypeInfo_var;
extern String_t* _stringLiteral2140524769;
extern String_t* _stringLiteral2864059369;
extern String_t* _stringLiteral3452614534;
extern String_t* _stringLiteral3698381084;
extern String_t* _stringLiteral4255182569;
extern String_t* _stringLiteral528199797;
extern const uint32_t UriFormatException__ctor_m1115096473_MetadataUsageId;
extern const uint32_t UriParser_CreateDefaults_m404296154_MetadataUsageId;
extern const uint32_t UriParser_GetParser_m544052729_MetadataUsageId;
extern const uint32_t UriParser_InitializeAndValidate_m2008117311_MetadataUsageId;
extern const uint32_t UriParser_InternalRegister_m3643767086_MetadataUsageId;
extern const uint32_t UriParser__cctor_m3655686731_MetadataUsageId;
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
struct Il2CppArrayBounds;
#ifndef RUNTIMEARRAY_H
#define RUNTIMEARRAY_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEARRAY_H
#ifndef HASHTABLE_T1853889766_H
#define HASHTABLE_T1853889766_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Hashtable
struct Hashtable_t1853889766 : public RuntimeObject
{
public:
// System.Int32 System.Collections.Hashtable::inUse
int32_t ___inUse_1;
// System.Int32 System.Collections.Hashtable::modificationCount
int32_t ___modificationCount_2;
// System.Single System.Collections.Hashtable::loadFactor
float ___loadFactor_3;
// System.Collections.Hashtable/Slot[] System.Collections.Hashtable::table
SlotU5BU5D_t2994659099* ___table_4;
// System.Int32[] System.Collections.Hashtable::hashes
Int32U5BU5D_t385246372* ___hashes_5;
// System.Int32 System.Collections.Hashtable::threshold
int32_t ___threshold_6;
// System.Collections.Hashtable/HashKeys System.Collections.Hashtable::hashKeys
HashKeys_t1568156503 * ___hashKeys_7;
// System.Collections.Hashtable/HashValues System.Collections.Hashtable::hashValues
HashValues_t618387445 * ___hashValues_8;
// System.Collections.IHashCodeProvider System.Collections.Hashtable::hcpRef
RuntimeObject* ___hcpRef_9;
// System.Collections.IComparer System.Collections.Hashtable::comparerRef
RuntimeObject* ___comparerRef_10;
// System.Runtime.Serialization.SerializationInfo System.Collections.Hashtable::serializationInfo
SerializationInfo_t950877179 * ___serializationInfo_11;
// System.Collections.IEqualityComparer System.Collections.Hashtable::equalityComparer
RuntimeObject* ___equalityComparer_12;
public:
inline static int32_t get_offset_of_inUse_1() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___inUse_1)); }
inline int32_t get_inUse_1() const { return ___inUse_1; }
inline int32_t* get_address_of_inUse_1() { return &___inUse_1; }
inline void set_inUse_1(int32_t value)
{
___inUse_1 = value;
}
inline static int32_t get_offset_of_modificationCount_2() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___modificationCount_2)); }
inline int32_t get_modificationCount_2() const { return ___modificationCount_2; }
inline int32_t* get_address_of_modificationCount_2() { return &___modificationCount_2; }
inline void set_modificationCount_2(int32_t value)
{
___modificationCount_2 = value;
}
inline static int32_t get_offset_of_loadFactor_3() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___loadFactor_3)); }
inline float get_loadFactor_3() const { return ___loadFactor_3; }
inline float* get_address_of_loadFactor_3() { return &___loadFactor_3; }
inline void set_loadFactor_3(float value)
{
___loadFactor_3 = value;
}
inline static int32_t get_offset_of_table_4() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___table_4)); }
inline SlotU5BU5D_t2994659099* get_table_4() const { return ___table_4; }
inline SlotU5BU5D_t2994659099** get_address_of_table_4() { return &___table_4; }
inline void set_table_4(SlotU5BU5D_t2994659099* value)
{
___table_4 = value;
Il2CppCodeGenWriteBarrier((&___table_4), value);
}
inline static int32_t get_offset_of_hashes_5() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___hashes_5)); }
inline Int32U5BU5D_t385246372* get_hashes_5() const { return ___hashes_5; }
inline Int32U5BU5D_t385246372** get_address_of_hashes_5() { return &___hashes_5; }
inline void set_hashes_5(Int32U5BU5D_t385246372* value)
{
___hashes_5 = value;
Il2CppCodeGenWriteBarrier((&___hashes_5), value);
}
inline static int32_t get_offset_of_threshold_6() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___threshold_6)); }
inline int32_t get_threshold_6() const { return ___threshold_6; }
inline int32_t* get_address_of_threshold_6() { return &___threshold_6; }
inline void set_threshold_6(int32_t value)
{
___threshold_6 = value;
}
inline static int32_t get_offset_of_hashKeys_7() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___hashKeys_7)); }
inline HashKeys_t1568156503 * get_hashKeys_7() const { return ___hashKeys_7; }
inline HashKeys_t1568156503 ** get_address_of_hashKeys_7() { return &___hashKeys_7; }
inline void set_hashKeys_7(HashKeys_t1568156503 * value)
{
___hashKeys_7 = value;
Il2CppCodeGenWriteBarrier((&___hashKeys_7), value);
}
inline static int32_t get_offset_of_hashValues_8() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___hashValues_8)); }
inline HashValues_t618387445 * get_hashValues_8() const { return ___hashValues_8; }
inline HashValues_t618387445 ** get_address_of_hashValues_8() { return &___hashValues_8; }
inline void set_hashValues_8(HashValues_t618387445 * value)
{
___hashValues_8 = value;
Il2CppCodeGenWriteBarrier((&___hashValues_8), value);
}
inline static int32_t get_offset_of_hcpRef_9() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___hcpRef_9)); }
inline RuntimeObject* get_hcpRef_9() const { return ___hcpRef_9; }
inline RuntimeObject** get_address_of_hcpRef_9() { return &___hcpRef_9; }
inline void set_hcpRef_9(RuntimeObject* value)
{
___hcpRef_9 = value;
Il2CppCodeGenWriteBarrier((&___hcpRef_9), value);
}
inline static int32_t get_offset_of_comparerRef_10() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___comparerRef_10)); }
inline RuntimeObject* get_comparerRef_10() const { return ___comparerRef_10; }
inline RuntimeObject** get_address_of_comparerRef_10() { return &___comparerRef_10; }
inline void set_comparerRef_10(RuntimeObject* value)
{
___comparerRef_10 = value;
Il2CppCodeGenWriteBarrier((&___comparerRef_10), value);
}
inline static int32_t get_offset_of_serializationInfo_11() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___serializationInfo_11)); }
inline SerializationInfo_t950877179 * get_serializationInfo_11() const { return ___serializationInfo_11; }
inline SerializationInfo_t950877179 ** get_address_of_serializationInfo_11() { return &___serializationInfo_11; }
inline void set_serializationInfo_11(SerializationInfo_t950877179 * value)
{
___serializationInfo_11 = value;
Il2CppCodeGenWriteBarrier((&___serializationInfo_11), value);
}
inline static int32_t get_offset_of_equalityComparer_12() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___equalityComparer_12)); }
inline RuntimeObject* get_equalityComparer_12() const { return ___equalityComparer_12; }
inline RuntimeObject** get_address_of_equalityComparer_12() { return &___equalityComparer_12; }
inline void set_equalityComparer_12(RuntimeObject* value)
{
___equalityComparer_12 = value;
Il2CppCodeGenWriteBarrier((&___equalityComparer_12), value);
}
};
struct Hashtable_t1853889766_StaticFields
{
public:
// System.Int32[] System.Collections.Hashtable::primeTbl
Int32U5BU5D_t385246372* ___primeTbl_13;
public:
inline static int32_t get_offset_of_primeTbl_13() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766_StaticFields, ___primeTbl_13)); }
inline Int32U5BU5D_t385246372* get_primeTbl_13() const { return ___primeTbl_13; }
inline Int32U5BU5D_t385246372** get_address_of_primeTbl_13() { return &___primeTbl_13; }
inline void set_primeTbl_13(Int32U5BU5D_t385246372* value)
{
___primeTbl_13 = value;
Il2CppCodeGenWriteBarrier((&___primeTbl_13), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // HASHTABLE_T1853889766_H
#ifndef TYPECONVERTER_T2249118273_H
#define TYPECONVERTER_T2249118273_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverter
struct TypeConverter_t2249118273 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPECONVERTER_T2249118273_H
#ifndef EXCEPTION_T_H
#define EXCEPTION_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Exception
struct Exception_t : public RuntimeObject
{
public:
// System.IntPtr[] System.Exception::trace_ips
IntPtrU5BU5D_t4013366056* ___trace_ips_0;
// System.Exception System.Exception::inner_exception
Exception_t * ___inner_exception_1;
// System.String System.Exception::message
String_t* ___message_2;
// System.String System.Exception::help_link
String_t* ___help_link_3;
// System.String System.Exception::class_name
String_t* ___class_name_4;
// System.String System.Exception::stack_trace
String_t* ___stack_trace_5;
// System.String System.Exception::_remoteStackTraceString
String_t* ____remoteStackTraceString_6;
// System.Int32 System.Exception::remote_stack_index
int32_t ___remote_stack_index_7;
// System.Int32 System.Exception::hresult
int32_t ___hresult_8;
// System.String System.Exception::source
String_t* ___source_9;
// System.Collections.IDictionary System.Exception::_data
RuntimeObject* ____data_10;
public:
inline static int32_t get_offset_of_trace_ips_0() { return static_cast<int32_t>(offsetof(Exception_t, ___trace_ips_0)); }
inline IntPtrU5BU5D_t4013366056* get_trace_ips_0() const { return ___trace_ips_0; }
inline IntPtrU5BU5D_t4013366056** get_address_of_trace_ips_0() { return &___trace_ips_0; }
inline void set_trace_ips_0(IntPtrU5BU5D_t4013366056* value)
{
___trace_ips_0 = value;
Il2CppCodeGenWriteBarrier((&___trace_ips_0), value);
}
inline static int32_t get_offset_of_inner_exception_1() { return static_cast<int32_t>(offsetof(Exception_t, ___inner_exception_1)); }
inline Exception_t * get_inner_exception_1() const { return ___inner_exception_1; }
inline Exception_t ** get_address_of_inner_exception_1() { return &___inner_exception_1; }
inline void set_inner_exception_1(Exception_t * value)
{
___inner_exception_1 = value;
Il2CppCodeGenWriteBarrier((&___inner_exception_1), value);
}
inline static int32_t get_offset_of_message_2() { return static_cast<int32_t>(offsetof(Exception_t, ___message_2)); }
inline String_t* get_message_2() const { return ___message_2; }
inline String_t** get_address_of_message_2() { return &___message_2; }
inline void set_message_2(String_t* value)
{
___message_2 = value;
Il2CppCodeGenWriteBarrier((&___message_2), value);
}
inline static int32_t get_offset_of_help_link_3() { return static_cast<int32_t>(offsetof(Exception_t, ___help_link_3)); }
inline String_t* get_help_link_3() const { return ___help_link_3; }
inline String_t** get_address_of_help_link_3() { return &___help_link_3; }
inline void set_help_link_3(String_t* value)
{
___help_link_3 = value;
Il2CppCodeGenWriteBarrier((&___help_link_3), value);
}
inline static int32_t get_offset_of_class_name_4() { return static_cast<int32_t>(offsetof(Exception_t, ___class_name_4)); }
inline String_t* get_class_name_4() const { return ___class_name_4; }
inline String_t** get_address_of_class_name_4() { return &___class_name_4; }
inline void set_class_name_4(String_t* value)
{
___class_name_4 = value;
Il2CppCodeGenWriteBarrier((&___class_name_4), value);
}
inline static int32_t get_offset_of_stack_trace_5() { return static_cast<int32_t>(offsetof(Exception_t, ___stack_trace_5)); }
inline String_t* get_stack_trace_5() const { return ___stack_trace_5; }
inline String_t** get_address_of_stack_trace_5() { return &___stack_trace_5; }
inline void set_stack_trace_5(String_t* value)
{
___stack_trace_5 = value;
Il2CppCodeGenWriteBarrier((&___stack_trace_5), value);
}
inline static int32_t get_offset_of__remoteStackTraceString_6() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_6)); }
inline String_t* get__remoteStackTraceString_6() const { return ____remoteStackTraceString_6; }
inline String_t** get_address_of__remoteStackTraceString_6() { return &____remoteStackTraceString_6; }
inline void set__remoteStackTraceString_6(String_t* value)
{
____remoteStackTraceString_6 = value;
Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_6), value);
}
inline static int32_t get_offset_of_remote_stack_index_7() { return static_cast<int32_t>(offsetof(Exception_t, ___remote_stack_index_7)); }
inline int32_t get_remote_stack_index_7() const { return ___remote_stack_index_7; }
inline int32_t* get_address_of_remote_stack_index_7() { return &___remote_stack_index_7; }
inline void set_remote_stack_index_7(int32_t value)
{
___remote_stack_index_7 = value;
}
inline static int32_t get_offset_of_hresult_8() { return static_cast<int32_t>(offsetof(Exception_t, ___hresult_8)); }
inline int32_t get_hresult_8() const { return ___hresult_8; }
inline int32_t* get_address_of_hresult_8() { return &___hresult_8; }
inline void set_hresult_8(int32_t value)
{
___hresult_8 = value;
}
inline static int32_t get_offset_of_source_9() { return static_cast<int32_t>(offsetof(Exception_t, ___source_9)); }
inline String_t* get_source_9() const { return ___source_9; }
inline String_t** get_address_of_source_9() { return &___source_9; }
inline void set_source_9(String_t* value)
{
___source_9 = value;
Il2CppCodeGenWriteBarrier((&___source_9), value);
}
inline static int32_t get_offset_of__data_10() { return static_cast<int32_t>(offsetof(Exception_t, ____data_10)); }
inline RuntimeObject* get__data_10() const { return ____data_10; }
inline RuntimeObject** get_address_of__data_10() { return &____data_10; }
inline void set__data_10(RuntimeObject* value)
{
____data_10 = value;
Il2CppCodeGenWriteBarrier((&____data_10), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXCEPTION_T_H
#ifndef CULTUREINFO_T4157843068_H
#define CULTUREINFO_T4157843068_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Globalization.CultureInfo
struct CultureInfo_t4157843068 : public RuntimeObject
{
public:
// System.Boolean System.Globalization.CultureInfo::m_isReadOnly
bool ___m_isReadOnly_7;
// System.Int32 System.Globalization.CultureInfo::cultureID
int32_t ___cultureID_8;
// System.Int32 System.Globalization.CultureInfo::parent_lcid
int32_t ___parent_lcid_9;
// System.Int32 System.Globalization.CultureInfo::specific_lcid
int32_t ___specific_lcid_10;
// System.Int32 System.Globalization.CultureInfo::datetime_index
int32_t ___datetime_index_11;
// System.Int32 System.Globalization.CultureInfo::number_index
int32_t ___number_index_12;
// System.Boolean System.Globalization.CultureInfo::m_useUserOverride
bool ___m_useUserOverride_13;
// System.Globalization.NumberFormatInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::numInfo
NumberFormatInfo_t435877138 * ___numInfo_14;
// System.Globalization.DateTimeFormatInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::dateTimeInfo
DateTimeFormatInfo_t2405853701 * ___dateTimeInfo_15;
// System.Globalization.TextInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::textInfo
TextInfo_t3810425522 * ___textInfo_16;
// System.String System.Globalization.CultureInfo::m_name
String_t* ___m_name_17;
// System.String System.Globalization.CultureInfo::displayname
String_t* ___displayname_18;
// System.String System.Globalization.CultureInfo::englishname
String_t* ___englishname_19;
// System.String System.Globalization.CultureInfo::nativename
String_t* ___nativename_20;
// System.String System.Globalization.CultureInfo::iso3lang
String_t* ___iso3lang_21;
// System.String System.Globalization.CultureInfo::iso2lang
String_t* ___iso2lang_22;
// System.String System.Globalization.CultureInfo::icu_name
String_t* ___icu_name_23;
// System.String System.Globalization.CultureInfo::win3lang
String_t* ___win3lang_24;
// System.String System.Globalization.CultureInfo::territory
String_t* ___territory_25;
// System.Globalization.CompareInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::compareInfo
CompareInfo_t1092934962 * ___compareInfo_26;
// System.Int32* System.Globalization.CultureInfo::calendar_data
int32_t* ___calendar_data_27;
// System.Void* System.Globalization.CultureInfo::textinfo_data
void* ___textinfo_data_28;
// System.Globalization.Calendar[] System.Globalization.CultureInfo::optional_calendars
CalendarU5BU5D_t3985046076* ___optional_calendars_29;
// System.Globalization.CultureInfo System.Globalization.CultureInfo::parent_culture
CultureInfo_t4157843068 * ___parent_culture_30;
// System.Int32 System.Globalization.CultureInfo::m_dataItem
int32_t ___m_dataItem_31;
// System.Globalization.Calendar System.Globalization.CultureInfo::calendar
Calendar_t1661121569 * ___calendar_32;
// System.Boolean System.Globalization.CultureInfo::constructed
bool ___constructed_33;
// System.Byte[] System.Globalization.CultureInfo::cached_serialized_form
ByteU5BU5D_t4116647657* ___cached_serialized_form_34;
public:
inline static int32_t get_offset_of_m_isReadOnly_7() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___m_isReadOnly_7)); }
inline bool get_m_isReadOnly_7() const { return ___m_isReadOnly_7; }
inline bool* get_address_of_m_isReadOnly_7() { return &___m_isReadOnly_7; }
inline void set_m_isReadOnly_7(bool value)
{
___m_isReadOnly_7 = value;
}
inline static int32_t get_offset_of_cultureID_8() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___cultureID_8)); }
inline int32_t get_cultureID_8() const { return ___cultureID_8; }
inline int32_t* get_address_of_cultureID_8() { return &___cultureID_8; }
inline void set_cultureID_8(int32_t value)
{
___cultureID_8 = value;
}
inline static int32_t get_offset_of_parent_lcid_9() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___parent_lcid_9)); }
inline int32_t get_parent_lcid_9() const { return ___parent_lcid_9; }
inline int32_t* get_address_of_parent_lcid_9() { return &___parent_lcid_9; }
inline void set_parent_lcid_9(int32_t value)
{
___parent_lcid_9 = value;
}
inline static int32_t get_offset_of_specific_lcid_10() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___specific_lcid_10)); }
inline int32_t get_specific_lcid_10() const { return ___specific_lcid_10; }
inline int32_t* get_address_of_specific_lcid_10() { return &___specific_lcid_10; }
inline void set_specific_lcid_10(int32_t value)
{
___specific_lcid_10 = value;
}
inline static int32_t get_offset_of_datetime_index_11() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___datetime_index_11)); }
inline int32_t get_datetime_index_11() const { return ___datetime_index_11; }
inline int32_t* get_address_of_datetime_index_11() { return &___datetime_index_11; }
inline void set_datetime_index_11(int32_t value)
{
___datetime_index_11 = value;
}
inline static int32_t get_offset_of_number_index_12() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___number_index_12)); }
inline int32_t get_number_index_12() const { return ___number_index_12; }
inline int32_t* get_address_of_number_index_12() { return &___number_index_12; }
inline void set_number_index_12(int32_t value)
{
___number_index_12 = value;
}
inline static int32_t get_offset_of_m_useUserOverride_13() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___m_useUserOverride_13)); }
inline bool get_m_useUserOverride_13() const { return ___m_useUserOverride_13; }
inline bool* get_address_of_m_useUserOverride_13() { return &___m_useUserOverride_13; }
inline void set_m_useUserOverride_13(bool value)
{
___m_useUserOverride_13 = value;
}
inline static int32_t get_offset_of_numInfo_14() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___numInfo_14)); }
inline NumberFormatInfo_t435877138 * get_numInfo_14() const { return ___numInfo_14; }
inline NumberFormatInfo_t435877138 ** get_address_of_numInfo_14() { return &___numInfo_14; }
inline void set_numInfo_14(NumberFormatInfo_t435877138 * value)
{
___numInfo_14 = value;
Il2CppCodeGenWriteBarrier((&___numInfo_14), value);
}
inline static int32_t get_offset_of_dateTimeInfo_15() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___dateTimeInfo_15)); }
inline DateTimeFormatInfo_t2405853701 * get_dateTimeInfo_15() const { return ___dateTimeInfo_15; }
inline DateTimeFormatInfo_t2405853701 ** get_address_of_dateTimeInfo_15() { return &___dateTimeInfo_15; }
inline void set_dateTimeInfo_15(DateTimeFormatInfo_t2405853701 * value)
{
___dateTimeInfo_15 = value;
Il2CppCodeGenWriteBarrier((&___dateTimeInfo_15), value);
}
inline static int32_t get_offset_of_textInfo_16() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___textInfo_16)); }
inline TextInfo_t3810425522 * get_textInfo_16() const { return ___textInfo_16; }
inline TextInfo_t3810425522 ** get_address_of_textInfo_16() { return &___textInfo_16; }
inline void set_textInfo_16(TextInfo_t3810425522 * value)
{
___textInfo_16 = value;
Il2CppCodeGenWriteBarrier((&___textInfo_16), value);
}
inline static int32_t get_offset_of_m_name_17() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___m_name_17)); }
inline String_t* get_m_name_17() const { return ___m_name_17; }
inline String_t** get_address_of_m_name_17() { return &___m_name_17; }
inline void set_m_name_17(String_t* value)
{
___m_name_17 = value;
Il2CppCodeGenWriteBarrier((&___m_name_17), value);
}
inline static int32_t get_offset_of_displayname_18() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___displayname_18)); }
inline String_t* get_displayname_18() const { return ___displayname_18; }
inline String_t** get_address_of_displayname_18() { return &___displayname_18; }
inline void set_displayname_18(String_t* value)
{
___displayname_18 = value;
Il2CppCodeGenWriteBarrier((&___displayname_18), value);
}
inline static int32_t get_offset_of_englishname_19() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___englishname_19)); }
inline String_t* get_englishname_19() const { return ___englishname_19; }
inline String_t** get_address_of_englishname_19() { return &___englishname_19; }
inline void set_englishname_19(String_t* value)
{
___englishname_19 = value;
Il2CppCodeGenWriteBarrier((&___englishname_19), value);
}
inline static int32_t get_offset_of_nativename_20() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___nativename_20)); }
inline String_t* get_nativename_20() const { return ___nativename_20; }
inline String_t** get_address_of_nativename_20() { return &___nativename_20; }
inline void set_nativename_20(String_t* value)
{
___nativename_20 = value;
Il2CppCodeGenWriteBarrier((&___nativename_20), value);
}
inline static int32_t get_offset_of_iso3lang_21() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___iso3lang_21)); }
inline String_t* get_iso3lang_21() const { return ___iso3lang_21; }
inline String_t** get_address_of_iso3lang_21() { return &___iso3lang_21; }
inline void set_iso3lang_21(String_t* value)
{
___iso3lang_21 = value;
Il2CppCodeGenWriteBarrier((&___iso3lang_21), value);
}
inline static int32_t get_offset_of_iso2lang_22() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___iso2lang_22)); }
inline String_t* get_iso2lang_22() const { return ___iso2lang_22; }
inline String_t** get_address_of_iso2lang_22() { return &___iso2lang_22; }
inline void set_iso2lang_22(String_t* value)
{
___iso2lang_22 = value;
Il2CppCodeGenWriteBarrier((&___iso2lang_22), value);
}
inline static int32_t get_offset_of_icu_name_23() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___icu_name_23)); }
inline String_t* get_icu_name_23() const { return ___icu_name_23; }
inline String_t** get_address_of_icu_name_23() { return &___icu_name_23; }
inline void set_icu_name_23(String_t* value)
{
___icu_name_23 = value;
Il2CppCodeGenWriteBarrier((&___icu_name_23), value);
}
inline static int32_t get_offset_of_win3lang_24() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___win3lang_24)); }
inline String_t* get_win3lang_24() const { return ___win3lang_24; }
inline String_t** get_address_of_win3lang_24() { return &___win3lang_24; }
inline void set_win3lang_24(String_t* value)
{
___win3lang_24 = value;
Il2CppCodeGenWriteBarrier((&___win3lang_24), value);
}
inline static int32_t get_offset_of_territory_25() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___territory_25)); }
inline String_t* get_territory_25() const { return ___territory_25; }
inline String_t** get_address_of_territory_25() { return &___territory_25; }
inline void set_territory_25(String_t* value)
{
___territory_25 = value;
Il2CppCodeGenWriteBarrier((&___territory_25), value);
}
inline static int32_t get_offset_of_compareInfo_26() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___compareInfo_26)); }
inline CompareInfo_t1092934962 * get_compareInfo_26() const { return ___compareInfo_26; }
inline CompareInfo_t1092934962 ** get_address_of_compareInfo_26() { return &___compareInfo_26; }
inline void set_compareInfo_26(CompareInfo_t1092934962 * value)
{
___compareInfo_26 = value;
Il2CppCodeGenWriteBarrier((&___compareInfo_26), value);
}
inline static int32_t get_offset_of_calendar_data_27() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___calendar_data_27)); }
inline int32_t* get_calendar_data_27() const { return ___calendar_data_27; }
inline int32_t** get_address_of_calendar_data_27() { return &___calendar_data_27; }
inline void set_calendar_data_27(int32_t* value)
{
___calendar_data_27 = value;
}
inline static int32_t get_offset_of_textinfo_data_28() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___textinfo_data_28)); }
inline void* get_textinfo_data_28() const { return ___textinfo_data_28; }
inline void** get_address_of_textinfo_data_28() { return &___textinfo_data_28; }
inline void set_textinfo_data_28(void* value)
{
___textinfo_data_28 = value;
}
inline static int32_t get_offset_of_optional_calendars_29() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___optional_calendars_29)); }
inline CalendarU5BU5D_t3985046076* get_optional_calendars_29() const { return ___optional_calendars_29; }
inline CalendarU5BU5D_t3985046076** get_address_of_optional_calendars_29() { return &___optional_calendars_29; }
inline void set_optional_calendars_29(CalendarU5BU5D_t3985046076* value)
{
___optional_calendars_29 = value;
Il2CppCodeGenWriteBarrier((&___optional_calendars_29), value);
}
inline static int32_t get_offset_of_parent_culture_30() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___parent_culture_30)); }
inline CultureInfo_t4157843068 * get_parent_culture_30() const { return ___parent_culture_30; }
inline CultureInfo_t4157843068 ** get_address_of_parent_culture_30() { return &___parent_culture_30; }
inline void set_parent_culture_30(CultureInfo_t4157843068 * value)
{
___parent_culture_30 = value;
Il2CppCodeGenWriteBarrier((&___parent_culture_30), value);
}
inline static int32_t get_offset_of_m_dataItem_31() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___m_dataItem_31)); }
inline int32_t get_m_dataItem_31() const { return ___m_dataItem_31; }
inline int32_t* get_address_of_m_dataItem_31() { return &___m_dataItem_31; }
inline void set_m_dataItem_31(int32_t value)
{
___m_dataItem_31 = value;
}
inline static int32_t get_offset_of_calendar_32() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___calendar_32)); }
inline Calendar_t1661121569 * get_calendar_32() const { return ___calendar_32; }
inline Calendar_t1661121569 ** get_address_of_calendar_32() { return &___calendar_32; }
inline void set_calendar_32(Calendar_t1661121569 * value)
{
___calendar_32 = value;
Il2CppCodeGenWriteBarrier((&___calendar_32), value);
}
inline static int32_t get_offset_of_constructed_33() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___constructed_33)); }
inline bool get_constructed_33() const { return ___constructed_33; }
inline bool* get_address_of_constructed_33() { return &___constructed_33; }
inline void set_constructed_33(bool value)
{
___constructed_33 = value;
}
inline static int32_t get_offset_of_cached_serialized_form_34() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068, ___cached_serialized_form_34)); }
inline ByteU5BU5D_t4116647657* get_cached_serialized_form_34() const { return ___cached_serialized_form_34; }
inline ByteU5BU5D_t4116647657** get_address_of_cached_serialized_form_34() { return &___cached_serialized_form_34; }
inline void set_cached_serialized_form_34(ByteU5BU5D_t4116647657* value)
{
___cached_serialized_form_34 = value;
Il2CppCodeGenWriteBarrier((&___cached_serialized_form_34), value);
}
};
struct CultureInfo_t4157843068_StaticFields
{
public:
// System.Globalization.CultureInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::invariant_culture_info
CultureInfo_t4157843068 * ___invariant_culture_info_4;
// System.Object System.Globalization.CultureInfo::shared_table_lock
RuntimeObject * ___shared_table_lock_5;
// System.Int32 System.Globalization.CultureInfo::BootstrapCultureID
int32_t ___BootstrapCultureID_6;
// System.String System.Globalization.CultureInfo::MSG_READONLY
String_t* ___MSG_READONLY_35;
// System.Collections.Hashtable System.Globalization.CultureInfo::shared_by_number
Hashtable_t1853889766 * ___shared_by_number_36;
// System.Collections.Hashtable System.Globalization.CultureInfo::shared_by_name
Hashtable_t1853889766 * ___shared_by_name_37;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Globalization.CultureInfo::<>f__switch$map19
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map19_38;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Globalization.CultureInfo::<>f__switch$map1A
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map1A_39;
public:
inline static int32_t get_offset_of_invariant_culture_info_4() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___invariant_culture_info_4)); }
inline CultureInfo_t4157843068 * get_invariant_culture_info_4() const { return ___invariant_culture_info_4; }
inline CultureInfo_t4157843068 ** get_address_of_invariant_culture_info_4() { return &___invariant_culture_info_4; }
inline void set_invariant_culture_info_4(CultureInfo_t4157843068 * value)
{
___invariant_culture_info_4 = value;
Il2CppCodeGenWriteBarrier((&___invariant_culture_info_4), value);
}
inline static int32_t get_offset_of_shared_table_lock_5() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___shared_table_lock_5)); }
inline RuntimeObject * get_shared_table_lock_5() const { return ___shared_table_lock_5; }
inline RuntimeObject ** get_address_of_shared_table_lock_5() { return &___shared_table_lock_5; }
inline void set_shared_table_lock_5(RuntimeObject * value)
{
___shared_table_lock_5 = value;
Il2CppCodeGenWriteBarrier((&___shared_table_lock_5), value);
}
inline static int32_t get_offset_of_BootstrapCultureID_6() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___BootstrapCultureID_6)); }
inline int32_t get_BootstrapCultureID_6() const { return ___BootstrapCultureID_6; }
inline int32_t* get_address_of_BootstrapCultureID_6() { return &___BootstrapCultureID_6; }
inline void set_BootstrapCultureID_6(int32_t value)
{
___BootstrapCultureID_6 = value;
}
inline static int32_t get_offset_of_MSG_READONLY_35() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___MSG_READONLY_35)); }
inline String_t* get_MSG_READONLY_35() const { return ___MSG_READONLY_35; }
inline String_t** get_address_of_MSG_READONLY_35() { return &___MSG_READONLY_35; }
inline void set_MSG_READONLY_35(String_t* value)
{
___MSG_READONLY_35 = value;
Il2CppCodeGenWriteBarrier((&___MSG_READONLY_35), value);
}
inline static int32_t get_offset_of_shared_by_number_36() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___shared_by_number_36)); }
inline Hashtable_t1853889766 * get_shared_by_number_36() const { return ___shared_by_number_36; }
inline Hashtable_t1853889766 ** get_address_of_shared_by_number_36() { return &___shared_by_number_36; }
inline void set_shared_by_number_36(Hashtable_t1853889766 * value)
{
___shared_by_number_36 = value;
Il2CppCodeGenWriteBarrier((&___shared_by_number_36), value);
}
inline static int32_t get_offset_of_shared_by_name_37() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___shared_by_name_37)); }
inline Hashtable_t1853889766 * get_shared_by_name_37() const { return ___shared_by_name_37; }
inline Hashtable_t1853889766 ** get_address_of_shared_by_name_37() { return &___shared_by_name_37; }
inline void set_shared_by_name_37(Hashtable_t1853889766 * value)
{
___shared_by_name_37 = value;
Il2CppCodeGenWriteBarrier((&___shared_by_name_37), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map19_38() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___U3CU3Ef__switchU24map19_38)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map19_38() const { return ___U3CU3Ef__switchU24map19_38; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map19_38() { return &___U3CU3Ef__switchU24map19_38; }
inline void set_U3CU3Ef__switchU24map19_38(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map19_38 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map19_38), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map1A_39() { return static_cast<int32_t>(offsetof(CultureInfo_t4157843068_StaticFields, ___U3CU3Ef__switchU24map1A_39)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map1A_39() const { return ___U3CU3Ef__switchU24map1A_39; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map1A_39() { return &___U3CU3Ef__switchU24map1A_39; }
inline void set_U3CU3Ef__switchU24map1A_39(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map1A_39 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map1A_39), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CULTUREINFO_T4157843068_H
#ifndef SERIALIZATIONINFO_T950877179_H
#define SERIALIZATIONINFO_T950877179_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.Serialization.SerializationInfo
struct SerializationInfo_t950877179 : public RuntimeObject
{
public:
// System.Collections.Hashtable System.Runtime.Serialization.SerializationInfo::serialized
Hashtable_t1853889766 * ___serialized_0;
// System.Collections.ArrayList System.Runtime.Serialization.SerializationInfo::values
ArrayList_t2718874744 * ___values_1;
// System.String System.Runtime.Serialization.SerializationInfo::assemblyName
String_t* ___assemblyName_2;
// System.String System.Runtime.Serialization.SerializationInfo::fullTypeName
String_t* ___fullTypeName_3;
// System.Runtime.Serialization.IFormatterConverter System.Runtime.Serialization.SerializationInfo::converter
RuntimeObject* ___converter_4;
public:
inline static int32_t get_offset_of_serialized_0() { return static_cast<int32_t>(offsetof(SerializationInfo_t950877179, ___serialized_0)); }
inline Hashtable_t1853889766 * get_serialized_0() const { return ___serialized_0; }
inline Hashtable_t1853889766 ** get_address_of_serialized_0() { return &___serialized_0; }
inline void set_serialized_0(Hashtable_t1853889766 * value)
{
___serialized_0 = value;
Il2CppCodeGenWriteBarrier((&___serialized_0), value);
}
inline static int32_t get_offset_of_values_1() { return static_cast<int32_t>(offsetof(SerializationInfo_t950877179, ___values_1)); }
inline ArrayList_t2718874744 * get_values_1() const { return ___values_1; }
inline ArrayList_t2718874744 ** get_address_of_values_1() { return &___values_1; }
inline void set_values_1(ArrayList_t2718874744 * value)
{
___values_1 = value;
Il2CppCodeGenWriteBarrier((&___values_1), value);
}
inline static int32_t get_offset_of_assemblyName_2() { return static_cast<int32_t>(offsetof(SerializationInfo_t950877179, ___assemblyName_2)); }
inline String_t* get_assemblyName_2() const { return ___assemblyName_2; }
inline String_t** get_address_of_assemblyName_2() { return &___assemblyName_2; }
inline void set_assemblyName_2(String_t* value)
{
___assemblyName_2 = value;
Il2CppCodeGenWriteBarrier((&___assemblyName_2), value);
}
inline static int32_t get_offset_of_fullTypeName_3() { return static_cast<int32_t>(offsetof(SerializationInfo_t950877179, ___fullTypeName_3)); }
inline String_t* get_fullTypeName_3() const { return ___fullTypeName_3; }
inline String_t** get_address_of_fullTypeName_3() { return &___fullTypeName_3; }
inline void set_fullTypeName_3(String_t* value)
{
___fullTypeName_3 = value;
Il2CppCodeGenWriteBarrier((&___fullTypeName_3), value);
}
inline static int32_t get_offset_of_converter_4() { return static_cast<int32_t>(offsetof(SerializationInfo_t950877179, ___converter_4)); }
inline RuntimeObject* get_converter_4() const { return ___converter_4; }
inline RuntimeObject** get_address_of_converter_4() { return &___converter_4; }
inline void set_converter_4(RuntimeObject* value)
{
___converter_4 = value;
Il2CppCodeGenWriteBarrier((&___converter_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SERIALIZATIONINFO_T950877179_H
#ifndef STRING_T_H
#define STRING_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::length
int32_t ___length_0;
// System.Char System.String::start_char
Il2CppChar ___start_char_1;
public:
inline static int32_t get_offset_of_length_0() { return static_cast<int32_t>(offsetof(String_t, ___length_0)); }
inline int32_t get_length_0() const { return ___length_0; }
inline int32_t* get_address_of_length_0() { return &___length_0; }
inline void set_length_0(int32_t value)
{
___length_0 = value;
}
inline static int32_t get_offset_of_start_char_1() { return static_cast<int32_t>(offsetof(String_t, ___start_char_1)); }
inline Il2CppChar get_start_char_1() const { return ___start_char_1; }
inline Il2CppChar* get_address_of_start_char_1() { return &___start_char_1; }
inline void set_start_char_1(Il2CppChar value)
{
___start_char_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_2;
// System.Char[] System.String::WhiteChars
CharU5BU5D_t3528271667* ___WhiteChars_3;
public:
inline static int32_t get_offset_of_Empty_2() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_2)); }
inline String_t* get_Empty_2() const { return ___Empty_2; }
inline String_t** get_address_of_Empty_2() { return &___Empty_2; }
inline void set_Empty_2(String_t* value)
{
___Empty_2 = value;
Il2CppCodeGenWriteBarrier((&___Empty_2), value);
}
inline static int32_t get_offset_of_WhiteChars_3() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___WhiteChars_3)); }
inline CharU5BU5D_t3528271667* get_WhiteChars_3() const { return ___WhiteChars_3; }
inline CharU5BU5D_t3528271667** get_address_of_WhiteChars_3() { return &___WhiteChars_3; }
inline void set_WhiteChars_3(CharU5BU5D_t3528271667* value)
{
___WhiteChars_3 = value;
Il2CppCodeGenWriteBarrier((&___WhiteChars_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRING_T_H
#ifndef URI_T100236324_H
#define URI_T100236324_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Uri
struct Uri_t100236324 : public RuntimeObject
{
public:
// System.Boolean System.Uri::isUnixFilePath
bool ___isUnixFilePath_1;
// System.String System.Uri::source
String_t* ___source_2;
// System.String System.Uri::scheme
String_t* ___scheme_3;
// System.String System.Uri::host
String_t* ___host_4;
// System.Int32 System.Uri::port
int32_t ___port_5;
// System.String System.Uri::path
String_t* ___path_6;
// System.String System.Uri::query
String_t* ___query_7;
// System.String System.Uri::fragment
String_t* ___fragment_8;
// System.String System.Uri::userinfo
String_t* ___userinfo_9;
// System.Boolean System.Uri::isUnc
bool ___isUnc_10;
// System.Boolean System.Uri::isOpaquePart
bool ___isOpaquePart_11;
// System.Boolean System.Uri::isAbsoluteUri
bool ___isAbsoluteUri_12;
// System.String[] System.Uri::segments
StringU5BU5D_t1281789340* ___segments_13;
// System.Boolean System.Uri::userEscaped
bool ___userEscaped_14;
// System.String System.Uri::cachedAbsoluteUri
String_t* ___cachedAbsoluteUri_15;
// System.String System.Uri::cachedToString
String_t* ___cachedToString_16;
// System.String System.Uri::cachedLocalPath
String_t* ___cachedLocalPath_17;
// System.Int32 System.Uri::cachedHashCode
int32_t ___cachedHashCode_18;
// System.UriParser System.Uri::parser
UriParser_t3890150400 * ___parser_32;
public:
inline static int32_t get_offset_of_isUnixFilePath_1() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___isUnixFilePath_1)); }
inline bool get_isUnixFilePath_1() const { return ___isUnixFilePath_1; }
inline bool* get_address_of_isUnixFilePath_1() { return &___isUnixFilePath_1; }
inline void set_isUnixFilePath_1(bool value)
{
___isUnixFilePath_1 = value;
}
inline static int32_t get_offset_of_source_2() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___source_2)); }
inline String_t* get_source_2() const { return ___source_2; }
inline String_t** get_address_of_source_2() { return &___source_2; }
inline void set_source_2(String_t* value)
{
___source_2 = value;
Il2CppCodeGenWriteBarrier((&___source_2), value);
}
inline static int32_t get_offset_of_scheme_3() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___scheme_3)); }
inline String_t* get_scheme_3() const { return ___scheme_3; }
inline String_t** get_address_of_scheme_3() { return &___scheme_3; }
inline void set_scheme_3(String_t* value)
{
___scheme_3 = value;
Il2CppCodeGenWriteBarrier((&___scheme_3), value);
}
inline static int32_t get_offset_of_host_4() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___host_4)); }
inline String_t* get_host_4() const { return ___host_4; }
inline String_t** get_address_of_host_4() { return &___host_4; }
inline void set_host_4(String_t* value)
{
___host_4 = value;
Il2CppCodeGenWriteBarrier((&___host_4), value);
}
inline static int32_t get_offset_of_port_5() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___port_5)); }
inline int32_t get_port_5() const { return ___port_5; }
inline int32_t* get_address_of_port_5() { return &___port_5; }
inline void set_port_5(int32_t value)
{
___port_5 = value;
}
inline static int32_t get_offset_of_path_6() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___path_6)); }
inline String_t* get_path_6() const { return ___path_6; }
inline String_t** get_address_of_path_6() { return &___path_6; }
inline void set_path_6(String_t* value)
{
___path_6 = value;
Il2CppCodeGenWriteBarrier((&___path_6), value);
}
inline static int32_t get_offset_of_query_7() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___query_7)); }
inline String_t* get_query_7() const { return ___query_7; }
inline String_t** get_address_of_query_7() { return &___query_7; }
inline void set_query_7(String_t* value)
{
___query_7 = value;
Il2CppCodeGenWriteBarrier((&___query_7), value);
}
inline static int32_t get_offset_of_fragment_8() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___fragment_8)); }
inline String_t* get_fragment_8() const { return ___fragment_8; }
inline String_t** get_address_of_fragment_8() { return &___fragment_8; }
inline void set_fragment_8(String_t* value)
{
___fragment_8 = value;
Il2CppCodeGenWriteBarrier((&___fragment_8), value);
}
inline static int32_t get_offset_of_userinfo_9() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___userinfo_9)); }
inline String_t* get_userinfo_9() const { return ___userinfo_9; }
inline String_t** get_address_of_userinfo_9() { return &___userinfo_9; }
inline void set_userinfo_9(String_t* value)
{
___userinfo_9 = value;
Il2CppCodeGenWriteBarrier((&___userinfo_9), value);
}
inline static int32_t get_offset_of_isUnc_10() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___isUnc_10)); }
inline bool get_isUnc_10() const { return ___isUnc_10; }
inline bool* get_address_of_isUnc_10() { return &___isUnc_10; }
inline void set_isUnc_10(bool value)
{
___isUnc_10 = value;
}
inline static int32_t get_offset_of_isOpaquePart_11() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___isOpaquePart_11)); }
inline bool get_isOpaquePart_11() const { return ___isOpaquePart_11; }
inline bool* get_address_of_isOpaquePart_11() { return &___isOpaquePart_11; }
inline void set_isOpaquePart_11(bool value)
{
___isOpaquePart_11 = value;
}
inline static int32_t get_offset_of_isAbsoluteUri_12() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___isAbsoluteUri_12)); }
inline bool get_isAbsoluteUri_12() const { return ___isAbsoluteUri_12; }
inline bool* get_address_of_isAbsoluteUri_12() { return &___isAbsoluteUri_12; }
inline void set_isAbsoluteUri_12(bool value)
{
___isAbsoluteUri_12 = value;
}
inline static int32_t get_offset_of_segments_13() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___segments_13)); }
inline StringU5BU5D_t1281789340* get_segments_13() const { return ___segments_13; }
inline StringU5BU5D_t1281789340** get_address_of_segments_13() { return &___segments_13; }
inline void set_segments_13(StringU5BU5D_t1281789340* value)
{
___segments_13 = value;
Il2CppCodeGenWriteBarrier((&___segments_13), value);
}
inline static int32_t get_offset_of_userEscaped_14() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___userEscaped_14)); }
inline bool get_userEscaped_14() const { return ___userEscaped_14; }
inline bool* get_address_of_userEscaped_14() { return &___userEscaped_14; }
inline void set_userEscaped_14(bool value)
{
___userEscaped_14 = value;
}
inline static int32_t get_offset_of_cachedAbsoluteUri_15() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___cachedAbsoluteUri_15)); }
inline String_t* get_cachedAbsoluteUri_15() const { return ___cachedAbsoluteUri_15; }
inline String_t** get_address_of_cachedAbsoluteUri_15() { return &___cachedAbsoluteUri_15; }
inline void set_cachedAbsoluteUri_15(String_t* value)
{
___cachedAbsoluteUri_15 = value;
Il2CppCodeGenWriteBarrier((&___cachedAbsoluteUri_15), value);
}
inline static int32_t get_offset_of_cachedToString_16() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___cachedToString_16)); }
inline String_t* get_cachedToString_16() const { return ___cachedToString_16; }
inline String_t** get_address_of_cachedToString_16() { return &___cachedToString_16; }
inline void set_cachedToString_16(String_t* value)
{
___cachedToString_16 = value;
Il2CppCodeGenWriteBarrier((&___cachedToString_16), value);
}
inline static int32_t get_offset_of_cachedLocalPath_17() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___cachedLocalPath_17)); }
inline String_t* get_cachedLocalPath_17() const { return ___cachedLocalPath_17; }
inline String_t** get_address_of_cachedLocalPath_17() { return &___cachedLocalPath_17; }
inline void set_cachedLocalPath_17(String_t* value)
{
___cachedLocalPath_17 = value;
Il2CppCodeGenWriteBarrier((&___cachedLocalPath_17), value);
}
inline static int32_t get_offset_of_cachedHashCode_18() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___cachedHashCode_18)); }
inline int32_t get_cachedHashCode_18() const { return ___cachedHashCode_18; }
inline int32_t* get_address_of_cachedHashCode_18() { return &___cachedHashCode_18; }
inline void set_cachedHashCode_18(int32_t value)
{
___cachedHashCode_18 = value;
}
inline static int32_t get_offset_of_parser_32() { return static_cast<int32_t>(offsetof(Uri_t100236324, ___parser_32)); }
inline UriParser_t3890150400 * get_parser_32() const { return ___parser_32; }
inline UriParser_t3890150400 ** get_address_of_parser_32() { return &___parser_32; }
inline void set_parser_32(UriParser_t3890150400 * value)
{
___parser_32 = value;
Il2CppCodeGenWriteBarrier((&___parser_32), value);
}
};
struct Uri_t100236324_StaticFields
{
public:
// System.String System.Uri::hexUpperChars
String_t* ___hexUpperChars_19;
// System.String System.Uri::SchemeDelimiter
String_t* ___SchemeDelimiter_20;
// System.String System.Uri::UriSchemeFile
String_t* ___UriSchemeFile_21;
// System.String System.Uri::UriSchemeFtp
String_t* ___UriSchemeFtp_22;
// System.String System.Uri::UriSchemeGopher
String_t* ___UriSchemeGopher_23;
// System.String System.Uri::UriSchemeHttp
String_t* ___UriSchemeHttp_24;
// System.String System.Uri::UriSchemeHttps
String_t* ___UriSchemeHttps_25;
// System.String System.Uri::UriSchemeMailto
String_t* ___UriSchemeMailto_26;
// System.String System.Uri::UriSchemeNews
String_t* ___UriSchemeNews_27;
// System.String System.Uri::UriSchemeNntp
String_t* ___UriSchemeNntp_28;
// System.String System.Uri::UriSchemeNetPipe
String_t* ___UriSchemeNetPipe_29;
// System.String System.Uri::UriSchemeNetTcp
String_t* ___UriSchemeNetTcp_30;
// System.Uri/UriScheme[] System.Uri::schemes
UriSchemeU5BU5D_t2082808316* ___schemes_31;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Uri::<>f__switch$map12
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map12_33;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Uri::<>f__switch$map13
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map13_34;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Uri::<>f__switch$map14
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map14_35;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Uri::<>f__switch$map15
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map15_36;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Uri::<>f__switch$map16
Dictionary_2_t2736202052 * ___U3CU3Ef__switchU24map16_37;
public:
inline static int32_t get_offset_of_hexUpperChars_19() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___hexUpperChars_19)); }
inline String_t* get_hexUpperChars_19() const { return ___hexUpperChars_19; }
inline String_t** get_address_of_hexUpperChars_19() { return &___hexUpperChars_19; }
inline void set_hexUpperChars_19(String_t* value)
{
___hexUpperChars_19 = value;
Il2CppCodeGenWriteBarrier((&___hexUpperChars_19), value);
}
inline static int32_t get_offset_of_SchemeDelimiter_20() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___SchemeDelimiter_20)); }
inline String_t* get_SchemeDelimiter_20() const { return ___SchemeDelimiter_20; }
inline String_t** get_address_of_SchemeDelimiter_20() { return &___SchemeDelimiter_20; }
inline void set_SchemeDelimiter_20(String_t* value)
{
___SchemeDelimiter_20 = value;
Il2CppCodeGenWriteBarrier((&___SchemeDelimiter_20), value);
}
inline static int32_t get_offset_of_UriSchemeFile_21() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeFile_21)); }
inline String_t* get_UriSchemeFile_21() const { return ___UriSchemeFile_21; }
inline String_t** get_address_of_UriSchemeFile_21() { return &___UriSchemeFile_21; }
inline void set_UriSchemeFile_21(String_t* value)
{
___UriSchemeFile_21 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeFile_21), value);
}
inline static int32_t get_offset_of_UriSchemeFtp_22() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeFtp_22)); }
inline String_t* get_UriSchemeFtp_22() const { return ___UriSchemeFtp_22; }
inline String_t** get_address_of_UriSchemeFtp_22() { return &___UriSchemeFtp_22; }
inline void set_UriSchemeFtp_22(String_t* value)
{
___UriSchemeFtp_22 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeFtp_22), value);
}
inline static int32_t get_offset_of_UriSchemeGopher_23() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeGopher_23)); }
inline String_t* get_UriSchemeGopher_23() const { return ___UriSchemeGopher_23; }
inline String_t** get_address_of_UriSchemeGopher_23() { return &___UriSchemeGopher_23; }
inline void set_UriSchemeGopher_23(String_t* value)
{
___UriSchemeGopher_23 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeGopher_23), value);
}
inline static int32_t get_offset_of_UriSchemeHttp_24() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeHttp_24)); }
inline String_t* get_UriSchemeHttp_24() const { return ___UriSchemeHttp_24; }
inline String_t** get_address_of_UriSchemeHttp_24() { return &___UriSchemeHttp_24; }
inline void set_UriSchemeHttp_24(String_t* value)
{
___UriSchemeHttp_24 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeHttp_24), value);
}
inline static int32_t get_offset_of_UriSchemeHttps_25() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeHttps_25)); }
inline String_t* get_UriSchemeHttps_25() const { return ___UriSchemeHttps_25; }
inline String_t** get_address_of_UriSchemeHttps_25() { return &___UriSchemeHttps_25; }
inline void set_UriSchemeHttps_25(String_t* value)
{
___UriSchemeHttps_25 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeHttps_25), value);
}
inline static int32_t get_offset_of_UriSchemeMailto_26() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeMailto_26)); }
inline String_t* get_UriSchemeMailto_26() const { return ___UriSchemeMailto_26; }
inline String_t** get_address_of_UriSchemeMailto_26() { return &___UriSchemeMailto_26; }
inline void set_UriSchemeMailto_26(String_t* value)
{
___UriSchemeMailto_26 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeMailto_26), value);
}
inline static int32_t get_offset_of_UriSchemeNews_27() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeNews_27)); }
inline String_t* get_UriSchemeNews_27() const { return ___UriSchemeNews_27; }
inline String_t** get_address_of_UriSchemeNews_27() { return &___UriSchemeNews_27; }
inline void set_UriSchemeNews_27(String_t* value)
{
___UriSchemeNews_27 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeNews_27), value);
}
inline static int32_t get_offset_of_UriSchemeNntp_28() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeNntp_28)); }
inline String_t* get_UriSchemeNntp_28() const { return ___UriSchemeNntp_28; }
inline String_t** get_address_of_UriSchemeNntp_28() { return &___UriSchemeNntp_28; }
inline void set_UriSchemeNntp_28(String_t* value)
{
___UriSchemeNntp_28 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeNntp_28), value);
}
inline static int32_t get_offset_of_UriSchemeNetPipe_29() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeNetPipe_29)); }
inline String_t* get_UriSchemeNetPipe_29() const { return ___UriSchemeNetPipe_29; }
inline String_t** get_address_of_UriSchemeNetPipe_29() { return &___UriSchemeNetPipe_29; }
inline void set_UriSchemeNetPipe_29(String_t* value)
{
___UriSchemeNetPipe_29 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeNetPipe_29), value);
}
inline static int32_t get_offset_of_UriSchemeNetTcp_30() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___UriSchemeNetTcp_30)); }
inline String_t* get_UriSchemeNetTcp_30() const { return ___UriSchemeNetTcp_30; }
inline String_t** get_address_of_UriSchemeNetTcp_30() { return &___UriSchemeNetTcp_30; }
inline void set_UriSchemeNetTcp_30(String_t* value)
{
___UriSchemeNetTcp_30 = value;
Il2CppCodeGenWriteBarrier((&___UriSchemeNetTcp_30), value);
}
inline static int32_t get_offset_of_schemes_31() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___schemes_31)); }
inline UriSchemeU5BU5D_t2082808316* get_schemes_31() const { return ___schemes_31; }
inline UriSchemeU5BU5D_t2082808316** get_address_of_schemes_31() { return &___schemes_31; }
inline void set_schemes_31(UriSchemeU5BU5D_t2082808316* value)
{
___schemes_31 = value;
Il2CppCodeGenWriteBarrier((&___schemes_31), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map12_33() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___U3CU3Ef__switchU24map12_33)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map12_33() const { return ___U3CU3Ef__switchU24map12_33; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map12_33() { return &___U3CU3Ef__switchU24map12_33; }
inline void set_U3CU3Ef__switchU24map12_33(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map12_33 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map12_33), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map13_34() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___U3CU3Ef__switchU24map13_34)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map13_34() const { return ___U3CU3Ef__switchU24map13_34; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map13_34() { return &___U3CU3Ef__switchU24map13_34; }
inline void set_U3CU3Ef__switchU24map13_34(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map13_34 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map13_34), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map14_35() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___U3CU3Ef__switchU24map14_35)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map14_35() const { return ___U3CU3Ef__switchU24map14_35; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map14_35() { return &___U3CU3Ef__switchU24map14_35; }
inline void set_U3CU3Ef__switchU24map14_35(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map14_35 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map14_35), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map15_36() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___U3CU3Ef__switchU24map15_36)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map15_36() const { return ___U3CU3Ef__switchU24map15_36; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map15_36() { return &___U3CU3Ef__switchU24map15_36; }
inline void set_U3CU3Ef__switchU24map15_36(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map15_36 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map15_36), value);
}
inline static int32_t get_offset_of_U3CU3Ef__switchU24map16_37() { return static_cast<int32_t>(offsetof(Uri_t100236324_StaticFields, ___U3CU3Ef__switchU24map16_37)); }
inline Dictionary_2_t2736202052 * get_U3CU3Ef__switchU24map16_37() const { return ___U3CU3Ef__switchU24map16_37; }
inline Dictionary_2_t2736202052 ** get_address_of_U3CU3Ef__switchU24map16_37() { return &___U3CU3Ef__switchU24map16_37; }
inline void set_U3CU3Ef__switchU24map16_37(Dictionary_2_t2736202052 * value)
{
___U3CU3Ef__switchU24map16_37 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map16_37), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URI_T100236324_H
#ifndef URIPARSER_T3890150400_H
#define URIPARSER_T3890150400_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UriParser
struct UriParser_t3890150400 : public RuntimeObject
{
public:
// System.String System.UriParser::scheme_name
String_t* ___scheme_name_2;
// System.Int32 System.UriParser::default_port
int32_t ___default_port_3;
public:
inline static int32_t get_offset_of_scheme_name_2() { return static_cast<int32_t>(offsetof(UriParser_t3890150400, ___scheme_name_2)); }
inline String_t* get_scheme_name_2() const { return ___scheme_name_2; }
inline String_t** get_address_of_scheme_name_2() { return &___scheme_name_2; }
inline void set_scheme_name_2(String_t* value)
{
___scheme_name_2 = value;
Il2CppCodeGenWriteBarrier((&___scheme_name_2), value);
}
inline static int32_t get_offset_of_default_port_3() { return static_cast<int32_t>(offsetof(UriParser_t3890150400, ___default_port_3)); }
inline int32_t get_default_port_3() const { return ___default_port_3; }
inline int32_t* get_address_of_default_port_3() { return &___default_port_3; }
inline void set_default_port_3(int32_t value)
{
___default_port_3 = value;
}
};
struct UriParser_t3890150400_StaticFields
{
public:
// System.Object System.UriParser::lock_object
RuntimeObject * ___lock_object_0;
// System.Collections.Hashtable System.UriParser::table
Hashtable_t1853889766 * ___table_1;
// System.Text.RegularExpressions.Regex System.UriParser::uri_regex
Regex_t3657309853 * ___uri_regex_4;
// System.Text.RegularExpressions.Regex System.UriParser::auth_regex
Regex_t3657309853 * ___auth_regex_5;
public:
inline static int32_t get_offset_of_lock_object_0() { return static_cast<int32_t>(offsetof(UriParser_t3890150400_StaticFields, ___lock_object_0)); }
inline RuntimeObject * get_lock_object_0() const { return ___lock_object_0; }
inline RuntimeObject ** get_address_of_lock_object_0() { return &___lock_object_0; }
inline void set_lock_object_0(RuntimeObject * value)
{
___lock_object_0 = value;
Il2CppCodeGenWriteBarrier((&___lock_object_0), value);
}
inline static int32_t get_offset_of_table_1() { return static_cast<int32_t>(offsetof(UriParser_t3890150400_StaticFields, ___table_1)); }
inline Hashtable_t1853889766 * get_table_1() const { return ___table_1; }
inline Hashtable_t1853889766 ** get_address_of_table_1() { return &___table_1; }
inline void set_table_1(Hashtable_t1853889766 * value)
{
___table_1 = value;
Il2CppCodeGenWriteBarrier((&___table_1), value);
}
inline static int32_t get_offset_of_uri_regex_4() { return static_cast<int32_t>(offsetof(UriParser_t3890150400_StaticFields, ___uri_regex_4)); }
inline Regex_t3657309853 * get_uri_regex_4() const { return ___uri_regex_4; }
inline Regex_t3657309853 ** get_address_of_uri_regex_4() { return &___uri_regex_4; }
inline void set_uri_regex_4(Regex_t3657309853 * value)
{
___uri_regex_4 = value;
Il2CppCodeGenWriteBarrier((&___uri_regex_4), value);
}
inline static int32_t get_offset_of_auth_regex_5() { return static_cast<int32_t>(offsetof(UriParser_t3890150400_StaticFields, ___auth_regex_5)); }
inline Regex_t3657309853 * get_auth_regex_5() const { return ___auth_regex_5; }
inline Regex_t3657309853 ** get_address_of_auth_regex_5() { return &___auth_regex_5; }
inline void set_auth_regex_5(Regex_t3657309853 * value)
{
___auth_regex_5 = value;
Il2CppCodeGenWriteBarrier((&___auth_regex_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URIPARSER_T3890150400_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef BOOLEAN_T97287965_H
#define BOOLEAN_T97287965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t97287965
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_2)); }
inline bool get_m_value_2() const { return ___m_value_2; }
inline bool* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(bool value)
{
___m_value_2 = value;
}
};
struct Boolean_t97287965_StaticFields
{
public:
// System.String System.Boolean::FalseString
String_t* ___FalseString_0;
// System.String System.Boolean::TrueString
String_t* ___TrueString_1;
public:
inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); }
inline String_t* get_FalseString_0() const { return ___FalseString_0; }
inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; }
inline void set_FalseString_0(String_t* value)
{
___FalseString_0 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_0), value);
}
inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); }
inline String_t* get_TrueString_1() const { return ___TrueString_1; }
inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; }
inline void set_TrueString_1(String_t* value)
{
___TrueString_1 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T97287965_H
#ifndef DEFAULTURIPARSER_T95882050_H
#define DEFAULTURIPARSER_T95882050_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.DefaultUriParser
struct DefaultUriParser_t95882050 : public UriParser_t3890150400
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFAULTURIPARSER_T95882050_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::split_char
CharU5BU5D_t3528271667* ___split_char_0;
public:
inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); }
inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; }
inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; }
inline void set_split_char_0(CharU5BU5D_t3528271667* value)
{
___split_char_0 = value;
Il2CppCodeGenWriteBarrier((&___split_char_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef GENERICURIPARSER_T1141496137_H
#define GENERICURIPARSER_T1141496137_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.GenericUriParser
struct GenericUriParser_t1141496137 : public UriParser_t3890150400
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERICURIPARSER_T1141496137_H
#ifndef INT32_T2950945753_H
#define INT32_T2950945753_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t2950945753
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); }
inline int32_t get_m_value_2() const { return ___m_value_2; }
inline int32_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(int32_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T2950945753_H
#ifndef SYSTEMEXCEPTION_T176217640_H
#define SYSTEMEXCEPTION_T176217640_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.SystemException
struct SystemException_t176217640 : public Exception_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYSTEMEXCEPTION_T176217640_H
#ifndef URISCHEME_T722425697_H
#define URISCHEME_T722425697_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Uri/UriScheme
struct UriScheme_t722425697
{
public:
// System.String System.Uri/UriScheme::scheme
String_t* ___scheme_0;
// System.String System.Uri/UriScheme::delimiter
String_t* ___delimiter_1;
// System.Int32 System.Uri/UriScheme::defaultPort
int32_t ___defaultPort_2;
public:
inline static int32_t get_offset_of_scheme_0() { return static_cast<int32_t>(offsetof(UriScheme_t722425697, ___scheme_0)); }
inline String_t* get_scheme_0() const { return ___scheme_0; }
inline String_t** get_address_of_scheme_0() { return &___scheme_0; }
inline void set_scheme_0(String_t* value)
{
___scheme_0 = value;
Il2CppCodeGenWriteBarrier((&___scheme_0), value);
}
inline static int32_t get_offset_of_delimiter_1() { return static_cast<int32_t>(offsetof(UriScheme_t722425697, ___delimiter_1)); }
inline String_t* get_delimiter_1() const { return ___delimiter_1; }
inline String_t** get_address_of_delimiter_1() { return &___delimiter_1; }
inline void set_delimiter_1(String_t* value)
{
___delimiter_1 = value;
Il2CppCodeGenWriteBarrier((&___delimiter_1), value);
}
inline static int32_t get_offset_of_defaultPort_2() { return static_cast<int32_t>(offsetof(UriScheme_t722425697, ___defaultPort_2)); }
inline int32_t get_defaultPort_2() const { return ___defaultPort_2; }
inline int32_t* get_address_of_defaultPort_2() { return &___defaultPort_2; }
inline void set_defaultPort_2(int32_t value)
{
___defaultPort_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Uri/UriScheme
struct UriScheme_t722425697_marshaled_pinvoke
{
char* ___scheme_0;
char* ___delimiter_1;
int32_t ___defaultPort_2;
};
// Native definition for COM marshalling of System.Uri/UriScheme
struct UriScheme_t722425697_marshaled_com
{
Il2CppChar* ___scheme_0;
Il2CppChar* ___delimiter_1;
int32_t ___defaultPort_2;
};
#endif // URISCHEME_T722425697_H
#ifndef URITYPECONVERTER_T3695916615_H
#define URITYPECONVERTER_T3695916615_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UriTypeConverter
struct UriTypeConverter_t3695916615 : public TypeConverter_t2249118273
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URITYPECONVERTER_T3695916615_H
#ifndef VOID_T1185182177_H
#define VOID_T1185182177_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1185182177
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1185182177_H
#ifndef FORMATEXCEPTION_T154580423_H
#define FORMATEXCEPTION_T154580423_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.FormatException
struct FormatException_t154580423 : public SystemException_t176217640
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // FORMATEXCEPTION_T154580423_H
#ifndef STREAMINGCONTEXTSTATES_T3580100459_H
#define STREAMINGCONTEXTSTATES_T3580100459_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.Serialization.StreamingContextStates
struct StreamingContextStates_t3580100459
{
public:
// System.Int32 System.Runtime.Serialization.StreamingContextStates::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(StreamingContextStates_t3580100459, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STREAMINGCONTEXTSTATES_T3580100459_H
#ifndef REGEXOPTIONS_T92845595_H
#define REGEXOPTIONS_T92845595_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Text.RegularExpressions.RegexOptions
struct RegexOptions_t92845595
{
public:
// System.Int32 System.Text.RegularExpressions.RegexOptions::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(RegexOptions_t92845595, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REGEXOPTIONS_T92845595_H
#ifndef URIHOSTNAMETYPE_T881866241_H
#define URIHOSTNAMETYPE_T881866241_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UriHostNameType
struct UriHostNameType_t881866241
{
public:
// System.Int32 System.UriHostNameType::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UriHostNameType_t881866241, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URIHOSTNAMETYPE_T881866241_H
#ifndef URIKIND_T3816567336_H
#define URIKIND_T3816567336_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UriKind
struct UriKind_t3816567336
{
public:
// System.Int32 System.UriKind::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UriKind_t3816567336, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URIKIND_T3816567336_H
#ifndef URIPARTIAL_T1736313903_H
#define URIPARTIAL_T1736313903_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UriPartial
struct UriPartial_t1736313903
{
public:
// System.Int32 System.UriPartial::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UriPartial_t1736313903, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URIPARTIAL_T1736313903_H
#ifndef STREAMINGCONTEXT_T3711869237_H
#define STREAMINGCONTEXT_T3711869237_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.Serialization.StreamingContext
struct StreamingContext_t3711869237
{
public:
// System.Runtime.Serialization.StreamingContextStates System.Runtime.Serialization.StreamingContext::state
int32_t ___state_0;
// System.Object System.Runtime.Serialization.StreamingContext::additional
RuntimeObject * ___additional_1;
public:
inline static int32_t get_offset_of_state_0() { return static_cast<int32_t>(offsetof(StreamingContext_t3711869237, ___state_0)); }
inline int32_t get_state_0() const { return ___state_0; }
inline int32_t* get_address_of_state_0() { return &___state_0; }
inline void set_state_0(int32_t value)
{
___state_0 = value;
}
inline static int32_t get_offset_of_additional_1() { return static_cast<int32_t>(offsetof(StreamingContext_t3711869237, ___additional_1)); }
inline RuntimeObject * get_additional_1() const { return ___additional_1; }
inline RuntimeObject ** get_address_of_additional_1() { return &___additional_1; }
inline void set_additional_1(RuntimeObject * value)
{
___additional_1 = value;
Il2CppCodeGenWriteBarrier((&___additional_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Runtime.Serialization.StreamingContext
struct StreamingContext_t3711869237_marshaled_pinvoke
{
int32_t ___state_0;
Il2CppIUnknown* ___additional_1;
};
// Native definition for COM marshalling of System.Runtime.Serialization.StreamingContext
struct StreamingContext_t3711869237_marshaled_com
{
int32_t ___state_0;
Il2CppIUnknown* ___additional_1;
};
#endif // STREAMINGCONTEXT_T3711869237_H
#ifndef REGEX_T3657309853_H
#define REGEX_T3657309853_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Text.RegularExpressions.Regex
struct Regex_t3657309853 : public RuntimeObject
{
public:
// System.Text.RegularExpressions.IMachineFactory System.Text.RegularExpressions.Regex::machineFactory
RuntimeObject* ___machineFactory_1;
// System.Collections.IDictionary System.Text.RegularExpressions.Regex::mapping
RuntimeObject* ___mapping_2;
// System.Int32 System.Text.RegularExpressions.Regex::group_count
int32_t ___group_count_3;
// System.Int32 System.Text.RegularExpressions.Regex::gap
int32_t ___gap_4;
// System.Boolean System.Text.RegularExpressions.Regex::refsInitialized
bool ___refsInitialized_5;
// System.String[] System.Text.RegularExpressions.Regex::group_names
StringU5BU5D_t1281789340* ___group_names_6;
// System.Int32[] System.Text.RegularExpressions.Regex::group_numbers
Int32U5BU5D_t385246372* ___group_numbers_7;
// System.String System.Text.RegularExpressions.Regex::pattern
String_t* ___pattern_8;
// System.Text.RegularExpressions.RegexOptions System.Text.RegularExpressions.Regex::roptions
int32_t ___roptions_9;
// System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Text.RegularExpressions.Regex::capnames
Dictionary_2_t2736202052 * ___capnames_10;
// System.Collections.Generic.Dictionary`2<System.Int32,System.Int32> System.Text.RegularExpressions.Regex::caps
Dictionary_2_t1839659084 * ___caps_11;
// System.Int32 System.Text.RegularExpressions.Regex::capsize
int32_t ___capsize_12;
// System.String[] System.Text.RegularExpressions.Regex::capslist
StringU5BU5D_t1281789340* ___capslist_13;
public:
inline static int32_t get_offset_of_machineFactory_1() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___machineFactory_1)); }
inline RuntimeObject* get_machineFactory_1() const { return ___machineFactory_1; }
inline RuntimeObject** get_address_of_machineFactory_1() { return &___machineFactory_1; }
inline void set_machineFactory_1(RuntimeObject* value)
{
___machineFactory_1 = value;
Il2CppCodeGenWriteBarrier((&___machineFactory_1), value);
}
inline static int32_t get_offset_of_mapping_2() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___mapping_2)); }
inline RuntimeObject* get_mapping_2() const { return ___mapping_2; }
inline RuntimeObject** get_address_of_mapping_2() { return &___mapping_2; }
inline void set_mapping_2(RuntimeObject* value)
{
___mapping_2 = value;
Il2CppCodeGenWriteBarrier((&___mapping_2), value);
}
inline static int32_t get_offset_of_group_count_3() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___group_count_3)); }
inline int32_t get_group_count_3() const { return ___group_count_3; }
inline int32_t* get_address_of_group_count_3() { return &___group_count_3; }
inline void set_group_count_3(int32_t value)
{
___group_count_3 = value;
}
inline static int32_t get_offset_of_gap_4() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___gap_4)); }
inline int32_t get_gap_4() const { return ___gap_4; }
inline int32_t* get_address_of_gap_4() { return &___gap_4; }
inline void set_gap_4(int32_t value)
{
___gap_4 = value;
}
inline static int32_t get_offset_of_refsInitialized_5() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___refsInitialized_5)); }
inline bool get_refsInitialized_5() const { return ___refsInitialized_5; }
inline bool* get_address_of_refsInitialized_5() { return &___refsInitialized_5; }
inline void set_refsInitialized_5(bool value)
{
___refsInitialized_5 = value;
}
inline static int32_t get_offset_of_group_names_6() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___group_names_6)); }
inline StringU5BU5D_t1281789340* get_group_names_6() const { return ___group_names_6; }
inline StringU5BU5D_t1281789340** get_address_of_group_names_6() { return &___group_names_6; }
inline void set_group_names_6(StringU5BU5D_t1281789340* value)
{
___group_names_6 = value;
Il2CppCodeGenWriteBarrier((&___group_names_6), value);
}
inline static int32_t get_offset_of_group_numbers_7() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___group_numbers_7)); }
inline Int32U5BU5D_t385246372* get_group_numbers_7() const { return ___group_numbers_7; }
inline Int32U5BU5D_t385246372** get_address_of_group_numbers_7() { return &___group_numbers_7; }
inline void set_group_numbers_7(Int32U5BU5D_t385246372* value)
{
___group_numbers_7 = value;
Il2CppCodeGenWriteBarrier((&___group_numbers_7), value);
}
inline static int32_t get_offset_of_pattern_8() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___pattern_8)); }
inline String_t* get_pattern_8() const { return ___pattern_8; }
inline String_t** get_address_of_pattern_8() { return &___pattern_8; }
inline void set_pattern_8(String_t* value)
{
___pattern_8 = value;
Il2CppCodeGenWriteBarrier((&___pattern_8), value);
}
inline static int32_t get_offset_of_roptions_9() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___roptions_9)); }
inline int32_t get_roptions_9() const { return ___roptions_9; }
inline int32_t* get_address_of_roptions_9() { return &___roptions_9; }
inline void set_roptions_9(int32_t value)
{
___roptions_9 = value;
}
inline static int32_t get_offset_of_capnames_10() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___capnames_10)); }
inline Dictionary_2_t2736202052 * get_capnames_10() const { return ___capnames_10; }
inline Dictionary_2_t2736202052 ** get_address_of_capnames_10() { return &___capnames_10; }
inline void set_capnames_10(Dictionary_2_t2736202052 * value)
{
___capnames_10 = value;
Il2CppCodeGenWriteBarrier((&___capnames_10), value);
}
inline static int32_t get_offset_of_caps_11() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___caps_11)); }
inline Dictionary_2_t1839659084 * get_caps_11() const { return ___caps_11; }
inline Dictionary_2_t1839659084 ** get_address_of_caps_11() { return &___caps_11; }
inline void set_caps_11(Dictionary_2_t1839659084 * value)
{
___caps_11 = value;
Il2CppCodeGenWriteBarrier((&___caps_11), value);
}
inline static int32_t get_offset_of_capsize_12() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___capsize_12)); }
inline int32_t get_capsize_12() const { return ___capsize_12; }
inline int32_t* get_address_of_capsize_12() { return &___capsize_12; }
inline void set_capsize_12(int32_t value)
{
___capsize_12 = value;
}
inline static int32_t get_offset_of_capslist_13() { return static_cast<int32_t>(offsetof(Regex_t3657309853, ___capslist_13)); }
inline StringU5BU5D_t1281789340* get_capslist_13() const { return ___capslist_13; }
inline StringU5BU5D_t1281789340** get_address_of_capslist_13() { return &___capslist_13; }
inline void set_capslist_13(StringU5BU5D_t1281789340* value)
{
___capslist_13 = value;
Il2CppCodeGenWriteBarrier((&___capslist_13), value);
}
};
struct Regex_t3657309853_StaticFields
{
public:
// System.Text.RegularExpressions.FactoryCache System.Text.RegularExpressions.Regex::cache
FactoryCache_t2327118887 * ___cache_0;
public:
inline static int32_t get_offset_of_cache_0() { return static_cast<int32_t>(offsetof(Regex_t3657309853_StaticFields, ___cache_0)); }
inline FactoryCache_t2327118887 * get_cache_0() const { return ___cache_0; }
inline FactoryCache_t2327118887 ** get_address_of_cache_0() { return &___cache_0; }
inline void set_cache_0(FactoryCache_t2327118887 * value)
{
___cache_0 = value;
Il2CppCodeGenWriteBarrier((&___cache_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REGEX_T3657309853_H
#ifndef URIFORMATEXCEPTION_T953270471_H
#define URIFORMATEXCEPTION_T953270471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UriFormatException
struct UriFormatException_t953270471 : public FormatException_t154580423
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // URIFORMATEXCEPTION_T953270471_H
// System.Void System.Uri/UriScheme::.ctor(System.String,System.String,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriScheme__ctor_m1399779782 (UriScheme_t722425697 * __this, String_t* ___s0, String_t* ___d1, int32_t ___p2, const RuntimeMethod* method);
// System.String Locale::GetText(System.String)
extern "C" IL2CPP_METHOD_ATTR String_t* Locale_GetText_m3875126938 (RuntimeObject * __this /* static, unused */, String_t* ___msg0, const RuntimeMethod* method);
// System.Void System.FormatException::.ctor(System.String)
extern "C" IL2CPP_METHOD_ATTR void FormatException__ctor_m4049685996 (FormatException_t154580423 * __this, String_t* p0, const RuntimeMethod* method);
// System.Void System.FormatException::.ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
extern "C" IL2CPP_METHOD_ATTR void FormatException__ctor_m3747066592 (FormatException_t154580423 * __this, SerializationInfo_t950877179 * p0, StreamingContext_t3711869237 p1, const RuntimeMethod* method);
// System.Void System.Exception::GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
extern "C" IL2CPP_METHOD_ATTR void Exception_GetObjectData_m1103241326 (Exception_t * __this, SerializationInfo_t950877179 * p0, StreamingContext_t3711869237 p1, const RuntimeMethod* method);
// System.Void System.Object::.ctor()
extern "C" IL2CPP_METHOD_ATTR void Object__ctor_m297566312 (RuntimeObject * __this, const RuntimeMethod* method);
// System.Void System.Text.RegularExpressions.Regex::.ctor(System.String)
extern "C" IL2CPP_METHOD_ATTR void Regex__ctor_m897876424 (Regex_t3657309853 * __this, String_t* ___pattern0, const RuntimeMethod* method);
// System.String System.Uri::get_Scheme()
extern "C" IL2CPP_METHOD_ATTR String_t* Uri_get_Scheme_m2109479391 (Uri_t100236324 * __this, const RuntimeMethod* method);
// System.Boolean System.String::op_Inequality(System.String,System.String)
extern "C" IL2CPP_METHOD_ATTR bool String_op_Inequality_m215368492 (RuntimeObject * __this /* static, unused */, String_t* p0, String_t* p1, const RuntimeMethod* method);
// System.Void System.UriFormatException::.ctor(System.String)
extern "C" IL2CPP_METHOD_ATTR void UriFormatException__ctor_m3083316541 (UriFormatException_t953270471 * __this, String_t* ___message0, const RuntimeMethod* method);
// System.Void System.Collections.Hashtable::.ctor()
extern "C" IL2CPP_METHOD_ATTR void Hashtable__ctor_m1815022027 (Hashtable_t1853889766 * __this, const RuntimeMethod* method);
// System.Void System.DefaultUriParser::.ctor()
extern "C" IL2CPP_METHOD_ATTR void DefaultUriParser__ctor_m2377995797 (DefaultUriParser_t95882050 * __this, const RuntimeMethod* method);
// System.Void System.UriParser::InternalRegister(System.Collections.Hashtable,System.UriParser,System.String,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriParser_InternalRegister_m3643767086 (RuntimeObject * __this /* static, unused */, Hashtable_t1853889766 * ___table0, UriParser_t3890150400 * ___uriParser1, String_t* ___schemeName2, int32_t ___defaultPort3, const RuntimeMethod* method);
// System.Void System.Threading.Monitor::Enter(System.Object)
extern "C" IL2CPP_METHOD_ATTR void Monitor_Enter_m2249409497 (RuntimeObject * __this /* static, unused */, RuntimeObject * p0, const RuntimeMethod* method);
// System.Void System.Threading.Monitor::Exit(System.Object)
extern "C" IL2CPP_METHOD_ATTR void Monitor_Exit_m3585316909 (RuntimeObject * __this /* static, unused */, RuntimeObject * p0, const RuntimeMethod* method);
// System.Void System.UriParser::set_SchemeName(System.String)
extern "C" IL2CPP_METHOD_ATTR void UriParser_set_SchemeName_m266448765 (UriParser_t3890150400 * __this, String_t* ___value0, const RuntimeMethod* method);
// System.Void System.UriParser::set_DefaultPort(System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriParser_set_DefaultPort_m4007715058 (UriParser_t3890150400 * __this, int32_t ___value0, const RuntimeMethod* method);
// System.Void System.UriParser::CreateDefaults()
extern "C" IL2CPP_METHOD_ATTR void UriParser_CreateDefaults_m404296154 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method);
// System.Globalization.CultureInfo System.Globalization.CultureInfo::get_InvariantCulture()
extern "C" IL2CPP_METHOD_ATTR CultureInfo_t4157843068 * CultureInfo_get_InvariantCulture_m3532445182 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method);
// System.String System.String::ToLower(System.Globalization.CultureInfo)
extern "C" IL2CPP_METHOD_ATTR String_t* String_ToLower_m3490221821 (String_t* __this, CultureInfo_t4157843068 * p0, const RuntimeMethod* method);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Conversion methods for marshalling of: System.Uri/UriScheme
extern "C" void UriScheme_t722425697_marshal_pinvoke(const UriScheme_t722425697& unmarshaled, UriScheme_t722425697_marshaled_pinvoke& marshaled)
{
marshaled.___scheme_0 = il2cpp_codegen_marshal_string(unmarshaled.get_scheme_0());
marshaled.___delimiter_1 = il2cpp_codegen_marshal_string(unmarshaled.get_delimiter_1());
marshaled.___defaultPort_2 = unmarshaled.get_defaultPort_2();
}
extern "C" void UriScheme_t722425697_marshal_pinvoke_back(const UriScheme_t722425697_marshaled_pinvoke& marshaled, UriScheme_t722425697& unmarshaled)
{
unmarshaled.set_scheme_0(il2cpp_codegen_marshal_string_result(marshaled.___scheme_0));
unmarshaled.set_delimiter_1(il2cpp_codegen_marshal_string_result(marshaled.___delimiter_1));
int32_t unmarshaled_defaultPort_temp_2 = 0;
unmarshaled_defaultPort_temp_2 = marshaled.___defaultPort_2;
unmarshaled.set_defaultPort_2(unmarshaled_defaultPort_temp_2);
}
// Conversion method for clean up from marshalling of: System.Uri/UriScheme
extern "C" void UriScheme_t722425697_marshal_pinvoke_cleanup(UriScheme_t722425697_marshaled_pinvoke& marshaled)
{
il2cpp_codegen_marshal_free(marshaled.___scheme_0);
marshaled.___scheme_0 = NULL;
il2cpp_codegen_marshal_free(marshaled.___delimiter_1);
marshaled.___delimiter_1 = NULL;
}
// Conversion methods for marshalling of: System.Uri/UriScheme
extern "C" void UriScheme_t722425697_marshal_com(const UriScheme_t722425697& unmarshaled, UriScheme_t722425697_marshaled_com& marshaled)
{
marshaled.___scheme_0 = il2cpp_codegen_marshal_bstring(unmarshaled.get_scheme_0());
marshaled.___delimiter_1 = il2cpp_codegen_marshal_bstring(unmarshaled.get_delimiter_1());
marshaled.___defaultPort_2 = unmarshaled.get_defaultPort_2();
}
extern "C" void UriScheme_t722425697_marshal_com_back(const UriScheme_t722425697_marshaled_com& marshaled, UriScheme_t722425697& unmarshaled)
{
unmarshaled.set_scheme_0(il2cpp_codegen_marshal_bstring_result(marshaled.___scheme_0));
unmarshaled.set_delimiter_1(il2cpp_codegen_marshal_bstring_result(marshaled.___delimiter_1));
int32_t unmarshaled_defaultPort_temp_2 = 0;
unmarshaled_defaultPort_temp_2 = marshaled.___defaultPort_2;
unmarshaled.set_defaultPort_2(unmarshaled_defaultPort_temp_2);
}
// Conversion method for clean up from marshalling of: System.Uri/UriScheme
extern "C" void UriScheme_t722425697_marshal_com_cleanup(UriScheme_t722425697_marshaled_com& marshaled)
{
il2cpp_codegen_marshal_free_bstring(marshaled.___scheme_0);
marshaled.___scheme_0 = NULL;
il2cpp_codegen_marshal_free_bstring(marshaled.___delimiter_1);
marshaled.___delimiter_1 = NULL;
}
// System.Void System.Uri/UriScheme::.ctor(System.String,System.String,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriScheme__ctor_m1399779782 (UriScheme_t722425697 * __this, String_t* ___s0, String_t* ___d1, int32_t ___p2, const RuntimeMethod* method)
{
{
String_t* L_0 = ___s0;
__this->set_scheme_0(L_0);
String_t* L_1 = ___d1;
__this->set_delimiter_1(L_1);
int32_t L_2 = ___p2;
__this->set_defaultPort_2(L_2);
return;
}
}
extern "C" void UriScheme__ctor_m1399779782_AdjustorThunk (RuntimeObject * __this, String_t* ___s0, String_t* ___d1, int32_t ___p2, const RuntimeMethod* method)
{
UriScheme_t722425697 * _thisAdjusted = reinterpret_cast<UriScheme_t722425697 *>(__this + 1);
UriScheme__ctor_m1399779782(_thisAdjusted, ___s0, ___d1, ___p2, method);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void System.UriFormatException::.ctor()
extern "C" IL2CPP_METHOD_ATTR void UriFormatException__ctor_m1115096473 (UriFormatException_t953270471 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (UriFormatException__ctor_m1115096473_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
String_t* L_0 = Locale_GetText_m3875126938(NULL /*static, unused*/, _stringLiteral2864059369, /*hidden argument*/NULL);
FormatException__ctor_m4049685996(__this, L_0, /*hidden argument*/NULL);
return;
}
}
// System.Void System.UriFormatException::.ctor(System.String)
extern "C" IL2CPP_METHOD_ATTR void UriFormatException__ctor_m3083316541 (UriFormatException_t953270471 * __this, String_t* ___message0, const RuntimeMethod* method)
{
{
String_t* L_0 = ___message0;
FormatException__ctor_m4049685996(__this, L_0, /*hidden argument*/NULL);
return;
}
}
// System.Void System.UriFormatException::.ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
extern "C" IL2CPP_METHOD_ATTR void UriFormatException__ctor_m3466512970 (UriFormatException_t953270471 * __this, SerializationInfo_t950877179 * ___info0, StreamingContext_t3711869237 ___context1, const RuntimeMethod* method)
{
{
SerializationInfo_t950877179 * L_0 = ___info0;
StreamingContext_t3711869237 L_1 = ___context1;
FormatException__ctor_m3747066592(__this, L_0, L_1, /*hidden argument*/NULL);
return;
}
}
// System.Void System.UriFormatException::System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
extern "C" IL2CPP_METHOD_ATTR void UriFormatException_System_Runtime_Serialization_ISerializable_GetObjectData_m3030326401 (UriFormatException_t953270471 * __this, SerializationInfo_t950877179 * ___info0, StreamingContext_t3711869237 ___context1, const RuntimeMethod* method)
{
{
SerializationInfo_t950877179 * L_0 = ___info0;
StreamingContext_t3711869237 L_1 = ___context1;
Exception_GetObjectData_m1103241326(__this, L_0, L_1, /*hidden argument*/NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void System.UriParser::.ctor()
extern "C" IL2CPP_METHOD_ATTR void UriParser__ctor_m2454688443 (UriParser_t3890150400 * __this, const RuntimeMethod* method)
{
{
Object__ctor_m297566312(__this, /*hidden argument*/NULL);
return;
}
}
// System.Void System.UriParser::.cctor()
extern "C" IL2CPP_METHOD_ATTR void UriParser__cctor_m3655686731 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (UriParser__cctor_m3655686731_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
RuntimeObject * L_0 = (RuntimeObject *)il2cpp_codegen_object_new(RuntimeObject_il2cpp_TypeInfo_var);
Object__ctor_m297566312(L_0, /*hidden argument*/NULL);
((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->set_lock_object_0(L_0);
Regex_t3657309853 * L_1 = (Regex_t3657309853 *)il2cpp_codegen_object_new(Regex_t3657309853_il2cpp_TypeInfo_var);
Regex__ctor_m897876424(L_1, _stringLiteral528199797, /*hidden argument*/NULL);
((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->set_uri_regex_4(L_1);
Regex_t3657309853 * L_2 = (Regex_t3657309853 *)il2cpp_codegen_object_new(Regex_t3657309853_il2cpp_TypeInfo_var);
Regex__ctor_m897876424(L_2, _stringLiteral3698381084, /*hidden argument*/NULL);
((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->set_auth_regex_5(L_2);
return;
}
}
// System.Void System.UriParser::InitializeAndValidate(System.Uri,System.UriFormatException&)
extern "C" IL2CPP_METHOD_ATTR void UriParser_InitializeAndValidate_m2008117311 (UriParser_t3890150400 * __this, Uri_t100236324 * ___uri0, UriFormatException_t953270471 ** ___parsingError1, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (UriParser_InitializeAndValidate_m2008117311_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
Uri_t100236324 * L_0 = ___uri0;
NullCheck(L_0);
String_t* L_1 = Uri_get_Scheme_m2109479391(L_0, /*hidden argument*/NULL);
String_t* L_2 = __this->get_scheme_name_2();
IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var);
bool L_3 = String_op_Inequality_m215368492(NULL /*static, unused*/, L_1, L_2, /*hidden argument*/NULL);
if (!L_3)
{
goto IL_003c;
}
}
{
String_t* L_4 = __this->get_scheme_name_2();
IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var);
bool L_5 = String_op_Inequality_m215368492(NULL /*static, unused*/, L_4, _stringLiteral3452614534, /*hidden argument*/NULL);
if (!L_5)
{
goto IL_003c;
}
}
{
UriFormatException_t953270471 ** L_6 = ___parsingError1;
UriFormatException_t953270471 * L_7 = (UriFormatException_t953270471 *)il2cpp_codegen_object_new(UriFormatException_t953270471_il2cpp_TypeInfo_var);
UriFormatException__ctor_m3083316541(L_7, _stringLiteral2140524769, /*hidden argument*/NULL);
*((RuntimeObject **)(L_6)) = (RuntimeObject *)L_7;
Il2CppCodeGenWriteBarrier((RuntimeObject **)(L_6), (RuntimeObject *)L_7);
goto IL_003f;
}
IL_003c:
{
UriFormatException_t953270471 ** L_8 = ___parsingError1;
*((RuntimeObject **)(L_8)) = (RuntimeObject *)NULL;
Il2CppCodeGenWriteBarrier((RuntimeObject **)(L_8), (RuntimeObject *)NULL);
}
IL_003f:
{
return;
}
}
// System.Void System.UriParser::OnRegister(System.String,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriParser_OnRegister_m3283921560 (UriParser_t3890150400 * __this, String_t* ___schemeName0, int32_t ___defaultPort1, const RuntimeMethod* method)
{
{
return;
}
}
// System.Void System.UriParser::set_SchemeName(System.String)
extern "C" IL2CPP_METHOD_ATTR void UriParser_set_SchemeName_m266448765 (UriParser_t3890150400 * __this, String_t* ___value0, const RuntimeMethod* method)
{
{
String_t* L_0 = ___value0;
__this->set_scheme_name_2(L_0);
return;
}
}
// System.Int32 System.UriParser::get_DefaultPort()
extern "C" IL2CPP_METHOD_ATTR int32_t UriParser_get_DefaultPort_m2544851211 (UriParser_t3890150400 * __this, const RuntimeMethod* method)
{
{
int32_t L_0 = __this->get_default_port_3();
return L_0;
}
}
// System.Void System.UriParser::set_DefaultPort(System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriParser_set_DefaultPort_m4007715058 (UriParser_t3890150400 * __this, int32_t ___value0, const RuntimeMethod* method)
{
{
int32_t L_0 = ___value0;
__this->set_default_port_3(L_0);
return;
}
}
// System.Void System.UriParser::CreateDefaults()
extern "C" IL2CPP_METHOD_ATTR void UriParser_CreateDefaults_m404296154 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (UriParser_CreateDefaults_m404296154_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
Hashtable_t1853889766 * V_0 = NULL;
RuntimeObject * V_1 = NULL;
Exception_t * __last_unhandled_exception = 0;
NO_UNUSED_WARNING (__last_unhandled_exception);
Exception_t * __exception_local = 0;
NO_UNUSED_WARNING (__exception_local);
int32_t __leave_target = -1;
NO_UNUSED_WARNING (__leave_target);
{
IL2CPP_RUNTIME_CLASS_INIT(UriParser_t3890150400_il2cpp_TypeInfo_var);
Hashtable_t1853889766 * L_0 = ((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->get_table_1();
if (!L_0)
{
goto IL_000b;
}
}
{
return;
}
IL_000b:
{
Hashtable_t1853889766 * L_1 = (Hashtable_t1853889766 *)il2cpp_codegen_object_new(Hashtable_t1853889766_il2cpp_TypeInfo_var);
Hashtable__ctor_m1815022027(L_1, /*hidden argument*/NULL);
V_0 = L_1;
Hashtable_t1853889766 * L_2 = V_0;
DefaultUriParser_t95882050 * L_3 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_3, /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(Uri_t100236324_il2cpp_TypeInfo_var);
String_t* L_4 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeFile_21();
IL2CPP_RUNTIME_CLASS_INIT(UriParser_t3890150400_il2cpp_TypeInfo_var);
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_2, L_3, L_4, (-1), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_5 = V_0;
DefaultUriParser_t95882050 * L_6 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_6, /*hidden argument*/NULL);
String_t* L_7 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeFtp_22();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_5, L_6, L_7, ((int32_t)21), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_8 = V_0;
DefaultUriParser_t95882050 * L_9 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_9, /*hidden argument*/NULL);
String_t* L_10 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeGopher_23();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_8, L_9, L_10, ((int32_t)70), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_11 = V_0;
DefaultUriParser_t95882050 * L_12 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_12, /*hidden argument*/NULL);
String_t* L_13 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeHttp_24();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_11, L_12, L_13, ((int32_t)80), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_14 = V_0;
DefaultUriParser_t95882050 * L_15 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_15, /*hidden argument*/NULL);
String_t* L_16 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeHttps_25();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_14, L_15, L_16, ((int32_t)443), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_17 = V_0;
DefaultUriParser_t95882050 * L_18 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_18, /*hidden argument*/NULL);
String_t* L_19 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeMailto_26();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_17, L_18, L_19, ((int32_t)25), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_20 = V_0;
DefaultUriParser_t95882050 * L_21 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_21, /*hidden argument*/NULL);
String_t* L_22 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeNetPipe_29();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_20, L_21, L_22, (-1), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_23 = V_0;
DefaultUriParser_t95882050 * L_24 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_24, /*hidden argument*/NULL);
String_t* L_25 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeNetTcp_30();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_23, L_24, L_25, (-1), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_26 = V_0;
DefaultUriParser_t95882050 * L_27 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_27, /*hidden argument*/NULL);
String_t* L_28 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeNews_27();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_26, L_27, L_28, ((int32_t)119), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_29 = V_0;
DefaultUriParser_t95882050 * L_30 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_30, /*hidden argument*/NULL);
String_t* L_31 = ((Uri_t100236324_StaticFields*)il2cpp_codegen_static_fields_for(Uri_t100236324_il2cpp_TypeInfo_var))->get_UriSchemeNntp_28();
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_29, L_30, L_31, ((int32_t)119), /*hidden argument*/NULL);
Hashtable_t1853889766 * L_32 = V_0;
DefaultUriParser_t95882050 * L_33 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_33, /*hidden argument*/NULL);
UriParser_InternalRegister_m3643767086(NULL /*static, unused*/, L_32, L_33, _stringLiteral4255182569, ((int32_t)389), /*hidden argument*/NULL);
RuntimeObject * L_34 = ((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->get_lock_object_0();
V_1 = L_34;
RuntimeObject * L_35 = V_1;
Monitor_Enter_m2249409497(NULL /*static, unused*/, L_35, /*hidden argument*/NULL);
}
IL_00e6:
try
{ // begin try (depth: 1)
{
IL2CPP_RUNTIME_CLASS_INIT(UriParser_t3890150400_il2cpp_TypeInfo_var);
Hashtable_t1853889766 * L_36 = ((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->get_table_1();
if (L_36)
{
goto IL_00fb;
}
}
IL_00f0:
{
Hashtable_t1853889766 * L_37 = V_0;
IL2CPP_RUNTIME_CLASS_INIT(UriParser_t3890150400_il2cpp_TypeInfo_var);
((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->set_table_1(L_37);
goto IL_00fd;
}
IL_00fb:
{
V_0 = (Hashtable_t1853889766 *)NULL;
}
IL_00fd:
{
IL2CPP_LEAVE(0x109, FINALLY_0102);
}
} // end try (depth: 1)
catch(Il2CppExceptionWrapper& e)
{
__last_unhandled_exception = (Exception_t *)e.ex;
goto FINALLY_0102;
}
FINALLY_0102:
{ // begin finally (depth: 1)
RuntimeObject * L_38 = V_1;
Monitor_Exit_m3585316909(NULL /*static, unused*/, L_38, /*hidden argument*/NULL);
IL2CPP_END_FINALLY(258)
} // end finally (depth: 1)
IL2CPP_CLEANUP(258)
{
IL2CPP_JUMP_TBL(0x109, IL_0109)
IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *)
}
IL_0109:
{
return;
}
}
// System.Void System.UriParser::InternalRegister(System.Collections.Hashtable,System.UriParser,System.String,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void UriParser_InternalRegister_m3643767086 (RuntimeObject * __this /* static, unused */, Hashtable_t1853889766 * ___table0, UriParser_t3890150400 * ___uriParser1, String_t* ___schemeName2, int32_t ___defaultPort3, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (UriParser_InternalRegister_m3643767086_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
DefaultUriParser_t95882050 * V_0 = NULL;
{
UriParser_t3890150400 * L_0 = ___uriParser1;
String_t* L_1 = ___schemeName2;
NullCheck(L_0);
UriParser_set_SchemeName_m266448765(L_0, L_1, /*hidden argument*/NULL);
UriParser_t3890150400 * L_2 = ___uriParser1;
int32_t L_3 = ___defaultPort3;
NullCheck(L_2);
UriParser_set_DefaultPort_m4007715058(L_2, L_3, /*hidden argument*/NULL);
UriParser_t3890150400 * L_4 = ___uriParser1;
if (!((GenericUriParser_t1141496137 *)IsInstClass((RuntimeObject*)L_4, GenericUriParser_t1141496137_il2cpp_TypeInfo_var)))
{
goto IL_0026;
}
}
{
Hashtable_t1853889766 * L_5 = ___table0;
String_t* L_6 = ___schemeName2;
UriParser_t3890150400 * L_7 = ___uriParser1;
NullCheck(L_5);
VirtActionInvoker2< RuntimeObject *, RuntimeObject * >::Invoke(25 /* System.Void System.Collections.Hashtable::Add(System.Object,System.Object) */, L_5, L_6, L_7);
goto IL_0042;
}
IL_0026:
{
DefaultUriParser_t95882050 * L_8 = (DefaultUriParser_t95882050 *)il2cpp_codegen_object_new(DefaultUriParser_t95882050_il2cpp_TypeInfo_var);
DefaultUriParser__ctor_m2377995797(L_8, /*hidden argument*/NULL);
V_0 = L_8;
DefaultUriParser_t95882050 * L_9 = V_0;
String_t* L_10 = ___schemeName2;
NullCheck(L_9);
UriParser_set_SchemeName_m266448765(L_9, L_10, /*hidden argument*/NULL);
DefaultUriParser_t95882050 * L_11 = V_0;
int32_t L_12 = ___defaultPort3;
NullCheck(L_11);
UriParser_set_DefaultPort_m4007715058(L_11, L_12, /*hidden argument*/NULL);
Hashtable_t1853889766 * L_13 = ___table0;
String_t* L_14 = ___schemeName2;
DefaultUriParser_t95882050 * L_15 = V_0;
NullCheck(L_13);
VirtActionInvoker2< RuntimeObject *, RuntimeObject * >::Invoke(25 /* System.Void System.Collections.Hashtable::Add(System.Object,System.Object) */, L_13, L_14, L_15);
}
IL_0042:
{
UriParser_t3890150400 * L_16 = ___uriParser1;
String_t* L_17 = ___schemeName2;
int32_t L_18 = ___defaultPort3;
NullCheck(L_16);
VirtActionInvoker2< String_t*, int32_t >::Invoke(5 /* System.Void System.UriParser::OnRegister(System.String,System.Int32) */, L_16, L_17, L_18);
return;
}
}
// System.UriParser System.UriParser::GetParser(System.String)
extern "C" IL2CPP_METHOD_ATTR UriParser_t3890150400 * UriParser_GetParser_m544052729 (RuntimeObject * __this /* static, unused */, String_t* ___schemeName0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (UriParser_GetParser_m544052729_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
String_t* V_0 = NULL;
{
String_t* L_0 = ___schemeName0;
if (L_0)
{
goto IL_0008;
}
}
{
return (UriParser_t3890150400 *)NULL;
}
IL_0008:
{
IL2CPP_RUNTIME_CLASS_INIT(UriParser_t3890150400_il2cpp_TypeInfo_var);
UriParser_CreateDefaults_m404296154(NULL /*static, unused*/, /*hidden argument*/NULL);
String_t* L_1 = ___schemeName0;
IL2CPP_RUNTIME_CLASS_INIT(CultureInfo_t4157843068_il2cpp_TypeInfo_var);
CultureInfo_t4157843068 * L_2 = CultureInfo_get_InvariantCulture_m3532445182(NULL /*static, unused*/, /*hidden argument*/NULL);
NullCheck(L_1);
String_t* L_3 = String_ToLower_m3490221821(L_1, L_2, /*hidden argument*/NULL);
V_0 = L_3;
Hashtable_t1853889766 * L_4 = ((UriParser_t3890150400_StaticFields*)il2cpp_codegen_static_fields_for(UriParser_t3890150400_il2cpp_TypeInfo_var))->get_table_1();
String_t* L_5 = V_0;
NullCheck(L_4);
RuntimeObject * L_6 = VirtFuncInvoker1< RuntimeObject *, RuntimeObject * >::Invoke(22 /* System.Object System.Collections.Hashtable::get_Item(System.Object) */, L_4, L_5);
return ((UriParser_t3890150400 *)CastclassClass((RuntimeObject*)L_6, UriParser_t3890150400_il2cpp_TypeInfo_var));
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 42.601742 | 276 | 0.813817 | ShearerAWS |
b7cdd8fee874cc7a0fa0bd6c3cfee1eeeee26a58 | 414 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/tools/JiraService.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 1 | 2022-03-18T17:22:09.000Z | 2022-03-18T17:22:09.000Z | include/RED4ext/Scripting/Natives/Generated/tools/JiraService.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | null | null | null | include/RED4ext/Scripting/Natives/Generated/tools/JiraService.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 1 | 2022-02-13T01:44:55.000Z | 2022-02-13T01:44:55.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
namespace RED4ext
{
namespace tools {
struct JiraService
{
static constexpr const char* NAME = "toolsJiraService";
static constexpr const char* ALIAS = NAME;
uint8_t unk00[0xE8 - 0x0]; // 0
};
RED4EXT_ASSERT_SIZE(JiraService, 0xE8);
} // namespace tools
} // namespace RED4ext
| 19.714286 | 59 | 0.724638 | jackhumbert |
b7ce190ef178fda1e18a4ba7c521aa1f5c7484d6 | 7,947 | cpp | C++ | ModuleGOManager.cpp | N4bi/SahelanthropusEngine | e64c1e2a544b7f2c4e3bf50b027ef3914443ef55 | [
"MIT"
] | null | null | null | ModuleGOManager.cpp | N4bi/SahelanthropusEngine | e64c1e2a544b7f2c4e3bf50b027ef3914443ef55 | [
"MIT"
] | 1 | 2016-12-03T20:51:15.000Z | 2016-12-03T20:51:15.000Z | ModuleGOManager.cpp | N4bi/Sahelanthropus_Engine | e64c1e2a544b7f2c4e3bf50b027ef3914443ef55 | [
"MIT"
] | null | null | null | #include "Application.h"
#include "ModuleGOManager.h"
#include "GameObject.h"
#include "Component.h"
#include "ComponentTransform.h"
#include "Quadtree.h"
#include "Imgui\imgui.h"
#include <algorithm>
using namespace std;
ModuleGOManager::ModuleGOManager(Application * app, const char* name, bool start_enabled) : Module(app, name, start_enabled)
{
}
ModuleGOManager::~ModuleGOManager()
{
}
bool ModuleGOManager::Init(Json& config)
{
bool ret = true;
LOG("Init Game Object Manager");
root = new GameObject(nullptr, "root");
root->AddComponent(Component::TRANSFORM);
quad.Create(100.0f);
return ret;
}
bool ModuleGOManager::Start(float dt)
{
bool ret = true;
LOG("Start Game Object Manager");
return false;
}
update_status ModuleGOManager::PreUpdate(float dt)
{
//Delete game objects in the vector to delete
vector<GameObject*>::iterator it = to_delete.begin();
while (it != to_delete.end())
{
delete(*it);
++it;
}
to_delete.clear();
if (root)
{
DoPreUpdate(dt, root);
}
return UPDATE_CONTINUE;
}
update_status ModuleGOManager::Update(float dt)
{
if (root)
{
UpdateChilds(dt, root);
}
HierarchyInfo();
EditorWindow();
if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_DOWN)
{
LineSegment raycast = App->editor->main_camera_component->CastRay();
game_object_on_editor = SelectGameObject(raycast, CollectHits(raycast));
}
quad.Render();
return UPDATE_CONTINUE;
}
bool ModuleGOManager::CleanUp()
{
bool ret = true;
delete root;
game_object_on_editor = nullptr;
root = nullptr;
return ret;
}
GameObject* ModuleGOManager::CreateGameObject(GameObject* parent, const char* name)
{
GameObject* ret = new GameObject(parent, name);
if (parent == nullptr)
{
parent = root;
}
parent->childs.push_back(ret);
return ret;
}
void ModuleGOManager::DeleteGameObject(GameObject * go)
{
if (go != nullptr)
{
if (go->GetParent() != nullptr)
{
go->GetParent()->DeleteChilds(go);
}
go->DeleteAllChildren();
to_delete.push_back(go);
}
}
void ModuleGOManager::HierarchyInfo()
{
ImGui::Begin("Hierarchy");
ShowGameObjectsOnEditor(root->GetChilds());
ImGui::End();
}
void ModuleGOManager::ShowGameObjectsOnEditor(const vector<GameObject*>* childs)
{
vector<GameObject*>::const_iterator it = (*childs).begin();
while (it != (*childs).end())
{
uint flags = 0;
if ((*it) == game_object_on_editor)
{
flags = ImGuiTreeNodeFlags_Selected;
}
if ((*it)->childs.size() > 0)
{
if (ImGui::TreeNodeEx((*it)->name_object.data(), ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_DefaultOpen))
{
if (ImGui::IsItemClicked())
{
game_object_on_editor = (*it);
}
ShowGameObjectsOnEditor((*it)->GetChilds());
ImGui::TreePop();
}
}
else
{
if (ImGui::TreeNodeEx((*it)->name_object.data(), flags | ImGuiTreeNodeFlags_Leaf))
{
if (ImGui::IsItemClicked())
{
game_object_on_editor = (*it);
}
ImGui::TreePop();
}
}
++it;
}
}
void ModuleGOManager::EditorWindow()
{
ImGui::Begin("Editor");
if (game_object_on_editor)
{
bool is_enabled = game_object_on_editor->isEnabled();
if (ImGui::Checkbox(game_object_on_editor->name_object._Myptr(),&is_enabled))
{
if (is_enabled)
{
game_object_on_editor->Enable();
}
else
{
game_object_on_editor->Disable();
}
}
ImGui::SameLine();
bool wire_enabled = App->renderer3D->wireframe;
if (ImGui::Checkbox("Wireframe", &wire_enabled))
{
if (wire_enabled)
{
App->renderer3D->wireframe = true;
}
else
{
App->renderer3D->wireframe = false;
}
}
ImGui::SameLine();
ImGui::TextColored(IMGUI_GREEN,"ID object: ");
ImGui::SameLine();
ImGui::Text("%d", game_object_on_editor->GetID());
const vector<Component*>* components = game_object_on_editor->GetComponents();
for (vector<Component*>::const_iterator component = (*components).begin(); component != (*components).end(); ++component)
{
(*component)->ShowOnEditor();
}
}
ImGui::End();
}
int CheckDistance(const GameObject* go1, const GameObject* go2)
{
if (go1->distance_hit.Length() < go2->distance_hit.Length())
{
return 0;
}
}
GameObject * ModuleGOManager::SelectGameObject(const LineSegment & ray, const vector<GameObject*> hits)
{
GameObject* game_object_picked = nullptr;
float distance = App->editor->main_camera_component->frustum.farPlaneDistance;
vector<GameObject*>::const_iterator it = hits.begin();
while (it != hits.end())
{
if ((*it)->CheckHits(ray,distance))
{
game_object_picked = (*it);
}
++it;
}
return game_object_picked;
}
vector<GameObject*> ModuleGOManager::CollectHits(const LineSegment & ray) const
{
vector<GameObject*> objects_hit;
root->CollectRayHits(root, ray, objects_hit);
sort(objects_hit.begin(), objects_hit.end(), CheckDistance);
return objects_hit;
}
void ModuleGOManager::SaveGameObjectsOnScene(const char* name_file) const
{
Json data;
data.AddArray("Game Objects");
root->Save(data);
char* buff;
size_t size = data.Save(&buff);
App->fs->Save(name_file, buff, size);
delete[] buff;
}
GameObject * ModuleGOManager::LoadGameObjectsOnScene(Json & game_objects)
{
const char* name = game_objects.GetString("Name");
int id = game_objects.GetInt("ID Game Object");
int parent_id = game_objects.GetInt("ID Parent");
bool enabled = game_objects.GetBool("enabled");
//Search the parent of the game object
GameObject* parent = nullptr;
if (parent_id != 0 && root != nullptr)
{
parent = SearchGameObjectsByID(root, parent_id);
}
//Create the childs
GameObject* child = new GameObject(parent, name, id, enabled);
if (parent != nullptr)
{
parent->childs.push_back(child);
}
//Attach the components
Json component_data;
int component_array_size = game_objects.GetArraySize("Components");
for (uint i = 0; i < component_array_size; i++)
{
component_data = game_objects.GetArray("Components", i);
int type = component_data.GetInt("type");
Component* cmp_go = child->AddComponent((Component::Types)(type));
cmp_go->ToLoad(component_data);
}
return child;
}
GameObject * ModuleGOManager::SearchGameObjectsByID(GameObject * first_go, int id) const
{
GameObject* ret = nullptr;
if (first_go != nullptr)
{
if (first_go->id == id)
{
ret = first_go;
}
else
{
const std::vector<GameObject*>* game_objects = first_go->GetChilds();
vector<GameObject*>::const_iterator it = game_objects->begin();
while (it != game_objects->end())
{
ret = SearchGameObjectsByID((*it), id);
if (ret != nullptr)
{
break;
}
++it;
}
}
}
return ret;
}
void ModuleGOManager::InsertObjects()
{
if (root->childs.empty() == false)
{
root->InsertNode();
}
}
void ModuleGOManager::LoadScene(const char * directory)
{
char* buff;
uint size = App->fs->Load(directory, &buff);
Json scene(buff);
Json root;
root = scene.GetArray("Game Objects",0);
uint scene_size = scene.GetArraySize("Game Objects");
for (uint i = 0; i < scene_size; i++)
{
//the first one will be the root node, always.
if (i == 0)
{
this->root = LoadGameObjectsOnScene(scene.GetArray("Game Objects", i));
}
else
{
LoadGameObjectsOnScene(scene.GetArray("Game Objects", i));
}
}
delete[] buff;
}
void ModuleGOManager::DeleteScene()
{
DeleteGameObject(root);
game_object_on_editor = nullptr;
root = nullptr;
}
GameObject* ModuleGOManager::GetRoot() const
{
return root;
}
void ModuleGOManager::DoPreUpdate(float dt ,GameObject * go)
{
if (root != go)
{
go->PreUpdate(dt);
}
vector<GameObject*>::const_iterator it = go->childs.begin();
while (it != go->childs.end())
{
DoPreUpdate(dt, (*it));
++it;
}
}
void ModuleGOManager::UpdateChilds(float dt, GameObject * go)
{
if (root != go)
{
go->Update(dt);
}
vector<GameObject*>::const_iterator it = go->childs.begin();
while (it != go->childs.end())
{
UpdateChilds(dt, (*it));
++it;
}
}
| 19.011962 | 124 | 0.677866 | N4bi |
b7d034b70bd04af5845d11e29335c958fb8b471f | 1,619 | cpp | C++ | app/src/main/cpp/lesson7/CubesWithVboWithStride.cpp | karaianas/AndroidOpenGLESLessonsCpp | 6a2f8c25ef8e36ebe9414e16ad9e1f6b5e95da3c | [
"Apache-2.0"
] | 3 | 2017-07-23T11:08:39.000Z | 2019-12-27T05:57:11.000Z | OpenGLLesson/app/src/main/cpp/lesson7/CubesWithVboWithStride.cpp | biezhihua/Android_OpenGL_Demo | aacecdc4665023fa8b7a685b42bfd33486a4099f | [
"Apache-2.0"
] | null | null | null | OpenGLLesson/app/src/main/cpp/lesson7/CubesWithVboWithStride.cpp | biezhihua/Android_OpenGL_Demo | aacecdc4665023fa8b7a685b42bfd33486a4099f | [
"Apache-2.0"
] | 2 | 2019-05-20T07:45:47.000Z | 2019-12-27T05:57:15.000Z | //
// Created by biezhihua on 2017/7/23.
//
#include "CubesWithVboWithStride.h"
void CubesWithVboWithStride::renderer() {
int stride = (POSITION_DATA_SIZE + NORMAL_DATA_SIZE + TEXTURE_COORDINATE_DATA_SIZE) *
BYTES_PER_FLOAT;
// Pass in the position information
glBindBuffer(GL_ARRAY_BUFFER, mCubeBufferIdx);
glEnableVertexAttribArray(mPositionHandle);
glVertexAttribPointer(mPositionHandle, POSITION_DATA_SIZE, GL_FLOAT, GL_FALSE, stride, 0);
// Pass in the normal information
glBindBuffer(GL_ARRAY_BUFFER, mCubeBufferIdx);
glEnableVertexAttribArray(mNormalHandle);
glVertexAttribPointer(mNormalHandle, NORMAL_DATA_SIZE, GL_FLOAT, GL_FALSE, stride,
(const GLvoid *) (POSITION_DATA_SIZE * BYTES_PER_FLOAT));
// Pass in the texture information
glBindBuffer(GL_ARRAY_BUFFER, mCubeBufferIdx);
glEnableVertexAttribArray(mTextureCoordinateHandle);
glVertexAttribPointer(mTextureCoordinateHandle, TEXTURE_COORDINATE_DATA_SIZE, GL_FLOAT,
GL_FALSE,
stride, (const GLvoid *) ((POSITION_DATA_SIZE + NORMAL_DATA_SIZE) *
BYTES_PER_FLOAT));
// Clear the currently bound buffer (so future OpenGL calls do not use this buffer).
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Draw the mCubes.
glDrawArrays(GL_TRIANGLES, 0, mActualCubeFactor * mActualCubeFactor * mActualCubeFactor * 36);
}
void CubesWithVboWithStride::release() {
GLuint buffersToDelete[] = {mCubeBufferIdx};
glDeleteBuffers(1, buffersToDelete);
}
| 39.487805 | 98 | 0.703521 | karaianas |
b7d0f2b6c1f9e4ab5607d5a7cba3237bc92f4d23 | 39,461 | cpp | C++ | Source/AllProjects/CIDBuild/CIDBuild_ProjectInfo.cpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | 1 | 2019-05-28T06:33:01.000Z | 2019-05-28T06:33:01.000Z | Source/AllProjects/CIDBuild/CIDBuild_ProjectInfo.cpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | Source/AllProjects/CIDBuild/CIDBuild_ProjectInfo.cpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | //
// FILE NAME: CIDBuild_ProjectInfo.Cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/21/1998
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the TProjectInfo class, which represents the
// platform independent settings for a single facility, plus some info
// that is collected and cached away during processing.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDBuild.hpp"
// ---------------------------------------------------------------------------
// CLASS: TProjFileCopy
// PREFIX: pfc
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TProjFileCopy: Constructors and Destructor
// ---------------------------------------------------------------------------
TProjFileCopy::TProjFileCopy(const TBldStr& strOutPath) :
m_strOutPath(strOutPath)
{
}
TProjFileCopy::~TProjFileCopy()
{
}
// ---------------------------------------------------------------------------
// TProjFileCopy: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TProjFileCopy::AddSrcFile(const TBldStr& strToAdd)
{
m_listSrcFiles.Add(new TBldStr(strToAdd));
}
const TList<TBldStr>& TProjFileCopy::listSrcFiles() const
{
return m_listSrcFiles;
}
tCIDLib::TVoid TProjFileCopy::RemoveAll()
{
m_listSrcFiles.RemoveAll();
}
const TBldStr& TProjFileCopy::strOutPath() const
{
return m_strOutPath;
}
TBldStr& TProjFileCopy::strOutPath(const TBldStr& strToSet)
{
m_strOutPath = strToSet;
return m_strOutPath;
}
// ---------------------------------------------------------------------------
// CLASS: TProjectInfo
// PREFIX: proj
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TProjectInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TProjectInfo::TProjectInfo(const TBldStr& strName) :
m_bIsSample(kCIDLib::False)
, m_bMsgFile(kCIDLib::False)
, m_bNeedsAdminPrivs(kCIDLib::False)
, m_bPlatformDir(kCIDLib::False)
, m_bPlatformInclude(kCIDLib::False)
, m_bResFile(kCIDLib::False)
, m_bUseSysLibs(kCIDLib::False)
, m_bVarArgs(kCIDLib::False)
, m_bVersioned(kCIDLib::False)
, m_eDisplayType(tCIDBuild::EDisplayTypes::Console)
, m_eRTLMode(tCIDBuild::ERTLModes::MultiDynamic)
, m_eType(tCIDBuild::EProjTypes::Executable)
, m_strProjectName(strName)
, m_c4Base(0)
, m_c4DepIndex(0xFFFFFFFF)
{
//
// !NOTE: We cannot initialize a lot of stuff yet because its not known
// until we parse out our content from the .Projects file.
//
}
TProjectInfo::~TProjectInfo()
{
}
// ---------------------------------------------------------------------------
// TProjectInfo: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TProjectInfo::AddToDepGraph(TDependGraph& depgTarget)
{
//
// Add ourself to the dependency graph object, and save away the
// index at which it added us.
//
m_c4DepIndex = depgTarget.c4AddNewElement(m_strProjectName);
}
tCIDLib::TBoolean TProjectInfo::bDefineExists(const TBldStr& strToFind) const
{
TList<TKeyValuePair>::TCursor cursDefs(&m_listDefs);
if (cursDefs.bResetIter())
{
do
{
if (cursDefs.tCurElement().strKey() == strToFind)
return kCIDLib::True;
} while (cursDefs.bNext());
}
return kCIDLib::False;
}
tCIDLib::TBoolean TProjectInfo::bHasIDLFiles() const
{
return !m_listIDLFiles.bEmpty();
}
tCIDLib::TBoolean TProjectInfo::bHasMsgFile() const
{
return m_bMsgFile;
}
tCIDLib::TBoolean TProjectInfo::bHasResFile() const
{
return m_bResFile;
}
tCIDLib::TBoolean TProjectInfo::bIsSample() const
{
return m_bIsSample;
}
tCIDLib::TBoolean TProjectInfo::bMakeOutDir() const
{
// If a group type, nothing to do
if (m_eType == tCIDBuild::EProjTypes::Group)
return kCIDLib::True;
// If not exists, try to create it and return that result
if (!TUtils::bExists(m_strOutDir))
return TUtils::bMakeDir(m_strOutDir);
// Else nothing to do so return true
return kCIDLib::True;
}
tCIDLib::TBoolean TProjectInfo::bNeedsAdminPrivs() const
{
return m_bNeedsAdminPrivs;
}
tCIDLib::TBoolean TProjectInfo::bPlatformDir() const
{
return m_bPlatformDir;
}
tCIDLib::TBoolean
TProjectInfo::bSupportsPlatform(const TBldStr& strToCheck) const
{
//
// If m_bPlatformInclude is true, we see if this project is in our list.
// Else we see if it not in our list.
//
tCIDLib::TBoolean bInList = kCIDLib::False;
TList<TBldStr>::TCursor cursPlatforms(&m_listPlatforms);
if (cursPlatforms.bResetIter())
{
do
{
if (cursPlatforms.tCurElement().bIEquals(strToCheck))
{
bInList = kCIDLib::True;
break;
}
} while (cursPlatforms.bNext());
}
//
// If the flags are equal, taht means that either in the list and we are in
// include mode, or not in the list and we are in ignore mode, so either is
// what we are looking for.
//
return (bInList == m_bPlatformInclude);
}
tCIDLib::TBoolean TProjectInfo::bUseSysLibs() const
{
return m_bUseSysLibs;
}
tCIDLib::TBoolean
TProjectInfo::bUsesExtLib(const TBldStr& strToCheck) const
{
// Search the external libs list for this one.
TList<TBldStr>::TCursor cursLibs(&m_listExtLibs);
if (!cursLibs.bResetIter())
return kCIDLib::True;
do
{
if (cursLibs.tCurElement() == strToCheck)
return kCIDLib::True;
} while (cursLibs.bNext());
return kCIDLib::False;
}
tCIDLib::TBoolean TProjectInfo::bVarArgs() const
{
return m_bVarArgs;
}
tCIDLib::TBoolean TProjectInfo::bVersioned() const
{
return m_bVersioned;
}
tCIDLib::TCard4 TProjectInfo::c4Base() const
{
return m_c4Base;
}
tCIDLib::TCard4 TProjectInfo::c4CppCount() const
{
return m_listCpps.c4ElemCount();
}
tCIDLib::TCard4 TProjectInfo::c4DefCount() const
{
return m_listDefs.c4ElemCount();
}
tCIDLib::TCard4 TProjectInfo::c4DepCount() const
{
return m_listDeps.c4ElemCount();
}
tCIDLib::TCard4 TProjectInfo::c4DepIndex() const
{
return m_c4DepIndex;
}
tCIDLib::TCard4 TProjectInfo::c4HppCount() const
{
return m_listDefs.c4ElemCount();
}
tCIDLib::TVoid TProjectInfo::DumpSettings() const
{
stdOut << L"\n----------------------------------------------\n"
<< L"Settings for project: " << m_strProjectName << L"\n"
<< L"----------------------------------------------\n"
<< L" Name: " << m_strProjectName << L"\n"
<< L" Project Type: " << m_eType << L"\n"
<< L" Directory: " << m_strDirectory << L"\n"
<< L" Base: " << m_c4Base << L"\n"
<< L" Message File: " << (m_bMsgFile ? L"Yes\n" : L"No\n")
<< L" Admin Privs: " << (m_bNeedsAdminPrivs ? L"Yes\n" : L"No\n")
<< L" Resource File: " << (m_bResFile ? L"Yes\n" : L"No\n")
<< L" Platform Dir: " << (m_bPlatformDir ? L"Yes\n" : L"No\n")
<< L" Use Sys Libs: " << (m_bUseSysLibs ? L"Yes\n" : L"No\n")
<< L" Var Args: " << (m_bVarArgs ? L"Yes\n" : L"No\n")
<< L" RTL Mode: " << m_eRTLMode << L"\n"
<< L" Sample: " << (m_bIsSample ? L"Yes\n" : L"No\n");
stdOut << L" Platforms: ";
TList<TBldStr>::TCursor cursPlatforms(&m_listPlatforms);
if (!cursPlatforms.bResetIter())
{
stdOut << L"All";
}
else
{
do
{
stdOut << cursPlatforms.tCurElement() << L" ";
} while (cursPlatforms.bNext());
}
stdOut << kCIDBuild::EndLn;
}
tCIDBuild::EDisplayTypes TProjectInfo::eDisplayType() const
{
return m_eDisplayType;
}
tCIDBuild::ERTLModes TProjectInfo::eRTLMode() const
{
return m_eRTLMode;
}
tCIDBuild::EProjTypes TProjectInfo::eType() const
{
return m_eType;
}
const TList<TFindInfo>& TProjectInfo::listCpps() const
{
return m_listCpps;
}
const TList<TBldStr>& TProjectInfo::listCustomCmds() const
{
return m_listCustomCmds;
}
const TList<TBldStr>& TProjectInfo::listDeps() const
{
return m_listDeps;
}
const TList<TBldStr>& TProjectInfo::listExtLibs() const
{
return m_listExtLibs;
}
const TList<TProjFileCopy>& TProjectInfo::listFileCopies() const
{
return m_listFileCopies;
}
const TList<TFindInfo>& TProjectInfo::listHpps() const
{
return m_listHpps;
}
const TList<TIDLInfo>& TProjectInfo::listIDLFiles() const
{
return m_listIDLFiles;
}
const TList<TBldStr>& TProjectInfo::listIncludePaths() const
{
return m_listIncludePaths;
}
tCIDLib::TVoid TProjectInfo::LoadFileLists()
{
// If a group type, nothing to do
if (m_eType == tCIDBuild::EProjTypes::Group)
return;
// Change to this project's directory
if (!TUtils::bChangeDir(m_strProjectDir))
{
stdOut << L"Could not change to project directory: "
<< m_strProjectDir << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::Internal;
}
// Load up all of the H
TBldStr strSearch(m_strProjectDir);
strSearch.Append(kCIDBuild::pszAllHFiles);
TFindInfo::c4FindFiles(strSearch, m_listHpps);
// And Hpp files
strSearch = m_strProjectDir;
strSearch.Append(kCIDBuild::pszAllHppFiles);
TFindInfo::c4FindFiles(strSearch, m_listHpps);
// Load up all of the C files
strSearch = m_strProjectDir;
strSearch.Append(kCIDBuild::pszAllCFiles);
TFindInfo::c4FindFiles(strSearch, m_listCpps);
// And the Cpp files
strSearch = m_strProjectDir;
strSearch.Append(kCIDBuild::pszAllCppFiles);
TFindInfo::c4FindFiles(strSearch, m_listCpps);
//
// But, if this project has a per-platform directory, then we have to
// also do those files, which means we have to append onto the stuff we
// already got.
//
// For the Cpp files we tell it to return the relative path component.
// Since we give it only "platdir\*.XXX", we will get back just what we
// want, which is a path relative to the project directory.
//
if (m_bPlatformDir)
{
strSearch = kCIDBuild::pszPlatformDir;
strSearch.Append(L"\\", kCIDBuild::pszAllHFiles);
TFindInfo::c4FindFiles(strSearch, m_listHpps, tCIDBuild::EPathModes::Relative);
strSearch = kCIDBuild::pszPlatformDir;
strSearch.Append(L"\\", kCIDBuild::pszAllHppFiles);
TFindInfo::c4FindFiles(strSearch, m_listHpps, tCIDBuild::EPathModes::Relative);
strSearch = kCIDBuild::pszPlatformDir;
strSearch.Append(L"\\", kCIDBuild::pszAllCFiles);
TFindInfo::c4FindFiles(strSearch, m_listCpps, tCIDBuild::EPathModes::Relative);
strSearch = kCIDBuild::pszPlatformDir;
strSearch.Append(L"\\", kCIDBuild::pszAllCppFiles);
TFindInfo::c4FindFiles(strSearch, m_listCpps, tCIDBuild::EPathModes::Relative);
}
}
// Used by per-platform tools drivers to check for
const TKeyValuePair*
TProjectInfo::pkvpFindPlatOpt(const TBldStr& strPlatform, const TBldStr& strOption) const
{
//
// Loop through the list of lists. The key of the first entry in each one is
// platform name.
//
TPlatOptList::TCursor cursPlatOpts(&m_listPlatOpts);
if (!cursPlatOpts.bResetIter())
return nullptr;
do
{
TKVPList::TCursor cursPlat(&cursPlatOpts.tCurElement());
if (cursPlat.bResetIter())
{
if (cursPlat->strKey().bIEquals(strPlatform))
{
//
// This is the right platform, so check it's entries, move past the first one
// before we start.
//
if (!cursPlat.bNext())
break;
do
{
if (cursPlat->strKey().bIEquals(strOption))
return &cursPlat.tCurElement();
} while (cursPlat.bNext());
}
}
} while (cursPlatOpts.bNext());
return nullptr;
}
// This is called to let us parse our contents out of the project definition file
tCIDLib::TVoid TProjectInfo::ParseContent(TLineSpooler& lsplSource)
{
//
// Ok, lets go into a line reading loop and pull out or information
// we find the major sections here and then pass them off to private
// methods to deal with the details.
//
tCIDLib::TBoolean bSeenPlats = kCIDLib::False;
tCIDLib::TBoolean bDone = kCIDLib::False;
TBldStr strReadBuf;
while (!bDone)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected SETTINGS, DEPENDENTS, DEFINES, or END PROJECT"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"SETTINGS")
{
ParseSettings(lsplSource);
}
else if (strReadBuf == L"DEPENDENTS")
{
ParseDependents(lsplSource);
}
else if (strReadBuf == L"DEFINES")
{
ParseDefines(lsplSource);
}
else if (strReadBuf == L"EXCLUDEPLATS")
{
if (bSeenPlats)
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Only one of include/exclude platforms can be used"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
bSeenPlats = kCIDLib::True;
m_bPlatformInclude = kCIDLib::False;
ParsePlatforms(lsplSource);
}
else if (strReadBuf == L"EXTLIBS")
{
ParseExtLibs(lsplSource);
}
else if (strReadBuf == L"IDLFILES")
{
ParseIDLFiles(lsplSource);
}
else if (strReadBuf == L"INCLUDEPATHS")
{
ParseIncludePaths(lsplSource);
}
else if (strReadBuf == L"INCLUDEPLATS")
{
if (bSeenPlats)
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Only one of include/exclude platforms can be used"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
m_bPlatformInclude = kCIDLib::True;
ParsePlatforms(lsplSource);
}
else if (strReadBuf == L"END PROJECT")
{
bDone = kCIDLib::True;
}
else if (strReadBuf.bStartsWith(L"CUSTOMCMDS"))
{
ParseCustCmds(lsplSource);
}
else if (strReadBuf.bStartsWith(L"FILECOPIES"))
{
//
// It's a file copy block. Is can be followed by the target
// path for this block of copies.
//
strReadBuf.Cut(10);
strReadBuf.StripWhitespace();
if (strReadBuf[0] == L'=')
{
strReadBuf.Cut(1);
strReadBuf.StripWhitespace();
}
ParseFileCopies(lsplSource, strReadBuf);
}
else if (strReadBuf == L"PLATFORMOPTS")
{
ParsePlatOpts(lsplSource);
}
else
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected SETTINGS, DEPENDENTS, EXTLIBS, DEFINES, or END PROJECT"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
}
// Only do this stuff if not a group
if (m_eType != tCIDBuild::EProjTypes::Group)
{
// Build up a path the project's output
m_strOutDir = facCIDBuild.strOutDir();
m_strOutDir.Append(m_strProjectName);
m_strOutDir.Append(L".Out");
m_strOutDir.Append(L"\\");
// Build the name to the error ids header, which goes to the include dir
m_strOutErrHpp = m_strProjectDir; // facCIDBuild.strIncludeDir();
m_strOutErrHpp.Append(m_strProjectName);
m_strOutErrHpp.Append(L"_ErrorIds.hpp");
// Build the name to the message ids header, which goes to the include dir
m_strOutMsgHpp = m_strProjectDir; // facCIDBuild.strIncludeDir();
m_strOutMsgHpp.Append(m_strProjectName);
m_strOutMsgHpp.Append(L"_MessageIds.hpp");
// Bulld the name to the message text source, if any
m_strMsgSrc = m_strProjectDir;
m_strMsgSrc.Append(m_strProjectName);
m_strMsgSrc.Append(L"_");
m_strMsgSrc.Append(facCIDBuild.strLangSuffix());
m_strMsgSrc.Append(L".MsgText");
// Bulld the name to the GUI resource source, if any
m_strResSrc = m_strProjectDir;
m_strResSrc.Append(m_strProjectName);
m_strResSrc.Append(L".CIDRC");
//
// Build up the output binary message file name. If this project is
// versioned, then append the version postfix. And its language specific
// so add the language suffix.
//
m_strOutMsgs = facCIDBuild.strOutDir();
m_strOutMsgs.Append(m_strProjectName);
if (m_bVersioned)
m_strOutMsgs.Append(facCIDBuild.strVersionSuffix());
m_strOutMsgs.Append(L"_");
m_strOutMsgs.Append(facCIDBuild.strLangSuffix());
m_strOutMsgs.Append(L".CIDMsg");
//
// And do the same for the resource file. Its version specific, but not
// language specific.
//
m_strOutRes = facCIDBuild.strOutDir();
m_strOutRes.Append(m_strProjectName);
if (m_bVersioned)
m_strOutRes.Append(facCIDBuild.strVersionSuffix());
m_strOutRes.Append(L".CIDRes");
// And the resource header file
m_strOutResHpp = m_strProjectDir; // facCIDBuild.strIncludeDir();
m_strOutResHpp.Append(m_strProjectName);
m_strOutResHpp.Append(L"_ResourceIds.hpp");
//
// Allow the per-platform code to build up the paths to the primary
// output file.
//
BuildOutputFileName();
}
}
const TBldStr& TProjectInfo::strDirectory() const
{
return m_strDirectory;
}
const TBldStr& TProjectInfo::strExportKeyword() const
{
return m_strExportKeyword;
}
const TBldStr& TProjectInfo::strMsgSrc() const
{
return m_strMsgSrc;
}
const TBldStr& TProjectInfo::strResSrc() const
{
return m_strResSrc;
}
const TBldStr& TProjectInfo::strOutDir() const
{
return m_strOutDir;
}
const TBldStr& TProjectInfo::strOutErrHpp() const
{
return m_strOutErrHpp;
}
const TBldStr& TProjectInfo::strOutMsgHpp() const
{
return m_strOutMsgHpp;
}
const TBldStr& TProjectInfo::strOutMsgs() const
{
return m_strOutMsgs;
}
const TBldStr& TProjectInfo::strOutBin() const
{
return m_strOutBin;
}
const TBldStr& TProjectInfo::strOutRes() const
{
return m_strOutRes;
}
const TBldStr& TProjectInfo::strOutResHpp() const
{
return m_strOutResHpp;
}
const TBldStr& TProjectInfo::strProjectName() const
{
return m_strProjectName;
}
const TBldStr& TProjectInfo::strProjectDir() const
{
return m_strProjectDir;
}
// ---------------------------------------------------------------------------
// TProjectInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TProjectInfo::bSetSetting(const TBldStr& strName, const TBldStr& strValue)
{
if (strName == L"BASE")
{
//
// This is a number so it must convert correctly. Its just a simple
// decimal value.
//
if (!TRawStr::bXlatCard4(strValue.pszBuffer(), m_c4Base, 10))
return kCIDLib::False;
}
else if (strName == L"DIRECTORY")
{
// Store the raw directory
m_strDirectory = strValue;
// Build up the path to the directory and store it.
m_strProjectDir = facCIDBuild.strRootDir();
m_strProjectDir.Append(L"Source", L"\\");
m_strProjectDir.Append(L"AllProjects", L"\\");
// If it's not empty (i.e. top level), then add it, and end with a slash
if (!m_strDirectory.bEmpty())
{
m_strProjectDir.Append(m_strDirectory);
m_strProjectDir.Append(L"\\");
}
}
else if (strName == L"DISPLAY")
{
if (strValue == L"N/A")
m_eDisplayType = tCIDBuild::EDisplayTypes::NotApplicable;
else if (strValue == L"Console")
m_eDisplayType = tCIDBuild::EDisplayTypes::Console;
else if (strValue == L"GUI")
m_eDisplayType = tCIDBuild::EDisplayTypes::GUI;
else
return kCIDLib::False;
}
else if (strName == L"EXPORT")
{
m_strExportKeyword = strValue;
}
else if (strName == L"MSGFILE")
{
if (strValue == L"No")
{
m_bMsgFile = kCIDLib::False;
}
else if (strValue == L"Yes")
{
m_bMsgFile = kCIDLib::True;
}
else
{
// It's not valid
return kCIDLib::False;
}
}
else if (strName == L"RESFILE")
{
if (strValue == L"No")
{
m_bResFile = kCIDLib::False;
}
else if (strValue == L"Yes")
{
m_bResFile = kCIDLib::True;
}
else
{
// It's not valid
return kCIDLib::False;
}
}
else if (strName == L"ADMINPRIVS")
{
if (!TRawStr::bXlatBoolean(strValue.pszBuffer(), m_bNeedsAdminPrivs))
return kCIDLib::False;
}
else if (strName == L"PLATFORMDIR")
{
if (!TRawStr::bXlatBoolean(strValue.pszBuffer(), m_bPlatformDir))
return kCIDLib::False;
}
else if (strName == L"RTL")
{
if (strValue == L"Single/Static")
m_eRTLMode = tCIDBuild::ERTLModes::SingleStatic;
else if (strValue == L"Single/Dynamic")
m_eRTLMode = tCIDBuild::ERTLModes::SingleStatic;
else if (strValue == L"Multi/Static")
m_eRTLMode = tCIDBuild::ERTLModes::MultiStatic;
else if (strValue == L"Multi/Dynamic")
m_eRTLMode = tCIDBuild::ERTLModes::MultiDynamic;
else
return kCIDLib::False;
}
else if (strName == L"TYPE")
{
if (strValue == L"SharedObj")
m_eType = tCIDBuild::EProjTypes::SharedObj;
else if (strValue == L"SharedLib")
m_eType = tCIDBuild::EProjTypes::SharedLib;
else if (strValue == L"StaticLib")
m_eType = tCIDBuild::EProjTypes::StaticLib;
else if (strValue == L"Executable")
m_eType = tCIDBuild::EProjTypes::Executable;
else if (strValue == L"Service")
m_eType = tCIDBuild::EProjTypes::Service;
else if (strValue == L"FileCopy")
m_eType = tCIDBuild::EProjTypes::FileCopy;
else if (strValue == L"Group")
m_eType = tCIDBuild::EProjTypes::Group;
else
return kCIDLib::False;
}
else if (strName == L"VARARGS")
{
if (!TUtils::bXlatBool(strValue, m_bVarArgs))
return kCIDLib::False;
}
else if (strName == L"VERSIONED")
{
if (!TUtils::bXlatBool(strValue, m_bVersioned))
return kCIDLib::False;
}
else if (strName == L"USESYSLIBS")
{
if (!TUtils::bXlatBool(strValue, m_bUseSysLibs))
return kCIDLib::False;
}
else if (strName == L"SAMPLE")
{
if (!TRawStr::bXlatBoolean(strValue.pszBuffer(), m_bIsSample))
return kCIDLib::False;
}
else
{
// Don't know what this setting is
return kCIDLib::False;
}
return kCIDLib::True;
}
// Called to parse the contents of the custom commands block
tCIDLib::TVoid TProjectInfo::ParseCustCmds(TLineSpooler& lsplSource)
{
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected 'custom command line' or END CUSTOMCMDS"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END CUSTOMCMDS")
break;
// Just add it to our custom commands list
m_listCustomCmds.Add(new TBldStr(strReadBuf));
}
}
tCIDLib::TVoid TProjectInfo::ParseDefines(TLineSpooler& lsplSource)
{
TBldStr strName;
TBldStr strReadBuf;
TBldStr strValue;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected 'name=value' or END DEFINES"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END DEFINES")
break;
// Have to assume its a define so pull it out
if (!TUtils::bFindNVParts(strReadBuf, strName, strValue))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Badly formed DEFINE statement" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
// Add a new define, if it does not already exist
if (bDefineExists(strName))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Define '" << strName
<< L"' already exists" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::AlreadyExists;
}
// Ok we can add it
m_listDefs.Add(new TKeyValuePair(strName, strValue));
}
}
tCIDLib::TVoid TProjectInfo::ParseDependents(TLineSpooler& lsplSource)
{
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected 'dependent name' or END DEPENDENTS"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END DEPENDENTS")
break;
// Have to assume its the name of a dependent
m_listDeps.Add(new TBldStr(strReadBuf));
}
}
tCIDLib::TVoid TProjectInfo::ParseExtLibs(TLineSpooler& lsplSource)
{
// Only valid for code type projects
if (m_eType > tCIDBuild::EProjTypes::MaxCodeType)
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Not valid for this type of project"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::NotSupported;
}
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected include path or END EXTLIBS"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END EXTLIBS")
break;
//
// Have to assume its a lib path. It can start with the project dir
// macro, which we have to expand, else we take it as is.
//
if (strReadBuf.bStartsWith(L"$(ProjDir)\\"))
{
TBldStr strTmp(m_strProjectDir);
strTmp.AppendAt(strReadBuf, 11);
m_listExtLibs.Add(new TBldStr(strTmp));
}
else
{
m_listExtLibs.Add(new TBldStr(strReadBuf));
}
}
}
tCIDLib::TVoid
TProjectInfo::ParseFileCopies(TLineSpooler& lsplSource, const TBldStr& strTarPath)
{
// Add a new file copy object to the list, setting the passed target path
TProjFileCopy* pfcNew = new TProjFileCopy(strTarPath);
m_listFileCopies.Add(pfcNew);
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected include path or END FILECOPIES"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END FILECOPIES")
break;
// Have to assume its a file name to copy
pfcNew->AddSrcFile(strReadBuf);
}
//
// If there's one entry and it is in the form *, then we get the source
// directory and add all the files in that directory to the list.
//
if (pfcNew->listSrcFiles().c4ElemCount() == 1)
{
TListCursor<TBldStr> cursOrgList(&pfcNew->listSrcFiles());
if (cursOrgList.bResetIter())
{
if (cursOrgList.tCurElement() == L"*")
{
strReadBuf = strProjectDir();
strReadBuf.Append(L"\\*");
pfcNew->RemoveAll();
TList<TFindInfo> listNewList;
TFindInfo::c4FindFiles(strReadBuf, listNewList);
TListCursor<TFindInfo> cursNewList(&listNewList);
if (cursNewList.bResetIter())
{
do
{
if (!cursNewList.tCurElement().bIsDirectory())
pfcNew->AddSrcFile(cursNewList.tCurElement().strFileName());
} while (cursNewList.bNext());
}
}
}
}
}
tCIDLib::TVoid TProjectInfo::ParseIDLFiles(TLineSpooler& lsplSource)
{
// Only valid for code type projects
if (m_eType > tCIDBuild::EProjTypes::MaxCodeType)
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Not valid for a 'filecopy' project"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::NotSupported;
}
TIDLInfo idliTmp;
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected IDLFILE or END IDLFILES"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END IDLFILES")
break;
// It must be IDLFILE
if (strReadBuf != L"IDLFILE")
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected IDLFILE" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
//
// Ok, parse out the fields for this entry. It just has a few
// fields, the source IDL file path, the gen mode, and an optional
// name extension. We just create a new TIDLInfo object and let
// it parse itself out.
//
idliTmp.Parse(lsplSource);
// It worked, so add it to the list
m_listIDLFiles.Add(new TIDLInfo(idliTmp));
}
}
tCIDLib::TVoid TProjectInfo::ParseIncludePaths(TLineSpooler& lsplSource)
{
// Only valid for code type projects
if (m_eType > tCIDBuild::EProjTypes::MaxCodeType)
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Not valid for a 'filecopy' project"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::NotSupported;
}
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected include path or END INCLUDEPATHS"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END INCLUDEPATHS")
break;
//
// Have to assume its an include path. If it isn't fully qualified,
// then assume it is relative to the project source path. If if
// starts with $(ProjDir), replace that with the project directory.
//
if (TUtils::bIsFQPath(strReadBuf))
{
m_listIncludePaths.Add(new TBldStr(strReadBuf));
}
else if (strReadBuf.bStartsWith(L"$(ProjDir)\\"))
{
TBldStr strTmp(m_strProjectDir);
strTmp.AppendAt(strReadBuf, 11);
m_listIncludePaths.Add(new TBldStr(strTmp));
}
else
{
TBldStr strTmp(m_strProjectDir);
strTmp.Append(strReadBuf);
m_listIncludePaths.Add(new TBldStr(strTmp));
}
}
}
tCIDLib::TVoid TProjectInfo::ParsePlatforms(TLineSpooler& lsplSource)
{
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected 'platform name' or end of platforms"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (((strReadBuf == L"END INCLUDEPLATS") && m_bPlatformInclude)
|| ((strReadBuf == L"END EXPLUDEPLATS") && !m_bPlatformInclude))
{
break;
}
// Have to assume its the name of a support platform
m_listPlatforms.Add(new TBldStr(strReadBuf));
}
}
tCIDLib::TVoid TProjectInfo::ParsePlatOpts(TLineSpooler& lsplSource)
{
TBldStr strOptName;
TBldStr strOptValue;
TBldStr strPlatName;
TBldStr strReadBuf;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected END PLATFORMOPTS or PLATFORM="
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END PLATFORMOPTS")
{
break;
}
// It should start with PLATFORM= and the platform name
if (!strReadBuf.bStartsWith(L"PLATFORM="))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected END PLATFORMOPTS or PLATFORM="
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
// Next should be the platform name so get that out
strPlatName = strReadBuf;
strPlatName.Cut(9);
//
// Add a new list for this platform and a first entry with the key being
// the platform name.
//
TKVPList* plistNew = new TKVPList();
plistNew->Add(new TKeyValuePair(strPlatName, L""));
m_listPlatOpts.Add(plistNew);
//
// Now we loop till we see the end of this block, pulling out lines
// each of which is either a value or a key=value pair.
//
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected END PLATFORM or a platform option="
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END PLATFORM")
break;
// It has to be in our standard key=value format
if (!TUtils::bFindNVParts(strReadBuf, strOptName, strOptValue))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Badly formed platform option statement" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
// Add a new pair for this guy
plistNew->Add(new TKeyValuePair(strOptName, strOptValue));
}
}
}
tCIDLib::TVoid TProjectInfo::ParseSettings(TLineSpooler& lsplSource)
{
TBldStr strName;
TBldStr strReadBuf;
TBldStr strValue;
while (kCIDLib::True)
{
// Get the next line. If end of file, that's an error here
if (!lsplSource.bReadLine(strReadBuf))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Expected 'setting=value' or END SETTINGS"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::UnexpectedEOF;
}
if (strReadBuf == L"END SETTINGS")
break;
//
// Have to assume its a setting value, so lets see if we can
// recognize it. We use a utility function that will find the
// name/value parts of a string divided by an '=' sign.
//
if (!TUtils::bFindNVParts(strReadBuf, strName, strValue))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Badly formed SETTING statement" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
// Find out which one it is and check the value
if (!bSetSetting(strName, strValue))
{
stdOut << L"(Line " << lsplSource.c4CurLine()
<< L") Unknown SETTING name or bad value. Name="
<< strName << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
}
//
// Insure that we got any settings that must have been provided. If not, that's
// an error. The directory can be empty if it's a group
//
if (m_strProjectName.bEmpty())
{
stdOut << L"Project settings at line " << lsplSource.c4CurLine()
<< L" failed to define a project name"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
if (m_strDirectory.bEmpty() && (m_eType != tCIDBuild::EProjTypes::Group))
{
stdOut << L"Project settings at line " << lsplSource.c4CurLine()
<< L" failed to define a project name"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
}
| 29.273739 | 93 | 0.563772 | eudora-jia |
b7d35659ef2060ce2c97f553eae81ce927254b82 | 729 | cpp | C++ | Source/USemLog/Private/ROSProlog/SLROSServiceClient.cpp | Leusmann/USemLog | 3492a4fd55a524433785802c77444982e57f2e0a | [
"BSD-3-Clause"
] | 7 | 2017-10-05T09:47:40.000Z | 2020-10-15T04:02:07.000Z | Source/USemLog/Private/ROSProlog/SLROSServiceClient.cpp | Leusmann/USemLog | 3492a4fd55a524433785802c77444982e57f2e0a | [
"BSD-3-Clause"
] | 11 | 2017-08-10T10:01:55.000Z | 2020-12-31T13:02:33.000Z | Source/USemLog/Private/ROSProlog/SLROSServiceClient.cpp | Leusmann/USemLog | 3492a4fd55a524433785802c77444982e57f2e0a | [
"BSD-3-Clause"
] | 19 | 2017-03-07T08:18:43.000Z | 2021-11-09T10:58:04.000Z | // Copyright 2020, Institute for Artificial Intelligence - University of Bremen
// Author: Jose Rojas
#include "ROSProlog/SLROSServiceClient.h"
#include "ROSProlog/SLPrologClient.h"
// Constructor
SLROSServiceClient::SLROSServiceClient()
{
}
// Destructor
SLROSServiceClient::~SLROSServiceClient()
{
}
#if SL_WITH_ROSBRIDGE
// Init constructor
SLROSServiceClient::SLROSServiceClient(UObject *InOwner, FString InName, FString InType)
{
Owner = InOwner;
Name = InName;
Type = InType;
}
// Callback to ProcessResponse in owner
void SLROSServiceClient::Callback(TSharedPtr<FROSBridgeSrv::SrvResponse> InResponse)
{
USLPrologClient *Logger = Cast<USLPrologClient>(Owner);
Logger->ProcessResponse(InResponse, Type);
}
#endif
| 22.090909 | 88 | 0.784636 | Leusmann |
b7d80910df3a3500ed9e6b8c74b25b38b73214ec | 2,465 | cpp | C++ | node_modules/pxt-common-packages/libs/core/spi.cpp | johnwing/music2 | a8940cd3e53061d7ca0461811f9ffb2440b586a1 | [
"MIT"
] | null | null | null | node_modules/pxt-common-packages/libs/core/spi.cpp | johnwing/music2 | a8940cd3e53061d7ca0461811f9ffb2440b586a1 | [
"MIT"
] | null | null | null | node_modules/pxt-common-packages/libs/core/spi.cpp | johnwing/music2 | a8940cd3e53061d7ca0461811f9ffb2440b586a1 | [
"MIT"
] | null | null | null | #include "pxt.h"
#include "ErrorNo.h"
namespace pins {
class CodalSPIProxy {
private:
DevicePin* mosi;
DevicePin* miso;
DevicePin* sck;
CODAL_SPI spi;
public:
CodalSPIProxy* next;
public:
CodalSPIProxy(DevicePin* _mosi, DevicePin* _miso, DevicePin* _sck)
: mosi(_mosi)
, miso(_miso)
, sck(_sck)
, spi(*_mosi, *_miso, *_sck)
, next(NULL)
{
}
CODAL_SPI* getSPI() {
return &spi;
}
bool matchPins(DevicePin* mosi, DevicePin* miso, DevicePin* sck) {
return this->mosi == mosi && this->miso == miso && this->sck == sck;
}
int write(int value) {
return spi.write(value);
}
void transfer(Buffer command, Buffer response) {
auto cdata = NULL == command ? NULL : command->data;
auto clength = NULL == command ? 0 : command->length;
auto rdata = NULL == response ? NULL : response->data;
auto rlength = NULL == response ? 0 : response->length;
spi.transfer(cdata, clength, rdata, rlength);
}
void setFrequency(int frequency) {
spi.setFrequency(frequency);
}
void setMode(int mode) {
spi.setMode(mode);
}
};
SPI_ spis(NULL);
/**
* Opens a SPI driver
*/
//% help=pins/create-spi
//% parts=spi
SPI_ createSPI(DigitalInOutPin mosiPin, DigitalInOutPin misoPin, DigitalInOutPin sckPin) {
auto dev = spis;
while(dev) {
if (dev->matchPins(mosiPin, misoPin, sckPin))
return dev;
dev = dev->next;
}
auto ser = new CodalSPIProxy(mosiPin, misoPin, sckPin);
ser->next = spis;
spis = ser;
return ser;
}
}
namespace pxt {
CODAL_SPI* getSPI(DigitalInOutPin mosiPin, DigitalInOutPin misoPin, DigitalInOutPin sckPin) {
auto spi = pins::createSPI(mosiPin, misoPin, sckPin);
return spi->getSPI();
}
}
namespace SPIMethods {
/**
* Write to the SPI bus
*/
//%
int write(SPI_ device, int value) {
return device->write(value);
}
/**
* Transfer buffers over the SPI bus
*/
//% argsNullable
void transfer(SPI_ device, Buffer command, Buffer response) {
if (!device)
target_panic(PANIC_CAST_FROM_NULL);
if (!command && !response)
return;
device->transfer(command, response);
}
/**
* Sets the SPI clock frequency
*/
//%
void setFrequency(SPI_ device, int frequency) {
device->setFrequency(frequency);
}
/**
* Sets the SPI bus mode
*/
//%
void setMode(SPI_ device, int mode) {
device->setMode(mode);
}
}
| 19.72 | 93 | 0.622718 | johnwing |
b7dad7284b176e251ba382227bed98e79260bec6 | 106 | hpp | C++ | fft/ft_grid_helpers.hpp | simonpp/2dRidgeletBTE | 5d08cbb5c57fc276c7a528f128615d23c37ef6a0 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T03:15:56.000Z | 2019-11-08T03:15:56.000Z | fft/ft_grid_helpers.hpp | simonpp/2dRidgeletBTE | 5d08cbb5c57fc276c7a528f128615d23c37ef6a0 | [
"BSD-3-Clause"
] | null | null | null | fft/ft_grid_helpers.hpp | simonpp/2dRidgeletBTE | 5d08cbb5c57fc276c7a528f128615d23c37ef6a0 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T03:15:56.000Z | 2019-11-08T03:15:56.000Z | #pragma once
#include "ft_grid_helpers_impl/fourier_modes.hpp"
#include "ft_grid_helpers_impl/ftcut.hpp"
| 21.2 | 49 | 0.830189 | simonpp |
b7dbb9aa536d7bfa9ccfb9251da195052703ef03 | 9,327 | cpp | C++ | src/bindings/cpp/tests/testcpp_iter_name.cpp | dev2718/libelektra | cd581101febbc8ee2617243d0d93f871ef2fae88 | [
"BSD-3-Clause"
] | 188 | 2015-01-07T20:34:26.000Z | 2022-03-16T09:55:09.000Z | src/bindings/cpp/tests/testcpp_iter_name.cpp | dev2718/libelektra | cd581101febbc8ee2617243d0d93f871ef2fae88 | [
"BSD-3-Clause"
] | 3,813 | 2015-01-02T14:00:08.000Z | 2022-03-31T14:19:11.000Z | src/bindings/cpp/tests/testcpp_iter_name.cpp | dev2718/libelektra | cd581101febbc8ee2617243d0d93f871ef2fae88 | [
"BSD-3-Clause"
] | 149 | 2015-01-10T02:07:50.000Z | 2022-03-16T09:50:24.000Z | /**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include <tests.hpp>
#include <algorithm>
#include <vector>
#include <gtest/gtest.h>
TEST (test_iter_name, forward)
{
Key k ("user:/user\\/key4\\/1/user\\/key4\\/2/user\\/key4\\/3", KEY_END);
Key::iterator it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "name wrong";
++it;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
++it;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
++it;
EXPECT_EQ ((*it), "user/key4/3") << "name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), "user/key4/3") << "name wrong";
--it;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
--it;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
it++;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
it++;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
it++;
EXPECT_EQ ((*it), "user/key4/3") << "name wrong";
it++;
EXPECT_EQ (it, k.end ()) << "not at end";
it--;
EXPECT_EQ ((*it), "user/key4/3") << "name wrong";
it--;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
it--;
}
TEST (test_iter_name, reverse)
{
Key k ("user:/user\\/key4\\/1/user\\/key4\\/2/user\\/key4\\/3", KEY_END);
Key::reverse_iterator it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "name wrong";
--it;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
--it;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
--it;
EXPECT_EQ ((*it), "user/key4/3") << "name wrong";
// --it; // Misusage, do not go past begin
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
++it;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
++it;
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "name wrong";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
it--;
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "name wrong";
it--;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
it--;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
it--;
EXPECT_EQ ((*it), "user/key4/3") << "name wrong";
// it--; // Misusage, do not go past begin
EXPECT_EQ (it, k.rbegin ()) << "not at end";
it++;
EXPECT_EQ ((*it), "user/key4/2") << "name wrong";
it++;
EXPECT_EQ ((*it), "user/key4/1") << "name wrong";
}
TEST (iterNameCascading, forward)
{
Key k ("/\\/key4\\/1/\\/key4\\/2/\\/key4\\/3", KEY_END);
Key::iterator it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "cascading name wrong";
++it;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
++it;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
++it;
EXPECT_EQ ((*it), "/key4/3") << "name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), "/key4/3") << "name wrong";
--it;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
--it;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
it++;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
it++;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
it++;
EXPECT_EQ ((*it), "/key4/3") << "name wrong";
it++;
EXPECT_EQ (it, k.end ()) << "not at end";
it--;
EXPECT_EQ ((*it), "/key4/3") << "name wrong";
it--;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
it--;
}
TEST (iterNameCascading, reverse)
{
Key k ("/\\/key4\\/1/\\/key4\\/2/\\/key4\\/3", KEY_END);
Key::reverse_iterator it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "name wrong";
--it;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
--it;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
--it;
EXPECT_EQ ((*it), "/key4/3") << "name wrong";
// --it; // Misusage, do not go past begin
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
++it;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
++it;
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "name wrong";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
it--;
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "name wrong";
it--;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
it--;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
it--;
EXPECT_EQ ((*it), "/key4/3") << "name wrong";
// it--; // Misusage, do not go past begin
EXPECT_EQ (it, k.rbegin ()) << "not at end";
it++;
EXPECT_EQ ((*it), "/key4/2") << "name wrong";
it++;
EXPECT_EQ ((*it), "/key4/1") << "name wrong";
}
TEST (iterNameRoot, forward)
{
Key k ("/", KEY_END);
Key::iterator it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("meta:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_META }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_META }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("spec:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_SPEC }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_SPEC }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("proc:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_PROC }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_PROC }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("dir:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_DIR }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_DIR }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("user:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("system:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_SYSTEM }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_SYSTEM }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
k = Key ("default:/", KEY_END);
it = k.begin ();
EXPECT_EQ ((*it), std::string{ KEY_NS_DEFAULT }) << "cascading name wrong";
++it;
EXPECT_EQ (it, k.end ()) << "not at end";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_DEFAULT }) << "name wrong";
EXPECT_EQ (it, k.begin ()) << "not at begin";
}
TEST (iterNameRoot, reverse)
{
Key k ("/", KEY_END);
Key::reverse_iterator it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_CASCADING }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("meta:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_META }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("spec:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_SPEC }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("proc:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_PROC }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("dir:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_DIR }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("user:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_USER }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("system:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_SYSTEM }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
k = Key ("default:/", KEY_END);
it = k.rend ();
EXPECT_EQ ((*it), "") << "name wrong";
--it;
EXPECT_EQ ((*it), std::string{ KEY_NS_DEFAULT }) << "cascading name wrong";
EXPECT_EQ (it, k.rbegin ()) << "not at end";
++it;
EXPECT_EQ (it, k.rend ()) << "not at begin";
} | 25.908333 | 78 | 0.556878 | dev2718 |
b7e16b37994fa6d793355df9e7393c811592fbef | 7,274 | cpp | C++ | graphic/scenes/table/chicha.cpp | MihailJP/MiHaJong | b81168ab2696dd29af5c400b84c870a9b8a2f01e | [
"MIT"
] | 13 | 2016-01-20T02:10:52.000Z | 2022-03-08T15:51:36.000Z | graphic/scenes/table/chicha.cpp | MihailJP/MiHaJong | b81168ab2696dd29af5c400b84c870a9b8a2f01e | [
"MIT"
] | 13 | 2020-09-28T12:57:52.000Z | 2022-02-20T19:20:57.000Z | graphic/scenes/table/chicha.cpp | MihailJP/MiHaJong | b81168ab2696dd29af5c400b84c870a9b8a2f01e | [
"MIT"
] | 4 | 2016-09-19T13:44:10.000Z | 2022-02-18T08:13:37.000Z | #include "chicha.h"
#include "../../resource.h"
#include "../../sprite.h"
#include "../../gametbl.h"
#include "../../utils.h"
namespace mihajong_graphic {
using utils::playerRelative;
/* 起家マークを置く凹み */
void GameTableScreen::TrayReconst::ShowTray() {
constexpr RECT rect1 = {TrayHLeft, TrayHTop, TrayHRight, TrayHBottom,};
constexpr RECT rect2 = {TrayVLeft, TrayVTop, TrayVRight, TrayVBottom,};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TrayPosH, TrayPosV,
TrayHWidth, TrayHHeight, 0xffffffff, &rect1, TrayHWidth / 2, TrayHHeight / 2);
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TableSize - TrayPosH, TableSize - TrayPosV,
TrayHWidth, TrayHHeight, 0xffffffff, &rect1, TrayHWidth / 2, TrayHHeight / 2);
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TableSize - TrayPosV, TrayPosH,
TrayVWidth, TrayVHeight, 0xffffffff, &rect2, TrayVWidth / 2, TrayVHeight / 2);
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TrayPosV, TableSize - TrayPosH,
TrayVWidth, TrayVHeight, 0xffffffff, &rect2, TrayVWidth / 2, TrayVHeight / 2);
}
/* 起家マークの表示 */
void GameTableScreen::TrayReconst::ShowChiicha(const GameTable* gameStat) {
switch (playerRelative(0, gameStat->PlayerID)) {
case SeatRelative::self:
{
const RECT rect = {
static_cast<int32_t>((PlateWidthH + PlatePadding * 2) * (gameStat->GameRound / Players ) + PlatePadding), static_cast<int32_t>((PlateHeightH + PlatePadding * 2) * (0 ) + PlatePadding),
static_cast<int32_t>((PlateWidthH + PlatePadding * 2) * (gameStat->GameRound / Players + 1) - PlatePadding), static_cast<int32_t>((PlateHeightH + PlatePadding * 2) * (0 + 1) - PlatePadding),
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, PlatePosH, PlatePosV,
PlateWidthH, PlateHeightH, 0xffffffff, &rect, PlateWidthH / 2, PlateHeightH / 2);
}
break;
case SeatRelative::opposite:
{
const RECT rect = {
static_cast<int32_t>((PlateWidthH + PlatePadding * 2) * (gameStat->GameRound / Players ) + PlatePadding), static_cast<int32_t>((PlateHeightH + PlatePadding * 2) * (1 ) + PlatePadding),
static_cast<int32_t>((PlateWidthH + PlatePadding * 2) * (gameStat->GameRound / Players + 1) - PlatePadding), static_cast<int32_t>((PlateHeightH + PlatePadding * 2) * (1 + 1) - PlatePadding),
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TableSize - PlatePosH, TableSize - PlatePosV,
PlateWidthH, PlateHeightH, 0xffffffff, &rect, PlateWidthH / 2, PlateHeightH / 2);
}
break;
case SeatRelative::right:
{
const RECT rect = {
static_cast<int32_t>((PlateWidthV + PlatePadding * 2) * (gameStat->GameRound / Players ) + PlatePadding), static_cast<int32_t>((PlateHeightV + PlatePadding * 2) * (0 ) + PlatePadding + (PlateHeightH + PlatePadding * 2) * 2),
static_cast<int32_t>((PlateWidthV + PlatePadding * 2) * (gameStat->GameRound / Players + 1) - PlatePadding), static_cast<int32_t>((PlateHeightV + PlatePadding * 2) * (0 + 1) - PlatePadding + (PlateHeightH + PlatePadding * 2) * 2),
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, PlatePosV, TableSize - PlatePosH,
PlateWidthV, PlateHeightV, 0xffffffff, &rect, PlateWidthV / 2, PlateHeightV / 2);
}
break;
case SeatRelative::left:
{
const RECT rect = {
static_cast<int32_t>((PlateWidthV + PlatePadding * 2) * (gameStat->GameRound / Players ) + PlatePadding), static_cast<int32_t>((PlateHeightV + PlatePadding * 2) * (1 ) + PlatePadding + (PlateHeightH + PlatePadding * 2) * 2),
static_cast<int32_t>((PlateWidthV + PlatePadding * 2) * (gameStat->GameRound / Players + 1) - PlatePadding), static_cast<int32_t>((PlateHeightV + PlatePadding * 2) * (1 + 1) - PlatePadding + (PlateHeightH + PlatePadding * 2) * 2),
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TableSize - PlatePosV, PlatePosH,
PlateWidthV, PlateHeightV, 0xffffffff, &rect, PlateWidthV / 2, PlateHeightV / 2);
}
break;
}
}
/* ヤキトリマークの表示 */
void GameTableScreen::TrayReconst::ShowYakitori(const GameTable* gameStat) {
for (PlayerID i = 0; i < Players; ++i) {
if (!gameStat->Player[i].YakitoriFlag) continue;
switch (playerRelative(i, gameStat->PlayerID)) {
case SeatRelative::self:
{
constexpr RECT rect = {
(PlateWidthH + PlatePadding * 2) * (PlateID_Yakitori ) + PlatePadding, (PlateHeightH + PlatePadding * 2) * (0 ) + PlatePadding,
(PlateWidthH + PlatePadding * 2) * (PlateID_Yakitori + 1) - PlatePadding, (PlateHeightH + PlatePadding * 2) * (0 + 1) - PlatePadding,
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, YakitoriPosH, YakitoriPosV,
PlateWidthH, PlateHeightH, 0xffffffff, &rect, PlateWidthH / 2, PlateHeightH / 2);
}
break;
case SeatRelative::opposite:
{
constexpr RECT rect = {
(PlateWidthH + PlatePadding * 2) * (PlateID_Yakitori ) + PlatePadding, (PlateHeightH + PlatePadding * 2) * (1 ) + PlatePadding,
(PlateWidthH + PlatePadding * 2) * (PlateID_Yakitori + 1) - PlatePadding, (PlateHeightH + PlatePadding * 2) * (1 + 1) - PlatePadding,
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TableSize - YakitoriPosH, TableSize - YakitoriPosV,
PlateWidthH, PlateHeightH, 0xffffffff, &rect, PlateWidthH / 2, PlateHeightH / 2);
}
break;
case SeatRelative::right:
{
constexpr RECT rect = {
(PlateWidthV + PlatePadding * 2) * (PlateID_Yakitori ) + PlatePadding, (PlateHeightV + PlatePadding * 2) * (0 ) + PlatePadding + (PlateHeightH + PlatePadding * 2) * 2,
(PlateWidthV + PlatePadding * 2) * (PlateID_Yakitori + 1) - PlatePadding, (PlateHeightV + PlatePadding * 2) * (0 + 1) - PlatePadding + (PlateHeightH + PlatePadding * 2) * 2,
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, YakitoriPosV, TableSize - YakitoriPosH,
PlateWidthV, PlateHeightV, 0xffffffff, &rect, PlateWidthV / 2, PlateHeightV / 2);
}
break;
case SeatRelative::left:
{
constexpr RECT rect = {
(PlateWidthV + PlatePadding * 2) * (PlateID_Yakitori ) + PlatePadding, (PlateHeightV + PlatePadding * 2) * (1 ) + PlatePadding + (PlateHeightH + PlatePadding * 2) * 2,
(PlateWidthV + PlatePadding * 2) * (PlateID_Yakitori + 1) - PlatePadding, (PlateHeightV + PlatePadding * 2) * (1 + 1) - PlatePadding + (PlateHeightH + PlatePadding * 2) * 2,
};
SpriteRenderer::instantiate(caller->caller->getDevice())->ShowSprite(tChiicha, TableSize - YakitoriPosV, YakitoriPosH,
PlateWidthV, PlateHeightV, 0xffffffff, &rect, PlateWidthV / 2, PlateHeightV / 2);
}
break;
}
}
}
void GameTableScreen::TrayReconst::Render() {
ShowTray();
ShowChiicha(GameStatus::gameStat());
ShowYakitori(GameStatus::gameStat());
}
GameTableScreen::TrayReconst::TrayReconst(GameTableScreen* parent) {
caller = parent;
caller->LoadTexture(&tChiicha, MAKEINTRESOURCE(IDB_PNG_CHICHAMARK));
}
GameTableScreen::TrayReconst::~TrayReconst() {
#if defined(_WIN32) && defined(WITH_DIRECTX)
if (tChiicha) tChiicha->Release();
#endif
}
}
| 52.710145 | 234 | 0.697965 | MihailJP |
b7e878d6e6a49c3035795f494392cce1e16853c1 | 1,128 | cpp | C++ | Build/src/src/Scene/Courier.cpp | maz8569/OpenGLPAG | 3c470a6824c0d3169fdc65691f697c2af39a6442 | [
"MIT"
] | null | null | null | Build/src/src/Scene/Courier.cpp | maz8569/OpenGLPAG | 3c470a6824c0d3169fdc65691f697c2af39a6442 | [
"MIT"
] | null | null | null | Build/src/src/Scene/Courier.cpp | maz8569/OpenGLPAG | 3c470a6824c0d3169fdc65691f697c2af39a6442 | [
"MIT"
] | null | null | null | #include "Scene/Courier.h"
GameEngine::Courier::Courier(Ref<MousePicker> mousePicker, Ref<Model> model, std::shared_ptr<Shader> shader, std::shared_ptr<Collision> colMan)
: Entity(model, shader, colMan), m_mousePicker(mousePicker)
{
m_inputManager = mousePicker->getInputManager();
Entity::Update();
}
void GameEngine::Courier::render()
{
Entity::render();
}
void GameEngine::Courier::Update()
{
//if (get_transform().m_position.y > 10 || get_transform().m_position.y < -10)
//speed *= -1;
//get_transform().m_position.y += 0.01 * speed;
//update(get_parent()->get_transform(), true);
if (m_inputManager->m_isRclicked)
{
glm::vec3 start = m_mousePicker->getCameraPos();
glm::vec3 dir = m_mousePicker->getCurrentRay();
//std::cout << dir.x << " " << dir.y << " " << dir.z << " " << std::endl;
glm::vec3 end = dir *40.f + start;
get_transform().m_position = end;
update(get_parent()->get_transform(), true);
//std::cout << end.x << " " << end.y << " " << end.z << " " << std::endl;
}
Entity::Update();
}
void GameEngine::Courier::reactOnCollision(GObject* other)
{
//std::cout << "end";
}
| 24.521739 | 144 | 0.646277 | maz8569 |
b7eac2e350570f6a4631b596fd22d2f531d58abc | 3,280 | hpp | C++ | include/wiztk/gui/theme.hpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 37 | 2017-11-22T14:15:33.000Z | 2021-11-25T20:39:39.000Z | include/wiztk/gui/theme.hpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 3 | 2018-03-01T12:44:22.000Z | 2021-01-04T23:14:41.000Z | include/wiztk/gui/theme.hpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 10 | 2017-11-25T19:09:11.000Z | 2020-12-02T02:05:47.000Z | /*
* Copyright 2017 - 2018 The WizTK 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.
*/
#ifndef WIZTK_GUI_THEME_HPP_
#define WIZTK_GUI_THEME_HPP_
#include "wiztk/base/color.hpp"
#include "wiztk/base/thickness.hpp"
#include "wiztk/base/point.hpp"
#include "wiztk/graphics/shader.hpp"
#include "wiztk/graphics/font.hpp"
#include "wiztk/graphics/pixmap.hpp"
#include <vector>
#include <string>
class SkPixmap;
namespace wiztk {
namespace gui {
typedef void *(*ThemeCreateHandle)();
typedef void(*ThemeDestroyHandle)(void *p);
/**
* @ingroup gui
* @brief The global theme manager
*/
class WIZTK_EXPORT Theme {
friend class Application;
public:
using ColorF = base::ColorF;
using Margin = base::ThicknessI;
Theme(const Theme &) = delete;
Theme &operator=(const Theme &) = delete;
struct Schema {
struct Style {
ColorF foreground;
ColorF background;
ColorF outline;
};
Schema() {
active.foreground = 0xFF000000; // black
active.background = 0xFFFFFFFF; // white
active.outline = 0xFF000000; // black
inactive = active;
highlight = active;
}
~Schema() = default;
// TODO: use image
Style active;
Style inactive;
Style highlight;
};
struct Data {
Data();
std::string name;
Schema window;
Schema title_bar;
graphics::Font title_bar_font;
Schema button;
graphics::Font default_font;
};
static void Load(const char *name = nullptr);
static inline int GetShadowRadius() {
return kShadowRadius;
}
static inline int GetShadowOffsetX() {
return kShadowOffsetX;
}
static inline int GetShadowOffsetY() {
return kShadowOffsetY;
}
static inline const Margin &GetShadowMargin() {
return kShadowMargin;
}
static inline const graphics::Pixmap *GetShadowPixmap() {
return kShadowPixmap;
}
static const int kShadowImageWidth = 250;
static const int kShadowImageHeight = 250;
static const Data &GetData() { return kTheme->data_; }
protected:
Theme();
virtual ~Theme();
Data &data() { return data_; }
private:
/**
* @brief Initialize static properties
*
* This method is called only in Application
*/
static void Initialize();
/**
* @brief Release the memory allocated for theme
*
* This method is called only in Application
*/
static void Release();
static void GenerateShadowImage();
static int kShadowRadius;
static int kShadowOffsetX;
static int kShadowOffsetY;
static Margin kShadowMargin;
static std::vector<uint32_t> kShadowPixels;
static graphics::Pixmap *kShadowPixmap;
static Theme *kTheme;
Data data_;
};
} // namespace gui
} // namespace wiztk
#endif // WIZTK_GUI_THEME_HPP_
| 18.531073 | 75 | 0.68689 | wiztk |
b7ee91b261ce90ea20e87d53e1ddee4b85c6cebb | 911 | cpp | C++ | src/mxml/parsing/BackupHandler.cpp | dkun7944/mxml | 6450e7cab88eb6ee0ac469f437047072e1868ea4 | [
"MIT"
] | 18 | 2016-05-22T00:55:28.000Z | 2021-03-29T08:44:23.000Z | src/mxml/parsing/BackupHandler.cpp | dkun7944/mxml | 6450e7cab88eb6ee0ac469f437047072e1868ea4 | [
"MIT"
] | 6 | 2017-05-17T13:20:09.000Z | 2018-10-22T20:00:57.000Z | src/mxml/parsing/BackupHandler.cpp | dkun7944/mxml | 6450e7cab88eb6ee0ac469f437047072e1868ea4 | [
"MIT"
] | 14 | 2016-05-12T22:54:34.000Z | 2021-10-19T12:43:16.000Z | // Copyright © 2016 Venture Media Labs.
//
// This file is part of mxml. The full mxml copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "BackupHandler.h"
namespace mxml {
using dom::Backup;
using lxml::QName;
static const char* kDurationTag = "duration";
void BackupHandler::startElement(const QName& qname, const AttributeMap& attributes) {
_result.reset(new Backup());
}
lxml::RecursiveHandler* BackupHandler::startSubElement(const QName& qname) {
if (strcmp(qname.localName(), kDurationTag) == 0)
return &_integerHandler;
return 0;
}
void BackupHandler::endSubElement(const QName& qname, RecursiveHandler* parser) {
if (strcmp(qname.localName(), kDurationTag) == 0)
_result->setDuration(_integerHandler.result());
}
} // namespace mxml
| 28.46875 | 86 | 0.731065 | dkun7944 |
b7f0a85eea892c6ced2f518f928f02fd131e83ef | 1,306 | cpp | C++ | trick_source/sim_services/DataTypes/src/EnumDictionary.cpp | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 647 | 2015-05-07T16:08:16.000Z | 2022-03-30T02:33:21.000Z | trick_source/sim_services/DataTypes/src/EnumDictionary.cpp | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 995 | 2015-04-30T19:44:31.000Z | 2022-03-31T20:14:44.000Z | trick_source/sim_services/DataTypes/src/EnumDictionary.cpp | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 251 | 2015-05-15T09:24:34.000Z | 2022-03-22T20:39:05.000Z | #include <iostream>
#include <sstream>
#include "EnumDictionary.hh"
int EnumDictionary::getValue(std::string name ) {
enumDictionaryIterator = enumDictionary.find(name);
if (enumDictionaryIterator == enumDictionary.end()) {
std::stringstream error_stream ;
error_stream << "ERROR: Enumerator \"" << name << "\" not defined." << std::endl;
throw std::logic_error( error_stream.str());
} else {
return( enumDictionaryIterator->second );
}
}
void EnumDictionary::addEnumerator(std::string name, int value) {
enumDictionaryIterator = enumDictionary.find(name);
if (enumDictionaryIterator == enumDictionary.end()) {
enumDictionary[name] = value;
} else {
std::stringstream error_stream ;
error_stream << "ERROR: Attempt to re-define enumerator \"" << name << "\"." << std::endl;
throw std::logic_error( error_stream.str());
}
}
// MEMBER FUNCTION
std::string EnumDictionary::toString() {
std::ostringstream oss;
for ( enumDictionaryIterator = enumDictionary.begin();
enumDictionaryIterator != enumDictionary.end();
enumDictionaryIterator++ ) {
oss << enumDictionaryIterator->first << " = " << enumDictionaryIterator->second << std::endl;
}
return oss.str();
}
| 31.095238 | 101 | 0.649311 | gilbertguoze |
b7f2ffb1d9a3cc3fdacdf437c35be4d58c7a8216 | 14,165 | cpp | C++ | src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d9/renderer9_utils.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 513 | 2015-09-27T15:16:57.000Z | 2022-03-08T09:26:35.000Z | src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d9/renderer9_utils.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 133 | 2015-09-28T23:41:42.000Z | 2021-06-21T03:59:11.000Z | src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d9/renderer9_utils.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 40 | 2016-01-18T16:56:36.000Z | 2022-02-27T13:03:51.000Z | #include "precompiled.h"
//
// Copyright (c) 2002-2012 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.
//
// renderer9_utils.cpp: Conversion functions and other utility routines
// specific to the D3D9 renderer.
#include "libGLESv2/renderer/d3d9/renderer9_utils.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/Context.h"
#include "common/debug.h"
namespace gl_d3d9
{
D3DCMPFUNC ConvertComparison(GLenum comparison)
{
D3DCMPFUNC d3dComp = D3DCMP_ALWAYS;
switch (comparison)
{
case GL_NEVER: d3dComp = D3DCMP_NEVER; break;
case GL_ALWAYS: d3dComp = D3DCMP_ALWAYS; break;
case GL_LESS: d3dComp = D3DCMP_LESS; break;
case GL_LEQUAL: d3dComp = D3DCMP_LESSEQUAL; break;
case GL_EQUAL: d3dComp = D3DCMP_EQUAL; break;
case GL_GREATER: d3dComp = D3DCMP_GREATER; break;
case GL_GEQUAL: d3dComp = D3DCMP_GREATEREQUAL; break;
case GL_NOTEQUAL: d3dComp = D3DCMP_NOTEQUAL; break;
default: UNREACHABLE();
}
return d3dComp;
}
D3DCOLOR ConvertColor(gl::Color color)
{
return D3DCOLOR_RGBA(gl::unorm<8>(color.red),
gl::unorm<8>(color.green),
gl::unorm<8>(color.blue),
gl::unorm<8>(color.alpha));
}
D3DBLEND ConvertBlendFunc(GLenum blend)
{
D3DBLEND d3dBlend = D3DBLEND_ZERO;
switch (blend)
{
case GL_ZERO: d3dBlend = D3DBLEND_ZERO; break;
case GL_ONE: d3dBlend = D3DBLEND_ONE; break;
case GL_SRC_COLOR: d3dBlend = D3DBLEND_SRCCOLOR; break;
case GL_ONE_MINUS_SRC_COLOR: d3dBlend = D3DBLEND_INVSRCCOLOR; break;
case GL_DST_COLOR: d3dBlend = D3DBLEND_DESTCOLOR; break;
case GL_ONE_MINUS_DST_COLOR: d3dBlend = D3DBLEND_INVDESTCOLOR; break;
case GL_SRC_ALPHA: d3dBlend = D3DBLEND_SRCALPHA; break;
case GL_ONE_MINUS_SRC_ALPHA: d3dBlend = D3DBLEND_INVSRCALPHA; break;
case GL_DST_ALPHA: d3dBlend = D3DBLEND_DESTALPHA; break;
case GL_ONE_MINUS_DST_ALPHA: d3dBlend = D3DBLEND_INVDESTALPHA; break;
case GL_CONSTANT_COLOR: d3dBlend = D3DBLEND_BLENDFACTOR; break;
case GL_ONE_MINUS_CONSTANT_COLOR: d3dBlend = D3DBLEND_INVBLENDFACTOR; break;
case GL_CONSTANT_ALPHA: d3dBlend = D3DBLEND_BLENDFACTOR; break;
case GL_ONE_MINUS_CONSTANT_ALPHA: d3dBlend = D3DBLEND_INVBLENDFACTOR; break;
case GL_SRC_ALPHA_SATURATE: d3dBlend = D3DBLEND_SRCALPHASAT; break;
default: UNREACHABLE();
}
return d3dBlend;
}
D3DBLENDOP ConvertBlendOp(GLenum blendOp)
{
D3DBLENDOP d3dBlendOp = D3DBLENDOP_ADD;
switch (blendOp)
{
case GL_FUNC_ADD: d3dBlendOp = D3DBLENDOP_ADD; break;
case GL_FUNC_SUBTRACT: d3dBlendOp = D3DBLENDOP_SUBTRACT; break;
case GL_FUNC_REVERSE_SUBTRACT: d3dBlendOp = D3DBLENDOP_REVSUBTRACT; break;
default: UNREACHABLE();
}
return d3dBlendOp;
}
D3DSTENCILOP ConvertStencilOp(GLenum stencilOp)
{
D3DSTENCILOP d3dStencilOp = D3DSTENCILOP_KEEP;
switch (stencilOp)
{
case GL_ZERO: d3dStencilOp = D3DSTENCILOP_ZERO; break;
case GL_KEEP: d3dStencilOp = D3DSTENCILOP_KEEP; break;
case GL_REPLACE: d3dStencilOp = D3DSTENCILOP_REPLACE; break;
case GL_INCR: d3dStencilOp = D3DSTENCILOP_INCRSAT; break;
case GL_DECR: d3dStencilOp = D3DSTENCILOP_DECRSAT; break;
case GL_INVERT: d3dStencilOp = D3DSTENCILOP_INVERT; break;
case GL_INCR_WRAP: d3dStencilOp = D3DSTENCILOP_INCR; break;
case GL_DECR_WRAP: d3dStencilOp = D3DSTENCILOP_DECR; break;
default: UNREACHABLE();
}
return d3dStencilOp;
}
D3DTEXTUREADDRESS ConvertTextureWrap(GLenum wrap)
{
D3DTEXTUREADDRESS d3dWrap = D3DTADDRESS_WRAP;
switch (wrap)
{
case GL_REPEAT: d3dWrap = D3DTADDRESS_WRAP; break;
case GL_CLAMP_TO_EDGE: d3dWrap = D3DTADDRESS_CLAMP; break;
case GL_MIRRORED_REPEAT: d3dWrap = D3DTADDRESS_MIRROR; break;
default: UNREACHABLE();
}
return d3dWrap;
}
D3DCULL ConvertCullMode(GLenum cullFace, GLenum frontFace)
{
D3DCULL cull = D3DCULL_CCW;
switch (cullFace)
{
case GL_FRONT:
cull = (frontFace == GL_CCW ? D3DCULL_CW : D3DCULL_CCW);
break;
case GL_BACK:
cull = (frontFace == GL_CCW ? D3DCULL_CCW : D3DCULL_CW);
break;
case GL_FRONT_AND_BACK:
cull = D3DCULL_NONE; // culling will be handled during draw
break;
default: UNREACHABLE();
}
return cull;
}
D3DCUBEMAP_FACES ConvertCubeFace(GLenum cubeFace)
{
D3DCUBEMAP_FACES face = D3DCUBEMAP_FACE_POSITIVE_X;
switch (cubeFace)
{
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
face = D3DCUBEMAP_FACE_POSITIVE_X;
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
face = D3DCUBEMAP_FACE_NEGATIVE_X;
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
face = D3DCUBEMAP_FACE_POSITIVE_Y;
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
face = D3DCUBEMAP_FACE_NEGATIVE_Y;
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
face = D3DCUBEMAP_FACE_POSITIVE_Z;
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
face = D3DCUBEMAP_FACE_NEGATIVE_Z;
break;
default: UNREACHABLE();
}
return face;
}
DWORD ConvertColorMask(bool red, bool green, bool blue, bool alpha)
{
return (red ? D3DCOLORWRITEENABLE_RED : 0) |
(green ? D3DCOLORWRITEENABLE_GREEN : 0) |
(blue ? D3DCOLORWRITEENABLE_BLUE : 0) |
(alpha ? D3DCOLORWRITEENABLE_ALPHA : 0);
}
D3DTEXTUREFILTERTYPE ConvertMagFilter(GLenum magFilter, float maxAnisotropy)
{
if (maxAnisotropy > 1.0f)
{
return D3DTEXF_ANISOTROPIC;
}
D3DTEXTUREFILTERTYPE d3dMagFilter = D3DTEXF_POINT;
switch (magFilter)
{
case GL_NEAREST: d3dMagFilter = D3DTEXF_POINT; break;
case GL_LINEAR: d3dMagFilter = D3DTEXF_LINEAR; break;
default: UNREACHABLE();
}
return d3dMagFilter;
}
void ConvertMinFilter(GLenum minFilter, D3DTEXTUREFILTERTYPE *d3dMinFilter, D3DTEXTUREFILTERTYPE *d3dMipFilter, float maxAnisotropy)
{
switch (minFilter)
{
case GL_NEAREST:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_NONE;
break;
case GL_LINEAR:
*d3dMinFilter = D3DTEXF_LINEAR;
*d3dMipFilter = D3DTEXF_NONE;
break;
case GL_NEAREST_MIPMAP_NEAREST:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_POINT;
break;
case GL_LINEAR_MIPMAP_NEAREST:
*d3dMinFilter = D3DTEXF_LINEAR;
*d3dMipFilter = D3DTEXF_POINT;
break;
case GL_NEAREST_MIPMAP_LINEAR:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_LINEAR;
break;
case GL_LINEAR_MIPMAP_LINEAR:
*d3dMinFilter = D3DTEXF_LINEAR;
*d3dMipFilter = D3DTEXF_LINEAR;
break;
default:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_NONE;
UNREACHABLE();
}
if (maxAnisotropy > 1.0f)
{
*d3dMinFilter = D3DTEXF_ANISOTROPIC;
}
}
D3DFORMAT ConvertRenderbufferFormat(GLenum format)
{
switch (format)
{
case GL_NONE: return D3DFMT_NULL;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGBA8_OES: return D3DFMT_A8R8G8B8;
case GL_RGB565: return D3DFMT_R5G6B5;
case GL_RGB8_OES: return D3DFMT_X8R8G8B8;
case GL_DEPTH_COMPONENT16:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES: return D3DFMT_D24S8;
default: UNREACHABLE(); return D3DFMT_A8R8G8B8;
}
}
D3DMULTISAMPLE_TYPE GetMultisampleTypeFromSamples(GLsizei samples)
{
if (samples <= 1)
return D3DMULTISAMPLE_NONE;
else
return (D3DMULTISAMPLE_TYPE)samples;
}
}
namespace d3d9_gl
{
unsigned int GetStencilSize(D3DFORMAT stencilFormat)
{
if (stencilFormat == D3DFMT_INTZ)
{
return 8;
}
switch(stencilFormat)
{
case D3DFMT_D24FS8:
case D3DFMT_D24S8:
return 8;
case D3DFMT_D24X4S4:
return 4;
case D3DFMT_D15S1:
return 1;
case D3DFMT_D16_LOCKABLE:
case D3DFMT_D32:
case D3DFMT_D24X8:
case D3DFMT_D32F_LOCKABLE:
case D3DFMT_D16:
return 0;
//case D3DFMT_D32_LOCKABLE: return 0; // DirectX 9Ex only
//case D3DFMT_S8_LOCKABLE: return 8; // DirectX 9Ex only
default:
return 0;
}
}
unsigned int GetAlphaSize(D3DFORMAT colorFormat)
{
switch (colorFormat)
{
case D3DFMT_A16B16G16R16F:
return 16;
case D3DFMT_A32B32G32R32F:
return 32;
case D3DFMT_A2R10G10B10:
return 2;
case D3DFMT_A8R8G8B8:
return 8;
case D3DFMT_A1R5G5B5:
return 1;
case D3DFMT_X8R8G8B8:
case D3DFMT_R5G6B5:
return 0;
default:
return 0;
}
}
GLsizei GetSamplesFromMultisampleType(D3DMULTISAMPLE_TYPE type)
{
if (type == D3DMULTISAMPLE_NONMASKABLE)
return 0;
else
return type;
}
bool IsFormatChannelEquivalent(D3DFORMAT d3dformat, GLenum format)
{
switch (d3dformat)
{
case D3DFMT_L8:
return (format == GL_LUMINANCE);
case D3DFMT_A8L8:
return (format == GL_LUMINANCE_ALPHA);
case D3DFMT_DXT1:
return (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
case D3DFMT_DXT3:
return (format == GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE);
case D3DFMT_DXT5:
return (format == GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE);
case D3DFMT_A8R8G8B8:
case D3DFMT_A16B16G16R16F:
case D3DFMT_A32B32G32R32F:
return (format == GL_RGBA || format == GL_BGRA_EXT);
case D3DFMT_X8R8G8B8:
return (format == GL_RGB);
default:
if (d3dformat == D3DFMT_INTZ && gl::IsDepthTexture(format))
return true;
return false;
}
}
GLenum ConvertBackBufferFormat(D3DFORMAT format)
{
switch (format)
{
case D3DFMT_A4R4G4B4: return GL_RGBA4;
case D3DFMT_A8R8G8B8: return GL_RGBA8_OES;
case D3DFMT_A1R5G5B5: return GL_RGB5_A1;
case D3DFMT_R5G6B5: return GL_RGB565;
case D3DFMT_X8R8G8B8: return GL_RGB8_OES;
default:
UNREACHABLE();
}
return GL_RGBA4;
}
GLenum ConvertDepthStencilFormat(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
{
return GL_DEPTH24_STENCIL8_OES;
}
switch (format)
{
case D3DFMT_D16:
case D3DFMT_D24X8:
return GL_DEPTH_COMPONENT16;
case D3DFMT_D24S8:
return GL_DEPTH24_STENCIL8_OES;
case D3DFMT_UNKNOWN:
return GL_NONE;
default:
UNREACHABLE();
}
return GL_DEPTH24_STENCIL8_OES;
}
GLenum ConvertRenderTargetFormat(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
{
return GL_DEPTH24_STENCIL8_OES;
}
switch (format)
{
case D3DFMT_A4R4G4B4: return GL_RGBA4;
case D3DFMT_A8R8G8B8: return GL_RGBA8_OES;
case D3DFMT_A1R5G5B5: return GL_RGB5_A1;
case D3DFMT_R5G6B5: return GL_RGB565;
case D3DFMT_X8R8G8B8: return GL_RGB8_OES;
case D3DFMT_D16:
case D3DFMT_D24X8:
return GL_DEPTH_COMPONENT16;
case D3DFMT_D24S8:
return GL_DEPTH24_STENCIL8_OES;
case D3DFMT_UNKNOWN:
return GL_NONE;
default:
UNREACHABLE();
}
return GL_RGBA4;
}
GLenum GetEquivalentFormat(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
return GL_DEPTH24_STENCIL8_OES;
if (format == D3DFMT_NULL)
return GL_NONE;
switch (format)
{
case D3DFMT_A4R4G4B4: return GL_RGBA4;
case D3DFMT_A8R8G8B8: return GL_RGBA8_OES;
case D3DFMT_A1R5G5B5: return GL_RGB5_A1;
case D3DFMT_R5G6B5: return GL_RGB565;
case D3DFMT_X8R8G8B8: return GL_RGB8_OES;
case D3DFMT_D16: return GL_DEPTH_COMPONENT16;
case D3DFMT_D24S8: return GL_DEPTH24_STENCIL8_OES;
case D3DFMT_UNKNOWN: return GL_NONE;
case D3DFMT_DXT1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case D3DFMT_DXT3: return GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
case D3DFMT_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
case D3DFMT_A32B32G32R32F: return GL_RGBA32F_EXT;
case D3DFMT_A16B16G16R16F: return GL_RGBA16F_EXT;
case D3DFMT_L8: return GL_LUMINANCE8_EXT;
case D3DFMT_A8L8: return GL_LUMINANCE8_ALPHA8_EXT;
default: UNREACHABLE();
return GL_NONE;
}
}
}
namespace d3d9
{
bool IsCompressedFormat(D3DFORMAT surfaceFormat)
{
switch(surfaceFormat)
{
case D3DFMT_DXT1:
case D3DFMT_DXT2:
case D3DFMT_DXT3:
case D3DFMT_DXT4:
case D3DFMT_DXT5:
return true;
default:
return false;
}
}
size_t ComputeRowSize(D3DFORMAT format, unsigned int width)
{
if (format == D3DFMT_INTZ)
{
return 4 * width;
}
switch (format)
{
case D3DFMT_L8:
return 1 * width;
case D3DFMT_A8L8:
return 2 * width;
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
return 4 * width;
case D3DFMT_A16B16G16R16F:
return 8 * width;
case D3DFMT_A32B32G32R32F:
return 16 * width;
case D3DFMT_DXT1:
return 8 * ((width + 3) / 4);
case D3DFMT_DXT3:
case D3DFMT_DXT5:
return 16 * ((width + 3) / 4);
default:
UNREACHABLE();
return 0;
}
}
}
| 28.273453 | 132 | 0.641864 | viewdy |
b7f3356d2e71d6734f46b3d88fcccf7bcd40ff47 | 287 | cpp | C++ | framework/src/Core/Network/Tcp/TcpClient.cpp | gautier-lefebvre/cppframework | bc1c3405913343274d79240b17ab75ae3f2adf56 | [
"MIT"
] | null | null | null | framework/src/Core/Network/Tcp/TcpClient.cpp | gautier-lefebvre/cppframework | bc1c3405913343274d79240b17ab75ae3f2adf56 | [
"MIT"
] | 3 | 2015-12-21T09:04:49.000Z | 2015-12-21T19:22:47.000Z | framework/src/Core/Network/Tcp/TcpClient.cpp | gautier-lefebvre/cppframework | bc1c3405913343274d79240b17ab75ae3f2adf56 | [
"MIT"
] | null | null | null | #include "Core/Network/Tcp/TcpClient.hh"
using namespace fwk;
TcpClient::TcpClient(const std::string& hostname, uint16_t port, TcpSocketStream* socket):
Lockable(),
hostname(hostname),
port(port),
socket(socket),
active(false),
events()
{}
TcpClient::~TcpClient(void) {}
| 19.133333 | 90 | 0.714286 | gautier-lefebvre |
b7f4b488d5a57aa67fba4e99201a3bf0ded49aab | 1,650 | cpp | C++ | potrace/src/ossimPotraceToolFactory.cpp | dardok/ossim-plugins | 3406ffed9fcab88fe4175b845381611ac4122c81 | [
"MIT"
] | 12 | 2016-09-09T01:24:12.000Z | 2022-01-09T21:45:58.000Z | potrace/src/ossimPotraceToolFactory.cpp | dardok/ossim-plugins | 3406ffed9fcab88fe4175b845381611ac4122c81 | [
"MIT"
] | 5 | 2016-02-04T16:10:40.000Z | 2021-06-29T05:00:29.000Z | potrace/src/ossimPotraceToolFactory.cpp | dardok/ossim-plugins | 3406ffed9fcab88fe4175b845381611ac4122c81 | [
"MIT"
] | 20 | 2015-11-17T11:46:22.000Z | 2021-11-12T19:23:54.000Z | //**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <ossim/util/ossimToolRegistry.h>
#include <potrace/src/ossimPotraceTool.h>
#include <potrace/src/ossimPotraceToolFactory.h>
using namespace std;
ossimPotraceToolFactory* ossimPotraceToolFactory::s_instance = 0;
ossimPotraceToolFactory* ossimPotraceToolFactory::instance()
{
if (!s_instance)
s_instance = new ossimPotraceToolFactory;
return s_instance;
}
ossimPotraceToolFactory::ossimPotraceToolFactory()
{
}
ossimPotraceToolFactory::~ossimPotraceToolFactory()
{
ossimToolRegistry::instance()->unregisterFactory(this);
}
ossimTool* ossimPotraceToolFactory::createTool(const std::string& argName) const
{
ossimString utilName (argName);
utilName.downcase();
if ((utilName == "potrace") || (argName == "ossimPotraceTool"))
return new ossimPotraceTool;
return 0;
}
void ossimPotraceToolFactory::getCapabilities(std::map<std::string, std::string>& capabilities) const
{
capabilities.insert(pair<string, string>("potrace", ossimPotraceTool::DESCRIPTION));
}
std::map<std::string, std::string> ossimPotraceToolFactory::getCapabilities() const
{
std::map<std::string, std::string> result;
getCapabilities(result);
return result;
}
void ossimPotraceToolFactory::getTypeNameList(vector<ossimString>& typeList) const
{
typeList.push_back("ossimPotraceTool");
}
| 27.966102 | 101 | 0.666061 | dardok |
b7f5a6353f521eeca03324ef9ee2f41d8efe1c7a | 2,578 | cpp | C++ | Practice/2018/2018.12.6/Luogu3835.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.12.6/Luogu3835.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.12.6/Luogu3835.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=505000*50;
const int inf=2147483647;
class Treap
{
public:
int key,size,ch[2];
};
int nodecnt;
Treap T[maxN];
int root[maxN];
int random(int l,int r);
int Newnode(int key);
int Copynode(int id);
void Init();
void Update(int x);
void Split(int now,int k,int &x,int &y);
int Merge(int x,int y);
int main(){
freopen("td.in","r",stdin);
srand(20010622);
int TTT;scanf("%d",&TTT);
Init();
for (int ti=1;ti<=TTT;ti++){
int vi,opt,key;scanf("%d%d%d",&vi,&opt,&key);
if (opt==1){
int x,y;Split(root[vi],key,x,y);
int z=Newnode(key);
root[ti]=Merge(Merge(x,z),y);
}
if (opt==2){
int x,y,z;Split(root[vi],key,x,z);
Split(x,key-1,x,y);
root[ti]=Merge(Merge(x,Merge(T[y].ch[0],T[y].ch[1])),z);
}
if (opt==3){
int x,y;Split(root[vi],key-1,x,y);
printf("%d\n",T[x].size);
root[ti]=Merge(x,y);
}
if (opt==4){
int now=root[vi];++key;
do{
if (T[T[now].ch[0]].size>=key) now=T[now].ch[0];
else if (T[T[now].ch[0]].size+1==key) break;
else key-=T[T[now].ch[0]].size+1,now=T[now].ch[1];
}
while (1);
printf("%d\n",T[now].key);
root[ti]=root[vi];
}
if (opt==5){
int x,y;Split(root[vi],key-1,x,y);
int now=x;while (T[now].ch[1]) now=T[now].ch[1];
printf("%d\n",T[now].key);root[ti]=Merge(x,y);
}
if (opt==6){
int x,y;Split(root[vi],key,x,y);
int now=y;while (T[now].ch[0]) now=T[now].ch[0];
printf("%d\n",T[now].key);root[ti]=Merge(x,y);
}
}
return 0;
}
int random(int l,int r){
double dou=1.0*rand()/RAND_MAX;
return min(r,(int)(dou*(r-l+1))+l);
}
int Newnode(int key){
int id=++nodecnt;
T[id].ch[0]=T[id].ch[1]=0;T[id].size=1;
T[id].key=key;return id;
}
int Copynode(int id){
T[++nodecnt]=T[id];return nodecnt;
}
void Init(){
int x=Newnode(-2147483647),y=Newnode(2147483647);
root[0]=x;T[x].ch[1]=y;Update(x);return;
}
void Update(int x){
T[x].size=T[T[x].ch[0]].size+T[T[x].ch[1]].size+1;
return;
}
void Split(int now,int k,int &x,int &y){
if (now==0){
x=y=0;return;
}
if (T[now].key<=k){
x=Copynode(now);Split(T[now].ch[1],k,T[x].ch[1],y);Update(x);
}
else{
y=Copynode(now);Split(T[now].ch[0],k,x,T[y].ch[0]);Update(y);
}
return;
}
int Merge(int x,int y){
if ((x==0)||(y==0)) return x+y;
int z;
if (random(1,T[x].size+T[y].size)<=T[x].size){
z=x;T[z].ch[1]=Merge(T[x].ch[1],y);
}
else{
z=y;T[z].ch[0]=Merge(x,T[y].ch[0]);
}
Update(z);return z;
}
| 20.140625 | 63 | 0.579131 | SYCstudio |
b7f66fd8067cc2de00df33f7a1c7dc50d7ca966a | 5,096 | cpp | C++ | RX64M/rx64m_DA_sample/main.cpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 56 | 2015-06-04T14:15:38.000Z | 2022-03-01T22:58:49.000Z | RX64M/rx64m_DA_sample/main.cpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 30 | 2019-07-27T11:03:14.000Z | 2021-12-14T09:59:57.000Z | RX64M/rx64m_DA_sample/main.cpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 15 | 2017-06-24T11:33:39.000Z | 2021-12-07T07:26:58.000Z | //=====================================================================//
/*! @file
@brief RX64M D/A 出力サンプル @n
・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する。@n
・DA0(P03)、DA1(P05) からアナログ出力する。@n
・サンプリング間隔は 48KHz @n
・コンソールから、周波数を入力すると、その周波数で sin/cos @n
を出力する。
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_mgr.hpp"
#include "common/fixed_fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/delay.hpp"
#include "common/command.hpp"
#include "common/tpu_io.hpp"
#include "common/intmath.hpp"
// ソフトウェアー(タイマー割り込みタスク)で転送を行う場合に有効にする。
// ※無効にした場合、DMA転送で行われる。
// #define SOFT_TRANS
namespace {
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::cmt_mgr<device::CMT0> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 128> BUFFER;
typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI;
SCI sci_;
utils::command<256> cmd_;
/// DMAC 終了割り込み
class dmac_term_task {
volatile uint32_t count_;
public:
dmac_term_task() : count_(0) { }
void operator() () {
// DMA を再スタート
device::DMAC0::DMCNT.DTE = 1; // DMA 再開
++count_;
}
uint32_t get_count() const { return count_; }
};
typedef device::dmac_mgr<device::DMAC0, dmac_term_task> DMAC_MGR;
DMAC_MGR dmac_mgr_;
typedef device::R12DA DAC;
typedef device::dac_out<DAC> DAC_OUT;
DAC_OUT dac_out_;
struct wave_t {
uint16_t l; ///< D/A CH0
uint16_t r; ///< D/A CH1
};
static const uint32_t WAVE_NUM = 1024;
wave_t wave_[WAVE_NUM];
// 48KHz サンプリング割り込み
class timer_task {
uint16_t pos_;
public:
timer_task() : pos_(0) { }
void operator() () {
const wave_t& w = wave_[pos_];
dac_out_.out0(w.l);
dac_out_.out1(w.r);
++pos_;
pos_ %= WAVE_NUM;
}
uint16_t get_pos() const { return pos_; }
};
#ifdef SOFT_TRANS
typedef device::tpu_io<device::TPU0, timer_task> TPU0;
#else
typedef device::tpu_io<device::TPU0, utils::null_task> TPU0;
#endif
TPU0 tpu0_;
bool init_ = false;
float freq_ = 100.0f;
uint32_t wpos_ = 0;
intmath::sincos_t sico_(0);
void service_sin_cos_()
{
uint32_t pos = (dmac_mgr_.get_count() & 0x3ff) ^ 0x3ff;
int32_t gain_shift = 16;
if(!init_) {
sico_.x = static_cast<int64_t>(32767) << gain_shift;
sico_.y = 0;
wpos_ = pos & 0x3ff;
init_ = true;
}
int32_t dt = static_cast<int32_t>(48000.0f / freq_);
uint32_t d = pos - wpos_;
if(d >= WAVE_NUM) d += WAVE_NUM;
for(uint32_t i = 0; i < d; ++i) {
wave_t w;
w.l = (sico_.x >> gain_shift) + 32768;
w.r = (sico_.y >> gain_shift) + 32768;
wave_[(wpos_ + (WAVE_NUM / 2)) & (WAVE_NUM - 1)] = w;
++wpos_;
wpos_ &= WAVE_NUM - 1;
intmath::build_sincos(sico_, dt);
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
char sci_getch(void)
{
return sci_.getch();
}
void sci_puts(const char *str)
{
sci_.puts(str);
}
uint16_t sci_length(void)
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
device::system_io<>::boost_master_clock();
{ // タイマー設定(100Hz)
uint8_t intr_level = 4;
cmt_.start(100, intr_level);
}
{ // SCI 設定
uint8_t intr_level = 2;
sci_.start(115200, intr_level);
}
{ // サンプリング・タイマー設定
uint8_t intr_level = 5;
if(!tpu0_.start(48000, intr_level)) {
utils::format("TPU0 start error...\n");
}
}
{ // 内臓12ビット D/A の設定
bool amp_ena = true;
dac_out_.start(DAC_OUT::output::CH0_CH1, amp_ena);
dac_out_.out0(32767);
dac_out_.out1(32767);
#if 0
int32_t gain_shift = 16;
intmath::sincos_t sico(static_cast<int64_t>(32767) << gain_shift);
for(uint32_t i = 0; i < WAVE_NUM; ++i) {
wave_t w;
#if 0
if(i & 1) {
w.l = 0xffff;
w.r = 0x0000;
} else {
w.l = 0x0000;
w.r = 0xffff;
}
#else
w.l = (sico.x >> gain_shift) + 32768;
w.r = (sico.y >> gain_shift) + 32768;
intmath::build_sincos(sico, WAVE_NUM / 4);
#endif
wave_[i] = w;
}
#endif
}
#ifndef SOFT_TRANS
{ // DMAC マネージャー開始
uint8_t intr_level = 4;
bool cpu_intr = true;
auto ret = dmac_mgr_.start(tpu0_.get_intr_vec(), DMAC_MGR::trans_type::SP_DN_32,
reinterpret_cast<uint32_t>(wave_), DAC::DADR0.address(), WAVE_NUM, intr_level, cpu_intr);
if(!ret) {
utils::format("DMAC Not start...\n");
}
}
#endif
utils::format("RX64M Internal D/A stream sample start\n");
cmd_.set_prompt("# ");
LED::DIR = 1;
uint32_t cnt = 0;
while(1) {
cmt_.sync();
service_sin_cos_();
// uint32_t pos = dmac_mgr_.get_count() & 0x3ff;
// utils::format("WP: %d\n") % pos;
if(cmd_.service()) {
char tmp[32];
if(cmd_.get_word(0, tmp, sizeof(tmp))) {
float freq = 0.0f;
if((utils::input("%f", tmp) % freq).status()) {
freq_ = freq;
init_ = false;
}
}
}
++cnt;
if(cnt >= 30) {
cnt = 0;
}
LED::P = (cnt < 10) ? 0 : 1;
}
}
| 20.465863 | 92 | 0.616366 | hirakuni45 |
b7fa247532e41f32d46e4fe210c23a69688f4f49 | 6,175 | cc | C++ | libmemcached/touch.cc | bureado/libmemcached | 3f27e2b935a0580ff3fa7c098040ce96083fa70f | [
"BSD-3-Clause"
] | null | null | null | libmemcached/touch.cc | bureado/libmemcached | 3f27e2b935a0580ff3fa7c098040ce96083fa70f | [
"BSD-3-Clause"
] | 1 | 2021-03-09T05:01:19.000Z | 2021-03-09T05:01:19.000Z | libmemcached/touch.cc | bureado/libmemcached | 3f27e2b935a0580ff3fa7c098040ce96083fa70f | [
"BSD-3-Clause"
] | 2 | 2015-02-03T02:37:59.000Z | 2020-10-20T09:12:02.000Z | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Libmemcached library
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* Copyright (C) 2006-2009 Brian Aker 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.
*
* * The names of its contributors 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 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 <libmemcached/common.h>
#include <libmemcached/memcached/protocol_binary.h>
static memcached_return_t ascii_touch(memcached_server_write_instance_st instance,
const char *key, size_t key_length,
time_t expiration)
{
char expiration_buffer[MEMCACHED_MAXIMUM_INTEGER_DISPLAY_LENGTH +1];
int expiration_buffer_length= snprintf(expiration_buffer, sizeof(expiration_buffer), " %llu", (unsigned long long)expiration);
if (size_t(expiration_buffer_length) >= sizeof(expiration_buffer) or expiration_buffer_length < 0)
{
return memcached_set_error(*instance, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT,
memcached_literal_param("snprintf(MEMCACHED_MAXIMUM_INTEGER_DISPLAY_LENGTH)"));
}
libmemcached_io_vector_st vector[]=
{
{ NULL, 0 },
{ memcached_literal_param("touch ") },
{ memcached_array_string(instance->root->_namespace), memcached_array_size(instance->root->_namespace) },
{ key, key_length },
{ expiration_buffer, expiration_buffer_length },
{ memcached_literal_param("\r\n") }
};
memcached_return_t rc;
if (memcached_failed(rc= memcached_vdo(instance, vector, 6, true)))
{
memcached_io_reset(instance);
return memcached_set_error(*instance, MEMCACHED_WRITE_FAILURE, MEMCACHED_AT);
}
return rc;
}
static memcached_return_t binary_touch(memcached_server_write_instance_st instance,
const char *key, size_t key_length,
time_t expiration)
{
protocol_binary_request_touch request= {}; //{.bytes= {0}};
request.message.header.request.magic= PROTOCOL_BINARY_REQ;
request.message.header.request.opcode= PROTOCOL_BINARY_CMD_TOUCH;
request.message.header.request.extlen= 4;
request.message.header.request.keylen= htons((uint16_t)(key_length +memcached_array_size(instance->root->_namespace)));
request.message.header.request.datatype= PROTOCOL_BINARY_RAW_BYTES;
request.message.header.request.bodylen= htonl((uint32_t)(key_length +memcached_array_size(instance->root->_namespace) +request.message.header.request.extlen));
request.message.body.expiration= htonl((uint32_t) expiration);
libmemcached_io_vector_st vector[]=
{
{ NULL, 0 },
{ request.bytes, sizeof(request.bytes) },
{ memcached_array_string(instance->root->_namespace), memcached_array_size(instance->root->_namespace) },
{ key, key_length }
};
memcached_return_t rc;
if (memcached_failed(rc= memcached_vdo(instance, vector, 4, true)))
{
memcached_io_reset(instance);
return memcached_set_error(*instance, MEMCACHED_WRITE_FAILURE, MEMCACHED_AT);
}
return rc;
}
memcached_return_t memcached_touch(memcached_st *ptr,
const char *key, size_t key_length,
time_t expiration)
{
return memcached_touch_by_key(ptr, key, key_length, key, key_length, expiration);
}
memcached_return_t memcached_touch_by_key(memcached_st *ptr,
const char *group_key, size_t group_key_length,
const char *key, size_t key_length,
time_t expiration)
{
LIBMEMCACHED_MEMCACHED_TOUCH_START();
memcached_return_t rc;
if (memcached_failed(rc= initialize_query(ptr, true)))
{
return rc;
}
if (memcached_failed(rc= memcached_validate_key_length(key_length, ptr->flags.binary_protocol)))
{
return rc;
}
uint32_t server_key= memcached_generate_hash_with_redistribution(ptr, group_key, group_key_length);
memcached_server_write_instance_st instance= memcached_server_instance_fetch(ptr, server_key);
if (ptr->flags.binary_protocol)
{
rc= binary_touch(instance, key, key_length, expiration);
}
else
{
rc= ascii_touch(instance, key, key_length, expiration);
}
if (memcached_failed(rc))
{
return memcached_set_error(*instance, rc, MEMCACHED_AT, memcached_literal_param("Error occcured while writing touch command to server"));
}
char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
rc= memcached_response(instance, buffer, sizeof(buffer), NULL);
if (rc == MEMCACHED_SUCCESS or rc == MEMCACHED_NOTFOUND)
{
return rc;
}
return memcached_set_error(*instance, rc, MEMCACHED_AT, memcached_literal_param("Error occcured while reading response"));
}
| 39.583333 | 161 | 0.717733 | bureado |
b7fb2c87216fb9c4de64639c62c267e25e91802c | 6,684 | hpp | C++ | CvGameCoreDLL/Boost-1.32.0/include/boost/regex/config/allocator.hpp | macaurther/DOCUSA | 40586727c351d1b1130c05c2d4648cca3a8bacf5 | [
"MIT"
] | 93 | 2015-11-20T04:13:36.000Z | 2022-03-24T00:03:08.000Z | CvGameCoreDLL/Boost-1.32.0/include/boost/regex/config/allocator.hpp | macaurther/DOCUSA | 40586727c351d1b1130c05c2d4648cca3a8bacf5 | [
"MIT"
] | 206 | 2015-11-09T00:27:15.000Z | 2021-12-04T19:05:18.000Z | CvGameCoreDLL/Boost-1.32.0/include/boost/regex/config/allocator.hpp | dguenms/Dawn-of-Civilization | 1c4f510af97a869637cddb4c0859759158cea5ce | [
"MIT"
] | 117 | 2015-11-08T02:43:46.000Z | 2022-02-12T06:29:00.000Z | /*
*
* Copyright (c) 2001
* Dr John Maddock
*
* Use, modification and distribution are subject to 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_DETAIL_ALLOCATOR_HPP
#define BOOST_DETAIL_ALLOCATOR_HPP
#include <boost/config.hpp>
#include <cstdlib>
#include <new>
#include <assert.h>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::ptrdiff_t;
using ::size_t;
}
#endif
// see if we have SGI alloc class:
#if defined(BOOST_NO_STD_ALLOCATOR) && (defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) || defined(__GLIBCPP__) || defined(__STL_CONFIG_H))
# define BOOST_HAVE_SGI_ALLOCATOR
# include <memory>
# if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)
namespace boost{ namespace detail{
typedef std::__sgi_alloc alloc_type;
}}
# else
namespace boost{ namespace detail{
typedef std::alloc alloc_type;
}}
# endif
#endif
namespace boost{ namespace detail{
template <class T>
void allocator_construct(T* p, const T& t)
{ new (p) T(t); }
template <class T>
void allocator_destroy(T* p)
{
(void)p; // warning suppression
p->~T();
}
} }
#if !defined(BOOST_NO_STD_ALLOCATOR)
#include <memory>
#define BOOST_DEFAULT_ALLOCATOR(T) std::allocator< T >
namespace boost{ namespace detail{
template <class T, class A>
struct rebind_allocator
{
typedef typename A::template rebind<T> binder;
typedef typename binder::other type;
};
} // namespace detail
} // namespace boost
#elif !defined(BOOST_NO_MEMBER_TEMPLATES) && !defined(__SUNPRO_CC)
// no std::allocator, but the compiler supports the necessary syntax,
// write our own allocator instead:
#define BOOST_DEFAULT_ALLOCATOR(T) ::boost::detail::allocator< T >
namespace boost{ namespace detail{
template <class T>
class allocator
{
public:
typedef T value_type;
typedef value_type * pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
template <class U>
struct rebind
{
typedef allocator<U> other;
};
allocator(){}
template <class U>
allocator(const allocator<U>&){}
allocator(const allocator&){}
template <class U>
allocator& operator=(const allocator<U>&)
{ return *this; }
~allocator(){}
pointer address(reference x) { return &x; }
const_pointer address(const_reference x) const { return &x; }
pointer allocate(size_type n, const void* = 0)
{
#ifdef BOOST_HAVE_SGI_ALLOCATOR
return n != 0 ?
reinterpret_cast<pointer>(alloc_type::allocate(n * sizeof(value_type)))
: 0;
#else
return n != 0 ?
reinterpret_cast<pointer>(::operator new(n * sizeof(value_type)))
: 0;
#endif
}
void deallocate(pointer p, size_type n)
{
#ifdef BOOST_HAVE_SGI_ALLOCATOR
assert( (p == 0) == (n == 0) );
if (p != 0)
alloc_type::deallocate((void*)p, n);
#else
assert( (p == 0) == (n == 0) );
if (p != 0)
::operator delete((void*)p);
#endif
}
size_type max_size() const
{ return size_t(-1) / sizeof(value_type); }
void construct(pointer p, const T& val) const
{ allocator_construct(p, val); }
void destroy(pointer p) const
{ allocator_destroy(p); }
};
template <class T, class A>
struct rebind_allocator
{
typedef typename A::template rebind<T> binder;
typedef typename binder::other type;
};
} // namespace detail
} // namespace boost
#else
// no std::allocator, use workaround version instead,
// each allocator class must derive from a base class
// that allocates blocks of bytes:
#define BOOST_DEFAULT_ALLOCATOR(T) ::boost::detail::allocator_adapter<T, ::boost::detail::simple_alloc>
namespace boost{ namespace detail{
class simple_alloc
{
public:
typedef void value_type;
typedef value_type * pointer;
typedef const void* const_pointer;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
simple_alloc(){}
simple_alloc(const simple_alloc&){}
~simple_alloc(){}
pointer allocate(size_type n, const void* = 0)
{
#ifdef BOOST_HAVE_SGI_ALLOCATOR
return n != 0 ?
reinterpret_cast<pointer>(alloc_type::allocate(n))
: 0;
#else
return n != 0 ?
reinterpret_cast<pointer>(::operator new(n))
: 0;
#endif
}
void deallocate(pointer p, size_type n)
{
#ifdef BOOST_HAVE_SGI_ALLOCATOR
assert( (p == 0) == (n == 0) );
if (p != 0)
alloc_type::deallocate((void*)p, n);
#else
assert( (p == 0) == (n == 0) );
if (p != 0)
::operator delete((void*)p);
#endif
}
};
template <class T, class Base>
class allocator_adapter : public Base
{
public:
typedef T value_type;
typedef value_type * pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef Base base_type;
allocator_adapter(){}
allocator_adapter(const base_type& x) : Base(x){}
allocator_adapter& operator=(const base_type& x)
{
*(static_cast<base_type*>(this)) = x;
return *this;
}
~allocator_adapter(){}
pointer address(reference x) { return &x; }
const_pointer address(const_reference x) const { return &x; }
pointer allocate(size_type n, const void* = 0)
{
return n != 0 ?
reinterpret_cast<pointer>(base_type::allocate(n * sizeof(value_type)))
: 0;
}
void deallocate(pointer p, size_type n)
{
assert( (p == 0) == (n == 0) );
if (p != 0)
static_cast<base_type*>(this)->deallocate((void*)p, n * sizeof(value_type));
}
size_type max_size() const
{ return size_t(-1) / sizeof(value_type); }
void construct(pointer p, const T& val) const
{ allocator_construct(p, val); }
void destroy(pointer p) const
{ allocator_destroy(p); }
};
template <class T, class A>
struct rebind_allocator
{
typedef allocator_adapter<T, typename A::base_type> type;
};
} // namespace detail
} // namespace boost
#endif
#endif // include guard
| 23.702128 | 145 | 0.620586 | macaurther |
b7fb71f17b94d5234b88b3ada0117f1c78837393 | 8,036 | cpp | C++ | bindings/java/LSFJavaTest/jni/org_allseen_lsf_test_TransitionEffectManagerCallbackTest.cpp | alljoyn/lighting-apps | f423a252d64cbd41d575dcfe554a1cb5b49fa307 | [
"Apache-2.0"
] | null | null | null | bindings/java/LSFJavaTest/jni/org_allseen_lsf_test_TransitionEffectManagerCallbackTest.cpp | alljoyn/lighting-apps | f423a252d64cbd41d575dcfe554a1cb5b49fa307 | [
"Apache-2.0"
] | null | null | null | bindings/java/LSFJavaTest/jni/org_allseen_lsf_test_TransitionEffectManagerCallbackTest.cpp | alljoyn/lighting-apps | f423a252d64cbd41d575dcfe554a1cb5b49fa307 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
******************************************************************************/
#include <stddef.h>
#include <qcc/Debug.h>
#include <qcc/Log.h>
#include "XTransitionEffectManagerCallback.h"
#include "XCppTestDelegator.h"
#include "JEnum.h"
#include "JEnumArray.h"
#include "JLampDetails.h"
#include "XTransitionEffectV2.h"
#include "JLampState.h"
#include "JStringArray.h"
#include "NTypes.h"
#include "NUtil.h"
#include "XCppTestDelegator.h"
#include "org_allseen_lsf_test_TransitionEffectManagerCallbackTest.h"
#define QCC_MODULE "AJN-LSF-JNI-TEST"
using namespace ajn;
using namespace lsf;
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_getTransitionEffectReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID, jobject jTransitionEffect)
{
return XCppTestDelegator::Call_Void_ResponseCode_String_Object<XTransitionEffectManagerCallback, XTransitionEffectV2, TransitionEffect>(env, jCallback, jResponseCode, jTransitionEffectID, jTransitionEffect, &XTransitionEffectManagerCallback::GetTransitionEffectReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_applyTransitionEffectOnLampsReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID, jobjectArray jLampIDs)
{
return XCppTestDelegator::Call_Void_ResponseCode_String_StringList<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, jLampIDs, &XTransitionEffectManagerCallback::ApplyTransitionEffectOnLampsReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_applyTransitionEffectOnLampGroupsReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID, jobjectArray jLampGroupIDs)
{
return XCppTestDelegator::Call_Void_ResponseCode_String_StringList<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, jLampGroupIDs, &XTransitionEffectManagerCallback::ApplyTransitionEffectOnLampGroupsReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_getAllTransitionEffectIDsReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jobjectArray jTransitionEffectIDs)
{
return XCppTestDelegator::Call_Void_ResponseCode_StringList<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectIDs, &XTransitionEffectManagerCallback::GetAllTransitionEffectIDsReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_updateTransitionEffectReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID)
{
return XCppTestDelegator::Call_Void_ResponseCode_String<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, &XTransitionEffectManagerCallback::UpdateTransitionEffectReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_deleteTransitionEffectReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID)
{
return XCppTestDelegator::Call_Void_ResponseCode_String<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, &XTransitionEffectManagerCallback::DeleteTransitionEffectReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_getTransitionEffectNameReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID, jstring jLanguage, jstring jTransitionEffectName)
{
return XCppTestDelegator::Call_Void_ResponseCode_String_String_String<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, jLanguage, jTransitionEffectName, &XTransitionEffectManagerCallback::GetTransitionEffectNameReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_setTransitionEffectNameReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID, jstring jLanguage)
{
return XCppTestDelegator::Call_Void_ResponseCode_String_String<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, jLanguage, &XTransitionEffectManagerCallback::SetTransitionEffectNameReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_createTransitionEffectReplyCB(JNIEnv *env, jobject thiz, jobject jCallback, jobject jResponseCode, jstring jTransitionEffectID, jlong jTrackingID)
{
return XCppTestDelegator::Call_Void_ResponseCode_String_UInt32<XTransitionEffectManagerCallback>(env, jCallback, jResponseCode, jTransitionEffectID, jTrackingID, &XTransitionEffectManagerCallback::CreateTransitionEffectReplyCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_transitionEffectsNameChangedCB(JNIEnv *env, jobject thiz, jobject jCallback, jobjectArray jTransitionEffectIDs)
{
return XCppTestDelegator::Call_Void_StringList<XTransitionEffectManagerCallback>(env, jCallback, jTransitionEffectIDs, &XTransitionEffectManagerCallback::TransitionEffectsNameChangedCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_transitionEffectsCreatedCB(JNIEnv *env, jobject thiz, jobject jCallback, jobjectArray jTransitionEffectIDs)
{
return XCppTestDelegator::Call_Void_StringList<XTransitionEffectManagerCallback>(env, jCallback, jTransitionEffectIDs, &XTransitionEffectManagerCallback::TransitionEffectsCreatedCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_transitionEffectsUpdatedCB(JNIEnv *env, jobject thiz, jobject jCallback, jobjectArray jTransitionEffectIDs)
{
return XCppTestDelegator::Call_Void_StringList<XTransitionEffectManagerCallback>(env, jCallback, jTransitionEffectIDs, &XTransitionEffectManagerCallback::TransitionEffectsUpdatedCB, __func__);
}
JNIEXPORT
jstring JNICALL Java_org_allseen_lsf_test_TransitionEffectManagerCallbackTest_transitionEffectsDeletedCB(JNIEnv *env, jobject thiz, jobject jCallback, jobjectArray jTransitionEffectIDs)
{
return XCppTestDelegator::Call_Void_StringList<XTransitionEffectManagerCallback>(env, jCallback, jTransitionEffectIDs, &XTransitionEffectManagerCallback::TransitionEffectsDeletedCB, __func__);
}
| 59.088235 | 284 | 0.833001 | alljoyn |
b7fbc13163bcf254debfd31d029e3753edf16856 | 1,161 | hpp | C++ | include/States/SaveState.hpp | thibautcornolti/IndieStudio | 1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7 | [
"MIT"
] | null | null | null | include/States/SaveState.hpp | thibautcornolti/IndieStudio | 1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7 | [
"MIT"
] | null | null | null | include/States/SaveState.hpp | thibautcornolti/IndieStudio | 1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** bomberman
** File description:
** SaveState.hpp
*/
#ifndef BOMBERMAN_SAVESTATE_HPP
#define BOMBERMAN_SAVESTATE_HPP
#include <time.h>
#include "../Abstracts/AState.hpp"
#include "../Abstracts/AMenuSound.hpp"
#define SAVE_BUTTON_NUMBER 2
class SaveState : public AState, public AMenuSound {
public:
explicit SaveState(AStateShare &_share);
~SaveState();
enum Actions {
SAVE = 800,
CANCEL
};
const std::string getName() const override;
void loadButtons();
void unloadButtons();
void load() override;
void unload() override;
void update() override;
void draw() override;
bool applyEventButton(const irr::SEvent &ev, SaveState::Actions id);
irr::gui::IGUIButton *getButton(SaveState::Actions) const;
struct ButtonsDesc {
irr::core::rect<irr::s32> pos;
std::string name;
std::function<bool(SaveState *)> fct;
};
void eventsSetup();
void eventsClean();
void externalEventsClean();
private:
std::vector<irr::gui::IGUIButton *> _buttons;
static const std::map<SaveState::Actions, ButtonsDesc> _descs;
irr::gui::IGUIButton *_name;
bool _eventsActivate;
};
#endif /* !BOMBERMAN_SAVESTATE_HPP */
| 19.677966 | 69 | 0.723514 | thibautcornolti |
b7fcce7a23b53ad27b52bffb490cfaeac7acb822 | 1,400 | cpp | C++ | PAT_B/B1055|集体照|e.g.cpp | FunamiYui/PAT_Code_Akari | 52e06689b6bf8177c43ab9256719258c47e80b25 | [
"MIT"
] | null | null | null | PAT_B/B1055|集体照|e.g.cpp | FunamiYui/PAT_Code_Akari | 52e06689b6bf8177c43ab9256719258c47e80b25 | [
"MIT"
] | null | null | null | PAT_B/B1055|集体照|e.g.cpp | FunamiYui/PAT_Code_Akari | 52e06689b6bf8177c43ab9256719258c47e80b25 | [
"MIT"
] | null | null | null | //example
//对于某一排来说,每次都是左右交替进行人的放置,因此按此排内部的序号来说一定是一侧奇数一侧偶数
//最后从后排往前排一依次输出每排的人的姓名
//将所有人按身高从高到低排序,身高相同时按照姓名字典序从小到大排序
//定义变量num表示当前排的人数,初值为n - (k - 1) * (n / k),即最后一排人数
//再定义变量leftPos表示该排身高最高的人在数组中的编号,于是该排所有人在数组中的编号范围是[leftPos, leftPos + num - 1]
//当处理完一排后,将leftPos加上num即可得到前一排身高最高的人在数组中的编号
//本题必须在最后一行输出换行,否则会有若干组数据"格式错误"
//姓名的数组大小至少需要开9
//本体也可以用双端队列解决,或是使用数组模拟双端队列来实现
//直接做法
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 10010;
struct Person {
char name[10]; //姓名
int height; //身高
} person[maxn];
bool cmp(Person a, Person b) { //先按身高从高到低,再按姓名字典序从小到大
if(a.height != b.height) return a.height > b.height;
else return strcmp(a.name, b.name) < 0;
}
int main() {
int n, k; //n为人数,k为排数
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++) { //输入每个人的姓名和身高
scanf("%s%d", person[i].name, &person[i].height);
}
sort(person, person + n, cmp); //排序
//num为当前排人数,leftPos为当前排的身高最高者的位置
int num = n - (k - 1) * (n / k), leftPos = 0;
while(leftPos < n) { //每次处理一排
for(int i = (num % 2) ? (num - 2) : (num - 1); i >= 1; i -= 2) {
printf("%s ", person[leftPos + i].name); //从最大奇数到最小奇数输出
}
for(int i = 0; i < num; i += 2) {
printf("%s", person[leftPos + i].name); //从最小偶数到最大偶数
if(i < num - 2) printf(" ");
else printf("\n"); //本题必须换行
}
leftPos += num; //前一排的身高最高者的位置
num = n / k; //除最后一排外,前面所有排的人数都是n / k
}
return 0;
}
| 27.45098 | 77 | 0.637857 | FunamiYui |
4d001073e89c0ca5b69ecdd0dc73a9c6bba32baf | 1,318 | cpp | C++ | src/Core/Scripting/ScriptAssembly.cpp | lauriscx/DEngine | 2e64c91f64715dd730f21f27355c3efa7faff85f | [
"MIT"
] | null | null | null | src/Core/Scripting/ScriptAssembly.cpp | lauriscx/DEngine | 2e64c91f64715dd730f21f27355c3efa7faff85f | [
"MIT"
] | null | null | null | src/Core/Scripting/ScriptAssembly.cpp | lauriscx/DEngine | 2e64c91f64715dd730f21f27355c3efa7faff85f | [
"MIT"
] | null | null | null | #include "ScriptAssembly.h"
ScriptAssembly::ScriptAssembly(const std::string& Name, const std::string& AssemblyName) {
//Examples https://cpp.hotexamples.com/examples/-/-/mono_add_internal_call/cpp-mono_add_internal_call-function-examples.html
mono_set_dirs(".", ".");//Set where to search for assembly file.(Location is project file whihc is has kind application or console application(exe)).
m_AssemblyName = AssemblyName;
m_PtrMonoDomain = mono_jit_init(Name.c_str());//Unknow why here we neeed provide this string.
if (m_PtrMonoDomain) {
//Information which is usefull to implement load dll from VFS https://stackoverflow.com/questions/36094802/embeded-mono-load-assemblies-from-memory
m_PtrAssembly = mono_domain_assembly_open(m_PtrMonoDomain, (AssemblyName + std::string(".dll")).c_str());//In feature need change to us VFS
if (m_PtrAssembly) {
m_PtrAssemblyImage = mono_assembly_get_image(m_PtrAssembly);
}
}
}
Class * ScriptAssembly::GetClass(std::string className) {
if (m_PtrAssemblyImage) {
m_Classes[className] = Class(m_PtrAssemblyImage, className, m_AssemblyName);
return &m_Classes[className];
}
return nullptr;
}
ScriptAssembly::~ScriptAssembly() {
if (m_PtrMonoDomain) {
mono_jit_cleanup(m_PtrMonoDomain);//if used mono_jit_init need use mono_jit_clean (probably).
}
}
| 43.933333 | 150 | 0.773141 | lauriscx |
4d002074e04e0dc695f191346860b577a64b5373 | 964 | hpp | C++ | sdl2-sonic-drivers/src/drivers/midi/devices/ScummVM.hpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | 3 | 2021-10-31T14:24:00.000Z | 2022-03-16T08:15:31.000Z | sdl2-sonic-drivers/src/drivers/midi/devices/ScummVM.hpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | 48 | 2020-06-05T11:11:29.000Z | 2022-02-27T23:58:44.000Z | sdl2-sonic-drivers/src/drivers/midi/devices/ScummVM.hpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <drivers/midi/Device.hpp>
#include <drivers/midi/scummvm/MidiDriver_ADLIB.hpp>
#include <memory>
#include <cstdint>
#include <hardware/opl/OPL.hpp>
namespace drivers
{
namespace midi
{
namespace devices
{
/**
* @brief Wrapper around ScummVM MidiDriver
* At the moment support only OPL
* Better rename to OPL?
*/
class ScummVM : public Device
{
public:
explicit ScummVM(std::shared_ptr<hardware::opl::OPL> opl, const bool opl3mode);
~ScummVM();
inline void sendEvent(const audio::midi::MIDIEvent& e) const noexcept override;
inline void sendMessage(const uint8_t msg[], const uint8_t size) const noexcept override;
private:
std::shared_ptr<drivers::midi::scummvm::MidiDriver_ADLIB> _adlib;
};
}
}
}
| 26.777778 | 105 | 0.570539 | Raffaello |
4d013bb873fed2521820894736d56ec8300f55e1 | 5,608 | hpp | C++ | src/math/TEuler.hpp | Tonvey/ceramics | 9735b7579c7970155f4b72b9c8a55f920800f186 | [
"MIT"
] | null | null | null | src/math/TEuler.hpp | Tonvey/ceramics | 9735b7579c7970155f4b72b9c8a55f920800f186 | [
"MIT"
] | null | null | null | src/math/TEuler.hpp | Tonvey/ceramics | 9735b7579c7970155f4b72b9c8a55f920800f186 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <cassert>
#include <cmath>
#include <functional>
#include <initializer_list>
#include "../utils/TProperty.hpp"
#include "TMathUtils.hpp"
#include "../CeramicsPrerequisites.h"
#include "ERotationOrder.h"
CERAMICS_NAMESPACE_BEGIN
template <class T>
struct TEuler
{
typedef T value_type;
typedef TEuler<T> type;
static RotationOrder DefaultOrder;
T x, y, z;
RotationOrder order = XYZ;
TEuler(T x = 0, T y = 0, T z = 0, RotationOrder order = DefaultOrder)
{
this->x = x;
this->y = y;
this->z = z;
this->order = order;
}
void set(T x, T y, T z, RotationOrder order)
{
this->x = x;
this->y = y;
this->z = z;
this->order = order;
// TODO change callback
}
type &operator=(const type &other)
{
this->set(other.x, other.y, other.z, other.order);
return *this;
}
void setFromRotationMatrix(TMatrix<T, 4, 4> m, RotationOrder order = XYZ)
{
auto clamp = TMathUtils<T>::clamp;
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
auto &te = m.elements;
auto m11 = te[0], m12 = te[1], m13 = te[2];
auto m21 = te[4], m22 = te[5], m23 = te[6];
auto m31 = te[8], m32 = te[9], m33 = te[10];
switch (order)
{
case RotationOrder::XYZ:
this->y = std::asin(clamp(m13, -1, 1));
if (std::abs(m13) < 0.9999999)
{
this->x = std::atan2(-m23, m33);
this->z = std::atan2(-m12, m11);
}
else
{
this->x = std::atan2(m32, m22);
this->z = 0;
}
break;
case RotationOrder::YXZ:
this->x = std::asin(-clamp(m23, -1, 1));
if (std::abs(m23) < 0.9999999)
{
this->y = std::atan2(m13, m33);
this->z = std::atan2(m21, m22);
}
else
{
this->y = std::atan2(-m31, m11);
this->z = 0;
}
break;
case RotationOrder::ZXY:
this->x = std::asin(clamp(m32, -1, 1));
if (std::abs(m32) < 0.9999999)
{
this->y = std::atan2(-m31, m33);
this->z = std::atan2(-m12, m22);
}
else
{
this->y = 0;
this->z = std::atan2(m21, m11);
}
break;
case RotationOrder::ZYX:
this->y = std::asin(-clamp(m31, -1, 1));
if (std::abs(m31) < 0.9999999)
{
this->x = std::atan2(m32, m33);
this->z = std::atan2(m21, m11);
}
else
{
this->x = 0;
this->z = std::atan2(-m12, m22);
}
break;
case RotationOrder::YZX:
this->z = std::asin(clamp(m21, -1, 1));
if (std::abs(m21) < 0.9999999)
{
this->x = std::atan2(-m23, m22);
this->y = std::atan2(-m31, m11);
}
else
{
this->x = 0;
this->y = std::atan2(m13, m33);
}
break;
case RotationOrder::XZY:
this->z = std::asin(-clamp(m12, -1, 1));
if (std::abs(m12) < 0.9999999)
{
this->x = std::atan2(m32, m22);
this->y = std::atan2(m13, m11);
}
else
{
this->x = std::atan2(-m23, m33);
this->y = 0;
}
break;
default:
// TODO
// console.warn( 'CERAMICS.Euler: .setFromRotationMatrix()
// encountered an unknown order: ' + order );
break;
}
this->order = order;
}
void setFromQuaternion(TQuaternion<T> q, RotationOrder order = XYZ)
{
auto matrix = TMatrix<T, 4, 4>::makeRotationFromQuaternion(q);
return this->setFromRotationMatrix(matrix, order);
}
void setFromVector3(TVector<T, 3> v, RotationOrder order = XYZ)
{
return this->set(v.x(), v.y(), v.z(), order);
}
void reorder(RotationOrder newOrder)
{
// WARNING: this discards revolution information -bhouston
TQuaternion<T> _quaternion;
_quaternion.setFromEuler(this);
return this->setFromQuaternion(_quaternion, newOrder);
}
bool equals(const type &euler)
{
return (euler->x == this->x) && (euler->y == this->y) &&
(euler->z == this->z) && (euler.order == this->order);
}
template <class array_t>
type &fromArray(array_t array)
{
this->x = array[0];
this->y = array[1];
this->z = array[2];
// if ( array[ 3 ] !== undefined )
this->order = array[3];
return *this;
}
template <class array_t>
array_t toArray(array_t array, int offset)
{
// if ( array === undefined ) array = [];
// if ( offset === undefined ) offset = 0;
array[offset] = this->x;
array[offset + 1] = this->y;
array[offset + 2] = this->z;
array[offset + 3] = this->order;
return array;
}
TVector<T, 3> toVector3()
{
return TVector<T, 3>(this->x, this->y, this->z);
}
};
template <class T>
RotationOrder TEuler<T>::DefaultOrder = XYZ;
CERAMICS_NAMESPACE_END
| 23.464435 | 79 | 0.460057 | Tonvey |
4d02be25c3782f4318044705938fbf4b6608e2b2 | 4,653 | hpp | C++ | deps/boost/include/boost/graph/adj_list_serialize.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 80 | 2021-09-07T12:44:32.000Z | 2022-03-29T01:22:19.000Z | deps/boost/include/boost/graph/adj_list_serialize.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 2 | 2021-12-23T02:49:42.000Z | 2022-02-15T05:28:24.000Z | deps/boost/include/boost/graph/adj_list_serialize.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 25 | 2021-09-14T06:24:25.000Z | 2022-03-20T06:55:07.000Z | //=======================================================================
// Copyright 2005 Jeremy G. Siek
// Authors: Jeremy G. Siek
//
// 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_GRAPH_ADJ_LIST_SERIALIZE_HPP
#define BOOST_GRAPH_ADJ_LIST_SERIALIZE_HPP
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/pending/property_serialize.hpp>
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/serialization/collections_save_imp.hpp>
#include <boost/serialization/collections_load_imp.hpp>
#include <boost/serialization/split_free.hpp>
namespace boost
{
namespace serialization
{
// Turn off tracking for adjacency_list. It's not polymorphic, and we
// need to do this to enable saving of non-const adjacency lists.
template < class OEL, class VL, class D, class VP, class EP, class GP,
class EL >
struct tracking_level< boost::adjacency_list< OEL, VL, D, VP, EP, GP, EL > >
{
typedef mpl::integral_c_tag tag;
typedef mpl::int_< track_never > type;
BOOST_STATIC_CONSTANT(int, value = tracking_level::type::value);
};
template < class Archive, class OEL, class VL, class D, class VP, class EP,
class GP, class EL >
inline void save(Archive& ar,
const boost::adjacency_list< OEL, VL, D, VP, EP, GP, EL >& graph,
const unsigned int /* file_version */
)
{
typedef adjacency_list< OEL, VL, D, VP, EP, GP, EL > Graph;
typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
int V = num_vertices(graph);
int E = num_edges(graph);
ar << BOOST_SERIALIZATION_NVP(V);
ar << BOOST_SERIALIZATION_NVP(E);
// assign indices to vertices
std::map< Vertex, int > indices;
int num = 0;
BGL_FORALL_VERTICES_T(v, graph, Graph)
{
indices[v] = num++;
ar << serialization::make_nvp(
"vertex_property", get(vertex_all_t(), graph, v));
}
// write edges
BGL_FORALL_EDGES_T(e, graph, Graph)
{
ar << serialization::make_nvp("u", indices[source(e, graph)]);
ar << serialization::make_nvp("v", indices[target(e, graph)]);
ar << serialization::make_nvp(
"edge_property", get(edge_all_t(), graph, e));
}
ar << serialization::make_nvp(
"graph_property", get_property(graph, graph_all_t()));
}
template < class Archive, class OEL, class VL, class D, class VP, class EP,
class GP, class EL >
inline void load(
Archive& ar, boost::adjacency_list< OEL, VL, D, VP, EP, GP, EL >& graph,
const unsigned int /* file_version */
)
{
typedef adjacency_list< OEL, VL, D, VP, EP, GP, EL > Graph;
typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
typedef typename graph_traits< Graph >::edge_descriptor Edge;
unsigned int V;
ar >> BOOST_SERIALIZATION_NVP(V);
unsigned int E;
ar >> BOOST_SERIALIZATION_NVP(E);
std::vector< Vertex > verts(V);
int i = 0;
while (V-- > 0)
{
Vertex v = add_vertex(graph);
verts[i++] = v;
ar >> serialization::make_nvp(
"vertex_property", get(vertex_all_t(), graph, v));
}
while (E-- > 0)
{
int u;
int v;
ar >> BOOST_SERIALIZATION_NVP(u);
ar >> BOOST_SERIALIZATION_NVP(v);
Edge e;
bool inserted;
boost::tie(e, inserted) = add_edge(verts[u], verts[v], graph);
ar >> serialization::make_nvp(
"edge_property", get(edge_all_t(), graph, e));
}
ar >> serialization::make_nvp(
"graph_property", get_property(graph, graph_all_t()));
}
template < class Archive, class OEL, class VL, class D, class VP, class EP,
class GP, class EL >
inline void serialize(Archive& ar,
boost::adjacency_list< OEL, VL, D, VP, EP, GP, EL >& graph,
const unsigned int file_version)
{
boost::serialization::split_free(ar, graph, file_version);
}
} // serialization
} // boost
#endif // BOOST_GRAPH_ADJ_LIST_SERIALIZE_HPP
| 35.519084 | 81 | 0.570815 | kindlychung |
4d034b5a6ae599a2d21dbd7aedc042bcbe70203c | 1,528 | cpp | C++ | source/Library.Shared/ModelManager.cpp | DakkyDaWolf/OpenGL | 628e9aed116022175cc0c59c88ace7688309628c | [
"MIT"
] | null | null | null | source/Library.Shared/ModelManager.cpp | DakkyDaWolf/OpenGL | 628e9aed116022175cc0c59c88ace7688309628c | [
"MIT"
] | null | null | null | source/Library.Shared/ModelManager.cpp | DakkyDaWolf/OpenGL | 628e9aed116022175cc0c59c88ace7688309628c | [
"MIT"
] | null | null | null | #include "pch.h"
#include "ModelManager.h"
using namespace std;
namespace Library
{
pair<Model, vector<MeshResource>>& ModelManager::LoadModel(const std::string& fileName)
{
Model loadedModel(fileName, true);
auto assembledEntry = make_pair(fileName, make_pair(move(loadedModel), vector<MeshResource>()));
for (auto& mesh : assembledEntry.second.first.Meshes())
{
assembledEntry.second.second.push_back(MeshResource(*mesh));
}
++ModelsLoaded;
return RegisteredModels.emplace(move(assembledEntry)).first->second;
}
Model& ModelManager::GetModel(const std::string& fileName)
{
if (fileName.empty()) throw runtime_error("invalid filename: empty");
if (!RegisteredModels.count(fileName)) return LoadModel(fileName).first;
return RegisteredModels.at(fileName).first;
}
MeshResource& ModelManager::GetMesh(const std::string& fileName, size_t index)
{
if (fileName.empty()) throw runtime_error("invalid filename: empty");
if (!RegisteredModels.count(fileName)) return LoadModel(fileName).second[index];
return RegisteredModels.at(fileName).second[index];
}
std::vector<MeshResource>& ModelManager::GetMeshes(const std::string& fileName)
{
if (fileName.empty()) throw runtime_error("invalid filename: empty");
if (!RegisteredModels.count(fileName)) return LoadModel(fileName).second;
return RegisteredModels.at(fileName).second;
}
} | 29.960784 | 104 | 0.679319 | DakkyDaWolf |
4d035b516778b0b5acf09a84fcac8ead7e785c2f | 4,552 | cpp | C++ | object_tests/src/array_tests.cpp | pierrebai/dak | 3da144aecfc941efe10abe0167b1d3a838a6a0d5 | [
"MIT"
] | null | null | null | object_tests/src/array_tests.cpp | pierrebai/dak | 3da144aecfc941efe10abe0167b1d3a838a6a0d5 | [
"MIT"
] | null | null | null | object_tests/src/array_tests.cpp | pierrebai/dak | 3da144aecfc941efe10abe0167b1d3a838a6a0d5 | [
"MIT"
] | null | null | null | #include <CppUnitTest.h>
#include <dak/object/array.h>
#include <dak/object/tests/helpers.h>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace dak::object::tests
{
TEST_CLASS(array_tests)
{
public:
array_tests()
{
any_op::register_ops();
register_object_ops();
}
TEST_METHOD(array_base)
{
array_t a;
Assert::AreEqual<index_t>(0, a.size());
a.grow() = 3;
a.grow() = 4;
a.grow() = 5.0;
a.grow() = L"6";
Assert::AreEqual<index_t>(4, a.size());
Assert::AreEqual<int32_t>(3, a[0]);
Assert::AreEqual<int64_t>(4, a[1]);
Assert::AreEqual<double>(5.0, a[2]);
Assert::AreEqual<text_t>(L"6", a[3]);
Assert::IsFalse(a.erase(5));
Assert::IsFalse(a.erase(4));
Assert::IsTrue(a.erase(3));
Assert::IsTrue(a.erase(2));
Assert::IsTrue(a.erase(1));
Assert::IsTrue(a.erase(0));
Assert::AreEqual<index_t>(0, a.size());
Assert::AreEqual(typeid(void), a[-1000].get_type());
const array_t b;
Assert::AreEqual(typeid(void), b[-1000].get_type());
}
TEST_METHOD(array_append)
{
array_t a1;
a1.grow() = 3;
a1.grow() = 4;
a1.grow() = 5.0;
a1.grow() = L"6";
array_t a2;
a2 += a1;
Assert::AreEqual<index_t>(4, a1.size());
Assert::AreEqual<index_t>(4, a2.size());
Assert::AreEqual<int32_t>(3, a2[0]);
Assert::AreEqual<int64_t>(4, a2[1]);
Assert::AreEqual<double>(5.0, a2[2]);
Assert::AreEqual<text_t>(L"6", a2[3]);
Assert::AreEqual(a1, a2);
}
TEST_METHOD(array_insert)
{
array_t a1;
a1.grow() = 3;
a1.grow() = 4;
a1.grow() = 5.0;
a1.grow() = L"6";
a1.insert(1) = 33;
Assert::AreEqual<index_t>(5, a1.size());
Assert::AreEqual<int32_t>(3, a1[0]);
Assert::AreEqual<int32_t>(33, a1[1]);
Assert::AreEqual<int64_t>(4, a1[2]);
Assert::AreEqual<double>(5.0, a1[3]);
Assert::AreEqual<text_t>(L"6", a1[4]);
}
TEST_METHOD(array_iterator)
{
array_t a1;
a1.grow() = 3;
a1.grow() = 4ll;
a1.grow() = 5.0;
a1.grow() = L"6";
int32_t count = 0;
for (const value_t& e : a1)
{
count += 1;
switch (count)
{
case 1:
Assert::AreEqual<int32_t>(3, e);
break;
case 2:
Assert::AreEqual<int64_t>(4, e);
break;
case 3:
Assert::AreEqual<double>(5.0, e);
break;
case 4:
Assert::AreEqual<text_t>(L"6", e);
break;
}
}
Assert::AreEqual<int32_t>(4, count);
}
TEST_METHOD(array_negative_index)
{
array_t a1;
a1[-1] = 3.;
Assert::AreEqual<index_t>(1, a1.size());
Assert::AreEqual<double>(3., a1[0]);
a1[-7] = L"first";
Assert::AreEqual<index_t>(7, a1.size());
Assert::AreEqual<text_t>(text_t(L"first"), a1[0]);
Assert::AreEqual<const datatype_t&>(typeid(void), a1[1].get_type());
Assert::AreEqual<const datatype_t&>(typeid(void), a1[2].get_type());
Assert::AreEqual<const datatype_t&>(typeid(void), a1[3].get_type());
Assert::AreEqual<const datatype_t&>(typeid(void), a1[4].get_type());
Assert::AreEqual<const datatype_t&>(typeid(void), a1[5].get_type());
Assert::AreEqual<const datatype_t&>(typeid(void), a1[6].get_type());
// Note: insert inserts before the index given, so -1 inserts before the last value.
a1.insert(-1) = 8;
Assert::AreEqual<index_t>(8, a1.size());
Assert::AreEqual<int64_t>(8, a1[6]);
Assert::AreEqual<int64_t>(0, a1[7]);
Assert::IsFalse(a1.erase(-9));
Assert::AreEqual<index_t>(8, a1.size());
Assert::AreEqual<text_t>(text_t(L"first"), a1[0]);
Assert::IsTrue(a1.erase(-8));
Assert::AreEqual<index_t>(7, a1.size());
Assert::AreEqual<const datatype_t&>(typeid(void), a1[0].get_type());
Assert::IsTrue(a1.erase(-1));
Assert::AreEqual<index_t>(6, a1.size());
Assert::AreEqual<int64_t>(8, a1[5]);
}
};
}
| 27.095238 | 93 | 0.501318 | pierrebai |
4d07adfd12de072911c72e3c60f3882768d05cbd | 740 | hpp | C++ | src/public/GpuGeometry.hpp | linuxaged/gfx | 5ec841ddabca5ce589cd1ca095ce81ec52b438ee | [
"MIT"
] | null | null | null | src/public/GpuGeometry.hpp | linuxaged/gfx | 5ec841ddabca5ce589cd1ca095ce81ec52b438ee | [
"MIT"
] | null | null | null | src/public/GpuGeometry.hpp | linuxaged/gfx | 5ec841ddabca5ce589cd1ca095ce81ec52b438ee | [
"MIT"
] | null | null | null | #pragma once
#include "GpuBuffer.hpp"
#include "GpuVertexAttribute.hpp"
namespace lxd
{
class GpuGeometry
{
public:
GpuGeometry( GpuContext* context, const GpuVertexAttributeArrays* attribs,
const GpuTriangleIndexArray* indices, const bool dynamic = false );
~GpuGeometry();
public:
const GpuVertexAttribute* layout;
int vertexAttribsFlags;
int instanceAttribsFlags;
int vertexCount;
int instanceCount;
int indexCount;
GpuBuffer vertexBuffer;
GpuBuffer instanceBuffer;
GpuBuffer indexBuffer;
};
} // namespace lxd
| 27.407407 | 84 | 0.564865 | linuxaged |
4d0b7b1b15d31050b49ce1c05cde7361f680d6d3 | 7,086 | hpp | C++ | boost/hash/block_cyphers/basic_shacal.hpp | dillonl/boost-cmake | 7204d4c68345a0b26e24f51fa46a04b1d2bda3e7 | [
"BSL-1.0"
] | null | null | null | boost/hash/block_cyphers/basic_shacal.hpp | dillonl/boost-cmake | 7204d4c68345a0b26e24f51fa46a04b1d2bda3e7 | [
"BSL-1.0"
] | null | null | null | boost/hash/block_cyphers/basic_shacal.hpp | dillonl/boost-cmake | 7204d4c68345a0b26e24f51fa46a04b1d2bda3e7 | [
"BSL-1.0"
] | null | null | null |
//
// Copyright 2010 Scott McMurray.
// 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_HASH_BLOCK_CYPHERS_BASIC_SHACAL_HPP
#define BOOST_HASH_BLOCK_CYPHERS_BASIC_SHACAL_HPP
#include <boost/hash/block_cyphers/detail/shacal_policy.hpp>
#include <boost/hash/block_cyphers/detail/shacal1_policy.hpp>
#include <boost/static_assert.hpp>
#ifdef BOOST_HASH_SHOW_PROGRESS
#include <cstdio>
#endif
//
// Encrypt implemented directly from the SHA standard as found at
// http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
//
// Decrypt is a straight-forward inverse
//
// In SHA terminology:
// - plaintext = H^(i-1)
// - cyphertext = H^(i)
// - key = M^(i)
// - schedule = W
//
namespace boost {
namespace hashes {
namespace block_cyphers {
//
// The algorithms for SHA(-0) and SHA-1 are identical apart from the
// key scheduling, so encapsulate that as a class that takes an
// already-prepared schedule. (Constructor is protected to help keep
// people from accidentally giving it just a key in a schedule.)
//
class basic_shacal {
public:
typedef detail::shacal_policy policy_type;
static unsigned const word_bits = policy_type::word_bits;
typedef policy_type::word_type word_type;
static unsigned const key_bits = policy_type::key_bits;
static unsigned const key_words = policy_type::key_words;
typedef policy_type::key_type key_type;
static unsigned const block_bits = policy_type::block_bits;
static unsigned const block_words = policy_type::block_words;
typedef policy_type::block_type block_type;
static unsigned const rounds = policy_type::rounds;
typedef policy_type::schedule_type schedule_type;
protected:
basic_shacal(schedule_type const &s) : schedule(s) {}
private:
schedule_type const schedule;
public:
block_type
encypher(block_type const &plaintext) {
return encypher_block(plaintext);
}
private:
block_type
encypher_block(block_type const &plaintext) {
return encypher_block(schedule, plaintext);
}
static block_type
encypher_block(schedule_type const &schedule,
block_type const &plaintext) {
#ifdef BOOST_HASH_SHOW_PROGRESS
for (unsigned t = 0; t < block_words; ++t) {
std::printf(word_bits == 32 ?
"H[%d] = %.8x\n" :
"H[%d] = %.16lx\n",
t, plaintext[t]);
}
#endif
// Initialize working variables with block
word_type a = plaintext[0], b = plaintext[1],
c = plaintext[2], d = plaintext[3],
e = plaintext[4];
// Encypher block
#ifdef BOOST_HASH_NO_OPTIMIZATION
for (unsigned t = 0; t < rounds; ++t) {
word_type T = policy_type::ROTL<5>(a)
+ policy_type::f(t,b,c,d)
+ e
+ policy_type::constant(t)
+ schedule[t];
e = d;
d = c;
c = policy_type::ROTL<30>(b);
b = a;
a = T;
#ifdef BOOST_HASH_SHOW_PROGRESS
printf(word_bits == 32 ?
"t = %2d: %.8x %.8x %.8x %.8x %.8x\n" :
"t = %2d: %.16lx %.16lx %.16lx %.16lx %.16lx\n",
t, a, b, c, d, e);
#endif
}
#else // BOOST_HASH_NO_OPTIMIZATION
# ifdef BOOST_HASH_SHOW_PROGRESS
# define BOOST_HASH_SHACAL1_TRANSFORM_PROGRESS \
printf(word_bits == 32 ? \
"t = %2d: %.8x %.8x %.8x %.8x %.8x\n" : \
"t = %2d: %.16lx %.16lx %.16lx %.16lx %.16lx\n", \
t, a, b, c, d, e);
# else
# define BOOST_HASH_SHACAL1_TRANSFORM_PROGRESS
# endif
# define BOOST_HASH_SHACAL1_TRANSFORM \
word_type T = policy_type::ROTL<5>(a) \
+ policy_type::f(t,b,c,d) \
+ e \
+ policy_type::constant(t) \
+ schedule[t]; \
e = d; \
d = c; \
c = policy_type::ROTL<30>(b); \
b = a; \
a = T; \
BOOST_HASH_SHACAL1_TRANSFORM_PROGRESS
BOOST_STATIC_ASSERT(rounds == 80);
BOOST_STATIC_ASSERT(rounds % block_words == 0);
for (unsigned t = 0; t < 20; ) {
for (int n = block_words; n--; ++t) {
BOOST_HASH_SHACAL1_TRANSFORM
}
}
for (unsigned t = 20; t < 40; ) {
for (int n = block_words; n--; ++t) {
BOOST_HASH_SHACAL1_TRANSFORM
}
}
for (unsigned t = 40; t < 60; ) {
for (int n = block_words; n--; ++t) {
BOOST_HASH_SHACAL1_TRANSFORM
}
}
for (unsigned t = 60; t < 80; ) {
for (int n = block_words; n--; ++t) {
BOOST_HASH_SHACAL1_TRANSFORM
}
}
#endif
block_type cyphertext = {{a, b, c, d, e}};
return cyphertext;
}
public:
block_type
decypher(block_type const &plaintext) {
return decypher_block(plaintext);
}
private:
block_type
decypher_block(block_type const &plaintext) {
return decypher_block(schedule, plaintext);
}
static block_type
decypher_block(schedule_type const &schedule,
block_type const &cyphertext) {
#ifdef BOOST_HASH_SHOW_PROGRESS
for (unsigned t = 0; t < block_words; ++t) {
std::printf(word_bits == 32 ?
"H[%d] = %.8x\n" :
"H[%d] = %.16lx\n",
t, cyphertext[t]);
}
#endif
// Initialize working variables with block
word_type a = cyphertext[0], b = cyphertext[1],
c = cyphertext[2], d = cyphertext[3],
e = cyphertext[4];
// Decypher block
for (unsigned t = rounds; t--; ) {
word_type T = a;
a = b;
b = policy_type::ROTR<30>(c);
c = d;
d = e;
e = T
- policy_type::ROTL<5>(a)
- policy_type::f(t, b, c, d)
- policy_type::constant(t)
- schedule[t];
#ifdef BOOST_HASH_SHOW_PROGRESS
std::printf(word_bits == 32 ?
"t = %2d: %.8x %.8x %.8x %.8x %.8x\n" :
"t = %2d: %.16lx %.16lx %.16lx %.16lx %.16lx\n",
t, a, b, c, d, e);
#endif
}
block_type plaintext = {{a, b, c, d, e}};
return plaintext;
}
};
} // namespace block_cyphers
} // namespace hashes
} // namespace boost
#endif // BOOST_HASH_BLOCK_CYPHERS_BASIC_SHACAL_HPP
| 30.282051 | 73 | 0.52639 | dillonl |
4d0bda3f477f32cc21f869ba4521bb21ab99bed7 | 1,571 | cpp | C++ | Solitaire/game.cpp | LazyMechanic/Solitaire | 7e6e72cf32695267e7ec7fa5c8bd366b0553b439 | [
"Apache-2.0"
] | null | null | null | Solitaire/game.cpp | LazyMechanic/Solitaire | 7e6e72cf32695267e7ec7fa5c8bd366b0553b439 | [
"Apache-2.0"
] | null | null | null | Solitaire/game.cpp | LazyMechanic/Solitaire | 7e6e72cf32695267e7ec7fa5c8bd366b0553b439 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "game.h"
short Game::g_gameCondition = Condition::Nothing;
Game::~Game()
{
}
bool Game::Init()
{
// Check files
if (!m_cardsImage.loadFromFile("data/cards.png") || !m_backgroundImage.loadFromFile("data/background.png") || !m_windowIcon.loadFromFile("data/ico.png") || !Timer::SetTimerText() || !EndGame::Init(m_backgroundImage) || !Config::Init()) {
return false;
}
// Create window
m_window.create(sf::VideoMode(800, 600), "Solitaire", sf::Style::Titlebar | sf::Style::Close);
m_window.setIcon(32, 32, m_windowIcon.getPixelsPtr());
m_window.setVerticalSyncEnabled(true);
// Init gaming table, his constans and Input
Input::Init(this);
m_gamingTable.Init(m_cardsImage, m_backgroundImage, m_window);
m_gamingTable.InitOffset(m_window.getSize());
return true;
}
void Game::Run()
{
sf::Clock timer;
while (m_window.isOpen() && Game::g_gameCondition == Condition::Nothing && Timer::GetCurrentTime() > 0) {
auto dt = timer.restart();
// Update scene
Input::Update();
Timer::Update(dt.asMilliseconds() > 100 ? 100 : dt.asMilliseconds());
m_gamingTable.Update(dt.asSeconds());
m_window.clear(sf::Color(0, 128, 0));
// Draw scene
m_gamingTable.Draw(m_window);
// Display scene
m_window.display();
}
// Check loss time
if (Timer::GetCurrentTime() < 1) {
Game::g_gameCondition = Condition::Lose;
Config::Update(-300);
}
// Draw last scene - end game
EndGame::Draw(m_window, Game::g_gameCondition);
// closing waiting
while (m_window.isOpen()) Input::Update();
// Save score
Config::Save();
}
| 26.183333 | 238 | 0.694462 | LazyMechanic |
4d0c54073ae29c60b9b60f52a8663ff734531f3a | 1,150 | cpp | C++ | src/core/xt/xt/backend/pulse/Service.cpp | sjoerdvankreel/xt-audio | 960d6ed595c872c01af5c321b38b88a6ea07680a | [
"MIT"
] | 49 | 2017-04-01T00:41:14.000Z | 2022-03-23T09:03:28.000Z | src/core/xt/xt/backend/pulse/Service.cpp | sjoerdvankreel/xt-audio | 960d6ed595c872c01af5c321b38b88a6ea07680a | [
"MIT"
] | 18 | 2017-04-29T22:46:35.000Z | 2022-02-26T18:33:47.000Z | src/core/xt/xt/backend/pulse/Service.cpp | sjoerdvankreel/xt-audio | 960d6ed595c872c01af5c321b38b88a6ea07680a | [
"MIT"
] | 14 | 2017-05-01T12:33:20.000Z | 2021-10-01T07:16:26.000Z | #if XT_ENABLE_PULSE
#include <xt/backend/pulse/Shared.hpp>
#include <pulse/pulseaudio.h>
#include <cstring>
XtFault
PulseService::GetFormatFault() const
{ return XT_PA_ERR_FORMAT; }
XtServiceCaps
PulseService::GetCapabilities() const
{
auto result = XtServiceCapsAggregation | XtServiceCapsChannelMask;
return static_cast<XtServiceCaps>(result);
}
XtFault
PulseService::OpenDeviceList(XtEnumFlags flags, XtDeviceList** list) const
{
bool input = (flags & XtEnumFlagsInput) != 0;
bool output = (flags & XtEnumFlagsOutput) != 0;
*list = new PulseDeviceList(input, output);
return PA_OK;
}
XtFault
PulseService::OpenDevice(char const* id, XtDevice** device) const
{
XtFault fault;
XtPaSimple pa;
XtBool output = strcmp(id, "0");
if((fault = XtiCreatePulseDefaultClient(output, &pa.pa)) != PA_OK) return fault;
*device = new PulseDevice(output);
return PA_OK;
}
XtFault
PulseService::GetDefaultDeviceId(XtBool output, XtBool* valid, char* buffer, int32_t* size) const
{
if(output) XtiCopyString("1", buffer, size);
else XtiCopyString("0", buffer, size);
*valid = XtTrue;
return PA_OK;
}
#endif // XT_ENABLE_PULSE | 25 | 97 | 0.73913 | sjoerdvankreel |
4d0e5c059871ea1c87197a9b6fccca9448831639 | 4,075 | cpp | C++ | src/apps/vis/tasks/vis_create_dynamic_tree_edges.cpp | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | 15 | 2015-07-07T15:48:30.000Z | 2019-10-27T18:49:49.000Z | src/apps/vis/tasks/vis_create_dynamic_tree_edges.cpp | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | null | null | null | src/apps/vis/tasks/vis_create_dynamic_tree_edges.cpp | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | 4 | 2016-11-23T05:50:01.000Z | 2019-09-18T12:44:36.000Z | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include "apps/vis/tasks/vis_create_dynamic_tree_edges.h"
#include "apps/vis/elements/vis_drawable_edge_default.h"
#include "apps/vis/elements/vis_drawable_edge_dynamic_tree.h"
#include "apps/vis/elements/vis_drawable_node_default.h"
#ifdef HAVE_BOOST_REGEX
#include <boost/regex.hpp>
#endif
using namespace shawn;
namespace vis
{
CreateDynamicTreeEdgesTask::
CreateDynamicTreeEdgesTask()
{}
// ----------------------------------------------------------------------
CreateDynamicTreeEdgesTask::
~CreateDynamicTreeEdgesTask()
{}
// ----------------------------------------------------------------------
std::string
CreateDynamicTreeEdgesTask::
name( void )
const throw()
{ return "vis_create_dynamic_tree_edges"; }
// ----------------------------------------------------------------------
std::string
CreateDynamicTreeEdgesTask::
description( void )
const throw()
{ return "XXX"; }
// ----------------------------------------------------------------------
void
CreateDynamicTreeEdgesTask::
run( shawn::SimulationController& sc )
throw( std::runtime_error )
{
VisualizationTask::run(sc);
GroupElement* all_edges = new GroupElement("all.edges");
visualization_w().add_element(all_edges);
std::string pref = sc.environment().
optional_string_param("prefix",DrawableEdgeDynamicTree::PREFIX);
std::string node_prefix = sc.environment().
optional_string_param("node_prefix",DrawableNodeDefault::PREFIX);
std::string _source_regex = sc.environment().optional_string_param("source_regex", ".*");
std::string _target_regex = sc.environment().optional_string_param("target_regex", ".*");
const shawn::Node &dummy = *(visualization().world().begin_nodes());
std::cout << "Regex: " << _source_regex << std::endl;
DrawableEdgeDynamicTree* ded =
new DrawableEdgeDynamicTree(dummy,dummy, pref, node_prefix, _source_regex, _target_regex);
ded->init();
visualization_w().add_element(ded);
all_edges->add_element(*ded);
}
// ----------------------------------------------------------------------
GroupElement*
CreateDynamicTreeEdgesTask::
group( shawn::SimulationController& sc )
throw( std::runtime_error )
{
std::string n = sc.environment().optional_string_param("group","");
if( n.empty() )
return NULL;
ElementHandle eh =
visualization_w().element_w( n );
if( eh.is_null() )
throw std::runtime_error(std::string("no such group: ")+n);
GroupElement* ge = dynamic_cast<GroupElement*>(eh.get());
if( ge == NULL )
throw std::runtime_error(std::string("element is no group: ")+n);
return ge;
}
// ----------------------------------------------------------------------
const DrawableNode*
CreateDynamicTreeEdgesTask::
drawable_node( const shawn::Node& v,
const std::string& nprefix )
throw( std::runtime_error )
{
std::string n = nprefix+std::string(".")+v.label();
ConstElementHandle eh =
visualization().element( n );
if( eh.is_null() )
throw std::runtime_error(std::string("no such element: ")+n);
const DrawableNode* dn = dynamic_cast<const DrawableNode*>(eh.get());
if( dn == NULL )
throw std::runtime_error(std::string("element is no DrawableNode: ")+n);
return dn;
}
}
#endif
| 37.731481 | 114 | 0.551411 | itm |
4d0f7a46669052ac2cc8f620c783585a14292004 | 717 | cpp | C++ | test/test_is_used.cpp | KOLANICH/argparse | ccf3920ce205b02f09325c8f454e2fe9ce4edfb5 | [
"MIT"
] | 1,101 | 2019-04-02T13:59:40.000Z | 2022-03-31T23:14:00.000Z | test/test_is_used.cpp | KOLANICH/argparse | ccf3920ce205b02f09325c8f454e2fe9ce4edfb5 | [
"MIT"
] | 108 | 2019-04-08T23:46:13.000Z | 2022-03-31T15:13:58.000Z | test/test_is_used.cpp | KOLANICH/argparse | ccf3920ce205b02f09325c8f454e2fe9ce4edfb5 | [
"MIT"
] | 144 | 2019-04-09T22:06:47.000Z | 2022-03-31T13:09:43.000Z | #include <doctest.hpp>
#include <argparse/argparse.hpp>
using doctest::test_suite;
TEST_CASE("User-supplied argument" * test_suite("is_used")) {
argparse::ArgumentParser program("test");
program.add_argument("--dir")
.default_value(std::string("/"));
program.parse_args({ "test", "--dir", "/home/user" });
REQUIRE(program.get("--dir") == "/home/user");
REQUIRE(program.is_used("--dir") == true);
}
TEST_CASE("Not user-supplied argument" * test_suite("is_used")) {
argparse::ArgumentParser program("test");
program.add_argument("--dir")
.default_value(std::string("/"));
program.parse_args({ "test" });
REQUIRE(program.get("--dir") == "/");
REQUIRE(program.is_used("--dir") == false);
}
| 31.173913 | 65 | 0.658298 | KOLANICH |
4d108ef626f44e7134ef6d8bf438b938a501a2cd | 693 | hpp | C++ | engine/actions/include/HelpAction.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/actions/include/HelpAction.hpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/actions/include/HelpAction.hpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #pragma once
#include "IActionManager.hpp"
class HelpAction : public IActionManager
{
public:
ActionCostValue help(CreaturePtr creature) const;
ActionCostValue keybindings() const;
ActionCostValue introduction_roguelikes() const;
ActionCostValue game_history() const;
ActionCostValue strategy_basics() const;
ActionCostValue casino_games() const;
ActionCostValue get_action_cost_value(CreaturePtr creature) const override;
protected:
friend class ActionManager;
friend class HelpCommandProcessor;
HelpAction();
ActionCostValue display_text(const std::string& title_sid, const std::string& text_sid, const bool maintain_formatting) const;
};
| 30.130435 | 130 | 0.776335 | sidav |
4d1329f20b33722b882c6ff82f332fc2ecf66051 | 2,096 | cpp | C++ | Homework/GraphingCalculator/GraphingCalculator/src/Token.cpp | benjaminmao123/PCC_CS003A | 0339d83ebab7536952644517a99dc46702035b2b | [
"MIT"
] | null | null | null | Homework/GraphingCalculator/GraphingCalculator/src/Token.cpp | benjaminmao123/PCC_CS003A | 0339d83ebab7536952644517a99dc46702035b2b | [
"MIT"
] | null | null | null | Homework/GraphingCalculator/GraphingCalculator/src/Token.cpp | benjaminmao123/PCC_CS003A | 0339d83ebab7536952644517a99dc46702035b2b | [
"MIT"
] | null | null | null | /*
* Author: Benjamin Mao
* Project: RPN
* Purpose: Base class for all the tokens
* which include Operand and Operators.
*
* Notes: None.
*/
#include "Token.h"
Token::Token()
: tokenType(TokenType::NONE), baseTokenType(TokenType::NONE),
numArgs(0)
{
}
/*
@summary: Getter for tokenString.
*/
const std::string &Token::GetTokenString() const
{
return tokenString;
}
/*
@summary: Getter for tokenType.
*/
TokenType Token::GetTokenType() const
{
return tokenType;
}
TokenType Token::GetBaseTokenType() const
{
return baseTokenType;
}
unsigned int Token::GetNumArgs() const
{
return numArgs;
}
/*
@summary: Setter for tokenString.
@param <const std::string &str>: String to set tokenString.
*/
void Token::SetTokenString(const std::string &str)
{
tokenString = str;
}
/*
@summary: Setter for tokenType.
@param <TokenType type>: TokenType to set tokenType.
*/
void Token::SetTokenType(TokenType type)
{
tokenType = type;
}
void Token::SetBaseTokenType(TokenType type)
{
baseTokenType = type;
}
void Token::SetNumArgs(unsigned int num)
{
numArgs = num;
}
/*
@summary: Overloaded stream insertion operator.
@param <std::ostream &os>: The ostream object.
@param <const Token &rhs>: The token to print.
*/
std::ostream &operator<<(std::ostream &os, const Token &rhs)
{
os << rhs.GetTokenString();
return os;
}
/*
@summary: Default constructor.
Initializes precedence and tokenString.
*/
LeftParenthesis::LeftParenthesis()
{
SetTokenString("(");
SetTokenType(TokenType::L_PARENTH);
SetBaseTokenType(TokenType::NONE);
}
/*
@summary: Evaluates the current operation.
*/
double LeftParenthesis::Evaluate() const
{
return 0.0;
}
/*
@summary: Default constructor.
Initializes precedence and tokenString.
*/
RightParenthesis::RightParenthesis()
{
SetTokenString(")");
SetTokenType(TokenType::R_PARENTH);
SetBaseTokenType(TokenType::NONE);
}
/*
@summary: Evaluates the current operation.
*/
double RightParenthesis::Evaluate() const
{
return 0.0;
} | 16.903226 | 65 | 0.678912 | benjaminmao123 |
4d16b136a894f70a6cffc9c0fa53590f89c3be6f | 1,194 | cpp | C++ | ige/src/ecs/Entity.cpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 3 | 2021-06-05T00:36:50.000Z | 2022-02-27T10:23:53.000Z | ige/src/ecs/Entity.cpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 11 | 2021-05-08T22:00:24.000Z | 2021-11-11T22:33:43.000Z | ige/src/ecs/Entity.cpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 4 | 2021-05-20T12:41:23.000Z | 2021-11-09T14:19:18.000Z | #include "igepch.hpp"
#include "ige/ecs/Entity.hpp"
#include <cstddef>
#include <cstdint>
using ige::ecs::EntityId;
using ige::ecs::EntityPool;
EntityId::EntityId(std::size_t index, std::uint64_t gen)
: m_index(index)
, m_generation(gen)
{
}
std::size_t EntityId::index() const
{
return m_index;
}
std::uint64_t EntityId::generation() const
{
return m_generation;
}
EntityId EntityId::next_gen() const
{
return { m_index, m_generation + 1 };
}
EntityId EntityPool::allocate()
{
auto it_available = m_released.begin();
if (it_available != m_released.end()) {
EntityId entity = it_available->next_gen();
m_released.erase(it_available);
m_entities.insert(entity);
return entity;
} else {
EntityId entity { m_size++, 0 };
m_entities.insert(entity);
return entity;
}
}
bool EntityPool::release(EntityId entity)
{
auto iter = m_entities.find(entity);
if (iter != m_entities.end()) {
m_released.insert(entity);
m_entities.erase(iter);
return true;
}
return false;
}
bool EntityPool::exists(EntityId entity) const
{
return m_entities.contains(entity);
}
| 18.65625 | 56 | 0.649079 | Arcahub |
4d16d978af99044cd4ad2b4654a67b9e32983efc | 623 | cpp | C++ | usaco/CountingLiars2022Bronze.cpp | datpq/competitive-programming | ed5733cc55fa4167c4a2e828894b044ea600dcac | [
"MIT"
] | 1 | 2022-02-24T21:35:18.000Z | 2022-02-24T21:35:18.000Z | usaco/CountingLiars2022Bronze.cpp | datpq/competitive-programming | ed5733cc55fa4167c4a2e828894b044ea600dcac | [
"MIT"
] | null | null | null | usaco/CountingLiars2022Bronze.cpp | datpq/competitive-programming | ed5733cc55fa4167c4a2e828894b044ea600dcac | [
"MIT"
] | 1 | 2022-02-12T14:40:21.000Z | 2022-02-12T14:40:21.000Z | #include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
int n; cin >> n;
map<int, pair<int, int>> m;
int G = 0, L = 0;
while (n--) {
char c; int p; cin >> c >> p;
if (!m.count(p)) m[p] = { 0, 0 };
if (c == 'G') {
m[p].second++; G++;
}
else {
m[p].first++; L++;
}
}
int best = G;
int ans = best;
int lastL = 0;
for (auto& x : m) {
ans -= (x.second.second - lastL);
lastL = x.second.first;
best = min(best, ans);
}
cout << best << endl;
return 0;
} | 20.096774 | 41 | 0.41573 | datpq |
4d1823f52370dde40a424e8d058afbf43dbf2341 | 1,672 | hpp | C++ | irohad/model/converters/pb_transaction_factory.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | null | null | null | irohad/model/converters/pb_transaction_factory.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | null | null | null | irohad/model/converters/pb_transaction_factory.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* 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 IROHA_PB_TRANSACTION_FACTORY_HPP
#define IROHA_PB_TRANSACTION_FACTORY_HPP
#include <memory>
#include "model/transaction.hpp"
#include "transaction.pb.h"
namespace iroha {
namespace model {
namespace converters {
/**
* Converting business objects to protobuf and vice versa
*/
class PbTransactionFactory {
public:
PbTransactionFactory() {}
/**
* Convert block to proto block
* @param block - reference to block
* @return proto block
*/
static protocol::Transaction serialize(const model::Transaction &tx);
/**
* Convert proto block to model block
* @param pb_block - reference to proto block
* @return model block
*/
static std::shared_ptr<model::Transaction> deserialize(
const protocol::Transaction &pb_tx);
};
} // namespace converters
} // namespace model
} // namespace iroha
#endif // IROHA_PB_TRANSACTION_FACTORY_HPP
| 30.4 | 77 | 0.669258 | truongnmt |
4d1c9ed2f5b09a76c4ea8b8c399d060f47dbaf87 | 10,555 | cpp | C++ | src/apps/webpositive/support/FontSelectionView.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2016-03-29T21:45:21.000Z | 2016-12-20T00:50:38.000Z | src/apps/webpositive/support/FontSelectionView.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/apps/webpositive/support/FontSelectionView.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | /*
* Copyright 2001-2010, Haiku.
* Distributed under the terms of the MIT License.
*
* Authors:
* Mark Hogben
* DarkWyrm <bpmagic@columbus.rr.com>
* Axel Dörfler, axeld@pinc-software.de
* Philippe Saint-Pierre, stpere@gmail.com
* Stephan Aßmus <superstippi@gmx.de>
*/
#include "FontSelectionView.h"
#include <Box.h>
#include <Catalog.h>
#include <Locale.h>
#include <Looper.h>
#include <MenuField.h>
#include <MenuItem.h>
#include <PopUpMenu.h>
#include <String.h>
#include <StringView.h>
#include <LayoutItem.h>
#include <GroupLayoutBuilder.h>
#include <stdio.h>
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Font Selection view"
static const float kMinSize = 8.0;
static const float kMaxSize = 18.0;
static const int32 kMsgSetFamily = 'fmly';
static const int32 kMsgSetStyle = 'styl';
static const int32 kMsgSetSize = 'size';
// #pragma mark -
FontSelectionView::FontSelectionView(const char* name, const char* label,
bool separateStyles, const BFont* currentFont)
:
BHandler(name),
fMessage(NULL),
fTarget(NULL)
{
if (currentFont == NULL)
fCurrentFont = _DefaultFont();
else
fCurrentFont = *currentFont;
fSavedFont = fCurrentFont;
fSizesMenu = new BPopUpMenu("size menu");
fFontsMenu = new BPopUpMenu("font menu");
// font menu
fFontsMenuField = new BMenuField("fonts", label, fFontsMenu, B_WILL_DRAW);
fFontsMenuField->SetFont(be_bold_font);
// styles menu, if desired
if (separateStyles) {
fStylesMenu = new BPopUpMenu("styles menu");
fStylesMenuField = new BMenuField("styles", B_TRANSLATE("Style:"),
fStylesMenu, B_WILL_DRAW);
} else {
fStylesMenu = NULL;
fStylesMenuField = NULL;
}
// size menu
fSizesMenuField = new BMenuField("size", B_TRANSLATE("Size:"), fSizesMenu,
B_WILL_DRAW);
fSizesMenuField->SetAlignment(B_ALIGN_RIGHT);
// preview
fPreviewText = new BStringView("preview text",
B_TRANSLATE_COMMENT("The quick brown fox jumps over the lazy dog.",
"Don't translate this literally ! Use a phrase showing all "
"chars from A to Z."));
fPreviewText->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED,
B_SIZE_UNLIMITED));
fPreviewText->SetHighUIColor(B_PANEL_BACKGROUND_COLOR, 1.65);
fPreviewText->SetAlignment(B_ALIGN_RIGHT);
_UpdateFontPreview();
}
FontSelectionView::~FontSelectionView()
{
// Some controls may not have been attached...
if (!fPreviewText->Window())
delete fPreviewText;
if (!fSizesMenuField->Window())
delete fSizesMenuField;
if (fStylesMenuField && !fStylesMenuField->Window())
delete fStylesMenuField;
if (!fFontsMenuField->Window())
delete fFontsMenuField;
delete fMessage;
}
void
FontSelectionView::AttachedToLooper()
{
_BuildSizesMenu();
UpdateFontsMenu();
}
void
FontSelectionView::MessageReceived(BMessage* message)
{
switch (message->what) {
case kMsgSetSize:
{
int32 size;
if (message->FindInt32("size", &size) != B_OK
|| size == fCurrentFont.Size())
break;
fCurrentFont.SetSize(size);
_UpdateFontPreview();
_Invoke();
break;
}
case kMsgSetFamily:
{
const char* family;
if (message->FindString("family", &family) != B_OK)
break;
font_style style;
fCurrentFont.GetFamilyAndStyle(NULL, &style);
BMenuItem* familyItem = fFontsMenu->FindItem(family);
if (familyItem != NULL) {
_SelectCurrentFont(false);
BMenuItem* styleItem;
if (fStylesMenuField != NULL)
styleItem = fStylesMenuField->Menu()->FindMarked();
else {
styleItem = familyItem->Submenu()->FindItem(style);
if (styleItem == NULL)
styleItem = familyItem->Submenu()->ItemAt(0);
}
if (styleItem != NULL) {
styleItem->SetMarked(true);
fCurrentFont.SetFamilyAndStyle(family, styleItem->Label());
_UpdateFontPreview();
}
if (fStylesMenuField != NULL)
_AddStylesToMenu(fCurrentFont, fStylesMenuField->Menu());
}
_Invoke();
break;
}
case kMsgSetStyle:
{
const char* family;
const char* style;
if (message->FindString("family", &family) != B_OK
|| message->FindString("style", &style) != B_OK)
break;
BMenuItem *familyItem = fFontsMenu->FindItem(family);
if (!familyItem)
break;
_SelectCurrentFont(false);
familyItem->SetMarked(true);
fCurrentFont.SetFamilyAndStyle(family, style);
_UpdateFontPreview();
_Invoke();
break;
}
default:
BHandler::MessageReceived(message);
}
}
void
FontSelectionView::SetMessage(BMessage* message)
{
delete fMessage;
fMessage = message;
}
void
FontSelectionView::SetTarget(BHandler* target)
{
fTarget = target;
}
// #pragma mark -
void
FontSelectionView::SetFont(const BFont& font, float size)
{
BFont resizedFont(font);
resizedFont.SetSize(size);
SetFont(resizedFont);
}
void
FontSelectionView::SetFont(const BFont& font)
{
if (font == fCurrentFont && font == fSavedFont)
return;
_SelectCurrentFont(false);
fSavedFont = fCurrentFont = font;
_UpdateFontPreview();
_SelectCurrentFont(true);
_SelectCurrentSize(true);
}
void
FontSelectionView::SetSize(float size)
{
SetFont(fCurrentFont, size);
}
const BFont&
FontSelectionView::Font() const
{
return fCurrentFont;
}
void
FontSelectionView::SetDefaults()
{
BFont defaultFont = _DefaultFont();
if (defaultFont == fCurrentFont)
return;
_SelectCurrentFont(false);
fCurrentFont = defaultFont;
_UpdateFontPreview();
_SelectCurrentFont(true);
_SelectCurrentSize(true);
}
void
FontSelectionView::Revert()
{
if (!IsRevertable())
return;
_SelectCurrentFont(false);
fCurrentFont = fSavedFont;
_UpdateFontPreview();
_SelectCurrentFont(true);
_SelectCurrentSize(true);
}
bool
FontSelectionView::IsDefaultable()
{
return fCurrentFont != _DefaultFont();
}
bool
FontSelectionView::IsRevertable()
{
return fCurrentFont != fSavedFont;
}
void
FontSelectionView::UpdateFontsMenu()
{
int32 numFamilies = count_font_families();
fFontsMenu->RemoveItems(0, fFontsMenu->CountItems(), true);
BFont font = fCurrentFont;
font_family currentFamily;
font_style currentStyle;
font.GetFamilyAndStyle(¤tFamily, ¤tStyle);
for (int32 i = 0; i < numFamilies; i++) {
font_family family;
uint32 flags;
if (get_font_family(i, &family, &flags) != B_OK)
continue;
// if we're setting the fixed font, we only want to show fixed fonts
if (!strcmp(Name(), "fixed") && (flags & B_IS_FIXED) == 0)
continue;
font.SetFamilyAndFace(family, B_REGULAR_FACE);
BMessage* message = new BMessage(kMsgSetFamily);
message->AddString("family", family);
message->AddString("name", Name());
BMenuItem* familyItem;
if (fStylesMenuField != NULL) {
familyItem = new BMenuItem(family, message);
} else {
// Each family item has a submenu with all styles for that font.
BMenu* stylesMenu = new BMenu(family);
_AddStylesToMenu(font, stylesMenu);
familyItem = new BMenuItem(stylesMenu, message);
}
familyItem->SetMarked(strcmp(family, currentFamily) == 0);
fFontsMenu->AddItem(familyItem);
familyItem->SetTarget(this);
}
// Separate styles menu for only the current font.
if (fStylesMenuField != NULL)
_AddStylesToMenu(fCurrentFont, fStylesMenuField->Menu());
}
// #pragma mark - private
BLayoutItem*
FontSelectionView::CreateSizesLabelLayoutItem()
{
return fSizesMenuField->CreateLabelLayoutItem();
}
BLayoutItem*
FontSelectionView::CreateSizesMenuBarLayoutItem()
{
return fSizesMenuField->CreateMenuBarLayoutItem();
}
BLayoutItem*
FontSelectionView::CreateFontsLabelLayoutItem()
{
return fFontsMenuField->CreateLabelLayoutItem();
}
BLayoutItem*
FontSelectionView::CreateFontsMenuBarLayoutItem()
{
return fFontsMenuField->CreateMenuBarLayoutItem();
}
BLayoutItem*
FontSelectionView::CreateStylesLabelLayoutItem()
{
if (fStylesMenuField)
return fStylesMenuField->CreateLabelLayoutItem();
return NULL;
}
BLayoutItem*
FontSelectionView::CreateStylesMenuBarLayoutItem()
{
if (fStylesMenuField)
return fStylesMenuField->CreateMenuBarLayoutItem();
return NULL;
}
BView*
FontSelectionView::PreviewBox() const
{
return fPreviewText;
}
// #pragma mark - private
void
FontSelectionView::_Invoke()
{
if (fTarget != NULL && fTarget->Looper() != NULL && fMessage != NULL) {
BMessage message(*fMessage);
fTarget->Looper()->PostMessage(&message, fTarget);
}
}
BFont
FontSelectionView::_DefaultFont() const
{
if (strcmp(Name(), "bold") == 0)
return *be_bold_font;
if (strcmp(Name(), "fixed") == 0)
return *be_fixed_font;
else
return *be_plain_font;
}
void
FontSelectionView::_SelectCurrentFont(bool select)
{
font_family family;
font_style style;
fCurrentFont.GetFamilyAndStyle(&family, &style);
BMenuItem *item = fFontsMenu->FindItem(family);
if (item != NULL) {
item->SetMarked(select);
if (item->Submenu() != NULL) {
item = item->Submenu()->FindItem(style);
if (item != NULL)
item->SetMarked(select);
}
}
}
void
FontSelectionView::_SelectCurrentSize(bool select)
{
char label[16];
snprintf(label, sizeof(label), "%" B_PRId32, (int32)fCurrentFont.Size());
BMenuItem* item = fSizesMenu->FindItem(label);
if (item != NULL)
item->SetMarked(select);
}
void
FontSelectionView::_UpdateFontPreview()
{
fPreviewText->SetFont(&fCurrentFont);
}
void
FontSelectionView::_BuildSizesMenu()
{
const int32 sizes[] = {7, 8, 9, 10, 11, 12, 13, 14, 18, 21, 24, 0};
// build size menu
for (int32 i = 0; sizes[i]; i++) {
int32 size = sizes[i];
if (size < kMinSize || size > kMaxSize)
continue;
char label[32];
snprintf(label, sizeof(label), "%" B_PRId32, size);
BMessage* message = new BMessage(kMsgSetSize);
message->AddInt32("size", size);
message->AddString("name", Name());
BMenuItem* item = new BMenuItem(label, message);
if (size == fCurrentFont.Size())
item->SetMarked(true);
fSizesMenu->AddItem(item);
item->SetTarget(this);
}
}
void
FontSelectionView::_AddStylesToMenu(const BFont& font, BMenu* stylesMenu) const
{
stylesMenu->RemoveItems(0, stylesMenu->CountItems(), true);
stylesMenu->SetRadioMode(true);
font_family family;
font_style style;
font.GetFamilyAndStyle(&family, &style);
BString currentStyle(style);
int32 numStyles = count_font_styles(family);
for (int32 j = 0; j < numStyles; j++) {
if (get_font_style(family, j, &style) != B_OK)
continue;
BMessage* message = new BMessage(kMsgSetStyle);
message->AddString("family", (char*)family);
message->AddString("style", (char*)style);
BMenuItem* item = new BMenuItem(style, message);
item->SetMarked(currentStyle == style);
stylesMenu->AddItem(item);
item->SetTarget(this);
}
}
| 20.028463 | 79 | 0.714543 | axeld |
4d2112cc143eb22dbf48e50678e77ceb984a7d5c | 3,255 | cpp | C++ | GUIWidgets/BasicStreamEditor/DDTable.cpp | gladk/Dyssol-open | 53eb7b589ad03eb477d743ee6a90ee10297a9366 | [
"BSD-3-Clause"
] | 1 | 2020-07-31T07:10:11.000Z | 2020-07-31T07:10:11.000Z | GUIWidgets/BasicStreamEditor/DDTable.cpp | gladk/Dyssol-open | 53eb7b589ad03eb477d743ee6a90ee10297a9366 | [
"BSD-3-Clause"
] | null | null | null | GUIWidgets/BasicStreamEditor/DDTable.cpp | gladk/Dyssol-open | 53eb7b589ad03eb477d743ee6a90ee10297a9366 | [
"BSD-3-Clause"
] | 1 | 2021-03-04T06:44:38.000Z | 2021-03-04T06:44:38.000Z | /* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */
#include "DDTable.h"
#include <QHeaderView>
CDDTable::CDDTable( QWidget *parent, Qt::WindowFlags flags ) : QWidget(parent, flags)
{
m_pData = NULL;
m_bNormalize = false;
m_pTable = new CQtTable( this );
layout = new QHBoxLayout;
layout->addWidget(m_pTable);
setLayout(layout);
m_pTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
QObject::connect( m_pTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(ItemWasChanged(QTableWidgetItem*)) );
}
CDDTable::~CDDTable()
{
m_pData = NULL;
}
void CDDTable::SetDistribution( CDenseDistr2D* _pDistribution )
{
m_pData = _pDistribution;
m_pTable->setColumnCount( m_pData->GetDimensionsNumber() + 1 );
SetHeaders();
UpdateWholeView();
}
void CDDTable::SetNormalizationCheck( bool _bAnalyse )
{
m_bNormalize = _bAnalyse;
UpdateWholeView();
}
void CDDTable::SetEditable(bool _bEditable)
{
m_pTable->SetEditable(_bEditable);
}
void CDDTable::SetHeaders()
{
if( m_pData == NULL ) return;
m_pTable->setHorizontalHeaderItem( 0, new QTableWidgetItem("Time [s]") );
for( int i=0; i<(int)m_pData->GetDimensionsNumber(); ++i )
{
if( m_pTable->columnCount() < i+2 )
m_pTable->insertColumn( i+2 );
m_pTable->setHorizontalHeaderItem( i+1, new QTableWidgetItem( QString::fromUtf8( m_pData->GetLabel(i).c_str() ) ) );
}
}
void CDDTable::CheckNormalization()
{
for( unsigned i=0; i<m_pData->GetTimePointsNumber(); ++i )
{
std::vector<double> vTemp = m_pData->GetValueForIndex(i);
double dSum = 0;
for( unsigned j=0; j<vTemp.size(); ++j )
dSum += vTemp[j];
if( dSum != 1 )
for( int j=0; j<m_pTable->columnCount(); ++j )
m_pTable->item( i, j )->setBackground( Qt::lightGray );
else
for( int j=0; j<m_pTable->columnCount(); ++j )
m_pTable->item( i, j )->setBackground( Qt::white );
}
}
void CDDTable::UpdateWholeView()
{
if( m_pData == NULL ) return;
m_bAvoidSignal = true;
int iRow;
for( iRow=0; iRow<(int)m_pData->GetTimePointsNumber(); ++iRow )
{
if( iRow >= m_pTable->rowCount() )
m_pTable->insertRow(iRow);
std::vector<double> vTemp = m_pData->GetValueForIndex( iRow );
m_pTable->setItem( iRow, 0, new QTableWidgetItem( QString::number( m_pData->GetTimeForIndex( iRow ) ) ));
m_pTable->item( iRow, 0 )->setFlags( m_pTable->item( iRow, 0 )->flags() & ~Qt::ItemIsEditable );
for( unsigned i=0; i<vTemp.size(); ++i )
m_pTable->setItem( iRow, i+1, new QTableWidgetItem( QString::number( vTemp[i] ) ));
}
while( m_pTable->rowCount() > (int)m_pData->GetTimePointsNumber())
m_pTable->removeRow( m_pTable->rowCount()-1 );
if( m_bNormalize )
CheckNormalization();
m_bAvoidSignal = false;
}
//void CDDTable::setVisible( bool _bVisible )
//{
// if ( _bVisible )
// UpdateWholeView();
// QWidget::setVisible( _bVisible );
//}
void CDDTable::ItemWasChanged( QTableWidgetItem* _pItem )
{
if( m_bAvoidSignal ) return;
unsigned nTimeIndex = _pItem->row();
unsigned nDimIndex = _pItem->column() - 1;
double dVal = _pItem->text().toDouble();
if( dVal < 0 ) dVal = 0;
m_pData->SetValue( nTimeIndex, nDimIndex, dVal );
UpdateWholeView();
emit DataChanged();
}
| 26.25 | 142 | 0.691859 | gladk |
4d24dba9103c6edaab819e7c275ffc14e2841f72 | 1,852 | hpp | C++ | include/enum_tools.hpp | upobir/Enum_Tools | 3b99d4853d4d4a23b9254bc9b7a6530b9d0e19e8 | [
"MIT"
] | null | null | null | include/enum_tools.hpp | upobir/Enum_Tools | 3b99d4853d4d4a23b9254bc9b7a6530b9d0e19e8 | [
"MIT"
] | null | null | null | include/enum_tools.hpp | upobir/Enum_Tools | 3b99d4853d4d4a23b9254bc9b7a6530b9d0e19e8 | [
"MIT"
] | null | null | null | #ifdef GENERATE_DECLARATION_FOR
#define __SIGNATURE GENERATE_DECLARATION_FOR
#define __IMPL_DECLARATION(name, ...) \
{ \
__VA_ARGS__ \
}; \
char const * enumString(name e); \
template<typename T> \
std::vector<T> const enumValues(); \
template<typename T> \
int enumCount();
#define ENUM_CLASS(name, ...) \
enum class name __IMPL_DECLARATION(name, __VA_ARGS__)
#define ENUM_CLASS_WITH_TYPE(name, type, ...) \
enum class name : type __IMPL_DECLARATION(name, __VA_ARGS__)
#define ENUM_PLAIN(name) \
name,
#define ENUM_VALUE(name, value) \
name = value,
__SIGNATURE
#undef __IMPL_DECLARATION
#undef ENUM_CLASS
#undef ENUM_CLASS_WITH_TYPE
#undef ENUM_PLAIN
#undef ENUM_VALUE
#undef __SIGNATURE
#undef GENERATE_DECLARATION_FOR
#endif
#ifdef GENERATE_DEFINITION_FOR
#define __SIGNATURE GENERATE_DEFINITION_FOR
#define ENUM_CLASS_WITH_TYPE(name, type, ...) \
ENUM_CLASS(name, __VA_ARGS__)
#define ENUM_VALUE(name, value) \
ENUM_PLAIN(name)
#define ENUM_CLASS(name, ...) \
char const * enumString(name e){ \
using enumtype = name; \
switch(e){ \
__VA_ARGS__ \
} \
throw "Invalid enum value"; \
return 0; \
}
#define ENUM_PLAIN(name) \
case enumtype :: name : \
return #name ; \
__SIGNATURE
#undef ENUM_CLASS
#undef ENUM_PLAIN
// TODO maybe consider a global vector?
#define ENUM_CLASS(name, ...) \
template<> \
std::vector<name> const enumValues<name>() { \
using enumtype = name; \
return { __VA_ARGS__ }; \
}
#define ENUM_PLAIN(name) \
enumtype :: name ,
__SIGNATURE
#undef ENUM_CLASS
#undef ENUM_PLAIN
#define ENUM_CLASS(name, ...) \
template<> \
int enumCount<name>() { \
return 0 __VA_ARGS__ ; \
}
#define ENUM_PLAIN(name) \
+ 1
__SIGNATURE
#undef ENUM_CLASS
#undef ENUM_PLAIN
#undef ENUM_CLASS_WITH_TYPE
#undef ENUM_VALUE
#undef __SIGNATURE
#undef GENERATE_DEFINITION_FOR
#endif | 17.980583 | 60 | 0.721382 | upobir |
4d2699f1db5c4f512e3eb5c6a710a8ff327426e5 | 742 | hpp | C++ | src/preprocess/mt-metis-0.7.2/wildriver/src/VectorReaderFactory.hpp | curiosityyy/SubgraphMatchGPU | 7089496084d94a72693dca230ed5165cb94ae4a4 | [
"MIT"
] | 2 | 2017-07-25T19:46:52.000Z | 2018-02-13T15:24:02.000Z | external/mt-metis-0.7.2/wildriver/src/VectorReaderFactory.hpp | yfg/GDSP | 56fe2242b32d3a1efd24733d0ab30242ee3df2ba | [
"MIT"
] | 25 | 2017-07-20T02:35:49.000Z | 2018-12-21T01:43:42.000Z | external/mt-metis-0.7.2/wildriver/src/VectorReaderFactory.hpp | yfg/GDSP | 56fe2242b32d3a1efd24733d0ab30242ee3df2ba | [
"MIT"
] | null | null | null | /**
* @file VectorReaderFactory.hpp
* @brief Class for instantiating vector readers.
* @author Dominique LaSalle <wildriver@domnet.org>
* Copyright 2015-2016
* @version 1
* @date 2015-02-07
*/
#ifndef WILDRIVER_VECTORREADERFACTORY_HPP
#define WILDRIVER_VECTORREADERFACTORY_HPP
#include <memory>
#include <string>
#include "IVectorReader.hpp"
namespace WildRiver
{
class VectorReaderFactory
{
public:
/**
* @brief Allocate a new vector readder subclass based on teh file
* extension.
*
* @param name The filename/path to open.
*
* @return The newly opened vector reader.
*/
static std::unique_ptr<IVectorReader> make(
std::string const & name);
};
}
#endif
| 13.017544 | 70 | 0.672507 | curiosityyy |
4d2c203b5abe796346d389d430964b001bd6a2be | 4,672 | cpp | C++ | SharedCode/SMbbox3d.cpp | timskillman/raspberrypi | bf5ce1fe98f2b6571a05da2e92a7b783441ac692 | [
"MIT"
] | 17 | 2018-11-17T14:41:54.000Z | 2021-12-07T17:01:21.000Z | SharedCode/SMbbox3d.cpp | timskillman/raspberrypi | bf5ce1fe98f2b6571a05da2e92a7b783441ac692 | [
"MIT"
] | 4 | 2018-10-18T05:43:57.000Z | 2020-10-01T22:03:08.000Z | SharedCode/SMbbox3d.cpp | timskillman/raspberrypi | bf5ce1fe98f2b6571a05da2e92a7b783441ac692 | [
"MIT"
] | 4 | 2018-10-18T05:15:57.000Z | 2020-11-04T04:13:46.000Z | #include "SMbbox3d.h"
#ifdef __WINDOWS__
#include <cmath>
#endif
void SMbbox3d::init()
{
min = vec3f(1e8, 1e8, 1e8);
max = vec3f(-1e8, -1e8, -1e8);
radius = 0;
}
SMbbox3d::SMbbox3d(vec3f _min, vec3f _max)
{
init();
}
void SMbbox3d::update(vec3f point)
{
if (point.x < min.x) min.x = point.x;
if (point.x > max.x) max.x = point.x;
if (point.y < min.y) min.y = point.y;
if (point.y > max.y) max.y = point.y;
if (point.z < min.z) min.z = point.z;
if (point.z > max.z) max.z = point.z;
//approximate radius from bbox ..
vec3f d = max - center();
float r = sqrtf(d.x*d.x + d.y*d.y + d.z*d.z);
if (r > radius) radius = r;
}
void SMbbox3d::update(SMbbox3d box, SMmatrix* mtx)
{
update(mtx->transformVec(vec3f(box.min.x, box.min.y, box.min.z)));
update(mtx->transformVec(vec3f(box.max.x, box.min.y, box.min.z)));
update(mtx->transformVec(vec3f(box.max.x, box.max.y, box.min.z)));
update(mtx->transformVec(vec3f(box.min.x, box.max.y, box.min.z)));
update(mtx->transformVec(vec3f(box.min.x, box.min.y, box.max.z)));
update(mtx->transformVec(vec3f(box.max.x, box.min.y, box.max.z)));
update(mtx->transformVec(vec3f(box.max.x, box.max.y, box.max.z)));
update(mtx->transformVec(vec3f(box.min.x, box.max.y, box.max.z)));
}
void SMbbox3d::update(SMbbox3d box)
{
update(vec3f(box.min.x, box.min.y, box.min.z));
update(vec3f(box.max.x, box.min.y, box.min.z));
update(vec3f(box.max.x, box.max.y, box.min.z));
update(vec3f(box.min.x, box.max.y, box.min.z));
update(vec3f(box.min.x, box.min.y, box.max.z));
update(vec3f(box.max.x, box.min.y, box.max.z));
update(vec3f(box.max.x, box.max.y, box.max.z));
update(vec3f(box.min.x, box.max.y, box.max.z));
}
void SMbbox3d::set(SMbbox3d box, SMmatrix* mtx)
{
init();
update(box, mtx);
}
void SMbbox3d::bboxFromVerts(std::vector<float> &verts, uint32_t start, uint32_t vsize, uint32_t stride)
{
min.x = verts[start]; max.x = min.x;
min.y = verts[start + 1]; max.y = min.y;
min.z = verts[start + 2]; max.z = min.z;
for (uint32_t i = 0; i < vsize; i += stride) {
if (verts[i] < min.x) min.x = verts[i]; else if (verts[i] > max.x) max.x = verts[i];
if (verts[i + 1] < min.y) min.y = verts[i + 1]; else if (verts[i + 1] > max.y) max.y = verts[i + 1];
if (verts[i + 2] < min.z) min.z = verts[i + 2]; else if (verts[i + 2] > max.z) max.z = verts[i + 2];
}
}
void SMbbox3d::radiusFromVerts(std::vector<float> &verts, vec3f centre, uint32_t start, uint32_t size, uint32_t stride)
{
uint32_t st = start*stride;
uint32_t sz = size*stride;
//Works out the bounding radius of the vertices
radius = 0;
//TODO: This should strictly determine bounds by vertices 'used' in the scene according to polygon indices.
for (std::size_t i = st; i < (st+sz); i=stride) {
vec3f d = vec3f(verts[i], verts[i+1], verts[i+2]) - centre;
float r = sqrtf(d.x*d.x + d.y*d.y + d.z*d.z);
if (r > radius) radius = r;
}
}
float SMbbox3d::radiusFromTVerts(std::vector<float> &verts, vec3f centre, SMmatrix* mtx, uint32_t start, uint32_t size, uint32_t stride)
{
uint32_t st = start*stride;
uint32_t sz = size*stride;
//Works out the bounding radius of the vertices
float rad = 0;
//TODO: This should strictly determine bounds by vertices 'used' in the scene according to polygon indices.
for (std::size_t i = st; i < (st + sz); i = stride) {
vec3f d = mtx->transformVec(vec3f(verts[i], verts[i + 1], verts[i + 2])) - centre;
float r = sqrtf(d.x*d.x + d.y*d.y + d.z*d.z);
if (r > rad) rad = r;
}
return rad;
}
SMbbox3d SMbbox3d::bboxFromTVerts(SMmatrix* mtx)
{
//Transforms a bounding box with a matrix
SMbbox3d tbox;
tbox.update(*this);
return tbox;
}
void SMbbox3d::bboxFromTVerts(std::vector<float> &verts, SMmatrix* mtx, uint32_t start, uint32_t size, uint32_t stride)
{
uint32_t st = start*stride;
uint32_t sz = size*stride;
//Assumes first three values of the vertex element is position data
min = mtx->transformVec(vec3f(verts[st], verts[st+1], verts[st+2]));
max = min;
//TODO: This should strictly determine bounds by vertices 'used' in the scene according to polygon indices.
for (std::size_t i = st; i < (st+sz); i += stride) {
vec3f tvec = mtx->transformVec(vec3f(verts[i], verts[i + 1], verts[i + 2]));
if (tvec.x < min.x) min.x = tvec.x; else if (tvec.x > max.x) max.x = tvec.x;
if (tvec.y < min.y) min.y = tvec.y; else if (tvec.y > max.y) max.y = tvec.y;
if (tvec.z < min.z) min.z = tvec.z; else if (tvec.z > max.z) max.z = tvec.z;
}
radius = radiusFromTVerts(verts, center(), mtx, start, size, stride);
}
void SMbbox3d::translate(vec3f t)
{
min += t; max += t;
}
void SMbbox3d::moveto(vec3f p)
{
vec3f bc = center();
min = (min-bc)+p;
max = (max-bc)+p;
} | 32.22069 | 136 | 0.648545 | timskillman |
4d2cd2c663b134e7f69151b525afbc5308ac77b0 | 571 | hpp | C++ | include/mgard-x/MDR/Writer/WriterInterface.hpp | JieyangChen7/MGARD | acec8facae1e2767a3adff2bb3c30f3477e69bdb | [
"Apache-2.0"
] | null | null | null | include/mgard-x/MDR/Writer/WriterInterface.hpp | JieyangChen7/MGARD | acec8facae1e2767a3adff2bb3c30f3477e69bdb | [
"Apache-2.0"
] | null | null | null | include/mgard-x/MDR/Writer/WriterInterface.hpp | JieyangChen7/MGARD | acec8facae1e2767a3adff2bb3c30f3477e69bdb | [
"Apache-2.0"
] | null | null | null | #ifndef _MDR_WRITER_INTERFACE_HPP
#define _MDR_WRITER_INTERFACE_HPP
namespace MDR {
namespace concepts {
// Refactored data writer
class WriterInterface {
public:
virtual ~WriterInterface() = default;
virtual std::vector<uint32_t> write_level_components(
const std::vector<std::vector<uint8_t *>> &level_components,
const std::vector<std::vector<uint32_t>> &level_sizes) const = 0;
virtual void write_metadata(uint8_t const *metadata, uint32_t size) const = 0;
virtual void print() const = 0;
};
} // namespace concepts
} // namespace MDR
#endif
| 24.826087 | 80 | 0.744308 | JieyangChen7 |
4d325d3af3083b0d8034d923dfb5f15049d5fb9b | 15,456 | cpp | C++ | messungen/normalize_17-Trace/normalize/main.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 16 | 2021-04-10T16:28:00.000Z | 2021-12-12T10:15:23.000Z | messungen/normalize_17-Trace/normalize/main.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | null | null | null | messungen/normalize_17-Trace/normalize/main.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 2 | 2021-04-10T16:32:36.000Z | 2021-04-11T14:13:45.000Z | //
// main.cpp
// normalize
//
// Created by tihmstar on 31.10.19.
// Copyright © 2019 tihmstar. All rights reserved.
//
#include <iostream>
#include "Traces.hpp"
#include <vector>
#include <future>
#include <sys/stat.h>
#include <string.h>
#include <limits.h>
#include <tuple>
#include <algorithm>
#include <archive.h>
#include <archive_entry.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/resource.h>
#define assure(cond) do {if (!(cond)) {printf("ERROR: ASSURE FAILED IN main.cpp ON LINE=%d\n",__LINE__); raise(SIGABRT); exit(-1);}}while (0)
#define safeFree(ptr) do { if (ptr){ free(ptr); ptr = NULL;} }while(0)
#define SIMD
#ifdef SIMD
#include "immintrin.h" // for AVX
#endif
#ifdef DEBUG
#define dbg_assure(cond) assure(cond)
#else
#define dbg_assure(cond) //
#endif
#define MAX(a,b) (a > b) ? (a) : (b)
#define MIN(a,b) (a < b) ? (a) : (b)
#define MOVE_RADIUS 500
#ifdef NOMAIN
#define DONT_HAVE_FILESYSTEM
#endif
#ifndef DONT_HAVE_FILESYSTEM
#include <filesystem>
#ifdef __APPLE__
using namespace std::__fs;
#endif //__APPLE__
#else
#include <dirent.h>
//really crappy implementation in case <filesystem> isn't available :o
class myfile{
std::string _path;
public:
myfile(std::string p): _path(p){}
std::string path(){return _path;}
};
class diriter{
public:
std::vector<myfile> _file;
auto begin(){return _file.begin();}
auto end(){return _file.end();}
};
namespace std {
namespace filesystem{
diriter directory_iterator(std::string);
}
}
diriter std::filesystem::directory_iterator(std::string dirpath){
DIR *dir = NULL;
struct dirent *ent = NULL;
diriter ret;
assure(dir = opendir(dirpath.c_str()));
while ((ent = readdir (dir)) != NULL) {
if (ent->d_type != DT_REG)
continue;
ret._file.push_back({dirpath + "/" + ent->d_name});
}
if (dir) closedir(dir);
return ret;
}
#endif
using namespace std;
void increase_file_limit() {
struct rlimit rl = {};
int error = getrlimit(RLIMIT_NOFILE, &rl);
assure(error == 0);
rl.rlim_cur = 10240;
rl.rlim_max = rl.rlim_cur;
error = setrlimit(RLIMIT_NOFILE, &rl);
if (error != 0) {
printf("could not increase file limit\n");
}
error = getrlimit(RLIMIT_NOFILE, &rl);
assure(error == 0);
if (rl.rlim_cur != 10240) {
printf("file limit is %llu\n", rl.rlim_cur);
}
}
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
#ifdef SIMD
__v16qi abs(__v16qi val){
__v16qi zero = _mm_set1_epi8(0);
__v16qi neg = _mm_sub_epi8(zero, val);
__v16qi absv = _mm_max_epi8(neg, val);
return absv;
}
//Sub method
int maxfaltung(const int8_t *t1, const int8_t *t2, int size){
int faltn = 0;
int64_t minFaltWert = LLONG_MAX;
__v16qi zero = _mm_setzero_si128();
for (int n=-MOVE_RADIUS; n<MOVE_RADIUS; n++) {
__v2di faltWerte = _mm_setzero_si128();
for (int k=0; k<size-sizeof(__v16qi); k+=sizeof(__v16qi)) {
__v16qi v1 = *(__v16qi*)&t1[k]; //aligned access
__v16qi v2; //usually unaligned access
((__v8qi*)&v2)[0] = *(__v8qi*)&t2[k+n];
((__v8qi*)&v2)[1] = *(__v8qi*)&t2[k+n+sizeof(__v8qi)];
__v16qi diff = v1 - v2;
__v16qi ndiff = _mm_sub_epi8(zero, diff);
__v16qi adiff = _mm_max_epi8(ndiff, diff);
__v2di falt = _mm_sad_epu8(adiff, zero);
faltWerte = _mm_add_epi64(faltWerte, falt);
}
int64_t faltWert = ((int64_t*)&faltWerte)[0] + ((int64_t*)&faltWerte)[1];
if (minFaltWert>faltWert) {
minFaltWert = faltWert;
faltn = n;
}
}
return faltn;
}
#else
#error no non-SIMD implementation
#endif //SIMD
int doNormalize(const char *indir, const char *outdir, int threadsCnt, int maxTraces){
printf("start\n");
atomic<uint16_t> wantWriteCounter{0};
vector<future<void>> workers;
int8_t *meanTrace = NULL;
int8_t *meanTrace2 = NULL;
int8_t *meanTrace3 = NULL;
printf("threads=%d\n",threadsCnt);
printf("indir=%s\n",indir);
printf("outdir=%s\n",outdir);
#pragma mark list files
printf("reading trace\n");
vector<string> toNormalizeList;
mutex meanLock;
mutex listLock;
mutex fileWriteEvent;
for(auto& p: filesystem::directory_iterator(indir)){
if (!ends_with(p.path(), ".dat") && !ends_with(p.path(), ".dat.tar.gz")) {
continue;
}
printf("adding to list=%s\n",p.path().c_str());
toNormalizeList.push_back(p.path());
if (maxTraces && (int)toNormalizeList.size() >= maxTraces) {
printf("limiting list to %d files\n",maxTraces);
break;
}
}
size_t filesCnt = toNormalizeList.size();
std::reverse(toNormalizeList.begin(),toNormalizeList.end());
atomic_uint16_t activeWorkerCnt{0};
auto workerfunc = [&](int workerNum)->void{
printf("[T-%d] worker started\n",workerNum);
++activeWorkerCnt;
while (true) {
printf("[T-%d] getting tracesfile...\n",workerNum);
listLock.lock();
size_t todoCnt = toNormalizeList.size();
if (toNormalizeList.size()) {
vector<tuple<int8_t*, uint8_t *, uint8_t *>> *tstarts = new vector<tuple<int8_t*, uint8_t *, uint8_t *>>();
struct stat fstat = {};
string tpath = toNormalizeList.back();
toNormalizeList.pop_back();
listLock.unlock();
string filename = tpath.substr(tpath.find_last_of("/")+1);
string outfilepath = outdir;
if (outfilepath.back() != '/') {
outfilepath+= '/';
}
outfilepath+="normalized_";
outfilepath+=filename;
if (stat(outfilepath.c_str(),&fstat) != -1) {
printf("[T-%d] normalized trace already exists=%s\n",workerNum,outfilepath.c_str());
continue;
}
printf("[T-%d] [ %3lu of %3lu] normalizing trace=%s\n",workerNum,(filesCnt+1-todoCnt),filesCnt,tpath.c_str());
Traces *curtrace = new Traces(tpath.c_str());
#define START_POS 0
#define FALT_SIZE 3000
#define FALT_SIZE2 3000
#define FALT_SIZE3 1000
//#define SAMPLE_SIZE 35000
#define SAMPLE_SIZE 74000
//#define MIN_PEAK_VALUE (-65)
//#define PRE_SIZE (1000)
uint32_t tracesInFile = 0;
int tnum = -1;
for (auto ms : *curtrace) {
tnum++;
int maxPos = START_POS;
int maxVal = 0;
for (int p=47000; p<53000; p++) {
if (ms->Trace[p]<-65) {
maxPos = p;
goto afterBadTrace;
break;
}
}
badtrace:
#ifdef DEBUG
printf("badtrace=%d\n",tnum);
#endif
continue;
afterBadTrace:
int off = 0;
off -=1000;
if (!meanTrace) {
meanLock.lock();
if (!meanTrace) {
//first set a mean
assure(meanTrace = (int8_t*)malloc((FALT_SIZE + MOVE_RADIUS) * sizeof(*meanTrace)));
memcpy(meanTrace, (int8_t*)&ms->Trace[maxPos], (FALT_SIZE + MOVE_RADIUS) * sizeof(*meanTrace));
}
meanLock.unlock();
}else{
off = maxfaltung(meanTrace, &ms->Trace[maxPos], FALT_SIZE);
}
off -= 47000;
for (int p=26500; p<33500; p++) {
if (ms->Trace[maxPos+off+p] < -2) {
goto badtrace;
}
}
for (int p=37500; p<46000; p++) {
if (ms->Trace[maxPos+off+p] < -65) {
goto badtrace;
}
}
for (int p=36700; p<44000; p++) {
if (ms->Trace[maxPos+off+p] < 10) {
goto badtrace;
}
}
tracesInFile++;
tstarts->push_back({(int8_t*)&ms->Trace[maxPos+off]/*Trace*/,(uint8_t*)ms->Input/*Plaintext*/,(uint8_t*)ms->Output/*Ciphertext*/});
#ifdef DEBUG
if (tnum % 100 == 0) {
printf("[T-%d] tracenum=%d\n",workerNum,tnum);
}
#warning DEBUG
if (tnum > 2000) break;
#endif
}
auto compressedwritefunc = [&fileWriteEvent, &wantWriteCounter](Traces *curtrace,vector<tuple<int8_t*, uint8_t *, uint8_t *>> *tstarts, uint32_t tracesInFile, string outfilepath, int workerNum)->void{
printf("[WT-%d] compressing normalized trace...\n",workerNum);
ssize_t lastSlash = outfilepath.rfind("/");
std::string outfilename = outfilepath;
if (lastSlash != std::string::npos) {
outfilename = outfilepath.substr(lastSlash+1);
}
if (outfilepath.substr(outfilepath.size()-sizeof(".tar.gz")+1) != ".tar.gz") {
outfilepath += ".tar.gz";
}
std::string tmpoutfilepath = outfilepath;
tmpoutfilepath += ".partial";
struct archive *a = NULL;
struct archive_entry *entry = NULL;
a = archive_write_new();
archive_write_add_filter_gzip(a);
archive_write_set_format_pax_restricted(a);
archive_write_open_filename(a, tmpoutfilepath.c_str());
uint32_t np = SAMPLE_SIZE;
size_t fileSize = sizeof(tracesInFile) + tstarts->size() * (sizeof(np) + sizeof(Traces::MeasurementStructure::Input) + sizeof(Traces::MeasurementStructure::Output) + np);
if (outfilename.substr(outfilename.size()-sizeof(".tar.gz")+1) == ".tar.gz") {
outfilename = outfilename.substr(0,outfilename.size()-sizeof(".tar.gz")+1);
}
entry = archive_entry_new();
archive_entry_set_pathname(entry, outfilename.c_str());
archive_entry_set_size(entry, fileSize); // Note 3
archive_entry_set_filetype(entry, AE_IFREG);
archive_entry_set_perm(entry, 0644);
archive_entry_set_mtime(entry, time(NULL), 0);
archive_write_header(a, entry);
archive_write_data(a, &tracesInFile, sizeof(tracesInFile)); //TracesInFile (actual data!)
for (auto p : *tstarts) {
archive_write_data(a, &np, sizeof(np)); //PointsPerTrace
archive_write_data(a, get<1>(p), sizeof(Traces::MeasurementStructure::Input)); //Plaintext
archive_write_data(a, get<2>(p), sizeof(Traces::MeasurementStructure::Output)); //Ciphertext
archive_write_data(a, get<0>(p), np); //Trace
}
archive_entry_free(entry);
archive_write_close(a); // Note 4
archive_write_free(a); // Note 5
delete curtrace;
delete tstarts;
rename(tmpoutfilepath.c_str(), outfilepath.c_str());
printf("[WT-%d] done saving compressed normalized trace to %s! (%u remaining writers)\n",workerNum, outfilepath.c_str(),((uint16_t)wantWriteCounter)-1);
wantWriteCounter.fetch_sub(1);
fileWriteEvent.unlock(); //send wantWriteCounter update event
};
while (wantWriteCounter.fetch_add(1) > threadsCnt) {
wantWriteCounter.fetch_sub(1);
printf("[T-%d] writer limit reached, waiting for some writers to finish...\n",workerNum);
fileWriteEvent.lock();
}
fileWriteEvent.unlock(); //always send event when counter is modified
std::thread wthread(compressedwritefunc,curtrace,tstarts,tracesInFile,outfilepath,workerNum);
wthread.detach();
}else{
listLock.unlock();
printf("[T-%d] no more traces available\n",workerNum);
break;
}
}
--activeWorkerCnt;
printf("[T-%d] worker finished (%d remaining workers)\n",workerNum,(uint16_t)activeWorkerCnt);
};
printf("spinning up %d worker threads\n",threadsCnt);
for (int i=0; i<threadsCnt; i++){
workers.push_back(std::async(std::launch::async,workerfunc,i));
// workerfunc(i);
sleep(1);
}
printf("waiting for workers to finish...\n");
for (int i=0; i<threadsCnt; i++){
workers[i].wait();
}
printf("all workers finished!\n");
printf("waiting for writers to finish...\n");
while ((uint16_t)wantWriteCounter > 0) {
//we are only waiting for a few writers here, which are about to finish
//eventlocks lead to locking issues.
//don't hog CPU and sping here, sleep should be good enough, we won't stay here very long
sleep(5);
}
printf("all writers finished!\n");
// assure(beginOffset < (PRE_SIZE_WORK - PRE_SIZE));
// assure(-endOffset < (SAMPLE_SIZE_WORK - SAMPLE_SIZE));
safeFree(meanTrace);
safeFree(meanTrace2);
safeFree(meanTrace3);
printf("done!\n");
return 0;
}
int r_main(int argc, const char * argv[]) {
if (argc < 3) {
printf("Usage: %s <traces dir path> <outdir>\n",argv[0]);
return -1;
}
increase_file_limit();
int threadsCnt = (int)sysconf(_SC_NPROCESSORS_ONLN);
int maxTraces = 0;
const char *indir = argv[1];
const char *outdir = argv[2];
if (argc > 3) {
threadsCnt = atoi(argv[3]);
}
if (argc > 4) {
maxTraces = atoi(argv[4]);
}
return doNormalize(indir, outdir, threadsCnt, maxTraces);
}
#ifndef NOMAIN
int main(int argc, const char * argv[]) {
#ifdef DEBUG
return r_main(argc, argv);
#else //DEBUG
try {
r_main(argc, argv);
} catch (int e) {
printf("ERROR: died on line=%d\n",e);
}
#endif //DEBUG
}
#endif //NOMAIN
| 32.06639 | 216 | 0.522386 | tihmstar |
4d32964fecfdc00c83931a8d29dc1b4f3875822b | 491 | cpp | C++ | src/main.cpp | electromaggot/HelloVulkanSDL | 9f63569f1b902ec761d855d6829beead01e8f72b | [
"Unlicense"
] | 3 | 2019-12-05T04:46:47.000Z | 2021-09-04T23:14:27.000Z | src/main.cpp | electromaggot/HelloVulkanSDL | 9f63569f1b902ec761d855d6829beead01e8f72b | [
"Unlicense"
] | 2 | 2022-02-18T10:40:12.000Z | 2022-02-20T16:29:37.000Z | src/main.cpp | electromaggot/HelloVulkanSDL | 9f63569f1b902ec761d855d6829beead01e8f72b | [
"Unlicense"
] | null | null | null | //
// main.cpp
//
// Created 1/27/19 by Tadd Jensen
// © 0000 (uncopyrighted; use at will)
//
#include "HelloTriangle.h"
#include "AppConstants.h"
#include "Logging.h"
int main(int argc, char* argv[])
{
AppConstants.setExePath(argv[0]);
LogStartup();
HelloApplication app;
try {
app.Init();
app.Run();
} catch (const exception& e) {
const char* message = e.what();
app.DialogBox(message);
Log(RAW, "FAIL: %s", message);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 15.34375 | 38 | 0.653768 | electromaggot |
2ec179ff2601e6190d42b11645f386ca07d2a501 | 3,190 | cpp | C++ | backends/analysis/ub/ControlLattice.cpp | dragosdmtrsc/bf4 | 2e15e50acc4314737d99093b3d900fa44d795958 | [
"Apache-2.0"
] | 10 | 2020-08-05T12:52:37.000Z | 2021-05-20T02:15:04.000Z | backends/analysis/ub/ControlLattice.cpp | shellqiqi/bf4 | 6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f | [
"Apache-2.0"
] | 4 | 2020-09-28T12:17:50.000Z | 2021-11-23T12:23:38.000Z | backends/analysis/ub/ControlLattice.cpp | shellqiqi/bf4 | 6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f | [
"Apache-2.0"
] | 2 | 2020-10-13T07:59:42.000Z | 2021-12-08T21:35:05.000Z | //
// Created by dragos on 17.12.2019.
//
#include "ControlLattice.h"
#include "AnalysisContext.h"
namespace analysis {
ControlLattice::ControlLattice(ReferenceMap *refMap, TypeMap *typeMap,
const CFG *g, NodeToFunctionMap *funmap)
: refMap(refMap), typeMap(typeMap), cfg(g), funmap(funmap) {}
NodeValues<control_struct> ControlLattice::run() {
DefaultDiscipline dd(&cfg->holder, cfg->start_node);
auto init = this->operator()();
init.control_nodes.emplace();
NodeValues<control_struct> res({{cfg->start_node, init}});
auto rr = std::ref(*this);
WorklistAlgo<control_struct, decltype(rr), DefaultDiscipline, decltype(rr),
decltype(rr)>
algo(*cfg, rr, dd, rr, rr);
algo(cfg->start_node, res);
return std::move(res);
}
ControlLattice::Lattice ControlLattice::operator()() {
return analysis::ControlLattice::Lattice();
}
ControlLattice::Lattice ControlLattice::
operator()(node_t n, const Edge &, const ControlLattice::Lattice &l) {
if (std::any_of(instructions(n).begin(), instructions(n).end(),
[this](const IR::Node *n) {
return is_controlled(node_t(n), refMap, typeMap);
})) {
control_struct cpy;
for (auto path : l.control_nodes) {
path.push_back(n);
cpy.control_nodes.emplace(path);
}
return std::move(cpy);
}
return l;
}
ControlLattice::Lattice ControlLattice::
operator()(node_t, const Edge &, const ControlLattice::Lattice &,
const ControlLattice::Lattice &) {
BUG("should not reach this point");
}
ControlLattice::Lattice ControlLattice::
operator()(const ControlLattice::Lattice &l, ControlLattice::Lattice r) {
if (l.control_nodes.empty())
return std::move(r);
if (r.control_nodes.empty())
return l;
for (const auto &x : l.control_nodes)
r.control_nodes.emplace(x);
return std::move(r);
}
NodeValues<control_struct>
ControlLattice::controlPaths(ReferenceMap *refMap, TypeMap *typeMap,
const CFG *g, NodeToFunctionMap *funmap) {
ControlLattice controlLattice(refMap, typeMap, g, funmap);
return controlLattice.run();
}
NodeValues<control_struct>
ControlLattice::controlPaths(ReferenceMap *refMap, TypeMap *typeMap,
EdgeHolder &g, const node_t &start,
NodeToFunctionMap *funmap) {
auto cfg = new CFG(nullptr, std::move(g));
cfg->start_node = start;
auto ret = controlPaths(refMap, typeMap, cfg, funmap);
g = std::move(cfg->holder);
return std::move(ret);
}
NodeValues<NodeSet> ReachControls::run() {
DefaultDiscipline dd(&cfg->holder, cfg->start_node);
auto init = this->operator()();
NodeValues<Lattice> res({{cfg->start_node, init}});
auto rr = std::ref(*this);
WorklistAlgo<Lattice, decltype(rr), DefaultDiscipline, decltype(rr),
decltype(rr)>
algo(*cfg, rr, dd, rr, rr);
algo(cfg->start_node, res);
return std::move(res);
}
ReachControls::ReachControls(ReferenceMap *refMap, TypeMap *typeMap,
const CFG *cfg, NodeToFunctionMap *funmap)
: refMap(refMap), typeMap(typeMap), cfg(cfg), funmap(funmap) {}
} | 32.886598 | 77 | 0.655799 | dragosdmtrsc |
2ec4fcdf2bcc951a27ba495a8edaa1a6c512fa79 | 905 | cpp | C++ | src/pwc.cpp | CardinalModules/TheXOR | 910b76622c9100d9755309adf76542237c6d3a77 | [
"CC0-1.0"
] | 1 | 2021-12-12T22:08:23.000Z | 2021-12-12T22:08:23.000Z | src/pwc.cpp | CardinalModules/TheXOR | 910b76622c9100d9755309adf76542237c6d3a77 | [
"CC0-1.0"
] | null | null | null | src/pwc.cpp | CardinalModules/TheXOR | 910b76622c9100d9755309adf76542237c6d3a77 | [
"CC0-1.0"
] | 1 | 2021-12-12T22:08:29.000Z | 2021-12-12T22:08:29.000Z | #include "../include/pwc.hpp"
void pwc::process(const ProcessArgs &args)
{
float vOut = 0;
if(trigger.process(inputs[IN].getVoltage()))
{
float v = (0.001f+params[PW].getValue()) * 0.01f; // valore in secondi
pulsed.trigger(v);
vOut = LVL_MAX;
} else
{
float deltaTime = 1.0 / args.sampleRate;
int pulseStatus = pulsed.process(deltaTime);
if (pulseStatus == -1)
{
vOut = 0;
} else
{
vOut = pulsed.inProgress ? LVL_MAX : 0;
}
}
outputs[OUT].setVoltage(vOut);
}
pwcWidget::pwcWidget(pwc *module)
{
CREATE_PANEL(module, this, 3, "res/modules/pwc.svg");
addInput(createInput<portRSmall>(Vec(mm2px(4.678), yncscape(97.491, 5.885)), module, pwc::IN));
addParam(createParam<Davies1900hFixWhiteKnobSmall>(Vec(mm2px(3.620), yncscape(55.82, 8)), module, pwc::PW));
addOutput(createOutput<portRSmall>(Vec(mm2px(4.678), yncscape(9.385, 5.885)), module, pwc::OUT));
}
| 24.459459 | 109 | 0.666298 | CardinalModules |
2ec8bf18bba624a9745419c0f9f7a3e1b84c6f72 | 3,510 | cc | C++ | bazel/process-creation-times/createproc-win.cc | laszlocsomor/projects | fb0f8b62046c0c420dc409d2e44c10728028ea1a | [
"Apache-2.0"
] | 2 | 2018-02-21T13:51:38.000Z | 2019-09-10T19:35:15.000Z | bazel/process-creation-times/createproc-win.cc | laszlocsomor/projects | fb0f8b62046c0c420dc409d2e44c10728028ea1a | [
"Apache-2.0"
] | null | null | null | bazel/process-creation-times/createproc-win.cc | laszlocsomor/projects | fb0f8b62046c0c420dc409d2e44c10728028ea1a | [
"Apache-2.0"
] | 2 | 2018-08-14T11:31:21.000Z | 2020-01-10T15:47:49.000Z | #define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <string.h>
#include <algorithm>
#include <array>
#include <iostream>
bool RunProc(char* cmdline, LARGE_INTEGER* create_time, LARGE_INTEGER* full_time) {
LARGE_INTEGER start;
QueryPerformanceCounter(&start);
PROCESS_INFORMATION processInfo;
STARTUPINFOA startupInfo = {0};
BOOL ok = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL,
&startupInfo, &processInfo);
if (!ok) {
DWORD err = GetLastError();
std::cerr << "ERROR: CreateProcessA error: " << err << std::endl;
return false;
}
QueryPerformanceCounter(create_time);
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
QueryPerformanceCounter(full_time);
create_time->QuadPart -= start.QuadPart;
full_time->QuadPart -= start.QuadPart;
return true;
}
size_t percentile_index(size_t total, size_t a, size_t b) {
return std::min<size_t>(total - 1, (total * a) / b);
}
int main(int argc, char* argv[]) {
if (argc == 1) {
static const size_t kSamples = 1000;
char cmdline[1000];
size_t argv0len = strlen(argv[0]);
strcpy(cmdline, argv[0]);
cmdline[argv0len] = ' ';
cmdline[argv0len + 1] = 'x';
cmdline[argv0len + 2] = 0;
std::array<LARGE_INTEGER, kSamples> create_time;
std::array<LARGE_INTEGER, kSamples> full_time;
for (size_t i = 0; i < kSamples; ++i) {
if (!RunProc(cmdline, &create_time[i], &full_time[i])) {
return 1;
}
if (i % 10 == 0) {
std::cout << "ran " << i << " processes\r";
}
}
std::sort(
create_time.begin(), create_time.end(),
[](LARGE_INTEGER a, LARGE_INTEGER b) { return a.QuadPart < b.QuadPart; });
std::sort(
full_time.begin(), full_time.end(),
[](LARGE_INTEGER a, LARGE_INTEGER b) { return a.QuadPart < b.QuadPart; });
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
for (size_t i = 0; i < kSamples; ++i) {
create_time[i].QuadPart = (create_time[i].QuadPart * 1000000) / freq.QuadPart;
full_time[i].QuadPart = (full_time[i].QuadPart * 1000000) / freq.QuadPart;
}
std::cout << std::endl;
std::cout << "CreateProcess times" << std::endl;
std::cout << " 95th %%: " << create_time[percentile_index(kSamples, 95, 100)].QuadPart << " us" << std::endl;
std::cout << " 99th %%: " << create_time[percentile_index(kSamples, 99, 100)].QuadPart << " us" << std::endl;
std::cout << " 99.5th %%: " << create_time[percentile_index(kSamples, 995, 1000)].QuadPart << " us" << std::endl;
std::cout << " 99.9th %%: " << create_time[percentile_index(kSamples, 999, 1000)].QuadPart << " us" << std::endl;
std::cout << " max: " << create_time[kSamples - 1].QuadPart << " us" << std::endl;
std::cout << std::endl;
std::cout << "CreateProcess + WaitForSingleObject times" << std::endl;
std::cout << " 95th %%: " << full_time[percentile_index(kSamples, 95, 100)].QuadPart << " us" << std::endl;
std::cout << " 99th %%: " << full_time[percentile_index(kSamples, 99, 100)].QuadPart << " us" << std::endl;
std::cout << " 99.5th %%: " << full_time[percentile_index(kSamples, 995, 1000)].QuadPart << " us" << std::endl;
std::cout << " 99.9th %%: " << full_time[percentile_index(kSamples, 999, 1000)].QuadPart << " us" << std::endl;
std::cout << " max: " << full_time[kSamples - 1].QuadPart << " us" << std::endl;
}
return 0;
}
| 42.289157 | 118 | 0.623932 | laszlocsomor |
2eca4984678648b60563a603980246481717f2a0 | 11,470 | cc | C++ | src/argh/argh.cc | shrimpster00/argh | e9570ec712573156b04b0b29395877cf8d76da10 | [
"MIT"
] | 1 | 2021-09-25T03:31:58.000Z | 2021-09-25T03:31:58.000Z | src/argh/argh.cc | shrimpster00/argh | e9570ec712573156b04b0b29395877cf8d76da10 | [
"MIT"
] | null | null | null | src/argh/argh.cc | shrimpster00/argh | e9570ec712573156b04b0b29395877cf8d76da10 | [
"MIT"
] | null | null | null | // src/argh/argh.cc
// v0.3.2
//
// Author: Cayden Lund
// Date: 09/28/2021
//
// This file contains the argh implementation.
// Use this utility to parse command line arguments.
//
// Copyright (C) 2021 Cayden Lund <https://github.com/shrimpster00>
// License: MIT <opensource.org/licenses/MIT>
#include "argh.h"
#include "positional_arg.h"
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_set>
#include <vector>
// The argh namespace contains all of the argh functionality
// and utility functions.
namespace argh
{
// The argh::argh class is the main class for the argh utility.
// Use this class to parse command line arguments from the argv vector.
//
// We follow the GNU style of arguments, and define two types of arguments:
//
// 1. Options.
// These may be defined as a single dash followed by a single letter,
// or by a double dash followed by a single word.
// A list of single-letter options may be given at once, following a single dash without spaces.
// These are usually not required arguments.
// There are two kinds of options:
// a. Flags. These are boolean arguments that are either present or not present.
// b. Parameters. These are arguments that take a value.
// If a parameter contains the character '=', its value is the rest of the string.
// Otherwise, the value is the next argument in the argv vector.
// 2. Positional arguments.
// These are arguments that are interpreted by the program.
// Positional arguments are often required.
//
// Usage is quite simple.
//
// Pass the argv vector to the constructor.
//
// argh::argh args(argv);
//
// Access flags using the operator[] with a string.
//
// if (args["-h"] || args["--help"])
// {
// std::cout << "Help message." << std::endl;
// return 0;
// }
//
// Access parameters using the operator() with a string.
//
// std::string output_file = args("--output");
//
// Access positional arguments using the operator[] with an integer.
//
// std::string filename = args[0];
//
// The argh constructor.
//
// * int argc - The count of command line arguments.
// * char *argv[] - The command line arguments.
argh::argh(int argc, char *argv[])
{
initialize();
for (int i = 1; i < argc; i++)
{
parse_argument(argv[i]);
}
}
// The argh constructor, as above, but with an array of strings.
//
// * int argc - The count of command line arguments.
// * std::string argv[] - The command line arguments.
argh::argh(int argc, std::string argv[])
{
initialize();
for (int i = 0; i < argc; i++)
{
parse_argument(argv[i]);
}
}
// A zero-argument method for initializing the instance variables.
void argh::initialize()
{
this->args = std::vector<std::string>();
this->flags = std::unordered_set<std::string>();
this->parameters = std::unordered_map<std::string, std::string>();
this->positional_arguments = std::vector<positional_arg>();
this->double_dash_set = false;
this->last_flag = "";
}
// A private method for parsing a single argument.
//
// * std::string arg - The argument to parse.
void argh::parse_argument(std::string arg)
{
// Make sure the argument is not empty.
if (arg.length() == 0)
return;
// If we've seen a double dash, we're parsing positional arguments.
if (double_dash_set)
{
this->args.push_back(arg);
positional_arg arg_obj(arg);
this->positional_arguments.push_back(arg_obj);
return;
}
// Is the argument a single dash?
if (arg == "-")
{
// A single dash is a positional argument.
parse_positional_argument(arg);
this->last_flag = "";
return;
}
// Is the argument a double dash?
if (arg == "--")
{
// A double dash means that all following arguments are positional arguments.
this->args.push_back(arg);
this->double_dash_set = true;
this->last_flag = "";
return;
}
// Is the argument a flag?
if (is_flag(arg))
{
parse_flag(arg);
return;
}
// If we've made it this far, the argument is either the value of a parameter
// or a positional argument.
parse_positional_argument(arg);
}
// A helper method for parsing a single flag.
//
// * std::string arg - The argument to parse.
void argh::parse_flag(std::string arg)
{
// Does the argument contain '='?
if (arg.find('=') != std::string::npos)
{
// If so, it's a parameter.
std::string key = arg.substr(0, arg.find('='));
std::string value = arg.substr(arg.find('=') + 1);
this->parameters[key] = value;
this->flags.insert(key);
this->args.push_back(arg);
this->last_flag = "";
return;
}
// Does the flag start with a double dash?
if (arg.length() >= 2 && arg.substr(0, 2) == "--")
{
this->flags.insert(arg);
this->args.push_back(arg);
this->last_flag = arg;
return;
}
else
{
// Treat each character following the single dash as a flag.
for (long unsigned int i = 1; i < arg.length(); i++)
{
std::string flag = "-" + arg.substr(i, 1);
this->flags.insert(flag);
this->last_flag = flag;
}
this->args.push_back(arg);
return;
}
}
// A helper method for parsing a single positional argument.
//
// * std::string arg - The argument to parse.
void argh::parse_positional_argument(std::string arg)
{
if (this->last_flag.length() > 0)
{
this->parameters[this->last_flag] = arg;
positional_arg arg_obj(this->last_flag, arg);
this->positional_arguments.push_back(arg_obj);
}
else
{
positional_arg arg_obj(arg);
this->positional_arguments.push_back(arg_obj);
}
this->last_flag = "";
this->args.push_back(arg);
}
// A method to determine whether an argument is a flag.
//
// * std::string arg - The argument to check.
//
// * return (bool) - True if the argument is a flag, false otherwise.
bool argh::is_flag(std::string arg)
{
if (arg.length() < 2)
return false;
if (arg == "--")
return false;
return arg[0] == '-';
}
// A method to mark an argument as a parameter, not a positional argument.
// Note: This method runs in O(N) time, where N is the number of arguments,
// provided that there is only one of the given parameter.
//
// * std::string arg - The argument to mark as a parameter.
void argh::mark_parameter(std::string arg)
{
for (long unsigned int i = 0; i < this->positional_arguments.size(); i++)
{
if (this->positional_arguments[i].get_owner() == arg)
{
this->positional_arguments.erase(this->positional_arguments.begin() + i);
mark_parameter(arg);
return;
}
}
}
// Overload the [] operator to access a flag by name.
//
// * std::string name - The name of the flag.
//
// * return (bool) - The value of the flag.
bool argh::operator[](std::string name)
{
return this->flags.count(name);
}
// Overload the () operator to access a parameter by name.
//
// * std::string name - The name of the parameter.
//
// * return (std::string) - The value of the parameter.
std::string argh::operator()(std::string name)
{
mark_parameter(name);
if (this->parameters.count(name))
return this->parameters[name];
return "";
}
// Overload the [] operator to access the positional arguments by index.
//
// ==============================================================================================================
// | |
// | It's important to note that the parser does not understand the difference |
// | between a positional argument and the value of a parameter! |
// | |
// | For instance: |
// | "program -o output.txt file.txt" |
// | Should "output.txt" be interpreted as a positional argument, or as the value of the "-o" parameter? |
// | "program -v file.txt" |
// | Should "file.txt" be interpreted as a positional argument, or as the value of the "-v" parameter? |
// | |
// | For this reason, all arguments that are not flags or parameters |
// | are considered positional arguments by default. |
// | If you want to change this behavior, you can use one of the following approaches: |
// | 1. Use the argh::set_parameter(parameter) function to mark the argument |
// | following a given parameter as the parameter's value. |
// | 2. Use the argh::operator(parameter) operater to query the value of a parameter |
// | before using the argh::operator[] to access the positional arguments. |
// | |
// ==============================================================================================================
//
// * int index - The index of the positional argument.
//
// * return (std::string) - The value of the positional argument.
std::string argh::operator[](int index)
{
if ((long unsigned int)index < this->positional_arguments.size())
return this->positional_arguments[index].get_value();
return "";
}
// Returns the number of positional arguments.
//
// * return (int) - The number of positional arguments.
int argh::size()
{
return this->positional_arguments.size();
}
}
| 36.762821 | 117 | 0.498344 | shrimpster00 |
2eca7bea048f63ca5a67b6620d40a90d3213291b | 48,187 | cpp | C++ | src/common.cpp | vadimostanin2/sneeze-detector | 2bac0d08cb4960b7dc16492b8c69ff1459dd9334 | [
"MIT"
] | 11 | 2015-04-18T23:42:44.000Z | 2021-04-03T18:23:44.000Z | src/common.cpp | vadimostanin2/sneeze-detector | 2bac0d08cb4960b7dc16492b8c69ff1459dd9334 | [
"MIT"
] | null | null | null | src/common.cpp | vadimostanin2/sneeze-detector | 2bac0d08cb4960b7dc16492b8c69ff1459dd9334 | [
"MIT"
] | 3 | 2017-06-02T17:07:08.000Z | 2019-04-18T05:59:48.000Z | /*
* common.c
*
* Created on: Nov 12, 2014
* Author: vostanin
*/
#include "common.h"
#include <unistd.h>
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include "Mfcc.h"
#include "dtw.h"
RangeDistance global_ranges[] = {
{RANGE_1_E, 1},
{RANGE_2_E, 2},
{RANGE_4_E, 4},
{RANGE_8_E, 8},
{RANGE_16_E, 16},
{RANGE_32_E, 32},
{RANGE_64_E, 64},
{RANGE_128_E, 128},
{RANGE_256_E, 256},
{RANGE_512_E, 512},
{RANGE_1024_E, 1024},
{RANGE_2048_E, 2048},
{RANGE_4096_E, 4096},
{RANGE_8192_E, 8192},
{RANGE_16384_E, 16384},
{RANGE_32768_E, 32768},
{RANGE_65536_E, 65536},
};
//
//void dump( vector<signal_type> & input )
//{
// ofstream file( "dump.txt", ios_base::app );
//
// for( size_t i = 0 ; i < input.size() ; i++ )
// {
// file << input[i] << " " << flush;
// }
// file << endl;
// file.close();
//}
void dump( vector_mfcc_level_1 & input )
{
ofstream file( "dump.txt", ios_base::app );
for( size_t i = 0 ; i < input.size() ; i++ )
{
file << input[i] << " " << std::flush;
}
file << endl;
file.close();
}
void dump( vector<freq_magn_type> & input )
{
ofstream file( "dump.txt", ios_base::app );
for( size_t i = 0 ; i < input.size() ; i++ )
{
file << input[i].freq << "=" << input[i].magnitude << " " << flush;
}
file << endl;
file.close();
}
void save_mfcc_coefficients( vector<vector<vector<float> > > & all_mfcc_v )
{
size_t all_mfcc_v_count = all_mfcc_v.size();
for( int all_mfcc_v_i = 0 ; all_mfcc_v_i < all_mfcc_v_count ; all_mfcc_v_i++ )
{
char str_num[] = { (char)(all_mfcc_v_i + 48), '\0' };
string filename = string( "mfcc_" ) + str_num;
ofstream file( filename.c_str(), ios_base::trunc );
file << all_mfcc_v[all_mfcc_v_i].size() << endl;
for( size_t mfcc_v_i = 0 ; mfcc_v_i < all_mfcc_v[all_mfcc_v_i].size() ; mfcc_v_i++ )
{
size_t mfcc_v_count = all_mfcc_v[all_mfcc_v_i][mfcc_v_i].size();
for( size_t mfcc_i = 0 ; mfcc_i < mfcc_v_count ; mfcc_i++ )
{
file << all_mfcc_v[all_mfcc_v_i][mfcc_v_i][mfcc_i] << flush;
if( ( mfcc_i + 1 ) < mfcc_v_count )
{
file << " " << flush;
}
}
file << endl;
}
file.close();
}
}
void load_mfcc_coefficients( vector<vector<vector<float> > > & all_mfcc_v )
{
all_mfcc_v.clear();
for( size_t file_i = 0 ; ; file_i++ )
{
char str_num[] = { (char)(file_i + 48), '\0' };
string filename = string( "mfcc_" ) + str_num;
ifstream infile( filename.c_str() );
if( false == infile.is_open() )
{
break;
}
vector<vector<float> > mfcc_v;
int mfcc_count = 0;
infile >> mfcc_count;
string line;
while (getline(infile, line, '\n'))
{
if( true == line.empty() )
{
continue;
}
vector<float> mfcc;
stringstream str_stream( line );
while(str_stream.eof() != true)
{
float cc = 0;
str_stream >> cc;
mfcc.push_back( cc );
}
mfcc_v.push_back( mfcc );
}
all_mfcc_v.push_back( mfcc_v );
}
}
void get_mean_two_mfcc( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, vector_mfcc_level_1 & mean )
{
size_t mfcc_1_size = mfcc_1.size();
size_t mfcc_2_size = mfcc_2.size();
if( mfcc_1_size == 0 )
{
return;
}
if( mfcc_1_size != mfcc_2_size )
{
return;
}
mean.resize( mfcc_1_size, 0.0 );
for( unsigned int mfcc_i = 0 ; mfcc_i < mfcc_1_size ; mfcc_i++ )
{
mean[mfcc_i] = (mfcc_1[mfcc_i] + mfcc_2[mfcc_i]) / 2;
}
}
void mfcc_meaning( vector_mfcc_level_3 & sounds, unsigned int merging_count, float threshold, vector_mfcc_level_3 & sounds_result )
{
size_t sound_count_size = sounds.size();
for( unsigned int sound_i = 0 ; sound_i < sound_count_size ; sound_i++ )
{
vector_mfcc_level_2 & mfcc_v = sounds[sound_i];
vector_mfcc_level_2 mfcc_v_result;
mfcc_meaning( mfcc_v, merging_count, threshold, mfcc_v_result );
sounds_result.push_back( mfcc_v_result );
}
}
void mfcc_meaning( vector_mfcc_level_2 & mfcc_v, unsigned int merging_count, float threshold, vector_mfcc_level_2 & mfcc_v_result )
{
size_t count = mfcc_v.size();
size_t mfcc_size = mfcc_v[0].size();
vector<unsigned int> used_mfcc;
for( unsigned int mfcc_i = 0 ; mfcc_i < count ; mfcc_i++ )
{
vector_mfcc_level_1 last_mean = mfcc_v[mfcc_i];
if( std::find( used_mfcc.begin(), used_mfcc.end(), mfcc_i) == used_mfcc.end() )
{
for( unsigned int merging_i = 0 ; merging_i < merging_count ; merging_i++ )
{
double min_value = 1000.0;
unsigned int min_index = 0;
double distance = 0.0;
for( unsigned int mfcc_j = 0 ; mfcc_j < count ; mfcc_j++ )
{
if( std::find( used_mfcc.begin(), used_mfcc.end(), mfcc_j) == used_mfcc.end() )
{
mfcc_get_distance( mfcc_v[mfcc_i], mfcc_v[mfcc_j], distance );
if( distance < min_value )
{
min_value = distance;
min_index = mfcc_j;
}
}
}
used_mfcc.push_back( min_index );
vector_mfcc_level_1 mean;
get_mean_two_mfcc( last_mean, mfcc_v[min_index], mean );
last_mean = mean;
}
mfcc_v_result.push_back( last_mean );
}
}
}
double complex_magnitude( complex_type cpx )
{
double real = cpx[0];
double im = cpx[1];
return sqrt( ( real * real ) + ( im * im ) );
}
void zero( complex_type & cpx )
{
cpx[0] = 0.0;
cpx[1] = 0.0;
}
void freqfilter(vector<complex_type> & complexes, double samplerate, unsigned int left_freq, unsigned int right_freq)
{
sf_count_t i;
sf_count_t samples2;
size_t count = complexes.size();
samples2 = count / 2;
for( i=0; i < count ; i++ )
{
double freq = ((double)i * samplerate / (double)count);
if( freq < left_freq || freq > right_freq )
{
zero( complexes[i] );
}
}
}
bool filename_pattern_match( string & filename, string & pattern )
{
bool result = true;
const char * str_filename = filename.c_str();
const char * str_pattern = pattern.c_str();
const char delim[2] = { '*', '\0' };
char * pch = NULL;
pch = strtok( (char*)str_pattern, delim );
while (pch != NULL)
{
if( strstr( str_filename, pch ) == NULL )
{
result = false;
break;
}
pch = strtok( NULL, "*" );
}
return result;
}
void read_wav_data( string & wav_file, vector<signal_type> & wav_raw, int & channels_count )
{
SF_INFO info_in;
SNDFILE * fIn = sf_open( wav_file.c_str(), SFM_READ, &info_in );
if( fIn == NULL )
{
return;
}
int nTotalRead = 0;
int nRead = 0;
channels_count = info_in.channels;
do
{
vector<signal_type> temp;
temp.resize(info_in.frames * info_in.channels);
nRead = sf_readf_float( fIn, &temp[0], info_in.frames - nTotalRead );
wav_raw.insert( wav_raw.end(), temp.begin(), temp.begin() + nRead * info_in.channels );
nTotalRead += nRead;
}
while( nTotalRead < info_in.frames );
sf_close(fIn);
}
void evarage_channels( vector<signal_type> & wav_raw, unsigned int channels_count, vector<signal_type> & chunk_merged )
{
if( channels_count == 1 )
{
chunk_merged.clear();
chunk_merged.assign( wav_raw.begin(), wav_raw.end() );
}
else
{
unsigned int wav_raw_size = wav_raw.size();
chunk_merged.resize( wav_raw_size / channels_count );
for( unsigned int wav_raw_i = 0 ; wav_raw_i < wav_raw_size ; wav_raw_i += channels_count )
{
float sum_amplitude = 0.0;
for( unsigned int channel_i = 0 ; channel_i < channels_count ; channel_i ++ )
{
double val = wav_raw[wav_raw_i + channel_i];
sum_amplitude += val;
}
chunk_merged[ wav_raw_i / channels_count ] = sum_amplitude / channels_count;
}
}
}
void save_chunk_data(vector<signal_type> & chunk_data, int index )
{
SF_INFO info_out = { 0 };
info_out.channels = 1;
info_out.samplerate = 16000;
unsigned int minutes = 60*24;
int seconds = minutes * 60;
info_out.frames = info_out.samplerate * info_out.channels * seconds;
info_out.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16 | SF_ENDIAN_LITTLE;
char outfilepath[BUFSIZ] = {'\0'};
sprintf(outfilepath, "%d.wav", index);
SNDFILE * fOut = NULL;
fOut = sf_open( outfilepath, SFM_WRITE, &info_out );
sf_writef_float( fOut, &chunk_data[0], chunk_data.size() );
sf_close(fOut);
}
void normalize( vector<signal_type> & signal, float max_val)
{
// recherche de la valeur max du signal
float max=0.f;
size_t size = signal.size();
for(size_t i=0 ; i<size ; i++)
{
if (abs(signal[i])>max) max=abs(signal[i]);
}
// ajustage du signal
float ratio = max_val/max;
for(size_t i=0 ; i<size ; i++)
{
signal[i] = signal[i]*ratio;
}
}
void movesignal_to_value( vector<signal_type> & signal, float val)
{
// recherche de la valeur max du signal
float max=0.f;
size_t size = signal.size();
for(size_t i=0 ; i<size ; i++)
{
signal[i] += val;
}
}
void negative_values_zeroes( vector<float> & signal )
{
size_t size = signal.size();
for(size_t i=0 ; i<size ; i++)
{
if( signal[i] < 0 )
{
signal[i] = 0;
}
}
}
void cut_zeroes( vector<float> & signal )
{
size_t size = signal.size();
unsigned int insert_i = 0;
size_t search_i = 0;
for( search_i = 0 ; search_i < size ; search_i++)
{
if( signal[search_i] != 0 )
{
signal[insert_i] = signal[search_i];
insert_i++;
}
}
}
void get_current_folder( string & folder )
{
char cwd[BUFSIZ] = { '\0' };
getcwd( cwd, BUFSIZ );
folder = cwd;
}
void movesignal_to_0_1( vector<signal_type> & signal )
{
normalize( signal, 0.5f );
movesignal_to_value( signal, 0.5f );
}
void period_start_get( vector<signal_type> & signal, size_t & signal_index )
{
size_t signal_length = signal.size();
float last_value = 0.0;
for( size_t signal_i = 0 ; signal_i < signal_length ; signal_i++ )
{
signal_type value = signal[signal_i];
if( value >= 0 && last_value < 0 )
{
signal_index = signal_i;
break;
}
last_value = value;
}
}
bool period_next_get( vector<signal_type> & signal, unsigned int index, unsigned int & estimate_signals, vector<signal_type> & perioded_chunk )
{
size_t signal_length = signal.size();
float last_value = 0.0;
estimate_signals = 0;
bool found = false;
size_t zero_counter = 0;
for( size_t signal_i = index ; signal_i < signal_length ; signal_i++ )
{
signal_type value = signal[signal_i];
if( zero_counter >= 2 )
{
found = true;
perioded_chunk.clear();
break;
}
if( ( value >= 0 && last_value < 0 ) )
{
size_t chunk_size = perioded_chunk.size();
if( chunk_size >= 1 )
{
found = true;
}
else
{
perioded_chunk.clear();
}
break;
}
else if ( value != 0 )
{
perioded_chunk.push_back( value );
estimate_signals++;
zero_counter = 0;
}
else if ( value == 0 )
{
zero_counter++;
}
last_value = value;
}
return found;
}
bool period_prev_get( vector<signal_type> & signal, unsigned int index, unsigned int & estimate_signals, vector<signal_type> & perioded_chunk )
{
float last_value = 0.0;
estimate_signals = 0;
bool found = false;
for( int signal_i = index ; signal_i >= 0 ; signal_i-- )
{
signal_type value = signal[signal_i];
if( ( value >= 0 && last_value < 0 ) || ( last_value == 0 && value == 0 ) )
{
size_t chunk_size = perioded_chunk.size();
if( chunk_size >= 1 )
{
found = true;
}
else
{
perioded_chunk.clear();
}
break;
}
else
{
perioded_chunk.push_back( value );
estimate_signals++;
}
last_value = value;
}
return found;
}
void divide_on_perioded_chunks( vector<signal_type> & signal, vector<vector<signal_type> > & perioded_chunks, size_t periods_count, size_t threshold_signals_per_chunk )
{
size_t signal_length = signal.size();
size_t signal_start = 0;
period_start_get( signal, signal_start );
for( size_t signal_i = signal_start ; signal_i < signal_length ; )
{
vector<signal_type> chunk;
for( size_t period_i = 0 ; period_i < periods_count ; period_i++ )
{
vector<signal_type> period;
unsigned int estimate_signals = 0;
period_next_get( signal, signal_i, estimate_signals, period );
if( false == period.empty() )
{
chunk.insert( chunk.end(), period.begin(), period.end() );
}
signal_i += estimate_signals;
}
size_t chunk_size = chunk.size();
size_t perioded_chunks_count = perioded_chunks.size();
if( chunk_size >= threshold_signals_per_chunk )
{
perioded_chunks.push_back( chunk );
}
else
{
break;
}
}
}
void divide_on_seconds_chunks( vector<signal_type> & signal, vector<vector<signal_type> > & perioded_chunks, size_t samplerate )
{
size_t signal_length = signal.size();
unsigned int seconds_count = signal_length/samplerate;
for( size_t signal_i = 0 ; signal_i < seconds_count ; signal_i ++ )
{
vector<signal_type> chunk( samplerate );
memcpy( &chunk[0], &signal[ signal_i * samplerate ], samplerate * sizeof( float ) );
perioded_chunks.push_back( chunk );
}
}
bool make_train_file_with_vector( vector<signal_type> & magnitudes, unsigned int num_input_neurons, unsigned int num_output_neurons, vector<int> & outputs )
{
string header_out_file_name = "freqs_train_header.txt";
string data_out_file_name = "freqs_train_data.txt";
int num_data = 0;
static bool global_first_open = true;
if( true == global_first_open )
{
unlink( header_out_file_name.c_str() );
unlink( data_out_file_name.c_str() );
unlink( "../freqs_train.txt" );
}
else
{
ifstream header_file( header_out_file_name.c_str(), ios_base::in );
if( true == header_file.is_open() )
{
header_file >> num_data;
header_file.close();
}
else
{
cout << strerror(errno) << endl;
}
}
ofstream header_out_file( header_out_file_name.c_str(), ios_base::out );
ofstream data_out_file( data_out_file_name.c_str(), ios_base::app );
ofstream train_file( "../freqs_train.txt", ios_base::trunc );
if( false == header_out_file.is_open() )
{
return false;
}
if( false == data_out_file.is_open() )
{
return false;
}
if( false == train_file.is_open() )
{
return false;
}
////////////PREPARE HEADER
if( true == global_first_open )
{
num_data = 1;
header_out_file<<num_data << " " << num_input_neurons << " " << num_output_neurons << endl << flush;
}
else
{
string line;
stringstream str_stream;
num_data = num_data + 1;
str_stream << num_data << " " << num_input_neurons << " " << num_output_neurons;
line = str_stream.str();
// cout<< line << endl;
header_out_file << line << endl << flush;
}
////////////PREPARE DATA
data_out_file << flush;
unsigned int directions_count = magnitudes.size();
for( unsigned int direction_i = 0 ; direction_i < directions_count ; direction_i++ )
{
vector<signal_type>::value_type val = magnitudes[direction_i];
data_out_file << val << flush;
if( ( direction_i + 1) < directions_count )
{
data_out_file << " " << flush;
}
}
data_out_file << endl;
const size_t outputs_count = outputs.size();
for( size_t output_i = 0 ; output_i < outputs_count ; output_i++ )
{
if( true == outputs[output_i] )
{
data_out_file << 1 << flush;
}
else if( false == outputs[output_i] )
{
data_out_file << 0 << flush;
}
if( ( output_i + 1) < outputs_count )
{
data_out_file << " " << flush;
}
}
data_out_file << endl;
data_out_file << flush;
data_out_file.close();
std::string line;
{
ifstream header_in_file( header_out_file_name.c_str(), ios_base::in );
while (std::getline(header_in_file, line))
{
train_file << line << endl << flush;
}
}
{
ifstream data_in_file( data_out_file_name.c_str(), ios_base::in );
while (std::getline(data_in_file, line))
{
train_file << line << endl << flush;
}
}
global_first_open = false;
return true;
}
bool freq_range_template_equal( vector_mfcc_level_1 & freq_range_template_1, vector_mfcc_level_1 & freq_range_template_2, unsigned int threshold_failed )
{
size_t freq_count_1 = freq_range_template_1.size();
size_t freq_count_2 = freq_range_template_2.size();
if( freq_count_1 != freq_count_2 )
{
return false;
}
if( freq_count_1 == 0 )
{
return false;
}
int res = memcmp( &freq_range_template_1[0], &freq_range_template_2[0], freq_count_1 * sizeof( freq_range_template_1[0] ) );
if( res != 0 )
{
return false;
}
/*
int sum_diff = 0;
for( size_t range_i = 0 ; range_i < freq_count_1 ; range_i++ )
{
vector_mfcc_level_1::value_type * freq_range_template_2_ptr = &freq_range_template_2[0];
vector_mfcc_level_1::value_type type_1 = freq_range_template_1[range_i];
vector_mfcc_level_1::value_type type_2 = freq_range_template_2[range_i];
double pow_1 = log2( type_1 );
double pow_2 = log2( type_2 );
if( type_1 != type_2 )
{
int diff_pow = (int)pow_1 - pow_2;
sum_diff += diff_pow;
if( sum_diff > threshold_failed )
{
return false;
}
}
}
*/
return true;
}
bool compare( const freq_magn_type & _1, const freq_magn_type & _2 )
{
return _1.freq < _2.freq;
}
void template_freq_range_fill_distance_from_each_to_next( vector<signal_type> & signal, vector_mfcc_level_1 & freq_range_template )
{
freq_range_template.clear();
complex_type * complexes = NULL;
fftwf_plan plan;
make_fft( signal, &complexes, &plan );
const int freqs_range_count = FREQUENCY_PROCESSED_COUNT;
size_t complex_count = signal.size();
vector<complex_type> complexes_v( complexes, complexes + complex_count );
freqfilter( complexes_v, 16000, 50, 8000 );
vector<freq_magn_type> max_freqs_v;
getFrequencesWithHigherMagnitudes( freqs_range_count, complexes_v, max_freqs_v, 16000 );
if( max_freqs_v.empty() == true )
{
return;
}
std::sort(max_freqs_v.begin(), max_freqs_v.end(), compare );
signal_type prev_freq = max_freqs_v[0].freq;
size_t freq_count = max_freqs_v.size();
size_t range_count = sizeof( global_ranges )/ sizeof( global_ranges[0] );
for( size_t freq_i = 0 ; freq_i < freq_count ; freq_i++ )
{
freq_magn_type & curr_freq_magn = max_freqs_v[freq_i];
float distance = abs( curr_freq_magn.freq - prev_freq );
bool found = false;
for( size_t range_i = 0 ; range_i < range_count ; range_i++ )
{
const int distance_threshold = global_ranges[range_i].distance;
if( distance < distance_threshold )
{
found = true;
freq_range_template.push_back( global_ranges[range_i].range_type );
// cout<< distance_threshold << ", " << flush;
break;
}
}
prev_freq = curr_freq_magn.freq;
}
// cout << endl;
freq_count = freq_range_template.size();
destroy_fft( &complexes, &plan );
}
void template_freq_range_fill_distance_from_each_to_max( vector<signal_type> & signal, vector_mfcc_level_1 & freq_range_template )
{
freq_range_template.clear();
complex_type * complexes = NULL;
fftwf_plan plan;
make_fft( signal, &complexes, &plan );
const int freqs_range_count = FREQUENCY_PROCESSED_COUNT;
size_t complex_count = signal.size();
vector<complex_type> complexes_v( complexes, complexes + complex_count );
freqfilter( complexes_v, 16000, 50, 8000 );
vector<freq_magn_type> max_freqs_v;
getFrequencesWithHigherMagnitudes( freqs_range_count, complexes_v, max_freqs_v, 16000 );
if( max_freqs_v.empty() == true )
{
return;
}
signal_type prev_freq = max_freqs_v[0].freq;
size_t freq_count = max_freqs_v.size();
size_t range_count = sizeof( global_ranges )/ sizeof( global_ranges[0] );
for( size_t freq_i = 0 ; freq_i < freq_count ; freq_i++ )
{
freq_magn_type & curr_freq_magn = max_freqs_v[freq_i];
float distance = abs( curr_freq_magn.freq - prev_freq );
for( size_t range_i = 0 ; range_i < range_count ; range_i++ )
{
const int distance_threshold = global_ranges[range_i].distance;
if( distance < distance_threshold )
{
freq_range_template.push_back( global_ranges[range_i].range_type );
break;
}
}
}
freq_count = freq_range_template.size();
destroy_fft( &complexes, &plan );
}
void make_fft( vector<signal_type> & data, complex_type ** fft_result, fftwf_plan * plan_forward )
{
size_t data_count = data.size();
*fft_result = ( complex_type* ) fftwf_malloc( sizeof( complex_type ) * 2 * data_count );
*plan_forward = fftwf_plan_dft_r2c_1d( data_count, &data[0], *fft_result, FFTW_ESTIMATE );
// Perform the FFT on our chunk
fftwf_execute( *plan_forward );
}
void destroy_fft( complex_type ** fft_result, fftwf_plan * plan_forward )
{
fftwf_destroy_plan( *plan_forward );
*plan_forward = 0;
fftwf_free( *fft_result );
*fft_result = NULL;
}
void getFrequencesWithHigherMagnitudes( size_t frequencyCount, vector<complex_type> & complexes, vector<freq_magn_type> & freqs, size_t samplerate )
{
double prev_max_magnitude = 1000000.0;
size_t prev_max_magnitude_index = 0.0;
size_t freqs_count = complexes.size();
if( freqs_count < frequencyCount )
{
return;
}
static signal_type * freqs_ptr = (signal_type*)calloc( samplerate, sizeof( signal_type ) );
memset( freqs_ptr, 0, samplerate * sizeof( signal_type ) );
for( size_t bins_counter_i = 0 ; bins_counter_i < frequencyCount ; bins_counter_i++ )
{
float max_magnitude = 0.0;
size_t max_magnitude_index = 0.0;
for( size_t freq_i = 0 ; freq_i < freqs_count ; freq_i++ )
{
float magnitude = complex_magnitude( complexes[freq_i] );
if( max_magnitude < magnitude && magnitude < prev_max_magnitude )
{
max_magnitude = magnitude;
max_magnitude_index = freq_i;
}
}
float freq = ((float)max_magnitude_index * samplerate / (float)freqs_count);
freq_magn_type value = { freq, max_magnitude };
freqs.push_back( value );
prev_max_magnitude = max_magnitude;
prev_max_magnitude_index = max_magnitude_index;
}
freqs_count = freqs.size();
// free( freqs_ptr );
}
float get_minimum_amplitude( vector<float> & signal, float & peak_value, unsigned int & peak_index)
{
unsigned int count_i = 0;
float minimum = 1000.0;
int maximum_index = 0.0;
unsigned int count = signal.size();
for( count_i = 1 ; count_i < count ; count_i++ )
{
if(signal[count_i] < 0)
{
float curr = signal[count_i];
if( minimum < curr )
{
minimum = curr;
maximum_index = count_i;
}
}
}
peak_value = minimum;
peak_index = maximum_index;
return minimum;
}
float get_maximum_amplitude( vector<float> & signal, float & peak_value, unsigned int & peak_index)
{
int count_i = 0;
float maximum = 0.0;
int maximum_index = 0.0;
int count = signal.size();
for( count_i = 1 ; count_i < ( count - 1 ) ; count_i++ )
{
if(signal[count_i] > 0)
{
float prev = signal[count_i - 1];
float curr = signal[count_i];
float next = signal[count_i + 1];
if( prev < curr && next < curr)
{
if( maximum < curr )
{
maximum = curr;
maximum_index = count_i;
}
}
}
}
peak_value = maximum;
peak_index = maximum_index;
return maximum;
}
void trim_sides_periods_bellow_threshold( vector<signal_type> & perioded_signal, float threshold_amplitude, vector<signal_type> & perioded_signal_result )
{
unsigned int estimate_signals_sum = 0;
unsigned int signal_count = perioded_signal.size();
{
vector<signal_type> copy_src_signal = perioded_signal;
bool found_first_above_threshold = false;
for( unsigned int period_i = 0 ; ; period_i++ )
{
int start_index = (signal_count - estimate_signals_sum - 1);
vector<signal_type> period;
if( (start_index < 0) )
{
break;
}
unsigned int estimate_signals = 0;
period_prev_get( copy_src_signal, start_index, estimate_signals, period );
estimate_signals_sum += estimate_signals;
if( true == period.empty() )
{
break;
}
float max_value = 0.0;
unsigned int max_index = 0;
if( true == condition_check_signal_threshold( period, threshold_amplitude, max_value, max_index ) )
{
found_first_above_threshold = true;
}
if( true == found_first_above_threshold )
{
perioded_signal_result.clear();
perioded_signal_result.assign( copy_src_signal.begin(), copy_src_signal.begin() + ( signal_count - estimate_signals_sum ) );
break;
}
}
}
std::reverse( perioded_signal_result.begin(), perioded_signal_result.end() );
{
vector<signal_type> copy_src_signal = perioded_signal_result;
bool found_first_above_threshold = false;
estimate_signals_sum = -1;
for( unsigned int period_i = 0 ; ; period_i++ )
{
unsigned int start_index = ( estimate_signals_sum + 1 );
vector<signal_type> period;
if( (start_index >= signal_count) )
{
break;
}
unsigned int estimate_signals = 0;
period_next_get( copy_src_signal, start_index, estimate_signals, period );
estimate_signals_sum += estimate_signals;
if( true == period.empty() )
{
break;
}
float max_value = 0.0;
unsigned int max_index = 0;
if( true == condition_check_signal_threshold( period, threshold_amplitude, max_value, max_index ) )
{
found_first_above_threshold = true;
}
if( true == found_first_above_threshold )
{
perioded_signal_result.clear();
size_t copy_src_signal_count = copy_src_signal.size();
perioded_signal_result.assign( copy_src_signal.begin() + estimate_signals_sum, copy_src_signal.end() );
break;
}
}
}
size_t copy_src_signal_count = perioded_signal_result.size();
// save_chunk_data( perioded_signal_result, 3 );
}
bool copy_periods_before_after_signal_index( vector<signal_type> & signal, float threshold_amplitude, unsigned int signal_index, unsigned int periods_count,
unsigned int max_perioded_chunks_count, vector<signal_type> & all_perioded_chunk, unsigned int & out_new_signal_index,
bool no_matter_bounds, COPY_SIGNAL_ERROR_E & error )
{
unsigned int estimate_signals = 0;
error = COPY_SIGNAL_ERROR_SUCCESS;
size_t signal_count = signal.size();
size_t all_perioded_chunk_count = 0;
unsigned int estimate_signals_sum = 0;
for( unsigned int periods_i = 0 ; periods_i < max_perioded_chunks_count ; periods_i++ )
{
bool need_break = false;
vector<signal_type> one_perioded_chunk;
for( unsigned int period_i = 0 ; period_i < periods_count ; period_i++ )
{
int start_index = (signal_index - estimate_signals_sum - 1);
vector<signal_type> period;
if( start_index < 0 )
{
if( false == no_matter_bounds )
{
error = COPY_SIGNAL_ERROR_NEED_PREV_SIGNAL;
all_perioded_chunk.clear();
return false;
}
else
{
need_break = true;
break;
}
}
period_prev_get( signal, start_index, estimate_signals, period );
if( false == period.empty() )
{
one_perioded_chunk.insert( one_perioded_chunk.end(), period.begin(), period.end() );
}
else
{
need_break = true;
break;
}
estimate_signals_sum += estimate_signals;
}
float max_value = 0.0;
unsigned int max_index = 0;
if( false == condition_check_signal_threshold( one_perioded_chunk, threshold_amplitude, max_value, max_index ) )
{
break;
}
else
{
all_perioded_chunk.insert( all_perioded_chunk.end(), one_perioded_chunk.begin(), one_perioded_chunk.end() );
all_perioded_chunk_count = all_perioded_chunk.size();
}
if( true == need_break )
{
break;
}
}
all_perioded_chunk_count = all_perioded_chunk.size();
std::reverse( all_perioded_chunk.begin(), all_perioded_chunk.end() );
all_perioded_chunk.push_back( signal[signal_index] );
out_new_signal_index = all_perioded_chunk.size() - 1;
estimate_signals_sum = 0;
for( unsigned int periods_i = 0 ; periods_i < max_perioded_chunks_count ; periods_i++ )
{
bool need_break = false;
vector<signal_type> one_perioded_chunk;
for( unsigned int period_i = 0 ; period_i < periods_count ; period_i++ )
{
unsigned int start_index = (signal_index + estimate_signals_sum + 1);
vector<signal_type> period;
if( start_index >= signal_count )
{
if( false == no_matter_bounds )
{
error = COPY_SIGNAL_ERROR_NEED_NEXT_AND_PREV_SIGNAL;
all_perioded_chunk.clear();
return false;
}
else
{
need_break = true;
break;
}
}
period_next_get( signal, start_index, estimate_signals, period );
if( false == period.empty() )
{
one_perioded_chunk.insert( one_perioded_chunk.end(), period.begin(), period.end() );
}
else
{
need_break = true;
break;
}
estimate_signals_sum += estimate_signals;
}
size_t one_perioded_chunk_count = one_perioded_chunk.size();
float max_value = 0.0;
unsigned int max_index = 0;
if( false == condition_check_signal_threshold( one_perioded_chunk, threshold_amplitude, max_value, max_index ) )
{
break;
}
else
{
all_perioded_chunk.insert( all_perioded_chunk.end(), one_perioded_chunk.begin(), one_perioded_chunk.end() );
}
if( true == need_break )
{
break;
}
}
vector<signal_type> trimmed_perioded_signal;
all_perioded_chunk_count = all_perioded_chunk.size();
trim_sides_periods_bellow_threshold( all_perioded_chunk, threshold_amplitude, trimmed_perioded_signal );
all_perioded_chunk.swap( trimmed_perioded_signal );
all_perioded_chunk_count = all_perioded_chunk.size();
error = COPY_SIGNAL_ERROR_SUCCESS;
return true;
}
void autoCorrelation( vector<signal_type> & signal, vector<signal_type> & correlated_signal )
{
size_t signal_length = signal.size();
correlated_signal.resize( signal_length );
float sum = 0;
size_t i = 0, j = 0;
for( i = 0 ; i < signal_length ; i++ )
{
sum=0;
for( j = 0 ; j < signal_length - i ; j++ )
{
sum += signal[ j ] * signal[ j + i ];
}
correlated_signal[ i ] = sum;
}
}
float get_average_amplitude( vector<float> & signal, unsigned int range_min_frame, unsigned int range_max_frame)
{
double average_amplitude_before_maximum = 0.0;
double sum_amplitudes_before_maximum = 0.0;
int significant_values_count_in_range_before = 0;
unsigned int count_i = 0;
for( count_i = range_min_frame ; count_i < ( range_max_frame - 1 ) ; count_i++ )
{
if(signal[count_i] > 0)
{
double prev = signal[count_i - 1];
double curr = signal[count_i];
double next = signal[count_i + 1];
if( prev < curr && next < curr)
{
significant_values_count_in_range_before++;
sum_amplitudes_before_maximum += signal[count_i];
}
}
}
average_amplitude_before_maximum = sum_amplitudes_before_maximum/significant_values_count_in_range_before;
return average_amplitude_before_maximum;
}
void get_time_chunk_signal_corner( vector<float> & signal, double maximum, int maximum_index, bool prev, int & corner)
{
{
size_t signal_count = signal.size();
int bound_frame_near_maximum = 0;
float average_amplitude_near_maximum = 0.0;
float sin_value = 0.0;
float katet_2 = 0.0;
float delta_katet_1 = 0.0;
float hipothenuze = 0.0;
if( prev )
{
bound_frame_near_maximum = 1;// cause of 0-1 in function bellow
average_amplitude_near_maximum = get_average_amplitude( signal, bound_frame_near_maximum, maximum_index);
katet_2 = 1;
delta_katet_1 = (maximum - average_amplitude_near_maximum) * katet_2;
hipothenuze = std::sqrt( delta_katet_1*delta_katet_1 + katet_2*katet_2);
sin_value = katet_2 / hipothenuze;
}
else
{
bound_frame_near_maximum = signal_count - 1;
average_amplitude_near_maximum = get_average_amplitude( signal, maximum_index, bound_frame_near_maximum);
katet_2 = (signal_count - maximum_index) / 2;
delta_katet_1 = (maximum - average_amplitude_near_maximum) * katet_2;
hipothenuze = std::sqrt( delta_katet_1*delta_katet_1 + katet_2*katet_2);
sin_value = katet_2 / hipothenuze;
}
corner = (asin(sin_value) * 180 / M_PI - 45 ) * 2;
}
}
bool condition_check_signal_threshold( vector<signal_type> & signal, float threshold_positive, float & peak_value, unsigned int & peak_index )
{
peak_index = 0;
get_maximum_amplitude( signal, peak_value, peak_index );
cout << "max_amplitude=" << peak_value << endl;
if( peak_value >= threshold_positive )
{
return true;
}
return false;
}
bool condition_check_signal_corner_shoulder_at_max( vector<signal_type> & signal, float maximum, unsigned int maximum_index )
{
float high_threshold = 60;
bool previous_corner = true;
int corner_before = 0;
get_time_chunk_signal_corner( signal, maximum, maximum_index, previous_corner, corner_before);
if( corner_before > high_threshold )
{
cout << "corner_before=" << corner_before << " FAILED" << endl;
return false;
}
previous_corner = false;
int corner_after = 0;
get_time_chunk_signal_corner( signal, maximum, maximum_index, previous_corner, corner_after);
if( corner_after > high_threshold )
{
cout<< "corner_after=" << corner_after << " FAILED" << endl;
return false;
}
cout<< "corner_after=" << corner_after << "; corner_before=" << corner_before << " SUCCESS" << endl;
return true;
}
// Generate window function (Hanning) see http://www.musicdsp.org/files/wsfir.h
void wHanning( int fftFrameSize, vector<float> & hanning )
{
hanning.resize( fftFrameSize );
for( int k = 0; k < fftFrameSize ; k++)
{
hanning[k] = (-1) * 0.5 * cos( 2.0 * M_PI * (double)k / (double)fftFrameSize) + 0.5;
}
}
void apply_hanning_window( vector<signal_type> & magnitudes )
{
vector<float> hanning;
const size_t magnitudes_count = magnitudes.size();
wHanning( magnitudes_count, hanning );
// float * hanning_pointer = &hanning[0];
signal_type * magn_ptr = &magnitudes[0];
for( size_t magnitude_i = 0; magnitude_i < magnitudes_count ; magnitude_i++)
{
float curr_magnitude = magnitudes[magnitude_i];
double hann = hanning[magnitude_i];
magnitudes[magnitude_i] = curr_magnitude * hann;
}
}
void get_spectrum_magnitudes( vector<signal_type> & signal_chunk, vector<signal_type> & magnitudes)
{
complex_type * fft_result = NULL;
fftwf_plan plan = NULL;
make_fft( signal_chunk, &fft_result, &plan );
size_t FFTLen = signal_chunk.size();
size_t specLen = FFTLen / 2;
magnitudes.resize( specLen );
for( size_t fft_i = 0 ; fft_i < specLen ; fft_i++ )
{
magnitudes[fft_i] = complex_magnitude( fft_result[fft_i] );
}
destroy_fft( &fft_result, &plan );
}
void get_mfcc_coefficients( vector<signal_type> & signal_chunk, vector<float> & mfcc_coefficients)
{
vector<signal_type> magnitudes;
get_spectrum_magnitudes( signal_chunk, magnitudes );
size_t specLen = magnitudes.size();
Mfcc mfcc;
int numCoeffs = 14; // number of MFCC coefficients to calculate
int numFilters = 32; // number of filters for MFCC calc
mfcc_coefficients.resize( numCoeffs );
mfcc.init( 16000, numFilters, specLen, numCoeffs );
mfcc.getCoefficients( &magnitudes[0], &mfcc_coefficients[0] );
}
void mfcc_get_distance( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, double & distance )
{
distance = 0.0f;
size_t mfcc_1_size = mfcc_1.size();
size_t mfcc_2_size = mfcc_2.size();
if( mfcc_1_size == 0 )
{
return;
}
if( mfcc_1_size != mfcc_2_size )
{
return;
}
double square_sum = 0;
for( size_t mfcc_i = 0 ; mfcc_i < mfcc_1_size ; mfcc_i++ )
{
double delta = mfcc_1[mfcc_i] - mfcc_2[mfcc_i];
double square = delta * delta;
square_sum += square;
}
distance = sqrt( square_sum );
}
void dtw_get_distance( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, double & distance )
{
distance = 0.0f;
float * mfcc_1_ptr = &mfcc_1[0];
float * mfcc_2_ptr = &mfcc_2[0];
dtw_get_distance( mfcc_1_ptr, mfcc_2_ptr, mfcc_1.size(), mfcc_2.size(), distance );
}
void dtw_get_distance( float * mfcc_1, float * mfcc_2, unsigned int mfcc_1_size, unsigned int mfcc_2_size, double & distance )
{
distance = 0.0f;
if( mfcc_1_size == 0 )
{
return;
}
if( mfcc_1_size != mfcc_2_size )
{
return;
}
DTW dtw( mfcc_1_size, mfcc_2_size );
distance = dtw.run( mfcc_1, mfcc_2, mfcc_1_size, mfcc_2_size );
}
void hmm_get_propability( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, double & distance )
{
}
void prepare_signal_near_peak( vector<signal_type> & present_signal, vector<signal_type> & past_signal, vector<signal_type> & future_signal, float threshold, unsigned int max_index, unsigned int periods_count_per_chunk, unsigned int max_chunks_count, vector<signal_type> & prepared_signal, unsigned int & new_max_index )
{
COPY_SIGNAL_ERROR_E error = COPY_SIGNAL_ERROR_SUCCESS;
COPY_SIGNAL_ERROR_E last_error = error;
int temp_max_index = max_index;
vector<signal_type> signal = present_signal;
bool no_mater_bounds = false;
while( true )
{
vector<signal_type> perioded_signal;
bool bCopy = copy_periods_before_after_signal_index(signal, threshold, temp_max_index, periods_count_per_chunk, max_chunks_count, perioded_signal, new_max_index, no_mater_bounds, error );
if( bCopy == true && error == COPY_SIGNAL_ERROR_SUCCESS )
{
size_t perioded_signal_count = perioded_signal.size();
prepared_signal = perioded_signal;
last_error = error;
break;
}
else if( error == COPY_SIGNAL_ERROR_NEED_PREV_SIGNAL )
{
if( last_error == error )
{
no_mater_bounds = true;
}
else
{
no_mater_bounds = false;
}
signal.clear();
signal.insert( signal.begin(), past_signal.begin(), past_signal.end() );
signal.insert( signal.end(), present_signal.begin(), present_signal.end() );
temp_max_index = max_index + past_signal.size();
last_error = error;
}
else if( error == COPY_SIGNAL_ERROR_NEED_NEXT_AND_PREV_SIGNAL )
{
if( last_error == error )
{
no_mater_bounds = true;
}
else
{
no_mater_bounds = false;
}
signal.clear();
signal.insert( signal.begin(), past_signal.begin(), past_signal.end() );
signal.insert( signal.end(), present_signal.begin(), present_signal.end() );
signal.insert( signal.end(), future_signal.begin(), future_signal.end() );
last_error = error;
}
else
{
prepared_signal.clear();
last_error = error;
break;
}
}
}
void merge_and_split_with_cross( vector<vector<signal_type> > & perioded_chunks, unsigned int periods_count, vector<vector<signal_type> > & perioded_crossed_chunks )
{
vector<signal_type> signal;
size_t perioded_count = perioded_chunks.size();
for( size_t perioded_i = 0; perioded_i < perioded_count ; perioded_i++ )
{
vector<signal_type> & perioded_chunk = perioded_chunks[perioded_i];
signal.insert( signal.end(), perioded_chunk.begin(), perioded_chunk.end() );
}
size_t signal_length = signal.size();
unsigned int perioded_offset_signal_index = 0;
size_t signal_i = 0;
for( size_t perioded_i = 0 ; signal_i < signal_length ; perioded_i++ )
{
vector<signal_type> cross_perioded_chunk;
unsigned int start_copy_index = perioded_offset_signal_index;
for( size_t period_i = 0 ; period_i < periods_count ; period_i++ )
{
unsigned int estimate_signals = 0;
vector<signal_type> period;
signal_i = start_copy_index;
period_next_get( signal, start_copy_index, estimate_signals, period );
if( false == period.empty() )
{
cross_perioded_chunk.insert( cross_perioded_chunk.end(), period.begin(), period.end() );
}
else
{
break;
}
signal_i += estimate_signals;
start_copy_index += estimate_signals;
if( period_i == ( periods_count/2 - 1) )
{
perioded_offset_signal_index = signal_i;
}
}
if( false == cross_perioded_chunk.empty() )
{
perioded_crossed_chunks.push_back( cross_perioded_chunk );
}
else
{
continue;
}
}
}
struct CRange
{
double min_value;
double max_value;
CRange():min_value(0), max_value(0.1){}
};
int get_amplitude_range_index( vector<CRange> ranges, double amplitude)
{
int index = 0;
size_t range_count = ranges.size();
for( index = 0 ; index < range_count ; index++ )
{
if( amplitude > ranges[index].min_value && amplitude < ranges[index].max_value )
{
break;
}
}
return index;
}
void get_most_meet_amplitude_range( vector<signal_type> & signal, float & low_range, float & high_range )
{
float min_range_amplitude_value = 0.0;
float max_range_amplitude_value = 1.0;
float range_delta = 0.01;
const int ranges_count = (max_range_amplitude_value - min_range_amplitude_value) / range_delta;
vector<CRange> ranges( ranges_count );
for(int i = 0 ; i < ranges_count ; i++ )
{
ranges[i].min_value = min_range_amplitude_value + range_delta*i;
ranges[i].max_value = min_range_amplitude_value + range_delta*( i + 1 );
}
int most_meet_range_index = 0;
const unsigned int max_amplitude_ranges_count = ranges_count;
vector<int> range_arr( max_amplitude_ranges_count );
size_t count = signal.size();
for( unsigned int signal_i = 1 ; signal_i < ( count -1 ) ; signal_i++ )
{
if( signal[signal_i] > 0 )
{
double prev = signal[signal_i - 1];
double curr = signal[signal_i];
double next = signal[signal_i + 1];
if( prev < curr && next < curr)
{
int range_index = 0;
range_index = get_amplitude_range_index( ranges, signal[signal_i] );
range_arr[range_index]++;
}
}
}
double temp_max = 0.0;
for( unsigned int range_i = 0 ; range_i < max_amplitude_ranges_count ; range_i++ )
{
int range_meet = range_arr[range_i];
if( temp_max < range_meet )
{
temp_max = range_meet;
most_meet_range_index = range_i;
}
}
low_range = ranges[most_meet_range_index].min_value;
high_range = ranges[most_meet_range_index].max_value;
}
void get_atleast_meet_amplitude_range( vector<signal_type> & signal, unsigned int minimum_peaks_count, float & low_range, float & high_range )
{
float min_range_amplitude_value = 0.0;
float max_range_amplitude_value = 1.0;
float range_delta = 0.01;
const int ranges_count = (max_range_amplitude_value - min_range_amplitude_value) / range_delta;
vector<CRange> ranges( ranges_count );
for(int i = 0 ; i < ranges_count ; i++ )
{
ranges[i].min_value = min_range_amplitude_value + range_delta*i;
ranges[i].max_value = min_range_amplitude_value + range_delta*( i + 1 );
}
const int max_amplitude_ranges_count = ranges_count;
vector<int> range_arr( max_amplitude_ranges_count );
size_t count = signal.size();
for( unsigned int signal_i = 1 ; signal_i < ( count -1 ) ; signal_i++ )
{
if( signal[signal_i] > 0 )
{
double prev = signal[signal_i - 1];
double curr = signal[signal_i];
double next = signal[signal_i + 1];
if( prev < curr && next < curr)
{
int range_index = 0;
range_index = get_amplitude_range_index( ranges, signal[signal_i] );
range_arr[range_index]++;
}
}
}
int minimum_meet_range_index = 0;
for( int range_i = max_amplitude_ranges_count - 1 ; range_i >= 0 ; range_i-- )
{
int range_meet_count = range_arr[range_i];
if( range_meet_count >= minimum_peaks_count )
{
minimum_meet_range_index = range_i;
break;
}
}
low_range = ranges[minimum_meet_range_index].min_value;
high_range = ranges[minimum_meet_range_index].max_value;
}
float get_mean_peak_amplitude( vector<signal_type> & signal )
{
size_t count = signal.size();
double sum_peak = 0.0;
unsigned int peak_counter = 0;
for( unsigned int signal_i = 1 ; signal_i < ( count -1 ) ; signal_i++ )
{
if( signal[signal_i] > 0 )
{
double prev = signal[signal_i - 1];
double curr = signal[signal_i];
double next = signal[signal_i + 1];
if( prev < curr && next < curr)
{
sum_peak += curr;
peak_counter += 1;
}
}
}
return (float)sum_peak/peak_counter;
}
void training_sound_template_remove_same( vector_mfcc_level_3 & all_templates_ranges, size_t & removed_number, size_t & remain_number )
{
vector_mfcc_level_3::iterator sounds_begin_1 = all_templates_ranges.begin();
vector_mfcc_level_3::iterator sounds_end_1 = all_templates_ranges.end();
vector_mfcc_level_3::iterator sounds_iter_1 = sounds_begin_1;
removed_number = 0;
remain_number = 0;
size_t remove_counter = 0;
for( ; sounds_iter_1 != sounds_end_1 ; sounds_iter_1++ )
{
bool bErased_in_sound = false;
vector_mfcc_level_2 & templates = (*sounds_iter_1);
vector_mfcc_level_2::iterator templates_begin_1 = templates.begin();
vector_mfcc_level_2::iterator templates_end_1 = templates.end();
vector_mfcc_level_2::iterator templates_iter_1 = templates_begin_1;
for( ; templates_iter_1 != templates_end_1 ; )
{
vector_mfcc_level_1 & template_1 = (*templates_iter_1);
bool bErased = false;
vector_mfcc_level_3::iterator sounds_begin_2 = all_templates_ranges.begin();
vector_mfcc_level_3::iterator sounds_end_2 = all_templates_ranges.end();
vector_mfcc_level_3::iterator sounds_iter_2 = sounds_begin_2;
for( ; sounds_iter_2 != sounds_end_2 ; sounds_iter_2++ )
{
vector_mfcc_level_2 & templates = (*sounds_iter_2);
vector_mfcc_level_2::iterator templates_begin_2 = templates.begin();
vector_mfcc_level_2::iterator templates_end_2 = templates.end();
vector_mfcc_level_2::iterator templates_iter_2 = templates_begin_2;
for( ; templates_iter_2 != templates_end_2 ; )
{
if( templates_iter_1 == templates_iter_2 )
{
templates_iter_2++;
continue;
}
vector_mfcc_level_1 & template_2 = (*templates_iter_2);
if( freq_range_template_equal( template_1, template_2, 0 ) )
{
templates_iter_2 = templates.erase( templates_iter_2 );
remove_counter++;
bErased = true;
break;
}
else
{
templates_iter_2++;
}
}
if( true == bErased )
{
bErased_in_sound = true;
break;
}
}
if( true == bErased )
{
templates_begin_1 = templates.begin();
templates_iter_1 = templates_begin_1;
bErased_in_sound = false;
removed_number ++;
}
else
{
templates_iter_1++;
}
}
if( false == bErased_in_sound )
{
remain_number += templates.size();
}
}
}
void training_sound_template_remove_nearest( vector_mfcc_level_2 & templates_ranges_1, vector_mfcc_level_2 & templates_ranges_2, float min_distance, size_t & removed_number, size_t & remain_number )
{
removed_number = 0;
remain_number = 0;
size_t remove_counter = 0;
vector_mfcc_level_2::iterator templates_begin_1 = templates_ranges_1.begin();
vector_mfcc_level_2::iterator templates_end_1 = templates_ranges_1.end();
vector_mfcc_level_2::iterator templates_iter_1 = templates_begin_1;
for( ; templates_iter_1 != templates_end_1 ; )
{
vector_mfcc_level_1 & template_1 = (*templates_iter_1);
bool bErased = false;
vector_mfcc_level_2::iterator templates_begin_2 = templates_ranges_2.begin();
vector_mfcc_level_2::iterator templates_end_2 = templates_ranges_2.end();
vector_mfcc_level_2::iterator templates_iter_2 = templates_begin_2;
for( ; templates_iter_2 != templates_end_2 ; )
{
vector_mfcc_level_1 & template_2 = (*templates_iter_2);
double distance = 0;
mfcc_get_distance( template_1, template_2, distance );
if( distance < min_distance )
{
templates_iter_2 = templates_ranges_2.erase( templates_iter_2 );
templates_iter_1 = templates_ranges_1.erase( templates_iter_1 );
remove_counter++;
bErased = true;
break;
}
else
{
templates_iter_2++;
}
}
if( false == bErased )
{
templates_iter_1++;
}
}
remain_number = 0;
remain_number += templates_ranges_1.size();
remain_number += templates_ranges_2.size();
removed_number = remove_counter;
}
| 26.047027 | 320 | 0.672567 | vadimostanin2 |
2ed50e6d8f1948cd6a2c2bc343aefc8919fb1b75 | 1,419 | cpp | C++ | 8 Hashing/4 unordered map/main.cpp | AdityaVSM/algorithms | 0ab0147a1e3905cf3096576a89cbce13de2673ed | [
"MIT"
] | null | null | null | 8 Hashing/4 unordered map/main.cpp | AdityaVSM/algorithms | 0ab0147a1e3905cf3096576a89cbce13de2673ed | [
"MIT"
] | null | null | null | 8 Hashing/4 unordered map/main.cpp | AdityaVSM/algorithms | 0ab0147a1e3905cf3096576a89cbce13de2673ed | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
/*
* used to store key-value pair
* unordered maps are implemented using hashing
* elements are arranged internally in any random order
* Repetitive elements can be stored
set.begin() -> O(1) in worst case
set.end() -> O(1) in worst case
set.size() -> O(1) in worst case
set.empty() -> O(1) in worst case
set.erase(it) -> O(1) on average
set.count() -> O(1) on average
set.find() -> O(1) on average
set.insert() -> O(1) on average
[] -> O(1) on average
at -> O(1) on average
*/
int main(){
unordered_map<string, int> m;
m["India"] = 1;
m["UK"] = 24;
m["NZ"] = 13;
m.insert({"US",10});
for (auto it:m)
cout<<"{"<<it.first<<","<<it.second<<"} ";
//find function return address if exists else it returns m.end()
//can also be used to find value of that key
if(m.find("Srilanka")!=m.end())
cout<<"\nSrilanka exists";
else
cout<<"\nSrilanka doesn't exists in map";
auto it1 = m.find("UK");
if(it1!=m.end())
cout<<"\nValue of UK = "<<it1->second;
//count(m) prints 1 if element m exists and 0 if it doesn't exist.
//return type is size_t
if(m.count("India"))
cout<<"\nIndia Exists in map";
else
cout<<"\nIndia doesn't exists in map";
cout<<"\nSize of map "<<m.size();
return 0;
} | 24.465517 | 71 | 0.561663 | AdityaVSM |
2ee43c534273e25c33536761eec08a851552e0b2 | 1,093 | cpp | C++ | School/Clasa a XI-a/Septembrie 2016/sumtri1/main.cpp | AbeleMM/Algorithmic-Problems | 72a8014deeb20ba76189821b7428db06cd27a32e | [
"MIT"
] | 2 | 2019-11-26T13:52:39.000Z | 2022-03-09T16:52:39.000Z | School/Clasa a XI-a/Septembrie 2016/sumtri1/main.cpp | AbeleMM/Algorithmic-Problems | 72a8014deeb20ba76189821b7428db06cd27a32e | [
"MIT"
] | null | null | null | School/Clasa a XI-a/Septembrie 2016/sumtri1/main.cpp | AbeleMM/Algorithmic-Problems | 72a8014deeb20ba76189821b7428db06cd27a32e | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
using namespace std;
ifstream in("sumtri1.in");
ofstream out("sumtri1.out");
int v[102][102],n,mn,alt[102][102],jalt=1;
void fct(int i,int j){
if(i!=1 || j!=1){
if(j==1)
fct(i-1,j);
else if(j==i)
fct(i-1,j-1);
else if(v[i-1][j-1]<v[i-1][j])
fct(i-1,j-1);
else
fct(i-1,j);
}
out<<alt[i][j]<<" ";
}
int main()
{
in>>n;
for(int i=1;i<=n;++i)
for(int j=1;j<=i;++j)
in>>alt[i][j];
for(int i=1;i<=n;++i)
for(int j=1;j<=i;++j)
v[i][j]=alt[i][j];
for(int i=2;i<=n;++i)
for(int j=1;j<=i;++j){
if(j==1)
v[i][j]+=v[i-1][j];
else if(j==i)
v[i][j]+=v[i-1][j-1];
else if(v[i-1][j-1]<v[i-1][j])
v[i][j]+=v[i-1][j-1];
else
v[i][j]+=v[i-1][j];
}
mn=v[n][1];
for(int i=2;i<=n;++i)
if(v[n][i]<mn)
mn=v[n][i],jalt=i;
out<<mn<<"\n";
fct(n,jalt);
return 0;
}
| 22.306122 | 42 | 0.37054 | AbeleMM |
2ee9dcc8b4f44d02e92dabb33a093d7861599580 | 2,989 | cc | C++ | scann/scann/oss_wrappers/scann_status_builder.cc | deepneuralmachine/google-research | d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231 | [
"Apache-2.0"
] | 1 | 2021-01-08T03:21:19.000Z | 2021-01-08T03:21:19.000Z | scann/scann/oss_wrappers/scann_status_builder.cc | deepneuralmachine/google-research | d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231 | [
"Apache-2.0"
] | null | null | null | scann/scann/oss_wrappers/scann_status_builder.cc | deepneuralmachine/google-research | d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The Google Research 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 "scann/oss_wrappers/scann_status_builder.h"
namespace tensorflow {
namespace scann_ops {
StatusBuilder::StatusBuilder(const Status& status) : status_(status) {}
StatusBuilder::StatusBuilder(Status&& status) : status_(status) {}
StatusBuilder::StatusBuilder(tensorflow::error::Code code)
: status_(code, "") {}
StatusBuilder::StatusBuilder(const StatusBuilder& sb) : status_(sb.status_) {
if (sb.streamptr_ != nullptr) {
streamptr_ = absl::make_unique<std::ostringstream>(sb.streamptr_->str());
}
}
Status StatusBuilder::CreateStatus() && {
auto result = [&] {
if (streamptr_->str().empty()) return status_;
std::string new_msg =
absl::StrCat(status_.error_message(), "; ", streamptr_->str());
return Status(status_.code(), new_msg);
}();
status_ = errors::Unknown("");
streamptr_ = nullptr;
return result;
}
StatusBuilder& StatusBuilder::LogError() & { return *this; }
StatusBuilder&& StatusBuilder::LogError() && { return std::move(LogError()); }
StatusBuilder::operator Status() const& {
if (streamptr_ == nullptr) return status_;
return StatusBuilder(*this).CreateStatus();
}
StatusBuilder::operator Status() && {
if (streamptr_ == nullptr) return status_;
return std::move(*this).CreateStatus();
}
StatusBuilder AbortedErrorBuilder() { return StatusBuilder(error::ABORTED); }
StatusBuilder AlreadyExistsErrorBuilder() {
return StatusBuilder(error::ALREADY_EXISTS);
}
StatusBuilder CancelledErrorBuilder() {
return StatusBuilder(error::CANCELLED);
}
StatusBuilder FailedPreconditionErrorBuilder() {
return StatusBuilder(error::FAILED_PRECONDITION);
}
StatusBuilder InternalErrorBuilder() { return StatusBuilder(error::INTERNAL); }
StatusBuilder InvalidArgumentErrorBuilder() {
return StatusBuilder(error::INVALID_ARGUMENT);
}
StatusBuilder NotFoundErrorBuilder() { return StatusBuilder(error::NOT_FOUND); }
StatusBuilder OutOfRangeErrorBuilder() {
return StatusBuilder(error::OUT_OF_RANGE);
}
StatusBuilder UnauthenticatedErrorBuilder() {
return StatusBuilder(error::UNAUTHENTICATED);
}
StatusBuilder UnavailableErrorBuilder() {
return StatusBuilder(error::UNAVAILABLE);
}
StatusBuilder UnimplementedErrorBuilder() {
return StatusBuilder(error::UNIMPLEMENTED);
}
StatusBuilder UnknownErrorBuilder() { return StatusBuilder(error::UNKNOWN); }
} // namespace scann_ops
} // namespace tensorflow
| 33.58427 | 80 | 0.748745 | deepneuralmachine |
2eeb73aac334c4959666b5084f63b760b01e46f7 | 791 | cpp | C++ | src/device_emulate.cpp | angainor/hwmalloc | 2cab9d95f90cef21d3cb7497c2e0fce73e8cc571 | [
"BSD-3-Clause"
] | null | null | null | src/device_emulate.cpp | angainor/hwmalloc | 2cab9d95f90cef21d3cb7497c2e0fce73e8cc571 | [
"BSD-3-Clause"
] | null | null | null | src/device_emulate.cpp | angainor/hwmalloc | 2cab9d95f90cef21d3cb7497c2e0fce73e8cc571 | [
"BSD-3-Clause"
] | null | null | null | /*
* ghex-org
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <hwmalloc/device.hpp>
#include <cstdlib>
#include <cstring>
namespace hwmalloc
{
int
get_num_devices()
{
return 1;
}
int
get_device_id()
{
return 0;
}
void
set_device_id(int /*id*/)
{
}
void*
device_malloc(std::size_t size)
{
return std::memset(std::malloc(size), 0, size);
}
void
device_free(void* ptr) noexcept
{
std::free(ptr);
}
void
memcpy_to_device(void* dst, void const* src, std::size_t count)
{
std::memcpy(dst, src, count);
}
void
memcpy_to_host(void* dst, void const* src, std::size_t count)
{
std::memcpy(dst, src, count);
}
} // namespace hwmalloc
| 13.637931 | 63 | 0.670038 | angainor |
2eeb80e260f7f969c492f7a386b7323d232ae4cd | 391 | hpp | C++ | Game/Game/src/Result.hpp | ikuramikan/get_the_cats | 58cebec03454a9fda246a20cdecb84ae41724ea4 | [
"MIT"
] | 1 | 2021-02-24T12:08:30.000Z | 2021-02-24T12:08:30.000Z | Game/Game/src/Result.hpp | ikuramikan/get_the_cats | 58cebec03454a9fda246a20cdecb84ae41724ea4 | [
"MIT"
] | null | null | null | Game/Game/src/Result.hpp | ikuramikan/get_the_cats | 58cebec03454a9fda246a20cdecb84ae41724ea4 | [
"MIT"
] | null | null | null | #pragma once
#include "Common.hpp"
#include "Cat_anime.hpp"
class Result : public MyApp::Scene
{
private:
const Font font{30};
RectF end_buttom{ Arg::center = Vec2{600, 470}, 200, 60 };
int32 game_score = getData().game_score;
Transition transition{ 0.4s, 0.2s };
Cat_anime cat_anime;
public:
Result(const InitData& init);
void update() override;
void draw() const override;
};
| 17.772727 | 59 | 0.70844 | ikuramikan |
2eecf678bb3fb830e3786728008a85e6e3a5bd05 | 9,498 | cpp | C++ | src/afk/ui/Ui.cpp | christocs/ICT397 | 5ff6e4ed8757effad19b88fdb91f36504208f942 | [
"ISC"
] | null | null | null | src/afk/ui/Ui.cpp | christocs/ICT397 | 5ff6e4ed8757effad19b88fdb91f36504208f942 | [
"ISC"
] | null | null | null | src/afk/ui/Ui.cpp | christocs/ICT397 | 5ff6e4ed8757effad19b88fdb91f36504208f942 | [
"ISC"
] | null | null | null | #include "afk/ui/Ui.hpp"
#include <filesystem>
#include <vector>
#include <imgui/examples/imgui_impl_glfw.h>
#include <imgui/examples/imgui_impl_opengl3.h>
#include <imgui/imgui.h>
#include "afk/Afk.hpp"
#include "afk/debug/Assert.hpp"
#include "afk/io/Log.hpp"
#include "afk/io/Path.hpp"
#include "afk/renderer/Renderer.hpp"
#include "afk/ai/DifficultyManager.hpp"
#include "afk/ui/Unicode.hpp"
#include "cmake/Git.hpp"
#include "cmake/Version.hpp"
using Afk::Engine;
using Afk::Ui;
using std::vector;
using std::filesystem::path;
Ui::~Ui() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
auto Ui::initialize(Renderer::Window _window) -> void {
afk_assert(_window != nullptr, "Window is uninitialized");
afk_assert(!this->is_initialized, "UI already initialized");
this->ini_path = Afk::get_absolute_path(".imgui.ini").string();
this->window = _window;
IMGUI_CHECKVERSION();
ImGui::CreateContext();
auto &io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.IniFilename = this->ini_path.c_str();
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(this->window, true);
ImGui_ImplOpenGL3_Init("#version 410");
auto *noto_sans = io.Fonts->AddFontFromFileTTF(
Afk::get_absolute_path("res/font/NotoSans-Regular.ttf").string().c_str(),
Ui::FONT_SIZE, nullptr, Afk::unicode_ranges.data());
this->fonts["Noto Sans"] = noto_sans;
auto *source_code_pro = io.Fonts->AddFontFromFileTTF(
Afk::get_absolute_path("res/font/SourceCodePro-Regular.ttf").string().c_str(),
Ui::FONT_SIZE, nullptr, Afk::unicode_ranges.data());
this->fonts["Source Code Pro"] = source_code_pro;
auto &style = ImGui::GetStyle();
style.ScaleAllSizes(this->scale);
this->is_initialized = true;
}
auto Ui::prepare() const -> void {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
auto Ui::draw() -> void {
this->draw_stats();
if (this->show_menu) {
this->draw_menu_bar();
}
this->draw_about();
this->draw_log();
this->draw_model_viewer();
this->draw_terrain_controller();
this->draw_exit_screen();
if (this->show_imgui) {
ImGui::ShowDemoWindow(&this->show_imgui);
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
auto Ui::draw_about() -> void {
if (!this->show_about) {
return;
}
ImGui::Begin("About", &this->show_about);
ImGui::Text("afk engine version %s build %.6s (%s)", AFK_VERSION,
GIT_HEAD_HASH, GIT_IS_DIRTY ? "dirty" : "clean");
ImGui::Separator();
ImGui::Text("%s", GIT_COMMIT_SUBJECT);
ImGui::Text("Author: %s", GIT_AUTHOR_NAME);
ImGui::Text("Date: %s", GIT_COMMIT_DATE);
ImGui::End();
}
auto Ui::draw_menu_bar() -> void {
// auto &afk = Engine::get();
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("Tools")) {
if (ImGui::MenuItem("Log")) {
this->show_log = true;
}
if (ImGui::MenuItem("Model viewer")) {
this->show_model_viewer = true;
}
if (ImGui::MenuItem("Terrain controller")) {
this->show_terrain_controller = true;
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Difficulty")) {
if (ImGui::MenuItem("Easy", nullptr, Afk::Engine::get().difficulty_manager.get_difficulty() == AI::DifficultyManager::Difficulty::EASY)) {
if (Afk::Engine::get().difficulty_manager.get_difficulty() != AI::DifficultyManager::Difficulty::EASY) {
Afk::Engine::get().difficulty_manager.set_difficulty(AI::DifficultyManager::Difficulty::EASY);
}
}
if (ImGui::MenuItem("Normal", nullptr, Afk::Engine::get().difficulty_manager.get_difficulty() == AI::DifficultyManager::Difficulty::NORMAL)) {
if (Afk::Engine::get().difficulty_manager.get_difficulty() != AI::DifficultyManager::Difficulty::NORMAL) {
Afk::Engine::get().difficulty_manager.set_difficulty(AI::DifficultyManager::Difficulty::NORMAL);
}
}
if (ImGui::MenuItem("Hard", nullptr, Afk::Engine::get().difficulty_manager.get_difficulty() == AI::DifficultyManager::Difficulty::HARD)) {
if (Afk::Engine::get().difficulty_manager.get_difficulty() != AI::DifficultyManager::Difficulty::HARD) {
Afk::Engine::get().difficulty_manager.set_difficulty(AI::DifficultyManager::Difficulty::HARD);
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Help")) {
if (ImGui::MenuItem("About")) {
this->show_about = true;
}
if (ImGui::MenuItem("Imgui")) {
this->show_imgui = true;
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("Exit")) {
// afk.exit();
this->show_exit_screen = true;
}
ImGui::EndMainMenuBar();
}
}
auto Ui::draw_stats() -> void {
const auto offset_x = 10.0f;
const auto offset_y = 37.0f;
static auto corner = 1;
auto &io = ImGui::GetIO();
if (corner != -1) {
const auto window_pos =
ImVec2{(corner & 1) ? io.DisplaySize.x - offset_x : offset_x,
(corner & 2) ? io.DisplaySize.y - offset_y : offset_y};
const auto window_pos_pivot =
ImVec2{(corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f};
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
}
ImGui::SetNextWindowBgAlpha(0.35f);
ImGui::SetNextWindowSize({200, 100});
if (ImGui::Begin("Stats", &this->show_stats,
(corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDecoration |
ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) {
const auto &afk = Engine::get();
const auto pos = afk.camera.get_position();
const auto angles = afk.camera.get_angles();
ImGui::Text("%.1f fps (%.4f ms)", static_cast<double>(io.Framerate),
static_cast<double>(io.Framerate) / 1000.0);
ImGui::Separator();
ImGui::Text("Position {%.1f, %.1f, %.1f}", static_cast<double>(pos.x),
static_cast<double>(pos.y), static_cast<double>(pos.z));
ImGui::Text("Angles {%.1f, %.1f}", static_cast<double>(angles.x),
static_cast<double>(angles.y));
if (ImGui::BeginPopupContextWindow()) {
if (ImGui::MenuItem("Custom", nullptr, corner == -1)) {
corner = -1;
}
if (ImGui::MenuItem("Top left", nullptr, corner == 0)) {
corner = 0;
}
if (ImGui::MenuItem("Top right", nullptr, corner == 1)) {
corner = 1;
}
if (ImGui::MenuItem("Bottom left", nullptr, corner == 2)) {
corner = 2;
}
if (ImGui::MenuItem("Bottom right", nullptr, corner == 3)) {
corner = 3;
}
if (this->show_stats && ImGui::MenuItem("Close")) {
this->show_stats = false;
}
ImGui::EndPopup();
}
}
ImGui::End();
}
auto Ui::draw_log() -> void {
if (!this->show_log) {
return;
}
ImGui::SetNextWindowSize({500, 400});
this->log.draw("Log", &this->show_log);
}
auto Ui::draw_model_viewer() -> void {
if (!this->show_model_viewer) {
return;
}
auto &afk = Engine::get();
const auto &models = afk.renderer.get_models();
ImGui::SetNextWindowSize({700, 500});
if (ImGui::Begin("Models", &this->show_model_viewer)) {
static auto selected = models.begin()->first;
ImGui::BeginChild("left pane", ImVec2(250, 0), true);
for (const auto &[key, value] : models) {
if (ImGui::Selectable(key.string().c_str(), selected.lexically_normal() ==
key.lexically_normal())) {
selected = key;
}
}
ImGui::EndChild();
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::BeginChild("item view", {0, -ImGui::GetFrameHeightWithSpacing()});
if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) {
if (ImGui::BeginTabItem("Details")) {
const auto &model = models.at(selected);
ImGui::TextWrapped("Total meshes: %zu\n", model.meshes.size());
ImGui::Separator();
auto i = 0;
for (const auto &mesh : model.meshes) {
ImGui::TextWrapped("Mesh %d:\n", i);
ImGui::TextWrapped("VAO: %u\n", mesh.ibo);
ImGui::TextWrapped("VBO: %u\n", mesh.vbo);
ImGui::TextWrapped("IBO: %u\n", mesh.ibo);
ImGui::TextWrapped("Indices: %zu\n", mesh.num_indices);
ImGui::Separator();
++i;
}
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndChild();
ImGui::EndGroup();
}
ImGui::End();
}
auto Ui::draw_terrain_controller() -> void {
if (!this->show_terrain_controller) {
return;
}
ImGui::SetNextWindowSize({300, 150});
if (ImGui::Begin("Terrain controller", &this->show_terrain_controller)) {
// ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
}
ImGui::End();
}
auto Ui::draw_exit_screen() -> void {
if (!this->show_exit_screen) {
return;
}
auto &afk = Engine::get();
const auto texture = afk.renderer.get_texture("res/ui/exit.png");
ImGui::SetNextWindowSize({525, 600});
ImGui::Begin("Exit screen", &this->show_exit_screen);
ImGui::Image(reinterpret_cast<void *>(texture.id),
{static_cast<float>(texture.width), static_cast<float>(texture.height)});
if (ImGui::Button("Exit")) {
afk.exit();
}
ImGui::End();
}
| 30.056962 | 148 | 0.619604 | christocs |
2eef26d831511ea853beb50ca153acb93feecd97 | 1,738 | cpp | C++ | src/apps/haikudepot/util/RatingUtils.cpp | chamalwr/haiku | b2bf76c43decc3fc2de50c4750f830b16807ddef | [
"MIT"
] | 2 | 2020-02-02T06:48:30.000Z | 2020-04-05T13:58:32.000Z | src/apps/haikudepot/util/RatingUtils.cpp | honza1a/haiku | 3959883f5047e803205668d4eb7d083b2d81e2da | [
"MIT"
] | null | null | null | src/apps/haikudepot/util/RatingUtils.cpp | honza1a/haiku | 3959883f5047e803205668d4eb7d083b2d81e2da | [
"MIT"
] | null | null | null | /*
* Copyright 2020, Andrew Lindesay <apl@lindesay.co.nz>.
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include <View.h>
#include "HaikuDepotConstants.h"
#include "RatingUtils.h"
BReference<SharedBitmap> RatingUtils::sStarBlueBitmap
= BReference<SharedBitmap>(new SharedBitmap(RSRC_STAR_BLUE));
BReference<SharedBitmap> RatingUtils::sStarGrayBitmap
= BReference<SharedBitmap>(new SharedBitmap(RSRC_STAR_GREY));
/*static*/ void
RatingUtils::Draw(BView* target, BPoint at, float value)
{
const BBitmap* star;
if (value < RATING_MIN)
star = sStarGrayBitmap->Bitmap(SharedBitmap::SIZE_16);
else
star = sStarBlueBitmap->Bitmap(SharedBitmap::SIZE_16);
if (star == NULL) {
debugger("no star icon found in application resources.");
return;
}
Draw(target, at, value, star);
}
/*static*/ void
RatingUtils::Draw(BView* target, BPoint at, float value,
const BBitmap* star)
{
BRect rect = BOUNDS_RATING;
rect.OffsetBy(at);
// a rectangle covering the whole area of the stars
target->FillRect(rect, B_SOLID_LOW);
if (star == NULL) {
debugger("no star icon found in application resources.");
return;
}
target->SetDrawingMode(B_OP_OVER);
float x = 0;
for (int i = 0; i < 5; i++) {
target->DrawBitmap(star, at + BPoint(x, 0));
x += SIZE_RATING_STAR + WIDTH_RATING_STAR_SPACING;
}
if (value >= RATING_MIN && value < 5.0f) {
target->SetDrawingMode(B_OP_OVER);
rect = BOUNDS_RATING;
rect.right = x - 2;
rect.left = ceilf(rect.left + (value / 5.0f) * rect.Width());
rect.OffsetBy(at);
rgb_color color = target->LowColor();
color.alpha = 190;
target->SetHighColor(color);
target->SetDrawingMode(B_OP_ALPHA);
target->FillRect(rect, B_SOLID_HIGH);
}
} | 22.868421 | 71 | 0.706559 | chamalwr |
2eef9c9d94e6311eb3d54f2b401e764e2273b930 | 538 | cpp | C++ | tests/src/good/StaticInternalVariableAddress_test.cpp | Ybalrid/jet-live | 14b909b00b98399d7e046cd8b7500a3fdfe0a0b1 | [
"MIT"
] | 325 | 2019-01-05T12:40:46.000Z | 2022-03-26T09:06:40.000Z | tests/src/good/StaticInternalVariableAddress_test.cpp | Ybalrid/jet-live | 14b909b00b98399d7e046cd8b7500a3fdfe0a0b1 | [
"MIT"
] | 23 | 2019-01-05T19:43:47.000Z | 2022-01-10T20:11:06.000Z | tests/src/good/StaticInternalVariableAddress_test.cpp | Ybalrid/jet-live | 14b909b00b98399d7e046cd8b7500a3fdfe0a0b1 | [
"MIT"
] | 29 | 2019-01-05T18:49:08.000Z | 2022-03-20T19:14:30.000Z |
#include <catch.hpp>
#include <iostream>
#include <thread>
#include "utility/StaticInternalVariableAddress.hpp"
#include "Globals.hpp"
#include "WaitForReload.hpp"
TEST_CASE("Relocation of static internal variable, comparing address", "[variable]")
{
auto oldVariableAddress = getStaticInternalVariableAddress();
std::cout << "JET_TEST: disable(st_intern_var_addr:1)" << std::endl;
waitForReload();
auto newVariableAddress = getStaticInternalVariableAddress();
REQUIRE(oldVariableAddress == newVariableAddress);
}
| 28.315789 | 84 | 0.758364 | Ybalrid |
2ef53b08ed9cdd1c32c0d9e916268f7bcc1488b5 | 2,638 | cpp | C++ | src/Scheduling/E_Task.cpp | martinc2907/KENS3-1 | f622c069da63b20102aee587209f288d0ff61292 | [
"MIT"
] | 1 | 2020-11-19T11:23:32.000Z | 2020-11-19T11:23:32.000Z | src/Scheduling/E_Task.cpp | martinc2907/KENS3-1 | f622c069da63b20102aee587209f288d0ff61292 | [
"MIT"
] | null | null | null | src/Scheduling/E_Task.cpp | martinc2907/KENS3-1 | f622c069da63b20102aee587209f288d0ff61292 | [
"MIT"
] | 1 | 2019-09-02T07:52:52.000Z | 2019-09-02T07:52:52.000Z | /*
* E_Task.cpp
*
* Created on: 2014. 12. 3.
* Author: Keunhong Lee
*/
#include <E/E_System.hpp>
#include <E/E_Module.hpp>
#include <E/Scheduling/E_Task.hpp>
#include <E/Scheduling/E_Computer.hpp>
#include <E/Scheduling/E_Job.hpp>
#include <E/Scheduling/E_Scheduler.hpp>
namespace E
{
PeriodicTask::PeriodicTask(Computer* computer, Time period, Time executionTime, Time startOffset) : Module(computer->getSystem()), Task()
{
this->period = period;
this->executionTime = executionTime;
this->computer = computer;
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, startOffset);
}
PeriodicTask::~PeriodicTask()
{
}
Module::Message* PeriodicTask::messageReceived(Module* from, Module::Message* message)
{
Message* selfMessage = dynamic_cast<Message*>(message);
switch(selfMessage->type)
{
case TIMER:
{
computer->raiseJob(this, this->executionTime, this->getSystem()->getCurrentTime() + this->period);
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, this->period);
break;
}
default:
assert(0);
}
return nullptr;
}
void PeriodicTask::messageCancelled(Module* to, Module::Message* message)
{
delete message;
}
void PeriodicTask::messageFinished(Module* to, Module::Message* message, Module::Message* response)
{
delete message;
}
SporadicTask::SporadicTask(Computer* computer, Time period, Time executionTime, Time startOffset) : Module(computer->getSystem()), Task()
{
this->minPeriod = period;
this->worstExecution = executionTime;
this->computer = computer;
this->startOffset = startOffset;
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, startOffset);
}
SporadicTask::~SporadicTask()
{
}
Time SporadicTask::getMinPeriod()
{
return minPeriod;
}
Time SporadicTask::getWorstExecution()
{
return worstExecution;
}
Module::Message* SporadicTask::messageReceived(Module* from, Module::Message* message)
{
Message* selfMessage = dynamic_cast<Message*>(message);
switch(selfMessage->type)
{
case TIMER:
{
computer->raiseJob(this, this->worstExecution, this->getSystem()->getCurrentTime() + this->minPeriod);
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, this->minPeriod);
break;
}
default:
assert(0);
}
return nullptr;
}
void SporadicTask::messageCancelled(Module* to, Module::Message* message)
{
delete message;
}
void SporadicTask::messageFinished(Module* to, Module::Message* message, Module::Message* response)
{
delete message;
}
}
| 19.984848 | 137 | 0.728961 | martinc2907 |
2ef6f08b927c25b94c1db02d189c595db8dd0221 | 11,899 | cpp | C++ | src/CacheManager.cpp | MyunginLee/tinc | d5d681d6fddca5fe9c194df0ba25902d785c895f | [
"BSD-3-Clause"
] | null | null | null | src/CacheManager.cpp | MyunginLee/tinc | d5d681d6fddca5fe9c194df0ba25902d785c895f | [
"BSD-3-Clause"
] | 2 | 2020-12-22T19:22:37.000Z | 2020-12-22T19:44:09.000Z | src/CacheManager.cpp | MyunginLee/tinc | d5d681d6fddca5fe9c194df0ba25902d785c895f | [
"BSD-3-Clause"
] | 3 | 2020-07-23T00:16:54.000Z | 2022-02-05T08:28:34.000Z | #include "tinc/CacheManager.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include "al/io/al_File.hpp"
#define TINC_META_VERSION_MAJOR 1
#define TINC_META_VERSION_MINOR 0
using namespace tinc;
// To regenerate this file run update_schema_cpp.sh
#include "tinc_cache_schema.cpp"
CacheManager::CacheManager(DistributedPath cachePath) : mCachePath(cachePath) {
auto person_schema = nlohmann::json::parse(
doc_tinc_cache_schema_json,
doc_tinc_cache_schema_json + doc_tinc_cache_schema_json_len);
try {
mValidator.set_root_schema(person_schema); // insert root-schema
} catch (const std::exception &e) {
std::cerr << "Validation of schema failed, here is why: " << e.what()
<< "\n";
}
if (!al::File::exists(mCachePath.rootPath + mCachePath.relativePath)) {
al::Dir::make(mCachePath.rootPath + mCachePath.relativePath);
}
if (!al::File::exists(mCachePath.filePath())) {
writeToDisk();
} else {
try {
updateFromDisk();
} catch (std::exception &e) {
std::string backupFilename = mCachePath.filePath() + ".old";
size_t count = 0;
while (al::File::exists(mCachePath.filePath() + std::to_string(count))) {
count++;
}
if (!al::File::copy(mCachePath.filePath(),
mCachePath.filePath() + std::to_string(count))) {
std::cerr << "Cache invalid and backup failed." << std::endl;
throw std::exception();
}
std::cerr << "Invalid cache format. Ignoring old cache." << std::endl;
}
}
}
void CacheManager::appendEntry(CacheEntry &entry) {
std::unique_lock<std::mutex> lk(mCacheLock);
mEntries.push_back(entry);
}
std::vector<std::string> CacheManager::findCache(const SourceInfo &sourceInfo,
bool verifyHash) {
std::unique_lock<std::mutex> lk(mCacheLock);
for (const auto &entry : mEntries) {
if (entry.sourceInfo.commandLineArguments ==
sourceInfo.commandLineArguments &&
entry.sourceInfo.tincId == sourceInfo.tincId &&
entry.sourceInfo.type == sourceInfo.type) {
auto entryArguments = entry.sourceInfo.arguments;
bool argsMatch = false;
if (sourceInfo.arguments.size() == entry.sourceInfo.arguments.size()) {
size_t matchCount = 0;
for (const auto &sourceArg : sourceInfo.arguments) {
for (auto arg = entryArguments.begin(); arg != entryArguments.end();
arg++) {
if (sourceArg.id == arg->id) {
if (sourceArg.value.type == arg->value.type) {
if (sourceArg.value.type == VARIANT_DOUBLE ||
sourceArg.value.type == VARIANT_FLOAT) {
if (sourceArg.value.valueDouble == arg->value.valueDouble) {
entryArguments.erase(arg);
matchCount++;
break;
}
} else if (sourceArg.value.type == VARIANT_INT32 ||
sourceArg.value.type == VARIANT_INT64) {
if (sourceArg.value.valueInt64 == arg->value.valueInt64) {
entryArguments.erase(arg);
matchCount++;
break;
}
} else if (sourceArg.value.type == VARIANT_STRING) {
if (sourceArg.value.valueStr == arg->value.valueStr) {
entryArguments.erase(arg);
matchCount++;
break;
}
} else {
std::cerr << "ERROR: Unsupported type for argument value"
<< std::endl;
}
} else {
std::cout << "ERROR: type mismatch for argument in cache. "
"Ignoring cache"
<< std::endl;
continue;
}
}
}
}
if (matchCount == sourceInfo.arguments.size() &&
entryArguments.size() == 0) {
return entry.filenames;
}
} else {
// TODO develop mechanisms to recover stale cache
std::cout << "Warning, cache entry found, but argument size mismatch"
<< std::endl;
}
}
}
return {};
}
std::string CacheManager::cacheDirectory() { return mCachePath.path(); }
void CacheManager::updateFromDisk() {
std::unique_lock<std::mutex> lk(mCacheLock);
// j["tincMetaVersionMajor"] = TINC_META_VERSION_MAJOR;
// j["tincMetaVersionMinor"] = TINC_META_VERSION_MINOR;
// j["entries"] = {};
std::ifstream f(mCachePath.filePath());
if (f.good()) {
nlohmann::json j;
f >> j;
try {
mValidator.validate(j);
} catch (const std::exception &e) {
std::cerr << "Validation failed, here is why: " << e.what() << std::endl;
return;
}
if (j["tincMetaVersionMajor"] != TINC_META_VERSION_MAJOR ||
j["tincMetaVersionMinor"] != TINC_META_VERSION_MINOR) {
std::cerr << "Incompatible schema version: " << j["tincMetaVersionMajor"]
<< "." << j["tincMetaVersionMinor"] << " .This binary uses "
<< TINC_META_VERSION_MAJOR << "." << TINC_META_VERSION_MINOR
<< "\n";
return;
}
mEntries.clear();
for (auto entry : j["entries"]) {
CacheEntry e;
e.timestampStart = entry["timestamp"]["start"];
e.timestampEnd = entry["timestamp"]["end"];
e.filenames = entry["filenames"].get<std::vector<std::string>>();
e.cacheHits = entry["cacheHits"];
e.stale = entry["stale"];
e.userInfo.userName = entry["userInfo"]["userName"];
e.userInfo.userHash = entry["userInfo"]["userHash"];
e.userInfo.ip = entry["userInfo"]["ip"];
e.userInfo.port = entry["userInfo"]["port"];
e.userInfo.server = entry["userInfo"]["server"];
e.sourceInfo.type = entry["sourceInfo"]["type"];
e.sourceInfo.tincId = entry["sourceInfo"]["tincId"];
e.sourceInfo.commandLineArguments =
entry["sourceInfo"]["commandLineArguments"];
e.sourceInfo.workingPath.relativePath =
entry["sourceInfo"]["workingPath"]["relativePath"];
e.sourceInfo.workingPath.rootPath =
entry["sourceInfo"]["workingPath"]["rootPath"];
e.sourceInfo.hash = entry["sourceInfo"]["hash"];
for (auto arg : entry["sourceInfo"]["arguments"]) {
SourceArgument newArg;
newArg.id = arg["id"];
if (arg["value"].is_number_float()) {
newArg.value = arg["value"].get<double>();
} else if (arg["value"].is_number_integer()) {
newArg.value = arg["value"].get<int64_t>();
} else if (arg["value"].is_string()) {
newArg.value = arg["value"].get<std::string>();
}
e.sourceInfo.arguments.push_back(newArg);
}
for (auto arg : entry["sourceInfo"]["dependencies"]) {
SourceArgument newArg;
newArg.id = arg["id"];
if (arg["value"].is_number_float()) {
newArg.value = arg["value"].get<double>();
} else if (arg["value"].is_number_integer()) {
newArg.value = arg["value"].get<int64_t>();
} else if (arg["value"].is_string()) {
newArg.value = arg["value"].get<std::string>();
}
e.sourceInfo.dependencies.push_back(newArg);
}
for (auto arg : entry["sourceInfo"]["fileDependencies"]) {
DistributedPath newArg(arg["filename"], arg["relativePath"],
arg["rootPath"]);
e.sourceInfo.fileDependencies.push_back(newArg);
}
mEntries.push_back(e);
}
} else {
std::cerr << "Error attempting to read cache: " << mCachePath.filePath()
<< std::endl;
}
}
// when creating the validator
void CacheManager::writeToDisk() {
std::unique_lock<std::mutex> lk(mCacheLock);
std::ofstream o(mCachePath.filePath());
if (o.good()) {
nlohmann::json j;
j["tincMetaVersionMajor"] = TINC_META_VERSION_MAJOR;
j["tincMetaVersionMinor"] = TINC_META_VERSION_MINOR;
j["entries"] = std::vector<nlohmann::json>();
for (auto &e : mEntries) {
nlohmann::json entry;
entry["timestamp"]["start"] = e.timestampStart;
entry["timestamp"]["end"] = e.timestampEnd;
entry["filenames"] = e.filenames;
entry["cacheHits"] = e.cacheHits;
entry["stale"] = e.stale;
entry["userInfo"]["userName"] = e.userInfo.userName;
entry["userInfo"]["userHash"] = e.userInfo.userHash;
entry["userInfo"]["ip"] = e.userInfo.ip;
entry["userInfo"]["port"] = e.userInfo.port;
entry["userInfo"]["server"] = e.userInfo.server;
entry["sourceInfo"]["type"] = e.sourceInfo.type;
entry["sourceInfo"]["tincId"] = e.sourceInfo.tincId;
entry["sourceInfo"]["commandLineArguments"] =
e.sourceInfo.commandLineArguments;
// TODO validate working path
entry["sourceInfo"]["workingPath"]["relativePath"] =
e.sourceInfo.workingPath.relativePath;
entry["sourceInfo"]["workingPath"]["rootPath"] =
e.sourceInfo.workingPath.rootPath;
entry["sourceInfo"]["hash"] = e.sourceInfo.hash;
entry["sourceInfo"]["arguments"] = std::vector<nlohmann::json>();
entry["sourceInfo"]["dependencies"] = std::vector<nlohmann::json>();
entry["sourceInfo"]["fileDependencies"] = std::vector<nlohmann::json>();
for (auto arg : e.sourceInfo.arguments) {
nlohmann::json newArg;
newArg["id"] = arg.id;
if (arg.value.type == VARIANT_DOUBLE ||
arg.value.type == VARIANT_FLOAT) {
newArg["value"] = arg.value.valueDouble;
} else if (arg.value.type == VARIANT_INT32 ||
arg.value.type == VARIANT_INT64) {
newArg["value"] = arg.value.valueInt64;
} else if (arg.value.type == VARIANT_STRING) {
newArg["value"] = arg.value.valueStr;
} else {
newArg["value"] = nlohmann::json();
}
entry["sourceInfo"]["arguments"].push_back(newArg);
}
for (auto arg : e.sourceInfo.dependencies) {
nlohmann::json newArg;
newArg["id"] = arg.id;
if (arg.value.type == VARIANT_DOUBLE ||
arg.value.type == VARIANT_FLOAT) {
newArg["value"] = arg.value.valueDouble;
} else if (arg.value.type == VARIANT_INT32 ||
arg.value.type == VARIANT_INT64) {
newArg["value"] = arg.value.valueInt64;
} else if (arg.value.type == VARIANT_STRING) {
newArg["value"] = arg.value.valueStr;
} else {
newArg["value"] = nlohmann::json();
}
entry["sourceInfo"]["dependencies"].push_back(newArg);
}
for (auto arg : e.sourceInfo.fileDependencies) {
nlohmann::json newArg;
newArg["fileName"] = arg.filename;
newArg["relativePath"] = arg.relativePath;
newArg["rootPath"] = arg.rootPath;
entry["sourceInfo"]["fileDependencies"].push_back(newArg);
}
j["entries"].push_back(entry);
}
o << j << std::endl;
o.close();
} else {
std::cerr << "ERROR: Can't create cache file: " << mCachePath.filePath()
<< std::endl;
throw std::runtime_error("Can't create cache file");
}
}
std::string CacheManager::dump() {
writeToDisk();
std::unique_lock<std::mutex> lk(mCacheLock);
std::ifstream f(mCachePath.filePath());
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
void CacheManager::tincSchemaFormatChecker(const std::string &format,
const std::string &value) {
if (format == "date-time") {
// TODO validate date time
return;
// throw std::invalid_argument("value is not a good something");
} else
throw std::logic_error("Don't know how to validate " + format);
}
| 36.612308 | 79 | 0.575763 | MyunginLee |
2ef799625cf3bb8252f8682ac6587aaab8cbb875 | 622 | cpp | C++ | third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | {% include 'copyright_block.txt' %}
#include "config.h"
#include "{{cpp_class}}.h"
{% for filename in cpp_includes %}
#include "{{filename}}"
{% endfor %}
namespace blink {
{# Constructor #}
{{cpp_class}}::{{cpp_class}}()
{
{% for member in members if member.cpp_default_value %}
{{member.setter_name}}({{member.cpp_default_value}});
{% endfor %}
}
DEFINE_TRACE({{cpp_class}})
{
{% for member in members if member.is_traceable %}
visitor->trace(m_{{member.cpp_name}});
{% endfor %}
{% if parent_cpp_class %}
{{parent_cpp_class}}::trace(visitor);
{% endif %}
}
} // namespace blink
| 20.733333 | 59 | 0.630225 | wenfeifei |
2efa49e56c80c9ecd4a078791134a409ab19f01a | 360 | cpp | C++ | socket/tcp_socket.cpp | xqq/drawboard | 993f0f90c127c51ad5837656fc1383b2d9e7ddde | [
"MIT"
] | 10 | 2020-01-18T09:28:47.000Z | 2020-04-28T15:37:42.000Z | socket/tcp_socket.cpp | xqq/drawboard | 993f0f90c127c51ad5837656fc1383b2d9e7ddde | [
"MIT"
] | 1 | 2020-04-28T15:29:52.000Z | 2020-04-28T15:35:03.000Z | socket/tcp_socket.cpp | xqq/drawboard | 993f0f90c127c51ad5837656fc1383b2d9e7ddde | [
"MIT"
] | 2 | 2020-01-20T06:54:26.000Z | 2022-01-11T09:01:42.000Z | //
// @author magicxqq <xqq@xqq.im>
//
#include "tcp_socket.hpp"
#ifndef _WIN32
#include "tcp_socket_posix.hpp"
#else
#include "tcp_socket_winsock.hpp"
#endif
TcpSocket* TcpSocket::Create() {
TcpSocket* socket = nullptr;
#ifndef _WIN32
socket = new TcpSocketPosix();
#else
socket = new TcpSocketWinsock();
#endif
return socket;
}
| 14.4 | 37 | 0.677778 | xqq |
2efbe52d51c61fd110b20b361b1193a087607a7f | 940 | cpp | C++ | plugin/dllmain.cpp | matanki-saito/vic2dll | c5ecc1820ba6376ba83ab50cdf0087bb5eb20c41 | [
"MIT"
] | null | null | null | plugin/dllmain.cpp | matanki-saito/vic2dll | c5ecc1820ba6376ba83ab50cdf0087bb5eb20c41 | [
"MIT"
] | 15 | 2021-08-08T15:16:33.000Z | 2022-02-27T07:41:59.000Z | plugin/dllmain.cpp | matanki-saito/vic2dll | c5ecc1820ba6376ba83ab50cdf0087bb5eb20c41 | [
"MIT"
] | null | null | null | // dllmain.cpp : DLL アプリケーションのエントリ ポイントを定義します。
#include "pch.h"
#include "plugin.h"
#include "mod_download.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ulReasonForCall,
LPVOID lpReserved
)
{
if (ulReasonForCall == DLL_PROCESS_ATTACH) {
BytePattern::StartLog(L"vic2_jps");
DllError e = {};
// 設定
RunOptions options;
// Version取得
Version::GetVersionFromExe(&options);
// INIから取得
Ini::GetOptionsFromIni(&options);
// Versionチェック
if (Validator::ValidateVersion(e, options)) {
// mod download
#ifndef _DEBUG
e |= ModDownload::Init();
#endif
// フォント読み込み
e |= Font::Init(options);
// メインテキスト
e |= MainText::Init(options);
// ツールチップとボタン
e |= TooltipAndButton::Init(options);
Validator::Validate(e, options);
}
}
else if (ulReasonForCall == DLL_PROCESS_DETACH) {
BytePattern::ShutdownLog();
}
return TRUE;
}
| 18.431373 | 50 | 0.626596 | matanki-saito |
2efcae515c322a32f0824a5328284a24682d69e4 | 1,846 | cpp | C++ | main.cpp | fhwedel-hoe/ueye_mjpeg_streamer | 3aec9638ffa764b22e798753a312ac5e8b61a468 | [
"MIT"
] | 2 | 2020-03-13T01:56:32.000Z | 2020-08-19T22:12:10.000Z | main.cpp | fhwedel-hoe/ueye_mjpeg_streamer | 3aec9638ffa764b22e798753a312ac5e8b61a468 | [
"MIT"
] | null | null | null | main.cpp | fhwedel-hoe/ueye_mjpeg_streamer | 3aec9638ffa764b22e798753a312ac5e8b61a468 | [
"MIT"
] | 1 | 2021-02-06T19:49:33.000Z | 2021-02-06T19:49:33.000Z | #include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <chrono>
#include <stdexcept>
#include <thread>
#include <memory>
#include <dlfcn.h>
#include "publisher.hpp"
#include "compress.hpp"
#include "serve.hpp"
#include "camera.hpp"
void capture(IPC_globals & ipc) {
for (;;) { // stream forever
try { // do not break loop due to exceptions
ipc.readers.read(); // wait for reader
std::cerr << "Initializing camera for new recording session..." << std::endl;
std::unique_ptr<Camera> camera = init_camera();
std::cerr << "Camera initialized, starting stream..." << std::endl;
/* capture a single image and submit it to the streaming library */
while (ipc.readers.read_unsafe() > 0) {
/* grab raw image data frame */
RawImage raw_image = camera->grab_frame();
/* compress image data */
binary_data image_compressed =
compress(raw_image.data, raw_image.width, raw_image.height, raw_image.pixelFormat);
/* publish for readers */
ipc.data.publish(image_compressed);
}
std::cerr << "Stopping camera due to lack of viewers..." << std::endl;
// ^^ happens implicitly during destructor
} catch (std::exception & se) {
std::cerr << "Unexpected exception: " << se.what() << "\n";
}
}
}
IPC_globals ipc_globals;
const unsigned short server_port = 8080;
int main(int, char**) {
std::thread(capture, std::ref(ipc_globals)).detach();
try {
boost::asio::io_service io_service;
server(io_service, server_port, ipc_globals);
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| 33.563636 | 103 | 0.582882 | fhwedel-hoe |
2efd72ac39f7a136a4318c3720610d7cbf173798 | 3,459 | cpp | C++ | src/coremods/core_modules.cpp | BerilBBJ/beryldb | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 206 | 2021-04-27T21:44:24.000Z | 2022-02-23T12:01:20.000Z | src/coremods/core_modules.cpp | BerilBBJ/beryldb | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 10 | 2021-05-04T19:46:59.000Z | 2021-10-01T23:43:07.000Z | src/coremods/core_modules.cpp | berylcorp/beryl | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 7 | 2021-04-28T16:17:56.000Z | 2021-12-10T01:14:42.000Z | /*
* BerylDB - A lightweight database.
* http://www.beryldb.com
*
* Copyright (C) 2021 - Carlos F. Ferry <cferry@beryldb.com>
*
* This file is part of BerylDB. BerylDB is free software: you can
* redistribute it and/or modify it under the terms of the BSD License
* version 3.
*
* More information about our licensing can be found at https://docs.beryl.dev
*/
#include "beryl.h"
#include "notifier.h"
#include "engine.h"
/*
* Loadmodule Loads a module. Keep in mind that given modules must
* exist in coremodules or modules in order to be loaded.
*
* @requires 'r'.
*
* @parameters:
*
* · string : module to load.
*
* @protocol:
*
* · protocol : OK, or ERR_UNLOAD_MOD.
*/
class CommandLoadmodule : public Command
{
public:
CommandLoadmodule(Module* parent) : Command(parent, "LOADMODULE", 1, 1)
{
flags = 'r';
syntax = "<modulename>";
}
COMMAND_RESULT Handle(User* user, const Params& parameters);
};
COMMAND_RESULT CommandLoadmodule::Handle(User* user, const Params& parameters)
{
if (Kernel->Modules->Load(parameters[0]))
{
sfalert(user, NOTIFY_DEFAULT, "Module %s loaded.", parameters[0].c_str());
user->SendProtocol(BRLD_OK, PROCESS_OK);
return SUCCESS;
}
else
{
user->SendProtocol(ERR_INPUT2, ERR_UNLOAD_MOD, Kernel->Modules->LastError());
return FAILED;
}
}
/*
* ULoadmodule UnLoads a module. Keep in mind that given modules must
* be loaded in order to be unloaded.
*
* @requires 'r'.
*
* @parameters:
*
* · string : module to unload.
*
* @protocol:
*
* · protocol : OK, ERR_UNLOAD_MOD, or ERROR.
*/
class CommandUnloadmodule : public Command
{
public:
CommandUnloadmodule(Module* parent) : Command(parent, "UNLOADMODULE", 1)
{
flags = 'r';
syntax = "<modulename>";
}
COMMAND_RESULT Handle(User* user, const Params& parameters);
};
COMMAND_RESULT CommandUnloadmodule::Handle(User* user, const Params& parameters)
{
if (Daemon::Match(parameters[0], "core_*", ascii_case_insensitive))
{
sfalert(user, NOTIFY_DEFAULT, "Warning: Unloading core module %s.", parameters[0].c_str());
}
Module* InUse = Kernel->Modules->Find(parameters[0]);
if (InUse == creator)
{
user->SendProtocol(ERR_INPUT, PROCESS_ERROR);
return FAILED;
}
if (InUse && Kernel->Modules->Unload(InUse))
{
sfalert(user, NOTIFY_DEFAULT, "Module %s loaded.", parameters[0].c_str());
user->SendProtocol(BRLD_OK, PROCESS_OK);
}
else
{
user->SendProtocol(ERR_INPUT2, ERR_UNLOAD_MOD, (InUse ? Kernel->Modules->LastError() : NOT_FOUND));
return FAILED;
}
return SUCCESS;
}
class ModuleCoreModule : public Module
{
private:
CommandLoadmodule cmdloadmod;
CommandUnloadmodule cmdunloadmod;
public:
ModuleCoreModule() : cmdloadmod(this), cmdunloadmod(this)
{
}
Version GetDescription()
{
return Version("Provides Load and Unload module commands.", VF_BERYLDB|VF_CORE);
}
};
MODULE_LOAD(ModuleCoreModule)
| 24.707143 | 113 | 0.583117 | BerilBBJ |
2c00303aca9fea8f9a1ccc0474b81e684cafcf34 | 5,482 | hpp | C++ | include/mtao/types.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | include/mtao/types.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | 4 | 2020-04-18T16:16:05.000Z | 2020-04-18T16:17:36.000Z | include/mtao/types.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | #pragma once
// Verbose because clang/llvm pretend to have gnuc
#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wint-in-bool-context"
#endif
#include <Eigen/Dense>
#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic pop
#endif
#include <map>
#include <vector>
namespace mtao {
template <typename T, int A, int B>
using Matrix = Eigen::Matrix<T, A, B>;
template <typename T, int A>
using SquareMatrix = Matrix<T, A, A>;
template <typename T>
using MatrixX = SquareMatrix<T, Eigen::Dynamic>;
template <typename T, int D>
using Vector = Matrix<T, D, 1>;
template <typename T, int D>
using RowVector = Matrix<T, 1, D>;
template <typename T>
using VectorX = Vector<T, Eigen::Dynamic>;
template <typename T>
using RowVectorX = RowVector<T, Eigen::Dynamic>;
template <typename T>
using Vector2 = Vector<T, 2>;
template <typename T>
using RowVector2 = RowVector<T, 2>;
template <typename T>
using Vector3 = Vector<T, 3>;
template <typename T>
using RowVector3 = RowVector<T, 3>;
template <typename T>
using Vector4 = Vector<T, 4>;
template <typename T>
using RowVector4 = RowVector<T, 4>;
template <typename T, int D>
using ColVectors = Matrix<T, D, Eigen::Dynamic>;
template <typename T, int D>
using RowVectors = Matrix<T, Eigen::Dynamic, D>;
using Mat3i = SquareMatrix<int, 3>;
using Mat2i = SquareMatrix<int, 2>;
using ColVecs4i = ColVectors<int, 4>;
using ColVecs3i = ColVectors<int, 3>;
using ColVecs2i = ColVectors<int, 2>;
using RowVecs3i = RowVectors<int, 3>;
using RowVecs2i = RowVectors<int, 2>;
using Vec3i = Vector<int, 3>;
using Vec2i = Vector<int, 2>;
using MatXi = MatrixX<int>;
using VecXi = VectorX<int>;
using RowVecXi = RowVectorX<int>;
using Mat4f = SquareMatrix<float, 4>;
using Mat3f = SquareMatrix<float, 3>;
using Mat2f = SquareMatrix<float, 2>;
using ColVecs4f = ColVectors<float, 4>;
using ColVecs3f = ColVectors<float, 3>;
using ColVecs2f = ColVectors<float, 2>;
using RowVecs3f = RowVectors<float, 3>;
using RowVecs2f = RowVectors<float, 2>;
using Vec4f = Vector<float, 4>;
using Vec3f = Vector<float, 3>;
using Vec2f = Vector<float, 2>;
using MatXf = MatrixX<float>;
using VecXf = VectorX<float>;
using RowVecXf = RowVectorX<float>;
using Mat4d = SquareMatrix<double, 4>;
using Mat3d = SquareMatrix<double, 3>;
using Mat2d = SquareMatrix<double, 2>;
using ColVecs4d = ColVectors<double, 4>;
using ColVecs3d = ColVectors<double, 3>;
using ColVecs2d = ColVectors<double, 2>;
using RowVecs3d = RowVectors<double, 3>;
using RowVecs2d = RowVectors<double, 2>;
using Vec4d = Vector<double, 4>;
using Vec3d = Vector<double, 3>;
using Vec2d = Vector<double, 2>;
using MatXd = MatrixX<double>;
using VecXd = VectorX<double>;
using RowVecXd = RowVectorX<double>;
using Vec2i = Vector2<int>;
using Vec3i = Vector3<int>;
using Vec4i = Vector4<int>;
// types packaged for a given embedded dimensions
template <typename T, int D_>
struct embedded_types {
using Scalar = T;
constexpr static int D = D_;
template <int A, int B>
using Matrix = Matrix<T, A, B>;
template <int A>
using SquareMatrix = SquareMatrix<T, A>;
template <int A>
using Vector = Vector<T, A>;
using VectorD = Vector<D>;
using SquareMatrixD = SquareMatrix<D>;
using MatrixX = mtao::MatrixX<T>;
using VectorX = mtao::VectorX<T>;
template <int D>
using ColVectors = Matrix<D, Eigen::Dynamic>;
template <int D>
using RowVectors = Matrix<Eigen::Dynamic, D>;
template <int N>
using ColVectorsD = Matrix<D, N>;
template <int N>
using RowVectorsD = Matrix<N, D>;
using ColVectorsDX = ColVectorsD<Eigen::Dynamic>;
using RowVectorsDX = RowVectorsD<Eigen::Dynamic>;
};
template <typename T>
struct scalar_types {
typedef Eigen::Matrix<T, 2, 1> Vec2;
typedef Eigen::Matrix<T, 3, 1> Vec3;
typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VecX;
typedef Eigen::Matrix<T, 2, 2> Mat2;
typedef Eigen::Matrix<T, 3, 3> Mat3;
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatX;
};
template <int Dim>
struct dim_types {
typedef Eigen::Matrix<double, Dim, 1> Vecf;
typedef Eigen::Matrix<float, Dim, 1> Vecd;
typedef Eigen::Matrix<int, Dim, 1> Veci;
typedef Eigen::Matrix<double, Dim, Dim> Matf;
typedef Eigen::Matrix<float, Dim, Dim> Matd;
};
template <typename T, int Dim>
struct numerical_types {
typedef Eigen::Matrix<T, Dim, 1> Vec;
typedef Eigen::Matrix<T, Dim, Dim> Mat;
};
namespace internal {
template <typename T>
struct allocator_selector {
using type = std::allocator<T>;
};
template <typename T, int R, int C>
struct allocator_selector<Eigen::Matrix<T, R, C>> {
using type = Eigen::aligned_allocator<Eigen::Matrix<T, R, C>>;
};
} // namespace internal
template <typename T>
using allocator = typename internal::allocator_selector<T>::type;
template <typename T, typename Allocator = mtao::allocator<T>>
using vector = std::vector<T, Allocator>;
template <typename Key, typename T, typename Compare = std::less<Key>,
typename Allocator = mtao::allocator<std::pair<const Key, T>>>
using map = std::map<Key, T, Compare, Allocator>;
template <typename T>
struct scalar_type {
using type = T;
};
template <typename T, int R, int C>
struct scalar_type<Eigen::Matrix<T, R, C>> {
using type = T;
};
template <typename T>
using scalar_type_t = typename scalar_type<T>::type;
} // namespace mtao
| 29.315508 | 73 | 0.703393 | mtao |
2c03da1dd464fbc37bff173f8f70e58cea01bf5d | 562 | cpp | C++ | chapter01/1.4_Flow_of_Control/1.4.3_Reading_an_Unknown_Number_of_Inputs.cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | 9 | 2019-05-10T05:39:21.000Z | 2022-02-22T08:04:52.000Z | chapter01/1.4_Flow_of_Control/1.4.3_Reading_an_Unknown_Number_of_Inputs.cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | null | null | null | chapter01/1.4_Flow_of_Control/1.4.3_Reading_an_Unknown_Number_of_Inputs.cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | 6 | 2019-05-13T13:39:19.000Z | 2022-02-22T08:05:01.000Z | /**
* 1.4.3 读取数量不定的输入数据
* @Author Bob
* @Eamil 0haizhu0@gmail.com
* @Date 2017/6/26
*/
#include <iostream>
/**
* 读取数量不定的输入数据,
* 只有输入换行符(比如:\n)或者非法字符(非数字,但直接回车不会停止)的时候才会停止接收数据,输出运算结果
* @EOF EOF 是 end of file 的缩写,windows环境是:ctrl+Z,unix 环境是:ctrl+D,即可模拟(?)EOF
*/
int main(){
std::cout << "数量不定的输入数据:输入一系列整数(想结束输入参数的时候输入 EOF 或者输入非数字字符即可):" << std::endl;
int sum = 0, value = 0;
// 在while循环中完成数据读取操作
while (std::cin >> value) { // 只要cin读取成功就返回true,读取结束或者非法则返回false
sum += value;
}
std::cout << "Sum is " << sum << std::endl;
return 0;
} | 23.416667 | 79 | 0.635231 | NorthFacing |
2c03ebf0289ea27755cd98b27d0c4648d6331887 | 909 | hpp | C++ | libctrpf/include/CTRPluginFrameworkImpl/Menu/GatewayRAMDumper.hpp | MirayXS/Vapecord-ACNL-Plugin | 247eb270dfe849eda325cc0c6adc5498d51de3ef | [
"MIT"
] | null | null | null | libctrpf/include/CTRPluginFrameworkImpl/Menu/GatewayRAMDumper.hpp | MirayXS/Vapecord-ACNL-Plugin | 247eb270dfe849eda325cc0c6adc5498d51de3ef | [
"MIT"
] | null | null | null | libctrpf/include/CTRPluginFrameworkImpl/Menu/GatewayRAMDumper.hpp | MirayXS/Vapecord-ACNL-Plugin | 247eb270dfe849eda325cc0c6adc5498d51de3ef | [
"MIT"
] | null | null | null | #ifndef CTRPLUGINFRAMEWORKIMPL_GATEWAYRAMDUMPER_HPP
#define CTRPLUGINFRAMEWORKIMPL_GATEWAYRAMDUMPER_HPP
#include "types.h"
#include "CTRPluginFrameworkImpl/Search/Search.hpp"
namespace CTRPluginFramework
{
class GatewayRAMDumper
{
public:
GatewayRAMDumper(void);
~GatewayRAMDumper(void){}
// Return true if finished
bool operator()(void);
bool _SelectRegion();
private:
void _OpenFile(void);
void _WriteHeader(void);
void _DrawProgress(void);
std::string _fileName;
File _file;
u32 _currentAddress;
u32 _endAddress;
u32 _regionIndex;
u32 _achievedSize;
u32 _totalSize;
std::vector<Region> _regions;
};
}
#endif | 25.25 | 51 | 0.547855 | MirayXS |
2c089201d3bed722abb3d92e212d3fa43fe74a6e | 10,469 | cpp | C++ | engine/hid/src/hid.cpp | Epitaph128/defold | 554625a6438c38014b8f701c4a6e0ca684478618 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-11-13T09:03:39.000Z | 2020-11-13T09:03:45.000Z | engine/hid/src/hid.cpp | Epitaph128/defold | 554625a6438c38014b8f701c4a6e0ca684478618 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | engine/hid/src/hid.cpp | Epitaph128/defold | 554625a6438c38014b8f701c4a6e0ca684478618 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-06T08:54:02.000Z | 2020-07-06T08:54:02.000Z | // Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 <assert.h>
#include <dlib/log.h>
#include "hid.h"
#include "hid_private.h"
#include <string.h>
#include <dlib/dstrings.h>
#include <dlib/utf8.h>
namespace dmHID
{
NewContextParams::NewContextParams()
{
memset(this, 0, sizeof(NewContextParams));
}
Context::Context()
{
memset(this, 0, sizeof(Context));
}
HContext NewContext(const NewContextParams& params)
{
HContext context = new Context();
context->m_IgnoreMouse = params.m_IgnoreMouse;
context->m_IgnoreKeyboard = params.m_IgnoreKeyboard;
context->m_IgnoreGamepads = params.m_IgnoreGamepads;
context->m_IgnoreTouchDevice = params.m_IgnoreTouchDevice;
context->m_IgnoreAcceleration = params.m_IgnoreAcceleration;
context->m_FlipScrollDirection = params.m_FlipScrollDirection;
context->m_GamepadConnectivityCallback = params.m_GamepadConnectivityCallback;
return context;
}
void SetGamepadFuncUserdata(HContext context, void* userdata)
{
context->m_GamepadConnectivityUserdata = userdata;
}
void DeleteContext(HContext context)
{
delete context;
}
HGamepad GetGamepad(HContext context, uint8_t index)
{
if (index < MAX_GAMEPAD_COUNT)
return &context->m_Gamepads[index];
else
return INVALID_GAMEPAD_HANDLE;
}
uint32_t GetGamepadButtonCount(HGamepad gamepad)
{
return gamepad->m_ButtonCount;
}
uint32_t GetGamepadHatCount(HGamepad gamepad)
{
return gamepad->m_HatCount;
}
uint32_t GetGamepadAxisCount(HGamepad gamepad)
{
return gamepad->m_AxisCount;
}
bool IsKeyboardConnected(HContext context)
{
return context->m_KeyboardConnected;
}
bool IsMouseConnected(HContext context)
{
return context->m_MouseConnected;
}
bool IsGamepadConnected(HGamepad gamepad)
{
if (gamepad != 0x0)
return gamepad->m_Connected;
else
return false;
}
bool IsTouchDeviceConnected(HContext context)
{
return context->m_TouchDeviceConnected;
}
bool IsAccelerometerConnected(HContext context)
{
return context->m_AccelerometerConnected;
}
bool GetKeyboardPacket(HContext context, KeyboardPacket* out_packet)
{
if (out_packet != 0x0 && context->m_KeyboardConnected)
{
*out_packet = context->m_KeyboardPacket;
return true;
}
else
{
return false;
}
}
bool GetTextPacket(HContext context, TextPacket* out_packet)
{
if (out_packet != 0x0 && context->m_KeyboardConnected)
{
*out_packet = context->m_TextPacket;
context->m_TextPacket.m_Size = 0;
context->m_TextPacket.m_Text[0] = '\0';
return true;
}
else
{
return false;
}
}
void AddKeyboardChar(HContext context, int chr) {
if (context) {
char buf[5];
uint32_t n = dmUtf8::ToUtf8((uint16_t) chr, buf);
buf[n] = '\0';
TextPacket* p = &context->m_TextPacket;
p->m_Size = dmStrlCat(p->m_Text, buf, sizeof(p->m_Text));
}
}
bool GetMarkedTextPacket(HContext context, MarkedTextPacket* out_packet)
{
if (out_packet != 0x0 && context->m_KeyboardConnected)
{
*out_packet = context->m_MarkedTextPacket;
context->m_MarkedTextPacket.m_Size = 0;
context->m_MarkedTextPacket.m_HasText = 0;
context->m_MarkedTextPacket.m_Text[0] = '\0';
return true;
}
else
{
return false;
}
}
void SetMarkedText(HContext context, char* text) {
if (context) {
MarkedTextPacket* p = &context->m_MarkedTextPacket;
p->m_HasText = 1;
p->m_Size = dmStrlCpy(p->m_Text, text, sizeof(p->m_Text));
}
}
void SetGamepadConnectivity(HContext context, int gamepad, bool connected) {
assert(context);
GamepadPacket* p = &context->m_Gamepads[gamepad].m_Packet;
p->m_GamepadDisconnected = !connected;
p->m_GamepadConnected = connected;
}
bool GetMousePacket(HContext context, MousePacket* out_packet)
{
if (out_packet != 0x0 && context->m_MouseConnected)
{
*out_packet = context->m_MousePacket;
return true;
}
else
{
return false;
}
}
bool GetGamepadPacket(HGamepad gamepad, GamepadPacket* out_packet)
{
if (gamepad != 0x0 && out_packet != 0x0)
{
*out_packet = gamepad->m_Packet;
gamepad->m_Packet.m_GamepadDisconnected = false;
gamepad->m_Packet.m_GamepadConnected = false;
return true;
}
else
{
return false;
}
}
bool GetTouchDevicePacket(HContext context, TouchDevicePacket* out_packet)
{
if (out_packet != 0x0 && context->m_TouchDeviceConnected)
{
*out_packet = context->m_TouchDevicePacket;
return true;
}
else
{
return false;
}
}
bool GetAccelerationPacket(HContext context, AccelerationPacket* out_packet)
{
if (out_packet != 0x0)
{
*out_packet = context->m_AccelerationPacket;
return true;
}
else
{
return false;
}
}
bool GetKey(KeyboardPacket* packet, Key key)
{
if (packet != 0x0)
return packet->m_Keys[key / 32] & (1 << (key % 32));
else
return false;
}
void SetKey(HContext context, Key key, bool value)
{
if (context != 0x0)
{
if (value)
context->m_KeyboardPacket.m_Keys[key / 32] |= (1 << (key % 32));
else
context->m_KeyboardPacket.m_Keys[key / 32] &= ~(1 << (key % 32));
}
}
bool GetMouseButton(MousePacket* packet, MouseButton button)
{
if (packet != 0x0)
return packet->m_Buttons[button / 32] & (1 << (button % 32));
else
return false;
}
void SetMouseButton(HContext context, MouseButton button, bool value)
{
if (context != 0x0)
{
if (value)
context->m_MousePacket.m_Buttons[button / 32] |= (1 << (button % 32));
else
context->m_MousePacket.m_Buttons[button / 32] &= ~(1 << (button % 32));
}
}
void SetMousePosition(HContext context, int32_t x, int32_t y)
{
if (context != 0x0)
{
MousePacket& packet = context->m_MousePacket;
packet.m_PositionX = x;
packet.m_PositionY = y;
}
}
void SetMouseWheel(HContext context, int32_t value)
{
if (context != 0x0)
{
context->m_MousePacket.m_Wheel = value;
}
}
bool GetGamepadButton(GamepadPacket* packet, uint32_t button)
{
if (packet != 0x0)
return packet->m_Buttons[button / 32] & (1 << (button % 32));
else
return false;
}
void SetGamepadButton(HGamepad gamepad, uint32_t button, bool value)
{
if (gamepad != 0x0)
{
if (value)
gamepad->m_Packet.m_Buttons[button / 32] |= (1 << (button % 32));
else
gamepad->m_Packet.m_Buttons[button / 32] &= ~(1 << (button % 32));
}
}
bool GetGamepadHat(GamepadPacket* packet, uint32_t hat, uint8_t& hat_value)
{
if (packet != 0x0)
{
hat_value = packet->m_Hat[hat];
return true;
} else {
return false;
}
}
void SetGamepadAxis(HGamepad gamepad, uint32_t axis, float value)
{
if (gamepad != 0x0)
{
gamepad->m_Packet.m_Axis[axis] = value;
}
}
// NOTE: A bit contrived function only used for unit-tests. See AddTouchPosition
bool GetTouch(TouchDevicePacket* packet, uint32_t touch_index, int32_t* x, int32_t* y, uint32_t* id, bool* pressed, bool* released)
{
if (packet != 0x0
&& x != 0x0
&& y != 0x0
&& id != 0x0)
{
if (touch_index < packet->m_TouchCount)
{
const Touch& t = packet->m_Touches[touch_index];
*x = t.m_X;
*y = t.m_Y;
*id = t.m_Id;
if (pressed != 0x0) {
*pressed = t.m_Phase == dmHID::PHASE_BEGAN;
}
if (released != 0x0) {
*released = t.m_Phase == dmHID::PHASE_ENDED || t.m_Phase == dmHID::PHASE_CANCELLED;
}
return true;
}
}
return false;
}
// NOTE: A bit contrived function only used for unit-tests
// We should perhaps include additional relevant touch-arguments
void AddTouch(HContext context, int32_t x, int32_t y, uint32_t id, Phase phase)
{
if (context->m_TouchDeviceConnected)
{
TouchDevicePacket& packet = context->m_TouchDevicePacket;
if (packet.m_TouchCount < MAX_TOUCH_COUNT)
{
Touch& t = packet.m_Touches[packet.m_TouchCount++];
t.m_X = x;
t.m_Y = y;
t.m_Id = id;
t.m_Phase = phase;
}
}
}
void ClearTouches(HContext context)
{
if (context->m_TouchDeviceConnected)
{
context->m_TouchDevicePacket.m_TouchCount = 0;
}
}
}
| 27.47769 | 135 | 0.560512 | Epitaph128 |
2c0a985f02c864619b7ede4d6f772be0853b8751 | 354 | cpp | C++ | ExpressionEvaluation/evaluation/operand/custom_function/custom_function.cpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | ExpressionEvaluation/evaluation/operand/custom_function/custom_function.cpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | ExpressionEvaluation/evaluation/operand/custom_function/custom_function.cpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | #include "custom_function.hpp"
namespace expression::evaluate {
custom_function::custom_function(evaluation_function user_function, const argument_compilers &compilers)
: operand(compilers),
user_function_(move(user_function)) {}
double custom_function::get_result(const std::valarray<double> &args) const {
return user_function_(args);
}
} | 32.181818 | 104 | 0.788136 | suiyili |
2c0dcfcd6110029e98d6ac97cd541c2e43449ab1 | 2,484 | cpp | C++ | src/old_src/Pearson_test.cpp | doliinychenko/iSS | 9391b8830e385c0f5f1600a1cfd1ad355ea582c5 | [
"MIT"
] | 4 | 2018-11-29T14:34:55.000Z | 2020-11-25T14:44:32.000Z | src/old_src/Pearson_test.cpp | doliinychenko/iSS | 9391b8830e385c0f5f1600a1cfd1ad355ea582c5 | [
"MIT"
] | 1 | 2020-04-05T01:17:31.000Z | 2020-04-05T01:17:31.000Z | src/old_src/Pearson_test.cpp | doliinychenko/iSS | 9391b8830e385c0f5f1600a1cfd1ad355ea582c5 | [
"MIT"
] | 6 | 2018-04-06T17:08:35.000Z | 2020-10-19T19:10:38.000Z | // Ver 1.1
// Note that all calculations are done at a given particle rapidity y; and all
// "y_minus_y_minus_eta_s" appearences in the code are y-y_minus_eta_s.
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
#include<cmath>
#include<iomanip>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "arsenal.h"
#include "Pearson_distribution.h"
using namespace std;
int main() {
double hist_size = 10.;
int hist_length = 101;
double *hist = new double[hist_length];
double *hist_x = new double[hist_length];
double dx = hist_size/(hist_length - 1.);
for (int i = 0; i < hist_length; i++) {
hist_x[i] = -hist_size/2. + i*dx;
hist[i] = 0.0;
}
double chi_1 = 0.;
double chi_2 = 0.1;
double chi_3 = 0.0;
double chi_4 = 0.08;
PearsonDistribution test(chi_1, chi_2, chi_3, chi_4);
// sw.tic();
// sum = 0;
// for (long i=1; i<=10000; i++) sum += binomial_coefficient(i, i/2);
// cout << "sum=" << sum << endl;
// sw.toc();
// cout << "1 takes time: " << sw.takeTime() << endl;
// sw.tic();
// sum = 0;
// for (long i=1; i<=10000; i++) sum += 1.0/(i+1)/beta_function(i-i/2+1, i/2+1);
// cout << "sum=" << sum << endl;
// sw.toc();
// cout << "2 takes time: " << sw.takeTime() << endl;
// for (long i=0; i<10; i++) cout << i << " " << nbd.pdf(i) << endl;
// for (double i=0; i<10; i+=0.25) cout << setw(10) << i << " " << nbd.envelopPdfTab->map(i) << endl;
// for (double i=0; i<0.1; i+=0.003641) cout << setw(10) << i << " " << nbd.envelopInvCDFTab->map(i) << endl;
// nbd.envelopPdfTab->printFunction();
long n_sample = 5000000;
for (long i = 0; i < n_sample; i++) {
double random_sample = test.rand();
int idx = static_cast<int>((random_sample + (hist_size + dx)/2.)/dx);
if (idx >= 0 && idx < hist_length) {
hist[idx] += 1.;
}
}
ofstream checkof("check_Pearson.dat");
for (int i = 0; i < hist_length; i++) {
hist[i] /= (n_sample*dx);
hist[i] += 1e-30;
}
double norm = hist[50]/test.pdf(hist_x[50]);
for (int i = 0; i < hist_length; i++) {
checkof << scientific << setw(18) << setprecision(6)
<< hist_x[i] << " "
<< test.pdf(hist_x[i])*norm << " "
<< hist[i] << endl;
}
checkof.close();
delete[] hist_x;
delete[] hist;
}
| 28.551724 | 114 | 0.53744 | doliinychenko |
2c0e69620b0dd8f94f782d65279b6e7313c63381 | 7,812 | cxx | C++ | src/filter/vtkPCLMovingLeastSquaresFilter.cxx | Kitware/ParaView-PCLPlugin | e3948034d6d105b22e3dffad20d8b8149e000d79 | [
"Apache-2.0"
] | 5 | 2019-10-11T14:09:10.000Z | 2021-07-31T20:01:53.000Z | src/filter/vtkPCLMovingLeastSquaresFilter.cxx | dys564843131/ParaView-PCLPlugin | a6c13164bfe46796647ea3a7b4433a28d61f0bbc | [
"Apache-2.0"
] | null | null | null | src/filter/vtkPCLMovingLeastSquaresFilter.cxx | dys564843131/ParaView-PCLPlugin | a6c13164bfe46796647ea3a7b4433a28d61f0bbc | [
"Apache-2.0"
] | 2 | 2019-12-09T01:53:24.000Z | 2021-07-31T20:01:54.000Z | //==============================================================================
//
// Copyright 2012-2019 Kitware, 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 "vtkPCLMovingLeastSquaresFilter.h"
#include "vtkPCLConversions.h"
#include "vtkObjectFactory.h"
#define PCL_NO_PRECOMPILE 1
#include <pcl/surface/mls.h>
#include <pcl/search/kdtree.h>
//------------------------------------------------------------------------------
// The indices must correspond to the ones in the proxy.
template <typename PointType, typename NormalType>
typename pcl::MovingLeastSquares<PointType,NormalType>::UpsamplingMethod
getUpsamplingMethod(unsigned int index)
{
switch (index)
{
case 1:
return pcl::MovingLeastSquares<PointType,NormalType>::DISTINCT_CLOUD;
case 2:
return pcl::MovingLeastSquares<PointType,NormalType>::SAMPLE_LOCAL_PLANE;
case 3:
return pcl::MovingLeastSquares<PointType,NormalType>::RANDOM_UNIFORM_DENSITY;
case 4:
return pcl::MovingLeastSquares<PointType,NormalType>::VOXEL_GRID_DILATION;
case 0:
default:
return pcl::MovingLeastSquares<PointType,NormalType>::NONE;
}
}
//------------------------------------------------------------------------------
char const * getUpsamplingMethodString(unsigned int index)
{
switch (index)
{
case 1:
return "DISTINCT_CLOUD";
case 2:
return "SAMPLE_LOCAL_PLANE";
case 3:
return "RANDOM_UNIFORM_DENSITY";
case 4:
return "VOXEL_GRID_DILATION";
case 0:
default:
return "NONE";
}
}
//------------------------------------------------------------------------------
// The indices must correspond to the ones in the proxy.
pcl::MLSResult::ProjectionMethod
getProjectionMethod(unsigned int index)
{
switch (index)
{
case 1:
return pcl::MLSResult::SIMPLE;
case 2:
return pcl::MLSResult::ORTHOGONAL;
case 0:
default:
return pcl::MLSResult::NONE;
}
}
//------------------------------------------------------------------------------
char const * getProjectionMethodString(unsigned int index)
{
switch (index)
{
case 1:
return "SIMPLE";
case 2:
return "ORTHOGONAL";
case 0:
default:
return "NONE";
}
}
//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkPCLMovingLeastSquaresFilter);
//------------------------------------------------------------------------------
vtkPCLMovingLeastSquaresFilter::vtkPCLMovingLeastSquaresFilter()
{
}
//------------------------------------------------------------------------------
vtkPCLMovingLeastSquaresFilter::~vtkPCLMovingLeastSquaresFilter()
{
}
//------------------------------------------------------------------------------
void vtkPCLMovingLeastSquaresFilter::PrintSelf(ostream & os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ComputeNormals: " << (this->ComputeNormals ? "yes" : "no") << '\n';
os << indent << "PolynomialOrder: " << this->PolynomialOrder << '\n';
os << indent << "SearchRadius: " << this->SearchRadius << '\n';
os << indent << "SqrGaussParam: " << this->SqrGaussParam << '\n';
os << indent << "UpsamplingRadius: " << this->UpsamplingRadius << '\n';
os << indent << "UpsamplingStepSize: " << this->UpsamplingStepSize << '\n';
os << indent << "PointDensity: " << this->PointDensity << '\n';
os << indent << "DilationVoxelSize: " << this->DilationVoxelSize << '\n';
os << indent << "CacheMLSResults: " << this->CacheMLSResults << '\n';
os << indent << "NumberOfThreads: " << this->NumberOfThreads << '\n';
os << indent << "UpsamplingMethod: " << getUpsamplingMethodString(this->UpsamplingMethod) << '\n';
os << indent << "ProjectionMethod: " << getProjectionMethodString(this->ProjectionMethod) << '\n';
os << indent << "UseKdtree: " << this->UseKdTree << "\n";
os << indent << "Epsilon: " << this->Epsilon << "\n";
}
//------------------------------------------------------------------------------
int vtkPCLMovingLeastSquaresFilter::ApplyPCLFilter(
vtkPolyData * input,
vtkPolyData * output
)
{
int index = vtkPCLConversions::GetPointTypeIndex(input);
#define _statement(PointType) return this->InternalApplyPCLFilter<PointType>(input, output);
PCLP_INVOKE_WITH_PCL_XYZ_POINT_TYPE(index, _statement)
#undef _statement
vtkErrorMacro(<< "no XYZ point data in input")
return 0;
}
//------------------------------------------------------------------------------
// Apply the filter to any point type.
template <typename PointType>
int vtkPCLMovingLeastSquaresFilter::InternalApplyPCLFilter(
vtkPolyData * input,
vtkPolyData * output
)
{
if (this->ComputeNormals)
{
std::set<std::string> requiredFieldNames { "normal_x", "normal_y", "normal_z" };
PointType const point;
int index = vtkPCLConversions::GetPointTypeIndex<PointType const &>(point, requiredFieldNames);
#define _statement(NormalPointType) return this->InternalInternalApplyPCLFilter<PointType, NormalPointType>(input, output);
PCLP_INVOKE_WITH_XYZ_NORMAL_POINT_TYPE(index, _statement)
#undef _statement
vtkErrorMacro(<< "failed to determine a corresponding point type with normal attributes")
return 0;
}
else
{
return this->InternalInternalApplyPCLFilter<PointType, PointType>(input, output);
}
}
template <typename InPointType, typename OutPointType>
int vtkPCLMovingLeastSquaresFilter::InternalInternalApplyPCLFilter(
vtkPolyData * input,
vtkPolyData * output
)
{
// For convenience, typedef the cloud type based on the template point type.
// typedef pcl::Normal NormalPointType;
typedef pcl::PointCloud<InPointType> InCloudT;
typedef pcl::PointCloud<OutPointType> OutCloudT;
// typedef pcl::PointCloud<NormalPointType> NormalCloudT;
typedef pcl::search::KdTree<InPointType> KdTreeT;
typename InCloudT::Ptr inputCloud(new InCloudT);
typename OutCloudT::Ptr outputCloud(new OutCloudT);
// typename NormalCloudT::Ptr normalCloud(new NormalCloudT);
vtkPCLConversions::PointCloudFromPolyData(input, inputCloud);
// pcl::MovingLeastSquares<InPointType, NormalPointType> mls;
pcl::MovingLeastSquares<InPointType, OutPointType> mls;
mls.setUpsamplingMethod(
getUpsamplingMethod<InPointType, OutPointType>(
this->UpsamplingMethod
)
);
mls.setProjectionMethod(getProjectionMethod(this->ProjectionMethod));
mls.setInputCloud(inputCloud);
// mls.setOutputNormals(normalCloud);
if (this->UseKdTree)
{
typename KdTreeT::Ptr kdtree(new KdTreeT());
kdtree->setEpsilon(this->Epsilon);
mls.setSearchMethod(kdtree);
}
mls.setComputeNormals(this->ComputeNormals);
mls.setPolynomialOrder(this->PolynomialOrder);
// mls.setPolynomialFit(this->PolynomialFit);
mls.setSearchRadius(this->SearchRadius);
mls.setSqrGaussParam(this->SqrGaussParam);
mls.setUpsamplingRadius(this->UpsamplingRadius);
mls.setUpsamplingStepSize(this->UpsamplingStepSize);
mls.setPointDensity(this->PointDensity);
mls.setDilationVoxelSize(this->DilationVoxelSize);
mls.setDilationIterations(this->DilationIterations);
mls.setCacheMLSResults(this->CacheMLSResults);
mls.setNumberOfThreads(this->NumberOfThreads);
mls.process((* outputCloud));
vtkPCLConversions::PolyDataFromPointCloud(outputCloud, output);
return 1;
}
| 34.263158 | 123 | 0.647593 | Kitware |
2c0fab5d22ae16693a4679df1ace86e3d7ce5bb0 | 3,459 | cpp | C++ | Old/Source/SceneModule.cpp | TinoTano/Games_Factory_2D | 116ec94f05eb805654f3d30735134e81eb873c60 | [
"MIT"
] | 1 | 2020-02-07T04:50:57.000Z | 2020-02-07T04:50:57.000Z | Old/Source/SceneModule.cpp | TinoTano/Games_Factory_2D | 116ec94f05eb805654f3d30735134e81eb873c60 | [
"MIT"
] | null | null | null | Old/Source/SceneModule.cpp | TinoTano/Games_Factory_2D | 116ec94f05eb805654f3d30735134e81eb873c60 | [
"MIT"
] | 1 | 2020-02-07T04:51:00.000Z | 2020-02-07T04:51:00.000Z | #include "SceneModule.h"
#include "GameObject.h"
#include "Application.h"
#include "CameraModule.h"
#include "ComponentTransform.h"
#include "Scene.h"
#include "Data.h"
#include "Log.h"
#include "FileSystemModule.h"
SceneModule::SceneModule(const char* moduleName, bool gameModule) : Module(moduleName, gameModule)
{
updateSceneVertices = false;
currentScene = nullptr;
clearScene = false;
}
SceneModule::~SceneModule()
{
}
bool SceneModule::Init(Data& settings)
{
NewScene();
return true;
}
bool SceneModule::PreUpdate(float delta_time)
{
if (clearScene)
{
NewScene();
clearScene = false;
}
return true;
}
bool SceneModule::Update(float delta_time)
{
return true;
}
bool SceneModule::CleanUp()
{
DestroyScene();
return true;
}
void SceneModule::NewScene()
{
DestroyScene();
currentScene = new Scene("Default", "", "");
sceneGameObjects.clear();
sceneGameObjects.emplace_back(currentScene->GetRootGameObject());
}
void SceneModule::DestroyScene()
{
if (currentScene != nullptr)
{
delete currentScene;
currentScene = nullptr;
}
}
void SceneModule::LoadScene(std::string path)
{
Data data;
if (data.LoadData(path))
{
int dataType = data.GetInt("Type");
if (dataType != Resource::RESOURCE_SCENE)
{
CONSOLE_ERROR("%s", "Failed to load a Scene. " + path + " Is not a valid Scene Path");
return;
}
NewScene();
int gameObjectCount = data.GetInt("GameObjectCount");
for (int i = 0; i < gameObjectCount; i++)
{
Data sectionData;
if (data.GetSectionData("GameObject" + std::to_string(i), sectionData))
{
GameObject* gameObject = nullptr;
if (i == 0)
{
gameObject = currentScene->GetRootGameObject();
}
else
{
gameObject = App->sceneModule->CreateNewObject();
}
gameObject->LoadData(sectionData);
}
}
}
}
void SceneModule::SaveScene(std::string path)
{
Data data;
data.AddInt("Type", Resource::RESOURCE_SCENE);
data.AddInt("GameObjectCount", sceneGameObjects.size());
for (int i = 0; i < sceneGameObjects.size(); i++)
{
data.CreateSection("GameObject" + std::to_string(i));
sceneGameObjects[i]->SaveData(data);
data.CloseSection("GameObject" + std::to_string(i));
}
if (App->fileSystemModule->GetExtension(path) != ".scene")
{
path += ".scene";
}
data.SaveData(path);
}
void SceneModule::ClearScene()
{
clearScene = true;
}
GameObject* SceneModule::CreateNewObject(GameObject* parent, std::string name)
{
if (name.empty()) name = "GameObject ";
GameObject* go = new GameObject(name + std::to_string(sceneGameObjects.size()), parent);
sceneGameObjects.emplace_back(go);
return go;
}
GameObject * SceneModule::DuplicateGameObject(GameObject & go)
{
Data data;
go.SaveData(data);
GameObject* duplicated = CreateNewObject();
std::string UID = duplicated->GetUID();
duplicated->LoadData(data);
duplicated->SetUID(UID);
return duplicated;
}
void SceneModule::RemoveGameObject(GameObject & gameObject)
{
GameObject* sceneRoot = currentScene->GetRootGameObject();
sceneRoot->RemoveChild(&gameObject);
for (int i = 0; i < sceneGameObjects.size(); i++)
{
if (sceneGameObjects[i] == &gameObject)
{
sceneGameObjects.erase(sceneGameObjects.begin() + i);
break;
}
}
}
GameObject * SceneModule::FindGameObject(std::string UID)
{
GameObject* ret = nullptr;
for (GameObject* gameObject : sceneGameObjects)
{
if (gameObject->GetUID() == UID)
{
ret = gameObject;
}
}
return ret;
}
| 19.432584 | 98 | 0.689217 | TinoTano |
2c0fb45aa4ab3d4f4eee4b6179bd5d949e05e07d | 5,464 | cpp | C++ | editor/source/widget/debugger/pass/debugger_pass.cpp | skarab/coffee-master | 6c3ff71b7f15735e41c9859b6db981b94414c783 | [
"MIT"
] | null | null | null | editor/source/widget/debugger/pass/debugger_pass.cpp | skarab/coffee-master | 6c3ff71b7f15735e41c9859b6db981b94414c783 | [
"MIT"
] | null | null | null | editor/source/widget/debugger/pass/debugger_pass.cpp | skarab/coffee-master | 6c3ff71b7f15735e41c9859b6db981b94414c783 | [
"MIT"
] | null | null | null | #include "widget/debugger/pass/debugger_pass.h"
namespace coffee_editor
{
//-META---------------------------------------------------------------------------------------//
COFFEE_BeginType(widget::DebuggerPass);
COFFEE_Ancestor(graphics::FramePass);
COFFEE_EndType();
namespace widget
{
//-CONSTRUCTORS-------------------------------------------------------------------------------//
DebuggerPass::DebuggerPass() :
graphics::FramePass("Debugger"),
_PassType(DEBUGGER_PASS_TYPE_None)
{
}
//--------------------------------------------------------------------------------------------//
DebuggerPass::~DebuggerPass()
{
SetPassType(DEBUGGER_PASS_TYPE_None);
}
//--------------------------------------------------------------------------------------------//
void DebuggerPass::SetPassType(DEBUGGER_PASS_TYPE type)
{
graphics::FramePassSystem& system = graphics::FramePassSystem::Get();
if (_PassType!=DEBUGGER_PASS_TYPE_None)
{
system.GetPasses()[system.GetPasses().GetSize()-1] = NULL;
system.GetPasses().Remove(system.GetPasses().GetSize()-1);
Finalize(NULL);
}
_PassType = type;
if (_PassType!=DEBUGGER_PASS_TYPE_None)
{
system.GetPasses().AddItem(this);
Initialize(NULL);
}
}
//-OPERATIONS---------------------------------------------------------------------------------//
void DebuggerPass::Initialize(graphics::FramePass* previous_pass)
{
_Layer = COFFEE_New(graphics::FrameLayerBGRA, GetFrameBuffer().GetWidth(), GetFrameBuffer().GetHeight(), false);
GetFrameBuffer().AttachLayer(*_Layer);
switch (_PassType)
{
case DEBUGGER_PASS_TYPE_Depth:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_depth.material");
break;
case DEBUGGER_PASS_TYPE_LinearDepth:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_linear_depth.material");
break;
case DEBUGGER_PASS_TYPE_Normal:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_normal.material");
break;
case DEBUGGER_PASS_TYPE_Color:
case DEBUGGER_PASS_TYPE_Material:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_rgb8.material");
break;
case DEBUGGER_PASS_TYPE_Lightning:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_lightning.material");
break;
case DEBUGGER_PASS_TYPE_DetectNAN:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_detect_nan.material");
break;
}
}
//--------------------------------------------------------------------------------------------//
void DebuggerPass::Finalize(graphics::FramePass* previous_pass)
{
GetFrameBuffer().DetachLayer(*_Layer);
COFFEE_Delete(_Layer);
}
//--------------------------------------------------------------------------------------------//
void DebuggerPass::Render(graphics::Viewport& viewport, graphics::FramePass* previous_pass)
{
if (viewport.HasCamera() && _Material.IsAvailable())
{
graphics::FramePassSystem& system = graphics::FramePassSystem::Get();
switch(_PassType)
{
case DEBUGGER_PASS_TYPE_Depth: system.GetGBufferPass().GetDepth().Bind(0); break;
case DEBUGGER_PASS_TYPE_LinearDepth: system.GetGBufferPass().GetLinearDepth().Bind(0); break;
case DEBUGGER_PASS_TYPE_Normal: system.GetGBufferPass().GetNormal().Bind(0); break;
case DEBUGGER_PASS_TYPE_Color: system.GetGBufferPass().GetColor().Bind(0); break;
case DEBUGGER_PASS_TYPE_Material: system.GetGBufferPass().GetMaterial().Bind(0); break;
case DEBUGGER_PASS_TYPE_Lightning: system.GetLightningPass().GetFrameBuffer().GetLayer(0).Bind(0); break;
case DEBUGGER_PASS_TYPE_DetectNAN: system.GetSkyPass().GetFrameBuffer().GetLayer(0).Bind(0); break;
}
_Material.Bind();
RenderQuad(viewport);
_Material.UnBind();
switch(_PassType)
{
case DEBUGGER_PASS_TYPE_Depth: system.GetGBufferPass().GetDepth().UnBind(0); break;
case DEBUGGER_PASS_TYPE_LinearDepth: system.GetGBufferPass().GetLinearDepth().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Normal: system.GetGBufferPass().GetNormal().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Color: system.GetGBufferPass().GetColor().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Material: system.GetGBufferPass().GetMaterial().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Lightning: system.GetLightningPass().GetFrameBuffer().GetLayer(0).UnBind(0); break;
case DEBUGGER_PASS_TYPE_DetectNAN: system.GetSkyPass().GetFrameBuffer().GetLayer(0).UnBind(0); break;
}
}
else
{
graphics::Renderer::Get().ClearColor();
}
}
}
}
| 40.474074 | 126 | 0.551428 | skarab |
2c10dff7684bfd5c53d6b9c0e57ff82bc948d935 | 8,803 | cpp | C++ | app/src/main/cpp/src/wallOverlap.cpp | CCH852573130/3DPrinting11 | dfe6e6c1a17c1a222d93c5c835c67e5b43999024 | [
"MIT"
] | null | null | null | app/src/main/cpp/src/wallOverlap.cpp | CCH852573130/3DPrinting11 | dfe6e6c1a17c1a222d93c5c835c67e5b43999024 | [
"MIT"
] | null | null | null | app/src/main/cpp/src/wallOverlap.cpp | CCH852573130/3DPrinting11 | dfe6e6c1a17c1a222d93c5c835c67e5b43999024 | [
"MIT"
] | 3 | 2020-04-12T01:53:41.000Z | 2020-07-06T08:07:49.000Z | /** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */
#include "wallOverlap.h"
#include <cmath> // isfinite
#include <sstream>
#include "utils/AABB.h" // for debug output svg html
#include "utils/SVG.h"
namespace cura
{
WallOverlapComputation::WallOverlapComputation(Polygons& polygons, const coord_t line_width)
: overlap_linker(polygons, line_width)
, line_width(line_width)
{
}
Ratio WallOverlapComputation::getFlow(const Point& from, const Point& to)
{
using Point2LinkIt = PolygonProximityLinker::Point2Link::iterator;
if (!overlap_linker.isLinked(from))
{ // [from] is not linked
return 1;
}
const std::pair<Point2LinkIt, Point2LinkIt> to_links = overlap_linker.getLinks(to);
if (to_links.first == to_links.second)
{ // [to] is not linked
return 1;
}
coord_t overlap_area = 0;
// note that we don't need to loop over all from_links, because they are handled in the previous getFlow(.) call (or in the very last)
for (Point2LinkIt to_link_it = to_links.first; to_link_it != to_links.second; ++to_link_it)
{
const ProximityPointLink& to_link = to_link_it->second;
ListPolyIt to_it = to_link.a;
ListPolyIt to_other_it = to_link.b;
if (to_link.a.p() != to)
{
assert(to_link.b.p() == to && "Either part of the link should be the point in the link!");
std::swap(to_it, to_other_it);
}
ListPolyIt from_it = to_it.prev();
ListPolyIt to_other_next_it = to_other_it.next(); // move towards [from]; the lines on the other side move in the other direction
// to from
// o<--o<--T<--F
// | : :
// v : :
// o-->o-->o-->o
// , ,
// ; to_other_next
// to other
bool are_in_same_general_direction = dot(from - to, to_other_it.p() - to_other_next_it.p()) > 0;
// handle multiple points linked to [to]
// o<<<T<<<F
// / |
// / |
// o>>>o>>>o
// , ,
// ; to other next
// to other
if (!are_in_same_general_direction)
{
overlap_area = std::max(overlap_area, handlePotentialOverlap(to_it, to_it, to_link, to_other_next_it, to_other_it));
}
// handle multiple points linked to [to_other]
// o<<<T<<<F
// | /
// | /
// o>>>o>>>o
bool all_are_in_same_general_direction = are_in_same_general_direction && dot(from - to, to_other_it.prev().p() - to_other_it.p()) > 0;
if (!all_are_in_same_general_direction)
{
overlap_area = std::max(overlap_area, handlePotentialOverlap(from_it, to_it, to_link, to_other_it, to_other_it));
}
// handle normal case where the segment from-to overlaps with another segment
// o<<<T<<<F
// | |
// | |
// o>>>o>>>o
// , ,
// ; to other next
// to other
if (!are_in_same_general_direction)
{
overlap_area = std::max(overlap_area, handlePotentialOverlap(from_it, to_it, to_link, to_other_next_it, to_other_it));
}
}
coord_t normal_area = vSize(from - to) * line_width;
Ratio ratio = Ratio(normal_area - overlap_area) / normal_area;
// clamp the ratio because overlap compensation might be faulty because
// WallOverlapComputation::getApproxOverlapArea only gives roughly accurate results
return std::min(1.0_r, std::max(0.0_r, ratio));
}
coord_t WallOverlapComputation::handlePotentialOverlap(const ListPolyIt from_it, const ListPolyIt to_it, const ProximityPointLink& to_link, const ListPolyIt from_other_it, const ListPolyIt to_other_it)
{
if (from_it == to_other_it && from_it == from_other_it)
{ // don't compute overlap with a line and itself
return 0;
}
const ProximityPointLink* from_link = overlap_linker.getLink(from_it, from_other_it);
if (!from_link)
{
return 0;
}
if (!getIsPassed(to_link, *from_link))
{ // check whether the segment is already passed
setIsPassed(to_link, *from_link);
return 0;
}
return getApproxOverlapArea(from_it.p(), to_it.p(), to_link.dist, to_other_it.p(), from_other_it.p(), from_link->dist);
}
coord_t WallOverlapComputation::getApproxOverlapArea(const Point from, const Point to, const coord_t to_dist, const Point other_from, const Point other_to, const coord_t from_dist)
{
const coord_t overlap_width_2 = line_width * 2 - from_dist - to_dist; //Twice the width of the overlap area, perpendicular to the lines.
// check whether the line segment overlaps with the point if one of the line segments is just a point
if (from == to)
{
if (LinearAlg2D::pointIsProjectedBeyondLine(from, other_from, other_to) != 0)
{
return 0;
}
const coord_t overlap_length_2 = vSize(other_to - other_from); //Twice the length of the overlap area, alongside the lines.
return overlap_length_2 * overlap_width_2 / 4; //Area = width * height.
}
if (other_from == other_to)
{
if (LinearAlg2D::pointIsProjectedBeyondLine(other_from, from, to) != 0)
{
return 0;
}
const coord_t overlap_length_2 = vSize(from - to); //Twice the length of the overlap area, alongside the lines.
return overlap_length_2 * overlap_width_2 / 4; //Area = width * height.
}
short from_rel = LinearAlg2D::pointIsProjectedBeyondLine(from, other_from, other_to);
short to_rel = LinearAlg2D::pointIsProjectedBeyondLine(to, other_from, other_to);
short other_from_rel = LinearAlg2D::pointIsProjectedBeyondLine(other_from, from, to);
short other_to_rel = LinearAlg2D::pointIsProjectedBeyondLine(other_to, from, to);
if (from_rel != 0 && to_rel == from_rel && other_from_rel != 0 && other_to_rel == other_from_rel)
{
// both segments project fully beyond or before each other
// for example: or:
// O<------O . O------>O
// : : \_
// ' O------->O O------>O
return 0;
}
if (from_rel != 0 && from_rel == other_from_rel && to_rel == 0 && other_to_rel == 0)
{
// only ends of line segments overlap
//
// to_proj
// ^^^^^
// O<--+----O
// : :
// O-----+-->O
// ,,,,,
// other_to_proj
const Point other_vec = other_from - other_to;
const coord_t to_proj = dot(to - other_to, other_vec) / vSize(other_vec);
const Point vec = from - to;
const coord_t other_to_proj = dot(other_to - to, vec) / vSize(vec);
const coord_t overlap_length_2 = to_proj + other_to_proj; //Twice the length of the overlap area, alongside the lines.
return overlap_length_2 * overlap_width_2 / 4; //Area = width * height.
}
if (to_rel != 0 && to_rel == other_to_rel && from_rel == 0 && other_from_rel == 0)
{
// only beginnings of line segments overlap
//
// from_proj
// ^^^^^
// O<---+---O
// : :
// O---+---->O
// ,,,,,
// other_from_proj
const Point other_vec = other_to - other_from;
const coord_t from_proj = dot(from - other_from, other_vec) / vSize(other_vec);
const Point vec = to - from;
const coord_t other_from_proj = dot(other_from - from, vec) / vSize(vec);
const coord_t overlap_length_2 = from_proj + other_from_proj; //Twice the length of the overlap area, alongside the lines.
return overlap_length_2 * overlap_width_2 / 4; //Area = width * height.
}
//More complex case.
const Point from_middle = other_to + from; // don't divide by two just yet
const Point to_middle = other_from + to; // don't divide by two just yet
const coord_t overlap_length_2 = vSize(from_middle - to_middle); //(An approximation of) twice the length of the overlap area, alongside the lines.
return overlap_length_2 * overlap_width_2 / 4; //Area = width * height.
}
bool WallOverlapComputation::getIsPassed(const ProximityPointLink& link_a, const ProximityPointLink& link_b)
{
return passed_links.find(SymmetricPair<ProximityPointLink>(link_a, link_b)) != passed_links.end();
}
void WallOverlapComputation::setIsPassed(const ProximityPointLink& link_a, const ProximityPointLink& link_b)
{
passed_links.emplace(link_a, link_b);
}
}//namespace cura
| 39.475336 | 201 | 0.607861 | CCH852573130 |
2c11fe91348d6a10133757e74e6d5e77d9ecf30b | 5,903 | cpp | C++ | src/layer/convolution1d.cpp | jonetomtom/ncnn | 6c2cee818668bc19ce3fbcd68e3964283050554b | [
"BSD-3-Clause"
] | 14 | 2021-07-30T11:03:47.000Z | 2021-08-24T08:08:23.000Z | src/layer/convolution1d.cpp | Timen/ncnn | 0d32389efd486358d58e18605c95c275f129e6fa | [
"BSD-3-Clause"
] | 72 | 2020-09-13T18:19:44.000Z | 2022-03-30T21:17:23.000Z | src/layer/convolution1d.cpp | Timen/ncnn | 0d32389efd486358d58e18605c95c275f129e6fa | [
"BSD-3-Clause"
] | 5 | 2021-09-12T03:26:28.000Z | 2021-10-09T07:39:15.000Z | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "convolution1d.h"
#include "layer_type.h"
namespace ncnn {
Convolution1D::Convolution1D()
{
one_blob_only = true;
support_inplace = false;
}
int Convolution1D::load_param(const ParamDict& pd)
{
num_output = pd.get(0, 0);
kernel_w = pd.get(1, 0);
dilation_w = pd.get(2, 1);
stride_w = pd.get(3, 1);
pad_left = pd.get(4, 0);
pad_right = pd.get(15, pad_left);
pad_value = pd.get(18, 0.f);
bias_term = pd.get(5, 0);
weight_data_size = pd.get(6, 0);
activation_type = pd.get(9, 0);
activation_params = pd.get(10, Mat());
return 0;
}
int Convolution1D::load_model(const ModelBin& mb)
{
weight_data = mb.load(weight_data_size, 0);
if (weight_data.empty())
return -100;
if (bias_term)
{
bias_data = mb.load(num_output, 1);
if (bias_data.empty())
return -100;
}
return 0;
}
int Convolution1D::create_pipeline(const Option& opt)
{
return 0;
}
int Convolution1D::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
{
int w = bottom_blob.w;
int h = bottom_blob.h;
size_t elemsize = bottom_blob.elemsize;
// NCNN_LOGE("Convolution1D input %d x %d pad = %d ksize=%d stride=%d", w, h, pad_w, kernel_w, stride_w);
const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
Mat bottom_blob_bordered;
make_padding(bottom_blob, bottom_blob_bordered, opt);
if (bottom_blob_bordered.empty())
return -100;
w = bottom_blob_bordered.w;
h = bottom_blob_bordered.h;
int outw = (w - kernel_extent_w) / stride_w + 1;
// float32
top_blob.create(outw, num_output, elemsize, opt.blob_allocator);
if (top_blob.empty())
return -100;
// num_output
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < num_output; p++)
{
float* outptr = top_blob.row(p);
for (int j = 0; j < outw; j++)
{
float sum = 0.f;
if (bias_term)
sum = bias_data[p];
const float* kptr = (const float*)weight_data + kernel_w * h * p;
for (int q = 0; q < h; q++)
{
const float* sptr = bottom_blob_bordered.row(q) + j * stride_w;
for (int k = 0; k < kernel_w; k++)
{
float val = *sptr;
float wt = kptr[k];
sum += val * wt;
sptr += dilation_w;
}
kptr += kernel_w;
}
if (activation_type == 1)
{
sum = std::max(sum, 0.f);
}
else if (activation_type == 2)
{
float slope = activation_params[0];
sum = sum > 0.f ? sum : sum * slope;
}
else if (activation_type == 3)
{
float min = activation_params[0];
float max = activation_params[1];
if (sum < min)
sum = min;
if (sum > max)
sum = max;
}
else if (activation_type == 4)
{
sum = static_cast<float>(1.f / (1.f + exp(-sum)));
}
else if (activation_type == 5)
{
const float MISH_THRESHOLD = 20;
float x = sum, y;
if (x > MISH_THRESHOLD)
y = x;
else if (x < -MISH_THRESHOLD)
y = expf(x);
else
y = logf(expf(x) + 1);
sum = static_cast<float>(x * tanh(y));
}
outptr[j] = sum;
}
}
return 0;
}
void Convolution1D::make_padding(const Mat& bottom_blob, Mat& bottom_blob_bordered, const Option& opt) const
{
int w = bottom_blob.w;
const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
bottom_blob_bordered = bottom_blob;
if (pad_left > 0 || pad_right > 0)
{
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, 0, pad_left, pad_right, BORDER_CONSTANT, pad_value, opt_b);
}
else if (pad_left == -233 && pad_right == -233)
{
// tensorflow padding=SAME or onnx padding=SAME_UPPER
int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w;
if (wpad > 0)
{
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, 0, wpad / 2, wpad - wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
}
}
else if (pad_left == -234 && pad_right == -234)
{
// onnx padding=SAME_LOWER
int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w;
if (wpad > 0)
{
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, 0, wpad - wpad / 2, wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
}
}
}
} // namespace ncnn
| 29.368159 | 132 | 0.553786 | jonetomtom |
2c12a8ac7a3f1da1e55f6a1229ed3f71ad14d6da | 5,939 | cpp | C++ | src/array/service/io_locker/io_locker.cpp | poseidonos/poseidonos | 1d4a72c823739ef3eaf86e65c57d166ef8f18919 | [
"BSD-3-Clause"
] | 38 | 2021-04-06T03:20:55.000Z | 2022-03-02T09:33:28.000Z | src/array/service/io_locker/io_locker.cpp | poseidonos/poseidonos | 1d4a72c823739ef3eaf86e65c57d166ef8f18919 | [
"BSD-3-Clause"
] | 19 | 2021-04-08T02:27:44.000Z | 2022-03-23T00:59:04.000Z | src/array/service/io_locker/io_locker.cpp | poseidonos/poseidonos | 1d4a72c823739ef3eaf86e65c57d166ef8f18919 | [
"BSD-3-Clause"
] | 28 | 2021-04-08T04:39:18.000Z | 2022-03-24T05:56:00.000Z | /*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Samsung Electronics Corporation nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "io_locker.h"
#include "src/include/array_mgmt_policy.h"
#include "src/include/pos_event_id.h"
#include "src/logger/logger.h"
namespace pos
{
bool
IOLocker::Register(vector<ArrayDevice*> devList)
{
group.AddDevice(devList);
size_t prevSize = lockers.size();
for (IArrayDevice* d : devList)
{
if (_Find(d) == nullptr)
{
IArrayDevice* m = group.GetMirror(d);
if (m != nullptr)
{
StripeLocker* locker = new StripeLocker();
lockers.emplace(d, locker);
lockers.emplace(m, locker);
}
}
}
size_t newSize = lockers.size();
POS_TRACE_INFO(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Register, {} devs added, size: {} -> {}",
devList.size(), prevSize, newSize);
return true;
}
void
IOLocker::Unregister(vector<ArrayDevice*> devList)
{
size_t prevSize = lockers.size();
for (IArrayDevice* d : devList)
{
StripeLocker* locker = _Find(d);
if (locker != nullptr)
{
lockers.erase(d);
IArrayDevice* m = group.GetMirror(d);
if (m != nullptr)
{
lockers.erase(m);
}
delete locker;
locker = nullptr;
}
}
group.RemoveDevice(devList);
size_t newSize = lockers.size();
POS_TRACE_INFO(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Unregister, {} devs removed, size: {} -> {}",
devList.size(), prevSize, newSize);
}
bool
IOLocker::TryBusyLock(IArrayDevice* dev, StripeId from, StripeId to)
{
StripeLocker* locker = _Find(dev);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::TryBusyLock, no locker exists");
return true;
}
return locker->TryBusyLock(from, to);
}
bool
IOLocker::TryLock(set<IArrayDevice*>& devs, StripeId val)
{
set<StripeLocker*> lockersByGroup;
for (IArrayDevice* d : devs)
{
StripeLocker* locker = _Find(d);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::TryLock, no locker exists");
return true;
}
lockersByGroup.insert(locker);
}
int lockedCnt = 0;
for (auto it = lockersByGroup.begin(); it != lockersByGroup.end(); ++it)
{
bool ret = (*it)->TryLock(val);
if (ret == true)
{
lockedCnt++;
}
else
{
while (lockedCnt > 0)
{
--it;
(*it)->Unlock(val);
lockedCnt--;
}
return false;
}
}
return true;
}
void
IOLocker::Unlock(IArrayDevice* dev, StripeId val)
{
StripeLocker* locker = _Find(dev);
if (locker != nullptr)
{
locker->Unlock(val);
}
else
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Unlock, no locker exists");
}
}
void
IOLocker::Unlock(set<IArrayDevice*>& devs, StripeId val)
{
set<StripeLocker*> lockersByGroup;
for (IArrayDevice* d : devs)
{
StripeLocker* locker = _Find(d);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Unlock, no locker exists");
}
lockersByGroup.insert(locker);
}
for (StripeLocker* locker : lockersByGroup)
{
locker->Unlock(val);
}
}
bool
IOLocker::ResetBusyLock(IArrayDevice* dev)
{
StripeLocker* locker = _Find(dev);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::ResetBusyLock, no locker exists");
return true;
}
return locker->ResetBusyLock();
}
StripeLocker*
IOLocker::_Find(IArrayDevice* dev)
{
auto it = lockers.find(dev);
if (it == lockers.end())
{
return nullptr;
}
return it->second;
}
} // namespace pos
| 29.112745 | 107 | 0.619465 | poseidonos |
2c16201d9f01279d05306ce5974b31a3ee0fc175 | 1,841 | cpp | C++ | ImportantExample/360/src/main/common/scorewidget.cpp | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | 3 | 2018-12-24T19:35:52.000Z | 2022-02-04T14:45:59.000Z | ImportantExample/360/src/main/common/scorewidget.cpp | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | null | null | null | ImportantExample/360/src/main/common/scorewidget.cpp | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | 1 | 2019-05-09T02:42:40.000Z | 2019-05-09T02:42:40.000Z | #include "scorewidget.h"
#include <QPainter>
#include "../../common/numbersanimwidget.h"
#include "../../common/common.h"
ScoreWidget::ScoreWidget(QWidget *parent)
: QWidget(parent)
{
this->setAttribute(Qt::WA_TranslucentBackground);
m_backgroundPix.load(":/main/examine_score");
this->setFixedSize(m_backgroundPix.size());
m_fenPix.load(":/main/fen");
m_numWidget = new NumbersAnimWidget(this);
m_numWidget->setInitInfo(100, 3, ":/numbers/main/");
m_numWidget->move((width()-m_numWidget->width())/2 - 30, (height() - m_numWidget->height())/2 + 5);
m_numWidget->hide();
}
void ScoreWidget::setScoreStatus(int status)
{
m_status = status;
switch (status)
{
case SCORE_QUESTION:
m_numWidget->hide();
m_forePix.load(":/main/question");
break;
case SCORE_EXCLAMATION:
m_numWidget->hide();
m_forePix.load(":/main/exclamation");
break;
case SCORE_NUMBERS:
m_numWidget->show();
break;
default:
break;
}
update();
}
void ScoreWidget::setNums(int num)
{
this->setScoreStatus(SCORE_NUMBERS);
m_numWidget->setNums(num);
}
void ScoreWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.drawPixmap(rect(), m_backgroundPix);
if(m_status == SCORE_QUESTION || m_status == SCORE_EXCLAMATION)
{
painter.drawPixmap((width() - m_forePix.width())/2, (height() - m_forePix.height())/2, \
m_forePix.width(), m_forePix.height(), m_forePix);
}
else if(m_status == SCORE_NUMBERS)
{
painter.drawPixmap(m_numWidget->x() + m_numWidget->width(), \
m_numWidget->y() + m_numWidget->height() - m_fenPix.height() - 20, \
m_fenPix.width(), m_fenPix.height(), m_fenPix);
}
}
| 28.323077 | 103 | 0.617056 | xiaohaijin |
2c17838f1d68291992228e8ab36c0665aec6ae8b | 690 | cpp | C++ | uva/11286.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | uva/11286.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | uva/11286.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
using namespace std;
int main(){
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int t, n[6];
char ch[20];
string s;
while(scanf("%d", &t) != EOF && t){
map<string, int> mp;
while(t--){
for(int i = 0; i < 5; scanf("%d", &n[i]), i++);
sort(n, n + 5);
sprintf(ch, "%d%d%d%d%d", n[0], n[1], n[2], n[3], n[4]);
s = ch;
mp[s]++;
}
int mn = 0, m = 0;
for(map<string, int> :: iterator it = mp.begin(); it != mp.end(); it++){
if((*it).second > m){
m = (*it).second;
mn = 0;
}
if((*it).second == m) mn += m;
}
printf("%d\n", mn);
}
return 0;
}
| 23 | 76 | 0.434783 | cosmicray001 |