hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
305493fcc4ec6e3a8c26685129e17d124781fdbc | 8,263 | cpp | C++ | memo.cpp | Nitta-K-git/PCL_samples | eb242dbb642971a289511f0c040c3f4108245230 | [
"MIT"
] | null | null | null | memo.cpp | Nitta-K-git/PCL_samples | eb242dbb642971a289511f0c040c3f4108245230 | [
"MIT"
] | null | null | null | memo.cpp | Nitta-K-git/PCL_samples | eb242dbb642971a289511f0c040c3f4108245230 | [
"MIT"
] | null | null | null | int
pcl::io::savePLYFile (const std::string &file_name, const pcl::PolygonMesh &mesh, unsigned precision)
{
if (mesh.cloud.data.empty ())
{
PCL_ERROR ("[pcl::io::savePLYFile] Input point cloud has no data!\n");
return (-1);
}
// Open file
std::ofstream fs;
fs.precision (precision);
fs.open (file_name.c_str ());
if (!fs)
{
PCL_ERROR ("[pcl::io::savePLYFile] Error during opening (%s)!\n", file_name.c_str ());
return (-1);
}
// number of points
size_t nr_points = mesh.cloud.width * mesh.cloud.height;
size_t point_size = mesh.cloud.data.size () / nr_points;
// number of faces
size_t nr_faces = mesh.polygons.size ();
// Write header
fs << "ply";
fs << "\nformat ascii 1.0";
fs << "\ncomment PCL generated";
// Vertices
fs << "\nelement vertex "<< mesh.cloud.width * mesh.cloud.height;
fs << "\nproperty float x"
"\nproperty float y"
"\nproperty float z";
// Check if we have color on vertices
int rgba_index = getFieldIndex (mesh.cloud, "rgba"),
rgb_index = getFieldIndex (mesh.cloud, "rgb");
if (rgba_index != -1)
{
fs << "\nproperty uchar red"
"\nproperty uchar green"
"\nproperty uchar blue"
"\nproperty uchar alpha";
}
else if (rgb_index != -1)
{
fs << "\nproperty uchar red"
"\nproperty uchar green"
"\nproperty uchar blue";
}
// Check if we have normal on vertices
int normal_x_index = getFieldIndex(mesh.cloud, "normal_x");
int normal_y_index = getFieldIndex(mesh.cloud, "normal_y");
int normal_z_index = getFieldIndex(mesh.cloud, "normal_z");
if (normal_x_index != -1 && normal_y_index != -1 && normal_z_index != -1)
{
fs << "\nproperty float nx"
"\nproperty float ny"
"\nproperty float nz";
}
// Check if we have curvature on vertices
int curvature_index = getFieldIndex(mesh.cloud, "curvature");
if ( curvature_index != -1)
{
fs << "\nproperty float curvature";
}
// Faces
fs << "\nelement face "<< nr_faces;
fs << "\nproperty list uchar int vertex_indices";
fs << "\nend_header\n";
// Write down vertices
for (size_t i = 0; i < nr_points; ++i)
{
int xyz = 0;
for (size_t d = 0; d < mesh.cloud.fields.size (); ++d)
{
int count = mesh.cloud.fields[d].count;
if (count == 0)
count = 1; // we simply cannot tolerate 0 counts (coming from older converter code)
int c = 0;
// adding vertex
if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
mesh.cloud.fields[d].name == "x" ||
mesh.cloud.fields[d].name == "y" ||
mesh.cloud.fields[d].name == "z"))
{
float value;
memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof (float)], sizeof (float));
fs << value;
// if (++xyz == 3)
// break;
++xyz;
}
else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) &&
(mesh.cloud.fields[d].name == "rgb"))
{
pcl::RGB color;
memcpy (&color, &mesh.cloud.data[i * point_size + mesh.cloud.fields[rgb_index].offset + c * sizeof (float)], sizeof (RGB));
fs << int (color.r) << " " << int (color.g) << " " << int (color.b);
}
else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::UINT32) &&
(mesh.cloud.fields[d].name == "rgba"))
{
pcl::RGB color;
memcpy (&color, &mesh.cloud.data[i * point_size + mesh.cloud.fields[rgba_index].offset + c * sizeof (uint32_t)], sizeof (RGB));
fs << int (color.r) << " " << int (color.g) << " " << int (color.b) << " " << int (color.a);
}
else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
mesh.cloud.fields[d].name == "normal_x" ||
mesh.cloud.fields[d].name == "normal_y" ||
mesh.cloud.fields[d].name == "normal_z"))
{
float value;
memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof(float)], sizeof(float));
fs << value;
}
else if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && (
mesh.cloud.fields[d].name == "curvature"))
{
float value;
memcpy(&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset + c * sizeof(float)], sizeof(float));
fs << value;
}
fs << " ";
}
if (xyz != 3)
{
PCL_ERROR ("[pcl::io::savePLYFile] Input point cloud has no XYZ data!\n");
return (-2);
}
fs << '\n';
}
// Write down faces
for (size_t i = 0; i < nr_faces; i++)
{
fs << mesh.polygons[i].vertices.size () << " ";
size_t j = 0;
for (j = 0; j < mesh.polygons[i].vertices.size () - 1; ++j)
fs << mesh.polygons[i].vertices[j] << " ";
fs << mesh.polygons[i].vertices[j] << '\n';
}
// Close file
fs.close ();
return (0);
}
int
pcl::PLYReader::read (const std::string &file_name, pcl::PolygonMesh &mesh,
Eigen::Vector4f &origin, Eigen::Quaternionf &orientation,
int &ply_version, const int offset)
{
// kept only for backward compatibility
int data_type;
unsigned int data_idx;
polygons_ = &(mesh.polygons);
if (this->readHeader (file_name, mesh.cloud, origin, orientation, ply_version, data_type, data_idx, offset))
{
PCL_ERROR ("[pcl::PLYReader::read] problem parsing header!\n");
return (-1);
}
// a range_grid element was found ?
size_t r_size;
if ((r_size = (*range_grid_).size ()) > 0 && r_size != vertex_count_)
{
//cloud.header = cloud_->header;
std::vector<pcl::uint8_t> data ((*range_grid_).size () * mesh.cloud.point_step);
const static float f_nan = std::numeric_limits <float>::quiet_NaN ();
const static double d_nan = std::numeric_limits <double>::quiet_NaN ();
for (size_t r = 0; r < r_size; ++r)
{
if ((*range_grid_)[r].size () == 0)
{
for (size_t f = 0; f < cloud_->fields.size (); ++f)
if (cloud_->fields[f].datatype == ::pcl::PCLPointField::FLOAT32)
memcpy (&data[r * cloud_->point_step + cloud_->fields[f].offset],
reinterpret_cast<const char*> (&f_nan), sizeof (float));
else if (cloud_->fields[f].datatype == ::pcl::PCLPointField::FLOAT64)
memcpy (&data[r * cloud_->point_step + cloud_->fields[f].offset],
reinterpret_cast<const char*> (&d_nan), sizeof (double));
else
memset (&data[r * cloud_->point_step + cloud_->fields[f].offset], 0,
pcl::getFieldSize (cloud_->fields[f].datatype) * cloud_->fields[f].count);
}
else
memcpy (&data[r* cloud_->point_step], &cloud_->data[(*range_grid_)[r][0] * cloud_->point_step], cloud_->point_step);
}
cloud_->data.swap (data);
}
orientation_ = Eigen::Quaternionf (orientation);
origin_ = origin;
for (size_t i = 0; i < cloud_->fields.size (); ++i)
{
if (cloud_->fields[i].name == "nx")
cloud_->fields[i].name = "normal_x";
if (cloud_->fields[i].name == "ny")
cloud_->fields[i].name = "normal_y";
if (cloud_->fields[i].name == "nz")
cloud_->fields[i].name = "normal_z";
}
return (0);
}
int
pcl::PLYReader::readHeader (const std::string &file_name, pcl::PCLPointCloud2 &cloud,
Eigen::Vector4f &origin, Eigen::Quaternionf &orientation,
int &, int &, unsigned int &, const int)
{
// Silence compiler warnings
cloud_ = &cloud;
range_grid_ = new std::vector<std::vector<int> >;
cloud_->width = cloud_->height = 0;
origin = Eigen::Vector4f::Zero ();
orientation = Eigen::Quaternionf::Identity ();
if (!parse (file_name))
{
PCL_ERROR ("[pcl::PLYReader::read] problem parsing header!\n");
return (-1);
}
cloud_->row_step = cloud_->point_step * cloud_->width;
return 0;
}
| 35.926087 | 136 | 0.558635 | [
"mesh",
"vector"
] |
306227ef91cff440f5f793c425fdce1ba54cdf53 | 728 | cpp | C++ | training/money1.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | training/money1.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | training/money1.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | /*
ID: drayale1
LANG: C++
TASK: money
*/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
const int N = 10010;
int v, n;
ll f[N];
bool visited[N];
vector<int> coins;
int main() {
freopen("money.in", "r", stdin);
freopen("money.out", "w", stdout);
cin >> v >> n;
coins.push_back(0);
for (int i = 0; i < v; i++) {
int c; cin >> c;
coins.push_back(c);
}
memset(f, 0, sizeof f);
f[0] = 1;
for (int i = 1; i <= v; i++)
for (int j = coins[i]; j <= n; j++) {
f[j] += f[j - coins[i]];
}
//for (int i = 0; i <= n; i++) cout << f[i] << endl;
cout << f[n] << endl;
} | 16.930233 | 56 | 0.486264 | [
"vector"
] |
30635d021e4e4a8fe6c89042ca980ed6277815d3 | 1,318 | cpp | C++ | aslam_cv/aslam_cv_backend/test/testReprojectionError.cpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 2,690 | 2015-01-07T03:50:23.000Z | 2022-03-31T20:27:01.000Z | aslam_cv/aslam_cv_backend/test/testReprojectionError.cpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 481 | 2015-01-27T10:21:00.000Z | 2022-03-31T14:02:41.000Z | aslam_cv/aslam_cv_backend/test/testReprojectionError.cpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 1,091 | 2015-01-26T21:21:13.000Z | 2022-03-30T01:55:33.000Z | // Bring in gtest
#include <gtest/gtest.h>
#include <sm/eigen/gtest.hpp>
#include <aslam/backend/test/ErrorTermTestHarness.hpp>
#include <aslam/cameras.hpp>
#include <aslam/CameraGeometryDesignVariableContainer.hpp>
#include <aslam/backend/HomogeneousPoint.hpp>
TEST( CvBackendTestSuite, testReprojectionError ) {
using namespace aslam;
using namespace aslam::backend;
using namespace aslam::cameras;
typedef DistortedOmniRsCameraGeometry camera_geometry_t;
boost::shared_ptr<camera_geometry_t> geometry(new camera_geometry_t( camera_geometry_t::getTestGeometry() ) );
boost::shared_ptr< CameraGeometryDesignVariableContainer > geometryDvc( new CameraGeometryDesignVariableContainer( geometry, true, true, true ));
Eigen::Matrix2d invR;
invR.setIdentity();
Eigen::Vector4d p = sm::kinematics::toHomogeneous(geometry->createRandomVisiblePoint());
boost::shared_ptr<aslam::backend::HomogeneousPoint> pt( new aslam::backend::HomogeneousPoint(p) );
pt->setActive(true);
pt->setBlockIndex(0);
HomogeneousExpression hep(pt);
Eigen::VectorXd y;
geometry->homogeneousToKeypoint(p,y);
boost::shared_ptr< aslam::ReprojectionError > re = geometryDvc->createReprojectionError( y, invR, hep);
ErrorTermTestHarness<2> harness( (aslam::backend::ErrorTerm*)re.get());
harness.testAll();
}
| 35.621622 | 147 | 0.776176 | [
"geometry"
] |
3065fc6f80c1e850c44845872be16793d0c44e96 | 816 | cpp | C++ | src/floorboard.cpp | paked/basin | d1d09a3f9aff5ef90f2a18e95789328857e4ffbc | [
"MIT"
] | null | null | null | src/floorboard.cpp | paked/basin | d1d09a3f9aff5ef90f2a18e95789328857e4ffbc | [
"MIT"
] | null | null | null | src/floorboard.cpp | paked/basin | d1d09a3f9aff5ef90f2a18e95789328857e4ffbc | [
"MIT"
] | null | null | null | #include <floorboard.hpp>
#include <e/core.hpp>
Floorboard::Floorboard(int x, int y, bool fake) : fake(fake) {
localDepth = DEPTH_BG + DEPTH_BELOW * 10;
sprite = new Sprite("floorboard.png", x, y);
light = new Sprite("light_small.png");
light->x = x;
light->y = y;
reg(sprite);
}
void Floorboard::tick(float dt) {
Entity::tick(dt);
if (!glowing) {
return;
}
if (glowingStartTime + glowDuration < SDL_GetTicks()) {
light->alpha = 255;
glowing = false;
return;
}
float p = 1 - (SDL_GetTicks() - glowingStartTime)/(float)glowDuration;
light->alpha = 255 * (p*p);
}
void Floorboard::trigger() {
glowing = true;
glowingStartTime = SDL_GetTicks();
}
void Floorboard::glow() {
if (!glowing) {
return;
}
light->render(Core::renderer, scene->camera);
}
| 16.32 | 72 | 0.625 | [
"render"
] |
30679714d048fd2962ffc9c960a35d5eabb893dd | 2,782 | hpp | C++ | armadillo_matrix/include/armadillo_bits/fn_sum.hpp | Lauradejong92/wire-grad | 0bfd3fb42df363f43eb89f35c2f0769fb805f6cd | [
"BSD-2-Clause"
] | 1 | 2022-02-02T15:47:24.000Z | 2022-02-02T15:47:24.000Z | armadillo_matrix/include/armadillo_bits/fn_sum.hpp | Lauradejong92/wire-grad | 0bfd3fb42df363f43eb89f35c2f0769fb805f6cd | [
"BSD-2-Clause"
] | null | null | null | armadillo_matrix/include/armadillo_bits/fn_sum.hpp | Lauradejong92/wire-grad | 0bfd3fb42df363f43eb89f35c2f0769fb805f6cd | [
"BSD-2-Clause"
] | 2 | 2019-02-28T17:36:19.000Z | 2021-01-24T14:04:18.000Z | // Copyright (C) 2008-2010 NICTA (www.nicta.com.au)
// Copyright (C) 2008-2010 Conrad Sanderson
//
// This file is part of the Armadillo C++ library.
// It is provided without any warranty of fitness
// for any purpose. You can redistribute this file
// and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published
// by the Free Software Foundation, either version 3
// of the License or (at your option) any later version.
// (see http://www.opensource.org/licenses for more info)
//! \addtogroup fn_sum
//! @{
//! \brief
//! Delayed sum of elements of a matrix along a specified dimension (either rows or columns).
//! The result is stored in a dense matrix that has either one column or one row.
//! For dim = 0, find the sum of each column.
//! For dim = 1, find the sum of each row.
//! The default is dim = 0.
//! NOTE: this function works differently than in Matlab/Octave.
template<typename T1>
arma_inline
const Op<T1, op_sum>
sum(const Base<typename T1::elem_type,T1>& X, const uword dim = 0)
{
arma_extra_debug_sigprint();
return Op<T1, op_sum>(X.get_ref(), dim, 0);
}
//! \brief
//! Immediate 'sum all values' operation for a row vector
template<typename eT>
inline
arma_warn_unused
eT
sum(const Row<eT>& X)
{
arma_extra_debug_sigprint();
return accu(X);
}
//! \brief
//! Immediate 'sum all values' operation for a column vector
template<typename eT>
inline
arma_warn_unused
eT
sum(const Col<eT>& X)
{
arma_extra_debug_sigprint();
return accu(X);
}
//! \brief
//! Immediate 'sum all values' operation,
//! invoked, for example, by: sum(sum(A))
template<typename T1>
inline
arma_warn_unused
typename T1::elem_type
sum(const Op<T1, op_sum>& in)
{
arma_extra_debug_sigprint();
arma_extra_debug_print("sum(): two consecutive sum() calls detected");
return accu(in.m);
}
template<typename T1>
arma_inline
const Op<Op<T1, op_sum>, op_sum>
sum(const Op<T1, op_sum>& in, const uword dim)
{
arma_extra_debug_sigprint();
return Op<Op<T1, op_sum>, op_sum>(in, dim, 0);
}
//! sum all values of a subview_row
template<typename eT>
inline
arma_warn_unused
eT
sum(const subview_row<eT>& X)
{
arma_extra_debug_sigprint();
return accu(X);
}
//! sum all values of a subview_col
template<typename eT>
inline
arma_warn_unused
eT
sum(const subview_col<eT>& X)
{
arma_extra_debug_sigprint();
return accu(X);
}
//! sum all values of a diagview
template<typename eT>
inline
arma_warn_unused
eT
sum(const diagview<eT>& X)
{
arma_extra_debug_sigprint();
return accu(X);
}
template<typename eT, typename T1>
inline
arma_warn_unused
eT
sum(const subview_elem1<eT,T1>& A)
{
arma_extra_debug_sigprint();
return accu(A);
}
//! @}
| 18.183007 | 93 | 0.698778 | [
"vector"
] |
3069bc58542231d2900431cc59054726c070df47 | 6,194 | cpp | C++ | src/engine/render/rendertimers.cpp | Duskhorn/libprimis | 3b1189d0f8c8ea31c4752ed1ce34e9289a26b6fc | [
"Zlib"
] | null | null | null | src/engine/render/rendertimers.cpp | Duskhorn/libprimis | 3b1189d0f8c8ea31c4752ed1ce34e9289a26b6fc | [
"Zlib"
] | null | null | null | src/engine/render/rendertimers.cpp | Duskhorn/libprimis | 3b1189d0f8c8ea31c4752ed1ce34e9289a26b6fc | [
"Zlib"
] | null | null | null | /* rendertimers.cpp: renderer functionality used for displaying rendering stats
* while the program is running
*
* timers can be created with designated start/stop points in the code; sub-ms
* times needed for accurate diagnosis possible (each frame is ~16.6ms @ 60Hz)
*
* used in rendergl.cpp
*/
#include "../libprimis-headers/cube.h"
#include "../../shared/geomexts.h"
#include "../../shared/glexts.h"
#include "rendergl.h"
#include "rendertext.h"
#include "renderva.h"
#include "interface/control.h"
void cleanuptimers(); //needed for timer script gvar
VARFN(timer, usetimers, 0, 0, 1, cleanuptimers()); //toggles logging timer information & rendering it
VAR(frametimer, 0, 0, 1); //toggles timing how long each frame takes (and rendering it to timer ui)
struct timer
{
enum
{
Timer_MaxQuery = 4 //max number of gl queries
};
const char *name; //name the timer reports as
bool gpu; //whether the timer is for gpu time (true) or cpu time
GLuint query[Timer_MaxQuery]; //gpu query information
int waiting; //internal bitmask for queries
uint starttime; //time the timer was started (in terms of ms since game started)
float result, //raw value of the timer, -1 if no info available
print; //the time the timer displays: ms per frame for whatever object
};
//locally relevant functionality
namespace
{
static vector<timer> timers;
static vector<int> timerorder;
static int timercycle = 0;
timer *findtimer(const char *name, bool gpu) //also creates a new timer if none found
{
for(int i = 0; i < timers.length(); i++)
{
if(!std::strcmp(timers[i].name, name) && timers[i].gpu == gpu)
{
timerorder.removeobj(i);
timerorder.add(i);
return &timers[i];
}
}
timerorder.add(timers.length());
timer &t = timers.add();
t.name = name;
t.gpu = gpu;
std::memset(t.query, 0, sizeof(t.query));
if(gpu)
{
glGenQueries(timer::Timer_MaxQuery, t.query);
}
t.waiting = 0;
t.starttime = 0;
t.result = -1;
t.print = -1;
return &t;
}
}
//externally relevant functionality
//used to start a timer in some part of the code, cannot be used outside of rendering part
/**
* @brief activates a timer that starts its query from a given point in the code
*
* Creates a new timer if necessary.
*
* @param name The name of the timer to use
* @param gpu Toggles timing GPU rendering time
*
* @return a pointer to the relevant timer
*/
timer *begintimer(const char *name, bool gpu)
{
if(!usetimers || inbetweenframes || (gpu && (!hasTQ || deferquery)))
{
return nullptr;
}
timer *t = findtimer(name, gpu);
if(t->gpu)
{
deferquery++;
glBeginQuery(GL_TIME_ELAPSED_EXT, t->query[timercycle]);
t->waiting |= 1<<timercycle;
}
else
{
t->starttime = getclockmillis();
}
return t;
}
//used to end a timer started by begintimer(), needs to be included sometime after begintimer
//the part between begintimer() and endtimer() is what gets timed
void endtimer(timer *t)
{
if(!t)
{
return;
}
if(t->gpu)
{
glEndQuery(GL_TIME_ELAPSED_EXT);
deferquery--;
}
else
{
t->result = std::max(static_cast<float>(getclockmillis() - t->starttime), 0.0f);
}
}
//foreach timer, query what time has passed since last update
void synctimers()
{
timercycle = (timercycle + 1) % timer::Timer_MaxQuery;
for(int i = 0; i < timers.length(); i++)
{
timer &t = timers[i];
if(t.waiting&(1<<timercycle))
{
GLint available = 0;
while(!available)
{
glGetQueryObjectiv(t.query[timercycle], GL_QUERY_RESULT_AVAILABLE, &available);
}
GLuint64EXT result = 0;
glGetQueryObjectui64v_(t.query[timercycle], GL_QUERY_RESULT, &result);
t.result = std::max(static_cast<float>(result) * 1e-6f, 0.0f);
t.waiting &= ~(1<<timercycle);
}
else
{
t.result = -1;
}
}
}
/**
* @brief deletes the elements in the timers global vector
*
* Deletes the elements in the `timer` global variable. If any GPU queries are active,
* they are cancelled so as not to waste the GPU's time
*/
void cleanuptimers()
{
for(int i = 0; i < timers.length(); i++)
{
timer &t = timers[i];
if(t.gpu)
{
glDeleteQueries(timer::Timer_MaxQuery, t.query);
}
}
timers.shrink(0);
timerorder.shrink(0);
}
/*
* draws timers to the screen using hardcoded text
*
* if frametimer gvar is enabled, also shows the overall frame time
* otherwise, prints out all timer information available
*/
void printtimers(int conw, int conh, int framemillis)
{
if(!frametimer && !usetimers)
{
return;
}
static int lastprint = 0;
int offset = 0;
if(frametimer)
{
static int printmillis = 0;
if(totalmillis - lastprint >= 200)
{
printmillis = framemillis;
}
draw_textf("frame time %i ms", conw-20*FONTH, conh-FONTH*3/2-offset*9*FONTH/8, printmillis);
offset++;
}
if(usetimers)
{
for(int i = 0; i < timerorder.length(); i++)
{
timer &t = timers[timerorder[i]];
if(t.print < 0 ? t.result >= 0 : totalmillis - lastprint >= 200)
{
t.print = t.result;
}
if(t.print < 0 || (t.gpu && !(t.waiting&(1<<timercycle))))
{
continue;
}
draw_textf("%s%s %5.2f ms", conw-20*FONTH, conh-FONTH*3/2-offset*9*FONTH/8, t.name, t.gpu ? "" : " (cpu)", t.print);
offset++;
}
}
if(totalmillis - lastprint >= 200)
{
lastprint = totalmillis;
}
}
| 28.412844 | 128 | 0.567 | [
"object",
"vector"
] |
3077aa9cd9c5860f0329da589057a7138e2d0886 | 2,862 | cpp | C++ | neon/Helium/HeliumForWindows/Implementation/Plugins/WTG_Scanner_PLG/ScannerModule.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 173 | 2015-01-02T11:14:08.000Z | 2022-03-05T09:54:54.000Z | neon/Helium/HeliumForWindows/Implementation/Plugins/WTG_Scanner_PLG/ScannerModule.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 263 | 2015-01-05T04:35:22.000Z | 2021-09-07T06:00:02.000Z | neon/Helium/HeliumForWindows/Implementation/Plugins/WTG_Scanner_PLG/ScannerModule.cpp | watusi/rhodes | 07161cca58ff6a960bbd1b79b36447b819bfa0eb | [
"MIT"
] | 77 | 2015-01-12T20:57:18.000Z | 2022-02-17T15:15:14.000Z | #include "ScannerModule.h"
#include "Scanner.h"
CScannerModule::CScannerModule(PPBCORESTRUCT pPBCoreStructure)
{
}
BOOL CScannerModule::onInit(PPBSTRUCT pPBStructure)
{
wcscpy(m_szModName, L"Scanner");
RegisterForEvent(PB_BROWSER_BEFORE_NAV_EVENT);
RegisterForEvent(PB_BROWSER_DOC_COMPLETE_EVENT);
RegisterForEvent(RHO_APPFOCUS_EVENT);
return TRUE;
}
void CScannerModule::onDeInit(PPBSTRUCT pPBStructure)
{
UnRegisterForEvent(PB_BROWSER_BEFORE_NAV_EVENT);
UnRegisterForEvent(PB_BROWSER_DOC_COMPLETE_EVENT);
UnRegisterForEvent(RHO_APPFOCUS_EVENT);
}
BOOL CScannerModule::onAttachInstance(PPBSTRUCT pPBStructure, PPBINSTSTRUCT pInstStruct)
{
// Create Scanner object and Initialise it.
CScanner *pScanner = new CScanner(pInstStruct->instID, this);
pInstStruct->pWrappedObj = pScanner;
BOOL bReturnValue = pScanner->Initialise(pPBStructure->bLaunchingAppHasFocus);
return TRUE;
}
BOOL CScannerModule::onReleaseInstance(PPBSTRUCT pPBStructure, PPBINSTSTRUCT pInstStruct)
{
CScanner* pScanner = (CScanner*)(pInstStruct->pWrappedObj);
if (pScanner)
delete pScanner;
return TRUE;
}
BOOL CScannerModule::onBeforeNavigate(int iInstID)
{
CScanner *pScanner = NULL;
pScanner = (CScanner*) GetObjFromID(iInstID);
if (pScanner != NULL)
{
return pScanner->BeforeNavigate();
}
else
return FALSE;
}
BOOL CScannerModule::onDocumentComplete(int iInstID)
{
CScanner *pScanner = NULL;
pScanner = (CScanner*) GetObjFromID(iInstID);
if (pScanner != NULL)
{
return pScanner->DocumentComplete();
}
else
return FALSE;
}
BOOL CScannerModule::onRhoAppFocus(bool bActivate, int iInstID)
{
CScanner *pScanner = NULL;
pScanner = (CScanner*) GetObjFromID(iInstID);
if (pScanner != NULL)
{
return pScanner->ApplicationFocusChange(bActivate);
}
else
return FALSE;
};
BOOL CScannerModule::MetaProc(PBMetaStruct *pbMetaStructure, PPBSTRUCT pPBStructure, void *pParam)
{
CScanner* pScanner = (CScanner*) (pParam);
if (!pScanner)
return FALSE;
// Consider my parameter value retrieval hack
// if (wcslen(pbMetaStructure->lpValue) >= 3 && wcsncmp(pbMetaStructure->lpValue, L"GET", 3) == 0)
// {
// int iLen = pScanner->RetrieveEMMLTag(pbMetaStructure->lpParameter, NULL);
// if (iLen < 0)
// {
// DEBUGMSG(TRUE, (L"Failed to Retrieve value for property: %s", pbMetaStructure->lpParameter));
// }
// else
// {
// WCHAR* szValue = new WCHAR[iLen];
// pScanner->RetrieveEMMLTag(pbMetaStructure->lpParameter, szValue);
// DEBUGMSG(TRUE, (L"\nRetrieved value for %s, it was: %s\n", pbMetaStructure->lpParameter, szValue));
// return TRUE;
// }
// }
Log(PB_LOG_WARNING, L"The Scanner API has been deprecated in 4.0, please transition your applications to use the Barcode API for future releases", _T(__FUNCTION__), __LINE__);
return pScanner->ParseMETATag(pbMetaStructure->lpParameter, pbMetaStructure->lpValue);
}
| 27 | 176 | 0.75297 | [
"object"
] |
307f525173757da23cbc2d2acf1214e111788310 | 2,553 | cpp | C++ | benchmark/histogram_parallel_filling.cpp | henryiii/histogram | d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c | [
"BSL-1.0"
] | 44 | 2020-12-21T05:14:38.000Z | 2022-03-15T11:27:32.000Z | benchmark/histogram_parallel_filling.cpp | henryiii/histogram | d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c | [
"BSL-1.0"
] | 79 | 2018-08-01T11:50:45.000Z | 2020-11-17T13:40:06.000Z | benchmark/histogram_parallel_filling.cpp | henryiii/histogram | d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c | [
"BSL-1.0"
] | 21 | 2020-12-22T09:40:16.000Z | 2021-12-07T18:16:00.000Z | // Copyright 2015-2018 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <benchmark/benchmark.h>
#include <atomic>
#include <boost/histogram.hpp>
#include <boost/histogram/algorithm/sum.hpp>
#include <chrono>
#include <functional>
#include <numeric>
#include <thread>
#include <vector>
namespace bh = boost::histogram;
template <typename T>
class copyable_atomic : public std::atomic<T> {
public:
using std::atomic<T>::atomic;
// zero-initialize the atomic T
copyable_atomic() noexcept : std::atomic<T>(T()) {}
// this is potentially not thread-safe, see below
copyable_atomic(const copyable_atomic& rhs) : std::atomic<T>() { this->operator=(rhs); }
// this is potentially not thread-safe, see below
copyable_atomic& operator=(const copyable_atomic& rhs) {
if (this != &rhs) { std::atomic<T>::store(rhs.load()); }
return *this;
}
};
template <class Histogram>
void fill_histogram(Histogram& h, unsigned ndata) {
using namespace std::chrono_literals;
for (unsigned i = 0; i < ndata; ++i) {
std::this_thread::sleep_for(10ns); // simulate some work
h(double(i) / ndata);
}
}
static void NoThreads(benchmark::State& state) {
auto h =
bh::make_histogram_with(std::vector<unsigned>(), bh::axis::regular<>(100, 0, 1));
const unsigned ndata = state.range(0);
for (auto _ : state) {
state.PauseTiming();
h.reset();
state.ResumeTiming();
fill_histogram(h, ndata);
state.PauseTiming();
assert(ndata == std::accumulate(h.begin(), h.end(), 0.0));
state.ResumeTiming();
}
}
static void AtomicStorage(benchmark::State& state) {
auto h = bh::make_histogram_with(std::vector<copyable_atomic<unsigned>>(),
bh::axis::regular<>(100, 0, 1));
const unsigned nthreads = state.range(0);
const unsigned ndata = state.range(1);
for (auto _ : state) {
state.PauseTiming();
h.reset();
std::vector<std::thread> pool;
pool.reserve(nthreads);
state.ResumeTiming();
for (unsigned i = 0; i < nthreads; ++i)
pool.emplace_back(fill_histogram<decltype(h)>, std::ref(h), ndata / nthreads);
for (auto&& t : pool) t.join();
state.PauseTiming();
assert(ndata == std::accumulate(h.begin(), h.end(), 0.0));
state.ResumeTiming();
}
}
BENCHMARK(NoThreads)->RangeMultiplier(2)->Range(8 << 3, 8 << 5);
BENCHMARK(AtomicStorage)->RangeMultiplier(2)->Ranges({{1, 4}, {8 << 3, 8 << 5}});
| 30.392857 | 90 | 0.657658 | [
"vector"
] |
30817e7d230e4d0701b1e5fe2366f3de61cb71d2 | 3,620 | cpp | C++ | benchmark/askit_release/treecode/src/test_id.cpp | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 20 | 2019-05-14T20:08:08.000Z | 2021-09-22T20:48:29.000Z | benchmark/askit_release/treecode/src/test_id.cpp | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 2 | 2020-10-06T09:47:52.000Z | 2020-10-09T04:27:39.000Z | benchmark/askit_release/treecode/src/test_id.cpp | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 2 | 2019-08-11T22:29:45.000Z | 2020-10-08T20:02:46.000Z |
#include "test_id.hpp"
using namespace askit;
// builds the approximation to A from the ID
// returns it in A_approx
double askit::reconstruct_mat(int num_rows, int num_cols, int k,
const double* A, std::vector<lapack_int>& skeleton, std::vector<double>& proj)
{
std::vector<double> Acol(num_rows * k);
std::vector<double> A_nocol(num_rows * (num_cols - k));
for (int i = 0; i < num_rows; i++)
{
// Iterate through skeleton
for (int j = 0; j < k; j++)
{
Acol[i + j*num_rows] = A[i + skeleton[j]*num_rows];
} // for j (in skeleton)
for (int j = k; j < num_cols; j++)
{
A_nocol[i + (j-k)*num_rows] = A[i + skeleton[j]*num_rows];
} // for j (not in skeleton)
} // for i
// A_approx = Acol * proj
std::vector<double> A_approx(num_rows * (num_cols - k));
std::cout << "Rebuilding approx\n";
int num_cols_minus_k = num_cols - k;
double oned = 1.0;
double zerod = 0.0;
int one = 1;
cblas_dgemm("N", "N", &num_rows, &num_cols_minus_k,
&k, &oned, Acol.data(), &num_rows, proj.data(), &k, &zerod, A_approx.data(), &num_rows);
return compute_error(num_rows, num_cols, k, A_nocol, A_approx, A);
} // reconstruct mat
double askit::compute_error(int num_rows, int num_cols, int k,
std::vector<double>& A_nocol, std::vector<double>& A_approx, const double* A)
{
std::cout << "Computing norms\n";
// A_approx = A_approx - A_nocol
int size = num_rows * (num_cols - k);
double minusone = -1.0;
int one = 1;
cblas_daxpy(&size, &minusone, A_nocol.data(), &one, A_approx.data(), &one);
// doing F-norm for now
// stupid Lapack aux routines aren't found, so do it manually
double norm_A_approx = 0.0;
for (int i = 0; i < num_rows * (num_cols - k); i++)
{
norm_A_approx += A_approx[i] * A_approx[i];
}
std::cout << "approx norm: " << norm_A_approx << "\n";
double norm_A = 0.0;
for (int i = 0; i < num_rows * num_cols; i++)
{
norm_A += A[i] * A[i];
}
std::cout << "exact norm: " << norm_A << "\n";
double error = sqrt(norm_A_approx / norm_A);
return error;
}
double askit::test_id_error(const double* A, int num_rows, int num_cols, int k)
{
std::vector<lapack_int> skeleton(num_cols);
std::vector<double> proj(k * (num_cols - k));
// important because ID now overwrites it's input with QR stuff
double* A_copy = new double[num_rows*num_cols];
memcpy(A_copy, A, num_rows * num_cols * sizeof(double));
IDWorkspace workspace(k, num_cols);
compute_id(A_copy, num_rows, num_cols, k, skeleton, proj, workspace);
double error = reconstruct_mat(num_rows, num_cols, k, A, skeleton, proj);
std::cout << "\nRank " << k << " ID, F-norm error: " << error << "\n\n";
delete A_copy;
return error;
}
double askit::test_adaptive_id(const double* A, int num_rows, int num_cols, double epsilon, int max_rank)
{
std::vector<lapack_int> skeleton;
std::vector<double> proj;
// important because ID now overwrites it's input with QR stuff
double* A_copy = new double[ num_rows * num_cols ];
memcpy(A_copy, A, num_rows * num_cols * sizeof(double));
IDWorkspace workspace(max_rank, num_cols);
int rank = compute_adaptive_id(A_copy, num_rows, num_cols,
skeleton, proj, workspace, epsilon, max_rank);
std::cout << "Computed rank " << rank << " adaptive ID.\n";
double error = reconstruct_mat(num_rows, num_cols, rank, A, skeleton, proj);
std::cout << "\nRank " << rank << " adaptive ID, F-norm error: " << error << "\n\n";
delete A_copy;
return error;
} // test_adaptive_id
| 26.814815 | 105 | 0.630387 | [
"vector"
] |
3085fd1fc52de8818da628cb246b3b5059d5c0b3 | 1,289 | cpp | C++ | main/source/cl_dll/geiger.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 27 | 2015-01-05T19:25:14.000Z | 2022-03-20T00:34:34.000Z | main/source/cl_dll/geiger.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 9 | 2015-01-14T06:51:46.000Z | 2021-03-19T12:07:18.000Z | main/source/cl_dll/geiger.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 5 | 2015-01-11T10:31:24.000Z | 2021-01-06T01:32:58.000Z | /***
*
* Copyright (c) 1999, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
//
// Geiger.cpp
//
// implementation of CHudAmmo class
//
#include "hud.h"
#include "cl_util.h"
#include <string.h>
#include <time.h>
#include <stdio.h>
#include "mod/AvHNetworkMessages.h"
DECLARE_MESSAGE(m_Geiger, Geiger )
int CHudGeiger::Init(void)
{
HOOK_MESSAGE( Geiger );
m_iGeigerRange = 0;
m_iFlags = 0;
//gHUD.AddHudElem(this);
srand( (unsigned)time( NULL ) );
return 1;
};
int CHudGeiger::VidInit(void)
{
return 1;
};
int CHudGeiger::MsgFunc_Geiger(const char *pszName, int iSize, void *pbuf)
{
//update geiger data
NetMsg_GeigerRange( pbuf, iSize, m_iGeigerRange );
m_iGeigerRange <<= 2;
m_iFlags |= HUD_ACTIVE;
return 1;
}
int CHudGeiger::Draw (float flTime)
{
return 1;
}
| 20.140625 | 79 | 0.67339 | [
"object"
] |
30a11c06568902bbcbc894ab18725b9ef5dcec6f | 11,682 | cpp | C++ | applications/physbam/physbam-lib/Public_Library/PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_SOLID_WALL_SLIP.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/Public_Library/PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_SOLID_WALL_SLIP.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/Public_Library/PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_SOLID_WALL_SLIP.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | //#####################################################################
// Copyright 2004, Ron Fedkiw, Frank Losasso, Andrew Selle.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Arrays/ARRAY.h>
#include <PhysBAM_Tools/Grids_Dyadic/DYADIC_GRID_ITERATOR_NODE.h>
#include <PhysBAM_Tools/Grids_Dyadic/MAP_QUADTREE_MESH.h>
#include <PhysBAM_Tools/Log/DEBUG_UTILITIES.h>
#include <PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_SOLID_WALL_SLIP.h>
using namespace PhysBAM;
//#####################################################################
// Constructor
//#####################################################################
template<class TV> BOUNDARY_SOLID_WALL_SLIP<TV>::
BOUNDARY_SOLID_WALL_SLIP(const bool left_constant_extrapolation_input,const bool right_constant_extrapolation_input,const bool bottom_constant_extrapolation_input,
const bool top_constant_extrapolation_input,const bool front_constant_extrapolation_input,const bool back_constant_extrapolation_input)
{
Set_Constant_Extrapolation(left_constant_extrapolation_input,right_constant_extrapolation_input,bottom_constant_extrapolation_input,top_constant_extrapolation_input,
front_constant_extrapolation_input,back_constant_extrapolation_input);
}
//#####################################################################
// Destructor
//#####################################################################
template<class TV> BOUNDARY_SOLID_WALL_SLIP<TV>::
~BOUNDARY_SOLID_WALL_SLIP()
{
}
//#####################################################################
// Function Fill_Ghost_Cells
//#####################################################################
template<class TV> void BOUNDARY_SOLID_WALL_SLIP<TV>::
Fill_Ghost_Cells(const GRID<TV>& grid,const ARRAY<TV,VECTOR<int,2> >& V,ARRAY<TV,VECTOR<int,2> >& V_ghost,const T dt,const T time,const int number_of_ghost_cells)
{
if(V.length != 1) PHYSBAM_FUNCTION_IS_NOT_DEFINED();
int i,j,m=grid.m,n=grid.n;
for(i=1;i<=m;i++) for(j=1;j<=n;j++) V_ghost(i,j)=V(i,j); // interior
if(left_constant_extrapolation) Fill_Left_Ghost_Cells(grid,V_ghost,time);
else for(j=1;j<=n;j++){
V_ghost(0,j).x=-V_ghost(2,j).x;V_ghost(-1,j).x=-V_ghost(3,j).x;V_ghost(-2,j).x=-V_ghost(4,j).x;
V_ghost(0,j).y=V_ghost(2,j).y;V_ghost(-1,j).y=V_ghost(3,j).y;V_ghost(-2,j).y=V_ghost(4,j).y;}
if(right_constant_extrapolation) Fill_Right_Ghost_Cells(grid,V_ghost,time);
else for(j=1;j<=n;j++){
V_ghost(m+1,j).x=-V_ghost(m-1,j).x;V_ghost(m+2,j).x=-V_ghost(m-2,j).x;V_ghost(m+3,j).x=-V_ghost(m-3,j).x;
V_ghost(m+1,j).y=V_ghost(m-1,j).y;V_ghost(m+2,j).y=V_ghost(m-2,j).y;V_ghost(m+3,j).y=V_ghost(m-3,j).y;}
if(bottom_constant_extrapolation) Fill_Bottom_Ghost_Cells(grid,V_ghost,time);
else for(i=-2;i<=m+3;i++){
V_ghost(i,0).x=V_ghost(i,2).x;V_ghost(i,-1).x=V_ghost(i,3).x;V_ghost(i,-2).x=V_ghost(i,4).x;
V_ghost(i,0).y=-V_ghost(i,2).y;V_ghost(i,-1).y=-V_ghost(i,3).y;V_ghost(i,-2).y=-V_ghost(i,4).y;}
if(top_constant_extrapolation) Fill_Top_Ghost_Cells(grid,V_ghost,time);
else for(i=-2;i<=m+3;i++){
V_ghost(i,n+1).x=V_ghost(i,n-1).x;V_ghost(i,n+2).x=V_ghost(i,n-2).x;V_ghost(i,n+3).x=V_ghost(i,n-3).x;
V_ghost(i,n+1).y=-V_ghost(i,n-1).y;V_ghost(i,n+2).y=-V_ghost(i,n-2).y;V_ghost(i,n+3).y=-V_ghost(i,n-3).y;}
}
//#####################################################################
// Function Apply_Boundary_Condition
//#####################################################################
template<class TV> void BOUNDARY_SOLID_WALL_SLIP<TV>::
Apply_Boundary_Condition(const GRID<TV>& grid,ARRAY<TV,VECTOR<int,2> >& V,const T time)
{
if(V.length != 1) PHYSBAM_FUNCTION_IS_NOT_DEFINED();
int i,j,m=grid.m,n=grid.n;
if(!left_constant_extrapolation)for(j=1;j<=n;j++)V(1,j).x=0;
if(!right_constant_extrapolation)for(j=1;j<=n;j++)V(m,j).x=0;
if(!bottom_constant_extrapolation)for(i=1;i<=m;i++)V(i,1).y=0;
if(!top_constant_extrapolation)for(i=1;i<=m;i++)V(i,n).y=0;
}
//#####################################################################
// Function Fill_Ghost_Cells
//#####################################################################
template<class TV> void BOUNDARY_SOLID_WALL_SLIP<TV>::
Fill_Ghost_Cells(const GRID<TV>& grid,const ARRAY<TV,VECTOR<int,3> >& V,ARRAY<TV,VECTOR<int,3> >& V_ghost,const T dt,const T time,const int number_of_ghost_cells)
{
if(V.length != 1) PHYSBAM_FUNCTION_IS_NOT_DEFINED();
int i,j,ij,m=grid.m,n=grid.n,mn=grid.mn;
for(i=1;i<=m;i++) for(j=1;j<=n;j++) for(ij=1;ij<=mn;ij++) V_ghost(i,j,ij)=V(i,j,ij); // interior
if(left_constant_extrapolation) Fill_Left_Ghost_Cells(grid,V_ghost,time);
else for(j=1;j<=n;j++) for(ij=1;ij<=mn;ij++){
V_ghost(0,j,ij)[1]=-V_ghost(2,j,ij)[1];V_ghost(-1,j,ij)[1]=-V_ghost(3,j,ij)[1];V_ghost(-2,j,ij)[1]=-V_ghost(4,j,ij)[1];
V_ghost(0,j,ij)[2]=V_ghost(2,j,ij)[2];V_ghost(-1,j,ij)[2]=V_ghost(3,j,ij)[2];V_ghost(-2,j,ij)[2]=V_ghost(4,j,ij)[2];
V_ghost(0,j,ij)[3]=V_ghost(2,j,ij)[3];V_ghost(-1,j,ij)[3]=V_ghost(3,j,ij)[3];V_ghost(-2,j,ij)[3]=V_ghost(4,j,ij)[3];}
if(right_constant_extrapolation) Fill_Right_Ghost_Cells(grid,V_ghost,time);
else for(j=1;j<=n;j++) for(ij=1;ij<=mn;ij++){
V_ghost(m+1,j,ij)[1]=-V_ghost(m-1,j,ij)[1];V_ghost(m+2,j,ij)[1]=-V_ghost(m-2,j,ij)[1];V_ghost(m+3,j,ij)[1]=-V_ghost(m-3,j,ij)[1];
V_ghost(m+1,j,ij)[2]=V_ghost(m-1,j,ij)[2];V_ghost(m+2,j,ij)[2]=V_ghost(m-2,j,ij)[2];V_ghost(m+3,j,ij)[2]=V_ghost(m-3,j,ij)[2];
V_ghost(m+1,j,ij)[3]=V_ghost(m-1,j,ij)[3];V_ghost(m+2,j,ij)[3]=V_ghost(m-2,j,ij)[3];V_ghost(m+3,j,ij)[3]=V_ghost(m-3,j,ij)[3];}
if(bottom_constant_extrapolation) Fill_Bottom_Ghost_Cells(grid,V_ghost,time);
else for(i=-2;i<=m+3;i++) for(ij=1;ij<=mn;ij++){
V_ghost(i,0,ij)[1]=V_ghost(i,2,ij)[1];V_ghost(i,-1,ij)[1]=V_ghost(i,3,ij)[1];V_ghost(i,-2,ij)[1]=V_ghost(i,4,ij)[1];
V_ghost(i,0,ij)[2]=-V_ghost(i,2,ij)[2];V_ghost(i,-1,ij)[2]=-V_ghost(i,3,ij)[2];V_ghost(i,-2,ij)[2]=-V_ghost(i,4,ij)[2];
V_ghost(i,0,ij)[3]=V_ghost(i,2,ij)[3];V_ghost(i,-1,ij)[3]=V_ghost(i,3,ij)[3];V_ghost(i,-2,ij)[3]=V_ghost(i,4,ij)[3];}
if(top_constant_extrapolation) Fill_Top_Ghost_Cells(grid,V_ghost,time);
else for(i=-2;i<=m+3;i++) for(ij=1;ij<=mn;ij++){
V_ghost(i,n+1,ij)[1]=V_ghost(i,n-1,ij)[1];V_ghost(i,n+2,ij)[1]=V_ghost(i,n-2,ij)[1];V_ghost(i,n+3,ij)[1]=V_ghost(i,n-3,ij)[1];
V_ghost(i,n+1,ij)[2]=-V_ghost(i,n-1,ij)[2];V_ghost(i,n+2,ij)[2]=-V_ghost(i,n-2,ij)[2];V_ghost(i,n+3,ij)[2]=-V_ghost(i,n-3,ij)[2];
V_ghost(i,n+1,ij)[3]=V_ghost(i,n-1,ij)[3];V_ghost(i,n+2,ij)[3]=V_ghost(i,n-2,ij)[3];V_ghost(i,n+3,ij)[3]=V_ghost(i,n-3,ij)[3];}
if(front_constant_extrapolation) Fill_Front_Ghost_Cells(grid,V_ghost,time);
else for(i=-2;i<=m+3;i++) for(j=-2;j<=n+3;j++){
V_ghost(i,j,0)[1]=V_ghost(i,j,2)[1];V_ghost(i,j,-1)[1]=V_ghost(i,j,3)[1];V_ghost(i,j,-2)[1]=V_ghost(i,j,4)[1];
V_ghost(i,j,0)[2]=V_ghost(i,j,2)[2];V_ghost(i,j,-1)[2]=V_ghost(i,j,3)[2];V_ghost(i,j,-2)[2]=V_ghost(i,j,4)[2];
V_ghost(i,j,0)[3]=-V_ghost(i,j,2)[3];V_ghost(i,j,-1)[3]=-V_ghost(i,j,3)[3];V_ghost(i,j,-2)[3]=-V_ghost(i,j,4)[3];}
if(back_constant_extrapolation) Fill_Back_Ghost_Cells(grid,V_ghost,time);
else for(i=-2;i<=m+3;i++) for(j=-2;j<=n+3;j++){
V_ghost(i,j,mn+1)[1]=V_ghost(i,j,mn-1)[1];V_ghost(i,j,mn+2)[1]=V_ghost(i,j,mn-2)[1];V_ghost(i,j,mn+3)[1]=V_ghost(i,j,mn-3)[1];
V_ghost(i,j,mn+1)[2]=V_ghost(i,j,mn-1)[2];V_ghost(i,j,mn+2)[2]=V_ghost(i,j,mn-2)[2];V_ghost(i,j,mn+3)[2]=V_ghost(i,j,mn-3)[2];
V_ghost(i,j,mn+1)[3]=-V_ghost(i,j,mn-1)[3];V_ghost(i,j,mn+2)[3]=-V_ghost(i,j,mn-2)[3];V_ghost(i,j,mn+3)[3]=-V_ghost(i,j,mn-3)[3];}
}
//#####################################################################
// Function Apply_Boundary_Condition
//#####################################################################
template<class TV> void BOUNDARY_SOLID_WALL_SLIP<TV>::
Apply_Boundary_Condition(const GRID<TV>& grid,ARRAY<TV,VECTOR<int,3> >& V,const T time)
{
if(V.length != 1) PHYSBAM_FUNCTION_IS_NOT_DEFINED();
int i,j,ij,m=grid.m,n=grid.n,mn=grid.mn;
if(!left_constant_extrapolation)for(j=1;j<=n;j++)for(ij=1;ij<=mn;ij++)V(1,j,ij)[1]=0;
if(!right_constant_extrapolation)for(j=1;j<=n;j++)for(ij=1;ij<=mn;ij++)V(m,j,ij)[1]=0;
if(!bottom_constant_extrapolation)for(i=1;i<=m;i++)for(ij=1;ij<=mn;ij++)V(i,1,ij)[2]=0;
if(!top_constant_extrapolation)for(i=1;i<=m;i++)for(ij=1;ij<=mn;ij++)V(i,n,ij)[2]=0;
if(!front_constant_extrapolation)for(i=1;i<=m;i++)for(j=1;j<=n;j++)V(i,j,1)[3]=0;
if(!back_constant_extrapolation)for(i=1;i<=m;i++)for(j=1;j<=n;j++)V(i,j,mn)[3]=0;
}
#ifndef COMPILE_WITHOUT_DYADIC_SUPPORT
//#####################################################################
// Function Apply_Boundary_Condition
//#####################################################################
template<class TV> void BOUNDARY_SOLID_WALL_SLIP<TV>::
Apply_Boundary_Condition(const QUADTREE_GRID<T>& grid,ARRAY<TV>& V,const T time)
{
if(!left_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<QUADTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(1));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[1]=0;
if(!right_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<QUADTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(2));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[1]=0;
if(!bottom_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<QUADTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(3));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[2]=0;
if(!top_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<QUADTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(4));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[2]=0;
}
//#####################################################################
// Function Apply_Boundary_Condition
//#####################################################################
template<class TV> void BOUNDARY_SOLID_WALL_SLIP<TV>::
Apply_Boundary_Condition(const OCTREE_GRID<T>& grid,ARRAY<TV>& V,const T time)
{
if(!left_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(1));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[1]=0;
if(!right_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(2));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[1]=0;
if(!bottom_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(3));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[2]=0;
if(!top_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(4));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[2]=0;
if(!front_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(5));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[3]=0;
if(!back_constant_extrapolation) for(DYADIC_GRID_ITERATOR_NODE<OCTREE_GRID<T> > iterator(grid,grid.Map_Individual_Side_Boundary_Nodes(6));iterator.Valid();iterator.Next()) V(iterator.Node_Index())[3]=0;
}
#endif
| 76.855263 | 210 | 0.622154 | [
"vector"
] |
30a2571e21ff9de212e9eada8df94b2244ce8a8b | 10,553 | cpp | C++ | model/Survey.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | model/Survey.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | 1 | 2020-03-18T19:06:28.000Z | 2020-03-23T12:30:00.000Z | model/Survey.cpp | textmagic/textmagic-rest-cpp-v2 | 769c81c3ba5b9f5ac49728f47557db846a0e9a33 | [
"MIT"
] | null | null | null | /**
* TextMagic API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 2
*
*
* NOTE: This class is auto generated by the swagger code generator 2.4.8.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "Survey.h"
namespace com {
namespace textmagic {
namespace client {
namespace model {
Survey::Survey()
{
m_Id = 0;
m_Name = utility::conversions::to_string_t("");
m_Status = utility::conversions::to_string_t("");
m_CreatedAt = utility::datetime();
m_UpdatedAt = utility::datetime();
m_ReceipentsIsSet = false;
m_CountriesIsSet = false;
}
Survey::~Survey()
{
}
void Survey::validate()
{
// TODO: implement validation
}
web::json::value Survey::toJson() const
{
web::json::value val = web::json::value::object();
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id);
val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name);
val[utility::conversions::to_string_t("status")] = ModelBase::toJson(m_Status);
val[utility::conversions::to_string_t("createdAt")] = ModelBase::toJson(m_CreatedAt);
val[utility::conversions::to_string_t("updatedAt")] = ModelBase::toJson(m_UpdatedAt);
{
std::vector<web::json::value> jsonArray;
for( auto& item : m_Receipents )
{
jsonArray.push_back(ModelBase::toJson(item));
}
if(jsonArray.size() > 0)
{
val[utility::conversions::to_string_t("receipents")] = web::json::value::array(jsonArray);
}
}
{
std::vector<web::json::value> jsonArray;
for( auto& item : m_Countries )
{
jsonArray.push_back(ModelBase::toJson(item));
}
if(jsonArray.size() > 0)
{
val[utility::conversions::to_string_t("countries")] = web::json::value::array(jsonArray);
}
}
return val;
}
void Survey::fromJson(web::json::value& val)
{
if(val.has_field(utility::conversions::to_string_t("id")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("id")];
if(!fieldValue.is_null())
{
setId(ModelBase::int32_tFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("name")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("name")];
if(!fieldValue.is_null())
{
setName(ModelBase::stringFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("status")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("status")];
if(!fieldValue.is_null())
{
setStatus(ModelBase::stringFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("createdAt")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("createdAt")];
if(!fieldValue.is_null())
{
setCreatedAt(ModelBase::dateFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("updatedAt")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("updatedAt")];
if(!fieldValue.is_null())
{
setUpdatedAt(ModelBase::dateFromJson(fieldValue));
}
}
{
m_Receipents.clear();
std::vector<web::json::value> jsonArray;
if(val.has_field(utility::conversions::to_string_t("receipents")))
{
for( auto& item : val[utility::conversions::to_string_t("receipents")].as_array() )
{
if(item.is_null())
{
m_Receipents.push_back( std::shared_ptr<SurveyRecipient>(nullptr) );
}
else
{
std::shared_ptr<SurveyRecipient> newItem(new SurveyRecipient());
newItem->fromJson(item);
m_Receipents.push_back( newItem );
}
}
}
}
{
m_Countries.clear();
std::vector<web::json::value> jsonArray;
if(val.has_field(utility::conversions::to_string_t("countries")))
{
for( auto& item : val[utility::conversions::to_string_t("countries")].as_array() )
{
if(item.is_null())
{
m_Countries.push_back( std::shared_ptr<SurveySenderCountries>(nullptr) );
}
else
{
std::shared_ptr<SurveySenderCountries> newItem(new SurveySenderCountries());
newItem->fromJson(item);
m_Countries.push_back( newItem );
}
}
}
}
}
void Survey::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("status"), m_Status));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("createdAt"), m_CreatedAt));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("updatedAt"), m_UpdatedAt));
{
std::vector<web::json::value> jsonArray;
for( auto& item : m_Receipents )
{
jsonArray.push_back(ModelBase::toJson(item));
}
if(jsonArray.size() > 0)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("receipents"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json")));
}
}
{
std::vector<web::json::value> jsonArray;
for( auto& item : m_Countries )
{
jsonArray.push_back(ModelBase::toJson(item));
}
if(jsonArray.size() > 0)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("countries"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json")));
}
}
}
void Survey::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
setId(ModelBase::int32_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id"))));
setName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("name"))));
setStatus(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("status"))));
setCreatedAt(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("createdAt"))));
setUpdatedAt(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("updatedAt"))));
{
m_Receipents.clear();
if(multipart->hasContent(utility::conversions::to_string_t("receipents")))
{
web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("receipents"))));
for( auto& item : jsonArray.as_array() )
{
if(item.is_null())
{
m_Receipents.push_back( std::shared_ptr<SurveyRecipient>(nullptr) );
}
else
{
std::shared_ptr<SurveyRecipient> newItem(new SurveyRecipient());
newItem->fromJson(item);
m_Receipents.push_back( newItem );
}
}
}
}
{
m_Countries.clear();
if(multipart->hasContent(utility::conversions::to_string_t("countries")))
{
web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("countries"))));
for( auto& item : jsonArray.as_array() )
{
if(item.is_null())
{
m_Countries.push_back( std::shared_ptr<SurveySenderCountries>(nullptr) );
}
else
{
std::shared_ptr<SurveySenderCountries> newItem(new SurveySenderCountries());
newItem->fromJson(item);
m_Countries.push_back( newItem );
}
}
}
}
}
int32_t Survey::getId() const
{
return m_Id;
}
void Survey::setId(int32_t value)
{
m_Id = value;
}
utility::string_t Survey::getName() const
{
return m_Name;
}
void Survey::setName(utility::string_t value)
{
m_Name = value;
}
utility::string_t Survey::getStatus() const
{
return m_Status;
}
void Survey::setStatus(utility::string_t value)
{
m_Status = value;
}
utility::datetime Survey::getCreatedAt() const
{
return m_CreatedAt;
}
void Survey::setCreatedAt(utility::datetime value)
{
m_CreatedAt = value;
}
utility::datetime Survey::getUpdatedAt() const
{
return m_UpdatedAt;
}
void Survey::setUpdatedAt(utility::datetime value)
{
m_UpdatedAt = value;
}
std::vector<std::shared_ptr<SurveyRecipient>>& Survey::getReceipents()
{
return m_Receipents;
}
void Survey::setReceipents(std::vector<std::shared_ptr<SurveyRecipient>> value)
{
m_Receipents = value;
m_ReceipentsIsSet = true;
}
bool Survey::receipentsIsSet() const
{
return m_ReceipentsIsSet;
}
void Survey::unsetReceipents()
{
m_ReceipentsIsSet = false;
}
std::vector<std::shared_ptr<SurveySenderCountries>>& Survey::getCountries()
{
return m_Countries;
}
void Survey::setCountries(std::vector<std::shared_ptr<SurveySenderCountries>> value)
{
m_Countries = value;
m_CountriesIsSet = true;
}
bool Survey::countriesIsSet() const
{
return m_CountriesIsSet;
}
void Survey::unsetCountries()
{
m_CountriesIsSet = false;
}
}
}
}
}
| 29.560224 | 206 | 0.623804 | [
"object",
"vector",
"model"
] |
30a2f634c94811340fb6794eadf6c27a91602b42 | 7,356 | cpp | C++ | src/demo/benchmark_suite/benchmark_suite.cpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 5 | 2015-08-25T15:40:09.000Z | 2020-03-15T19:33:22.000Z | src/demo/benchmark_suite/benchmark_suite.cpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | null | null | null | src/demo/benchmark_suite/benchmark_suite.cpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 3 | 2019-01-24T13:14:51.000Z | 2022-01-03T07:30:20.000Z |
#include "functions/MultiVariableOptimProblem.h"
#include "functions/Sphere.h"
#include "functions/Ackley.h"
#include "functions/F10.h"
#include "functions/F5.h"
#include <geneial/algorithm/SteadyStateAlgorithm.h>
#include <geneial/algorithm/criteria/CombinedCriterion.h>
#include <geneial/algorithm/criteria/MaxGenerationCriterion.h>
#include <geneial/algorithm/criteria/NegationDecorator.h>
#include <geneial/algorithm/criteria/FitnessValueReachedCriterion.h>
#include <geneial/algorithm/criteria/FixPointCriterion.h>
#include <geneial/core/population/builder/MultiValueChromosomeFactory.h>
#include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossover.h>
#include <geneial/core/operations/replacement/ReplaceWorstOperation.h>
#include <geneial/core/operations/replacement/ReplaceRandomOperation.h>
#include <geneial/core/operations/mutation/UniformMutationOperation.h>
#include <geneial/core/operations/selection/RouletteWheelSelection.h>
#include <geneial/core/operations/coupling/RandomCouplingOperation.h>
#include <geneial/core/operations/choosing/ChooseRandom.h>
#include <geneial/core/fitness/FitnessEvaluator.h>
#include <geneial/utility/ThreadedExecutionManager.h>
#include <geneial/algorithm/observer/BestChromosomeObserver.h>
#include <stdexcept>
#include <cassert>
#include <memory>
#include <chrono>
#include <thread>
#include <limits>
#include <unistd.h>
using namespace geneial;
using namespace geneial::algorithm;
using namespace geneial::algorithm::stopping_criteria;
using namespace geneial::population;
using namespace geneial::population::chromosome;
using namespace geneial::operation::selection;
using namespace geneial::operation::coupling;
using namespace geneial::operation::crossover;
using namespace geneial::operation::replacement;
using namespace geneial::operation::mutation;
using namespace geneial::operation::choosing;
class GlobalMimiziationProblemEvaluator: public FitnessEvaluator<double>
{
private:
std::shared_ptr<const MultiVariableOptimiProblem> _problemInstance;
public:
GlobalMimiziationProblemEvaluator(std::shared_ptr<const MultiVariableOptimiProblem> problemInstance):
_problemInstance(problemInstance)
{
}
std::unique_ptr<Fitness<double>> evaluate(const BaseChromosome<double>& chromosome) const
{
try
{
const MultiValueChromosome<double, double>& mvc =
dynamic_cast<const MultiValueChromosome<double, double>&>(chromosome);
return
std::unique_ptr<Fitness<double>>(
new Fitness<double>(-1 * _problemInstance->compute(mvc.getContainer())));
} catch (std::bad_cast)
{
throw new std::runtime_error("Chromosome is not an Integer MultiValueChromosome with double fitness!");
}
std::unique_ptr<Fitness<double>> ptr(new Fitness<double>(std::numeric_limits<double>::signaling_NaN()));
return ptr;
}
};
int main(int argc, char **argv)
{
std::cout
//<< "\x1b[0m\x1b[35;1m\x1b[41;1m"
<< "GENEIAL Benchmark Suite - Version " << GENEIAL_VERSION_MAJOR << "." << GENEIAL_VERSION_MINOR << " ("
<< GENEIAL_BUILD_TYPE << ")" << std::endl;
std::vector <
std::pair< unsigned int,std::shared_ptr<MultiVariableOptimiProblem>>> problems {
{2,std::make_shared<Ackley> ()},
{2,std::make_shared<Sphere> ()},
{2,std::make_shared<F10> ()},
{2,std::make_shared<F5> ()}
};
for (const auto & optimProblem : problems)
{
auto evaluator = std::make_shared<GlobalMimiziationProblemEvaluator>(optimProblem.second);
auto algorithmBuilder = SteadyStateAlgorithm<double>::Builder();
//Factory:
MultiValueChromosomeFactory<double, double>::Builder factoryBuilder(evaluator);
factoryBuilder.getSettings().setNum(optimProblem.first);
factoryBuilder.getSettings().setRandomMin(-1000);
factoryBuilder.getSettings().setRandomMax( 1000);
auto factory = std::dynamic_pointer_cast<MultiValueChromosomeFactory<double, double>>(factoryBuilder.create());
algorithmBuilder.setChromosomeFactory(factory);
//Mutation:
UniformMutationOperation<double,double>::Builder mutationBuilder(factory);
auto choosing = ChooseRandom<double>::Builder().setProbability(0.1).create();
mutationBuilder.setChoosingOperation(choosing);
mutationBuilder.getSettings().setMinimumPointsToMutate(1);
mutationBuilder.getSettings().setMaximumPointsToMutate(optimProblem.first);
algorithmBuilder.setMutationOperation(mutationBuilder.create());
//Selection:
auto selectionBuilder = RouletteWheelSelection<double>::Builder();
selectionBuilder.getSettings().setNumberOfParents(10);
algorithmBuilder.setSelectionOperation(selectionBuilder.create());
//Coupling:
auto couplingBuilder = RandomCouplingOperation<double>::Builder();
couplingBuilder.getSettings().setNumberOfOffspring(20);
algorithmBuilder.setCouplingOperation(couplingBuilder.create());
//Crossover:
auto crossoverBuilder = MultiValueChromosomeNPointCrossover<double, double>::Builder(factory);
crossoverBuilder.getCrossoverSettings().setCrossOverPoints(1);
crossoverBuilder.getCrossoverSettings().setWidthSetting(MultiValueChromosomeNPointCrossoverSettings::RANDOM_MIN_WIDTH);
//crossoverBuilder.getCrossoverSettings().setMinWidth(3);
algorithmBuilder.setCrossoverOperation(crossoverBuilder.create());
//Replacement:
auto replacementBuilder = ReplaceRandomOperation<double>::Builder();
replacementBuilder.getSettings().setMode(BaseReplacementSettings::REPLACE_ALL_OFFSPRING);
replacementBuilder.getSettings().setAmountElitism(20);
//replacementBuilder.getSettings().setAmountToReplace(30);
algorithmBuilder.setReplacementOperation(replacementBuilder.create());
//Stopping Criteria
auto stoppingCriterion = std::make_shared<CombinedCriterion<double>>();
stoppingCriterion->add(CombinedCriterion<double>::INIT,
std::make_shared<MaxGenerationCriterion<double>>(1000000));
algorithmBuilder.setStoppingCriterion(stoppingCriterion);
auto algorithm = algorithmBuilder.create();
algorithm->getPopulationSettings().setMaxChromosomes(100);
algorithm->solve();
auto mvc = std::dynamic_pointer_cast<MultiValueChromosome<double, double> >(
algorithm->getHighestFitnessChromosome());
// std::cout << std::endl;
std::cout << optimProblem.second->getName() << std::endl;
std::cout << "ended after " << algorithm->getPopulation().getAge() << " generations" << std::endl;
std::cout <<"Best chromosome" << std::endl;
std::cout << *mvc << std::endl << std::endl;
std::cout << "Minimum:"<<std::endl;
for(const auto min : optimProblem.second->getMinima(optimProblem.first))
{
std::cout << min << ",";
}
}
}
| 39.336898 | 131 | 0.694943 | [
"vector"
] |
dd65f52e6b3bf0bf87507961287f56bf172d0efe | 13,183 | cpp | C++ | ShapeOperations/DorlingCartogram.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | ShapeOperations/DorlingCartogram.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | ShapeOperations/DorlingCartogram.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | /**
* GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
*
* This file is part of GeoDa.
*
* GeoDa is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GeoDa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* The following code is mostly a modified version of Daniel Dorling's
* Area Cartogram code (his own invention), as found in the Appendix of the
* book:
* Area cartograms: their use and creation, Concepts and Techniques in
* Modern Geography series no. 59, University of East Anglia: Environmental
* Publications.
*
* Dorling's code is Public Domain. The original code is in C, and we have
* made only small modifications to support data structure needs. For easy
* comparison to the original code, we have mostly left his variable names,
* comments, and looping logic intact.
*/
#include <wx/msgdlg.h>
#include <wx/stopwatch.h>
#include "../logger.h"
#include "../GenUtils.h"
#include "GalWeight.h"
#include "DorlingCartogram.h"
CartNbrInfo::CartNbrInfo(GalElement* gal, int num_obs)
: bodies(num_obs+1)
{
typedef int* int_ptr;
typedef double* dbl_ptr;
nbours = new int[bodies];
nbour = new int_ptr[bodies];
border = new dbl_ptr[bodies];
perimeter = new double[bodies];
for (int i=0; i<num_obs; i++) {
int n_cnt = gal[i].Size();
nbours[i+1] = n_cnt;
nbour[i+1] = new int[n_cnt+1];
border[i+1] = new double[n_cnt+1];
perimeter[i+1] = n_cnt;
for (int j=0; j<n_cnt; j++) {
nbour[i+1][j+1] = gal[i][j]+1;
border[i+1][j+1] = 1;
}
}
//for (int i=1; i<=num_obs; i++) {
// wxString msg;
// msg << "obs: " << i << " perimeter: " << perimeter[i];
// msg << " nbours: " << nbours[i];
// for (int j=1; j<=nbours[i]; j++) {
// msg << "\n ";
// msg << "nbour[" << i << "][" << j << "]: " << nbour[i][j];
// msg << ", border: " << border[i][j];
// }
// LOG_MSG(msg);
//}
LOG_MSG("Done CartNbrInfo creation");
}
CartNbrInfo::~CartNbrInfo()
{
if (nbour) {
for (int i=1; i<bodies; i++) if (nbour[i]) delete [] nbour[i];
delete [] nbour;
}
if (border) {
for (int i=1; i<bodies; i++) if (border[i]) delete [] border[i];
delete [] border;
}
if (perimeter) delete [] perimeter;
}
const double DorlingCartogram::friction = 0.25;
const double DorlingCartogram::ratio = 0.1;
const double DorlingCartogram::pi = 3.141592653589793238463;
DorlingCartogram::DorlingCartogram(CartNbrInfo* nbs,
const std::vector<double>& orig_x,
const std::vector<double>& orig_y,
const std::vector<double>& orig_data,
const double& orig_data_min,
const double& orig_data_max)
: output_radius(orig_x.size()),
output_x(orig_x.size()), output_y(orig_x.size()),
bodies(orig_x.size()+1),
nbours(nbs->nbours), nbour(nbs->nbour), border(nbs->border),
perimeter(nbs->perimeter),
secs_per_iter(0.01)
{
LOG_MSG("Entering DorlingCartogram()");
x = new double[bodies];
y = new double[bodies];
people = new double[bodies];
radius = new double[bodies];
xvector = new double[bodies];
yvector = new double[bodies];
list = new int[bodies];
tree = new leaf[bodies];
init_cartogram(orig_x, orig_y, orig_data, orig_data_min, orig_data_max);
LOG_MSG("Exiting DorlingCartogram()");
}
DorlingCartogram::~DorlingCartogram()
{
if (x) delete [] x;
if (y) delete [] y;
if (people) delete [] people;
if (radius) delete [] radius;
if (xvector) delete [] xvector;
if (yvector) delete [] yvector;
if (list) delete [] list;
if (tree) delete [] tree;
}
// Global variables: tree, x, y, body
void DorlingCartogram::add_point(int pointer, int axis, int body)
{
if (tree[pointer].id == 0) {
tree[pointer].id = body;
tree[pointer].left = 0;
tree[pointer].right = 0;
tree[pointer].xpos = x[body];
tree[pointer].ypos = y[body];
} else {
if (axis == 1) {
if (x[body] >= tree[pointer].xpos) {
if (tree[pointer].left == 0){
end_pointer += 1;
tree[pointer].left = end_pointer;
}
add_point(tree[pointer].left, 3-axis, body);
} else {
if (tree[pointer].right == 0) {
end_pointer +=1;
tree[pointer].right = end_pointer;
}
add_point(tree[pointer].right, 3-axis, body);
}
} else {
if (y[body] >= tree[pointer].ypos) {
if (tree[pointer].left == 0) {
end_pointer += 1;
tree[pointer].left = end_pointer;
}
add_point(tree[pointer].left, 3-axis, body);
} else {
if (tree[pointer].right == 0) {
end_pointer += 1;
tree[pointer].right = end_pointer;
}
add_point(tree[pointer].right, 3-axis, body);
}
}
}
}
// Global variables: tree, x, y, body, list, number, distance
// modified variables: list and number
void DorlingCartogram::get_point(int pointer, int axis, int body)
{
if (pointer > 0) {
if (tree[pointer].id > 0) {
if (axis == 1) {
if (x[body]-distance < tree[pointer].xpos) {
get_point(tree[pointer].right, 3-axis, body);
}
if (x[body]+distance >= tree[pointer].xpos) {
get_point(tree[pointer].left, 3-axis, body);
}
}
if (axis == 2) {
if (y[body]-distance < tree[pointer].ypos) {
get_point(tree[pointer].right, 3-axis, body);
}
if (y[body] + distance >= tree[pointer].ypos) {
get_point(tree[pointer].left, 3-axis, body);
}
}
if ((x[body]-distance < tree[pointer].xpos) &&
(x[body]+distance >= tree[pointer].xpos)) {
if ((y[body]-distance < tree[pointer].ypos) &&
(y[body]+distance >= tree[pointer].ypos)) {
number += 1;
list[number] = tree[pointer].id;
}
}
}
}
}
// We pass in orig_data_min(max) as parameters rather than calculating
// them so that radius scales can be identical for mutiple cartograms
// across time. orig_x / orig_y will normally be the same, so they
// are not passed in.
void DorlingCartogram::init_cartogram(const std::vector<double>& orig_x,
const std::vector<double>& orig_y,
const std::vector<double>& orig_data,
const double& orig_data_min,
const double& orig_data_max)
{
const double map_to_people = 9000000;
const double map_to_coorindate = 300000;
// Dorling's code assumes a strictly positive people array since
// he was dealing with population counts in each region. We will
// therefore scale and translate our array as appropriate.
double min = orig_data_min;
double max = orig_data_max;
double range = max-min;
for (int i=0, its=orig_data.size(); i<its; i++) people[i+1] = orig_data[i];
if (min < 0) {
double d = -min;
for (int b=1; b<bodies; b++) people[b] += d;
min += d;
max += d;
}
if (min == max) {
for (int b=1; b<bodies; b++) people[b] = 1;
min = 1;
max = 1;
}
if (min*10 < range) {
double d = range/10;
for (int b=1; b<bodies; b++) people[b] += d;
min += d;
max += d;
}
double xmin, xmax, ymin, ymax;
SampleStatistics::CalcMinMax(orig_x, xmin, xmax);
SampleStatistics::CalcMinMax(orig_y, ymin, ymax);
double xrange = xmax-xmin;
if (xrange == 0) xrange = 1.0;
double yrange = ymax-ymin;
if (yrange == 0) yrange = 1.0;
double map_range = GenUtils::max<double>(xrange, yrange);
double t_dist = 0.0;
double t_radius = 0.0;
for (int body=1; body<bodies; body++) {
x[body] = (orig_x[body-1] / map_range) * map_to_coorindate;
y[body] = (orig_y[body-1] / map_range) * map_to_coorindate;
}
if (range == 0) range = 1.0;
for (int b=1; b<bodies; b++) {
people[b] = (people[b] / range) * map_to_people;
}
double xd;
double yd;
for (int body=1; body<bodies; body++) {
for (int nb = 1; nb <= nbours[body]; nb++) {
if (nbour[body][nb] > 0) {
if (nbour[body][nb] < body) {
xd = x[body] - x[nbour[body][nb]];
yd = y[body] - y[nbour[body][nb]];
t_dist += sqrt(xd*xd+yd*yd);
t_radius += sqrt(people[body]/pi) +
sqrt(people[nbour[body][nb]]/pi);
}
}
}
}
double scale = t_dist / t_radius;
if (scale == 0) scale = 1.0;
widest = 0.0;
for (int body=1; body<bodies; body++) {
radius[body] = scale*sqrt(people[body]/pi);
//LOG_MSG(wxString::Format("obs %d, radius: %f people: %f",
// body, radius[body], people[body]));
if (radius[body] > widest) widest = radius[body];
xvector[body] = 0.0;
yvector[body] = 0.0;
}
LOG_MSG("initialization complete");
for (int i=0, its=bodies-1; i<its; i++) output_radius[i] = radius[i+1];
}
int DorlingCartogram::improve(int num_iters)
{
wxStopWatch sw;
// start the big loop creating the tree each iter
int other;
double closest;
double dist;
double overlap;
double atrdst;
double repdst;
double xattract;
double yattract;
double xrepel;
double yrepel;
double xtotal;
double ytotal;
double xd;
double yd;
for (int itter=0; itter<num_iters; itter++) {
for (int body=1; body<bodies; body++) tree[body].id = 0;
end_pointer = 1;
for (int body=1; body<bodies; body++) add_point(1,1,body);
// loop of independent body movements
for (int body=1; body<bodies; body++) {
// get <number> of neighbors within <distance> into <list[]>
number = 0;
distance = widest + radius[body];
get_point(1,1,body);
xrepel = yrepel = 0.0;
xattract = yattract = 0.0;
closest = widest;
//LOG_MSG(wxString::Format(" number %d:", number));
// work out repelling force of overlapping neighbors
if (number > 0) {
for (int nb=1; nb<=number; nb++) {
other = list[nb];
if (other != body) {
xd = x[other]-x[body];
yd = y[other]-y[body];
dist = sqrt(xd*xd+yd*yd);
if (dist < closest) closest = dist;
overlap = radius[body] + radius[other]-dist;
if (overlap > 0 && dist > 1) {
xrepel = xrepel-overlap*(x[other]-x[body])/dist;
yrepel = yrepel-overlap*(y[other]-y[body])/dist;
}
}
}
}
// work out forces of attraction between neighbours
for (int nb=1; nb<=nbours[body]; nb++) {
other = nbour[body][nb];
if (other != 0) {
xd = (x[body]-x[other]);
yd = (y[body]-y[other]);
dist = sqrt(xd*xd+yd*yd);
overlap = dist - radius[body] - radius[other];
if (overlap > 0.0) {
overlap = overlap *
border[body][nb]/perimeter[body];
xattract = xattract + overlap*(x[other]-x[body])/dist;
yattract = yattract + overlap*(y[other]-y[body])/dist;
}
}
}
// now work out the combined effect of attraction and repulsion
atrdst = sqrt(xattract * xattract + yattract * yattract);
repdst = sqrt(xrepel * xrepel+ yrepel * yrepel);
if (repdst > closest) {
xrepel = closest * xrepel / (repdst +1.0);
yrepel = closest * yrepel / (repdst +1.0);
repdst = closest;
}
if (repdst > 0.0) {
xtotal = (1.0-ratio) * xrepel +
ratio*(repdst*xattract/(atrdst+1.0));
ytotal = (1.0-ratio) * yrepel +
ratio*(repdst*yattract/(atrdst+1.0));
} else {
if (atrdst > closest) {
xattract = closest *xattract/(atrdst+1);
yattract = closest *yattract/(atrdst+1);
}
xtotal = xattract;
ytotal = yattract;
}
xvector[body] = friction * (xvector[body]+xtotal);
yvector[body] = friction * (yvector[body]+ytotal);
}
// update the positions
for (int body=1; body<bodies; body++) {
x[body] += (xvector[body]); //+ 0.5);
y[body] += (yvector[body]); // + 0.5);
}
}
//LOG_MSG(wxString::Format("CartogramNewView after %d iterations:",
// num_iters));
//for (int b=1; b<bodies; b++) {
// LOG_MSG(wxString::Format(" obs %d, r: %f x: %f y %f", b,
// radius[b], x[b], y[b]));
//}
for (int i=0, its=bodies-1; i<its; i++) {
output_x[i] = x[i+1];
output_y[i] = y[i+1];
}
int ms = sw.Time();
secs_per_iter = (((double) ms)/1000.0) / ((double) num_iters);
LOG_MSG(wxString::Format("CartogramNewView after %d iterations took %d ms",
num_iters, (int) ms));
//wxMessageBox(wxString::Format("CartogramNewView after %d iterations took %ld ms",
// num_iters, sw.Time()));
return ms;
}
| 30.375576 | 84 | 0.581127 | [
"vector"
] |
dd7edb5ed1912d8bfe8203e766a1422a1f131b6a | 13,161 | cpp | C++ | Cocos2DX_3.x/Demos/Classes/Knight.cpp | aceiii/DragonBonesCPP | cc314ea233026fb0176bc2b8d9efb4ced6a3ca1f | [
"MIT"
] | 1 | 2021-01-11T21:09:35.000Z | 2021-01-11T21:09:35.000Z | Cocos2DX_3.x/Demos/Classes/Knight.cpp | aceiii/DragonBonesCPP | cc314ea233026fb0176bc2b8d9efb4ced6a3ca1f | [
"MIT"
] | null | null | null | Cocos2DX_3.x/Demos/Classes/Knight.cpp | aceiii/DragonBonesCPP | cc314ea233026fb0176bc2b8d9efb4ced6a3ca1f | [
"MIT"
] | null | null | null | #include "Knight.h"
USING_NS_CC;
Scene* KnightGame::createScene()
{
auto scene = Scene::create();
auto layer = KnightGame::create();
scene->addChild(layer);
return scene;
}
const int KnightGame::GROUND = 120.f;
const float KnightGame::G = -0.6f;
KnightGame* KnightGame::instance = nullptr;
bool KnightGame::init()
{
if (!LayerColor::initWithColor(cocos2d::Color4B(105, 105, 105, 255)))
{
return false;
}
KnightGame::instance = this;
_left = false;
_right = false;
_player = nullptr;
// Load DragonBones Data.
const auto dragonBonesData = factory.loadDragonBonesData("Knight/Knight.json");
factory.loadTextureAtlasData("Knight/Knight_texture_1.json");
if (dragonBonesData)
{
cocos2d::Director::getInstance()->getScheduler()->schedule(
schedule_selector(KnightGame::_enterFrameHandler),
this, 0.f, false
);
const auto keyboardListener = cocos2d::EventListenerKeyboard::create();
keyboardListener->onKeyPressed = CC_CALLBACK_2(KnightGame::_keyBoardPressedHandler, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(KnightGame::_keyBoardReleasedHandler, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardListener, this);
const auto touchListener = cocos2d::EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(KnightGame::_touchHandler, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this);
_player = new Hero();
}
else
{
assert(false);
}
const auto text = cocos2d::Label::create();
text->setPosition(480.f, 60.f);
text->setString("Press W/A/S/D to move. Press SPACE to switch weapen. Press Q/E to upgrade weapen.\nClick to attack.");
text->setAlignment(cocos2d::TextHAlignment::CENTER);
this->addChild(text);
return true;
}
void KnightGame::addBullet(KnightBullet* bullet)
{
_bullets.push_back(bullet);
}
void KnightGame::_enterFrameHandler(float passedTime)
{
_player->update();
int i = _bullets.size();
while (i--)
{
const auto bullet = _bullets[i];
if (bullet->update())
{
_bullets.erase(std::find(_bullets.begin(), _bullets.end(), bullet));
delete bullet;
}
}
dragonBones::WorldClock::clock.advanceTime(passedTime);
}
void KnightGame::_keyBoardPressedHandler(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event)
{
switch (keyCode)
{
case cocos2d::EventKeyboard::KeyCode::KEY_A:
case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW:
_left = true;
_updateMove(-1);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
_right = true;
_updateMove(1);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_W:
case cocos2d::EventKeyboard::KeyCode::KEY_UP_ARROW:
_player->jump();
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
case cocos2d::EventKeyboard::KeyCode::KEY_DOWN_ARROW:
break;
case cocos2d::EventKeyboard::KeyCode::KEY_Q:
_player->upgradeWeapon(-1);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_E:
_player->upgradeWeapon(1);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_SPACE:
_player->switchWeapon();
break;
}
}
void KnightGame::_keyBoardReleasedHandler(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event)
{
switch (keyCode)
{
case cocos2d::EventKeyboard::KeyCode::KEY_A:
case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW:
_left = false;
_updateMove(-1);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
_right = false;
_updateMove(1);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_W:
case cocos2d::EventKeyboard::KeyCode::KEY_UP_ARROW:
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
case cocos2d::EventKeyboard::KeyCode::KEY_DOWN_ARROW:
break;
}
}
bool KnightGame::_touchHandler(const cocos2d::Touch* touch, cocos2d::Event* event)
{
_player->attack();
return true;
}
void KnightGame::_updateMove(int dir) const
{
if (_left && _right)
{
_player->move(dir);
}
else if (_left)
{
_player->move(-1);
}
else if (_right)
{
_player->move(1);
}
else
{
_player->move(0);
}
}
const int Hero::MAX_WEAPON_LEVEL = 3;
const float Hero::JUMP_SPEED = 20.f;
const float Hero::MOVE_SPEED = 4.f;
std::vector<std::string> Hero::WEAPON_LIST;
Hero::Hero() :
_isJumping(false),
_isAttacking(false),
_hitCount(0),
_weaponIndex(0),
_weaponName(""),
_weaponsLevel(),
_faceDir(1),
_moveDir(0),
_speedX(0.f),
_speedY(0.f),
_armature(nullptr),
_armatureDisplay(nullptr),
_armArmature(nullptr)
{
WEAPON_LIST.push_back("sword");
WEAPON_LIST.push_back("pike");
WEAPON_LIST.push_back("axe");
WEAPON_LIST.push_back("bow");
_weaponName = WEAPON_LIST[_weaponIndex];
_weaponsLevel.resize(4, 0);
_armature = KnightGame::instance->factory.buildArmature("knight");
_armatureDisplay = dynamic_cast<dragonBones::CCArmatureDisplay*>(_armature->getDisplay());
_armatureDisplay->setPosition(480.f, KnightGame::GROUND);
_armatureDisplay->setScale(1.f);
_armArmature = _armature->getSlot("armOutside")->getChildArmature();
const auto armArmatureDisplay = dynamic_cast<dragonBones::CCArmatureDisplay*>(_armArmature->getDisplay());
armArmatureDisplay->getEventDispatcher()->setEnabled(true);
armArmatureDisplay->getEventDispatcher()->addCustomEventListener(dragonBones::EventObject::COMPLETE, std::bind(&Hero::_armEventHandler, this, std::placeholders::_1));
armArmatureDisplay->getEventDispatcher()->addCustomEventListener(dragonBones::EventObject::FRAME_EVENT, std::bind(&Hero::_armEventHandler, this, std::placeholders::_1));
_updateAnimation();
dragonBones::WorldClock::clock.add(_armature);
KnightGame::instance->addChild(_armatureDisplay);
}
Hero::~Hero()
{
}
void Hero::update()
{
_updatePosition();
}
void Hero::move(int dir)
{
if (_moveDir == dir)
{
return;
}
_moveDir = dir;
if (_moveDir)
{
if (_faceDir != _moveDir)
{
_faceDir = _moveDir;
_armatureDisplay->setScaleX(-_armatureDisplay->getScaleX());
}
}
_updateAnimation();
}
void Hero::jump()
{
if (_isJumping)
{
return;
}
_isJumping = true;
_speedY = JUMP_SPEED;
_armature->getAnimation().fadeIn("jump");
}
void Hero::attack()
{
if (_isAttacking)
{
return;
}
_isAttacking = true;
const auto animationName = "attack_" + _weaponName + "_" + dragonBones::to_string(_hitCount + 1);
_armArmature->getAnimation().fadeIn(animationName);
}
void Hero::switchWeapon()
{
_isAttacking = false;
_hitCount = 0;
_weaponIndex++;
if (_weaponIndex >= WEAPON_LIST.size())
{
_weaponIndex = 0;
}
_weaponName = WEAPON_LIST[_weaponIndex];
_armArmature->getAnimation().fadeIn("ready_" + _weaponName);
}
void Hero::upgradeWeapon(int dir)
{
auto weaponLevel = _weaponsLevel[_weaponIndex] + dir;
weaponLevel %= MAX_WEAPON_LEVEL;
if (weaponLevel < 0)
{
weaponLevel = MAX_WEAPON_LEVEL + weaponLevel;
}
_weaponsLevel[_weaponIndex] = weaponLevel;
// Replace display.
if (_weaponName == "bow")
{
_armArmature->getSlot("bow")->setChildArmature(KnightGame::instance->factory.buildArmature("knightFolder/" + _weaponName + "_" + dragonBones::to_string(weaponLevel + 1)));
}
else
{
KnightGame::instance->factory.replaceSlotDisplay(
"", "weapons", "weapon",
"knightFolder/" + _weaponName + "_" + dragonBones::to_string(weaponLevel + 1),
*_armArmature->getSlot("weapon")
);
}
}
void Hero::_armEventHandler(cocos2d::EventCustom* event)
{
const auto eventObject = (dragonBones::EventObject*)event->getUserData();
if (eventObject->type == dragonBones::EventObject::COMPLETE)
{
_isAttacking = false;
_hitCount = 0;
const auto animationName = "ready_" + _weaponName;
_armArmature->getAnimation().fadeIn(animationName);
}
else if (eventObject->type == dragonBones::EventObject::FRAME_EVENT)
{
if (eventObject->name == "ready")
{
_isAttacking = false;
_hitCount++;
}
else if (eventObject->name == "fire")
{
const auto display = dynamic_cast<dragonBones::CCArmatureDisplay*>(eventObject->armature->getDisplay());
const auto firePointBone = eventObject->armature->getBone("bow");
const auto transform = display->getNodeToWorldTransform();
cocos2d::Vec3 localPoint(firePointBone->global.x, -firePointBone->global.y, 0.f);
cocos2d::Vec2 globalPoint;
transform.transformPoint(&localPoint);
globalPoint.set(localPoint.x, localPoint.y);
auto radian = 0.f;
if (_faceDir > 0)
{
radian = firePointBone->global.getRotation() + display->getRotation() * dragonBones::ANGLE_TO_RADIAN;
}
else
{
radian = dragonBones::PI - (firePointBone->global.getRotation() + display->getRotation() * dragonBones::ANGLE_TO_RADIAN);
}
switch (_weaponsLevel[_weaponIndex])
{
case 0:
_fire(globalPoint, radian);
break;
case 1:
_fire(globalPoint, radian + 3.f * dragonBones::ANGLE_TO_RADIAN);
_fire(globalPoint, radian - 3.f * dragonBones::ANGLE_TO_RADIAN);
break;
case 2:
_fire(globalPoint, radian + 6.f * dragonBones::ANGLE_TO_RADIAN);
_fire(globalPoint, radian);
_fire(globalPoint, radian - 6.f * dragonBones::ANGLE_TO_RADIAN);
break;
}
}
}
}
void Hero::_fire(const cocos2d::Vec2& firePoint, float radian)
{
const auto bullet = new KnightBullet("arrow", radian, 20.f, firePoint);
KnightGame::instance->addBullet(bullet);
}
void Hero::_updateAnimation()
{
if (_isJumping)
{
return;
}
if (_moveDir == 0)
{
_speedX = 0.f;
_armature->getAnimation().fadeIn("stand");
}
else
{
_speedX = MOVE_SPEED * _moveDir;
_armature->getAnimation().fadeIn("run");
}
}
void Hero::_updatePosition()
{
const auto& position = _armatureDisplay->getPosition();
if (_speedX != 0.f)
{
_armatureDisplay->setPosition(position.x + _speedX, position.y);
if (position.x < 0.f)
{
_armatureDisplay->setPosition(0.f, position.y);
}
else if (position.x > 960.f)
{
_armatureDisplay->setPosition(960.f, position.y);
}
}
if (_speedY != 0.f)
{
if (_speedY > 0.f && _speedY + KnightGame::G <= 0.f)
{
_armature->getAnimation().fadeIn("fall");
}
_speedY += KnightGame::G;
_armatureDisplay->setPosition(position.x, position.y + _speedY);
if (position.y < KnightGame::GROUND)
{
_armatureDisplay->setPosition(position.x, KnightGame::GROUND);
_isJumping = false;
_speedY = 0.f;
_speedX = 0.f;
_updateAnimation();
}
}
}
KnightBullet::KnightBullet(const std::string & armatureName, float radian, float speed, const cocos2d::Vec2& position)
{
_speedX = std::cos(radian) * speed;
_speedY = -std::sin(radian) * speed;
_armature = KnightGame::instance->factory.buildArmature(armatureName);
_armatureDisplay = dynamic_cast<dragonBones::CCArmatureDisplay*>(_armature->getDisplay());
_armatureDisplay->setPosition(position);
_armatureDisplay->setRotation(radian * dragonBones::RADIAN_TO_ANGLE);
_armature->getAnimation().play("idle");
dragonBones::WorldClock::clock.add(_armature);
KnightGame::instance->addChild(_armatureDisplay);
}
KnightBullet::~KnightBullet()
{
}
bool KnightBullet::update()
{
const auto& position = _armatureDisplay->getPosition();
_speedY += KnightGame::G;
_armatureDisplay->setPosition(position.x + _speedX, position.y + _speedY);
_armatureDisplay->setRotation(std::atan2(-_speedY, _speedX) * dragonBones::RADIAN_TO_ANGLE);
if (
position.x < -100.f || position.x >= 960.f + 100.f ||
position.y < -100.f || position.y >= 640.f + 100.f
)
{
dragonBones::WorldClock::clock.remove(_armature);
KnightGame::instance->removeChild(_armatureDisplay);
_armature->dispose();
return true;
}
return false;
} | 27.304979 | 179 | 0.630499 | [
"vector",
"transform"
] |
dd7f279904d49220598ac103ba8ceead743073e7 | 2,125 | hpp | C++ | src/share/monitor/grabber_alerts_monitor.hpp | cyrusccy/Karabiner-Elements | 90f83e487a0b6c671bc76f48c01e91fb28ae67c2 | [
"Unlicense"
] | null | null | null | src/share/monitor/grabber_alerts_monitor.hpp | cyrusccy/Karabiner-Elements | 90f83e487a0b6c671bc76f48c01e91fb28ae67c2 | [
"Unlicense"
] | null | null | null | src/share/monitor/grabber_alerts_monitor.hpp | cyrusccy/Karabiner-Elements | 90f83e487a0b6c671bc76f48c01e91fb28ae67c2 | [
"Unlicense"
] | null | null | null | #pragma once
// `krbn::grabber_alerts_monitor` can be used safely in a multi-threaded environment.
#include "constants.hpp"
#include "filesystem.hpp"
#include "json_utility.hpp"
#include "logger.hpp"
#include "monitor/file_monitor.hpp"
#include <fstream>
namespace krbn {
class grabber_alerts_monitor final : public pqrs::dispatcher::extra::dispatcher_client {
public:
// Signals (invoked from the shared dispatcher thread)
boost::signals2::signal<void(std::shared_ptr<nlohmann::json> alerts)> alerts_changed;
// Methods
grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;
grabber_alerts_monitor(const std::string& grabber_alerts_json_file_path) {
std::vector<std::string> targets = {
grabber_alerts_json_file_path,
};
file_monitor_ = std::make_unique<file_monitor>(targets);
file_monitor_->file_changed.connect([this](auto&& changed_file_path,
auto&& changed_file_body) {
if (changed_file_body) {
try {
auto json = nlohmann::json::parse(*changed_file_body);
// json example
//
// {
// "alerts": [
// "system_policy_prevents_loading_kext"
// ]
// }
if (auto v = json_utility::find_array(json, "alerts")) {
auto s = v->dump();
if (last_json_string_ != s) {
last_json_string_ = s;
auto alerts = std::make_shared<nlohmann::json>(*v);
enqueue_to_dispatcher([this, alerts] {
alerts_changed(alerts);
});
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", changed_file_path, e.what());
}
}
});
}
virtual ~grabber_alerts_monitor(void) {
detach_from_dispatcher([this] {
file_monitor_ = nullptr;
});
}
void async_start(void) {
file_monitor_->async_start();
}
private:
std::unique_ptr<file_monitor> file_monitor_;
boost::optional<std::string> last_json_string_;
};
} // namespace krbn
| 27.597403 | 93 | 0.608 | [
"vector"
] |
dd8113f3b40b4ec126a0670d228d3b771fef10cd | 11,039 | cpp | C++ | src/peersafe/app/tx/impl/SchemaTx.cpp | ChainSQL/chainsqld | 6af7eb0624c67776098250a39eae9f195d8a473a | [
"BSL-1.0"
] | 211 | 2017-12-11T03:11:37.000Z | 2022-03-15T12:38:19.000Z | src/peersafe/app/tx/impl/SchemaTx.cpp | ChainSQL/chainsqld | 6af7eb0624c67776098250a39eae9f195d8a473a | [
"BSL-1.0"
] | 17 | 2017-12-18T07:22:06.000Z | 2022-02-15T10:24:29.000Z | src/peersafe/app/tx/impl/SchemaTx.cpp | ChainSQL/chainsqld | 6af7eb0624c67776098250a39eae9f195d8a473a | [
"BSL-1.0"
] | 81 | 2017-12-11T03:09:21.000Z | 2022-03-20T09:42:42.000Z | #include <peersafe/app/tx/SchemaTx.h>
#include <peersafe/schema/SchemaParams.h>
#include <peersafe/app/tx/impl/Tuning.h>
#include <ripple/protocol/STTx.h>
#include <ripple/ledger/View.h>
#include <ripple/protocol/st.h>
#include <ripple/app/main/Application.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/core/Config.h>
namespace ripple {
// A validator node can only participate in MAX_VALIDATOR_SCHEMA_COUNT schemas
TER
checkCountsForValidator(
PreclaimContext const& ctx,
std::vector<Blob> const& validators)
{
// check for final node count
if (ctx.tx.getFieldU16(sfTransactionType) == ttSCHEMA_MODIFY &&
ctx.tx.getFieldU16(sfOpType) == (uint16_t)SchemaModifyOp::del)
{
return tesSUCCESS;
}
std::map<Blob, int> mapValidatorCount;
for (auto const& v : validators)
{
++mapValidatorCount[v];
}
// This is a time-consuming process for a project that has many
// sles.
for (auto sle : ctx.view.sles)
{
if (sle->getType() != ltSCHEMA)
continue;
for (auto& validator : sle->getFieldArray(sfValidators))
{
Json::Value val(Json::objectValue);
auto publicKey = validator.getFieldVL(sfPublicKey);
if (++mapValidatorCount[publicKey] > MAX_VALIDATOR_SCHEMA_COUNT)
return tefSCHEMA_MAX_SCHEMAS;
}
}
return tesSUCCESS;
}
TER preClaimCommon(PreclaimContext const& ctx)
{
std::vector<Blob> validators;
auto const& vals = ctx.tx.getFieldArray(sfValidators);
for (auto val : vals)
{
// check the construct of the validators object
if (val.getCount() != 1 ||
!val.isFieldPresent(sfPublicKey) ||
val.getFieldVL(sfPublicKey).size() == 0 ||
!publicKeyType(makeSlice(val.getFieldVL(sfPublicKey))))
{
return temBAD_VALIDATOR;
}
if (std::find(validators.begin(), validators.end(), val.getFieldVL(sfPublicKey)) != validators.end())
return tefBAD_DUPLACATE_ITEM;
validators.push_back(val.getFieldVL(sfPublicKey));
}
std::vector<Blob> peerList;
auto const& peers = ctx.tx.getFieldArray(sfPeerList);
for (auto peer : peers)
{
// check the construct of the validators object
if (peer.getCount() != 1 || !peer.isFieldPresent(sfEndpoint) ||
peer.getFieldVL(sfEndpoint).size() == 0)
{
return temBAD_PEERLIST;
}
if (std::find(peerList.begin(), peerList.end(), peer.getFieldVL(sfEndpoint)) != peerList.end())
return tefBAD_DUPLACATE_ITEM;
peerList.push_back(peer.getFieldVL(sfEndpoint));
}
if (validators.size() != peerList.size())
return temMALFORMED;
return checkCountsForValidator(ctx,validators);
}
TER checkMulsignValid(STArray const & vals, STArray const& txSigners)
{
for (auto const& txSigner : txSigners)
{
auto const &spk = txSigner.getFieldVL(sfSigningPubKey);
auto iter(vals.end());
iter = std::find_if(vals.begin(), vals.end(),
[spk](STObject const &val) {
if (val.getFieldVL(sfPublicKey) == spk) return true;
return false;
});
if (iter == vals.end())
{
return temBAD_SIGNERFORVAL;
}
}
return tesSUCCESS;
}
void setVavlidValInfo(STObject &val, const STTx & tx)
{
val.setFieldU8(sfSigned, (uint8_t)0);
// Multi-Sign
if (tx.getSigningPubKey().empty())
{
// Get the array of transaction signers.
STArray const& txSigners(tx.getFieldArray(sfSigners));
auto const &spk = val.getFieldVL(sfPublicKey);
for (auto const& txSigner : txSigners)
{
if (txSigner.getFieldVL(sfSigningPubKey) == spk)
{
val.setFieldU8(sfSigned, 1);
}
}
}
}
NotTEC SchemaCreate::preflight(PreflightContext const& ctx)
{
auto const ret = preflight1(ctx);
if (!isTesSuccess(ret))
return ret;
if( !ctx.tx.isFieldPresent(sfSchemaName) ||
!ctx.tx.isFieldPresent(sfSchemaStrategy) ||
!ctx.tx.isFieldPresent(sfValidators) ||
!ctx.tx.isFieldPresent(sfPeerList))
return temMALFORMED;
if (ctx.app.schemaId() != beast::zero)
return tefSCHEMA_TX_FORBIDDEN;
return preflight2(ctx);
}
TER SchemaCreate::preclaim(PreclaimContext const& ctx)
{
auto j = ctx.app.journal("preclaimSchema");
if ((uint8_t)SchemaStragegy::with_state == ctx.tx.getFieldU8(sfSchemaStrategy) &&
(!ctx.tx.isFieldPresent(sfAnchorLedgerHash) ||
!ctx.app.getLedgerMaster().getLedgerByHash(ctx.tx.getFieldH256(sfAnchorLedgerHash))))
{
JLOG(j.trace()) << "anchor ledger is not match the schema strategy.";
return temBAD_ANCHORLEDGER;
}
if (ctx.tx.getFieldArray(sfValidators).size() <= 0 ||
ctx.tx.getFieldArray(sfPeerList).size() <= 0)
{
return temMALFORMED;
}
else if (ctx.tx.getFieldArray(sfValidators).size() < MIN_NODE_COUNT_SCHEMA ||
ctx.tx.getFieldArray(sfPeerList).size() < MIN_NODE_COUNT_SCHEMA)
{
return tefSCHEMA_NODE_COUNT;
}
if( ctx.tx.isFieldPresent(sfSchemaAdmin) )
{
AccountID const uSchemaAccountID(ctx.tx[sfSchemaAdmin]);
auto const k = keylet::account(uSchemaAccountID);
auto const sleSchemaAdmin = ctx.view.read(k);
if (!sleSchemaAdmin)
{
// Schema Admin account does not exist.
return temBAD_SCHEMAADMIN;
}
}
auto const ret = preClaimCommon(ctx);
if (!isTesSuccess(ret))
return ret;
return checkMulsignValid(ctx.tx.getFieldArray(sfValidators), ctx.tx.getFieldArray(sfSigners));
}
TER SchemaCreate::doApply()
{
auto j = ctx_.app.journal("schemaCreateApply");
auto const account = ctx_.tx[sfAccount];
auto const sle = ctx_.view().peek(keylet::account(account));
// Create schema in ledger
auto const slep = std::make_shared<SLE>(
keylet::schema(account, (*sle)[sfSequence] - 1, ctx_.view().info().parentHash));
(*slep)[sfAccount] = account;
(*slep)[sfSchemaName] = ctx_.tx[sfSchemaName];
(*slep)[sfSchemaStrategy] = ctx_.tx[sfSchemaStrategy];
(*slep)[~sfSchemaAdmin] = ctx_.tx[~sfSchemaAdmin];
(*slep)[~sfAnchorLedgerHash] = ctx_.tx[~sfAnchorLedgerHash];
//Reset validators
{
STArray vals = ctx_.tx.getFieldArray(sfValidators);
for (auto& val : vals)
{
setVavlidValInfo(val, ctx_.tx);
}
slep->setFieldArray(sfValidators, vals);
}
STArray const& peerList = ctx_.tx.getFieldArray(sfPeerList);
slep->setFieldArray(sfPeerList, peerList);
ctx_.view().insert(slep);
// Add schema to schema_index
{
auto sleIndexes = ctx_.view().peek(keylet::schema_index());
STVector256 schemas;
bool exists = true;
if (!sleIndexes)
{
sleIndexes = std::make_shared<SLE>(keylet::schema_index());
exists = false;
}
else
schemas = sleIndexes->getFieldV256(sfSchemaIndexes);
schemas.push_back(slep->key());
sleIndexes->setFieldV256(sfSchemaIndexes, schemas);
if (exists)
ctx_.view().update(sleIndexes);
else
ctx_.view().insert(sleIndexes);
}
// Add schema to sender's owner directory
{
auto page = dirAdd(ctx_.view(), keylet::ownerDir(account), slep->key(),
false, describeOwnerDir(account), ctx_.app.journal("View"));
if (!page)
return tecDIR_FULL;
(*slep)[sfOwnerNode] = *page;
}
adjustOwnerCount(ctx_.view(), sle, 1, ctx_.journal);
ctx_.view().update(sle);
JLOG(j.trace()) << "schema sle is created.";
return tesSUCCESS;
}
//------------------------------------------------------------------------------
NotTEC SchemaModify::preflight(PreflightContext const& ctx)
{
auto const ret = preflight1(ctx);
if (!isTesSuccess(ret))
return ret;
if (!ctx.tx.isFieldPresent(sfOpType) ||
!ctx.tx.isFieldPresent(sfValidators) ||
!ctx.tx.isFieldPresent(sfPeerList) ||
!ctx.tx.isFieldPresent(sfSchemaID))
return temMALFORMED;
if (ctx.app.schemaId() != beast::zero)
return tefSCHEMA_TX_FORBIDDEN;
return preflight2(ctx);
}
TER SchemaModify::preclaim(PreclaimContext const& ctx)
{
auto j = ctx.app.journal("schemaModifyPreclaim");
if (ctx.tx.getFieldU16(sfOpType) != (uint16_t)SchemaModifyOp::add &&
ctx.tx.getFieldU16(sfOpType) != (uint16_t)SchemaModifyOp::del)
{
JLOG(j.trace()) << "modify operator is not valid.";
return temBAD_OPTYPE;
}
if (ctx.tx.getFieldArray(sfValidators).size() <= 0 &&
ctx.tx.getFieldArray(sfPeerList).size() <= 0)
{
return temMALFORMED;
}
return preClaimCommon(ctx);
}
TER SchemaModify::doApply()
{
auto j = ctx_.app.journal("schemaModifyApply");
auto sleSchema = ctx_.view().peek(Keylet(ltSCHEMA, ctx_.tx.getFieldH256(sfSchemaID)));
if (sleSchema == nullptr)
{
return tefBAD_SCHEMAID;
}
auto const account = ctx_.tx[sfAccount];
if (!ctx_.tx.getSigningPubKey().empty())
{
if (!sleSchema->isFieldPresent(sfSchemaAdmin))
{
return tefBAD_SCHEMAADMIN;
}
if (sleSchema->getAccountID(sfSchemaAdmin) != ctx_.tx.getAccountID(sfAccount))
{
return tefBAD_SCHEMAADMIN;
}
}
else
{
if (sleSchema->getAccountID(sfAccount) != ctx_.tx.getAccountID(sfAccount))
{
return tefBAD_SCHEMAACCOUNT;
}
auto const ret = checkMulsignValid(sleSchema->getFieldArray(sfValidators), ctx_.tx.getFieldArray(sfSigners));
if (!isTesSuccess(ret))
return ret;
}
//for sle
auto & peers = sleSchema->peekFieldArray(sfPeerList);
auto & vals = sleSchema->peekFieldArray(sfValidators);
//for tx
STArray const & peersTx = ctx_.tx.getFieldArray(sfPeerList);
STArray valsTx = ctx_.tx.getFieldArray(sfValidators);
//check for final node count
if (ctx_.tx.getFieldU16(sfOpType) == (uint16_t)SchemaModifyOp::del)
{
if (vals.size() - valsTx.size() < MIN_NODE_COUNT_SCHEMA)
return tefSCHEMA_NODE_COUNT;
}
for (auto& valTx : valsTx)
{
auto iter(vals.end());
iter = std::find_if(vals.begin(), vals.end(),
[valTx](STObject const &val) {
auto const& spk = val.getFieldVL(sfPublicKey);
auto const& spkTx = valTx.getFieldVL(sfPublicKey);
return spk == spkTx;
});
if (ctx_.tx.getFieldU16(sfOpType) == (uint16_t)SchemaModifyOp::add)
{
if (iter != vals.end())
{
return tefSCHEMA_VALIDATOREXIST;
}
setVavlidValInfo(valTx, ctx_.tx);
vals.push_back(valTx);
}
else
{
if (iter == vals.end())
{
return tefSCHEMA_NOVALIDATOR;
}
vals.erase(iter);
}
}
for (auto const& peerTx : peersTx)
{
auto iter(peers.end());
iter = std::find_if(peers.begin(), peers.end(),
[peerTx](STObject const &peer) {
auto const& sEndpoint = peer.getFieldVL(sfEndpoint);
auto const& sEndpointTx = peerTx.getFieldVL(sfEndpoint);
return sEndpoint == sEndpointTx;
});
if (ctx_.tx.getFieldU16(sfOpType) == (uint16_t)SchemaModifyOp::add)
{
if (iter != peers.end())
{
return tefSCHEMA_PEEREXIST;
}
peers.push_back(peerTx);
}
else
{
if (iter == peers.end())
{
return tefSCHEMA_NOPEER;
}
peers.erase(iter);
}
}
ctx_.view().update(sleSchema);
return tesSUCCESS;
}
}
| 26.92439 | 112 | 0.657849 | [
"object",
"vector"
] |
dd87d809858f890a30e22139780e130b5782fd3a | 2,201 | cpp | C++ | driver_massless/DebugGizmo.cpp | Massless-io/OpenVRDriver_MasslessPen | bce3c01877752d4e9c2135dec3e56b40e956ae60 | [
"BSD-3-Clause-Clear",
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | driver_massless/DebugGizmo.cpp | Massless-io/OpenVRDriver_MasslessPen | bce3c01877752d4e9c2135dec3e56b40e956ae60 | [
"BSD-3-Clause-Clear",
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | driver_massless/DebugGizmo.cpp | Massless-io/OpenVRDriver_MasslessPen | bce3c01877752d4e9c2135dec3e56b40e956ae60 | [
"BSD-3-Clause-Clear",
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | /* Copyright (C) 2020 Massless Corp. - All Rights Reserved
* Author: Jacob Hilton.
* You may use, distribute and modify this code under the
* terms of the BSD 3-Clause "New" or "Revised" License.
*
* You should have received a copy of this license with
* this file. If not, please email support@massless.io
*/
#include "DebugGizmo.hpp"
#include "DriverLog.hpp"
DebugGizmo::DebugGizmo(std::shared_ptr<SettingsManager> settings_manager, std::function<void(DebugGizmo*)> pose_action):
m_settingsManager(settings_manager),
m_poseAction(pose_action)
{
this->m_currentGizmoPose = this->getNotTrackingOpenVRPose();
}
void DebugGizmo::update(std::vector<vr::VREvent_t> events)
{
if (this->m_deviceIndex != vr::k_unTrackedDeviceIndexInvalid)
{
this->m_poseAction(this);
}
}
vr::EVRInitError DebugGizmo::Activate(vr::TrackedDeviceIndex_t index)
{
this->m_deviceIndex = index;
this->m_propertiesHandle = vr::VRProperties()->TrackedDeviceToPropertyContainer(this->m_deviceIndex);
vr::VRProperties()->SetUint64Property(this->m_propertiesHandle, vr::Prop_CurrentUniverseId_Uint64, 2);
vr::VRProperties()->SetStringProperty(this->m_propertiesHandle, vr::Prop_RenderModelName_String, "locator");
return vr::EVRInitError::VRInitError_None;
}
void DebugGizmo::Deactivate()
{
this->m_deviceIndex = vr::k_unTrackedDeviceIndexInvalid;
}
void DebugGizmo::EnterStandby()
{
}
void* DebugGizmo::GetComponent(const char* pchComponentNameAndVersion)
{
return nullptr;
}
void DebugGizmo::DebugRequest(const char* pchRequest, char* pchResponseBuffer, uint32_t unResponseBufferSize)
{
if (unResponseBufferSize >= 1)
pchResponseBuffer[0] = 0;
}
vr::DriverPose_t DebugGizmo::GetPose()
{
return this->m_currentGizmoPose;
}
vr::DriverPose_t DebugGizmo::getNotTrackingOpenVRPose()
{
vr::DriverPose_t out_pose = { 0 };
out_pose.deviceIsConnected = false;
out_pose.poseIsValid = false;
out_pose.result = vr::TrackingResult_Uninitialized;
out_pose.willDriftInYaw = false;
out_pose.shouldApplyHeadModel = false;
return out_pose;
}
vr::TrackedDeviceIndex_t DebugGizmo::getIndex()
{
return this->m_deviceIndex;
}
| 27.5125 | 120 | 0.743753 | [
"vector"
] |
dd883fb67bd3a1b46babb65da445c09d32f9a79a | 2,363 | cc | C++ | 2019/day16.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | 2019/day16.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | 2019/day16.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using Pattern = std::vector<int>;
int GetPatternValue(Pattern const &base_pattern, int row_idx, int element_idx) {
auto const y = row_idx + 1;
auto const t = 4 * y;
auto const x = (element_idx + 1) % t;
if (x >= 2 * y) {
if (x >= 3 * y) {
return base_pattern[3];
}
return base_pattern[2];
} else if (x >= y) {
return base_pattern[1];
}
return base_pattern[0];
}
std::vector<int> DoFFT(std::vector<int> const &input_list, int phase,
Pattern const &base_pattern) {
std::vector<int> output_list;
for (int i = 0; i < input_list.size(); ++i) {
int64_t r = 0;
for (int i2 = 0; i2 < input_list.size(); ++i2) {
r += input_list[i2] * GetPatternValue(base_pattern, i, i2);
}
output_list.push_back(std::abs(r) % 10);
}
return output_list;
}
std::vector<int> DoFFT_partial(std::vector<int> const &input_list, int phase,
Pattern const &base_pattern, int64_t offset) {
std::vector<int> output_list;
output_list.resize(input_list.size());
assert(offset > input_list.size() / 2);
int64_t s = 0;
for (int64_t i = offset; i < input_list.size(); ++i) {
s += input_list[i];
}
for (int64_t i = offset; i < input_list.size(); ++i) {
auto r = s;
s -= input_list[i];
output_list[i] = std::abs(r) % 10;
}
return output_list;
}
int main() {
std::vector<int> base_elements;
{
std::string line;
std::getline(std::cin, line);
for (auto c : line) {
base_elements.push_back(c - '0');
}
}
int64_t offset = 0;
for (int i = 0; i < 7; ++i) {
auto const d = base_elements[i];
offset = offset * 10 + d;
}
Pattern base_pattern{0, 1, 0, -1};
{
auto l = base_elements;
for (int i = 1; i <= 100; ++i) {
l = DoFFT(l, i, base_pattern);
}
for (int i = 0; i < 8; ++i) {
std::cout << l[i];
}
std::cout << "\n";
}
std::vector<int> elements;
for (int i = 0; i < 10000; ++i) {
std::copy(base_elements.begin(), base_elements.end(),
std::back_inserter(elements));
}
auto l = elements;
for (int i = 1; i <= 100; ++i) {
l = DoFFT_partial(l, i, base_pattern, offset);
}
for (auto i = offset; i < offset + 8; ++i) {
std::cout << l[i];
}
std::cout << "\n";
return 0;
}
| 24.360825 | 80 | 0.559035 | [
"vector"
] |
dd8bd9ecc4604f8bc4256740a55919df662ac905 | 54,574 | hpp | C++ | packages/data/endl/src/Data_ENDLDataContainer_def.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/data/endl/src/Data_ENDLDataContainer_def.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/data/endl/src/Data_ENDLDataContainer_def.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file Data_ENDLDataContainer_def.hpp
//! \author Luke Kersting
//! \brief The native eadl container template defs.
//!
//---------------------------------------------------------------------------//
#ifndef DATA_ENDL_DATA_CONTAINER_DEF_HPP
#define DATA_ENDL_DATA_CONTAINER_DEF_HPP
// Boost Includes
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/nvp.hpp>
namespace Data{
// Set the coherent photon cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setCoherentCrossSectionInterpType()
{
d_coherent_cross_section_interp_type = InterpType::name();
}
// Set the coherent form factor interpolation type
template<typename InterpType>
void ENDLDataContainer::setCoherentFormFactorInterpType()
{
d_coherent_form_factor_interp_type = InterpType::name();
}
// Set the coherent imaginary anomalous scattering factor interpolation type
template<typename InterpType>
void ENDLDataContainer::setCoherentImaginaryAnomalousFactorInterpType()
{
d_coherent_imaginary_anomalous_scattering_factor_interp_type =
InterpType::name();
}
// Set the coherent real anomalous scattering factor interpolation type
template<typename InterpType>
void ENDLDataContainer::setCoherentRealAnomalousFactorInterpType()
{
d_coherent_real_anomalous_scattering_factor_interp_type = InterpType::name();
}
// Set the coherent average energy of the scattered photon interpolation type
template<typename InterpType>
void ENDLDataContainer::setCoherentAveragePhotonEnergyInterpType()
{
d_coherent_average_photon_energy_interp_type = InterpType::name();
}
// Set the incoherent photon cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setIncoherentCrossSectionInterpType()
{
d_incoherent_cross_section_interp_type = InterpType::name();
}
// Set the incoherent scattering function interpolation type
template<typename InterpType>
void ENDLDataContainer::setIncoherentScatteringFunctionInterpType()
{
d_incoherent_scattering_function_interp_type = InterpType::name();
}
// Set the incoherent average energy of the scattered photon
template<typename InterpType>
void ENDLDataContainer::setIncoherentAveragePhotonEnergyInterpType()
{
d_incoherent_average_photon_energy_interp_type = InterpType::name();
}
// Set the incoherent average energy of the recoil electron interpolation type
template<typename InterpType>
void ENDLDataContainer::setIncoherentAverageElectronEnergyInterpType()
{
d_incoherent_average_electron_energy_interp_type = InterpType::name();
}
// Set the photoelectric photon cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricCrossSectionInterpType()
{
d_photoelectric_cross_section_interp_type = InterpType::name();
}
// Set the photoelectric average energy of the residual atom interpolation type
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricAverageResidualEnergyInterpType()
{
d_photoelectric_average_residual_energy_interp_type = InterpType::name();
}
// Set the photoelectric average energy of the secondary photons interpolation type
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricAveragePhotonsEnergyInterpType()
{
d_photoelectric_secondary_photons_energy_interp_type = InterpType::name();
}
// Set the photoelectric average energy of the secondary electrons interpolation type
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricAverageElectronsEnergyInterpType()
{
d_photoelectric_secondary_electrons_energy_interp_type = InterpType::name();
}
// Set the photoelectric photon cross section interpolation type for a subshell
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricCrossSectionInterpType( const unsigned subshell )
{
d_photoelectric_subshell_cross_section_interp_type[subshell] =
InterpType::name();
}
// Set the photoelectric average energy of the residual atom interpolation type for a subshell
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricAverageResidualEnergyInterpType( const unsigned subshell )
{
d_photoelectric_subshell_average_residual_energy_interp_type[subshell] =
InterpType::name();
}
// Set the photoelectric average energy of the secondary photons interpolation type for a subshell
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricAveragePhotonsEnergyInterpType( const unsigned subshell )
{
d_photoelectric_subshell_secondary_photons_energy_interp_type[subshell] =
InterpType::name();
}
// Set the photoelectric average energy of the secondary electrons interpolation type for a subshell
template<typename InterpType>
void ENDLDataContainer::setPhotoelectricAverageElectronsEnergyInterpType( const unsigned subshell )
{
d_photoelectric_subshell_secondary_electrons_energy_interp_type[subshell] =
InterpType::name();
}
// Set the pair production photon cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setPairProductionCrossSectionInterpType()
{
d_pair_production_cross_section_interp_type = InterpType::name();
}
// Set the pair production average energy of the secondary positron interpolation type
template<typename InterpType>
void ENDLDataContainer::setPairProductionAveragePositronEnergyInterpType()
{
d_pair_production_average_positron_energy_interp_type = InterpType::name();
}
// Set the pair production average energy of the secondary electron interpolation type
template<typename InterpType>
void ENDLDataContainer::setPairProductionAverageElectronEnergyInterpType()
{
d_pair_production_average_electron_energy_interp_type = InterpType::name();
}
// Set the triplet production photon cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setTripletProductionCrossSectionInterpType()
{
d_triplet_production_cross_section_interp_type = InterpType::name();
}
// Set the triplet production average energy of the secondary positron interpolation type
template<typename InterpType>
void ENDLDataContainer::setTripletProductionAveragePositronEnergyInterpType()
{
d_triplet_production_average_positron_energy_interp_type =
InterpType::name();
}
// Set the triplet production average energy of the secondary electron interpolation type
template<typename InterpType>
void ENDLDataContainer::setTripletProductionAverageElectronEnergyInterpType()
{
d_triplet_production_average_electron_energy_interp_type =
InterpType::name();
}
// Set the electron elastic transport cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setElasticTransportCrossSectionInterpType()
{
d_elastic_transport_cross_section_interp_type = InterpType::name();
}
// Set the electron elastic cross section below mu = 0.999999 interpolation type
template<typename InterpType>
void ENDLDataContainer::setCutoffElasticCrossSectionInterpType()
{
d_cutoff_elastic_cross_section_interp_type = InterpType::name();
}
// Set the cutoff elastic average energy to the residual atom interpolation type
template<typename InterpType>
void ENDLDataContainer::setCutoffElasticResidualEnergyInterpType()
{
d_cutoff_elastic_residual_energy_interp_type = InterpType::name();
}
// Set the cutoff elastic average energy of the scattered electron
template<typename InterpType>
void ENDLDataContainer::setCutoffElasticScatteredElectronEnergyInterpType()
{
d_cutoff_elastic_scattered_electron_energy_interp_type = InterpType::name();
}
// Set the elastic scattering pdf interpolation type
template<typename InterpType>
void ENDLDataContainer::setCutoffElasticPDFInterpType()
{
d_cutoff_elastic_pdf_interp_type = InterpType::name();
}
// Set the total elastic electron cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setTotalElasticCrossSectionInterpType()
{
d_total_elastic_cross_section_interp_type = InterpType::name();
}
// Set the electroionization electron cross section interpolation type for a subshell
template<typename InterpType>
void ENDLDataContainer::setElectroionizationCrossSectionInterpType( const unsigned subshell )
{
d_electroionization_subshell_cross_section_interp_type[subshell] =
InterpType::name();
}
// Set the electroionization average scattered electron energy interpolation type for a subshell
template<typename InterpType>
void ENDLDataContainer::setElectroionizationAverageScatteredElectronEnergyInterpType( const unsigned subshell )
{
d_electroionization_average_scattered_electron_energy_interp_type[subshell] =
InterpType::name();
}
// Set the electroionization average recoil electron energy interp type for a subshell
template<typename InterpType>
void ENDLDataContainer::setElectroionizationAverageRecoilElectronEnergyInterpType( const unsigned subshell )
{
d_electroionization_average_recoil_electron_energy_interp_type[subshell] =
InterpType::name();
}
// Set electroionization recoil energy pdf interpolation type for all incident energies in a subshell
template<typename InterpType>
void ENDLDataContainer::setElectroionizationRecoilPDFInterpType( const unsigned subshell )
{
d_electroionization_recoil_pdf_interp_type[subshell] = InterpType::name();
}
// Set the bremsstrahlung electron cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setBremsstrahlungCrossSectionInterpType()
{
d_bremsstrahlung_cross_section_interp_type = InterpType::name();
}
// Set the bremsstrahlung average energy of the secondary photon interpolation type
template<typename InterpType>
void ENDLDataContainer::setBremsstrahlungAveragePhotonEnergyInterpType()
{
d_bremsstrahlung_average_photon_energy_interp_type = InterpType::name();
}
// Set all the bremsstrahlung photon energy pdf data interpolation type
template<typename InterpType>
void ENDLDataContainer::setBremsstrahlungPhotonPDFInterpType()
{
d_bremsstrahlung_photon_pdf_interp_type = InterpType::name();
}
// Set the bremsstrahlung average energy of the secondary electron interpolation type
template<typename InterpType>
void ENDLDataContainer::setBremsstrahlungAverageElectronEnergyInterpType()
{
d_bremsstrahlung_average_electron_energy_interp_type = InterpType::name();
}
// Set the atomic excitation electron cross section interpolation type
template<typename InterpType>
void ENDLDataContainer::setAtomicExcitationCrossSectionInterpType()
{
d_atomic_excitation_cross_section_interp_type = InterpType::name();
}
// Set the atomic excitation average energy loss interpolation type
template<typename InterpType>
void ENDLDataContainer::setAtomicExcitationEnergyLossInterpType()
{
d_atomic_excitation_energy_loss_interp_type = InterpType::name();
}
// Save the data to an archive
template<typename Archive>
void ENDLDataContainer::save( Archive& ar,
const unsigned version) const
{
ar & boost::serialization::make_nvp( "atomic_number", d_atomic_number );
ar & boost::serialization::make_nvp( "atomic_weight", d_atomic_weight );
//---------------------------------------------------------------------------//
// RELAXATION DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "subshells", d_subshells );
ar & boost::serialization::make_nvp( "subshell_occupancies",
d_subshell_occupancies );
ar & boost::serialization::make_nvp( "subshell_binding_energies",
d_subshell_binding_energies );
ar & boost::serialization::make_nvp( "subshell_kinetic_energies",
d_subshell_kinetic_energies );
ar & boost::serialization::make_nvp( "subshell_average_radii",
d_subshell_average_radii );
ar & boost::serialization::make_nvp( "subshell_radiative_levels",
d_subshell_radiative_levels );
ar & boost::serialization::make_nvp( "subshell_non_radiative_levels",
d_subshell_non_radiative_levels );
ar & boost::serialization::make_nvp( "subshell_local_depositions",
d_subshell_local_depositions );
ar & boost::serialization::make_nvp( "subshell_average_photon_numbers",
d_subshell_average_photon_numbers );
ar & boost::serialization::make_nvp( "subshell_average_photon_energies",
d_subshell_average_photon_energies );
ar & boost::serialization::make_nvp( "subshell_average_electron_numbers",
d_subshell_average_electron_numbers );
ar & boost::serialization::make_nvp( "subshell_average_electron_energies",
d_subshell_average_electron_energies );
ar & boost::serialization::make_nvp( "radiative_transition_probabilities",
d_radiative_transition_probabilities );
ar & boost::serialization::make_nvp( "radiative_transition_energies",
d_radiative_transition_energies );
ar & boost::serialization::make_nvp( "non_radiative_transition_probabilities",
d_non_radiative_transition_probabilities );
ar & boost::serialization::make_nvp( "non_radiative_transition_energies",
d_non_radiative_transition_energies );
//---------------------------------------------------------------------------//
// THE COHERENT PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "coherent_cross_section_energy_grid",
d_coherent_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "coherent_cross_section",
d_coherent_cross_section );
ar & boost::serialization::make_nvp( "coherent_cross_section_interp_type",
d_coherent_cross_section_interp_type );
ar & boost::serialization::make_nvp( "coherent_form_factor_argument",
d_coherent_form_factor_argument );
ar & boost::serialization::make_nvp( "coherent_form_factor",
d_coherent_form_factor );
ar & boost::serialization::make_nvp( "coherent_form_factor_interp_type",
d_coherent_form_factor_interp_type );
ar & boost::serialization::make_nvp(
"coherent_imaginary_anomalous_scattering_factor_incident_energy",
d_coherent_imaginary_anomalous_scattering_factor_incident_energy );
ar & boost::serialization::make_nvp(
"coherent_imaginary_anomalous_scattering_factor",
d_coherent_imaginary_anomalous_scattering_factor );
ar & boost::serialization::make_nvp(
"coherent_imaginary_anomalous_scattering_factor_interp_type",
d_coherent_imaginary_anomalous_scattering_factor_interp_type );
ar & boost::serialization::make_nvp(
"coherent_real_anomalous_scattering_factor_incident_energy",
d_coherent_real_anomalous_scattering_factor_incident_energy );
ar & boost::serialization::make_nvp(
"coherent_real_anomalous_scattering_factor",
d_coherent_real_anomalous_scattering_factor );
ar & boost::serialization::make_nvp(
"coherent_real_anomalous_scattering_factor_interp_type",
d_coherent_real_anomalous_scattering_factor_interp_type );
ar & boost::serialization::make_nvp(
"coherent_average_photon_incident_energy",
d_coherent_average_photon_incident_energy );
ar & boost::serialization::make_nvp( "coherent_average_photon_energy",
d_coherent_average_photon_energy );
ar & boost::serialization::make_nvp(
"coherent_average_photon_energy_interp_type",
d_coherent_average_photon_energy_interp_type );
//---------------------------------------------------------------------------//
// THE INCOHERENT PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "incoherent_cross_section_energy_grid",
d_incoherent_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "incoherent_cross_section",
d_incoherent_cross_section );
ar & boost::serialization::make_nvp( "incoherent_cross_section_interp_type",
d_incoherent_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"incoherent_scattering_function_argument",
d_incoherent_scattering_function_argument );
ar & boost::serialization::make_nvp( "incoherent_scattering_function",
d_incoherent_scattering_function );
ar & boost::serialization::make_nvp(
"incoherent_scattering_function_interp_type",
d_incoherent_scattering_function_interp_type );
ar & boost::serialization::make_nvp(
"incoherent_average_photon_incident_energy",
d_incoherent_average_photon_incident_energy );
ar & boost::serialization::make_nvp( "incoherent_average_photon_energy",
d_incoherent_average_photon_energy );
ar & boost::serialization::make_nvp(
"incoherent_average_photon_energy_interp_type",
d_incoherent_average_photon_energy_interp_type );
ar & boost::serialization::make_nvp(
"incoherent_average_electron_incident_energy",
d_incoherent_average_electron_incident_energy );
ar & boost::serialization::make_nvp( "incoherent_average_electron_energy",
d_incoherent_average_electron_energy );
ar & boost::serialization::make_nvp(
"incoherent_average_electron_energy_interp_type",
d_incoherent_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// THE PHOTOELECTRIC PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"photoelectric_cross_section_energy_grid",
d_photoelectric_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "photoelectric_cross_section",
d_photoelectric_cross_section );
ar & boost::serialization::make_nvp(
"photoelectric_cross_section_interp_type",
d_photoelectric_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_average_residual_incident_energy",
d_photoelectric_average_residual_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_average_residual_energy",
d_photoelectric_average_residual_energy );
ar & boost::serialization::make_nvp(
"photoelectric_average_residual_energy_interp_type",
d_photoelectric_average_residual_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_photons_incident_energy",
d_photoelectric_secondary_photons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_photons_energy",
d_photoelectric_secondary_photons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_photons_energy_interp_type",
d_photoelectric_secondary_photons_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_electrons_incident_energy",
d_photoelectric_secondary_electrons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_electrons_energy",
d_photoelectric_secondary_electrons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_electrons_energy_interp_type",
d_photoelectric_secondary_electrons_energy_interp_type );
//---------------------------------------------------------------------------//
// THE PHOTOELECTRIC PHOTON DATA BY SUBSHELL
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"photoelectric_subshell_cross_section_energy_grid",
d_photoelectric_subshell_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "photoelectric_subshell_cross_section",
d_photoelectric_subshell_cross_section );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_cross_section_interp_type",
d_photoelectric_subshell_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_average_residual_incident_energy",
d_photoelectric_subshell_average_residual_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_average_residual_energy",
d_photoelectric_subshell_average_residual_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_average_residual_energy_interp_type",
d_photoelectric_subshell_average_residual_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_photons_incident_energy",
d_photoelectric_subshell_secondary_photons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_photons_energy",
d_photoelectric_subshell_secondary_photons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_photons_energy_interp_type",
d_photoelectric_subshell_secondary_photons_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_electrons_incident_energy",
d_photoelectric_subshell_secondary_electrons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_electrons_energy",
d_photoelectric_subshell_secondary_electrons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_electrons_energy_interp_type",
d_photoelectric_subshell_secondary_electrons_energy_interp_type );
//---------------------------------------------------------------------------//
// THE PAIR PRODUCTION PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"pair_production_cross_section_energy_grid",
d_pair_production_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "pair_production_cross_section",
d_pair_production_cross_section );
ar & boost::serialization::make_nvp(
"pair_production_cross_section_interp_type",
d_pair_production_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"pair_production_average_positron_incident_energy",
d_pair_production_average_positron_incident_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_positron_energy",
d_pair_production_average_positron_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_positron_energy_interp_type",
d_pair_production_average_positron_energy_interp_type );
ar & boost::serialization::make_nvp(
"pair_production_average_electron_incident_energy",
d_pair_production_average_electron_incident_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_electron_energy",
d_pair_production_average_electron_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_electron_energy_interp_type",
d_pair_production_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// THE TRIPLET PRODUCTION PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"triplet_production_cross_section_energy_grid",
d_triplet_production_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "triplet_production_cross_section",
d_triplet_production_cross_section );
ar & boost::serialization::make_nvp(
"triplet_production_cross_section_interp_type",
d_triplet_production_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"triplet_production_average_positron_incident_energy",
d_triplet_production_average_positron_incident_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_positron_energy",
d_triplet_production_average_positron_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_positron_energy_interp_type",
d_triplet_production_average_positron_energy_interp_type );
ar & boost::serialization::make_nvp(
"triplet_production_average_electron_incident_energy",
d_triplet_production_average_electron_incident_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_electron_energy",
d_triplet_production_average_electron_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_electron_energy_interp_type",
d_triplet_production_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// ELASTIC DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "elastic_energy_grid",
d_elastic_energy_grid );
ar & boost::serialization::make_nvp( "elastic_transport_cross_section",
d_elastic_transport_cross_section );
ar & boost::serialization::make_nvp(
"elastic_transport_cross_section_interp_type",
d_elastic_transport_cross_section_interp_type );
ar & boost::serialization::make_nvp( "cutoff_elastic_cross_section",
d_cutoff_elastic_cross_section );
ar & boost::serialization::make_nvp(
"cutoff_elastic_cross_section_interp_type",
d_cutoff_elastic_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"cutoff_elastic_residual_incident_energy",
d_cutoff_elastic_residual_incident_energy );
ar & boost::serialization::make_nvp( "cutoff_elastic_residual_energy",
d_cutoff_elastic_residual_energy );
ar & boost::serialization::make_nvp(
"cutoff_elastic_residual_energy_interp_type",
d_cutoff_elastic_residual_energy_interp_type );
ar & boost::serialization::make_nvp(
"cutoff_elastic_scattered_electron_incident_energy",
d_cutoff_elastic_scattered_electron_incident_energy );
ar & boost::serialization::make_nvp(
"cutoff_elastic_scattered_electron_energy",
d_cutoff_elastic_scattered_electron_energy );
ar & boost::serialization::make_nvp(
"cutoff_elastic_scattered_electron_energy_interp_type",
d_cutoff_elastic_scattered_electron_energy_interp_type );
ar & boost::serialization::make_nvp( "cutoff_elastic_angular_energy_grid",
d_cutoff_elastic_angular_energy_grid );
ar & boost::serialization::make_nvp( "cutoff_elastic_angles",
d_cutoff_elastic_angles );
ar & boost::serialization::make_nvp( "cutoff_elastic_pdf",
d_cutoff_elastic_pdf );
ar & boost::serialization::make_nvp( "cutoff_elastic_pdf_interp_type",
d_cutoff_elastic_pdf_interp_type );
ar & boost::serialization::make_nvp( "total_elastic_cross_section",
d_total_elastic_cross_section );
ar & boost::serialization::make_nvp(
"total_elastic_cross_section_interp_type",
d_total_elastic_cross_section_interp_type );
/*
ar & boost::serialization::make_nvp(
"screened_rutherford_elastic_cross_section",
d_screened_rutherford_elastic_cross_section );
ar & boost::serialization::make_nvp(
"screened_rutherford_normalization_constant",
d_screened_rutherford_normalization_constant );
ar & boost::serialization::make_nvp( "moliere_screening_constant",
d_moliere_screening_constant );
*/
//---------------------------------------------------------------------------//
// ELECTROIONIZATION DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"electroionization_subshell_cross_section_energy_grid",
d_electroionization_subshell_cross_section_energy_grid );
ar & boost::serialization::make_nvp(
"electroionization_subshell_cross_section",
d_electroionization_subshell_cross_section );
ar & boost::serialization::make_nvp(
"electroionization_subshell_cross_section_interp_type",
d_electroionization_subshell_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"electroionization_average_scattered_electron_incident_energy",
d_electroionization_average_scattered_electron_incident_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_scattered_electron_energy",
d_electroionization_average_scattered_electron_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_scattered_electron_energy_interp_type",
d_electroionization_average_scattered_electron_energy_interp_type );
ar & boost::serialization::make_nvp(
"electroionization_average_recoil_electron_incident_energy",
d_electroionization_average_recoil_electron_incident_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_recoil_electron_energy",
d_electroionization_average_recoil_electron_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_recoil_electron_energy_interp_type",
d_electroionization_average_recoil_electron_energy_interp_type );
ar & boost::serialization::make_nvp( "electroionization_recoil_energy_grid",
d_electroionization_recoil_energy_grid );
ar & boost::serialization::make_nvp( "electroionization_recoil_energy",
d_electroionization_recoil_energy );
ar & boost::serialization::make_nvp( "electroionization_recoil_pdf",
d_electroionization_recoil_pdf );
ar & boost::serialization::make_nvp(
"electroionization_recoil_pdf_interp_type",
d_electroionization_recoil_pdf_interp_type );
//---------------------------------------------------------------------------//
// BREMSSTRAHLUNG DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"bremsstrahlung_cross_section_energy_grid",
d_bremsstrahlung_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "bremsstrahlung_cross_section",
d_bremsstrahlung_cross_section );
ar & boost::serialization::make_nvp(
"bremsstrahlung_cross_section_interp_type",
d_bremsstrahlung_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_photon_incident_energy",
d_bremsstrahlung_average_photon_incident_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_photon_energy",
d_bremsstrahlung_average_photon_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_photon_energy_interp_type",
d_bremsstrahlung_average_photon_energy_interp_type );
ar & boost::serialization::make_nvp( "bremsstrahlung_photon_energy_grid",
d_bremsstrahlung_photon_energy_grid );
ar & boost::serialization::make_nvp( "bremsstrahlung_photon_energy",
d_bremsstrahlung_photon_energy );
ar & boost::serialization::make_nvp( "bremsstrahlung_photon_pdf",
d_bremsstrahlung_photon_pdf );
ar & boost::serialization::make_nvp(
"bremsstrahlung_photon_pdf_interp_type",
d_bremsstrahlung_photon_pdf_interp_type );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_electron_incident_energy",
d_bremsstrahlung_average_electron_incident_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_electron_energy",
d_bremsstrahlung_average_electron_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_electron_energy_interp_type",
d_bremsstrahlung_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// ATOMIC EXCITATION DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"atomic_excitation_energy_grid",
d_atomic_excitation_energy_grid );
ar & boost::serialization::make_nvp( "atomic_excitation_cross_section",
d_atomic_excitation_cross_section );
ar & boost::serialization::make_nvp(
"atomic_excitation_cross_section_interp_type",
d_atomic_excitation_cross_section_interp_type );
ar & boost::serialization::make_nvp( "atomic_excitation_energy_loss",
d_atomic_excitation_energy_loss );
ar & boost::serialization::make_nvp(
"atomic_excitation_energy_loss_interp_type",
d_atomic_excitation_energy_loss_interp_type );
}
// Load the data from an archive
template<typename Archive>
void ENDLDataContainer::load( Archive& ar,
const unsigned version )
{
ar & boost::serialization::make_nvp( "atomic_number", d_atomic_number );
ar & boost::serialization::make_nvp( "atomic_weight", d_atomic_weight );
//---------------------------------------------------------------------------//
// RELAXATION DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "subshells", d_subshells );
ar & boost::serialization::make_nvp( "subshell_occupancies",
d_subshell_occupancies );
ar & boost::serialization::make_nvp( "subshell_binding_energies",
d_subshell_binding_energies );
ar & boost::serialization::make_nvp( "subshell_kinetic_energies",
d_subshell_kinetic_energies );
ar & boost::serialization::make_nvp( "subshell_average_radii",
d_subshell_average_radii );
ar & boost::serialization::make_nvp( "subshell_radiative_levels",
d_subshell_radiative_levels );
ar & boost::serialization::make_nvp( "subshell_non_radiative_levels",
d_subshell_non_radiative_levels );
ar & boost::serialization::make_nvp( "subshell_local_depositions",
d_subshell_local_depositions );
ar & boost::serialization::make_nvp( "subshell_average_photon_numbers",
d_subshell_average_photon_numbers );
ar & boost::serialization::make_nvp( "subshell_average_photon_energies",
d_subshell_average_photon_energies );
ar & boost::serialization::make_nvp( "subshell_average_electron_numbers",
d_subshell_average_electron_numbers );
ar & boost::serialization::make_nvp( "subshell_average_electron_energies",
d_subshell_average_electron_energies );
ar & boost::serialization::make_nvp( "radiative_transition_probabilities",
d_radiative_transition_probabilities );
ar & boost::serialization::make_nvp( "radiative_transition_energies",
d_radiative_transition_energies );
ar & boost::serialization::make_nvp( "non_radiative_transition_probabilities",
d_non_radiative_transition_probabilities );
ar & boost::serialization::make_nvp( "non_radiative_transition_energies",
d_non_radiative_transition_energies );
//---------------------------------------------------------------------------//
// THE COHERENT PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "coherent_cross_section_energy_grid",
d_coherent_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "coherent_cross_section",
d_coherent_cross_section );
ar & boost::serialization::make_nvp( "coherent_cross_section_interp_type",
d_coherent_cross_section_interp_type );
ar & boost::serialization::make_nvp( "coherent_form_factor_argument",
d_coherent_form_factor_argument );
ar & boost::serialization::make_nvp( "coherent_form_factor",
d_coherent_form_factor );
ar & boost::serialization::make_nvp( "coherent_form_factor_interp_type",
d_coherent_form_factor_interp_type );
ar & boost::serialization::make_nvp(
"coherent_imaginary_anomalous_scattering_factor_incident_energy",
d_coherent_imaginary_anomalous_scattering_factor_incident_energy );
ar & boost::serialization::make_nvp(
"coherent_imaginary_anomalous_scattering_factor",
d_coherent_imaginary_anomalous_scattering_factor );
ar & boost::serialization::make_nvp(
"coherent_imaginary_anomalous_scattering_factor_interp_type",
d_coherent_imaginary_anomalous_scattering_factor_interp_type );
ar & boost::serialization::make_nvp(
"coherent_real_anomalous_scattering_factor_incident_energy",
d_coherent_real_anomalous_scattering_factor_incident_energy );
ar & boost::serialization::make_nvp(
"coherent_real_anomalous_scattering_factor",
d_coherent_real_anomalous_scattering_factor );
ar & boost::serialization::make_nvp(
"coherent_real_anomalous_scattering_factor_interp_type",
d_coherent_real_anomalous_scattering_factor_interp_type );
ar & boost::serialization::make_nvp(
"coherent_average_photon_incident_energy",
d_coherent_average_photon_incident_energy );
ar & boost::serialization::make_nvp( "coherent_average_photon_energy",
d_coherent_average_photon_energy );
ar & boost::serialization::make_nvp(
"coherent_average_photon_energy_interp_type",
d_coherent_average_photon_energy_interp_type );
//---------------------------------------------------------------------------//
// THE INCOHERENT PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "incoherent_cross_section_energy_grid",
d_incoherent_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "incoherent_cross_section",
d_incoherent_cross_section );
ar & boost::serialization::make_nvp( "incoherent_cross_section_interp_type",
d_incoherent_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"incoherent_scattering_function_argument",
d_incoherent_scattering_function_argument );
ar & boost::serialization::make_nvp( "incoherent_scattering_function",
d_incoherent_scattering_function );
ar & boost::serialization::make_nvp(
"incoherent_scattering_function_interp_type",
d_incoherent_scattering_function_interp_type );
ar & boost::serialization::make_nvp(
"incoherent_average_photon_incident_energy",
d_incoherent_average_photon_incident_energy );
ar & boost::serialization::make_nvp( "incoherent_average_photon_energy",
d_incoherent_average_photon_energy );
ar & boost::serialization::make_nvp(
"incoherent_average_photon_energy_interp_type",
d_incoherent_average_photon_energy_interp_type );
ar & boost::serialization::make_nvp(
"incoherent_average_electron_incident_energy",
d_incoherent_average_electron_incident_energy );
ar & boost::serialization::make_nvp( "incoherent_average_electron_energy",
d_incoherent_average_electron_energy );
ar & boost::serialization::make_nvp(
"incoherent_average_electron_energy_interp_type",
d_incoherent_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// THE PHOTOELECTRIC PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"photoelectric_cross_section_energy_grid",
d_photoelectric_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "photoelectric_cross_section",
d_photoelectric_cross_section );
ar & boost::serialization::make_nvp(
"photoelectric_cross_section_interp_type",
d_photoelectric_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_average_residual_incident_energy",
d_photoelectric_average_residual_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_average_residual_energy",
d_photoelectric_average_residual_energy );
ar & boost::serialization::make_nvp(
"photoelectric_average_residual_energy_interp_type",
d_photoelectric_average_residual_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_photons_incident_energy",
d_photoelectric_secondary_photons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_photons_energy",
d_photoelectric_secondary_photons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_photons_energy_interp_type",
d_photoelectric_secondary_photons_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_electrons_incident_energy",
d_photoelectric_secondary_electrons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_electrons_energy",
d_photoelectric_secondary_electrons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_secondary_electrons_energy_interp_type",
d_photoelectric_secondary_electrons_energy_interp_type );
//---------------------------------------------------------------------------//
// THE PHOTOELECTRIC PHOTON DATA BY SUBSHELL
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"photoelectric_subshell_cross_section_energy_grid",
d_photoelectric_subshell_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "photoelectric_subshell_cross_section",
d_photoelectric_subshell_cross_section );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_cross_section_interp_type",
d_photoelectric_subshell_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_average_residual_incident_energy",
d_photoelectric_subshell_average_residual_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_average_residual_energy",
d_photoelectric_subshell_average_residual_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_average_residual_energy_interp_type",
d_photoelectric_subshell_average_residual_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_photons_incident_energy",
d_photoelectric_subshell_secondary_photons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_photons_energy",
d_photoelectric_subshell_secondary_photons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_photons_energy_interp_type",
d_photoelectric_subshell_secondary_photons_energy_interp_type );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_electrons_incident_energy",
d_photoelectric_subshell_secondary_electrons_incident_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_electrons_energy",
d_photoelectric_subshell_secondary_electrons_energy );
ar & boost::serialization::make_nvp(
"photoelectric_subshell_secondary_electrons_energy_interp_type",
d_photoelectric_subshell_secondary_electrons_energy_interp_type );
//---------------------------------------------------------------------------//
// THE PAIR PRODUCTION PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"pair_production_cross_section_energy_grid",
d_pair_production_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "pair_production_cross_section",
d_pair_production_cross_section );
ar & boost::serialization::make_nvp(
"pair_production_cross_section_interp_type",
d_pair_production_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"pair_production_average_positron_incident_energy",
d_pair_production_average_positron_incident_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_positron_energy",
d_pair_production_average_positron_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_positron_energy_interp_type",
d_pair_production_average_positron_energy_interp_type );
ar & boost::serialization::make_nvp(
"pair_production_average_electron_incident_energy",
d_pair_production_average_electron_incident_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_electron_energy",
d_pair_production_average_electron_energy );
ar & boost::serialization::make_nvp(
"pair_production_average_electron_energy_interp_type",
d_pair_production_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// THE TRIPLET PRODUCTION PHOTON DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"triplet_production_cross_section_energy_grid",
d_triplet_production_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "triplet_production_cross_section",
d_triplet_production_cross_section );
ar & boost::serialization::make_nvp(
"triplet_production_cross_section_interp_type",
d_triplet_production_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"triplet_production_average_positron_incident_energy",
d_triplet_production_average_positron_incident_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_positron_energy",
d_triplet_production_average_positron_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_positron_energy_interp_type",
d_triplet_production_average_positron_energy_interp_type );
ar & boost::serialization::make_nvp(
"triplet_production_average_electron_incident_energy",
d_triplet_production_average_electron_incident_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_electron_energy",
d_triplet_production_average_electron_energy );
ar & boost::serialization::make_nvp(
"triplet_production_average_electron_energy_interp_type",
d_triplet_production_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// ELASTIC DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp( "elastic_energy_grid",
d_elastic_energy_grid );
ar & boost::serialization::make_nvp( "elastic_transport_cross_section",
d_elastic_transport_cross_section );
ar & boost::serialization::make_nvp(
"elastic_transport_cross_section_interp_type",
d_elastic_transport_cross_section_interp_type );
ar & boost::serialization::make_nvp( "cutoff_elastic_cross_section",
d_cutoff_elastic_cross_section );
ar & boost::serialization::make_nvp(
"cutoff_elastic_cross_section_interp_type",
d_cutoff_elastic_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"cutoff_elastic_residual_incident_energy",
d_cutoff_elastic_residual_incident_energy );
ar & boost::serialization::make_nvp( "cutoff_elastic_residual_energy",
d_cutoff_elastic_residual_energy );
ar & boost::serialization::make_nvp(
"cutoff_elastic_residual_energy_interp_type",
d_cutoff_elastic_residual_energy_interp_type );
ar & boost::serialization::make_nvp(
"cutoff_elastic_scattered_electron_incident_energy",
d_cutoff_elastic_scattered_electron_incident_energy );
ar & boost::serialization::make_nvp(
"cutoff_elastic_scattered_electron_energy",
d_cutoff_elastic_scattered_electron_energy );
ar & boost::serialization::make_nvp(
"cutoff_elastic_scattered_electron_energy_interp_type",
d_cutoff_elastic_scattered_electron_energy_interp_type );
ar & boost::serialization::make_nvp( "cutoff_elastic_angular_energy_grid",
d_cutoff_elastic_angular_energy_grid );
ar & boost::serialization::make_nvp( "cutoff_elastic_angles",
d_cutoff_elastic_angles );
ar & boost::serialization::make_nvp( "cutoff_elastic_pdf",
d_cutoff_elastic_pdf );
ar & boost::serialization::make_nvp( "cutoff_elastic_pdf_interp_type",
d_cutoff_elastic_pdf_interp_type );
ar & boost::serialization::make_nvp( "total_elastic_cross_section",
d_total_elastic_cross_section );
ar & boost::serialization::make_nvp(
"total_elastic_cross_section_interp_type",
d_total_elastic_cross_section_interp_type );
/*
ar & boost::serialization::make_nvp(
"screened_rutherford_elastic_cross_section",
d_screened_rutherford_elastic_cross_section );
ar & boost::serialization::make_nvp(
"screened_rutherford_normalization_constant",
d_screened_rutherford_normalization_constant );
ar & boost::serialization::make_nvp( "moliere_screening_constant",
d_moliere_screening_constant );
*/
//---------------------------------------------------------------------------//
// ELECTROIONIZATION DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"electroionization_subshell_cross_section_energy_grid",
d_electroionization_subshell_cross_section_energy_grid );
ar & boost::serialization::make_nvp(
"electroionization_subshell_cross_section",
d_electroionization_subshell_cross_section );
ar & boost::serialization::make_nvp(
"electroionization_subshell_cross_section_interp_type",
d_electroionization_subshell_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"electroionization_average_scattered_electron_incident_energy",
d_electroionization_average_scattered_electron_incident_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_scattered_electron_energy",
d_electroionization_average_scattered_electron_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_scattered_electron_energy_interp_type",
d_electroionization_average_scattered_electron_energy_interp_type );
ar & boost::serialization::make_nvp(
"electroionization_average_recoil_electron_incident_energy",
d_electroionization_average_recoil_electron_incident_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_recoil_electron_energy",
d_electroionization_average_recoil_electron_energy );
ar & boost::serialization::make_nvp(
"electroionization_average_recoil_electron_energy_interp_type",
d_electroionization_average_recoil_electron_energy_interp_type );
ar & boost::serialization::make_nvp( "electroionization_recoil_energy_grid",
d_electroionization_recoil_energy_grid );
ar & boost::serialization::make_nvp( "electroionization_recoil_energy",
d_electroionization_recoil_energy );
ar & boost::serialization::make_nvp( "electroionization_recoil_pdf",
d_electroionization_recoil_pdf );
ar & boost::serialization::make_nvp(
"electroionization_recoil_pdf_interp_type",
d_electroionization_recoil_pdf_interp_type );
//---------------------------------------------------------------------------//
// BREMSSTRAHLUNG DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"bremsstrahlung_cross_section_energy_grid",
d_bremsstrahlung_cross_section_energy_grid );
ar & boost::serialization::make_nvp( "bremsstrahlung_cross_section",
d_bremsstrahlung_cross_section );
ar & boost::serialization::make_nvp(
"bremsstrahlung_cross_section_interp_type",
d_bremsstrahlung_cross_section_interp_type );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_photon_incident_energy",
d_bremsstrahlung_average_photon_incident_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_photon_energy",
d_bremsstrahlung_average_photon_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_photon_energy_interp_type",
d_bremsstrahlung_average_photon_energy_interp_type );
ar & boost::serialization::make_nvp( "bremsstrahlung_photon_energy_grid",
d_bremsstrahlung_photon_energy_grid );
ar & boost::serialization::make_nvp( "bremsstrahlung_photon_energy",
d_bremsstrahlung_photon_energy );
ar & boost::serialization::make_nvp( "bremsstrahlung_photon_pdf",
d_bremsstrahlung_photon_pdf );
ar & boost::serialization::make_nvp(
"bremsstrahlung_photon_pdf_interp_type",
d_bremsstrahlung_photon_pdf_interp_type );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_electron_incident_energy",
d_bremsstrahlung_average_electron_incident_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_electron_energy",
d_bremsstrahlung_average_electron_energy );
ar & boost::serialization::make_nvp(
"bremsstrahlung_average_electron_energy_interp_type",
d_bremsstrahlung_average_electron_energy_interp_type );
//---------------------------------------------------------------------------//
// ATOMIC EXCITATION DATA
//---------------------------------------------------------------------------//
ar & boost::serialization::make_nvp(
"atomic_excitation_energy_grid",
d_atomic_excitation_energy_grid );
ar & boost::serialization::make_nvp( "atomic_excitation_cross_section",
d_atomic_excitation_cross_section );
ar & boost::serialization::make_nvp(
"atomic_excitation_cross_section_interp_type",
d_atomic_excitation_cross_section_interp_type );
ar & boost::serialization::make_nvp( "atomic_excitation_energy_loss",
d_atomic_excitation_energy_loss );
ar & boost::serialization::make_nvp(
"atomic_excitation_energy_loss_interp_type",
d_atomic_excitation_energy_loss_interp_type );
}
} // end Data namespace
#endif // end DATA_ENDL_DATA_CONTAINER_DEF_HPP
//---------------------------------------------------------------------------//
// end Data_ENDLDataContainer_def.hpp
//---------------------------------------------------------------------------//
| 47.662882 | 111 | 0.730128 | [
"vector"
] |
dd98c495f1e19043996545b59bd35bb4e0e64d3d | 343 | cpp | C++ | leet_code/arrays/XgraterthanX.cpp | sahilduhan/codeforces | a8042d52c12806e026fd7027e35e97ed8b4eeed6 | [
"MIT"
] | null | null | null | leet_code/arrays/XgraterthanX.cpp | sahilduhan/codeforces | a8042d52c12806e026fd7027e35e97ed8b4eeed6 | [
"MIT"
] | null | null | null | leet_code/arrays/XgraterthanX.cpp | sahilduhan/codeforces | a8042d52c12806e026fd7027e35e97ed8b4eeed6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int specialArray(vector<int> &nums)
{
int result=0;
for(int i=0;i<nums.size(); i++)
{
if(nums[i]>= nums.size()+1) result++;
}
if(result==0) result=-1;
return result;
}
};
int main()
{
return 0;
} | 16.333333 | 49 | 0.501458 | [
"vector"
] |
dd9fec0a2682f92ce6cb225db5206c9c9ae2f034 | 17,681 | cpp | C++ | client/ui/UIBase.cpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 6 | 2015-01-03T08:18:16.000Z | 2022-01-22T00:01:23.000Z | client/ui/UIBase.cpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 1 | 2021-10-03T19:07:56.000Z | 2021-10-03T19:07:56.000Z | client/ui/UIBase.cpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 1 | 2021-10-03T19:29:40.000Z | 2021-10-03T19:29:40.000Z | //
// UIBase.cpp
//
/**
* @module global
* @submodule UI
*/
/**
* @class Base
* @namespace UI
*/
#include "UIBase.hpp"
#include "../InputManager.hpp"
#include "../ScriptEnvironment.hpp"
#include "../../common/unicode.hpp"
#include <DxLib.h>
#include <algorithm>
UIBase::UIBase() :
hover_flag_(false)
{
}
UIBase::~UIBase()
{
parent_.Dispose();
for (auto it = children_.begin(); it != children_.end(); ++it) {
auto child = *it;
child.Dispose();
}
}
void UIBase::ProcessInput(InputManager* input)
{
}
void UIBase::Update()
{
};
void UIBase::Draw()
{
if(!children_.empty()){
DrawChildren();
}
}
void UIBase::AsyncUpdate()
{
AsyncUpdateChildren();
}
void UIBase::UpdatePosition()
{
int parent_x_,
parent_y_,
parent_width_,
parent_height_;
// 親のサイズを取得
if (parent_.IsEmpty()) {
parent_x_ = 0;
parent_y_ = 0;
GetScreenState(&parent_width_, &parent_height_, nullptr);
} else {
// UIBasePtr parent_ptr = *static_cast<UIBasePtr*>(parent_->GetPointerFromInternalField(0));
UIBasePtr parent_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(parent_->GetInternalField(0))->Value());
parent_x_ = parent_ptr->absolute_x();
parent_y_ = parent_ptr->absolute_y();
parent_width_ = parent_ptr->absolute_width();
parent_height_ = parent_ptr->absolute_height();
}
// 幅を計算
if ((docking_ & DOCKING_LEFT) && (docking_ & DOCKING_RIGHT)) {
int left = parent_x_ + left_;
int right = parent_x_ + parent_width_ - right_;
absolute_rect_.width = right - left;
} else {
absolute_rect_.width = width_;
}
// 高さを計算
if ((docking_ & DOCKING_TOP) && (docking_ & DOCKING_BOTTOM)) {
int top = parent_y_ + top_;
int bottom = parent_y_ + parent_height_ - bottom_;
absolute_rect_.height = bottom - top;
} else {
absolute_rect_.height = height_;
}
// 左上X座標を計算
if (docking_ & DOCKING_HCENTER) {
absolute_rect_.x = parent_x_ + parent_width_ / 2 - absolute_rect_.width / 2;
} else if (docking_ & DOCKING_RIGHT) {
absolute_rect_.x = parent_x_ + parent_width_ - right_ - absolute_rect_.width;
} else {
absolute_rect_.x = parent_x_ + left_;
}
// 左上Y座標を計算
if (docking_ & DOCKING_VCENTER) {
absolute_rect_.y = parent_y_ + parent_height_ / 2 - absolute_rect_.height / 2;
} else if (docking_ & DOCKING_BOTTOM) {
absolute_rect_.y = parent_y_ + parent_height_ - bottom_ - absolute_rect_.height;
} else {
absolute_rect_.y = parent_y_ + top_;
}
}
Handle<Value> UIBase::Function_addChild(const Arguments& args)
{
assert(args.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(args.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(args.This()->GetInternalField(0))->Value());
assert(self);
if (args.Length() > 0 && args[0]->IsObject()) {
auto child = args[0]->ToObject();
if (args.This() != child) {
// UIBasePtr child_ptr = *static_cast<UIBasePtr*>(child->GetPointerFromInternalField(0));
UIBasePtr child_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(child->GetInternalField(0))->Value());
child_ptr->set_parent(args.This());
self->children_.push_back(Persistent<Object>::New(child));
}
}
return args.This();
}
Handle<Value> UIBase::Function_removeChild(const Arguments& args)
{
assert(args.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(args.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(args.This()->GetInternalField(0))->Value());
assert(self);
if (args.Length() > 0 && args[0]->IsObject()) {
auto child = args[0]->ToObject();
auto it = std::find(self->children_.begin(), self->children_.end(), child);
if (it != self->children_.end()) {
// UIBasePtr child_ptr = *static_cast<UIBasePtr*>((*it)->GetPointerFromInternalField(0));
UIBasePtr child_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast((*it)->GetInternalField(0))->Value());
child_ptr->set_parent(Handle<Object>());
self->children_.erase(it);
}
}
return args.This();
}
Handle<Value> UIBase::Function_parent(const Arguments& args)
{
assert(args.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(args.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(args.This()->GetInternalField(0))->Value());
assert(self);
if (!self->parent_.IsEmpty()) {
return self->parent_;
} else {
return Undefined();
}
}
Handle<Value> UIBase::Property_visible(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Boolean::New(self->visible_);
}
void UIBase::Property_set_visible(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->visible_ = value->ToBoolean()->BooleanValue();
}
Handle<Value> UIBase::Property_width(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->width_);
}
void UIBase::Property_set_width(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->width_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_height(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->height_);
}
void UIBase::Property_set_height(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->height_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_top(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->top_);
}
void UIBase::Property_set_top(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->top_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_left(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->left_);
}
void UIBase::Property_set_left(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->left_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_right(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->right_);
}
void UIBase::Property_set_right(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->right_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_bottom(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->bottom_);
}
void UIBase::Property_set_bottom(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->bottom_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_docking(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return Integer::New(self->docking_);
}
void UIBase::Property_set_docking(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
self->docking_ = value->ToInteger()->IntegerValue();
}
Handle<Value> UIBase::Property_on_click(Local<String> property, const AccessorInfo &info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
return self->on_click_;
}
void UIBase::Property_set_on_click(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
assert(info.This()->InternalFieldCount() > 0);
// UIBasePtr self = *static_cast<UIBasePtr*>(info.This()->GetPointerFromInternalField(0));
UIBasePtr self = *static_cast<UIBasePtr*>(Local<External>::Cast(info.This()->GetInternalField(0))->Value());
if (value->IsFunction()) {
self->on_click_ = Persistent<Function>::New(value.As<Function>());
}
}
void UIBase::DefineInstanceTemplate(Handle<ObjectTemplate>* object)
{
Handle<ObjectTemplate>& instance_template = *object;
/**
* UIオブジェクトに子供を追加します
*
* @method addChild
* @param {UIObject} child
* @return {UIObject} 自分自身
* @chainable
*/
SetFunction(&instance_template, "addChild", Function_addChild);
/**
* UIオブジェクトから子供を削除します
*
* @method removeChild
* @param {UIObject} child
* @return {UIObject} 自分自身
* @chainable
*/
SetFunction(&instance_template, "removeChild", Function_removeChild);
/**
* 親オブジェクトを返します
*
* @method parent
* @return {UIObject|Undefined} 親オブジェクト
*/
SetFunction(&instance_template, "parent", Function_parent);
/**
* UIObjectの幅(px)
*
* @property width
* @type Integer
*/
SetProperty(&instance_template, "width", Property_width, Property_set_width);
/**
* UIObjectの高さ(px)
*
* @property height
* @type Integer
*/
SetProperty(&instance_template, "height", Property_height, Property_set_height);
/**
* UIObjectの上余白(px)
*
* @property top
* @type Integer
* @default 12
*/
SetProperty(&instance_template, "top", Property_top, Property_set_top);
/**
* UIObjectの左余白(px)
*
* @property left
* @type Integer
* @default 12
*/
SetProperty(&instance_template, "left", Property_left, Property_set_left);
/**
* UIObjectの下余白(px)
*
* @property bottom
* @type Integer
* @default 12
*/
SetProperty(&instance_template, "bottom", Property_bottom, Property_set_bottom);
/**
* UIObjectの右余白(px)
*
* @property right
* @type Integer
* @default 12
*/
SetProperty(&instance_template, "right", Property_right, Property_set_right);
/**
* UIObjectがどの方向に対して固定余白を持つか指定します
*
* @property docking
* @type Integer
* @default UI.DOCKING_TOP | UI.DOCKING_LEFT
*/
SetProperty(&instance_template, "docking", Property_docking, Property_set_docking);
/**
* UIObjectの可視状態
*
* @property visible
* @type Boolean
* @default true
*/
SetProperty(&instance_template, "visible", Property_visible, Property_set_visible);
SetProperty(&instance_template, "onclick", Property_on_click, Property_set_on_click);
}
void UIBase::ProcessInputChildren(InputManager* input)
{
for (auto it = children_.begin(); it != children_.end(); ++it) {
auto child = *it;
// UIBasePtr child_ptr = *static_cast<UIBasePtr*>(child->GetPointerFromInternalField(0));
UIBasePtr child_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(child->GetInternalField(0))->Value());
child_ptr->ProcessInput(input);
}
}
void UIBase::UpdateChildren()
{
for (auto it = children_.begin(); it != children_.end(); ++it) {
auto child = *it;
// UIBasePtr child_ptr = *static_cast<UIBasePtr*>(child->GetPointerFromInternalField(0));
UIBasePtr child_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(child->GetInternalField(0))->Value());
child_ptr->Update();
}
}
void UIBase::DrawChildren()
{
for (auto it = children_.begin(); it != children_.end(); ++it) {
auto child = *it;
// UIBasePtr child_ptr = *static_cast<UIBasePtr*>(child->GetPointerFromInternalField(0));
UIBasePtr child_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(child->GetInternalField(0))->Value());
child_ptr->Draw();
}
}
void UIBase::AsyncUpdateChildren()
{
for (auto it = children_.begin(); it != children_.end(); ++it) {
auto child = *it;
// UIBasePtr child_ptr = *static_cast<UIBasePtr*>(child->GetPointerFromInternalField(0));
UIBasePtr child_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(child->GetInternalField(0))->Value());
child_ptr->AsyncUpdate();
}
}
void UIBase::UpdateBaseImage()
{
}
void UIBase::GetParam(const Handle<Object>& object, const std::string& name, int* value)
{
Handle<String> key = String::New(name.c_str());
if (object->Has(key)) {
*value = object->Get(key)->ToInteger()->Value();
}
}
void UIBase::GetParam(const Handle<Object>& object, const std::string& name, bool* value)
{
Handle<String> key = String::New(name.c_str());
if (object->Has(key)) {
*value = object->Get(key)->ToBoolean()->Value();
}
}
void UIBase::GetParam(const Handle<Object>& object, const std::string& name,
std::string* value)
{
Handle<String> key = String::New(name.c_str());
if (object->Has(key)) {
*value = std::string(
*v8::String::Utf8Value(object->Get(key)->ToString()));
}
}
void UIBase::Focus()
{
if (!parent_.IsEmpty()) {
// UIBasePtr parent_ptr = *static_cast<UIBasePtr*>(parent_->GetPointerFromInternalField(0));
UIBasePtr parent_ptr = *static_cast<UIBasePtr*>(Local<External>::Cast(parent_->GetInternalField(0))->Value());
parent_ptr->Focus();
}
focus_index_ = ++max_focus_index;
}
Handle<Object> UIBase::parent() const
{
return parent_;
}
void UIBase::set_parent(const Handle<Object>& parent)
{
parent_ = Persistent<Object>::New(parent);
}
UIBasePtr UIBase::parent_c() const
{
return parent_c_;
}
void UIBase::set_parent_c(const UIBasePtr& parent)
{
parent_c_ = parent;
}
Input* UIBase::input_adpator() const
{
return input_adaptor_;
}
void UIBase::set_input_adaptor(Input* adaptor)
{
input_adaptor_ = adaptor;
}
size_t UIBase::children_size() const
{
return children_.size();
}
| 32.925512 | 115 | 0.673152 | [
"object"
] |
ddac047275ce910a8f36547f05064b27f926b74e | 561 | cpp | C++ | 747. Largest Number At Least Twice of Others/src/main.cpp | zhenkunhe/LeetCode | 17a9a4d63d21888c7e7d300d5e29201f8621fd63 | [
"MIT"
] | null | null | null | 747. Largest Number At Least Twice of Others/src/main.cpp | zhenkunhe/LeetCode | 17a9a4d63d21888c7e7d300d5e29201f8621fd63 | [
"MIT"
] | null | null | null | 747. Largest Number At Least Twice of Others/src/main.cpp | zhenkunhe/LeetCode | 17a9a4d63d21888c7e7d300d5e29201f8621fd63 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int dominantIndex(vector<int>& nums)
{
if ( nums.size() == 0 ) return -1;
int max = 0, sec = 0, size = nums.size();
for (int i = 1; i < size; i++)
{
if ( nums[i] > nums[max] )
{
sec = max;
max = i;
}
else if ( nums[i] > nums[sec] || max == sec ) sec = i;
}
return (nums[max] >= nums[sec] * 2 || max == sec) ? max : -1;
}
};
int main()
{
Solution s;
vector<int> nums { 3, 6, 1, 0 };
cout << s.dominantIndex(nums) << endl;
return 0;
}
| 16.028571 | 63 | 0.529412 | [
"vector"
] |
ddae5ff891313ebd91e2327d48ff89f3a483df1d | 17,260 | cc | C++ | test/test_communicator_send_recv.cc | mlund/mpl | 7324df0d86b9c03fb5a9526c0216455a843a0f23 | [
"BSD-3-Clause"
] | 94 | 2015-09-22T12:04:21.000Z | 2022-03-29T07:32:06.000Z | test/test_communicator_send_recv.cc | mlund/mpl | 7324df0d86b9c03fb5a9526c0216455a843a0f23 | [
"BSD-3-Clause"
] | 28 | 2015-11-25T17:36:50.000Z | 2022-03-28T22:56:41.000Z | test/test_communicator_send_recv.cc | mlund/mpl | 7324df0d86b9c03fb5a9526c0216455a843a0f23 | [
"BSD-3-Clause"
] | 19 | 2015-11-24T22:00:25.000Z | 2022-02-15T01:17:25.000Z | #define BOOST_TEST_MODULE communicator_send_recv
#include <boost/test/included/unit_test.hpp>
#include <limits>
#include <cstddef>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <tuple>
#include <utility>
#include <algorithm>
#include <mpl/mpl.hpp>
#include "test_helper.hpp"
template<typename T>
bool send_recv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0)
comm_world.send(data, 1);
if (comm_world.rank() == 1) {
T data_r;
comm_world.recv(data_r, 0);
return data_r == data;
}
return true;
}
template<typename T>
bool send_recv_iter_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0)
comm_world.send(std::begin(data), std::end(data), 1);
if (comm_world.rank() == 1) {
T data_r;
if constexpr (std::is_const_v<std::remove_reference_t<decltype(*std::begin(data_r))>>) {
comm_world.recv(data_r, 0);
return data_r == data;
} else {
if constexpr (has_resize<T>())
data_r.resize(data.size());
comm_world.recv(std::begin(data_r), std::end(data_r), 0);
return data_r == data;
}
}
return true;
}
template<typename T>
bool bsend_recv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
int size;
if constexpr (has_size<T>::value)
size = comm_world.bsend_size<typename T::value_type>(data.size());
else
size = comm_world.bsend_size<T>();
mpl::bsend_buffer buff(size);
comm_world.bsend(data, 1);
}
if (comm_world.rank() == 1) {
T data_r;
comm_world.recv(data_r, 0);
return data_r == data;
}
return true;
}
template<typename T>
bool bsend_recv_iter_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
int size;
if constexpr (has_size<T>::value)
size = comm_world.bsend_size<typename T::value_type>(data.size());
else
size = comm_world.bsend_size<T>();
mpl::bsend_buffer buff(size);
comm_world.bsend(std::begin(data), std::end(data), 1);
}
if (comm_world.rank() == 1) {
T data_r;
if constexpr (std::is_const_v<std::remove_reference_t<decltype(*std::begin(data_r))>>) {
T data_r;
comm_world.recv(data_r, 0);
return data_r == data;
} else {
if constexpr (has_resize<T>())
data_r.resize(data.size());
comm_world.recv(std::begin(data_r), std::end(data_r), 0);
return data_r == data;
}
}
return true;
}
template<typename T>
bool ssend_recv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0)
comm_world.ssend(data, 1);
if (comm_world.rank() == 1) {
T data_r;
comm_world.recv(data_r, 0);
return data_r == data;
}
return true;
}
template<typename T>
bool ssend_recv_iter_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0)
comm_world.ssend(std::begin(data), std::end(data), 1);
if (comm_world.rank() == 1) {
T data_r;
if constexpr (std::is_const_v<std::remove_reference_t<decltype(*std::begin(data_r))>>) {
comm_world.recv(data_r, 0);
return data_r == data;
} else {
if constexpr (has_resize<T>())
data_r.resize(data.size());
comm_world.recv(std::begin(data_r), std::end(data_r), 0);
return data_r == data;
}
}
return true;
}
template<typename T>
bool rsend_recv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
comm_world.barrier();
comm_world.rsend(data, 1);
} else if (comm_world.rank() == 1) {
// must ensure that MPI_Recv is called before mpl::communicator::rsend
if constexpr (has_begin_end<T>() and has_size<T>() and has_resize<T>()) {
// T is an STL container
T data_r;
data_r.resize(data.size());
mpl::irequest r{comm_world.irecv(begin(data_r), end(data_r), 0)};
comm_world.barrier();
r.wait();
return data_r == data;
} else if constexpr (has_begin_end<T>() and has_size<T>()) {
// T is an STL container without resize member, e.g., std::set
std::vector<typename T::value_type> data_r;
data_r.resize(data.size());
mpl::irequest r{comm_world.irecv(begin(data_r), end(data_r), 0)};
comm_world.barrier();
r.wait();
return std::equal(begin(data_r), end(data_r), begin(data));
} else {
// T is some fundamental type
// mpl::communicator::irecv does not suffice in the cases above as the irecv performs a
// probe first to receive STL containers
T data_r;
mpl::irequest r{comm_world.irecv(data_r, 0)};
comm_world.barrier();
r.wait();
return data_r == data;
}
} else
comm_world.barrier();
return true;
}
template<typename T>
bool rsend_recv_iter_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
comm_world.barrier();
comm_world.rsend(std::begin(data), std::end(data), 1);
} else if (comm_world.rank() == 1) {
// must ensure that MPI_Recv is called before mpl::communicator::rsend
if constexpr (has_begin_end<T>() and has_size<T>() and has_resize<T>()) {
T data_r;
data_r.resize(data.size());
mpl::irequest r{comm_world.irecv(begin(data_r), end(data_r), 0)};
comm_world.barrier();
r.wait();
return data_r == data;
} else if constexpr (has_begin_end<T>() and has_size<T>()) {
// T is an STL container without resize member, e.g., std::set
std::vector<typename T::value_type> data_r;
data_r.resize(data.size());
mpl::irequest r{comm_world.irecv(begin(data_r), end(data_r), 0)};
comm_world.barrier();
r.wait();
return std::equal(begin(data_r), end(data_r), begin(data));
} else {
// T is some fundamental type
// mpl::communicator::irecv does not suffice in the cases above as the irecv performs a
// probe first to receive STL containers
T data_r;
mpl::irequest r{comm_world.irecv(data_r, 0)};
comm_world.barrier();
r.wait();
return data_r == data;
}
} else
comm_world.barrier();
return true;
}
BOOST_AUTO_TEST_CASE(send_recv) {
// integer types
BOOST_TEST(send_recv_test(std::byte(77)));
BOOST_TEST(send_recv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(send_recv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(send_recv_test(static_cast<wchar_t>('A')));
BOOST_TEST(send_recv_test(static_cast<char16_t>('A')));
BOOST_TEST(send_recv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(send_recv_test(static_cast<float>(3.14)));
BOOST_TEST(send_recv_test(static_cast<double>(3.14)));
BOOST_TEST(send_recv_test(static_cast<long double>(3.14)));
BOOST_TEST(send_recv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(send_recv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(send_recv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(send_recv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(send_recv_test(my_enum::val));
// pairs, tuples and arrays
BOOST_TEST(send_recv_test(std::pair<int, double>{1, 2.3}));
BOOST_TEST(send_recv_test(std::tuple<int, double, bool>{1, 2.3, true}));
BOOST_TEST(send_recv_test(std::array<int, 5>{1, 2, 3, 4, 5}));
// strings and STL containers
BOOST_TEST(send_recv_test(std::string{"Hello World"}));
BOOST_TEST(send_recv_test(std::wstring{L"Hello World"}));
BOOST_TEST(send_recv_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(send_recv_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(send_recv_test(std::set<int>{1, 2, 3, 4, 5}));
// iterators
BOOST_TEST(send_recv_iter_test(std::array<int, 5>{1, 2, 3, 4, 5}));
BOOST_TEST(send_recv_iter_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(send_recv_iter_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(send_recv_iter_test(std::set<int>{1, 2, 3, 4, 5}));
}
BOOST_AUTO_TEST_CASE(bsend_recv) {
// integer types
BOOST_TEST(bsend_recv_test(std::byte(77)));
BOOST_TEST(bsend_recv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(bsend_recv_test(static_cast<wchar_t>('A')));
BOOST_TEST(bsend_recv_test(static_cast<char16_t>('A')));
BOOST_TEST(bsend_recv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(bsend_recv_test(static_cast<float>(3.14)));
BOOST_TEST(bsend_recv_test(static_cast<double>(3.14)));
BOOST_TEST(bsend_recv_test(static_cast<long double>(3.14)));
BOOST_TEST(bsend_recv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(bsend_recv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(bsend_recv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(bsend_recv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(bsend_recv_test(my_enum::val));
// pairs, tuples and arrays
BOOST_TEST(bsend_recv_test(std::pair<int, double>{1, 2.3}));
BOOST_TEST(bsend_recv_test(std::tuple<int, double, bool>{1, 2.3, true}));
BOOST_TEST(bsend_recv_test(std::array<int, 5>{1, 2, 3, 4, 5}));
// strings and STL containers
BOOST_TEST(bsend_recv_test(std::string{"Hello World"}));
BOOST_TEST(bsend_recv_test(std::wstring{L"Hello World"}));
BOOST_TEST(bsend_recv_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(bsend_recv_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(bsend_recv_test(std::set<int>{1, 2, 3, 4, 5}));
// iterators
BOOST_TEST(bsend_recv_iter_test(std::array<int, 5>{1, 2, 3, 4, 5}));
BOOST_TEST(bsend_recv_iter_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(bsend_recv_iter_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(bsend_recv_iter_test(std::set<int>{1, 2, 3, 4, 5}));
}
BOOST_AUTO_TEST_CASE(ssend_recv) {
// integer types
BOOST_TEST(ssend_recv_test(std::byte(77)));
BOOST_TEST(ssend_recv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(ssend_recv_test(static_cast<wchar_t>('A')));
BOOST_TEST(ssend_recv_test(static_cast<char16_t>('A')));
BOOST_TEST(ssend_recv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(ssend_recv_test(static_cast<float>(3.14)));
BOOST_TEST(ssend_recv_test(static_cast<double>(3.14)));
BOOST_TEST(ssend_recv_test(static_cast<long double>(3.14)));
BOOST_TEST(ssend_recv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(ssend_recv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(ssend_recv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(ssend_recv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(ssend_recv_test(my_enum::val));
// pairs, tuples and arrays
BOOST_TEST(ssend_recv_test(std::pair<int, double>{1, 2.3}));
BOOST_TEST(ssend_recv_test(std::tuple<int, double, bool>{1, 2.3, true}));
BOOST_TEST(ssend_recv_test(std::array<int, 5>{1, 2, 3, 4, 5}));
// strings and STL containers
BOOST_TEST(ssend_recv_test(std::string{"Hello World"}));
BOOST_TEST(ssend_recv_test(std::wstring{L"Hello World"}));
BOOST_TEST(ssend_recv_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(ssend_recv_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(ssend_recv_test(std::set<int>{1, 2, 3, 4, 5}));
// iterators
BOOST_TEST(ssend_recv_iter_test(std::array<int, 5>{1, 2, 3, 4, 5}));
BOOST_TEST(ssend_recv_iter_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(ssend_recv_iter_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(ssend_recv_iter_test(std::set<int>{1, 2, 3, 4, 5}));
}
BOOST_AUTO_TEST_CASE(rsend_recv) {
// integer types
BOOST_TEST(rsend_recv_test(std::byte(77)));
BOOST_TEST(rsend_recv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(rsend_recv_test(static_cast<wchar_t>('A')));
BOOST_TEST(rsend_recv_test(static_cast<char16_t>('A')));
BOOST_TEST(rsend_recv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(rsend_recv_test(static_cast<float>(3.14)));
BOOST_TEST(rsend_recv_test(static_cast<double>(3.14)));
BOOST_TEST(rsend_recv_test(static_cast<long double>(3.14)));
BOOST_TEST(rsend_recv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(rsend_recv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(rsend_recv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(rsend_recv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(rsend_recv_test(my_enum::val));
// pairs, tuples and arrays
BOOST_TEST(rsend_recv_test(std::pair<int, double>{1, 2.3}));
BOOST_TEST(rsend_recv_test(std::tuple<int, double, bool>{1, 2.3, true}));
BOOST_TEST(rsend_recv_test(std::array<int, 5>{1, 2, 3, 4, 5}));
// strings and STL containers
BOOST_TEST(rsend_recv_test(std::string{"Hello World"}));
BOOST_TEST(rsend_recv_test(std::wstring{L"Hello World"}));
BOOST_TEST(rsend_recv_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(rsend_recv_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(rsend_recv_test(std::set<int>{1, 2, 3, 4, 5}));
// iterators
BOOST_TEST(rsend_recv_iter_test(std::array<int, 5>{1, 2, 3, 4, 5}));
BOOST_TEST(rsend_recv_iter_test(std::vector<int>{1, 2, 3, 4, 5}));
BOOST_TEST(rsend_recv_iter_test(std::list<int>{1, 2, 3, 4, 5}));
BOOST_TEST(rsend_recv_iter_test(std::set<int>{1, 2, 3, 4, 5}));
}
| 40.803783 | 93 | 0.684705 | [
"vector"
] |
ddc394b91f0deda430d989718d15265b8e2950bb | 744 | cpp | C++ | contest/compfest/11/Training Home/Pemrograman Kompetitif Dasar/Math/D.cpp | andraantariksa/code-exercise-answer | 69b7dbdc081cdb094cb110a72bc0c9242d3d344d | [
"MIT"
] | 1 | 2019-11-06T15:17:48.000Z | 2019-11-06T15:17:48.000Z | contest/compfest/11/Training Home/Pemrograman Kompetitif Dasar/Math/D.cpp | andraantariksa/code-exercise-answer | 69b7dbdc081cdb094cb110a72bc0c9242d3d344d | [
"MIT"
] | null | null | null | contest/compfest/11/Training Home/Pemrograman Kompetitif Dasar/Math/D.cpp | andraantariksa/code-exercise-answer | 69b7dbdc081cdb094cb110a72bc0c9242d3d344d | [
"MIT"
] | 1 | 2018-11-13T08:43:26.000Z | 2018-11-13T08:43:26.000Z | #include <bits/stdc++.h>
using namespace std;
typedef short i16;
typedef unsigned short u16;
typedef int i32;
typedef unsigned int u32;
typedef long int i64;
typedef unsigned long int u64;
int main()
{
i64 N, K;
cin >> N >> K;
vector<bool> p_table(700001, true);
vector<i32> p_l;
p_table[1] = false;
for(i32 i = 2; i <= sqrt(700000); i++)
{
for(i32 j = i * i; j <= 700000; j += i)
{
if(p_table[j])
{
p_table[j] = false;
}
}
}
for(i32 i = 2; i <= 700000; i++)
{
if(p_table[i])
{
p_l.push_back(i);
}
}
for(i32 i = 0; i < N; i++)
{
printf("%d\n", p_l[i * K + 1 - 1]);
}
}
| 17.302326 | 47 | 0.459677 | [
"vector"
] |
ddc53772efef4dc00b191486831a9bd3b7e459ad | 2,079 | cc | C++ | cpp-standard-library/18.1.2.cc | ysuttep/books-exercise | 975a26dc4bee620160a8023dcdca323f6247a497 | [
"MIT"
] | null | null | null | cpp-standard-library/18.1.2.cc | ysuttep/books-exercise | 975a26dc4bee620160a8023dcdca323f6247a497 | [
"MIT"
] | null | null | null | cpp-standard-library/18.1.2.cc | ysuttep/books-exercise | 975a26dc4bee620160a8023dcdca323f6247a497 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <thread>
#include <map>
#include <vector>
#include <string>
std::string SupportXmlEncode(const std::string& container) {
std::string tmp = container;
if( tmp.empty() ) return tmp;
std::string::size_type pos = 0;
for (size_t i = 0; i < 10000; ++i)
{
pos = tmp.find_first_of("\"&<>", pos);
if (pos == std::string::npos) break;
std::string replacement;
switch (tmp[pos])
{
case '\"': replacement = """; break;
case '&': replacement = "&"; break;
case '<': replacement = "<"; break;
case '>': replacement = ">"; break;
default: ;
}
tmp.replace(pos, 1, replacement);
//std::cout << tmp << std::endl;
pos += replacement.size();
replacement.clear();
};
return tmp;
}
std::vector<std::string> SupportXmlEncode(const std::vector<std::string>& container)
{
std::vector<std::string> tmp = container;
if( tmp.empty() ) return tmp;
for(std::vector<std::string>::iterator itr = tmp.begin();
itr != tmp.end(); ++itr )
{
std::string tmp = SupportXmlEncode(*itr);
(*itr).clear();
(*itr) = tmp;
}
return tmp;
}
std::map<std::string,std::string> SupportXmlEncode(const std::map<std::string,std::string>& container)
{
std::map<std::string,std::string> tmp = container;
if( tmp.empty() ) return tmp;
for(std::map<std::string,std::string>::iterator itr = tmp.begin();
itr != container.end(); ++itr )
{
std::string tmp = SupportXmlEncode(itr->second);
(*itr).second.clear();
(*itr).second += tmp;
}
return tmp;
}
void TEST_F() {
std::string xmlstr = "djslfka&js\"dklfj<dj>dfj<dkfj";
std::cout << SupportXmlEncode(xmlstr) << std::endl;
std::vector<std::string> vecxmlstr (10, xmlstr);
std::vector<std::string> tmpresult = SupportXmlEncode(vecxmlstr);
std::cout << tmpresult[0] << std::endl;
}
int main(void) {
TEST_F();
}
| 25.9875 | 102 | 0.561809 | [
"vector"
] |
ddcaf390a2e782b641bf8f52fdd57854918c4e09 | 7,796 | cc | C++ | src/datetime/tasks/extract_field.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 67 | 2021-04-12T18:06:55.000Z | 2022-03-28T06:51:05.000Z | src/datetime/tasks/extract_field.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 2 | 2021-06-22T00:30:36.000Z | 2021-07-01T22:12:43.000Z | src/datetime/tasks/extract_field.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 6 | 2021-04-14T21:28:00.000Z | 2022-03-22T09:45:25.000Z | /* Copyright 2021 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "datetime/tasks/extract_field.h"
#include "column/column.h"
#include "util/allocator.h"
#include "deserializer.h"
namespace legate {
namespace pandas {
namespace datetime {
using namespace Legion;
using ColumnView = detail::Column;
namespace detail {
template <DatetimeFieldCode CODE>
struct Extractor;
template <>
struct Extractor<DatetimeFieldCode::YEAR> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_day = 86400000000000L;
const int z = ((t >= 0 ? t : t - (units_per_day - 1)) / units_per_day) + 719468;
const int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097);
const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
const int y = static_cast<int>(yoe) + era * 400;
const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
const unsigned mp = (5 * doy + 2) / 153;
const unsigned m = mp + (mp < 10 ? 3 : -9);
if (m <= 2)
return y + 1;
else
return y;
}
};
template <>
struct Extractor<DatetimeFieldCode::MONTH> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_day = 86400000000000L;
const int z = ((t >= 0 ? t : t - (units_per_day - 1)) / units_per_day) + 719468;
const int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097);
const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
const unsigned mp = (5 * doy + 2) / 153;
return mp + (mp < 10 ? 3 : -9);
}
};
template <>
struct Extractor<DatetimeFieldCode::DAY> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_day = 86400000000000L;
const int z = ((t >= 0 ? t : t - (units_per_day - 1)) / units_per_day) + 719468;
const int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097);
const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
const unsigned mp = (5 * doy + 2) / 153;
return doy - (153 * mp + 2) / 5 + 1;
}
};
template <>
struct Extractor<DatetimeFieldCode::HOUR> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_day = 86400000000000;
const int64_t units_per_hour = 3600000000000;
return t >= 0 ? ((t % units_per_day) / units_per_hour)
: ((units_per_day + (t % units_per_day)) / units_per_hour);
}
};
template <>
struct Extractor<DatetimeFieldCode::MINUTE> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_hour = 3600000000000;
const int64_t units_per_minute = 60000000000;
return t >= 0 ? ((t % units_per_hour) / units_per_minute)
: ((units_per_hour + (t % units_per_hour)) / units_per_minute);
}
};
template <>
struct Extractor<DatetimeFieldCode::SECOND> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_minute = 60000000000;
const int64_t units_per_second = 1000000000;
return t >= 0 ? ((t % units_per_minute) / units_per_second)
: ((units_per_minute + (t % units_per_minute)) / units_per_second);
}
};
template <>
struct Extractor<DatetimeFieldCode::WEEKDAY> {
// Copied from the cuDF code
constexpr int16_t operator()(const int64_t& t) const
{
const int64_t units_per_day = 86400000000000L;
const int z = ((t >= 0 ? t : t - (units_per_day - 1)) / units_per_day) + 719468;
const int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097);
const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
const unsigned mp = (5 * doy + 2) / 153;
const unsigned d = doy - (153 * mp + 2) / 5 + 1;
int m = mp + (mp < 10 ? 3 : -9);
int y = static_cast<int>(yoe) + era * 400;
// apply Zeller's algorithm
if (m <= 2) { y += 1; }
if (m == 1) {
m = 13;
y -= 1;
}
if (m == 2) {
m = 14;
y -= 1;
}
const unsigned k = y % 100;
const unsigned j = y / 100;
const unsigned h = (d + 13 * (m + 1) / 5 + k + k / 4 + j / 4 + 5 * j) % 7;
return (h - 2 + 7) % 7; // pandas convention Monday = 0
}
};
template <DatetimeFieldCode CODE>
ColumnView extract_field(const ColumnView& in, alloc::Allocator& allocator)
{
auto size = in.size();
auto p_in = in.column<int64_t>();
auto p_out = allocator.allocate_elements<int16_t>(size);
Extractor<CODE> extract{};
if (in.nullable()) {
auto in_b = in.bitmask();
for (auto idx = 0; idx < size; ++idx) {
if (!in_b.get(idx)) continue;
p_out[idx] = extract(p_in[idx]);
}
} else
for (auto idx = 0; idx < size; ++idx) p_out[idx] = extract(p_in[idx]);
return ColumnView(TypeCode::INT16, p_out, size);
}
ColumnView extract_field(const ColumnView& in, DatetimeFieldCode code, alloc::Allocator& allocator)
{
switch (code) {
case DatetimeFieldCode::YEAR: {
return extract_field<DatetimeFieldCode::YEAR>(in, allocator);
}
case DatetimeFieldCode::MONTH: {
return extract_field<DatetimeFieldCode::MONTH>(in, allocator);
}
case DatetimeFieldCode::DAY: {
return extract_field<DatetimeFieldCode::DAY>(in, allocator);
}
case DatetimeFieldCode::HOUR: {
return extract_field<DatetimeFieldCode::HOUR>(in, allocator);
}
case DatetimeFieldCode::MINUTE: {
return extract_field<DatetimeFieldCode::MINUTE>(in, allocator);
}
case DatetimeFieldCode::SECOND: {
return extract_field<DatetimeFieldCode::SECOND>(in, allocator);
}
case DatetimeFieldCode::WEEKDAY: {
return extract_field<DatetimeFieldCode::WEEKDAY>(in, allocator);
}
}
assert(false);
return ColumnView();
}
} // namespace detail
/*static*/ void ExtractFieldTask::cpu_variant(const Task* task,
const std::vector<PhysicalRegion>& regions,
Context context,
Runtime* runtime)
{
Deserializer ctx{task, regions};
DatetimeFieldCode code;
OutputColumn out;
Column<true> in;
deserialize(ctx, code);
deserialize(ctx, out);
deserialize(ctx, in);
if (in.empty()) {
out.make_empty(true);
return;
}
alloc::DeferredBufferAllocator allocator;
auto result = detail::extract_field(in.view(), code, allocator);
out.return_from_view(allocator, result);
}
static void __attribute__((constructor)) register_tasks(void)
{
ExtractFieldTask::register_variants();
}
} // namespace datetime
} // namespace pandas
} // namespace legate
| 30.936508 | 99 | 0.624808 | [
"vector"
] |
ddd02b1f51b6dcd6f08bff1e7886725a99b6ee9d | 1,622 | cpp | C++ | MaxLevelSum.cpp | aak-301/data-structure | 13d63e408a0001ceb06e2937ab8fcc3f176db78d | [
"Apache-2.0"
] | null | null | null | MaxLevelSum.cpp | aak-301/data-structure | 13d63e408a0001ceb06e2937ab8fcc3f176db78d | [
"Apache-2.0"
] | null | null | null | MaxLevelSum.cpp | aak-301/data-structure | 13d63e408a0001ceb06e2937ab8fcc3f176db78d | [
"Apache-2.0"
] | null | null | null | // https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
#include<iostream>
#include<vector>
#include<queue>
#include<map>
using namespace std;
struct TreeNode{
int val;
struct TreeNode *left, *right;
TreeNode(int x){
val=x;
left=NULL;
right=NULL;
}
};
int maxLevelSum(TreeNode* root) {
queue<TreeNode* >q;
q.push(root);
long int maxSum = INT_MIN;
int maxLevel;
long int sum;
int l=0;
while(!q.empty()){
sum=0;
l++;
int n = q.size();
for(int i=0;i<n;i++){
TreeNode* temp = q.front();
q.pop();
sum+=temp->val;
if(temp->left != NULL)
q.push(temp->left);
if(temp->right!=NULL)
q.push(temp->right);
}
if(sum>maxSum){
maxLevel=l;
maxSum=sum;
}
}
return maxLevel;
}
int main(){
/*
1
/ \
7 0
/\
7 -8
*/
struct TreeNode* root = new TreeNode(1);
root->left = new TreeNode(7);
root->left->right = new TreeNode(-8);
root->left->left = new TreeNode(7);
root->right = new TreeNode(0);
// struct TreeNode* root = new TreeNode(989);
// root->right = new TreeNode(10250);
// root->right->left = new TreeNode(98693);
// root->right->right = new TreeNode(-89388);
// root->right->right->right = new TreeNode(-32127);
cout<<maxLevelSum(root);
}
| 22.84507 | 69 | 0.467941 | [
"vector"
] |
ddd571708258ec1ba88dd76c403c5b09b840ef77 | 5,373 | hpp | C++ | lab3a-sem2/src/Matrix.hpp | yevkk/labs-oop | b6887e26779575693bb6bf37af9e2fffb8053acd | [
"Apache-2.0"
] | null | null | null | lab3a-sem2/src/Matrix.hpp | yevkk/labs-oop | b6887e26779575693bb6bf37af9e2fffb8053acd | [
"Apache-2.0"
] | 1 | 2019-12-09T00:52:05.000Z | 2019-12-09T00:52:05.000Z | lab3a-sem2/src/Matrix.hpp | yevkk/labs-oop-sem1 | b6887e26779575693bb6bf37af9e2fffb8053acd | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <type_traits>
#include <vector>
template<typename T>
class Matrix;
enum class MatrixMultiplicationPolicy {
Default, Strassen, StrassenParallel
};
namespace detail {
template<typename TT>
Matrix<TT> defaultMultiplication(const Matrix<TT> &lhs, const Matrix<TT> &rhs);
template<typename TT>
Matrix<TT> StrassenMultiplication(const Matrix<TT> &lhs,
const Matrix<TT> &rhs,
MatrixMultiplicationPolicy policy,
const std::size_t &size_bound
);
template<typename TT>
Matrix<TT> StrassenMultiplicationStep(const Matrix<TT> &lhs,
const Matrix<TT> &rhs,
const std::size_t &size,
const std::size_t &size_bound
);
template<typename TT>
Matrix<TT> StrassenMultiplicationStepParallel(const Matrix<TT> &lhs,
const Matrix<TT> &rhs,
const std::size_t &size,
const std::size_t &size_bound
);
}
/**
* @brief a class for storing numerical matrix
* @tparam T arithmetic type of elements stored in matrix
*/
template<typename T>
class Matrix {
static_assert(std::is_arithmetic_v<T>);
public:
/**
* @brief constructor
* @param size_r number of rows
* @param size_c number of columns
* @param default_element a value to fill matrix with
*/
Matrix(const std::size_t &rows, const std::size_t &cols, const T &default_element = 0);
Matrix(std::initializer_list<std::vector<T>> elements);
explicit Matrix(const std::vector<std::vector<T>> &elements);
/**
* @brief gives access to an element value
* @param row element's row index
* @param col element's column index
* @return value stored in corresponding place
*/
T operator()(const std::size_t &row, const std::size_t &col) const;
/**
* @brief gives access to an element
* @param row element's row index
* @param col element's column index
* @return a reference to value stored in corresponding place
*/
T &operator()(const std::size_t &row, const std::size_t &col);
/**
* @return number of rows in matrix
*/
[[nodiscard]] std::size_t size_rows() const;
/**
* @return number of columns in matrix
*/
[[nodiscard]] std::size_t size_cols() const;
/**
* @brief prints matrix to output stream
* @tparam OStream type of stream tp be used
* @param os a stream reference
*/
template<typename OStream>
void print(OStream &os);
template<typename TT>
friend Matrix<TT> detail::StrassenMultiplication(const Matrix<TT> &lhs,
const Matrix<TT> &rhs,
MatrixMultiplicationPolicy policy,
const std::size_t &size_bound
);
template<typename TT>
friend Matrix<TT> detail::StrassenMultiplicationStep(const Matrix<TT> &lhs,
const Matrix<TT> &rhs,
const std::size_t &size,
const std::size_t &size_bound
);
template<typename TT>
friend Matrix<TT> detail::StrassenMultiplicationStepParallel(const Matrix<TT> &lhs,
const Matrix<TT> &rhs,
const std::size_t &size,
const std::size_t &size_bound
);
~Matrix();
private:
std::vector<std::vector<T>> _rows;
};
template<typename T>
Matrix(std::initializer_list<std::vector<T>>) -> Matrix<T>;
template<typename T>
Matrix(const std::size_t &, const std::size_t &, const T &) -> Matrix<T>;
template<typename T>
Matrix<T> operator+(const Matrix<T> &lhs, const Matrix<T> &rhs);
template<typename T>
Matrix<T> operator-(const Matrix<T> &lhs, const Matrix<T> &rhs);
template<typename T>
bool operator==(const Matrix<T> &lhs, const Matrix<T> &rhs);
template<typename T>
bool operator!=(const Matrix<T> &lhs, const Matrix<T> &rhs);
/**
* @brief matrix multiplication
* @tparam T arithmetic type of elements stored in matrix
* @param lhs left multiplication argument
* @param rhs right multiplication argument
* @return result os multiplication
*/
template<typename T>
Matrix<T> multiply(const Matrix<T> &lhs,
const Matrix<T> &rhs);
constexpr std::size_t SIZE_BOUND = 64;
/**
* @brief matrix multiplication
* @tparam T arithmetic type of elements stored in matrix
* @param lhs left multiplication argument
* @param rhs right multiplication argument
* @param policy multiplication policy
* @return result os multiplication
*/
template<typename T>
Matrix<T> multiply(const Matrix<T> &lhs,
const Matrix<T> &rhs,
MatrixMultiplicationPolicy policy,
const std::size_t &size_bound = SIZE_BOUND
);
#include "Matrix.hxx" | 31.605882 | 94 | 0.568025 | [
"vector"
] |
ddd8a0126e837d5cb692f1fb1dd85c6b90160c86 | 2,520 | cpp | C++ | mmdet/ops/ops/roi_align/src/rroi_align_cuda.cpp | qgh1223/SLRDet | f63335e9626067b462ad548c98f986e0d33addf9 | [
"Apache-2.0"
] | 27 | 2019-11-20T07:34:15.000Z | 2022-03-04T01:02:33.000Z | mmdet/ops/ops/roi_align/src/rroi_align_cuda.cpp | qgh1223/SLRDet | f63335e9626067b462ad548c98f986e0d33addf9 | [
"Apache-2.0"
] | 5 | 2019-12-03T13:16:02.000Z | 2020-01-16T08:59:53.000Z | mmdet/ops/ops/roi_align/src/rroi_align_cuda.cpp | LUCKMOONLIGHT/SLRDet | f63335e9626067b462ad548c98f986e0d33addf9 | [
"Apache-2.0"
] | 5 | 2019-12-03T12:21:36.000Z | 2021-12-17T12:37:08.000Z | #include <torch/extension.h>
#include <cmath>
#include <vector>
at::Tensor ROIAlignRotated_forward_cuda(const at::Tensor& input,
const at::Tensor& rois,
const float spatial_scale,
const int pooled_height,
const int pooled_width,
const int sampling_ratio);
at::Tensor ROIAlignRotated_backward_cuda(const at::Tensor& grad,
const at::Tensor& rois,
const float spatial_scale,
const int pooled_height,
const int pooled_width,
const int batch_size,
const int channels,
const int height,
const int width,
const int sampling_ratio);
at::Tensor ROIAlignRotated_forward(const at::Tensor& input,
const at::Tensor& rois,
const float spatial_scale,
const int pooled_height,
const int pooled_width,
const int sampling_ratio) {
if (input.type().is_cuda()) {
return ROIAlignRotated_forward_cuda(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio);
}
}
at::Tensor ROIAlignRotated_backward(const at::Tensor& grad,
const at::Tensor& rois,
const float spatial_scale,
const int pooled_height,
const int pooled_width,
const int batch_size,
const int channels,
const int height,
const int width,
const int sampling_ratio) {
if (grad.type().is_cuda()) {
return ROIAlignRotated_backward_cuda(grad, rois, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width, sampling_ratio);
}
AT_ERROR("Not implemented on the CPU");
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("roi_align_rotated_forward",&ROIAlignRotated_forward,"ROIAlignRotated_forward");
m.def("roi_align_rotated_backward",&ROIAlignRotated_backward,"ROIAlignRotated_backward");
}
| 45 | 151 | 0.5 | [
"vector"
] |
dddc4891d32a5ad8d9450d4d3a0c01594152d8bb | 520 | cpp | C++ | zend/function.cpp | kirmorozov/PHP-CPP | fde096ca0a23c33c63e7c5f529891e9b679601a1 | [
"Apache-2.0"
] | 1,027 | 2015-01-05T02:52:17.000Z | 2022-03-26T22:30:14.000Z | zend/function.cpp | kirmorozov/PHP-CPP | fde096ca0a23c33c63e7c5f529891e9b679601a1 | [
"Apache-2.0"
] | 312 | 2015-01-01T08:58:12.000Z | 2022-03-31T09:26:55.000Z | zend/function.cpp | kirmorozov/PHP-CPP | fde096ca0a23c33c63e7c5f529891e9b679601a1 | [
"Apache-2.0"
] | 324 | 2015-01-06T01:57:21.000Z | 2022-03-31T14:13:49.000Z | /**
* Function.cpp
*
* Implementation file for the Function class
*
* @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
* @copyright 2015 Copernica BV
*/
/**
* Dependencies
*/
#include "includes.h"
/**
* Set up namespace
*/
namespace Php {
/**
* Constructor
* @param function The function to be wrapped
*/
Function::Function(const std::function<Php::Value(Php::Parameters&)> &function) : Value(Object(Functor::entry(), new Functor(function))) {}
/**
* End of namespace
*/
}
| 16.774194 | 139 | 0.646154 | [
"object"
] |
50b41293d8ac9b17ade8053c91b52e4a09180791 | 1,991 | cpp | C++ | stack/42.trapping-rain-water.cpp | yeweili94/leetcode | 900fd11795f760e3d1d646f1f63887d4d22eb46e | [
"MIT"
] | null | null | null | stack/42.trapping-rain-water.cpp | yeweili94/leetcode | 900fd11795f760e3d1d646f1f63887d4d22eb46e | [
"MIT"
] | null | null | null | stack/42.trapping-rain-water.cpp | yeweili94/leetcode | 900fd11795f760e3d1d646f1f63887d4d22eb46e | [
"MIT"
] | null | null | null | /*
* [42] Trapping Rain Water
*
* https://leetcode.com/problems/trapping-rain-water/description/
*
* algorithms
* Hard (38.80%)
* Total Accepted: 190.7K
* Total Submissions: 491.4K
* Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
*
* Given n non-negative integers representing an elevation map where the width
* of each bar is 1, compute how much water it is able to trap after raining.
*
*
* The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
* In this case, 6 units of rain water (blue section) are being trapped. Thanks
* Marcos for contributing this image!
*
* Example:
*
*
* Input: [0,1,0,2,1,0,1,3,2,1,2,1]
* Output: 6
*/
class Solution {
public:
int trap(vector<int>& height) {
int size = height.size();
vector<int> left(size, 0);
vector<int> right(size, size - 1);
stack<int> st;
for (int i = 0; i < size; i++) {
if (st.empty()) {
st.push(i);
} else {
while (!st.empty() && height[st.top()] > height[i]) {
right[st.top()] = i - 1;
st.pop();
}
st.push(i);
}
}
while (!st.empty()) {
right[st.top()] = size - 1;
st.pop();
}
for (int i = size - 1; i >= 0; i--) {
if (st.empty()) {
st.push(i);
} else {
while (!st.empty() && height[st.top()] > height[i]) {
left[st.top()] = i + 1;
st.pop();
}
st.push(i);
}
}
while (!st.empty()) {
right[st.top()] = 0;
st.pop();
}
int ret = 0;
for (int i = 0; i < size; i++) {
ret += (min(height[left[i]], height[right[i]]) - height[i]);
printf("%d\t%d", height[left[i]], height[right[i]]);
}
return ret;
}
};
| 27.652778 | 79 | 0.447514 | [
"vector"
] |
50bc503901cbe9cb919d7a5f8da68432cadfe7fe | 122,976 | cpp | C++ | base/ntsetup/oobe/msobcomm/refdial.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/ntsetup/oobe/msobcomm/refdial.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/ntsetup/oobe/msobcomm/refdial.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // RefDial.cpp : Implementation of CRefDial
//#include "stdafx.h"
//#include "icwhelp.h"
#include <urlmon.h>
#include "commerr.h"
#include "RefDial.h"
#include "msobcomm.h"
#include "appdefs.h"
#include "commerr.h"
#include "util.h"
#include "msobdl.h"
//#include <mshtmhst.h>
const WCHAR c_szCreditsMagicNum[] = L"1 425 555 1212";
const WCHAR c_szRegStrValDigitalPID[] = L"DigitalProductId";
const WCHAR c_szSignedPIDFName[] = L"signed.pid";
const WCHAR c_szRASProfiles[] = L"RemoteAccess\\Profile";
const WCHAR c_szProxyEnable[] = L"ProxyEnable";
const WCHAR c_szURLReferral[] = L"URLReferral";
const WCHAR c_szRegPostURL[] = L"RegPostURL";
const WCHAR c_szStayConnected[] = L"Stayconnected";
static const WCHAR szOptionTag[] = L"<OPTION>%s";
WCHAR g_BINTOHEXLookup[16] =
{
L'0',L'1',L'2',L'3',L'4',L'5',L'6',L'7',
L'8',L'9',L'A',L'B',L'C',L'D',L'E',L'F'
};
extern CObCommunicationManager* gpCommMgr;
extern BOOL isAlnum(WCHAR c);
// ############################################################################
HRESULT Sz2URLValue(WCHAR *s, WCHAR *buf, UINT uiLen)
{
HRESULT hr;
WCHAR *t;
hr = ERROR_SUCCESS;
for (t=buf;*s; s++)
{
if (*s == L' ') *t++ = L'+';
else if (isAlnum(*s)) *t++ = *s;
else {
wsprintf(t, L"%%%02X", (WCHAR) *s);
t += 3;
}
}
*t = L'\0';
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: LineCallback()
//
// Synopsis: Call back for TAPI line
//
//+---------------------------------------------------------------------------
void CALLBACK LineCallback(DWORD hDevice,
DWORD dwMessage,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2,
DWORD_PTR dwParam3)
{
return;
}
void WINAPI MyProgressCallBack
(
HINTERNET hInternet,
DWORD_PTR dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength
)
{
CRefDial *pRefDial = (CRefDial *)dwContext;
int prc;
if (!dwContext)
return;
switch(dwInternetStatus)
{
case CALLBACK_TYPE_PROGRESS:
prc = *(int*)lpvStatusInformation;
// Set the status string ID
pRefDial->m_DownloadStatusID = 0;//IDS_RECEIVING_RESPONSE;
// Post a message to fire an event
PostMessage(gpCommMgr->m_hwndCallBack,
WM_OBCOMM_DOWNLOAD_PROGRESS,
gpCommMgr->m_pRefDial->m_dwCnType,
prc);
break;
case CALLBACK_TYPE_URL:
if (lpvStatusInformation)
lstrcpy(pRefDial->m_szRefServerURL, (LPWSTR)lpvStatusInformation);
break;
default:
//TraceMsg(TF_GENERAL, L"CONNECT:Unknown Internet Status (%d.\n"), dwInternetStatus);
pRefDial->m_DownloadStatusID = 0;
break;
}
}
DWORD WINAPI DownloadThreadInit(LPVOID lpv)
{
HRESULT hr = ERROR_NOT_ENOUGH_MEMORY;
CRefDial *pRefDial = (CRefDial*)lpv;
HINSTANCE hDLDLL = NULL; // Download .DLL
FARPROC fp;
//MinimizeRNAWindowEx();
hDLDLL = LoadLibrary(DOWNLOAD_LIBRARY);
if (!hDLDLL)
{
hr = ERROR_DOWNLOAD_NOT_FOUND;
//AssertMsg(0, L"icwdl missing");
goto ThreadInitExit;
}
// Set up for download
//
fp = GetProcAddress(hDLDLL, DOWNLOADINIT);
if (fp == NULL)
{
hr = ERROR_DOWNLOAD_NOT_FOUND;
//AssertMsg(0, L"DownLoadInit API missing");
goto ThreadInitExit;
}
hr = ((PFNDOWNLOADINIT)fp)(pRefDial->m_szUrl, (DWORD FAR *)pRefDial, &pRefDial->m_dwDownLoad, gpCommMgr->m_hwndCallBack);
if (hr != ERROR_SUCCESS)
goto ThreadInitExit;
// Set up call back for progress dialog
//
fp = GetProcAddress(hDLDLL, DOWNLOADSETSTATUS);
//Assert(fp);
hr = ((PFNDOWNLOADSETSTATUS)fp)(pRefDial->m_dwDownLoad, (INTERNET_STATUS_CALLBACK)MyProgressCallBack);
// Download stuff MIME multipart
//
fp = GetProcAddress(hDLDLL, DOWNLOADEXECUTE);
//Assert(fp);
hr = ((PFNDOWNLOADEXECUTE)fp)(pRefDial->m_dwDownLoad);
if (hr)
{
goto ThreadInitExit;
}
fp = GetProcAddress(hDLDLL, DOWNLOADPROCESS);
//Assert(fp);
hr = ((PFNDOWNLOADPROCESS)fp)(pRefDial->m_dwDownLoad);
if (hr)
{
goto ThreadInitExit;
}
hr = ERROR_SUCCESS;
ThreadInitExit:
// Clean up
//
if (pRefDial->m_dwDownLoad)
{
fp = GetProcAddress(hDLDLL, DOWNLOADCLOSE);
//Assert(fp);
((PFNDOWNLOADCLOSE)fp)(pRefDial->m_dwDownLoad);
pRefDial->m_dwDownLoad = 0;
}
// Call the OnDownLoadCompelete method
if (ERROR_SUCCESS == hr)
{
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_DOWNLOAD_DONE, gpCommMgr->m_pRefDial->m_dwCnType, 0);
}
// Free the libs used to do the download
if (hDLDLL)
FreeLibrary(hDLDLL);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: RasErrorToIDS()
//
// Synopsis: Interpret and wrap RAS errors
//
//+---------------------------------------------------------------------------
DWORD RasErrorToIDS(DWORD dwErr)
{
switch(dwErr)
{
case SUCCESS:
return 0;
case ERROR_LINE_BUSY:
return ERR_COMM_RAS_PHONEBUSY;
case ERROR_NO_ANSWER: // No pick up
case ERROR_NO_CARRIER: // No negotiation
case ERROR_PPP_TIMEOUT: // get this on CHAP timeout
return ERR_COMM_RAS_SERVERBUSY;
case ERROR_NO_DIALTONE:
return ERR_COMM_RAS_NODIALTONE;
case ERROR_HARDWARE_FAILURE: // modem turned off
case ERROR_PORT_ALREADY_OPEN: // procomm/hypertrm/RAS has COM port
case ERROR_PORT_OR_DEVICE: // got this when hypertrm had the device open -- jmazner
return ERR_COMM_RAS_NOMODEM;
}
return ERR_COMM_RAS_UNKNOWN;
}
DWORD DoConnMonitor(LPVOID lpv)
{
if (gpCommMgr)
gpCommMgr->m_pRefDial->ConnectionMonitorThread(NULL);
return 1;
}
void CreateConnMonitorThread(LPVOID lpv)
{
DWORD dwThreadID;
if (gpCommMgr->m_pRefDial->m_hConnMonThread)
gpCommMgr->m_pRefDial->TerminateConnMonitorThread();
gpCommMgr->m_pRefDial->m_hConnMonThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)DoConnMonitor,
(LPVOID)0,
0,
&dwThreadID);
}
HRESULT CRefDial::OnDownloadEvent(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL* bHandled)
{
if (uMsg == WM_OBCOMM_DOWNLOAD_DONE)
{
DWORD dwThreadResults = STILL_ACTIVE;
int iRetries = 0;
// We keep the RAS connection open here, it must be explicitly
// close by the container (a call DoHangup)
// This code will wait until the download thread exists, and
// collect the download status.
if (m_hThread)
{
do {
if (!GetExitCodeThread(m_hThread, &dwThreadResults))
{
//ASSERT(0, L"CONNECT:GetExitCodeThread failed.\n");
}
iRetries++;
if (dwThreadResults == STILL_ACTIVE)
Sleep(500);
} while (dwThreadResults == STILL_ACTIVE && iRetries < MAX_EXIT_RETRIES);
m_hThread = NULL;
}
// BUGBUG: Is bstrURL used for anything??
// See if there is an URL to pass to the container
BSTR bstrURL;
if (m_szRefServerURL[0] != L'\0')
bstrURL = SysAllocString(m_szRefServerURL);
else
bstrURL = NULL;
// The download is complete now, so we reset this to TRUE, so the RAS
// event handler does not get confused
m_bDownloadHasBeenCanceled = TRUE;
// Read and parse the download folder.
*bHandled = ParseISPInfo(NULL, ICW_ISPINFOPath, TRUE);
// Free any memory allocated above during the conversion
SysFreeString(bstrURL);
}
return 0;
}
//+---------------------------------------------------------------------------
//
// Function: TerminateConnMonitorThread()
//
// Synopsis: Termintate connection monitor thread
//
//+---------------------------------------------------------------------------
void CRefDial::TerminateConnMonitorThread()
{
DWORD dwThreadResults = STILL_ACTIVE;
int iRetries = 0;
if (m_hConnMonThread)
{
SetEvent(m_hConnectionTerminate);
// We keep the RAS connection open here, it must be explicitly
// close by the container (a call DoHangup)
// This code will wait until the monitor thread exists, and
// collect the status.
do
{
if (!GetExitCodeThread(m_hConnMonThread, &dwThreadResults))
{
break;
}
iRetries++;
if (dwThreadResults == STILL_ACTIVE)
Sleep(500);
} while (dwThreadResults == STILL_ACTIVE && iRetries < MAX_EXIT_RETRIES);
CloseHandle(m_hConnMonThread);
m_hConnMonThread = NULL;
}
}
//+---------------------------------------------------------------------------
//
// Function: ConnectionMonitorThread()
//
// Synopsis: Monitor connection status
//
//+---------------------------------------------------------------------------
DWORD CRefDial::ConnectionMonitorThread(LPVOID pdata)
{
HRESULT hr = E_FAIL;
MSG msg;
DWORD dwRetCode;
HANDLE hEventList[1];
BOOL bConnected;
m_hConnectionTerminate = CreateEvent(NULL, TRUE, FALSE, NULL);
hEventList[0] = m_hConnectionTerminate;
while(TRUE)
{
// We will wait on window messages and also the named event.
dwRetCode = MsgWaitForMultipleObjects(1,
&hEventList[0],
FALSE,
1000, // 1 second
QS_ALLINPUT);
if(dwRetCode == WAIT_TIMEOUT)
{
RasGetConnectStatus(&bConnected);
// If we've got disconnected, then we notify UI
if (!bConnected)
{
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONDIALERROR, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)ERROR_REMOTE_DISCONNECTION);
break;
}
}
else if(dwRetCode == WAIT_OBJECT_0)
{
break;
}
else if(dwRetCode == WAIT_OBJECT_0 + 1)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (WM_QUIT == msg.message)
{
//*pbRetVal = FALSE;
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
}
CloseHandle(m_hConnectionTerminate);
m_hConnectionTerminate = NULL;
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: RasDialFunc()
//
// Synopsis: Call back for RAS
//
//+---------------------------------------------------------------------------
void CALLBACK CRefDial::RasDialFunc(HRASCONN hRas,
UINT unMsg,
RASCONNSTATE rasconnstate,
DWORD dwError,
DWORD dwErrorEx)
{
if (gpCommMgr)
{
if (dwError)
{
if (ERROR_USER_DISCONNECTION != dwError)
{
gpCommMgr->m_pRefDial->DoHangup();
//gpCommMgr->Fire_DialError((DWORD)rasconnstate);
TRACE1(L"DialError %d", dwError);
gpCommMgr->m_pRefDial->m_dwRASErr = dwError; // Store dialing error
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONDIALERROR, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)gpCommMgr->m_pRefDial->m_dwRASErr);
}
}
else
{
switch(rasconnstate)
{
case RASCS_OpenPort:
//gpCommMgr->Fire_Dialing((DWORD)rasconnstate);
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONDIALING, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)0);
break;
case RASCS_StartAuthentication: // WIN 32 only
//gpCommMgr->Fire_Connecting();
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONCONNECTING, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)0);
break;
case RASCS_Authenticate: // WIN 32 only
//gpCommMgr->Fire_Connecting();
if (IsNT())
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONCONNECTING, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)0);
break;
case RASCS_PortOpened:
break;
case RASCS_ConnectDevice:
break;
case RASCS_DeviceConnected:
case RASCS_AllDevicesConnected:
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONCONNECTING, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)0);
break;
case RASCS_Connected:
{
CreateConnMonitorThread(NULL);
PostMessage(gpCommMgr->m_hwndCallBack,
WM_OBCOMM_ONCONNECTED,
(WPARAM)gpCommMgr->m_pRefDial->m_dwCnType,
(LPARAM)0);
break;
}
case RASCS_Disconnected:
{
if (CONNECTED_REFFERAL == gpCommMgr->m_pRefDial->m_dwCnType &&
!gpCommMgr->m_pRefDial->m_bDownloadHasBeenCanceled)
{
HINSTANCE hDLDLL = LoadLibrary(DOWNLOAD_LIBRARY);
if (hDLDLL)
{
FARPROC fp = GetProcAddress(hDLDLL, DOWNLOADCANCEL);
if(fp)
((PFNDOWNLOADCANCEL)fp)(gpCommMgr->m_pRefDial->m_dwDownLoad);
FreeLibrary(hDLDLL);
hDLDLL = NULL;
gpCommMgr->m_pRefDial->m_bDownloadHasBeenCanceled = TRUE;
}
}
// If we get a disconnected status from the RAS server, then
// hangup the modem here
gpCommMgr->m_pRefDial->DoHangup();
//gpCommMgr->Fire_DialError((DWORD)rasconnstate);
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONDISCONNECT, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)0);
break;
}
default:
break;
}
}
}
return;
}
/////////////////////////////////////////////////////////////////////////////
// CRefDial
CRefDial::CRefDial()
{
HKEY hkey = NULL;
DWORD dwResult = 0;
*m_szCurrentDUNFile = 0;
*m_szLastDUNFile = 0;
*m_szEntryName = 0;
*m_szConnectoid = 0;
*m_szPID = 0;
*m_szRefServerURL = 0;
*m_szRegServerName = 0;
m_nRegServerPort = INTERNET_INVALID_PORT_NUMBER;
m_fSecureRegServer = FALSE;
*m_szRegFormAction = 0;
*m_szISPSupportNumber = 0;
*m_szISPFile = 0;
m_hrDisplayableNumber = ERROR_SUCCESS;
m_dwCountryCode = 0;
m_RasStatusID = 0;
m_dwTapiDev = 0xFFFFFFFF; // NOTE: 0 is a valid value
m_dwWizardVersion = 0;
m_lCurrentModem = -1;
m_lAllOffers = 0;
m_PhoneNumberEnumidx = 0;
m_dwRASErr = 0;
m_bDownloadHasBeenCanceled = TRUE; // This will get set to FALSE when a DOWNLOAD starts
m_bQuitWizard = FALSE;
m_bTryAgain = FALSE;
m_bDisconnect = FALSE;
m_bDialCustom = FALSE;
m_bModemOverride = FALSE; //allows campus net to be used.
m_hrasconn = NULL;
m_pszDisplayable = NULL;
m_pcRNA = NULL;
m_hRasDll = NULL;
m_fpRasDial = NULL;
m_fpRasGetEntryDialParams = NULL;
m_lpGatherInfo = new GATHERINFO;
m_reflpRasEntryBuff = NULL;
m_reflpRasDevInfoBuff = NULL;
m_hThread = NULL;
m_hDialThread = NULL;
m_hConnMonThread = NULL;
m_bUserInitiateHangup = FALSE;
m_pszOriginalDisplayable = NULL;
m_bDialAlternative = TRUE;
memset(&m_SuggestInfo, 0, sizeof(m_SuggestInfo));
memset(&m_szConnectoid, 0, RAS_MaxEntryName+1);
m_dwAppMode = 0;
m_bDial = FALSE;
m_dwCnType = CONNECTED_ISP_SIGNUP;
m_pszISPList = FALSE;
m_dwNumOfAutoConfigOffers = 0;
m_pCSVList = NULL;
m_unSelectedISP = 0;
m_bstrPromoCode = SysAllocString(L"\0");
m_bstrProductCode = SysAllocString(L"\0");
m_bstrSignedPID = SysAllocString(L"\0");
m_bstrSupportNumber = SysAllocString(L"\0");
m_bstrLoggingStartUrl = SysAllocString(L"\0");
m_bstrLoggingEndUrl = SysAllocString(L"\0");
// This Critical Section is used by DoHangup and GetDisplayableNumber
InitializeCriticalSection (&m_csMyCriticalSection);
// Initialize m_dwConnectionType.
m_dwConnectionType = 0;
if ( RegOpenKey(HKEY_LOCAL_MACHINE, ICSSETTINGSPATH,&hkey) == ERROR_SUCCESS)
{
DWORD dwSize = sizeof(DWORD);
DWORD dwType = REG_DWORD;
if (RegQueryValueEx(hkey, ICSCLIENT,NULL,&dwType,(LPBYTE)&dwResult, &dwSize) != ERROR_SUCCESS)
dwResult = 0;
RegCloseKey(hkey);
}
if ( 0 != dwResult )
m_dwConnectionType = CONNECTION_ICS_TYPE;
}
CRefDial::~CRefDial()
{
if (m_hrasconn)
DoHangup();
if (m_hConnMonThread)
{
SetEvent(m_hConnectionTerminate);
}
if (NULL != m_hThread)
{
CloseHandle(m_hThread);
m_hThread = NULL;
}
if (NULL != m_hDialThread)
{
CloseHandle(m_hDialThread);
m_hDialThread = NULL;
}
if (NULL != m_hConnMonThread)
{
CloseHandle(m_hConnMonThread);
m_hConnMonThread = NULL;
}
if (m_lpGatherInfo)
delete(m_lpGatherInfo);
if( (m_pcRNA!=NULL) && (*m_szConnectoid != 0) )
{
m_pcRNA->RasDeleteEntry(NULL, m_szConnectoid);
}
if ( m_pcRNA )
delete m_pcRNA;
if(m_reflpRasEntryBuff)
{
GlobalFree(m_reflpRasEntryBuff);
m_reflpRasEntryBuff = NULL;
}
if(m_reflpRasDevInfoBuff)
{
GlobalFree(m_reflpRasDevInfoBuff);
m_reflpRasDevInfoBuff = NULL;
}
if (m_pszISPList)
delete [] m_pszISPList;
DeleteCriticalSection(&m_csMyCriticalSection);
if (m_pszOriginalDisplayable)
{
GlobalFree(m_pszOriginalDisplayable);
m_pszOriginalDisplayable = NULL;
}
CleanISPList();
}
void CRefDial::CleanISPList(void)
{
if (m_pCSVList)
{
ISPLIST* pCurr;
while (m_pCSVList->pNext != NULL)
{
pCurr = m_pCSVList;
if (NULL != m_pCSVList->pElement)
{
delete pCurr->pElement;
}
m_pCSVList = pCurr->pNext;
delete pCurr;
}
if (NULL != m_pCSVList->pElement)
delete m_pCSVList->pElement;
delete m_pCSVList;
m_pCSVList = NULL;
m_pSelectedISPInfo = NULL;
}
}
/******************************************************************************
// These functions come from the existing ICW code and are use to setup a
// connectiod to the referral server, dial it, and perform the download.
******************************************************************************/
//+----------------------------------------------------------------------------
// Function: ReadConnectionInformation
//
// Synopsis: Read the contents from the ISP file
//
// Arguments: none
//
// Returns: error value - ERROR_SUCCESS = succes
//
// History: 1/9/98 DONALDM Adapted from ICW 1.x
//-----------------------------------------------------------------------------
//INT _convert;
DWORD CRefDial::ReadConnectionInformation(void)
{
DWORD hr;
WCHAR szUserName[UNLEN+1];
WCHAR szPassword[PWLEN+1];
LPWSTR pszTemp;
BOOL bReboot;
LPWSTR lpRunOnceCmd;
bReboot = FALSE;
lpRunOnceCmd = NULL;
//
// Get the name of DUN file from ISP file, if there is one.
//
WCHAR pszDunFile[MAX_PATH];
*m_szCurrentDUNFile = 0;
hr = GetDataFromISPFile(m_szISPFile, INF_SECTION_ISPINFO, INF_DUN_FILE, pszDunFile,MAX_PATH);
if (ERROR_SUCCESS == hr)
{
//
// Get the full path to the DUN File
//
WCHAR szTempPath[MAX_PATH];
lstrcpy(szTempPath, pszDunFile);
if (!(hr = SearchPath(NULL, szTempPath,NULL,MAX_PATH,pszDunFile,&pszTemp)))
{
//ErrorMsg1(m_hWnd, IDS_CANTREADTHISFILE, CharUpper(pszDunFile));
goto ReadConnectionInformationExit;
}
//
// save current DUN file name in global (for ourself)
//
lstrcpy(m_szCurrentDUNFile, pszDunFile);
}
//
// Read the DUN/ISP file File
//
hr = m_ISPImport.ImportConnection(*m_szCurrentDUNFile != 0 ? m_szCurrentDUNFile : m_szISPFile,
m_szISPSupportNumber,
m_szEntryName,
szUserName,
szPassword,
&bReboot);
lstrcpyn( m_szConnectoid, m_szEntryName, lstrlen(m_szEntryName) + 1);
if (/*(VER_PLATFORM_WIN32_NT == g_dwPlatform) &&*/ (ERROR_INVALID_PARAMETER == hr))
{
// If there are only dial-out entries configured on NT, we get
// ERROR_INVALID_PARAMETER returned from RasSetEntryProperties,
// which InetConfigClient returns to ImportConnection which
// returns it to us. If we get this error, we want to display
// a different error instructing the user to configure a modem
// for dial-out.
////MessageBox(GetSz(IDS_NODIALOUT),
// GetSz(IDS_TITLE),
// MB_ICONERROR | MB_OK | MB_APPLMODAL);
goto ReadConnectionInformationExit;
}
else
if (ERROR_CANNOT_FIND_PHONEBOOK_ENTRY == hr)
{
//
// The disk is full, or something is wrong with the
// phone book file
////MessageBox(GetSz(IDS_NOPHONEENTRY),
// GetSz(IDS_TITLE),
// MB_ICONERROR | MB_OK | MB_APPLMODAL);
goto ReadConnectionInformationExit;
}
else if (hr == ERROR_CANCELLED)
{
////TraceMsg(TF_GENERAL, L"ICWHELP: User cancelled, quitting.\n");
goto ReadConnectionInformationExit;
}
else if (hr == ERROR_RETRY)
{
//TraceMsg(TF_GENERAL, L"ICWHELP: User retrying.\n");
goto ReadConnectionInformationExit;
}
else if (hr != ERROR_SUCCESS)
{
////ErrorMsg1(m_hWnd, IDS_CANTREADTHISFILE, CharUpper(pszDunFile));
goto ReadConnectionInformationExit;
}
else
{
//
// place the name of the connectoid in the registry
//
if (ERROR_SUCCESS != (hr = StoreInSignUpReg((LPBYTE)m_szEntryName, BYTES_REQUIRED_BY_SZ(m_szEntryName), REG_SZ, RASENTRYVALUENAME)))
{
////MsgBox(IDS_CANTSAVEKEY, MB_MYERROR);
goto ReadConnectionInformationExit;
}
}
ReadConnectionInformationExit:
return hr;
}
HRESULT CRefDial::ReadPhoneBook(LPGATHERINFO lpGatherInfo, PSUGGESTINFO pSuggestInfo)
{
HRESULT hr = ERROR_CANNOT_FIND_PHONEBOOK_ENTRY;;
if (pSuggestInfo && m_lpGatherInfo)
{
//
// If phonenumber is not filled in by the ISP file,
// get phone number from oobe phone book
//
pSuggestInfo->wNumber = 1;
lpGatherInfo->m_bUsePhbk = TRUE;
WCHAR szEntrySection[3];
WCHAR szEntryName[MAX_PATH];
WCHAR szEntryValue[MAX_PATH];
INT nPick = 1;
INT nTotal= 3;
WCHAR szFileName[MAX_PATH];
LPWSTR pszTemp;
// Get Country ID from TAPI
m_SuggestInfo.AccessEntry.dwCountryCode = m_lpGatherInfo->m_dwCountryCode;
// Get the name of phone book
GetPrivateProfileString(INF_SECTION_ISPINFO,
INF_PHONE_BOOK,
cszOobePhBkFile,
szEntryValue,
MAX_CHARS_IN_BUFFER(szEntryValue),
m_szISPFile);
SearchPath(NULL, szEntryValue,NULL,MAX_PATH,&szFileName[0],&pszTemp);
wsprintf(szEntrySection, L"%ld", m_lpGatherInfo->m_dwCountryID);
// Read the total number of phone numbers
nTotal = GetPrivateProfileInt(szEntrySection,
cszOobePhBkCount,
1,
szFileName);
GetPrivateProfileString(szEntrySection,
cszOobePhBkRandom,
L"No",
szEntryValue,
MAX_CHARS_IN_BUFFER(szEntryValue),
szFileName);
if (0 == lstrcmp(szEntryValue, L"Yes"))
{
// Pick a random number to dial
nPick = (rand() % nTotal) + 1;
}
else
{
nPick = (pSuggestInfo->dwPick % nTotal) + 1;
}
// Read the name of the city
wsprintf(szEntryName, cszOobePhBkCity, nPick);
GetPrivateProfileString(szEntrySection,
szEntryName,
L"",
szEntryValue,
MAX_CHARS_IN_BUFFER(szEntryValue),
szFileName);
lstrcpy(pSuggestInfo->AccessEntry.szCity, szEntryValue);
if (0 == lstrlen(szEntryValue))
{
goto ReadPhoneBookExit;
}
// Read the dunfile entry from the phonebook
// lstrcpy(pSuggestInfo->AccessEntry.szDataCenter, L"icwip.dun");
wsprintf(szEntryName, cszOobePhBkDunFile, nPick);
GetPrivateProfileString(szEntrySection,
szEntryName,
L"",
szEntryValue,
MAX_CHARS_IN_BUFFER(szEntryValue),
szFileName);
lstrcpy(pSuggestInfo->AccessEntry.szDataCenter, szEntryValue);
if (0 == lstrlen(szEntryValue))
{
goto ReadPhoneBookExit;
}
// Pick up country code from the Phonebook
wsprintf(szEntryName, cszOobePhBkAreaCode, nPick);
GetPrivateProfileString(szEntrySection,
szEntryName,
L"",
szEntryValue,
MAX_CHARS_IN_BUFFER(szEntryValue),
szFileName);
lstrcpy(pSuggestInfo->AccessEntry.szAreaCode, szEntryValue);
// No area code is possible
// Read the phone number (without areacode) from the Phonebook
wsprintf(szEntryName, cszOobePhBkNumber, nPick);
GetPrivateProfileString(szEntrySection,
szEntryName,
L"",
szEntryValue,
MAX_CHARS_IN_BUFFER(szEntryValue),
szFileName);
lstrcpy(pSuggestInfo->AccessEntry.szAccessNumber, szEntryValue);
if (0 == lstrlen(szEntryValue))
{
goto ReadPhoneBookExit;
}
hr = ERROR_SUCCESS;
}
ReadPhoneBookExit:
return hr;
}
HRESULT CRefDial::GetDisplayableNumber()
{
HRESULT hr = ERROR_SUCCESS;
LPRASENTRY lpRasEntry = NULL;
LPRASDEVINFO lpRasDevInfo = NULL;
DWORD dwRasEntrySize = 0;
DWORD dwRasDevInfoSize = 0;
RNAAPI *pcRNA = NULL;
LPLINETRANSLATEOUTPUT lpOutput1 = NULL;
DWORD dwNumDev;
LPLINETRANSLATEOUTPUT lpOutput2;
LPLINEEXTENSIONID lpExtensionID = NULL;
// Turns out that DialThreadInit can call this at the same time
// that script will call this. So, we need to prevent them from
// stepping on shared variables - m_XXX.
EnterCriticalSection (&m_csMyCriticalSection);
//
// Get phone number from connectoid
//
hr = MyRasGetEntryProperties(NULL,
m_szConnectoid,
&lpRasEntry,
&dwRasEntrySize,
&lpRasDevInfo,
&dwRasDevInfoSize);
if (hr != ERROR_SUCCESS || NULL == lpRasEntry)
{
goto GetDisplayableNumberExit;
}
//
// If this is a dial as is number, just get it from the structure
//
m_bDialAsIs = !(lpRasEntry->dwfOptions & RASEO_UseCountryAndAreaCodes);
if (m_bDialAsIs)
{
if (m_pszDisplayable) GlobalFree(m_pszDisplayable);
m_pszDisplayable = (LPWSTR)GlobalAlloc(GPTR, BYTES_REQUIRED_BY_SZ(lpRasEntry->szLocalPhoneNumber));
if (!m_pszDisplayable)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto GetDisplayableNumberExit;
}
lstrcpy(m_szPhoneNumber, lpRasEntry->szLocalPhoneNumber);
lstrcpy(m_pszDisplayable, lpRasEntry->szLocalPhoneNumber);
WCHAR szAreaCode[MAX_AREACODE+1];
WCHAR szCountryCode[8];
if (SUCCEEDED(tapiGetLocationInfo(szCountryCode, szAreaCode)))
{
if (szCountryCode[0] != L'\0')
m_dwCountryCode = _wtoi(szCountryCode);
else
m_dwCountryCode = 1;
}
else
{
m_dwCountryCode = 1;
}
}
else
{
//
// If there is no area code, don't use parentheses
//
if (lpRasEntry->szAreaCode[0])
wsprintf(m_szPhoneNumber, L"+%lu (%s) %s\0",lpRasEntry->dwCountryCode,
lpRasEntry->szAreaCode, lpRasEntry->szLocalPhoneNumber);
else
wsprintf(m_szPhoneNumber, L"+%lu %s\0",lpRasEntry->dwCountryCode,
lpRasEntry->szLocalPhoneNumber);
//
// Initialize TAPIness
//
dwNumDev = 0;
DWORD dwVer = 0x00020000;
hr = lineInitializeEx(&m_hLineApp,
NULL,
LineCallback,
NULL,
&dwNumDev,
&dwVer,
NULL);
if (hr != ERROR_SUCCESS)
goto GetDisplayableNumberExit;
lpExtensionID = (LPLINEEXTENSIONID )GlobalAlloc(GPTR, sizeof(LINEEXTENSIONID));
if (!lpExtensionID)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto GetDisplayableNumberExit;
}
if (m_dwTapiDev == 0xFFFFFFFF)
{
m_dwTapiDev = 0;
}
//
// ChrisK Olympus 5558 6/11/97
// PPTP device will choke the version negotiating
//
do { //E_FAIL here?
hr = lineNegotiateAPIVersion(m_hLineApp,
m_dwTapiDev,
0x00010004,
0x00020000,
&m_dwAPIVersion,
lpExtensionID);
} while (hr != ERROR_SUCCESS && m_dwTapiDev++ < dwNumDev - 1);
if (m_dwTapiDev >= dwNumDev)
{
m_dwTapiDev = 0;
}
// ditch it since we don't use it
//
if (lpExtensionID) GlobalFree(lpExtensionID);
lpExtensionID = NULL;
if (hr != ERROR_SUCCESS)
goto GetDisplayableNumberExit;
// Format the phone number
//
lpOutput1 = (LPLINETRANSLATEOUTPUT)GlobalAlloc(GPTR, sizeof(LINETRANSLATEOUTPUT));
if (!lpOutput1)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto GetDisplayableNumberExit;
}
lpOutput1->dwTotalSize = sizeof(LINETRANSLATEOUTPUT);
// Turn the canonical form into the "displayable" form
//
hr = lineTranslateAddress(m_hLineApp, m_dwTapiDev,m_dwAPIVersion,
m_szPhoneNumber, 0,
LINETRANSLATEOPTION_CANCELCALLWAITING,
lpOutput1);
// We've seen hr == ERROR_SUCCESS but the size is too small,
// Also, the docs hint that some error cases are due to struct too small.
if (lpOutput1->dwNeededSize > lpOutput1->dwTotalSize)
{
lpOutput2 = (LPLINETRANSLATEOUTPUT)GlobalAlloc(GPTR, (size_t)lpOutput1->dwNeededSize);
if (!lpOutput2)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto GetDisplayableNumberExit;
}
lpOutput2->dwTotalSize = lpOutput1->dwNeededSize;
GlobalFree(lpOutput1);
lpOutput1 = lpOutput2;
lpOutput2 = NULL;
hr = lineTranslateAddress(m_hLineApp, m_dwTapiDev,
m_dwAPIVersion, m_szPhoneNumber,0,
LINETRANSLATEOPTION_CANCELCALLWAITING,
lpOutput1);
}
if (hr != ERROR_SUCCESS)
{
goto GetDisplayableNumberExit;
}
if (m_pszDisplayable)
{
GlobalFree(m_pszDisplayable);
}
m_pszDisplayable = (LPWSTR)GlobalAlloc(GPTR, ((size_t)lpOutput1->dwDisplayableStringSize+1));
if (!m_pszDisplayable)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto GetDisplayableNumberExit;
}
lstrcpyn(m_pszDisplayable,
(LPWSTR)&((LPBYTE)lpOutput1)[lpOutput1->dwDisplayableStringOffset],
(int)(lpOutput1->dwDisplayableStringSize/sizeof(WCHAR)));
WCHAR szAreaCode[MAX_AREACODE+1];
WCHAR szCountryCode[8];
if (SUCCEEDED(tapiGetLocationInfo(szCountryCode, szAreaCode)))
{
if (szCountryCode[0] != L'\0')
m_dwCountryCode = _wtoi(szCountryCode);
else
m_dwCountryCode = 1;
}
else
{
m_dwCountryCode = 1;
}
}
GetDisplayableNumberExit:
if (lpOutput1) GlobalFree(lpOutput1);
if (m_hLineApp) lineShutdown(m_hLineApp);
// Release ownership of the critical section
LeaveCriticalSection (&m_csMyCriticalSection);
return hr;
}
BOOL CRefDial::FShouldRetry(HRESULT hrErr)
{
BOOL bRC;
m_uiRetry++;
if (hrErr == ERROR_LINE_BUSY ||
hrErr == ERROR_VOICE_ANSWER ||
hrErr == ERROR_NO_ANSWER ||
hrErr == ERROR_NO_CARRIER ||
hrErr == ERROR_AUTHENTICATION_FAILURE ||
hrErr == ERROR_PPP_TIMEOUT ||
hrErr == ERROR_REMOTE_DISCONNECTION ||
hrErr == ERROR_AUTH_INTERNAL ||
hrErr == ERROR_PROTOCOL_NOT_CONFIGURED ||
hrErr == ERROR_PPP_NO_PROTOCOLS_CONFIGURED)
{
bRC = TRUE;
} else {
bRC = FALSE;
}
bRC = bRC && m_uiRetry < MAX_RETIES;
return bRC;
}
DWORD CRefDial:: DialThreadInit(LPVOID pdata)
{
WCHAR szPassword[PWLEN+1];
WCHAR szUserName[UNLEN + 1];
WCHAR szDomain[DNLEN+1];
LPRASDIALPARAMS lpRasDialParams = NULL;
LPRASDIALEXTENSIONS lpRasDialExtentions = NULL;
HRESULT hr = ERROR_SUCCESS;
BOOL bPW;
DWORD dwResult;
// Initialize the dial error member
m_dwRASErr = 0;
if (!m_pcRNA)
{
hr = E_FAIL;
goto DialExit;
}
// Get connectoid information
//
lpRasDialParams = (LPRASDIALPARAMS)GlobalAlloc(GPTR, sizeof(RASDIALPARAMS));
if (!lpRasDialParams)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto DialExit;
}
lpRasDialParams->dwSize = sizeof(RASDIALPARAMS);
lstrcpyn(lpRasDialParams->szEntryName, m_szConnectoid,MAX_CHARS_IN_BUFFER(lpRasDialParams->szEntryName));
bPW = FALSE;
hr = m_pcRNA->RasGetEntryDialParams(NULL, lpRasDialParams,&bPW);
if (hr != ERROR_SUCCESS)
{
goto DialExit;
}
lpRasDialExtentions = (LPRASDIALEXTENSIONS)GlobalAlloc(GPTR, sizeof(RASDIALEXTENSIONS));
if (lpRasDialExtentions)
{
lpRasDialExtentions->dwSize = sizeof(RASDIALEXTENSIONS);
lpRasDialExtentions->dwfOptions = RDEOPT_UsePrefixSuffix;
}
//
// Add the user's password
//
szPassword[0] = 0;
szUserName[0] = 0;
WCHAR szOOBEInfoINIFile[MAX_PATH];
SearchPath(NULL, cszOOBEINFOINI, NULL, MAX_CHARS_IN_BUFFER(szOOBEInfoINIFile), szOOBEInfoINIFile, NULL);
GetPrivateProfileString(INFFILE_USER_SECTION,
INFFILE_PASSWORD,
NULLSZ,
szPassword,
PWLEN + 1,
*m_szCurrentDUNFile != 0 ? m_szCurrentDUNFile : m_szISPFile);
if (m_lpGatherInfo->m_bUsePhbk)
{
if (GetPrivateProfileString(DUN_SECTION,
USERNAME,
NULLSZ,
szUserName,
UNLEN + 1,
szOOBEInfoINIFile))
{
if(szUserName[0])
lstrcpy(lpRasDialParams->szUserName, szUserName);
}
}
if(szPassword[0])
lstrcpy(lpRasDialParams->szPassword, szPassword);
GetPrivateProfileString(INFFILE_USER_SECTION,
INFFILE_DOMAIN,
NULLSZ,
szDomain,
DNLEN + 1,
*m_szCurrentDUNFile != 0 ? m_szCurrentDUNFile : m_szISPFile);
szDomain[0] = 0;
if (szDomain[0])
lstrcpy(lpRasDialParams->szDomain, szDomain);
dwResult = m_pcRNA->RasDial( lpRasDialExtentions,
NULL,
lpRasDialParams,
1,
CRefDial::RasDialFunc,
&m_hrasconn);
if (( dwResult != ERROR_SUCCESS))
{
// We failed to connect for some reason, so hangup
if (m_hrasconn)
{
if (m_pcRNA)
{
m_pcRNA->RasHangUp(m_hrasconn);
m_hrasconn = NULL;
}
}
goto DialExit;
}
if (m_bFromPhoneBook && (GetDisplayableNumber() == ERROR_SUCCESS))
{
if (m_pszOriginalDisplayable)
GlobalFree(m_pszOriginalDisplayable);
m_pszOriginalDisplayable = (LPWSTR)GlobalAlloc(GPTR, BYTES_REQUIRED_BY_SZ(m_pszDisplayable));
lstrcpy(m_pszOriginalDisplayable, m_pszDisplayable);
TRACE1(L"DialThreadInit: Dialing phone number %s",
m_pszOriginalDisplayable);
m_bFromPhoneBook = FALSE;
}
DialExit:
if (lpRasDialParams)
GlobalFree(lpRasDialParams);
lpRasDialParams = NULL;
if (lpRasDialExtentions)
GlobalFree(lpRasDialExtentions);
lpRasDialExtentions = NULL;
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_DIAL_DONE, 0, 0);
//m_dwRASErr = RasErrorToIDS(hr);
m_dwRASErr = hr;
return S_OK;
}
DWORD WINAPI DoDial(LPVOID lpv)
{
if (gpCommMgr)
gpCommMgr->m_pRefDial->DialThreadInit(NULL);
return 1;
}
// This function will perform the actual dialing
HRESULT CRefDial::DoConnect(BOOL * pbRetVal)
{
//Fix for redialing, on win9x we need to make sure we "hangup"
//and free the rna resources in case we are redialing.
//NT - is smart enough not to need it but it won't hurt.
if (m_hrasconn)
{
if (m_pcRNA)
m_pcRNA->RasHangUp(m_hrasconn);
m_hrasconn = NULL;
}
if (CONNECTED_REFFERAL == m_dwCnType)
FormReferralServerURL(pbRetVal);
#if defined(PRERELEASE)
if (FCampusNetOverride())
{
m_bModemOverride = TRUE;
if (gpCommMgr)
{
// Pretend we have the connection
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONCONNECTED, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType , (LPARAM)0);
// Pretend we have connection and downloaded
//PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_DOWNLOAD_DONE, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType, (LPARAM)0);
}
}
#endif
if (!m_bModemOverride)
{
DWORD dwThreadID;
if (m_hThread)
CloseHandle(m_hThread);
m_hDialThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)DoDial,
(LPVOID)0,
0,
&dwThreadID);
}
m_bModemOverride = FALSE;
*pbRetVal = (NULL != m_hThread);
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Function: MyRasGetEntryProperties()
//
// Synopsis: Performs some buffer size checks and then calls RasGetEntryProperties()
// See the RasGetEntryProperties() docs to understand why this is needed.
//
// Arguments: Same as RasGetEntryProperties with the following exceptions:
// lplpRasEntryBuff -- pointer to a pointer to a RASENTRY struct. On successfull
// return, *lplpRasEntryBuff will point to the RASENTRY struct
// and buffer returned by RasGetEntryProperties.
// NOTE: should not have memory allocated to it at call time!
// To emphasize this point, *lplpRasEntryBuff must be NULL
// lplpRasDevInfoBuff -- pointer to a pointer to a RASDEVINFO struct. On successfull
// return, *lplpRasDevInfoBuff will point to the RASDEVINFO struct
// and buffer returned by RasGetEntryProperties.
// NOTE: should not have memory allocated to it at call time!
// To emphasize this point, *lplpRasDevInfoBuff must be NULL
// NOTE: Even on a successfull call to RasGetEntryProperties,
// *lplpRasDevInfoBuff may return with a value of NULL
// (occurs when there is no extra device info)
//
// Returns: ERROR_NOT_ENOUGH_MEMORY if unable to allocate either RASENTRY or RASDEVINFO buffer
// Otherwise, it retuns the error code from the call to RasGetEntryProperties.
// NOTE: if return is anything other than ERROR_SUCCESS, *lplpRasDevInfoBuff and
// *lplpRasEntryBuff will be NULL,
// and *lpdwRasEntryBuffSize and *lpdwRasDevInfoBuffSize will be 0
//
// Example:
//
// LPRASENTRY lpRasEntry = NULL;
// LPRASDEVINFO lpRasDevInfo = NULL;
// DWORD dwRasEntrySize, dwRasDevInfoSize;
//
// hr = MyRasGetEntryProperties( NULL,
// g_pcDialErr->m_szConnectoid,
// &lpRasEntry,
// &dwRasEntrySize,
// &lpRasDevInfo,
// &dwRasDevInfoSize);
//
//
// if (hr != ERROR_SUCCESS)
// {
// //handle errors here
// } else
// {
// //continue processing
// }
//
//
// History: 9/10/96 JMazner Created for icwconn2
// 9/17/96 JMazner Adapted for icwconn1
// 1/8/98 DONALDM Moved to the new ICW/GetConn project
//----------------------------------------------------------------------------
HRESULT CRefDial::MyRasGetEntryProperties(LPWSTR lpszPhonebookFile,
LPWSTR lpszPhonebookEntry,
LPRASENTRY *lplpRasEntryBuff,
LPDWORD lpdwRasEntryBuffSize,
LPRASDEVINFO *lplpRasDevInfoBuff,
LPDWORD lpdwRasDevInfoBuffSize)
{
HRESULT hr;
DWORD dwOldDevInfoBuffSize;
//Assert( NULL != lplpRasEntryBuff );
//Assert( NULL != lpdwRasEntryBuffSize );
//Assert( NULL != lplpRasDevInfoBuff );
//Assert( NULL != lpdwRasDevInfoBuffSize );
*lpdwRasEntryBuffSize = 0;
*lpdwRasDevInfoBuffSize = 0;
if (!m_pcRNA)
{
m_pcRNA = new RNAAPI;
hr = ERROR_NOT_ENOUGH_MEMORY;
goto MyRasGetEntryPropertiesErrExit;
}
// use RasGetEntryProperties with a NULL lpRasEntry pointer to find out size buffer we need
// As per the docs' recommendation, do the same with a NULL lpRasDevInfo pointer.
hr = m_pcRNA->RasGetEntryProperties(lpszPhonebookFile, lpszPhonebookEntry,
(LPBYTE) NULL,
lpdwRasEntryBuffSize,
(LPBYTE) NULL,
lpdwRasDevInfoBuffSize);
// we expect the above call to fail because the buffer size is 0
// If it doesn't fail, that means our RasEntry is messed, so we're in trouble
if( ERROR_BUFFER_TOO_SMALL != hr )
{
goto MyRasGetEntryPropertiesErrExit;
}
// dwRasEntryBuffSize and dwRasDevInfoBuffSize now contain the size needed for their
// respective buffers, so allocate the memory for them
// dwRasEntryBuffSize should never be less than the size of the RASENTRY struct.
// If it is, we'll run into problems sticking values into the struct's fields
//Assert( *lpdwRasEntryBuffSize >= sizeof(RASENTRY) );
if (m_reflpRasEntryBuff)
{
if (*lpdwRasEntryBuffSize > m_reflpRasEntryBuff->dwSize)
{
LPRASENTRY lpRasEntryTemp = (LPRASENTRY)GlobalReAlloc(m_reflpRasEntryBuff, *lpdwRasEntryBuffSize, GPTR);
if (lpRasEntryTemp)
{
m_reflpRasEntryBuff = lpRasEntryTemp;
}
else
{
GlobalFree(m_reflpRasEntryBuff);
m_reflpRasEntryBuff = NULL;
}
}
}
else
{
m_reflpRasEntryBuff = (LPRASENTRY)GlobalAlloc(GPTR, *lpdwRasEntryBuffSize);
}
if (!m_reflpRasEntryBuff)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto MyRasGetEntryPropertiesErrExit;
}
// This is a bit convoluted: lpRasEntrySize->dwSize needs to contain the size of _only_ the
// RASENTRY structure, and _not_ the actual size of the buffer that lpRasEntrySize points to.
// This is because the dwSize field is used by RAS for compatability purposes to determine which
// version of the RASENTRY struct we're using.
// Same holds for lpRasDevInfo->dwSize
m_reflpRasEntryBuff->dwSize = sizeof(RASENTRY);
//
// Allocate the DeviceInfo size that RasGetEntryProperties told us we needed.
// If size is 0, don't alloc anything
//
if( *lpdwRasDevInfoBuffSize > 0 )
{
//Assert( *lpdwRasDevInfoBuffSize >= sizeof(RASDEVINFO) );
if (m_reflpRasDevInfoBuff)
{
// check if existing size is not sufficient
if ( *lpdwRasDevInfoBuffSize > m_reflpRasDevInfoBuff->dwSize )
{
LPRASDEVINFO lpRasDevInfoTemp = (LPRASDEVINFO)GlobalReAlloc(m_reflpRasDevInfoBuff, *lpdwRasDevInfoBuffSize, GPTR);
if (lpRasDevInfoTemp)
{
m_reflpRasDevInfoBuff = lpRasDevInfoTemp;
}
else
{
GlobalFree(m_reflpRasDevInfoBuff);
m_reflpRasDevInfoBuff = NULL;
}
}
}
else
{
m_reflpRasDevInfoBuff = (LPRASDEVINFO)GlobalAlloc(GPTR, *lpdwRasDevInfoBuffSize);
}
if (!m_reflpRasDevInfoBuff)
{
hr = ERROR_NOT_ENOUGH_MEMORY;
goto MyRasGetEntryPropertiesErrExit;
}
}
else
{
m_reflpRasDevInfoBuff = NULL;
}
if( m_reflpRasDevInfoBuff )
{
m_reflpRasDevInfoBuff->dwSize = sizeof(RASDEVINFO);
}
// now we're ready to make the actual call...
// jmazner see below for why this is needed
dwOldDevInfoBuffSize = *lpdwRasDevInfoBuffSize;
hr = m_pcRNA->RasGetEntryProperties(lpszPhonebookFile, lpszPhonebookEntry,
(LPBYTE) m_reflpRasEntryBuff,
lpdwRasEntryBuffSize,
(LPBYTE) m_reflpRasDevInfoBuff,
lpdwRasDevInfoBuffSize);
// jmazner 10/7/96 Normandy #8763
// For unknown reasons, in some cases on win95, devInfoBuffSize increases after the above call,
// but the return code indicates success, not BUFFER_TOO_SMALL. If this happens, set the
// size back to what it was before the call, so the DevInfoBuffSize and the actuall space allocated
// for the DevInfoBuff match on exit.
if( (ERROR_SUCCESS == hr) && (dwOldDevInfoBuffSize != *lpdwRasDevInfoBuffSize) )
{
*lpdwRasDevInfoBuffSize = dwOldDevInfoBuffSize;
}
*lplpRasEntryBuff = m_reflpRasEntryBuff;
*lplpRasDevInfoBuff = m_reflpRasDevInfoBuff;
return( hr );
MyRasGetEntryPropertiesErrExit:
if(m_reflpRasEntryBuff)
{
GlobalFree(m_reflpRasEntryBuff);
m_reflpRasEntryBuff = NULL;
*lplpRasEntryBuff = NULL;
}
if(m_reflpRasDevInfoBuff)
{
GlobalFree(m_reflpRasDevInfoBuff);
m_reflpRasDevInfoBuff = NULL;
*lplpRasDevInfoBuff = NULL;
}
*lpdwRasEntryBuffSize = 0;
*lpdwRasDevInfoBuffSize = 0;
return( hr );
}
HRESULT MyGetFileVersion(LPCWSTR pszFileName, LPGATHERINFO lpGatherInfo)
{
HRESULT hr = ERROR_NOT_ENOUGH_MEMORY;
DWORD dwSize = 0;
DWORD dwTemp = 0;
LPVOID pv = NULL, pvVerInfo = NULL;
UINT uiSize;
DWORD dwVerPiece;
//int idx;
// verify parameters
//
//Assert(pszFileName && lpGatherInfo);
// Get version
//
dwSize = GetFileVersionInfoSize((LPWSTR)pszFileName, &dwTemp);
if (!dwSize)
{
hr = GetLastError();
goto MyGetFileVersionExit;
}
pv = (LPVOID)GlobalAlloc(GPTR, (size_t)dwSize);
if (!pv) goto MyGetFileVersionExit;
if (!GetFileVersionInfo((LPWSTR)pszFileName, dwTemp,dwSize,pv))
{
hr = GetLastError();
goto MyGetFileVersionExit;
}
if (!VerQueryValue(pv, L"\\\0",&pvVerInfo,&uiSize))
{
hr = GetLastError();
goto MyGetFileVersionExit;
}
pvVerInfo = (LPVOID)((DWORD_PTR)pvVerInfo + sizeof(DWORD)*4);
lpGatherInfo->m_szSUVersion[0] = L'\0';
dwVerPiece = (*((LPDWORD)pvVerInfo)) >> 16;
wsprintf(lpGatherInfo->m_szSUVersion, L"%d.",dwVerPiece);
dwVerPiece = (*((LPDWORD)pvVerInfo)) & 0x0000ffff;
wsprintf(lpGatherInfo->m_szSUVersion, L"%s%d.",lpGatherInfo->m_szSUVersion,dwVerPiece);
dwVerPiece = (((LPDWORD)pvVerInfo)[1]) >> 16;
wsprintf(lpGatherInfo->m_szSUVersion, L"%s%d.",lpGatherInfo->m_szSUVersion,dwVerPiece);
dwVerPiece = (((LPDWORD)pvVerInfo)[1]) & 0x0000ffff;
wsprintf(lpGatherInfo->m_szSUVersion, L"%s%d",lpGatherInfo->m_szSUVersion,dwVerPiece);
if (!VerQueryValue(pv, L"\\VarFileInfo\\Translation",&pvVerInfo,&uiSize))
{
hr = GetLastError();
goto MyGetFileVersionExit;
}
// separate version information from character set
lpGatherInfo->m_lcidApps = (LCID)(LOWORD(*(DWORD*)pvVerInfo));
hr = ERROR_SUCCESS;
MyGetFileVersionExit:
if (pv) GlobalFree(pv);
return hr;
}
DWORD CRefDial::FillGatherInfoStruct(LPGATHERINFO lpGatherInfo)
{
HKEY hkey = NULL;
SYSTEM_INFO si;
WCHAR szTempPath[MAX_PATH];
DWORD dwRet = ERROR_SUCCESS;
lpGatherInfo->m_lcidUser = GetUserDefaultLCID();
lpGatherInfo->m_lcidSys = GetSystemDefaultLCID();
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osvi))
{
// Nevermind, we'll just assume the version is 0.0 if we can't read it
//
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
}
lpGatherInfo->m_dwOS = osvi.dwPlatformId;
lpGatherInfo->m_dwMajorVersion = osvi.dwMajorVersion;
lpGatherInfo->m_dwMinorVersion = osvi.dwMinorVersion;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
GetSystemInfo(&si);
lpGatherInfo->m_wArchitecture = si.wProcessorArchitecture;
// Sign-up version
//
lpGatherInfo->m_szSUVersion[0] = L'\0';
if( MyGetModuleFileName(0/*_Module.GetModuleInstance()*/, szTempPath, MAX_PATH))
{
if ((MyGetFileVersion(szTempPath, lpGatherInfo)) != ERROR_SUCCESS)
{
return (GetLastError());
}
}
else
return( GetLastError() );
// 2/20/97 jmazner Olympus #259
if ( RegOpenKey(HKEY_LOCAL_MACHINE, ICWSETTINGSPATH,&hkey) == ERROR_SUCCESS)
{
DWORD dwSize;
DWORD dwType;
dwType = REG_SZ;
dwSize = BYTES_REQUIRED_BY_CCH(MAX_RELPROD + 1);
if (RegQueryValueEx(hkey, RELEASEPRODUCTKEY,NULL,&dwType,(LPBYTE)&lpGatherInfo->m_szRelProd[0],&dwSize) != ERROR_SUCCESS)
lpGatherInfo->m_szRelProd[0] = L'\0';
dwSize = BYTES_REQUIRED_BY_CCH(MAX_RELVER + 1);
if (RegQueryValueEx(hkey, RELEASEVERSIONKEY,NULL,&dwType,(LPBYTE)&lpGatherInfo->m_szRelVer[0],&dwSize) != ERROR_SUCCESS)
lpGatherInfo->m_szRelVer[0] = L'\0';
RegCloseKey(hkey);
}
// PromoCode
lpGatherInfo->m_szPromo[0] = L'\0';
WCHAR szPIDPath[MAX_PATH]; // Reg path to the PID
// Form the Path, it is HKLM\\Software\\Microsoft\Windows[ NT]\\CurrentVersion
lstrcpy(szPIDPath, L"");
// Form the Path, it is HKLM\\Software\\Microsoft\Windows[ NT]\\CurrentVersion
lstrcpy(szPIDPath, L"Software\\Microsoft\\Windows");
lstrcat(szPIDPath, L"\\CurrentVersion");
BYTE byDigitalPID[MAX_DIGITAL_PID];
// Get the Product ID for this machine
if ( RegOpenKey(HKEY_LOCAL_MACHINE, szPIDPath,&hkey) == ERROR_SUCCESS)
{
DWORD dwSize;
DWORD dwType;
dwType = REG_BINARY;
dwSize = sizeof(byDigitalPID);
if (RegQueryValueEx(hkey,
c_szRegStrValDigitalPID,
NULL,
&dwType,
(LPBYTE)byDigitalPID,
&dwSize) == ERROR_SUCCESS)
{
// BINHEX the digital PID data so we can send it to the ref_server
int i = 0;
BYTE by;
for (DWORD dwX = 0; dwX < dwSize; dwX++)
{
by = byDigitalPID[dwX];
m_szPID[i++] = g_BINTOHEXLookup[((by & 0xF0) >> 4)];
m_szPID[i++] = g_BINTOHEXLookup[(by & 0x0F)];
}
m_szPID[i] = L'\0';
}
else
{
m_szPID[0] = L'\0';
}
RegCloseKey(hkey);
}
return( dwRet );
}
// ############################################################################
HRESULT CRefDial::CreateEntryFromDUNFile(LPWSTR pszDunFile)
{
WCHAR szFileName[MAX_PATH];
WCHAR szUserName[UNLEN+1];
WCHAR szPassword[PWLEN+1];
LPWSTR pszTemp;
HRESULT hr;
BOOL fNeedsRestart=FALSE;
hr = ERROR_SUCCESS;
// Get fully qualified path name
//
if (!SearchPath(NULL, pszDunFile,NULL,MAX_PATH,&szFileName[0],&pszTemp))
{
hr = ERROR_FILE_NOT_FOUND;
goto CreateEntryFromDUNFileExit;
}
// save current DUN file name in global
lstrcpy(m_szCurrentDUNFile, &szFileName[0]);
hr = m_ISPImport.ImportConnection (&szFileName[0], m_szISPSupportNumber, m_szEntryName, szUserName, szPassword, &fNeedsRestart);
// place the name of the connectoid in the registry
//
if (ERROR_SUCCESS != (StoreInSignUpReg((LPBYTE)m_szEntryName,
BYTES_REQUIRED_BY_SZ(m_szEntryName),
REG_SZ, RASENTRYVALUENAME)))
{
goto CreateEntryFromDUNFileExit;
}
lstrcpy(m_szLastDUNFile, pszDunFile);
CreateEntryFromDUNFileExit:
return hr;
}
HRESULT CRefDial::SetupForRASDialing
(
LPGATHERINFO lpGatherInfo,
HINSTANCE hPHBKDll,
LPDWORD lpdwPhoneBook,
PSUGGESTINFO pSuggestInfo,
WCHAR *pszConnectoid,
BOOL FAR *bConnectiodCreated
)
{
WCHAR szEntry[MAX_RASENTRYNAME];
DWORD dwSize = BYTES_REQUIRED_BY_CCH(MAX_RASENTRYNAME);
RASENTRY *prasentry = NULL;
RASDEVINFO *prasdevinfo = NULL;
DWORD dwRasentrySize = 0;
DWORD dwRasdevinfoSize = 0;
HINSTANCE hRasDll = NULL;
LPRASCONN lprasconn = NULL;
HRESULT hr = ERROR_NOT_ENOUGH_MEMORY;
m_bUserInitiateHangup = FALSE;
// Load the connectoid
//
if (!m_pcRNA)
m_pcRNA = new RNAAPI;
if (!m_pcRNA)
goto SetupForRASDialingExit;
prasentry = (RASENTRY*)GlobalAlloc(GPTR, sizeof(RASENTRY)+2);
//Assert(prasentry);
if (!prasentry)
{
hr = GetLastError();
goto SetupForRASDialingExit;
}
prasentry->dwSize = sizeof(RASENTRY);
dwRasentrySize = sizeof(RASENTRY);
prasdevinfo = (RASDEVINFO*)GlobalAlloc(GPTR, sizeof(RASDEVINFO));
if (!prasdevinfo)
{
hr = GetLastError();
goto SetupForRASDialingExit;
}
prasdevinfo->dwSize = sizeof(RASDEVINFO);
dwRasdevinfoSize = sizeof(RASDEVINFO);
hr = ReadSignUpReg((LPBYTE)&szEntry[0], &dwSize, REG_SZ,
RASENTRYVALUENAME);
if (hr != ERROR_SUCCESS)
goto SetupForRASDialingExit;
hr = m_pcRNA->RasGetEntryProperties(NULL, szEntry,
(LPBYTE)prasentry,
&dwRasentrySize,
(LPBYTE)prasdevinfo,
&dwRasdevinfoSize);
if (hr == ERROR_BUFFER_TOO_SMALL)
{
GlobalFree(prasentry);
prasentry = (RASENTRY*)GlobalAlloc(GPTR, ((size_t)dwRasentrySize));
prasentry->dwSize = dwRasentrySize;
GlobalFree(prasdevinfo);
prasdevinfo = (RASDEVINFO*)GlobalAlloc(GPTR, ((size_t)dwRasdevinfoSize));
prasdevinfo->dwSize = dwRasdevinfoSize;
hr = m_pcRNA->RasGetEntryProperties(NULL, szEntry,
(LPBYTE)prasentry,
&dwRasentrySize,
(LPBYTE)prasdevinfo,
&dwRasdevinfoSize);
}
if (hr != ERROR_SUCCESS)
goto SetupForRASDialingExit;
//
// Check to see if the phone number was filled in
//
if (lstrcmp(&prasentry->szLocalPhoneNumber[0], DUN_NOPHONENUMBER) == 0)
{
//
// If phonenumber is not filled in by the ISP file,
// get phone number from oobe phone book
//
m_bFromPhoneBook = TRUE;
hr = ReadPhoneBook(lpGatherInfo, pSuggestInfo);
}
else
{
ZeroMemory(pszConnectoid, dwSize);
hr = ReadSignUpReg((LPBYTE)pszConnectoid, &dwSize, REG_SZ,
RASENTRYVALUENAME);
if (hr != ERROR_SUCCESS)
goto SetupForRASDialingExit;
// Use the RASENTRY that we have to create the connectiod
hr = m_pcRNA->RasSetEntryProperties(NULL,
pszConnectoid,
(LPBYTE)prasentry,
dwRasentrySize,
(LPBYTE)prasdevinfo,
dwRasdevinfoSize);
*bConnectiodCreated = TRUE;
}
SetupForRASDialingExit:
if (prasentry)
GlobalFree(prasentry);
if (prasdevinfo)
GlobalFree(prasdevinfo);
return hr;
}
// 10/22/96 jmazner Normandy #9923
// Since in SetupConnectoidExit we're treating results other than ERROR_SUCCESS as
// indicating successfull completion, we need bSuccess to provide a simple way for the
// caller to tell whether the function completed.
HRESULT CRefDial::SetupConnectoid
(
PSUGGESTINFO pSuggestInfo,
int irc,
WCHAR *pszConnectoid,
DWORD dwSize,
BOOL *pbSuccess
)
{
HRESULT hr = ERROR_NOT_ENOUGH_MEMORY;
RASENTRY *prasentry = NULL;
RASDEVINFO *prasdevinfo = NULL;
DWORD dwRasentrySize = 0;
DWORD dwRasdevinfoSize = 0;
HINSTANCE hPHBKDll = NULL;
HINSTANCE hRasDll =NULL;
LPWSTR lpszSetupFile;
LPRASCONN lprasconn = NULL;
//Assert(pbSuccess);
if (!pSuggestInfo)
{
hr = ERROR_PHBK_NOT_FOUND;
goto SetupConnectoidExit;
}
lpszSetupFile = *m_szCurrentDUNFile != 0 ? m_szCurrentDUNFile : m_szISPFile;
WCHAR szFileName[MAX_PATH];
LPWSTR pszTemp;
SearchPath(NULL, pSuggestInfo->AccessEntry.szDataCenter,NULL,MAX_PATH,&szFileName[0],&pszTemp);
if(0 != lstrcmpi(m_szCurrentDUNFile, szFileName))
{
hr = CreateEntryFromDUNFile(pSuggestInfo->AccessEntry.szDataCenter);
if (hr == ERROR_SUCCESS)
{
ZeroMemory(pszConnectoid, dwSize);
hr = ReadSignUpReg((LPBYTE)pszConnectoid, &dwSize, REG_SZ,
RASENTRYVALUENAME);
if (hr != ERROR_SUCCESS)
goto SetupConnectoidExit;
if( prasentry )
{
GlobalFree( prasentry );
prasentry = NULL;
dwRasentrySize = NULL;
}
if( prasdevinfo )
{
GlobalFree( prasdevinfo );
prasdevinfo = NULL;
dwRasdevinfoSize = NULL;
}
}
else
{
// 10/22/96 jmazner Normandy #9923
goto SetupConnectoidExit;
}
}
hr = MyRasGetEntryProperties(NULL,
pszConnectoid,
&prasentry,
&dwRasentrySize,
&prasdevinfo,
&dwRasdevinfoSize);
if (hr != ERROR_SUCCESS || NULL == prasentry)
goto SetupConnectoidExit;
/*
else
{
goto SetupConnectoidExit;
}*/
prasentry->dwCountryID = pSuggestInfo->AccessEntry.dwCountryID;
lstrcpyn(prasentry->szAreaCode,
pSuggestInfo->AccessEntry.szAreaCode,
MAX_CHARS_IN_BUFFER(prasentry->szAreaCode));
lstrcpyn(prasentry->szLocalPhoneNumber,
pSuggestInfo->AccessEntry.szAccessNumber,
MAX_CHARS_IN_BUFFER(prasentry->szLocalPhoneNumber));
prasentry->dwCountryCode = 0;
prasentry->dwfOptions |= RASEO_UseCountryAndAreaCodes;
// 10/19/96 jmazner Multiple modems problems
// If no device name and type has been specified, grab the one we've stored
// in ConfigRasEntryDevice
if( 0 == lstrlen(prasentry->szDeviceName) )
{
// doesn't make sense to have an empty device name but a valid device type
//Assert( 0 == lstrlen(prasentry->szDeviceType) );
// double check that we've already stored the user's choice.
//Assert( lstrlen(m_ISPImport.m_szDeviceName) );
//Assert( lstrlen(m_ISPImport.m_szDeviceType) );
lstrcpyn( prasentry->szDeviceName, m_ISPImport.m_szDeviceName, lstrlen(m_ISPImport.m_szDeviceName) );
lstrcpyn( prasentry->szDeviceType, m_ISPImport.m_szDeviceType, lstrlen(m_ISPImport.m_szDeviceType) );
}
// Write out new connectoid
if (m_pcRNA)
hr = m_pcRNA->RasSetEntryProperties(NULL, pszConnectoid,
(LPBYTE)prasentry,
dwRasentrySize,
(LPBYTE)prasdevinfo,
dwRasdevinfoSize);
// Set this connetiod to have not proxy enabled
/*
WCHAR szConnectionProfile[REGSTR_MAX_VALUE_LENGTH];
lstrcpy(szConnectionProfile, c_szRASProfiles);
lstrcat(szConnectionProfile, L"\\");
lstrcat(szConnectionProfile, pszConnectoid);
reg.CreateKey(HKEY_CURRENT_USER, szConnectionProfile);
reg.SetValue(c_szProxyEnable, (DWORD)0);*/
SetupConnectoidExit:
*pbSuccess = FALSE;
if (hr == ERROR_SUCCESS)
*pbSuccess = TRUE;
return hr;
}
void CRefDial::GetISPFileSettings(LPWSTR lpszFile)
{
WCHAR szTemp[INTERNET_MAX_URL_LENGTH];
/*GetINTFromISPFile(lpszFile,
(LPWSTR)cszBrandingSection,
(LPWSTR)cszBrandingFlags,
(int FAR *)&m_lBrandingFlags,
BRAND_DEFAULT);*/
// Read the Support Number
if (ERROR_SUCCESS == GetDataFromISPFile(lpszFile,
(LPWSTR)cszSupportSection,
(LPWSTR)cszSupportNumber,
szTemp,
MAX_CHARS_IN_BUFFER(szTemp)))
{
m_bstrSupportNumber= SysAllocString(szTemp);
}
else
m_bstrSupportNumber = NULL;
if (ERROR_SUCCESS == GetDataFromISPFile(lpszFile,
(LPWSTR)cszLoggingSection,
(LPWSTR)cszStartURL,
szTemp,
MAX_CHARS_IN_BUFFER(szTemp)))
{
m_bstrLoggingStartUrl = SysAllocString(szTemp);
}
else
m_bstrLoggingStartUrl = NULL;
if (ERROR_SUCCESS == GetDataFromISPFile(lpszFile,
(LPWSTR)cszLoggingSection,
(LPWSTR)cszEndURL,
szTemp,
MAX_CHARS_IN_BUFFER(szTemp)))
{
m_bstrLoggingEndUrl = SysAllocString(szTemp);
}
else
m_bstrLoggingEndUrl = NULL;
}
// This function will accept user selected values that are necessary to
// setup a connectiod for dialing
// Returns:
// TRUE OK to dial
// FALSE Some kind of problem
// QuitWizard - TRUE, then terminate
// UserPickNumber - TRUE, then display Pick a Number DLG
// QuitWizard and UserPickNumber both FALSE, then just
// display the page prior to Dialing UI.
HRESULT CRefDial::SetupForDialing
(
UINT nType,
BSTR bstrISPFile,
DWORD dwCountry,
BSTR bstrAreaCode,
DWORD dwFlag,
DWORD dwAppMode,
DWORD dwMigISPIdx,
LPCWSTR szRasDeviceName
)
{
HRESULT hr = S_OK;
long lRC = 0;
HINSTANCE hPHBKDll = NULL;
DWORD dwPhoneBook = 0;
BOOL bSuccess = FALSE;
BOOL bConnectiodCreated = FALSE;
LPWSTR pszTemp;
WCHAR szISPPath[MAX_PATH];
WCHAR szShortISPPath[MAX_PATH];
m_dwCnType = nType;
if (!bstrAreaCode)
goto SetupForDialingExit;
if (CONNECTED_ISP_MIGRATE == m_dwCnType) // ACCOUNT MIGRATION
{
if (!m_pCSVList)
ParseISPInfo(NULL, ICW_ISPINFOPath, TRUE);
if (m_pCSVList && (dwMigISPIdx < m_dwNumOfAutoConfigOffers))
{
ISPLIST* pCurr = m_pCSVList;
for( UINT i = 0; i < dwMigISPIdx && pCurr->pNext != NULL; i++)
pCurr = pCurr->pNext;
if (NULL != (m_pSelectedISPInfo = (CISPCSV *) pCurr->pElement))
{
lstrcpy(szShortISPPath, m_pSelectedISPInfo->get_szISPFilePath());
}
}
}
else // ISP FILE SIGNUP
{
if (!bstrISPFile)
goto SetupForDialingExit;
lstrcpyn(szShortISPPath, bstrISPFile, MAX_PATH);
}
// Locate ISP file
if (!SearchPath(NULL, szShortISPPath,INF_SUFFIX,MAX_PATH,szISPPath,&pszTemp))
{
hr = ERROR_FILE_NOT_FOUND;
goto SetupForDialingExit;
}
if(0 == lstrcmpi(m_szISPFile, szISPPath) &&
0 == lstrcmpi(m_lpGatherInfo->m_szAreaCode, bstrAreaCode) &&
m_lpGatherInfo->m_dwCountryID == dwCountry)
{
if (m_bDialCustom)
{
m_bDialCustom = FALSE;
return S_OK;
}
// If ISP file is the same, no need to recreate connectoid
// Modify the connectiod here
// If we used the phonebook for this connectoid, we need to
// continue and import the dun files. Otherwise, we are done
if (!m_lpGatherInfo->m_bUsePhbk)
{
return S_OK;
}
if (m_bDialAlternative)
{
m_SuggestInfo.dwPick++;
}
}
else
{
BOOL bRet;
RemoveConnectoid(&bRet);
m_SuggestInfo.dwPick = 0;
m_bDialCustom = FALSE;
}
if (CONNECTED_REFFERAL == m_dwCnType)
{
// Check whether the isp file is ICW capable by reading the referral URL
GetPrivateProfileString(INF_SECTION_ISPINFO,
c_szURLReferral,
L"",
m_szRefServerURL,
INTERNET_MAX_URL_LENGTH,
szISPPath);
}
lstrcpy(m_szISPFile, szISPPath);
m_dwAppMode = dwAppMode;
// Initialize failure codes
m_bQuitWizard = FALSE;
m_bUserPickNumber = FALSE;
m_lpGatherInfo->m_bUsePhbk = FALSE;
// Stuff the Area Code, and Country Code into the GatherInfo struct
m_lpGatherInfo->m_dwCountryID = dwCountry;
m_lpGatherInfo->m_dwCountryCode = dwFlag;
lstrcpyn(
m_lpGatherInfo->m_szAreaCode,
bstrAreaCode,
MAX_CHARS_IN_BUFFER(m_lpGatherInfo->m_szAreaCode)
);
m_SuggestInfo.AccessEntry.dwCountryID = dwCountry;
m_SuggestInfo.AccessEntry.dwCountryCode = dwFlag;
lstrcpy(m_SuggestInfo.AccessEntry.szAreaCode, bstrAreaCode);
GetISPFileSettings(szISPPath);
lstrcpyn(
m_ISPImport.m_szDeviceName,
szRasDeviceName,
MAX_CHARS_IN_BUFFER(m_ISPImport.m_szDeviceName)
);
// Read the Connection File information which will create
// a connectiod from the passed in ISP file
hr = ReadConnectionInformation();
// If we failed for some reason above, we need to return
// the error to the caller, and Quit The Wizard.
if (S_OK != hr)
goto SetupForDialingExit;
FillGatherInfoStruct(m_lpGatherInfo);
// Setup, and possible create a connectiod
hr = SetupForRASDialing(m_lpGatherInfo,
hPHBKDll,
&dwPhoneBook,
&m_SuggestInfo,
&m_szConnectoid[0],
&bConnectiodCreated);
if (ERROR_SUCCESS != hr)
{
m_bQuitWizard = TRUE;
goto SetupForDialingExit;
}
// If we have a RASENTRY struct from SetupForRASDialing, then just use it
// otherwise use the suggest info
if (!bConnectiodCreated)
{
// If there is only 1 suggested number, then we setup the
// connectiod, and we are ready to dial
if (1 == m_SuggestInfo.wNumber)
{
hr = SetupConnectoid(&m_SuggestInfo, 0, &m_szConnectoid[0],
sizeof(m_szConnectoid), &bSuccess);
if( !bSuccess )
{
goto SetupForDialingExit;
}
}
else
{
// More than 1 entry in the Phonebook, so we need to
// ask the user which one they want to use
hr = ERROR_FILE_NOT_FOUND;
goto SetupForDialingExit;
}
}
// Success if we get to here
SetupForDialingExit:
if (ERROR_SUCCESS != hr)
*m_szISPFile = 0;
return hr;
}
HRESULT CRefDial::CheckPhoneBook
(
BSTR bstrISPFile,
DWORD dwCountry,
BSTR bstrAreaCode,
DWORD dwFlag,
BOOL *pbRetVal
)
{
HRESULT hr = S_OK;
long lRC = 0;
HINSTANCE hPHBKDll = NULL;
DWORD dwPhoneBook = 0;
BOOL bSuccess = FALSE;
BOOL bConnectiodCreated = FALSE;
LPWSTR pszTemp;
WCHAR szISPPath[MAX_PATH];
*pbRetVal = FALSE;
if (!bstrISPFile || !bstrAreaCode)
{
hr = ERROR_FILE_NOT_FOUND;
goto CheckPhoneBookExit;
}
// Locate ISP file
if (!SearchPath(NULL, bstrISPFile,INF_SUFFIX,MAX_PATH,szISPPath,&pszTemp))
{
hr = ERROR_FILE_NOT_FOUND;
goto CheckPhoneBookExit;
}
//lstrcpy(m_szISPFile, szISPPath);
// Stuff the Area Code, and Country Code into the GatherInfo struct
m_lpGatherInfo->m_dwCountryID = dwCountry;
m_lpGatherInfo->m_dwCountryCode = dwFlag;
lstrcpy(m_lpGatherInfo->m_szAreaCode, bstrAreaCode);
m_SuggestInfo.AccessEntry.dwCountryID = dwCountry;
m_SuggestInfo.AccessEntry.dwCountryCode = dwFlag;
lstrcpy(m_SuggestInfo.AccessEntry.szAreaCode, bstrAreaCode);
//
// If phonenumber is not filled in by the ISP file,
// get phone number from oobe phone book
//
hr = ReadPhoneBook(m_lpGatherInfo, &m_SuggestInfo);
if (ERROR_CANNOT_FIND_PHONEBOOK_ENTRY != hr)
*pbRetVal = TRUE;
CheckPhoneBookExit:
return hr;
}
// This function will determine if we can connect to the next server in
// the same phone call
// Returns:
// S_OK OK to stay connected
// E_FAIL Need to redial
HRESULT CRefDial::CheckStayConnected(BSTR bstrISPFile, BOOL *pbVal)
{
BOOL bSuccess = FALSE;
LPWSTR pszTemp;
WCHAR szISPPath[MAX_PATH];
*pbVal = FALSE;
// Locate ISP file
if (SearchPath(NULL, bstrISPFile,INF_SUFFIX,MAX_PATH,szISPPath,&pszTemp))
{
if (GetPrivateProfileInt(INF_SECTION_CONNECTION,
c_szStayConnected,
0,
szISPPath))
{
*pbVal = TRUE;
}
}
return S_OK;
}
HRESULT CRefDial::RemoveConnectoid(BOOL * pVal)
{
if (m_hrasconn)
DoHangup();
if( (m_pcRNA!=NULL) && (m_szConnectoid[0]!=L'\0') )
{
m_pcRNA->RasDeleteEntry(NULL, m_szConnectoid);
}
return S_OK;
}
HRESULT CRefDial::GetDialPhoneNumber(BSTR * pVal)
{
if (pVal == NULL)
return E_POINTER;
// Generate a Displayable number
if (GetDisplayableNumber() == ERROR_SUCCESS)
*pVal = SysAllocString(m_pszDisplayable);
else
*pVal = SysAllocString(m_szPhoneNumber);
return S_OK;
}
HRESULT CRefDial::GetPhoneBookNumber(BSTR * pVal)
{
if (pVal == NULL)
return E_POINTER;
// Generate a Displayable number
if (m_pszOriginalDisplayable)
*pVal = SysAllocString(m_pszOriginalDisplayable);
else if (GetDisplayableNumber() == ERROR_SUCCESS)
*pVal = SysAllocString(m_pszDisplayable);
else
*pVal = SysAllocString(m_szPhoneNumber);
return S_OK;
}
HRESULT CRefDial::PutDialPhoneNumber(BSTR bstrNewVal)
{
LPRASENTRY lpRasEntry = NULL;
LPRASDEVINFO lpRasDevInfo = NULL;
DWORD dwRasEntrySize = 0;
DWORD dwRasDevInfoSize = 0;
RNAAPI *pcRNA = NULL;
HRESULT hr;
// Get the current RAS entry properties
hr = MyRasGetEntryProperties(NULL,
m_szConnectoid,
&lpRasEntry,
&dwRasEntrySize,
&lpRasDevInfo,
&dwRasDevInfoSize);
if (NULL ==lpRasDevInfo)
{
dwRasDevInfoSize = 0;
}
if (hr == ERROR_SUCCESS && NULL != lpRasEntry)
{
// Replace the phone number with the new one
//
lstrcpy(lpRasEntry->szLocalPhoneNumber, bstrNewVal);
// non-zero dummy values are required due to bugs in win95
lpRasEntry->dwCountryID = 1;
lpRasEntry->dwCountryCode = 1;
lpRasEntry->szAreaCode[1] = L'\0';
lpRasEntry->szAreaCode[0] = L'8';
// Set to dial as is
//
lpRasEntry->dwfOptions &= ~RASEO_UseCountryAndAreaCodes;
pcRNA = new RNAAPI;
if (pcRNA)
{
TRACE6(L"CRefDial::put_DialPhoneNumber - MyRasGetEntryProperties()"
L"lpRasEntry->dwfOptions: %ld"
L"lpRasEntry->dwCountryID: %ld"
L"lpRasEntry->dwCountryCode: %ld"
L"lpRasEntry->szAreaCode: %s"
L"lpRasEntry->szLocalPhoneNumber: %s"
L"lpRasEntry->dwAlternateOffset: %ld",
lpRasEntry->dwfOptions,
lpRasEntry->dwCountryID,
lpRasEntry->dwCountryCode,
lpRasEntry->szAreaCode,
lpRasEntry->szLocalPhoneNumber,
lpRasEntry->dwAlternateOffset
);
pcRNA->RasSetEntryProperties(NULL,
m_szConnectoid,
(LPBYTE)lpRasEntry,
dwRasEntrySize,
(LPBYTE)lpRasDevInfo,
dwRasDevInfoSize);
delete pcRNA;
m_bDialCustom = TRUE;
}
}
// Regenerate the displayable number
//GetDisplayableNumber();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Function: SetDialAlternative
//
// Synopsis: Set whether or not to look for another number in phonebook
// when dialing next time
//
//+---------------------------------------------------------------------------
HRESULT CRefDial::SetDialAlternative(BOOL bVal)
{
m_bDialAlternative = bVal;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Function: DoHangup
//
// Synopsis: Hangup the modem for the currently active RAS session
//
//+---------------------------------------------------------------------------
HRESULT CRefDial::DoHangup()
{
// Set the disconnect flag as the system may be too busy with dialing.
// Once we get a chance to terminate dialing, we know we have to hangu
EnterCriticalSection (&m_csMyCriticalSection);
// Your code to access the shared resource goes here.
TerminateConnMonitorThread();
if (NULL != m_hrasconn)
{
RNAAPI* pRNA = new RNAAPI();
if (pRNA)
{
pRNA->RasHangUp(m_hrasconn);
m_hrasconn = NULL;
delete pRNA;
}
}
// Release ownership of the critical section
LeaveCriticalSection (&m_csMyCriticalSection);
return (m_hrasconn == NULL) ? S_OK : E_POINTER;
}
BOOL CRefDial::get_QueryString(WCHAR* szTemp, DWORD cchMax)
{
WCHAR szOOBEInfoINIFile[MAX_PATH];
WCHAR szISPSignup[MAX_PATH];
WCHAR szOEMName[MAX_PATH];
WCHAR szQueryString[MAX_SECTIONS_BUFFER*2];
WCHAR szBroadbandDeviceName[MAX_STRING];
WCHAR szBroadbandDevicePnpid[MAX_STRING];
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osvi))
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
if (VER_PLATFORM_WIN32_WINDOWS == osvi.dwPlatformId)
m_lpGatherInfo->m_dwOS = 1;
else if (VER_PLATFORM_WIN32_NT == osvi.dwPlatformId)
m_lpGatherInfo->m_dwOS = 2;
else
m_lpGatherInfo->m_dwOS = 0;
SearchPath(NULL, cszOOBEINFOINI, NULL, MAX_CHARS_IN_BUFFER(szOOBEInfoINIFile), szOOBEInfoINIFile, NULL);
DWORD dwOfferCode = 0;
if(m_dwAppMode == APMD_MSN)
{
lstrcpy(szISPSignup, L"MSN");
}
else
{
GetPrivateProfileString(cszSignup,
cszISPSignup,
L"",
szISPSignup,
MAX_CHARS_IN_BUFFER(szISPSignup),
szOOBEInfoINIFile);
dwOfferCode = GetPrivateProfileInt(cszSignup,
cszOfferCode,
0,
szOOBEInfoINIFile);
}
GetPrivateProfileString(cszBranding,
cszOEMName,
L"",
szOEMName,
MAX_CHARS_IN_BUFFER(szOEMName),
szOOBEInfoINIFile);
GetPrivateProfileString(cszOptions,
cszBroadbandDeviceName,
L"",
szBroadbandDeviceName,
MAX_CHARS_IN_BUFFER(szBroadbandDeviceName),
szOOBEInfoINIFile);
GetPrivateProfileString(cszOptions,
cszBroadbandDevicePnpid,
L"",
szBroadbandDevicePnpid,
MAX_CHARS_IN_BUFFER(szBroadbandDevicePnpid),
szOOBEInfoINIFile);
//DT tells the ISP if the query is coming from fullscreen OOBE or the desktop (windowed) version of OOBE. DT=1 means desktop version, DT=0 means fullscreen.
INT nDT = (m_dwAppMode == APMD_OOBE) ? 0 : 1;
wsprintf(szQueryString, L"LCID=%lu&TCID=%lu&ISPSignup=%s&OfferCode=%lu&OS=%lu%&BUILD=%ld&DT=%lu&OEMName=%s&BroadbandDeviceName=%s&BroadbandDevicePnpid=%s",
GetUserDefaultUILanguage(),
m_lpGatherInfo->m_dwCountryID,
szISPSignup,
dwOfferCode,
m_lpGatherInfo->m_dwOS,
LOWORD(osvi.dwBuildNumber),
nDT,
szOEMName,
szBroadbandDeviceName,
szBroadbandDevicePnpid);
// Parse the ISP section in the INI file to find query pair to append
WCHAR *pszKeys = NULL;
PWSTR pszKey = NULL;
WCHAR szValue[MAX_PATH];
ULONG ulRetVal = 0;
BOOL bEnumerate = TRUE;
ULONG ulBufferSize = MAX_SECTIONS_BUFFER;
WCHAR szOobeinfoPath[MAX_PATH + 1];
//BUGBUG :: this search path is foir the same file as the previous one and is redundant.
SearchPath(NULL, cszOOBEINFOINI, NULL, MAX_PATH, szOobeinfoPath, NULL);
// Loop to find the appropriate buffer size to retieve the ins to memory
ulBufferSize = MAX_KEYS_BUFFER;
ulRetVal = 0;
if (!(pszKeys = (LPWSTR)GlobalAlloc(GPTR, ulBufferSize*sizeof(WCHAR)))) {
return FALSE;
}
while (ulRetVal < (ulBufferSize - 2))
{
ulRetVal = ::GetPrivateProfileString(cszISPQuery, NULL, L"", pszKeys, ulBufferSize, szOobeinfoPath);
if (0 == ulRetVal)
bEnumerate = FALSE;
if (ulRetVal < (ulBufferSize - 2))
{
break;
}
GlobalFree( pszKeys );
ulBufferSize += ulBufferSize;
pszKeys = (LPWSTR)GlobalAlloc(GPTR, ulBufferSize*sizeof(WCHAR));
if (!pszKeys)
{
bEnumerate = FALSE;
}
}
if (bEnumerate)
{
// Enumerate each key value pair in the section
pszKey = pszKeys;
while (*pszKey)
{
ulRetVal = ::GetPrivateProfileString(cszISPQuery, pszKey, L"", szValue, MAX_CHARS_IN_BUFFER(szValue), szOobeinfoPath);
if ((ulRetVal != 0) && (ulRetVal < MAX_CHARS_IN_BUFFER(szValue) - 1))
{
// Append query pair
wsprintf(szQueryString, L"%s&%s=%s", szQueryString, pszKey, szValue);
}
pszKey += lstrlen(pszKey) + 1;
}
}
if(GetPrivateProfileInt(INF_SECTION_URL,
ISP_MSNSIGNUP,
0,
m_szISPFile))
{
lstrcat(szQueryString, QUERY_STRING_MSNSIGNUP);
}
if (pszKeys)
GlobalFree( pszKeys );
if (cchMax < (DWORD)lstrlen(szQueryString) + 1)
return FALSE;
lstrcpy(szTemp, szQueryString);
return TRUE;
}
HRESULT CRefDial::get_SignupURL(BSTR * pVal)
{
WCHAR szTemp[INTERNET_MAX_URL_LENGTH] = L"";
if (pVal == NULL)
return E_POINTER;
// Get the URL from the ISP file, and then convert it
if (SUCCEEDED(GetDataFromISPFile(m_szISPFile, INF_SECTION_URL, INF_SIGNUP_URL,&szTemp[0],INTERNET_MAX_URL_LENGTH)))
{
if(*szTemp)
{
WCHAR szUrl[INTERNET_MAX_URL_LENGTH];
WCHAR szQuery[MAX_PATH * 4] = L"\0";
get_QueryString(szQuery, MAX_CHARS_IN_BUFFER(szQuery));
wsprintf(szUrl, L"%s%s",
szTemp,
szQuery);
*pVal = SysAllocString(szUrl);
}
else
*pVal = NULL;
}
else
{
*pVal = NULL;
}
return S_OK;
}
//BUGBUG:: this should be combined with get_SignupURL
HRESULT CRefDial::get_ReconnectURL(BSTR * pVal)
{
WCHAR szTemp[INTERNET_MAX_URL_LENGTH] = L"\0";
if (pVal == NULL)
return E_POINTER;
// Get the URL from the ISP file, and then convert it
if (SUCCEEDED(GetDataFromISPFile(m_szISPFile, INF_SECTION_URL, INF_RECONNECT_URL,&szTemp[0],INTERNET_MAX_URL_LENGTH)))
{
WCHAR szUrl[INTERNET_MAX_URL_LENGTH];
WCHAR szQuery[MAX_PATH * 4] = L"\0";
DWORD dwErr = 0;
if(*szTemp)
{
get_QueryString(szQuery, MAX_CHARS_IN_BUFFER(szQuery));
if (m_dwRASErr)
dwErr = 1;
wsprintf(szUrl, L"%s%s&Error=%ld",
szTemp,
szQuery,
dwErr);
*pVal = SysAllocString(szUrl);
}
else
*pVal = NULL;
}
else
{
*pVal = NULL;
}
return S_OK;
}
HRESULT CRefDial::GetConnectionType(DWORD * pdwVal)
{
*pdwVal = m_dwConnectionType;
return S_OK;
}
HRESULT CRefDial::GetDialErrorMsg(BSTR * pVal)
{
if (pVal == NULL)
return E_POINTER;
return S_OK;
}
HRESULT CRefDial::GetSupportNumber(BSTR * pVal)
{
/*
WCHAR szSupportNumber[MAX_PATH];
if (pVal == NULL)
return E_POINTER;
if (m_SupportInfo.GetSupportInfo(szSupportNumber, m_dwCountryCode))
*pVal = SysAllocString(szSupportNumber);
else
*pVal = NULL;
*/
return S_OK;
}
BOOL CRefDial::IsDBCSString( CHAR *sz )
{
if (!sz)
return FALSE;
while( NULL != *sz )
{
if (IsDBCSLeadByte(*sz)) return FALSE;
sz++;
}
return TRUE;
}
//+---------------------------------------------------------------------------
//
// Function: RasGetConnectStatus
//
// Synopsis: Checks for existing Ras connection; return TRUE for connected
// Return FALSE for disconnect.
//
//+---------------------------------------------------------------------------
HRESULT CRefDial::RasGetConnectStatus(BOOL *pVal)
{
HRESULT hr = E_FAIL;
*pVal = FALSE;
if (NULL != m_hrasconn)
{
RASCONNSTATUS rasConnectState;
rasConnectState.dwSize = sizeof(RASCONNSTATUS);
if (m_pcRNA)
{
if (0 == m_pcRNA->RasGetConnectStatus(m_hrasconn, &rasConnectState))
{
if (RASCS_Disconnected != rasConnectState.rasconnstate)
*pVal = TRUE;
}
hr = S_OK;
}
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: DoOfferDownload
//
// Synopsis: Download the ISP offer from the ISP server
//
//+---------------------------------------------------------------------------
HRESULT CRefDial::DoOfferDownload(BOOL *pbRetVal)
{
HRESULT hr;
RNAAPI *pcRNA;
//
// Hide RNA window on Win95 retail
//
// MinimizeRNAWindow(m_pszConnectoid, g_hInst);
// 4/2/97 ChrisK Olympus 296
// g_hRNAZapperThread = LaunchRNAReestablishZapper(g_hInst);
//
// The connection is open and ready. Start the download.
//
m_dwThreadID = 0;
m_hThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)DownloadThreadInit,
(LPVOID)this,
0,
&m_dwThreadID);
// 5-1-97 ChrisK Olympus 2934
// m_objBusyMessages.Start(m_hWnd, IDC_LBLSTATUS,m_hrasconn);
// If we dont get the donwload thread, then kill the open
// connection
if (!m_hThread)
{
hr = GetLastError();
if (m_hrasconn)
{
pcRNA = new RNAAPI;
if (pcRNA)
{
pcRNA->RasHangUp(m_hrasconn);
m_hrasconn = NULL;
delete pcRNA;
pcRNA = NULL;
}
}
*pbRetVal = FALSE;
}
else
{
// Download has started.
m_bDownloadHasBeenCanceled = FALSE;
*pbRetVal = TRUE;
}
return S_OK;
}
// Form the Dialing URL. Must be called after setting up for dialing.
HRESULT CRefDial::FormReferralServerURL(BOOL * pbRetVal)
{
WCHAR szTemp[MAX_PATH] = L"\0";
WCHAR szPromo[MAX_PATH]= L"\0";
WCHAR szProd[MAX_PATH] = L"\0";
WCHAR szArea[MAX_PATH] = L"\0";
WCHAR szOEM[MAX_PATH] = L"\0";
DWORD dwCONNWIZVersion = 500; // Version of CONNWIZ.HTM
//
// ChrisK Olympus 3997 5/25/97
//
WCHAR szRelProd[MAX_PATH] = L"\0";
WCHAR szRelProdVer[MAX_PATH] = L"\0";
HRESULT hr = ERROR_SUCCESS;
OSVERSIONINFO osvi;
//
// Build URL complete with name value pairs
//
hr = GetDataFromISPFile(m_szISPFile, INF_SECTION_ISPINFO, INF_REFERAL_URL,&szTemp[0],256);
if (L'\0' == szTemp[0])
{
//MsgBox(IDS_MSNSU_WRONG, MB_MYERROR);
return hr;
}
//Assert(szTemp[0]);
Sz2URLValue(m_szOEM, szOEM,0);
Sz2URLValue(m_lpGatherInfo->m_szAreaCode, szArea,0);
if (m_bstrProductCode)
Sz2URLValue(m_bstrProductCode, szProd,0);
else
Sz2URLValue(DEFAULT_PRODUCTCODE, szProd,0);
if (m_bstrPromoCode)
Sz2URLValue(((BSTR)m_bstrPromoCode), szPromo,0);
else
Sz2URLValue(DEFAULT_PROMOCODE, szPromo,0);
//
// ChrisK Olympus 3997 5/25/97
//
Sz2URLValue(m_lpGatherInfo->m_szRelProd, szRelProd, 0);
Sz2URLValue(m_lpGatherInfo->m_szRelVer, szRelProdVer, 0);
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osvi))
{
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
}
// Autoconfig will set alloffers always.
if ( m_lAllOffers || (m_lpGatherInfo->m_dwFlag & ICW_CFGFLAG_AUTOCONFIG) )
{
m_lpGatherInfo->m_dwFlag |= ICW_CFGFLAG_ALLOFFERS;
}
wsprintf(m_szUrl, L"%slcid=%lu&sysdeflcid=%lu&appslcid=%lu&icwos=%lu&osver=%lu.%2.2d%s&arch=%u&promo=%s&oem=%s&area=%s&country=%lu&icwver=%s&prod=%s&osbld=%d&icwrp=%s&icwrpv=%s&wizver=%lu&PID=%s&cfgflag=%lu",
szTemp,
m_lpGatherInfo->m_lcidUser,
m_lpGatherInfo->m_lcidSys,
m_lpGatherInfo->m_lcidApps,
m_lpGatherInfo->m_dwOS,
m_lpGatherInfo->m_dwMajorVersion,
m_lpGatherInfo->m_dwMinorVersion,
ICW_OS_VER,
m_lpGatherInfo->m_wArchitecture,
szPromo,
szOEM,
szArea,
m_lpGatherInfo->m_dwCountryCode,
&m_lpGatherInfo->m_szSUVersion[0],
szProd,
LOWORD(osvi.dwBuildNumber),
szRelProd,
szRelProdVer,
dwCONNWIZVersion,
m_szPID,
m_lpGatherInfo->m_dwFlag);
StoreInSignUpReg(
(LPBYTE)m_lpGatherInfo,
sizeof(GATHERINFO),
REG_BINARY,
GATHERINFOVALUENAME);
return hr;
}
/*******************************************************************
NAME: ParseISPInfo
SYNOPSIS: Called when page is displayed
ENTRY: hDlg - dialog window
fFirstInit - TRUE if this is the first time the dialog
is initialized, FALSE if this InitProc has been called
before (e.g. went past this page and backed up)
********************************************************************/
BOOL CRefDial::ParseISPInfo
(
HWND hDlg,
WCHAR *pszCSVFileName,
BOOL bCheckDupe
)
{
// On the first init, we will read the ISPINFO.CSV file, and populate the ISP LISTVIEW
CCSVFile far *pcCSVFile;
CISPCSV far *pcISPCSV;
BOOL bRet = TRUE;
BOOL bHaveCNSOffer = FALSE;
BOOL bISDNMode = FALSE;
HRESULT hr;
CleanISPList();
ISPLIST* pCurr = NULL;
DWORD dwCurrISPListSize = 1;
m_dwNumOfAutoConfigOffers = 0;
m_unSelectedISP = 0;
// Open and process the CSV file
pcCSVFile = new CCSVFile;
if (!pcCSVFile)
{
// BUGBUG: Show Error Message
return (FALSE);
}
if (!pcCSVFile->Open(pszCSVFileName))
{
// BUGBUG: Show Error Message
delete pcCSVFile;
pcCSVFile = NULL;
return (FALSE);
}
// Read the first line, since it contains field headers
pcISPCSV = new CISPCSV;
if (!pcISPCSV)
{
// BUGBUG Show error message
delete pcCSVFile;
return (FALSE);
}
if (ERROR_SUCCESS != (hr = pcISPCSV->ReadFirstLine(pcCSVFile)))
{
// Handle the error case
delete pcCSVFile;
pcCSVFile = NULL;
return (FALSE);
}
delete pcISPCSV; // Don't need this one any more
// Create the SELECT tag for the html so it can get all the country names in one shot.
if (m_pszISPList)
delete [] m_pszISPList;
m_pszISPList = new WCHAR[1024];
if (!m_pszISPList)
return FALSE;
memset(m_pszISPList, 0, sizeof(m_pszISPList));
do {
// Allocate a new ISP record
pcISPCSV = new CISPCSV;
if (!pcISPCSV)
{
// BUGBUG Show error message
bRet = FALSE;
break;
}
// Read a line from the ISPINFO file
hr = pcISPCSV->ReadOneLine(pcCSVFile);
if (hr == ERROR_SUCCESS)
{
// If this line contains a nooffer flag, then leave now
if (!(pcISPCSV->get_dwCFGFlag() & ICW_CFGFLAG_OFFERS))
{
m_dwNumOfAutoConfigOffers = 0;
break;
}
if ((pcISPCSV->get_dwCFGFlag() & ICW_CFGFLAG_AUTOCONFIG) &&
(bISDNMode ? (pcISPCSV->get_dwCFGFlag() & ICW_CFGFLAG_ISDN_OFFER) : TRUE) )
{
// Form the ISP list option tag for HTML
WCHAR szBuffer[MAX_PATH];
wsprintf(szBuffer, szOptionTag, pcISPCSV->get_szISPName());
DWORD dwSizeReq = (DWORD)lstrlen(m_pszISPList) + lstrlen(szBuffer) + 1;
if (dwCurrISPListSize < dwSizeReq)
{
WCHAR *szTemp = new WCHAR[dwSizeReq];
if (szTemp)
lstrcpy(szTemp, m_pszISPList);
dwCurrISPListSize = dwSizeReq;
delete [] m_pszISPList;
m_pszISPList = szTemp;
}
// Add the isp to the list.
if (m_pszISPList)
lstrcat(m_pszISPList, szBuffer);
if (m_pCSVList == NULL) // First one
{
// Add the CSV file object to the first node of linked list
ISPLIST* pNew = new ISPLIST;
pNew->pElement = pcISPCSV;
pNew->uElem = m_dwNumOfAutoConfigOffers;
pNew->pNext = NULL;
pCurr = pNew;
m_pCSVList = pCurr;
}
else
{
// Append CSV object to the end of list
ISPLIST* pNew = new ISPLIST;
pNew->pElement = pcISPCSV;
pNew->uElem = m_dwNumOfAutoConfigOffers;
pNew->pNext = NULL;
pCurr->pNext = pNew;
pCurr = pCurr->pNext;
}
++m_dwNumOfAutoConfigOffers;
}
else
{
delete pcISPCSV;
}
}
else if (hr == ERROR_NO_MORE_ITEMS)
{
delete pcISPCSV; // We don't need this one
break;
}
else if (hr == ERROR_FILE_NOT_FOUND)
{
// do not show this ISP when its data is invalid
// we don't want to halt everything. Just let it contine
delete pcISPCSV;
}
else
{
// Show error message Later
delete pcISPCSV;
//iNumOfAutoConfigOffers = ISP_INFO_NO_VALIDOFFER;
bRet = FALSE;
break;
}
} while (TRUE);
delete pcCSVFile;
return bRet;
}
HRESULT CRefDial::GetISPList(BSTR* pbstrISPList)
{
if (pbstrISPList)
*pbstrISPList = NULL;
else
return E_FAIL;
if (!m_pszISPList)
{
ParseISPInfo(NULL, ICW_ISPINFOPath, TRUE);
}
if (m_pszISPList && *m_pszISPList)
{
*pbstrISPList = SysAllocString(m_pszISPList);
return S_OK;
}
return E_FAIL;
}
HRESULT CRefDial::Set_SelectISP(UINT nVal)
{
if (nVal < m_dwNumOfAutoConfigOffers)
{
m_unSelectedISP = nVal;
}
return S_OK;
}
HRESULT CRefDial::Set_ConnectionMode(UINT nVal)
{
if (nVal < m_dwNumOfAutoConfigOffers)
{
m_unSelectedISP = nVal;
}
return S_OK;
}
HRESULT CRefDial::Get_ConnectionMode(UINT *pnVal)
{
if (pnVal)
{
*pnVal = m_dwCnType;
return S_OK;
}
return E_FAIL;
}
HRESULT CRefDial::ProcessSignedPID(BOOL * pbRetVal)
{
HANDLE hfile;
DWORD dwFileSize;
DWORD dwBytesRead;
LPBYTE lpbSignedPID;
LPWSTR lpszSignedPID;
*pbRetVal = FALSE;
// Open the PID file for Binary Reading. It will be in the CWD
if (INVALID_HANDLE_VALUE != (hfile = CreateFile(c_szSignedPIDFName,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL)))
{
dwFileSize = GetFileSize(hfile, NULL);
// Allocate a buffer to read the file, and one to store the BINHEX version
lpbSignedPID = new BYTE[dwFileSize];
lpszSignedPID = new WCHAR[(dwFileSize * 2) + 1];
if (lpbSignedPID && lpszSignedPID)
{
if (ReadFile(hfile, (LPVOID) lpbSignedPID, dwFileSize, &dwBytesRead, NULL) &&
(dwFileSize == dwBytesRead))
{
// BINHEX the signed PID data so we can send it to the signup server
DWORD dwX = 0;
BYTE by;
for (DWORD dwY = 0; dwY < dwFileSize; dwY++)
{
by = lpbSignedPID[dwY];
lpszSignedPID[dwX++] = g_BINTOHEXLookup[((by & 0xF0) >> 4)];
lpszSignedPID[dwX++] = g_BINTOHEXLookup[(by & 0x0F)];
}
lpszSignedPID[dwX] = L'\0';
// Convert the signed pid to a BSTR
m_bstrSignedPID = SysAllocString(lpszSignedPID);
// Set the return value
*pbRetVal = TRUE;
}
}
// Free the buffers we allocated
if (lpbSignedPID)
{
delete[] lpbSignedPID;
}
if (lpszSignedPID)
{
delete[] lpszSignedPID;
}
// Close the File
CloseHandle(hfile);
#ifndef DEBUG
// Delete the File
// defer removal of this file until the container app exits.
// see BUG 373.
//DeleteFile(c_szSignedPIDFName);
#endif
}
return S_OK;
}
HRESULT CRefDial::get_SignedPID(BSTR * pVal)
{
if (pVal == NULL)
return E_POINTER;
*pVal = SysAllocString(m_bstrSignedPID);
return S_OK;
}
HRESULT CRefDial::get_ISDNAutoConfigURL(BSTR * pVal)
{
WCHAR szTemp[256];
if (pVal == NULL)
return E_POINTER;
// Get the URL from the ISP file, and then convert it
if (SUCCEEDED(GetDataFromISPFile(m_szISPFile, INF_SECTION_URL, INF_ISDN_AUTOCONFIG_URL,&szTemp[0],256)))
{
*pVal = SysAllocString(szTemp);
}
else
{
*pVal = NULL;
}
return S_OK;
}
HRESULT CRefDial::get_ISPName(BSTR * pVal)
{
if (m_pSelectedISPInfo)
{
*pVal = SysAllocString(m_pSelectedISPInfo->get_szISPName());
}
else
{
*pVal = NULL;
}
return S_OK;
}
HRESULT CRefDial::get_AutoConfigURL(BSTR * pVal)
{
WCHAR szTemp[256];
if (pVal == NULL)
return E_POINTER;
// Get the URL from the ISP file, and then convert it
if (SUCCEEDED(GetDataFromISPFile(m_szISPFile, INF_SECTION_URL, INF_AUTOCONFIG_URL,&szTemp[0],256)))
{
*pVal = SysAllocString(szTemp);
}
else
{
*pVal = NULL;
}
return S_OK;
}
HRESULT CRefDial::DownloadISPOffer(BOOL *pbVal, BSTR *pVal)
{
HRESULT hr = S_OK;
// Download the ISP file, and then copy its contents
// If Ras is complete
if (pbVal && pVal)
{
// Download the first page from Webgate
BSTR bstrURL = NULL;
BSTR bstrQueryURL = NULL;
BOOL bRet;
*pVal = NULL;
*pbVal = FALSE;
m_pISPData = new CICWISPData;
WCHAR szTemp[10]; // Big enough to format a WORD
// Add the PID, GIUD, and Offer ID to the ISP data object
ProcessSignedPID(&bRet);
if (bRet)
{
m_pISPData->PutDataElement(ISPDATA_SIGNED_PID, m_bstrSignedPID, FALSE);
}
else
{
m_pISPData->PutDataElement(ISPDATA_SIGNED_PID, NULL, FALSE);
}
// GUID comes from the ISPCSV file
m_pISPData->PutDataElement(ISPDATA_GUID,
m_pSelectedISPInfo->get_szOfferGUID(),
FALSE);
// Offer ID comes from the ISPCSV file as a WORD
// NOTE: This is the last one, so besure AppendQueryPair does not add an Ampersand
if (m_pSelectedISPInfo)
{
wsprintf (szTemp, L"%d", m_pSelectedISPInfo->get_wOfferID());
m_pISPData->PutDataElement(ISPDATA_OFFERID, szTemp, FALSE);
}
// BUGBUG: If ISDN get the ISDN Autoconfig URL
if (m_ISPImport.m_bIsISDNDevice)
{
get_ISDNAutoConfigURL(&bstrURL);
}
else
{
get_AutoConfigURL(&bstrURL);
}
if (*bstrURL)
{
// Get the full signup url with Query string params added to it
m_pISPData->GetQueryString(bstrURL, &bstrQueryURL);
// Setup WebGate
if (S_OK != gpCommMgr->FetchPage(bstrQueryURL, pVal))
{
// Download problem:
// User has disconnected
if (TRUE == m_bUserInitiateHangup)
{
hr = E_FAIL;
}
}
else
{
*pbVal = TRUE;
}
}
// Now that webgate is done with it, free the queryURL
SysFreeString(bstrQueryURL);
// Memory cleanup
SysFreeString(bstrURL);
delete m_pISPData;
m_pISPData = NULL;
}
return hr;
}
HRESULT CRefDial::RemoveDownloadDir()
{
DWORD dwAttribs;
WCHAR szDownloadDir[MAX_PATH];
WCHAR szSignedPID[MAX_PATH];
// form the ICW98 dir. It is basically the CWD
if(!GetOOBEPath(szDownloadDir))
return S_OK;
// remove the signed.pid file from the ICW directory (see BUG 373)
wsprintf(szSignedPID, L"%s%s", szDownloadDir, L"\\signed.pid");
if (GetFileAttributes(szSignedPID) != 0xFFFFFFFF)
{
SetFileAttributes(szSignedPID, FILE_ATTRIBUTE_NORMAL);
DeleteFile(szSignedPID);
}
lstrcat(szDownloadDir, L"\\download");
// See if the directory exists
dwAttribs = GetFileAttributes(szDownloadDir);
if (dwAttribs != 0xFFFFFFFF && dwAttribs & FILE_ATTRIBUTE_DIRECTORY)
DeleteDirectory(szDownloadDir);
return S_OK;
}
void CRefDial::DeleteDirectory (LPCWSTR szDirName)
{
WIN32_FIND_DATA fdata;
WCHAR szPath[MAX_PATH];
HANDLE hFile;
BOOL fDone;
wsprintf(szPath, L"%s\\*.*", szDirName);
hFile = FindFirstFile (szPath, &fdata);
if (INVALID_HANDLE_VALUE != hFile)
fDone = FALSE;
else
fDone = TRUE;
while (!fDone)
{
wsprintf(szPath, L"%s\\%s", szDirName, fdata.cFileName);
if (fdata.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
if (lstrcmpi(fdata.cFileName, L".") != 0 &&
lstrcmpi(fdata.cFileName, L"..") != 0)
{
// recursively delete this dir too
DeleteDirectory(szPath);
}
}
else
{
SetFileAttributes(szPath, FILE_ATTRIBUTE_NORMAL);
DeleteFile(szPath);
}
if (FindNextFile(hFile, &fdata) == 0)
{
FindClose(hFile);
fDone = TRUE;
}
}
SetFileAttributes(szDirName, FILE_ATTRIBUTE_NORMAL);
RemoveDirectory(szDirName);
}
HRESULT CRefDial::PostRegData(DWORD dwSrvType, LPWSTR szPath)
{
static WCHAR hdrs[] = L"Content-Type: application/x-www-form-urlencoded";
static WCHAR accept[] = L"Accept: */*";
static LPCWSTR rgsz[] = {accept, NULL};
WCHAR szRegPostURL[INTERNET_MAX_URL_LENGTH] = L"\0";
HRESULT hRet = E_FAIL;
if (POST_TO_MS & dwSrvType)
{
// Get the RegPostURL from Reg.isp file for MS registration
GetPrivateProfileString(INF_SECTION_URL,
c_szRegPostURL,
L"",
szRegPostURL,
INTERNET_MAX_URL_LENGTH,
m_szISPFile);
}
else if (POST_TO_OEM & dwSrvType)
{
WCHAR szOOBEInfoINIFile[MAX_PATH];
SearchPath(NULL, cszOOBEINFOINI, NULL, MAX_CHARS_IN_BUFFER(szOOBEInfoINIFile), szOOBEInfoINIFile, NULL);
GetPrivateProfileString(INF_OEMREGPAGE,
c_szRegPostURL,
L"",
szRegPostURL,
INTERNET_MAX_URL_LENGTH,
szOOBEInfoINIFile);
}
// Connecting to http://mscomdev.dns.microsoft.com/register.asp.
if (CrackUrl(
szRegPostURL,
m_szRegServerName,
m_szRegFormAction,
&m_nRegServerPort,
&m_fSecureRegServer))
{
HINTERNET hSession = InternetOpen(
L"OOBE",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0
);
if (hSession)
{
HINTERNET hConnect = InternetConnect(
hSession,
m_szRegServerName,
m_nRegServerPort,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
0,
1
);
if (hConnect)
{
// INTERNET_FLAG_SECURE is needed KB Q168151
HINTERNET hRequest = HttpOpenRequest(
hConnect,
L"POST",
m_szRegFormAction,
NULL,
NULL,
rgsz,
(m_fSecureRegServer) ? INTERNET_FLAG_SECURE : 0,
1
);
if (hRequest)
{
// The data for the HttpSendRequest has to be in ANSI. The server side does
// not understand a UNICODE string. If the server side gets changed to understand
// UNICODE data, the conversion below needs to be removed.
LPSTR szAnsiData = NULL;
INT iLength;
// compute the length
//
iLength = WideCharToMultiByte(CP_ACP, 0, szPath, -1, NULL, 0, NULL, NULL);
if (iLength > 0)
{
szAnsiData = new char[iLength];
if (szAnsiData)
{
WideCharToMultiByte(CP_ACP, 0, szPath, -1, szAnsiData, iLength, NULL, NULL);
szAnsiData[iLength - 1] = 0;
}
}
if (szAnsiData)
{
// 2nd/3rd params are a string/char length pair,
// but 4th/5th params are a buffer/byte length pair.
if (HttpSendRequest(hRequest, hdrs, lstrlen(hdrs), szAnsiData, lstrlenA(szAnsiData)))
{
// Get size of file in bytes.
WCHAR bufQuery[32] ;
DWORD dwFileSize ;
DWORD cchMaxBufQuery = MAX_CHARS_IN_BUFFER(bufQuery);
BOOL bQuery = HttpQueryInfo(hRequest,
HTTP_QUERY_CONTENT_LENGTH,
bufQuery,
&cchMaxBufQuery,
NULL) ;
if (bQuery)
{
// The Query was successful, so allocate the memory.
dwFileSize = (DWORD)_wtol(bufQuery) ;
}
else
{
// The Query failed. Allocate some memory. Should allocate memory in blocks.
dwFileSize = 5*1024 ;
}
// BUGBUG: What is the purpose of this code?? It
// appears to read a file, null-terminate the buffer,
// then delete the buffer. Why??
BYTE* rgbFile = new BYTE[dwFileSize+1] ;
if (rgbFile)
{
DWORD dwBytesRead ;
BOOL bRead = InternetReadFile(hRequest,
rgbFile,
dwFileSize+1,
&dwBytesRead);
if (bRead)
{
rgbFile[dwBytesRead] = 0 ;
hRet = S_OK;
} // InternetReadFile
delete [] rgbFile;
}
}
else
{
DWORD dwErr = GetLastError();
}
delete [] szAnsiData;
}
InternetCloseHandle(hRequest);
hRet = S_OK;
}
InternetCloseHandle(hConnect);
}
InternetCloseHandle(hSession);
}
}
if (hRet != S_OK)
{
DWORD dwErr = GetLastError();
hRet = HRESULT_FROM_WIN32(dwErr);
}
TRACE2(TEXT("Post registration data to %s 0x%08lx"), szRegPostURL, hRet);
return hRet;
}
// This function will accept user selected values that are necessary to
// setup a connectiod for dialing
// Returns:
// TRUE OK to dial
// FALSE Some kind of problem
// QuitWizard - TRUE, then terminate
// UserPickNumber - TRUE, then display Pick a Number DLG
// QuitWizard and UserPickNumber both FALSE, then just
// display the page prior to Dialing UI.
HRESULT CRefDial::Connect
(
UINT nType,
BSTR bstrISPFile,
DWORD dwCountry,
BSTR bstrAreaCode,
DWORD dwFlag,
DWORD dwAppMode
)
{
HRESULT hr = S_OK;
BOOL bSuccess = FALSE;
BOOL bRetVal = FALSE;
LPWSTR pszTemp;
WCHAR szISPPath[MAX_PATH];
m_dwCnType = nType;
if (!bstrISPFile || !bstrAreaCode)
{
return E_FAIL;
}
// Locate ISP file
if (!SearchPath(NULL, bstrISPFile,INF_SUFFIX,MAX_PATH,szISPPath,&pszTemp))
{
hr = ERROR_FILE_NOT_FOUND;
return hr;
}
// Check whether the isp file is ICW capable by reading the referral URL
GetPrivateProfileString(INF_SECTION_ISPINFO,
c_szURLReferral,
L"",
m_szRefServerURL,
INTERNET_MAX_URL_LENGTH,
szISPPath);
lstrcpy(m_szISPFile, szISPPath);
m_dwAppMode = dwAppMode;
// Initialize failure codes
m_bQuitWizard = FALSE;
m_bUserPickNumber = FALSE;
m_lpGatherInfo->m_bUsePhbk = FALSE;
// Stuff the Area Code, and Country Code into the GatherInfo struct
m_lpGatherInfo->m_dwCountryID = dwCountry;
m_lpGatherInfo->m_dwCountryCode = dwFlag;
lstrcpy(m_lpGatherInfo->m_szAreaCode, bstrAreaCode);
m_SuggestInfo.AccessEntry.dwCountryID = dwCountry;
m_SuggestInfo.AccessEntry.dwCountryCode = dwFlag;
lstrcpy(m_SuggestInfo.AccessEntry.szAreaCode, bstrAreaCode);
GetISPFileSettings(szISPPath);
FillGatherInfoStruct(m_lpGatherInfo);
if (CONNECTED_REFFERAL == m_dwCnType)
FormReferralServerURL(&bRetVal);
// LAN connection support in desktop mode
if (gpCommMgr)
{
// Pretend we have the connection
PostMessage(gpCommMgr->m_hwndCallBack, WM_OBCOMM_ONCONNECTED, (WPARAM)gpCommMgr->m_pRefDial->m_dwCnType , (LPARAM)0);
}
return hr;
}
HRESULT CRefDial::CheckOnlineStatus(BOOL *pbVal)
{
// #if defined(DEBUG)
// *pbVal = TRUE;
// return S_OK;
// #endif
*pbVal = (BOOL)(m_hrasconn != NULL);
return S_OK;
}
BOOL CRefDial::CrackUrl(
const WCHAR* lpszUrlIn,
WCHAR* lpszHostOut,
WCHAR* lpszActionOut,
INTERNET_PORT* lpnHostPort,
BOOL* lpfSecure)
{
URL_COMPONENTS urlcmpTheUrl;
LPURL_COMPONENTS lpUrlComp = &urlcmpTheUrl;
urlcmpTheUrl.dwStructSize = sizeof(urlcmpTheUrl);
urlcmpTheUrl.lpszScheme = NULL;
urlcmpTheUrl.lpszHostName = NULL;
urlcmpTheUrl.lpszUserName = NULL;
urlcmpTheUrl.lpszPassword = NULL;
urlcmpTheUrl.lpszUrlPath = NULL;
urlcmpTheUrl.lpszExtraInfo = NULL;
urlcmpTheUrl.dwSchemeLength = 1;
urlcmpTheUrl.dwHostNameLength = 1;
urlcmpTheUrl.dwUserNameLength = 1;
urlcmpTheUrl.dwPasswordLength = 1;
urlcmpTheUrl.dwUrlPathLength = 1;
urlcmpTheUrl.dwExtraInfoLength = 1;
if (!InternetCrackUrl(lpszUrlIn, lstrlen(lpszUrlIn),0, lpUrlComp) || !lpszHostOut || !lpszActionOut || !lpnHostPort || !lpfSecure)
{
return FALSE;
}
else
{
if (urlcmpTheUrl.dwHostNameLength != 0)
{
lstrcpyn(lpszHostOut, urlcmpTheUrl.lpszHostName, urlcmpTheUrl.dwHostNameLength+1);
}
if (urlcmpTheUrl.dwUrlPathLength != 0)
{
lstrcpyn(lpszActionOut, urlcmpTheUrl.lpszUrlPath, urlcmpTheUrl.dwUrlPathLength+1);
}
*lpfSecure = (urlcmpTheUrl.nScheme == INTERNET_SCHEME_HTTPS) ? TRUE : FALSE;
*lpnHostPort = urlcmpTheUrl.nPort;
return TRUE;
}
}
| 31.347438 | 213 | 0.522484 | [
"object"
] |
50c768f35e3fd812be682aafbd7aa7501c09956a | 1,266 | hpp | C++ | include/hydro/engine/document/Action.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/engine/document/Action.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/engine/document/Action.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#ifndef __h3o_engine_Action__
#define __h3o_engine_Action__
#include "ActionIdentity.hpp"
#include "Entity.hpp"
namespace hydro::engine
{
/**
* The Action class represents an Action entity in a document.
*/
class Action final : public Entity
{
public:
/**
* Creates an Action object as a child of some parent entity.
* @param parent The parent entity that will own the action entity.
* @param identity The identity that describes the action entity.
*/
Action(Entity *parent, ActionIdentity *identity);
/**
* Destroys the action object.
*/
virtual ~Action();
/**
* Accepts a visitor allowing the visitor to visit the action entity.
* @param visitor The visitor to accept.
*/
virtual void accept(DocumentVisitor *visitor) override { visitor->visit(this); }
};
} // namespace hydro::engine
#endif /* __h3o_engine_Action__ */
| 26.375 | 84 | 0.550553 | [
"object"
] |
50ccc48c49aad28d4df4ee618a6fb10195306c2f | 1,702 | hpp | C++ | soccer/radio/NetworkRadio.hpp | kasohrab/robocup-software | 73c92878baf960844b5a4b34c72804093f1ea459 | [
"Apache-2.0"
] | null | null | null | soccer/radio/NetworkRadio.hpp | kasohrab/robocup-software | 73c92878baf960844b5a4b34c72804093f1ea459 | [
"Apache-2.0"
] | null | null | null | soccer/radio/NetworkRadio.hpp | kasohrab/robocup-software | 73c92878baf960844b5a4b34c72804093f1ea459 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <mutex>
#include <boost/config.hpp>
#include <RobotIntent.hpp>
#include <boost/asio.hpp>
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>
#include "Radio.hpp"
#include "rc-fshare/rtp.hpp"
/**
* @brief Interface for the radio over regular network interface
*
* TODO(Kyle): Clean this up by removing dual-radio support.
*/
class NetworkRadio : public Radio {
public:
NetworkRadio(int server_port);
[[nodiscard]] bool isOpen() const override;
void send(const std::array<RobotIntent, Num_Shells>& intents,
const std::array<MotionSetpoint, Num_Shells>& setpoints) override;
void receive() override;
void switchTeam(bool blueTeam) override;
protected:
struct RobotConnection {
boost::asio::ip::udp::endpoint endpoint;
RJ::Time last_received;
};
// Connections to the robots, indexed by robot ID.
std::vector<std::optional<RobotConnection>> _connections{};
// Map from IP address to robot ID.
std::map<boost::asio::ip::udp::endpoint, int> _robot_ip_map{};
void receivePacket(const boost::system::error_code& error,
std::size_t num_bytes);
void startReceive();
boost::asio::io_service _context;
boost::asio::ip::udp::socket _socket;
// Written by `async_receive_from`.
std::array<char, rtp::ReverseSize> _recv_buffer;
boost::asio::ip::udp::endpoint _robot_endpoint;
// Read from by `async_send_to`
std::vector<
std::array<uint8_t, rtp::HeaderSize + sizeof(rtp::RobotTxMessage)>>
_send_buffers{};
constexpr static std::chrono::duration kTimeout =
std::chrono::milliseconds(250);
};
| 25.787879 | 80 | 0.676263 | [
"vector"
] |
50cd846e551d4cda29c2fc0c55eca7dcc7f7abda | 2,640 | cc | C++ | packages/isar_flutter_libs/linux/isar_flutter_libs_plugin.cc | richard457/isar | e15b3bc2833a3b47050a83f983b0f908d59300aa | [
"Apache-2.0"
] | 1 | 2022-03-30T16:46:58.000Z | 2022-03-30T16:46:58.000Z | packages/isar_flutter_libs/linux/isar_flutter_libs_plugin.cc | richard457/isar | e15b3bc2833a3b47050a83f983b0f908d59300aa | [
"Apache-2.0"
] | null | null | null | packages/isar_flutter_libs/linux/isar_flutter_libs_plugin.cc | richard457/isar | e15b3bc2833a3b47050a83f983b0f908d59300aa | [
"Apache-2.0"
] | null | null | null | #include "include/isar_flutter_libs/isar_flutter_libs_plugin.h"
#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include <sys/utsname.h>
#include <cstring>
#define ISAR_FLUTTER_LIBS_PLUGIN(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj), isar_flutter_libs_plugin_get_type(), \
IsarFlutterLibsPlugin))
struct _IsarFlutterLibsPlugin {
GObject parent_instance;
};
G_DEFINE_TYPE(IsarFlutterLibsPlugin, isar_flutter_libs_plugin, g_object_get_type())
// Called when a method call is received from Flutter.
static void isar_flutter_libs_plugin_handle_method_call(
IsarFlutterLibsPlugin* self,
FlMethodCall* method_call) {
g_autoptr(FlMethodResponse) response = nullptr;
const gchar* method = fl_method_call_get_name(method_call);
if (strcmp(method, "getPlatformVersion") == 0) {
struct utsname uname_data = {};
uname(&uname_data);
g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version);
g_autoptr(FlValue) result = fl_value_new_string(version);
response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
fl_method_call_respond(method_call, response, nullptr);
}
static void isar_flutter_libs_plugin_dispose(GObject* object) {
G_OBJECT_CLASS(isar_flutter_libs_plugin_parent_class)->dispose(object);
}
static void isar_flutter_libs_plugin_class_init(IsarFlutterLibsPluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = isar_flutter_libs_plugin_dispose;
}
static void isar_flutter_libs_plugin_init(IsarFlutterLibsPlugin* self) {}
static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call,
gpointer user_data) {
IsarFlutterLibsPlugin* plugin = ISAR_FLUTTER_LIBS_PLUGIN(user_data);
isar_flutter_libs_plugin_handle_method_call(plugin, method_call);
}
void isar_flutter_libs_plugin_register_with_registrar(FlPluginRegistrar* registrar) {
IsarFlutterLibsPlugin* plugin = ISAR_FLUTTER_LIBS_PLUGIN(
g_object_new(isar_flutter_libs_plugin_get_type(), nullptr));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlMethodChannel) channel =
fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
"isar_flutter_libs",
FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(channel, method_call_cb,
g_object_ref(plugin),
g_object_unref);
g_object_unref(plugin);
}
| 37.183099 | 85 | 0.749621 | [
"object"
] |
50dffc5c1fb44b444cc123d1690d2a8880e1b5ad | 3,142 | cpp | C++ | src/Data/Commands/Model/LexiconModel.cpp | viveret/script-ai | 15f8dc561e55812de034bb729e83ff01bec61743 | [
"BSD-3-Clause"
] | null | null | null | src/Data/Commands/Model/LexiconModel.cpp | viveret/script-ai | 15f8dc561e55812de034bb729e83ff01bec61743 | [
"BSD-3-Clause"
] | null | null | null | src/Data/Commands/Model/LexiconModel.cpp | viveret/script-ai | 15f8dc561e55812de034bb729e83ff01bec61743 | [
"BSD-3-Clause"
] | null | null | null | #include "LexiconModel.hpp"
#include "SentenceModel.hpp"
#include "../../../StackOverflow.hpp"
#include "../../../SentenceIterator.hpp"
#include <iostream>
#include <cassert>
#include <random>
using namespace ScriptAI;
using namespace Sql;
LexiconModel::LexiconModel(int capacity) {
if (capacity > 0) {
this->lexicon.reserve(capacity);
}
}
void LexiconModel::clear() {
for (size_t i = 0; i < this->lexicon.size(); i++) {
this->lexicon[i].feature_index = 0;
this->lexicon[i].freq = 0;
this->lexicon[i].occurrences = 0;
this->lexicon[i].label = "";
}
this->lexicon.clear();
this->_reverse.clear();
}
bool LexiconModel::is_empty() {
return this->_reverse.empty();
}
void LexiconModel::add_sentence(SentenceModel *sentence) {
for (FixedSentenceIterator it(sentence); it.good(); it.next()) {
this->add_word(it.word);
}
}
void LexiconModel::add_word(std::string& word) {
trim(word);
assert(word.length() > 0);
auto e = this->_reverse.find(this->hash(word));
if (e != this->_reverse.end()) {
this->lexicon[e->second].occurrences++;
} else {
auto count = this->lexicon.size();
this->lexicon.push_back(LexiconFeatureModel { count, 1, 0, word });
this->_reverse[this->hash(word)] = count;
}
}
void LexiconModel::add(LexiconFeatureModel* word) {
if (word->feature_index >= this->lexicon.capacity()) {
std::cerr << "Lexicon overflow" << std::endl;
} else {
this->lexicon.push_back(*word);
this->_reverse[this->hash(word->label)] = word->feature_index;
return;
}
assert(false);
}
void LexiconModel::copy(LexiconFeatureModel* word) {
if (word->feature_index >= this->lexicon.size()) {
std::cerr << "Lexicon overflow" << std::endl;
} else {
this->lexicon[word->feature_index].copy(word);
this->_reverse[this->hash(word->label)] = word->feature_index;
return;
}
assert(false);
}
bool LexiconModel::exists(std::string& word) {
return this->_reverse.find(this->hash(word)) != this->_reverse.end();
}
bool LexiconModel::try_get_id(std::string& word, size_t &id) {
auto e = this->_reverse.find(this->hash(word));
if (e != this->_reverse.end()) {
id = this->lexicon[e->second].feature_index;
return true;
}
std::cerr << "No word " << word << " in lexicon" << std::endl;
return false;
}
std::string LexiconModel::select_one(std::vector<double>& probs) {
std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count());
std::discrete_distribution<size_t> distribution(probs.begin(),
probs.end());
auto index = distribution(generator);
if (index >= this->lexicon.capacity()) {
std::cerr << "Lexicon overflow" << std::endl;
} else if (index < this->lexicon.size()) {
return this->lexicon[index].label;
}
assert(false);
return "";
}
size_t LexiconModel::hash(std::string& word) {
return std::hash<std::string>{}(word);
} | 29.092593 | 102 | 0.606302 | [
"vector"
] |
50e96e66d9234b04e5ab410263acb24ef1fabb86 | 32,741 | cpp | C++ | src/qnodeeditorsocketmodel.cpp | rochus/qt5-node-editor | 9c9bc9b713aa6fe4c59e6d70ce0115a2800d461a | [
"MIT"
] | 168 | 2015-07-02T09:41:31.000Z | 2020-12-29T11:33:09.000Z | src/qnodeeditorsocketmodel.cpp | Guyiguang/qt5-node-editor | 9c9bc9b713aa6fe4c59e6d70ce0115a2800d461a | [
"MIT"
] | 11 | 2015-06-19T07:39:40.000Z | 2018-09-04T13:49:23.000Z | src/qnodeeditorsocketmodel.cpp | rochus/qt5-node-editor | 9c9bc9b713aa6fe4c59e6d70ce0115a2800d461a | [
"MIT"
] | 52 | 2015-04-02T03:59:26.000Z | 2020-12-29T11:33:10.000Z | #include "qnodeeditorsocketmodel.h"
#include "graphicsnode.hpp"
#include "graphicsnodescene.hpp"
#include "graphicsbezieredge.hpp"
#include "graphicsbezieredge_p.h"
#include "qreactiveproxymodel.h"
#include "qmodeldatalistdecoder.h"
#include <QtCore/QDebug>
#include <QtCore/QMimeData>
#include <QtCore/QSortFilterProxyModel>
#include "qobjectmodel.h" //TODO remove
#if QT_VERSION < 0x050700
//Q_FOREACH is deprecated and Qt CoW containers are detached on C++11 for loops
template<typename T>
const T& qAsConst(const T& v)
{
return const_cast<const T&>(v);
}
#endif
class QNodeEdgeFilterProxy;
struct EdgeWrapper;
struct SocketWrapper;
struct NodeWrapper final
{
NodeWrapper(QNodeEditorSocketModel *q, const QPersistentModelIndex& i) : m_Node(q, i) {}
GraphicsNode m_Node;
// Keep aligned with the source row
QVector<int> m_lSourcesFromSrc {};
QVector<int> m_lSinksFromSrc {};
QVector<int> m_lSourcesToSrc {};
QVector<int> m_lSinksToSrc {};
// Keep aligned with the node row
QVector<SocketWrapper*> m_lSources {};
QVector<SocketWrapper*> m_lSinks {};
mutable QNodeEdgeFilterProxy *m_pSourceProxy {Q_NULLPTR};
mutable QNodeEdgeFilterProxy *m_pSinkProxy {Q_NULLPTR};
QRectF m_SceneRect;
};
struct SocketWrapper final
{
SocketWrapper(const QModelIndex& idx, GraphicsNodeSocket::SocketType t, NodeWrapper* n)
: m_Socket(idx, t, &n->m_Node), m_pNode(n) {}
GraphicsNodeSocket m_Socket;
NodeWrapper* m_pNode;
EdgeWrapper* m_EdgeWrapper {Q_NULLPTR};
};
//TODO split the "data" and "proxy" part of this class and use it to replace
// the NodeWrapper:: content. This way, getting an on demand proxy will cost
// "nothing"
class QNodeEdgeFilterProxy final : public QAbstractProxyModel
{
Q_OBJECT
public:
explicit QNodeEdgeFilterProxy(QNodeEditorSocketModelPrivate* d, NodeWrapper *w, GraphicsNodeSocket::SocketType t);
virtual int rowCount(const QModelIndex& parent = {}) const override;
virtual QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override;
virtual QModelIndex mapToSource(const QModelIndex& proxyIndex) const override;
virtual int columnCount(const QModelIndex& parent = {}) const override;
virtual QModelIndex index(int row, int column, const QModelIndex& parent ={}) const override;
virtual QVariant data(const QModelIndex& idx, int role) const override;
virtual QModelIndex parent(const QModelIndex& idx) const override;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
virtual Qt::ItemFlags flags(const QModelIndex &idx) const override;
// void updateExtraColumns(
private:
const GraphicsNodeSocket::SocketType m_Type;
const NodeWrapper *m_pWrapper;
// Helpers
void processRow(const QModelIndex& srcIdx);
QNodeEditorSocketModelPrivate* d_ptr;
};
struct EdgeWrapper final
{
explicit EdgeWrapper(QNodeEditorEdgeModel* m, const QModelIndex& index)
: m_Edge(m, index)
{ Q_ASSERT(index.isValid()); }
SocketWrapper* m_pSource {Q_NULLPTR};
GraphicsBezierEdge m_Edge ;
SocketWrapper* m_pSink {Q_NULLPTR};
bool m_IsShown { false };
int m_EdgeId {s_CurId++};
static int s_CurId;
};
class QNodeEditorSocketModelPrivate final : public QObject
{
Q_OBJECT
public:
enum class State {
NORMAL,
DRAGGING,
};
explicit QNodeEditorSocketModelPrivate(QObject* p) : QObject(p) {}
QNodeEditorEdgeModel m_EdgeModel {this};
QVector<NodeWrapper*> m_lWrappers;
QVector<EdgeWrapper*> m_lEdges;
GraphicsNodeScene* m_pScene;
State m_State {State::NORMAL};
quint32 m_CurrentTypeId {QMetaType::UnknownType};
// helper
GraphicsNode* insertNode(int idx);
NodeWrapper* getNode(const QModelIndex& idx, bool r = false) const;
void insertSockets(const QModelIndex& parent, int first, int last);
void updateSockets(const QModelIndex& parent, int first, int last);
GraphicsDirectedEdge* initiateConnectionFromSource(
const QModelIndex& index,
GraphicsNodeSocket::SocketType type,
const QPointF& point
);
// Use a template so the compiler can safely inline the result
template<
QVector<int> NodeWrapper::* SM,
QVector<SocketWrapper*> NodeWrapper::* S,
SocketWrapper* EdgeWrapper::* E
>
inline SocketWrapper* getSocketCommon(const QModelIndex& idx) const;
SocketWrapper* getSourceSocket(const QModelIndex& idx) const;
SocketWrapper* getSinkSocket(const QModelIndex& idx) const;
QNodeEditorSocketModel* q_ptr;
public Q_SLOTS:
void slotRowsInserted (const QModelIndex& parent, int first, int last);
void slotConnectionsInserted(const QModelIndex& parent, int first, int last);
void slotConnectionsChanged (const QModelIndex& tl, const QModelIndex& br );
void slotAboutRemoveItem (const QModelIndex &parent, int first, int last);
void exitDraggingMode();
};
int EdgeWrapper::s_CurId = 1;
QNodeEditorSocketModel::QNodeEditorSocketModel( QReactiveProxyModel* rmodel, GraphicsNodeScene* scene ) :
QTypeColoriserProxy(rmodel), d_ptr(new QNodeEditorSocketModelPrivate(this))
{
Q_ASSERT(rmodel);
setBackgroundRole<bool>(QBrush("#ff0000"));
setBackgroundRole<int>(QBrush("#ff00ff"));
setBackgroundRole<QAbstractItemModel*>(QBrush("#ffff00"));
rmodel->addConnectedRole(QObjectModel::Role::ValueRole);
d_ptr->q_ptr = this;
d_ptr->m_pScene = scene;
setSourceModel(rmodel);
d_ptr->m_EdgeModel.setSourceModel(rmodel->connectionsModel());
connect(this, &QAbstractItemModel::rowsInserted,
d_ptr, &QNodeEditorSocketModelPrivate::slotRowsInserted);
connect(this, &QAbstractItemModel::rowsAboutToBeRemoved,
d_ptr, &QNodeEditorSocketModelPrivate::slotAboutRemoveItem);
connect(&d_ptr->m_EdgeModel, &QAbstractItemModel::rowsInserted,
d_ptr, &QNodeEditorSocketModelPrivate::slotConnectionsInserted);
connect(&d_ptr->m_EdgeModel, &QAbstractItemModel::dataChanged,
d_ptr, &QNodeEditorSocketModelPrivate::slotConnectionsChanged);
rmodel->setCurrentProxy(this);
}
QNodeEditorSocketModel::~QNodeEditorSocketModel()
{
while (!d_ptr->m_lEdges.isEmpty())
delete d_ptr->m_lEdges.takeLast();
while (!d_ptr->m_lWrappers.isEmpty())
delete d_ptr->m_lWrappers.takeLast();
delete d_ptr;
}
void QNodeEditorSocketModel::setSourceModel(QAbstractItemModel *sm)
{
// This models can only work with a QReactiveProxyModel (no proxies)
Q_ASSERT(qobject_cast<QReactiveProxyModel*>(sm));
QTypeColoriserProxy::setSourceModel(sm);
//TODO clear (this can wait, it wont happen anyway)
d_ptr->slotRowsInserted({}, 0, sourceModel()->rowCount() -1 );
}
bool QNodeEditorSocketModel::setData(const QModelIndex &idx, const QVariant &value, int role)
{
if (!idx.isValid())
return false;
if (role == Qt::SizeHintRole && value.canConvert<QRectF>() && !idx.parent().isValid()) {
auto n = d_ptr->getNode(idx);
Q_ASSERT(n);
n->m_SceneRect = value.toRectF();
Q_EMIT dataChanged(idx, idx);
// All socket position also changed
const int cc = rowCount(idx);
if (cc)
Q_EMIT dataChanged(index(0,0,idx), index(cc -1, 0, idx));
return true;
}
return QTypeColoriserProxy::setData(idx, value, role);
}
QMimeData *QNodeEditorSocketModel::mimeData(const QModelIndexList &idxs) const
{
auto md = QTypeColoriserProxy::mimeData(idxs);
// Assume the QMimeData exist only while the data is being dragged
if (md) {
const QModelDataListDecoder decoder(md);
auto typeId = decoder.typeId(Qt::EditRole);
if (typeId != QMetaType::UnknownType) {
d_ptr->m_State = QNodeEditorSocketModelPrivate::State::DRAGGING;
d_ptr->m_CurrentTypeId = typeId;
connect(md, &QObject::destroyed, d_ptr,
&QNodeEditorSocketModelPrivate::exitDraggingMode);
for (auto n : qAsConst(d_ptr->m_lWrappers))
n->m_Node.update();
}
}
return md;
}
Qt::ItemFlags QNodeEditorSocketModel::flags(const QModelIndex &idx) const
{
Qt::ItemFlags f = QTypeColoriserProxy::flags(idx);
// Disable everything but compatible sockets
return f ^ ((
d_ptr->m_State == QNodeEditorSocketModelPrivate::State::DRAGGING &&
(!idx.data(Qt::EditRole).canConvert(d_ptr->m_CurrentTypeId)) &&
f | Qt::ItemIsEnabled
) ? Qt::ItemIsEnabled : Qt::NoItemFlags);;
}
void QNodeEditorSocketModelPrivate::exitDraggingMode()
{
m_CurrentTypeId = QMetaType::UnknownType;
m_State = QNodeEditorSocketModelPrivate::State::NORMAL;
for (auto n : qAsConst(m_lWrappers))
n->m_Node.update();
}
GraphicsNodeScene* QNodeEditorSocketModel::scene() const
{
return d_ptr->m_pScene;
}
GraphicsNodeScene* QNodeEditorEdgeModel::scene() const
{
return d_ptr->m_pScene;
}
int QNodeEditorSocketModel::sourceSocketCount(const QModelIndex& idx) const
{
const auto nodew = d_ptr->getNode(idx);
return nodew ? nodew->m_lSources.size() : 0;
}
int QNodeEditorSocketModel::sinkSocketCount(const QModelIndex& idx) const
{
const auto nodew = d_ptr->getNode(idx);
return nodew ? nodew->m_lSinks.size() : 0;
}
GraphicsNode* QNodeEditorSocketModel::getNode(const QModelIndex& idx, bool recursive)
{
if ((!idx.isValid()) || idx.model() != this)
return Q_NULLPTR;
const auto i = (recursive && idx.parent().isValid()) ? idx.parent() : idx;
auto nodew = d_ptr->getNode(i);
return nodew ? &nodew->m_Node : Q_NULLPTR;
}
template<
QVector<int> NodeWrapper::* SM,
QVector<SocketWrapper*> NodeWrapper::* S,
SocketWrapper* EdgeWrapper::* E
>
SocketWrapper* QNodeEditorSocketModelPrivate::getSocketCommon(const QModelIndex& idx) const
{
// Use some dark template metamagic. This could have been done otherwise
if (!idx.parent().isValid())
return Q_NULLPTR;
if (idx.model() == q_ptr->edgeModel()) {
const EdgeWrapper* e = m_lEdges[idx.row()];
return (*e).*E;
}
const NodeWrapper* nodew = getNode(idx, true);
if (!nodew)
return Q_NULLPTR;
// The -1 is because int defaults to 0 and invalid is -1
const int relIdx = ((*nodew).*SM).size() > idx.row() ?
((*nodew).*SM)[idx.row()] - 1 : -1;
auto ret = relIdx != -1 ? ((*nodew).*S)[relIdx] : Q_NULLPTR;
// Q_ASSERT((!ret) || ret->m_Socket.index() == idx);
return ret;
}
SocketWrapper* QNodeEditorSocketModelPrivate::getSourceSocket(const QModelIndex& idx) const
{
return getSocketCommon<
&NodeWrapper::m_lSourcesFromSrc, &NodeWrapper::m_lSources, &EdgeWrapper::m_pSource
>(idx);
}
SocketWrapper* QNodeEditorSocketModelPrivate::getSinkSocket(const QModelIndex& idx) const
{
return getSocketCommon<
&NodeWrapper::m_lSinksFromSrc, &NodeWrapper::m_lSinks, &EdgeWrapper::m_pSink
>(idx);
}
GraphicsNodeSocket* QNodeEditorSocketModel::getSourceSocket(const QModelIndex& idx)
{
return &d_ptr->getSocketCommon<
&NodeWrapper::m_lSourcesFromSrc, &NodeWrapper::m_lSources, &EdgeWrapper::m_pSource
>(idx)->m_Socket;
}
GraphicsNodeSocket* QNodeEditorSocketModel::getSinkSocket(const QModelIndex& idx)
{
return &d_ptr->getSocketCommon<
&NodeWrapper::m_lSinksFromSrc, &NodeWrapper::m_lSinks, &EdgeWrapper::m_pSink
>(idx)->m_Socket;
}
GraphicsDirectedEdge* QNodeEditorSocketModel::getSourceEdge(const QModelIndex& idx)
{
return idx.model() == edgeModel() ?
&d_ptr->m_lEdges[idx.row()]->m_Edge : Q_NULLPTR;
//FIXME support SocketModel index
}
GraphicsDirectedEdge* QNodeEditorSocketModel::getSinkEdge(const QModelIndex& idx)
{
return idx.model() == edgeModel() ?
&d_ptr->m_lEdges[idx.row()]->m_Edge : Q_NULLPTR;
//FIXME support SocketModel index
}
QNodeEditorEdgeModel* QNodeEditorSocketModel::edgeModel() const
{
return &d_ptr->m_EdgeModel;
}
GraphicsDirectedEdge* QNodeEditorSocketModelPrivate::initiateConnectionFromSource( const QModelIndex& idx, GraphicsNodeSocket::SocketType type, const QPointF& point )
{
Q_UNUSED(type ); //TODO use it or delete it
Q_UNUSED(point); //TODO use it or delete it
if (!idx.parent().isValid()) {
qWarning() << "Cannot initiate an edge from an invalid node index";
return Q_NULLPTR;
}
const int last = q_ptr->edgeModel()->rowCount() - 1;
if (m_lEdges.size() <= last || !m_lEdges[last]) {
m_lEdges.resize(std::max(m_lEdges.size(), last+1));
m_lEdges[last] = new EdgeWrapper(
q_ptr->edgeModel(),
q_ptr->edgeModel()->index(last, 1)
);
m_pScene->addItem(m_lEdges[last]->m_Edge.graphicsItem());
}
return &m_lEdges[last]->m_Edge;
}
GraphicsDirectedEdge* QNodeEditorSocketModel::initiateConnectionFromSource(const QModelIndex& index, const QPointF& point)
{
return d_ptr->initiateConnectionFromSource(
index, GraphicsNodeSocket::SocketType::SOURCE, point
);
}
GraphicsDirectedEdge* QNodeEditorSocketModel::initiateConnectionFromSink(const QModelIndex& index, const QPointF& point)
{
return d_ptr->initiateConnectionFromSource(
index, GraphicsNodeSocket::SocketType::SINK, point
);
}
QAbstractItemModel *QNodeEditorSocketModel::sinkSocketModel(const QModelIndex& node) const
{
auto n = d_ptr->getNode(node);
if (!n)
return Q_NULLPTR;
if (!n->m_pSinkProxy)
n->m_pSinkProxy = new QNodeEdgeFilterProxy(
d_ptr,
n,
GraphicsNodeSocket::SocketType::SINK
);
return n->m_pSinkProxy;
}
QAbstractItemModel *QNodeEditorSocketModel::sourceSocketModel(const QModelIndex& node) const
{
auto n = d_ptr->getNode(node);
if (!n)
return Q_NULLPTR;
if (!n->m_pSourceProxy)
n->m_pSourceProxy = new QNodeEdgeFilterProxy(
d_ptr,
n,
GraphicsNodeSocket::SocketType::SOURCE
);
return n->m_pSourceProxy;
}
void QNodeEditorSocketModelPrivate::slotRowsInserted(const QModelIndex& parent, int first, int last)
{
if (last < first) return;
if (!parent.isValid()) {
// create new nodes
for (int i = first; i <= last; i++) {
const auto idx = q_ptr->index(i, 0);
if (idx.isValid()) {
insertNode(idx.row());
slotRowsInserted(idx, 0, q_ptr->rowCount(idx));
}
}
}
else if (!parent.parent().isValid())
insertSockets(parent, first, last);
}
GraphicsNode* QNodeEditorSocketModelPrivate::insertNode(int idx)
{
const auto idx2 = q_ptr->index(idx, 0);
Q_ASSERT(idx2.isValid());
if (idx == 0 && m_lWrappers.size())
Q_ASSERT(false);
auto nw = new NodeWrapper(q_ptr, idx2);
m_lWrappers.insert(idx, nw);
m_pScene->addItem(nw->m_Node.graphicsItem());
return &nw->m_Node;
}
NodeWrapper* QNodeEditorSocketModelPrivate::getNode(const QModelIndex& idx, bool r) const
{
// for convenience
auto i = idx.model() == q_ptr->sourceModel() ? q_ptr->mapFromSource(idx) : idx;
if ((!i.isValid()) || i.model() != q_ptr)
return Q_NULLPTR;
if (i.parent().isValid() && r)
i = i.parent();
if (i.parent().isValid())
return Q_NULLPTR;
Q_ASSERT(i == q_ptr->index(i.row(), i.column()));
Q_ASSERT(i.row() < q_ptr->rowCount());
// This should have been taken care of already. If it isn't, either the
// source model is buggy (it will cause crashes later anyway) or this
// code is (and in that case, the state is already corrupted, ignoring that
// will cause garbage data to be shown/serialized).
Q_ASSERT(m_lWrappers.size() > i.row());
return m_lWrappers[i.row()];
}
void QNodeEditorSocketModelPrivate::insertSockets(const QModelIndex& parent, int first, int last)
{
Q_UNUSED(first)
Q_UNUSED(last)
auto nodew = getNode(parent);
Q_ASSERT(nodew);
Q_ASSERT(parent.isValid() && (!parent.parent().isValid()));
Q_ASSERT(parent.model() == q_ptr);
Q_ASSERT(nodew->m_lSourcesFromSrc.size() >= first);
Q_ASSERT(nodew->m_lSinksFromSrc.size() >= first);
for (int i = first; i <= last; i++) {
const auto idx = q_ptr->index(i, 0, parent);
// It doesn't attempt to insert the socket at the correct index as
// many items will be rejected
constexpr static const Qt::ItemFlags sourceFlags(
Qt::ItemIsDragEnabled |
Qt::ItemIsSelectable
);
// SOURCES
if ((idx.flags() & sourceFlags) == sourceFlags) {
auto s = new SocketWrapper(
idx,
GraphicsNodeSocket::SocketType::SOURCE,
nodew
);
nodew->m_lSourcesFromSrc.insert(i, nodew->m_lSources.size() + 1);
nodew->m_lSources << s;
nodew->m_lSourcesToSrc << i;
}
else
nodew->m_lSourcesFromSrc.insert(i, 0);
constexpr static const Qt::ItemFlags sinkFlags(
Qt::ItemIsDropEnabled |
Qt::ItemIsSelectable |
Qt::ItemIsEditable
);
// SINKS
if ((idx.flags() & sinkFlags) == sinkFlags) {
auto s = new SocketWrapper(
idx,
GraphicsNodeSocket::SocketType::SINK,
nodew
);
nodew->m_lSinksFromSrc.insert(i, nodew->m_lSinks.size() + 1);
nodew->m_lSinks << s;
nodew->m_lSinksToSrc << i;
}
else
nodew->m_lSinksFromSrc.insert(i, 0);
nodew->m_Node.update();
}
Q_ASSERT(nodew->m_lSinksFromSrc.size() == nodew->m_lSourcesFromSrc.size());
}
void QNodeEditorSocketModelPrivate::updateSockets(const QModelIndex& parent, int first, int last)
{
Q_UNUSED(parent)
Q_UNUSED(first)
Q_UNUSED(last)
//TODO
}
QNodeEditorEdgeModel::QNodeEditorEdgeModel(QNodeEditorSocketModelPrivate* parent)
: QIdentityProxyModel(parent), d_ptr(parent)
{
}
QNodeEditorEdgeModel::~QNodeEditorEdgeModel()
{ /* Nothing is owned by the edge model*/ }
bool QNodeEditorEdgeModel::canConnect(const QModelIndex& idx1, const QModelIndex& idx2) const
{
Q_UNUSED(idx1)
Q_UNUSED(idx2)
return true; //TODO
}
bool QNodeEditorEdgeModel::connectSocket(const QModelIndex& idx1, const QModelIndex& idx2)
{
if (idx1.model() != d_ptr->q_ptr || idx2.model() != d_ptr->q_ptr)
return false;
auto m = qobject_cast<QReactiveProxyModel*>(d_ptr->q_ptr->sourceModel());
m->connectIndices(
d_ptr->q_ptr->mapToSource(idx1),
d_ptr->q_ptr->mapToSource(idx2)
);
return true;
}
// bool QNodeEditorEdgeModel::setData(const QModelIndex &index, const QVariant &value, int role)
// {
// if (!index.isValid())
// return false;
//
// switch (role) {
// case Qt::SizeHintRole:
// break;
// }
//
// return QIdentityProxyModel::setData(index, value, role);
// }
QVariant QNodeEditorEdgeModel::data(const QModelIndex& idx, int role) const
{
if (!idx.isValid())
return {};
Q_ASSERT(idx.model() == this);
QModelIndex srcIdx;
switch(idx.column()) {
case QReactiveProxyModel::ConnectionsColumns::SOURCE:
srcIdx = mapToSource(idx).data(
QReactiveProxyModel::ConnectionsRoles::SOURCE_INDEX
).toModelIndex();
break;
case QReactiveProxyModel::ConnectionsColumns::DESTINATION:
srcIdx = mapToSource(idx).data(
QReactiveProxyModel::ConnectionsRoles::DESTINATION_INDEX
).toModelIndex();
break;
case QReactiveProxyModel::ConnectionsColumns::CONNECTION:
srcIdx = mapToSource(index(idx.row(),2)).data(
QReactiveProxyModel::ConnectionsRoles::DESTINATION_INDEX
).toModelIndex();
// Use the socket background as line color
if (role != Qt::ForegroundRole)
break;
if (!srcIdx.isValid()) {
srcIdx = mapToSource(index(idx.row(),0)).data(
QReactiveProxyModel::ConnectionsRoles::SOURCE_INDEX
).toModelIndex();
}
return d_ptr->q_ptr->mapFromSource(srcIdx).data(Qt::BackgroundRole);
}
if (srcIdx.model() == d_ptr->q_ptr->sourceModel())
srcIdx = d_ptr->q_ptr->mapFromSource(srcIdx);
// It will crash soon if it is false, better do it now
Q_ASSERT(
(!srcIdx.isValid()) ||
srcIdx.model() == d_ptr->q_ptr ||
srcIdx.model() == d_ptr->q_ptr->edgeModel()
);
if (srcIdx.model() == d_ptr->q_ptr && srcIdx.parent().isValid()) //TODO remove
Q_ASSERT(srcIdx.parent().data() == d_ptr->q_ptr->index(srcIdx.parent().row(),0).data());
auto sock = (!idx.column()) ?
d_ptr->getSourceSocket(srcIdx) : d_ptr->getSinkSocket(srcIdx);
if (sock && role == Qt::SizeHintRole)
return sock->m_Socket.graphicsItem()->mapToScene(0,0);
return QIdentityProxyModel::data(idx, role);
}
void QNodeEditorSocketModelPrivate::slotConnectionsInserted(const QModelIndex& parent, int first, int last)
{
//FIXME dead code
typedef QReactiveProxyModel::ConnectionsColumns Column;
auto srcSockI = q_ptr->index(first, Column::SOURCE).data(
QReactiveProxyModel::ConnectionsRoles::SOURCE_INDEX
);
auto destSockI = q_ptr->index(first, Column::DESTINATION).data(
QReactiveProxyModel::ConnectionsRoles::DESTINATION_INDEX
);
// If this happens, then the model is buggy or there is a race condition.
if ((!srcSockI.isValid()) && (!destSockI.isValid()))
return;
//TODO support rows removed
// Avoid pointless indentation
if (last > first)
slotConnectionsInserted(parent, ++first, last);
}
void QNodeEditorSocketModelPrivate::slotConnectionsChanged(const QModelIndex& tl, const QModelIndex& br)
{
typedef QReactiveProxyModel::ConnectionsRoles CRole;
for (int i = tl.row(); i <= br.row(); i++) {
const auto src = m_EdgeModel.index(i, 0).data(CRole::SOURCE_INDEX ).toModelIndex();
const auto sink = m_EdgeModel.index(i, 2).data(CRole::DESTINATION_INDEX).toModelIndex();
// Make sure the edge exists
if (m_lEdges.size()-1 < i || !m_lEdges[i]) {
m_lEdges.resize(std::max(m_lEdges.size(), i+1));
m_lEdges[i] = new EdgeWrapper(&m_EdgeModel, m_EdgeModel.index(i, 1));
}
auto e = m_lEdges[i];
auto oldSrc(e->m_pSource), oldSink(e->m_pSink);
// Update the node mapping
if ((e->m_pSource = getSourceSocket(src)))
e->m_pSource->m_Socket.setEdge(m_EdgeModel.index(i, 0));
if (oldSrc != e->m_pSource) {
if (oldSrc)
oldSrc->m_Socket.setEdge({});
if (oldSrc && oldSrc->m_EdgeWrapper && oldSrc->m_EdgeWrapper == e) {
oldSrc->m_EdgeWrapper = Q_NULLPTR;
}
if (e->m_pSource) {
e->m_pSource->m_EdgeWrapper = e;
}
}
if ((e->m_pSink = getSinkSocket(sink)))
e->m_pSink->m_Socket.setEdge(m_EdgeModel.index(i, 2));
if (oldSink != e->m_pSink) {
if (oldSink)
oldSink->m_Socket.setEdge({});
if (oldSink && oldSink->m_EdgeWrapper && oldSink->m_EdgeWrapper == e) {
oldSink->m_EdgeWrapper = Q_NULLPTR;
}
if (e->m_pSink)
e->m_pSink->m_EdgeWrapper = e;
}
// Update the graphic item
const bool isUsed = e->m_pSource || e->m_pSink;
e->m_Edge.update();
if (e->m_IsShown != isUsed && isUsed)
m_pScene->addItem(e->m_Edge.graphicsItem());
else if (e->m_IsShown != isUsed && !isUsed)
m_pScene->removeItem(e->m_Edge.graphicsItem());
e->m_IsShown = isUsed;
}
}
void QNodeEditorSocketModelPrivate::slotAboutRemoveItem(const QModelIndex &parent, int first, int last)
{
if (first < 0 || last < first)
return;
if (!parent.isValid() && m_lWrappers.size() > last) {
for (int i = first; i <= last; i++) {
const auto idx = q_ptr->index(i, 0, parent);
// remove the sockets
slotAboutRemoveItem(idx, 0, q_ptr->rowCount(idx) - 1);
auto nw = m_lWrappers[i];
nw->m_Node.setCentralWidget(Q_NULLPTR);
m_pScene->removeItem(nw->m_Node.graphicsItem());
m_lWrappers.remove(i - (i-first));
delete nw;
}
}
else if (parent.isValid() && !parent.parent().isValid()) {
auto nw = m_lWrappers[parent.row()];
Q_ASSERT(nw);
QList<int> srcToDel, sinkToDel;
for (int i = first; i <= last; i++) {
Q_ASSERT(parent == nw->m_Node.index());
Q_ASSERT(nw->m_lSinksFromSrc.size() == nw->m_lSourcesFromSrc.size());
Q_ASSERT(nw->m_lSourcesFromSrc.size() > q_ptr->rowCount(parent));
int sid = nw->m_lSourcesFromSrc[i] - 1;
if (sid >= 0) {
auto sw = nw->m_lSources[sid];
m_pScene->removeItem(sw->m_Socket.graphicsItem());
srcToDel << sid;
delete sw;
}
sid = nw->m_lSinksFromSrc[i] - 1;
if (sid >= 0) {
auto sw = nw->m_lSinks[sid];
m_pScene->removeItem(sw->m_Socket.graphicsItem());
sinkToDel << sid;
delete sw;
}
}
nw->m_lSinksFromSrc.remove(first, last - first + 1);
nw->m_lSourcesFromSrc.remove(first, last - first + 1);
// remove from the list, this assume the sockets are ordered
for (int i = 0; i < srcToDel.size(); i++) {
nw->m_lSources.remove(srcToDel[i] - i);
nw->m_lSourcesToSrc.remove(srcToDel[i] - i);
}
for (int i = 0; i < sinkToDel.size(); i++) {
nw->m_lSinks.remove(sinkToDel[i] - i);
nw->m_lSinksToSrc.remove(sinkToDel[i] - i);
}
// reload the "FromSrc" mapping
int rc(q_ptr->rowCount(parent) - (last - first) - 1), csrc(0), csink(0);
for (int i = 0; i < rc; i++) {
const auto idx2 = q_ptr->index(i, 0, parent);
nw->m_lSourcesFromSrc[i] = (csrc < nw->m_lSources.size()
&& nw->m_lSources[csrc]->m_Socket.index() == idx2
&& ++csrc) ? csrc : -1;
nw->m_lSinksFromSrc[i] = (csink < nw->m_lSinks.size()
&& nw->m_lSinks[csink]->m_Socket.index() == idx2
&& ++csink) ? csink : -1;
}
}
}
QNodeEditorSocketModel* QNodeEditorEdgeModel::socketModel() const
{
return d_ptr->q_ptr;
}
QNodeEdgeFilterProxy::QNodeEdgeFilterProxy(QNodeEditorSocketModelPrivate* d, NodeWrapper *w, GraphicsNodeSocket::SocketType t) :
QAbstractProxyModel(d), m_Type(t), m_pWrapper(w), d_ptr(d)
{
setSourceModel(d->q_ptr);
}
int QNodeEdgeFilterProxy::rowCount(const QModelIndex& parent) const
{
if (parent.isValid())
return 0;
switch (m_Type) {
case GraphicsNodeSocket::SocketType::SOURCE:
return m_pWrapper->m_lSources.size();
case GraphicsNodeSocket::SocketType::SINK:
return m_pWrapper->m_lSinks.size();
}
return 0;
}
QModelIndex QNodeEdgeFilterProxy::mapFromSource(const QModelIndex& srcIdx) const
{
static const auto check = [](
const QVector<int>& l, const QModelIndex& src, const GraphicsNode* n
) -> bool {
return src.isValid()
&& l.size() > src.row()
&& n->index() == src.parent()
&& l[src.row()];
};
switch (m_Type) {
case GraphicsNodeSocket::SocketType::SOURCE:
if (check(m_pWrapper->m_lSourcesFromSrc, srcIdx, &m_pWrapper->m_Node))
return createIndex(m_pWrapper->m_lSourcesFromSrc[srcIdx.row()] - 1, 0, Q_NULLPTR);
break;
case GraphicsNodeSocket::SocketType::SINK:
if (check(m_pWrapper->m_lSinksFromSrc, srcIdx, &m_pWrapper->m_Node))
return createIndex(m_pWrapper->m_lSinksFromSrc[srcIdx.row()] - 1, 0, Q_NULLPTR);
break;
}
return {};
}
QModelIndex QNodeEdgeFilterProxy::mapToSource(const QModelIndex& proxyIndex) const
{
if ((!proxyIndex.isValid()) || proxyIndex.model() != this)
return {};
if (proxyIndex.column())
return {};
const auto srcP = m_pWrapper->m_Node.index();
switch (m_Type) {
case GraphicsNodeSocket::SocketType::SOURCE:
return d_ptr->q_ptr->index(m_pWrapper->m_lSourcesToSrc[proxyIndex.row()], 0, srcP);
case GraphicsNodeSocket::SocketType::SINK:
return d_ptr->q_ptr->index(m_pWrapper->m_lSinksToSrc[proxyIndex.row()], 0, srcP);
}
return {};
}
int QNodeEdgeFilterProxy::columnCount(const QModelIndex& parent) const
{
return parent.isValid() ? 0 : 4;
}
QModelIndex QNodeEdgeFilterProxy::index(int row, int column, const QModelIndex& parent) const
{
if (parent.isValid() || row < 0 || column < 0 || column > 3)
return {};
switch(m_Type) {
case GraphicsNodeSocket::SocketType::SOURCE:
if (row < m_pWrapper->m_lSources.size())
return createIndex(row, column, nullptr);
break;
case GraphicsNodeSocket::SocketType::SINK:
if (row < m_pWrapper->m_lSinks.size())
return createIndex(row, column, nullptr);
break;
}
return {};
}
QVariant QNodeEdgeFilterProxy::data(const QModelIndex& idx, int role) const
{
if ((!idx.isValid()) || idx.model() != this)
return {};
if (!idx.column())
return QAbstractProxyModel::data(idx, role);
SocketWrapper* i = Q_NULLPTR;
switch (m_Type) {
case GraphicsNodeSocket::SocketType::SOURCE:
Q_ASSERT(idx.row() < m_pWrapper->m_lSources.size());
i = m_pWrapper->m_lSources[idx.row()];
break;
case GraphicsNodeSocket::SocketType::SINK:
Q_ASSERT(idx.row() < m_pWrapper->m_lSinks.size());
i = m_pWrapper->m_lSinks[idx.row()];
break;
}
// There is nothing to display if the socket isn't connected
if ((!i) || (!i->m_EdgeWrapper))
return {};
const auto edgeIdx = i->m_EdgeWrapper->m_Edge.index();
if (idx.column() == 1) {
if (role == Qt::DisplayRole)
return i->m_EdgeWrapper->m_EdgeId;
else
return edgeIdx.data(role);
}
// This leaves columns 2 and 3 to handle
if (i->m_EdgeWrapper->m_pSink && i->m_EdgeWrapper->m_pSource) {
switch (m_Type) {
case GraphicsNodeSocket::SocketType::SOURCE:
if (idx.column() == 2)
return edgeIdx.model()->index(edgeIdx.row(), 2).data(role);
else {
return i->m_EdgeWrapper->m_pSink->m_pNode->m_Node.index().data(role);
}
case GraphicsNodeSocket::SocketType::SINK:
if (idx.column() == 2)
return edgeIdx.model()->index(edgeIdx.row(), 0).data(role);
else {
return i->m_EdgeWrapper->m_pSource->m_pNode->m_Node.index().data(role);
}
}
}
return {};
}
QModelIndex QNodeEdgeFilterProxy::parent(const QModelIndex& idx) const
{
Q_UNUSED(idx);
return {};
}
QVariant QNodeEdgeFilterProxy::headerData(int section, Qt::Orientation ori, int role) const
{
// The default one is good enough
if (ori == Qt::Vertical || role != Qt::DisplayRole)
return {};
static QVariant sock {QStringLiteral("Socket name")};
static QVariant edge {QStringLiteral("Edge")};
static QVariant other {QStringLiteral("Connected socket")};
static QVariant node {QStringLiteral("Connected node")};
switch(section) {
case 0:
return sock;
case 1:
return edge;
case 2:
return other;
case 3:
return node;
};
return {};
}
Qt::ItemFlags QNodeEdgeFilterProxy::flags(const QModelIndex &idx) const
{
if (!idx.isValid())
return Qt::NoItemFlags;
if (!idx.column())
return QAbstractProxyModel::flags(idx);
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
#include <qnodeeditorsocketmodel.moc>
| 30.092831 | 166 | 0.632632 | [
"model"
] |
50f677438320dca04985de7d0e6bfcd6f150b1b7 | 35,790 | cpp | C++ | src/Renderer.cpp | Quivscor/SoulEngine | 2951de54cd09c5a017c01d8ea124e375f0b62b9f | [
"MIT"
] | 2 | 2020-06-24T10:18:13.000Z | 2020-06-25T19:34:57.000Z | src/Renderer.cpp | Quivscor/SoulEngine | 2951de54cd09c5a017c01d8ea124e375f0b62b9f | [
"MIT"
] | null | null | null | src/Renderer.cpp | Quivscor/SoulEngine | 2951de54cd09c5a017c01d8ea124e375f0b62b9f | [
"MIT"
] | null | null | null | #include "Renderer.h"
#include "Model.h"
#include "TextRendering.h"
#include<Billboard.h>
#include <stb_image.h>
Shader* Renderer::defaultShader = nullptr;
Shader* Renderer::screenShader = nullptr;
Renderer::Renderer(Shader* shader, Shader* screenShader, Shader* skyBoxShader, Shader* refractorShader, Model* crystal)
{
lightPos = glm::vec3(50.0f,30.0f, 60.f);
this->lightProjection = glm::mat4(glm::ortho(-60.0f, 60.0f, -60.0f, 60.0f, near_plane, far_plane));
//this->lightView = glm::lookAt(lightPos, glm::vec3(0.0f), mainCamera->GetComponent<Camera>()->upVector);
this->lightView = glm::lookAt(lightPos, glm::vec3(50.0f, 0.0f, 40.0f), glm::vec3(.0, -1.0,-1.0));
this->lightSpaceMatrix = lightProjection * lightView;
defaultShader = shader;
this->screenShader = screenShader;
this->skyBoxShader = skyBoxShader;
this->refractorShader = refractorShader;
this->crystal = crystal;
/*box = new Billboard("./res/textures/ExampleBillboard.DDS", true);
box2 = new Billboard("./res/textures/stone.jpg", false);*/
simpleDepthShader = new Shader("./res/shaders/shadow_mapping_depth.vs", "./res/shaders/shadow_mapping_depth.fs");
//hud = new HUD(2.f,2.f, -1.f,- 1.f, "./res/textures/unknown1.jpg");
glGenFramebuffers(1, &depthMapFBO);
glGenTextures(1, &depthMap);
glBindTexture(GL_TEXTURE_2D, depthMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
float borderColor[] = { 1.0, 1.0, 1.0, 1.0 };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
// attach depth texture as FBO's depth buffer
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
// glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthMap, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//framebuffer configuration
glGenFramebuffers(1, &frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
//create a color attachment texture
glGenTextures(1, &textureColorBuffer);
glBindTexture(GL_TEXTURE_2D, textureColorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1920, 1080, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorBuffer, 0);
//create a renderebuffer object for depth and stencil attachment
glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1920, 1080);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
glGenVertexArrays(1, &quadVAO);
glGenBuffers(1, &quadVBO);
glBindVertexArray(quadVAO);
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
// skybox VAO
float skyboxVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
glGenVertexArrays(1, &skyboxVAO);
glGenBuffers(1, &skyboxVBO);
glBindVertexArray(skyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
std::vector<std::string> faces
{
"./res/textures/skybox/right.jpg",
"./res/textures/skybox/left.jpg",
"./res/textures/skybox/top.jpg",
"./res/textures/skybox/bottom.jpg",
"./res/textures/skybox/front.jpg",
"./res/textures/skybox/back.jpg",
};
cubemapTexture = loadCubemap(faces);
skyBoxShader->use();
skyBoxShader->setInt("skybox", 0);
}
Renderer::~Renderer()
{
}
void Renderer::Init()
{
cameraComponent = mainCamera->GetComponent<Camera>();
cameraTransform = mainCamera->GetComponent<Transform>();
std::cout << "\n=== Sorting Renderer Entities by shader\n";
SortEntities();
}
void Renderer::Update() const
{
glClearColor(0.0f, 0.3f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
DrawShadows();
DrawMeshes();
DrawGrass();
//DrawFrustum(mainCamera->GetComponent<Camera>()->m_Frustum);
/*glm::mat4 text_matrix_2D = glm::ortho(0.0f, 1280.0f, 0.0f, 720.0f);
glm::mat4 translate_2d_text = glm::translate(text_matrix_2D, glm::vec3(20.0f, 65.0f, .0f));
glm::mat4 scale_2d_text = glm::scale(glm::mat4(), glm::vec3(0.5f, 0.5f, 0.5f));
TextRendering::Instance()->draw("Poruszanie - WASD", glm::vec3(1.0f, 0.0f, 0.0f), text_matrix_2D);*/
std::shared_ptr<Transform> trns = m_Entities[0]->GetComponent<Transform>();
//std::cout << trns->GetLocalPosition().x << std::endl;
/*Billboard::Instance("./res/textures/ExampleBillboard.DDS", true,mainCamera, glm::vec3(trns->GetLocalPosition().x, trns->GetLocalPosition().y + 1.5f, trns->GetLocalPosition().z - 0.f), glm::vec2(1.0f, 0.125f));
Billboard::Instance("./res/textures/stone.jpg", false, mainCamera, glm::vec3(trns->GetLocalPosition().x, trns->GetLocalPosition().y + 2.5f, trns->GetLocalPosition().z - 0.f), glm::vec2(1.0f, 0.125f));*/
/*Billboard::Instance("./res/textures/ExampleBillboard.DDS", true)->Draw(mainCamera, glm::vec3(trns->GetLocalPosition().x, trns->GetLocalPosition().y + 1.5f, trns->GetLocalPosition().z - 0.f),glm::vec2(1.0f,0.125f));
Billboard::Instance("./res/textures/stone.jpg", false)->Draw(mainCamera, glm::vec3(trns->GetLocalPosition().x, trns->GetLocalPosition().y + 2.5f, trns->GetLocalPosition().z - 0.f), glm::vec2(1.0f, 0.125f));*/
glm::mat4 scale = glm::scale(trns->GetLocalMatrix(), glm::vec3(0.5f, 0.5f, 0.5f));
//glm::mat4 set_text_to_origin = glm::translate(trns->GetLocalMatrix(), glm::vec3(-2.f, 20.0f, 0.0f));
glm::mat4 text_rotate_y = glm::rotate(glm::mat4(), glm::radians(-trns->GetLocalRotation().y), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 text_translate_to_model_1 = glm::translate(trns->GetLocalMatrix(), glm::vec3(trns->GetLocalPosition().x - 2.f, trns->GetLocalPosition().y + 20.0f, trns->GetLocalPosition().z));
glm::mat4 text_matrix_3D_model_1 = cameraComponent->GetProjection() * cameraTransform->GetGlobalMatrix() * text_translate_to_model_1 * scale;
//TextRendering::Instance()->draw("Gracz", glm::vec3(1.0f, 0.0f, 0.0f), text_matrix_3D_model_1);
// drawing crystal object
refractorShader->use();
refractorShader->setMat4("projection", cameraComponent->GetProjection());
refractorShader->setMat4("view", cameraTransform->GetGlobalMatrix());
glm::mat4 model = glm::mat4(1.0f);
//model = glm::translate(model, glm::vec3(3.0f, 5.0f, 1.5f));
model = glm::scale(model, glm::vec3(1.0f, 3.0f, 1.0f));
//model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
refractorShader->setMat4("model", model);
refractorShader->setVec3("cameraPos", cameraTransform->GetGlobalPosition());
refractorShader->setInt("texture_diffuse1", 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, instanceManagers[0]->m_mesh->material->GetTextures()[0].id);
glBindVertexArray(crystal->meshes[0].GetVAO());
glDrawElements(GL_TRIANGLES, crystal->meshes[0].indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// draw skybox last
glDepthFunc(GL_LEQUAL); // change depth function so depth test passes when values are equal to depth buffer's content
skyBoxShader->use();
model = glm::mat4(1.0f);
glm::mat4 view = cameraTransform->GetGlobalMatrix();
view = glm::mat4(glm::mat3(cameraTransform->GetGlobalMatrix())); // remove translation from the view matrix
skyBoxShader->setMat4("view", view);
skyBoxShader->setMat4("model", model);
glm::mat4 projection = cameraComponent->GetProjection();
//glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
skyBoxShader->setMat4("projection", projection);
// skybox cube
glBindVertexArray(skyboxVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS); // set depth function back to default
DrawHPbar();
//Drawparts();
if (berserkerModeActive == true)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_DEPTH_TEST);
glClearColor(0.0f, 0.3f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
screenShader->use();
screenShader->setInt("screenTexture", 0);
glBindVertexArray(quadVAO);
glDisable(GL_DEPTH_TEST);
glBindTexture(GL_TEXTURE_2D, textureColorBuffer);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
DrawGUI();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
//hud->Drawbar();
}
void Renderer::LateUpdate() const
{
glfwSwapBuffers(Window::GetInstance()->GetMWindow());
}
void Renderer::DrawGUI() const
{
glm::mat4 text_matrix_2D = glm::ortho(0.0f, 1920.0f, 0.0f, 1080.0f);
for (int i = 0; i < m_Entities.size(); i++)
{
if (!m_Entities[i]->isActive)
continue;
if (m_Entities[i]->GetComponent<Text>() != nullptr)
{
std::shared_ptr<Text> text = m_Entities[i]->GetComponent<Text>();
TextRendering::Instance()->draw(text->text, text->color, text_matrix_2D * EntityManager::GetInstance()->GetEntity(text->GetOwnerID())->GetComponent<Transform>()->GetGlobalMatrix());
}
}
for (int i = 0; i < HUDs.size(); i++)
{
if (EntityManager::GetInstance()->GetEntity(HUDs[i].first->GetOwnerID())->isActive == true)
HUDs[i].first->Drawbar();
}
}
void Renderer::DrawHPbar() const
{
for (int i = 0; i < billboards.size(); i++)
{
if (EntityManager::GetInstance()->GetEntity(billboards[i].first->GetOwnerID())->isActive == true)
billboards[i].first->Draw(mainCamera, glm::vec3(billboards[i].second->GetGlobalPosition().x, billboards[i].second->GetGlobalPosition().y + 1.5f, billboards[i].second->GetGlobalPosition().z - 0.f), glm::vec2(1.0f, 0.125f));
}
}
void Renderer::DrawShadows() const
{
//lightProjection = glm::perspective(glm::radians(45.0f), (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT, near_plane, far_plane); // note that if you use a perspective projection matrix you'll have to change the light position as the current light position isn't enough to reflect the whole scene
simpleDepthShader->use();
simpleDepthShader->setMat4("lightSpaceMatrix", lightSpaceMatrix);
glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glClear(GL_DEPTH_BUFFER_BIT);
//glActiveTexture(GL_TEXTURE0);
////glBindTexture(GL_TEXTURE_2D, instanceManagers[0]->m_mesh->material->GetTextures()[0].id);
//glBindTexture(GL_TEXTURE_2D, cubemapTexture);
for (int i = 0; i < m_Entities.size(); i++)
{
if (!m_Entities[i]->isActive)
continue;
std::shared_ptr<Transform> trns = m_Entities[i]->GetComponent<Transform>();
std::shared_ptr<Mesh> mesh = m_Entities[i]->GetComponent<Mesh>();
float renderingRange = 20.0f;
if (m_Entities[i]->layer == Layer::GroundLayer)
{
renderingRange = 36.0f;
}
if (m_Entities[i]->layer != Layer::WaterLayer)
{
if (cameraComponent->DistanceFromCameraTarget(trns) > renderingRange)
continue;
}
simpleDepthShader->setMat4("model", trns->GetGlobalMatrix());
//simpleDepthShader->setMat4("model", trns->GetLocalMatrix());
if (mesh != nullptr)
{
std::shared_ptr<Model> modelComponent = m_Entities[i]->GetComponent<Model>();
if (modelComponent != nullptr)
{
modelComponent->initShaders(simpleDepthShader);
modelComponent->ChangeShadowBonesPositions();
simpleDepthShader->setBool("anim", true);
//m_Entities[i]->GetComponent<Mesh>()->material->SetShader(defaultShader);
}
else
{
simpleDepthShader->setBool("anim", false);
}
glBindVertexArray(mesh->GetVAO());
if (mesh->hasEBO)
{
glDrawElements(GL_TRIANGLES, mesh->indices.size(), GL_UNSIGNED_INT, 0);
}
else
{
glDrawArrays(GL_TRIANGLES, 0, mesh->vertices.size());
}
glBindVertexArray(0);
}
}
//simpleDepthShader->setMat4("model", *instanceManagers[0]->instanceModels);
//glBindVertexArray(instanceManagers[0]->m_model->meshes[0].GetVAO());
//glDrawElementsInstanced(GL_TRIANGLES, instanceManagers[0]->m_model->meshes[0].indices.size(), GL_UNSIGNED_INT, 0, instanceManagers[0]->amount);
////glBindVertexArray(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// reset viewport
glViewport(0, 0, 1920, 1080);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Renderer::DrawMeshes() const
{
//glm::mat4 lightProjection = glm::mat4(), lightView = glm::mat4();
//glm::mat4 lightSpaceMatrix = glm::mat4();
////lightProjection = glm::perspective(glm::radians(45.0f), (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT, near_plane, far_plane); // note that if you use a perspective projection matrix you'll have to change the light position as the current light position isn't enough to reflect the whole scene
//lightProjection = glm::ortho(-50.0f, 50.0f, -50.0f, 50.0f, near_plane, far_plane);
////lightView = glm::lookAt(lightPos, glm::vec3(0.0f), mainCamera->GetComponent<Camera>()->upVector);
//lightView = glm::lookAt(lightPos, glm::vec3(0.0f), glm::vec3(0.0, -1.0, 0.0));
//lightSpaceMatrix = lightProjection * lightView;
int modelsDrawnCount = 0;
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if (berserkerModeActive == true)
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0f, 0.3f, 0.5f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
for (int i = 0; i < m_Entities.size(); i++)
{
if (!m_Entities[i]->isActive)
continue;
std::shared_ptr<Transform> trns = m_Entities[i]->GetComponent<Transform>();
std::shared_ptr<Mesh> mesh = m_Entities[i]->GetComponent<Mesh>();
float renderingRange = 20.0f;
if (m_Entities[i]->layer == Layer::GroundLayer)
{
renderingRange = 36.0f;
}
if (m_Entities[i]->layer != Layer::WaterLayer)
{
if (cameraComponent->DistanceFromCameraTarget(trns) > renderingRange)
continue;
}
modelsDrawnCount++;
if (mesh != nullptr)
{
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
int anyTexture = 0;
Shader* shader = m_Entities[i]->GetComponent<Mesh>()->material->GetShader();
for (int j = 0; j < mesh->material->GetTextures().size(); j++)
{
anyTexture = 1;
//defaultShader->setInt("material.diffuse", i);
glActiveTexture(GL_TEXTURE0 + j); //glActiveTexture(diffuse_textureN), where N = GL_TEXTURE0 + i
std::string number = "";
std::string name = mesh->material->GetTextures()[j].type;
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++);
//defaultShader->setFloat(("material." + name + number).c_str(), i);
glBindTexture(GL_TEXTURE_2D, mesh->material->GetTextures()[j].id);
//glUniform1i(glGetUniformLocation(shader->ID, ("material." + name + number).c_str()), j);
}
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, depthMap);
/* glUniform1i(glGetUniformLocation(shader->ID, "material.shadowMap"), mesh->material->GetTextures().size());
unsigned int xd = glGetUniformLocation(shader->ID, "lightSpaceMatrix");
glUniformMatrix4fv(xd, 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix));*/
glm::vec3 playerPosition = mainCamera->GetComponent<Camera>()->cameraTarget->GetGlobalPosition();
shader->use();
shader->setVec3("dir_light.direction", glm::vec3(.0, -1.0, -1.0));
shader->setInt("material.shadowMap", 2);
shader->setMat4("lightSpaceMatrix", lightSpaceMatrix);
shader->setVec3("playerPosition", playerPosition);
std::shared_ptr<Model> modelComponent = m_Entities[i]->GetComponent<Model>();
if (modelComponent != nullptr)
{
modelComponent->initShaders(shader);
modelComponent->ChangeBonePositions();
//m_Entities[i]->GetComponent<Mesh>()->material->SetShader(defaultShader);
}
glUniform3f(glGetUniformLocation(shader->ID, "view_pos"), mainCamera->GetComponent<Transform>()->GetGlobalPosition().x, mainCamera->GetComponent<Transform>()->GetGlobalPosition().y, mainCamera->GetComponent<Transform>()->GetGlobalPosition().z);
glUniform1f(glGetUniformLocation(shader->ID, "material.shininess"), 0.5f);
glUniform1f(glGetUniformLocation(shader->ID, "material.transparency"), 1.0f);
glUniform3f(glGetUniformLocation(shader->ID, "dir_light.ambient"), 0.45f, 0.45f, 0.45f);
glUniform3f(glGetUniformLocation(shader->ID, "dir_light.diffuse"), 0.15f, 0.15f, 0.15f);
glUniform3f(glGetUniformLocation(shader->ID, "dir_light.specular"), 0.1f, 0.1f, 0.1f);
//// Point Light 1
//glUniform3f(glGetUniformLocation(shader->ID, "point_light.position"), mainCamera->GetComponent<Transform>()->GetGlobalPosition().x, mainCamera->GetComponent<Transform>()->GetGlobalPosition().y, mainCamera->GetComponent<Transform>()->GetGlobalPosition().z);
//glUniform3f(glGetUniformLocation(shader->ID, "point_light.ambient"), -0.2f, -1.0f, -0.3f);
//glUniform3f(glGetUniformLocation(shader->ID, "point_light.diffuse"), 0.4f, 0.4f, 0.4f);
//glUniform3f(glGetUniformLocation(shader->ID, "point_light.specular"), 0.5f, 0.5f, 0.5f);
//glUniform1f(glGetUniformLocation(shader->ID, "point_light.constant"), 1.0f);
//glUniform1f(glGetUniformLocation(shader->ID, "point_light.linear"), 0.007);
//glUniform1f(glGetUniformLocation(shader->ID, "point_light.quadratic"), 0.0002);
////glUniform3f(glGetUniformLocation(shader->ID, "dir_light.direction"), -0.2f, -1.0f, -50.3f);
//glUniform3f(glGetUniformLocation(shader->ID, "dir_light.ambient"), 0.55f, 0.55f, 0.55f);
//glUniform3f(glGetUniformLocation(shader->ID, "dir_light.diffuse"), 0.15f, 0.15f, 0.15f);
//glUniform3f(glGetUniformLocation(shader->ID, "dir_light.specular"), 0.1f, 0.1f, 0.1f);
//player position
//glUniform3f(glGetUniformLocation(shader->ID, "playerPosition"), playerPosition.x, playerPosition.y, playerPosition.z);
glm::mat4 mvp = cameraComponent->GetProjection() * cameraTransform->GetGlobalMatrix() * trns->GetGlobalMatrix();
/*std::cout << "\n"<< cameraComponent->GetProjection()[0][0] << " " << cameraComponent->GetProjection()[0][1] << " " << cameraComponent->GetProjection()[0][2] << " " << cameraComponent->GetProjection()[0][3]
<< "\n " << cameraComponent->GetProjection()[1][0] << " " << cameraComponent->GetProjection()[1][1] << " " << cameraComponent->GetProjection()[1][2] << " " << cameraComponent->GetProjection()[1][3]
<< "\n " << cameraComponent->GetProjection()[2][0] << " " << cameraComponent->GetProjection()[2][1] << " " << cameraComponent->GetProjection()[2][2] << " " << cameraComponent->GetProjection()[2][3]
<< "\n " << cameraComponent->GetProjection()[3][0] << " " << cameraComponent->GetProjection()[3][1] << " " << cameraComponent->GetProjection()[3][2] << " " << cameraComponent->GetProjection()[3][3];
std::cout << "\n" << cameraTransform->GetGlobalMatrix()[0][0] << " " << cameraTransform->GetGlobalMatrix()[0][1] << " " << cameraTransform->GetGlobalMatrix()[0][2] << " " << cameraTransform->GetGlobalMatrix()[0][3]
<< "\n " << cameraTransform->GetGlobalMatrix()[1][0] << " " << cameraTransform->GetGlobalMatrix()[1][1] << " " << cameraTransform->GetGlobalMatrix()[1][2] << " " << cameraTransform->GetGlobalMatrix()[1][3]
<< "\n " << cameraTransform->GetGlobalMatrix()[2][0] << " " << cameraTransform->GetGlobalMatrix()[2][1] << " " << cameraTransform->GetGlobalMatrix()[2][2] << " " << cameraTransform->GetGlobalMatrix()[2][3]
<< "\n " << cameraTransform->GetGlobalMatrix()[3][0] << " " << cameraTransform->GetGlobalMatrix()[3][1] << " " << cameraTransform->GetGlobalMatrix()[3][2] << " " << cameraTransform->GetGlobalMatrix()[3][3];
std::cout << "\n" << trns->GetGlobalMatrix()[0][0] << " " << trns->GetGlobalMatrix()[0][1] << " " << trns->GetGlobalMatrix()[0][2] << " " << trns->GetGlobalMatrix()[0][3]
<< "\n " << trns->GetGlobalMatrix()[1][0] << " " << trns->GetGlobalMatrix()[1][1] << " " << trns->GetGlobalMatrix()[1][2] << " " << trns->GetGlobalMatrix()[1][3]
<< "\n " << trns->GetGlobalMatrix()[2][0] << " " << trns->GetGlobalMatrix()[2][1] << " " << trns->GetGlobalMatrix()[2][2] << " " << trns->GetGlobalMatrix()[2][3]
<< "\n " << trns->GetGlobalMatrix()[3][0] << " " << trns->GetGlobalMatrix()[3][1] << " " << trns->GetGlobalMatrix()[3][2] << " " << trns->GetGlobalMatrix()[3][3];*/
unsigned int model = glGetUniformLocation(shader->ID, "M_matrix");
glUniformMatrix4fv(model, 1, GL_FALSE, &(trns->GetGlobalMatrix())[0][0]);
unsigned int transformLoc = glGetUniformLocation(shader->ID, "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &(mvp)[0][0]);
glUniform1f(glGetUniformLocation(shader->ID, "waveTime"), (float)TimeCustom::GetTime() * 0.1f);
unsigned int colorLoc = glGetUniformLocation(shader->ID, "color");
glUniform3fv(colorLoc, 1, glm::value_ptr(mesh->material->GetColor()));
glUniformMatrix4fv(glGetUniformLocation(shader->ID, "M_matrix"), 1, GL_FALSE, &(trns->GetGlobalMatrix())[0][0]);
glm::mat4 matr_normals_cube = glm::mat4(glm::transpose(glm::inverse(trns->GetGlobalMatrix())));
glUniformMatrix4fv(glGetUniformLocation(shader->ID, "normals_matrix"), 1, GL_FALSE, &matr_normals_cube[0][0]);
unsigned int hasTexture = glGetUniformLocation(shader->ID, "hasTexture");
glUniform1i(hasTexture, anyTexture);
// draw mesh
glBindVertexArray(mesh->GetVAO());
if (mesh->hasEBO)
{
glDrawElements(GL_TRIANGLES, mesh->indices.size(), GL_UNSIGNED_INT, 0);
}
else
{
glDrawArrays(GL_TRIANGLES, 0, mesh->vertices.size());
}
glBindVertexArray(0);
}
if(debugMode)
{
std::shared_ptr<Collider> collider = m_Entities[i]->GetComponent<Collider>();
if (collider != nullptr && collider->enabled == true)
{
DrawColliders(collider, trns);
}
}
}
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
//std::cout << "Models drawn: " << modelsDrawnCount << "\n";
}
void Renderer::DrawGrass() const
{
//simpleDepthShader->use();
//simpleDepthShader->setMat4("lightSpaceMatrix", lightSpaceMatrix);
//glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
//glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
//glClear(GL_DEPTH_BUFFER_BIT);
//*std::shared_ptr<Transform> trns = m_Entities[i]->GetComponent<Transform>();
//std::shared_ptr<Mesh> mesh = m_Entities[i]->GetComponent<Mesh>();*/
//simpleDepthShader->setMat4("model",* instanceManagers[0]->instanceModels);
//glBindVertexArray(instanceManagers[0]->m_model->meshes[0].GetVAO());
//glDrawElementsInstanced(GL_TRIANGLES, instanceManagers[0]->m_model->meshes[0].indices.size(), GL_UNSIGNED_INT, 0, instanceManagers[0]->amount);
//glBindVertexArray(0);
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
//// reset viewport
//glViewport(0, 0, 1280, 720);
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//glm::mat4 view = camera.GetViewMatrix();
//glm::mat4 lightProjection = glm::mat4(), lightView = glm::mat4();
//glm::mat4 lightSpaceMatrix = glm::mat4();
////lightProjection = glm::perspective(glm::radians(45.0f), (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT, near_plane, far_plane); // note that if you use a perspective projection matrix you'll have to change the light position as the current light position isn't enough to reflect the whole scene
//lightProjection = glm::ortho(-50.0f, 50.0f, -50.0f, 50.0f, near_plane, far_plane);
////lightView = glm::lookAt(lightPos, glm::vec3(0.0f), mainCamera->GetComponent<Camera>()->upVector);
//lightView = glm::lookAt(lightPos, glm::vec3(0.0f), glm::vec3(0.0, -1.0, 0.0));
//lightSpaceMatrix = lightProjection * lightView;
instanceManagers[0]->m_shader->use();
instanceManagers[0]->m_shader->setVec3("dir_light.direction", glm::vec3(.0, -1.0, -1.0));
glUniform3f(glGetUniformLocation(instanceManagers[0]->m_shader->ID, "view_pos"), mainCamera->GetComponent<Transform>()->GetGlobalPosition().x, mainCamera->GetComponent<Transform>()->GetGlobalPosition().y, mainCamera->GetComponent<Transform>()->GetGlobalPosition().z);
glUniform1f(glGetUniformLocation(instanceManagers[0]->m_shader->ID, "material.shininess"), 0.5f);
glUniform1f(glGetUniformLocation(instanceManagers[0]->m_shader->ID, "material.transparency"), 1.0f);
glUniform3f(glGetUniformLocation(instanceManagers[0]->m_shader->ID, "dir_light.ambient"), 0.45f, 0.45f, 0.45f);
glUniform3f(glGetUniformLocation(instanceManagers[0]->m_shader->ID, "dir_light.diffuse"), 0.15f, 0.15f, 0.15f);
glUniform3f(glGetUniformLocation(instanceManagers[0]->m_shader->ID, "dir_light.specular"), 0.1f, 0.1f, 0.1f);
instanceManagers[0]->m_shader->setInt("material.shadowMap", 2);
instanceManagers[0]->m_shader->setMat4("projection", cameraComponent->GetProjection());
instanceManagers[0]->m_shader->setMat4("view", cameraTransform->GetGlobalMatrix());
instanceManagers[0]->m_shader->setMat4("lightSpaceMatrix", lightSpaceMatrix);
instanceManagers[0]->m_shader->setInt("texture_diffuse1", 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, instanceManagers[0]->m_mesh->material->GetTextures()[0].id);
glBindVertexArray(instanceManagers[0]->m_model->meshes[0].GetVAO());
glDrawElementsInstanced(GL_TRIANGLES, instanceManagers[0]->m_model->meshes[0].indices.size(), GL_UNSIGNED_INT, 0, instanceManagers[0]->amount);
glBindVertexArray(0);
//glBindTexture(GL_TEXTURE_2D, instanceManagers.at[0]->m_model.get
////glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
////glm::mat4 view = camera.GetViewMatrix();
//instanceManagers[0]->m_shader->use();
//instanceManagers[0]->m_shader->setMat4("projection", cameraComponent->GetProjection());
//instanceManagers[0]->m_shader->setMat4("view", cameraTransform->GetGlobalMatrix());
//instanceManagers[0]->m_shader->setInt("texture_diffuse1", 0);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, instanceManagers[0]->m_mesh->material->GetTextures()[0].id);
//glBindVertexArray(instanceManagers[0]->m_model->meshes[0].GetVAO());
//glDrawElementsInstanced(GL_TRIANGLES, instanceManagers[0]->m_model->meshes[0].indices.size(), GL_UNSIGNED_INT, 0, instanceManagers[0]->amount);
//glBindVertexArray(0);
////glBindTexture(GL_TEXTURE_2D, instanceManagers.at[0]->m_model.get
}
void Renderer::RegisterManager(std::shared_ptr<InstanceManager> instanceManager)
{
instanceManagers.push_back(instanceManager);
}
void Renderer::Drawparts() const
{
for (int i = 0; i < Parts.size(); i++)
{
if (EntityManager::GetInstance()->GetEntity(Parts[i].first->GetOwnerID())->isActive == true)
Parts[i].first->Draw(mainCamera, glm::vec3(Parts[i].second->GetGlobalPosition().x, Parts[i].second->GetGlobalPosition().y + 1.5f, Parts[i].second->GetGlobalPosition().z - 0.f), glm::vec2(1.0f, 0.125f));
}
}
void Renderer::DrawColliders(std::shared_ptr<Collider> col, std::shared_ptr<Transform> trns) const
{
Shader* shader = defaultShader;
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
int pointsCount = (col->polygon.points.size() + 1) * 3;
float* vertices = new float[pointsCount];
for (int i = 0; i < col->polygon.points.size(); i++)
{
vertices[i * 3] = col->polygon.points[i].x;
vertices[i * 3 + 1] = 0.0f;
vertices[i * 3 + 2] = col->polygon.points[i].y;
//std::cout << vertices[i * 3] << " " << vertices[i * 3 + 1] << " " << vertices[i * 3 + 2] << " " << std::endl;
}
vertices[pointsCount - 3] = col->polygon.points[0].x;
vertices[pointsCount - 2] = 0.0f;
vertices[pointsCount - 1] = col->polygon.points[0].y;
//std::cout << vertices[pointsCount - 3] << " " << vertices[pointsCount - 2] << " " << vertices[pointsCount - 1] << " " << std::endl;
//std::cout << "Break" << std::endl;
/*float vertices[] = {
-5.0, 0.0f, -5.0,
-5.0, 0.0f, 5.0,
5.0, 0.0f, 5.0,
5.0, 0.0f, -5.0,
-5.0, 0.0f, -5.0
};*/
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, pointsCount * sizeof(float), vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// texture coord attribute
//glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
//glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
shader->use();
glm::mat4 mvp = mainCamera->GetComponent<Camera>()->GetProjection() * mainCamera->GetComponent<Transform>()->GetGlobalMatrix();// *trns->matrix;
unsigned int transformLoc = glGetUniformLocation(shader->ID, "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &(mvp)[0][0]);
unsigned int colorLoc = glGetUniformLocation(shader->ID, "color");
glUniform3fv(colorLoc, 1, glm::value_ptr(glm::vec3(0.0, 1.0f, 0.0f)));
unsigned int hasTexture = glGetUniformLocation(shader->ID, "hasTexture");
glUniform1i(hasTexture, 0);
glDrawArrays(GL_LINE_STRIP, 0, col->polygon.shape.size() + 1);
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
}
void Renderer::DrawCube(std::shared_ptr<Transform> transform, std::shared_ptr<Material> material)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
float vertices[] = {
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// texture coord attribute
//glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
//glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
defaultShader->use();
glm::mat4 mvp = cameraComponent->GetProjection() * cameraTransform->GetGlobalMatrix() * transform->GetGlobalMatrix();
unsigned int transformLoc = glGetUniformLocation(defaultShader->ID, "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &(mvp)[0][0]);
unsigned int colorLoc = glGetUniformLocation(defaultShader->ID, "color");
glUniform3fv(colorLoc, 1, glm::value_ptr(material->GetColor()));
unsigned int hasTexture = glGetUniformLocation(defaultShader->ID, "hasTexture");
glUniform1i(hasTexture, 0);
glDrawArrays(GL_TRIANGLES, 0, 36);
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
}
Shader* Renderer::GetDefualtShader()
{
return Renderer::defaultShader;
}
void Renderer::SetCamera(std::shared_ptr<Entity> camera)
{
mainCamera = camera;
//camProjection = camera->GetComponent<Camera>()->GetProjection();
//camView = camera->GetComponent<Transform>()->matrix;
}
/*void Renderer::DebugSetProjectionView(Transform* view, Camera* projection)
{
camProjection = projection;
camView = view;
}*/
unsigned int loadCubemap(std::vector<std::string> faces)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
void Renderer::SortEntities()
{
std::sort(m_Entities.begin(), m_Entities.end(),
[](const std::shared_ptr<Entity> &entity1, const std::shared_ptr<Entity> &entity2)
{
unsigned int shaderID1 = 0, shaderID2 = 0;
if (entity1->GetComponent<Mesh>() != nullptr)
{
shaderID1 = entity1->GetComponent<Mesh>()->material->GetShader()->ID;
}
if (entity2->GetComponent<Mesh>() != nullptr)
{
shaderID2 = entity2->GetComponent<Mesh>()->material->GetShader()->ID;
}
return shaderID1 > shaderID2;
});
}
void Renderer::RegisterBillboard(std::shared_ptr<Entity> billboard)
{
billboards.push_back(std::make_pair(billboard->GetComponent<Billboard>(), billboard->GetComponent<Transform>()));
}
void Renderer::RegisterHUD(std::shared_ptr<Entity> hut)
{
HUDs.push_back(std::make_pair(hut->GetComponent<HUD>(), hut->GetComponent<Transform>()));
}
void Renderer::RegisterPar(std::shared_ptr<Entity> Part)
{
Parts.push_back(std::make_pair(Part->GetComponent<Particles>(), Part->GetComponent<Transform>()));
}
| 39.372937 | 299 | 0.697066 | [
"mesh",
"render",
"object",
"shape",
"vector",
"model",
"transform"
] |
dd00b0592dfc9b696416bf1c0fdd8333b39538e3 | 15,054 | cc | C++ | src/drivers/devices/cuda/flowunit/torch/torch_inference_flowunit_test.cc | yamal-shang/modelbox | b2785568f4acd56d4922a793aa25516f883edc26 | [
"Apache-2.0"
] | 51 | 2021-09-24T08:57:44.000Z | 2022-03-31T09:12:46.000Z | src/drivers/devices/cuda/flowunit/torch/torch_inference_flowunit_test.cc | yamal-shang/modelbox | b2785568f4acd56d4922a793aa25516f883edc26 | [
"Apache-2.0"
] | 3 | 2022-02-22T07:13:02.000Z | 2022-03-30T02:03:40.000Z | src/drivers/devices/cuda/flowunit/torch/torch_inference_flowunit_test.cc | yamal-shang/modelbox | b2785568f4acd56d4922a793aa25516f883edc26 | [
"Apache-2.0"
] | 31 | 2021-11-29T02:22:39.000Z | 2022-03-15T03:05:24.000Z | /*
* Copyright 2021 The Modelbox Project Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cuda_runtime.h>
#include <dlfcn.h>
#include <functional>
#include <future>
#include <random>
#include <thread>
#include "modelbox/base/log.h"
#include "modelbox/base/utils.h"
#include "modelbox/buffer.h"
#include "driver_flow_test.h"
#include "flowunit_mockflowunit/flowunit_mockflowunit.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "test/mock/minimodelbox/mockflow.h"
using ::testing::_;
namespace modelbox {
class TorchInferenceFlowUnitTest : public testing::Test {
public:
TorchInferenceFlowUnitTest()
: driver_flow_(std::make_shared<MockFlow>()) {}
protected:
virtual void SetUp() {
int count = 0;
cudaGetDeviceCount(&count);
if (count <= 0) {
MBLOG_INFO << "no cuda device, skip test suit";
GTEST_SKIP();
}
AddMockFlowUnit();
SetUpTomlFiles();
}
virtual void TearDown() {
int count = 0;
cudaGetDeviceCount(&count);
if (count <= 0) {
GTEST_SKIP();
}
RemoveFiles();
driver_flow_ = nullptr;
};
std::shared_ptr<MockFlow> GetDriverFlow();
const std::string test_lib_dir = TEST_DRIVER_DIR,
test_data_dir = TEST_DATA_DIR, test_assets = TEST_ASSETS,
test_pt_file = "pytorch_example.pt",
test_pt_file_en = "pytorch_example_en.pt",
test_pt_2_output_file = "pytorch_example_2.pt",
test_toml_file = "virtual_torch_test.toml",
test_toml_file_en = "virtual_torch_test_encryt.toml",
test_toml_2_output_file = "virtual_torch_test_2.toml";
std::string torch_model_path, dest_pt_file, dest_toml_file;
std::string dest_pt_2_output_file, dest_toml_2_output_file;
std::string dest_pt_file_en, dest_toml_file_en;
private:
void AddMockFlowUnit();
void Register_Test_0_1_Flowunit();
void Register_Test_1_0_Flowunit();
void Register_Test_2_0_Flowunit();
void SetUpTomlFiles();
void RemoveFiles();
std::shared_ptr<MockFlow> driver_flow_;
};
void TorchInferenceFlowUnitTest::RemoveFiles() {
auto ret = remove(dest_toml_file.c_str());
EXPECT_EQ(ret, 0);
ret = remove(dest_pt_file.c_str());
EXPECT_EQ(ret, 0);
ret = remove(dest_pt_2_output_file.c_str());
EXPECT_EQ(ret, 0);
ret = remove(dest_toml_2_output_file.c_str());
EXPECT_EQ(ret, 0);
ret = remove(dest_toml_file_en.c_str());
EXPECT_EQ(ret, 0);
ret = remove(dest_pt_file_en.c_str());
EXPECT_EQ(ret, 0);
ret = remove(torch_model_path.c_str());
EXPECT_EQ(ret, 0);
}
void TorchInferenceFlowUnitTest::SetUpTomlFiles() {
const std::string src_file_dir = test_assets + "/torch";
const std::string src_pt_file = src_file_dir + "/" + test_pt_file;
const std::string src_file_pt_toml = test_data_dir + "/" + test_toml_file;
const std::string src_pt_2_output_file =
src_file_dir + "/" + test_pt_2_output_file;
const std::string src_file_pt_2_output_toml =
test_data_dir + "/" + test_toml_2_output_file;
const std::string src_pt_file_en = src_file_dir + "/" + test_pt_file_en;
const std::string src_file_pt_toml_en =
test_data_dir + "/" + test_toml_file_en;
torch_model_path = test_data_dir + "/torch";
auto mkdir_ret = mkdir(torch_model_path.c_str(), 0700);
EXPECT_EQ(mkdir_ret, 0);
dest_pt_file = torch_model_path + "/" + test_pt_file;
auto status = CopyFile(src_pt_file, dest_pt_file, 0);
EXPECT_EQ(status, STATUS_OK);
dest_toml_file = torch_model_path + "/" + test_toml_file;
status = CopyFile(src_file_pt_toml, dest_toml_file, 0);
EXPECT_EQ(status, STATUS_OK);
dest_pt_2_output_file = torch_model_path + "/" + test_pt_2_output_file;
status = CopyFile(src_pt_2_output_file, dest_pt_2_output_file, 0);
EXPECT_EQ(status, STATUS_OK);
dest_toml_2_output_file = torch_model_path + "/" + test_toml_2_output_file;
status = CopyFile(src_file_pt_2_output_toml, dest_toml_2_output_file, 0);
EXPECT_EQ(status, STATUS_OK);
dest_pt_file_en = torch_model_path + "/" + test_pt_file_en;
status = CopyFile(src_pt_file_en, dest_pt_file_en, 0);
EXPECT_EQ(status, STATUS_OK);
dest_toml_file_en = torch_model_path + "/" + test_toml_file_en;
status = CopyFile(src_file_pt_toml_en, dest_toml_file_en, 0);
EXPECT_EQ(status, STATUS_OK);
}
void TorchInferenceFlowUnitTest::Register_Test_0_1_Flowunit() {
auto mock_desc = GenerateFlowunitDesc("test_0_1", {}, {"Out_1"});
mock_desc->SetFlowType(STREAM);
auto open_func =
[=](const std::shared_ptr<modelbox::Configuration> &flow_option,
std::shared_ptr<MockFlowUnit> mock_flowunit) -> Status {
std::weak_ptr<MockFlowUnit> mock_flowunit_wp;
mock_flowunit_wp = mock_flowunit;
auto spt = mock_flowunit_wp.lock();
auto ext_data = spt->CreateExternalData();
if (!ext_data) {
MBLOG_ERROR << "can not get external data.";
}
auto buffer_list = ext_data->CreateBufferList();
buffer_list->Build({10 * sizeof(int)});
auto data = (int *)buffer_list->MutableData();
for (size_t i = 0; i < 10; i++) {
data[i] = i;
}
auto status = ext_data->Send(buffer_list);
if (!status) {
MBLOG_ERROR << "external data send buffer list failed:" << status;
}
status = ext_data->Close();
if (!status) {
MBLOG_ERROR << "external data close failed:" << status;
}
return modelbox::STATUS_OK;
};
auto process_func =
[=](std::shared_ptr<DataContext> op_ctx,
std::shared_ptr<MockFlowUnit> mock_flowunit) -> Status {
auto output_buf_1 = op_ctx->Output("Out_1");
std::vector<size_t> shape_vector(1, 200 * sizeof(float));
modelbox::ModelBoxDataType type = MODELBOX_FLOAT;
output_buf_1->Build(shape_vector);
output_buf_1->Set("type", type);
std::vector<size_t> shape{20, 10};
output_buf_1->Set("shape", shape);
auto dev_data = (float *)(output_buf_1->MutableData());
float num = 1.0;
for (size_t i = 0; i < output_buf_1->Size(); ++i) {
for (size_t j = 0; j < 200; ++j) {
dev_data[i * 200 + j] = num;
}
}
MBLOG_DEBUG << output_buf_1->GetBytes();
MBLOG_DEBUG << "test_0_1 gen data, 0" << output_buf_1->Size();
return modelbox::STATUS_OK;
};
auto mock_functions = std::make_shared<MockFunctionCollection>();
mock_functions->RegisterOpenFunc(open_func);
mock_functions->RegisterProcessFunc(process_func);
driver_flow_->AddFlowUnitDesc(mock_desc, mock_functions->GenerateCreateFunc(),
TEST_DRIVER_DIR);
};
void TorchInferenceFlowUnitTest::Register_Test_1_0_Flowunit() {
auto mock_desc = GenerateFlowunitDesc("test_1_0", {"In_1"}, {});
mock_desc->SetFlowType(STREAM);
auto post_func = [=](std::shared_ptr<DataContext> data_ctx,
std::shared_ptr<MockFlowUnit> mock_flowunit) {
MBLOG_INFO << "test_1_0 "
<< "DataPost";
return modelbox::STATUS_STOP;
};
auto process_func = [=](std::shared_ptr<DataContext> op_ctx,
std::shared_ptr<MockFlowUnit> mock_flowunit) {
std::shared_ptr<BufferList> input_bufs = op_ctx->Input("In_1");
EXPECT_EQ(input_bufs->Size(), 1);
std::vector<size_t> shape_vector{10, 10};
std::vector<size_t> input_shape;
auto result = input_bufs->At(0)->Get("shape", input_shape);
EXPECT_TRUE(result);
EXPECT_EQ(input_shape, shape_vector);
for (size_t i = 0; i < input_bufs->Size(); ++i) {
auto input_data =
static_cast<const float *>(input_bufs->ConstBufferData(i));
MBLOG_DEBUG << "index: " << i;
for (size_t j = 0; j < 100; j += 10) {
MBLOG_DEBUG << input_data[j];
}
EXPECT_NEAR(input_data[0], 9.3490, 1e-4);
EXPECT_NEAR(input_data[10], 7.3774, 1e-4);
EXPECT_NEAR(input_data[20], 10.6521, 1e-4);
EXPECT_NEAR(input_data[30], 8.6493, 1e-4);
EXPECT_NEAR(input_data[40], 8.0384, 1e-4);
EXPECT_NEAR(input_data[50], 9.2835, 1e-4);
EXPECT_NEAR(input_data[60], 11.0915, 1e-4);
EXPECT_NEAR(input_data[70], 10.5014, 1e-4);
EXPECT_NEAR(input_data[80], 12.0796, 1e-4);
EXPECT_NEAR(input_data[90], 11.1132, 1e-4);
}
return modelbox::STATUS_OK;
};
auto mock_functions = std::make_shared<MockFunctionCollection>();
mock_functions->RegisterDataPostFunc(post_func);
mock_functions->RegisterProcessFunc(process_func);
driver_flow_->AddFlowUnitDesc(mock_desc, mock_functions->GenerateCreateFunc(),
TEST_DRIVER_DIR);
};
void TorchInferenceFlowUnitTest::Register_Test_2_0_Flowunit() {
auto mock_desc = GenerateFlowunitDesc("test_2_0", {"In_1", "In_2"}, {});
mock_desc->SetFlowType(STREAM);
auto post_func = [=](std::shared_ptr<DataContext> data_ctx,
std::shared_ptr<MockFlowUnit> mock_flowunit) {
MBLOG_INFO << "test_2_0 "
<< "DataPost";
return modelbox::STATUS_STOP;
};
auto process_func = [=](std::shared_ptr<DataContext> op_ctx,
std::shared_ptr<MockFlowUnit> mock_flowunit) {
std::shared_ptr<BufferList> input_bufs = op_ctx->Input("In_1");
EXPECT_EQ(input_bufs->Size(), 1);
std::vector<size_t> shape_vector{10, 10};
std::vector<size_t> input_shape;
auto result = input_bufs->At(0)->Get("shape", input_shape);
EXPECT_TRUE(result);
EXPECT_EQ(input_shape, shape_vector);
auto input_bufs_2 = op_ctx->Input("In_2");
std::vector<size_t> input_shape_2;
result = input_bufs_2->At(0)->Get("shape", input_shape_2);
EXPECT_TRUE(result);
std::vector<size_t> shape_vector_2{20, 10};
EXPECT_EQ(input_shape_2, shape_vector_2);
EXPECT_EQ(static_cast<const float *>(input_bufs_2->ConstBufferData(0))[0],
1.0);
for (size_t i = 0; i < input_bufs->Size(); ++i) {
auto input_data =
static_cast<const float *>(input_bufs->ConstBufferData(i));
MBLOG_DEBUG << "index: " << i;
for (size_t j = 0; j < 100; j += 10) {
MBLOG_DEBUG << input_data[j];
}
EXPECT_NEAR(input_data[0], 10.2705, 1e-4);
EXPECT_NEAR(input_data[10], 9.03664, 1e-4);
EXPECT_NEAR(input_data[20], 9.106, 1e-4);
EXPECT_NEAR(input_data[30], 10.322, 1e-4);
EXPECT_NEAR(input_data[40], 10.6219, 1e-4);
EXPECT_NEAR(input_data[50], 10.5359, 1e-4);
EXPECT_NEAR(input_data[60], 10.6534, 1e-4);
EXPECT_NEAR(input_data[70], 10.1457, 1e-4);
EXPECT_NEAR(input_data[80], 7.73253, 1e-4);
EXPECT_NEAR(input_data[90], 8.46899, 1e-4);
}
return modelbox::STATUS_OK;
};
auto mock_functions = std::make_shared<MockFunctionCollection>();
mock_functions->RegisterDataPostFunc(post_func);
mock_functions->RegisterProcessFunc(process_func);
driver_flow_->AddFlowUnitDesc(mock_desc, mock_functions->GenerateCreateFunc(),
TEST_DRIVER_DIR);
};
void TorchInferenceFlowUnitTest::AddMockFlowUnit() {
Register_Test_0_1_Flowunit();
Register_Test_1_0_Flowunit();
Register_Test_2_0_Flowunit();
}
std::shared_ptr<MockFlow> TorchInferenceFlowUnitTest::GetDriverFlow() {
return driver_flow_;
}
TEST_F(TorchInferenceFlowUnitTest, RunUnitSingleOutput) {
std::string toml_content = R"(
[log]
level = "DEBUG"
[driver]
skip-default=true
dir=[")" + test_lib_dir + "\",\"" +
test_data_dir + "/torch\"]\n " +
R"([graph]
graphconf = '''digraph demo {
test_0_1[type=flowunit, flowunit=test_0_1, device=cpu, deviceid=0, label="<Out_1>"]
inference[type=flowunit, flowunit=torch, device=cuda, deviceid=0, label="<input> | <output>", skip_first_dim=true]
test_1_0[type=flowunit, flowunit=test_1_0, device=cpu, deviceid=0, label="<In_1>"]
test_0_1:Out_1 -> inference:input
inference:output -> test_1_0:In_1
}'''
format = "graphviz"
)";
auto driver_flow = GetDriverFlow();
auto ret = driver_flow->BuildAndRun("RunUnit", toml_content);
EXPECT_EQ(ret, STATUS_STOP);
}
TEST_F(TorchInferenceFlowUnitTest, RunUnitSingleOutputEncrypt) {
std::string toml_content = R"(
[log]
level = "DEBUG"
[driver]
skip-default=true
dir=[")" + test_lib_dir + "\",\"" +
test_data_dir + "/torch\"]\n " +
R"([graph]
graphconf = '''digraph demo {
test_0_1[type=flowunit, flowunit=test_0_1, device=cpu, deviceid=0, label="<Out_1>"]
inference[type=flowunit, flowunit=torch_encrypt, device=cuda, deviceid=0, label="<input> | <output>", skip_first_dim=true]
test_1_0[type=flowunit, flowunit=test_1_0, device=cpu, deviceid=0, label="<In_1>"]
test_0_1:Out_1 -> inference:input
inference:output -> test_1_0:In_1
}'''
format = "graphviz"
)";
auto driver_flow = GetDriverFlow();
auto ret = driver_flow->BuildAndRun("RunUnit", toml_content);
EXPECT_EQ(ret, STATUS_STOP);
}
TEST_F(TorchInferenceFlowUnitTest, RunUnitMutiOutput) {
std::string toml_content = R"(
[log]
level = "DEBUG"
[driver]
skip-default=true
dir=[")" + test_lib_dir + "\",\"" +
test_data_dir + "/torch\"]\n " +
R"([graph]
graphconf = '''digraph demo {
test_0_1[type=flowunit, flowunit=test_0_1, device=cpu, deviceid=0, label="<Out_1>"]
inference[type=flowunit, flowunit=torch_2, device=cuda, deviceid=0, label="<input> | <output>", skip_first_dim=true]
test_2_0[type=flowunit, flowunit=test_2_0, device=cpu, deviceid=0, label="<In_1>"]
test_0_1:Out_1 -> inference:input
inference:output1 -> test_2_0:In_1
inference:output2 -> test_2_0:In_2
}'''
format = "graphviz"
)";
auto driver_flow = GetDriverFlow();
auto ret = driver_flow->BuildAndRun("RunUnit", toml_content);
EXPECT_EQ(ret, STATUS_STOP);
}
} // namespace modelbox | 37.262376 | 132 | 0.639764 | [
"shape",
"vector"
] |
dd0b3c6ec22dfb3b3de5b243740188dd6bcecb0b | 679 | hpp | C++ | 16.hpp | fun4algs/lc | fd5bb9ee560d1f465abee249b029e7b825de06ab | [
"MIT"
] | 4 | 2020-06-12T14:10:22.000Z | 2020-06-17T09:18:59.000Z | 16.hpp | fun4algs/lc | fd5bb9ee560d1f465abee249b029e7b825de06ab | [
"MIT"
] | null | null | null | 16.hpp | fun4algs/lc | fd5bb9ee560d1f465abee249b029e7b825de06ab | [
"MIT"
] | null | null | null | class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int n = nums.size(), res = nums[0] + nums[1] + nums[2];
for(int k = 0;k < n - 2; ++k){
if(k > 0 && nums[k-1] == nums[k]) continue;
int i = k + 1, j = n - 1;
while(i < j){
int sum = nums[k] + nums[i] + nums[j];
if(sum == target) return sum;
if(abs(sum - target) < abs(res - target)){
res = sum;
}
if(sum > target) --j;
else ++i;
}
}
return res;
}
};
| 29.521739 | 63 | 0.381443 | [
"vector"
] |
dd0f45ee8989c8253bb52bcdf33295f1f5a9ff2b | 5,397 | cpp | C++ | Scene/MyScene.cpp | tinyHui/G53GRA | de9866313b78a4e68102507d3dea50a1dcb7e246 | [
"Apache-2.0"
] | null | null | null | Scene/MyScene.cpp | tinyHui/G53GRA | de9866313b78a4e68102507d3dea50a1dcb7e246 | [
"Apache-2.0"
] | null | null | null | Scene/MyScene.cpp | tinyHui/G53GRA | de9866313b78a4e68102507d3dea50a1dcb7e246 | [
"Apache-2.0"
] | null | null | null |
/*
Use this as the starting point to your work.
For each object in your scene, #include its header file then add it to the scene with AddObjectToScene()
*/
#include "Environment.h"
#include "MyScene.h"
#include "Chair.h"
#include "CouchMain.h"
#include "CouchSide.h"
#include "Carpet.h"
#include "Table.h"
#include "Room.h"
#include "Clock.h"
#include "Lamp.h"
#include "Dog.h"
#include "Sun.h"
#include "LampLight.h"
using namespace datastruct;
#define WGL_SAMPLE_BUFFERS_ARB 0x2041
#define WGL_SAMPLES_ARB 0x2042
bool arbMultisampleSupported = false;
int arbMultisampleFormat = 0;
// Constructor creates your Scene and initialises the base class Scene
MyScene::MyScene( int argc, char **argv, const char *title, const int windowWidth, const int windowHeight ) : Scene(argc, argv, title, windowWidth, windowHeight)
{
}
// Initialise your scene by adding all the objects you want to be in the scene here
void MyScene::Init()
{
// set background colour
glClearDepth(1);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
// living room
CuboidConfig* room_config = new CuboidConfig();
room_config->width = room::WIDTH;
room_config->depth = room::DEPTH;
room_config->height = room::HEIGHT;
Position* room_pos = new Position();
Room* living_room = new Room(room_config, room_pos);
AddObjectToScene(living_room);
// livingroom
Position* carpet_pos = new Position();
carpet_pos->x = carpet::X;
carpet_pos->z = carpet::Z;
Carpet* carpet = new Carpet(carpet_pos);
AddObjectToScene(carpet);
Position* couch_main_pos = new Position();
couch_main_pos->x = carpet_pos->x;
couch_main_pos->z = carpet_pos->z - carpet::DEPTH / 2 - carpet::CARPET_SOFA_GAP;
CouchMain* couch_main = new CouchMain(couch_main_pos);
AddObjectToScene(couch_main);
Position* r_couch_side_pos = new Position();
r_couch_side_pos->x = carpet_pos->x + carpet::WIDTH / 2 + carpet::CARPET_SOFA_GAP;
r_couch_side_pos->z = carpet_pos->z;
r_couch_side_pos->y_angle = -90;
CouchSide* r_couch_side = new CouchSide(r_couch_side_pos);
AddObjectToScene(r_couch_side);
Position* l_couch_side_pos = new Position();
l_couch_side_pos->x = carpet_pos->x - carpet::WIDTH / 2 - carpet::CARPET_SOFA_GAP;
l_couch_side_pos->z = carpet_pos->z;
l_couch_side_pos->y_angle = 90;
CouchSide* l_couch_side = new CouchSide(l_couch_side_pos);
AddObjectToScene(l_couch_side);
Position* lamp_pos = new Position();
lamp_pos->x = carpet_pos->x - carpet::WIDTH / 2 - carpet::CARPET_LAMP_GAP;
lamp_pos->z = carpet_pos->z - carpet::DEPTH / 2 - carpet::CARPET_LAMP_GAP;
lamp_pos->y_angle = 45;
Lamp* lamp = new Lamp(lamp_pos);
AddObjectToScene(lamp);
// dining_hall
Position* table_pos = new Position();
table_pos->x = - room::WIDTH / 2 + room::DHALL_WIDTH / 2;
table_pos->y = room::DHALL_HEIGHT;
table_pos->z = room::DEPTH / 2 - room::DHALL_DEPTH / 2;
table_pos->y_angle = 20;
Table* table = new Table(table_pos);
AddObjectToScene(table);
Position* chair1_pos = new Position();
chair1_pos->x = table_pos->x + chair::R;
chair1_pos->y = table_pos->y;
chair1_pos->z = table_pos->z + chair::R;
chair1_pos->y_angle = -115;
Chair* chair1 = new Chair(chair1_pos);
AddObjectToScene(chair1);
Position* chair2_pos = new Position();
chair2_pos->x = table_pos->x + chair::R;
chair2_pos->y = table_pos->y;
chair2_pos->z = table_pos->z - chair::R;
chair2_pos->y_angle = -45;
Chair* chair2 = new Chair(chair2_pos);
AddObjectToScene(chair2);
Position* chair3_pos = new Position();
chair3_pos->x = table_pos->x - chair::R;
chair3_pos->y = table_pos->y;
chair3_pos->z = table_pos->z - chair::R;
chair3_pos->y_angle = 45;
Chair* chair3 = new Chair(chair3_pos);
AddObjectToScene(chair3);
Position* chair4_pos = new Position();
chair4_pos->x = table_pos->x - chair::R;
chair4_pos->y = table_pos->y;
chair4_pos->z = table_pos->z + chair::R;
chair4_pos->y_angle = 115;
Chair* chair4 = new Chair(chair4_pos);
AddObjectToScene(chair4);
Position* clock_pos = new Position();
clock_pos->x = 0 + room::WIDTH / 2 - time_clock::BASE_THICK - 1;
clock_pos->y = room::DHALL_HEIGHT + 48;
clock_pos->z = 0 + room::DEPTH / 2 - 30;
clock_pos->x_angle = 5;
clock_pos->y_angle = -90;
Clock* clock = new Clock(clock_pos);
AddObjectToScene(clock);
Position* dog_pos = new Position();
dog_pos->x = dog::X;
dog_pos->y = dog::Y;
dog_pos->z = dog::Z;
Dog* dog = new Dog(dog_pos);
AddObjectToScene(dog);
Position* lamplight_pos = new Position();
lamplight_pos->x = lamp_pos->x;
lamplight_pos->y = lamp_pos->y + lamp::BOTTOM_THICK + lamp::LEG_HEIGHT + lamp::LIGHT_THICK / 2;
lamplight_pos->z = lamp_pos->z;
LampLight* lamplight = new LampLight(lamplight_pos);
AddObjectToScene(lamplight);
Sun* sun = new Sun();
AddObjectToScene(sun);
} | 34.596154 | 162 | 0.656846 | [
"object"
] |
dd137ed530325ef49e4ed0b35ee904fdcbed1b4f | 2,875 | cpp | C++ | Pinball NEW/ModuleFonts.cpp | PowerHunters/Physics4Pinball | 84b309a9430f139dcd564ba8e3e991dfafabdceb | [
"MIT"
] | null | null | null | Pinball NEW/ModuleFonts.cpp | PowerHunters/Physics4Pinball | 84b309a9430f139dcd564ba8e3e991dfafabdceb | [
"MIT"
] | null | null | null | Pinball NEW/ModuleFonts.cpp | PowerHunters/Physics4Pinball | 84b309a9430f139dcd564ba8e3e991dfafabdceb | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModuleFonts.h"
#include <string>
// Constructor
ModuleFonts::ModuleFonts(Application* app, bool start_enabled) : Module(app, start_enabled)
{}
// Destructor
ModuleFonts::~ModuleFonts()
{}
// Load new texture from file path
int ModuleFonts::Load(const char* texture_path, const char* characters, uint rows)
{
int id = -1;
if (texture_path == nullptr || characters == nullptr || rows == 0)
{
LOG("Could not load font");
return id;
}
SDL_Texture* tex = App->textures->Load(texture_path);
if (tex == nullptr || strlen(characters) >= MAX_FONT_CHARS)
{
LOG("Could not load font at %s with characters '%s'", texture_path, characters);
return id;
}
id = 0;
for (; id < MAX_FONTS; ++id)
if (fonts[id].graphic == nullptr)
break;
if (id == MAX_FONTS)
{
LOG("Cannot load font %s. Array is full (max %d).", texture_path, MAX_FONTS);
return id;
}
uint font1W;
uint font1H;
fonts[id].graphic = tex; // graphic: pointer to the texture
fonts[id].rows = rows; // rows: rows of characters in the texture
fonts[id].len = strlen(characters); // len: length of the table
App->textures->GetSize(tex, font1W, font1H);
fonts[id].row_chars = SDL_strlen(characters);
fonts[id].char_w = 15;
fonts[id].char_h = 18;
strcpy_s(fonts[id].table, characters);
LOG("Successfully loaded BMP font from %s", texture_path);
return id;
}
//for (int j = 0; j < rows; j++)
//{
// for (int i = 0; i < fonts[1].row_chars; i++)
// {
// fonts[1].table[i] = characters + sizeof(characters)*i;
// }
//}
void ModuleFonts::UnLoad(int font_id)
{
if (font_id >= 0 && font_id < MAX_FONTS && fonts[font_id].graphic != nullptr)
{
App->textures->Unload(fonts[font_id].graphic);
fonts[font_id].graphic = nullptr;
LOG("Successfully Unloaded BMP font_id %d", font_id);
}
}
void ModuleFonts::BlitText(int x, int y, int font_id, const char* text) const
{
if (text == nullptr || font_id < 0 || font_id >= MAX_FONTS || fonts[font_id].graphic == nullptr)
{
LOG("Unable to render text with bmp font id %d", font_id);
return;
}
const Font* font = &fonts[font_id];
SDL_Rect rect;
uint len = strlen(text);
rect.w = font->char_w;
rect.h = font->char_h;
for (uint i = 0; i < len; ++i)
{
for (uint j = 0; j < font->len; ++j)
{
if (font->table[j] == text[i])
{
//We blit the letter
rect.x = j * font->char_w;
rect.y = 0;
App->renderer->Blit(font->graphic, x, y, &rect);
//And we go to the next one
break;
}
}
x += font->char_w;
}
}
uint ModuleFonts::Get_CharWidth(int fontId) const
{
if (fontId < 0 || fontId > MAX_FONTS)
{
LOG("Accessing invalid font! SDL_Error: %s\n", SDL_GetError());//This is not a SDL error, but hopefully it will crash if we access an invalid font
}
return fonts[fontId].char_w;
} | 23.373984 | 148 | 0.651478 | [
"render"
] |
dd143a5410b054e7b6388d918d58b9155cb7c601 | 3,682 | inl | C++ | Kalix.Core/Libraries/x64/include/dseed/math/vectors/simd.constructors.inl | daramkun/Kalix | b73123428909620b29936d4637a93baf6e33e69a | [
"Zlib",
"Apache-2.0"
] | null | null | null | Kalix.Core/Libraries/x64/include/dseed/math/vectors/simd.constructors.inl | daramkun/Kalix | b73123428909620b29936d4637a93baf6e33e69a | [
"Zlib",
"Apache-2.0"
] | null | null | null | Kalix.Core/Libraries/x64/include/dseed/math/vectors/simd.constructors.inl | daramkun/Kalix | b73123428909620b29936d4637a93baf6e33e69a | [
"Zlib",
"Apache-2.0"
] | null | null | null | #pragma warning (disable: 26495)
///////////////////////////////////////////////////////////////////////////////////////////
//
// 4D Vector Constructors
//
///////////////////////////////////////////////////////////////////////////////////////////
namespace dseed
{
inline f32x4_t::f32x4_t() noexcept { }
inline f32x4_t::f32x4_t(float v) noexcept
#if DONT_USE_SIMD
: _x(v), _y(v), _z(v), _w(v)
#elif !DONT_USE_SSE
: _intrinsic(_mm_set1_ps(v))
#elif !DONT_USE_NEON
: _intrinsic(vmovq_n_f32(v))
#endif
{ }
inline f32x4_t::f32x4_t(float x, float y, float z, float w) noexcept
#if DONT_USE_SIMD
: _x(x), _y(y), _z(z), _w(w)
#elif !DONT_USE_SSE
: _intrinsic(_mm_set_ps(w, z, y, x))
#endif
{
#if !DONT_USE_NEON
float temp[] = { x, y, z, w };
_intrinsic = vld1q_f32(temp);
#endif
}
inline f32x4_t::f32x4_t(const float arr[4]) noexcept
{
#if !DONT_USE_SSE
_intrinsic = _mm_load_ps(arr);
#elif !DONT_USE_NEON
_intrinsic = vld1q_f32(arr);
#elif DONT_USE_SIMD
_x = arr[0]; _y = arr[1]; _z = arr[2]; _w = arr[3];
#endif
}
inline f32x4_t::f32x4_t(const f32x4_t* v) noexcept
#if DONT_USE_SIMD
: _x(v->_x), _y(v->_y), _z(v->_z), _w(v->_w)
#elif !DONT_USE_SSE || !DONT_USE_NEON
: _intrinsic(v->_intrinsic)
#endif
{ }
inline f32x4_t::f32x4_t(const f32x4_t& v) noexcept
#if DONT_USE_SIMD
: _x(v._x), _y(v._y), _z(v._z), _w(v._w)
#elif !DONT_USE_SSE || !DONT_USE_NEON
: _intrinsic(v._intrinsic)
#endif
{ }
#if !DONT_USE_SSE
inline f32x4_t::f32x4_t(__m128 v) noexcept : _intrinsic(v) { }
#elif !DONT_USE_NEON
f32x4_t(float32x4_t v) : _intrinsoc(v) noexcept { }
#endif
inline f32x4_t f32x4_t::load(const float arr[4]) noexcept
{
return f32x4_t(arr);
}
inline void f32x4_t::store(float arr[4], const f32x4_t* v) noexcept
{
#if !DONT_USE_SSE
_mm_store_ps(arr, v->_intrinsic);
#elif !DONT_USE_NEON
vst1q_f32(arr, v->_intrinsic);
#elif DONT_USE_SIMD
memcpy(arr, v, sizeof(vector4f));
#endif
}
inline i32x4_t::i32x4_t() noexcept { }
inline i32x4_t::i32x4_t(int v) noexcept
#if DONT_USE_SIMD
: _x(v), _y(v), _z(v), _w(v)
#elif !DONT_USE_SSE
: _intrinsic(_mm_set1_epi32(v))
#elif !DONT_USE_NEON
: _intrinsic(vmovq_n_i32(v))
#endif
{ }
inline i32x4_t::i32x4_t(int x, int y, int z, int w) noexcept
#if DONT_USE_SIMD
: _x(x), _y(y), _z(z), _w(w)
#elif !DONT_USE_SSE
: _intrinsic(_mm_set_epi32(w, z, y, x))
#endif
{
#if !DONT_USE_NEON
int arr[4] = { x, y, z, w };
_intrinsic = vld1q_f32(arr);
#endif
}
inline i32x4_t::i32x4_t(const int arr[4]) noexcept
{
#if !DONT_USE_SSE
_intrinsic = _mm_load_si128((const __m128i*)arr);
#elif !DONT_USE_NEON
_intrinsic = vld1q_i32(arr);
#elif DONT_USE_SIMD
_x = arr[0]; _y = arr[1]; _z = arr[2]; _w = arr[3];
#endif
}
inline i32x4_t::i32x4_t(const i32x4_t* v) noexcept
#if DONT_USE_SIMD
: _x(v->_x), _y(v->_y), _z(v->_z), _w(v->_w)
#elif !DONT_USE_SSE
: _intrinsic(v->_intrinsic)
#elif !DONT_USE_NEON
: _intrinsic(v->_intrinsic)
#endif
{ }
inline i32x4_t::i32x4_t(const i32x4_t& v) noexcept
#if DONT_USE_SIMD
: _x(v._x), _y(v._y), _z(v._z), _w(v._w)
#elif !DONT_USE_SSE
: _intrinsic(v._intrinsic)
#elif !DONT_USE_NEON
: _intrinsic(v._intrinsic)
#endif
{ }
#if !DONT_USE_SSE
inline i32x4_t::i32x4_t(__m128i v) noexcept { _intrinsic = v; }
#elif !DONT_USE_NEON
i32x4_t::i32x4_t(int32x4_t v) noexcept { _intrinsic = v; }
#endif
inline i32x4_t i32x4_t::load(const int arr[4]) noexcept
{
return i32x4_t(arr);
}
inline void i32x4_t::store(int arr[4], const i32x4_t* v) noexcept
{
#if !DONT_USE_SSE
_mm_store_si128((__m128i*)arr, v->_intrinsic);
#elif !DONT_USE_NEON
vst1q_i32(arr, v->_intrinsic);
#elif DONT_USE_SIMD
memcpy(arr, v, sizeof(i32x4_t));
#endif
}
} | 24.878378 | 91 | 0.652363 | [
"vector"
] |
dd169808ebf155896b39edc89670a6905f16e929 | 5,107 | cpp | C++ | src/imageproc/main.cpp | panjabi/automcq | e7e7f4d161d41f98d5f54ba46c9981a667c80109 | [
"MIT"
] | null | null | null | src/imageproc/main.cpp | panjabi/automcq | e7e7f4d161d41f98d5f54ba46c9981a667c80109 | [
"MIT"
] | null | null | null | src/imageproc/main.cpp | panjabi/automcq | e7e7f4d161d41f98d5f54ba46c9981a667c80109 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <math.h>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
// Returns aligned image
Mat alignImage( Mat image ) {
Mat org = imread( "template-blank.jpg", CV_LOAD_IMAGE_GRAYSCALE );
if(!org.data) std::cout << "unable to read template image";
// Detect the keypoints using SURF Detector
int minHessian = 400;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypointsOrg, keypointsImage;
detector.detect( org, keypointsOrg );
detector.detect( image, keypointsImage );
// Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;
Mat descriptorsOrg, descriptorsImage;
extractor.compute( org, keypointsOrg, descriptorsOrg );
extractor.compute( image, keypointsImage, descriptorsImage );
// Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptorsOrg, descriptorsImage, matches );
double max_dist = 0;
double min_dist = 100;
// Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptorsOrg.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
// Use "good" matches (i.e. whose distance is less than ((399*min_dist)+max_dist)/400 )
std::vector< DMatch > good_matches;
for( int i = 0; i < descriptorsOrg.rows; i++ )
{ if( matches[i].distance < ((399*min_dist)+max_dist)/400 )
{ good_matches.push_back( matches[i]); }
}
// Localize the object
std::vector<Point2f> kptsOrg;
std::vector<Point2f> kptsImage;
for( int i = 0; i < good_matches.size(); i++ )
{
// Get the keypoints from the good matches
kptsOrg.push_back( keypointsOrg[ good_matches[i].queryIdx ].pt );
kptsImage.push_back( keypointsImage[ good_matches[i].trainIdx ].pt );
}
Mat H = findHomography( kptsImage, kptsOrg, CV_RANSAC );
warpPerspective( image, org, H, org.size() );
// imshow( "img_object", org);
// waitKey(0);
return org;
}
// Define the positions of options/ rollnumber
Mat definePtns ( int numQues, int numOpts, int numQuesRow, int centerX, int centerY, int distRow, int distCol, int distOpts ) {
Mat optsPtns( numQues, numOpts, CV_16UC2 );
unsigned int colNum = 0;
unsigned int rowNum = 0;
for (int i = 0; i < numQues; ++i)
{
for (int j = 0; j < numOpts; ++j)
{
colNum = i/numQuesRow;
rowNum = i%numQuesRow;
optsPtns.at<Vec2s>(i,j)[0] = centerX + (distCol*colNum) + (distOpts*j);
optsPtns.at<Vec2s>(i,j)[1] = centerY + (distRow*rowNum);
}
}
return optsPtns;
}
// If a given option is marked
short isOptMarked( Vec2s optCenter, Mat& image, int radius ) {
float X = 0.0;
float Y = 0.0;
float effRadius = radius - 0.5;
unsigned int counter = 0;
unsigned int sum = 0;
unsigned int threshold = 80;
short isMarked = 0;
for (int j = optCenter[1]-radius+1; j <= optCenter[1]+radius ; ++j)
{
for (int i = optCenter[0]-radius+1; i <= optCenter[0]+radius; ++i)
{
X = i - (optCenter[0] + 0.5);
Y = j - (optCenter[1] + 0.5);
if ((X*X) + (Y*Y) <= (effRadius*effRadius))
{
counter = counter + 1;
sum = sum + image.at<uchar>(j,i);
}
}
}
if (sum/counter < threshold)
{
isMarked = 1;
}
return isMarked;
}
// Reads the marked answer options
Mat readOpts( Mat& image ) {
// define constants
int numQues = 60;
int numQuesRow = 21;
int numOpts = 5;
int distRow = 42;
int distCol = 182;
int distOpts = 28;
int centerX = 221;
int centerY = 176;
int radius = 10;
Mat opts( numQues, numOpts, CV_8SC1);
Mat optsPtns = definePtns( numQues, numOpts, numQuesRow, centerX, centerY, distRow, distCol, distOpts );
for (int i = 0; i < optsPtns.rows; ++i)
{
for (int j = 0; j < optsPtns.cols; ++j)
{
Vec2s optCenter = optsPtns.at<Vec2s>(i,j);
opts.at<short>(i,j) = isOptMarked(optCenter, image, radius);
}
}
return opts;
}
// Read the roll number bubbles
int readRoll( Mat& image ) {
// define constants
int numDgts = 10;
int numUnts = 5;
int distUnts = 31;
int distRow = 28;
int centerX = 19;
int centerY = 204;
int radius = 11;
int rollNo = 0;
Mat rollPtns = definePtns( numDgts, numUnts, numDgts, centerX, centerY, distRow, 0, distUnts );
for (int j = 0; j < rollPtns.cols; ++j)
{
for (int i = 0; i < rollPtns.rows; ++i)
{
Vec2s optCenter = rollPtns.at<Vec2s>(i,j);
if( isOptMarked(optCenter, image, radius) == 1 )
{
rollNo += i * pow( 10, rollPtns.cols-1-j );
continue;
}
}
}
return rollNo;
}
// Main function
int main(int argc, char** argv) {
Mat image = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
if(!image.data) std::cout << "unable to read argument image";
Mat imageAligned = alignImage( image );
Mat markedOpts = readOpts( imageAligned );
int rollNo = readRoll( imageAligned );
std::cout << rollNo << "\n";
}
| 24.791262 | 127 | 0.63834 | [
"object",
"vector"
] |
dd1b5cdc1663e7bf5eb6cfbc41439e48bf941eaf | 2,707 | cpp | C++ | HydroUQ/projectsettings.cpp | pmackenz/HydroUQ | 31e7c7525fb3548d40c951b96a999f7b927dd581 | [
"BSD-2-Clause"
] | null | null | null | HydroUQ/projectsettings.cpp | pmackenz/HydroUQ | 31e7c7525fb3548d40c951b96a999f7b927dd581 | [
"BSD-2-Clause"
] | null | null | null | HydroUQ/projectsettings.cpp | pmackenz/HydroUQ | 31e7c7525fb3548d40c951b96a999f7b927dd581 | [
"BSD-2-Clause"
] | null | null | null | #include "projectsettings.h"
#include "ui_projectsettings.h"
#include <QDebug>
//*********************************************************************************
// Project settings
//*********************************************************************************
projectsettings::projectsettings(int type, QWidget *parent) :
QFrame(parent),
ui(new Ui::projectsettings)
{
ui->setupUi(this);
// Initialize to show / hide elements
hideshowelems(type);
}
//*********************************************************************************
// Delete project settings
//*********************************************************************************
projectsettings::~projectsettings()
{
delete ui;
}
//*********************************************************************************
// Refresh data
//*********************************************************************************
void projectsettings::refreshData(int type)
{
// Initialize to show / hide elements
hideshowelems(type);
}
//*********************************************************************************
// Show - hide elements
//*********************************************************************************
void projectsettings::hideshowelems(int type)
{
(void) type;
}
//*********************************************************************************
// Get data from project settings
//*********************************************************************************
bool projectsettings::getData(QMap<QString, QString> & map, int type)
{
bool hasData=false;
(void) type;
map.insert("Work directory",ui->Lbl_WorkDir->text());
map.insert("Project name",ui->Led_PName->text());
map.insert("Project description",ui->Ted_PDesc->toPlainText());
map.insert("Simulation type",QString::number(ui->CmB_SimType->currentIndex()));
map.insert("Turbulence model",QString::number(ui->CmB_TurbModel->currentIndex()));
hasData = true;
return hasData;
}
//*********************************************************************************
// Setting project directory
//*********************************************************************************
void projectsettings::on_Btn_WDir_clicked()
{
workdirUrl = QFileDialog::getExistingDirectoryUrl(this, tr("Open Directory"), QUrl("/home/Users"),QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
QString workdir = workdirUrl.toString();
// If the workdir is not empty or not, set the text accordingly
if(workdir.isEmpty())
{
ui->Lbl_WorkDir->setText("\nSet working directory\n");
}
else
{
ui->Lbl_WorkDir->setText(workdirUrl.toLocalFile());
}
}
| 33.8375 | 164 | 0.436646 | [
"model"
] |
dd2d9f759fe1b466b88829c5a6d4fce2c93891c4 | 2,706 | cc | C++ | mpi-examples/mandelbrot.cc | highperformancecoder/classdesc | 15ff06aded75498ef85cf63da4870022aef37ad2 | [
"MIT"
] | 1 | 2021-01-31T22:53:35.000Z | 2021-01-31T22:53:35.000Z | mpi-examples/mandelbrot.cc | highperformancecoder/classdesc | 15ff06aded75498ef85cf63da4870022aef37ad2 | [
"MIT"
] | 9 | 2017-11-26T23:08:07.000Z | 2018-07-04T00:59:26.000Z | mpi-examples/mandelbrot.cc | highperformancecoder/classdesc | 15ff06aded75498ef85cf63da4870022aef37ad2 | [
"MIT"
] | 3 | 2017-07-23T19:29:05.000Z | 2018-04-19T12:02:25.000Z | /*
@copyright Russell Standish 2000-2013
@author Russell Standish
This file is part of Classdesc
Open source licensed under the MIT license. See LICENSE for details.
*/
#include <mpi.h>
#include <complex>
#include <vector>
#include "pack_stl.h"
#include "classdescMP.h"
#include "classdesc_epilogue.h"
#include <iostream>
using namespace std;
using namespace classdesc;
const int chunk=64;
const int nx=256;
const int ny=chunk*4; /* ensure ny is a multiple of chunk */
const int maxiter=1000;
struct S
{
void get_counts(MPIbuf& args)
{
int ix,i,j,k, minj;
args >> ix;
vector<int> ret_count(chunk);
complex<double> z, kappa;
i=ix/ny; minj=ix%ny;
for (j=minj; j<minj+chunk; j++)
{
z=kappa=complex<double>((4.0*(i-nx/2))/nx, (4.0*(j-ny/2)/ny));
for (k=0; ; k++)
{
if (abs(z)>2 || k==maxiter)
{
ret_count[j-minj]=(k*256)/maxiter;
break;
}
z=z*z+kappa;
}
}
args.reset() << ix << ret_count;
}
};
extern "C" {
void raster(int *,int,int);
void raster_pause();
}
int main(int argc, char *argv[])
{
try {
int T[nx*ny];
int p, rij;
vector<int> ret_count(chunk);
MPISPMD parallelEnvironment(argc,argv);
MPIslave<S> slave;
{ /* parallel code here */
if (slave.nprocs()<2)
{
cerr << "need at least 2 processors for master-slave" << endl;
abort();
}
// this chunk of code does nothing other than exercise the bcast method
slave.bcast(slave << &S::get_counts << 0);
/* hand out work */
for (int ij=0; ij<nx*ny; ij+=chunk)
{
if (!slave.idle.size())
{
slave.get_returnv()>> rij >> ret_count;
for(size_t i=0; i<ret_count.size(); i++) T[rij+i]=ret_count[i];
}
slave.exec(slave << &S::get_counts << ij);
}
/* process final computations */
while (!slave.all_idle())
{
slave.get_returnv()>> rij >> ret_count;
for(size_t i=0; i<ret_count.size(); i++) T[rij+i]=ret_count[i];
}
} /* end of parallel processing region */
#if 1
#ifndef AEGIS_TEST
/* raster code for visualising results */
raster(T,nx,ny);
raster_pause();
#endif
#endif
#ifdef AEGIS_TEST
/* this section is used as an AEGIS test */
int T1[nx*ny], ij;
S s;
for (ij=0; ij<nx*ny; ij+=chunk)
{
MPIbuf b; b<<ij;
s.get_counts(b);
b >> rij >> ret_count;
for(size_t i=0; i<ret_count.size(); i++) T1[rij+i]=ret_count[i];
}
int same=1;
for (ij=0; same && ij<nx*ny; ij++) same &= T[ij]==T1[ij];
if (!same)
{
cerr << "parallel and serial version differ at ij=" << ij << endl;
abort();
}
#endif
}
catch (const runtime_error& x) {cerr <<x.what()<<endl; abort();}
return 0;
}
| 20.815385 | 75 | 0.59017 | [
"vector"
] |
dd3808219712d20ee95fc0b35f3077216ef517fa | 354 | cc | C++ | test/test-tools.cc | noryb009/lick | 77716e9ed4304bdab8725974e40e74f2f1616a9d | [
"MIT"
] | 50 | 2015-05-02T13:00:25.000Z | 2022-02-22T15:16:25.000Z | test/test-tools.cc | noryb009/lick | 77716e9ed4304bdab8725974e40e74f2f1616a9d | [
"MIT"
] | 55 | 2016-08-30T05:17:14.000Z | 2022-03-27T01:01:02.000Z | test/test-tools.cc | noryb009/lick | 77716e9ed4304bdab8725974e40e74f2f1616a9d | [
"MIT"
] | 12 | 2016-11-13T07:20:58.000Z | 2021-12-09T07:33:47.000Z | #include "test-tools.h"
lickdir_t *test_lick(const char *dir) {
return new_lickdir(dir[0],
concat_strs(2, dir, "/entries"),
concat_strs(2, dir, "/res"));
}
node_t *vector_to_list(const std::vector<void*> &v) {
node_t *lst = nullptr;
for (auto it = v.rbegin(); it != v.rend(); ++it) {
lst = new_node(*it, lst);
}
return lst;
}
| 22.125 | 53 | 0.601695 | [
"vector"
] |
dd3b38b74ea44ab71eda17cafffe43f0972fb401 | 3,330 | cpp | C++ | ch04/e4-07.cpp | nanonashy/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 3 | 2021-12-17T17:25:18.000Z | 2022-03-02T15:52:23.000Z | ch04/e4-07.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T07:16:34.000Z | 2020-04-22T10:04:04.000Z | ch04/e4-07.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T08:13:51.000Z | 2020-04-22T08:13:51.000Z | // 問題文:
// 練習問題5の電卓プログラムを書き換え、数字又は単語として書かれた1桁の数字(のみ)を
// 受け取るように変更する。
//
// コメント:
// ・少しでもコンソールlikeにするために、quit
// と入力しプログラムを終了するようにしました。 (generate_number関数から -2
// を受け取ると bool quit が true になりwhileループが終了します。)
// ・文字列と演算子をスペースを空けずに入力すると、文字列+演算子をstringとして読み込んで
// しまうので、使う際は演算子の前後にスペースを空ける必要があります。
// ・unsigned と signed の数値の比較による警告を回避するために、24行目は
// int(names.size())に、 34行目は unsigned int と記述してある。
#include "../include/std_lib_facilities.h"
const vector<std::string> names = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
int generate_number() {
std::string name;
int number{0};
int output{-1};
if (std::cin >> number) {
if (number < 0 || number >= int(names.size()))
std::cout << "入力された整数は有効ではありません。\n";
else
output = number;
} else {
std::cin.clear();
std::cin >> name;
if (name == "quit")
output = -2;
else {
for (unsigned int i = 0; i < names.size(); ++i) {
if (name == names[i])
output = i;
}
if (output == -1)
std::cout << "入力された " << name
<< " は有効な文字列ではありません。\n";
}
}
return output;
}
int main() {
bool quit = false;
double val1{0};
double val2{0};
char op{' '};
std::cout << "1桁電卓プログラムです。\n"
<< "一桁の整数(0~9)又はその英語名を演算子(+ - * "
"/)を挟んで入力してください。("
"演算子の前後にはスペースを入力してください)\n"
<< "quit で終了します...\n>> ";
while (!quit) {
val1 = generate_number();
if (val1 == -1) {
std::cin.clear();
val1 = 0;
std::cout << "もう一度やり直してください。\n>> ";
} else if (val1 == -2) {
std::cout << "プログラムを終了します...\n";
quit = true;
} else {
cin >> op;
val2 = generate_number();
if (val2 == -1) {
std::cin.clear();
val2 = 0;
std::cout << "もう一度やり直してください。\n>> ";
} else {
switch (op) {
case '+':
std::cout << "The sum of " << val1 << " and " << val2
<< " is " << val1 + val2 << '\n';
break;
case '-':
std::cout << "The difference of " << val1 << " and " << val2
<< " is " << val1 - val2 << '\n';
break;
case '*':
std::cout << "The product of " << val1 << " and " << val2
<< " is " << val1 * val2 << '\n';
break;
case '/':
if (val2 != 0)
std::cout << "The division of " << val1 << " and "
<< val2 << " is " << val1 / val2 << '\n';
else
std::cout << "ERROR: Division by zero\n";
break;
default:
break;
}
std::cout << ">> ";
}
}
}
return 0;
} | 31.714286 | 81 | 0.381081 | [
"vector"
] |
dd407a22b13d9bfa452d202352ad9feb0fda872d | 3,377 | cpp | C++ | dataserver/src/storage/stats_col.cpp | jimdb-org/jimdb | 927e4447879189597dbe7f91a7fe0e8865107ef4 | [
"Apache-2.0"
] | 59 | 2020-01-10T06:27:12.000Z | 2021-12-16T06:37:36.000Z | dataserver/src/storage/stats_col.cpp | jimdb-org/jimdb | 927e4447879189597dbe7f91a7fe0e8865107ef4 | [
"Apache-2.0"
] | null | null | null | dataserver/src/storage/stats_col.cpp | jimdb-org/jimdb | 927e4447879189597dbe7f91a7fe0e8865107ef4 | [
"Apache-2.0"
] | 3 | 2020-02-13T05:04:20.000Z | 2020-06-29T01:07:48.000Z | // Copyright 2019 The JIMDB 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 "stats_col.h"
#include "processor_table_read.h"
#include "processor_order_by.h"
#include "histogram.h"
namespace jim {
namespace ds {
namespace storage {
StatsCol::StatsCol(const dspb::ColumnsStatsRequest& req, Store& s){
keySchema_.CopyFrom(s.GetKeySchema());
colLen_ = req.columns_info_size();
for (auto& schemaCol : keySchema_.key_cols()) {
if (schemaCol.id() == req.columns_info(0).id()) {
pk_id_ = schemaCol.id();
--colLen_;
has_pk_ = true;
break;
}
}
bucketMax_ = req.bucket_max();
fmSketchMax_ = req.sketch_max();
sampleMax_ = req.sample_max();
cmSketchDepth_ = req.cmsketch_depth();
cmSketchWidth_ = req.cmsketch_width();
dspb::TableRead tableRead;
tableRead.set_type(dspb::KEYS_RANGE_TYPE);
dspb::Ordering ordering;
ordering.set_count(10000);
for (auto& cl : req.columns_info()) {
tableRead.add_columns()->CopyFrom(cl);
auto clOrdering = ordering.add_columns();
clOrdering->mutable_expr()->set_expr_type(dspb::Column);
clOrdering->mutable_expr()->mutable_column()->set_id(cl.id());
clOrdering->set_asc(true);
if (cl.id() != pk_id_) {
cols_.push_back(cl.id());
}
}
tableRead.mutable_range()->CopyFrom(req.range());
std::unique_ptr<Processor> processor = std::unique_ptr<Processor>(new TableRead( tableRead, req.range(), s , false));
processor = std::unique_ptr<Processor>(new OrderBy( ordering, std::move(processor), false));
processor_ = std::move(processor);
}
Status StatsCol::StatsColResp(dspb::ColumnsStatsResponse& resp){
Histogram pk_hist(bucketMax_);
SampleCollector sample(sampleMax_, fmSketchMax_, cmSketchDepth_, cmSketchWidth_);
std::vector<SampleCollector> collects(colLen_, sample);
Status s;
do {
RowResult row;
s = processor_->next(row);
if (!s.ok()) break;
auto mapFields = row.GetMapFields();
if (has_pk_) {
auto pkPair = mapFields.find(pk_id_);
if (pkPair != mapFields.end() && pkPair->second != nullptr) {
pk_hist.Append(pkPair->second->ToString());
}
}
for (uint32_t n = 0; n < cols_.size(); ++n) {
auto field = mapFields.find(cols_[n]);
if (field != mapFields.end()) {
collects[n].Collect(field->second->ToString().c_str());
} else {
collects[n].Collect(nullptr);
}
}
} while(s.ok());
pk_hist.ToProto(*(resp.mutable_pk_hist()));
for(auto& collect : collects) {
collect.ToProto(*(resp.add_collectors()));
}
return Status::OK();
}
}// end storage
}// end ds
}// end jim
| 34.459184 | 121 | 0.628368 | [
"vector"
] |
dd4c6d423d2795ebb0c1bc67f6058070ef84a1cf | 29,284 | cpp | C++ | benchmark_suite/src/io/gnuplot.cpp | captain-yoshi/moveit_benchmark_suite | cfd8c7da141bcd738440a418c94f6d79f44fbc8b | [
"BSD-3-Clause"
] | null | null | null | benchmark_suite/src/io/gnuplot.cpp | captain-yoshi/moveit_benchmark_suite | cfd8c7da141bcd738440a418c94f6d79f44fbc8b | [
"BSD-3-Clause"
] | 34 | 2021-09-05T21:48:42.000Z | 2022-03-31T21:29:47.000Z | benchmark_suite/src/io/gnuplot.cpp | captain-yoshi/moveit_benchmark_suite | cfd8c7da141bcd738440a418c94f6d79f44fbc8b | [
"BSD-3-Clause"
] | 2 | 2021-09-04T11:39:35.000Z | 2022-03-18T14:35:11.000Z | /* Author: Zachary Kingston */
#include <moveit_benchmark_suite/io.h>
#include <moveit_benchmark_suite/io/gnuplot.h>
#include <moveit_benchmark_suite/yaml.h>
#include <moveit_benchmark_suite/token.h>
#include <cmath>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream_buffer.hpp>
using namespace moveit_benchmark_suite::IO;
#if IS_BOOST_164
namespace bp = boost::process;
namespace bio = boost::iostreams;
#endif
///
/// GNUPlotTerminal
///
GNUPlotTerminal::GNUPlotTerminal(const std::string& mode) : mode(mode){};
///
/// QtTerminal
///
QtTerminal::QtTerminal() : GNUPlotTerminal(TERMINAL_QT_STR)
{
}
QtTerminal::QtTerminal(const TerminalSize& size) : GNUPlotTerminal(TERMINAL_QT_STR), size(size)
{
}
QtTerminal::~QtTerminal()
{
}
std::string QtTerminal::getCmd() const
{
return log::format("set term %1% noraise size %2%,%3%", mode, size.x, size.y);
}
///
/// SvgTerminal
///
SvgTerminal::SvgTerminal() : GNUPlotTerminal(TERMINAL_SVG_STR)
{
}
SvgTerminal::SvgTerminal(const TerminalSize& size) : GNUPlotTerminal(TERMINAL_SVG_STR), size(size)
{
}
SvgTerminal::~SvgTerminal()
{
}
std::string SvgTerminal::getCmd() const
{
return log::format("set term %1% size %2%,%3%", mode, size.x, size.y);
}
///
/// GNUPlotHelper
///
GNUPlotHelper::Instance::Instance()
{
#if IS_BOOST_164
auto path = bp::search_path("gnuplot");
if (path.empty())
throw std::runtime_error("GNUPlot not found, please install!");
gnuplot_ = bp::child(bp::search_path("gnuplot"), //"-persist", //
bp::std_err > *error_, //
bp::std_out > *output_, //
bp::std_in < input_, svc_);
th_ = std::thread([&] { svc_.run(); });
#else
throw std::runtime_error("GNUPlot helper not supported, Boost 1.64 and above is required!");
#endif
}
GNUPlotHelper::Instance::~Instance()
{
svc_.stop();
th_.detach();
}
void GNUPlotHelper::Instance::write(const std::string& line)
{
#if IS_BOOST_164
input_ << line;
if (debug_)
std::cout << line;
#endif
}
void GNUPlotHelper::Instance::writeline(const std::string& line)
{
write(line);
flush();
}
void GNUPlotHelper::Instance::flush()
{
#if IS_BOOST_164
input_ << std::endl;
if (debug_)
std::cout << std::endl;
#endif
}
std::shared_ptr<std::future<std::vector<char>>> GNUPlotHelper::Instance::getOutput()
{
return output_;
}
std::shared_ptr<std::future<std::vector<char>>> GNUPlotHelper::Instance::getError()
{
return error_;
}
std::set<std::string> GNUPlotHelper::getInstanceNames() const
{
std::set<std::string> instance_set;
for (const auto& instance : instances_)
instance_set.insert(instance.first);
return instance_set;
}
void GNUPlotHelper::getInstanceOutput(const std::string& instance, std::string& output)
{
auto in = getInstance(instance);
// Kill gnuplot process
in->writeline("exit");
auto future_out = in->getOutput();
auto raw = future_out->get();
std::vector<std::string> data;
std::string line;
bio::stream_buffer<bio::array_source> sb(raw.data(), raw.size());
std::istream is(&sb);
for (std::string line; std::getline(is, line);)
output.append(line + "\n");
}
void GNUPlotHelper::configureTerminal(const std::string& instance_id, const GNUPlotTerminal& terminal)
{
auto in = getInstance(instance_id);
in->writeline(terminal.getCmd());
}
void GNUPlotHelper::configurePlot(const PlottingOptions& options)
{
auto in = getInstance(options.instance);
in->writeline(log::format("set title \"%1%\"", replaceStr(options.title, "_", "\\\\_")));
if (not options.x.label.empty())
in->writeline(log::format("set xlabel \"%1%\"", replaceStr(options.x.label, "_", "\\\\_")));
if (std::isfinite(options.x.max))
in->writeline(log::format("set xrange [:%1%]", options.x.max));
if (std::isfinite(options.x.min))
in->writeline(log::format("set xrange [%1%:]", options.x.min));
if (not options.y.label.empty())
in->writeline(log::format("set ylabel \"%1%\"", replaceStr(options.y.label, "_", "\\\\_")));
if (std::isfinite(options.y.max))
in->writeline(log::format("set yrange [:%1%]", options.y.max));
if (std::isfinite(options.y.min))
in->writeline(log::format("set yrange [%1%:]", options.y.min));
}
void GNUPlotHelper::timeseries(const TimeSeriesOptions& options)
{
configurePlot(options);
auto in = getInstance(options.instance);
in->writeline("set datafile separator \",\"");
in->write("plot ");
auto n = options.points.size();
auto it1 = options.points.begin();
for (std::size_t i = 0; i < n; ++i, ++it1)
{
in->write(log::format("'%1%' using 1:2 with lines lw 2 title \"%2%\"", //
(i == 0) ? "-" : "", //
it1->first));
if (i != n - 1)
in->write(", ");
}
in->flush();
auto it2 = options.points.begin();
for (std::size_t i = 0; i < n; ++i, ++it2)
{
for (const auto& point : it2->second)
in->writeline(log::format("%1%,%2%", point.first, point.second));
in->writeline("e");
}
}
void GNUPlotHelper::boxplot(const BoxPlotOptions& options)
{
configurePlot(options);
auto in = getInstance(options.instance);
std::vector<std::string> xtick_titles;
std::vector<std::string> legend_titles;
double boxwidth = 0.5;
double boxwidth_gap = 0.15;
bool is_legend = (options.values.size() == 1 && options.values.begin()->first.empty()) ? false : true;
auto it1 = options.values.begin();
int n_legend = options.values.size();
int n_xtick = it1->second.size();
// data blocks
int ctr = 0;
for (std::size_t i = 0; i < n_legend; ++i, ++it1)
{
legend_titles.push_back(replaceStr(it1->first, "_", "\\\\_"));
auto it2 = it1->second.begin();
for (std::size_t j = 0; j < n_xtick; ++j, ++it2)
{
in->writeline(log::format("$data%1% <<EOD", ctr + 1));
if (it2 != it1->second.end())
{
for (const auto& val : it2->second)
{
in->writeline(log::format("%1%", val));
}
}
in->writeline("EOD");
ctr++;
}
}
in->writeline("set datafile separator \",\"");
// in->writeline("set border 10 front lt black linewidth 1.000 dashtype solid");
in->writeline("set border back");
in->writeline("set style data boxplot");
in->writeline("set style fill solid 0.5 border -1");
if (options.sorted)
in->writeline("set style boxplot sorted");
if (options.outliers)
in->writeline("set style boxplot outliers pointtype 7");
else
in->writeline("set style boxplot nooutliers");
if (is_legend)
{
int legend_title_n = 0;
for (const auto& legend_title : legend_titles)
{
if (legend_title.size() > legend_title_n)
legend_title_n = legend_title.size();
}
in->writeline(log::format("set rmargin %1%", legend_title_n + 6)); // Disable legend
in->writeline("set key at screen 1, graph 1"); // Disable legend
}
else
in->writeline("unset key"); // Disable legend
// xticks
for (const auto& xtick : options.values.begin()->second)
xtick_titles.push_back(replaceStr(xtick.first, "_", "\\\\_"));
in->writeline("set bmargin 6");
in->write("set xtics (");
// auto it2 = options.xticks.begin();
double xtick_center_start = (double)n_legend * boxwidth / 2.0 + boxwidth_gap;
std::vector<double> x_offsets;
if (is_legend)
{
for (std::size_t i = 0; i < xtick_titles.size(); ++i)
{
double xtick_center = xtick_center_start + (double(i) * boxwidth_gap + double(i) * double(n_legend) / 2.0);
in->write(log::format("\"%1%\" %2%", xtick_titles[i], std::to_string(xtick_center)));
double xtick_start = xtick_center - double(n_legend) * boxwidth / 2.0 + boxwidth / 2.0;
x_offsets.push_back(xtick_start);
if (i != xtick_titles.size() - 1)
in->write(", ");
}
}
else
{
for (std::size_t i = 0; i < xtick_titles.size(); ++i)
{
in->write(log::format("\"%1%\" %2%", xtick_titles[i], i + 1));
if (i != xtick_titles.size() - 1)
in->write(", ");
}
}
in->writeline(") scale 0.0 center");
// Set Data block in order
std::vector<int> index;
if (is_legend)
{
int idx = 0;
for (int i = 0; i < n_xtick; ++i)
{
idx = i;
for (int j = 0; j < n_legend; ++j)
{
index.push_back(idx + 1);
idx += n_xtick;
}
}
}
// plot
ctr = 0;
in->write("plot ");
for (std::size_t i = 0; i < n_xtick; ++i)
{
for (std::size_t j = 0; j < n_legend; ++j)
{
if (is_legend)
in->writeline(log::format("'$data%1%' using (%2%):1 title \"%3%\" lt %4%%5%", index[ctr],
x_offsets[i] + j * boxwidth, (i == 0) ? legend_titles[j] : "", j + 1,
(i + j == n_xtick + n_legend - 2) ? "" : ", \\"));
else
in->writeline(log::format("'$data%1%' using (%2%):1%3%", ctr + 1, ctr + 1,
(i + j == n_xtick + n_legend - 2) ? "" : ", \\"));
ctr++;
}
}
}
void GNUPlotHelper::bargraph(const BarGraphOptions& options)
{
configurePlot(options);
auto in = getInstance(options.instance);
std::vector<std::string> xtick_titles;
std::vector<std::string> legend_titles;
double boxwidth = 0.5;
double boxwidth_gap = 0.15;
bool is_legend = (options.values.size() == 1 && options.values.begin()->first.empty()) ? false : true;
auto it1 = options.values.begin();
int n_legend = options.values.size();
int n_xtick = it1->second.size();
// data blocks
int ctr = 0;
for (std::size_t i = 0; i < n_legend; ++i, ++it1)
{
legend_titles.push_back(replaceStr(it1->first, "_", "\\\\_"));
auto it2 = it1->second.begin();
for (std::size_t j = 0; j < n_xtick; ++j, ++it2)
{
in->writeline(log::format("$data%1% <<EOD", ctr + 1));
if (it2 != it1->second.end())
{
for (const auto& val : it2->second)
{
in->writeline(log::format("%1%", val));
}
}
in->writeline("EOD");
ctr++;
}
}
// plot configuration
if (options.percent)
in->writeline("set title offset 0,1");
in->writeline("set datafile separator \",\"");
in->writeline(log::format("set boxwidth %1%", boxwidth));
in->writeline("set style fill solid 0.5 border -1");
in->writeline(log::format("set offsets %1%, %1%, 0, 0", boxwidth));
if (is_legend)
{
int legend_title_n = 0;
for (const auto& legend_title : legend_titles)
{
if (legend_title.size() > legend_title_n)
legend_title_n = legend_title.size();
}
in->writeline(log::format("set rmargin %1%", legend_title_n + 6)); // Disable legend
in->writeline("set key at screen 1, graph 1"); // Disable legend
}
else
in->writeline("unset key"); // Disable legend
if (options.percent)
in->writeline("set format y \"%g%%\""); // Percent format
in->writeline("set bmargin 6");
// xticks
for (const auto& xtick : options.values.begin()->second)
{
xtick_titles.push_back(replaceStr(xtick.first, "_", "\\\\_"));
}
in->write("set xtics (");
// auto it2 = options.xticks.begin();
double xtick_center_start = (double)n_legend * boxwidth / 2.0 + boxwidth_gap;
std::vector<double> x_offsets;
if (is_legend)
{
for (std::size_t i = 0; i < xtick_titles.size(); ++i)
{
double xtick_center = xtick_center_start + (double(i) * boxwidth_gap + double(i) * double(n_legend) / 2.0);
in->write(log::format("\"%1%\" %2%", xtick_titles[i], std::to_string(xtick_center)));
double xtick_start = xtick_center - double(n_legend) * boxwidth / 2.0 + boxwidth / 2.0;
x_offsets.push_back(xtick_start);
if (i != xtick_titles.size() - 1)
in->write(", ");
}
}
else
{
for (std::size_t i = 0; i < xtick_titles.size(); ++i)
{
in->write(log::format("\"%1%\" %2%", xtick_titles[i], i + 1));
if (i != xtick_titles.size() - 1)
in->write(", ");
}
}
in->writeline(") scale 0.0 center");
std::vector<int> index;
if (is_legend)
{
int idx = 0;
for (int i = 0; i < n_xtick; ++i)
{
idx = i;
for (int j = 0; j < n_legend; ++j)
{
index.push_back(idx + 1);
idx += n_xtick;
}
}
}
ctr = 0;
in->write("plot ");
for (std::size_t i = 0; i < n_xtick; ++i)
{
for (std::size_t j = 0; j < n_legend; ++j)
{
if (is_legend)
in->writeline(log::format("'$data%1%' using (%2%):1 title \"%3%\" with boxes lt %4%%5%", index[ctr],
x_offsets[i] + j * boxwidth, (i == 0) ? legend_titles[j] : "", j + 1,
(i + j == n_xtick + n_legend - 2) ? "" : ", \\"));
else
in->writeline(log::format("'$data%1%' using (%2%):1 with boxes %3%", ctr + 1, ctr + 1,
(i + j == n_xtick + n_legend - 2) ? "" : ", \\"));
ctr++;
}
}
// reset variables in case where using multiplot
if (options.percent)
in->writeline("unset format");
}
void GNUPlotHelper::multiplot(const MultiPlotOptions& options)
{
auto in = getInstance(options.instance);
in->writeline(
log::format("set multiplot layout %1%,%2% title \"%3%\"", options.layout.row, options.layout.col, options.title));
}
std::shared_ptr<GNUPlotHelper::Instance> GNUPlotHelper::getInstance(const std::string& name)
{
if (instances_.find(name) == instances_.end())
instances_.emplace(name, std::make_shared<Instance>());
return instances_.find(name)->second;
}
///
/// GNUPlotDataSet
///
GNUPlotDataSet::GNUPlotDataSet(){};
/** \brief Destructor.
*/
GNUPlotDataSet::~GNUPlotDataSet(){};
/** \brief Visualize results.
* \param[in] results Results to visualize.
*/
void GNUPlotDataSet::addMetric(const std::string& metric, const PlotType& plottype)
{
plot_types_.push_back(std::make_pair(metric, plottype));
};
void GNUPlotDataSet::addMetric(const std::string& metric, const std::string& plottype)
{
auto it = plottype_map.find(plottype);
if (it == plottype_map.end())
ROS_WARN("Cannot find plot type");
else
addMetric(metric, it->second);
};
void GNUPlotDataSet::dump(const DataSetPtr& dataset, const GNUPlotTerminal& terminal,
const GNUPlotHelper::MultiPlotOptions& mpo, const TokenSet& xtick_set,
const TokenSet& legend_set)
{
std::vector<DataSetPtr> datasets;
datasets.push_back(dataset);
dump(datasets, terminal, mpo, xtick_set, legend_set);
};
void GNUPlotDataSet::dump(const std::vector<DataSetPtr>& datasets, const GNUPlotTerminal& terminal,
const GNUPlotHelper::MultiPlotOptions& mpo, const TokenSet& xtick_set,
const TokenSet& legend_set)
{
if (plot_types_.empty())
{
ROS_WARN("No plot type specified");
return;
}
int layout_size = mpo.layout.row * mpo.layout.col;
if (layout_size < plot_types_.size())
ROS_WARN("Metrics cannot fit in plot layout");
helper_.configureTerminal(mpo.instance, terminal);
if (layout_size > 1)
helper_.multiplot(mpo);
if (!validOverlap(xtick_set, legend_set))
{
ROS_WARN("Tokens overlap");
return;
}
for (const auto& pair : plot_types_)
{
switch (pair.second)
{
case PlotType::BarGraph:
dumpBarGraph(pair.first, datasets, xtick_set, legend_set, mpo);
break;
case PlotType::BoxPlot:
dumpBoxPlot(pair.first, datasets, xtick_set, legend_set, mpo);
break;
default:
ROS_WARN("Plot Type not implemented");
break;
}
}
};
GNUPlotHelper& GNUPlotDataSet::getGNUPlotHelper()
{
return helper_;
}
void GNUPlotDataSet::dumpBoxPlot(const std::string& metric, const std::vector<DataSetPtr>& datasets,
const TokenSet& xtick_set, const TokenSet& legend_set,
const GNUPlotHelper::MultiPlotOptions& mpo)
{
GNUPlotHelper::BoxPlotOptions bpo;
if (mpo.title.empty())
bpo.title = log::format("\\\"%1%\\\" for Experiment \\\"%2%\\\"", metric, datasets[0]->name);
else
bpo.title = mpo.title;
bpo.y.label = metric;
bpo.y.min = 0.;
fillDataSet(metric, datasets, xtick_set, legend_set, bpo.values);
if (bpo.values.empty())
{
ROS_WARN("No values to plot...");
return;
}
helper_.boxplot(bpo);
};
void GNUPlotDataSet::dumpBarGraph(const std::string& metric, const std::vector<DataSetPtr>& datasets,
const TokenSet& xtick_set, const TokenSet& legend_set,
const GNUPlotHelper::MultiPlotOptions& mpo)
{
GNUPlotHelper::BarGraphOptions bgo;
bgo.percent = false;
if (mpo.title.empty())
bgo.title = log::format("\\\"%1%\\\" for Experiment \\\"%2%\\\"", metric, datasets[0]->name);
else
bgo.title = mpo.title;
bgo.y.label = metric;
bgo.y.min = 0.;
fillDataSet(metric, datasets, xtick_set, legend_set, bgo.values);
if (bgo.values.empty())
{
ROS_WARN("No values to plot...");
return;
}
helper_.bargraph(bgo);
};
bool GNUPlotDataSet::validOverlap(const TokenSet& xtick_set, const TokenSet& legend_set)
{
int overlap_ctr = 0;
for (const auto& t1 : legend_set)
{
for (const auto& t2 : legend_set)
{
if (token::overlap(t1, t2))
overlap_ctr++;
}
}
if (overlap_ctr > legend_set.size())
return false;
overlap_ctr = 0;
for (const auto& t1 : xtick_set)
{
for (const auto& t2 : xtick_set)
{
if (token::overlap(t1, t2))
overlap_ctr++;
}
}
if (overlap_ctr > xtick_set.size())
return false;
return true;
}
bool GNUPlotDataSet::fillDataSet(const std::string& metric_name, const std::vector<DataSetPtr>& datasets,
const TokenSet& xtick_set, const TokenSet& legend_set,
GNUPlotHelper::PlotValues& plt_values)
{
std::string xlabel_del = "\\n";
std::string legend_del = " + ";
std::vector<DataSetPtr> filtered_datasets;
filterDataSet(legend_set, xtick_set, datasets, filtered_datasets);
bool multiple_datasets = (filtered_datasets.size() > 1) ? true : false;
for (const auto& dataset : filtered_datasets)
{
for (const auto& data_map : dataset->data)
{
const auto& data_vec = data_map.second;
if (data_vec.empty())
continue;
std::string legend_name;
std::string xtick_name;
if (!filterDataLegend(data_vec[0], dataset->metadata, legend_set, legend_name, legend_del) ||
!filterDataXtick(data_vec[0], dataset->metadata, xtick_set, legend_set, xtick_name, xlabel_del,
multiple_datasets))
continue;
if (data_vec.empty())
continue;
const auto& metric_map = data_vec[0]->metrics;
const auto& it = metric_map.find(metric_name);
if (it == metric_map.end())
continue;
std::vector<double> metrics;
for (const auto& data : data_vec)
{
const auto& it = data->metrics.find(metric_name);
if (it != data->metrics.end())
{
double metric = toMetricDouble(it->second);
metrics.push_back(metric);
}
}
auto it2 = plt_values.find(legend_name);
if (it2 == plt_values.end())
plt_values.insert({ { legend_name, { { xtick_name, metrics } } } });
else
{
if (it2->second.find(xtick_name) != it2->second.end())
ROS_WARN_STREAM(log::format("Xtick label '%1%' for metric '%2%' was overwritten", xtick_name, metric_name));
it2->second.insert({ { xtick_name, metrics } });
}
}
}
// Filter out redundant xlabels
int n_labels = 0;
std::map<std::string, int> labels_map;
for (const auto& legend_map : plt_values)
{
for (const auto& labels : legend_map.second)
{
auto label_keys = splitStr(labels.first, xlabel_del);
for (const auto& key : label_keys)
{
auto it = labels_map.find(key);
if (it == labels_map.end())
labels_map.insert({ key, 1 });
else
it->second++;
}
}
n_labels += legend_map.second.size();
}
// Erase
for (auto it = labels_map.cbegin(); it != labels_map.cend() /* not hoisted */; /* no increment */)
{
if (plt_values.size() == it->second || it->second != n_labels)
labels_map.erase(it++); // or "it = m.erase(it)" since C++11
else
++it;
}
// Create new container with new xlabels keys
GNUPlotHelper::PlotValues temp;
for (const auto& legend_map : plt_values)
{
temp.insert({ legend_map.first, {} });
auto it = temp.find(legend_map.first);
for (const auto& labels : legend_map.second)
{
std::string new_key = labels.first;
for (const auto& rm : labels_map)
{
if (!rm.first.empty())
{
new_key = replaceStr(new_key, rm.first + xlabel_del, "");
new_key = replaceStr(new_key, rm.first, "");
}
}
it->second.insert({ new_key, std::move(labels.second) });
}
}
plt_values.clear();
plt_values = temp;
temp.clear();
// Filter out redundant legend
std::set<std::string> remove_set;
for (const auto& legend_map : plt_values)
{
auto keys = splitStr(legend_map.first, legend_del);
for (const auto& key : keys)
{
int ctr = 0;
for (const auto& legend_map_ : plt_values)
{
if (legend_map_.first.find(key) != std::string::npos)
ctr++;
}
if (ctr == plt_values.size())
remove_set.insert(key);
}
}
for (auto& legend_map : plt_values)
{
bool found = false;
std::string new_key = legend_map.first;
for (const auto& rm : remove_set)
{
if (!rm.empty())
{
new_key = replaceStr(legend_map.first, legend_del + rm, "");
new_key = replaceStr(legend_map.first, rm, "");
}
}
if (new_key.size() >= legend_del.size())
{
if (legend_del.compare(&new_key[new_key.size() - legend_del.size()]) == 0)
for (int i = 0; i < legend_del.size(); ++i)
new_key.pop_back(); // Remove trailing delimiter
}
temp.insert({ new_key, std::move(legend_map.second) });
}
plt_values.clear();
plt_values = temp;
// Add missing labels with empty data
// TODO: works but MUST change logic in GNUPlot script
// if (plt_values.size() > 1)
// {
// for (const auto& legend_map : temp)
// {
// for (const auto& label_map : legend_map.second)
// {
// for (const auto& legend_map2 : temp)
// {
// auto it = temp.find(legend_map2.first);
// if (it == temp.end())
// continue;
// else
// {
// auto it1 = it->second.find(label_map.first);
// if (it1 == it->second.end())
// {
// auto it2 = plt_values.find(legend_map2.first);
// it2->second.insert({ label_map.first, {} });
// }
// }
// }
// }
// }
// }
// Warn if legend labels are not of same size
int label_size = plt_values.begin()->second.size();
for (const auto& legend_map : plt_values)
{
if (legend_map.second.size() != label_size)
{
ROS_WARN("Missing labels in some legend, some labels will not plot.");
break;
}
}
return true;
}
bool GNUPlotDataSet::filterDataSet(const TokenSet& legend_set, const TokenSet& filter_set,
const std::vector<DataSetPtr>& datasets, std::vector<DataSetPtr>& filtered_datasets)
{
if (legend_set.empty() && filter_set.empty())
{
for (const auto& dataset : datasets)
filtered_datasets.push_back(dataset);
return true;
}
TokenSet all_set;
std::set_union(legend_set.begin(), legend_set.end(), filter_set.begin(), filter_set.end(),
std::inserter(all_set, all_set.begin()));
for (const auto& dataset : datasets)
{
bool add = true;
std::set<std::string> dataset_fail;
std::set<std::string> dataset_success;
for (const auto& t : all_set)
{
YAML::Node node;
if (!token::compareToNode(t, dataset->metadata, node))
{
if (token::hasValue(t) && t.key_root.compare(DATASET_CONFIG_KEY) == 0)
{
std::set<std::string> keys = token::getChildNodeKeys(node);
auto it = keys.find(t.value);
if (it == keys.end())
{
add = false;
break;
}
}
else if (token::hasValue(t) && t.key_root.compare(DATASET_CONFIG_KEY))
{
dataset_fail.insert(t.group);
}
else
{
add = false;
break;
}
}
else
{
if (t.key_root.compare(DATASET_CONFIG_KEY))
{
dataset_success.insert(t.group);
}
}
}
for (const auto& group_fail : dataset_fail)
{
if (dataset_success.find(group_fail) == dataset_success.end())
{
add = false;
break;
}
}
if (add)
filtered_datasets.push_back(dataset);
}
return true;
}
bool GNUPlotDataSet::filterDataLegend(const DataPtr& data, const YAML::Node& metadata, const TokenSet& legend_set,
std::string& legend_name, const std::string& del)
{
YAML::Node node;
node = YAML::Clone(metadata);
node[DATA_CONFIG_KEY] = data->query->group_name_map;
std::set<std::string> dataset_fail;
std::set<std::string> dataset_success;
for (const auto& token : legend_set)
{
YAML::Node res;
if (token::compareToNode(token, node, res))
dataset_success.insert(token.group);
else
{
dataset_fail.insert(token.group);
continue;
}
if (token::hasValue(token))
if (token.key_root.compare(DATA_CONFIG_KEY) == 0)
legend_name += token.value;
else
legend_name += token.group + ": " + token.value;
else
{
// try getting child node keys
std::set<std::string> keys = token::getChildNodeKeys(res);
// get node value
if (keys.empty())
keys.insert(token::getNodeValue(res));
std::string filter_value;
for (const auto& key : keys)
{
filter_value += key;
filter_value += "+";
}
if (!filter_value.empty())
filter_value.pop_back();
if (token.key_root.compare(DATA_CONFIG_KEY) == 0)
legend_name += filter_value;
else
legend_name += token.group + ": " + token.value;
}
legend_name += del;
}
for (const auto& group_fail : dataset_fail)
{
if (dataset_success.find(group_fail) == dataset_success.end())
return false;
}
// Remove trailing delimiter
if (!legend_name.empty())
for (int i = 0; i < del.size(); ++i)
legend_name.pop_back();
if (!legend_set.empty() && legend_name.empty())
return false;
return true;
}
bool GNUPlotDataSet::filterDataXtick(const DataPtr& data, const YAML::Node& metadata, const TokenSet& xtick_set,
const TokenSet& legend_set, std::string& xtick_name, const std::string& del,
bool multiple_datasets)
{
YAML::Node node;
node = YAML::Clone(metadata);
node[DATA_CONFIG_KEY] = data->query->group_name_map;
// Add missing default config groups
TokenSet xlabel_set = xtick_set;
for (const auto& id : data->query->group_name_map)
{
bool match = false;
for (const auto& xlabel : xlabel_set)
{
Token t(xlabel);
if (t.group.compare("config/" + id.first + "/") == 0)
{
match = true;
break;
}
}
if (!match)
xlabel_set.insert("config/" + id.first + "/" + id.second);
}
std::set<std::string> dataset_fail;
std::set<std::string> dataset_success;
for (const auto& token : xlabel_set)
{
YAML::Node res;
if (token::compareToNode(token, node, res))
dataset_success.insert(token.group);
else
{
dataset_fail.insert(token.group);
continue;
}
// Check token againt legend set
bool legend_match = false;
for (const auto& legend : legend_set)
{
if (legend.group.compare(token.group) == 0)
{
legend_match = true;
break;
}
}
if (legend_match)
continue;
// Belongs to 'config/' node
if (token.key_root.compare(DATA_CONFIG_KEY) == 0)
{
auto label = token::getNodeValue(res);
xtick_name += label + del;
}
else
{
auto label = token::getNodeValue(res);
if (!label.empty())
xtick_name += label + del;
else
{
auto labels = token::getChildNodeKeys(res);
for (const auto& label : labels)
xtick_name += label + del;
}
}
}
// Filter out if failure label not in success
for (const auto& group_fail : dataset_fail)
{
if (dataset_success.find(group_fail) == dataset_success.end())
return false;
}
if (!xtick_name.empty())
for (int i = 0; i < del.size(); ++i)
xtick_name.pop_back(); // Remove trailing delimiter
if (xtick_name.empty())
return false;
return true;
}
| 26.287253 | 120 | 0.590117 | [
"vector",
"solid"
] |
dd5157c57a0f1c05b843532730435413356bfba8 | 1,586 | cpp | C++ | aws-cpp-sdk-macie2/source/model/Page.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-macie2/source/model/Page.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-macie2/source/model/Page.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/macie2/model/Page.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Macie2
{
namespace Model
{
Page::Page() :
m_lineRangeHasBeenSet(false),
m_offsetRangeHasBeenSet(false),
m_pageNumber(0),
m_pageNumberHasBeenSet(false)
{
}
Page::Page(JsonView jsonValue) :
m_lineRangeHasBeenSet(false),
m_offsetRangeHasBeenSet(false),
m_pageNumber(0),
m_pageNumberHasBeenSet(false)
{
*this = jsonValue;
}
Page& Page::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("lineRange"))
{
m_lineRange = jsonValue.GetObject("lineRange");
m_lineRangeHasBeenSet = true;
}
if(jsonValue.ValueExists("offsetRange"))
{
m_offsetRange = jsonValue.GetObject("offsetRange");
m_offsetRangeHasBeenSet = true;
}
if(jsonValue.ValueExists("pageNumber"))
{
m_pageNumber = jsonValue.GetInt64("pageNumber");
m_pageNumberHasBeenSet = true;
}
return *this;
}
JsonValue Page::Jsonize() const
{
JsonValue payload;
if(m_lineRangeHasBeenSet)
{
payload.WithObject("lineRange", m_lineRange.Jsonize());
}
if(m_offsetRangeHasBeenSet)
{
payload.WithObject("offsetRange", m_offsetRange.Jsonize());
}
if(m_pageNumberHasBeenSet)
{
payload.WithInt64("pageNumber", m_pageNumber);
}
return payload;
}
} // namespace Model
} // namespace Macie2
} // namespace Aws
| 17.23913 | 69 | 0.703657 | [
"model"
] |
dd51f1bd0f0d5e5eadbb8af324afc07acd060a5f | 5,315 | cpp | C++ | projectionmethod.cpp | haranjackson/ProjectionMethod | 22bb282c718916e30cb8daa7dc8f13ad7c4292b7 | [
"MIT"
] | 3 | 2018-05-04T00:51:16.000Z | 2021-08-10T15:14:43.000Z | projectionmethod.cpp | haranjackson/ProjectionMethod | 22bb282c718916e30cb8daa7dc8f13ad7c4292b7 | [
"MIT"
] | null | null | null | projectionmethod.cpp | haranjackson/ProjectionMethod | 22bb282c718916e30cb8daa7dc8f13ad7c4292b7 | [
"MIT"
] | null | null | null | #include <vector>
#include "lib/Eigen327/Dense"
#include "lib/Eigen327/Sparse"
#include "lib/Eigen327/Eigenvalues"
#include "matrixops.h"
double TOL = 1e-6; // For calculating steady state
SpMat diff_mat(int n, double h, double c)
{
// c: Neumann=1, Dirichlet=2, Dirichlet mid=3;
SpMat ret(n,n);
std::vector<T> tripletList;
tripletList.reserve(3*n-2);
tripletList.push_back(T(0, 0, c));
tripletList.push_back(T(n-1, n-1, c));
tripletList.push_back(T(0, 1, -1));
tripletList.push_back(T(1, 0, -1));
for (int i=1; i<n-1; i++)
{
tripletList.push_back(T(i, i+1, -1));
tripletList.push_back(T(i+1 ,i, -1));
tripletList.push_back(T(i, i, 2));
}
ret.setFromTriplets(tripletList.begin(), tripletList.end());
return ret / (h*h);
}
std::vector<Mat> simulate(double Re, double tf, double uLid, int nx, int ny,
double dt, bool steadyState)
{
int nt = (int)ceil(tf/dt);
dt = tf / nt;
double hx = 1./nx;
double hy = 1./ny;
// initial conditions
Mat U = Mat::Zero(nx-1, ny);
Mat V = Mat::Zero(nx, ny-1);
Mat P;
// boundary conditions
Vec uN = uLid * Vec::Ones(nx+1);
Vec uS = Vec::Zero(nx+1);
Vec uE = Vec::Zero(ny);
Vec uW = Vec::Zero(ny);
Vec vN = Vec::Zero(nx);
Vec vS = Vec::Zero(nx);
Vec vE = Vec::Zero(ny+1);
Vec vW = Vec::Zero(ny+1);
Mat Ubc(nx-1,ny);
Ubc << Mat::Zero(nx-1,ny-1), 2*uN.segment(1,nx-1);
Ubc *= dt/(Re*hx*hx);
SpMat Ap = kron(speye(ny),diff_mat(nx,hx,1)) +
kron(diff_mat(ny,hy,1),speye(nx));
Ap.coeffRef(0,0) *= 3./2;
SpMat Au = speye((nx-1)*ny) +
dt/Re * (kron(speye(ny), diff_mat(nx-1,hx,2)) +
kron(diff_mat(ny,hy,3), speye(nx-1)));
SpMat Av = speye(nx*(ny-1)) +
dt/Re * (kron(speye(ny-1), diff_mat(nx,hx,3)) +
kron(diff_mat(ny-1,hy,2), speye(nx)));
SpMat As = kron(speye(ny-1),diff_mat(nx-1,hx,2)) +
kron(diff_mat(ny-1,hy,2),speye(nx-1));
Eigen::SimplicialLDLT<SpMat> Lp(Ap);
Eigen::SimplicialLDLT<SpMat> Lu(Au);
Eigen::SimplicialLDLT<SpMat> Lv(Av);
Eigen::SimplicialLDLT<SpMat> Ls(As);
int k = 1;
while(true)
{
Mat Uprev = U;
Mat Vprev = V;
// calculate gamma
double y1 = U.lpNorm<Eigen::Infinity>() / hx;
double y2 = V.lpNorm<Eigen::Infinity>() / hy;
double y0 = 1.2 * dt * std::max(y1,y2);
double gamma = std::min(y0, 1.);
// nonlinear terms
Mat Ue0 = vconcat(uW.transpose(), U, uE.transpose());
Mat Ue = hconcat(-Ue0.col(0), Ue0, 2*uN-Ue0.col(ny-1));
Mat Ve0 = hconcat(vS, V, vN);
Mat Ve = vconcat(-Ve0.row(0), Ve0, -Ve0.row(nx-1));
Mat Ua = avg(Ue.transpose()).transpose();
Mat Ud = diff(Ue.transpose()).transpose() / 2;
Mat Va = avg(Ve);
Mat Vd = diff(Ve) / 2;
Mat tmp1 = Ua.cwiseProduct(Va) - gamma * Ua.cwiseAbs().cwiseProduct(Vd);
Mat UVx = diff(tmp1) / hx;
Mat tmp2 = Ua.cwiseProduct(Va) - gamma * Ud.cwiseProduct(Va.cwiseAbs());
Mat UVy = diff(tmp2.transpose()).transpose() / hy;
Ua = avg(Ue.block(0,1,nx+1,ny));
Ud = diff(Ue.block(0,1,nx+1,ny)) / 2;
Va = avg(Ve.block(1,0,nx,ny+1).transpose()).transpose();
Vd = diff(Ve.block(1,0,nx,ny+1).transpose()).transpose() / 2;
tmp1 = Ua.cwiseProduct(Ua) - gamma * Ua.cwiseAbs().cwiseProduct(Ud);
Mat U2x = diff(tmp1) / hx;
tmp2 = Va.cwiseProduct(Va) - gamma * Va.cwiseAbs().cwiseProduct(Vd);
Mat V2y = diff(tmp2.transpose()).transpose() / hy;
U -= dt * (UVy.block(1, 0, nx-1, ny) + U2x);
V -= dt * (UVx.block(0, 1, nx, ny-1) + V2y);
// implicit viscosity
Vec rhs = reshape(U+Ubc,0,1);
Vec u = Lu.solve(rhs);
U = reshape(u,nx-1,ny);
rhs = reshape(V,0,1);
Vec v = Lv.solve(rhs);
V = reshape(v,nx,ny-1);
// pressure
Mat tmp = diff(vconcat(uW.transpose(), U, uE.transpose())) / hx +
diff(hconcat(vS, V, vN).transpose()).transpose() / hy;
rhs = reshape(tmp,0,1);
Vec p = -Lp.solve(rhs);
P = reshape(p,nx,ny);
U -= diff(P) / hx;
V -= diff(P.transpose()).transpose() / hy;
k += 1;
if (steadyState)
{
if ((U-Uprev).lpNorm<Eigen::Infinity>() < TOL &&
(V-Vprev).lpNorm<Eigen::Infinity>() < TOL)
break;
}
else if (k>nt)
break;
int N = nx/2;
assert(!isnan(P(N,N)));
}
std::vector<Mat> ret(5);
Mat tmp1 = vconcat(uW.transpose(), U, uE.transpose());
Mat tmp2 = avg(tmp1.transpose()).transpose();
ret[0] = hconcat(uS, tmp2, uN);
tmp1 = hconcat(vS, V, vN);
tmp2 = avg(tmp1);
ret[1] = vconcat(vW.transpose(), tmp2, vE.transpose());
ret[2] = P;
Mat W0 = diff(U.transpose()).transpose()/hy - diff(V)/hx;
Vec rhs = reshape(W0, 0, 1);
Vec s = Ls.solve(rhs);
Mat S = Mat::Zero(nx+1, ny+1);
Mat W = Mat::Zero(nx+1, ny+1);
S.block(1,1,nx-1,ny-1) = reshape(s,nx-1,ny-1);
W.block(1,1,nx-1,ny-1) = W0;
ret[3] = S;
ret[4] = W;
return ret;
}
| 29.527778 | 80 | 0.524553 | [
"vector"
] |
dd53b822bd3d12ffc60924701012c743591657f2 | 6,499 | cpp | C++ | Pang/Pang/Source/ModuleParticles.cpp | UriKurae/Pang | 2634bb22e674f022c0218a3802d0d5f80a9661fa | [
"MIT"
] | 1 | 2020-12-21T17:21:28.000Z | 2020-12-21T17:21:28.000Z | Pang/Pang/Source/ModuleParticles.cpp | UriKurae/Pang | 2634bb22e674f022c0218a3802d0d5f80a9661fa | [
"MIT"
] | null | null | null | Pang/Pang/Source/ModuleParticles.cpp | UriKurae/Pang | 2634bb22e674f022c0218a3802d0d5f80a9661fa | [
"MIT"
] | null | null | null | #include "ModuleParticles.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModuleCollisions.h"
#include "ModuleTileset.h"
#include "ModuleAudio.h"
#include "SDL/include/SDL_timer.h"
ModuleParticles::ModuleParticles(bool startEnabled) : Module(startEnabled)
{
name = "PARTICLES";
for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
particles[i] = nullptr;
gunShotHitWall.anim.PushBack({ 251, 14, 14, 5 });
gunShotHitWall.anim.PushBack({ 271, 14, 14, 5 });
gunShotHitWall.anim.loop = false;
gunShotHitWall.anim.speed = 0.1f;
}
ModuleParticles::~ModuleParticles()
{
}
bool ModuleParticles::Start()
{
LOG("Loading particles");
texture = App->textures->Load("Assets/Balloons/Particles.png");
gunShotHit = App->audio->LoadFx("Assets/Sound/FX/HitGunShoot.wav");
return true;
}
bool ModuleParticles::CleanUp()
{
LOG("Unloading particles");
// Delete all remaining active particles on application exit
for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
if(particles[i] != nullptr)
{
delete particles[i];
particles[i] = nullptr;
}
}
App->audio->UnloadFx(gunShotHit);
App->textures->Unload(texture);
return true;
}
void ModuleParticles::OnCollision(Collider* c1, Collider* c2)
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
// Always destroy particles that collide
if (particles[i] != nullptr && particles[i]->collider == c1 && c2->type == Collider::Type::BALLOON)
{
delete particles[i];
particles[i] = nullptr;
break;
}
}
}
update_status ModuleParticles::Update()
{
for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
Particle* particle = particles[i];
if(particle == nullptr) continue;
// Call particle Update. If it has reached its lifetime, destroy it
if(particle->Update() == false)
{
delete particle;
particles[i] = nullptr;
}
}
breakableCollision();
unbreakableCollision();
wallCollision();
return update_status::UPDATE_CONTINUE;
}
update_status ModuleParticles::PostUpdate()
{
//Iterating all particle array and drawing any active particles
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
Particle* particle = particles[i];
if (particle != nullptr && particle->isAlive)
{
App->render->Blit(texture, particle->position.x, particle->position.y, &(particle->anim.GetCurrentFrame()));
}
}
return update_status::UPDATE_CONTINUE;
}
Particle* ModuleParticles::AddParticle(const Particle& particle, int x, int y, Collider::Type colliderType, uint delay)
{
Particle* newParticle = nullptr;
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
//Finding an empty slot for a new particle
if (particles[i] == nullptr)
{
newParticle = new Particle(particle);
newParticle->frameCount = -(int)delay; // We start the frameCount as the negative delay
newParticle->position.x = x; // so when frameCount reaches 0 the particle will be activated
newParticle->position.y = y;
//Adding the particle's collider
if (colliderType != Collider::Type::NONE)
newParticle->collider = App->collisions->AddCollider(newParticle->anim.GetCurrentFrame(), colliderType, this);
particles[i] = newParticle;
break;
}
}
return newParticle;
}
void ModuleParticles::breakableCollision()
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; i++)
{
iPoint tile;
if (particles[i] != nullptr)
{
tile = { particles[i]->position.x / TILE_SIZE, particles[i]->position.y / TILE_SIZE };
}
if (App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::BREAKABLE && particles[i] != nullptr) {
App->tileset->changeTile(tile);
delete particles[i];
particles[i] = nullptr;
break;
}
else if (App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::BREAKABLE && App->tileset->getTileLevel(tile.y, tile.x + 1).id == ModuleTileset::TileType::EMPTY && particles[i] != nullptr) {
App->tileset->changeTile(tile);
delete particles[i];
particles[i] = nullptr;
break;
}
else if (App->tileset->getTileLevel(tile.y, tile.x + 1).id == ModuleTileset::TileType::BREAKABLE && App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::EMPTY && particles[i] != nullptr) {
App->tileset->changeTile(tile);
delete particles[i];
particles[i] = nullptr;
break;
}
}
}
void ModuleParticles::unbreakableCollision()
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; i++)
{
iPoint tile;
if (particles[i] != nullptr)
{
tile = { particles[i]->position.x / TILE_SIZE, particles[i]->position.y / TILE_SIZE };
}
if (App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::UNBREAKABLE && particles[i] != nullptr && particles[i]->collider->type == Collider::Type::PLAYER_SHOT) {
//App->audio->PlayFx(gunShotHit);
//AddParticle(gunShotHitWall, particles[i]->position.x - 3, particles[i]->position.y, Collider::Type::NONE, 0);
delete particles[i];
particles[i] = nullptr;
break;
}
else if (App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::UNBREAKABLE && App->tileset->getTileLevel(tile.y, tile.x + 1).id == ModuleTileset::TileType::EMPTY && particles[i] != nullptr ) {
//App->audio->PlayFx(gunShotHit);
//AddParticle(gunShotHitWall, particles[i]->position.x - 3, particles[i]->position.y, Collider::Type::NONE, 0);
delete particles[i];
particles[i] = nullptr;
break;
}
else if (App->tileset->getTileLevel(tile.y, tile.x + 1).id == ModuleTileset::TileType::UNBREAKABLE && App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::EMPTY && particles[i] != nullptr) {
//App->audio->PlayFx(gunShotHit);
//AddParticle(gunShotHitWall, particles[i]->position.x - 3, particles[i]->position.y, Collider::Type::NONE, 0);
delete particles[i];
particles[i] = nullptr;
break;
}
}
}
void ModuleParticles::wallCollision()
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; i++)
{
iPoint tile;
if (particles[i] != nullptr)
{
tile = { particles[i]->position.x / TILE_SIZE, particles[i]->position.y / TILE_SIZE };
}
if (App->tileset->getTileLevel(tile.y, tile.x).id == ModuleTileset::TileType::WALL && App->tileset->getTileLevel(tile.y, tile.x + 1).id == ModuleTileset::TileType::WALL && particles[i] != nullptr) {
//App->audio->PlayFx(gunShotHit);
//AddParticle(gunShotHitWall, particles[i]->position.x - 3, particles[i]->position.y, Collider::Type::NONE, 0);
delete particles[i];
particles[i] = nullptr;
break;
}
}
} | 27.892704 | 214 | 0.679181 | [
"render"
] |
dd5b8d78db219da3d7ed674712096ec447613719 | 28,307 | cpp | C++ | BigInt/main.cpp | SeijiEmery/BigInt | c1c681613b97d85b28c80e74f992b5e5af38cab5 | [
"MIT"
] | null | null | null | BigInt/main.cpp | SeijiEmery/BigInt | c1c681613b97d85b28c80e74f992b5e5af38cab5 | [
"MIT"
] | null | null | null | BigInt/main.cpp | SeijiEmery/BigInt | c1c681613b97d85b28c80e74f992b5e5af38cab5 | [
"MIT"
] | null | null | null | //
// main.cpp
// BigInt
//
// Created by semery on 8/25/16.
// Copyright © 2016 Seiji Emery. All rights reserved.
//
#include <iostream>
#include <vector>
#include <cassert>
#define ENABLE_UNITTESTS 1
#define UNITTEST_REPORT_ON_SUCCESS 0
#include "unittest.hpp"
namespace storage {
constexpr size_t STORAGE_BITS = 32;
typedef uint32_t smallInt_t; // BigInt storage type
typedef uint64_t bigInt_t; // BigInt operation type (mul + add ops need 2x precision for overflow)
constexpr size_t LOW_BITMASK = (1L << STORAGE_BITS) - 1;
constexpr size_t HIGH_BITMASK = ~LOW_BITMASK;
constexpr smallInt_t MAX = (smallInt_t)((1L << STORAGE_BITS) - 1);
UNITTEST_METHOD(verifyStorageValueTypes) {
TEST_ASSERT_EQ(STORAGE_BITS, 32, "storage size changed! (tests assume 32-bit");
TEST_ASSERT_EQ(sizeof(smallInt_t) * 8, STORAGE_BITS, "storage size does not match STORAGE_BITS!");
TEST_ASSERT_EQ(sizeof(smallInt_t) * 2, sizeof(bigInt_t), "big int is not 2x size of small int!");
TEST_ASSERT_EQ((smallInt_t)(1L << STORAGE_BITS), 0, "storage size not big enough");
TEST_ASSERT_EQ((bigInt_t)(1L << STORAGE_BITS), 1L << STORAGE_BITS, "op size not big enough");
TEST_ASSERT_EQ(LOW_BITMASK & HIGH_BITMASK, 0, "LOW_BITMASK overlaps with HIGH_BITMASK");
TEST_ASSERT_EQ(LOW_BITMASK | HIGH_BITMASK, ((size_t)0) - 1, "LOW_BITMASK does not have perfect coverage with HIGH_BITMASK");
TEST_ASSERT(MAX != 0, "storage::MAX cannot fit in storage value");
TEST_ASSERT_EQ((bigInt_t)MAX, (bigInt_t)((1L << STORAGE_BITS) - 1), "invalid storage::MAX");
TEST_ASSERT_EQ(MAX + 1, 0, "storage::MAX + 1 should wrap to 0");
} UNITTEST_END_METHOD
bigInt_t fromIntParts (smallInt_t high, smallInt_t low) {
return ((bigInt_t)high << STORAGE_BITS) | (bigInt_t)low;
}
UNITTEST_METHOD(fromIntParts) {
TEST_ASSERT_EQ(fromIntParts(0x15, 0x227), 0x1500000227);
TEST_ASSERT_EQ(fromIntParts(0x0, (smallInt_t)0xAAAA12847923), 0x12847923);
TEST_ASSERT_EQ(fromIntParts(0x0, 0x0), 0x0);
TEST_ASSERT_EQ(fromIntParts(0xAA, 0x0), 0xAA00000000);
} UNITTEST_END_METHOD
void storeIntParts (bigInt_t v, smallInt_t& high, smallInt_t& low) {
high = (smallInt_t)((v & HIGH_BITMASK) >> STORAGE_BITS);
low = (smallInt_t)(v & LOW_BITMASK);
}
UNITTEST_METHOD(storeIntParts) {
smallInt_t a, b;
storeIntParts(0x0, a, b);
TEST_ASSERT_EQ(a, 0);
TEST_ASSERT_EQ(b, 0);
storeIntParts(0x1500000227, a, b);
TEST_ASSERT_EQ(a, 0x15);
TEST_ASSERT_EQ(b, 0x227);
storeIntParts(0xAAAA12847923, a, b);
TEST_ASSERT_EQ(a, 0xAAAA);
TEST_ASSERT_EQ(b, 0x12847923);
storeIntParts(0xAA00000000, a, b);
TEST_ASSERT_EQ(a, 0xAA);
TEST_ASSERT_EQ(b, 0x0);
} UNITTEST_END_METHOD
UNITTEST_MAIN_METHOD(storage::unittests) {
RUN_UNITTEST(verifyStorageValueTypes, UNITTEST_INSTANCE);
RUN_UNITTEST(fromIntParts, UNITTEST_INSTANCE);
RUN_UNITTEST(storeIntParts, UNITTEST_INSTANCE);
} UNITTEST_END_METHOD
}; // namespace storage
class BigInt {
std::vector<storage::smallInt_t> sections;
bool sign = false;
public:
BigInt (const std::string& s) {
auto ptr = s.c_str();
initFromString(ptr);
}
BigInt (const BigInt & v) : sections(v.sections), sign(v.sign) {}
private:
// Private constructor for unit tests (unsafe for external code; would need to normalize values)
BigInt (std::initializer_list<storage::smallInt_t> values) : sections(values) {}
BigInt (bool sign, std::initializer_list<storage::smallInt_t> values) : sign(sign), sections(values) {}
BigInt () {}
template <bool sign = true>
static BigInt create (std::initializer_list<storage::smallInt_t> values) { return { sign, values }; }
public:
void initFromString (const char*& s) {
sections.clear();
if (s[0] == '-') ++s, sign = true;
else if (s[0] == '+') ++s, sign = false;
if (s[0] < '0' || s[0] > '9')
throw new std::runtime_error("String does not form a valid integer!");
while (!(s[0] < '0' || s[0] > '9'))
pushDecimalDigit(s[0] - '0'), ++s;
}
static UNITTEST_METHOD(initFromString) {
BigInt a { "1" };
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 1);
BigInt b { "42" };
TEST_ASSERT_EQ(b.sections.size(), 1);
TEST_ASSERT_EQ(b.sections[0], 42);
// If this changes next tests won't work
TEST_ASSERT_EQ(sizeof(typeof(b.sections[0])), 4, "base size changed? (expected 32-bit storage, 64-bit ops)");
BigInt c { "4294967297" }; // 1 << 32 + 1
TEST_ASSERT_EQ(c.sections.size(), 2);
TEST_ASSERT_EQ(c.sections[0], 1);
TEST_ASSERT_EQ(c.sections[1], 1);
BigInt d { "64424509677" }; // (1 << 32) * 15 + 237
TEST_ASSERT_EQ(d.sections.size(), 2);
TEST_ASSERT_EQ(d.sections[0], 237);
TEST_ASSERT_EQ(d.sections[1], 15);
BigInt e { "-64424509677" };
TEST_ASSERT_EQ(e.sign, true);
TEST_ASSERT_EQ(e.sections.size(), 2);
TEST_ASSERT_EQ(e.sections[0], 237);
TEST_ASSERT_EQ(e.sections[1], 15);
BigInt f { "0" };
TEST_ASSERT_EQ(f.sections.size(), 1);
TEST_ASSERT_EQ(f.sections[0], 0);
BigInt g { "64424509440" }; // (1 << 32) * 15
TEST_ASSERT_EQ(g.sections.size(), 2);
TEST_ASSERT_EQ(g.sections[0], 0);
TEST_ASSERT_EQ(g.sections[1], 15);
BigInt h { "4294967296" }; // 1 << 32 exact
TEST_ASSERT_EQ(h.sections.size(), 2);
TEST_ASSERT_EQ(h.sections[0], 0);
TEST_ASSERT_EQ(h.sections[1], 1);
} UNITTEST_END_METHOD
void pushDecimalDigit (storage::smallInt_t digit) {
assert(digit <= 9);
if (!sections.size())
sections.push_back(digit);
else
multiplyAdd(10, digit);
}
static UNITTEST_METHOD(pushDecimalDigit) {
BigInt a { 0 };
TEST_ASSERT_EQ(a.sections.size(), 1);
a.sections.pop_back();
a.pushDecimalDigit(9);
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 9);
a.pushDecimalDigit(1);
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 91);
a.pushDecimalDigit(5);
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 915);
} UNITTEST_END_METHOD
BigInt& operator+= (storage::smallInt_t v) {
return multiplyAdd(1, v);
}
static UNITTEST_METHOD(scalarAdd) {
BigInt a { 15 };
TEST_ASSERT_EQ(a.sections.size(), 1, "bad initial size!");
TEST_ASSERT_EQ(a.sections[0], 15, "bad init value");
a += 3;
TEST_ASSERT_EQ(a.sections.size(), 1, "bad size after += 3");
TEST_ASSERT_EQ(a.sections[0], 18, "+= 3");
a += 12;
TEST_ASSERT_EQ(a.sections.size(), 1, "bad size after += 12");
TEST_ASSERT_EQ(a.sections[0], 30, "+= 12");
a += (((size_t)1 << storage::STORAGE_BITS) - 1);
TEST_ASSERT_EQ(a.sections.size(), 2, "should overflow to 2 values");
TEST_ASSERT_EQ(a.sections[0], 29, "low value (post overflow)");
TEST_ASSERT_EQ(a.sections[1], 1, "high value (post overflow)");
a.sections.pop_back();
a.sections.pop_back();
TEST_ASSERT_EQ(a.sections.size(), 0, "bad section size!");
a += 0;
TEST_ASSERT_EQ(a.sections.size(), 1, "bad size after += 0");
TEST_ASSERT_EQ(a.sections[0], 0, "probably dead now");
a.sections.pop_back();
TEST_ASSERT_EQ(a.sections.size(), 0, "bad size (see above)");
a += 1;
TEST_ASSERT_EQ(a.sections.size(), 1, "bad size after += 1");
TEST_ASSERT_EQ(a.sections[0], 1, "+= 1");
// note: this is reversed:
// bit 0-31 bit 32-63 bit 64-95 bit 96-127
BigInt b { storage::MAX, storage::MAX, storage::MAX, 125 };
TEST_ASSERT_EQ(b.sections.size(), 4, "b invalid storage size?!");
TEST_ASSERT_EQ(b.sections[0], storage::MAX, "b initial min value");
TEST_ASSERT_EQ(b.sections[3], 125, "b initial max value");
b += 6;
TEST_ASSERT_EQ(b.sections.size(), 4, "b storage size should not change");
TEST_ASSERT_EQ(b.sections[0], 5, "bit 0: storage::MAX should overflow to 5");
TEST_ASSERT_EQ(b.sections[1], 0, "bit 32: storage::MAX should overflow to 0 (carry +1)");
TEST_ASSERT_EQ(b.sections[2], 0, "bit 64: storage::MAX should overflow to 0 (carry +1)");
TEST_ASSERT_EQ(b.sections[3], 126, "bit 96: should get carry +1");
} UNITTEST_END_METHOD
BigInt& operator *= (storage::smallInt_t v) {
return multiplyAdd(v, 0);
}
static UNITTEST_METHOD(scalarMul) {
BigInt a { 1 };
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 1);
a *= 15;
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 15);
a *= storage::MAX;
TEST_ASSERT_EQ(a.sections.size(), 2, "15 * storage::MAX");
TEST_ASSERT_EQ(a.sections[0], (15L * storage::MAX) % (1L << storage::STORAGE_BITS), "15 * storage::MAX: low bits");
TEST_ASSERT_EQ(a.sections[1], (15L * storage::MAX) / (1L << storage::STORAGE_BITS), "15 * storage::MAX: high bits");
//
// Test multiplying a 160-bit big num by a large 32-bit coefficient:
//
// note: reversed
// min value max value
BigInt b { 0x28fa9923, 0x49378824, 0xffff99ff, 0xffffffff, 0x22487943 };
TEST_ASSERT_EQ(b.sections.size(), 5, "b storage section count");
TEST_ASSERT_EQ(b.sections[0], 0x28fa9923, "b[0] initial");
TEST_ASSERT_EQ(b.sections[1], 0x49378824, "b[1] initial");
TEST_ASSERT_EQ(b.sections[2], 0xffff99ff, "b[2] initial");
TEST_ASSERT_EQ(b.sections[3], 0xffffffff, "b[3] initial");
TEST_ASSERT_EQ(b.sections[4], 0x22487943, "b[4] initial");
// Multiply the above big num by a large number
b *= 0x59ff2938;
// Calculate our expected result manually:
size_t MAX_WRAP = 1L << storage::STORAGE_BITS;
size_t m0 = (0x28fa9923L * 0x59ff2938L), x0 = m0 % MAX_WRAP, c0 = m0 / MAX_WRAP;
size_t m1 = (0x49378824L * 0x59ff2938L + c0), x1 = m1 % MAX_WRAP, c1 = m1 / MAX_WRAP;
size_t m2 = (0xffff99ffL * 0x59ff2938L + c1), x2 = m2 % MAX_WRAP, c2 = m2 / MAX_WRAP;
size_t m3 = (0xffffffffL * 0x59ff2938L + c2), x3 = m3 % MAX_WRAP, c3 = m3 / MAX_WRAP;
size_t m4 = (0x22487943L * 0x59ff2938L + c3), x4 = m4 % MAX_WRAP, c4 = m4 / MAX_WRAP;
// And compare with result:
TEST_ASSERT_EQ(b.sections.size(), 6, "should have 6 sections?");
TEST_ASSERT_EQ(b.sections[0], x0, "b[0] post-multiply");
TEST_ASSERT_EQ(b.sections[1], x1, "b[1] post-multiply");
TEST_ASSERT_EQ(b.sections[2], x2, "b[2] post-multiply");
TEST_ASSERT_EQ(b.sections[3], x3, "b[3] post-multiply");
TEST_ASSERT_EQ(b.sections[4], x4, "b[4] post-multiply");
TEST_ASSERT_EQ(b.sections[5], c4, "b[5] post-multiply");
} UNITTEST_END_METHOD
// Executes a multiply + add operation: multiplies each digit in BigNum by base, adds an additional scalar value (carry).
// Incidentally, multiply is just this with carry = 0, and add scalar is this with base = 1.
BigInt& multiplyAdd (storage::smallInt_t base, storage::smallInt_t carry) {
for (auto i = 0; i < sections.size(); ++i) {
auto r = (storage::bigInt_t)sections[i] * (storage::bigInt_t)base + (storage::bigInt_t)carry;
storage::storeIntParts(r, carry, sections[i]);
}
if (carry || !sections.size()) sections.push_back(carry);
return *this;
}
static UNITTEST_METHOD(scalarMultiplyAdd) {
// Since we've already tested *= and += (we'll assume the above tests passed),
// we'll use this test to double check x = x * 10 + n, which is the core of our
// decimal-to-binary algorithm.
BigInt a { 0 };
TEST_ASSERT_EQ(a.sections.size(), 1, "a initial size");
TEST_ASSERT_EQ(a.sections[0], 0, "a[0] initial");
a.multiplyAdd(10, 1);
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 1, "a[0] (0) * 10 + 1");
a.multiplyAdd(10, 9);
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 19, "a[0] (1) * 10 + 9");
a.multiplyAdd(256, 22);
TEST_ASSERT_EQ(a.sections.size(), 1);
TEST_ASSERT_EQ(a.sections[0], 4886, "a[0] (19) * 256 + 22");
// Test with true big int:
BigInt b { 0x1210981F, 0xFA093811, 0x9C049814, 0x342981F9 };
TEST_ASSERT_EQ(b.sections.size(), 4);
TEST_ASSERT_EQ(b.sections[0], 0x1210981F);
TEST_ASSERT_EQ(b.sections[1], 0xFA093811);
TEST_ASSERT_EQ(b.sections[2], 0x9C049814);
TEST_ASSERT_EQ(b.sections[3], 0x342981F9);
b.multiplyAdd(256, 5);
TEST_ASSERT_EQ(b.sections.size(), 5);
TEST_ASSERT_EQ(b.sections[0], 0x10981F05);
TEST_ASSERT_EQ(b.sections[1], 0x09381112);
TEST_ASSERT_EQ(b.sections[2], 0x049814FA);
TEST_ASSERT_EQ(b.sections[3], 0x2981F99C);
TEST_ASSERT_EQ(b.sections[4], 0x00000034);
} UNITTEST_END_METHOD
BigInt& scalarDiv (storage::smallInt_t d, storage::smallInt_t& rem) {
rem = 0;
for (auto i = sections.size(); i > 0; --i) {
auto n = storage::fromIntParts(rem, sections[i-1]);
sections[i-1] = (storage::smallInt_t)(n / (storage::bigInt_t)d);
rem = (storage::smallInt_t)(n % (storage::bigInt_t)d);
}
while (sections.size() > 0 && sections.back() == 0)
sections.pop_back();
return *this;
}
BigInt& operator /= (storage::smallInt_t v) {
storage::smallInt_t r;
return scalarDiv(v, r);
}
static UNITTEST_METHOD(scalarDiv) {
// Unit tests TBD
} UNITTEST_END_METHOD
// Signed multiply / divide operations
BigInt& operator *= (int v) {
if (v < 0)
sign = !sign, v = -v;
return operator *= ((storage::smallInt_t)v);
}
BigInt& operator /= (int v) {
if (v < 0)
sign = !sign, v = -v;
return operator /= ((storage::smallInt_t)v);
}
std::vector<char>& writeString (std::vector<char>& str, bool writeNull = false) {
if (sign) str.push_back('-');
if (!sections.size()) {
str.push_back('0');
return str;
} else {
// Using a copy (this operation is destructive), write digits in reverse order
BigInt temp { *this };
assert(temp.sections.size() == sections.size());
auto s0 = str.size();
storage::smallInt_t rem;
while (temp.sections.size()) {
temp.scalarDiv(10, rem);
str.push_back('0' + rem);
}
// And then reverse to get correct value
for (auto i = s0, j = str.size()-1; i < j; ++i, --j)
std::swap(str[i], str[j]);
if (writeNull)
str.push_back('\0');
return str;
}
}
static UNITTEST_METHOD(writeString) {
std::vector<char> s;
TEST_ASSERT_EQ(std::string("0"), BigInt{0}.writeString(s, true).data()); s.clear();
TEST_ASSERT_EQ(std::string("1"), BigInt{1}.writeString(s, true).data()); s.clear();
typedef std::initializer_list<storage::smallInt_t> iv;
TEST_ASSERT_EQ(BigInt{true, iv{24}}.sign, true);
TEST_ASSERT_EQ(BigInt{true, iv{24}}.sections.size(), 1);
TEST_ASSERT_EQ(BigInt{true, iv{24}}.sections[0], 24);
TEST_ASSERT_EQ(std::string("-24"), BigInt{true, iv{24}}.writeString(s, true).data()); s.clear();
TEST_ASSERT_EQ(std::string("680564733841876926926749214863536422912"), BigInt::pow2(129).writeString(s, true).data()); s.clear();
} UNITTEST_END_METHOD
operator bool () const { return sections.size() && !(sections.size() == 1 && sections[0] == 0); }
bool operator == (const BigInt& other) const { return this->cmp(other) == 0; }
bool operator <= (const BigInt& other) const { return this->cmp(other) <= 0; }
bool operator >= (const BigInt& other) const { return this->cmp(other) >= 0; }
int cmp (const BigInt& other) const {
if (!this->operator bool()) return !other.operator bool() ? 0 : other.sign ? 1 : -1;
if (!other.operator bool()) return sign ? -1 : 1;
if (sign != other.sign) return sign ? -1 : 1;
assert(sections.size() && other.sections.size());
if (sections.size() != other.sections.size())
return sections.size() < other.sections.size() ? -2 : 2;
// for (auto i = std::min(sections.size(), other.sections.size()); i --> 0; ) {
for (auto i = 0; i < std::min(sections.size(), other.sections.size()); ++i) {
if (sections[i] < other.sections[i]) return sign ? 1 : -1;
if (sections[i] > other.sections[i]) return sign ? -1 : 1;
}
return 0;
}
static UNITTEST_METHOD(cmp) {
#define BINT(sign,args...) BigInt{sign, std::initializer_list<storage::smallInt_t>{args}}
#define BINT_TEST_CMP(a,b, args...) TEST_ASSERT_EQ(a.cmp(b), args)
TEST_ASSERT_EQ(BINT(true, 0).operator bool(), false, "BigInt operator bool ( 0 )");
TEST_ASSERT_EQ(BINT(false, 0).operator bool(), false, "BigInt operator bool ( 0 )");
TEST_ASSERT_EQ(BINT(true, 1).operator bool(), true, "BigInt operator bool ( 1 )");
TEST_ASSERT_EQ(BINT(true, 24, 12, 99, 84, 239).operator bool(), true, "BigInt operator bool ( ... )");
auto a = BINT(true, 0);
TEST_ASSERT(a.sections.size()) && (a.sections.pop_back(), true) &&
TEST_ASSERT_EQ(a.operator bool(), false);
a.sections.push_back(0); TEST_ASSERT_EQ(a.operator bool(), false);
a.sections[0] = 1; TEST_ASSERT_EQ(a.operator bool(), true);
BINT_TEST_CMP(BINT(true, 0), BINT(true, 0), 0);
BINT_TEST_CMP(BINT(true, 0), BINT(false, 0), 0);
BINT_TEST_CMP(BINT(false, 0), BINT(true, 0), 0);
BINT_TEST_CMP(BINT(false, 0), BINT(false, 0), 0);
BINT_TEST_CMP(BINT(true, 42), BINT(true, 42), 0, "42 == 42?");
BINT_TEST_CMP(BINT(false, 42), BINT(false, 42), 0, "42 == 42?");
BINT_TEST_CMP(BINT(true, 42), BINT(false, 42), -1, "-42 < 42?");
BINT_TEST_CMP(BINT(false, 42), BINT(true, 42), 1, "42 > -42?");
BINT_TEST_CMP(BINT(true, 42), BINT(false, 0), -1, "-42 < 0?");
BINT_TEST_CMP(BINT(false, 42), BINT(false, 0), 1, "42 > 0?");
BINT_TEST_CMP(BINT(true, 42), BINT(true, 0), -1, "-42 < 0?");
BINT_TEST_CMP(BINT(false, 42), BINT(true, 0), 1, "42 > 0?");
BINT_TEST_CMP(BINT(true, 42), BINT(true, 41), -1, "-42 < -41?");
BINT_TEST_CMP(BINT(false, 42), BINT(false, 43), -1, "42 < 43?");
BINT_TEST_CMP(BINT(true, 42, 299, 384), BINT(true, 42, 299, 384), 0, "-42 299 384 == -42 299 384?");
BINT_TEST_CMP(BINT(false, 42, 299, 384), BINT(false, 42, 299, 384), 0, "+42 299 384 == +42 299 384?");
BINT_TEST_CMP(BINT(false, 41, 399, 389), BINT(false, 42, 299, 384), -1, "+41 399 389 < +42 299 384?");
BINT_TEST_CMP(BINT(true, 41, 399, 389), BINT(true, 42, 299, 384), 1, "-41 399 389 > -42 299 384?");
BINT_TEST_CMP(BINT(false, 42, 399, 383), BINT(false, 42, 299, 384), 1, "+42 399 383 > +42 299 384?");
BINT_TEST_CMP(BINT(false, 42, 299, 389), BINT(false, 42, 299, 384), 1, "+42 299 389 > +42 299 384?");
BINT_TEST_CMP(BigInt::pow2(229), BigInt::pow2(229), 0);
BINT_TEST_CMP(BigInt::pow2(230), BigInt::pow2(229), 1);
BINT_TEST_CMP(BigInt::pow2(229), BigInt::pow2(230), -1);
#undef BINT_TEST_CMP
#undef BINT
} UNITTEST_END_METHOD
BigInt operator * (const BigInt & v) {
// Zero case
if (!operator bool() || !v.operator bool()) {
return sections.clear(), *this;
}
// Otherwise, prepare to multiply, and reserve space for new digits
BigInt r; r.sections.resize(sections.size() + v.sections.size(), 0);
storage::smallInt_t carry;
for (auto i = 0; i < sections.size(); ++i) {
for (auto j = 0; j < v.sections.size(); ++j) {
auto p = (storage::bigInt_t)sections[i] * (storage::bigInt_t)v.sections[j] + (storage::bigInt_t)r.sections[i+j];
storage::storeIntParts(p, carry, r.sections[i+j]);
for (auto k = i+j+1; carry != 0; ++k) {
if (k > r.sections.size()) {
r.sections.push_back(carry); break;
} else {
auto s = (storage::bigInt_t)r.sections[k] + (storage::bigInt_t)carry;
storage::storeIntParts(s, carry, r.sections[k]);
}
}
}
}
return r;
}
static UNITTEST_METHOD(bigInt_mul) {
auto a = BigInt::pow2(39) * BigInt::pow2(78);
TEST_ASSERT_EQ(std::string(BigInt::pow2(117).toString()), "166153499473114484112975882535043072");
auto x = BigInt("92837508234109812317501984209810928409182094187192");
auto y = BigInt("19874891279817498172489713987498173849713897489171");
auto z = x * y;
auto zero = BigInt{0};
auto one = BigInt{1};
TEST_ASSERT_EQ(std::string(x.toString()), "92837508234109812317501984209810928409182094187192");
TEST_ASSERT_EQ(std::string(y.toString()), "19874891279817498172489713987498173849713897489171");
TEST_ASSERT_EQ(std::string(z.toString()), "18451353828420942924773305110003083474370975946120"
"06265189858865520503519713569495483976002866897832");
TEST_ASSERT_EQ(z, z);
TEST_ASSERT_EQ(z * 1, z);
TEST_ASSERT_EQ(z * 0, x * 0);
TEST_ASSERT_EQ(std::string((z * zero).toString()), "0");
TEST_ASSERT_EQ(z * one, z);
TEST_ASSERT_EQ(z * zero, zero);
} UNITTEST_END_METHOD
BigInt& operator += (const BigInt& v) {
// Zero case
if (!v) return *this;
sections.resize(std::max(sections.size(), v.sections.size()) + 1, 0);
storage::smallInt_t carry = 0;
auto i = 0;
for (; i < v.sections.size(); ++i) {
auto s = (storage::bigInt_t)sections[i] + (storage::bigInt_t)v.sections[i] + carry;
storage::storeIntParts(s, carry, sections[i]);
}
for (; carry && i < sections.size(); ++i) {
auto s = (storage::bigInt_t)sections[i] + carry;
storage::storeIntParts(s, carry, sections[i]);
}
if (carry) sections.push_back(carry);
return *this;
}
BigInt operator+ (const BigInt& v) const {
BigInt temp { *this };
temp += v;
return *this;
}
static UNITTEST_METHOD(bigInt_add) {
} UNITTEST_END_METHOD
static UNITTEST_METHOD(bigInt_sub) {
} UNITTEST_END_METHOD
static UNITTEST_METHOD(bigInt_div) {
} UNITTEST_END_METHOD
// Vector (BigInt * BigInt) Addition, Multiplication, Division TBD
// BigInt 2's complement negative numbers TBD
// BigInt comparison TBD
// Basic pow2 operation
static BigInt pow2 (unsigned n) {
BigInt x { 1 };
while (n > 0)
--n, x *= 2;
return x;
}
static UNITTEST_METHOD(pow2) {
TEST_ASSERT_EQ(std::string(BigInt::pow2(0).toString()), "1", "2^0");
TEST_ASSERT_EQ(std::string(BigInt::pow2(1).toString()), "2", "2^1");
TEST_ASSERT_EQ(std::string(BigInt::pow2(2).toString()), "4", "2^2");
TEST_ASSERT_EQ(std::string(BigInt::pow2(3).toString()), "8", "2^3");
TEST_ASSERT_EQ(std::string(BigInt::pow2(4).toString()), "16", "2^4");
TEST_ASSERT_EQ(std::string(BigInt::pow2(5).toString()), "32", "2^5");
TEST_ASSERT_EQ(std::string(BigInt::pow2(6).toString()), "64", "2^6");
TEST_ASSERT_EQ(std::string(BigInt::pow2(7).toString()), "128", "2^7");
TEST_ASSERT_EQ(std::string(BigInt::pow2(8).toString()), "256", "2^8");
TEST_ASSERT_EQ(std::string(BigInt::pow2(16).toString()), "65536", "2^16");
TEST_ASSERT_EQ(std::string(BigInt::pow2(32).toString()), "4294967296", "2^32");
TEST_ASSERT_EQ(std::string(BigInt::pow2(64).toString()), "18446744073709551616", "2^64");
TEST_ASSERT_EQ(std::string(BigInt::pow2(128).toString()), "340282366920938463463374607431768211456", "2^128");
TEST_ASSERT_EQ(std::string(BigInt::pow2(256).toString()),
"115792089237316195423570985008687907853269984665640564039457584007913129639936", "2^256");
TEST_ASSERT_EQ(std::string(BigInt::pow2(512).toString()),
"134078079299425970995740249982058461274793658205923933777235614437217640300735"
"46976801874298166903427690031858186486050853753882811946569946433649006084096", "2^512");
TEST_ASSERT_EQ(std::string(BigInt::pow2(1024).toString()),
"17976931348623159077293051907890247336179769789423065727343008115773267580550"
"09631327084773224075360211201138798713933576587897688144166224928474306394741"
"24377767893424865485276302219601246094119453082952085005768838150682342462881"
"473913110540827237163350510684586298239947245938479716304835356329624224137216", "2^1024");
} UNITTEST_END_METHOD
private:
std::vector<char> _tempStr;
public:
const char* toString () {
_tempStr.clear();
writeString(_tempStr);
_tempStr.push_back('\0');
return _tempStr.data();
}
static UNITTEST_MAIN_METHOD(BigInt) {
RUN_UNITTEST(scalarAdd, UNITTEST_INSTANCE) &&
RUN_UNITTEST(scalarMul, UNITTEST_INSTANCE) &&
RUN_UNITTEST(scalarDiv, UNITTEST_INSTANCE) &&
RUN_UNITTEST(scalarMultiplyAdd, UNITTEST_INSTANCE) &&
RUN_UNITTEST(pushDecimalDigit, UNITTEST_INSTANCE) &&
RUN_UNITTEST(initFromString, UNITTEST_INSTANCE) &&
RUN_UNITTEST(writeString, UNITTEST_INSTANCE) &&
RUN_UNITTEST(pow2, UNITTEST_INSTANCE) &&
RUN_UNITTEST(cmp, UNITTEST_INSTANCE) &&
RUN_UNITTEST(bigInt_mul, UNITTEST_INSTANCE) &&
RUN_UNITTEST(bigInt_add, UNITTEST_INSTANCE) &&
RUN_UNITTEST(bigInt_sub, UNITTEST_INSTANCE) &&
RUN_UNITTEST(bigInt_div, UNITTEST_INSTANCE);
} UNITTEST_END_METHOD
};
std::ostream& operator << (std::ostream& os, BigInt v) {
return os << v.toString();
}
bool runAllTests () {
return
RUN_UNITTEST_MAIN(storage) &&
RUN_UNITTEST_MAIN(BigInt);
}
int main(int argc, const char * argv[]) {
if (!runAllTests())
return -1;
auto x = BigInt { "-123456789123456789123456789123456789123456789" };
auto y = BigInt { "2" };
std::cout << "x = " << x << '\n';
std::cout << "y = " << y << '\n';
unsigned i = 0; auto v = BigInt { "1" };
while (i < 130) {
std::cout << "2^" << i << " = " << v << '\n';
v *= 2;
i += 1;
}
auto n = 32768; // 2^15; will calculate by bruteforcing x *= 2 n times.
std::cout << "2^" << n << " = " << BigInt::pow2(n) << '\n';
return 0;
}
| 41.08418 | 137 | 0.583354 | [
"vector"
] |
dd5e99d114e1aad97c7278769255ee2d937ecf60 | 1,879 | cpp | C++ | project1/game/GameStart.cpp | jojonium/IMGD-3000-Technical-Game-Development-I | f3d9da9ec3b21774633d13912b1a05c0035628c1 | [
"MIT"
] | null | null | null | project1/game/GameStart.cpp | jojonium/IMGD-3000-Technical-Game-Development-I | f3d9da9ec3b21774633d13912b1a05c0035628c1 | [
"MIT"
] | 3 | 2019-12-10T18:43:42.000Z | 2019-12-11T00:40:00.000Z | project1/game/GameStart.cpp | jojonium/IMGD-3000-Technical-Game-Development-I | f3d9da9ec3b21774633d13912b1a05c0035628c1 | [
"MIT"
] | null | null | null | //
// GameStart.cpp
//
// Engine includes
#include "LogManager.h"
#include "DisplayManager.h"
#include "EventKeyboard.h"
#include "GameManager.h"
#include "ResourceManager.h"
#include "Music.h"
// Game includes
#include "GameStart.h"
#include "Hero.h"
#include "Points.h"
#include "Boss.h"
#include "BossHealth.h"
GameStart::GameStart() {
// Set Type.
setType("GameStart");
// Set Sprite.
setSprite("gamestart");
// Set location to center of window
setLocation(df::CENTER_CENTER);
// Register our interest in keyboard events
registerInterest(df::KEYBOARD_EVENT);
// Get music and play it
p_music = RM.getMusic("start music");
playMusic();
}
// Handles keyboard events to either start or exit the game
int GameStart::eventHandler(const df::Event *p_e) {
if (p_e->getType() == df::KEYBOARD_EVENT) {
df::EventKeyboard *p_k_e = (df::EventKeyboard *) p_e;
switch (p_k_e->getKey()) {
case df::Keyboard::P: // play
start();
break;
case df::Keyboard::Q: // quit
GM.setGameOver();
break;
default:
break;
}
return 1;
}
return 0;
}
void GameStart::start() {
// Spawn 16 saucers for the start of the game
for (int i = 0; i < 16; ++i)
new Saucer;
// Spawn Boss TODO remove
new Boss;
// Spawn Hero
new Hero;
// Set up the points display
new Points;
// Set up the nuke display
df::ViewObject *p_vo = new df::ViewObject;
p_vo->setLocation(df::TOP_LEFT);
p_vo->setViewString("Nukes");
p_vo->setValue(1);
p_vo->setColor(df::YELLOW);
// Set up Boss Health display
new BossHealth;
// Pause music
p_music->pause();
// Become inactive when the game starts
setActive(false);
}
// Override default draw so as not to display "value".
int GameStart::draw() {
return df::Object::draw();
}
void GameStart::playMusic() {
p_music->play();
}
| 19.572917 | 59 | 0.645556 | [
"object"
] |
e577d683c19f3f9e22558c6c3ab28013e46899f7 | 3,926 | cpp | C++ | uut/math/uutVector3.cpp | kolyden/engine | cab1881a8493b591a136a5ce3d502e704fdea7bf | [
"Unlicense"
] | null | null | null | uut/math/uutVector3.cpp | kolyden/engine | cab1881a8493b591a136a5ce3d502e704fdea7bf | [
"Unlicense"
] | null | null | null | uut/math/uutVector3.cpp | kolyden/engine | cab1881a8493b591a136a5ce3d502e704fdea7bf | [
"Unlicense"
] | null | null | null | #include "uutVector3.h"
namespace uut
{
Vector3f Vector3f::cross(const Vector3f &p, const Vector3f &q)
{
return Vector3f((p.y * q.z) - (p.z * q.y),
(p.z * q.x) - (p.x * q.z),
(p.x * q.y) - (p.y * q.x));
}
float Vector3f::distance(const Vector3f &pt1, const Vector3f &pt2)
{
// Calculates the distance between 2 points.
return sqrtf(distanceSq(pt1, pt2));
}
float Vector3f::distanceSq(const Vector3f &pt1, const Vector3f &pt2)
{
// Calculates the squared distance between 2 points.
return ((pt1.x - pt2.x) * (pt1.x - pt2.x))
+ ((pt1.y - pt2.y) * (pt1.y - pt2.y))
+ ((pt1.z - pt2.z) * (pt1.z - pt2.z));
}
float Vector3f::dot(const Vector3f &p, const Vector3f &q)
{
return (p.x * q.x) + (p.y * q.y) + (p.z * q.z);
}
Vector3f Vector3f::lerp(const Vector3f &p, const Vector3f &q, float t)
{
// Linearly interpolates from 'p' to 'q' as t varies from 0 to 1.
return p + t * (q - p);
}
void Vector3f::orthogonalize(Vector3f &v1, Vector3f &v2)
{
// Performs Gram-Schmidt Orthogonalization on the 2 basis vectors to
// turn them into orthonormal basis vectors.
v2 = v2 - proj(v2, v1);
v2.normalize();
}
void Vector3f::orthogonalize(Vector3f &v1, Vector3f &v2, Vector3f &v3)
{
// Performs Gram-Schmidt Orthogonalization on the 3 basis vectors to
// turn them into orthonormal basis vectors.
v2 = v2 - proj(v2, v1);
v2.normalize();
v3 = v3 - proj(v3, v1) - proj(v3, v2);
v3.normalize();
}
Vector3f Vector3f::proj(const Vector3f &p, const Vector3f &q)
{
// Calculates the projection of 'p' onto 'q'.
float length = q.magnitude();
return (Vector3f::dot(p, q) / (length * length)) * q;
}
Vector3f Vector3f::perp(const Vector3f &p, const Vector3f &q)
{
// Calculates the component of 'p' perpendicular to 'q'.
float length = q.magnitude();
return p - ((Vector3f::dot(p, q) / (length * length)) * q);
}
Vector3f Vector3f::reflect(const Vector3f &i, const Vector3f &n)
{
// Calculates reflection vector from entering ray direction 'i'
// and surface normal 'n'.
return i - 2.0f * Vector3f::proj(i, n);
}
Vector3f::Vector3f(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {}
Vector3f &Vector3f::operator+=(const Vector3f &rhs)
{
x += rhs.x, y += rhs.y, z += rhs.z;
return *this;
}
bool Vector3f::operator==(const Vector3f &rhs) const
{
return Math::closeEnough(x, rhs.x) && Math::closeEnough(y, rhs.y)
&& Math::closeEnough(z, rhs.z);
}
bool Vector3f::operator!=(const Vector3f &rhs) const
{
return !(*this == rhs);
}
Vector3f &Vector3f::operator-=(const Vector3f &rhs)
{
x -= rhs.x, y -= rhs.y, z -= rhs.z;
return *this;
}
Vector3f &Vector3f::operator*=(float scalar)
{
x *= scalar, y *= scalar, z *= scalar;
return *this;
}
Vector3f &Vector3f::operator/=(float scalar)
{
x /= scalar, y /= scalar, z /= scalar;
return *this;
}
Vector3f Vector3f::operator+(const Vector3f &rhs) const
{
Vector3f tmp(*this);
tmp += rhs;
return tmp;
}
Vector3f Vector3f::operator-(const Vector3f &rhs) const
{
Vector3f tmp(*this);
tmp -= rhs;
return tmp;
}
Vector3f Vector3f::operator*(float scalar) const
{
return Vector3f(x * scalar, y * scalar, z * scalar);
}
Vector3f Vector3f::operator/(float scalar) const
{
return Vector3f(x / scalar, y / scalar, z / scalar);
}
float Vector3f::magnitude() const
{
return sqrtf((x * x) + (y * y) + (z * z));
}
float Vector3f::magnitudeSq() const
{
return (x * x) + (y * y) + (z * z);
}
Vector3f Vector3f::inverse() const
{
return Vector3f(-x, -y, -z);
}
void Vector3f::normalize()
{
float invMag = 1.0f / magnitude();
x *= invMag, y *= invMag, z *= invMag;
}
void Vector3f::set(float x_, float y_, float z_)
{
x = x_, y = y_, z = z_;
}
} | 23.939024 | 75 | 0.596026 | [
"vector"
] |
e57fee98c6dd0c3b9cdfae71f05b8f6c94cf5211 | 1,122 | cpp | C++ | ubb/pdp/exam/subject-2-2018/matrix.cpp | AlexanderChristian/private_courses | c80f3526af539e35f93b460f3909f669aaef573c | [
"MIT"
] | null | null | null | ubb/pdp/exam/subject-2-2018/matrix.cpp | AlexanderChristian/private_courses | c80f3526af539e35f93b460f3909f669aaef573c | [
"MIT"
] | 6 | 2020-03-04T20:52:39.000Z | 2022-03-31T00:33:07.000Z | ubb/pdp/exam/subject-2-2018/matrix.cpp | AlexanderChristian/private_courses | c80f3526af539e35f93b460f3909f669aaef573c | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <thread>
using namespace std;
int n;
vector <vector <int>> a, b, c;
inline void solve(int T) {
vector <thread> t;
for(int idx = 0; idx < T; ++ idx) {
t.push_back(thread([&, idx, T](){
for(int i = idx; i < n; i += T) {
for(int j = 0; j < n; ++ j) {
for(int k = 0; k < n; ++ k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}));
}
for(int i = 0; i < t.size(); ++ i) {
t[i].join();
}
}
int main() {
ifstream fin("input.in");
fin >> n;
for(int i = 0; i < n; ++ i) {
a.push_back(vector <int> ());
c.push_back(vector <int> ());
for(int j = 0; j < n; ++ j) {
int x;
fin >> x;
a.back().push_back(x);
c.back().push_back(0);
}
}
for(int i = 0; i < n; ++ i) {
b.push_back(vector <int>() );
for(int j = 0; j < n; ++ j) {
int x;
fin >> x;
b.back().push_back(x);
}
}
solve(5);
for(int i = 0; i < n; ++ i) {
for(int j = 0; j < n; ++ j) {
cerr << c[i][j] << ' ';
}
cerr << '\n';
}
}
| 17.809524 | 41 | 0.409982 | [
"vector"
] |
e595813529c6848a67d7c597082e11d021487fcc | 1,954 | hpp | C++ | B-SYN-400-LYN-4-1-abstractVM/include/checker.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 2 | 2022-02-07T12:44:51.000Z | 2022-02-08T12:04:08.000Z | B-SYN-400-LYN-4-1-abstractVM/include/checker.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | null | null | null | B-SYN-400-LYN-4-1-abstractVM/include/checker.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 1 | 2022-01-23T21:26:06.000Z | 2022-01-23T21:26:06.000Z | /*
** EPITECH PROJECT, 2021
** B-SYN-400-LYN-4-1-abstractVM-
** File description:
** checker
*/
#ifndef CHECKER_HPP
#define CHECKER_HPP
class checker
{
public:
checker();
~checker();
std::vector<std::string> _data;
bool check(std::string);
bool check_path(void);
bool check_exit(void);
bool load(void);
bool check_command(size_t);
bool check_type(size_t);
bool check_data(std::string, std::string);
bool number(std::string);
bool search_command(std::string, std::string, std::string);
bool search_type(std::string);
bool errors(std::string);
private:
std::vector<std::string> _command = {
"pop",
"dump",
"clear",
"dup",
"swap",
"add",
"sub",
"mul",
"div",
"mod",
"print",
"exit",
"push",
"assert",
"load",
"store",
";;"
};
std::vector<bool> _require = {
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
true,
true,
true,
true,
false
};
std::array<std::string, 6> _type = {
"int8",
"int16",
"int32",
"float",
"double",
"bigdecimal"
};
std::string _path = EMPTY;
};
#endif /* CHECKER_HP */
| 23.542169 | 71 | 0.352098 | [
"vector"
] |
e59e308dda633798f0d6a8a90552e3d69d47bc37 | 4,928 | cpp | C++ | dependencies/PyMesh/tools/Wires/Attributes/WireEdgePeriodicIndexAttribute.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | 5 | 2018-06-04T19:52:02.000Z | 2022-01-22T09:04:00.000Z | dependencies/PyMesh/tools/Wires/Attributes/WireEdgePeriodicIndexAttribute.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | dependencies/PyMesh/tools/Wires/Attributes/WireEdgePeriodicIndexAttribute.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | /* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */
#include "WireEdgePeriodicIndexAttribute.h"
#include <functional>
#include <list>
#include <Misc/Triplet.h>
#include <Misc/TripletMap.h>
#include <Misc/HashGrid.h>
#include <Wires/WireNetwork/WireNetwork.h>
using namespace PyMesh;
namespace WireEdgePeriodicIndexAttributeHelper {
typedef std::list<std::function<VectorF(const VectorF&)> > FunctionList;
FunctionList get_periodic_transforms(const VectorF& bbox_size) {
const size_t dim = bbox_size.size();
FunctionList transforms;
if (dim == 2) {
Vector2F step[] = {
Vector2F(bbox_size[0], 0.0),
Vector2F(0.0, bbox_size[1])
};
transforms.push_back([=](const VectorF& v) { return v+step[0]; });
transforms.push_back([=](const VectorF& v) { return v+step[1]; });
} else if (dim == 3) {
Vector3F step[] = {
Vector3F( bbox_size[0], 0.0, 0.0),
Vector3F( 0.0, bbox_size[1], 0.0),
Vector3F( 0.0, 0.0, bbox_size[2]),
Vector3F( bbox_size[0], bbox_size[1], 0.0),
Vector3F(-bbox_size[0], bbox_size[1], 0.0),
Vector3F( bbox_size[0], 0.0,-bbox_size[2]),
Vector3F( bbox_size[0], 0.0, bbox_size[2]),
Vector3F( 0.0,-bbox_size[1], bbox_size[2]),
Vector3F( 0.0, bbox_size[1], bbox_size[2])
};
transforms.push_back([=](const VectorF& v) { return v+step[0]; });
transforms.push_back([=](const VectorF& v) { return v+step[1]; });
transforms.push_back([=](const VectorF& v) { return v+step[2]; });
transforms.push_back([=](const VectorF& v) { return v+step[3]; });
transforms.push_back([=](const VectorF& v) { return v+step[4]; });
transforms.push_back([=](const VectorF& v) { return v+step[5]; });
transforms.push_back([=](const VectorF& v) { return v+step[6]; });
transforms.push_back([=](const VectorF& v) { return v+step[7]; });
transforms.push_back([=](const VectorF& v) { return v+step[8]; });
} else {
std::stringstream err_msg;
err_msg << "Unsupported dimension: " << dim;
throw NotImplementedError(err_msg.str());
}
return transforms;
}
}
using namespace WireEdgePeriodicIndexAttributeHelper;
void WireEdgePeriodicIndexAttribute::compute(const WireNetwork& network) {
const Float EPS = 1e-6;
const size_t num_vertices = network.get_num_vertices();
const size_t num_edges = network.get_num_edges();
const MatrixFr& vertices = network.get_vertices();
const MatrixIr& edges = network.get_edges();
const VectorF bbox_min = vertices.colwise().minCoeff();
const VectorF bbox_max = vertices.colwise().maxCoeff();
const VectorF bbox_size = bbox_max - bbox_min;
std::vector<bool> on_min_border(num_vertices, false);
HashGrid::Ptr grid = HashGrid::create(EPS, network.get_dim());
for (size_t i=0; i<num_vertices; i++) {
const VectorF& v = vertices.row(i);
grid->insert(i, v);
if ((v-bbox_min).cwiseAbs().minCoeff() < EPS) {
on_min_border[i] = true;
}
}
m_values.resize(num_edges, 1);
TripletMap<size_t> edge_map;
for (size_t i=0; i<num_edges; i++) {
const VectorI& edge = edges.row(i);
Triplet trip(edge[0], edge[1]);
edge_map.insert(trip, i);
m_values(i, 0) = i;
}
FunctionList transforms = get_periodic_transforms(bbox_size);
for (auto transform : transforms) {
for (size_t i=0; i<num_edges; i++) {
const VectorI& edge = edges.row(i);
if (on_min_border[edge[0]] || on_min_border[edge[1]]) {
VectorF v0 = transform(vertices.row(edge[0]));
VectorF v1 = transform(vertices.row(edge[1]));
VectorI opposite_v0_index = grid->get_items_near_point(v0);
VectorI opposite_v1_index = grid->get_items_near_point(v1);
if (opposite_v0_index.size() != 1 ||
opposite_v1_index.size() != 1) { continue; }
Triplet trip(opposite_v0_index[0], opposite_v1_index[0]);
auto itr = edge_map.find(trip);
if (itr != edge_map.end()) {
if (itr->second.size() != 1) {
throw RuntimeError("Duplicated edge detected");
}
size_t j = itr->second[0];
size_t label = std::min(m_values(i, 0), m_values(j, 0));
m_values(i, 0) = label;
m_values(j, 0) = label;
}
}
}
}
}
| 40.727273 | 78 | 0.552557 | [
"vector",
"transform"
] |
e5a9b38835e4b367b38d15b3fc56ed8fb6f84343 | 3,551 | cpp | C++ | example/demo_1d_vector.cpp | pabristow/svg_plot | 59e06b752acc252498e0ddff560b01fb951cb909 | [
"BSL-1.0"
] | 24 | 2016-03-09T03:23:06.000Z | 2021-01-12T14:02:07.000Z | example/demo_1d_vector.cpp | pabristow/svg_plot | 59e06b752acc252498e0ddff560b01fb951cb909 | [
"BSL-1.0"
] | 11 | 2018-03-05T14:39:48.000Z | 2021-08-22T09:00:33.000Z | example/demo_1d_vector.cpp | pabristow/svg_plot | 59e06b752acc252498e0ddff560b01fb951cb909 | [
"BSL-1.0"
] | 10 | 2016-11-04T14:36:04.000Z | 2020-07-17T08:12:03.000Z | /*! \file demo_1d_vector.cpp
\brief Simple plot of vector of 1D data.
\details An example to demonstrate simple 1D plot using two vectors,
see also demo_1d_containers for examples using other STL containers.
\author Jacob Voytko & Paul A. Bristow
\date Feb 2009
*/
// Copyright Jacob Voytko 2007
// Copyright Paul A Bristow 2008, 2009
// 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)
// This file is written to be included from a Quickbook .qbk document.
// It can be compiled by the C++ compiler, and run. Any output can
// also be added here as comment or included or pasted in elsewhere.
// Caution: this file contains Quickbook markup as well as code
// and comments: don't change any of the special comment markups!
//[demo_1d_vector_1
/*`First we need a few includes to use Boost.Plot:
*/
#include <boost/svg_plot/svg_1d_plot.hpp>
using namespace boost::svg;
#include <vector>
using std::vector;
//] [/demo_1d_vector_1]
int main()
{
//[demo_1d_vector_2
/*`STL vector is used as the container for our two data series,
and values are inserted using push_back. Since this is a 1-D plot
the order of data values is not important.
*/
vector<double> dan_times;
dan_times.push_back(3.1);
dan_times.push_back(4.2);
vector<double> elaine_times;
elaine_times.push_back(2.1);
elaine_times.push_back(7.8);
/*`The constructor initializes a new 1D plot, called `my_plot`, and also sets all the very many defaults for axes, width, colors, etc.
*/
svg_1d_plot my_plot;
/*`A few (member) functions that set are fairly self-explanatory:
* title provides a title at the top for the whole plot,
* `legend_on(true)` will mean that titles of data series and markers will display in the legend box.
* `x_range(-1, 11)` sets the axis limits from -1 to +11 (instead of the default -10 to +10).
* `background_border_color(blue)` sets just one of the very many options.
*/
my_plot.background_border_color(blue)
.legend_on(true)
.title("Race Times")
.x_range(-1, 11);
my_plot.legend_lines(true);
/*`The syntax `my_plot.title("Hello").legend_on(true)...` may appear unfamiliar,
but is a convenient way of specifying many parameters in any order. It is equivalent to:
``
my_plot.title("Race Times");
my_plot.legend_on(true);
my_plot.x_range(-1, 11);
my_plot.background_border_color(blue);
``
Chaining thus allows you to avoid repeatedly typing "`myplot.`"
and easily group related settings like plot window, axes ... together.
A fixed order would clearly become impracticable with
hundreds of possible arguments needed to set all the myriad plot options.
Within all of the plot classes, 'chaining' works the same way,
by returning a reference to the calling object thus `return *this;`
Then we need to add our data series,
and add optional (but very helpful) data series titles
if we want them to show on the legend.
*/
my_plot.plot(dan_times, "Dan").shape(circlet).size(10).stroke_color(red).fill_color(green);
my_plot.plot(elaine_times, "Elaine").shape(vertical_line).stroke_color(blue);
/*`Finally, we can write the SVG to a file of our choice.
*/
my_plot.write("./demo_1d_vector.svg");
//] [/demo_1d_vector_2]
return 0;
} // int main()
/*
Output:
//[demo_1d_vector_output
Compiling...
demo_1d_vector.cpp
Linking...
Embedding manifest...
Autorun "j:\Cpp\SVG\debug\demo_1d_vector.exe"
Build Time 0:04
//] [/demo_1d_vector_output]
*/
| 30.878261 | 135 | 0.736694 | [
"object",
"shape",
"vector"
] |
e5ae13ad746f93c60bf7f1e77bcab2aea65fd8a9 | 636 | cpp | C++ | src/gui/glwidget.cpp | sstanfield/hexGame | 99edad55703846992d3f64ad4cf9d146d57ca625 | [
"Zlib"
] | null | null | null | src/gui/glwidget.cpp | sstanfield/hexGame | 99edad55703846992d3f64ad4cf9d146d57ca625 | [
"Zlib"
] | null | null | null | src/gui/glwidget.cpp | sstanfield/hexGame | 99edad55703846992d3f64ad4cf9d146d57ca625 | [
"Zlib"
] | null | null | null | #include "glwidget.h"
#include "render/gl_util.h"
namespace hexgame {
namespace gui {
GLWidget::GLWidget() {
tb::g_renderer->AddListener(this);
}
GLWidget::~GLWidget() {
tb::g_renderer->RemoveListener(this);
}
void GLWidget::OnPaint(const PaintProps &paint_props) {
if (!init) {
initGL();
init = true;
}
GLint v[4];
glGetIntegerv(GL_VIEWPORT, v);
int dx, dy;
tb::g_renderer->GetTranslate(&dx, &dy);
tb::g_renderer->BeginNativeRender();
tb::TBRect r = GetRect();
tb::TBRect padr = GetPaddingRect();
glViewport(dx+padr.x, (v[3]-(dy+r.h))+padr.y, padr.w, padr.h);
render();
tb::g_renderer->EndNativeRender();
}
}
}
| 18.171429 | 63 | 0.672956 | [
"render"
] |
e5afd4b1b63868ecb04e9f6ca381e1c7b4fdcf1c | 2,460 | cpp | C++ | uhk/acm2819.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm2819.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm2819.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
using namespace std;
const int INF = 2147483640;
typedef long long ll;
const int maxn1 = 100 + 10;
const int maxn2 = 110;
struct HC
{
vector<int>G[maxn1];
int uN;
int Mx[maxn1], My[maxn2];
int dx[maxn1], dy[maxn2];
int dist;
bool visit[maxn2];
void init()
{
for (int i = 0; i <= uN; i++)
G[i].clear();
}
void addedge(int u, int v)
{
G[u].push_back(v);
}
bool SearchP()
{
queue<int>Q;
dist = INF;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
for (int i = 1; i <= uN; i++)
{
if (Mx[i] == -1)
{
Q.push(i);
dx[i] = 0;
}
}
while (!Q.empty())
{
int u = Q.front();
Q.pop();
if (dx[u] > dist)
break;
int sz = G[u].size();
for (int i = 0; i < sz; i++)
{
int v = G[u][i];
if (dy[v] == -1)
{
dy[v] = dx[u] + 1;
if (My[v] == -1)
dist = dy[v];
else
{
dx[My[v]] = dy[v] + 1;
Q.push(My[v]);
}
}
}
}
return dist != INF;
}
bool dfs(int u)
{
int sz = G[u].size();
for (int i = 0; i < sz; i++)
{
int v = G[u][i];
if (!visit[v] && dy[v] == dx[u] + 1)
{
visit[v] = true;
if (My[v] != -1 && dy[v] == dist)
continue;
if (My[v] == -1 || dfs(My[v]))
{
My[v] = u;
Mx[u] = v;
return true;
}
}
}
return false;
}
int MaxMatch()
{
int res = 0;
memset(Mx, -1, sizeof(Mx));
memset(My, -1, sizeof(My));
while (SearchP())
{
memset(visit, false, sizeof(visit));
for (int i = 1; i <= uN; i++)
{
if (Mx[i] == -1 && dfs(i))
res++;
}
}
return res;
}
};
HC hop;
//要先给uN赋值
//初始化hop.init()
int a[maxn1], b[maxn2];
int main()
{
int i, j, k, u, n, m;
while (scanf("%d", &n) != EOF)
{
hop.init();
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
scanf("%d", &u);
if (u)
{
hop.addedge(i, j);
}
}
}
hop.uN = n;
if (hop.MaxMatch() == n)
{
int res = 0;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n && hop.Mx[j] != i; j++);
if (i != j)
{
res++;
a[res] = i;
b[res] = j;
swap(hop.Mx[i], hop.Mx[j]);
}
}
// if (res > 1000)
// {
// printf("-1\n");
// continue;
// }
printf("%d\n", res);
for (i = 1; i <= res; i++)
{
printf("R %d %d\n", a[i], b[i]);
}
}
else
printf("-1\n");
}
return 0;
} | 15.56962 | 47 | 0.433333 | [
"vector"
] |
e5b2d5db4dbed4cf5af975ed08ed874bc0190c7e | 1,005 | cpp | C++ | src/libs/xmlutil/sc_xmltransformer.cpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | src/libs/xmlutil/sc_xmltransformer.cpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | src/libs/xmlutil/sc_xmltransformer.cpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | //#############################
#include "sc_xmltransformer.hpp"
#include <si_macros.hpp>
using rpms::SC_XMLTransformer;
///////////////////////////////////////////
SC_XMLTransformer::SC_XMLTransformer( const std::string &aXMLToTransform )
: SA_XMLDocument(), mXML(aXMLToTransform)
{
TRY(SC_XMLTransformer( const std::string &aXMLToTransform ));
CATCH;
}
///////////////////////////////////////////
SC_XMLTransformer::~SC_XMLTransformer()
{
TRY(SC_XMLTransformer::~SC_XMLTransformer());
CATCH;
}
///////////////////////////////////////////
void SC_XMLTransformer::load()
{
TRY(SC_XMLTransformer::load());
createTreeFromString(mXML);
CATCH;
}
///////////////////////////////////////////
void SC_XMLTransformer::debug() const
{
}
bool SC_XMLTransformer::transform( const std::string &aXSLPath )
{
TRY(SC_XMLTransformer::transform(const std::string &aXSLPath ));
return transformDoc(aXSLPath);
CATCH;
}
///////////////////////////////////////////
| 22.840909 | 74 | 0.538308 | [
"transform"
] |
e5b8ff9e3ac05141280264b52c821b393e3ed940 | 1,751 | cpp | C++ | VoiceBridge/VoiceBridge/kaldi-win/src/bin/am-info.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 18 | 2018-02-15T03:14:32.000Z | 2021-07-06T08:21:13.000Z | VoiceBridge/VoiceBridge/kaldi-win/src/bin/am-info.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 3 | 2020-10-25T16:35:55.000Z | 2020-10-26T04:59:46.000Z | VoiceBridge/VoiceBridge/kaldi-win/src/bin/am-info.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 7 | 2018-09-16T20:40:17.000Z | 2021-07-06T08:21:14.000Z | /*
Copyright 2017-present Zoltan Somogyi (AI-TOOLKIT), All Rights Reserved
You may use this file only if you agree to the software license:
AI-TOOLKIT Open Source Software License - Version 2.1 - February 22, 2018:
https://ai-toolkit.blogspot.com/p/ai-toolkit-open-source-software-license.html.
Also included with the source code distribution in AI-TOOLKIT-LICENSE.txt.
Based on : Copyright 2012-2013 Johns Hopkins University (Author: Daniel Povey), Apache 2.0
See ../../COPYING for clarification regarding multiple authors
*/
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "gmm/am-diag-gmm.h"
#include "hmm/transition-model.h"
#include "kaldi-win/src/kaldi_src.h"
//various properties of a model, of any type
int AmInfo(std::string model_in_filename,
int & nofphones,
int & nofpdfs,
int & noftransitionids,
int & noftransitionstates
) {
try {
using namespace kaldi;
typedef kaldi::int32 int32;
TransitionModel trans_model;
{
bool binary_read;
Input ki(model_in_filename, &binary_read);
trans_model.Read(ki.Stream(), binary_read);
}
KALDI_LOG << "number of phones " << trans_model.GetPhones().size() << '\n';
KALDI_LOG << "number of pdfs " << trans_model.NumPdfs() << '\n';
KALDI_LOG << "number of transition-ids " << trans_model.NumTransitionIds()
<< '\n';
KALDI_LOG << "number of transition-states "
<< trans_model.NumTransitionStates() << '\n';
nofphones = trans_model.GetPhones().size();
nofpdfs = trans_model.NumPdfs();
noftransitionids = trans_model.NumTransitionIds();
noftransitionstates = trans_model.NumTransitionStates();
return 0;
} catch(const std::exception &e) {
KALDI_ERR << e.what();
return -1;
}
}
| 31.267857 | 91 | 0.703027 | [
"model"
] |
e5ba2d85272782131d51843a1396b64d1f121cc8 | 8,315 | hpp | C++ | include/RAIIGen/Generator/Simple/SimpleGeneratorConfig.hpp | Unarmed1000/RAIIGen | 2516ab5949c1fb54ca1b6e51e5e99e15ecfebbfb | [
"BSD-3-Clause"
] | 8 | 2016-11-02T14:08:51.000Z | 2021-03-25T02:00:00.000Z | include/RAIIGen/Generator/Simple/SimpleGeneratorConfig.hpp | Unarmed1000/RAIIGen | 2516ab5949c1fb54ca1b6e51e5e99e15ecfebbfb | [
"BSD-3-Clause"
] | 4 | 2016-08-23T12:37:17.000Z | 2016-09-30T01:58:20.000Z | include/RAIIGen/Generator/Simple/SimpleGeneratorConfig.hpp | Unarmed1000/RAIIGen | 2516ab5949c1fb54ca1b6e51e5e99e15ecfebbfb | [
"BSD-3-Clause"
] | null | null | null | #ifndef MB_GENERATOR_SIMPLE_SIMPLEGENERATORCONFIG_HPP
#define MB_GENERATOR_SIMPLE_SIMPLEGENERATORCONFIG_HPP
//***************************************************************************************************************************************************
//* BSD 3-Clause License
//*
//* Copyright (c) 2016, Rene Thrane
//* All rights reserved.
//*
//* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//*
//* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
//* documentation and/or other materials provided with the distribution.
//* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
//* software without specific prior written permission.
//*
//* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//***************************************************************************************************************************************************
#include <RAIIGen/Generator/BlackListEntry.hpp>
#include <RAIIGen/Generator/ClassFunctionAbsorb.hpp>
#include <RAIIGen/Generator/FunctionGuard.hpp>
#include <RAIIGen/Generator/GeneratorConfig.hpp>
#include <RAIIGen/Generator/RAIIClassCustomization.hpp>
#include <RAIIGen/Generator/RAIIClassMethodOverrides.hpp>
#include <RAIIGen/Generator/Simple/VersionGuardConfig.hpp>
#include <RAIIGen/Generator/TypeNameAliasEntry.hpp>
#include <unordered_map>
namespace MB
{
struct SimpleGeneratorConfig : public GeneratorConfig
{
const std::vector<RAIIClassCustomization> RAIIClassCustomizations;
const std::vector<ClassFunctionAbsorb> ClassFunctionAbsorbtion;
const std::unordered_map<std::string, RAIIClassMethodOverrides> ClassMethodOverrides;
const std::unordered_map<std::string, std::string> TypeDefaultValues;
const std::vector<std::string> ForceNullParameter;
const std::vector<FunctionGuard> FunctionGuards;
const std::vector<BlackListEntry> FunctionNameBlacklist;
const std::vector<BlackListEntry> EnumNameBlacklist;
const std::vector<BlackListEntry> EnumMemberBlacklist;
const std::unordered_map<std::string, std::string> TypeNameAliases;
const std::string TypeNamePrefix;
const std::string FunctionNamePrefix;
const std::string ErrorCodeTypeName;
const bool UnrollCreateStructs;
const bool OwnershipTransferUseClaimMode;
const VersionGuardConfig VersionGuard;
const bool IsVulkan;
SimpleGeneratorConfig()
: UnrollCreateStructs(false)
, OwnershipTransferUseClaimMode(false)
, IsVulkan(false)
, VersionGuard()
{
}
SimpleGeneratorConfig(const GeneratorConfig& config, const std::vector<RAIIClassCustomization>& raiiClassCustomizations,
const std::vector<ClassFunctionAbsorb>& classFunctionAbsorbtion,
const std::unordered_map<std::string, RAIIClassMethodOverrides> classMethodOverrides,
const std::unordered_map<std::string, std::string>& typeDefaultValues, const std::vector<std::string>& forceNullParameter,
const std::vector<FunctionGuard>& functionGuards, const std::vector<BlackListEntry>& functionNameBlacklist,
const std::vector<BlackListEntry>& enumNameBlacklist, const std::vector<BlackListEntry>& enumMemberBlacklist,
const std::vector<TypeNameAliasEntry>& typeNameAliases,
const std::string& typeNamePrefix, const std::string& functionNamePrefix, const std::string& errorCodeTypeName,
const bool unrollCreateStructs, const bool ownershipTransferUseClaimMode,
const VersionGuardConfig versionGuard = VersionGuardConfig(), const bool isVulkan = false)
: GeneratorConfig(config)
, RAIIClassCustomizations(raiiClassCustomizations)
, ClassFunctionAbsorbtion(classFunctionAbsorbtion)
, ClassMethodOverrides(classMethodOverrides)
, TypeDefaultValues(typeDefaultValues)
, ForceNullParameter(forceNullParameter)
, FunctionGuards(functionGuards)
, FunctionNameBlacklist(functionNameBlacklist)
, EnumNameBlacklist(enumNameBlacklist)
, EnumMemberBlacklist(enumMemberBlacklist)
, TypeNameAliases(GenerateAliases(typeNameAliases))
, TypeNamePrefix(typeNamePrefix)
, FunctionNamePrefix(functionNamePrefix)
, ErrorCodeTypeName(errorCodeTypeName)
, UnrollCreateStructs(unrollCreateStructs)
, OwnershipTransferUseClaimMode(ownershipTransferUseClaimMode)
, VersionGuard(versionGuard)
, IsVulkan(isVulkan)
{
}
SimpleGeneratorConfig(const BasicConfig& basicConfig, const std::vector<FunctionNamePair>& functionPairs,
const std::vector<FunctionNamePair>& manualFunctionMatches,
const std::vector<RAIIClassCustomization>& raiiClassCustomizations,
const std::vector<ClassFunctionAbsorb>& classFunctionAbsorbtion,
const std::unordered_map<std::string, RAIIClassMethodOverrides> classMethodOverrides,
const std::unordered_map<std::string, std::string>& typeDefaultValues, const std::vector<std::string>& forceNullParameter,
const std::vector<FunctionGuard>& functionGuards, const std::vector<BlackListEntry>& functionNameBlacklist,
const std::vector<BlackListEntry>& enumNameBlacklist, const std::vector<BlackListEntry>& enumMemberBlacklist,
const std::vector<TypeNameAliasEntry>& typeNameAliases, const std::string& typeNamePrefix,
const std::string& functionNamePrefix, const std::string& errorCodeTypeName,
const bool unrollCreateStructs, const bool ownershipTransferUseClaimMode,
const VersionGuardConfig versionGuard = VersionGuardConfig(), const bool isVulkan = false)
: GeneratorConfig(basicConfig, functionPairs, manualFunctionMatches)
, RAIIClassCustomizations(raiiClassCustomizations)
, ClassFunctionAbsorbtion(classFunctionAbsorbtion)
, ClassMethodOverrides(classMethodOverrides)
, TypeDefaultValues(typeDefaultValues)
, ForceNullParameter(forceNullParameter)
, FunctionGuards(functionGuards)
, FunctionNameBlacklist(functionNameBlacklist)
, EnumNameBlacklist(enumNameBlacklist)
, EnumMemberBlacklist(enumMemberBlacklist)
, TypeNameAliases(GenerateAliases(typeNameAliases))
, TypeNamePrefix(typeNamePrefix)
, FunctionNamePrefix(functionNamePrefix)
, ErrorCodeTypeName(errorCodeTypeName)
, UnrollCreateStructs(unrollCreateStructs)
, OwnershipTransferUseClaimMode(ownershipTransferUseClaimMode)
, VersionGuard(versionGuard)
, IsVulkan(isVulkan)
{
}
static std::unordered_map<std::string, std::string> GenerateAliases(const std::vector<TypeNameAliasEntry>& typeNameAliases)
{
std::unordered_map<std::string, std::string> result(typeNameAliases.size() * 2);
for (auto& rEntry : typeNameAliases)
{
result[rEntry.Name0] = rEntry.Name1;
result[rEntry.Name1] = rEntry.Name0;
}
return result;
}
};
}
#endif
| 57.743056 | 149 | 0.706434 | [
"vector"
] |
e5c8518e625fc7fe338f3bcb55cc9a739b550cb1 | 11,408 | cpp | C++ | Player.cpp | OrA27/Monopoly | b057ad3de4eb2cdc5897446d417646c2034fb6ad | [
"MIT"
] | null | null | null | Player.cpp | OrA27/Monopoly | b057ad3de4eb2cdc5897446d417646c2034fb6ad | [
"MIT"
] | null | null | null | Player.cpp | OrA27/Monopoly | b057ad3de4eb2cdc5897446d417646c2034fb6ad | [
"MIT"
] | null | null | null | #include "Player.h"
/// <summary>
/// constructs player object
/// </summary>
/// <param name="name">name of player</param>
/// <param name="start">starting position of player</param>
Player::Player(string name, Slot* start)
{
this->setName(name);
balance = 0;
this->setLoc(start);
in_jail = false;
}
/// <summary>
/// copying constructor for player
/// </summary>
/// <param name=""></param>
Player::Player(const Player& other)
{
*this = other;
}
/// <summary>
/// destructor for player
/// </summary>
Player::~Player()
{
#ifdef DEBUG
cout << this->p_name << " was removed from the game" << endl;
p_name = "";
balance = 0;
location = nullptr;
#endif // DEBUG
}
Player& Player::operator=(const Player& other)
{
throw COPY PLAYER;
}
/// <summary>
/// sets the name of the player
/// </summary>
/// <param name="name">name of player</param>
/// <returns>void</returns>
void Player::setName(const string& name) throw(string)
{
if (name == "") { throw STRING PLAYER "setName"; }
p_name = name;
}
/// <summary>
/// sets the player's location on the slots
/// </summary>
/// <param name="local">slot the player will step into</param>
/// <returns>void</returns>
void Player::setLoc(Slot* local) throw(string)
{
if (&local == nullptr) { throw ADDRESS PLAYER "setLoc"; }
location = local;
}
/// <summary>
/// sets the balance of the player to a fixed number
/// </summary>
/// <param name="b">amount of money in player's balance</param>
/// <returns>void</returns>
void Player::setBalance(int b)
{
// no need for (b < 0) Error since it indicates a loss
balance = b;
}
/// <summary>
/// changes the balance of the player
/// and place properties of it in or out of mortgages
/// depending on the value
/// </summary>
/// <param name="change">amount of money to be added\subtracted</param>
/// <returns>bool</returns>
bool Player::changeBalance(int change) throw(string)
{
if (change > 0)
{
cout << this->getName() << " received " << change << " NIS" << endl;
this->setBalance(this->balance + change); // adds the change to balance
vector<Asset*>::iterator iter; // create an appropriate iterator
int payout = 0;
for (iter = owned.begin(); iter != owned.end(); iter++) // go over asset vector
{
//calculate the amount of money needed to pay the mortgage
payout = round((*iter)->getMortgage() * INTEREST * (*iter)->getPPrice());
if (payout > 0 && this->balance > payout) // check if it's possible to pay it
{
this->payMortgage(**iter, payout);
}
}
cout << this->getName() << " now has " << this->balance << " NIS" << endl;
return true;
}
else if (change < 0) { return pawn(change); } // if player needs to be charged go to pawn method
else { return true; } // value is 0 and therefor invalid
}
/// <summary>
/// Player pays out mortgage of specific Asset he owns
/// </summary>
/// <param name="prprty">the asset player is paying out</param>
/// <param name="payout">the amount of money needs to be payed</param>
/// <returns>void</returns>
void Player::payMortgage(Asset& prprty, int payout)
{
if (prprty.getOwner() != this) { throw MIX PLAYER "in payMortgage"; } // asset owner is not current player
this->setBalance(this->balance - payout); // pay the mortgage
prprty.setMortgage(0); // remove mortgage from asset
cout << prprty.getMainName() << " at " << prprty.getName() << " mortgage has been paid" << endl;
}
/// <summary>
/// pawns player buildings until it can pay the change
/// </summary>
/// <param name="change">the amount of money needs to be payed</param>
/// <returns>bool</returns>
bool Player::pawn(int change)
{
vector<Asset*>::iterator iter; // appropriate iterator
//loop as long as iterator has not reached the end and balance is not enough for the change
cout << this->getName() << " needs to pay " << -1 * change << " NIS" << endl;
for (iter = owned.begin(); iter != owned.end() && this->balance < abs(change); iter++)
{
if ((*iter)->getMortgage() == 0) // check if house is not mortgaged
{
(*iter)->setMortgage(1); // pawn the house
this->setBalance(this->balance + (*iter)->getPPrice()); // give player some money
//notify of asset being pawned
cout << (*iter)->getMainName() << " at " << (*iter)->getName()
<< " has been pawned due to lack of funds" << endl;
}
}
if (this->balance > abs(change)) // check in case all assets have been pawned
{
this->setBalance(this->balance + change); // remove change (which is negative) from balance
cout << this->getName() << " now has " << this->balance << " NIS left" << endl;
return true;
}
cout << "sadly, " << this->getName() << " has no money and no Active Assets left" << endl;
return false;
}
/// <summary>
/// set an Asset as owned by the player
/// and adds it to the player owned Assets
/// </summary>
/// <param name="prprty">the asset to be bought\owned</param>
void Player::buyProperty(Asset& prprty)
{
int price = prprty.getPPrice();
if (this->balance >= price) // player can afford asset
{
this->setBalance(this->balance - price); // pay for it
prprty.setOwner(*this); // set player as owner
this->owned.push_back(&prprty); // add asset to owned vector
cout << this->getName() << " successfully bought the property for "
<< price << " NIS and now has " << this->balance << " NIS left" << endl;
}
else // player can't afford
{
cout << this->getName() << " could not buy the property - not enough money" << endl; //notify player
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
void Player::quit()
{
vector<Asset*>::iterator it;
for (it = this->owned.begin(); it != this->owned.end(); it++) // go over owned assets
{
(*it)->release(); // releases them from player
}
this->owned.clear(); // clears owned asset vector
}
/// <summary>
/// moving logic of a player
/// </summary>
/// <param name="the_board">give access to the board of the game</param>
void Player::move(vector<Slot*>& the_board)
{
int dice = 1, i = 0;
//set iterator to current location of player
vector<Slot*>::iterator it = find(the_board.begin(),the_board.end(),this->location);
int idx_e, idx_s = distance(the_board.begin(), it); //get index of location on board
this->printLoc(idx_s); // print location
dice = (rand() % 6) + 1; // roll a number between 1-6
cout << this->p_name << " rolled a " << dice << endl; // notify dice value
it = the_board.begin() + ((idx_s + dice) % the_board.size()); // update location
if (idx_s > (idx_e = distance(the_board.begin(), it))) // check if completed a full circle
{
this->changeBalance(BASE); // add 350 to player balance
this->increaseMortgage(); // self explanatory
}
this->location = *it; // set new location of player
this->printLoc(idx_e); // print new location of player
}
/// <summary>
/// increases mortgage on all pawned assets of the player
/// </summary>
void Player::increaseMortgage()
{
vector<Asset*>::iterator a_it;
int mort; // int to call the getMortgage function n times and not 2n times
for (a_it = owned.begin(); a_it != owned.end(); a_it++) // go over player assets
{
mort = (*a_it)->getMortgage(); // self explanatory
if (mort > 0) // if mortgage is over 0
{
(*a_it)->setMortgage(mort + 1); //increases mortgage by 1
}
}
}
/// <summary>
/// prints location of player
/// </summary>
/// <param name="idx">index of location on the board vector</param>
void Player::printLoc(int idx) const
{
cout << this->p_name <<" is on slot No." << idx + 1 << " "; // idx is increased by 1 because it starts from 0
this->location->print(); // print location data
cout << endl;
}
/// <summary>
/// logic of asset tiles
/// </summary>
/// <returns>bool</returns>
bool Player::asset()
{
Asset* tile = static_cast<Asset*>(this->location);
bool opt = false;
if (!tile->getOwner()) // if asset has no owner
{
#ifndef DEBUG
cout << "would you like to buy it for "
<< tile->getPPrice() <<"? (yes=1:no=0)" << endl;
cin >> opt;
#else
opt = true;
#endif
if (opt) { this->buyProperty(*tile); } // attempt to buy the house;
return true;
}
else if(tile->getOwner() != this)
{
cout << "''hi " << this->p_name << " enjoy your stay in our humble estate''"<< endl;
int rent = tile->getRPrice(); // get the rent price of the asset
opt = this->changeBalance(-1 * rent); // player tries to pay
if (tile->getMortgage()) { return opt; } // if house is pawned just return result of opt
if (!opt) { rent = this->balance; } // if player failed to pay full sum
// it pays with the everything it has
tile->getOwner()->changeBalance(rent); // owner of asset gets payed
return opt; // return result of opt
}
else
{
cout << this->p_name << " stopped for a drink in their property" << endl;
return true;
}
}
/// <summary>
/// logic of instruction tiles
/// </summary>
/// <returns>bool</returns>
bool Player::instruct(Deck& deck) throw(string)
{
Instruction* tile = static_cast<Instruction*>(this->location);
//char type = tile->getType();
switch (tile->getType())
{
case 'T': // instruction is type T
cout << this->p_name << " takes a card from the deck" << endl;
return this->getTicket(deck); // get a ticket and follow its value
case 'J': // instruction is type J
cout << this->p_name << " has been arrested during a visit at the county jail" << endl;
this->in_jail = true; // put player into jail
return true;
case 'S': // instruction is type s
// IMPORTANT we were not told what to do in this case
// we took the liberty to follow Monopoly rules
// and double the player starting money (adding another 350 to player)
// this option can be activated by enabling the DOUBLE constant in Instruction.h
#ifdef DOUBLE
cout << "well, well, well... it seems " << this->p_name
<< " is in luck and receives extra cash" << endl;
return changeBalance(BASE); // always returns true
#else
return true;
#endif // DDUBLE
default:
throw VALUE PLAYER "instruct"; // used for testing
}
}
/// <summary>
/// checks if player's in jail
/// and releases if necessary
/// </summary>
/// <returns>bool</returns>
bool Player::isInJail()
{
if (this->in_jail) // if player's in jail
{
cout << this->p_name << " is in jail and can't move this turn :(" << endl;
in_jail = false; // change status
return true;
}
return false;
}
/// <summary>
/// pulls a card from deck
/// and changes balance accordingly
/// </summary>
/// <param name="deck">deck to pull cards from</param>
/// <returns></returns>
bool Player::getTicket(Deck& deck)
{
return this->changeBalance(deck.pullCard());
}
/// <summary>
/// prints the status of the player
/// not const because it uses an iterator
/// </summary>
void Player::printStatus()
{
cout << "they have " << this->balance << " NIS" << endl;
if (this->owned.size())
{
cout << "and own the following assets:" << endl;
vector<Asset*>::iterator it;
for (it = this->owned.begin(); it != this->owned.end(); it++)
{
int m = (*it)->getMortgage();
cout << (**it) << (m ? " pawned" : " active") << endl;
}
}
else { cout << "and have no assets" << endl; }
}
| 31 | 111 | 0.622896 | [
"object",
"vector"
] |
e5daf10d1e6b45b8681f2fd5a3598f389d899dc2 | 8,806 | cpp | C++ | lib/Controller.cpp | tonytonev/Facial-Recognition-Login-IYF | 90949aa6cd8ed910cf28c1948f94f932a52162b5 | [
"MIT"
] | null | null | null | lib/Controller.cpp | tonytonev/Facial-Recognition-Login-IYF | 90949aa6cd8ed910cf28c1948f94f932a52162b5 | [
"MIT"
] | null | null | null | lib/Controller.cpp | tonytonev/Facial-Recognition-Login-IYF | 90949aa6cd8ed910cf28c1948f94f932a52162b5 | [
"MIT"
] | null | null | null | #include "Controller.h"
using namespace std;
Controller::Controller()
{
confidenceThreshold = 0.9;
// Load the model
model = NULL;
// Initalize the face detection module, used for pre-processing
fdm = new FDMBasic("../data/Haars/haarcascade_frontalface_alt.xml", "../data/Haars/haarcascade_profileface.xml", "../data/Haars/ojoI.xml" ,"../data/Haars/ojoD.xml", "../data/Haars/Nariz.xml","../data/Haars/Mouth.xml");
// Initalize log
controllerLog = stdout; //fopen("OutputLogs/controllerLog.txt", "w");
}
Controller::~Controller()
{
fclose(controllerLog);
delete model;
}
void Controller::setFaceModel(void* fm)
{
model = (Model *)fm;
}
/*
Preconditions: Takes the username, the password, and an image of the user attempting to login. Image must be pre-processed.
Postconditions: Returns an loginResult code.
*/
loginResult Controller::Login(char* username, char* password, IplImage* userImage)
{
fprintf(controllerLog, "Entered Controller->Login\n");
if(!hasModel())
return lrFailedLogin;
// Authenticate user and get user id
int UserID = model->authUser(username, password);
// If username/password authentification failed return
if (UserID == 0)
{
fprintf(controllerLog, "Username/password are incorrect\n");
return lrFailedLogin;
}
//checking to see if what UserID gets
fprintf(controllerLog, "UserID = %d\n\n", UserID);
// Get face model XML char*
char* faceModelXML = model->getFaceModelXML(UserID);
//test output the contents of the faceModel
fprintf(controllerLog, "FaceModelXML:\n%.100s\n\n", faceModelXML);
// Create face model object and load from XML
FaceModel* faceModel = new EigenFaceModel(UserID, faceModelXML);
// Compare face model with parameter 'userImage'
double confidenceLevel = faceModel->compare(userImage);
fprintf(controllerLog, "Confidence level: %f\n", confidenceLevel);
// Return the result
if (confidenceLevel < 0)
{
fprintf(controllerLog, "Return failed login\n\n");
return lrFailedLogin;
}
//shouldn't happen till confidence level is implemeneted
else if (confidenceLevel < confidenceThreshold)
{
fprintf(controllerLog, "Return bad image\n\n");
return lrBadImage;
}
fprintf(controllerLog, "Return successful login\n\n");
return lrSuccess;
}
/*
Preconditions: Takes the username and password of a user, a face image array, and the number of images in the array.
Images must be pre-processed.
Postconditions: If the user exists and the password is correct, replaces any existing model with a new model trained on the input images.
If the user doesn't exist, the user is created and trained on the images.
*/
trainResult Controller::Train(char* username, char* password, IplImage ** faceImgArr, int nFaces)
{
fprintf(controllerLog, "Entered Controller->Train\n");
if(!hasModel())
return trFail;
if( nFaces < 1)
{
//Must of passed at least 1 image to combine with test images
return trFail;
}
int UserId;
// If user already exists, find user id
UserId = model->authUser(username, password);
// If user not found or login filed, attempt to insert a new user
if (UserId == 0)
UserId = model->insertUser(username, password);
// If unable to create new user, return
if (UserId == 0)
{
fprintf(controllerLog, "Login for existing user failed or unable to insert new user.\n");
return trFail;
}
//checking to see if what UserID gets
fprintf(controllerLog, "UserId = %d\n", UserId);
// Create and face model object and train on images
FaceModel* faceModel = new EigenFaceModel(UserId, faceImgArr, nFaces);
//get all the eigenface information into xml format
char * faceModelXML = faceModel->exportToXML();
/*fprintf(controllerLog, "BACK IN TRAIN\n");
fprintf(controllerLog, "Face Model size %d\n",strlen(faceModelXML));
fprintf(controllerLog, "Face Model %s\n", faceModelXML);*/
//save the created face model xml char* in the db
if(model->setFaceModelXML(UserId, (char*)faceModelXML))
{
fprintf(controllerLog, "Successfully set face model for user: %d\n", UserId);
delete [] faceModelXML;
return trSuccess;
}
else
{
fprintf(controllerLog, "Unable to set face model for user: %d\n", UserId);
delete [] faceModelXML;
return trFail;
}
}
// Wrapper function for library API
loginResult Controller::Login(char* username, char* password, char* imgFilename)
{
fprintf(controllerLog, "what is imgfilename: %s\n", imgFilename);
// Load face image from file
IplImage * faceImg;
//allocate space for image
faceImg = cvLoadImage(imgFilename, CV_LOAD_IMAGE_GRAYSCALE);
if(!faceImg)
{
fprintf(controllerLog, "Could not load image file\n");
return lrBadImage;
}
return Login(username, password, faceImg);
}
// Wrapper function for library API
loginResult Controller::Login(char* username, char* password, void* faceImg)
{
return Login(username, password, (IplImage*)faceImg);
}
// Wrapper function for library API
trainResult Controller::Train(char* username, char* password, char** imgFilenames, int nFaces)
{
IplImage* faceImg[nFaces];
// Load face images from file
for (int i = 0; i < nFaces; i++)
{
faceImg[i] = cvLoadImage(imgFilenames[i], CV_LOAD_IMAGE_GRAYSCALE);
if(faceImg == NULL)
fprintf(controllerLog, "Could not load image file\n");
}
return Train(username, password, faceImg, nFaces);
}
// Wrapper function for library API
trainResult Controller::Train(char* username, char* password, void** IplImages, int nFaces)
{
return Train(username, password, (IplImage**)IplImages, nFaces);
}
// Gets the distance for a given username and a given image
double Controller::getDistance(char* username, char* imgFilename)
{
if(!hasModel())
return -1.0;
// Get user id
int UserID = model->getIdForUser(username);
// Load face image from file
IplImage* faceImg = cvLoadImage(imgFilename, CV_LOAD_IMAGE_GRAYSCALE);
// Get face model XML string
char* faceModelXML = model->getFaceModelXML(UserID);
// Create face model object and load from XML
EigenFaceModel* faceModel = new EigenFaceModel(UserID, faceModelXML);
return faceModel->distanceToNN(faceImg);
}
int Controller::compareFaces(char * faceImgFilename1, char * faceImgFilename2)
{
// Load face images from file
IplImage* faceImg1 = cvLoadImage(faceImgFilename1, CV_LOAD_IMAGE_GRAYSCALE);
IplImage* faceImg2 = cvLoadImage(faceImgFilename2, CV_LOAD_IMAGE_GRAYSCALE);
IplImage* trainingImgs[] = {faceImg1, faceImg1};
// Create face model object and load XML
EigenFaceModel* faceModel = new EigenFaceModel(0, trainingImgs, 2 );
if (faceModel->compare(faceImg2) > confidenceThreshold)
return 1;
else
return 0;
}
/*
Preconditions: inputFaceImg is an image of a face.
Postconditions: Returns cropped, black-and-white version of the input image
*/
IplImage* Controller::preProcess(IplImage* inputFaceImg)
{
IplImage * faceArray[1];
// Detect, crop, and preprocess faces
int nFaces = fdm->detectFaces(inputFaceImg, faceArray, 1);
// If faces were detected, return processed face
if (nFaces > 0)
{
return faceArray[0];
}
// If not faces were detected, return NULL
return NULL;
}
// Wrapper for lib interface
void* Controller::preProcess(void* inputFaceImg)
{
return (void*)preProcess((IplImage*)inputFaceImg);
}
/*
Preconditions: Output filename must end in .pgm
Postconditions: Takes an input file is read, processsed, and output stored in the location specified by outputImgFilename.
Returns true if successful, and false if unable to detect any faces.
*/
bool Controller::preProcess(char* inputImgFilename, char* outputImgFilename)
{
// Load input image from file
IplImage* inputFaceImg = cvLoadImage(inputImgFilename, CV_LOAD_IMAGE_ANYCOLOR);
// Preprocess face
IplImage* outputFaceImg = preProcess(inputFaceImg);
cvReleaseImage(&inputFaceImg);
// If faces were detected, save output to file
if (outputFaceImg != NULL)
{
cvSaveImage(outputImgFilename, outputFaceImg);
cvReleaseImage(&outputFaceImg);
return true;
}
// If not faces were detected, return false
return false;
}
bool Controller::hasModel()
{
if(model == NULL)
{
fprintf(controllerLog, "Pass in a model first.\n");
return false;
}
return true;
}
| 29.550336 | 222 | 0.680559 | [
"object",
"model"
] |
e5e714ad3aa79947cd36ace35e42c73e7e625adf | 8,159 | cpp | C++ | src/mongo/db/query/sbe_sub_planner.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/sbe_sub_planner.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/sbe_sub_planner.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/query/sbe_sub_planner.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/plan_cache_key_factory.h"
#include "mongo/db/query/query_planner.h"
#include "mongo/db/query/sbe_multi_planner.h"
#include "mongo/db/query/stage_builder_util.h"
#include "mongo/db/query/util/make_data_structure.h"
namespace mongo::sbe {
CandidatePlans SubPlanner::plan(
std::vector<std::unique_ptr<QuerySolution>> solutions,
std::vector<std::pair<std::unique_ptr<PlanStage>, stage_builder::PlanStageData>>) {
const auto& mainColl = _collections.getMainCollection();
// Plan each branch of the $or.
auto subplanningStatus = QueryPlanner::planSubqueries(
_opCtx, {} /* getSolutionCachedData */, mainColl, _cq, _queryParams);
if (!subplanningStatus.isOK()) {
return planWholeQuery();
}
auto multiplanCallback = [&](CanonicalQuery* cq,
std::vector<std::unique_ptr<QuerySolution>> solutions)
-> StatusWith<std::unique_ptr<QuerySolution>> {
// One of the indexes in '_queryParams' might have been dropped while planning a previous
// branch of the OR query. In this case, fail with a 'QueryPlanKilled' error.
_indexExistenceChecker.check();
// Ensure that no previous plans are registered to yield while we multi plan each branch.
_yieldPolicy->clearRegisteredPlans();
std::vector<std::pair<std::unique_ptr<PlanStage>, stage_builder::PlanStageData>> roots;
for (auto&& solution : solutions) {
roots.push_back(stage_builder::buildSlotBasedExecutableTree(
_opCtx, _collections, *cq, *solution, _yieldPolicy));
}
// Clear any plans registered to yield once multiplanning is done for this branch. We don't
// want to leave dangling pointers to the execution plans used in multi planning hanging
// around in the YieldPolicy.
ON_BLOCK_EXIT([this]() { _yieldPolicy->clearRegisteredPlans(); });
// We pass the SometimesCache option to the MPS because the SubplanStage currently does
// not use the 'CachedSolutionPlanner' eviction mechanism. We therefore are more
// conservative about putting a potentially bad plan into the cache in the subplan path.
MultiPlanner multiPlanner{
_opCtx, _collections, *cq, _queryParams, PlanCachingMode::SometimesCache, _yieldPolicy};
auto&& [candidates, winnerIdx] = multiPlanner.plan(std::move(solutions), std::move(roots));
invariant(winnerIdx < candidates.size());
return std::move(candidates[winnerIdx].solution);
};
auto subplanSelectStat = QueryPlanner::choosePlanForSubqueries(
_cq, _queryParams, std::move(subplanningStatus.getValue()), multiplanCallback);
// One of the indexes in '_queryParams' might have been dropped while planning the final branch
// of the OR query. In this case, fail with a 'QueryPlanKilled' error.
_indexExistenceChecker.check();
if (!subplanSelectStat.isOK()) {
// Query planning can continue if we failed to find a solution for one of the children.
// Otherwise, it cannot, as it may no longer be safe to access the collection (an index
// may have been dropped, we may have exceeded the time limit, etc).
uassert(4822874,
subplanSelectStat.getStatus().reason(),
subplanSelectStat == ErrorCodes::NoQueryExecutionPlans);
return planWholeQuery();
}
// Build a plan stage tree from a composite solution.
auto compositeSolution = std::move(subplanSelectStat.getValue());
// If some agg pipeline stages are being pushed down, extend the solution with them.
if (!_cq.pipeline().empty()) {
compositeSolution = QueryPlanner::extendWithAggPipeline(
_cq, std::move(compositeSolution), _queryParams.secondaryCollectionsInfo);
}
auto&& [root, data] = stage_builder::buildSlotBasedExecutableTree(
_opCtx, _collections, _cq, *compositeSolution, _yieldPolicy);
auto status = prepareExecutionPlan(root.get(), &data);
uassertStatusOK(status);
auto [result, recordId, exitedEarly] = status.getValue();
tassert(5323804, "sub-planner unexpectedly exited early during prepare phase", !exitedEarly);
// TODO SERVER-61507: do it unconditionally when $group pushdown is integrated with the SBE plan
// cache.
if (_cq.pipeline().empty()) {
plan_cache_util::updatePlanCache(_opCtx, mainColl, _cq, *compositeSolution, *root, data);
}
return {makeVector(plan_ranker::CandidatePlan{
std::move(compositeSolution), std::move(root), std::move(data)}),
0};
}
CandidatePlans SubPlanner::planWholeQuery() const {
// Use the query planning module to plan the whole query.
auto statusWithMultiPlanSolns = QueryPlanner::plan(_cq, _queryParams);
auto solutions = uassertStatusOK(std::move(statusWithMultiPlanSolns));
// Only one possible plan. Build the stages from the solution.
if (solutions.size() == 1) {
// If some agg pipeline stages are being pushed down, extend the solution with them.
if (!_cq.pipeline().empty()) {
solutions[0] = QueryPlanner::extendWithAggPipeline(
_cq, std::move(solutions[0]), _queryParams.secondaryCollectionsInfo);
}
auto&& [root, data] = stage_builder::buildSlotBasedExecutableTree(
_opCtx, _collections, _cq, *solutions[0], _yieldPolicy);
auto status = prepareExecutionPlan(root.get(), &data);
uassertStatusOK(status);
auto [result, recordId, exitedEarly] = status.getValue();
tassert(
5323805, "sub-planner unexpectedly exited early during prepare phase", !exitedEarly);
return {makeVector(plan_ranker::CandidatePlan{
std::move(solutions[0]), std::move(root), std::move(data)}),
0};
}
// Many solutions. Build a plan stage tree for each solution and create a multi planner to pick
// the best, update the cache, and so on.
std::vector<std::pair<std::unique_ptr<PlanStage>, stage_builder::PlanStageData>> roots;
for (auto&& solution : solutions) {
roots.push_back(stage_builder::buildSlotBasedExecutableTree(
_opCtx, _collections, _cq, *solution, _yieldPolicy));
}
MultiPlanner multiPlanner{
_opCtx, _collections, _cq, _queryParams, PlanCachingMode::AlwaysCache, _yieldPolicy};
return multiPlanner.plan(std::move(solutions), std::move(roots));
}
} // namespace mongo::sbe
| 49.150602 | 100 | 0.693467 | [
"vector"
] |
e5eb2a2d3b802bfffaf30b9c4a57f0a843fedbbf | 30,733 | cpp | C++ | src/path_abundance_estimator.cpp | jeizenga/rpvg | 1536699bef3902a504de7235587e583ca9e73aa4 | [
"MIT"
] | null | null | null | src/path_abundance_estimator.cpp | jeizenga/rpvg | 1536699bef3902a504de7235587e583ca9e73aa4 | [
"MIT"
] | null | null | null | src/path_abundance_estimator.cpp | jeizenga/rpvg | 1536699bef3902a504de7235587e583ca9e73aa4 | [
"MIT"
] | null | null | null |
#include <limits>
#include <chrono>
#include "sparsepp/spp.h"
#include "path_abundance_estimator.hpp"
const uint32_t min_em_conv_its = 10;
const double min_em_abundance = 1e-8;
const double abundance_gibbs_gamma = 1;
const uint32_t min_rel_likelihood_scaling = 1e4;
PathAbundanceEstimator::PathAbundanceEstimator(const uint32_t max_em_its_in, const double max_rel_em_conv_in, const uint32_t num_gibbs_samples_in, const uint32_t gibbs_thin_its_in, const double prob_precision) : max_em_its(max_em_its_in), max_rel_em_conv(max_rel_em_conv_in), num_gibbs_samples(num_gibbs_samples_in), gibbs_thin_its(gibbs_thin_its_in), PathEstimator(prob_precision) {}
void PathAbundanceEstimator::estimate(PathClusterEstimates * path_cluster_estimates, const vector<ReadPathProbabilities> & cluster_probs, mt19937 * mt_rng) {
if (!cluster_probs.empty()) {
Utils::ColMatrixXd read_path_probs;
Utils::ColVectorXd noise_probs;
Utils::RowVectorXd read_counts;
constructProbabilityMatrix(&read_path_probs, &noise_probs, &read_counts, cluster_probs, path_cluster_estimates->paths.size());
detractNoiseAndNormalizeProbabilityMatrix(&read_path_probs, &noise_probs, &read_counts);
if (read_path_probs.rows() == 0) {
assert(noise_probs.rows() == 0);
assert(read_counts.cols() == 0);
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
return;
}
const double total_read_count = read_counts.sum();
assert(total_read_count > 0);
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, false);
EMAbundanceEstimator(path_cluster_estimates, read_path_probs, read_counts, total_read_count);
if (num_gibbs_samples > 0) {
vector<CountSamples> * gibbs_read_count_samples = &(path_cluster_estimates->gibbs_read_count_samples);
gibbs_read_count_samples->emplace_back(CountSamples());
gibbs_read_count_samples->back().path_ids = vector<uint32_t>(path_cluster_estimates->abundances.cols());
iota(gibbs_read_count_samples->back().path_ids.begin(), gibbs_read_count_samples->back().path_ids.end(), 0);
gibbs_read_count_samples->back().samples = vector<vector<double> >(path_cluster_estimates->abundances.cols(), vector<double>());
gibbsReadCountSampler(path_cluster_estimates, read_path_probs, read_counts, total_read_count, abundance_gibbs_gamma, mt_rng);
}
path_cluster_estimates->abundances *= total_read_count;
} else {
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
}
}
void PathAbundanceEstimator::EMAbundanceEstimator(PathClusterEstimates * path_cluster_estimates, const Utils::ColMatrixXd & read_path_probs, const Utils::RowVectorXd & read_counts, const double total_read_count) const {
Utils::RowVectorXd prev_abundances = path_cluster_estimates->abundances;
uint32_t em_conv_its = 0;
for (uint32_t i = 0; i < max_em_its; ++i) {
Utils::ColMatrixXd read_posteriors = read_path_probs.array().rowwise() * path_cluster_estimates->abundances.array();
read_posteriors = read_posteriors.array().colwise() / read_posteriors.rowwise().sum().array();
path_cluster_estimates->abundances = read_counts * read_posteriors;
path_cluster_estimates->abundances /= total_read_count;
bool has_converged = true;
for (size_t i = 0; i < path_cluster_estimates->abundances.cols(); ++i) {
if (path_cluster_estimates->abundances(0, i) >= min_em_abundance) {
auto rel_abundance_diff = fabs(path_cluster_estimates->abundances(0, i) - prev_abundances(0, i)) / path_cluster_estimates->abundances(0, i);
if (rel_abundance_diff > max_rel_em_conv) {
has_converged = false;
break;
}
}
}
if (has_converged) {
em_conv_its++;
if (em_conv_its == min_em_conv_its) {
break;
}
} else {
em_conv_its = 0;
}
prev_abundances = path_cluster_estimates->abundances;
}
double abundances_sum = 0;
for (size_t i = 0; i < path_cluster_estimates->abundances.cols(); ++i) {
if (path_cluster_estimates->abundances(0, i) < min_em_abundance) {
path_cluster_estimates->abundances(0, i) = 0;
}
abundances_sum += path_cluster_estimates->abundances(0, i);
}
if (abundances_sum > 0) {
path_cluster_estimates->abundances = path_cluster_estimates->abundances / abundances_sum;
}
}
void PathAbundanceEstimator::gibbsReadCountSampler(PathClusterEstimates * path_cluster_estimates, const Utils::ColMatrixXd & read_path_probs, const Utils::RowVectorXd & read_counts, const double total_read_count, const double gamma, mt19937 * mt_rng) const {
assert(!path_cluster_estimates->gibbs_read_count_samples.empty());
assert(path_cluster_estimates->gibbs_read_count_samples.back().path_ids.size() == path_cluster_estimates->abundances.cols());
assert(path_cluster_estimates->gibbs_read_count_samples.back().samples.size() == path_cluster_estimates->abundances.cols());
assert(Utils::doubleCompare(path_cluster_estimates->abundances.sum(), 1));
Utils::RowVectorXd gibbs_abundances = path_cluster_estimates->abundances;
const uint32_t num_gibbs_its = num_gibbs_samples * gibbs_thin_its;
for (uint32_t gibbs_it = 1; gibbs_it <= num_gibbs_its; ++gibbs_it) {
Utils::ColMatrixXd read_posteriors = read_path_probs.array().rowwise() * gibbs_abundances.array();
read_posteriors = read_posteriors.array().colwise() / read_posteriors.rowwise().sum().array();
vector<uint32_t> gibbs_path_read_counts(gibbs_abundances.cols(), 0);
for (size_t i = 0; i < read_posteriors.rows(); ++i) {
uint32_t row_reads_counts = read_counts(0, i);
double row_sum_probs = 1;
for (size_t j = 0; j < read_posteriors.cols(); ++j) {
auto cur_prob = read_posteriors(i, j);
if (cur_prob > 0) {
assert(row_sum_probs > 0);
binomial_distribution<uint32_t> path_read_count_sampler(row_reads_counts, min(1.0, cur_prob / row_sum_probs));
auto path_read_count = path_read_count_sampler(*mt_rng);
gibbs_path_read_counts.at(j) += path_read_count;
row_reads_counts -= path_read_count;
if (row_reads_counts == 0) {
break;
}
}
row_sum_probs -= cur_prob;
}
assert(row_reads_counts == 0);
}
double gibbs_abundances_sum = 0;
for (size_t i = 0; i < gibbs_abundances.cols(); ++i) {
gamma_distribution<double> gamma_count_dist(gibbs_path_read_counts.at(i) + gamma, 1);
gibbs_abundances(0, i) = gamma_count_dist(*mt_rng);
gibbs_abundances_sum += gibbs_abundances(0, i);
}
gibbs_abundances = gibbs_abundances / gibbs_abundances_sum;
if (gibbs_it % gibbs_thin_its == 0) {
for (size_t i = 0; i < gibbs_abundances.cols(); ++i) {
path_cluster_estimates->gibbs_read_count_samples.back().samples.at(i).emplace_back(gibbs_abundances(0, i) * total_read_count);
}
}
}
}
void PathAbundanceEstimator::updateEstimates(PathClusterEstimates * path_cluster_estimates, const PathClusterEstimates & new_path_cluster_estimates, const vector<uint32_t> & path_indices, const uint32_t sample_count) const {
assert(new_path_cluster_estimates.abundances.cols() == path_indices.size());
for (size_t i = 0; i < path_indices.size(); ++i) {
path_cluster_estimates->abundances(0, path_indices.at(i)) += (new_path_cluster_estimates.abundances(0, i) * sample_count);
}
if (!new_path_cluster_estimates.gibbs_read_count_samples.empty()) {
assert(new_path_cluster_estimates.gibbs_read_count_samples.size() == 1);
path_cluster_estimates->gibbs_read_count_samples.emplace_back(move(new_path_cluster_estimates.gibbs_read_count_samples.front()));
}
}
MinimumPathAbundanceEstimator::MinimumPathAbundanceEstimator(const uint32_t max_em_its, const double max_rel_em_conv, const uint32_t num_gibbs_samples, const uint32_t gibbs_thin_its, const double prob_precision) : PathAbundanceEstimator(max_em_its, max_rel_em_conv, num_gibbs_samples, gibbs_thin_its, prob_precision) {}
void MinimumPathAbundanceEstimator::estimate(PathClusterEstimates * path_cluster_estimates, const vector<ReadPathProbabilities> & cluster_probs, mt19937 * mt_rng) {
if (!cluster_probs.empty()) {
Utils::ColMatrixXd read_path_probs;
Utils::ColVectorXd noise_probs;
Utils::RowVectorXd read_counts;
constructProbabilityMatrix(&read_path_probs, &noise_probs, &read_counts, cluster_probs, path_cluster_estimates->paths.size());
Utils::ColMatrixXb read_path_cover = Utils::ColMatrixXb::Zero(read_path_probs.rows(), read_path_probs.cols());
Utils::RowVectorXd path_weights = Utils::RowVectorXd::Zero(read_path_probs.cols());
for (size_t i = 0; i < read_path_probs.rows(); ++i) {
if (Utils::doubleCompare(noise_probs(i), 1)) {
read_counts(i) = 0;
}
for (auto & path_probs: cluster_probs.at(i).pathProbs()) {
for (auto & path: path_probs.second) {
assert(path_probs.first > 0);
read_path_cover(i, path) = true;
path_weights(path) += log(path_probs.first) * read_counts(i);
}
}
}
path_weights *= -1;
vector<uint32_t> min_path_cover = weightedMinimumPathCover(read_path_cover, read_counts, path_weights);
if (!min_path_cover.empty()) {
Utils::ColMatrixXd min_path_read_path_probs;
Utils::ColVectorXd min_path_noise_probs;
Utils::RowVectorXd min_path_read_counts;
constructPartialProbabilityMatrix(&min_path_read_path_probs, &min_path_noise_probs, &min_path_read_counts, cluster_probs, min_path_cover, path_cluster_estimates->paths.size(), true);
detractNoiseAndNormalizeProbabilityMatrix(&min_path_read_path_probs, &min_path_noise_probs, &min_path_read_counts);
if (min_path_read_path_probs.rows() == 0) {
assert(min_path_noise_probs.rows() == 0);
assert(min_path_read_counts.cols() == 0);
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
return;
}
assert(min_path_read_path_probs.cols() >= 1);
readCollapseProbabilityMatrix(&min_path_read_path_probs, &min_path_read_counts);
const double total_min_path_read_counts = min_path_read_counts.sum();
assert(total_min_path_read_counts > 0);
PathClusterEstimates min_path_cluster_estimates;
min_path_cluster_estimates.initEstimates(min_path_read_path_probs.cols(), 0, false);
EMAbundanceEstimator(&min_path_cluster_estimates, min_path_read_path_probs, min_path_read_counts, total_min_path_read_counts);
assert(min_path_cluster_estimates.abundances.cols() == min_path_cover.size());
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
if (num_gibbs_samples > 0) {
vector<CountSamples> * gibbs_read_count_samples = &(min_path_cluster_estimates.gibbs_read_count_samples);
gibbs_read_count_samples->emplace_back(CountSamples());
gibbs_read_count_samples->back().path_ids = min_path_cover;
gibbs_read_count_samples->back().samples = vector<vector<double> >(min_path_cluster_estimates.abundances.cols(), vector<double>());
gibbsReadCountSampler(&min_path_cluster_estimates, min_path_read_path_probs, min_path_read_counts, total_min_path_read_counts, abundance_gibbs_gamma, mt_rng);
}
min_path_cluster_estimates.abundances *= total_min_path_read_counts;
updateEstimates(path_cluster_estimates, min_path_cluster_estimates, min_path_cover, 1);
} else {
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
}
} else {
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
}
}
vector<uint32_t> MinimumPathAbundanceEstimator::weightedMinimumPathCover(const Utils::ColMatrixXb & read_path_cover, const Utils::RowVectorXd & read_counts, const Utils::RowVectorXd & path_weights) const {
assert(read_path_cover.rows() == read_counts.cols());
assert(read_path_cover.cols() == path_weights.cols());
if (read_path_cover.cols() == 1) {
return vector<uint32_t>({0});
}
auto uncovered_read_counts = read_counts;
vector<uint32_t> min_path_cover;
min_path_cover.reserve(read_path_cover.cols());
while (uncovered_read_counts.maxCoeff() > 0) {
Utils::RowVectorXd weighted_read_path_cover = (uncovered_read_counts * read_path_cover.cast<double>()).array() / path_weights.array();
assert(weighted_read_path_cover.size() == read_path_cover.cols());
double max_weighted_read_path_cover = 0;
int32_t max_weighted_read_path_cover_idx = -1;
for (size_t i = 0; i < weighted_read_path_cover.size(); ++i) {
if (weighted_read_path_cover(i) > max_weighted_read_path_cover) {
max_weighted_read_path_cover = weighted_read_path_cover(i);
max_weighted_read_path_cover_idx = i;
}
}
assert(max_weighted_read_path_cover > 0);
assert(max_weighted_read_path_cover_idx >= 0);
min_path_cover.emplace_back(max_weighted_read_path_cover_idx);
uncovered_read_counts = (uncovered_read_counts.array() * (!read_path_cover.col(max_weighted_read_path_cover_idx).transpose().array()).cast<double>()).matrix();
}
assert(min_path_cover.size() <= read_path_cover.cols());
sort(min_path_cover.begin(), min_path_cover.end());
return min_path_cover;
}
NestedPathAbundanceEstimator::NestedPathAbundanceEstimator(const uint32_t group_size_in, const uint32_t num_subset_samples_in, const bool infer_collapsed_in, const bool use_group_post_gibbs_in, const uint32_t max_em_its, const double max_rel_em_conv, const uint32_t num_gibbs_samples, const uint32_t gibbs_thin_its, const double prob_precision) : group_size(group_size_in), num_subset_samples(num_subset_samples_in), infer_collapsed(infer_collapsed_in), use_group_post_gibbs(use_group_post_gibbs_in), PathAbundanceEstimator(max_em_its, max_rel_em_conv, num_gibbs_samples, gibbs_thin_its, prob_precision) {}
void NestedPathAbundanceEstimator::estimate(PathClusterEstimates * path_cluster_estimates, const vector<ReadPathProbabilities> & cluster_probs, mt19937 * mt_rng) {
if (infer_collapsed) {
inferAbundancesCollapsedGroups(path_cluster_estimates, cluster_probs, mt_rng);
} else {
inferAbundancesIndependentGroups(path_cluster_estimates, cluster_probs, mt_rng);
}
}
void NestedPathAbundanceEstimator::inferAbundancesIndependentGroups(PathClusterEstimates * path_cluster_estimates, const vector<ReadPathProbabilities> & cluster_probs, mt19937 * mt_rng) const {
if (!cluster_probs.empty()) {
auto path_groups = findPathGroups(path_cluster_estimates->paths);
vector<vector<uint32_t> > path_subset_samples(num_subset_samples);
for (auto & path_subset: path_subset_samples) {
path_subset.reserve(path_groups.size() * group_size);
}
for (auto & group: path_groups) {
Utils::ColMatrixXd group_read_path_probs;
Utils::ColVectorXd group_noise_probs;
Utils::RowVectorXd group_read_counts;
constructPartialProbabilityMatrix(&group_read_path_probs, &group_noise_probs, &group_read_counts, cluster_probs, group, path_cluster_estimates->paths.size(), false);
addNoiseAndNormalizeProbabilityMatrix(&group_read_path_probs, group_noise_probs);
readCollapseProbabilityMatrix(&group_read_path_probs, &group_read_counts);
group_noise_probs = group_read_path_probs.col(group_read_path_probs.cols() - 1);
group_read_path_probs.conservativeResize(group_read_path_probs.rows(), group_read_path_probs.cols() - 1);
vector<uint32_t> group_path_counts;
group_path_counts.reserve(group.size());
for (size_t i = 0; i < group.size(); ++i) {
group_path_counts.emplace_back(path_cluster_estimates->paths.at(group.at(i)).source_count);
}
PathClusterEstimates group_path_cluster_estimates;
if (use_group_post_gibbs) {
estimatePathGroupPosteriorsGibbs(&group_path_cluster_estimates, group_read_path_probs, group_noise_probs, group_read_counts, group_path_counts, group_size, mt_rng);
} else {
if (group_size == 2) {
const double min_rel_likelihood = 1 / static_cast<double>(min_rel_likelihood_scaling * num_subset_samples);
calculatePathGroupPosteriorsBounded(&group_path_cluster_estimates, group_read_path_probs, group_noise_probs, group_read_counts, group_path_counts, group_size, min_rel_likelihood);
} else {
calculatePathGroupPosteriorsFull(&group_path_cluster_estimates, group_read_path_probs, group_noise_probs, group_read_counts, group_path_counts, group_size);
}
}
sampleGroupPathIndices(&path_subset_samples, group_path_cluster_estimates, group, mt_rng);
}
spp::sparse_hash_map<vector<uint32_t>, uint32_t> clustered_path_subset_samples;
for (auto & path_subset: path_subset_samples) {
sort(path_subset.begin(), path_subset.end());
auto clustered_path_subset_samples_it = clustered_path_subset_samples.emplace(path_subset, 0);
clustered_path_subset_samples_it.first->second++;
}
inferPathSubsetAbundance(path_cluster_estimates, cluster_probs, mt_rng, clustered_path_subset_samples);
} else {
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
}
}
void NestedPathAbundanceEstimator::inferAbundancesCollapsedGroups(PathClusterEstimates * path_cluster_estimates, const vector<ReadPathProbabilities> & cluster_probs, mt19937 * mt_rng) {
if (!cluster_probs.empty()) {
auto path_source_groups = findPathSourceGroups(path_cluster_estimates->paths);
Utils::ColMatrixXd group_read_path_probs;
Utils::ColVectorXd group_noise_probs;
Utils::RowVectorXd group_read_counts;
constructGroupedProbabilityMatrix(&group_read_path_probs, &group_noise_probs, &group_read_counts, cluster_probs, path_source_groups.first, path_cluster_estimates->paths.size());
addNoiseAndNormalizeProbabilityMatrix(&group_read_path_probs, group_noise_probs);
readCollapseProbabilityMatrix(&group_read_path_probs, &group_read_counts);
group_noise_probs = group_read_path_probs.col(group_read_path_probs.cols() - 1);
group_read_path_probs.conservativeResize(group_read_path_probs.rows(), group_read_path_probs.cols() - 1);
PathClusterEstimates group_path_cluster_estimates;
if (use_group_post_gibbs) {
estimatePathGroupPosteriorsGibbs(&group_path_cluster_estimates, group_read_path_probs, group_noise_probs, group_read_counts, path_source_groups.second, group_size, mt_rng);
} else {
if (group_size == 2) {
const double min_rel_likelihood = 1 / static_cast<double>(min_rel_likelihood_scaling * num_subset_samples);
calculatePathGroupPosteriorsBounded(&group_path_cluster_estimates, group_read_path_probs, group_noise_probs, group_read_counts, path_source_groups.second, group_size, min_rel_likelihood);
} else {
calculatePathGroupPosteriorsFull(&group_path_cluster_estimates, group_read_path_probs, group_noise_probs, group_read_counts, path_source_groups.second, group_size);
}
}
spp::sparse_hash_map<vector<uint32_t>, uint32_t> path_subset_samples;
samplePathSubsetIndices(&path_subset_samples, group_path_cluster_estimates, path_source_groups.first, mt_rng);
inferPathSubsetAbundance(path_cluster_estimates, cluster_probs, mt_rng, path_subset_samples);
} else {
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
}
}
vector<vector<uint32_t> > NestedPathAbundanceEstimator::findPathGroups(const vector<PathInfo> & paths) const {
vector<vector<uint32_t> > path_groups;
spp::sparse_hash_map<uint32_t, uint32_t> path_group_indexes;
for (size_t i = 0; i < paths.size(); ++i) {
auto path_group_indexes_it = path_group_indexes.emplace(paths.at(i).group_id, path_group_indexes.size());
if (path_group_indexes_it.second) {
path_groups.emplace_back(vector<uint32_t>());
}
path_groups.at(path_group_indexes_it.first->second).emplace_back(i);
}
return path_groups;
}
pair<vector<vector<uint32_t> >, vector<uint32_t> > NestedPathAbundanceEstimator::findPathSourceGroups(const vector<PathInfo> & paths) const {
spp::sparse_hash_map<uint32_t, vector<uint32_t> > source_id_paths;
for (size_t i = 0; i < paths.size(); ++i) {
for (auto & id: paths.at(i).source_ids) {
auto source_id_paths_it = source_id_paths.emplace(id, vector<uint32_t>());
source_id_paths_it.first->second.emplace_back(i);
}
}
pair<vector<vector<uint32_t> >, vector<uint32_t> > path_source_groups;
auto source_id_paths_it = source_id_paths.begin();
while (source_id_paths_it != source_id_paths.end()) {
if (source_id_paths_it->second.empty()) {
++source_id_paths_it;
continue;
}
path_source_groups.second.emplace_back(1);
auto source_id_paths_it2 = source_id_paths_it;
++source_id_paths_it2;
while (source_id_paths_it2 != source_id_paths.end()) {
if (!source_id_paths_it2->second.empty()) {
if (source_id_paths_it->second == source_id_paths_it2->second) {
path_source_groups.second.back()++;
source_id_paths_it2->second.clear();
}
}
++source_id_paths_it2;
}
assert(!source_id_paths_it->second.empty());
path_source_groups.first.emplace_back(source_id_paths_it->second);
source_id_paths_it->second.clear();
++source_id_paths_it;
}
assert(path_source_groups.first.size() == path_source_groups.second.size());
return path_source_groups;
}
void NestedPathAbundanceEstimator::sampleGroupPathIndices(vector<vector<uint32_t> > * path_subset_samples, const PathClusterEstimates & group_path_cluster_estimates, const vector<uint32_t> & group, mt19937 * mt_rng) const {
assert(group_path_cluster_estimates.posteriors.size() == group_path_cluster_estimates.path_group_sets.size());
discrete_distribution<uint32_t> path_group_set_sampler(group_path_cluster_estimates.posteriors.begin(), group_path_cluster_estimates.posteriors.end());
for (size_t i = 0; i < num_subset_samples; ++i) {
vector<uint32_t> path_group_set = group_path_cluster_estimates.path_group_sets.at(path_group_set_sampler(*mt_rng));
assert(!path_group_set.empty());
assert(path_group_set.size() == group_size);
sort(path_group_set.begin(), path_group_set.end());
for (auto & path_group: path_group_set) {
path_subset_samples->at(i).emplace_back(group.at(path_group));
}
}
}
void NestedPathAbundanceEstimator::samplePathSubsetIndices(spp::sparse_hash_map<vector<uint32_t>, uint32_t> * path_subset_samples, const PathClusterEstimates & group_path_cluster_estimates, const vector<vector<uint32_t> > & path_groups, mt19937 * mt_rng) const {
assert(group_path_cluster_estimates.posteriors.size() == group_path_cluster_estimates.path_group_sets.size());
discrete_distribution<uint32_t> path_group_set_sampler(group_path_cluster_estimates.posteriors.begin(), group_path_cluster_estimates.posteriors.end());
vector<uint32_t> path_group_set_sample_counts(group_path_cluster_estimates.path_group_sets.size(), 0);
for (size_t i = 0; i < num_subset_samples; ++i) {
path_group_set_sample_counts.at(path_group_set_sampler(*mt_rng)) += 1;
}
for (size_t i = 0; i < path_group_set_sample_counts.size(); ++i) {
if (path_group_set_sample_counts.at(i) > 0) {
auto path_group_set = group_path_cluster_estimates.path_group_sets.at(i);
assert(!path_group_set.empty());
assert(path_group_set.size() == group_size);
vector<uint32_t> path_subset;
for (auto & group: path_group_set) {
for (auto & path: path_groups.at(group)) {
path_subset.emplace_back(path);
}
}
sort(path_subset.begin(), path_subset.end());
auto path_subset_samples_it = path_subset_samples->emplace(path_subset, 0);
path_subset_samples_it.first->second += path_group_set_sample_counts.at(i);
}
}
}
void NestedPathAbundanceEstimator::inferPathSubsetAbundance(PathClusterEstimates * path_cluster_estimates, const vector<ReadPathProbabilities> & cluster_probs, mt19937 * mt_rng, const spp::sparse_hash_map<vector<uint32_t>, uint32_t> & path_subset_samples) const {
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
spp::sparse_hash_map<vector<uint32_t>, uint32_t> subset_path_group_samples;
for (auto & path_subset: path_subset_samples) {
assert(!path_subset.first.empty());
assert(path_subset.second > 0);
spp::sparse_hash_map<uint32_t, vector<uint32_t> > subset_path_group;
for (auto & path: path_subset.first) {
auto subset_path_group_it = subset_path_group.emplace(path_cluster_estimates->paths.at(path).group_id, vector<uint32_t>());
subset_path_group_it.first->second.emplace_back(path);
}
for (auto & path_group: subset_path_group) {
auto subset_path_group_samples_it = subset_path_group_samples.emplace(path_group.second, 0);
subset_path_group_samples_it.first->second += path_subset.second;
}
vector<uint32_t> collapsed_path_subset;
collapsed_path_subset.reserve(path_subset.first.size());
collapsed_path_subset.emplace_back(path_subset.first.front());
for (size_t i = 1; i < path_subset.first.size(); ++i) {
if (path_subset.first.at(i) != collapsed_path_subset.back()) {
collapsed_path_subset.emplace_back(path_subset.first.at(i));
}
}
Utils::ColMatrixXd subset_read_path_probs;
Utils::ColVectorXd subset_noise_probs;
Utils::RowVectorXd subset_read_counts;
constructPartialProbabilityMatrix(&subset_read_path_probs, &subset_noise_probs, &subset_read_counts, cluster_probs, collapsed_path_subset, path_cluster_estimates->paths.size(), true);
detractNoiseAndNormalizeProbabilityMatrix(&subset_read_path_probs, &subset_noise_probs, &subset_read_counts);
if (subset_read_path_probs.rows() == 0) {
assert(subset_noise_probs.rows() == 0);
assert(subset_read_counts.cols() == 0);
path_cluster_estimates->initEstimates(path_cluster_estimates->paths.size(), 0, true);
return;
}
assert(subset_read_path_probs.cols() >= 1);
readCollapseProbabilityMatrix(&subset_read_path_probs, &subset_read_counts);
const double total_subset_read_counts = subset_read_counts.sum();
assert(total_subset_read_counts > 0);
PathClusterEstimates subset_path_cluster_estimates;
subset_path_cluster_estimates.initEstimates(subset_read_path_probs.cols(), 0, false);
EMAbundanceEstimator(&subset_path_cluster_estimates, subset_read_path_probs, subset_read_counts, total_subset_read_counts);
assert(subset_path_cluster_estimates.abundances.cols() == collapsed_path_subset.size());
if (num_gibbs_samples > 0) {
vector<CountSamples> * gibbs_read_count_samples = &(subset_path_cluster_estimates.gibbs_read_count_samples);
gibbs_read_count_samples->emplace_back(CountSamples());
gibbs_read_count_samples->back().path_ids = collapsed_path_subset;
gibbs_read_count_samples->back().samples = vector<vector<double> >(subset_path_cluster_estimates.abundances.cols(), vector<double>());
for (uint32_t i = 0; i < path_subset.second; ++i) {
gibbsReadCountSampler(&subset_path_cluster_estimates, subset_read_path_probs, subset_read_counts, total_subset_read_counts, abundance_gibbs_gamma, mt_rng);
}
}
subset_path_cluster_estimates.abundances *= total_subset_read_counts;
updateEstimates(path_cluster_estimates, subset_path_cluster_estimates, collapsed_path_subset, path_subset.second);
}
assert(path_cluster_estimates->posteriors.empty());
assert(path_cluster_estimates->path_group_sets.empty());
path_cluster_estimates->posteriors.reserve(subset_path_group_samples.size());
path_cluster_estimates->path_group_sets.reserve(subset_path_group_samples.size());
for (auto & path_group_sample: subset_path_group_samples) {
assert(path_group_sample.first.size() <= group_size);
path_cluster_estimates->posteriors.emplace_back(path_group_sample.second / static_cast<double>(num_subset_samples));
path_cluster_estimates->path_group_sets.emplace_back(path_group_sample.first);
}
for (size_t i = 0; i < path_cluster_estimates->abundances.cols(); ++i) {
path_cluster_estimates->abundances(0, i) /= static_cast<double>(num_subset_samples);
}
}
| 41.870572 | 606 | 0.701624 | [
"vector"
] |
e5ebf84b5b72341841c6c9e33beb705401f9e145 | 39,161 | cpp | C++ | Pinochle/Player.cpp | nparajul/Pinochle | 5cf692deb21be40929dd77659e98e42a79aedbbd | [
"MIT"
] | 1 | 2020-11-03T18:08:18.000Z | 2020-11-03T18:08:18.000Z | Pinochle/Player.cpp | nparajul/Pinochle | 5cf692deb21be40929dd77659e98e42a79aedbbd | [
"MIT"
] | null | null | null | Pinochle/Player.cpp | nparajul/Pinochle | 5cf692deb21be40929dd77659e98e42a79aedbbd | [
"MIT"
] | null | null | null | /*
************************************************************
* Name: Nitesh Parajuli *
* Project: Project 1 Pinochle C++ *
* Class: CMPS366 OPL *
* Date: 09/29/2020 *
************************************************************
*/
#include"pch.h"
#include "Player.h"
/* *********************************************************************
Function Name: Player
Purpose: To construct a player object
Parameters:
Return Value: None
Algorithm:
Assistance Received: None
********************************************************************* */
Player::Player()
{
mPlayerRoundScore = 0;
mPlayerTotalScore = 0;
quitGame = false;
}
/* *********************************************************************
Function Name: printHandCards
Purpose: To display cards in hand pile to console
Parameters:
Return Value: None
Local Variables: None
Algorithm: Loop through mHandPile vector and display the card
Assistance Received: None
********************************************************************* */
void Player::printHandCards()
{
for (int i = 0; i < mHandPile.size(); i++)
{
cout << mHandPile[i]->getFace() << mHandPile[i]->getSuit() << " ";
}
cout << endl;
}
/* *********************************************************************
Function Name: printCapturePile
Purpose: To display cards in capture pile to console
Parameters:
Return Value: None
Local Variables: None
Algorithm: Loop through mCapturePile vector and display the card
Assistance Received: None
********************************************************************* */
void Player::printCapturePile()
{
for (int i = 0; i < mCapturePile.size(); i++)
{
cout << mCapturePile[i]->getFace() << mCapturePile[i]->getSuit()<<" ";
}
cout << endl;
}
/* *********************************************************************
Function Name: dealSingleCard
Purpose: To add new cards from the stock pile to mHandPile and mPlayablePile
Parameters:
Return Value: None
Local Variables: None
Algorithm: Push newly drawn card to hand pile and playable pile
Assistance Received: None
********************************************************************* */
void Player::dealSingleCard(Card* card)
{
mHandPile.push_back(card);
mPlayablePile.push_back(card);
}
/* *********************************************************************
Function Name: clearPilesandScores
Purpose: To reset all piles and scores for a new round
Parameters:
Return Value: None
Local Variables: None
Algorithm: Clear all piles and reset round score
Assistance Received: None
********************************************************************* */
void Player::clearPilesandScores()
{
this->mHandPile.clear();
this->meldMap.clear();
this->mPlayablePile.clear();
this->mCapturePile.clear();
this->activeMelds.clear();
this->mPlayerRoundScore = 0;
}
/* *********************************************************************
Function Name: updateMeldMap
Purpose: To add new meld card to meldMap with meldType and remove the card from hand pile
Parameters:
1. card - pointer to card object that needs to be added to meldmap and removed from hand pile
2. meldType - string, the name of the meld
Return Value: None
Local Variables: None
Algorithm:
1. Add the new meld card in meldMap and link it to meldType
2. Remove the meld card from hand pile
Assistance Received: None
********************************************************************* */
void Player::updateMeldMap(Card* card, string meldType)
{
(this->meldMap[card]).push_back(meldType);
this->mHandPile.erase(remove(this->mHandPile.begin(), this->mHandPile.end(), card), this->mHandPile.end());
}
/* *********************************************************************
Function Name: getActiveMeld
Purpose: To display a string containing all valid active melds to the console or to save it to file.
Parameters:
Return Value:
returnVal -string, a string containing all melds (comma separated) displayed as per project's requirement
Local Variables:
mapIndex - int, a reference integer representing the current key in the map
Algorithm:
1. Iterate through the activeMelds map
2. For each iteration,
1. Display the cards linked to the meld
2. Add '*' if the card is being used for more than one active meld
Assistance Received: None
********************************************************************* */
string Player::getActiveMeld()
{
string returnVal = "";
map<string, vector<vector<Card*>>>::iterator it;
int mapIndex = 0;
for (it= activeMelds.begin();it!=activeMelds.end();it++)
{
mapIndex++;
for (int i = 0; i < it->second.size(); i++)
{
for (int j = 0; j < it->second[i].size(); j++)
{
if (it->second[i][j]->getActiveMeldNums() > 1)
{
returnVal += it->second[i][j]->getFace();
returnVal += it->second[i][j]->getSuit();
returnVal += "* ";
}
else
{
returnVal += it->second[i][j]->getFace();
returnVal += it->second[i][j]->getSuit();
returnVal += " ";
}
}
if (mapIndex < activeMelds.size())
{
returnVal += ", ";
}
else if(i != it->second.size()-1)
{
returnVal += ", ";
}
else
{
continue;
}
}
}
return returnVal;
}
/* *********************************************************************
Function Name: displayPlayerStats
Purpose: To display a player's hand pile, capture pile, active melds, and scores to the console
Parameters:
Return Value:
Local Variables:
Algorithm: Use respective utility functions to display required stats to the screen
Assistance Received: None
********************************************************************* */
void Player::displayPlayerStats()
{
cout << "\tHand: ";
this->printHandCards();
cout << "\tCapture Pile: ";
this->printCapturePile();
cout << "\tMeld: ";
cout<<this->getActiveMeld()<<endl;
cout << "\tRound Score: " << this->getPlayerRoundScore() << endl;
cout << "\tTotal Score: " << this->getPlayerTotalScore() << endl << endl;
}
/* *********************************************************************
Function Name: validateMeldCards
Purpose: To check if a set of cards can yield a legit meld and award points accordingly
Parameters:
meldCards - vector containing a set of cards supplied by the player for the meld
Return Value:
meldPoints - int, the points rewarded for the meld
Local Variables:
hasANewMeldCard - bool, a flag which checks if at least one new card has been used for the meld
playerMeldMap -map, player's current meld map which stores the cards used by the player for melds so far with the meld names linked to it
reUsedCards - bool, a flag which checks if any cards supplied has already been used for a meld with same name
cardValues - vector, a vector containing the string representation of the cards used for the meld
meldType - string, the meld that is generated by the supplied card
Algorithm:
1. For each card
1. Loop through player's meld map and check if the card has already been used for a meld.
2. If at least one new card is found,
3. Get the which meld is yielded by the set of supplied cards
4. Iterate through the player's meld map and check if any of the supplied card has already been used for the same meld name
5. If not, assign appropriate meld points.
6. If yes, break and assign 0 meld points.
3. Else, break and assign 0 meldPoints.
4. Return meldPoints
Assistance Received: None
********************************************************************* */
int Player::validateMeldCards(vector<Card*> meldCards)
{
if (meldCards.size() > 0)
{
bool hasANewMeldCard = false;
map<Card*, vector<string>> playerMeldMap = this->getMeldMap();
for (int k = 0; k < meldCards.size(); k++)
{
map<Card*, vector<string>>::iterator it;
it = playerMeldMap.find(meldCards[k]);
if (it == playerMeldMap.end())
{
hasANewMeldCard = true;
break;
}
}
int meldPoints = 0;
bool reUsedCards = false;
if (hasANewMeldCard)
{
vector<string> cardValues;
for (int i = 0; i < meldCards.size(); i++)
{
cardValues.push_back(meldCards[i]->getFace() + meldCards[i]->getSuit());
}
char trumpSuit = trumpCard->getSuit()[0];
string meldType = getMeldType(cardValues,trumpSuit);
if (meldType != "None")
{
for (int i = 0; i < meldCards.size(); i++)
{
map<Card*, vector<string>>::iterator it;
it = playerMeldMap.find(meldCards[i]);
if (it != playerMeldMap.end())
{
vector<string>::iterator vecIt;
vecIt = find((it->second).begin(), (it->second).end(), meldType);
if (vecIt != (it->second).end())
{
//cout << "One of your cards has already been used for the same meld. No points earned" << endl;
reUsedCards = true;
meldPoints = 0;
break;
}
}
}
if (!reUsedCards)
{
meldPoints = getMeldPoints(meldType);
//cout << "A " << meldType << " meld" << endl;
}
}
else
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
meldPoints = 0;
}
return meldPoints;
}
else
{
//cout << "All cards supplied have already been used for a meld. Moving on." << endl;
meldPoints = 0;
}
//this->updatePlayerScore(meldPoints);
}
return 0;
}
/* *********************************************************************
Function Name: getMeldType
Purpose: To get the meld type based on cards supplied
Parameters:
meldCards - vector containing a set of string representations of the supplied cards
trumpSuit - char, the trump suit
Return Value:
meldType - string, the name of the meld yielded
Local Variables:
numCards - int, number of cards supplied by the user
Algorithm:
1. Identify the number of cards being used for the meld.
2. Based on the number of cards, check if they can yield a meld based on game's requirement
3. If yes, set the meld type
4. If not, set meldType to None
5. If not, set meldType to None
6. Return meldType
Assistance Received: None
********************************************************************* */
string Player::getMeldType(vector<string> meldCards, char trumpSuit)
{
int numCards = meldCards.size();
string meldType = "";
//char trumpSuit = trumpCard->getSuit()[0];
if (numCards == 1)
{
if (meldCards[0][0] == '9' && meldCards[0][1] == trumpSuit)
{
meldType = "Dix";
}
else
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
meldType = "None";
}
}
else if (numCards == 2)
{
int i = 0;
if ((meldCards[i][0] == 'J' && meldCards[i][1] == 'D') && (meldCards[i + 1][0] == 'Q' && meldCards[i + 1][1] == 'S'))
{
//cout << "A Pinochle meld. You've earned 40 points" << endl;
meldType = "Pinochle";
}
else if ((meldCards[i][0] == 'Q' && meldCards[i][1] == 'S') && (meldCards[i + 1][0] == 'J' && meldCards[i + 1][1] == 'D'))
{
//cout << "A Pinochle meld. You've earned 40 points" << endl;
meldType = "Pinochle";
}
else if ((meldCards[i][0] == 'K' && meldCards[i][1] == trumpSuit) && (meldCards[i + 1][0] == 'Q' && meldCards[i+1][1] == trumpSuit))
{
//cout << "A royal marriage. You've earned 40 points" << endl;
meldType = "RoyalMarriage";
}
else if ((meldCards[i][0] == 'Q' && meldCards[i][1] == trumpSuit) && (meldCards[i + 1][0] == 'K' && meldCards[i + 1][1] == trumpSuit))
{
//cout << "A royal marriage. You've earned 40 points" << endl;
meldType = "RoyalMarriage";
}
else if ((meldCards[i][1] == meldCards[i + 1][1]) &&
(meldCards[i][0] == 'K' || meldCards[i][0] == 'Q') &&
(meldCards[i + 1][0] == 'Q' || meldCards[i + 1][0] == 'K') &&
(meldCards[i][0] != meldCards[i + 1][0]))
{
//cout << "A marriage. You've earned 20 points" << endl;
meldType = "Marriage";
}
else
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
meldType = "None";
}
}
else if (numCards == 4)
{
bool isSameFace = true;
bool isUniqueSuit = true;
char cardFace = meldCards[0][0];
if (cardFace == 'J' || cardFace == 'Q' || cardFace == 'K' || cardFace == 'A')
{
for (int i = 1; i < numCards; i++)
{
if (meldCards[i][0] != cardFace)
{
//cout << "None" << endl;
isSameFace = false;
meldType = "None";
break;
}
}
for (int i = 0; i < numCards - 1; i++)
{
for (int j = i + 1; j < numCards; j++)
{
if (meldCards[i][1] == meldCards[j][1])
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
isUniqueSuit = false;
meldType = "None";
break;
}
}
}
if (isSameFace && isUniqueSuit)
{
if (cardFace == 'J')
{
//cout << "Four Jacks meld! You've earned 40 points." << endl;
meldType = "FourJacks";
}
else if (cardFace == 'Q')
{
//cout << "Four Queens meld! You've earned 60 points." << endl;
meldType = "FourQueens";
}
else if (cardFace == 'K')
{
//cout << "Four Kings meld! You've earned 80 points." << endl;
meldType = "FourKings";
}
else if (cardFace == 'A')
{
//cout << "Four Aces meld! You've earned 100 points." << endl;
meldType = "FourAces";
}
else
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
meldType = "None";
}
}
}
else
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
meldType = "None";
}
}
else if (numCards == 5)
{
bool isAllTrumpSuit = true;
bool isAllLegitFlushCards = true;
for (int i = 0; i < numCards; i++)
{
if (meldCards[i][1] != trumpSuit)
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
isAllTrumpSuit = false;
meldType = "None";
break;
}
}
for (int i = 0; i < numCards - 1; i++)
{
for (int j = i + 1; j < numCards; j++)
{
if ((meldCards[i][0] == meldCards[j][0]) || meldCards[i][0] == '9' || meldCards[j][0] == '9')
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
isAllLegitFlushCards = false;
meldType = "None";
break;
}
}
}
if (isAllTrumpSuit && isAllLegitFlushCards)
{
//cout << "A flush meld! You've earned 100 points" << endl;
meldType = "Flush";
}
}
else
{
//cout << "No possible melds with the given cards. You didn't earn any points." << endl;
meldType = "None";
}
return meldType;
}
/* *********************************************************************
Function Name: getMeldPoints
Purpose: To get the points for a meld
Parameters:
meldCards - string, name of the meld
Return Value: meld points
Local Variables:
Algorithm: Return the points of a meld as per game's requirement
Assistance Received: None
********************************************************************* */
int Player::getMeldPoints(string meldType)
{
if (meldType == "Dix")
{
return 10;
}
else if (meldType == "Marriage")
{
return 20;
}
else if (meldType == "Pinochle")
{
return 40;
}
else if (meldType == "RoyalMarriage")
{
return 40;
}
else if (meldType == "FourJacks")
{
return 40;
}
else if (meldType == "FourQueens")
{
return 60;
}
else if (meldType == "FourKings")
{
return 80;
}
else if (meldType == "FourAces")
{
return 100;
}
else if (meldType == "Flush")
{
return 150;
}
else
{
return 0;
}
return 0;
}
/* *********************************************************************
Function Name: totalPossibleMelds
Purpose: To get all possible melds from a set of cards
Parameters:
cards - vector, a list of pointers to cards
Return Value:
possibleMelds - map, a map with meld type as key, and a list of list of cards used for that meld type
Local Variables:
returnPoints - int, the meld points returned for a set of cards
referencedCard - vector, a utility vector to keep track of the referenced card
Algorithm: Return the points of a meld as per game's requirement
Assistance Received: None
********************************************************************* */
map<string, vector<vector<Card*>>> Player::totalPossibleMelds(vector<Card*> cards)
{
int returnPoints=0;
vector<bool> referencedCard;
vector < vector<Card*>> combos;
for (int i = 0; i < cards.size(); i++)
{
referencedCard.push_back(false);
}
for (int i = 1; i <= 5; i++)
{
if (i != 3)
{
generateAllCardsCombo(combos, cards, i, 0, 0, referencedCard);
}
}
map<string, vector<vector<Card*>>> possibleMelds;
for (int j = 0; j < combos.size(); j++)
{
vector<string> cardValues;
for (int i = 0; i < combos[j].size(); i++)
{
cardValues.push_back(combos[j][i]->getFace() + combos[j][i]->getSuit());
}
int meldPoint = validateMeldCards(combos[j]);
if (meldPoint > 0)
{
char trumpSuit = trumpCard->getSuit()[0];
string meldType = getMeldType(cardValues, trumpSuit);
possibleMelds[meldType].push_back(combos[j]);
//returnPoints += meldPoint;
}
}
//system("pause");
return possibleMelds;
}
/* *********************************************************************
Function Name: generateAllCardsCombo
Purpose: To genearate a list of all possible combination of certain number of cards
Parameters:
combos - vector, vector storing all generated combinations
cards - vector, pile of cards being used for the generating the combinations
requiredLength - int, number of cards in the desired combination
startIndex -int, the card with reference to which the combination is being generated
currLength -int, the number of cards in the current combinaion
referencedCard - vector, - a utility vector to keep track of which card has been referenced for the combination
Return Value: None
Local Variables:
temp - vector, a vector storing the combinations which needs to be pushed to the combos
Algorithm:
1. check if current length is the desired length, if yes check which card has been referenced and push them in temp vector, and return.
2. if current length exceeds desired length, return.
3. if starting index is the last index in the pile, return.
4. recursively call the function with a next index and for next length
5. change the referencedCard value to indicate that the card is not longer the referenced card
6. recursively call the function by for next index
Assistance Received: None
********************************************************************* */
void Player::generateAllCardsCombo(vector<vector<Card*>>&combos, vector<Card*> cards, int requiredLength, int startIndex, int currLength, vector<bool> referencedCard)
{
if (currLength > requiredLength)
{
return;
}
else if (currLength == requiredLength)
{
vector<Card*> temp;
for (int i = 0; i < cards.size(); i++)
{
if (referencedCard[i] == true)
{
temp.push_back(cards[i]);
}
}
combos.push_back(temp);
return;
}
if (startIndex == cards.size())
{
return;
}
referencedCard[startIndex] = true;
generateAllCardsCombo(combos, cards, requiredLength, startIndex + 1, currLength + 1, referencedCard);
referencedCard[startIndex] = false;
generateAllCardsCombo(combos, cards, requiredLength,startIndex + 1, currLength, referencedCard);
}
/* *********************************************************************
Function Name: bestChaseMove
Purpose: To get the a map storing indexes of the best card for a chase move as its index, and the expensiveness of the card as its value
Parameters:
turninfo - an object of TurnInfo class which includes information about this turn
Return Value:
winningMap - map, a map containing all winning indexes of playable pile as index and their calculated points as value
Local Variables:
leadCard - a pointer to a card which stores lead card value
Algorithm:
1. Loop through the playable pile. For each card, check if it can win the lead card.
2. If yes,
3. check if it's a trump card,
4. If yes, award card point value + 100, and store the card's index and points in the map
5. If no, award card point value only, and store the card's index and points in the map
6. If no,
7. continue running the loop
8. Return the w
Assistance Received: None
********************************************************************* */
map<int, int> Player::bestChaseMove(TurnInfo* turnInfo)
{
int mostInexpensiveIndex = 0;
Card* leadCard = turnInfo->getLeadCard();
map<int, int> winningMap;
for (int i = 0; i < mPlayablePile.size(); i++)
{
if (mPlayablePile[i]->getSuit() == leadCard->getSuit() && leadCard->getSuit() == trumpCard->getSuit())
{
if (mPlayablePile[i]->convertFaceToPoints() > leadCard->convertFaceToPoints())
{
winningMap[i] = 100 + mPlayablePile[i]->convertFaceToPoints();
}
}
else if (mPlayablePile[i]->getSuit() == leadCard->getSuit())
{
if (mPlayablePile[i]->convertFaceToPoints() > leadCard->convertFaceToPoints())
{
winningMap[i] = mPlayablePile[i]->convertFaceToPoints();
}
}
else if (mPlayablePile[i]->getSuit() == trumpCard->getSuit())
{
winningMap[i] = 100 + mPlayablePile[i]->convertFaceToPoints();
}
else
{
continue;
}
}
return winningMap;
}
/* *********************************************************************
Function Name: bestLeadMove
Purpose: To get the index of the best possible playable card after meld consideration
Parameters:
turninfo - an object of TurnInfo class which includes information about this turn
Return Value:
bestPlayableCard - int, the index of the best playable card
Local Variables:
maximumMeldPoints - int, the maximum possible meldpoints that could be saved when a card is played
winningMap - map, a map containing all card indexes of playable pile as its index, and the meld points that will be left if that card is played
checkCard - pointer to a card which is undergoing the checking process
tempCheckVec - vector, a list of all remaining cards left in the pile after a card is played
possibleMelds - map, a map storing all possible valid melds and the cards used for that meld from tempCheckVec
totalMeldPoints - int , sotres the meldPoints that could be generated from each meldtype of possibleMelds
Algorithm:
1. Loop thorugh the pile to find the playability of each card, for each card,
2. Create a temp vetor storing the remaining cards and find the meldpoints that the temp vector can yield
3. compare the meldpoints with the maximum meld points so far and update if the current meldPoint is the maximum so far
4. store the card and the meldpoints that could be generated if the card is played in winning map
5. Loop through the winning map,
6. For each iteration see if the linked points is maximum generated meldPoints for a card in the pile
7. If yes, compare its expensiveness with the previous cards in the map and track the strongest playable card among such cards
8. If not, do nothing.
9. Return the strongest playable card
Assistance Received: None
********************************************************************* */
int Player::bestLeadMove(TurnInfo* turnInfo)
{
int bestPlayableCard = 0;
int maximumMeldPoints = 0;
map<int, int> winningMap;
for (int i = 0; i < mPlayablePile.size(); i++)
{
Card* checkCard = mPlayablePile[i];
vector<Card*> tempCheckVec;
for (int j = 0; j < mPlayablePile.size(); j++)
{
if (mPlayablePile[j] != checkCard)
{
tempCheckVec.push_back(mPlayablePile[j]);
}
}
map<string, vector<vector<Card*>>> possibleMelds = totalPossibleMelds(tempCheckVec);
int totalMeldPoints = 0;
for (auto& i : possibleMelds)
{
string meldType = i.first;
totalMeldPoints += i.second.size() * getMeldPoints(meldType);
}
if (maximumMeldPoints < totalMeldPoints)
{
maximumMeldPoints = totalMeldPoints;
}
winningMap[i] = totalMeldPoints;
}
bool checkBegin = false;
for (auto& t : winningMap)
{
if (t.second == maximumMeldPoints)
{
if (checkBegin)
{
int prevPoint = mPlayablePile[bestPlayableCard]->convertFaceToPoints();
if (mPlayablePile[bestPlayableCard]->getSuit() == trumpCard->getSuit())
{
prevPoint = 100 + prevPoint;
}
int thisPoint = mPlayablePile[t.first]->convertFaceToPoints();
if (mPlayablePile[t.first]->getSuit() == trumpCard->getSuit())
{
thisPoint = 100 + thisPoint;
}
if (thisPoint > prevPoint)
{
bestPlayableCard = t.first;
}
}
else
{
bestPlayableCard = t.first;
checkBegin = true;
}
}
}
return bestPlayableCard;
}
/* *********************************************************************
Function Name: removePlayedCard
Purpose: To remove the played card from all piles that needs to get rid of it
Parameters:
playedCard - a pointer to the played card
Return Value: None
Local Variables:
found -bool, a flag indicating if the card is found in the active meld map
removeVec - vector, a list of used in the meld which also includes the played card
Algorithm:
1. Remove the card from playable pile if it exists
2. Remove the card from hand pile if it exists
3. Remove the card from meld pile if it exists
4. Iterate through the active meld map, and for each meldType present in the meld map, see if the played card has been used for that meld type
5. If yes, get the set of cards and remove played card from it and decrement activeMeldsUsedFor value.
6. Check if other cards in that set have been used for other melds,
7. If yes do not move them to hand pile but decrement its activeMeldsUsedFor value
8. If not, move them to the handpile and decrement its activeMeldsUsedFor value
9. Remove the set of cards from the active meld
10. If not, continue the checking process for other meldtype.
11. Remove the cards from meld map if it exists as we longer need to track its meld history.
Assistance Received: None
********************************************************************* */
void Player::removePlayedCard(Card* playedCard)
{
this->mPlayablePile.erase(remove(this->mPlayablePile.begin(), this->mPlayablePile.end(), playedCard), this->mPlayablePile.end());
this->mHandPile.erase(remove(this->mHandPile.begin(), this->mHandPile.end(), playedCard), this->mHandPile.end());
this->mMeldPile.erase(remove(this->mMeldPile.begin(), this->mMeldPile.end(), playedCard), this->mMeldPile.end());
map<string, vector<vector<Card*>>>::iterator it;
for (it=activeMelds.begin();it!=activeMelds.end();)
{
bool found = false;
for (int count1 = 0; count1 < it->second.size(); count1++)
{
for (int count2 = 0; count2 < it->second[count1].size(); count2++)
{
if (it->second[count1][count2] == playedCard)
{
found = true;
playedCard->setActiveMeldNums(-1);
break;
}
}
if (found == true)
{
vector<Card*> removeVec = it->second[count1];
removeVec.erase(remove(removeVec.begin(), removeVec.end(), playedCard), removeVec.end());
for (int i = 0; i < removeVec.size(); i++)
{
if (removeVec[i]->getActiveMeldNums() == 1)
{
mHandPile.push_back(removeVec[i]);
this->mMeldPile.erase(remove(this->mMeldPile.begin(), this->mMeldPile.end(), removeVec[i]), this->mMeldPile.end());
}
removeVec[i]->setActiveMeldNums(-1);
}
it->second.erase(it->second.begin() + count1);
}
}
if (it->second.empty() == true)
{
it = activeMelds.erase(it);
}
else
{
it++;
}
}
map<Card*, vector<string>>::iterator it1;
it1 = this->meldMap.find(playedCard);
if (it1 != this->meldMap.end())
{
this->meldMap.erase(it1);
}
}
/* *********************************************************************
Function Name: savePlayersStats
Purpose: To save the current stats of the player to a save file
Parameters:
saveFile - object of the ofstream class used to write to a file
Return Value: None
Local Variables:
Algorithm:
Get all the stats that need to be saved, using accessor and utility functions and write them in a file in required format.
Assistance Received: None
********************************************************************* */
void Player::savePlayersStats(ofstream &saveFile)
{
saveFile << "\tScore: " << this->getPlayerTotalScore() << " / " << this->getPlayerRoundScore() << "\n";
saveFile << "\tHand: ";
for (int i = 0; i < this->getHandPile().size(); i++)
{
saveFile << (this->getHandPile()[i])->getFace() << (this->getHandPile()[i]->getSuit()) << " ";
}
saveFile << "\n";
saveFile << "\tCapture Pile: ";
for (int i = 0; i < this->getCapturePile().size(); i++)
{
saveFile << (this->getCapturePile()[i])->getFace() << (this->getCapturePile()[i]->getSuit()) << " ";
}
saveFile << "\n";
saveFile << "\tMelds: " << this->getActiveMeld() << "\n\n";
}
/* *********************************************************************
Function Name: loadScores
Purpose: To load player's round score and total score from a saved file
Parameters:
score -string, the string which indicates player's scores in the saved file
Return Value: None
Local Variables:
scores - vector, a vector which sotres total score and round score of the player
ss - object of stringstream class used to read the score string in saved file
Algorithm:
Parse the string and get round score and total score and store them in the scores vector
Update the player's member variables holding the round scores and total scores by accessing scores from the vector
Assistance Received: None
********************************************************************* */
void Player::loadScores(string score)
{
vector<int> scores;
stringstream ss(score);
for (int i; ss >> i;)
{
scores.push_back(i);
while (ss.peek() == '/' || ss.peek() == ' ')
ss.ignore();
}
this->mPlayerTotalScore = scores[0];
this->mPlayerRoundScore = scores[1];
}
/* *********************************************************************
Function Name: loadHandPile
Purpose: To load player's hand pile
Parameters:
pile -string, the string which indicates player's hand pile in the saved file
Return Value: None
Local Variables:
ss - object of stringstream class used to read the pile string in saved file
Algorithm:
Parse the pile string and get each card from it. For each Create a new card object for it and store its face and suit value, and push it to player's handPile and playablePile
Assistance Received: None
********************************************************************* */
void Player::loadHandPile(string pile)
{
istringstream ss(pile);
if (!pile.empty())
{
string card;
while(ss>>card)
{
if (!card.empty())
{
string face(1, card[0]);
string suit(1, card[1]);
Card* newCard = new Card(face, suit);
mHandPile.push_back(newCard);
mPlayablePile.push_back(newCard);
}
}
}
}
/* *********************************************************************
Function Name: loadCapturePile
Purpose: To load player's capture pile
Parameters:
pile -string, the string which indicates player's capture pile in the saved file
Return Value: None
Local Variables:
ss - object of stringstream class used to read the pile string in saved file
Algorithm:
Parse the pile string and get each card from it. For each create a new card object for it and store its face and suit value, and push it to player's capture pile.
Assistance Received: None
********************************************************************* */
void Player::loadCapturePile(string pile)
{
istringstream ss(pile);
if (!pile.empty())
{
string card;
while (ss >> card)
{
if (!card.empty())
{
string face(1, card[0]);
string suit(1, card[1]);
mCapturePile.push_back(new Card(face, suit));
}
}
}
}
/* *********************************************************************
Function Name: loadCapturePile
Purpose: To load player's meld pile, meld map, and activeMelds
Parameters:
pile -string, the string which indicates player's melds in the saved file
trumpSuit - char, the trump suit of the round
Return Value: None
Local Variables:
repeatedCards - vector, a vector storing the cards with '*' value
ss - object of stringstream class used to read the melds string in saved file
tempMeldMap - map, a temp meld map which regularly updates itself and represents the player's meld map after final verification
meldTrack - map, a map which holds the nth meld in the melds string in the saved file and links to it's meld type
meldNum - int, the position of a meld in the melds string
Algorithm:
1. Retrive each meld from melds by using the ',' delimitter, identify its meld Type based on the cards used in the meld, and store it's position within the melds string with its meldType in the meldTrack map
2. Iterate through the melds string, for each meld in the melds string
3. Split the meld string into its card values
4. See if the card has an '*' linked to it.
5. If not, create a new card object for it and push it to meld pile, tempMeldMap with its meld type.
6. If yes, check the tempMeldMap to see if the card has already been used for a same meld name
7. If yes, create a new card object for it and push it to meld pile, tempMeldMap with its meld type.
8. If not, check if it has been used for any other meld names so far by referencing the repeatedMelds vector.
9. If yes, do not create a new card for it as it might be the same card object. But update its tempMeldMap value to indicate its usage for a second meld.
10. If not, create a new card object for it as it's the card's first appearance and push it to meld pile, tempMeldMap with its meld type, and repeatedCards vector.
5. Update the player's active melds to store the meld type and the cards used in that meld type.
6. Iterate through each card in the repeated card vector to check for correct meld assignments. For each card
7. Reference the temp meld map and find the number of melds it has been used for.
8. If the number is less than 2, get the card's face value. Reference the tempMeldMap and find the other card with the same face value.
9. Find number of melds the the other card has been used for, if that's greater than 2, find the melds that card is linked to.
10 . Find a meld type that the current card in repeated card hasn't been used for. And link the current card to that meld. Update this information in tempMeldMap, and active melds.
11. Copy the content of tempMeldMap to player's meldmap.
12. Store the index values of tempMeldMap in meld pile, and playable pile.
13. Update the activeMeldsUsed for value for each card using tempMeldMap.
Assistance Received: None
********************************************************************* */
void Player::loadMeldPile(string pile, char trumpSuit)
{
vector<Card*> repeatedCards;
stringstream ss(pile);
map<Card*, vector<string>> tempMeldMap;
map<int, string> meldTrack;
int meldNum = 0;
while (ss.good())
{
string eachMeld;
getline(ss, eachMeld, ',');
while (!eachMeld.empty() && eachMeld[eachMeld.size() - 1] == ' ')
{
eachMeld.pop_back();
}
istringstream ss(eachMeld);
if (!pile.empty())
{
vector<string> cards;
string card;
while (ss >> card)
{
if (card[card.size() - 1] == '*')
{
card.pop_back();
}
cards.push_back(card);
}
string meldType = getMeldType(cards,trumpSuit);
meldTrack[meldNum] = meldType;
meldNum++;
}
}
meldNum = 0;
stringstream ss2(pile);
while (ss2.good())
{
string eachMeld;
getline(ss2, eachMeld, ',');
while (!eachMeld.empty() && eachMeld[eachMeld.size() - 1] == ' ')
{
eachMeld.pop_back();
}
istringstream ss(eachMeld);
if (!pile.empty())
{
vector<string> cards;
vector<Card*> thisMeldCards;
string card;
string thisMeld = meldTrack[meldNum];
while (ss >> card)
{
if (card[card.size() - 1] == '*')
{
map<Card*, vector<string>>::iterator it;
bool firstInstance = true;
for (it = tempMeldMap.begin(); it != tempMeldMap.end(); it++)
{
char thisFace = it->first->getFace()[0];
char thisSuit = it->first->getSuit()[0];
if (thisFace == card[0] && thisSuit == card[1])
{
firstInstance = false;
auto vecIt = find(it->second.begin(), it->second.end(), thisMeld);
if (vecIt != it->second.end())
{
string face(1, card[0]);
string suit(1, card[1]);
Card* newCard = new Card(face, suit);
tempMeldMap[newCard].push_back(thisMeld);
thisMeldCards.push_back(newCard);
repeatedCards.push_back(newCard);
}
else
{
tempMeldMap[it->first].push_back(thisMeld);
thisMeldCards.push_back(it->first);
auto repVecIt = find(repeatedCards.begin(), repeatedCards.end(), it->first);
if (repVecIt == repeatedCards.end())
{
repeatedCards.push_back(it->first);
}
}
break;
}
else
{
continue;
}
}
if (firstInstance)
{
string face(1, card[0]);
string suit(1, card[1]);
Card* newCard = new Card(face, suit);
tempMeldMap[newCard].push_back(thisMeld);
thisMeldCards.push_back(newCard);
}
}
else
{
string face(1, card[0]);
string suit(1, card[1]);
Card* newCard = new Card(face, suit);
tempMeldMap[newCard].push_back(thisMeld);
thisMeldCards.push_back(newCard);
}
}
activeMelds[thisMeld].push_back(thisMeldCards);
meldNum++;
}
}
for (int i = 0; i < repeatedCards.size(); i++)
{
int numCards = tempMeldMap[repeatedCards[i]].size();
if (numCards < 2)
{
string meldOne = tempMeldMap[repeatedCards[i]][0];
string face = repeatedCards[i]->getFace();
string suit = repeatedCards[i]->getSuit();
for (auto it = tempMeldMap.begin(); it != tempMeldMap.end(); it++)
{
if (it->first != repeatedCards[i])
{
string mapCardFace = it->first->getFace();
string mapCardSuit = it->first->getSuit();
if (mapCardFace == face && mapCardSuit == suit)
{
if (it->second.size() > 2)
{
string meldTransfer;
int j = 0;
while (true)
{
if (it->second[j] != meldOne)
{
meldTransfer = it->second[j];
break;
}
j++;
}
it->second.erase(remove(it->second.begin(), it->second.end(), meldTransfer), it->second.end());
tempMeldMap[repeatedCards[i]].push_back(meldTransfer);
for (int j = 0; j < activeMelds[meldTransfer].size(); j++)
{
auto vecIt = find(activeMelds[meldTransfer][j].begin(), activeMelds[meldTransfer][j].end(), it->first);
if (vecIt != activeMelds[meldTransfer][j].end())
{
*vecIt = repeatedCards[i];
}
}
break;
}
}
}
}
}
}
meldMap.insert(tempMeldMap.begin(), tempMeldMap.end());
for (auto it = tempMeldMap.begin(); it != tempMeldMap.end(); it++)
{
mMeldPile.push_back(it->first);
mPlayablePile.push_back(it->first);
it->first->setActiveMeldNums(it->second.size());
}
}
| 30.357364 | 208 | 0.612472 | [
"object",
"vector"
] |
e5ec8f51d9f6496107b61394914012d8d47af75c | 1,052 | cpp | C++ | Solutions/(1) Vitos Family.cpp | BenSuth/Online-Judge-Solutions | d137d9482586160a27089a38963a8864af02d6ec | [
"MIT"
] | null | null | null | Solutions/(1) Vitos Family.cpp | BenSuth/Online-Judge-Solutions | d137d9482586160a27089a38963a8864af02d6ec | [
"MIT"
] | null | null | null | Solutions/(1) Vitos Family.cpp | BenSuth/Online-Judge-Solutions | d137d9482586160a27089a38963a8864af02d6ec | [
"MIT"
] | null | null | null | /*
UVA 10041 Vito's Family
Ben Sutherland
*/
#include <iostream>
#include <algorithm>
#include <vector>
using std::cin, std::cout, std::endl, std::sort, std::vector;
int main(void)
{
/* Get number of test cases */
int testCase;
cin >> testCase;
int r, mid, distance, temp; // number of relatives, average ditance, distance required to travel, temporary variable
while(testCase--)
{
cin >> r; // get number of relatives
vector<int> location; // store location of each relative in array
distance = 0; // start distance traveled at zero
/* Populate Location */
for (int i = 0; i < r; i++)
{
cin >> temp;
location.push_back(temp);
}
// sort to find the middle/average
sort(location.begin(), location.end());
mid = location[r/2];
/* The minimum distance travelled is the distance from the middle to each point */
for (int i = 0; i < r; i++) distance += abs(location[i] - mid);
cout << distance << endl; // formatted output
}
return 0;
} | 26.3 | 119 | 0.611217 | [
"vector"
] |
e5f930d563440edd3d2e9974a941b1d7eadfd5f7 | 858 | cpp | C++ | series2_handout/unstructured_euler/naca_airfoil.cpp | BeatHubmann/19H-AdvNCSE | 3979f768da933de82bd6ab29bbf31ea9fc31e501 | [
"MIT"
] | 1 | 2020-01-05T22:38:47.000Z | 2020-01-05T22:38:47.000Z | series2_handout/unstructured_euler/naca_airfoil.cpp | BeatHubmann/19H-AdvNCSE | 3979f768da933de82bd6ab29bbf31ea9fc31e501 | [
"MIT"
] | null | null | null | series2_handout/unstructured_euler/naca_airfoil.cpp | BeatHubmann/19H-AdvNCSE | 3979f768da933de82bd6ab29bbf31ea9fc31e501 | [
"MIT"
] | 1 | 2019-12-08T20:43:27.000Z | 2019-12-08T20:43:27.000Z | #include "solve_euler.hpp"
#include "writer.hpp"
int main(int, char **) {
auto mesh = load_naca_mesh(ANCSE_DATA_PATH "/naca.mesh");
int n_cells = mesh.getNumberOfTriangles();
Eigen::MatrixXd u0(n_cells, 4);
for (int i = 0; i < n_cells; ++i) {
double T = 1.0;
double p = 1.0;
double cs = std::sqrt(GAMMA * T);
double M = 0.85; // Mach number
double alpha = 1.0; // angle of attack
double rho = p / T;
double vx = M * cs * std::cos(alpha * M_PI / 180.0);
double vy = M * cs * std::sin(alpha * M_PI / 180.0);
u0(i, 0) = rho;
u0(i, 1) = rho * vx;
u0(i, 2) = rho * vy;
u0(i, 3) = euler::energyFromPVars(rho, vx, vy, p);
}
auto U = solveEuler(u0, mesh, 100.0);
writeMatrixToFile("naca_u.txt", U);
mesh.writeToFile("naca");
}
| 26 | 61 | 0.529138 | [
"mesh"
] |
e5fe69992348e98bec2a4ff77ed0383087491cf5 | 20,922 | cpp | C++ | dbswznm/WznmAMPersonDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | dbswznm/WznmAMPersonDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | dbswznm/WznmAMPersonDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file WznmAMPersonDetail.cpp
* database access for table TblWznmAMPersonDetail (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#include "WznmAMPersonDetail.h"
using namespace std;
using namespace Sbecore;
/******************************************************************************
class WznmAMPersonDetail
******************************************************************************/
WznmAMPersonDetail::WznmAMPersonDetail(
const ubigint ref
, const ubigint refWznmMPerson
, const string x1SrefKType
, const string Val
) {
this->ref = ref;
this->refWznmMPerson = refWznmMPerson;
this->x1SrefKType = x1SrefKType;
this->Val = Val;
};
bool WznmAMPersonDetail::operator==(
const WznmAMPersonDetail& comp
) {
return false;
};
bool WznmAMPersonDetail::operator!=(
const WznmAMPersonDetail& comp
) {
return(!operator==(comp));
};
/******************************************************************************
class ListWznmAMPersonDetail
******************************************************************************/
ListWznmAMPersonDetail::ListWznmAMPersonDetail() {
};
ListWznmAMPersonDetail::ListWznmAMPersonDetail(
const ListWznmAMPersonDetail& src
) {
nodes.resize(src.nodes.size(), NULL);
for (unsigned int i = 0; i < nodes.size(); i++) nodes[i] = new WznmAMPersonDetail(*(src.nodes[i]));
};
ListWznmAMPersonDetail::~ListWznmAMPersonDetail() {
clear();
};
void ListWznmAMPersonDetail::clear() {
for (unsigned int i = 0; i < nodes.size(); i++) if (nodes[i]) delete nodes[i];
nodes.resize(0);
};
unsigned int ListWznmAMPersonDetail::size() const {
return(nodes.size());
};
void ListWznmAMPersonDetail::append(
WznmAMPersonDetail* rec
) {
nodes.push_back(rec);
};
WznmAMPersonDetail* ListWznmAMPersonDetail::operator[](
const uint ix
) {
WznmAMPersonDetail* retval = NULL;
if (ix < size()) retval = nodes[ix];
return retval;
};
ListWznmAMPersonDetail& ListWznmAMPersonDetail::operator=(
const ListWznmAMPersonDetail& src
) {
WznmAMPersonDetail* rec;
if (&src != this) {
clear();
for (unsigned int i = 0; i < src.size(); i++) {
rec = new WznmAMPersonDetail(*(src.nodes[i]));
nodes.push_back(rec);
};
};
return(*this);
};
bool ListWznmAMPersonDetail::operator==(
const ListWznmAMPersonDetail& comp
) {
bool retval;
retval = (size() == comp.size());
if (retval) {
for (unsigned int i = 0; i < size(); i++) {
retval = ( *(nodes[i]) == *(comp.nodes[i]) );
if (!retval) break;
};
};
return retval;
};
bool ListWznmAMPersonDetail::operator!=(
const ListWznmAMPersonDetail& comp
) {
return(!operator==(comp));
};
/******************************************************************************
class TblWznmAMPersonDetail
******************************************************************************/
TblWznmAMPersonDetail::TblWznmAMPersonDetail() {
};
TblWznmAMPersonDetail::~TblWznmAMPersonDetail() {
};
bool TblWznmAMPersonDetail::loadRecBySQL(
const string& sqlstr
, WznmAMPersonDetail** rec
) {
return false;
};
ubigint TblWznmAMPersonDetail::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWznmAMPersonDetail& rst
) {
return 0;
};
ubigint TblWznmAMPersonDetail::insertRec(
WznmAMPersonDetail* rec
) {
return 0;
};
ubigint TblWznmAMPersonDetail::insertNewRec(
WznmAMPersonDetail** rec
, const ubigint refWznmMPerson
, const string x1SrefKType
, const string Val
) {
ubigint retval = 0;
WznmAMPersonDetail* _rec = NULL;
_rec = new WznmAMPersonDetail(0, refWznmMPerson, x1SrefKType, Val);
insertRec(_rec);
retval = _rec->ref;
if (rec == NULL) delete _rec;
else *rec = _rec;
return retval;
};
ubigint TblWznmAMPersonDetail::appendNewRecToRst(
ListWznmAMPersonDetail& rst
, WznmAMPersonDetail** rec
, const ubigint refWznmMPerson
, const string x1SrefKType
, const string Val
) {
ubigint retval = 0;
WznmAMPersonDetail* _rec = NULL;
retval = insertNewRec(&_rec, refWznmMPerson, x1SrefKType, Val);
rst.nodes.push_back(_rec);
if (rec != NULL) *rec = _rec;
return retval;
};
void TblWznmAMPersonDetail::insertRst(
ListWznmAMPersonDetail& rst
, bool transact
) {
};
void TblWznmAMPersonDetail::updateRec(
WznmAMPersonDetail* rec
) {
};
void TblWznmAMPersonDetail::updateRst(
ListWznmAMPersonDetail& rst
, bool transact
) {
};
void TblWznmAMPersonDetail::removeRecByRef(
ubigint ref
) {
};
bool TblWznmAMPersonDetail::loadRecByRef(
ubigint ref
, WznmAMPersonDetail** rec
) {
return false;
};
ubigint TblWznmAMPersonDetail::loadRstByPrs(
ubigint refWznmMPerson
, const bool append
, ListWznmAMPersonDetail& rst
) {
return 0;
};
ubigint TblWznmAMPersonDetail::loadRstByRefs(
vector<ubigint>& refs
, const bool append
, ListWznmAMPersonDetail& rst
) {
ubigint numload = 0;
WznmAMPersonDetail* rec = NULL;
if (!append) rst.clear();
for (unsigned int i = 0; i < refs.size(); i++) if (loadRecByRef(refs[i], &rec)) {
rst.nodes.push_back(rec);
numload++;
};
return numload;
};
#if defined(SBECORE_MAR) || defined(SBECORE_MY)
/******************************************************************************
class MyTblWznmAMPersonDetail
******************************************************************************/
MyTblWznmAMPersonDetail::MyTblWznmAMPersonDetail() :
TblWznmAMPersonDetail()
, MyTable()
{
stmtInsertRec = NULL;
stmtUpdateRec = NULL;
stmtRemoveRecByRef = NULL;
};
MyTblWznmAMPersonDetail::~MyTblWznmAMPersonDetail() {
if (stmtInsertRec) delete(stmtInsertRec);
if (stmtUpdateRec) delete(stmtUpdateRec);
if (stmtRemoveRecByRef) delete(stmtRemoveRecByRef);
};
void MyTblWznmAMPersonDetail::initStatements() {
stmtInsertRec = createStatement("INSERT INTO TblWznmAMPersonDetail (refWznmMPerson, x1SrefKType, Val) VALUES (?,?,?)", false);
stmtUpdateRec = createStatement("UPDATE TblWznmAMPersonDetail SET refWznmMPerson = ?, x1SrefKType = ?, Val = ? WHERE ref = ?", false);
stmtRemoveRecByRef = createStatement("DELETE FROM TblWznmAMPersonDetail WHERE ref = ?", false);
};
bool MyTblWznmAMPersonDetail::loadRecBySQL(
const string& sqlstr
, WznmAMPersonDetail** rec
) {
MYSQL_RES* dbresult; MYSQL_ROW dbrow;
WznmAMPersonDetail* _rec = NULL;
bool retval = false;
if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) {
string dbms = "MyTblWznmAMPersonDetail::loadRecBySQL() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
dbresult = mysql_store_result(dbs);
if (!dbresult) {
string dbms = "MyTblWznmAMPersonDetail::loadRecBySQL() / store result / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
if (mysql_num_rows(dbresult) == 1) {
dbrow = mysql_fetch_row(dbresult);
unsigned long* dblengths = mysql_fetch_lengths(dbresult);
_rec = new WznmAMPersonDetail();
if (dbrow[0]) _rec->ref = atoll((char*) dbrow[0]); else _rec->ref = 0;
if (dbrow[1]) _rec->refWznmMPerson = atoll((char*) dbrow[1]); else _rec->refWznmMPerson = 0;
if (dbrow[2]) _rec->x1SrefKType.assign(dbrow[2], dblengths[2]); else _rec->x1SrefKType = "";
if (dbrow[3]) _rec->Val.assign(dbrow[3], dblengths[3]); else _rec->Val = "";
retval = true;
};
mysql_free_result(dbresult);
*rec = _rec;
return retval;
};
ubigint MyTblWznmAMPersonDetail::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWznmAMPersonDetail& rst
) {
MYSQL_RES* dbresult; MYSQL_ROW dbrow; ubigint numrow; ubigint numread = 0;
WznmAMPersonDetail* rec;
if (!append) rst.clear();
if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) {
string dbms = "MyTblWznmAMPersonDetail::loadRstBySQL() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
dbresult = mysql_store_result(dbs);
if (!dbresult) {
string dbms = "MyTblWznmAMPersonDetail::loadRstBySQL() / store result / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
numrow = mysql_num_rows(dbresult);
if (numrow > 0) {
rst.nodes.reserve(rst.nodes.size() + numrow);
while (numread < numrow) {
dbrow = mysql_fetch_row(dbresult);
unsigned long* dblengths = mysql_fetch_lengths(dbresult);
rec = new WznmAMPersonDetail();
if (dbrow[0]) rec->ref = atoll((char*) dbrow[0]); else rec->ref = 0;
if (dbrow[1]) rec->refWznmMPerson = atoll((char*) dbrow[1]); else rec->refWznmMPerson = 0;
if (dbrow[2]) rec->x1SrefKType.assign(dbrow[2], dblengths[2]); else rec->x1SrefKType = "";
if (dbrow[3]) rec->Val.assign(dbrow[3], dblengths[3]); else rec->Val = "";
rst.nodes.push_back(rec);
numread++;
};
};
mysql_free_result(dbresult);
return(numread);
};
ubigint MyTblWznmAMPersonDetail::insertRec(
WznmAMPersonDetail* rec
) {
unsigned long l[3]; my_bool n[3]; my_bool e[3];
l[1] = rec->x1SrefKType.length();
l[2] = rec->Val.length();
MYSQL_BIND bind[] = {
bindUbigint(&rec->refWznmMPerson,&(l[0]),&(n[0]),&(e[0])),
bindCstring((char*) (rec->x1SrefKType.c_str()),&(l[1]),&(n[1]),&(e[1])),
bindCstring((char*) (rec->Val.c_str()),&(l[2]),&(n[2]),&(e[2]))
};
if (mysql_stmt_bind_param(stmtInsertRec, bind)) {
string dbms = "MyTblWznmAMPersonDetail::insertRec() / bind / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
if (mysql_stmt_execute(stmtInsertRec)) {
string dbms = "MyTblWznmAMPersonDetail::insertRec() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
rec->ref = mysql_stmt_insert_id(stmtInsertRec);
return rec->ref;
};
void MyTblWznmAMPersonDetail::insertRst(
ListWznmAMPersonDetail& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]);
};
void MyTblWznmAMPersonDetail::updateRec(
WznmAMPersonDetail* rec
) {
unsigned long l[4]; my_bool n[4]; my_bool e[4];
l[1] = rec->x1SrefKType.length();
l[2] = rec->Val.length();
MYSQL_BIND bind[] = {
bindUbigint(&rec->refWznmMPerson,&(l[0]),&(n[0]),&(e[0])),
bindCstring((char*) (rec->x1SrefKType.c_str()),&(l[1]),&(n[1]),&(e[1])),
bindCstring((char*) (rec->Val.c_str()),&(l[2]),&(n[2]),&(e[2])),
bindUbigint(&rec->ref,&(l[3]),&(n[3]),&(e[3]))
};
if (mysql_stmt_bind_param(stmtUpdateRec, bind)) {
string dbms = "MyTblWznmAMPersonDetail::updateRec() / bind / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
if (mysql_stmt_execute(stmtUpdateRec)) {
string dbms = "MyTblWznmAMPersonDetail::updateRec() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
};
void MyTblWznmAMPersonDetail::updateRst(
ListWznmAMPersonDetail& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
};
void MyTblWznmAMPersonDetail::removeRecByRef(
ubigint ref
) {
unsigned long l; my_bool n; my_bool e;
MYSQL_BIND bind = bindUbigint(&ref,&l,&n,&e);
if (mysql_stmt_bind_param(stmtRemoveRecByRef, &bind)) {
string dbms = "MyTblWznmAMPersonDetail::removeRecByRef() / bind / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
if (mysql_stmt_execute(stmtRemoveRecByRef)) {
string dbms = "MyTblWznmAMPersonDetail::removeRecByRef() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
};
bool MyTblWznmAMPersonDetail::loadRecByRef(
ubigint ref
, WznmAMPersonDetail** rec
) {
if (ref == 0) {
*rec = NULL;
return false;
};
return loadRecBySQL("SELECT * FROM TblWznmAMPersonDetail WHERE ref = " + to_string(ref), rec);
};
ubigint MyTblWznmAMPersonDetail::loadRstByPrs(
ubigint refWznmMPerson
, const bool append
, ListWznmAMPersonDetail& rst
) {
return loadRstBySQL("SELECT ref, refWznmMPerson, x1SrefKType, Val FROM TblWznmAMPersonDetail WHERE refWznmMPerson = " + to_string(refWznmMPerson) + " ORDER BY x1SrefKType ASC", append, rst);
};
#endif
#if defined(SBECORE_PG)
/******************************************************************************
class PgTblWznmAMPersonDetail
******************************************************************************/
PgTblWznmAMPersonDetail::PgTblWznmAMPersonDetail() :
TblWznmAMPersonDetail()
, PgTable()
{
};
PgTblWznmAMPersonDetail::~PgTblWznmAMPersonDetail() {
// TODO: run SQL DEALLOCATE to free prepared statements
};
void PgTblWznmAMPersonDetail::initStatements() {
createStatement("TblWznmAMPersonDetail_insertRec", "INSERT INTO TblWznmAMPersonDetail (refWznmMPerson, x1SrefKType, Val) VALUES ($1,$2,$3) RETURNING ref", 3);
createStatement("TblWznmAMPersonDetail_updateRec", "UPDATE TblWznmAMPersonDetail SET refWznmMPerson = $1, x1SrefKType = $2, Val = $3 WHERE ref = $4", 4);
createStatement("TblWznmAMPersonDetail_removeRecByRef", "DELETE FROM TblWznmAMPersonDetail WHERE ref = $1", 1);
createStatement("TblWznmAMPersonDetail_loadRecByRef", "SELECT ref, refWznmMPerson, x1SrefKType, Val FROM TblWznmAMPersonDetail WHERE ref = $1", 1);
createStatement("TblWznmAMPersonDetail_loadRstByPrs", "SELECT ref, refWznmMPerson, x1SrefKType, Val FROM TblWznmAMPersonDetail WHERE refWznmMPerson = $1 ORDER BY x1SrefKType ASC", 1);
};
bool PgTblWznmAMPersonDetail::loadRec(
PGresult* res
, WznmAMPersonDetail** rec
) {
char* ptr;
WznmAMPersonDetail* _rec = NULL;
bool retval = false;
if (PQntuples(res) == 1) {
_rec = new WznmAMPersonDetail();
int fnum[] = {
PQfnumber(res, "ref"),
PQfnumber(res, "refwznmmperson"),
PQfnumber(res, "x1srefktype"),
PQfnumber(res, "val")
};
ptr = PQgetvalue(res, 0, fnum[0]); _rec->ref = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[1]); _rec->refWznmMPerson = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[2]); _rec->x1SrefKType.assign(ptr, PQgetlength(res, 0, fnum[2]));
ptr = PQgetvalue(res, 0, fnum[3]); _rec->Val.assign(ptr, PQgetlength(res, 0, fnum[3]));
retval = true;
};
PQclear(res);
*rec = _rec;
return retval;
};
ubigint PgTblWznmAMPersonDetail::loadRst(
PGresult* res
, const bool append
, ListWznmAMPersonDetail& rst
) {
ubigint numrow; ubigint numread = 0; char* ptr;
WznmAMPersonDetail* rec;
if (!append) rst.clear();
numrow = PQntuples(res);
if (numrow > 0) {
rst.nodes.reserve(rst.nodes.size() + numrow);
int fnum[] = {
PQfnumber(res, "ref"),
PQfnumber(res, "refwznmmperson"),
PQfnumber(res, "x1srefktype"),
PQfnumber(res, "val")
};
while (numread < numrow) {
rec = new WznmAMPersonDetail();
ptr = PQgetvalue(res, numread, fnum[0]); rec->ref = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[1]); rec->refWznmMPerson = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[2]); rec->x1SrefKType.assign(ptr, PQgetlength(res, numread, fnum[2]));
ptr = PQgetvalue(res, numread, fnum[3]); rec->Val.assign(ptr, PQgetlength(res, numread, fnum[3]));
rst.nodes.push_back(rec);
numread++;
};
};
PQclear(res);
return numread;
};
bool PgTblWznmAMPersonDetail::loadRecByStmt(
const string& srefStmt
, const unsigned int N
, const char** vals
, const int* l
, const int* f
, WznmAMPersonDetail** rec
) {
PGresult* res;
res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWznmAMPersonDetail::loadRecByStmt(" + srefStmt + ") / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
return loadRec(res, rec);
};
ubigint PgTblWznmAMPersonDetail::loadRstByStmt(
const string& srefStmt
, const unsigned int N
, const char** vals
, const int* l
, const int* f
, const bool append
, ListWznmAMPersonDetail& rst
) {
PGresult* res;
res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWznmAMPersonDetail::loadRstByStmt(" + srefStmt + ") / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
return loadRst(res, append, rst);
};
bool PgTblWznmAMPersonDetail::loadRecBySQL(
const string& sqlstr
, WznmAMPersonDetail** rec
) {
PGresult* res;
res = PQexec(dbs, sqlstr.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWznmAMPersonDetail::loadRecBySQL() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
return loadRec(res, rec);
};
ubigint PgTblWznmAMPersonDetail::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWznmAMPersonDetail& rst
) {
PGresult* res;
res = PQexec(dbs, sqlstr.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWznmAMPersonDetail::loadRstBySQL() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
return loadRst(res, append, rst);
};
ubigint PgTblWznmAMPersonDetail::insertRec(
WznmAMPersonDetail* rec
) {
PGresult* res;
char* ptr;
ubigint _refWznmMPerson = htonl64(rec->refWznmMPerson);
const char* vals[] = {
(char*) &_refWznmMPerson,
rec->x1SrefKType.c_str(),
rec->Val.c_str()
};
const int l[] = {
sizeof(ubigint),
0,
0
};
const int f[] = {1, 0, 0};
res = PQexecPrepared(dbs, "TblWznmAMPersonDetail_insertRec", 3, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWznmAMPersonDetail::insertRec() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
ptr = PQgetvalue(res, 0, 0); rec->ref = atoll(ptr);
PQclear(res);
return rec->ref;
};
void PgTblWznmAMPersonDetail::insertRst(
ListWznmAMPersonDetail& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
};
void PgTblWznmAMPersonDetail::updateRec(
WznmAMPersonDetail* rec
) {
PGresult* res;
ubigint _refWznmMPerson = htonl64(rec->refWznmMPerson);
ubigint _ref = htonl64(rec->ref);
const char* vals[] = {
(char*) &_refWznmMPerson,
rec->x1SrefKType.c_str(),
rec->Val.c_str(),
(char*) &_ref
};
const int l[] = {
sizeof(ubigint),
0,
0,
sizeof(ubigint)
};
const int f[] = {1, 0, 0, 1};
res = PQexecPrepared(dbs, "TblWznmAMPersonDetail_updateRec", 4, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
string dbms = "PgTblWznmAMPersonDetail::updateRec() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
PQclear(res);
};
void PgTblWznmAMPersonDetail::updateRst(
ListWznmAMPersonDetail& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
};
void PgTblWznmAMPersonDetail::removeRecByRef(
ubigint ref
) {
PGresult* res;
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
res = PQexecPrepared(dbs, "TblWznmAMPersonDetail_removeRecByRef", 1, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
string dbms = "PgTblWznmAMPersonDetail::removeRecByRef() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
PQclear(res);
};
bool PgTblWznmAMPersonDetail::loadRecByRef(
ubigint ref
, WznmAMPersonDetail** rec
) {
if (ref == 0) {
*rec = NULL;
return false;
};
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
return loadRecByStmt("TblWznmAMPersonDetail_loadRecByRef", 1, vals, l, f, rec);
};
ubigint PgTblWznmAMPersonDetail::loadRstByPrs(
ubigint refWznmMPerson
, const bool append
, ListWznmAMPersonDetail& rst
) {
ubigint _refWznmMPerson = htonl64(refWznmMPerson);
const char* vals[] = {
(char*) &_refWznmMPerson
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
return loadRstByStmt("TblWznmAMPersonDetail_loadRstByPrs", 1, vals, l, f, append, rst);
};
#endif
| 26.316981 | 191 | 0.662078 | [
"vector"
] |
f91261b948dc05b9283b39c5e9762bea5ef5dca7 | 11,521 | cpp | C++ | crypto/main.cpp | Enecuum/lib-crypto | d266593eb21070783ccadc51cd2ca9392ceff4fa | [
"MIT"
] | null | null | null | crypto/main.cpp | Enecuum/lib-crypto | d266593eb21070783ccadc51cd2ca9392ceff4fa | [
"MIT"
] | null | null | null | crypto/main.cpp | Enecuum/lib-crypto | d266593eb21070783ccadc51cd2ca9392ceff4fa | [
"MIT"
] | null | null | null | /**
* Enecuum Crypto Library source code
* See LICENCE file at the top of the source tree
*
* ******************************************
*
* main.cpp
* Example
*
* ******************************************
*
* Authors: A. Prudanov, I. Korobkov
*/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "crypto.h"
using namespace std;
int main(int argc, char ** argv)
{
BN_CTX* ctx = nullptr;
Curve* curve = nullptr;
EC_POINT* G = nullptr;
ellipticCurve* ec = nullptr;
EC_POINT* Q = nullptr;
vector<EC_POINT*> proj;
EC_POINT* check = nullptr;
EC_POINT* secret = nullptr;
EC_POINT* s1 = nullptr;
BigNumber a(1);
BigNumber b(0);
BigNumber p("80000000000000000000000000000000000200014000000000000000000000000000000000010000800000020000000000000000000000000000000000080003");
BigNumber order("80000000000000000000000000000000000200014000000000000000000000000000000000010000800000020000000000000000000000000000000000080004");
BigNumber gx("2920f2e5b594160385863841d901a3c0a73ba4dca53a8df03dc61d31eb3afcb8c87feeaa3f8ff08f1cca6b5fec5d3f2a4976862cf3c83ebcc4b78ebe87b44177");
BigNumber gy("2c022abadb261d2e79cb693f59cdeeeb8a727086303285e5e629915e665f7aebcbf20b7632c824b56ed197f5642244f3721c41c9d2e2e4aca93e892538cd198a");
BigNumber max_hash("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
BigNumber orderQ("3298c");
cout << "a: " << a.toDecString() << endl;
cout << "b: " << b.toDecString() << endl;
cout << "p: " << p.toDecString() << endl;
cout << "order: " << order.toDecString() << endl;
if (nullptr == (curve = new Curve(a, b, p, order, gx, gy))) {
handleError(NO_MEMORY); return INT_ERROR_RET;
}
BigNumber msk(10000000);
cout << "MSK: " << msk.toDecString() << endl;
BigNumber q = order; // G0 order
if (nullptr == (G = EC_POINT_new(curve->curve))) {
handleError(NO_MEMORY); return INT_ERROR_RET;
}
if (nullptr == (ctx = BN_CTX_new())) {
handleError(NO_MEMORY); return INT_ERROR_RET;
}
if (1 != EC_POINT_set_affine_coordinates_GFp(curve->curve, G, gx.bn, gy.bn, ctx)) {
handleError(NO_MEMORY); return INT_ERROR_RET;
}
std::cout << "\r\n PKG keys generation \r\n";
// Сalc public key for this session
// Second generator G (gens[1], 1158, 92)
// Random element gets from field of q = 13 (~ gens[1])
BigNumber r = getRandom(max_hash);
std::cout << "Random r: " << r.toDecString() << endl;
Integer Ip, Im;
Ip = Integer("6703903964971298549787012499102923063739684112761466562144343758833001675653841939454385015500446199477853424663597373826728056308768000892499915006541827");
Im = Integer(2);
string strIrred("2 1 1 6703903964971298549787012499102923063739684112761466562144343758833001675653841939454385015500446199477853424663597373826728056308768000892499915006541826");
string strA("0 1");
string strB("0 0");
string strG0_x("1 1971424652593645857677685913504949042673180456464917721388355467732670356866868453718540344482523620218083146279366045128738893020712321933640175997249379 4296897641464992034676854814757495000621938623767876348735377415270791885507945430568382535788680955541452197460367952645174915991662132695572019313583345");
string strG0_y("1 5439973223440119070103328012315186243431766339870489830477397472399815594412903491893756952248783128391927052429939035290789135974932506387114453095089572 3254491657578196534138971223937186183707778225921454196686815561535427648524577315556854258504535233566592842007776061702323300678216177012235337721726634");
if (nullptr == (ec = new ellipticCurve(Ip, Im, strIrred, strA, strB))) {
handleError(NO_MEMORY); return INT_ERROR_RET;
}
ellipticCurveFq E_Fq(ec);
BigNumber qhash("7cd925afaffb8466029213a05ae0faaff9c533dfb3ae446dbfcb971e45e2cacf");
Q = getQ(qhash, curve, E_Fq);
std::cout << "Q: ";
printPoint(Q, curve);
std::cout << "Key sharing: " << endl;
vector<BigNumber> ids;
for (int i = 0; i < 100; i++)
ids.push_back(BigNumber(i + 1));
vector<BigNumber> shares = shamir(msk, ids, 100, 3, q);
for (int i = 0; i < shares.size(); i++)
std::cout << "(" << shares[i].toDecString() << "), ";
vector<int> coalition = { 1, 55, 10 };
std::cout << "\r\nShadows: " << "\r\n";
proj = keyProj(coalition, shares, Q, curve);
for (int i = 0; i < proj.size(); i++) {
printPoint(proj[i], curve);
}
vector<int> coalition2 = { 1, 55, 10 };
std::cout << "\r\n Key recovery" << endl;
BigNumber q1("287a1a55f1c28b1c23a27eef69b6a537e5dfd068d43a34951ed645e049d6be0ac805e3c45501be831afe2d40a2395d8c72edb186c6d140bb85ae022a074b");
secret = keyRecovery(proj, coalition2, q1, curve);
std::cout << "Recovered secret SK: \t";
printPoint(secret, curve);
std::cout << "Check secret MSK * Q: \t";
check = mul(msk, Q, curve);
printPoint(check, curve);
//return 0;
std::cout << "\r\n Create signature" << endl;
BigNumber M(200);
BigNumber r2 = getRandom(q);
// R = rP
s1 = mul(r2, G, curve);
//std::cout << "S1: ";
//printPoint(s1, curve);
bool rres = verify_mobile(
"6703903964971298549787012499102923063739684112761466562144343758833001675653841939454385015500446199477853424663597373826728056308768000892499915006541827",
"0 1",
"0 0",
"80000000000000000000000000000000000200014000000000000000000000000000000000010000800000020000000000000000000000000000000000080004",
"2 1 1 6703903964971298549787012499102923063739684112761466562144343758833001675653841939454385015500446199477853424663597373826728056308768000892499915006541826",
"1 1971424652593645857677685913504949042673180456464917721388355467732670356866868453718540344482523620218083146279366045128738893020712321933640175997249379 4296897641464992034676854814757495000621938623767876348735377415270791885507945430568382535788680955541452197460367952645174915991662132695572019313583345",
"1 5439973223440119070103328012315186243431766339870489830477397472399815594412903491893756952248783128391927052429939035290789135974932506387114453095089572 3254491657578196534138971223937186183707778225921454196686815561535427648524577315556854258504535233566592842007776061702323300678216177012235337721726634",
2,
"1 6463583063506853453352145388557562342045097230688492424308762960259148626679694233304792496993896826204859767286406402028661773263552351316088010972635992 1416364819800415093000147933796337994391339019800078311831844813166613331367052012412062135770454209668583451908837134818641138833984169440926085257140004",
"1 6078398104078171632215695320773804401035385252644159046477855921450504663081503930748506940646128360937810792876085571074711657927225554046396682784191095 684613704912171420676283070735540821105033103251441886765466710413059666511493248245492678777726184493459839136863344011812422098470079101205394677191475",
"0 3470831550237819672838077551471498136543133545444604390853161848692005042308124460409689740770641992155090555806050873579947700883623574639834581493212985",
"0 1733574993285795463951614608926130592634635270276769479113634444427354889391360909387986984065006253554975343438496577407919375391296206198317458722434660",
"7cd925afaffb8466029213a05ae0faaff9c533dfb3ae446dbfcb971e45e2cacf",
"e3ef5e0cb7f89dfc1744003d9927bf588936e5a348641cf3984643a96014e22a",
"1 5553161562309620134204294307547179611636685754291535214076054128059515506033993893714735433610207337513297007943745903960736280984281319771387455094363055 6689291821874770449783470798967833024384908153897387642241791007779898182075451742944983283446597677757107561868230869942692013197487003982057559827210919",
"1 1409647240359222769554276508179480635408566023738878356661595724530348198250043359650835609016647773316137383233659454103710745566316894573620890364518372 3885560331261099024236364110126283369754589356789796979215968181927252095476961502262491073346156231135118163091525459453361435352300956275516792143616474"
);
cout << "Verified: " << rres << endl;
cout << "\n ------------------------------------------------------------------------------------ " << endl;
ExtensionField::Element HFq_x, HFq_y, SFq_x, SFq_y, G0_x, G0_y;
E_Fq.field->readElement(strG0_x, G0_x);
E_Fq.field->readElement(strG0_y, G0_y);
ecPoint G0_fq(G0_x, G0_y);
ecPoint MPK_fq;
E_Fq.scalarMultiply(MPK_fq, G0_fq, (Integer)(msk.toDecString()), -1);
cout << "\n MPK_fq: " << endl;
E_Fq.show(MPK_fq);
ecPoint secret_fq = mapToFq(secret, curve, E_Fq);
cout << "\n secret fq: " << endl;
E_Fq.show(secret_fq);
BigNumber hash("e3ef5e0cb7f89dfc1744003d9927bf588936e5a348641cf3984643a96014e22a");
cout << "\n hash: " << hash.toDecString() << endl;
ecPoint H_fq = hashToPoint(hash);
cout << "\n H_fq: " << endl;
E_Fq.show(H_fq);
ecPoint rH, S2_fq;
E_Fq.scalarMultiply(rH, H_fq, (Integer)(r2.toDecString()), -1);//R=6*P, order of P is not required
E_Fq.add(S2_fq,rH, secret_fq);//R=P+Q
cout << "\n S2_fq: " << endl;
E_Fq.show(S2_fq);
ecPoint S1_fq;
E_Fq.scalarMultiply(S1_fq, G0_fq, (Integer)(r2.toDecString()), -1);//R=6*P, order of P is not required
cout << "\n S1_fq: " << endl;
E_Fq.show(S1_fq);
ecPoint Q_Fq = mapToFq(Q, curve, E_Fq);
ecPoint QQ_Fq;
E_Fq.scalarMultiply(QQ_Fq, G0_fq, (Integer)(r.toDecString()), -1);//R=6*P, order of P is not required
BigNumber shash = getRandom(q);
ecPoint S_fq = hashToPointFq(secret_fq, shash, E_Fq);
cout << "\n S_fq: " << endl;
E_Fq.show(S_fq);
cout << "\n Q_Fq: " << endl;
E_Fq.show(Q_Fq);
bool res = verifyTate(S1_fq, S2_fq, hash, MPK_fq, Q_Fq, G0_fq, E_Fq);
cout << "\n res: " << res << endl;
ExtensionField::Element rr, bb, cc;
rr = tatePairing(S2_fq, G0_fq, S_fq, E_Fq);
bb = tatePairing(Q_Fq, MPK_fq, S_fq, E_Fq);
cc = tatePairing(H_fq, S1_fq, S_fq, E_Fq);
string strEta = "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000100000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000010";
BigNumber bnEta("80000000000000000000000000000000000200014000000000000000000000000000000000010000800000020000000000000000000000000000000000080002");
//eta = (p^k - 1)/q
//tate pairing return value should be in `eta` degree
//num = eval_miller(P, Q+S)/eval_miller(P, S)
//return (num^eta)
ExtensionField::Element r1, b1, c1, b1c1;
E_Fq.field->pow(r1, rr, strEta);
E_Fq.field->pow(b1, bb, strEta);
E_Fq.field->pow(c1, cc, strEta);
ExtensionField::Element bbcc;
E_Fq.field->mul(b1c1, b1, c1);
cout << "\n r1: " << endl;
E_Fq.field->writeElement(r1);
cout << "\n b1: " << endl;
E_Fq.field->writeElement(b1);
cout << "\n c1: " << endl;
E_Fq.field->writeElement(c1);
cout << "\n b1c1: " << endl;
E_Fq.field->writeElement(b1c1);
cout << "\n Verified: " << E_Fq.field->areEqual(r1, b1c1) << endl;
cout << "\r\nruntime is: " << clock() / 1000.0 << endl; // время работы программы
EC_POINT_free(s1); s1 = nullptr;
EC_POINT_free(secret); secret = nullptr;
EC_POINT_free(check); check = nullptr;
for (size_t i = 0; i < proj.size(); ++i) {
delete proj[i]; proj[i] = nullptr;
}
EC_POINT_free(Q);
delete ec; ec = nullptr;
EC_POINT_free(G); G = nullptr;
delete curve; curve = nullptr;
BN_CTX_free(ctx); ctx = nullptr;
return 0;
} | 45.718254 | 532 | 0.777797 | [
"vector"
] |
f912b6df18394c2dd0cddaec7ce130e6ae8838c4 | 3,138 | cpp | C++ | code/Core/Source/Render/T3DRenderTarget.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | 1 | 2021-11-16T15:11:52.000Z | 2021-11-16T15:11:52.000Z | code/Core/Source/Render/T3DRenderTarget.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | null | null | null | code/Core/Source/Render/T3DRenderTarget.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | null | null | null | /*******************************************************************************
* This file is part of Tiny3D (Tiny 3D Graphic Rendering Engine)
* Copyright (C) 2015-2020 Answer Wong
* For latest info, see https://github.com/answerear/Tiny3D
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "Render/T3DRenderTarget.h"
namespace Tiny3D
{
//--------------------------------------------------------------------------
T3D_IMPLEMENT_CLASS_1(RenderTarget, Object);
//--------------------------------------------------------------------------
RenderTarget::RenderTarget(const String &name)
: mWidth(0)
, mHeight(0)
, mColorDepth(0)
, mIsActive(true)
, mName(name)
{
}
RenderTarget::~RenderTarget()
{
}
//--------------------------------------------------------------------------
void RenderTarget::render()
{
auto itr = mViewportList.begin();
while (itr != mViewportList.end())
{
itr->second->render();
++itr;
}
}
//--------------------------------------------------------------------------
ViewportPtr RenderTarget::addViewport(CameraPtr camera, long_t zOrder,
Real left, Real top, Real width, Real height)
{
ViewportPtr viewport;
auto itr = mViewportList.find(zOrder);
if (itr == mViewportList.end())
{
viewport = Viewport::create(camera, this, left, top,
width, height, zOrder);
mViewportList.insert(ViewportValue(zOrder, viewport));
}
return viewport;
}
//--------------------------------------------------------------------------
TResult RenderTarget::removeViewport(long_t nZOrder)
{
TResult ret = T3D_OK;
do
{
auto itr = mViewportList.find(nZOrder);
if (itr == mViewportList.end())
{
ret = T3D_ERR_NOT_FOUND;
T3D_LOG_ERROR(LOG_TAG_RENDER,
"RenderTarget remove viewport but not found !!!");
break;
}
mViewportList.erase(itr);
} while (0);
return ret;
}
//--------------------------------------------------------------------------
TResult RenderTarget::removeAllViewports()
{
mViewportList.clear();
return T3D_OK;
}
}
| 28.017857 | 81 | 0.478011 | [
"render",
"object",
"3d"
] |
f91bfd3e6d6ed2c7a43733d74ba8194b411d93fa | 4,000 | hpp | C++ | lib/lvd/type.hpp | vdods/lvd | 864eaa25bdaddfc0dc7e788e693ebae3b42597be | [
"Apache-2.0"
] | null | null | null | lib/lvd/type.hpp | vdods/lvd | 864eaa25bdaddfc0dc7e788e693ebae3b42597be | [
"Apache-2.0"
] | null | null | null | lib/lvd/type.hpp | vdods/lvd | 864eaa25bdaddfc0dc7e788e693ebae3b42597be | [
"Apache-2.0"
] | null | null | null | // 2021.01.22 - Copyright Victor Dods - Licensed under Apache 2.0
#pragma once
namespace lvd {
// This allows an associative container whose key type is Type* to index types,
// using the singleton object for Type_t<T> for each T.
class Type { };
// Can be used as a value to represent the type T_ itself, making it possible to
// have types as first class values. This class has no members, so it's abstractly
// a singleton. There is an inline static singleton instance declared, so its
// address should uniquely identify the type (probably, maybe there are situations
// in which the linker wouldn't collapse them together).
//
// The global function ty<T_>() can be used to conveniently retrieve the Type_t<T_> singleton.
template <typename T_>
class Type_t : public Type {
public:
// For accessing the underlying type.
using T = T_;
// Use of singletons allows ty<T_> (defined below) to be uniquely identified by address,
// and therefore can be used as a runtime value for distinction or mapping. This singleton
// doesn't need to be const, because there's no state that can be changed anyway..
inline static Type_t SINGLETON = Type_t();
// This will call the constructor of T_ with the given args, so that an instance of Type_t<T_>
// can behave like `T_` itself.
template <typename... Args_>
auto operator() (Args_&&... args) const {
return T_(std::forward<Args_>(args)...);
}
template <typename Other_>
constexpr bool operator == (Type_t<Other_> const &) const { return std::is_same_v<T_,Other_>; }
template <typename Other_>
constexpr bool operator != (Type_t<Other_> const &) const { return !std::is_same_v<T_,Other_>; }
// This defines >= for subtype poset.
template <typename Other_>
constexpr bool is_supertype_of (Type_t<Other_> const &) const { return std::is_base_of_v<T_,Other_> || std::is_same_v<T_,Other_>; }
// This defines > for subtype poset.
template <typename Other_>
constexpr bool is_strict_supertype_of (Type_t<Other_> const &) const { return std::is_base_of_v<T_,Other_> && !std::is_same_v<T_,Other_>; }
// This defines <= for subtype poset.
template <typename Other_>
constexpr bool is_subtype_of (Type_t<Other_> const &other) const { return other.is_supertype_of(*this); }
// This defines < for subtype poset.
template <typename Other_>
constexpr bool is_strict_subtype_of (Type_t<Other_> const &other) const { return other.is_strict_supertype_of(*this); }
// This defines `comparable` condition for subtype poset (one type is a subtype of the other)
template <typename Other_>
constexpr bool is_related_to (Type_t<Other_> const &other) const { return this->is_subtype_of(other) || this->is_supertype_of(other); }
// This defines `incomparable` condition for subtype poset (neither is a subtype of the other)
template <typename Other_>
constexpr bool is_unrelated_to (Type_t<Other_> const &other) const { return !this->is_subtype_of(other) && !this->is_supertype_of(other); }
// TODO: Implement functions to produce types like pair, tuple, etc.
};
// This allows very terse use of Type_t<T_>.
template <typename T_>
inline static Type_t<T_> &ty = Type_t<T_>::SINGLETON;
// Convenience functions that does type deduction.
template <typename T_>
Type_t<T_> &type_of (T_ const &) {
return ty<T_>;
}
// // This one returns a non-singleton instance.
// template <typename T_>
// Type_t<T_> make_type_of (T_ const &) {
// return Type_t<T_>();
// }
// Template metafunction for determining if a given type is Type_t<T_> for some T_
template <typename T_> struct is_Type_t : public std::false_type { };
template <typename T_> inline bool constexpr is_Type_t_v = is_Type_t<T_>::value;
template <typename T_> struct is_Type_t<Type_t<T_>> : public std::true_type { };
// Helper for representing variadic sequences of types.
template <typename... Types_>
struct VariadicSequence_t { };
} // end namespace lvd
| 44.444444 | 143 | 0.71625 | [
"object"
] |
f91f8b273200ab2a71320fb50293fc05a39759b9 | 871 | cpp | C++ | Data Structures/Dynamic Programming/2-D DP/Grid Unique Paths/Memoization.cpp | ravikjha7/Competitive_Programming | 86df773c258d6675bb3244030e6d71aa32e01fce | [
"MIT"
] | null | null | null | Data Structures/Dynamic Programming/2-D DP/Grid Unique Paths/Memoization.cpp | ravikjha7/Competitive_Programming | 86df773c258d6675bb3244030e6d71aa32e01fce | [
"MIT"
] | null | null | null | Data Structures/Dynamic Programming/2-D DP/Grid Unique Paths/Memoization.cpp | ravikjha7/Competitive_Programming | 86df773c258d6675bb3244030e6d71aa32e01fce | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define mod 1000000007
void file()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
// Time Complexity : O(n*m)
// Space Complexity : O(n-1+m-1) + O(n*m)
int GridUniquePaths(int i,int j,vector<vector<int>> &dp) {
if(i == 0 || j == 0) {
return 1;
}
if(dp[i][j] != -1) return dp[i][j];
int left = GridUniquePaths(i-1,j,dp);
int up = GridUniquePaths(i,j-1,dp);
// Storing No Of Ways From That Point
return dp[i][j] = left + up;
}
void solve()
{
int n,m;
cin >> n >> m;
int count = 0;
vector<vector<int>> dp(n,vector<int>(m,-1));
cout << GridUniquePaths(n-1,m-1,dp) << endl;
}
int main()
{
file();
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
// cin >> t;
while(t--)
{
solve();
}
return 0;
} | 16.75 | 58 | 0.594719 | [
"vector"
] |
f9227938dedb227f7b30dea724d709052992cbcc | 6,107 | cpp | C++ | src/FileWriter.cpp | hyrise/bencho | 904eeeb420352fc1a5270c5911e9ea1401624eee | [
"MIT"
] | 1 | 2016-02-04T22:07:07.000Z | 2016-02-04T22:07:07.000Z | src/FileWriter.cpp | hyrise/bencho | 904eeeb420352fc1a5270c5911e9ea1401624eee | [
"MIT"
] | null | null | null | src/FileWriter.cpp | hyrise/bencho | 904eeeb420352fc1a5270c5911e9ea1401624eee | [
"MIT"
] | null | null | null | #include "FileWriter.h"
#include <string>
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <unistd.h>
#include "DirectoryManager.h"
#include "Parameter.h"
#include "ConfigFile.h"
#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)
extern char* global_program_invocation_name;
FileWriter::FileWriter(AbstractBenchmark *benchmark)
{
_benchmark = benchmark;
}
void FileWriter::psToPdf(string filename)
{
string command = ConfigFile::getExecutable("ps2pdf") + " " + filename + ".ps " + filename + ".pdf";
_benchmark->getDirectoryManager()->removeFile(filename + ".ps");
std::cout << "Chart written to " << filename << ".pdf" << std::endl;
}
void FileWriter::saveParameters(AbstractBenchmark *benchmark)
{
std::ofstream file;
std::vector<Parameter>::iterator p;
file.open (benchmark->getDirectoryManager()->getFilename(benchmark->getName(), ".parameter.txt").c_str());
file << benchmark->getCurrentVersion() << std::endl;
file << std::endl << benchmark->getName() << std::endl;
file << "################################" << std::endl;
for (p = benchmark->getParameters()->begin(); p != benchmark->getParameters()->end(); p++)
{
if (p->getValues().size() == 1)
{
file << p->getName() << ": " << p->getValues().at(0) << std::endl;
}
else if (p->getValues().size() > 1)
{
file << p->getName() << ": from " << p->getValues().front() << " to " << p->getValues().back() << " in " << p->getValues().size() << " steps." << std::endl;
}
}
char hostname[512];
gethostname(hostname, 512);
file << "Computer: " << hostname << std::endl;
//file << "Executable: " << global_program_invocation_name << std::endl; //ersetzten?
// copy setting.conf
file << "Settings: ";
std::ifstream settings_file(STR(BENCHO_DIR)"/settings.conf");
if (settings_file.is_open())
{
string settings_line;
string settings_line_after;
getline(settings_file, settings_line);
while (settings_file.good())
{
getline(settings_file, settings_line_after);
file << settings_line;
if (!settings_line_after.empty()) file << ", ";
settings_line = settings_line_after;
}
settings_file.close();
}
file << std::endl;
file.close();
std::cout << "Parameters written to " << benchmark->getDirectoryManager()->getFilename(benchmark->getName(), ".parameter.txt") << std::endl;
}
void FileWriter::dumpResult(AbstractBenchmark *benchmark)
{
std::ofstream file;
std::map<int, string>::iterator p;
size_t lines = benchmark->getRowCount();
file.open (benchmark->getDirectoryManager()->getFilename(benchmark->getName(), ".result.csv").c_str());
// write headers
file << "x ";
std::vector<std::map<string, int> > &combinations = benchmark->getCombinations();
std::map<string, int>::iterator it2;
for (it2 = combinations[0].begin(); it2 != combinations[0].end(); it2++)
file << "par_" << it2->first << " ";
std::map<int, string>::iterator it;
for (it = benchmark->getTestSeries().begin(); it != benchmark->getTestSeries().end(); it++)
{
file << it->second << "_incache ";
for (size_t i = 0; i < benchmark->getPerformanceCounters().size(); ++i)
{
file << it->second << "_" << benchmark->getPerformanceCounters()[i] << "_y ";
file << it->second << "_" << benchmark->getPerformanceCounters()[i] << "_error ";
if (benchmark->getRawDataOutput() && !benchmark->getFastMode())
{
for (size_t j = 0; j < benchmark->getMaxRuns(); ++j)
{
file << it->second << "_" << benchmark->getPerformanceCounters()[i] << "_y_raw_" << j << " ";
}
}
}
}
file << std::endl;
// write data
for (size_t line = 0; line < lines; ++line)
{
// write sequence id
file << benchmark->getResult_x(0, benchmark->getPerformanceCounters()[0]).at(line) << " ";
// write paramters
for (it2 = combinations[line].begin(); it2 != combinations[line].end(); it2++)
file << it2->second << " ";
// write results
for (it = benchmark->getTestSeries().begin(); it != benchmark->getTestSeries().end(); it++)
{
file << benchmark->getResult_incache(it->second) << " ";
for (size_t i = 0; i < benchmark->getPerformanceCounters().size(); ++i)
{
file << benchmark->getResult_y(it->first, benchmark->getPerformanceCounters()[i]).at(line) << " ";
file << benchmark->getResult_error(it->first, benchmark->getPerformanceCounters()[i]).at(line) << " ";
if (benchmark->getRawDataOutput() && !benchmark->getFastMode())
{
for (size_t j = 0; j < benchmark->getMaxRuns(); ++j)
{
file << benchmark->getResult_y_raw(it->first, benchmark->getPerformanceCounters()[i]).at(line).at(j) << " ";
}
}
}
}
file << std::endl;
}
file.close();
std::cout << "CSV written to " << benchmark->getDirectoryManager()->getFilename(benchmark->getName(), ".result.csv") << std::endl;
}
std::vector<string> FileWriter::getHeaders(AbstractBenchmark *benchmark)
{
std::vector<string> headers;
std::map<int, string>::iterator it;
for (it = benchmark->getTestSeries().begin(); it != benchmark->getTestSeries().end(); it++)
{
headers.push_back(it->second + "_incache ");
for (size_t i = 0; i < benchmark->getPerformanceCounters().size(); ++i)
{
headers.push_back(it->second + "_" + benchmark->getPerformanceCounters()[i] + "_y");
headers.push_back(it->second + "_" + benchmark->getPerformanceCounters()[i] + "_error");
}
}
return headers;
}
| 33.371585 | 168 | 0.564271 | [
"vector"
] |
234eb7f162ac6a8cb7689dfd1ed439ce04d2261a | 2,701 | cpp | C++ | src/testMap.cpp | SubramanianKrish/dynamic-rrt | 403713636c40bdbd71337de954b7130b7022f004 | [
"MIT"
] | 1 | 2021-05-30T15:50:07.000Z | 2021-05-30T15:50:07.000Z | src/testMap.cpp | SubramanianKrish/dynamic-rrt | 403713636c40bdbd71337de954b7130b7022f004 | [
"MIT"
] | null | null | null | src/testMap.cpp | SubramanianKrish/dynamic-rrt | 403713636c40bdbd71337de954b7130b7022f004 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_set>
#include <unordered_map>
#include "Obstacle.h"
#include "Map.h"
using namespace std;
int main() {
Map test_map;
// get static obstacle vector in the map
vector<Obstacle*> stat_obs = test_map.get_static_obs_vec();
// get map size
double x_size = test_map.get_x_size();
double y_size = test_map.get_y_size();
cout << "Successfully built a test map with " << stat_obs.size() << " obstacles" << endl;
cout << "The map has a size of (" << x_size << "x" << y_size << ")" << endl;
// extract the first obstacle
Obstacle obs1 = *stat_obs[0];
vector<double> feat1 = obs1.get_obs_feature();
// check if obstacle is static
bool is_static = obs1.isStatic();
if (is_static){
cout << "The first obstacle is static"<< endl;
}else{
cout << "The first obstacle is not static"<< endl;
}
// get position of the obstacle
double x1 = feat1[0];
double y1 = feat1[1];
if (feat1.size()==3){ // circular obstacle ==> 3 features
double radius = feat1[2];
cout << "the circular obstacle at position (" << x1 << ", " << y1 << ") has radius " << radius << endl;
}else{ // rectangular obstacle ==> 5 features
double length = feat1[2];
double width = feat1[3];
double theta = feat1[4]; // for testing static obstacles, theta should be 0
cout << "the rectangular obstacle at position (" << x1 << ", " << y1 << ") has length and width (" << length << ", " << width << ")" << endl;
}
// test dynamics obstacle
vector<DynamObstacle*> dynam_obs_vec = test_map.get_dynam_obs_vec();
DynamObstacle d0 = *dynam_obs_vec[0];
// inspect position at different timesteps
double curr_step = 60.0; // TODO: change this value to inspect dynamics obstacle position output
vector<double> dynam_feat0 = d0.get_obs_feature(121.0);
double dynam_x0 = dynam_feat0[0];
double dynam_y0 = dynam_feat0[1];
if (dynam_feat0.size()==3){ // circular obstacle ==> 3 features
double dynam_radius = dynam_feat0[2];
cout << "@ Timestep "<< curr_step << ": the dynamics circular obstacle at position (" << dynam_x0 << ", " << dynam_y0 << ") has radius " << dynam_radius << endl;
}else{ // rectangular obstacle ==> 5 features
double dynam_length = dynam_feat0[2];
double dynam_width = dynam_feat0[3];
double dynam_theta = dynam_feat0[4]; // for testing static obstacles, theta should be 0
cout << "the rectangular obstacle at position (" << dynam_x0 << ", " << dynam_x0 << ") has length and width (" << dynam_length << ", " << dynam_width << ")" << endl;
}
return 0;
}
| 42.873016 | 173 | 0.620511 | [
"vector"
] |
23536633502524556adf45d6d69d5a094a592beb | 1,720 | cpp | C++ | c++/0228-summary-ranges.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | 2 | 2019-04-13T09:55:04.000Z | 2019-05-16T12:47:40.000Z | c++/0228-summary-ranges.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | c++/0228-summary-ranges.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | // 21/11/21 = Sun
// 228. Summary Ranges [Easy]
// You are given a sorted unique integer array nums.
// Return the smallest sorted list of ranges that cover all the numbers in the
// array exactly. That is, each element of nums is covered by exactly one of the
// ranges, and there is no integer x such that x is in one of the ranges but not
// in nums.
// Each range [a,b] in the list should be output as:
// "a->b" if a != b
// "a" if a == b
// Example 1:
// Input: nums = [0,1,2,4,5,7]
// Output: ["0->2","4->5","7"]
// Explanation: The ranges are:
// [0,2] --> "0->2"
// [4,5] --> "4->5"
// [7,7] --> "7"
// Example 2:
// Input: nums = [0,2,3,4,6,8,9]
// Output: ["0","2->4","6","8->9"]
// Explanation: The ranges are:
// [0,0] --> "0"
// [2,4] --> "2->4"
// [6,6] --> "6"
// [8,9] --> "8->9"
// Example 3:
// Input: nums = []
// Output: []
// Example 4:
// Input: nums = [-1]
// Output: ["-1"]
// Example 5:
// Input: nums = [0]
// Output: ["0"]
// Constraints:
// 0 <= nums.length <= 20
// -2^31 <= nums[i] <= 2^31 - 1
// All the values of nums are unique.
// nums is sorted in ascending order.
class Solution {
public:
vector<string> summaryRanges(vector<int> &nums) {
vector<string> res;
if (nums.empty())
return res;
nums.push_back(nums.front());
int beg = nums[0];
int prev = nums[0];
string range = to_string(beg);
for (int i = 1; i != nums.size(); ++i) {
if (static_cast<long long>(nums[i]) != static_cast<long long>(prev) + 1) {
if (beg != prev) {
range += "->" + to_string(prev);
}
res.push_back(range);
beg = nums[i];
range = to_string(beg);
}
prev = nums[i];
}
return res;
}
};
| 22.631579 | 80 | 0.537209 | [
"vector"
] |
235c152373a43c4db92b2a0860d6bea73c604a56 | 796 | cpp | C++ | YKLib/YKObject.cpp | hanhan/YKDataStructuresLib | 8f4680fa25a44c8975004602e55be7f82ae11d1f | [
"MIT"
] | null | null | null | YKLib/YKObject.cpp | hanhan/YKDataStructuresLib | 8f4680fa25a44c8975004602e55be7f82ae11d1f | [
"MIT"
] | null | null | null | YKLib/YKObject.cpp | hanhan/YKDataStructuresLib | 8f4680fa25a44c8975004602e55be7f82ae11d1f | [
"MIT"
] | null | null | null | //
// YKObject.cpp
// YKLib
//
// Copyright © 2017年 nethanhan. All rights reserved.
//
#include "YKObject.hpp"
#include <cstdlib>
namespace YKLib
{
void* YKObject::operator new (unsigned long size) throw()
{
return malloc(size);
}
void YKObject::operator delete (void* p)
{
free(p);
}
void* YKObject::operator new[] (unsigned long size) throw()
{
return malloc(size);
}
void YKObject::operator delete[] (void* p)
{
free(p);
}
bool YKObject::operator == (const YKObject& object)
{
return (this == &object);
}
bool YKObject::operator != (const YKObject& object)
{
return (this != &object);
}
YKObject::~YKObject()
{
}
}
| 15.92 | 63 | 0.527638 | [
"object"
] |
23666a56415f1efe7c0c08100c696476ba145273 | 46,601 | cc | C++ | cartographer/mapping/internal/2d/pose_graph_2d.cc | zhaozhi1995/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | 12 | 2020-11-24T03:46:44.000Z | 2022-03-07T07:35:24.000Z | cartographer/mapping/internal/2d/pose_graph_2d.cc | rancheng/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | null | null | null | cartographer/mapping/internal/2d/pose_graph_2d.cc | rancheng/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | 9 | 2021-01-13T08:58:47.000Z | 2022-03-29T10:27:07.000Z | #include "cartographer/mapping/internal/2d/pose_graph_2d.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <sstream>
#include <string>
#include "Eigen/Eigenvalues"
#include "absl/memory/memory.h"
#include "cartographer/common/math.h"
#include "cartographer/mapping/internal/2d/overlapping_submaps_trimmer_2d.h"
#include "cartographer/mapping/proto/pose_graph/constraint_builder_options.pb.h"
#include "cartographer/sensor/compressed_point_cloud.h"
#include "cartographer/sensor/internal/voxel_filter.h"
#include "cartographer/transform/transform.h"
#include "glog/logging.h"
namespace cartographer {
namespace mapping {
PoseGraph2D::PoseGraph2D(const proto::PoseGraphOptions& options)
: background_thread_running_(false),
options_(options),
constraint_builder_(options_.constraint_builder_options()) {
if (options.has_overlapping_submaps_trimmer_2d()) {
const auto& trimmer_options = options.overlapping_submaps_trimmer_2d();
AddTrimmer(absl::make_unique<OverlappingSubmapsTrimmer2D>(
trimmer_options.fresh_submaps_count(),
trimmer_options.min_covered_area(),
trimmer_options.min_added_submaps_count()));
}
StartBackgroundThread();
}
PoseGraph2D::~PoseGraph2D() {
if (background_thread_running_) {
StopBackgroundThread();
}
}
void PoseGraph2D::StartBackgroundThread() {
CHECK(!background_thread_running_);
background_thread_running_ = true;
background_thread_ = std::thread(&PoseGraph2D::BackgroundThread, this);
}
void PoseGraph2D::StopBackgroundThread() {
CHECK(background_thread_running_);
{
// We take the mutex here despite the atomic bool because
// the thread will wait on a condition that will wake on Unlock()
absl::MutexLock locker(&mutex_);
background_thread_running_ = false;
}
background_thread_.join();
}
NodeId PoseGraph2D::AddNode(
std::shared_ptr<const TrajectoryNode::Data> constant_data,
const int trajectory_id,
const std::vector<std::shared_ptr<const Submap2D>>& insertion_submaps) {
absl::MutexLock locker(&mutex_);
AddTrajectoryIfNeeded(trajectory_id);
CHECK(CanAddWorkItemModifying(trajectory_id));
//
// insertion_submaps are 1 or a 2 submaps
// front() is the old submap = used for matching as it has more data
// back() is a new submap = will transition to front() eventually
//
//
// Determine the correct submap IDs
// Add a new submap if necessary
//
std::vector<SubmapId> submap_ids;
if (data_.submap_data.SizeOfTrajectoryOrZero(trajectory_id) == 0) {
const InternalSubmapData nd{insertion_submaps.back(),
SubmapState::kNoConstraintSearch,
std::set<NodeId>{}};
const SubmapId submap_id = data_.submap_data.Append(trajectory_id, nd);
const transform::Rigid2d global_submap_pose =
transform::Project2D(ComputeLocalToGlobalTransform(
data_.global_submap_poses_2d, trajectory_id) *
insertion_submaps.back()->local_pose());
data_.global_submap_poses_2d.Insert(
submap_id, optimization::SubmapSpec2D{global_submap_pose});
submap_ids.push_back(submap_id);
CHECK(submap_id.submap_index == 0);
} else if (insertion_submaps.size() == 1) {
CHECK_EQ(1, data_.submap_data.SizeOfTrajectoryOrZero(trajectory_id));
const SubmapId submap_id{trajectory_id, 0};
CHECK(data_.submap_data.at(submap_id).submap == insertion_submaps.front());
submap_ids.push_back(submap_id);
} else if (std::prev(data_.submap_data.EndOfTrajectory(trajectory_id))
->data.submap != insertion_submaps.back()) {
const SubmapId submap_id = data_.submap_data.Append(
trajectory_id,
InternalSubmapData{
insertion_submaps.back(), SubmapState::kNoConstraintSearch, {}});
auto end_it = data_.submap_data.EndOfTrajectory(trajectory_id);
const SubmapId back_submap = std::prev(end_it, 1)->id;
const SubmapId front_submap = std::prev(end_it, 2)->id;
CHECK_EQ(back_submap, submap_id);
const transform::Rigid2d front_pose = transform::Project2D(
data_.submap_data.at(front_submap).submap->local_pose());
const transform::Rigid2d back_pose = transform::Project2D(
data_.submap_data.at(back_submap).submap->local_pose());
const transform::Rigid2d last_global_pose =
data_.global_submap_poses_2d.at(front_submap).global_pose;
const transform::Rigid2d global_submap_pose =
last_global_pose * front_pose.inverse() * back_pose;
data_.global_submap_poses_2d.Insert(
submap_id, optimization::SubmapSpec2D{global_submap_pose});
submap_ids.push_back(front_submap);
submap_ids.push_back(back_submap);
CHECK(front_submap.submap_index == back_submap.submap_index - 1);
} else {
auto end_it = data_.submap_data.EndOfTrajectory(trajectory_id);
const SubmapId back_submap = std::prev(end_it, 1)->id;
const SubmapId front_submap = std::prev(end_it, 2)->id;
submap_ids.push_back(front_submap);
submap_ids.push_back(back_submap);
CHECK(front_submap.submap_index == back_submap.submap_index - 1);
}
CHECK_EQ(submap_ids.size(), insertion_submaps.size());
//
// Create a new TrajectoryNode
//
const transform::Rigid3d global_pose(
ComputeLocalToGlobalTransform(data_.global_submap_poses_2d,
trajectory_id) *
constant_data->local_pose);
const NodeId node_id = data_.trajectory_nodes.Append(
trajectory_id, TrajectoryNode{constant_data, global_pose});
//
// Add a constraint and a Node to the current and previous submaps
//
const transform::Rigid2d local_pose_2d =
transform::Project2D(constant_data->local_pose);
for (size_t i = 0; i < insertion_submaps.size(); ++i) {
const SubmapId submap_id = submap_ids[i];
// Even if this was the last node added to 'submap_id', the submap will
// only be marked as finished in 'data_.submap_data' further below.
CHECK(data_.submap_data.at(submap_id).state ==
SubmapState::kNoConstraintSearch);
data_.submap_data.at(submap_id).node_ids.emplace(node_id);
const transform::Rigid2d constraint_transform =
transform::Project2D(insertion_submaps[i]->local_pose()).inverse() *
local_pose_2d;
data_.constraints.push_back(
Constraint{submap_id,
node_id,
{transform::Embed3D(constraint_transform),
options_.matcher_translation_weight(),
options_.matcher_rotation_weight()},
Constraint::INTRA_SUBMAP});
}
if (insertion_submaps.front()->insertion_finished()) {
const SubmapId newly_finished_submap_id = submap_ids.front();
InternalSubmapData& finished_submap_data =
data_.submap_data.at(newly_finished_submap_id);
CHECK(finished_submap_data.state == SubmapState::kNoConstraintSearch);
finished_submap_data.state = SubmapState::kFinished;
}
return node_id;
}
PoseGraph2D::Statistics PoseGraph2D::CalculateStatistics() const {
Statistics stats;
//
// Count the number of INTER constraints
// Map the constraints by node
//
for (const int trajectory_id : data_.trajectory_nodes.trajectory_ids()) {
stats.global_traj_constraint_count.insert({trajectory_id, 0});
stats.local_traj_constraint_count.insert({trajectory_id, 0});
}
for (size_t i = 0; i < data_.constraints.size(); ++i) {
const auto constraint = data_.constraints[i];
if (constraint.tag == Constraint::INTER_SUBMAP) {
if (stats.node_inter_constraints.Contains(constraint.node_id))
stats.node_inter_constraints.at(constraint.node_id)
.push_back(constraint);
else
stats.node_inter_constraints.Insert(
constraint.node_id, std::vector<Constraint>{constraint});
std::unordered_map<int, size_t>* traj_count = nullptr;
MapById<SubmapId, size_t>* count = nullptr;
if (constraint.node_id.trajectory_id ==
constraint.submap_id.trajectory_id) {
traj_count = &stats.local_traj_constraint_count;
count = &stats.local_inter_constraint_count;
} else {
traj_count = &stats.global_traj_constraint_count;
count = &stats.global_inter_constraint_count;
}
if (count->Contains(constraint.submap_id))
count->at(constraint.submap_id)++;
else
count->Insert(constraint.submap_id, 1);
auto it = traj_count->find(constraint.node_id.trajectory_id);
if (it != traj_count->end())
it->second++;
else
traj_count->insert({constraint.node_id.trajectory_id, 1});
}
}
return stats;
}
std::vector<PoseGraphInterface::Constraint> PoseGraph2D::FindNewConstraints() {
mutex_.Lock();
std::vector<PoseGraphInterface::Constraint> new_constraints;
const Statistics stats = CalculateStatistics();
for (const int trajectory_id : data_.trajectory_nodes.trajectory_ids()) {
if (data_.trajectories_state.at(trajectory_id).state ==
PoseGraphInterface::TrajectoryState::ACTIVE) {
if (data_.trajectory_nodes.SizeOfTrajectoryOrZero(trajectory_id) == 0)
continue;
//
// Search for constraints on the last node
//
auto node_it =
std::prev(data_.trajectory_nodes.EndOfTrajectory(trajectory_id));
const NodeId node_id = node_it->id;
const size_t traj_global_constraint_count =
stats.global_traj_constraint_count.at(node_id.trajectory_id);
const bool globally_localized =
trajectory_id == 0 ||
static_cast<int>(traj_global_constraint_count) >=
options_.min_globally_searched_constraints_for_trajectory();
if (!globally_localized) {
MapById<SubmapId, const Submap2D*> global_submaps;
for (const auto submap_id_data : data_.submap_data) {
if (submap_id_data.id.trajectory_id != node_id.trajectory_id &&
submap_id_data.data.state == SubmapState::kFinished) {
auto ptr = dynamic_cast<const Submap2D*>(
data_.submap_data.at(submap_id_data.id).submap.get());
global_submaps.Insert(submap_id_data.id, ptr);
}
}
LOG(INFO) << "Search (globally) for constraints for Node: " << node_id;
mutex_.Unlock();
const TrajectoryNode::Data& constant_data =
*data_.trajectory_nodes.at(node_id).constant_data.get();
const auto result = constraint_builder_.GlobalSearchForConstraint(
node_id, global_submaps, constant_data);
mutex_.Lock();
if (result) new_constraints.push_back(result.value());
} else {
// globally localised
// decide whether to look for a new constraint
const int num_of_nodes_with_constraints =
stats.node_inter_constraints.SizeOfTrajectoryOrZero(trajectory_id);
int nodes_since_last_local_constraint = std::numeric_limits<int>::max();
int nodes_since_last_global_constraint =
std::numeric_limits<int>::max();
if (num_of_nodes_with_constraints > 0) {
auto it = stats.node_inter_constraints.EndOfTrajectory(trajectory_id);
while (it != stats.node_inter_constraints.BeginOfTrajectory(
trajectory_id)) {
it = std::prev(it);
const bool has_local_constraint =
std::any_of(it->data.begin(), it->data.end(),
[trajectory_id](const Constraint& c) {
return c.submap_id.trajectory_id == trajectory_id;
});
int distance = node_id.node_index - it->id.node_index;
if (has_local_constraint &&
distance < nodes_since_last_local_constraint) {
nodes_since_last_local_constraint = distance;
break;
}
}
it = stats.node_inter_constraints.EndOfTrajectory(trajectory_id);
while (it != stats.node_inter_constraints.BeginOfTrajectory(
trajectory_id)) {
it = std::prev(it);
const bool has_global_constraint =
std::any_of(it->data.begin(), it->data.end(),
[trajectory_id](const Constraint& c) {
return c.submap_id.trajectory_id != trajectory_id;
});
int distance = node_id.node_index - it->id.node_index;
if (has_global_constraint &&
distance < nodes_since_last_global_constraint) {
nodes_since_last_global_constraint = distance;
break;
}
}
}
// iterate through own submaps
// look for ones which are geometrically close to this node
// if few constraints then look for one
if (nodes_since_last_local_constraint >
options_.local_constraint_every_n_nodes()) {
for (auto submap_itr =
data_.submap_data.BeginOfTrajectory(trajectory_id);
submap_itr != data_.submap_data.EndOfTrajectory(trajectory_id);
++submap_itr) {
if (submap_itr->data.state == SubmapState::kFinished) {
const transform::Rigid2d initial_relative_pose =
data_.global_submap_poses_2d.at(submap_itr->id)
.global_pose.inverse() *
transform::Project2D(node_it->data.global_pose);
const bool nearby = initial_relative_pose.translation().norm() <
options_.max_constraint_match_distance();
if (nearby) {
LOG(INFO)
<< "Search (locally) for local constraint between Node: "
<< node_id << " and Submap: " << submap_itr->id
<< " relative_pose: " << initial_relative_pose;
mutex_.Unlock();
const auto result =
constraint_builder_.LocalSearchForConstraint(
node_id, submap_itr->id, initial_relative_pose,
static_cast<const Submap2D&>(
*data_.submap_data.at(submap_itr->id).submap.get()),
*node_it->data.constant_data.get());
mutex_.Lock();
if (result) new_constraints.push_back(result.value());
}
}
}
}
// iterate through submaps of other trajectories
// look for ones which are geometrically close to this node
// if few constraints then look for one
if (nodes_since_last_global_constraint >
options_.global_constraint_every_n_nodes()) {
for (const int other_trajectory_id :
data_.trajectory_nodes.trajectory_ids()) {
if (other_trajectory_id == trajectory_id) continue;
for (auto submap_itr =
data_.submap_data.BeginOfTrajectory(other_trajectory_id);
submap_itr !=
data_.submap_data.EndOfTrajectory(other_trajectory_id);
++submap_itr) {
if (submap_itr->data.state == SubmapState::kFinished) {
const transform::Rigid2d initial_relative_pose =
data_.global_submap_poses_2d.at(submap_itr->id)
.global_pose.inverse() *
transform::Project2D(node_it->data.global_pose);
const bool nearby = initial_relative_pose.translation().norm() <
options_.max_constraint_match_distance();
if (nearby) {
LOG(INFO)
<< "Search (locally) for global constraint between Node: "
<< node_id << " and Submap: " << submap_itr->id
<< " relative_pose: " << initial_relative_pose;
mutex_.Unlock();
const auto result =
constraint_builder_.LocalSearchForConstraint(
node_id, submap_itr->id, initial_relative_pose,
static_cast<const Submap2D&>(
*data_.submap_data.at(submap_itr->id)
.submap.get()),
*node_it->data.constant_data.get());
mutex_.Lock();
if (result) new_constraints.push_back(result.value());
}
}
}
}
}
}
}
}
mutex_.Unlock();
return new_constraints;
}
void PoseGraph2D::BackgroundThread() {
// The job of this thread is to periodically search for global constraints and
// run the optimisation
while (background_thread_running_) {
//
// Search for new constraints
//
std::vector<Constraint> new_constraints = FindNewConstraints();
//
// Add the new constraints to internal data
//
{
absl::MutexLock locker(&mutex_);
// add the new constraints
data_.constraints.insert(data_.constraints.end(), new_constraints.begin(),
new_constraints.end());
for (const Constraint& constraint : new_constraints) {
UpdateTrajectoryConnectivity(constraint);
}
}
//
// Run Optimization
//
if (!new_constraints.empty()) {
LOG(INFO) << "Running optimisation with new constraints: "
<< new_constraints.size();
RunOptimization();
//
// Execute trajectory trimmers
//
{
absl::MutexLock locker(&mutex_);
LOG(INFO) << "Execute trajectory trimmers";
{
DeleteTrajectoriesIfNeeded();
TrimmingHandle trimming_handle(this);
for (auto& trimmer : trimmers_) {
trimmer->Trim(&trimming_handle);
}
// Remove any finished trimmers
trimmers_.erase(
std::remove_if(trimmers_.begin(), trimmers_.end(),
[](std::unique_ptr<PoseGraphTrimmer>& trimmer) {
return trimmer->IsFinished();
}),
trimmers_.end());
}
}
} else {
std::size_t num_of_nodes = 0;
{
absl::MutexLock locker(&mutex_);
num_of_nodes = data_.trajectory_nodes.size();
}
auto predicate = [this, num_of_nodes]() -> bool {
return !background_thread_running_ ||
data_.trajectory_nodes.size() != num_of_nodes;
};
if (mutex_.LockWhenWithTimeout(absl::Condition(&predicate),
absl::Milliseconds(10000))) {
// LOG(INFO) << "Number of nodes changed!";
} else {
// LOG(INFO) << "Timeout expired!";
}
mutex_.Unlock();
}
}
}
void PoseGraph2D::RunOptimization(const int32 num_of_iterations) {
auto options = options_.optimization_problem_options();
if (num_of_iterations > 0)
options.mutable_ceres_solver_options()->set_max_num_iterations(
num_of_iterations);
optimization::OptimizationProblem2D optimization_problem(options);
//
// Copy required data for solve under mutex lock
//
MapById<NodeId, optimization::NodeSpec2D> node_data;
MapById<SubmapId, optimization::SubmapSpec2D> submap_data;
std::vector<Constraint> constraints;
std::map<int, PoseGraphInterface::TrajectoryState> trajectories_states;
std::map<std::string, LandmarkNode> landmark_nodes;
// before optimization
std::map<int, transform::Rigid3d> trajectory_local_to_global;
{
absl::MutexLock locker(&mutex_);
for (const auto& item : data_.trajectory_nodes) {
const transform::Rigid2d local_pose_2d =
transform::Project2D(item.data.constant_data->local_pose);
const transform::Rigid2d global_pose_2d =
transform::Project2D(item.data.global_pose);
node_data.Insert(
item.id, optimization::NodeSpec2D{item.data.constant_data->time,
local_pose_2d, global_pose_2d,
Eigen::Quaterniond::Identity()});
}
submap_data = data_.global_submap_poses_2d;
landmark_nodes = data_.landmark_nodes;
constraints = data_.constraints;
for (const auto& it : data_.trajectories_state) {
trajectories_states[it.first] = it.second.state;
}
for (const int trajectory_id : data_.trajectory_nodes.trajectory_ids()) {
trajectory_local_to_global[trajectory_id] = ComputeLocalToGlobalTransform(
data_.global_submap_poses_2d, trajectory_id);
}
}
//
// Run Solver
//
LOG(INFO) << "Optimization: nodes: " << node_data.size()
<< " submaps: " << submap_data.size()
<< " constraints: " << constraints.size()
<< " landmarks: " << landmark_nodes.size();
const auto result = optimization_problem.Solve(
node_data, submap_data, constraints, trajectories_states, landmark_nodes);
//
// Post Optimization data management
//
if (result.success) {
{
absl::MutexLock locker(&mutex_);
for (const auto item : result.node_poses) {
data_.trajectory_nodes.at(item.id).global_pose =
transform::Embed3D(item.data);
}
for (const auto item : result.submap_poses) {
data_.global_submap_poses_2d.at(item.id).global_pose = item.data;
}
for (const auto item : result.landmark_poses) {
data_.landmark_nodes.at(item.first).global_landmark_pose = item.second;
}
// Extrapolate all point cloud poses that were not included in the
// 'optimization_problem_' yet.
for (const int trajectory_id : data_.trajectory_nodes.trajectory_ids()) {
const auto local_to_new_global = ComputeLocalToGlobalTransform(
data_.global_submap_poses_2d, trajectory_id);
const auto local_to_old_global =
trajectory_local_to_global.at(trajectory_id);
const transform::Rigid3d old_global_to_new_global =
local_to_new_global * local_to_old_global.inverse();
const NodeId last_optimized_node_id =
std::prev(node_data.EndOfTrajectory(trajectory_id))->id;
auto node_it =
std::next(data_.trajectory_nodes.find(last_optimized_node_id));
for (; node_it != data_.trajectory_nodes.EndOfTrajectory(trajectory_id);
++node_it) {
auto& mutable_trajectory_node =
data_.trajectory_nodes.at(node_it->id);
mutable_trajectory_node.global_pose =
old_global_to_new_global * mutable_trajectory_node.global_pose;
}
}
}
if (global_slam_optimization_callback_) {
std::map<int, NodeId> trajectory_id_to_last_optimized_node_id;
std::map<int, SubmapId> trajectory_id_to_last_optimized_submap_id;
{
for (const int trajectory_id : node_data.trajectory_ids()) {
if (node_data.SizeOfTrajectoryOrZero(trajectory_id) == 0 ||
submap_data.SizeOfTrajectoryOrZero(trajectory_id) == 0) {
continue;
}
trajectory_id_to_last_optimized_node_id.emplace(
trajectory_id,
std::prev(node_data.EndOfTrajectory(trajectory_id))->id);
trajectory_id_to_last_optimized_submap_id.emplace(
trajectory_id,
std::prev(submap_data.EndOfTrajectory(trajectory_id))->id);
}
}
global_slam_optimization_callback_(
trajectory_id_to_last_optimized_submap_id,
trajectory_id_to_last_optimized_node_id);
}
}
}
void PoseGraph2D::AddTrajectoryIfNeeded(const int trajectory_id) {
data_.trajectories_state[trajectory_id];
CHECK(data_.trajectories_state.at(trajectory_id).state !=
TrajectoryState::FINISHED);
CHECK(data_.trajectories_state.at(trajectory_id).state !=
TrajectoryState::DELETED);
CHECK(data_.trajectories_state.at(trajectory_id).deletion_state ==
InternalTrajectoryState::DeletionState::NORMAL);
data_.trajectory_connectivity_state.Add(trajectory_id);
}
void PoseGraph2D::AddFixedFramePoseData(
const int trajectory_id,
const sensor::FixedFramePoseData& fixed_frame_pose_data) {
LOG(FATAL) << "Not yet implemented for 2D.";
}
void PoseGraph2D::AddLandmarkData(int trajectory_id,
const sensor::LandmarkData& landmark_data) {
absl::MutexLock locker(&mutex_);
CHECK(CanAddWorkItemModifying(trajectory_id));
for (const auto& observation : landmark_data.landmark_observations) {
data_.landmark_nodes[observation.id].landmark_observations.emplace_back(
PoseGraphInterface::LandmarkNode::LandmarkObservation{
trajectory_id, landmark_data.time,
observation.landmark_to_tracking_transform,
observation.translation_weight, observation.rotation_weight});
}
}
common::Time PoseGraph2D::GetLatestNodeTime(const NodeId& node_id,
const SubmapId& submap_id) const {
common::Time time = data_.trajectory_nodes.at(node_id).constant_data->time;
const InternalSubmapData& submap_data = data_.submap_data.at(submap_id);
if (!submap_data.node_ids.empty()) {
const NodeId last_submap_node_id =
*data_.submap_data.at(submap_id).node_ids.rbegin();
time = std::max(
time,
data_.trajectory_nodes.at(last_submap_node_id).constant_data->time);
}
return time;
}
void PoseGraph2D::UpdateTrajectoryConnectivity(const Constraint& constraint) {
CHECK_EQ(constraint.tag, Constraint::INTER_SUBMAP);
const common::Time time =
GetLatestNodeTime(constraint.node_id, constraint.submap_id);
data_.trajectory_connectivity_state.Connect(
constraint.node_id.trajectory_id, constraint.submap_id.trajectory_id,
time);
}
void PoseGraph2D::DeleteTrajectoriesIfNeeded() {
TrimmingHandle trimming_handle(this);
for (auto& it : data_.trajectories_state) {
if (it.second.deletion_state ==
InternalTrajectoryState::DeletionState::WAIT_FOR_DELETION) {
LOG(INFO) << "trajectory: " << it.first
<< " deletion_state: WAIT_FOR_DELETION";
auto submap_ids = trimming_handle.GetSubmapIds(it.first);
for (auto& submap_id : submap_ids) {
LOG(INFO) << "Trimming submap: " << submap_id;
trimming_handle.TrimSubmap(submap_id);
}
it.second.state = TrajectoryState::DELETED;
it.second.deletion_state = InternalTrajectoryState::DeletionState::NORMAL;
}
}
}
void PoseGraph2D::DeleteTrajectory(const int trajectory_id) {
// TODO deletion threading needs work
LOG(INFO) << "DeleteTrajectory: " << trajectory_id;
absl::MutexLock locker(&mutex_);
auto it = data_.trajectories_state.find(trajectory_id);
if (it == data_.trajectories_state.end()) {
LOG(WARNING) << "Skipping request to delete non-existing trajectory_id: "
<< trajectory_id;
return;
}
it->second.deletion_state =
InternalTrajectoryState::DeletionState::SCHEDULED_FOR_DELETION;
CHECK(data_.trajectories_state.at(trajectory_id).state !=
TrajectoryState::ACTIVE);
CHECK(data_.trajectories_state.at(trajectory_id).state !=
TrajectoryState::DELETED);
CHECK(data_.trajectories_state.at(trajectory_id).deletion_state ==
InternalTrajectoryState::DeletionState::SCHEDULED_FOR_DELETION);
data_.trajectories_state.at(trajectory_id).deletion_state =
InternalTrajectoryState::DeletionState::WAIT_FOR_DELETION;
}
void PoseGraph2D::FinishTrajectory(const int trajectory_id) {
absl::MutexLock locker(&mutex_);
CHECK(!IsTrajectoryFinished(trajectory_id));
data_.trajectories_state[trajectory_id].state = TrajectoryState::FINISHED;
for (const auto& submap : data_.submap_data.trajectory(trajectory_id)) {
data_.submap_data.at(submap.id).state = SubmapState::kFinished;
}
// TODO maybe trigger an optimisation?
}
bool PoseGraph2D::IsTrajectoryFinished(const int trajectory_id) const {
return data_.trajectories_state.count(trajectory_id) != 0 &&
data_.trajectories_state.at(trajectory_id).state ==
TrajectoryState::FINISHED;
}
void PoseGraph2D::FreezeTrajectory(const int trajectory_id) {
absl::MutexLock locker(&mutex_);
AddTrajectoryIfNeeded(trajectory_id);
data_.trajectory_connectivity_state.Add(trajectory_id);
CHECK(!IsTrajectoryFrozen(trajectory_id));
data_.trajectories_state[trajectory_id].state = TrajectoryState::FROZEN;
}
bool PoseGraph2D::IsTrajectoryFrozen(const int trajectory_id) const {
return data_.trajectories_state.count(trajectory_id) != 0 &&
data_.trajectories_state.at(trajectory_id).state ==
TrajectoryState::FROZEN;
}
void PoseGraph2D::AddSubmapFromProto(
const transform::Rigid3d& global_submap_pose, const proto::Submap& submap) {
CHECK(submap.has_submap_2d());
const SubmapId submap_id = {submap.submap_id().trajectory_id(),
submap.submap_id().submap_index()};
const transform::Rigid2d global_submap_pose_2d =
transform::Project2D(global_submap_pose);
{
absl::MutexLock locker(&mutex_);
const std::shared_ptr<const Submap2D> submap_ptr =
std::make_shared<const Submap2D>(submap.submap_2d(),
&conversion_tables_);
AddTrajectoryIfNeeded(submap_id.trajectory_id);
CHECK(IsTrajectoryFrozen(submap_id.trajectory_id));
CHECK(CanAddWorkItemModifying(submap_id.trajectory_id));
data_.submap_data.Insert(submap_id, InternalSubmapData());
data_.submap_data.at(submap_id).submap = submap_ptr;
// Immediately show the submap at the 'global_submap_pose'.
data_.global_submap_poses_2d.Insert(
submap_id, optimization::SubmapSpec2D{global_submap_pose_2d});
data_.submap_data.at(submap_id).state = SubmapState::kFinished;
// optimization_problem_->InsertSubmap(submap_id, global_submap_pose_2d);
}
}
void PoseGraph2D::AddNodeFromProto(const transform::Rigid3d& global_pose,
const proto::Node& node) {
const NodeId node_id = {node.node_id().trajectory_id(),
node.node_id().node_index()};
std::shared_ptr<const TrajectoryNode::Data> constant_data =
std::make_shared<const TrajectoryNode::Data>(FromProto(node.node_data()));
{
absl::MutexLock locker(&mutex_);
AddTrajectoryIfNeeded(node_id.trajectory_id);
CHECK(CanAddWorkItemModifying(node_id.trajectory_id));
data_.trajectory_nodes.Insert(node_id,
TrajectoryNode{constant_data, global_pose});
}
}
void PoseGraph2D::SetTrajectoryDataFromProto(
const proto::TrajectoryData& data) {
LOG(ERROR) << "not implemented";
}
void PoseGraph2D::AddNodeToSubmap(const NodeId& node_id,
const SubmapId& submap_id) {
absl::MutexLock locker(&mutex_);
CHECK(CanAddWorkItemModifying(submap_id.trajectory_id));
data_.submap_data.at(submap_id).node_ids.insert(node_id);
}
void PoseGraph2D::AddSerializedConstraints(
const std::vector<Constraint>& constraints) {
absl::MutexLock locker(&mutex_);
for (const auto& constraint : constraints) {
CHECK(data_.trajectory_nodes.Contains(constraint.node_id));
CHECK(data_.submap_data.Contains(constraint.submap_id));
CHECK(data_.trajectory_nodes.at(constraint.node_id).constant_data !=
nullptr);
CHECK(data_.submap_data.at(constraint.submap_id).submap != nullptr);
switch (constraint.tag) {
case Constraint::Tag::INTRA_SUBMAP:
CHECK(data_.submap_data.at(constraint.submap_id)
.node_ids.emplace(constraint.node_id)
.second);
break;
case Constraint::Tag::INTER_SUBMAP:
UpdateTrajectoryConnectivity(constraint);
break;
}
const Constraint::Pose pose = {constraint.pose.zbar_ij,
constraint.pose.translation_weight,
constraint.pose.rotation_weight};
data_.constraints.push_back(Constraint{
constraint.submap_id, constraint.node_id, pose, constraint.tag});
}
LOG(INFO) << "Loaded " << constraints.size() << " constraints.";
}
void PoseGraph2D::AddTrimmer(std::unique_ptr<PoseGraphTrimmer> trimmer) {
PoseGraphTrimmer* const trimmer_ptr = trimmer.release();
absl::MutexLock locker(&mutex_);
trimmers_.emplace_back(trimmer_ptr);
}
void PoseGraph2D::RunFinalOptimization() {
StopBackgroundThread();
RunOptimization(options_.max_num_final_iterations());
StartBackgroundThread();
}
bool PoseGraph2D::CanAddWorkItemModifying(int trajectory_id) {
auto it = data_.trajectories_state.find(trajectory_id);
if (it == data_.trajectories_state.end()) {
return true;
}
if (it->second.state == TrajectoryState::FINISHED) {
// TODO(gaschler): Replace all FATAL to WARNING after some testing.
LOG(FATAL) << "trajectory_id " << trajectory_id
<< " has finished "
"but modification is requested, skipping.";
return false;
}
if (it->second.deletion_state !=
InternalTrajectoryState::DeletionState::NORMAL) {
LOG(FATAL) << "trajectory_id " << trajectory_id
<< " has been scheduled for deletion "
"but modification is requested, skipping.";
return false;
}
if (it->second.state == TrajectoryState::DELETED) {
LOG(FATAL) << "trajectory_id " << trajectory_id
<< " has been deleted "
"but modification is requested, skipping.";
return false;
}
return true;
}
MapById<NodeId, TrajectoryNode> PoseGraph2D::GetTrajectoryNodes() const {
absl::MutexLock locker(&mutex_);
return data_.trajectory_nodes;
}
MapById<NodeId, TrajectoryNodePose> PoseGraph2D::GetTrajectoryNodePoses()
const {
MapById<NodeId, TrajectoryNodePose> node_poses;
absl::MutexLock locker(&mutex_);
for (const auto& node_id_data : data_.trajectory_nodes) {
absl::optional<TrajectoryNodePose::ConstantPoseData> constant_pose_data;
if (node_id_data.data.constant_data != nullptr) {
constant_pose_data = TrajectoryNodePose::ConstantPoseData{
node_id_data.data.constant_data->time,
node_id_data.data.constant_data->local_pose};
}
node_poses.Insert(
node_id_data.id,
TrajectoryNodePose{node_id_data.data.global_pose, constant_pose_data});
}
return node_poses;
}
std::map<int, PoseGraphInterface::TrajectoryState>
PoseGraph2D::GetTrajectoryStates() const {
std::map<int, PoseGraphInterface::TrajectoryState> trajectories_state;
absl::MutexLock locker(&mutex_);
for (const auto& it : data_.trajectories_state) {
trajectories_state[it.first] = it.second.state;
}
return trajectories_state;
}
std::map<std::string, transform::Rigid3d> PoseGraph2D::GetLandmarkPoses()
const {
std::map<std::string, transform::Rigid3d> landmark_poses;
absl::MutexLock locker(&mutex_);
for (const auto& landmark : data_.landmark_nodes) {
// Landmark without value has not been optimized yet.
if (!landmark.second.global_landmark_pose.has_value()) continue;
landmark_poses[landmark.first] =
landmark.second.global_landmark_pose.value();
}
return landmark_poses;
}
void PoseGraph2D::SetLandmarkPose(const std::string& landmark_id,
const transform::Rigid3d& global_pose,
const bool frozen) {
absl::MutexLock locker(&mutex_);
data_.landmark_nodes[landmark_id].global_landmark_pose = global_pose;
data_.landmark_nodes[landmark_id].frozen = frozen;
}
std::map<std::string /* landmark ID */, PoseGraphInterface::LandmarkNode>
PoseGraph2D::GetLandmarkNodes() const {
absl::MutexLock locker(&mutex_);
return data_.landmark_nodes;
}
std::map<int, PoseGraphInterface::TrajectoryData>
PoseGraph2D::GetTrajectoryData() const {
// The 2D optimization problem does not have any 'TrajectoryData'.
return {};
}
sensor::MapByTime<sensor::FixedFramePoseData>
PoseGraph2D::GetFixedFramePoseData() const {
// FixedFramePoseData is not yet implemented for 2D. We need to return empty
// so serialization works.
return {};
}
std::vector<PoseGraphInterface::Constraint> PoseGraph2D::constraints() const {
std::vector<PoseGraphInterface::Constraint> result;
absl::MutexLock locker(&mutex_);
for (const Constraint& constraint : data_.constraints) {
result.push_back(
Constraint{constraint.submap_id, constraint.node_id,
Constraint::Pose{constraint.pose.zbar_ij,
constraint.pose.translation_weight,
constraint.pose.rotation_weight},
constraint.tag});
}
return result;
}
void PoseGraph2D::SetInitialTrajectoryPose(const int from_trajectory_id,
const int to_trajectory_id,
const transform::Rigid3d& pose,
const common::Time time) {
absl::MutexLock locker(&mutex_);
data_.initial_trajectory_poses[from_trajectory_id] =
InitialTrajectoryPose{to_trajectory_id, pose, time};
}
transform::Rigid3d PoseGraph2D::GetInterpolatedGlobalTrajectoryPose(
const int trajectory_id, const common::Time time) const {
CHECK_GT(data_.trajectory_nodes.SizeOfTrajectoryOrZero(trajectory_id), 0);
const auto it = data_.trajectory_nodes.lower_bound(trajectory_id, time);
if (it == data_.trajectory_nodes.BeginOfTrajectory(trajectory_id)) {
return data_.trajectory_nodes.BeginOfTrajectory(trajectory_id)
->data.global_pose;
}
if (it == data_.trajectory_nodes.EndOfTrajectory(trajectory_id)) {
return std::prev(data_.trajectory_nodes.EndOfTrajectory(trajectory_id))
->data.global_pose;
}
return transform::Interpolate(
transform::TimestampedTransform{std::prev(it)->data.time(),
std::prev(it)->data.global_pose},
transform::TimestampedTransform{it->data.time(),
it->data.global_pose},
time)
.transform;
}
transform::Rigid3d PoseGraph2D::GetLocalToGlobalTransform(
const int trajectory_id) const {
absl::MutexLock locker(&mutex_);
return ComputeLocalToGlobalTransform(data_.global_submap_poses_2d,
trajectory_id);
}
std::vector<std::vector<int>> PoseGraph2D::GetConnectedTrajectories() const {
absl::MutexLock locker(&mutex_);
return data_.trajectory_connectivity_state.Components();
}
PoseGraphInterface::SubmapData PoseGraph2D::GetSubmapData(
const SubmapId& submap_id) const {
absl::MutexLock locker(&mutex_);
return GetSubmapDataUnderLock(submap_id);
}
MapById<SubmapId, PoseGraphInterface::SubmapData>
PoseGraph2D::GetAllSubmapData() const {
absl::MutexLock locker(&mutex_);
return GetSubmapDataUnderLock();
}
MapById<SubmapId, PoseGraphInterface::SubmapPose>
PoseGraph2D::GetAllSubmapPoses() const {
absl::MutexLock locker(&mutex_);
MapById<SubmapId, SubmapPose> submap_poses;
for (const auto& submap_id_data : data_.submap_data) {
auto submap_data = GetSubmapDataUnderLock(submap_id_data.id);
submap_poses.Insert(
submap_id_data.id,
PoseGraph::SubmapPose{submap_data.submap->num_range_data(),
submap_data.pose});
}
return submap_poses;
}
transform::Rigid3d PoseGraph2D::ComputeLocalToGlobalTransform(
const MapById<SubmapId, optimization::SubmapSpec2D>& global_submap_poses,
const int trajectory_id) const {
auto begin_it = global_submap_poses.BeginOfTrajectory(trajectory_id);
auto end_it = global_submap_poses.EndOfTrajectory(trajectory_id);
if (begin_it == end_it) {
const auto it = data_.initial_trajectory_poses.find(trajectory_id);
if (it != data_.initial_trajectory_poses.end()) {
return GetInterpolatedGlobalTrajectoryPose(it->second.to_trajectory_id,
it->second.time) *
it->second.relative_pose;
} else {
return transform::Rigid3d::Identity();
}
}
const SubmapId last_optimized_submap_id = std::prev(end_it)->id;
// Accessing 'local_pose' in Submap is okay, since the member is const.
return transform::Embed3D(
global_submap_poses.at(last_optimized_submap_id).global_pose) *
data_.submap_data.at(last_optimized_submap_id)
.submap->local_pose()
.inverse();
}
PoseGraphInterface::SubmapData PoseGraph2D::GetSubmapDataUnderLock(
const SubmapId& submap_id) const {
const auto it = data_.submap_data.find(submap_id);
if (it == data_.submap_data.end()) {
return {};
}
auto submap = it->data.submap;
if (data_.global_submap_poses_2d.Contains(submap_id)) {
// We already have an optimized pose.
return {submap,
transform::Embed3D(
data_.global_submap_poses_2d.at(submap_id).global_pose)};
}
// We have to extrapolate.
return {submap, ComputeLocalToGlobalTransform(data_.global_submap_poses_2d,
submap_id.trajectory_id) *
submap->local_pose()};
}
PoseGraph2D::TrimmingHandle::TrimmingHandle(PoseGraph2D* const parent)
: parent_(parent) {}
int PoseGraph2D::TrimmingHandle::num_submaps(const int trajectory_id) const {
const auto& submap_data = parent_->data_.global_submap_poses_2d;
return submap_data.SizeOfTrajectoryOrZero(trajectory_id);
}
MapById<SubmapId, PoseGraphInterface::SubmapData>
PoseGraph2D::TrimmingHandle::GetOptimizedSubmapData() const {
MapById<SubmapId, PoseGraphInterface::SubmapData> submaps;
for (const auto& submap_id_data : parent_->data_.submap_data) {
if (submap_id_data.data.state != SubmapState::kFinished ||
!parent_->data_.global_submap_poses_2d.Contains(submap_id_data.id)) {
continue;
}
submaps.Insert(
submap_id_data.id,
SubmapData{submap_id_data.data.submap,
transform::Embed3D(parent_->data_.global_submap_poses_2d
.at(submap_id_data.id)
.global_pose)});
}
return submaps;
}
std::vector<SubmapId> PoseGraph2D::TrimmingHandle::GetSubmapIds(
int trajectory_id) const {
std::vector<SubmapId> submap_ids;
const auto& submap_data = parent_->data_.global_submap_poses_2d;
for (const auto& it : submap_data.trajectory(trajectory_id)) {
submap_ids.push_back(it.id);
}
return submap_ids;
}
const MapById<NodeId, TrajectoryNode>&
PoseGraph2D::TrimmingHandle::GetTrajectoryNodes() const {
return parent_->data_.trajectory_nodes;
}
const std::vector<PoseGraphInterface::Constraint>&
PoseGraph2D::TrimmingHandle::GetConstraints() const {
return parent_->data_.constraints;
}
const MapById<SubmapId, std::set<NodeId>>
PoseGraph2D::TrimmingHandle::GetSubmapNodes() const {
MapById<SubmapId, std::set<NodeId>> submap_nodes;
for (const auto item : parent_->data_.submap_data)
submap_nodes.Insert(item.id, item.data.node_ids);
return submap_nodes;
}
bool PoseGraph2D::TrimmingHandle::IsFinished(const int trajectory_id) const {
return parent_->IsTrajectoryFinished(trajectory_id);
}
void PoseGraph2D::TrimmingHandle::SetTrajectoryState(int trajectory_id,
TrajectoryState state) {
parent_->data_.trajectories_state[trajectory_id].state = state;
}
void PoseGraph2D::TrimmingHandle::TrimSubmap(const SubmapId& submap_id) {
LOG(INFO) << "TrimSubmap: " << submap_id;
CHECK(parent_->data_.submap_data.at(submap_id).state ==
SubmapState::kFinished);
// Compile all nodes that are still INTRA_SUBMAP constrained once the submap
// with 'submap_id' is gone.
std::set<NodeId> nodes_to_retain;
for (const Constraint& constraint : parent_->data_.constraints) {
if (constraint.tag == Constraint::Tag::INTRA_SUBMAP &&
constraint.submap_id != submap_id) {
nodes_to_retain.insert(constraint.node_id);
}
}
// Remove all 'data_.constraints' related to 'submap_id'.
std::set<NodeId> nodes_to_remove;
{
std::vector<Constraint> constraints;
for (const Constraint& constraint : parent_->data_.constraints) {
if (constraint.submap_id == submap_id) {
if (constraint.tag == Constraint::Tag::INTRA_SUBMAP &&
nodes_to_retain.count(constraint.node_id) == 0) {
// This node will no longer be INTRA_SUBMAP constrained and has to be
// removed.
nodes_to_remove.insert(constraint.node_id);
}
} else {
constraints.push_back(constraint);
}
}
parent_->data_.constraints = std::move(constraints);
}
// Remove all 'data_.constraints' related to 'nodes_to_remove'.
{
std::vector<Constraint> constraints;
for (const Constraint& constraint : parent_->data_.constraints) {
if (nodes_to_remove.count(constraint.node_id) == 0) {
constraints.push_back(constraint);
}
}
parent_->data_.constraints = std::move(constraints);
}
// Mark the submap with 'submap_id' as trimmed and remove its data.
CHECK(parent_->data_.submap_data.at(submap_id).state ==
SubmapState::kFinished);
parent_->data_.submap_data.Trim(submap_id);
parent_->data_.global_submap_poses_2d.Trim(submap_id);
parent_->constraint_builder_.DeleteScanMatcher(submap_id);
// Remove the 'nodes_to_remove' from the pose graph and the optimization
// problem.
for (const NodeId& node_id : nodes_to_remove) {
parent_->data_.trajectory_nodes.Trim(node_id);
}
}
MapById<SubmapId, PoseGraphInterface::SubmapData>
PoseGraph2D::GetSubmapDataUnderLock() const {
MapById<SubmapId, PoseGraphInterface::SubmapData> submaps;
for (const auto& submap_id_data : data_.submap_data) {
submaps.Insert(submap_id_data.id,
GetSubmapDataUnderLock(submap_id_data.id));
}
return submaps;
}
void PoseGraph2D::SetGlobalSlamOptimizationCallback(
PoseGraphInterface::GlobalSlamOptimizationCallback callback) {
global_slam_optimization_callback_ = callback;
}
void PoseGraph2D::RegisterMetrics(metrics::FamilyFactory* family_factory) {}
} // namespace mapping
} // namespace cartographer
| 38.135025 | 80 | 0.67078 | [
"vector",
"transform"
] |
2366b1cd9dd3848291809e3f6cc6d794edd02cd1 | 21,564 | cpp | C++ | cameraRibbonExample/src/ofApp.cpp | preformIOstudios/preSENSE | 63bc8d2d17a869a4e6158c24e912b12bd8c37198 | [
"MIT"
] | null | null | null | cameraRibbonExample/src/ofApp.cpp | preformIOstudios/preSENSE | 63bc8d2d17a869a4e6158c24e912b12bd8c37198 | [
"MIT"
] | null | null | null | cameraRibbonExample/src/ofApp.cpp | preformIOstudios/preSENSE | 63bc8d2d17a869a4e6158c24e912b12bd8c37198 | [
"MIT"
] | null | null | null | /**
*
* OFDevCon Example Code Sprint
* Camera Ribbon example
* This example generates ribbons along the mouse trail that descend in space
* When you click space bar, you can
*
* Created by James George for openFrameworks workshop at Waves Festival Vienna sponsored by Lichterloh and Pratersauna
* Adapted during ofDevCon on 2/23/2012
*/
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
//just set up the openFrameworks stuff
ofSetFrameRate(60);//TODO: put this into the GUI
ofSetVerticalSync(true);
//initialize the variable so it's off at the beginning
usecamera = false;
pointsMax = 100; //TODO: put this into the GUI
//initialize kinect object
//TODO: only initialize necessary sources
kinect.open();
kinect.initDepthSource();
kinect.initColorSource();
kinect.initInfraredSource();
kinect.initBodySource();
kinect.initBodyIndexSource();
//set debugging variables
debugging = false;//TODO: put this into the GUI
previewScaleH = 1.0f;//TODO: put this into the GUI
previewScaleW = 1.0f;//TODO: put this into the GUI
//TODO: setup gui & text instructions for keypresses, etc.
// change color settings
// set mode to debugging
/////////////////////
// Initialize GUIS //
/////////////////////
currentLook = 1;
lookChanged = true;
//
//------------
// Main GUI --
//////////////
gui = new ofxUISuperCanvas("preSENCE ribb");
ofAddListener(gui->newGUIEvent, this, &ofApp::guiEvent);
gui->addSpacer();
gui->addTextArea("text", "'h' to hide this panel", OFX_UI_FONT_SMALL);
// gui -> addLabel("text", "'h' to hide this panel");
gui->addSpacer();
//
// radio list and key bindings to select different looks
gui->addLabel("looks: "); // TODO: Make this more like the editors where there's a "look Editor" that handles larger settings files which can be changed between
vector<string> looksList;
for (int i = 0; i < 4; i++) {
looksList.push_back(ofToString(i + 1));
}
ofxUIRadio *radioLook = gui->addRadio("look", looksList, OFX_UI_ORIENTATION_HORIZONTAL);
vector< ofxUIToggle*> toggles = radioLook->getToggles();
for (int i = 0; i < 4; i++) {
toggles[i]->bindToKey(ofToChar(ofToString(i + 1)));
}
gui->addTextArea("text", "press '1', '2', etc. to switch between different looks", OFX_UI_FONT_SMALL);
gui->addSpacer();
//
// FPS
gui->addFPSSlider("fps");
gui->addSpacer();
gui->addTextArea("text", "'+' or '-' to change frame rate");
gui->addIntSlider("set fps", 1, 60, &drawFrameRate);
gui->addSpacer();
//
// Background Color
gui->addTextArea("text", "background color");
gui->addSlider("red", 0.0, 255.0, &bgRed);
gui->addSlider("green", 0.0, 255.0, &bgGreen);
gui->addSlider("blue", 0.0, 255.0, &bgBlue);
gui->addSpacer();
//
// Background Gradient Color
gui->addTextArea("text", "gradient color");
gui->addSlider("gradRed", 0.0, 255.0, &bgGradRed);
gui->addSlider("gradGreen", 0.0, 255.0, &bgGradGreen);
gui->addSlider("gradBlue", 0.0, 255.0, &bgGradBlue);
gui->addSpacer();
//
// fullscreen toggle
ofxUIToggle *toggleFullScreen = gui->addToggle("fullscreen", false);
toggleFullScreen->bindToKey('f');
toggleFullScreen->bindToKey('F');
//
//
// draw index toggle
ofxUIToggle* toggleIndex = gui->addToggle("body index", &drawBodyIndex);
toggleIndex->bindToKey('i');
toggleIndex->bindToKey('I');
//
// draw bones toggle
ofxUIToggle* toggleBones = gui->addToggle("bones", &drawBones);
toggleBones->bindToKey('b');
toggleBones->bindToKey('B');
gui->addSpacer();
//
// debugging toggle
ofxUIToggle* toggleDebugging = gui->addToggle("debugging", &debugging);
toggleDebugging->bindToKey('d');
toggleDebugging->bindToKey('D');
//
// hard reset
ofxUIButton *buttonReset = gui->addButton("hardreset", false);
buttonReset->bindToKey('r');
buttonReset->bindToKey('R');
//
// save Settings
gui->addLabelButton("save main settings", false);
gui->autoSizeToFitWidgets();
//
//-------------
// Color GUI --
///////////////
guiColor = new ofxUISuperCanvas("preSENSE colors");
ofAddListener(guiColor->newGUIEvent, this, &ofApp::guiEvent);
guiColor->addSpacer();
//
guiColor->addLabel("foreground color settings", OFX_UI_FONT_MEDIUM);
vector< string > vnamesBlendIMG; vnamesBlendIMG.push_back("i0"); vnamesBlendIMG.push_back("iA"); vnamesBlendIMG.push_back("i+"); vnamesBlendIMG.push_back("i-"); vnamesBlendIMG.push_back("i*"); vnamesBlendIMG.push_back("iS");
ofxUIRadio *radioBlendIMG = guiColor->addRadio("foreground blend mode", vnamesBlendIMG, OFX_UI_ORIENTATION_HORIZONTAL);
guiColor->addSlider("fg red", 0.0, 255.0, &fgRed);
guiColor->addSlider("fg green", 0.0, 255.0, &fgGreen);
guiColor->addSlider("fg blue", 0.0, 255.0, &fgBlue);
guiColor->addSlider("fg alpha", 0.0, 255.0, &fgAlpha);
guiColor->addSpacer();
//
guiColor->addLabel("index image settings", OFX_UI_FONT_MEDIUM);
vector< string > vnamesDepthCLR; vnamesDepthCLR.push_back("PSYCHEDELIC_SHADES"); vnamesDepthCLR.push_back("PSYCHEDELIC"); vnamesDepthCLR.push_back("RAINBOW"); vnamesDepthCLR.push_back("CYCLIC_RAINBOW"); vnamesDepthCLR.push_back("BLUES"); vnamesDepthCLR.push_back("BLUES_INV"); vnamesDepthCLR.push_back("GREY"); vnamesDepthCLR.push_back("STATUS");
ofxUIRadio *radioMode = guiColor->addRadio("index color mode", vnamesDepthCLR, OFX_UI_ORIENTATION_VERTICAL);
vector< string > vnamesBlendDEPTH; vnamesBlendDEPTH.push_back("d0"); vnamesBlendDEPTH.push_back("dA"); vnamesBlendDEPTH.push_back("d+"); vnamesBlendDEPTH.push_back("d-"); vnamesBlendDEPTH.push_back("d*"); vnamesBlendDEPTH.push_back("dS");
ofxUIRadio *radioBlendDepth = guiColor->addRadio("index blend mode", vnamesBlendDEPTH, OFX_UI_ORIENTATION_HORIZONTAL);
guiColor->addSlider("index red", 0.0, 255.0, &indexRed);
guiColor->addSlider("index green", 0.0, 255.0, &indexGreen);
guiColor->addSlider("index blue", 0.0, 255.0, &indexBlue);
guiColor->addSlider("index alpha", 0.0, 255.0, &indexAlpha);
guiColor->addSpacer();
//
guiColor->addLabel("skeleton drawing settings", OFX_UI_FONT_MEDIUM);
vector< string > vnamesBlendSKEL; vnamesBlendSKEL.push_back("s0"); vnamesBlendSKEL.push_back("sA"); vnamesBlendSKEL.push_back("s+"); vnamesBlendSKEL.push_back("s-"); vnamesBlendSKEL.push_back("s*"); vnamesBlendSKEL.push_back("sS");
ofxUIRadio *radioBlendSkel = guiColor->addRadio("skeleton blend mode", vnamesBlendSKEL, OFX_UI_ORIENTATION_HORIZONTAL);
guiColor->addSlider("skel red", 0.0, 255.0, &skelRed);
guiColor->addSlider("skel green", 0.0, 255.0, &skelGreen);
guiColor->addSlider("skel blue", 0.0, 255.0, &skelBlue);
guiColor->addSlider("skel alpha", 0.0, 255.0, &skelAlpha);
guiColor->addSpacer();
//
// Save Settings
guiColor->addLabelButton("save color settings", false);
guiColor->autoSizeToFitWidgets();
}
//--------------------------------------------------------------
void ofApp::guiEvent(ofxUIEventArgs &e) {
//*
bool noCallbackForWidget = false;
string nameStr = e.widget->getName();
int kind = e.widget->getKind();
if (nameStr == "fullscreen") {
ofSetFullscreen(((ofxUIToggle *)e.widget)->getValue());
}
else if (nameStr == "save main settings") {
gui->saveSettings("guiSettings_" + ofToString(currentLook) + ".xml");
}
else if (nameStr == "save color settings") {
guiColor->saveSettings("guiSettings_" + ofToString(currentLook) + "_color.xml");
}
else if (nameStr == "look" || nameStr == "1" || nameStr == "2" || nameStr == "3" || nameStr == "4") {
ofxUIRadio *radioLook;
if (kind == OFX_UI_WIDGET_RADIO) radioLook = (ofxUIRadio *)e.widget;
else radioLook = (ofxUIRadio *)e.widget->getParent();
switch (radioLook->getValue()) {
case 0: // 1
currentLook = 1;
break;
case 1: // 2
currentLook = 2;
break;
case 2: // 3
currentLook = 3;
break;
case 3: // 4
currentLook = 4;
break;
default:
break;
}
lookChanged = true;
}
else if (nameStr == "hardreset") {
//resetParticles(true);
}
else if (nameStr == "foreground blend mode" || nameStr == "i0" || nameStr == "iA" || nameStr == "i+" || nameStr == "i-" || nameStr == "i*" || nameStr == "iS") {
ofxUIRadio *radio;
if (nameStr == "foreground blend mode") {
radio = (ofxUIRadio *)e.widget;
}
else {
radio = (ofxUIRadio *)e.widget->getParent();
}
fgBlendMode = radio->getValue();
}
else if (nameStr == "index color mode" || nameStr == "PSYCHEDELIC_SHADES" || nameStr == "PSYCHEDELIC" || nameStr == "RAINBOW" || nameStr == "CYCLIC_RAINBOW" || nameStr == "BLUES" || nameStr == "BLUES_INV" || nameStr == "GREY" || nameStr == "STATUS") {
ofxUIRadio *radio;
if (nameStr == "index color mode") {
radio = (ofxUIRadio *)e.widget;
}
else {
radio = (ofxUIRadio *)e.widget->getParent();
}
indexColorMode = radio->getValue();
//kinect.setDepthColoring((DepthColoring)indexColorMode); // TODO: is this even possible with ofxKFW2?
}
else if (nameStr == "index blend mode" || nameStr == "d0" || nameStr == "dA" || nameStr == "d+" || nameStr == "d-" || nameStr == "d*" || nameStr == "dS") {
ofxUIRadio *radio;
if (nameStr == "index blend mode") {
radio = (ofxUIRadio *)e.widget;
}
else {
radio = (ofxUIRadio *)e.widget->getParent();
}
indexBlendMode = radio->getValue();
}
else if (nameStr == "skeleton blend mode" || nameStr == "s0" || nameStr == "sA" || nameStr == "s+" || nameStr == "s-" || nameStr == "s*" || nameStr == "sS") {
ofxUIRadio *radio;
if (nameStr == "skeleton blend mode") {
radio = (ofxUIRadio *)e.widget;
}
else {
radio = (ofxUIRadio *)e.widget->getParent();
}
skelBlendMode = radio->getValue();
}
else {
// default
noCallbackForWidget = true;
}
// debug
if (ofGetLogLevel() == OF_LOG_VERBOSE) {
if (noCallbackForWidget) {
cout << "[verbose] ofApp::guiEvent(ofxUIEventArgs &e) -- unset callback for gui element name = " << nameStr << endl;
}
else {
cout << "[verbose] ofApp::guiEvent(ofxUIEventArgs &e) -- gui element name = " << nameStr << endl;
}
}
}
//--------------------------------------------------------------
void ofApp::update(){
fgColor = ofColor(fgRed, fgGreen, fgBlue, fgAlpha);
bgColor = ofColor(bgRed, bgGreen, bgBlue);
bgGradient = ofColor(bgGradRed, bgGradGreen, bgGradBlue);
indexColor = ofColor(indexRed, indexBlue, indexGreen);
skelColor = ofColor(skelRed, skelGreen, skelBlue, skelAlpha);
// GUI load settings when state changes
if (lookChanged) {
gui->loadSettings("guiSettings_" + ofToString(currentLook) + ".xml");
guiColor->loadSettings("guiSettings_" + ofToString(currentLook) + "_color.xml");
lookChanged = false;
}
drawFrameRate = ofGetFrameRate();
//don't move the points if we are using the camera
if(!usecamera){
ofVec3f sumOfAllPoints(0,0,0);
int pointCount = 0;
for(unsigned int i = 0; i < points.size(); i++){
points[i].z -= 4;
sumOfAllPoints += points[i];
pointCount += 1;
}
for (auto body : ribbons) {
for (auto ribbon : body) {
for (unsigned int i = 0; i < ribbon.size(); i++) {
ribbon[i].z += 4; // TODO: figure out why this isn't working
sumOfAllPoints += ribbon[i];
pointCount += 1;
}
}
}
center = sumOfAllPoints / pointCount;
}
/////////////////
// Kinect
///////////////////
kinect.update();
//Getting joint positions (skeleton tracking)
/*
{
auto bodies = kinect.getBodySource()->getBodies();
for (auto body : bodies) {
for (auto joint : body.joints) {
//TODO: now do something with the joints
}
}
}
//*/
//
//Getting bones (connected joints)
{
// Note that for this we need a reference of which joints are connected to each other.
// We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like
auto bodies = kinect.getBodySource()->getBodies();
auto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas();
ribbons.resize(bodies.size());
int bodyIDX = 0;
vector <float> bodyDepths;
for (auto body : bodies) {
if (body.tracked) {
bodyDepths.push_back(body.joints[JointType_SpineBase].getPositionInWorld().z);
ribbons[bodyIDX].resize(boneAtlas.size());
int boneIDX = 0; // each bone gets a ribbon (for now)
for (auto bone : boneAtlas) {
auto firstJointInBone = body.joints[bone.first];
auto secondJointInBone = body.joints[bone.second];
ofVec3f firstJPos = firstJointInBone.getPositionInDepthMap();
ofVec3f secondJPos = secondJointInBone.getPositionInDepthMap();
firstJPos.z = firstJointInBone.getPosition().z;
secondJPos.z = secondJointInBone.getPosition().z;
firstJPos *= depthMapScale;
secondJPos *= depthMapScale;
//store joint positions for ribbon drawing later on
if (ribbons[bodyIDX][boneIDX].size() <= pointsMax -2) {
ribbons[bodyIDX][boneIDX].push_back(firstJPos);
ribbons[bodyIDX][boneIDX].push_back(secondJPos);
} else {
for (int i = 0; i < pointsMax - 2; i += 2) {
ribbons[bodyIDX][boneIDX][i] = ribbons[bodyIDX][boneIDX][i + 2];
ribbons[bodyIDX][boneIDX][i+1] = ribbons[bodyIDX][boneIDX][i + 3];
}
ribbons[bodyIDX][boneIDX][pointsMax - 2] = firstJPos;
ribbons[bodyIDX][boneIDX][pointsMax - 1] = secondJPos;
}
boneIDX += 1;
}
} else {
ribbons[bodyIDX].resize(0);
bodyDepths.push_back(-1);
}
bodyIDX += 1;
}
//cout << "ofApp :: update () -- bodyDepthOrder = " + ofToString(bodyDepthOrder) << endl;
//cout << "ofApp :: update () -- bodyDepths = " + ofToString(bodyDepths) << endl;
// TODO: get / create a depth-sorted version of this list
bodyDepthOrder.clear();
for (int i = 0; i < bodyDepths.size(); i++) {
float depth = bodyDepths[i];
if (bodyDepthOrder.size() == 0) {
bodyDepthOrder.push_back(i);
} else if (depth > bodyDepthOrder.back()) {
bodyDepthOrder.push_back(i);
} else if (depth < bodyDepthOrder.front()) {
bodyDepthOrder.insert(bodyDepthOrder.begin(), i);
} else {
for (int idx = 1; idx < bodyDepthOrder.size(); idx++) {
if (depth < bodyDepthOrder[idx]) {
bodyDepthOrder.insert(bodyDepthOrder.begin() + idx, i);
break;
}
}
}
}
//cout << "ofApp :: update () -- bodyDepthOrder (sorted) = " + ofToString(bodyDepthOrder) << endl;
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackgroundGradient(bgGradient, bgColor, OF_GRADIENT_LINEAR); //todo: put gradient mode into UI
//if we're using the camera, start it.
//everything that you draw between begin()/end() shows up from the view of the camera
if(usecamera){
camera.begin();
}
ofPushStyle();
if (debugging) {
ofSetColor(fgColor);
ofEnableBlendMode((ofBlendMode)fgBlendMode);
//do the same thing from the first example...
ofMesh mesh;
mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
for (unsigned int i = 1; i < points.size(); i++) {
//find this point and the next point
ofVec3f thisPoint = points[i - 1];
ofVec3f nextPoint = points[i];
//get the direction from one to the next.
//the ribbon should fan out from this direction
ofVec3f direction = (nextPoint - thisPoint);
//get the distance from one point to the next
float distance = direction.length();
//get the normalized direction. normalized vectors always have a length of one
//and are really useful for representing directions as opposed to something with length
ofVec3f unitDirection = direction.getNormalized();
//find both directions to the left and to the right
ofVec3f toTheLeft = unitDirection.getRotated(-90, ofVec3f(0, 0, 1));
ofVec3f toTheRight = unitDirection.getRotated(90, ofVec3f(0, 0, 1));
//use the map function to determine the distance.
//the longer the distance, the narrower the line.
//this makes it look a bit like brush strokes
float thickness = ofMap(distance, 0, 60, 20, 2, true);//TODO: put these constants into the GUI
//TODO: have tail shrink towards end so it disappears
//calculate the points to the left and to the right
//by extending the current point in the direction of left/right by the length
ofVec3f leftPoint = thisPoint + toTheLeft*thickness;
ofVec3f rightPoint = thisPoint + toTheRight*thickness;
//add these points to the triangle strip
mesh.addVertex(ofVec3f(leftPoint.x, leftPoint.y, leftPoint.z));
mesh.addVertex(ofVec3f(rightPoint.x, rightPoint.y, rightPoint.z));
}
//end the shape
mesh.draw();
}
ofPopStyle();
ofPushStyle();
// TODO: sort so foremost bodies appear foremost
// draw ribbons
for (unsigned int bodyIDX = 0; bodyIDX < bodyDepthOrder.size(); bodyIDX++) {
ofSetColor(fgColor / (bodyDepthOrder.size() -bodyIDX));
ofEnableBlendMode((ofBlendMode)fgBlendMode);
for (unsigned int boneIDX = 0; boneIDX < ribbons[bodyDepthOrder[bodyIDX]].size(); boneIDX++) {
ofMesh meshRibbon;
meshRibbon.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
for (unsigned int point = 0; point < ribbons[bodyDepthOrder[bodyIDX]][boneIDX].size(); point++) {
//add each joint to the triangle strip
meshRibbon.addVertex(ribbons[bodyDepthOrder[bodyIDX]][boneIDX][point]);
}
//end the shape
meshRibbon.draw();
}
}
ofPopStyle();
//if we're using the camera, take it away
if(usecamera){
camera.end();
}
ofPushStyle();
//TODO: move these hardcoded numbers into GUI
if (debugging) {
//kinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); // note that the depth texture is RAW so may appear dark
// Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio
//float colorHeight = previewWidth * (kinect.getColorSource()->getHeight() / kinect.getColorSource()->getWidth());
//float colorTop = (previewHeight - colorHeight) / 2.0;
//kinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight);
//kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight);
//kinect.getInfraredSource()->draw(0, 0, previewWidth, previewHeight);
}
ofPopStyle();
ofPushStyle();
if (debugging || drawBodyIndex) {
ofSetColor(indexColor);
ofEnableBlendMode((ofBlendMode)indexBlendMode);
kinect.getBodyIndexSource()->draw(0, 0, previewWidth, previewHeight);
}
ofPopStyle();
ofPushStyle();
if (debugging || drawBones) {
ofSetColor(skelColor);
ofEnableBlendMode((ofBlendMode)skelBlendMode);
kinect.getBodySource()->drawProjected(0, 0, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera);
}
ofPopStyle();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key) {
case ' ':
//hitting space key swaps the camera view
usecamera = !usecamera;
break;
case 'h':
case 'H':
gui->toggleVisible();
guiColor->toggleVisible();
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
//if we are using the camera, the mouse moving should rotate it around the whole sculpture
if(usecamera){
float rotateAmount = ofMap(ofGetMouseX(), 0, ofGetWidth(), 0, 360);//TODO: put this into the GUI
ofVec3f furthestPoint;
if (points.size() > 0) {
furthestPoint = points[0];
}
else
{
furthestPoint = ofVec3f(x, y, 0);
}
ofVec3f directionToFurthestPoint = (furthestPoint - center);
ofVec3f directionToFurthestPointRotated = directionToFurthestPoint.getRotated(rotateAmount, ofVec3f(0,1,0));
camera.setPosition(center + directionToFurthestPointRotated);
camera.lookAt(center);
}
//otherwise add points like before
else {
ofVec3f mousePoint(x,y,0);
if (points.size() < pointsMax) {
points.push_back(mousePoint);
}
else {
for (int i = 0; i < pointsMax-1; i++) {
points[i] = points[i + 1];
}
points[pointsMax-1] = mousePoint;
}
}
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
previewWidth = ofGetWindowWidth() * previewScaleW;
previewHeight = ofGetWindowHeight() * previewScaleH;
//float depthMapScaleW = 1.5 * previewWidth / 512.0f; //TODO: put hard-coded values into GUI
//float depthMapScaleH = 1.5 * previewHeight / 424.0f; //TODO: put hard-coded values into GUI
//depthMapScale = ofVec3f(depthMapScaleW, depthMapScaleH, -100.0f * (depthMapScaleH + depthMapScaleW) / 2.0f); //TODO: put hard-coded values into GUI
float depthMapScaleW = previewWidth / 512.0f;
float depthMapScaleH = previewHeight / 424.0f;
depthMapScale = ofVec3f(depthMapScaleW, depthMapScaleH, (depthMapScaleH + depthMapScaleW) / 2.0f);
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 34.228571 | 347 | 0.644825 | [
"mesh",
"object",
"shape",
"vector"
] |
236d9d00e49ddfd7c0927808df18485245df0def | 1,108 | cpp | C++ | main/src/json_config.cpp | tessmero/cpp-fractal | f6b8694da6d5e4ccd25d7c6153f3a90ee15b8875 | [
"MIT"
] | null | null | null | main/src/json_config.cpp | tessmero/cpp-fractal | f6b8694da6d5e4ccd25d7c6153f3a90ee15b8875 | [
"MIT"
] | null | null | null | main/src/json_config.cpp | tessmero/cpp-fractal | f6b8694da6d5e4ccd25d7c6153f3a90ee15b8875 | [
"MIT"
] | null | null | null | #include "json_config.h"
#include "shape.h"
#include "json.hpp"
#include <fstream>
#include <string>
using namespace std;
using json = nlohmann::json;
JsonConfig::JsonConfig( char* filename ) {
m_filename = filename;
ifstream(filename) >> m_json;
}
Shape JsonConfig::getRShape() {
vector<float> x = m_json["rshape"]["x"].get<vector<float>>();
vector<float> y = m_json["rshape"]["y"].get<vector<float>>();
return Shape(x,y);
}
Shape JsonConfig::getBShape() {
vector<float> x = m_json["bshape"]["x"].get<vector<float>>();
vector<float> y = m_json["bshape"]["y"].get<vector<float>>();
return Shape(x,y);
}
unsigned JsonConfig::getDepth() {
return m_json["depth"]["value"].get<unsigned>();
}
bool JsonConfig::getFlip() {
return m_json["flip"]["value"].get<bool>();
}
string JsonConfig::getOutputFilename() {
return m_json["output"]["filename"];
}
unsigned JsonConfig::getOutputWidth() {
return m_json["output"]["width"].get<unsigned>();
}
unsigned JsonConfig::getOutputHeight() {
return m_json["output"]["height"].get<unsigned>();
} | 24.622222 | 64 | 0.644404 | [
"shape",
"vector"
] |
236fb19aacd74fa114576968c2b2b8d64bf1e722 | 8,719 | cc | C++ | stanford2/cc/w3_dyn_pro.cc | zaqwes8811/cs-courses | aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2 | [
"Apache-2.0"
] | null | null | null | stanford2/cc/w3_dyn_pro.cc | zaqwes8811/cs-courses | aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2 | [
"Apache-2.0"
] | null | null | null | stanford2/cc/w3_dyn_pro.cc | zaqwes8811/cs-courses | aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2 | [
"Apache-2.0"
] | null | null | null | // Knapsack:
// - параллелизация не сильно помогла - в два раза только - хотя и вышло все просто
// - похоже нужен другой алгоритм
//
// Если очень большой объем данных
// - Рекурсивная реализация
// - Использовать только 2 колонки - скорости это врядли прибавит
// - Образать веса которых не может быть - как в задаче из 1 части - похоже в алгоритме уже есть фильтр
// - Хэш таблица похоже безсмысленна, она реализована на основе массива - хотя...
// - Сортировка
//
#include <gtest/gtest.h>
// C++98
#include <vector>
#include <ostream>
#include <string>
// C++11
#include <unordered_map>
// 3rdparty
#include <boost/unordered_map.hpp>
//#include <google/dense_hash_map>
//#include <google/sparse_hash_map>
//#include <adobe/algorithm/sort.hpp>
// inner
#include "visuality/view.h"
#include "details/io_details.h"
using namespace std;
using view::operator<<;
using io_details::Item;
using io_details::get_test_items;
using io_details::get_dyn_items;
namespace {
struct TaskId {
TaskId(int _w_bound, int _idx) : w_bound(_w_bound), idx(_idx) {}
TaskId() : w_bound(0), idx(0) {}
int w_bound;
int idx;
};
struct ItemsCompare {
bool operator()(const Item& lhs, const Item& rhs) {
return !(lhs.w < rhs.w);
}
};
struct KeyHash {
std::size_t operator()(const TaskId& k) const
{
// Watch "Eff. Java."
// Проблема в том как скомбинировать.
// TODO: other method calc.
//
// Good hash for pair:
// http://stackoverflow.com/questions/12764645/good-hash-function-with-2-integer-for-a-special-key
// http://stackoverflow.com/questions/2634690/good-hash-function-for-a-2d-index
// !!! http://web.archive.org/web/20071223173210/http://www.concentric.net/~Ttwang/tech/inthash.htm
//
// Hash variants:
//return boost::hash<pair<int, int> >()(make_pair(k.idx,k.w_bound)); // slow
//return boost::hash<int>()(k.w_bound) ^ (boost::hash<int>()(k.idx) << 1);
//return boost::hash<int>()(k.idx) ^ (boost::hash<int>()(k.w_bound) >> 1);
//return (size_t)((k.idx << 19) | (k.w_bound << 7));
//return boost::hash<int>()(k.idx) * 37 + (boost::hash<int>()(k.w_bound));
//return ((997 + boost::hash<int>()(k.idx)))*997 + boost::hash<int>()(k.w_bound);
// max speed
return boost::hash<int>()(k.idx) ^ (boost::hash<int>()(k.w_bound) << 1);
}
};
struct KeyHashStd {
std::size_t operator()(const TaskId& k) const
{
// Watch "Eff. Java."
// Проблема в том как скомбинировать.
// TODO: other method calc.
// Влияет очень не слабо! Возможно лучше 2D version
return ((std::hash<int>()(k.idx)) ^ (std::hash<int>()(k.w_bound) << 1));
//return boost::hash<int>()(k.idx) * 37 + (boost::hash<int>()(k.w_bound));
return ((51 + std::hash<int>()(k.idx)))*51 + std::hash<int>()(k.w_bound);
}
};
struct KeyEqual {
bool operator()(const TaskId& lhs, const TaskId& rhs) const
{
return lhs.idx == rhs.idx && lhs.w_bound == rhs.w_bound;
}
};
ostream& operator<<(ostream& o, const TaskId& id)
{
o << "(" << id.w_bound << ", " << id.idx << ")\n";
return o;
}
} // namespace
namespace {
// Returns the maximum value that can be put in a knapsack of capacity W
template <typename Store>
int knapSack_hashtable(const TaskId& id,
const vector<Item>& items,
Store& store)
{
// check task is solved
if (store.end() != store.find(id)) {
return store[id];
}
// Work
int n = id.idx;
int w_bound = id.w_bound;
// Base Case
if (n == 0 || w_bound == 0)
return 0;
// If weight of the nth item is more than Knapsack capacity W, then
// this item cannot be included in the optimal solution
if (items[n-1].w > w_bound) {
return
knapSack_hashtable(TaskId(w_bound, n-1), items, store);
} else {
// Return the maximum of two cases: (1) nth item included (2) not included
int sum_values = std::max(
knapSack_hashtable(TaskId(w_bound - items[n-1].w, n-1), items, store) + items[n-1].v,
knapSack_hashtable(TaskId(w_bound, n-1), items, store));
// Добавляем решенную
store.insert(make_pair(id, sum_values));
return sum_values;
}
}
//template <typename Store>
// Too slooow
int knapSack_hashtable_2d(const TaskId& id,
const vector<Item>& items,
std::unordered_map<int, std::unordered_map<int, int> >& store)
{
// check task is solved
{
std::unordered_map<int, std::unordered_map<int, int> >::iterator it = store.find(id.w_bound);
if (store.end() != it) {
std::unordered_map<int, int> tmp = it->second;
if (tmp.end() != tmp.find(id.idx))
return tmp[id.idx];
}
}
// Work
int n = id.idx;
int w_bound = id.w_bound;
// Base Case
if (n == 0 || w_bound == 0)
return 0;
// If weight of the nth item is more than Knapsack capacity W, then
// this item cannot be included in the optimal solution
if (items[n-1].w > w_bound) {
return
knapSack_hashtable_2d(TaskId(w_bound, n-1), items, store);
} else {
// Return the maximum of two cases: (1) nth item included (2) not included
int sum_values = std::max(
knapSack_hashtable_2d(TaskId(w_bound - items[n-1].w, n-1), items, store) + items[n-1].v,
knapSack_hashtable_2d(TaskId(w_bound, n-1), items, store));
// Добавляем решенную
// Если первый раз, то создаем пустую таблицу
if (store.end() == store.find(id.w_bound)) {
store.insert(make_pair(id.w_bound, std::unordered_map<int, int>()));
}
store[id.w_bound].insert(make_pair(id.idx, sum_values));
//store.insert(make_pair(id, sum_values));
return sum_values;
}
}
}
TEST(W3, BigKnapsackProblem)
{
// V(i, x) = max(V(i-1, x), v(i) + V(i-1, x-w(i))
// if w(i) > x
// V(i, x) = V(i-1, x)
//
pair<int, vector<Item > > tmp = get_test_items("NoFile");
vector<Item> items = tmp.second;
int W = tmp.first;
// A[0,0]
int N = items.size();
vector<vector<int> > A(N, vector<int>(W+1, 0));
for (int i = 1; i < N; ++i) {
const int v = items[i].v;
const int w = items[i].w;
// Значения объема может быть любым с точностью до единицы
// Итерация по емкостям
for (int x = 0; x <= W; ++x) {
int w_boundary = x - w;
if (w_boundary < 0) {
A[i][x] = A[i-1][x]; // просто копирование
} else {
A[i][x] = std::max(A[i][x], A[i-1][w_boundary] + v); // BUG: looks like
}
}
}
//cout << " " << A;
}
TEST(W3, GeeksForGeek_hashtable)
{
pair<int, vector<Item > > tmp = get_test_items("NoFile");
vector<Item> items = tmp.second;
int W = tmp.first;
int count = items.size();
TaskId root(W, count);
boost::unordered_map<TaskId, int, KeyHash, KeyEqual> store;
int result = knapSack_hashtable(root, items, store);
printf("sum(v(i)) = %d \n", result);
assert(result == 8);
}
TEST(W3, GeeksForGeek_hashtable_homework)
{
//pair<int, vector<Item > > tmp = get_dyn_items("./input_data/knapsack1.txt");
pair<int, vector<Item > > tmp = get_dyn_items("./input_data/knapsack_big.txt");
///*
vector<Item> items = tmp.second;
// Попробовать отсортировать по весу - только дольше
//adobe::sort(items);//, ItemsCompare());
//std::sort(items.begin(), items.end(), ItemsCompare());
int W = tmp.first;
int count = items.size();
TaskId root(W, count);
boost::unordered_map<TaskId, int, KeyHash, KeyEqual> store;//(4000);
//std::unordered_map<TaskId, int, KeyHashStd, KeyEqual> store;
/*
//DANGER: it's slooooow or incorrect
//google::dense_hash_map<
google::sparse_hash_map<
TaskId, int
, KeyHashStd, KeyEqual
> store;
//store.set_empty_key(TaskId());
//*/
cout << store.max_bucket_count() << endl;
int result = knapSack_hashtable(root, items, store);
printf("sum(v(i)) = %d \n", result);
assert(result == 4243395);
}
// Very slooow.
TEST(W3, GeeksForGeek_hashtable_2homework)
{
//pair<int, vector<Item > > tmp = get_dyn_items("./input_data/knapsack1.txt");
pair<int, vector<Item > > tmp = get_test_items("./input_data/knapsack_big.txt");
///*
vector<Item> items = tmp.second;
int W = tmp.first;
int count = items.size();
TaskId root(W, count);
//boost::unordered_map<TaskId, int, KeyHash, KeyEqual> store;
std::unordered_map<int, std::unordered_map<int, int> > store;
int result = knapSack_hashtable_2d(root, items, store);
printf("sum(v(i)) = %d \n", result);
//assert(result == 4243395);
}
TEST(W3, SparseColumn) {
// TODO: похоже скорость должна быть много больше
}
TEST(W3, BranchAndBound) {
}
| 28.775578 | 105 | 0.614061 | [
"vector"
] |
23762aa2cd90c441dc21b3ae81ea663b67c5823c | 739 | cpp | C++ | spec/cpp_stl_98/test_nav_parent_false.cpp | DarkShadow44/kaitai_struct_tests | 4bb13cef82965cca66dda2eb2b77cd64e9f70a12 | [
"MIT"
] | 11 | 2018-04-01T03:58:15.000Z | 2021-08-14T09:04:55.000Z | spec/cpp_stl_98/test_nav_parent_false.cpp | DarkShadow44/kaitai_struct_tests | 4bb13cef82965cca66dda2eb2b77cd64e9f70a12 | [
"MIT"
] | 73 | 2016-07-20T10:27:15.000Z | 2020-12-17T18:56:46.000Z | spec/cpp_stl_98/test_nav_parent_false.cpp | DarkShadow44/kaitai_struct_tests | 4bb13cef82965cca66dda2eb2b77cd64e9f70a12 | [
"MIT"
] | 37 | 2016-08-15T08:25:56.000Z | 2021-08-28T14:48:46.000Z | // Autogenerated from KST: please remove this line if doing any edits by hand!
#include <boost/test/unit_test.hpp>
#include "nav_parent_false.h"
#include <iostream>
#include <fstream>
#include <vector>
BOOST_AUTO_TEST_CASE(test_nav_parent_false) {
std::ifstream ifs("src/nav_parent_codes.bin", std::ifstream::binary);
kaitai::kstream ks(&ifs);
nav_parent_false_t* r = new nav_parent_false_t(&ks);
BOOST_CHECK_EQUAL(r->child_size(), 3);
BOOST_CHECK_EQUAL(r->element_a()->foo()->code(), 73);
BOOST_CHECK_EQUAL(r->element_a()->foo()->more(), std::string("\x31\x32\x33", 3));
BOOST_CHECK_EQUAL(r->element_a()->bar()->foo()->code(), 66);
BOOST_CHECK_EQUAL(r->element_b()->foo()->code(), 98);
delete r;
}
| 33.590909 | 85 | 0.688769 | [
"vector"
] |
2376f39bdfbdee36c0ba65589729796de12732e4 | 5,700 | cpp | C++ | src/libs/transaction_common/TransactionProtoHelper.cpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | 1 | 2020-03-04T10:38:00.000Z | 2020-03-04T10:38:00.000Z | src/libs/transaction_common/TransactionProtoHelper.cpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | null | null | null | src/libs/transaction_common/TransactionProtoHelper.cpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | 1 | 2020-03-04T10:38:01.000Z | 2020-03-04T10:38:01.000Z | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: TransactionProtoHelper.cpp
* Author: ubuntu
*
* Created on March 19, 2018, 7:59 AM
*/
#include "keto/transaction_common/TransactionProtoHelper.hpp"
#include "keto/server_common/VectorUtils.hpp"
#include "keto/crypto/HashGenerator.hpp"
#include "keto/crypto/SignatureGenerator.hpp"
#include "keto/crypto/SecureVectorUtils.hpp"
#include "include/keto/transaction_common/TransactionProtoHelper.hpp"
namespace keto {
namespace transaction_common {
TransactionProtoHelper::TransactionProtoHelper() {
}
TransactionProtoHelper::TransactionProtoHelper(const keto::proto::Transaction& transaction) {
this->transaction.CopyFrom(transaction);
}
TransactionProtoHelper::TransactionProtoHelper(
const TransactionMessageHelperPtr& transactionMessageHelper) {
keto::asn1::HashHelper hashHelper = transactionMessageHelper->getHash();
transaction.set_transaction_hash(
hashHelper.operator keto::crypto::SecureVector().data(),
hashHelper.operator keto::crypto::SecureVector().size());
keto::asn1::SignatureHelper signatureHelper = transactionMessageHelper->getSignature();
transaction.set_transaction_signature(
signatureHelper.operator std::vector<uint8_t>().data(),
signatureHelper.operator std::vector<uint8_t>().size());
hashHelper = transactionMessageHelper->getCurrentAccount();
transaction.set_active_account(
hashHelper.operator keto::crypto::SecureVector().data(),
hashHelper.operator keto::crypto::SecureVector().size());
if (transactionMessageHelper->getStatus() == Status_init) {
transaction.set_status(keto::proto::TransactionStatus::INIT);
} else if (transactionMessageHelper->getStatus() == Status_debit) {
transaction.set_status(keto::proto::TransactionStatus::DEBIT);
} else if (transactionMessageHelper->getStatus() == Status_processing) {
transaction.set_status(keto::proto::TransactionStatus::PROCESS);
} else if (transactionMessageHelper->getStatus() == Status_fee) {
transaction.set_status(keto::proto::TransactionStatus::FEE);
} else if (transactionMessageHelper->getStatus() == Status_credit) {
transaction.set_status(keto::proto::TransactionStatus::CREDIT);
} else if (transactionMessageHelper->getStatus() == Status_complete) {
transaction.set_status(keto::proto::TransactionStatus::COMPLETE);
}
std::vector<uint8_t> serializedTransaction =
transactionMessageHelper->operator std::vector<uint8_t>();
transaction.set_asn1_transaction_message(
serializedTransaction.data(),serializedTransaction.size());
}
TransactionProtoHelper::~TransactionProtoHelper() {
}
TransactionProtoHelper& TransactionProtoHelper::setTransaction(
const TransactionMessageHelperPtr& transactionMessageHelper) {
keto::asn1::HashHelper hashHelper = transactionMessageHelper->getHash();
transaction.set_transaction_hash(
hashHelper.operator keto::crypto::SecureVector().data(),
hashHelper.operator keto::crypto::SecureVector().size());
keto::asn1::SignatureHelper signatureHelper = transactionMessageHelper->getSignature();
transaction.set_transaction_signature(
signatureHelper.operator std::vector<uint8_t>().data(),
signatureHelper.operator std::vector<uint8_t>().size());
hashHelper = transactionMessageHelper->getCurrentAccount();
transaction.set_active_account(
hashHelper.operator keto::crypto::SecureVector().data(),
hashHelper.operator keto::crypto::SecureVector().size());
if (transactionMessageHelper->getStatus() == Status_init) {
transaction.set_status(keto::proto::TransactionStatus::INIT);
} else if (transactionMessageHelper->getStatus() == Status_debit) {
transaction.set_status(keto::proto::TransactionStatus::DEBIT);
} else if (transactionMessageHelper->getStatus() == Status_processing) {
transaction.set_status(keto::proto::TransactionStatus::PROCESS);
} else if (transactionMessageHelper->getStatus() == Status_fee) {
transaction.set_status(keto::proto::TransactionStatus::FEE);
} else if (transactionMessageHelper->getStatus() == Status_credit) {
transaction.set_status(keto::proto::TransactionStatus::CREDIT);
} else if (transactionMessageHelper->getStatus() == Status_complete) {
transaction.set_status(keto::proto::TransactionStatus::COMPLETE);
}
std::vector<uint8_t> serializedTransaction =
transactionMessageHelper->operator std::vector<uint8_t>();
transaction.set_asn1_transaction_message(
serializedTransaction.data(),serializedTransaction.size());
return (*this);
}
TransactionProtoHelper& TransactionProtoHelper::setTransaction(
const std::string& buffer) {
transaction.ParseFromString(buffer);
return (*this);
}
TransactionProtoHelper::operator std::string() {
std::string buffer;
transaction.SerializeToString(&buffer);
return buffer;
}
TransactionProtoHelper::operator keto::proto::Transaction&() {
return this->transaction;
}
TransactionProtoHelper& TransactionProtoHelper::operator = (const keto::proto::Transaction& transaction) {
this->transaction.CopyFrom(transaction);
return (*this);
}
TransactionMessageHelperPtr TransactionProtoHelper::getTransactionMessageHelper() {
return TransactionMessageHelperPtr(
new TransactionMessageHelper(this->transaction.asn1_transaction_message()));
}
}
} | 40.140845 | 106 | 0.737895 | [
"vector"
] |
237e4e49a05a369e9feebb1c557ea12ea5ae6e5a | 3,864 | cc | C++ | ui/base/ime/win/tsf_input_scope_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ui/base/ime/win/tsf_input_scope_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ui/base/ime/win/tsf_input_scope_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ime/win/tsf_input_scope.h"
#include <InputScope.h>
#include <stddef.h>
#include "testing/gtest/include/gtest/gtest.h"
namespace ui {
namespace {
struct GetInputScopesTestCase {
TextInputType input_type;
TextInputMode input_mode;
size_t expected_size;
InputScope expected_input_scopes[2];
};
// Google Test pretty-printer.
void PrintTo(const GetInputScopesTestCase& data, std::ostream* os) {
*os << " input_type: " << testing::PrintToString(data.input_type)
<< "; input_mode: " << testing::PrintToString(data.input_mode);
}
class TSFInputScopeTest
: public testing::TestWithParam<GetInputScopesTestCase> {
};
const GetInputScopesTestCase kGetInputScopesTestCases[] = {
// Test cases of TextInputType.
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_TEXT, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_PASSWORD, TEXT_INPUT_MODE_DEFAULT, 1, {IS_PASSWORD}},
{TEXT_INPUT_TYPE_SEARCH, TEXT_INPUT_MODE_DEFAULT, 1, {IS_SEARCH}},
{TEXT_INPUT_TYPE_EMAIL,
TEXT_INPUT_MODE_DEFAULT,
1,
{IS_EMAIL_SMTPEMAILADDRESS}},
{TEXT_INPUT_TYPE_NUMBER, TEXT_INPUT_MODE_DEFAULT, 1, {IS_NUMBER}},
{TEXT_INPUT_TYPE_TELEPHONE,
TEXT_INPUT_MODE_DEFAULT,
1,
{IS_TELEPHONE_FULLTELEPHONENUMBER}},
{TEXT_INPUT_TYPE_URL, TEXT_INPUT_MODE_DEFAULT, 1, {IS_URL}},
{TEXT_INPUT_TYPE_DATE, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_DATE_TIME, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_DATE_TIME_LOCAL, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_MONTH, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_TIME, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_WEEK, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_TEXT_AREA, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_CONTENT_EDITABLE,
TEXT_INPUT_MODE_DEFAULT,
1,
{IS_DEFAULT}},
{TEXT_INPUT_TYPE_DATE_TIME_FIELD, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
// Test cases of TextInputMode.
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_DEFAULT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_TEXT, 1, {IS_DEFAULT}},
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_NUMERIC, 1, {IS_DIGITS}},
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_DECIMAL, 1, {IS_NUMBER}},
{TEXT_INPUT_TYPE_NONE,
TEXT_INPUT_MODE_TEL,
1,
{IS_TELEPHONE_FULLTELEPHONENUMBER}},
{TEXT_INPUT_TYPE_NONE,
TEXT_INPUT_MODE_EMAIL,
1,
{IS_EMAIL_SMTPEMAILADDRESS}},
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_URL, 1, {IS_URL}},
{TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_SEARCH, 1, {IS_SEARCH}},
// Mixed test cases.
{TEXT_INPUT_TYPE_EMAIL,
TEXT_INPUT_MODE_EMAIL,
1,
{IS_EMAIL_SMTPEMAILADDRESS}},
{TEXT_INPUT_TYPE_NUMBER,
TEXT_INPUT_MODE_NUMERIC,
2,
{IS_NUMBER, IS_DIGITS}},
{TEXT_INPUT_TYPE_TELEPHONE,
TEXT_INPUT_MODE_TEL,
1,
{IS_TELEPHONE_FULLTELEPHONENUMBER}},
{TEXT_INPUT_TYPE_URL, TEXT_INPUT_MODE_URL, 1, {IS_URL}},
};
TEST_P(TSFInputScopeTest, GetInputScopes) {
const GetInputScopesTestCase& test_case = GetParam();
std::vector<InputScope> input_scopes = tsf_inputscope::GetInputScopes(
test_case.input_type, test_case.input_mode);
EXPECT_EQ(test_case.expected_size, input_scopes.size());
for (size_t i = 0; i < test_case.expected_size; ++i)
EXPECT_EQ(test_case.expected_input_scopes[i], input_scopes[i]);
}
INSTANTIATE_TEST_CASE_P(,
TSFInputScopeTest,
::testing::ValuesIn(kGetInputScopesTestCases));
} // namespace
} // namespace ui
| 35.777778 | 80 | 0.736542 | [
"vector"
] |
238d7d35a469bf5f0bd8918cb759ff16ff6a59a8 | 23,933 | cpp | C++ | src/DewDropPlayer/UI/DewDiscSelector.cpp | kineticpsychology/Dew-Drop-Project | 1704ac491395800c0b1e54d1d0fd761fc5a71296 | [
"0BSD"
] | null | null | null | src/DewDropPlayer/UI/DewDiscSelector.cpp | kineticpsychology/Dew-Drop-Project | 1704ac491395800c0b1e54d1d0fd761fc5a71296 | [
"0BSD"
] | null | null | null | src/DewDropPlayer/UI/DewDiscSelector.cpp | kineticpsychology/Dew-Drop-Project | 1704ac491395800c0b1e54d1d0fd761fc5a71296 | [
"0BSD"
] | null | null | null | /*******************************************************************************
* *
* COPYRIGHT (C) Aug, 2020 | Polash Majumdar *
* *
* This file is part of the Dew Drop Player project. The file content comes *
* "as is" without any warranty of definitive functionality. The author of the *
* code is not to be held liable for any improper functionality, broken code, *
* bug and otherwise unspecified error that might cause damage or might break *
* the application where this code is imported. In accordance with the *
* Zero-Clause BSD licence model of the Dew Drop project, the end-user/adopter *
* of this code is hereby granted the right to use, copy, modify, and/or *
* distribute this code with/without keeping this copyright notice. *
* *
* TL;DR - It's a free world. All of us should give back to the world that we *
* get so much from. I have tried doing my part by making this code *
* free (as in free beer). Have fun. Just don't vandalize the code *
* or morph it into a malicious one. *
* *
*******************************************************************************/
#include "DewDiscSelector.h"
UINT DEWDISCSELECTOR::_snInstanceCount = 0;
LRESULT CALLBACK DEWDISCSELECTOR::_DSMsgHandler(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam, UINT_PTR nID, DWORD_PTR dwRefData)
{
return ((LPDEWDISCSELECTOR)dwRefData)->_WndProc(hWnd, nMsg, wParam, lParam);
return 0;
}
void DEWDISCSELECTOR::_HandleSizing()
{
RECT rctClient;
int iX, iY, iW, iH;
LVTILEVIEWINFO lvTVI { 0 };
GetClientRect(_hWndDiscSelector, &rctClient);
iX = _F(10); iY = _F(10); iW = rctClient.right - _F(20); iH = rctClient.bottom - _F(60);
SetWindowPos(_hLstDrives, 0, iX, iY, iW, iH, SWP_NOZORDER);
iW = _F(75); iH = _F(30); iY = rctClient.bottom - iH - _F(10);
iX = rctClient.right - iW - _F(10);
SetWindowPos(_hCmdOK, 0, iX, iY, iW, iH, SWP_NOZORDER);
iX = _F(10);
SetWindowPos(_hCmdCancel, 0, iX, iY, iW, iH, SWP_NOZORDER);
lvTVI.cbSize = sizeof(LVTILEVIEWINFO);
lvTVI.dwFlags = LVTVIF_FIXEDSIZE;
lvTVI.dwMask = LVTVIM_COLUMNS | LVTVIM_TILESIZE;
lvTVI.cLines = 3;
lvTVI.sizeTile.cx = (rctClient.right - _F(20)) - GetSystemMetrics(SM_CXVSCROLL);
lvTVI.sizeTile.cy = _F(DEWUI_DIM_SYM_DISC_ICON);
ListView_SetTileViewInfo(_hLstDrives, &lvTVI);
return;
}
void DEWDISCSELECTOR::_EnumDrives()
{
typedef struct _DEWDRIVELIST
{
wchar_t wsPathName[MAX_PATH];
wchar_t wsVolumeLabel[MAX_PATH];
wchar_t wsFSName[MAX_PATH];
wchar_t wsDriveType[32];
struct _DEWDRIVELIST *next;
} DEWDRIVELIST, *LPDEWDRIVELIST;
HANDLE hVol = NULL;
DWORD dwSize;
DWORD dwSerialNo, dwMaxComp, dwFSFlags;
BOOL bInserted;
wchar_t wsVolumeName[MAX_PATH];
wchar_t wsPathName[MAX_PATH];
LPDEWDRIVELIST lpStart = NULL, lpCurr, lpPrev = NULL, lpNext = NULL;
hVol = FindFirstVolume(wsVolumeName, MAX_PATH);
if (hVol != NULL && hVol != INVALID_HANDLE_VALUE)
{
do
{
dwSize = MAX_PATH;
dwSerialNo = dwMaxComp = dwFSFlags = 0;
GetVolumePathNamesForVolumeName(wsVolumeName, wsPathName, dwSize, &dwSize);
if (lstrlen(wsPathName))
{
lpCurr = (LPDEWDRIVELIST)LocalAlloc(LPTR, sizeof(DEWDRIVELIST));
lpCurr->next = NULL;
CopyMemory((lpCurr->wsPathName), wsPathName, MAX_PATH * sizeof(wchar_t));
GetVolumeInformation(lpCurr->wsPathName, (lpCurr->wsVolumeLabel), MAX_PATH, &dwSerialNo, &dwMaxComp, &dwFSFlags, (lpCurr->wsFSName), MAX_PATH);
switch(GetDriveType(lpCurr->wsPathName))
{
case DRIVE_NO_ROOT_DIR: { StringCchPrintf((lpCurr->wsDriveType), 32, L"Invalid Root Path\n"); break; }
case DRIVE_REMOVABLE: { StringCchPrintf((lpCurr->wsDriveType), 32, L"Removable Media\n"); break; }
case DRIVE_FIXED: { StringCchPrintf((lpCurr->wsDriveType), 32, L"Fixed Drive\n"); break; }
case DRIVE_REMOTE: { StringCchPrintf((lpCurr->wsDriveType), 32, L"Remote Drive\n"); break; }
case DRIVE_CDROM: { StringCchPrintf((lpCurr->wsDriveType), 32, L"CD ROM Drive\n"); break; }
case DRIVE_RAMDISK: { StringCchPrintf((lpCurr->wsDriveType), 32, L"RAM Disk\n"); break; }
default: StringCchPrintf((lpCurr->wsDriveType), 32, L"Unknown\n");
}
if (lpStart == NULL) // No entry. Empty list
{
lpStart = lpCurr;
}
else if (lstrcmpi((lpStart->wsPathName), (lpCurr->wsPathName)) > 0) // Entry needs to be made at the very beginning
{
lpCurr->next = lpStart;
lpStart = lpCurr;
}
else if (lpStart->next == NULL) // Just one entry is there. A new entry is to be made at the end
{
lpStart->next = lpCurr;
}
else
{
bInserted = FALSE;
lpPrev = lpStart;
do
{
lpNext = lpPrev->next;
if (lpNext != NULL &&
lstrcmpi((lpNext->wsPathName), (lpCurr->wsPathName)) > 0 &&
lstrcmpi((lpPrev->wsPathName), (lpCurr->wsPathName)) <= 0)
{
lpCurr->next = lpNext;
lpPrev->next = lpCurr;
bInserted = TRUE;
break;
}
lpPrev = lpPrev->next;
} while (lpPrev->next);
if (!bInserted)
lpPrev->next = lpCurr;
}
}
} while (FindNextVolume(hVol, wsVolumeName, MAX_PATH));
FindVolumeClose(hVol);
lpCurr = lpStart;
while (lpCurr)
{
lpPrev = lpCurr;
lpCurr = lpPrev->next;
// Filter to check for CDFS and only insert those into the listview
if (GetDriveType(lpPrev->wsPathName) == DRIVE_CDROM)
this->_AddDiscInfo(lpPrev->wsPathName, lpPrev->wsVolumeLabel, lpPrev->wsDriveType, lpPrev->wsFSName, (lpPrev == lpStart));
LocalFree(lpPrev);
}
}
return;
}
void DEWDISCSELECTOR::_AddDiscInfo(LPWSTR wsPath, LPWSTR wsLabel, LPWSTR wsDriveType, LPWSTR wsFSType, BOOL bFlushAll)
{
LVITEM lvItem { 0 };
int iIndex;
UINT nOrder[] = { 1, 2 };
int iColFmt[] = { LVCFMT_FILL, LVCFMT_FILL, LVCFMT_FILL };
wchar_t wsTitle[MAX_PATH * 2];
if (bFlushAll)
ListView_DeleteAllItems(_hLstDrives);
iIndex = ListView_GetItemCount(_hLstDrives);
StringCchPrintf(wsTitle, MAX_PATH * 2, L"%s (%s)", wsLabel, wsPath);
lvItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_COLUMNS;
lvItem.iItem = iIndex;
lvItem.iSubItem = 0;
lvItem.pszText = wsTitle;
lvItem.iImage = 0;
lvItem.cColumns = 2;
lvItem.puColumns = nOrder;
ListView_InsertItem(_hLstDrives, &lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = iIndex;
lvItem.iSubItem = 1;
lvItem.pszText = wsDriveType;
lvItem.iImage = 0;
ListView_SetItem(_hLstDrives, &lvItem);
lvItem.mask = LVIF_TEXT;
lvItem.iItem = iIndex;
lvItem.iSubItem = 2;
lvItem.pszText = wsFSType;
lvItem.iImage = 0;
ListView_SetItem(_hLstDrives, &lvItem);
return;
}
void DEWDISCSELECTOR::_DestroyGDIObjects()
{
int iIndex, iCount;
IMAGEINFO imgInfo { 0 };
if (_lpSymbolFont) { delete _lpSymbolFont; _lpSymbolFont = NULL; }
if (_hbrWndBack) { DeleteObject(_hbrWndBack); _hbrWndBack = NULL; }
if (_hbrBtnBack) { DeleteObject(_hbrBtnBack); _hbrBtnBack = NULL; }
if (_hPenBtnFocus) { DeleteObject(_hPenBtnFocus); _hPenBtnFocus = NULL; }
if (_hPenBtnBorder) { DeleteObject(_hPenBtnBorder); _hPenBtnBorder = NULL; }
if (_hPenLstBorder) { DeleteObject(_hPenLstBorder); _hPenLstBorder = NULL; }
if (_hPenWndBorder) { DeleteObject(_hPenWndBorder); _hPenWndBorder = NULL; }
if (_hFntUI) { DeleteObject(_hFntUI); _hFntUI = NULL; }
if (_hFntIcon) { DeleteObject(_hFntIcon); _hFntIcon = NULL; }
if (_pFntSymbol) { delete _pFntSymbol; _pFntSymbol = NULL; }
if (_pBrText) { delete _pBrText; _pBrText = NULL; }
iCount = ImageList_GetImageCount(_hImlDriveTypes);
for (iIndex = 0; iIndex < iCount; iIndex++)
{
ImageList_GetImageInfo(_hImlDriveTypes, iIndex, &imgInfo);
if (imgInfo.hbmImage) { DeleteObject(imgInfo.hbmImage); imgInfo.hbmImage = NULL; }
if (imgInfo.hbmMask) { DeleteObject(imgInfo.hbmMask); imgInfo.hbmMask = NULL; }
}
ImageList_RemoveAll(_hImlDriveTypes);
return;
}
void DEWDISCSELECTOR::_ApplyTheme(const DEWTHEME& Theme)
{
LOGFONT lgfFont { 0 };
HWND hWndChild = NULL;
Color crRef;
this->_DestroyGDIObjects();
_lpSymbolFont = new DEWSYMBOLFONT();
_hbrWndBack = CreateSolidBrush(Theme.WinStyle.BackColor);
_hbrBtnBack = CreateSolidBrush(Theme.MMButtonStyle.BackColor);
_hPenBtnFocus = CreatePen(PS_DOT, _F(1), Theme.MMButtonStyle.OutlineColor);
_hPenBtnBorder = CreatePen(PS_SOLID, _F(1), Theme.MMButtonStyle.OutlineColor);
_hPenLstBorder = CreatePen(PS_SOLID, _F(1), Theme.MMButtonStyle.OutlineColor);
_hPenWndBorder = CreatePen(PS_SOLID, _F(1), Theme.WinStyle.OutlineColor);
_crBtnText = Theme.MMButtonStyle.TextColor;
crRef.SetFromCOLORREF(Theme.ModuleStyle.TextColor);
_pBrText = new SolidBrush(crRef);
ListView_SetBkColor(_hLstDrives, Theme.ModuleStyle.BackColor);
ListView_SetTextBkColor(_hLstDrives, Theme.ModuleStyle.BackColor);
ListView_SetTextColor(_hLstDrives, Theme.ModuleStyle.TextColor);
ListView_SetOutlineColor(_hLstDrives, Theme.ModuleStyle.OutlineColor);
lgfFont.lfHeight = -MulDiv(8, _iDPI, 72);
lgfFont.lfWidth = 0;
lgfFont.lfWeight = FW_NORMAL;
lgfFont.lfCharSet = DEFAULT_CHARSET;
lgfFont.lfQuality = CLEARTYPE_QUALITY;
lgfFont.lfPitchAndFamily = DEFAULT_PITCH;
CopyMemory(lgfFont.lfFaceName, L"Tahoma", 32 * sizeof(wchar_t));
_hFntUI = CreateFontIndirect(&lgfFont);
lgfFont.lfHeight = -MulDiv(DEWUI_DIM_SYM_BUTTON_FONT, _iDPI, 72);
CopyMemory(lgfFont.lfFaceName, DEWUI_SYMBOL_FONT_NAME, 32 * sizeof(wchar_t));
_hFntIcon = CreateFontIndirect(&lgfFont);
_pFntSymbol = new Font(_lpSymbolFont->SymbolFontGDIPlus, (REAL)_F(DEWUI_DIM_SYM_DISC_FONT), FontStyleRegular, UnitPoint);
this->_AddImageListImage(DEWUI_SYMBOL_OPEN_DISC);
hWndChild = FindWindowEx(_hWndDiscSelector, hWndChild, NULL, NULL);
do
{
if (hWndChild)
SendMessage(hWndChild, WM_SETFONT, (WPARAM)_hFntUI, MAKELPARAM(TRUE, 0));
hWndChild = FindWindowEx(_hWndDiscSelector, hWndChild, NULL, NULL);
} while (hWndChild);
return;
}
void DEWDISCSELECTOR::_AddImageListImage(LPCWSTR wsSymbol)
{
Bitmap *pImg = NULL;
Color crRef;
Graphics *pGr = NULL;
int BTN_ICON_SIZE;
PointF ptStart (0.0f, 0.0f);
RectF rctPos;
HBITMAP hBmp;
BTN_ICON_SIZE = _F(DEWUI_DIM_SYM_DISC_ICON);
pImg = new Bitmap(BTN_ICON_SIZE, BTN_ICON_SIZE, PixelFormat32bppARGB);
pGr = Graphics::FromImage(pImg);
pGr->SetTextRenderingHint(TextRenderingHintAntiAlias);
pGr->MeasureString(wsSymbol, -1, _pFntSymbol, ptStart, &rctPos);
ptStart.X = ((REAL)BTN_ICON_SIZE - rctPos.Width)/2.0f;
ptStart.Y = ((REAL)BTN_ICON_SIZE - rctPos.Height)/2.0f;
pGr->DrawString(wsSymbol, -1, _pFntSymbol, ptStart, _pBrText);
pImg->GetHBITMAP(Color::Transparent, &hBmp);
ImageList_Add(_hImlDriveTypes, hBmp, (HBITMAP)NULL);
DeleteObject(hBmp);
delete pImg;
delete pGr;
return;
}
void DEWDISCSELECTOR::_SetCurrentSelection()
{
int iIndex;
LVITEM lvSel;
wchar_t wsSel[MAX_PATH * 2] { 0 };
iIndex = ListView_GetNextItem(_hLstDrives, -1, LVNI_SELECTED);
if (iIndex == -1) return;
lvSel.mask = LVIF_TEXT;
lvSel.iItem = iIndex;
lvSel.iSubItem = 0;
lvSel.pszText = wsSel;
lvSel.cchTextMax = MAX_PATH * 2;
ListView_GetItem(_hLstDrives, &lvSel);
CopyMemory(_wsSelPath, (StrStrI(wsSel, L":") - 1), 2 * sizeof(wchar_t));
SendMessage(_hWndDiscSelector, WM_CLOSE, 0, 0);
PostMessage(_hWndParent, WM_DEWMSG_DISC_SEL, 0, (LPARAM)_wsSelPath);
return;
}
void DEWDISCSELECTOR::_Draw()
{
RECT rctClient;
RECT rctList;
HGDIOBJ hObjOld;
GetClientRect(_hWndDiscSelector, &rctClient);
GetWindowRect(_hLstDrives, &rctList);
MapWindowPoints(HWND_DESKTOP, _hWndDiscSelector, (LPPOINT)&rctList, 2);
hObjOld = SelectObject(_hDC, _hbrWndBack);
SelectObject(_hDC, _hPenWndBorder);
Rectangle(_hDC, rctClient.left, rctClient.top, rctClient.right, rctClient.bottom);
SelectObject(_hDC, _hPenLstBorder);
rctList.left -= _F(1); rctList.top -= _F(1); rctList.right += _F(1); rctList.bottom += _F(1);
Rectangle(_hDC, rctList.left - 1, rctList.top, rctList.right, rctList.bottom);
SelectObject(_hDC, hObjOld);
return;
}
void DEWDISCSELECTOR::_DrawButton(const LPDRAWITEMSTRUCT& lpDIS, LPCWSTR wsText, LPCWSTR wsSymbol)
{
RECT rctText, rctIcon;
HGDIOBJ hObjOld, hOblOldIcon;
HDC hDCMem;
HBITMAP hBmpIcon;
// Current DC Settings
SetBkMode(lpDIS->hDC, TRANSPARENT);
SetTextColor(lpDIS->hDC, _crBtnText);
// Mem DC (Icon) Settings
rctIcon.left = 0;
rctIcon.top = 0;
rctIcon.right = lpDIS->rcItem.bottom - _F(7);
rctIcon.bottom = lpDIS->rcItem.bottom - _F(7);
hDCMem = CreateCompatibleDC(lpDIS->hDC);
hBmpIcon = CreateCompatibleBitmap(lpDIS->hDC, rctIcon.right, rctIcon.bottom);
hOblOldIcon = SelectObject(hDCMem, hBmpIcon);
SelectObject(hDCMem, _hFntIcon);
FillRect(hDCMem, &rctIcon, _hbrBtnBack);
SetTextColor(hDCMem, _crBtnText);
SetBkMode(hDCMem, TRANSPARENT);
DrawText(hDCMem, wsSymbol, -1, &rctIcon, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
hObjOld = SelectObject(lpDIS->hDC, _hbrBtnBack);
SelectObject(lpDIS->hDC, _hFntUI);
SelectObject(lpDIS->hDC, _hPenBtnBorder);
Rectangle(lpDIS->hDC, lpDIS->rcItem.left, lpDIS->rcItem.top, lpDIS->rcItem.right, lpDIS->rcItem.bottom);
if ((lpDIS->itemState & ODS_FOCUS) == ODS_FOCUS)
{
CopyMemory(&rctText, &(lpDIS->rcItem), sizeof(RECT));
InflateRect(&rctText, -_F(2), -_F(2));
SelectObject(lpDIS->hDC, _hPenBtnFocus);
Rectangle(lpDIS->hDC, rctText.left, rctText.top, rctText.right, rctText.bottom);
}
if ((lpDIS->itemState & ODS_SELECTED) == ODS_SELECTED)
BitBlt(lpDIS->hDC, _F(4), _F(4), rctIcon.right + _F(1), rctIcon.bottom + _F(1), hDCMem, 0, 0, SRCCOPY);
else
BitBlt(lpDIS->hDC, _F(3), _F(3), rctIcon.right, rctIcon.bottom, hDCMem, 0, 0, SRCCOPY);
SelectObject(hDCMem, hOblOldIcon);
DeleteObject(hBmpIcon);
DeleteDC(hDCMem);
CopyMemory(&rctText, &(lpDIS->rcItem), sizeof(RECT));
rctText.left = _F(30);
if ((lpDIS->itemState & ODS_SELECTED) == ODS_SELECTED)
OffsetRect(&rctText, _F(1), _F(1));
DrawText(lpDIS->hDC, wsText, -1, &rctText, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
SelectObject(lpDIS->hDC, hObjOld);
return;
}
LRESULT DEWDISCSELECTOR::_WndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps { 0 };
LPNMHDR lpNMH;
LPWINDOWPOS lpPos;
RECT rctWorkArea;
switch(nMsg)
{
case WM_COMMAND:
{
if ( (HWND)lParam == _hCmdCancel ||
((HWND)lParam == 0x00 && LOWORD(wParam) == IDCANCEL) )
SendMessage(_hWndDiscSelector, WM_CLOSE, 0, 0);
else if ( (HWND)lParam == _hCmdOK ||
((HWND)lParam == 0x00 && LOWORD(wParam) == IDOK) )
this->_SetCurrentSelection();
break;
}
case WM_NOTIFY:
{
lpNMH = (LPNMHDR)lParam;
if (lpNMH->hwndFrom == _hLstDrives)
{
if (lpNMH->code == NM_CLICK || lpNMH->code == LVN_ITEMCHANGED)
{
ShowWindow(_hCmdOK, ((ListView_GetNextItem(_hLstDrives, -1, LVNI_SELECTED) != -1) ? SW_SHOW : SW_HIDE));
}
else if (lpNMH->code == NM_DBLCLK)
{
this->_SetCurrentSelection();
}
}
return FALSE;
}
case WM_PAINT:
{
BeginPaint(hWnd, &ps);
this->_Draw();
EndPaint(hWnd, &ps);
return FALSE;
}
case WM_DRAWITEM:
{
if (((LPDRAWITEMSTRUCT)lParam)->hwndItem == _hCmdOK)
this->_DrawButton(((LPDRAWITEMSTRUCT)lParam), L"&OK", DEWUI_SYMBOL_BUTTON_OK);
else if (((LPDRAWITEMSTRUCT)lParam)->hwndItem == _hCmdCancel)
this->_DrawButton(((LPDRAWITEMSTRUCT)lParam), L"&Cancel", DEWUI_SYMBOL_BUTTON_CANCEL);
else
break;
return TRUE;
}
case WM_SIZE:
{
this->_HandleSizing();
return FALSE;
}
// Do not allow the window to move out of the work area
case WM_WINDOWPOSCHANGING:
{
SystemParametersInfo(SPI_GETWORKAREA, 0, &rctWorkArea, 0);
lpPos = (LPWINDOWPOS)lParam;
if (lpPos->cx + lpPos->x > rctWorkArea.right) lpPos->x = rctWorkArea.right - lpPos->cx;
if (lpPos->x < rctWorkArea.left) lpPos->x = rctWorkArea.left;
if (lpPos->cy + lpPos->y > rctWorkArea.bottom) lpPos->y = rctWorkArea.bottom - lpPos->cy;
if (lpPos->y < rctWorkArea.top) lpPos->y = rctWorkArea.top;
return 0;
}
case WM_CLOSE:
{
ShowWindow(_hWndDiscSelector, SW_HIDE);
PostMessage(_hWndParent, WM_DEWMSG_CHILD_CLOSED, 0, (LPARAM)_hWndDiscSelector);
SetForegroundWindow(_hWndParent);
return TRUE;
}
}
return DefSubclassProc(hWnd, nMsg, wParam, lParam);
}
DEWDISCSELECTOR::DEWDISCSELECTOR(HWND hWndParent, int iDPI, float fScale) : SelectedPath(_wsSelPath)
{
if ((DEWDISCSELECTOR::_snInstanceCount) == 0)
{
WNDCLASSEX wcex { 0 };
const wchar_t *wsClass = L"DEWDROP.DISCSEL.WND";
const DWORD dwWinStyle = WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN;
const DWORD dwBtnStyle = WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_OWNERDRAW;
const DWORD dwLstStyle = WS_CHILD | WS_VISIBLE | WS_BORDER | LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_TABSTOP;
LVCOLUMN lvc { 0 };
_hWndParent = hWndParent;
_hInstance = GetModuleHandle(NULL);
_iDPI = iDPI;
_fScale = fScale;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = DefWindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = _hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = wsClass;
RegisterClassEx(&wcex);
_hWndDiscSelector = CreateWindowEx(WS_EX_TOOLWINDOW, wsClass, L"Select an Audio CD Disc", dwWinStyle,
0, 0, 0, 0, _hWndParent, NULL, _hInstance, NULL);
_hLstDrives = CreateWindowEx(0, WC_LISTVIEW, L"", dwLstStyle,
0, 0, 0, 0, _hWndDiscSelector, NULL, _hInstance, NULL);
_hCmdOK = CreateWindowEx(0, L"BUTTON", L"&OK", dwBtnStyle,
0, 0, 0, 0, _hWndDiscSelector, NULL, _hInstance, NULL);
_hCmdCancel = CreateWindowEx(0, L"BUTTON", L"&Cancel", dwBtnStyle,
0, 0, 0, 0, _hWndDiscSelector, NULL, _hInstance, NULL);
_hImlDriveTypes = ImageList_Create(_F(DEWUI_DIM_SYM_DISC_ICON), _F(DEWUI_DIM_SYM_DISC_ICON), ILC_COLOR32 | ILC_MASK, 1, 1);
_hDC = GetDC(_hWndDiscSelector);
ListView_SetExtendedListViewStyleEx(_hLstDrives,
LVS_EX_DOUBLEBUFFER | LVS_EX_FULLROWSELECT,
LVS_EX_DOUBLEBUFFER | LVS_EX_FULLROWSELECT);
ListView_SetImageList(_hLstDrives, _hImlDriveTypes, LVSIL_NORMAL);
lvc.mask = LVCF_FMT | LVCF_TEXT;
lvc.fmt = LVCFMT_LEFT;
lvc.iImage = 0;
lvc.pszText = L"Label/Path";
lvc.iSubItem = 0;
ListView_InsertColumn(_hLstDrives, 0, &lvc);
lvc.pszText = L"Drive Type";
lvc.iSubItem = 1;
ListView_InsertColumn(_hLstDrives, 1, &lvc);
lvc.pszText = L"File System";
lvc.iSubItem = 2;
ListView_InsertColumn(_hLstDrives, 2, &lvc);
ListView_SetView(_hLstDrives, LV_VIEW_TILE);
SetWindowSubclass(_hWndDiscSelector, _DSMsgHandler, (UINT_PTR)_hWndDiscSelector, (DWORD_PTR)this);
}
(DEWDISCSELECTOR::_snInstanceCount)++;
return;
}
HWND DEWDISCSELECTOR::Show(const DEWTHEME& Theme)
{
int iWidth, iHeight, iXPos, iYPos;
int iParentWidth, iParentHeight;
RECT rctParent, rctWorkArea;
GetWindowRect(_hWndParent, &rctParent);
iWidth = _F(320);
iHeight = _F(400);
iParentWidth = rctParent.right - rctParent.left;
iParentHeight = rctParent.bottom - rctParent.top;
SystemParametersInfo(SPI_GETWORKAREA, 0, &rctWorkArea, 0);
iXPos = (iParentWidth - iWidth)/2 + rctParent.left;
iYPos = (iParentHeight - iHeight)/2 + rctParent.top;
if (iXPos < rctWorkArea.left) iXPos = rctWorkArea.left;
if (iYPos < rctWorkArea.top) iYPos = rctWorkArea.top;
if ((iXPos + iWidth) > rctWorkArea.right) iXPos = rctWorkArea.right - iWidth;
if ((iYPos + iHeight) > rctWorkArea.bottom) iYPos = rctWorkArea.bottom - iHeight;
ZeroMemory(_wsSelPath, 4 * sizeof(wchar_t)); // Flush out the current entry while opening the window
this->_ApplyTheme(Theme);
this->_EnumDrives();
SetWindowPos(_hWndDiscSelector, 0, iXPos, iYPos, iWidth, iHeight, SWP_NOZORDER);
ShowWindow(_hCmdOK, SW_HIDE);
ShowWindow(_hWndDiscSelector, SW_SHOW);
UpdateWindow(_hWndDiscSelector);
SetActiveWindow(_hWndDiscSelector);
if (_hWndParent)
EnableWindow(_hWndParent, FALSE);
return _hWndDiscSelector;
}
DEWDISCSELECTOR::~DEWDISCSELECTOR()
{
this->_DestroyGDIObjects();
RemoveWindowSubclass(_hWndDiscSelector, _DSMsgHandler, (UINT_PTR)_hWndDiscSelector);
ReleaseDC(_hWndDiscSelector, _hDC);
DestroyWindow(_hLstDrives);
DestroyWindow(_hCmdCancel);
DestroyWindow(_hCmdOK);
DestroyWindow(_hWndDiscSelector);
}
| 38.789303 | 159 | 0.603685 | [
"model"
] |
238f816054322494a59bd6fc530422f1e65351e3 | 1,574 | cc | C++ | UnitTest/Cards/CardTests.cc | estela19/Poker | 3af90696488f0782992c89c89d257cb70451ed49 | [
"MIT"
] | null | null | null | UnitTest/Cards/CardTests.cc | estela19/Poker | 3af90696488f0782992c89c89d257cb70451ed49 | [
"MIT"
] | 9 | 2019-11-04T12:14:33.000Z | 2019-11-27T08:13:20.000Z | UnitTest/Cards/CardTests.cc | estela19/Poker | 3af90696488f0782992c89c89d257cb70451ed49 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include <Poker/Cards/Card.h>
using namespace Poker;
TEST(CardTests, Operator)
{
Card c1(CardShape::CLOVER, CardNumber::SEVEN),
c2(CardShape::HEART, CardNumber::SIX),
c3(CardShape::CLOVER, CardNumber::SIX),
c4(CardShape::CLOVER, CardNumber::ACE),
c5(CardShape::HEART, CardNumber::SIX);
EXPECT_TRUE(c1 > c2);
EXPECT_TRUE(c1 > c3);
EXPECT_TRUE(c2 > c3);
EXPECT_FALSE(c5 > c4);
EXPECT_FALSE(c2 > c5);
EXPECT_TRUE(c1 >= c2);
EXPECT_TRUE(c1 >= c3);
EXPECT_TRUE(c2 >= c3);
EXPECT_FALSE(c5 >= c4);
EXPECT_TRUE(c2 >= c5);
EXPECT_FALSE(c1 < c2);
EXPECT_FALSE(c1 < c3);
EXPECT_FALSE(c2 < c3);
EXPECT_TRUE(c3 < c5);
EXPECT_TRUE(c5 < c4);
EXPECT_FALSE(c2 < c5);
EXPECT_FALSE(c1 <= c2);
EXPECT_FALSE(c1 <= c3);
EXPECT_FALSE(c2 <= c3);
EXPECT_TRUE(c5 <= c4);
EXPECT_TRUE(c2 <= c5);
EXPECT_FALSE(c1 == c2);
EXPECT_FALSE(c1 == c3);
EXPECT_FALSE(c2 == c3);
EXPECT_FALSE(c5 == c4);
EXPECT_TRUE(c2 == c5);
EXPECT_TRUE(c1 != c2);
EXPECT_TRUE(c1 != c3);
EXPECT_TRUE(c2 != c3);
EXPECT_TRUE(c5 != c4);
EXPECT_FALSE(c2 != c5);
}
TEST(CardTests, Constructor) {
Card c1(CardShape::CLOVER, CardNumber::SEVEN),
c2(CardShape::HEART, CardNumber::SIX);
EXPECT_EQ(c1.Shape(), CardShape::CLOVER);
EXPECT_EQ(c2.Shape(), CardShape::HEART);
EXPECT_EQ(c1.Number(), CardNumber::SEVEN);
EXPECT_EQ(c2.Number(), CardNumber::SIX);
} | 25.803279 | 51 | 0.58831 | [
"shape"
] |
23a2e07341cde9ceac20c53ead5933db46006bbb | 50,166 | hh | C++ | benchmark/DB_uindex.hh | dimstamat/sto-hybrid-oltp-olap | a13e1eaef419c21326832c6f7dbebbdc33204b60 | [
"MIT"
] | null | null | null | benchmark/DB_uindex.hh | dimstamat/sto-hybrid-oltp-olap | a13e1eaef419c21326832c6f7dbebbdc33204b60 | [
"MIT"
] | null | null | null | benchmark/DB_uindex.hh | dimstamat/sto-hybrid-oltp-olap | a13e1eaef419c21326832c6f7dbebbdc33204b60 | [
"MIT"
] | null | null | null | #pragma once
class logset_base;
template <int N_TBLS>
class logset_tbl;
extern logset_base* logs;
#ifndef LOG_NTABLES // should be defined in TPCC_bench.hh
#define LOG_NTABLES 0
#endif
namespace bench {
// unordered index implemented as hashtable
template <typename K, typename V, typename DBParams, short LOG=0>
class unordered_index : public index_common<K, V, DBParams>, public TObject {
// Dimos - emable logging
// template argument LOG
// 0 : no logging
// 1 : default logging - one log per thread
// 2 : one log per thread per table
// 3 : one std::unordered_map per thread per table
public:
// Premable
using C = index_common<K, V, DBParams>;
using typename C::key_type;
using typename C::value_type;
using typename C::sel_return_type;
using typename C::ins_return_type;
using typename C::del_return_type;
using typename C::version_type;
using typename C::value_container_type;
using typename C::comm_type;
using C::invalid_bit;
using C::insert_bit;
using C::delete_bit;
using C::row_update_bit;
using C::row_cell_bit;
using C::has_insert;
using C::has_delete;
using C::has_row_update;
using C::has_row_cell;
using C::sel_abort;
using C::ins_abort;
using C::del_abort;
using C::index_read_my_write;
static constexpr TransItem::flags_type log_add_bit = TransItem::user0_bit << 4u;
typedef typename get_occ_version<DBParams>::type bucket_version_type;
typedef std::hash<K> Hash;
typedef std::equal_to<K> Pred;
// our hashtable is an array of linked lists.
// an internal_elem is the node type for these linked lists
struct internal_elem {
internal_elem *next;
key_type key;
value_container_type row_container;
bool deleted;
internal_elem(const key_type& k, const value_type& v, bool valid)
: next(nullptr), key(k),
row_container((valid ? Sto::initialized_tid() : (Sto::initialized_tid() | invalid_bit)), !valid, v),
deleted(false) {}
version_type& version() {
return row_container.row_version();
}
bool valid() {
return !(version().value() & invalid_bit);
}
};
void thread_init() {}
void thread_init(int runner_num) {
// set logger!
if(LOG == 2){
if(!logger_ && logs)
set_logger_(& (reinterpret_cast<logset_tbl<LOG_NTABLES>*>(logs))->log(runner_num)); // get the corresponding log for that thread!
}
}
loginfo* logger() const {
return (loginfo*)logger_;
}
void* logger_tbl() const{
return logger_;
}
~unordered_index() override {}
private:
void set_logger_(void* logger) {
assert(!logger_ && logger);
logger_ = logger;
}
struct bucket_entry {
internal_elem *head;
// this is the bucket version number, which is incremented on insert
// we use it to make sure that an unsuccessful key lookup will still be
// unsuccessful at commit time (because this will always be true if no
// new inserts have occurred in this bucket)
bucket_version_type version;
bucket_entry() : head(nullptr), version(0) {}
};
typedef std::vector<bucket_entry> MapType;
// this is the hashtable itself, an array of bucket_entry's
MapType map_;
Hash hasher_;
Pred pred_;
uint64_t key_gen_;
// the index of this table in the log buffer when we choose one log per thread per table
int tbl_index_=0;
static __thread void* logger_; // one logger per thread! This will point to the corresponding log for that thread.
// used to mark whether a key is a bucket (for bucket version checks)
// or a pointer (which will always have the lower 3 bits as 0)
static constexpr uintptr_t bucket_bit = C::item_key_tag;
public:
// split version helper stuff
using index_t = unordered_index<K, V, DBParams, LOG>;
using column_access_t = typename split_version_helpers<index_t>::column_access_t;
using item_key_t = typename split_version_helpers<index_t>::item_key_t;
template <typename T>
static constexpr auto column_to_cell_accesses
= split_version_helpers<index_t>::template column_to_cell_accesses<T>;
template <typename T>
static constexpr auto extract_item_list
= split_version_helpers<index_t>::template extract_item_list<T>;
// Main constructor
unordered_index(size_t size, Hash h = Hash(), Pred p = Pred()) :
map_(), hasher_(h), pred_(p), key_gen_(0), tbl_index_(-1) {
map_.resize(size);
}
// Dimos - we need an empty constructor for the log! -> see log.hh
unordered_index(Hash h = Hash(), Pred p = Pred()) :
map_(), hasher_(h), pred_(p), key_gen_(0), tbl_index_(-1) {
}
// tbl_index: the index of this table in the log buffer
unordered_index(size_t size, int tbl_index, Hash h = Hash(), Pred p = Pred()) :
map_(), hasher_(h), pred_(p), key_gen_(0), tbl_index_(tbl_index) {
map_.resize(size);
assert(tbl_index>=0); //&& tbl_index <= logs_tbl->log(runner_num). getNumtbl ?? )
}
inline size_t hash(const key_type& k) const {
return hasher_(k);
}
inline size_t nbuckets() const {
return map_.size();
}
inline size_t find_bucket_idx(const key_type& k) const {
return hash(k) % nbuckets();
}
uint64_t gen_key() {
return fetch_and_add(&key_gen_, 1);
}
// Dimos - support traverse for using UIndex for the log!
void traverse_all(std::function<void(const key_type& , value_type* )> callback){
for (auto& buck : map_){
internal_elem *curr = buck.head;
while (curr){ // traverse all elements within bucket
callback(curr->key, &curr->row_container.row);
curr = curr->next;
}
}
}
sel_return_type
select_row(const key_type& k, RowAccess access) {
bucket_entry& buck = map_[find_bucket_idx(k)];
bucket_version_type buck_vers = buck.version;
fence();
internal_elem *e = find_in_bucket(buck, k);
if (e != nullptr) {
return select_row(reinterpret_cast<uintptr_t>(e), access);
} else {
if (!Sto::item(this, make_bucket_key(buck)).observe(buck_vers)) {
return sel_abort;
}
return { true, false, 0, nullptr };
}
}
sel_return_type
select_row(const key_type& k, std::initializer_list<column_access_t> accesses) {
bucket_entry& buck = map_[find_bucket_idx(k)];
bucket_version_type buck_vers = buck.version;
fence();
internal_elem *e = find_in_bucket(buck, k);
if (e != nullptr) {
return select_row(reinterpret_cast<uintptr_t>(e), accesses);
} else {
if (!Sto::item(this, make_bucket_key(buck)).observe(buck_vers)) {
return sel_abort;
}
return { true, false, 0, nullptr };
}
}
sel_return_type
select_row(uintptr_t rid, RowAccess access) {
auto e = reinterpret_cast<internal_elem*>(rid);
bool ok = true;
TransProxy row_item = Sto::item(this, item_key_t::row_item_key(e));
if (is_phantom(e, row_item))
return sel_abort;
if (index_read_my_write) {
if (has_delete(row_item))
return { true, false, 0, nullptr };
if (has_row_update(row_item)) {
value_type* vptr = nullptr;
if (has_insert(row_item))
vptr = &(e->row_container.row);
else
vptr = row_item.template raw_write_value<value_type*>();
assert(vptr);
return { true, true, rid, vptr };
}
}
switch (access) {
case RowAccess::UpdateValue:
ok = version_adapter::select_for_update(row_item, e->version());
row_item.add_flags(row_update_bit);
break;
case RowAccess::ObserveExists:
case RowAccess::ObserveValue:
ok = row_item.observe(e->version());
break;
default:
break;
}
if (!ok)
return sel_abort;
return { true, true, rid, &(e->row_container.row) };
}
sel_return_type
select_row(uintptr_t rid, std::initializer_list<column_access_t> accesses) {
auto e = reinterpret_cast<internal_elem*>(rid);
TransProxy row_item = Sto::item(this, item_key_t::row_item_key(e));
auto cell_accesses = column_to_cell_accesses<value_container_type>(accesses);
std::array<TransItem*, value_container_type::num_versions> cell_items {};
bool any_has_write;
bool ok;
std::tie(any_has_write, cell_items) = extract_item_list<value_container_type>(cell_accesses, this, e);
if (is_phantom(e, row_item))
return sel_abort;
if (index_read_my_write) {
if (has_delete(row_item)) {
return { true, false, 0, nullptr };
}
if (any_has_write || has_row_update(row_item)) {
value_type *vptr;
if (has_insert(row_item))
vptr = &(e->row_container.row);
else
vptr = row_item.template raw_write_value<value_type *>();
return { true, true, rid, vptr };
}
}
ok = access_all(cell_accesses, cell_items, e->row_container);
if (!ok)
return sel_abort;
return sel_return_type(true, true, rid, &(e->row_container.row));
}
void update_row(uintptr_t rid, value_type *new_row) {
auto e = reinterpret_cast<internal_elem*>(rid);
auto row_item = Sto::item(this, item_key_t::row_item_key(e));
row_item.acquire_write(e->version(), new_row);
if(LOG > 0)
row_item.add_flags(log_add_bit);
}
void update_row(uintptr_t rid, const comm_type &comm) {
assert(&comm);
auto row_item = Sto::item(this, item_key_t::row_item_key(reinterpret_cast<internal_elem *>(rid)));
row_item.add_commute(comm);
}
ins_return_type
insert_row(const key_type& k, value_type *vptr, bool overwrite = false) {
bucket_entry& buck = map_[find_bucket_idx(k)];
buck.version.lock_exclusive();
internal_elem* e = find_in_bucket(buck, k);
if (e) {
buck.version.unlock_exclusive();
auto row_item = Sto::item(this, item_key_t::row_item_key(e));
if (is_phantom(e, row_item))
return ins_abort;
if (index_read_my_write) {
if (has_delete(row_item)) {
row_item.clear_flags(delete_bit).clear_write().template add_write<value_type *>(vptr);
return { true, false };
}
}
if (overwrite) {
if (!version_adapter::select_for_overwrite(row_item, e->version(), vptr))
return ins_abort;
if (index_read_my_write) {
if (has_insert(row_item)) {
copy_row(e, vptr);
}
}
} else {
if (!row_item.observe(e->version()))
return ins_abort;
}
#if ADD_TO_LOG > 0
if(LOG > 0 && overwrite){
row_item.add_flags(log_add_bit);
}
#endif
return { true, true };
} else {
// insert the new row to the table and take note of bucket version changes
auto buck_vers_0 = bucket_version_type(buck.version.unlocked_value());
insert_in_bucket(buck, k, vptr, false);
internal_elem *new_head = buck.head;
auto buck_vers_1 = bucket_version_type(buck.version.unlocked_value());
buck.version.unlock_exclusive();
// update bucket version in the read set (if any) since it's changed by ourselves
auto bucket_item = Sto::item(this, make_bucket_key(buck));
if (bucket_item.has_read())
bucket_item.update_read(buck_vers_0, buck_vers_1);
auto item = Sto::item(this, item_key_t::row_item_key(new_head));
// XXX adding write is probably unnecessary, am I right?
item.template add_write<value_type*>(vptr);
item.add_flags(insert_bit);
#if ADD_TO_LOG > 0
if(LOG > 0){
bucket_item.add_flags(log_add_bit);
}
#endif
return { true, false };
}
}
// returns (success : bool, found : bool)
// for rows that are not inserted by this transaction, the actual delete doesn't take place
// until commit time
del_return_type
delete_row(const key_type& k) {
bucket_entry& buck = map_[find_bucket_idx(k)];
bucket_version_type buck_vers = buck.version;
fence();
internal_elem* e = find_in_bucket(buck, k);
if (e) {
auto item = Sto::item(this, item_key_t::row_item_key(e));
bool valid = e->valid();
if (is_phantom(e, item))
return del_abort;
if (index_read_my_write) {
if (!valid && has_insert(item)) {
// deleting something we inserted
_remove(e);
item.remove_read().remove_write().clear_flags(insert_bit | delete_bit);
Sto::item(this, make_bucket_key(buck)).observe(buck_vers);
return { true, true };
}
assert(valid);
if (has_delete(item))
return { true, false };
}
// select_for_update() will automatically add an observation for OCC version types
// so that we can catch change in "deleted" status of a table row at commit time
if (!version_adapter::select_for_update(item, e->version()))
return del_abort;
fence();
// it vital that we check the "deleted" status after registering an observation
if (e->deleted)
return del_abort;
item.add_flags(delete_bit);
return { true, true };
} else {
// not found -- add observation of bucket version
bool ok = Sto::item(this, make_bucket_key(buck)).observe(buck_vers);
if (!ok)
return del_abort;
return { true, false };
}
}
// non-transactional methods
value_type* nontrans_get(const key_type& k) {
bucket_entry& buck = map_[find_bucket_idx(k)];
internal_elem* e = find_in_bucket(buck, k);
if (e == nullptr)
return nullptr;
return &(e->row_container.row);
}
void nontrans_put(const key_type& k, const value_type& v) {
bucket_entry& buck = map_[find_bucket_idx(k)];
buck.version.lock_exclusive();
internal_elem *e = find_in_bucket(buck, k);
if (e == nullptr) {
internal_elem *new_head = new internal_elem(k, v, true);
new_head->next = buck.head;
buck.head = new_head;
} else {
copy_row(e, &v);
}
buck.version.unlock_exclusive();
}
// Dimos - required when using for log!
void nontrans_put_no_lock(const key_type& k, const value_type& v){
bucket_entry& buck = map_[find_bucket_idx(k)];
internal_elem *e = find_in_bucket(buck, k);
if (e == nullptr) {
internal_elem *new_head = new internal_elem(k, v, true);
new_head->next = buck.head;
buck.head = new_head;
} else {
copy_row(e, &v);
}
}
// TObject interface methods
bool lock(TransItem& item, Transaction& txn) override {
assert(!is_bucket(item));
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
if (key.is_row_item()) {
return txn.try_lock(item, e->version());
} else {
return txn.try_lock(item, e->row_container.version_at(key.cell_num()));
}
}
bool check(TransItem& item, Transaction& txn) override {
if (is_bucket(item)) {
bucket_entry &buck = *bucket_address(item);
return buck.version.cp_check_version(txn, item);
} else {
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
if (key.is_row_item())
return e->version().cp_check_version(txn, item);
else
return e->row_container.version_at(key.cell_num()).cp_check_version(txn, item);
}
}
inline void log_add(TransItem& item, internal_elem* e){
logcommand cmd;
if(has_insert(item)){
cmd = logcmd_put;
} else if(has_delete(item)){
cmd = logcmd_remove;
} else {
cmd = logcmd_replace;
}
#if LOG_DRAIN_REQUEST
kvepoch_t global_epoch_cp = global_log_epoch; // get a copy of the global log epoch. If it changes later on, we will see it during the next check
#endif
//TODO: Only for the first TItem in the write set:
// - check whether request_log_drain is true and if it is, set local_epoch = global_epoch. This will ensure that we decide in which epoch this transaction belongs to at commit time, and before we start logging its TItems.
// assign timestamp
loginfo::query_times qtimes;
//qtimes.ts = Sto::commit_tid(); // this won't work because there are no commit_tids set in Non-opaque/OCC so this will use global counter!
//qtimes.prev_ts = ( !has_insert(item) && !(has_delete(item)) ? TThread::txn->prev_commit_tid() : 0 );
qtimes.ts = e->version().value();
qtimes.prev_ts = 0;
void* logger = logger_tbl();
// check if there is a pending request for log drain and advance local epoch if there is!!
#if LOGGING == 2 && LOG_DRAIN_REQUEST
bool signal_logdrainer = false;
// We need to know whether this is the first TItem from the write set to be added to the log
// This is in case we have concurrent log drainers so that to advance local epoch right before committing the current txn!
// A log drain is requested. Simply advance local log epoch (will happen later on) and signal the condition variable of waiting log drainers
if(((reinterpret_cast<loginfo_tbl<LOG_NTABLES>*>(logger))->get_local_epoch() < global_epoch_cp) && item.has_flag(TransItem::first_titem_bit) ){ // change epoch now!
signal_logdrainer = true; // signal the cond variable that the log drainer is waiting on. It should be signaled right after we record a log record with the new log epoch (which is not visible to the log drainer)
qtimes.epoch = global_epoch_cp;
}
else { // do not change epoch yet! Do it in the next transaction!
qtimes.epoch = (reinterpret_cast<loginfo_tbl<LOG_NTABLES>*>(logger))->get_local_epoch();
}
#else
qtimes.epoch = global_log_epoch;
#endif
if(logger){
// Must use a local log_epoch so that to increase only when a log drain is requested AND the current transaction is committed and fully applied in the log. We will do local_epoch = global_epoch only when transaction committed successfully (in TPCC_bench.hh)
value_type* valp;
if(has_insert(item)){
#if LOGREC_OVERWRITE
if(LOG == 2)
valp = & ((reinterpret_cast<internal_elem_log*>(e))->row_container.row);
else
valp = &e->row_container.row;
#else
valp = &e->row_container.row;
#endif
}
else{
valp = item.template raw_write_value<value_type*>();
}
if(LOG == 1)
reinterpret_cast<loginfo*>(logger)->record(cmd, qtimes, Str(e->key), Str(*valp), tbl_index_);
else if(LOG == 2){
auto logger_tbl = reinterpret_cast<loginfo_tbl<LOG_NTABLES>*>(logger);
// experiment with not converting to string but storing the actual key:
// Not converting to string is a tiny bit better in high contention and a bit worse in low contention.
// Even Str() converts the struct to Str but keeps the entire size of the struct and not the actual size of the constructed string!
// In both cases it writes more bytes because the size of key in orders table is 3 64-bit uints and thus occupies 24 bytes even for small numbered kes.
// Experiment with converting to Str (call to_str()), and then we will only write as many digits as the key. A small key would only be 3 bytes (1 digit per key part: warehouse, district, o_id).
//auto callback = [] (logrec_kv* lr) -> void {
//};
#if LOG_RECS == 1 || LOG_RECS == 3
#if LOGREC_OVERWRITE
int log_indx = logger_tbl->get_log_index();
//std::cout<<"indx: "<< log_indx<<std::endl;
internal_elem_log* el = reinterpret_cast<internal_elem_log*>(e);
//if(cmd == logcmd_replace && el->log_pos[log_indx] >= 0){ // specify the location of the log record! This will overwrite existing log record for this key
// TODO: either >=0, or >0, depending on how we initialize the log_pos!
if(cmd == logcmd_replace && el->get_creation_epoch(log_indx) == qtimes.epoch.value()){ // specify the location of the log record! This will overwrite existing log record for this key, if they are for the same epoch
// make sure to check whether e->log_pos[log_indx] exists. It could be that the log command is replace (update_row), but it does not exist in the log! In case we apply the log entries after DB prepopulation and clear the log!
//logger_tbl->record(cmd, qtimes, Str(el->key), Str(*valp), tbl_index_, el->log_pos[log_indx] );
// TODO: for now do not overwrite, just to test the overhead of storing the log pos and epoch!
el->update_log_pos(log_indx, logger_tbl->record(cmd, qtimes, Str(el->key), Str(*valp), tbl_index_, el->get_log_pos(log_indx)));
//logger_tbl->record(cmd, qtimes, Str(el->key), Str(*valp), tbl_index_);
}
else if (el->get_creation_epoch(log_indx) == 0) // there is no log record location for this key (creation epoch =0), store it!
el->set_log_pos(log_indx, logger_tbl->record(cmd, qtimes, Str(el->key), Str(*valp), tbl_index_), qtimes.epoch.value());
else // different epoch, do not update!
logger_tbl->record(cmd, qtimes, Str(el->key), Str(*valp), tbl_index_);
#else
logger_tbl->record(cmd, qtimes, Str(e->key), Str(*valp), tbl_index_);
#endif
#if LOGGING == 2 && LOG_DRAIN_REQUEST
if(signal_logdrainer){
// add new epoch log record to all tables!
for (int i=0; i<LOG_NTABLES; i++){
if(logger_tbl->current_size(i) > 0 && i != tbl_index_)
logger_tbl->record_new_epoch(i, qtimes.epoch);
}
//if(logger_tbl->get_log_index() == 0) // do not signal the first log drainer right away otherwise it will miss the signal!
usleep(10);
//std::cout<<"Signaling log drainer!\n";
logger_tbl->signal_to_logdrain(); // signal the cond variable that the log drainer is waiting on. It should be signaled right after we record a log record with the new log epoch (which is not visible to the log drainer)
signal_logdrainer = false;
}
#endif
#elif LOG_RECS == 2
const char* k = e->key.to_str();
const char* v = valp->to_str();
reinterpret_cast<loginfo_tbl<LOG_NTABLES>*>(logger)->record(cmd, qtimes, k, strlen(k), v, strlen(v), tbl_index_);
delete[] k;
delete[] v;
#endif
//reinterpret_cast<loginfo_tbl<LOG_NTABLES>*>(logger)->record(cmd, qtimes, &e->key, sizeof(e->key), valp, sizeof(value_type), tbl_index_);
}
else if(LOG == 3)
reinterpret_cast<loginfo_map<LOG_NTABLES>*>(logger)->record(cmd, qtimes, Str(e->key), Str(*valp), tbl_index_);
}
}
void install(TransItem& item, Transaction& txn) override {
assert(!is_bucket(item));
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
if (key.is_row_item()) {
if (has_delete(item)) {
assert(e->valid() && !e->deleted);
e->deleted = true;
fence();
txn.set_version(e->version());
return;
}
if (!has_insert(item)) {
// update
if (item.has_commute()) {
comm_type &comm = item.write_value<comm_type>();
if (has_row_update(item)) {
copy_row(e, comm);
} else if (has_row_cell(item)) {
e->row_container.install_cell(comm);
}
} else {
auto vptr = item.write_value<value_type*>();
if (has_row_update(item)) {
copy_row(e, vptr);
} else if (has_row_cell(item)) {
e->row_container.install_cell(0, vptr);
}
}
}
txn.set_version_unlock(e->version(), item);
} else {
auto row_item = Sto::item(this, item_key_t::row_item_key(e));
if (!has_row_update(row_item)) {
if (row_item.has_commute()) {
comm_type &comm = row_item.template write_value<comm_type>();
assert(&comm);
e->row_container.install_cell(comm);
} else {
auto vptr = row_item.template raw_write_value<value_type*>();
e->row_container.install_cell(key.cell_num(), vptr);
}
}
txn.set_version_unlock(e->row_container.version_at(key.cell_num()), item);
}
// add to log here, so that we already have the updated version.
#if ADD_TO_LOG == 2
if(LOG > 0 && has_log_add(item))
log_add(item, e);
#endif
}
void unlock(TransItem& item) override {
assert(!is_bucket(item));
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
if (key.is_row_item())
e->version().cp_unlock(item);
else
e->row_container.version_at(key.cell_num()).cp_unlock(item);
}
void cleanup(TransItem& item, bool committed) override {
#if ADD_TO_LOG == 1
if(LOG > 0 && committed && has_log_add(item)){
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
log_add(item, e);
}
#endif
if (committed ? has_delete(item) : has_insert(item)) {
assert(!is_bucket(item));
auto key = item.key<item_key_t>();
internal_elem* e = key.internal_elem_ptr();
assert(!e->valid() || e->deleted);
_remove(e);
item.clear_needs_unlock();
}
}
private:
static bool
access_all(std::array<access_t, value_container_type::num_versions>& cell_accesses, std::array<TransItem*, value_container_type::num_versions>& cell_items, value_container_type& row_container) {
for (size_t idx = 0; idx < cell_accesses.size(); ++idx) {
auto& access = cell_accesses[idx];
auto proxy = TransProxy(*Sto::transaction(), *cell_items[idx]);
if (static_cast<uint8_t>(access) & static_cast<uint8_t>(access_t::read)) {
if (!proxy.observe(row_container.version_at(idx)))
return false;
}
if (static_cast<uint8_t>(access) & static_cast<uint8_t>(access_t::write)) {
if (!proxy.acquire_write(row_container.version_at(idx)))
return false;
if (proxy.item().key<item_key_t>().is_row_item()) {
proxy.item().add_flags(row_cell_bit);
}
}
}
return true;
}
// remove a k-v node during transactions (with locks)
void _remove(internal_elem *el) {
bucket_entry& buck = map_[find_bucket_idx(el->key)];
buck.version.lock_exclusive();
internal_elem *prev = nullptr;
internal_elem *curr = buck.head;
while (curr != nullptr && curr != el) {
prev = curr;
curr = curr->next;
}
assert(curr);
if (prev != nullptr)
prev->next = curr->next;
else
buck.head = curr->next;
buck.version.unlock_exclusive();
Transaction::rcu_delete(curr);
}
// non-transactional remove by key
bool remove(const key_type& k) {
bucket_entry& buck = map_[find_bucket_idx(k)];
buck.version.lock_exclusive();
internal_elem *prev = nullptr;
internal_elem *curr = buck.head;
while (curr != nullptr && !pred_(curr->key, k)) {
prev = curr;
curr = curr->next;
}
if (curr == nullptr) {
buck.version.unlock_exclusive();
return false;
}
if (prev != nullptr)
prev->next = curr->next;
else
buck.head = curr->next;
buck.version.unlock_exclusive();
delete curr;
return true;
}
// insert a k-v node to a bucket
void insert_in_bucket(bucket_entry& buck, const key_type& k, const value_type *v, bool valid) {
assert(buck.version.is_locked());
internal_elem *new_head = new internal_elem(k, v ? *v : value_type(), valid);
internal_elem *curr_head = buck.head;
new_head->next = curr_head;
buck.head = new_head;
buck.version.inc_nonopaque();
}
// find a key's k-v node (internal_elem) within a bucket
internal_elem *find_in_bucket(const bucket_entry& buck, const key_type& k) {
internal_elem *curr = buck.head;
while (curr && !pred_(curr->key, k))
curr = curr->next;
return curr;
}
static bool is_phantom(internal_elem *e, const TransItem& item) {
return (!e->valid() && !has_insert(item));
}
static bool has_log_add(const TransItem& item){
return (item.flags() & log_add_bit) != 0;
}
// TransItem keys
static bool is_bucket(const TransItem& item) {
return item.key<uintptr_t>() & bucket_bit;
}
static uintptr_t make_bucket_key(const bucket_entry& bucket) {
return (reinterpret_cast<uintptr_t>(&bucket) | bucket_bit);
}
static bucket_entry *bucket_address(const TransItem& item) {
uintptr_t bucket_key = item.key<uintptr_t>();
return reinterpret_cast<bucket_entry*>(bucket_key & ~bucket_bit);
}
static void copy_row(internal_elem *e, comm_type &comm) {
e->row_container.row = comm.operate(e->row_container.row);
}
static void copy_row(internal_elem *table_row, const value_type *value) {
if (value == nullptr)
return;
table_row->row_container.row = *value;
}
};
template <typename K, typename V, typename DBParams, short LOG>
__thread void* unordered_index<K, V, DBParams, LOG>::logger_;
// MVCC variant
template <typename K, typename V, typename DBParams>
class mvcc_unordered_index : public index_common<K, V, DBParams>, public TObject {
public:
// Premable
using C = index_common<K, V, DBParams>;
using typename C::key_type;
using typename C::value_type;
using typename C::sel_return_type;
using typename C::ins_return_type;
using typename C::del_return_type;
using typename C::version_type;
using typename C::value_container_type;
using typename C::comm_type;
using C::invalid_bit;
using C::insert_bit;
using C::delete_bit;
using C::row_update_bit;
using C::row_cell_bit;
using C::has_insert;
using C::has_delete;
using C::has_row_update;
using C::has_row_cell;
using C::sel_abort;
using C::ins_abort;
using C::del_abort;
using C::index_read_my_write;
typedef MvObject<value_type> object_type;
typedef typename object_type::history_type history_type;
typedef typename get_occ_version<DBParams>::type bucket_version_type;
typedef std::hash<K> Hash;
typedef std::equal_to<K> Pred;
// our hashtable is an array of linked lists.
// an internal_elem is the node type for these linked lists
struct internal_elem {
internal_elem *next;
key_type key;
object_type row;
internal_elem(const key_type& k)
: next(nullptr), key(k), row() {}
};
static void thread_init() {}
static void thread_init(int runner_num) {
(void)runner_num;
}
~mvcc_unordered_index() override {}
private:
struct bucket_entry {
internal_elem *head;
// this is the bucket version number, which is incremented on insert
// we use it to make sure that an unsuccessful key lookup will still be
// unsuccessful at commit time (because this will always be true if no
// new inserts have occurred in this bucket)
bucket_version_type version;
bucket_entry() : head(nullptr), version(0) {}
};
typedef std::vector<bucket_entry> MapType;
// this is the hashtable itself, an array of bucket_entry's
MapType map_;
Hash hasher_;
Pred pred_;
uint64_t key_gen_;
// the index of this table in the log buffer
int tbl_index_=0;
// used to mark whether a key is a bucket (for bucket version checks)
// or a pointer (which will always have the lower 3 bits as 0)
static constexpr uintptr_t bucket_bit = C::item_key_tag;
public:
// split version helper stuff
using index_t = mvcc_unordered_index<K, V, DBParams>;
using column_access_t = typename split_version_helpers<index_t>::column_access_t;
using item_key_t = typename split_version_helpers<index_t>::item_key_t;
// Main constructor
mvcc_unordered_index(size_t size, Hash h = Hash(), Pred p = Pred()) :
map_(), hasher_(h), pred_(p), key_gen_(0), tbl_index_(-1) {
map_.resize(size);
}
// tbl_index: the index of this table in the log buffer
mvcc_unordered_index(size_t size, int tbl_index, Hash h = Hash(), Pred p = Pred()) :
map_(), hasher_(h), pred_(p), key_gen_(0), tbl_index_(tbl_index) {
map_.resize(size);
assert(tbl_index>=0); //&& tbl_index <= logs_tbl->log(runner_num). getNumtbl ?? )
}
inline size_t hash(const key_type& k) const {
return hasher_(k);
}
inline size_t nbuckets() const {
return map_.size();
}
inline size_t find_bucket_idx(const key_type& k) const {
return hash(k) % nbuckets();
}
uint64_t gen_key() {
return fetch_and_add(&key_gen_, 1);
}
sel_return_type
select_row(const key_type& k, RowAccess access) {
bucket_entry& buck = map_[find_bucket_idx(k)];
bucket_version_type buck_vers = buck.version;
fence();
internal_elem *e = find_in_bucket(buck, k);
if (e != nullptr) {
return select_row(reinterpret_cast<uintptr_t>(e), access);
} else {
if (!Sto::item(this, make_bucket_key(buck)).observe(buck_vers)) {
return sel_abort;
}
return { true, false, 0, nullptr };
}
}
sel_return_type
select_row(const key_type& k, std::initializer_list<column_access_t> accesses) {
bucket_entry& buck = map_[find_bucket_idx(k)];
bucket_version_type buck_vers = buck.version;
fence();
internal_elem *e = find_in_bucket(buck, k);
if (e != nullptr) {
return select_row(reinterpret_cast<uintptr_t>(e), accesses);
} else {
if (!Sto::item(this, make_bucket_key(buck)).observe(buck_vers)) {
return sel_abort;
}
return { true, false, 0, nullptr };
}
}
sel_return_type
select_row(uintptr_t rid, RowAccess access) {
auto e = reinterpret_cast<internal_elem*>(rid);
TransProxy row_item = Sto::item(this, item_key_t::row_item_key(e));
history_type* h = e->row.find(txn_read_tid());
if (h->status_is(UNUSED))
return { true, false, 0, nullptr };
if (is_phantom(h, row_item))
return { true, false, 0, nullptr };
if (index_read_my_write) {
if (has_delete(row_item))
return { true, false, 0, nullptr };
if (has_row_update(row_item)) {
value_type* vptr = nullptr;
if (has_insert(row_item)) {
#if SAFE_FLATTEN
vptr = h->vp_safe_flatten();
if (vptr == nullptr)
return { false, false, 0, nullptr };
#else
vptr = h->vp();
#endif
} else {
vptr = row_item.template raw_write_value<value_type*>();
}
assert(vptr);
return { true, true, rid, vptr };
}
}
if (access != RowAccess::None) {
MvAccess::template read<value_type>(row_item, h);
#if SAFE_FLATTEN
auto vp = h->vp_safe_flatten();
if (vp == nullptr)
return { false, false, 0, nullptr };
#else
auto vp = h->vp();
assert(vp);
#endif
return { true, true, rid, vp };
} else {
return { true, true, rid, nullptr };
}
}
sel_return_type
select_row(uintptr_t, std::initializer_list<column_access_t>) {
always_assert(false, "Not implemented in MVCC, use split table instead.");
return { false, false, 0, nullptr };
}
void update_row(uintptr_t rid, value_type *new_row) {
auto e = reinterpret_cast<internal_elem*>(rid);
auto row_item = Sto::item(this, item_key_t::row_item_key(e));
row_item.add_write(new_row);
}
void update_row(uintptr_t rid, const comm_type &comm) {
assert(&comm);
auto row_item = Sto::item(this, item_key_t::row_item_key(reinterpret_cast<internal_elem *>(rid)));
row_item.add_commute(comm);
}
ins_return_type
insert_row(const key_type& k, value_type *vptr, bool overwrite = false) {
bucket_entry& buck = map_[find_bucket_idx(k)];
buck.version.lock_exclusive();
internal_elem* e = find_in_bucket(buck, k);
if (e) {
buck.version.unlock_exclusive();
auto row_item = Sto::item(this, item_key_t::row_item_key(e));
auto h = e->row.find(txn_read_tid());
if (is_phantom(h, row_item))
return ins_abort;
if (index_read_my_write) {
if (has_delete(row_item)) {
row_item.clear_flags(delete_bit).clear_write().template add_write<value_type*>(vptr);
return { true, false };
}
}
if (overwrite) {
row_item.template add_write<value_type*>(vptr);
} else {
MvAccess::template read<value_type>(row_item, h);
}
return { true, true };
} else {
// insert the new row to the table and take note of bucket version changes
auto buck_vers_0 = bucket_version_type(buck.version.unlocked_value());
insert_in_bucket(buck, k);
internal_elem *new_head = buck.head;
auto buck_vers_1 = bucket_version_type(buck.version.unlocked_value());
buck.version.unlock_exclusive();
// update bucket version in the read set (if any) since it's changed by ourselves
auto bucket_item = Sto::item(this, make_bucket_key(buck));
if (bucket_item.has_read())
bucket_item.update_read(buck_vers_0, buck_vers_1);
auto item = Sto::item(this, item_key_t::row_item_key(new_head));
// XXX adding write is probably unnecessary, am I right?
item.template add_write<value_type*>(vptr);
item.add_flags(insert_bit);
return { true, false };
}
}
// returns (success : bool, found : bool)
// for rows that are not inserted by this transaction, the actual delete doesn't take place
// until commit time
del_return_type
delete_row(const key_type& k) {
bucket_entry& buck = map_[find_bucket_idx(k)];
bucket_version_type buck_vers = buck.version;
fence();
internal_elem* e = find_in_bucket(buck, k);
if (e) {
auto row_item = Sto::item(this, item_key_t::row_item_key(e));
auto h = e->row.find(txn_read_tid());
if (is_phantom(h, row_item))
return { true, false };
if (index_read_my_write) {
if (has_delete(row_item))
return { true, false };
if (h->status_is(DELETED) && has_insert(row_item)) {
row_item.add_flags(delete_bit);
return { true, true };
}
}
MvAccess::template read<value_type>(row_item, h);
if (h->status_is(DELETED))
return { true, false };
row_item.add_write();
row_item.add_flags(delete_bit);
return { true, true };
} else {
// not found -- add observation of bucket version
bool ok = Sto::item(this, make_bucket_key(buck)).observe(buck_vers);
if (!ok)
return del_abort;
return { true, false };
}
}
// non-transactional methods
value_type* nontrans_get(const key_type& k) {
bucket_entry& buck = map_[find_bucket_idx(k)];
internal_elem* e = find_in_bucket(buck, k);
if (e == nullptr)
return nullptr;
return &(e->row.nontrans_access());
}
void nontrans_put(const key_type& k, const value_type& v) {
bucket_entry& buck = map_[find_bucket_idx(k)];
buck.version.lock_exclusive();
internal_elem *e = find_in_bucket(buck, k);
if (e == nullptr) {
internal_elem *new_head = new internal_elem(k);
new_head->row.nontrans_access() = v;
new_head->next = buck.head;
buck.head = new_head;
} else {
e->row.nontrans_access() = v;
}
buck.version.unlock_exclusive();
}
// TObject interface methods
bool lock(TransItem& item, Transaction& txn) override {
assert(!is_bucket(item));
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
history_type* hprev = nullptr;
if (item.has_read()) {
hprev = item.read_value<history_type*>();
if (Sto::commit_tid() < hprev->rtid()) {
TransProxy(txn, item).add_write(nullptr);
return false;
}
}
history_type* h;
if (item.has_commute()) {
auto wval = item.template write_value<comm_type>();
h = e->row.new_history(
Sto::commit_tid(), &e->row, std::move(wval), hprev);
} else {
auto wval = item.template raw_write_value<value_type*>();
if (has_delete(item)) {
h = e->row.new_history(
Sto::commit_tid(), &e->row, nullptr, hprev);
h->status_delete();
h->set_delete_cb(this, _delete_cb, e);
} else {
h = e->row.new_history(
Sto::commit_tid(), &e->row, wval, hprev);
}
}
assert(h);
bool result = e->row.cp_lock(Sto::commit_tid(), h);
if (!result && !h->status_is(MvStatus::ABORTED)) {
e->row.delete_history(h);
TransProxy(txn, item).add_mvhistory(nullptr);
} else {
TransProxy(txn, item).add_mvhistory(h);
}
return result;
}
bool check(TransItem& item, Transaction& txn) override {
if (is_bucket(item)) {
bucket_entry &buck = *bucket_address(item);
return buck.version.cp_check_version(txn, item);
} else {
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
auto h = item.template read_value<history_type*>();
auto result = e->row.cp_check(txn_read_tid(), h);
return result;
}
}
void install(TransItem& item, Transaction&) override {
assert(!is_bucket(item));
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
auto h = item.template write_value<history_type*>();
e->row.cp_install(h);
}
void unlock(TransItem& item) override {
(void)item;
assert(!is_bucket(item));
}
void cleanup(TransItem& item, bool committed) override {
if (!committed) {
auto key = item.key<item_key_t>();
auto e = key.internal_elem_ptr();
if (item.has_mvhistory()) {
auto h = item.template write_value<history_type*>();
if (h) {
e->row.abort(h);
}
}
}
}
private:
// remove a k-v node during transactions (with locks)
void _remove(internal_elem *el) {
bucket_entry& buck = map_[find_bucket_idx(el->key)];
buck.version.lock_exclusive();
internal_elem *prev = nullptr;
internal_elem *curr = buck.head;
while (curr != nullptr && curr != el) {
prev = curr;
curr = curr->next;
}
assert(curr);
if (prev != nullptr)
prev->next = curr->next;
else
buck.head = curr->next;
buck.version.unlock_exclusive();
Transaction::rcu_delete(curr);
}
// non-transactional remove by key
bool remove(const key_type& k) {
bucket_entry& buck = map_[find_bucket_idx(k)];
buck.version.lock_exclusive();
internal_elem *prev = nullptr;
internal_elem *curr = buck.head;
while (curr != nullptr && !pred_(curr->key, k)) {
prev = curr;
curr = curr->next;
}
if (curr == nullptr) {
buck.version.unlock_exclusive();
return false;
}
if (prev != nullptr)
prev->next = curr->next;
else
buck.head = curr->next;
buck.version.unlock_exclusive();
delete curr;
return true;
}
static void _delete_cb(
void *index_ptr, void *ele_ptr, void *history_ptr) {
auto ip = reinterpret_cast<mvcc_unordered_index<K, V, DBParams>*>(index_ptr);
auto el = reinterpret_cast<internal_elem*>(ele_ptr);
auto hp = reinterpret_cast<history_type*>(history_ptr);
bucket_entry& buck = ip->map_[ip->find_bucket_idx(el->key)];
buck.version.lock_exclusive();
internal_elem *prev = nullptr;
internal_elem *curr = buck.head;
while (curr != nullptr && curr != el) {
prev = curr;
curr = curr->next;
}
assert(curr);
if (prev != nullptr)
prev->next = curr->next;
else
buck.head = curr->next;
if (el->row.is_head(hp)) {
buck.version.unlock_exclusive();
Transaction::rcu_delete(el);
} else {
buck.version.unlock_exclusive();
}
}
// insert a k-v node to a bucket
void insert_in_bucket(bucket_entry& buck, const key_type& k) {
assert(buck.version.is_locked());
internal_elem *new_head = new internal_elem(k);
internal_elem *curr_head = buck.head;
new_head->next = curr_head;
buck.head = new_head;
buck.version.inc_nonopaque();
}
// find a key's k-v node (internal_elem) within a bucket
internal_elem *find_in_bucket(const bucket_entry& buck, const key_type& k) {
internal_elem *curr = buck.head;
while (curr && !pred_(curr->key, k))
curr = curr->next;
return curr;
}
static bool is_phantom(const history_type *h, const TransItem& item) {
return (h->status_is(DELETED) && !has_insert(item));
}
// TransItem keys
static bool is_bucket(const TransItem& item) {
return item.key<uintptr_t>() & bucket_bit;
}
static uintptr_t make_bucket_key(const bucket_entry& bucket) {
return (reinterpret_cast<uintptr_t>(&bucket) | bucket_bit);
}
static bucket_entry *bucket_address(const TransItem& item) {
uintptr_t bucket_key = item.key<uintptr_t>();
return reinterpret_cast<bucket_entry*>(bucket_key & ~bucket_bit);
}
static TransactionTid::type txn_read_tid() {
return Sto::read_tid<DBParams::Commute>();
}
};
}
| 37.521316 | 269 | 0.576825 | [
"vector"
] |
23a78175fcbb91c0d16951a941d3267e642db8ce | 13,830 | cpp | C++ | simulatorCore/src/network.cpp | egartner/Multi-robots | 025cc9e0426b9880ae2084d8e1ce8c275cb5f106 | [
"Apache-2.0"
] | 1 | 2016-12-22T08:06:26.000Z | 2016-12-22T08:06:26.000Z | simulatorCore/src/network.cpp | egartner/Multi-robots | 025cc9e0426b9880ae2084d8e1ce8c275cb5f106 | [
"Apache-2.0"
] | null | null | null | simulatorCore/src/network.cpp | egartner/Multi-robots | 025cc9e0426b9880ae2084d8e1ce8c275cb5f106 | [
"Apache-2.0"
] | null | null | null | /*
* network.cpp
*
* Created on: 24 mars 2013
* Author: dom
*/
#include <iostream>
#include <sstream>
#include <cmath>
#include <random>
#include "scheduler.h"
#include "network.h"
#include "trace.h"
#include "statsIndividual.h"
#include "utils.h"
#include "world.h"
#define SHADOWING_EXPONENT 2
#define SHADOWING_DEVIATION 4
using namespace std;
using namespace BaseSimulator;
using namespace BaseSimulator::utils;
//unsigned int Message::nextId = 0;
//unsigned int Message::nbMessages = 0;
uint64_t Message::nextId = 0;
uint64_t Message::nbMessages = 0;
uint64_t WirelessMessage::nextId = 0;
uint64_t WirelessMessage::nbMessages = 0;
unsigned int NetworkInterface::nextId = 0;
int NetworkInterface::defaultDataRate = 1000000;
//unsigned int P2PNetworkInterface::nextId = 0;
//int P2PNetworkInterface::defaultDataRate = 1000000;
//unsigned int WirelessNetworkInterface::nextId = 0;
//int WirelessNetworkInterface::defaultDataRate = 1000000;
//===========================================================================================================
//
// Message (class)
//
//===========================================================================================================
Message::Message() {
id = nextId;
nextId++;
nbMessages++;
MESSAGE_CONSTRUCTOR_INFO();
}
Message::~Message() {
MESSAGE_DESTRUCTOR_INFO();
nbMessages--;
}
uint64_t Message::getNbMessages() {
return(nbMessages);
}
string Message::getMessageName() {
return("generic message");
}
Message* Message::clone() {
Message* ptr = new Message();
ptr->sourceInterface = sourceInterface;
ptr->destinationInterface = destinationInterface;
ptr->type = type;
return ptr;
}
//===========================================================================================================
//
// WirelessMessage (class)
//
//===========================================================================================================
WirelessMessage::WirelessMessage(bID destId) {
id = nextId;
destinationId = destId;
nextId++;
nbMessages++;
MESSAGE_CONSTRUCTOR_INFO();
}
WirelessMessage::~WirelessMessage() {
MESSAGE_DESTRUCTOR_INFO();
nbMessages--;
}
uint64_t WirelessMessage::getNbMessages() {
return(nbMessages);
}
string WirelessMessage::getMessageName() {
return("generic wireless message");
}
WirelessMessage* WirelessMessage::clone() {
WirelessMessage* ptr = new WirelessMessage(destinationId);
ptr->sourceInterface = sourceInterface;
ptr->type = type;
return ptr;
}
//==========================================================================================================
//
// NetworkInterface (class)
//
//==========================================================================================================
NetworkInterface::NetworkInterface(BaseSimulator::BuildingBlock *b){
hostBlock = b;
availabilityDate=0;
globalId=nextId;
nextId++;
}
NetworkInterface::~NetworkInterface() {
}
//===========================================================================================================
//
// P2PNetworkInterface (class)
//
//===========================================================================================================
P2PNetworkInterface::P2PNetworkInterface(BaseSimulator::BuildingBlock *b) : NetworkInterface(b){
#ifndef NDEBUG
OUTPUT << "P2PNetworkInterface constructor" << endl;
#endif
dataRate = new StaticRate(defaultDataRate);
connectedInterface = NULL;
}
void P2PNetworkInterface::setDataRate(Rate *r) {
assert(r != NULL);
delete dataRate;
dataRate = r;
}
P2PNetworkInterface::~P2PNetworkInterface() {
#ifndef NDEBUG
OUTPUT << "P2PNetworkInterface destructor" << endl;
#endif
delete dataRate;
}
void P2PNetworkInterface::send(Message *m) {
getScheduler()->schedule(new NetworkInterfaceEnqueueOutgoingEvent(getScheduler()->now(), m, this));
}
bool P2PNetworkInterface::addToOutgoingBuffer(MessagePtr msg) {
stringstream info;
if (connectedInterface != NULL) {
outgoingQueue.push_back(msg);
BaseSimulator::utils::StatsIndividual::incOutgoingMessageQueueSize(hostBlock->stats);
if (availabilityDate < BaseSimulator::getScheduler()->now()) availabilityDate = BaseSimulator::getScheduler()->now();
if (outgoingQueue.size() == 1 && messageBeingTransmitted == NULL) { //TODO
BaseSimulator::getScheduler()->schedule(new NetworkInterfaceStartTransmittingEvent(availabilityDate,this));
}
return(true);
} else {
info.str("");
info << "*** WARNING *** [block " << hostBlock->blockId << ",interface " << globalId <<"] : trying to enqueue a Message but no interface connected";
BaseSimulator::getScheduler()->trace(info.str());
return(false);
}
}
void P2PNetworkInterface::send() {
MessagePtr msg;
stringstream info;
Time transmissionDuration;
if (!connectedInterface) {
info << "*** WARNING *** [block " << hostBlock->blockId << ",interface " << globalId <<"] : trying to send a Message but no interface connected";
BaseSimulator::getScheduler()->trace(info.str());
return;
}
if (outgoingQueue.size()==0) {
info << "*** ERROR *** [block " << hostBlock->blockId << ",interface " << globalId <<"] : The outgoing buffer of this interface should not be empty !";
BaseSimulator::getScheduler()->trace(info.str());
exit(EXIT_FAILURE);
}
msg = outgoingQueue.front();
outgoingQueue.pop_front();
BaseSimulator::utils::StatsIndividual::decOutgoingMessageQueueSize(hostBlock->stats);
transmissionDuration = getTransmissionDuration(msg);
messageBeingTransmitted = msg;
messageBeingTransmitted->sourceInterface = this;
messageBeingTransmitted->destinationInterface = connectedInterface;
availabilityDate = BaseSimulator::getScheduler()->now()+transmissionDuration;
/* info << "*** sending (interface " << localId << " of block " << hostBlock->blockId << ")";
getScheduler()->trace(info.str());*/
BaseSimulator::getScheduler()->schedule(new NetworkInterfaceStopTransmittingEvent(BaseSimulator::getScheduler()->now()+transmissionDuration, this));
StatsCollector::getInstance().incMsgCount();
StatsIndividual::incSentMessageCount(hostBlock->stats);
}
void P2PNetworkInterface::connect(P2PNetworkInterface *ni) {
// test ajouté par Ben, gestion du cas : connect(NULL)
if (ni) { // Connection
if (ni->connectedInterface != this) {
if (ni->connectedInterface != NULL) {
OUTPUT << "ERROR : connecting to an already connected P2PNetwork interface" << endl;
ni->connectedInterface->hostBlock->removeNeighbor(ni->connectedInterface);
ni->hostBlock->removeNeighbor(ni);
}
ni->connectedInterface = this;
hostBlock->addNeighbor(ni->connectedInterface, ni->hostBlock);
ni->hostBlock->addNeighbor(ni, ni->connectedInterface->hostBlock);
}
} else if (connectedInterface != NULL) {
// disconnect this interface and the remote one
hostBlock->removeNeighbor(this);
connectedInterface->hostBlock->removeNeighbor(connectedInterface);
connectedInterface->connectedInterface = NULL;
}
connectedInterface = ni;
}
Time P2PNetworkInterface::getTransmissionDuration(MessagePtr &m) {
double rate = dataRate->get();
Time transmissionDuration = (m->size()*8000000ULL)/rate;
//cerr << "TransmissionDuration: " << transmissionDuration << endl;
return transmissionDuration;
}
bool P2PNetworkInterface::isConnected() {
return connectedInterface != NULL;
}
//======================================================================================================
//
// WirelessNetworkInterface(class)
//
//======================================================================================================
WirelessNetworkInterface::WirelessNetworkInterface(BaseSimulator::BuildingBlock *b, float power, float threshold, float sensitivity) : NetworkInterface(b){
#ifndef NDEBUG
OUTPUT << "WirelessNetworkInterface constructor" << endl;
#endif
dataRate = new StaticRate(defaultDataRate);
// arbitrary values, please adjust to fit your simulated radio equipment
transmitPower = power;
receptionThreshold = threshold;
receptionSensitivity = sensitivity;
collisionOccuring = false;
transmitting = false;
receiving = false;
channelAvailability = true;
first = true;
}
WirelessNetworkInterface::~WirelessNetworkInterface(){
#ifndef NDEBUG
OUTPUT<< "WirelessNetworkInterface destructor" << endl;
#endif
}
void WirelessNetworkInterface::setReceptionThreshold(float threshold) {
receptionThreshold = threshold;
}
float WirelessNetworkInterface::getReceptionThreshold() {
return(receptionThreshold);
}
// Effectively start the transmission
// Do not call this function directly, it is called automatically when the previous transmission in the outgoing queue terminates
void WirelessNetworkInterface::send(){
WirelessMessagePtr msg;
stringstream info;
Time transmissionDuration;
if (outgoingQueue.size()==0) {
info << "*** ERROR *** [block " << hostBlock->blockId << ",wireless interface " << globalId <<"] : The outgoing buffer of this interface should not be empty !";
BaseSimulator::getScheduler()->trace(info.str());
exit(EXIT_FAILURE);
}
msg = outgoingQueue.front();
outgoingQueue.pop_front();
transmissionDuration = getTransmissionDuration(msg);
messageBeingTransmitted = msg;
messageBeingTransmitted->sourceInterface = this;
BaseSimulator::getWorld()->broadcastWirelessMessage(msg);
availabilityDate = BaseSimulator::getScheduler()->now()+transmissionDuration;
/* info << "*** sending (interface " << localId << " of block " << hostBlock->blockId << ")";
getScheduler()->trace(info.str());*/
transmitting = true;
BaseSimulator::getScheduler()->schedule(new WirelessNetworkInterfaceStopTransmittingEvent(BaseSimulator::getScheduler()->now()+transmissionDuration, this));
}
void WirelessNetworkInterface::startReceive(WirelessMessagePtr msg) {
stringstream info;
float distance;
float receivedPower = 0;
float snr = 0;
float noiseFloor = -130;
Vector3D vec1;
Vector3D vec2;
Time transmissionDuration = getTransmissionDuration(msg);
vec1=msg->sourceInterface->hostBlock->getPositionVector();
vec2=this->hostBlock->getPositionVector();
distance = sqrt(pow(abs(vec1.pt[0] - vec2.pt[0]),2)+pow(abs(vec1.pt[1] - vec2.pt[1]),2))*10;
receivedPower = pathLoss(msg->sourceInterface->getTransmitPower(), distance, 1.0, 1.0, 1.0) + shadowing(SHADOWING_EXPONENT, distance, SHADOWING_DEVIATION);
//info << "Message received with : " << receivedPower << endl;
if (receivedPower > receptionSensitivity){
channelAvailability = false;
BaseSimulator::getScheduler()->schedule(new WirelessNetworkInterfaceIdleEvent(BaseSimulator::getScheduler()->now()+transmissionDuration, this));
if (receivedPower < receptionThreshold) noiseFloor = receivedPower;
else if (receivedPower >= receptionThreshold) {
snr = receivedPower - noiseFloor;
info << "snr : "<<snr;
if(!this->isReceiving() && snr >= 15 && (msg->destinationId == this->hostBlock->blockId || msg->destinationId ==255)) {
receiving = true;
BaseSimulator::getScheduler()->schedule(new WirelessNetworkInterfaceStopReceiveEvent(BaseSimulator::getScheduler()->now()+transmissionDuration, this));
}
else if (this->isReceiving() || snr < 15){
collisionOccuring = true;
}
}
}
getScheduler()->trace(info.str());
}
void WirelessNetworkInterface::stopReceive() {
stringstream info;
receiving = false;
if (!collisionOccuring) {
this->hostBlock->scheduleLocalEvent(EventPtr(new WirelessNetworkInterfaceMessageReceivedEvent(BaseSimulator::getScheduler()->now(),this,messageBeingReceived)));
}
else {
collisionOccuring = false;
info << "A COLLISION HAS OCCURED!";
getScheduler()->trace(info.str());
}
}
void WirelessNetworkInterface::setTransmitPower(int power){
this->transmitPower = power;
}
float WirelessNetworkInterface::getTransmitPower(){
return(this->transmitPower);
}
Time WirelessNetworkInterface::getTransmissionDuration(WirelessMessagePtr &m) {
double rate = dataRate->get();
Time transmissionDuration = (m->size()*8000000ULL)/rate;
//cerr << "TransmissionDuration: " << transmissionDuration << endl;
return transmissionDuration;
}
bool WirelessNetworkInterface::addToOutgoingBuffer(WirelessMessagePtr msg) {
stringstream info;
outgoingQueue.push_back(msg);
//BaseSimulator::utils::StatsIndividual::incOutgoingMessageQueueSize(hostBlock->stats);
if (availabilityDate < BaseSimulator::getScheduler()->now()) availabilityDate = BaseSimulator::getScheduler()->now();
if (outgoingQueue.size() == 1 && messageBeingTransmitted == NULL) {
//
// Scheduling this event instead of directly calling send() allows for taking into account processing time
//
BaseSimulator::getScheduler()->schedule(new WirelessNetworkInterfaceChannelListeningEvent(availabilityDate,this));
}
// as long as there is no limit to the buffer size, this function will return true
return(true);
}
float WirelessNetworkInterface::pathLoss(float power, float distance, float gain, float tHeight, float rHeight){
//Compute the path loss using the two-ray ground model
float receivedPower = power + 10 * log10(pow(tHeight,2)*pow(rHeight,2)) - 25 * log10(distance);
return receivedPower;
}
float WirelessNetworkInterface::shadowing(float exponent, float distance, float deviation){
stringstream info;
std::random_device rand;
std::default_random_engine generator(rand());
std::normal_distribution<double> distribution(0, deviation);
float shadowing = distribution(generator);
info << "shadowing : " << shadowing;
//getScheduler()->trace(info.str());
return shadowing;
}
| 34.064039 | 168 | 0.668185 | [
"model"
] |
23ae70e5c5e74532e3d2c1f66a68297381881df7 | 6,039 | hpp | C++ | include/tree.hpp | davidallendj/ez_paint | c45ff17dec1e17b68e02afb7acae335093c79106 | [
"MIT"
] | null | null | null | include/tree.hpp | davidallendj/ez_paint | c45ff17dec1e17b68e02afb7acae335093c79106 | [
"MIT"
] | null | null | null | include/tree.hpp | davidallendj/ez_paint | c45ff17dec1e17b68e02afb7acae335093c79106 | [
"MIT"
] | null | null | null |
#ifndef FU_TREE_HPP
#define FU_TREE_HPP
#include "config.hpp"
#include "collision.hpp"
#include "utils.hpp"
#include <array>
#include <iterator>
#include <type_traits>
#include <vector>
#include <math.h>
#include <SFML/Config.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Shape.hpp>
namespace ez_paint
{
template <typename T>
concept IsRect = std::is_same<T, sf::FloatRect>::value || std::is_base_of_v<sf::Shape, T>;
template <size_t N>
class Node
{
public:
typedef std::array< Node<N>*, N > NodeArray;
typedef std::vector< Node<N>* > NodeVector;
explicit Node(const sf::FloatRect& bounds);
virtual ~Node();
const sf::FloatRect& getBounds() const;
const NodeArray& getNodes() const;
void setBounds(const sf::FloatRect& bounds);
NodeVector search(const sf::CircleShape& targetShape);
NodeVector search(const sf::FloatRect& targetBounds);
virtual void partition(sf::Uint64 height, const sf::FloatRect& parentBounds){};
protected:
NodeArray m_childNodes;
sf::FloatRect m_bounds;
};
template <size_t N>
Node<N>::Node(const sf::FloatRect& bounds)
: m_bounds(bounds)
{ m_childNodes.fill(nullptr); }
template <size_t N>
Node<N>::~Node()
{
// foreach(m_childNodes, [](Node<N> *node){
// if(node){
// delete node;
// node = nullptr;
// }
// });
}
template <size_t N>
const sf::FloatRect& Node<N>::getBounds() const
{ return m_bounds; }
template <size_t N>
const typename Node<N>::NodeArray& Node<N>::getNodes() const
{ return m_childNodes; }
template <size_t N>
void Node<N>::setBounds(const sf::FloatRect &bounds)
{ m_bounds = bounds; }
template <size_t N>
typename Node<N>::NodeVector Node<N>::search(const sf::CircleShape& targetShape)
{
NodeVector f;
for(const auto& node : m_childNodes)
{
if(!node)
continue;
// if(node->getBounds().intersects(targetBounds))
if(Collision::CircleTest(targetShape, node->getBounds()))
{
NodeVector nodes = node->search(targetShape);
if(nodes.empty())
f.emplace_back(node);
f.insert(f.end(),
std::make_move_iterator(nodes.begin()),
std::make_move_iterator(nodes.end())
);
nodes.erase(nodes.begin(), nodes.end());
}
}
return f;
}
template <size_t N>
typename Node<N>::NodeVector Node<N>::search(const sf::FloatRect& targetBounds)
{
NodeVector f;
for(const auto& node : m_childNodes)
{
if(!node)
continue;
// if(node->getBounds().intersects(targetBounds))
if(node->getBounds().intersects(targetBounds))
{
NodeVector nodes = node->search(targetBounds);
if(nodes.empty())
f.emplace_back(node);
f.insert(f.end(),
std::make_move_iterator(nodes.begin()),
std::make_move_iterator(nodes.end())
);
nodes.erase(nodes.begin(), nodes.end());
}
}
return f;
}
template <sf::Uint64 N>
class StaticTree
{
public:
typedef std::array< Node<N>*, N > NodeArray;
typedef std::vector< Node<N>* > NodeVector;
// template <typename Node>
StaticTree(const sf::FloatRect& bounds, sf::Uint64 depth = 1, Node<N> *node = nullptr);
virtual ~StaticTree();
void partition(sf::Uint64 depth);
void setBounds(const sf::FloatRect& bounds);
NodeVector search(const sf::CircleShape& targetShape);
NodeVector search(const sf::FloatRect& targetBounds);
protected:
Node<N> *m_root;
sf::Uint64 m_recommendedPartitions;
};
template <sf::Uint64 N>
// template <typename Node>
StaticTree<N>::StaticTree(const sf::FloatRect& bounds, sf::Uint64 depth, Node<N> *root)
// : m_root(root)
{
m_root = root;
partition( (depth > 0) ? depth : 0 );
}
template <sf::Uint64 N>
StaticTree<N>::~StaticTree<N>()
{
// if(m_root)
// {
// delete m_root;// do some shit
// m_root = nullptr;
// }
}
template <sf::Uint64 N>
typename StaticTree<N>::NodeVector
StaticTree<N>::search(const sf::FloatRect& targetBounds)
{
NodeVector f;
for(const auto& node : m_root->getNodes())
{
if(!node)
continue;
if(node->getBounds().intersects(targetBounds))
{
NodeVector nodes = node->search(targetBounds);
f.insert(f.end(),
std::make_move_iterator(nodes.begin()),
std::make_move_iterator(nodes.end())
);
nodes.erase(nodes.begin(), nodes.end());
}
}
return f;
}
template <sf::Uint64 N>
typename StaticTree<N>::NodeVector
StaticTree<N>::search(const sf::CircleShape& targetShape)
{
NodeVector f;
for(const auto& node : m_root->getNodes())
{
if(!node)
continue;
if(Collision::CircleTest(targetShape, node->getBounds()))
{
NodeVector nodes = node->search(targetShape);
f.insert(f.end(),
std::make_move_iterator(nodes.begin()),
std::make_move_iterator(nodes.end())
);
}
}
return f;
}
template <sf::Uint64 N>
void StaticTree<N>::partition(sf::Uint64 height)
{
sf::FloatRect bounds = m_root->getBounds();
m_root->partition(height, bounds);
}
template <sf::Uint64 N>
void StaticTree<N>::setBounds(const sf::FloatRect &bounds)
{ m_root->setBounds(bounds); }
// TODO: Need general implementation of partition() to achieve this
// typedef StaticTree<2> BinaryTree;
// typedef StaticTree<4> Quadtree;
// typedef StaticTree<8> Octree;
class QuadtreeNode : public Node<4>
{
public:
explicit QuadtreeNode(const sf::FloatRect& bounds);
virtual ~QuadtreeNode();
void partition(sf::Uint64 depth, const sf::FloatRect& parentBounds);
};
class Quadtree : public StaticTree<4>
{
public:
Quadtree(const sf::FloatRect& bounds, sf::Uint64 depth = config::TreePartitions);
virtual ~Quadtree();
};
class OctreeNode : public Node<8>
{
public:
explicit OctreeNode(const sf::FloatRect& bounds);
virtual ~OctreeNode();
void partition(sf::Uint64 depth, const sf::FloatRect& parent);
};
class Octree : public StaticTree<8>
{
public:
Octree(const sf::FloatRect& bounds, sf::Uint64 depth = config::TreePartitions);
virtual ~Octree();
};
}
#endif | 22.449814 | 91 | 0.665011 | [
"shape",
"vector"
] |
23c0e74b514c6f749660ea494adb0ecf2da08226 | 1,677 | cpp | C++ | Dynamic Programming/Minimum_SubsetSum_Difference_DP.cpp | parth1614/DSA_Questions | 7083952eb310a21f7e30267efa437dfbb8c0f88f | [
"MIT"
] | null | null | null | Dynamic Programming/Minimum_SubsetSum_Difference_DP.cpp | parth1614/DSA_Questions | 7083952eb310a21f7e30267efa437dfbb8c0f88f | [
"MIT"
] | null | null | null | Dynamic Programming/Minimum_SubsetSum_Difference_DP.cpp | parth1614/DSA_Questions | 7083952eb310a21f7e30267efa437dfbb8c0f88f | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
void subsetSum(vector<int>& arr,int range,int n){
vector<vector<bool>> t;
for(int i=0;i<n+1;++i){
vector<bool> temp;
for(int j=0;j<range+1;++j){
if(j==0 || (j==0&&i==0)){
temp.push_back(true);
}
else if(i==0){
temp.push_back(false);
}
}
t.push_back(temp);
temp.clear();
}
for(int i=1;i<n+1;++i){
for(int j=1;j<range+1;++j){
if(arr[i-1]<=j){
t[i][j] = (t[i-1][j-arr[i-1]] || t[i-1][j]);
}
else if(arr[i-1]>j){
t[i][j] = t[i-1][j];
}
}
}
//storing half of the last row in the vector
/*vector<bool> store(range/2);
for(int i=0;i<store.size();++i){
store[i] = t[n][i];
// cout<<store[i]<<endl;
}*/
int mini = INT_MAX;
// for(int i=0;i<store.size();++i){
// if(store[i]==true){
// mini = min(mini,(range-i));
// //cout<<mini<<endl;
// }
// }
for(int i=range/2;i>=0;--i){
if(t[n][i]==1){
mini = range - 2*i;
break;
}
}
// return mini;
//cout<<"Minimum SubsetSum diff is: "<<abs(range-(2*mini));
cout<<"final: "<<mini;
}
int main(){
int n;
cin>>n;
vector<int> arr;
for(int i=0;i<n;++i){
int x;
cin>>x;
arr.push_back(x);
}
int range = 0;
for(int i=0;i<n;++i){
range = range + arr[i];
}
// cout<<"The min subsetSum diff is: "<<subsetSum(arr,range,n);
subsetSum(arr,range,n);
}
| 22.662162 | 66 | 0.416816 | [
"vector"
] |
23d0254b2d501aff393f3f7eada307df3fa2ef56 | 828 | hpp | C++ | test/unit/test.hpp | rymut/mexcppclass | a6a1873a4c4d4f588490d3dc070cb7500fb82214 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-07-28T23:59:48.000Z | 2019-07-28T23:59:48.000Z | test/unit/test.hpp | rymut/mexcppclass | a6a1873a4c4d4f588490d3dc070cb7500fb82214 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | test/unit/test.hpp | rymut/mexcppclass | a6a1873a4c4d4f588490d3dc070cb7500fb82214 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2017-08-25T03:02:36.000Z | 2020-04-08T17:02:42.000Z | /// Copyright (C) 2017 by Boguslaw Rymut
///
/// This file is distributed under the Apache 2.0 License
/// See LICENSE for details.
#ifndef MEXCPPCLASS_TEST_UNIT_TEST_HPP_
#define MEXCPPCLASS_TEST_UNIT_TEST_HPP_
namespace mexcppclass {
namespace test {
namespace unit {
class Test {
public:
Test();
explicit Test(const double &value);
Test(const Test &rhs);
~Test();
void SetValue(const double &value);
const double &GetValue() const;
bool IsEqual(const Test &object) const;
bool IsEqual(const double &value) const;
Test &operator=(const Test &rhs);
private:
double value_;
};
class TestInternal {
public:
TestInternal();
~TestInternal();
};
} // namespace unit
} // namespace test
} // namespace mexcppclass
#endif // MEXCPPCLASS_TEST_UNIT_TEST_HPP_
| 20.7 | 58 | 0.684783 | [
"object"
] |
23d5759022e8788be091176182a4303f03274f0a | 699 | cpp | C++ | src/examples/executor/post_2.cpp | jjzhang166/executors | 9b42e193b27cc5c3308dd3bc4e52712c2e442c4b | [
"BSL-1.0"
] | 406 | 2015-01-19T06:35:42.000Z | 2022-03-30T04:38:12.000Z | src/examples/executor/post_2.cpp | rongming-lu/executors | 9b42e193b27cc5c3308dd3bc4e52712c2e442c4b | [
"BSL-1.0"
] | 1 | 2018-06-13T03:17:24.000Z | 2019-03-05T20:09:47.000Z | src/examples/executor/post_2.cpp | rongming-lu/executors | 9b42e193b27cc5c3308dd3bc4e52712c2e442c4b | [
"BSL-1.0"
] | 66 | 2015-01-22T09:01:17.000Z | 2022-03-30T04:38:13.000Z | #include <cstdlib>
#include <experimental/executor>
#include <experimental/thread_pool>
#include <iostream>
#include <thread>
using std::experimental::post;
using std::experimental::thread_pool;
struct work
{
};
void do_something(const work&)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
std::cerr << "Usage: post_2 <count>\n";
return 1;
}
std::vector<work> work_list(std::atoi(argv[1]));
// Start a large amount of work and join on the pool to complete.
thread_pool tp(16);
for (auto work: work_list)
{
post(tp,
[work]
{
do_something(work);
});
}
tp.join();
}
| 17.04878 | 67 | 0.638054 | [
"vector"
] |
23e5cd568cab63819f1db826a87cccda3df91e1b | 4,067 | cc | C++ | cc_code/src/hmm/step/peptide-emission.cc | erisyon/whatprot | 176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c | [
"MIT"
] | null | null | null | cc_code/src/hmm/step/peptide-emission.cc | erisyon/whatprot | 176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c | [
"MIT"
] | 1 | 2021-06-12T00:50:08.000Z | 2021-06-15T17:59:12.000Z | cc_code/src/hmm/step/peptide-emission.cc | erisyon/whatprot | 176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c | [
"MIT"
] | 1 | 2021-06-11T19:34:43.000Z | 2021-06-11T19:34:43.000Z | /******************************************************************************\
* Author: Matthew Beauregard Smith *
* Affiliation: The University of Texas at Austin *
* Department: Oden Institute and Institute for Cellular and Molecular Biology *
* PI: Edward Marcotte *
* Project: Protein Fluorosequencing *
\******************************************************************************/
// Defining symbols from header:
#include "peptide-emission.h"
// Standard C++ library headers:
#include <functional>
// Local project headers:
#include "common/radiometry.h"
#include "hmm/fit/error-model-fitter.h"
#include "hmm/state-vector/peptide-state-vector.h"
#include "tensor/tensor-iterator.h"
namespace whatprot {
namespace {
using std::function;
} // namespace
PeptideEmission::PeptideEmission(const Radiometry& radiometry,
int max_num_dyes,
function<double(double, int)> pdf)
: radiometry(radiometry),
num_timesteps(radiometry.num_timesteps),
num_channels(radiometry.num_channels),
max_num_dyes(max_num_dyes) {
values.resize(num_timesteps * num_channels * (max_num_dyes + 1));
for (int t = 0; t < num_timesteps; t++) {
for (int c = 0; c < num_channels; c++) {
for (int d = 0; d < (max_num_dyes + 1); d++) {
prob(t, c, d) = pdf(radiometry(t, c), d);
}
}
}
}
double& PeptideEmission::prob(int t, int c, int d) {
return values[(t * num_channels + c) * (max_num_dyes + 1) + d];
}
double PeptideEmission::prob(int t, int c, int d) const {
return values[(t * num_channels + c) * (max_num_dyes + 1) + d];
}
void PeptideEmission::forward(int* num_edmans, PeptideStateVector* psv) const {
TensorIterator* it = psv->tensor.iterator();
while (it->index < (*num_edmans + 1) * psv->tensor.strides[0]) {
double product = 1.0;
for (int c = 0; c < num_channels; c++) {
product *= prob((*num_edmans), c, it->loc[1 + c]);
}
*it->get() = *it->get() * product;
it->advance();
}
delete it;
}
void PeptideEmission::backward(const PeptideStateVector& input,
int* num_edmans,
PeptideStateVector* output) const {
ConstTensorIterator* inputit = input.tensor.const_iterator();
TensorIterator* outputit = output->tensor.iterator();
while (inputit->index < (*num_edmans + 1) * input.tensor.strides[0]) {
double product = 1.0;
for (int c = 0; c < num_channels; c++) {
product *= prob((*num_edmans), c, inputit->loc[1 + c]);
}
*outputit->get() = inputit->get() * product;
inputit->advance();
outputit->advance();
}
delete inputit;
delete outputit;
}
void PeptideEmission::improve_fit(const PeptideStateVector& forward_psv,
const PeptideStateVector& backward_psv,
const PeptideStateVector& next_backward_psv,
int num_edmans,
double probability,
ErrorModelFitter* fitter) const {
ConstTensorIterator* fit = forward_psv.tensor.const_iterator();
ConstTensorIterator* bit = backward_psv.tensor.const_iterator();
while (fit->index < (num_edmans + 1) * forward_psv.tensor.strides[0]) {
double p_state = fit->get() * bit->get() / probability;
for (int c = 0; c < num_channels; c++) {
int t = fit->loc[0];
double intensity = radiometry(num_edmans, c);
int dye_count = fit->loc[1 + c];
fitter->distribution_fit->add_sample(intensity, dye_count, p_state);
}
fit->advance();
bit->advance();
}
delete fit;
delete bit;
}
} // namespace whatprot | 38.367925 | 80 | 0.537743 | [
"vector",
"model"
] |
23e953f169fb0da08dac2e1ce7316e41c94fc7a6 | 2,105 | inl | C++ | src/python/cupoch_pybind/dl_converter.inl | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 522 | 2020-01-19T05:59:00.000Z | 2022-03-25T04:36:52.000Z | src/python/cupoch_pybind/dl_converter.inl | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 87 | 2020-02-23T09:56:48.000Z | 2022-03-25T13:35:15.000Z | src/python/cupoch_pybind/dl_converter.inl | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 74 | 2020-01-27T15:33:30.000Z | 2022-03-27T11:58:22.000Z | /**
* Copyright (c) 2020 Neka-Nat
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
#include "cupoch_pybind/dl_converter.h"
#include <Python.h>
#include "cupoch/utility/dl_converter.h"
namespace cupoch {
namespace dlpack {
template <typename T>
py::capsule ToDLpackCapsule(
utility::device_vector<T> &src) {
void const *managed_tensor = utility::ToDLPack(src);
return py::capsule(managed_tensor, "dltensor", [](::PyObject *obj) {
auto *ptr = ::PyCapsule_GetPointer(obj, "dltensor");
if (ptr != nullptr) {
auto *m_tsr = static_cast<::DLManagedTensor *>(ptr);
m_tsr->deleter(m_tsr);
} else {
::PyErr_Clear();
}
});
}
template <typename T>
void FromDLpackCapsule(
py::capsule dlpack, utility::device_vector<T> &dst) {
auto obj = py::cast<py::object>(dlpack);
::DLManagedTensor *managed_tensor =
(::DLManagedTensor *)::PyCapsule_GetPointer(obj.ptr(), "dltensor");
utility::FromDLPack<typename T::Scalar, T::SizeAtCompileTime>(managed_tensor, dst);
}
}
} | 37.589286 | 87 | 0.703088 | [
"object"
] |
23ed8f89bb3b73d67f10394fba86088de529381f | 7,948 | cpp | C++ | source/compiler1/tests/cpp_tests_launcher.cpp | Panzerschrek/U-00DC-Sprache | eb677a66d178985433a62eb6b8a50ce2cdb14b1a | [
"BSD-3-Clause"
] | 45 | 2016-06-21T22:28:43.000Z | 2022-03-26T12:21:46.000Z | source/compiler1/tests/cpp_tests_launcher.cpp | Panzerschrek/U-00DC-Sprache | eb677a66d178985433a62eb6b8a50ce2cdb14b1a | [
"BSD-3-Clause"
] | 6 | 2020-07-12T18:00:10.000Z | 2021-11-30T11:20:14.000Z | source/compiler1/tests/cpp_tests_launcher.cpp | Panzerschrek/U-00DC-Sprache | eb677a66d178985433a62eb6b8a50ce2cdb14b1a | [
"BSD-3-Clause"
] | 5 | 2019-09-03T17:20:34.000Z | 2022-01-30T15:10:21.000Z | #include <iostream>
#include <unordered_set>
#include "../../code_builder_lib_common/push_disable_llvm_warnings.hpp"
#include <llvm/Support/InitLLVM.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/raw_os_ostream.h>
#include "../../code_builder_lib_common/pop_llvm_warnings.hpp"
#include "../../tests/tests_common.hpp"
#include "../../tests/cpp_tests/tests.hpp"
#include "../launchers_common/funcs_c.hpp"
namespace U
{
namespace
{
llvm::ManagedStatic<llvm::LLVMContext> g_llvm_context;
UserHandle ErrorHanlder(
const UserHandle data, // should be "std::vector<CodeBuilderError>"
const uint32_t file_index,
const uint32_t line,
const uint32_t column,
const uint32_t error_code,
const U1_StringView& error_text )
{
CodeBuilderError error;
error.src_loc= SrcLoc( file_index, line, column );
error.code= CodeBuilderErrorCode(error_code);
error.text= std::string( error_text.data, error_text.data + error_text.size );
const auto errors_container= reinterpret_cast<std::vector<CodeBuilderError>*>(data);
errors_container->push_back( std::move(error) );
return reinterpret_cast<UserHandle>(&errors_container->back());
}
UserHandle TemplateErrorsContextHandler(
const UserHandle data, // should be "CodeBuilderError*"
const uint32_t file_index,
const uint32_t line,
const uint32_t column,
const U1_StringView& context_name,
const U1_StringView& args_description )
{
const auto out_error= reinterpret_cast<CodeBuilderError*>(data);
out_error->template_context= std::make_shared<TemplateErrorsContext>();
out_error->template_context->context_declaration_src_loc= SrcLoc( file_index, line, column );
out_error->template_context->context_name= std::string( context_name.data, context_name.data + context_name.size );
out_error->template_context->parameters_description= std::string( args_description.data, args_description.data + args_description.size );
return reinterpret_cast<UserHandle>( & out_error->template_context->errors );
}
const ErrorsHandlingCallbacks g_error_handling_callbacks
{
ErrorHanlder,
TemplateErrorsContextHandler,
};
// Returns "true" if should enable test.
bool FilterTest( const std::string& test_name )
{
const std::string test_name_without_file_name= test_name.substr(test_name.find_last_of(':') + 1);
static const std::unordered_set<std::string> c_test_to_disable
{
};
return c_test_to_disable.count( test_name_without_file_name ) == 0;
}
} // namespace
std::unique_ptr<llvm::Module> BuildProgram( const char* const text )
{
const U1_StringView text_view{ text, std::strlen(text) };
llvm::LLVMContext& llvm_context= *g_llvm_context;
llvm::DataLayout data_layout( GetTestsDataLayout() );
auto ptr=
U1_BuildProgram(
text_view,
llvm::wrap(&llvm_context),
llvm::wrap(&data_layout) );
U_TEST_ASSERT( ptr != nullptr );
return std::unique_ptr<llvm::Module>( reinterpret_cast<llvm::Module*>(ptr) );
}
ErrorTestBuildResult BuildProgramWithErrors( const char* const text )
{
const U1_StringView text_view{ text, std::strlen(text) };
llvm::LLVMContext& llvm_context= *g_llvm_context;
llvm::DataLayout data_layout( GetTestsDataLayout() );
ErrorTestBuildResult build_result;
const bool ok=
U1_BuildProgramWithErrors(
text_view,
llvm::wrap(&llvm_context),
llvm::wrap(&data_layout),
g_error_handling_callbacks,
reinterpret_cast<UserHandle>(&build_result.errors) );
U_TEST_ASSERT(ok);
return build_result;
}
std::unique_ptr<llvm::Module> BuildMultisourceProgram( std::vector<SourceEntry> sources, const std::string& root_file_path )
{
std::vector<U1_SourceFile> source_files;
source_files.reserve(sources.size());
for (const SourceEntry& entry : sources)
{
U1_SourceFile f{};
f.file_path.data= entry.file_path.data();
f.file_path.size= entry.file_path.size();
f.file_content.data= entry.text;
f.file_content.size= std::strlen(entry.text);
source_files.push_back(f);
}
const U1_StringView root_file_path_view{ root_file_path.data(), root_file_path.size() };
llvm::LLVMContext& llvm_context= *g_llvm_context;
llvm::DataLayout data_layout( GetTestsDataLayout() );
const auto ptr=
U1_BuildMultisourceProgram(
source_files.data(), source_files.size(),
root_file_path_view,
llvm::wrap(&llvm_context),
llvm::wrap(&data_layout) );
U_TEST_ASSERT( ptr != nullptr );
return std::unique_ptr<llvm::Module>( reinterpret_cast<llvm::Module*>(ptr) );
}
ErrorTestBuildResult BuildMultisourceProgramWithErrors( std::vector<SourceEntry> sources, const std::string& root_file_path )
{
std::vector<U1_SourceFile> source_files;
source_files.reserve(sources.size());
for (const SourceEntry& entry : sources)
{
U1_SourceFile f{};
f.file_path.data= entry.file_path.data();
f.file_path.size= entry.file_path.size();
f.file_content.data= entry.text;
f.file_content.size= std::strlen(entry.text);
source_files.push_back(f);
}
const U1_StringView root_file_path_view{ root_file_path.data(), root_file_path.size() };
llvm::LLVMContext& llvm_context= *g_llvm_context;
llvm::DataLayout data_layout( GetTestsDataLayout() );
ErrorTestBuildResult build_result;
const bool ok=
U1_BuildMultisourceProgramWithErrors(
source_files.data(), source_files.size(),
root_file_path_view,
llvm::wrap(&llvm_context),
llvm::wrap(&data_layout),
g_error_handling_callbacks,
reinterpret_cast<UserHandle>(&build_result.errors) );
U_TEST_ASSERT( ok );
return build_result;
}
std::unique_ptr<llvm::Module> BuildProgramForLifetimesTest( const char* text )
{
const U1_StringView text_view{ text, std::strlen(text) };
llvm::LLVMContext& llvm_context= *g_llvm_context;
llvm::DataLayout data_layout( GetTestsDataLayout() );
auto ptr=
U1_BuildProgramForLifetimesTest(
text_view,
llvm::wrap(&llvm_context),
llvm::wrap(&data_layout) );
U_TEST_ASSERT( ptr != nullptr );
return std::unique_ptr<llvm::Module>( reinterpret_cast<llvm::Module*>(ptr) );
}
EnginePtr CreateEngine( std::unique_ptr<llvm::Module> module, const bool needs_dump )
{
U_TEST_ASSERT( module != nullptr );
if( needs_dump )
{
llvm::raw_os_ostream stream(std::cout);
module->print( stream, nullptr );
}
llvm::EngineBuilder builder( std::move(module) );
llvm::ExecutionEngine* const engine= builder.create();
// llvm engine builder uses "new" operator inside it.
// So, we can correctly use unique_ptr for engine, because unique_ptr uses "delete" operator in destructor.
U_TEST_ASSERT( engine != nullptr );
return EnginePtr(engine);
}
bool HaveError( const std::vector<CodeBuilderError>& errors, const CodeBuilderErrorCode code, const unsigned int line )
{
for( const CodeBuilderError& error : errors )
{
if( error.code == code && error.src_loc.GetLine() == line )
return true;
}
return false;
}
} // namespace U
// Entry point for tests executable.
int main(int argc, char* argv[])
{
using namespace U;
const llvm::InitLLVM llvm_initializer(argc, argv);
const TestsFuncsContainer& funcs_container= GetTestsFuncsContainer();
std::cout << "Run " << funcs_container.size() << " Ü tests" << std::endl << std::endl;
unsigned int passed= 0u;
unsigned int disabled= 0u;
unsigned int failed= 0u;
unsigned int filtered= 0u;
for(const TestFuncData& func_data : funcs_container )
{
if( !FilterTest( func_data.name ) )
{
filtered++;
continue;
}
try
{
func_data.func();
++passed;
}
catch( const DisableTestException& )
{
// std::cout << "Test " << func_data.name << " disabled\n";
disabled++;
}
catch( const TestException& ex )
{
std::cout << "Test " << func_data.name << " failed: " << ex.what() << "\n" << std::endl;
failed++;
};
// We must kill ALL static internal llvm variables after each test.
llvm::llvm_shutdown();
}
std::cout << std::endl <<
passed << " tests passed\n" <<
disabled << " tests disabled\n" <<
filtered << " tests filtered\n" <<
failed << " tests failed" << std::endl;
return -int(failed);
}
| 27.985915 | 138 | 0.739809 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.