hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4c3d92eacb1af94282bc230c93323753495e4673 | 671 | cpp | C++ | LeetCode/198_house_robber/rob.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | LeetCode/198_house_robber/rob.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | LeetCode/198_house_robber/rob.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
std::vector<int> dp (nums.size(), 0);
dp[0] = nums[0];
dp[1] = nums[1];
if (nums.size() == 2) return max(dp[0], dp[1]);
int maxMoney = max(dp[0], dp[1]);
int maxBeforeNeighbour = 0;
for (int i = 2; i < nums.size(); i++) {
int neighbour = dp[i-1];
maxBeforeNeighbour = max(maxBeforeNeighbour, dp[i-2]);
maxMoney = max(nums[i]+maxBeforeNeighbour,neighbour);
dp[i] = maxMoney;
}
return maxMoney;
}
}; | 33.55 | 66 | 0.491803 | harveyc95 |
4c48ce428d67d135060b987cb097f2a7e4f0bf96 | 3,786 | cpp | C++ | tests/sort_strings_example.cpp | kurpicz/tlx | a9a8a76c40a734b1f771d6eba482ba7166f1f6b4 | [
"BSL-1.0"
] | 284 | 2017-02-26T08:49:15.000Z | 2022-03-30T21:55:37.000Z | tests/sort_strings_example.cpp | xiao2mo/tlx | b311126e670753897c1defceeaa75c83d2d9531a | [
"BSL-1.0"
] | 24 | 2017-09-05T21:02:41.000Z | 2022-03-07T10:09:59.000Z | tests/sort_strings_example.cpp | xiao2mo/tlx | b311126e670753897c1defceeaa75c83d2d9531a | [
"BSL-1.0"
] | 62 | 2017-02-23T12:29:27.000Z | 2022-03-31T07:45:59.000Z | /*******************************************************************************
* tests/sort_strings_example.cpp
*
* Part of tlx - http://panthema.net/tlx
*
* Copyright (C) 2020 Timo Bingmann <[email protected]>
*
* All rights reserved. Published under the Boost Software License, Version 1.0
******************************************************************************/
#include <tlx/cmdline_parser.hpp>
#include <tlx/simple_vector.hpp>
#include <tlx/string/format_iec_units.hpp>
#include <tlx/timestamp.hpp>
#include <tlx/sort/strings.hpp>
#include <tlx/sort/strings_parallel.hpp>
#include <cstring>
#include <fstream>
#include <iostream>
int main(int argc, char* argv[]) {
tlx::CmdlineParser cp;
// add description
cp.set_description("Example program to read a file and sort its lines.");
bool parallel = false;
cp.add_flag('p', "parallel", parallel, "sort with parallel algorithm");
// add a required parameter
std::string file;
cp.add_param_string("file", file, "A file to process");
// process command line
if (!cp.process(argc, argv))
return -1;
std::cerr << "Opening " << file << std::endl;
std::ifstream in(file.c_str());
if (!in.good()) {
std::cerr << "Error opening file: " << strerror(errno) << std::endl;
return -1;
}
if (!in.seekg(0, std::ios::end).good()) {
std::cerr << "Error seeking to end of file: " << strerror(errno)
<< std::endl;
return -1;
}
size_t size = in.tellg();
// allocate uninitialized memory area and string pointer array
tlx::simple_vector<uint8_t> data(size + 8);
std::vector<uint8_t*> strings;
// read file and make string pointer array
double ts1_read = tlx::timestamp();
std::cerr << "Reading " << size << " bytes" << std::endl;
in.seekg(0, std::ios::beg);
// first string pointer
strings.push_back(data.data() + 0);
size_t pos = 0;
while (pos < size) {
size_t rem = std::min<size_t>(2 * 1024 * 1024u, size - pos);
in.read(reinterpret_cast<char*>(data.data() + pos), rem);
uint8_t* chunk = data.data() + pos;
for (size_t i = 0; i < rem; ++i) {
if (chunk[i] == '\n') {
chunk[i] = 0;
if (pos + i + 1 < size) {
strings.push_back(chunk + i + 1);
}
}
else if (chunk[i] == '\0') {
if (pos + i + 1 < size) {
strings.push_back(chunk + i + 1);
}
}
}
pos += rem;
}
// final zero termination
data[size] = 0;
double ts2_read = tlx::timestamp();
std::cerr << "Reading took " << ts2_read - ts1_read << " seconds at "
<< tlx::format_iec_units(size / (ts2_read - ts1_read)) << "B/s"
<< std::endl;
std::cerr << "Found " << strings.size() << " strings to sort." << std::endl;
// sort
double ts1_sort = tlx::timestamp();
{
if (parallel)
tlx::sort_strings_parallel(strings);
else
tlx::sort_strings(strings);
}
double ts2_sort = tlx::timestamp();
std::cerr << "Sorting took " << ts2_sort - ts1_sort << " seconds."
<< std::endl;
// output sorted strings
double ts1_write = tlx::timestamp();
for (size_t i = 0; i < strings.size(); ++i) {
std::cout << strings[i] << '\n';
}
double ts2_write = tlx::timestamp();
std::cerr << "Writing took " << ts2_write - ts1_write << " seconds at "
<< tlx::format_iec_units(size / (ts2_write - ts1_write)) << "/s"
<< std::endl;
return 0;
}
/******************************************************************************/
| 28.900763 | 80 | 0.51215 | kurpicz |
4c48f3a0894321dcd250130dd421e2c59419090d | 128 | hpp | C++ | Vendor/GLM/glm/ext/vector_uint4.hpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | 2 | 2022-01-11T21:15:31.000Z | 2022-02-22T21:14:33.000Z | Vendor/GLM/glm/ext/vector_uint4.hpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | null | null | null | Vendor/GLM/glm/ext/vector_uint4.hpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:1afbf32485cf310fb8abd8f9610be2c7fef1fd71a5c4495cad4b942c74832b16
size 417
| 32 | 75 | 0.882813 | wdrDarx |
4c4be30e3878443d9effb9a9e22ae0838d6e87d2 | 2,439 | hpp | C++ | src/mfx/dsp/shape/DistBounce.hpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/dsp/shape/DistBounce.hpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/dsp/shape/DistBounce.hpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | /*****************************************************************************
DistBounce.hpp
Author: Laurent de Soras, 2018
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if ! defined (mfx_dsp_shape_DistBounce_CODEHEADER_INCLUDED)
#define mfx_dsp_shape_DistBounce_CODEHEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include <algorithm>
namespace mfx
{
namespace dsp
{
namespace shape
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
float DistBounce::process_sample (float x)
{
// Updates the current ball position according ot its speed
_pos += _speed;
float speed_max_loc = _speed_max;
// If the ball falls under the floor, makes it bounce
if (_pos < x)
{
_pos = x;
speed_max_loc = bounce (x);
}
// Also makes it bounce if it goes over the ceiling
else
{
const float tunnel_top = x + _tunnel_height;
if (_pos > tunnel_top)
{
_pos = tunnel_top;
speed_max_loc = bounce (x);
}
}
// Speed is updated one sample too late with regard to the gravity.
_speed -= _grav; // Updates the ball speed according to the gravity
_speed = std::min (_speed, speed_max_loc);
_prev_val = x;
return _pos;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
float DistBounce::bounce (float val)
{
// Computes the ball speed according to the bounce angle on the curve and
// bounce rate.
const float slope = val - _prev_val;
_speed = slope + (slope - _speed) * _bounce_rate;
// Prevents ball to elevate with an exagerated velocity, which would get
// it down very slowly (and would cut audio by saturation)
const float speed_max_loc = std::max (slope, _speed_max);
return speed_max_loc;
}
} // namespace shape
} // namespace dsp
} // namespace mfx
#endif // mfx_dsp_shape_DistBounce_CODEHEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 21.584071 | 78 | 0.563346 | mikelange49 |
4c53e89752572fe348dd8a7fdc646518d5d98b48 | 12,660 | cc | C++ | src/Utilities/iterateIdealH.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Utilities/iterateIdealH.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Utilities/iterateIdealH.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //------------------------------------------------------------------------------
// Iterate the ideal H algorithm to converge on a new H field.
// This routine replaces the H field in place.
//------------------------------------------------------------------------------
#include "iterateIdealH.hh"
#include "Field/FieldList.hh"
#include "NodeList/SmoothingScaleBase.hh"
#include "Utilities/allReduce.hh"
#include "Distributed/Communicator.hh"
#include "Geometry/GeometryRegistrar.hh"
#include <ctime>
using std::vector;
using std::string;
using std::pair;
using std::make_pair;
using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::max;
using std::abs;
namespace Spheral {
template<typename Dimension>
void
iterateIdealH(DataBase<Dimension>& dataBase,
const vector<Boundary<Dimension>*>& boundaries,
const TableKernel<Dimension>& W,
const SmoothingScaleBase<Dimension>& smoothingScaleMethod,
const int maxIterations,
const double tolerance,
const double nPerhForIteration,
const bool sphericalStart,
const bool fixDeterminant) {
typedef typename Dimension::Scalar Scalar;
typedef typename Dimension::Vector Vector;
typedef typename Dimension::SymTensor SymTensor;
// Start the timing.
const auto t0 = clock();
// Extract the state we care about.
const auto pos = dataBase.fluidPosition();
auto m = dataBase.fluidMass();
auto rho = dataBase.fluidMassDensity();
auto H = dataBase.fluidHfield();
// If we're using the fixDeterminant, take a snapshot of the input H determinants.
auto Hdet0 = dataBase.newFluidFieldList(double());
if (fixDeterminant) {
for (auto itr = dataBase.internalNodeBegin();
itr != dataBase.internalNodeEnd();
++itr) Hdet0(itr) = H(itr).Determinant();
}
// Store the input nperh for each NodeList.
// If we're rescaling the nodes per h for our work, make a cut at it.
vector<double> nperh0;
for (auto nodeListItr = dataBase.fluidNodeListBegin();
nodeListItr != dataBase.fluidNodeListEnd();
++nodeListItr) {
const auto nperh = (*nodeListItr)->nodesPerSmoothingScale();
nperh0.push_back(nperh);
if (distinctlyGreaterThan(nPerhForIteration, 0.0)) {
auto& Hfield = **(H.fieldForNodeList(**nodeListItr));
Hfield *= Dimension::rootnu(nperh/nPerhForIteration);
(*nodeListItr)->nodesPerSmoothingScale(nPerhForIteration);
}
}
CHECK(nperh0.size() == dataBase.numFluidNodeLists());
// If we are both fixing the H determinant and rescaling the nodes per h,
// we need a snapshot of the rescaled H determinant as well.
auto Hdet1 = dataBase.newFluidFieldList(double());
if (fixDeterminant) {
for (auto itr = dataBase.internalNodeBegin();
itr != dataBase.internalNodeEnd();
++itr) Hdet1(itr) = H(itr).Determinant();
}
// If requested, start by making all the H's round (volume preserving).
if (sphericalStart) {
for (auto itr = dataBase.internalNodeBegin();
itr != dataBase.internalNodeEnd();
++itr) {
const auto Hdeti = H(itr).Determinant();
const auto Hi = Dimension::rootnu(Hdeti) * SymTensor::one;
H(itr) = Hi;
}
}
// Build a list of flags to indicate which nodes have been completed.
auto flagNodeDone = dataBase.newFluidFieldList(0, "node completed");
// Iterate until we either hit the max iterations or the H's achieve convergence.
const auto numNodeLists = dataBase.numFluidNodeLists();
auto maxDeltaH = 2.0*tolerance;
auto itr = 0;
while (itr < maxIterations and maxDeltaH > tolerance) {
++itr;
maxDeltaH = 0.0;
// flagNodeDone = 0;
// Remove any old ghost node information from the NodeLists.
for (auto k = 0u; k < numNodeLists; ++k) {
auto nodeListPtr = *(dataBase.fluidNodeListBegin() + k);
nodeListPtr->numGhostNodes(0);
nodeListPtr->neighbor().updateNodes();
}
// Enforce boundary conditions.
for (auto k = 0u; k < boundaries.size(); ++k) {
auto boundaryPtr = *(boundaries.begin() + k);
boundaryPtr->setAllGhostNodes(dataBase);
boundaryPtr->applyFieldListGhostBoundary(m);
boundaryPtr->applyFieldListGhostBoundary(rho);
boundaryPtr->finalizeGhostBoundary();
for (auto nodeListItr = dataBase.fluidNodeListBegin();
nodeListItr != dataBase.fluidNodeListEnd();
++nodeListItr) {
(*nodeListItr)->neighbor().updateNodes();
}
}
// Prepare a FieldList to hold the new H.
FieldList<Dimension, SymTensor> H1(H);
H1.copyFields();
auto zerothMoment = dataBase.newFluidFieldList(0.0, "zerothMoment");
auto secondMoment = dataBase.newFluidFieldList(SymTensor::zero, "secondMoment");
// Get the new connectivity.
dataBase.updateConnectivityMap(false, false, false);
const auto& connectivityMap = dataBase.connectivityMap();
const auto& pairs = connectivityMap.nodePairList();
const auto npairs = pairs.size();
// Walk the pairs.
#pragma omp parallel
{
typename SpheralThreads<Dimension>::FieldListStack threadStack;
auto zerothMoment_thread = zerothMoment.threadCopy(threadStack);
auto secondMoment_thread = secondMoment.threadCopy(threadStack);
int i, j, nodeListi, nodeListj;
Scalar ri, rj, mRZi, mRZj, Wi, gWi, Wj, gWj;
Vector xij, etai, etaj, gradWi, gradWj;
SymTensor thpt;
#pragma omp for
for (auto k = 0u; k < npairs; ++k) {
i = pairs[k].i_node;
j = pairs[k].j_node;
nodeListi = pairs[k].i_list;
nodeListj = pairs[k].j_list;
// Anything to do?
if (flagNodeDone(nodeListi, i) == 0 or flagNodeDone(nodeListj, j) == 0) {
const auto& posi = pos(nodeListi, i);
const auto& Hi = H(nodeListi, i);
const auto mi = m(nodeListi, i);
const auto rhoi = rho(nodeListi, i);
const auto& posj = pos(nodeListj, j);
const auto& Hj = H(nodeListj, j);
const auto mj = m(nodeListj, j);
const auto rhoj = rho(nodeListj, j);
// Compute the node-node weighting
auto fweightij = 1.0;
if (nodeListi != nodeListj) {
if (GeometryRegistrar::coords() == CoordinateType::RZ){
ri = abs(posi.y());
rj = abs(posj.y());
mRZi = mi/(2.0*M_PI*ri);
mRZj = mj/(2.0*M_PI*rj);
fweightij = mRZj*rhoi/(mRZi*rhoj);
} else {
fweightij = mj*rhoi/(mi*rhoj);
}
}
xij = posi - posj;
etai = Hi*xij;
etaj = Hj*xij;
thpt = xij.selfdyad()/(xij.magnitude2() + 1.0e-10);
std::tie(Wi, gWi) = W.kernelAndGradValue(etai.magnitude(), 1.0);
gradWi = gWi*Hi*etai.unitVector();
std::tie(Wj, gWj) = W.kernelAndGradValue(etaj.magnitude(), 1.0);
gradWj = gWj*Hj*etaj.unitVector();
// Increment the moments
zerothMoment_thread(nodeListi, i) += fweightij* std::abs(gWi);
zerothMoment_thread(nodeListj, j) += 1.0/fweightij*std::abs(gWj);
secondMoment_thread(nodeListi, i) += fweightij* gradWi.magnitude2()*thpt;
secondMoment_thread(nodeListj, j) += 1.0/fweightij*gradWj.magnitude2()*thpt;
}
}
// Do the thread reduction for zeroth and second moments.
threadReduceFieldLists<Dimension>(threadStack);
} // OMP parallel
// Finish the moments and measure the new H.
for (auto nodeListi = 0u; nodeListi < numNodeLists; ++nodeListi) {
const auto nodeListPtr = *(dataBase.fluidNodeListBegin() + nodeListi);
const auto ni = nodeListPtr->numInternalNodes();
const auto hmin = nodeListPtr->hmin();
const auto hmax = nodeListPtr->hmax();
const auto hminratio = nodeListPtr->hminratio();
const auto nPerh = nodeListPtr->nodesPerSmoothingScale();
#pragma omp parallel for
for (auto i = 0u; i < ni; ++i) {
if (flagNodeDone(nodeListi, i) == 0) {
zerothMoment(nodeListi, i) = Dimension::rootnu(zerothMoment(nodeListi, i));
H1(nodeListi, i) = smoothingScaleMethod.newSmoothingScale(H(nodeListi, i),
pos(nodeListi, i),
zerothMoment(nodeListi, i),
secondMoment(nodeListi, i),
W,
hmin,
hmax,
hminratio,
nPerh,
connectivityMap,
nodeListi,
i);
// If we are preserving the determinant, do it.
if (fixDeterminant) {
H1(nodeListi, i) *= Dimension::rootnu(Hdet1(nodeListi, i)/H1(nodeListi, i).Determinant());
CHECK(fuzzyEqual(H1(nodeListi, i).Determinant(), Hdet1(nodeListi, i)));
}
// Check how much this H has changed.
const auto H1sqrt = H1(nodeListi, i).sqrt();
const auto phi = (H1sqrt*H(nodeListi, i).Inverse()*H1sqrt).Symmetric().eigenValues();
const auto phimin = phi.minElement();
const auto phimax = phi.maxElement();
const auto deltaHi = max(abs(phimin - 1.0), abs(phimax - 1.0));
if (deltaHi <= tolerance) flagNodeDone(nodeListi, i) = 1;
maxDeltaH = max(maxDeltaH, deltaHi);
}
}
}
// Assign the new H's.
H.assignFields(H1);
// Globally reduce the max H change.
maxDeltaH = allReduce(maxDeltaH, MPI_MAX, Communicator::communicator());
// Output the statitics.
if (Process::getRank() == 0)
cerr << "iterateIdealH: (iteration, deltaH) = ("
<< itr << ", "
<< maxDeltaH << ")"
<< endl;
}
// If we have rescaled the nodes per h, now we have to iterate the H determinant
// to convergence with the proper nperh.
if (distinctlyGreaterThan(nPerhForIteration, 0.0)) {
// Reset the nperh.
size_t k = 0;
for (auto nodeListItr = dataBase.fluidNodeListBegin();
nodeListItr != dataBase.fluidNodeListEnd();
++nodeListItr, ++k) {
CHECK(k < nperh0.size());
//const double nperh = nperh0[k];
// Field<Dimension, SymTensor>& Hfield = **(H.fieldForNodeList(**nodeListItr));
// Hfield *= Dimension::rootnu(nPerhForIteration/nperh);
(*nodeListItr)->nodesPerSmoothingScale(nperh0[k]);
}
CHECK(k == nperh0.size());
}
// If we're fixing the determinant, restore them.
if (fixDeterminant) {
for (auto itr = dataBase.internalNodeBegin();
itr != dataBase.internalNodeEnd();
++itr) {
H(itr) *= Dimension::rootnu(Hdet0(itr)/H(itr).Determinant());
ENSURE(fuzzyEqual(H(itr).Determinant(), Hdet0(itr), 1.0e-10));
}
}
// Leave the boundary conditions properly enforced.
for (auto nodeListItr = dataBase.fluidNodeListBegin();
nodeListItr != dataBase.fluidNodeListEnd();
++nodeListItr) {
(*nodeListItr)->numGhostNodes(0);
(*nodeListItr)->neighbor().updateNodes();
}
for (auto boundaryItr = boundaries.begin();
boundaryItr != boundaries.end();
++boundaryItr) {
(*boundaryItr)->setAllGhostNodes(dataBase);
(*boundaryItr)->finalizeGhostBoundary();
for (typename DataBase<Dimension>::FluidNodeListIterator nodeListItr = dataBase.fluidNodeListBegin();
nodeListItr != dataBase.fluidNodeListEnd();
++nodeListItr) {
(*nodeListItr)->neighbor().updateNodes();
}
}
for (auto boundaryItr = boundaries.begin();
boundaryItr != boundaries.end();
++boundaryItr) {
(*boundaryItr)->applyFieldListGhostBoundary(m);
}
for (auto boundaryItr = boundaries.begin();
boundaryItr != boundaries.end();
++boundaryItr) {
(*boundaryItr)->finalizeGhostBoundary();
}
// Report the final timing.
const auto t1 = clock();
if (Process::getRank() == 0)
cerr << "iterateIdealH: required a total of "
<< (t1 - t0)/CLOCKS_PER_SEC
<< " seconds."
<< endl;
}
}
| 37.455621 | 105 | 0.584834 | jmikeowen |
4c5707c14fa320d7b997f11c6df0b19a42788ebe | 3,696 | cpp | C++ | src/nbl/video/IPhysicalDevice.cpp | deprilula28/Nabla | 6b5de216221718191713dcf6de8ed6407182ddf0 | [
"Apache-2.0"
] | null | null | null | src/nbl/video/IPhysicalDevice.cpp | deprilula28/Nabla | 6b5de216221718191713dcf6de8ed6407182ddf0 | [
"Apache-2.0"
] | null | null | null | src/nbl/video/IPhysicalDevice.cpp | deprilula28/Nabla | 6b5de216221718191713dcf6de8ed6407182ddf0 | [
"Apache-2.0"
] | null | null | null | #include "nbl/video/IPhysicalDevice.h"
namespace nbl::video
{
IPhysicalDevice::IPhysicalDevice(core::smart_refctd_ptr<system::ISystem>&& s, core::smart_refctd_ptr<asset::IGLSLCompiler>&& glslc) :
m_system(std::move(s)), m_GLSLCompiler(std::move(glslc))
{
}
void IPhysicalDevice::addCommonGLSLDefines(std::ostringstream& pool, const bool runningInRenderdoc)
{
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_UBO_SIZE",m_limits.maxUBOSize);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_SSBO_SIZE",m_limits.maxSSBOSize);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_BUFFER_VIEW_TEXELS",m_limits.maxBufferViewSizeTexels);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_BUFFER_SIZE",m_limits.maxBufferSize);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_IMAGE_ARRAY_LAYERS",m_limits.maxImageArrayLayers);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_PER_STAGE_SSBO_COUNT",m_limits.maxPerStageSSBOs);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_SSBO_COUNT",m_limits.maxSSBOs);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_UBO_COUNT",m_limits.maxUBOs);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_TEXTURE_COUNT",m_limits.maxTextures);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_STORAGE_IMAGE_COUNT",m_limits.maxStorageImages);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_DRAW_INDIRECT_COUNT",m_limits.maxDrawIndirectCount);
addGLSLDefineToPool(pool,"NBL_LIMIT_MIN_POINT_SIZE",m_limits.pointSizeRange[0]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_POINT_SIZE",m_limits.pointSizeRange[1]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MIN_LINE_WIDTH",m_limits.lineWidthRange[0]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_LINE_WIDTH",m_limits.lineWidthRange[1]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_VIEWPORTS",m_limits.maxViewports);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_VIEWPORT_WIDTH",m_limits.maxViewportDims[0]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_VIEWPORT_HEIGHT",m_limits.maxViewportDims[1]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_WORKGROUP_SIZE_X",m_limits.maxWorkgroupSize[0]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_WORKGROUP_SIZE_Y",m_limits.maxWorkgroupSize[1]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_WORKGROUP_SIZE_Z",m_limits.maxWorkgroupSize[2]);
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_OPTIMALLY_RESIDENT_WORKGROUP_INVOCATIONS",m_limits.maxOptimallyResidentWorkgroupInvocations);
// TODO: Need upper and lower bounds on workgroup sizes!
// TODO: Need to know if subgroup size is constant/known
addGLSLDefineToPool(pool,"NBL_LIMIT_SUBGROUP_SIZE",m_limits.subgroupSize);
// TODO: @achal test examples 14 and 48 on all APIs and GPUs
addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_RESIDENT_INVOCATIONS",m_limits.maxResidentInvocations);
// TODO: Add feature defines
if (runningInRenderdoc)
addGLSLDefineToPool(pool,"NBL_RUNNING_IN_RENDERDOC");
}
bool IPhysicalDevice::validateLogicalDeviceCreation(const ILogicalDevice::SCreationParams& params) const
{
using range_t = core::SRange<const ILogicalDevice::SQueueCreationParams>;
range_t qcis(params.queueParams, params.queueParams+params.queueParamsCount);
for (const auto& qci : qcis)
{
if (qci.familyIndex >= m_qfamProperties->size())
return false;
const auto& qfam = (*m_qfamProperties)[qci.familyIndex];
if (qci.count == 0u)
return false;
if (qci.count > qfam.queueCount)
return false;
for (uint32_t i = 0u; i < qci.count; ++i)
{
const float priority = qci.priorities[i];
if (priority < 0.f)
return false;
if (priority > 1.f)
return false;
}
}
return true;
}
} | 42.976744 | 137 | 0.761093 | deprilula28 |
4c586bbb63dbe59906ec2df3117c23c85a6c9fc1 | 6,077 | hpp | C++ | src/core/pin_mesh_base.hpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 11 | 2016-03-31T17:46:15.000Z | 2022-02-14T01:07:56.000Z | src/core/pin_mesh_base.hpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 3 | 2016-04-04T16:40:47.000Z | 2019-10-16T22:22:54.000Z | src/core/pin_mesh_base.hpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 3 | 2019-10-16T22:20:15.000Z | 2019-11-28T11:59:03.000Z | /*
Copyright 2016 Mitchell Young
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.
*/
#pragma once
#include <string>
#include "util/global_config.hpp"
#include "util/pugifwd.hpp"
#include "geometry/geom.hpp"
#include "position.hpp"
namespace mocc {
/**
* \ref PinMesh is a virtual class, which provides methods for performing
* ray tracing and accessing data in common between all types of pin mesh,
* such as region volumes, x and y pitch, etc.
*/
class PinMesh {
public:
PinMesh(const pugi::xml_node &input);
virtual ~PinMesh()
{
}
int id() const
{
return id_;
}
int n_reg() const
{
return n_reg_;
}
int n_xsreg() const
{
return n_xsreg_;
}
real_t pitch_x() const
{
return pitch_x_;
}
real_t pitch_y() const
{
return pitch_y_;
}
real_t area() const
{
return pitch_x_ * pitch_y_;
}
const VecF &areas() const
{
return areas_;
}
/**
* \param[in] p1 the entry point of the ray.
* \param[in] p2 the exit point of the ray.
* \param[in] first_reg the index of the first FSR in the pin mesh.
* \param[in,out] s the vector of ray segment lengths to be modified.
* \param[in,out] reg the vector of ray segment FSR indices to be
* modified.
*
* \returns The number of segments that pass through pin geometry
* (useful for CMFD data).
*
* Given an entry and exit point, which should be on the boundary of the
* pin (in pin-local coordinates), and the index of the first FSR in the
* pin, append values to the vectors of segment length and corresponding
* region index.
*
*
* The segment lengths are uncorrected, which is to say that they are
* the true lengths of the rays as they pass through the mesh.
* Therefore, summing the volume of the segments in each FSR is not
* guaranteed to return the correct FSR volume. Make sure to correct for
* this after tracing all of the rays in a given angle.
*/
virtual int trace(Point2 p1, Point2 p2, int first_reg, VecF &s,
VecI ®) const = 0;
/**
* Find the pin-local region index corresponding to the point provided.
*
* \param[in] p the \ref Point2 for which to find the FSR index
*
* Given a point in pin-local coordinates, return the mesh region index
* in which the point resides
*/
virtual int find_reg(Point2 p) const = 0;
/**
* \brief Find a pin-local region index corresponding to the \ref Point2
* and \ref Direction provided
*
* \param p a \ref Point2 containing the pin-local coordinates to look
* up a region for.
* \param dir a \ref Direction of travel, used to establish sense w.r.t.
* internal surfaces.
*
* This is similar to PinMeshBase::find_reg(Point2), except that it
* handles the case where the point \p p lies directly on one of the
* surfaces in a well-defined manner. In such cases, the returned region
* index should refer to the region on the side of the surface pointed
* to by \p dir.
*/
virtual int find_reg(Point2 p, Direction dir) const = 0;
/**
* Return the number of flat source regions corresponding to an XS
* region (indexed pin-locally).
*/
virtual size_t n_fsrs(unsigned int xsreg) const = 0;
/**
* \brief Insert hte \ref PinMesh into the passed ostream.
*
* This is useful to be able to use \c operator<< on a polymorphic \ref
* PinMesh and have it work as expected.
*/
virtual void print(std::ostream &os) const;
/**
* \brief Return the distance to the nearest surface in the pin mesh,
* and the boundary of the pin if that surface is at the edge of the
* pin.
*
* \param p a Point2 containing the location from which to measure
* \param dir a Direction containing the direction in which to measure
* \param coincident whether the passed point is to be considered coincident
* with the surface. This is useful for preventing repeated, logically
* identical intersections
*/
virtual std::pair<real_t, bool>
distance_to_surface(Point2 p, Direction dir, int &coincident) const = 0;
/**
* This essentially wraps the \ref Point2 version
*/
std::pair<real_t, bool> distance_to_surface(Point3 p, Direction dir,
int &coincident) const
{
return this->distance_to_surface(p.to_2d(), dir, coincident);
}
/**
* \brief Return a string containing PyCairo commands to draw the \ref
* PinMesh.
*/
virtual std::string draw() const = 0;
/**
* \brief Provide stream insertion support.
*
* Calls the \ref PinMesh::print() routine, which is virtual, allowing
* for polymorphism.
*/
friend std::ostream &operator<<(std::ostream &os, const PinMesh &pm);
protected:
int id_;
int n_reg_;
int n_xsreg_;
real_t pitch_x_;
real_t pitch_y_;
VecF areas_;
};
/**
* This is a simple struct that contains a const pointer to a \ref PinMesh,
* along with a Position describing its location. This is essentially a
* useful tuple for returning both values from a lookup function (see
* \ref CoreMesh::get_pinmesh() and \ref Plane::get_pinmesh()).
*/
struct PinMeshTuple {
PinMeshTuple(Position pos, const PinMesh *pm) : position(pos), pm(pm)
{
}
Position position;
const PinMesh *pm;
};
}
| 30.084158 | 80 | 0.648017 | tp-ntouran |
4c61eb3fc7ad06b5159b7ffb6a1d040791b07154 | 604 | cpp | C++ | HDU/5443.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | 1 | 2019-09-07T15:56:05.000Z | 2019-09-07T15:56:05.000Z | HDU/5443.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | HDU/5443.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | //httpacm.hdu.edu.cnshowproblem.phppid=5443
#include <iostream>
using namespace std;
int cases, water, query;
int main()
{
scanf("%d", &cases);
while(cases--)
{
scanf("%d", &water);
int W[water];
for(int x=0; x<water; x++)
scanf("%d", &W[x]);
scanf("%d", &query);
int Max, front, back;
for(int x=0; x<query; x++)
{
Max=0;
scanf("%d %d", &front, &back);
for(int x=front-1; x<back; x++)
Max=max(Max, W[x]);
printf("%d\n", Max);
}
}
return 0;
}
| 20.827586 | 43 | 0.440397 | Superdanby |
4c6412b497606b2ef8f4b66092e7ae1d9fb47cca | 2,339 | cc | C++ | src/arch/beos/cbm5x0ui.cc | swingflip/C64_mini_VICE | 7a6d9d41ae60409a2bb985bb8d6324a7269a0daa | [
"Apache-2.0"
] | 2 | 2018-11-15T19:52:34.000Z | 2022-01-17T19:45:01.000Z | src/arch/beos/cbm5x0ui.cc | Classicmods/C64_mini_VICE | 7a6d9d41ae60409a2bb985bb8d6324a7269a0daa | [
"Apache-2.0"
] | null | null | null | src/arch/beos/cbm5x0ui.cc | Classicmods/C64_mini_VICE | 7a6d9d41ae60409a2bb985bb8d6324a7269a0daa | [
"Apache-2.0"
] | 3 | 2019-06-30T05:37:04.000Z | 2021-12-04T17:12:35.000Z | /*
* cbm5x0ui.cc - CBM5x0-specific user interface.
*
* Written by
* Marcus Sutton <[email protected]>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program 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 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#include "vice.h"
#include <Message.h>
#include <stdio.h>
extern "C" {
#include "cbm2ui.h"
#include "constants.h"
#include "ui.h"
#include "ui_cbm2.h"
#include "ui_sid.h"
#include "ui_vicii.h"
#include "video.h"
}
ui_menu_toggle cbm5x0_ui_menu_toggles[] = {
{ "VICIIDoubleSize", MENU_TOGGLE_DOUBLESIZE },
{ "VICIIDoubleScan", MENU_TOGGLE_DOUBLESCAN },
{ "VICIIVideoCache", MENU_TOGGLE_VIDEOCACHE },
{ NULL, 0 }
};
ui_res_possible_values cbm5x0RenderFilters[] = {
{ VIDEO_FILTER_NONE, MENU_RENDER_FILTER_NONE },
{ VIDEO_FILTER_CRT, MENU_RENDER_FILTER_CRT_EMULATION },
{ VIDEO_FILTER_SCALE2X, MENU_RENDER_FILTER_SCALE2X },
{ -1, 0 }
};
ui_res_value_list cbm5x0_ui_res_values[] = {
{ "VICIIFilter", cbm5x0RenderFilters },
{ NULL, NULL }
};
void cbm5x0_ui_specific(void *msg, void *window)
{
switch (((BMessage*)msg)->what) {
case MENU_CBM2_SETTINGS:
ui_cbm2();
break;
case MENU_VICII_SETTINGS:
ui_vicii();
break;
case MENU_SID_SETTINGS:
ui_sid(NULL);
break;
default: ;
}
}
int cbm5x0ui_init(void)
{
ui_register_machine_specific(cbm5x0_ui_specific);
ui_register_menu_toggles(cbm5x0_ui_menu_toggles);
ui_register_res_values(cbm5x0_ui_res_values);
ui_update_menus();
return 0;
}
void cbm5x0ui_shutdown(void)
{
}
| 26.280899 | 72 | 0.690038 | swingflip |
4c6bea12759255848c3d87615522d087bb847ad7 | 11,251 | hpp | C++ | contrib/TAMM/src/tamm/eigen_utils.hpp | smferdous1/gfcc | e7112c0dd60566266728e4d51ea8d30aea4b775d | [
"MIT"
] | 4 | 2020-10-14T17:43:00.000Z | 2021-06-21T08:23:01.000Z | contrib/TAMM/src/tamm/eigen_utils.hpp | smferdous1/gfcc | e7112c0dd60566266728e4d51ea8d30aea4b775d | [
"MIT"
] | 3 | 2020-06-03T19:54:30.000Z | 2022-03-10T22:59:30.000Z | contrib/TAMM/src/tamm/eigen_utils.hpp | smferdous1/gfcc | e7112c0dd60566266728e4d51ea8d30aea4b775d | [
"MIT"
] | 6 | 2020-06-08T03:54:16.000Z | 2022-03-02T17:47:51.000Z | #ifndef TAMM_EIGEN_UTILS_HPP_
#define TAMM_EIGEN_UTILS_HPP_
// Eigen matrix algebra library
#include "tamm/tamm.hpp"
#include <Eigen/Dense>
#include <unsupported/Eigen/CXX11/Tensor>
#undef I
using EigenTensorType=double;
using Matrix = Eigen::Matrix<EigenTensorType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
using Tensor1D = Eigen::Tensor<EigenTensorType, 1, Eigen::RowMajor>;
using Tensor2D = Eigen::Tensor<EigenTensorType, 2, Eigen::RowMajor>;
using Tensor3D = Eigen::Tensor<EigenTensorType, 3, Eigen::RowMajor>;
using Tensor4D = Eigen::Tensor<EigenTensorType, 4, Eigen::RowMajor>;
namespace tamm {
template<typename T, int ndim>
void patch_copy(std::vector<T>& sbuf,
Eigen::Tensor<T, ndim, Eigen::RowMajor>& etensor,
const std::array<int, ndim>& block_dims,
const std::array<int, ndim>& block_offset, bool t2e = true) {
assert(0);
}
template<typename T>
void patch_copy(std::vector<T>& sbuf,
Eigen::Tensor<T, 1, Eigen::RowMajor>& etensor,
const std::vector<size_t>& block_dims,
const std::vector<size_t>& block_offset, bool t2e = true) {
size_t c = 0;
for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0];
i++, c++) {
if(t2e)
etensor(i) = sbuf[c];
else
sbuf[c] = etensor(i);
}
}
template<typename T>
void patch_copy(std::vector<T>& sbuf,
Eigen::Tensor<T, 2, Eigen::RowMajor>& etensor,
const std::vector<size_t>& block_dims,
const std::vector<size_t>& block_offset, bool t2e = true) {
size_t c = 0;
for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) {
for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1];
j++, c++) {
if(t2e)
etensor(i, j) = sbuf[c];
else
sbuf[c] = etensor(i, j);
}
}
}
template<typename T>
void patch_copy(std::vector<T>& sbuf,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic,
Eigen::RowMajor>& etensor,
const std::vector<size_t>& block_dims,
const std::vector<size_t>& block_offset, bool t2e = true) {
size_t c = 0;
for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) {
for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1];
j++, c++) {
if(t2e)
etensor(i, j) = sbuf[c];
else
sbuf[c] = etensor(i, j);
}
}
}
template<typename T>
void patch_copy(std::vector<T>& sbuf,
Eigen::Tensor<T, 3, Eigen::RowMajor>& etensor,
const std::vector<size_t>& block_dims,
const std::vector<size_t>& block_offset, bool t2e = true) {
size_t c = 0;
for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) {
for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1];
j++) {
for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2];
k++, c++) {
if(t2e)
etensor(i, j, k) = sbuf[c];
else
sbuf[c] = etensor(i, j, k);
}
}
}
}
template<typename T>
void patch_copy(std::vector<T>& sbuf,
Eigen::Tensor<T, 4, Eigen::RowMajor>& etensor,
const std::vector<size_t>& block_dims,
const std::vector<size_t>& block_offset, bool t2e = true) {
size_t c = 0;
for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) {
for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1];
j++) {
for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2];
k++) {
for(size_t l = block_offset[3];
l < block_offset[3] + block_dims[3]; l++, c++) {
if(t2e)
etensor(i, j, k, l) = sbuf[c];
else
sbuf[c] = etensor(i, j, k, l);
}
}
}
}
}
template<typename T, int ndim>
Eigen::Tensor<T, ndim, Eigen::RowMajor> tamm_to_eigen_tensor(
const tamm::Tensor<T>& tensor) {
std::array<long, ndim> dims;
const auto& tindices = tensor.tiled_index_spaces();
for(int i = 0; i < ndim; i++) {
dims[i] = tindices[i].index_space().num_indices();
}
Eigen::Tensor<T, ndim, Eigen::RowMajor> etensor(dims);
etensor.setZero();
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, true);
}
return etensor;
}
template<typename T>
void tamm_to_eigen_tensor(
const tamm::Tensor<T>& tensor,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, true);
}
}
template<typename T, int ndim>
void tamm_to_eigen_tensor(const tamm::Tensor<T>& tensor,
Eigen::Tensor<T, ndim, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, true);
}
}
template<typename T, int ndim>
void eigen_to_tamm_tensor(tamm::Tensor<T>& tensor,
Eigen::Tensor<T, ndim, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
// tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, false);
tensor.put(blockid, buf);
}
}
template<typename T>
void eigen_to_tamm_tensor(
tamm::Tensor<T>& tensor,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
// tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, false);
tensor.put(blockid, buf);
}
}
template<typename T>
void eigen_to_tamm_tensor_acc(
tamm::Tensor<T>& tensor,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
// tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, false);
tensor.add(blockid, buf);
}
}
template<typename T>
void eigen_to_tamm_tensor_acc(
tamm::Tensor<T>& tensor,
Eigen::Tensor<T, 2, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
// tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, false);
tensor.add(blockid, buf);
}
}
template<typename T>
void eigen_to_tamm_tensor_acc(
tamm::Tensor<T>& tensor,
Eigen::Tensor<T, 3, Eigen::RowMajor>& etensor) {
for(const auto& blockid : tensor.loop_nest()) {
const tamm::TAMM_SIZE size = tensor.block_size(blockid);
std::vector<T> buf(size);
// tensor.get(blockid, buf);
auto block_dims = tensor.block_dims(blockid);
auto block_offset = tensor.block_offsets(blockid);
patch_copy<T>(buf, etensor, block_dims, block_offset, false);
tensor.add(blockid, buf);
}
}
template<typename T, typename fxn_t>
void call_eigen_matrix_fxn(const tamm::Tensor<T>& tensor, fxn_t fxn) {
tamm::Tensor<T> copy_t(tensor);
auto eigen_t = tamm_to_eigen_tensor<T, 2>(copy_t);
using eigen_matrix =
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
using eigen_map = Eigen::Map<eigen_matrix>;
const auto nrow = eigen_t.dimensions()[0];
const auto ncol = eigen_t.dimensions()[1];
eigen_map mapped_t(eigen_t.data(), nrow, ncol);
fxn(mapped_t);
}
template<int nmodes, typename T, typename matrix_type>
void eigen_matrix_to_tamm(matrix_type&& mat, tamm::Tensor<T>& t){
using tensor1_type = Eigen::Tensor<T, 1, Eigen::RowMajor>;
using tensor2_type = Eigen::Tensor<T, 2, Eigen::RowMajor>;
const auto nrows = mat.rows();
if constexpr(nmodes == 1){ //Actually a vector
tensor1_type t1(std::array<long int, 1>{nrows});
for(long int i = 0; i < nrows; ++i) t1(i) = mat(i);
eigen_to_tamm_tensor(t, t1);
}
else if constexpr(nmodes == 2){
const auto ncols = mat.cols();
tensor2_type t1(std::array<long int, 2>{nrows, ncols}) ;
for(long int i=0; i < nrows; ++i)
for(long int j =0; j< ncols; ++j)
t1(i, j) = mat(i, j);
eigen_to_tamm_tensor(t, t1);
}
}
template<typename T>
tamm::Tensor<T> retile_rank2_tensor(tamm::Tensor<T>& tensor, const tamm::TiledIndexSpace &t1, const tamm::TiledIndexSpace &t2) {
EXPECTS(tensor.num_modes() == 2);
//auto* ec_tmp = tensor.execution_context(); //TODO: figure out why this seg faults
tamm::ProcGroup pg = ProcGroup::create_coll(GA_MPI_Comm());
auto mgr = tamm::MemoryManagerGA::create_coll(pg);
tamm::Distribution_NW distribution;
tamm::ExecutionContext ec{pg,&distribution,mgr};
auto is1 = tensor.tiled_index_spaces()[0].index_space();
auto is2 = tensor.tiled_index_spaces()[1].index_space();
auto dim1 = is1.num_indices();
auto dim2 = is2.num_indices();
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> eigent(dim1,dim2);
tamm::Tensor<T> result{t1,t2};
tamm::Tensor<T>::allocate(&ec, result);
tamm_to_eigen_tensor(tensor,eigent);
eigen_to_tamm_tensor(result,eigent);
ec.pg().barrier();
return result;
}
}
#endif // TAMM_EIGEN_UTILS_HPP_
| 35.71746 | 128 | 0.607413 | smferdous1 |
4c705d4909c13e6b1fad2a89085c029747a42d7c | 11,419 | cc | C++ | quadris/grid.cc | kevinli9094/my_projects | fe38528e0cf3cebf1aba73fb69bca66a9c4d4ed7 | [
"MIT"
] | null | null | null | quadris/grid.cc | kevinli9094/my_projects | fe38528e0cf3cebf1aba73fb69bca66a9c4d4ed7 | [
"MIT"
] | null | null | null | quadris/grid.cc | kevinli9094/my_projects | fe38528e0cf3cebf1aba73fb69bca66a9c4d4ed7 | [
"MIT"
] | null | null | null | #include "grid.h"
#include "cell.h"
#include "textdisplay.h"
#include "block.h"
#include <iostream>
#include <string>
#include <sstream>
#include "window.h"
using namespace std;
Grid::Grid() : score(0), highscore(0), currentLevel(0){
W.fillRectangle(452, 0, 2, 814, Xwindow::Black);
W.drawString(470, 10, "Next:", Xwindow::Black);
W.drawString(470, 140, "Level:", Xwindow::Black);
W.drawString(470, 160, "Score:", Xwindow::Black);
W.drawString(470, 180, "Hi Score:", Xwindow::Black);
theGrid = new Cell*[179];
next = new Cell*[7];
for (int i = 0; i <= 179; i++){
theGrid[i] = new Cell;
theGrid[i]->setCoords(i / 10, i % 10, ((i % 10) * 45 + 2), ((i/ 10) * 45 + 2), 45, 45, &W);
}
for (int i = 0; i <= 7; i++){
next[i] = new Cell;
next[i]->setCoords(i / 4, i % 4, ((i % 4) * 45 + 472), ((i / 4) * 45 + 22), 45, 45, &W);
}
td = new TextDisplay();
}
Grid::~Grid() {
delete[] theGrid;
delete[] next;
delete td;
}
void Grid::settextonly(bool b){
this->textonly = b;
}
void Grid::setlevel(int i){
currentLevel = i;
}
int Grid::getcurrentLevel() {
return currentLevel;
}
int Grid::getscore() {
return score;
}
int Grid::gethighscore(){
return highscore;
}
void Grid::insertnext(Blocks *b){
for (int i = 0; i <= 7; i++) {
next[i]->blocktype = ' ';
}
next[(b->block1r - 2) * 4 + b->block1c]->blocktype = b->type;
next[(b->block2r - 2) * 4 + b->block2c]->blocktype = b->type;
next[(b->block3r - 2) * 4 + b->block3c]->blocktype = b->type;
next[(b->block4r - 2) * 4 + b->block4c]->blocktype = b->type;
}
void Grid::removeBlocks(Blocks *b){
theGrid[b->block1r * 10 + b->block1c]->blocktype = ' ';
theGrid[b->block2r * 10 + b->block2c]->blocktype = ' ';
theGrid[b->block3r * 10 + b->block3c]->blocktype = ' ';
theGrid[b->block4r * 10 + b->block4c]->blocktype = ' ';
theGrid[b->block1r * 10 + b->block1c]->notifyDisplay(*td);
theGrid[b->block2r * 10 + b->block2c]->notifyDisplay(*td);
theGrid[b->block3r * 10 + b->block3c]->notifyDisplay(*td);
theGrid[b->block4r * 10 + b->block4c]->notifyDisplay(*td);
theGrid[b->block1r * 10 + b->block1c]->lv = 0;
theGrid[b->block2r * 10 + b->block2c]->lv = 0;
theGrid[b->block3r * 10 + b->block3c]->lv = 0;
theGrid[b->block4r * 10 + b->block4c]->lv = 0;
}
void Grid::insertBlocks(Blocks *b){
theGrid[b->block1r * 10 + b->block1c]->blocktype = b->type;
theGrid[b->block2r * 10 + b->block2c]->blocktype = b->type;
theGrid[b->block3r * 10 + b->block3c]->blocktype = b->type;
theGrid[b->block4r * 10 + b->block4c]->blocktype = b->type;
theGrid[b->block1r * 10 + b->block1c]->notifyDisplay(*td);
theGrid[b->block2r * 10 + b->block2c]->notifyDisplay(*td);
theGrid[b->block3r * 10 + b->block3c]->notifyDisplay(*td);
theGrid[b->block4r * 10 + b->block4c]->notifyDisplay(*td);
theGrid[b->block1r * 10 + b->block1c]->lv = b->level;
theGrid[b->block2r * 10 + b->block2c]->lv = b->level;
theGrid[b->block3r * 10 + b->block3c]->lv = b->level;
theGrid[b->block4r * 10 + b->block4c]->lv = b->level;
}
bool Grid::isLose(Blocks *b) {
if ((theGrid[b->block1r * 10 + b->block1c]->getblocktype() == ' ') &
(theGrid[b->block2r * 10 + b->block2c]->getblocktype() == ' ') &
(theGrid[b->block3r * 10 + b->block3c]->getblocktype() == ' ') &
(theGrid[b->block4r * 10 + b->block4c]->getblocktype() == ' ')) {
return false;
}
return true;
}
void Grid::drop(Blocks *b){
this->removeBlocks(b);
int stopAt;
int i = 1;
bool done = false;
while (!done) {
if ((((b->block1r + i) == 17) |
((b->block2r + i) == 17) |
((b->block3r + i) == 17) |
((b->block4r + i) == 17)) &
((theGrid[(b->block1r + i) * 10 + b->block1c]->getblocktype() == ' ') &
(theGrid[(b->block2r + i) * 10 + b->block2c]->getblocktype() == ' ') &
(theGrid[(b->block3r + i) * 10 + b->block3c]->getblocktype() == ' ') &
(theGrid[(b->block4r + i) * 10 + b->block4c]->getblocktype() == ' '))){
i += 1;
done = true;
}
else if ((((b->block1r + i) == 17) |
((b->block2r + i) == 17) |
((b->block3r + i) == 17) |
((b->block4r + i) == 17))){
done = true;
}
else if ((theGrid[(b->block1r + i) * 10 + b->block1c]->getblocktype() != ' ') |
(theGrid[(b->block2r + i) * 10 + b->block2c]->getblocktype() != ' ') |
(theGrid[(b->block3r + i) * 10 + b->block3c]->getblocktype() != ' ') |
(theGrid[(b->block4r + i) * 10 + b->block4c]->getblocktype() != ' ')){
done = true;
}
else {
i += 1;
}
}
stopAt = i-1;
b->drop(stopAt);
this->insertBlocks(b);
theGrid[b->block1r * 10 + b->block1c]->addCell(theGrid[b->block2r * 10 + b->block2c]);
theGrid[b->block1r * 10 + b->block1c]->addCell(theGrid[b->block3r * 10 + b->block3c]);
theGrid[b->block1r * 10 + b->block1c]->addCell(theGrid[b->block4r * 10 + b->block4c]);
theGrid[b->block2r * 10 + b->block2c]->addCell(theGrid[b->block1r * 10 + b->block1c]);
theGrid[b->block2r * 10 + b->block2c]->addCell(theGrid[b->block3r * 10 + b->block3c]);
theGrid[b->block2r * 10 + b->block2c]->addCell(theGrid[b->block4r * 10 + b->block4c]);
theGrid[b->block3r * 10 + b->block3c]->addCell(theGrid[b->block1r * 10 + b->block1c]);
theGrid[b->block3r * 10 + b->block3c]->addCell(theGrid[b->block2r * 10 + b->block2c]);
theGrid[b->block3r * 10 + b->block3c]->addCell(theGrid[b->block4r * 10 + b->block4c]);
theGrid[b->block4r * 10 + b->block4c]->addCell(theGrid[b->block1r * 10 + b->block1c]);
theGrid[b->block4r * 10 + b->block4c]->addCell(theGrid[b->block2r * 10 + b->block2c]);
theGrid[b->block4r * 10 + b->block4c]->addCell(theGrid[b->block3r * 10 + b->block3c]);
int numOfLine = 0;
int lv0 = 0;
int lv1 = 0;
int lv2 = 0;
int lv3 = 0;
for (int k = 0; k <= 17; k++){
bool clear = true;
for (int i = 0; i <= 9; i++){
if (theGrid[k * 10 + i]->getblocktype() == ' ') {
clear = false;
}
}
if (clear) {
int num;
int level = 0;
for (int i = 0; i <= 9; i++){
num = theGrid[k * 10 + i]->getnum();
if (num == 0){
level = theGrid[k * 10 + i]->getlv();
if (level == 0) {
lv0 += 1;
}
if (level == 1) {
lv1 += 1;
}
if (level == 2) {
lv2 += 1;
}
if (level == 3) {
lv3 += 1;
}
}
else {
theGrid[k * 10 + i]->notifyOtherCells();
for (int j = 0; j < num; j++) {
theGrid[k * 10 + i]->restOfTheBlocks[j] = 0;
}
theGrid[k * 10 + i]->num = 0;
}
theGrid[k * 10 + i]->blocktype = ' ';
theGrid[k * 10 + i]->lv = 0;
}
numOfLine += 1;
Cell **tmp;
tmp = new Cell*[9];
for (int i = 0; i <= 9; i++) {
tmp[i] = theGrid[k * 10 + i];
}
for (int i = k; i > 0; i--) {
for (int j = 0; j <= 9; j++) {
theGrid[i * 10 + j] = theGrid[(i - 1) * 10 + j];
theGrid[i * 10 + j]->setCoords(i, j, (j * 45 + 2), (i * 45 + 2), 45, 45, &W);
}
}
for (int i = 0; i <= 9; i++) {
theGrid[i] = tmp[i];
tmp[i] = 0;
theGrid[i]->setCoords(0, i, (i * 45 + 2), (0 * 45 + 2), 45, 45, &W);
}
delete[] *tmp;
}
}
for (int k = 0; k <= 17; k++){
for (int i = 0; i <= 9; i++) {
theGrid[k * 10 + i]->notifyDisplay(*td);
}
}
score = score + ((currentLevel + numOfLine) * (currentLevel + numOfLine)) + lv0 + (lv1 * 4) + (lv2 * 9) + (lv3 * 16);
if (score > highscore){
highscore = score;
}
}
void Grid::move(Blocks *b, string s) {
this->removeBlocks(b);
if (s == "left") {
if ((b->block1c <= 0) |
(b->block2c <= 0) |
(b->block3c <= 0) |
(b->block4c <= 0)) {
}
else if ((theGrid[b->block1r * 10 + b->block1c - 1]->blocktype == ' ') &
(theGrid[b->block2r * 10 + b->block2c - 1]->blocktype == ' ') &
(theGrid[b->block3r * 10 + b->block3c - 1]->blocktype == ' ') &
(theGrid[b->block4r * 10 + b->block4c - 1]->blocktype == ' ')) {
b->move("left");
}
}
else if (s == "right") {
if ((b->block1c >= 9) |
(b->block2c >= 9) |
(b->block3c >= 9) |
(b->block4c >= 9)) {
}
else if ((theGrid[b->block1r * 10 + b->block1c + 1]->blocktype == ' ') &
(theGrid[b->block2r * 10 + b->block2c + 1]->blocktype == ' ') &
(theGrid[b->block3r * 10 + b->block3c + 1]->blocktype == ' ') &
(theGrid[b->block4r * 10 + b->block4c + 1]->blocktype == ' ')) {
b->move("right");
}
}
else if (s == "down") {
if ((b->block1r >= 17) |
(b->block2r >= 17) |
(b->block3r >= 17) |
(b->block4r >= 17)) {
}
else if ((theGrid[(b->block1r + 1) * 10 + b->block1c]->blocktype == ' ') &
(theGrid[(b->block2r + 1) * 10 + b->block2c]->blocktype == ' ') &
(theGrid[(b->block3r + 1) * 10 + b->block3c]->blocktype == ' ') &
(theGrid[(b->block4r + 1) * 10 + b->block4c]->blocktype == ' ')) {
b->move("down");
}
}
this->insertBlocks(b);
}
void Grid::rotate(Blocks *b, std::string s){
this->removeBlocks(b);
if (s == "clockwise") {
b->clockwise();
if ((b->block1r <= 17) &
(b->block2r <= 17) &
(b->block3r <= 17) &
(b->block4r <= 17) &
(b->block1c <= 9) &
(b->block2c <= 9) &
(b->block3c <= 9) &
(b->block4c <= 9) &
(theGrid[(b->block1r) * 10 + b->block1c]->blocktype == ' ') &
(theGrid[(b->block2r) * 10 + b->block2c]->blocktype == ' ') &
(theGrid[(b->block3r) * 10 + b->block3c]->blocktype == ' ') &
(theGrid[(b->block4r) * 10 + b->block4c]->blocktype == ' ') ) {
}
else {
b->counterclockwise();
}
}
else {
b->counterclockwise();
if ((b->block1r <= 17) &
(b->block2r <= 17) &
(b->block3r <= 17) &
(b->block4r <= 17) &
(b->block1c <= 9) &
(b->block2c <= 9) &
(b->block3c <= 9) &
(b->block4c <= 9) &
(theGrid[(b->block1r) * 10 + b->block1c]->blocktype == ' ') &
(theGrid[(b->block2r) * 10 + b->block2c]->blocktype == ' ') &
(theGrid[(b->block3r) * 10 + b->block3c]->blocktype == ' ') &
(theGrid[(b->block4r) * 10 + b->block4c]->blocktype == ' ') ) {
}
else {
b->clockwise();
}
}
this->insertBlocks(b);
}
void Grid::restart() {
score = 0;
currentLevel = 0;
td->restart();
for (int k = 0; k <= 17; k++){
for (int i = 0; i <= 9; i++){
theGrid[k * 10 + i]->reset();
theGrid[k * 10 + i]->setCoords(k, i, (i * 45 + 2), (k * 45 + 2), 45, 45, &W);
}
}
for (int k = 0; k <= 1; k++){
for (int i = 0; i <= 3; i++){
theGrid[k * 10 + i]->reset();
theGrid[k * 10 + i]->setCoords(k, i, (i * 45 + 472), (k * 45 + 22), 45, 45, &W);
}
}
}
ostream &operator<< (ostream &out, Grid &g) {
if (!(g.textonly)) {
for (int k = 0; k <= 17; k++){
for (int i = 0; i <= 9; i++) {
g.theGrid[k * 10 + i]->draw();
}
}
for (int k = 0; k <= 1; k++){
for (int i = 0; i <= 3; i++) {
g.next[k * 4 + i]->draw();
}
}
string l, s, hs;
stringstream lss;
stringstream sss;
stringstream hsss;
lss << g.currentLevel;
l = lss.str();
sss << g.score;
s = sss.str();
hsss << g.highscore;
hs = hsss.str();
g.W.fillRectangle(560, 140, 100, 100, Xwindow::White);
g.W.drawString(560, 140, l, Xwindow::Black);
g.W.drawString(560, 160, s, Xwindow::Black);
g.W.drawString(560, 180, hs, Xwindow::Black);
}
out << "Level: " << g.currentLevel << endl;
out << "Score: " << g.score << endl;
out << "Hi Score: " << g.highscore << endl;
out << "----------" << endl;
out << *(g.td) << endl;
out << "----------" << endl;
out << "Next:" << endl;
char display[7];
for (int i = 0; i < 2; i++){
for (int k = 0; k < 4; k++){
display[i * 4 + k] = (g.next[i * 4 + k])->getblocktype();
}
}
for (int i = 0; i < 2; i++){
for (int k = 0; k < 4; k++){
out << display[i * 4 + k];
}
out << endl;
}
return out;
} | 28.334988 | 118 | 0.523163 | kevinli9094 |
4c71d8f6475c29e56ba7811deaad7ae3556f5256 | 5,562 | cpp | C++ | main/solver/Solver.cpp | JLUCPGROUP/csptest | 0475c631a48511dd35e63397a74cbdf1388cf495 | [
"MIT"
] | null | null | null | main/solver/Solver.cpp | JLUCPGROUP/csptest | 0475c631a48511dd35e63397a74cbdf1388cf495 | [
"MIT"
] | null | null | null | main/solver/Solver.cpp | JLUCPGROUP/csptest | 0475c631a48511dd35e63397a74cbdf1388cf495 | [
"MIT"
] | null | null | null | #include "Solver.h"
namespace cudacp {
VarEvt::VarEvt(Network* m) :
size_(m->vars.size()),
cur_size_(0) {
vars = m->vars;
}
IntVar* VarEvt::operator[](const int i) const {
return vars[i];
}
int VarEvt::size() const {
return cur_size_;
}
IntVar* VarEvt::at(const int i) const {
return vars[i];
}
void VarEvt::push_back(IntVar* v) {
vars[cur_size_] = v;
++cur_size_;
}
void VarEvt::clear() {
cur_size_ = 0;
}
AssignedStack::AssignedStack(Network* m) :gm_(m) {
max_size_ = m->vars.size();
//vals_.resize(m->vars.size());
vals_.reserve(m->vars.size());
asnd_.resize(m->vars.size(), false);
}
void AssignedStack::initial(Network* m) {
gm_ = m;
max_size_ = m->vars.size();
//vals_.resize(m->vars.size());
vals_.reserve(m->vars.size());
asnd_.resize(m->vars.size(), false);
};
void AssignedStack::push(IntVal& v_a) {
//vals_[top_] = v_a;
//asnd_[v_a.vid()] = v_a.op();
//v_a.v()->assign(v_a.op());
//++top_;
vals_.push_back(v_a);
asnd_[v_a.vid()] = v_a.op();
v_a.v()->assign(v_a.op());
};
IntVal AssignedStack::pop() {
//--top_;
//asnd_[vals_[top_].vid()] = false;
//vals_[top_].v()->assign(false);
//return vals_[top_];
auto val = vals_.back();
vals_.pop_back();
asnd_[val.vid()] = false;
val.v()->assign(false);
return val;
}
//IntVal AssignedStack::top() const { return vals_[top_]; };
//int AssignedStack::size() const { return top_; }
//int AssignedStack::capacity() const { return max_size_; }
//bool AssignedStack::full() const { return top_ == max_size_; }
//bool AssignedStack::empty() const { return top_ == 0; }
//IntVal AssignedStack::operator[](const int i) const { return vals_[i]; };
//IntVal AssignedStack::at(const int i) const { return vals_[i]; };
//void AssignedStack::clear() { top_ = 0; };
//bool AssignedStack::assiged(const int v) const { return asnd_[v]; }
//bool AssignedStack::assiged(const IntVar* v) const { return assiged(v->id()); };
IntVal AssignedStack::top() const { return vals_.back(); }
int AssignedStack::size() const { return vals_.size(); }
int AssignedStack::capacity() const { return vals_.capacity(); }
bool AssignedStack::full() const { return size() == max_size_; }
bool AssignedStack::empty() const { return vals_.empty(); }
IntVal AssignedStack::operator[](const int i) const { return vals_[i]; }
IntVal AssignedStack::at(const int i) const { return vals_[i]; }
void AssignedStack::clear() { vals_.clear(); }
void AssignedStack::del(const IntVal val) {
remove(vals_.begin(), vals_.end(), val);
asnd_[val.vid()] = false;
}
bool AssignedStack::assiged(const int v) const { return asnd_[v]; }
bool AssignedStack::assiged(const IntVar* v) const { return assiged(v->id()); }
vector<IntVal> AssignedStack::vals() const { return vals_; }
ostream & operator<<(ostream & os, AssignedStack & I) {
for (int i = 0; i < I.size(); ++i)
os << I[i] << " ";
return os;
}
ostream & operator<<(ostream & os, AssignedStack * I) {
for (int i = 0; i < I->size(); ++i)
os << I->at(i) << " ";
return os;
}
void AssignedStack::update_model_assigned() {
for (auto val : vals_)
val.v()->assign(true);
}
///////////////////////////////////////////////////////////////////////
DeleteExplanation::DeleteExplanation(Network* m) :
m_(m) {
val_array_.resize(m_->vars.size(), vector<vector<IntVal>>(m_->max_domain_size()));
}
void DeleteExplanation::initial(Network* m) {
m_ = m;
val_array_.resize(m_->vars.size(), vector<vector<IntVal>>(m_->max_domain_size()));
}
vector<IntVal>& DeleteExplanation::operator[](const IntVal val) {
return val_array_[val.vid()][val.a()];
}
///////////////////////////////////////////////////////////////////////
arc_que::arc_que(const int cons_size, const int max_arity) :
arity_(max_arity),
m_size_(max_arity*cons_size + 1),
m_front_(0),
m_rear_(0) {
m_data_.resize(m_size_);
vid_set_.resize(m_size_);
}
void arc_que::MakeQue(const size_t cons_size, const size_t max_arity) {
arity_ = max_arity;
m_size_ = max_arity*cons_size + 1;
m_front_ = 0;
m_rear_ = 0;
m_data_.resize(m_size_);
vid_set_.resize(m_size_);
}
bool arc_que::empty() const {
return m_front_ == m_rear_;
}
bool arc_que::full() const {
return m_front_ == (m_rear_ + 1) % m_size_;
}
bool arc_que::push(arc& ele) throw(std::bad_exception) {
if (full())
throw std::bad_exception();
if (have(ele))
return false;
m_data_[m_rear_] = ele;
m_rear_ = (m_rear_ + 1) % m_size_;
have(ele) = 1;
return true;
}
arc arc_que::pop() throw(std::bad_exception) {
if (empty())
throw std::bad_exception();
arc tmp = m_data_[m_front_];
m_front_ = (m_front_ + 1) % m_size_;
have(tmp) = 0;
return tmp;
}
/////////////////////////////////////////////////////////////////////////
bool var_que::have(IntVar* v) {
return vid_set_[v->id()];
}
bool var_que::empty() const {
return m_front_ == m_rear_;
}
void var_que::initial(const int size) {
max_size_ = size + 1;
m_data_.resize(max_size_, nullptr);
vid_set_.resize(max_size_, 0);
m_front_ = 0;
m_rear_ = 0;
size_ = 0;
}
bool var_que::full() const {
return m_front_ == (m_rear_ + 1) % max_size_;
}
void var_que::push(IntVar* v) {
if (have(v))
return;
m_data_[m_rear_] = v;
m_rear_ = (m_rear_ + 1) % max_size_;
vid_set_[v->id()] = 1;
++size_;
}
IntVar* var_que::pop() {
IntVar* tmp = m_data_[m_front_];
m_front_ = (m_front_ + 1) % max_size_;
vid_set_[tmp->id()] = 0;
--size_;
return tmp;
}
void var_que::clear() {
m_front_ = 0;
m_rear_ = 0;
size_ = 0;
vid_set_.assign(vid_set_.size(), 0);
}
int var_que::max_size() const {
return max_size_;
}
int var_que::size() const {
return size_;
}
}
| 23.871245 | 83 | 0.634304 | JLUCPGROUP |
4c72a3bc63829c57f6812d99dc1fd8563948190e | 485 | hpp | C++ | plugins/opengl/include/sge/opengl/vf/color_formats.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/opengl/include/sge/opengl/vf/color_formats.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/opengl/include/sge/opengl/vf/color_formats.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENGL_VF_COLOR_FORMATS_HPP_INCLUDED
#define SGE_OPENGL_VF_COLOR_FORMATS_HPP_INCLUDED
#include <sge/renderer/vf/dynamic/color_format_vector.hpp>
namespace sge::opengl::vf
{
sge::renderer::vf::dynamic::color_format_vector color_formats();
}
#endif
| 25.526316 | 64 | 0.756701 | cpreh |
dbc96ef5cb52031d3609435909e9480440bb0cd3 | 4,465 | cc | C++ | src/PhysicsListMessenger.cc | phirippu/instrument-simulation | 0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8 | [
"CC-BY-4.0"
] | null | null | null | src/PhysicsListMessenger.cc | phirippu/instrument-simulation | 0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8 | [
"CC-BY-4.0"
] | null | null | null | src/PhysicsListMessenger.cc | phirippu/instrument-simulation | 0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8 | [
"CC-BY-4.0"
] | 1 | 2021-03-08T16:01:14.000Z | 2021-03-08T16:01:14.000Z | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file hadronic/Hadr01/src/PhysicsListMessenger.cc
/// \brief Implementation of the PhysicsListMessenger class
//
//
//
//
/////////////////////////////////////////////////////////////////////////
//
// PhysicsListMessenger
//
// Created: 31.01.2006 V.Ivanchenko
//
// Modified:
// 04.06.2006 Adoptation of Hadr01 (V.Ivanchenko)
//
////////////////////////////////////////////////////////////////////////
//
//
#include "PhysicsListMessenger.hh"
#include "PhysicsList.hh"
#include "G4UIcmdWithAString.hh"
#include "G4UIcmdWithoutParameter.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
PhysicsListMessenger::PhysicsListMessenger(PhysicsList* pPhys)
:G4UImessenger(), fPhysicsList(pPhys)
{
fPListCmd = new G4UIcmdWithAString("/physics/add",this);
fPListCmd->SetGuidance("Add modular physics list.");
fPListCmd->SetParameterName("PList",false);
fPListCmd->AvailableForStates(G4State_PreInit);
fListCmd = new G4UIcmdWithoutParameter("/physics/list",this);
fListCmd->SetGuidance("Available Physics Lists");
fListCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
PhysicsListMessenger::~PhysicsListMessenger()
{
delete fPListCmd;
delete fListCmd;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void PhysicsListMessenger::SetNewValue(G4UIcommand* command, G4String newValue)
{
if( command == fPListCmd ) {
if(fPhysicsList) {
G4String name = newValue;
if(name == "PHYSLIST") {
char* path = std::getenv(name);
if (path) name = G4String(path);
else {
G4cout << "### PhysicsListMessenger WARNING: "
<< " environment variable PHYSLIST is not defined"
<< G4endl;
return;
}
}
fPhysicsList->AddPhysicsList(name);
} else {
G4cout << "### PhysicsListMessenger WARNING: "
<< " /physics/add UI command is not available "
<< "for reference Physics List" << G4endl;
}
} else if( command == fListCmd ) {
if(fPhysicsList) {
fPhysicsList->List();
} else {
G4cout << "### PhysicsListMessenger WARNING: "
<< " /physics/list UI command is not available "
<< "for reference Physics List" << G4endl;
}
}
}
void PhysicsListMessenger::SayHello() {
G4cout << "[INFO] Hello from PhysicsListMessenger. Use /physics/add to add new physics." << G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 39.166667 | 103 | 0.542889 | phirippu |
dbcf9fe3ceb5d9de21cb26fedab6a6036cac3475 | 4,247 | cpp | C++ | mytunesmodel.cpp | Liz-Davies/2404 | a0d9e9c27286eccc9a086290ea223b41edabe248 | [
"FSFAP"
] | null | null | null | mytunesmodel.cpp | Liz-Davies/2404 | a0d9e9c27286eccc9a086290ea223b41edabe248 | [
"FSFAP"
] | null | null | null | mytunesmodel.cpp | Liz-Davies/2404 | a0d9e9c27286eccc9a086290ea223b41edabe248 | [
"FSFAP"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* Program: MyTunes Music Player */
/* Author: Louis Nel */
/* Sarah Davies - 100828244 */
/* Mike Sayegh - 101029473 */
/* Date: 21-SEP-2017 */
/* */
/* (c) 2017 Louis Nel */
/* All rights reserved. Distribution and */
/* reposting, in part or in whole, requires */
/* written consent of the author. */
/* */
/* COMP 2404 students may reuse this content for */
/* their course assignments without seeking consent */
/* * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "mytunesmodel.h"
using namespace std;
MyTunesModel::MyTunesModel(){}
// void Myrun();
MyTunesModel::~MyTunesModel(void){}
void MyTunesModel::addRecording(Recording * x){
recordings.add(*x);
}
void MyTunesModel::addUser(User * x){
users.add(*x);
}
void MyTunesModel::addSong(Song * x){
songs.add(*x);
}
void MyTunesModel::addTrack(Track * x){
tracks.add(*x);
}
Recording * MyTunesModel::getRecordingByID(int ID){
return recordings.findByID(ID);
}
User * MyTunesModel::getUserByID(string aUserName){
return users.findUserByID(aUserName);
}
Song * MyTunesModel::getSongByID(int ID){
return songs.findByID(ID);
}
Track * MyTunesModel::getTrackByID(int ID){
return tracks.findByID(ID);
}
void MyTunesModel::removeRecording(Recording * x){
recordings.remove(*x);
}
void MyTunesModel::removeUser(User * x){
users.remove(*x);
}
void MyTunesModel::removeSong(Song * x){
songs.remove(*x);
}
void MyTunesModel::removeTrack(Track * x){
tracks.remove(*x);
}
void MyTunesModel::globalTrackDelete(Track * track){
vector<User*> theUsers = users.getCollection();
for(vector<User*>::iterator itr = theUsers.begin(); itr != theUsers.end(); itr++){
User* user = *itr;
user->removeTrack(*track);
}
vector<Recording*> theRecordings = recordings.getCollection();
for(vector<Recording*>::iterator itr = theRecordings.begin(); itr != theRecordings.end(); itr++){
Recording* recording = *itr;
recording->removeTrack(*track);
}
tracks.remove(*track);
}
void MyTunesModel::deleteSong(Song * song){
//Perform Cascaded Delete
vector<Track*> theTracks = tracks.getCollection();
for(vector<Track*>::iterator itr = theTracks.begin(); itr != theTracks.end(); itr++){
Track* track = *itr;
Song* trackSong = track->getSong();
if(song == trackSong){
//Cascaded GLOBAL Delete
globalTrackDelete(track);
}
}
songs.remove(*song);
}
void MyTunesModel::executeCMDSHOW(Command cmd,UI & view){
//show recordings
//show recordings -r recording_id
//show songs
//show songs -s song_id
//show tracks
//show tracks -t track_id
//show users
//show users -u user_id
enum arguments {SHOW, COLLECTION, FLAG, MEMBER_ID};
if(cmd.isTokenAt(COLLECTION, "songs") && cmd.hasToken("-s"))
songs.showOn(view, stoi(cmd.getToken("-s")));
else if(cmd.isTokenAt(COLLECTION, "songs") && cmd.hasToken("-u")){
User * user = getUserByID(cmd.getToken("-u"));
if(user == NULL)view.printOutput("Error: User not found");
else user->showOn(view,cmd.getToken("-p"));
}
else if(cmd.isTokenAt(COLLECTION, "songs"))
songs.showOn(view);
else if(cmd.isTokenAt(COLLECTION, "recordings") && !cmd.hasToken("-r"))
recordings.showOn(view);
else if(cmd.isTokenAt(COLLECTION, "recordings") && cmd.hasToken("-r"))
recordings.showOn(view, stoi(cmd.getToken("-r")));
else if(cmd.isTokenAt(COLLECTION, "tracks") && !cmd.hasToken("-t"))
tracks.showOn(view);
else if(cmd.isTokenAt(COLLECTION, "tracks") && cmd.hasToken("-t"))
tracks.showOn(view, stoi(cmd.getToken("-t")));
else if(cmd.isTokenAt(COLLECTION, "users") && !cmd.hasToken("-u"))
users.showOn(view);
else if(cmd.isTokenAt(COLLECTION, "users") && cmd.hasToken("-u"))
users.showOn(view, cmd.getToken("-u"));
else view.printOutput("EXECUTING: " + cmd.getCommandString());
}
| 33.179688 | 99 | 0.597598 | Liz-Davies |
dbd396b0cf7ed94ed6ebcd2d8bff470bfb0937cf | 35,218 | cpp | C++ | test/blocks/electron/testcases_electron.cpp | awietek/hydra | 724a101500e308e91186a5cd6c5c520d8b343a6c | [
"Apache-2.0"
] | null | null | null | test/blocks/electron/testcases_electron.cpp | awietek/hydra | 724a101500e308e91186a5cd6c5c520d8b343a6c | [
"Apache-2.0"
] | null | null | null | test/blocks/electron/testcases_electron.cpp | awietek/hydra | 724a101500e308e91186a5cd6c5c520d8b343a6c | [
"Apache-2.0"
] | null | null | null | #include "testcases_electron.h"
namespace hydra::testcases::electron {
std::tuple<BondList, Couplings> get_linear_chain(int n_sites, double t,
double U) {
// Create model
BondList bondlist;
for (int s = 0; s < n_sites; ++s)
bondlist << Bond("HOP", "T", {s, (s + 1) % n_sites});
Couplings couplings;
couplings["T"] = t;
couplings["U"] = U;
return {bondlist, couplings};
}
std::tuple<BondList, Couplings> get_linear_chain_hb(int n_sites, double t,
double U, double J) {
// Create model
BondList bondlist;
// for (int s = 0; s < n_sites; ++s)
// bondlist << Bond("HOP", "T", {s, (s + 1) % n_sites});
for (int s = 0; s < n_sites; ++s)
bondlist << Bond("EXCHANGE", "J", {s, (s + 1) % n_sites});
Couplings couplings;
// couplings["T"] = t;
// couplings["U"] = U;
couplings["J"] = J;
return {bondlist, couplings};
}
std::tuple<PermutationGroup, std::vector<Representation>>
get_cyclic_group_irreps(int n_sites) {
// Create cyclic group as space group
std::vector<std::vector<int>> permutations;
for (int sym = 0; sym < n_sites; ++sym) {
std::vector<int> permutation;
for (int site = 0; site < n_sites; ++site) {
int newsite = (site + sym) % n_sites;
permutation.push_back(newsite);
}
permutations.push_back(permutation);
}
auto space_group = PermutationGroup(permutations);
// Create irreducible representations
std::vector<Representation> irreps;
for (int k = 0; k < n_sites; ++k) {
std::vector<complex> chis;
for (int l = 0; l < n_sites; ++l)
chis.push_back({std::cos(2 * M_PI * l * k / n_sites),
std::sin(2 * M_PI * l * k / n_sites)});
auto irrep = Representation(chis);
irreps.push_back(irrep);
}
return {space_group, irreps};
}
std::tuple<PermutationGroup, std::vector<Representation>, std::vector<int>>
get_cyclic_group_irreps_mult(int n_sites) {
// Create cyclic group as space group
std::vector<std::vector<int>> permutations;
for (int sym = 0; sym < n_sites; ++sym) {
std::vector<int> permutation;
for (int site = 0; site < n_sites; ++site) {
int newsite = (site + sym) % n_sites;
permutation.push_back(newsite);
}
permutations.push_back(permutation);
}
auto space_group = PermutationGroup(permutations);
// Create irreducible representations
std::vector<Representation> irreps;
std::vector<int> multiplicities;
for (int k = 0; k < n_sites; ++k) {
std::vector<complex> chis;
for (int l = 0; l < n_sites; ++l)
chis.push_back({std::cos(2 * M_PI * l * k / n_sites),
std::sin(2 * M_PI * l * k / n_sites)});
auto irrep = Representation(chis);
irreps.push_back(irrep);
multiplicities.push_back(1);
}
return {space_group, irreps, multiplicities};
}
std::tuple<BondList, Couplings> heisenberg_triangle() {
BondList bondlist;
bondlist << Bond("HEISENBERG", "J", {0, 1});
bondlist << Bond("HEISENBERG", "J", {1, 2});
bondlist << Bond("HEISENBERG", "J", {2, 0});
Couplings couplings;
couplings["J"] = 1.0;
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> heisenberg_alltoall(int n_sites) {
std::default_random_engine generator;
std::normal_distribution<double> distribution(0., 1.);
BondList bondlist;
Couplings couplings;
for (int s1 = 0; s1 < n_sites; ++s1)
for (int s2 = s1 + 1; s2 < n_sites; ++s2) {
std::stringstream ss;
ss << "J" << s1 << "_" << s2;
std::string name = ss.str();
double value = distribution(generator);
bondlist << Bond("HEISENBERG", name, {s1, s2});
couplings[name] = value;
}
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> heisenberg_kagome15() {
BondList bondlist;
bondlist << Bond("HEISENBERG", "J", {0, 1});
bondlist << Bond("HEISENBERG", "J", {0, 5});
bondlist << Bond("HEISENBERG", "J", {1, 2});
bondlist << Bond("HEISENBERG", "J", {1, 6});
bondlist << Bond("HEISENBERG", "J", {2, 3});
bondlist << Bond("HEISENBERG", "J", {2, 6});
bondlist << Bond("HEISENBERG", "J", {2, 10});
bondlist << Bond("HEISENBERG", "J", {3, 4});
bondlist << Bond("HEISENBERG", "J", {3, 10});
bondlist << Bond("HEISENBERG", "J", {3, 14});
bondlist << Bond("HEISENBERG", "J", {4, 5});
bondlist << Bond("HEISENBERG", "J", {4, 14});
bondlist << Bond("HEISENBERG", "J", {6, 7});
bondlist << Bond("HEISENBERG", "J", {7, 8});
bondlist << Bond("HEISENBERG", "J", {8, 9});
bondlist << Bond("HEISENBERG", "J", {9, 10});
bondlist << Bond("HEISENBERG", "J", {9, 11});
bondlist << Bond("HEISENBERG", "J", {10, 11});
bondlist << Bond("HEISENBERG", "J", {11, 12});
bondlist << Bond("HEISENBERG", "J", {12, 13});
bondlist << Bond("HEISENBERG", "J", {13, 14});
Couplings couplings;
couplings["J"] = 1.0;
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> heisenberg_kagome39() {
BondList bondlist;
bondlist << Bond("HEISENBERG", "J", {0, 1});
bondlist << Bond("HEISENBERG", "J", {0, 5});
bondlist << Bond("HEISENBERG", "J", {0, 27});
bondlist << Bond("HEISENBERG", "J", {0, 28});
bondlist << Bond("HEISENBERG", "J", {1, 2});
bondlist << Bond("HEISENBERG", "J", {1, 6});
bondlist << Bond("HEISENBERG", "J", {1, 28});
bondlist << Bond("HEISENBERG", "J", {2, 3});
bondlist << Bond("HEISENBERG", "J", {2, 6});
bondlist << Bond("HEISENBERG", "J", {2, 10});
bondlist << Bond("HEISENBERG", "J", {3, 4});
bondlist << Bond("HEISENBERG", "J", {3, 10});
bondlist << Bond("HEISENBERG", "J", {3, 14});
bondlist << Bond("HEISENBERG", "J", {4, 5});
bondlist << Bond("HEISENBERG", "J", {4, 14});
bondlist << Bond("HEISENBERG", "J", {4, 38});
bondlist << Bond("HEISENBERG", "J", {5, 27});
bondlist << Bond("HEISENBERG", "J", {5, 38});
bondlist << Bond("HEISENBERG", "J", {6, 7});
bondlist << Bond("HEISENBERG", "J", {6, 29});
bondlist << Bond("HEISENBERG", "J", {7, 8});
bondlist << Bond("HEISENBERG", "J", {7, 19});
bondlist << Bond("HEISENBERG", "J", {7, 29});
bondlist << Bond("HEISENBERG", "J", {8, 9});
bondlist << Bond("HEISENBERG", "J", {8, 15});
bondlist << Bond("HEISENBERG", "J", {8, 19});
bondlist << Bond("HEISENBERG", "J", {9, 10});
bondlist << Bond("HEISENBERG", "J", {9, 11});
bondlist << Bond("HEISENBERG", "J", {9, 15});
bondlist << Bond("HEISENBERG", "J", {10, 11});
bondlist << Bond("HEISENBERG", "J", {11, 12});
bondlist << Bond("HEISENBERG", "J", {11, 18});
bondlist << Bond("HEISENBERG", "J", {12, 13});
bondlist << Bond("HEISENBERG", "J", {12, 18});
bondlist << Bond("HEISENBERG", "J", {12, 26});
bondlist << Bond("HEISENBERG", "J", {13, 14});
bondlist << Bond("HEISENBERG", "J", {13, 26});
bondlist << Bond("HEISENBERG", "J", {13, 37});
bondlist << Bond("HEISENBERG", "J", {14, 37});
bondlist << Bond("HEISENBERG", "J", {15, 16});
bondlist << Bond("HEISENBERG", "J", {15, 22});
bondlist << Bond("HEISENBERG", "J", {16, 17});
bondlist << Bond("HEISENBERG", "J", {16, 22});
bondlist << Bond("HEISENBERG", "J", {16, 33});
bondlist << Bond("HEISENBERG", "J", {17, 18});
bondlist << Bond("HEISENBERG", "J", {17, 23});
bondlist << Bond("HEISENBERG", "J", {17, 33});
bondlist << Bond("HEISENBERG", "J", {18, 23});
bondlist << Bond("HEISENBERG", "J", {19, 20});
bondlist << Bond("HEISENBERG", "J", {19, 30});
bondlist << Bond("HEISENBERG", "J", {20, 21});
bondlist << Bond("HEISENBERG", "J", {20, 30});
bondlist << Bond("HEISENBERG", "J", {20, 31});
bondlist << Bond("HEISENBERG", "J", {21, 22});
bondlist << Bond("HEISENBERG", "J", {21, 31});
bondlist << Bond("HEISENBERG", "J", {21, 32});
bondlist << Bond("HEISENBERG", "J", {22, 32});
bondlist << Bond("HEISENBERG", "J", {23, 24});
bondlist << Bond("HEISENBERG", "J", {23, 34});
bondlist << Bond("HEISENBERG", "J", {24, 25});
bondlist << Bond("HEISENBERG", "J", {24, 34});
bondlist << Bond("HEISENBERG", "J", {24, 35});
bondlist << Bond("HEISENBERG", "J", {25, 26});
bondlist << Bond("HEISENBERG", "J", {25, 35});
bondlist << Bond("HEISENBERG", "J", {25, 36});
bondlist << Bond("HEISENBERG", "J", {26, 36});
Couplings couplings;
couplings["J"] = 1.0;
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> freefermion_alltoall(int n_sites) {
std::default_random_engine generator;
std::normal_distribution<double> distribution(0., 1.);
BondList bondlist;
Couplings couplings;
for (int s1 = 0; s1 < n_sites; ++s1)
for (int s2 = s1 + 1; s2 < n_sites; ++s2) {
std::stringstream ss;
ss << "T" << s1 << "_" << s2;
std::string name = ss.str();
double value = distribution(generator);
bondlist << Bond("HOP", name, {s1, s2});
couplings[name] = value;
}
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> freefermion_alltoall_complex_updn(int n_sites) {
std::default_random_engine generator;
std::normal_distribution<double> distribution(0., 1.);
BondList bondlist;
Couplings couplings;
for (int s1 = 0; s1 < n_sites; ++s1)
for (int s2 = s1 + 1; s2 < n_sites; ++s2) {
// Hopping on upspins
std::stringstream ss_up;
ss_up << "TUP" << s1 << "_" << s2;
std::string name_up = ss_up.str();
complex value_up =
complex(distribution(generator), distribution(generator));
bondlist << Bond("HOPUP", name_up, {s1, s2});
couplings[name_up] = value_up;
// Hopping on dnspins
std::stringstream ss_dn;
ss_dn << "TDN" << s1 << "_" << s2;
std::string name_dn = ss_dn.str();
complex value_dn =
complex(distribution(generator), distribution(generator));
bondlist << Bond("HOPDN", name_dn, {s1, s2});
couplings[name_dn] = value_dn;
}
return std::make_tuple(bondlist, couplings);
}
// std::tuple<BondList, Couplings> tJchain(int n_sites, double t,
// double J) {
// BondList bondlist;
// Couplings couplings;
// couplings["T"] = t;
// couplings["J"] = J;
// for (int s = 0; s < n_sites; ++s) {
// bondlist << Bond("HUBBARDHOP", "T", {s, (s + 1) % n_sites});
// bondlist << Bond("HEISENBERG", "J", {s, (s + 1) % n_sites});
// }
// return std::make_tuple(bondlist, couplings);
// }
std::tuple<BondList, Couplings, lila::Vector<double>> randomAlltoAll4NoU() {
BondList bondlist;
Couplings couplings;
// couplings["T01"] = 3;
// couplings["J01"] = 1;
// couplings["T02"] = 3;
// couplings["J02"] = -3;
// couplings["T03"] = 3;
// couplings["J03"] = 5;
// couplings["T12"] = 4;
// couplings["J12"] = -5;
// couplings["T13"] = -1;
// couplings["J13"] = -1;
// couplings["T23"] = 2;
// couplings["J23"] = 1;
couplings["T01"] = -3;
couplings["J01"] = 1;
couplings["T02"] = -3;
couplings["J02"] = -3;
couplings["T03"] = -3;
couplings["J03"] = 5;
couplings["T12"] = -4;
couplings["J12"] = -5;
couplings["T13"] = 1;
couplings["J13"] = -1;
couplings["T23"] = -2;
couplings["J23"] = 1;
bondlist << Bond("HOP", "T01", {0, 1});
bondlist << Bond("HOP", "T02", {0, 2});
bondlist << Bond("HOP", "T03", {0, 3});
bondlist << Bond("HOP", "T12", {1, 2});
bondlist << Bond("HOP", "T13", {1, 3});
bondlist << Bond("HOP", "T23", {2, 3});
bondlist << Bond("HEISENBERG", "J01", {0, 1});
bondlist << Bond("HEISENBERG", "J02", {0, 2});
bondlist << Bond("HEISENBERG", "J03", {0, 3});
bondlist << Bond("HEISENBERG", "J12", {1, 2});
bondlist << Bond("HEISENBERG", "J13", {1, 3});
bondlist << Bond("HEISENBERG", "J23", {2, 3});
lila::Vector<double> eigs = {-17.035603173216636,
-16.054529653295518,
-16.054529653295504,
-14.839136196281768,
-14.839136196281759,
-14.479223672075845,
-13.947060439818175,
-13.681140962579473,
-13.681140962579473,
-13.681140962579470,
-12.146019505147946,
-12.146019505147938,
-11.123249987689370,
-11.083677166546861,
-11.083677166546861,
-10.361590604796385,
-10.141075725997615,
-10.141075725997606,
-9.879061771701892,
-9.879061771701885,
-9.879061771701874,
-9.720915055042584,
-9.720915055042580,
-9.300171000114572,
-8.898903149068287,
-8.898903149068287,
-8.898903149068287,
-8.587797030969547,
-8.574093646826530,
-8.574093646826528,
-8.574093646826526,
-8.567342877760581,
-8.556463239828611,
-8.556463239828611,
-8.156431544113079,
-8.156431544113071,
-7.595003505113175,
-7.595003505113174,
-7.595003505113174,
-7.595003505113171,
-7.428914803058910,
-7.428914803058910,
-7.406132446925684,
-7.406132446925682,
-7.298052445959064,
-7.298052445959062,
-7.298052445959062,
-6.776050147544091,
-6.776050147544089,
-6.597100597834562,
-6.382421301285782,
-6.382421301285780,
-6.382421301285776,
-5.914206919262412,
-5.914206919262412,
-5.914206919262412,
-5.914206919262406,
-5.898063094032344,
-5.697730676986595,
-5.652742708313134,
-5.652742708313128,
-5.382395669397896,
-5.382395669397890,
-4.827554533410211,
-4.827554533410209,
-4.827554533410208,
-4.565866945456345,
-4.392721098506336,
-4.392721098506335,
-4.392721098506333,
-4.386896721326241,
-4.386896721326240,
-4.386896721326238,
-4.287074157175168,
-4.269109370889475,
-4.269109370889474,
-4.083758285516160,
-3.784107949888678,
-3.784107949888678,
-3.230851175883084,
-3.230851175883084,
-3.166425888361765,
-3.166425888361761,
-3.060272421221770,
-3.060272421221768,
-3.060272421221768,
-3.060272421221767,
-2.846017856191310,
-2.846017856191308,
-2.826551366644327,
-2.822163676323597,
-2.822163676323595,
-2.373593337341226,
-2.304206358771344,
-2.291423386597424,
-2.291423386597422,
-2.291423386597419,
-2.258325746389715,
-2.100087802223023,
-2.100087802223022,
-2.100087802223021,
-2.002616246412348,
-2.002616246412347,
-2.002616246412346,
-2.002616246412346,
-1.653289828765464,
-1.653289828765462,
-1.653289828765460,
-1.537108454167115,
-1.537108454167113,
-1.468496478890581,
-1.184332042222068,
-1.184332042222067,
-1.183220245290653,
-1.183220245290652,
-1.183220245290647,
-1.158824284368453,
-1.158824284368453,
-0.797210829513575,
-0.797210829513574,
-0.753299251580644,
-0.500000000000001,
-0.500000000000000,
-0.500000000000000,
-0.500000000000000,
-0.499999999999998,
-0.370985460263250,
-0.370985460263249,
-0.281075696274453,
-0.230909105391692,
-0.230909105391692,
-0.230909105391689,
0,
0,
0.226914386262986,
0.226914386262986,
0.226914386262988,
0.339587764690138,
0.339587764690138,
0.339587764690140,
0.339587764690141,
0.864151894040242,
0.864151894040242,
0.977357729518521,
0.977357729518522,
0.982508508938287,
0.982508508938294,
1.184332042222068,
1.184332042222068,
1.286333102260671,
1.360519899915624,
1.360519899915626,
1.831699701973819,
1.831699701973819,
1.831699701973821,
2.168605503366585,
2.304759071083118,
2.305593972115476,
2.305593972115481,
2.305593972115481,
2.565136835120275,
2.565136835120277,
2.680716385503151,
2.680716385503155,
2.680716385503157,
2.859450072401542,
2.867740829382918,
2.867740829382918,
2.867740829382920,
2.867740829382922,
2.919012177817019,
2.919012177817021,
3.230851175883083,
3.230851175883084,
3.586647790757984,
3.586647790757985,
3.866685809727107,
3.866685809727108,
3.866685809727108,
3.962683310049183,
3.962683310049187,
3.983903797596342,
3.983903797596345,
3.983903797596353,
4.106914761573067,
4.258514587211152,
4.258514587211155,
4.258514587211158,
4.279939892091212,
4.647129236685327,
4.647129236685331,
4.730285398111332,
5.382395669397893,
5.382395669397895,
5.557913081969264,
5.729878922142601,
5.729878922142602,
5.729878922142604,
5.729878922142607,
5.854994021510809,
5.854994021510811,
6.026195725670756,
6.026195725670764,
6.112978522336865,
6.112978522336867,
6.112978522336871,
6.298578032819039,
6.627388000300686,
6.627388000300687,
6.638917394627725,
6.638917394627728,
6.638917394627730,
7.106988282706432,
7.261271812957728,
7.428914803058909,
7.428914803058913,
7.634891575794040,
7.634891575794041,
7.634891575794042,
7.634891575794042,
8.034109956056216,
8.034109956056225,
8.433501672445885,
8.437627423133117,
8.437627423133124,
8.437627423133126,
8.487415286599031,
8.740704187459059,
8.740704187459061,
8.740704187459061,
8.758701982332155,
9.740946203547077,
9.740946203547077,
10.075541640416940,
10.075541640416946,
10.365553083134904,
10.365553083134905,
10.898695460947337,
10.898695460947337,
10.898695460947343,
11.368060459508595,
11.880069395522252,
12.081391252276028,
12.081391252276036,
12.355338794669144,
12.355338794669148,
12.833107262067776,
14.296824370037875,
14.296824370037879,
14.296824370037887,
15.091839736118505,
15.091839736118507,
15.880746138642490,
17.166681362460483,
17.166681362460491,
18.194539570876405};
return std::make_tuple(bondlist, couplings, eigs);
}
std::tuple<BondList, Couplings, lila::Vector<double>> randomAlltoAll4() {
BondList bondlist;
Couplings couplings;
// couplings["U"] = 5;
// couplings["T01"] = 3;
// couplings["J01"] = -1;
// couplings["T02"] = -3;
// couplings["J02"] = -5;
// couplings["T03"] = 3;
// couplings["J03"] = -3;
// couplings["T12"] = -1;
// couplings["J12"] = 1;
// couplings["T13"] = -3;
// couplings["J13"] = 2;
// couplings["T23"] = 0;
// couplings["J23"] = -4;
couplings["U"] = 5;
couplings["T01"] = -3;
couplings["J01"] = -1;
couplings["T02"] = 3;
couplings["J02"] = -5;
couplings["T03"] = -3;
couplings["J03"] = -3;
couplings["T12"] = 1;
couplings["J12"] = 1;
couplings["T13"] = 3;
couplings["J13"] = 2;
couplings["T23"] = 0;
couplings["J23"] = -4;
bondlist << Bond("HOP", "T01", {0, 1});
bondlist << Bond("HOP", "T02", {0, 2});
bondlist << Bond("HOP", "T03", {0, 3});
bondlist << Bond("HOP", "T12", {1, 2});
bondlist << Bond("HOP", "T13", {1, 3});
bondlist << Bond("HOP", "T23", {2, 3});
bondlist << Bond("HEISENBERG", "J01", {0, 1});
bondlist << Bond("HEISENBERG", "J02", {0, 2});
bondlist << Bond("HEISENBERG", "J03", {0, 3});
bondlist << Bond("HEISENBERG", "J12", {1, 2});
bondlist << Bond("HEISENBERG", "J13", {1, 3});
bondlist << Bond("HEISENBERG", "J23", {2, 3});
lila::Vector<double> eigs = {
-12.270231830055396, -12.270231830055389, -10.733666336755952,
-10.069390063366962, -9.060858377591751, -9.060858377591751,
-9.060858377591751, -8.419560252873284, -8.419560252873282,
-8.419560252873278, -6.383158148575644, -6.383158148575637,
-6.383158148575632, -6.352277902330186, -6.352277902330185,
-6.273324224596429, -6.273324224596422, -6.250906641891413,
-6.250906641891411, -6.164309032262214, -6.164309032262212,
-6.164309032262212, -6.164309032262211, -5.730618769293929,
-5.448935789669534, -5.448935789669532, -5.038951239070341,
-4.949876862328434, -4.949876862328423, -4.532986251596143,
-4.532986251596141, -4.532986251596141, -4.532986251596141,
-3.353197524407229, -3.353197524407228, -3.353197524407226,
-3.273406176414287, -3.002245918852136, -3.002245918852133,
-2.753141709527037, -2.753141709527034, -2.753141709527034,
-2.753141709527031, -2.646622091502864, -2.646622091502863,
-2.646622091502862, -2.500000000000006, -2.500000000000000,
-2.500000000000000, -2.500000000000000, -2.499999999999995,
-2.002043720414641, -2.002043720414640, -2.002043720414639,
-1.825844696317418, -1.825844696317417, -1.587175599207617,
-1.587175599207614, -1.332228906443854, -1.332228906443853,
-0.953827936085984, -0.635382900549627, -0.635382900549625,
-0.635382900549624, -0.397581339114120, -0.397581339114115,
-0.302660107585638, -0.302660107585633, -0.302660107585631,
-0.080803683543577, -0.080803683543570, 0,
0.216457675593863, 0.256166291525251, 0.601566977837033,
0.601566977837038, 0.601566977837038, 0.601566977837040,
0.975606313924293, 0.975606313924297, 1.014605271271656,
1.014605271271658, 1.015859809070357, 1.015859809070358,
1.015859809070360, 1.020308313587130, 1.114881844698814,
1.791357286454801, 1.791357286454802, 1.791357286454810,
1.812876191672553, 2.051032557261542, 2.051032557261543,
2.054529439890590, 2.054529439890591, 2.054529439890594,
2.464728271742040, 2.464728271742042, 2.464728271742044,
2.464728271742044, 2.561461716067067, 2.599451504679192,
2.710382274715613, 2.710382274715615, 2.710382274715616,
2.999999999999997, 3.000000000000001, 3.165957899766594,
3.165957899766600, 3.217491411604103, 3.217491411604104,
3.217491411604105, 3.264426167093818, 3.264426167093818,
3.275854965551124, 3.873065426792698, 3.930285431436003,
3.930285431436005, 4.357654287008264, 4.373227423701834,
4.373227423701834, 4.373227423701836, 4.744551703509988,
4.744551703509988, 4.764857447396031, 4.764857447396040,
4.764857447396043, 4.838082241099029, 4.838082241099031,
5.078388983561651, 5.078388983561652, 5.095728306021306,
5.095728306021313, 5.095728306021315, 5.095728306021317,
5.270280349321774, 5.629364135391933, 5.629364135391936,
5.732050357363664, 5.732050357363669, 5.732050357363673,
5.902527336054253, 5.997898395939853, 5.997898395939854,
5.997898395939856, 6.168989353312808, 6.168989353312815,
6.168989353312816, 6.168989353312816, 6.251638235870590,
6.251638235870590, 6.639239164264768, 6.871779959503020,
6.871779959503024, 6.913606012729136, 7.197663951269839,
7.197663951269844, 7.241663577600812, 7.241663577600815,
7.548559413909176, 7.548559413909178, 7.548559413909183,
7.889853801872584, 8.012439704238972, 8.012439704238977,
8.048368645785640, 8.048368645785644, 8.195982486905091,
8.195982486905091, 8.195982486905095, 8.291793376177347,
8.291793376177351, 8.291793376177356, 8.468003039901994,
8.884687492644268, 8.929394188779456, 8.929394188779456,
9.084392860883399, 9.084392860883403, 9.084392860883410,
9.119424084472175, 9.119424084472177, 9.119424084472177,
9.119424084472181, 9.374280903298303, 9.374280903298303,
9.470513926885971, 9.470513926885971, 9.807459688038790,
9.894356293199492, 10.161917758900962, 10.161917758900971,
10.343135676951986, 10.647301560880138, 10.647301560880139,
10.781521078539114, 10.816967757221121, 10.816967757221125,
10.816967757221128, 10.989949094629180, 10.989949094629189,
10.989949094629189, 11.783921524648289, 11.862403712063079,
11.862403712063086, 11.999999999999995, 11.999999999999995,
12.122579175754746, 12.122579175754746, 12.422108994367830,
12.422108994367832, 12.660280744665648, 12.660280744665650,
12.660280744665654, 12.782275159258591, 13.142554967689829,
13.262004386769918, 13.262004386769929, 13.262004386769933,
13.345289206597041, 13.345289206597041, 13.920776472179945,
14.125358959870058, 14.125358959870061, 14.245875071040452,
14.245875071040452, 14.710043063865781, 14.821095142124749,
15.455920358765942, 15.455920358765947, 15.455920358765953,
15.977688392619838, 15.977688392619839, 16.548872176333433,
16.587175599207608, 16.587175599207615, 16.668859213157941,
16.668859213157944, 16.859992272946350, 17.289815197741845,
17.339978797436935, 17.339978797436938, 17.339978797436956,
18.075989445512761, 18.075989445512761, 18.524216278708529,
18.776715574088868, 18.776715574088868, 20.000000000000000,
20.972807969213903, 21.250906641891415, 21.250906641891415,
22.411220290848199, 22.411220290848210, 22.508215798228996,
25.052426347353144};
return std::make_tuple(bondlist, couplings, eigs);
}
std::tuple<BondList, Couplings> randomAlltoAll3() {
BondList bondlist;
Couplings couplings;
couplings["T01"] = 1;
couplings["J01"] = -2;
couplings["T02"] = 0;
couplings["J02"] = -1;
couplings["T12"] = -5;
couplings["J12"] = -3;
bondlist << Bond("HUBBARDHOP", "T01", {0, 1});
bondlist << Bond("HUBBARDHOP", "T02", {0, 2});
bondlist << Bond("HUBBARDHOP", "T12", {1, 2});
bondlist << Bond("HEISENBERG", "J01", {0, 1});
bondlist << Bond("HEISENBERG", "J02", {0, 2});
bondlist << Bond("HEISENBERG", "J12", {1, 2});
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> square2x2(double t, double J) {
BondList bondlist;
Couplings couplings;
couplings["T"] = t;
couplings["J"] = J;
bondlist << Bond("HUBBARDHOP", "T", {0, 1});
bondlist << Bond("HUBBARDHOP", "T", {1, 0});
bondlist << Bond("HUBBARDHOP", "T", {2, 3});
bondlist << Bond("HUBBARDHOP", "T", {3, 2});
bondlist << Bond("HUBBARDHOP", "T", {0, 2});
bondlist << Bond("HUBBARDHOP", "T", {2, 0});
bondlist << Bond("HUBBARDHOP", "T", {1, 3});
bondlist << Bond("HUBBARDHOP", "T", {3, 1});
bondlist << Bond("HEISENBERG", "J", {0, 1});
bondlist << Bond("HEISENBERG", "J", {1, 0});
bondlist << Bond("HEISENBERG", "J", {2, 3});
bondlist << Bond("HEISENBERG", "J", {3, 2});
bondlist << Bond("HEISENBERG", "J", {0, 2});
bondlist << Bond("HEISENBERG", "J", {2, 0});
bondlist << Bond("HEISENBERG", "J", {1, 3});
bondlist << Bond("HEISENBERG", "J", {3, 1});
return std::make_tuple(bondlist, couplings);
}
std::tuple<BondList, Couplings> square3x3(double t, double J) {
BondList bondlist;
Couplings couplings;
couplings["T"] = t;
couplings["J"] = J;
bondlist << Bond("HOP", "T", {0, 1});
bondlist << Bond("HOP", "T", {1, 2});
bondlist << Bond("HOP", "T", {2, 0});
bondlist << Bond("HOP", "T", {3, 4});
bondlist << Bond("HOP", "T", {4, 5});
bondlist << Bond("HOP", "T", {5, 3});
bondlist << Bond("HOP", "T", {6, 7});
bondlist << Bond("HOP", "T", {7, 8});
bondlist << Bond("HOP", "T", {8, 6});
bondlist << Bond("HOP", "T", {0, 3});
bondlist << Bond("HOP", "T", {3, 6});
bondlist << Bond("HOP", "T", {6, 0});
bondlist << Bond("HOP", "T", {1, 4});
bondlist << Bond("HOP", "T", {4, 7});
bondlist << Bond("HOP", "T", {7, 1});
bondlist << Bond("HOP", "T", {2, 5});
bondlist << Bond("HOP", "T", {5, 8});
bondlist << Bond("HOP", "T", {8, 2});
bondlist << Bond("HEISENBERG", "J", {0, 1});
bondlist << Bond("HEISENBERG", "J", {1, 2});
bondlist << Bond("HEISENBERG", "J", {2, 0});
bondlist << Bond("HEISENBERG", "J", {3, 4});
bondlist << Bond("HEISENBERG", "J", {4, 5});
bondlist << Bond("HEISENBERG", "J", {5, 3});
bondlist << Bond("HEISENBERG", "J", {6, 7});
bondlist << Bond("HEISENBERG", "J", {7, 8});
bondlist << Bond("HEISENBERG", "J", {8, 6});
bondlist << Bond("HEISENBERG", "J", {0, 3});
bondlist << Bond("HEISENBERG", "J", {3, 6});
bondlist << Bond("HEISENBERG", "J", {6, 0});
bondlist << Bond("HEISENBERG", "J", {1, 4});
bondlist << Bond("HEISENBERG", "J", {4, 7});
bondlist << Bond("HEISENBERG", "J", {7, 1});
bondlist << Bond("HEISENBERG", "J", {2, 5});
bondlist << Bond("HEISENBERG", "J", {5, 8});
bondlist << Bond("HEISENBERG", "J", {8, 2});
return std::make_tuple(bondlist, couplings);
}
} // namespace hydra::testcases::electron
| 43.586634 | 80 | 0.502158 | awietek |
dbdb9256aa2526eec206e98330cdfafd568fbafd | 32,093 | cpp | C++ | src/Person.cpp | MasterMenOfficial/CSPSP-Client | d8ab8cc52543ca4cb136aab98c10d3efb61f8ebe | [
"BSD-3-Clause"
] | 3 | 2021-01-20T08:57:23.000Z | 2021-11-21T02:10:13.000Z | src/Person.cpp | MasterMenSilver/PSP-CSPSP-Client | d8ab8cc52543ca4cb136aab98c10d3efb61f8ebe | [
"BSD-3-Clause"
] | 1 | 2018-06-26T00:02:20.000Z | 2020-10-20T21:07:54.000Z | src/Person.cpp | MasterMenOfficial/CSPSP-1.92-rev9.0-Source-Code | d8ab8cc52543ca4cb136aab98c10d3efb61f8ebe | [
"BSD-3-Clause"
] | null | null | null |
#include "Person.h"
#include "Globals.h"
JRenderer* Person::mRenderer = NULL;
JSoundSystem* Person::mSoundSystem = NULL;
//------------------------------------------------------------------------------------------------
Person::Person(JQuad* quads[], JQuad* deadquad, std::vector<Bullet*>* bullets, std::vector<GunObject*>* guns, int team, char* name, int movementstyle)
{
mRenderer = JRenderer::GetInstance();
SetQuads(quads,deadquad);
mX = 0.0f;
mY = 0.0f;
mOldX = 0.0f;
mOldY = 0.0f;
mWalkX = 0.0f;
mWalkY = 0.0f;
mSpeed = 0.0f;
mAngle = 0.0f;
mMaxSpeed = 0.0f;
mMoveState = NOTMOVING;
mState = DEAD;
//mState = 0;
mStateTime = 0.0f;
mHealth = 100;
mRegen = 0.0f;
mRegenlol = 0.0f;
mRegenTimer = 2.0f; //default 1 sec
mRegenPoints = 5; //default 1 HP
mRegenSfxType = 0;
mGunMode = 0;
mSilencedUSP = false;
mSilencedM4A1 = false;
mLRTimer = 0.0f;
mComboType = 0;
mComboTimer = 0;
mMoney = 800;
mRecoilAngle = 0.0f;
SetTotalRotation(M_PI_2);
//mRotation = 0.0f;
//mFacingAngle = M_PI_2;
//mLastFireAngle = 0.0f;
mTeam = team;
strncpy(mName,name,25);
mName[25] = '\0';
mMovementStyle = movementstyle;
mNumKills = 0;
mNumDeaths = 0;
mSoundId = -1;
mNumDryFire = 0;
/*mGuns[PRIMARY] = NULL;
mGuns[SECONDARY] = NULL;
mGuns[KNIFE] = NULL;
mGuns[mGunIndex] = NULL;*/
for (int i=0; i<5; i++) {
mGuns[i] = NULL;
}
mGunIndex = KNIFE;
mFadeTime = 0.0f;
mStepTime = 0.0f;
mIsActive = true;
mBullets = bullets;
mGunObjects = guns;
mPing = 0.0f;
mIsPlayerOnline = false;
mIsFiring = false;
mHasFired = false;
mHasLR = false;
mIsFlashed = false;
mFlashTime = 0.0f;
mFlashIntensity = 0.0f;
mIsInBuyZone = false;
mIsInBombZone = false;
mNode = NULL;
mTargetNode = NULL;
for (int i=0; i<10; i++) {
mAnimations[i] = NULL;
}
for (int i=ANIM_PRIMARY; i<=ANIM_SECONDARY_RELOAD; i++) {
mAnimations[i] = new Animation(gKeyFrameAnims[i],true,false);
}
mCurrentAnimation = mAnimations[1];
mKeyFrame = KeyFrame();
mKeyFrame.angles[BODY] = 0.4f;
mKeyFrame.angles[RIGHTARM] = 0.0f;
mKeyFrame.angles[RIGHTHAND] = 0.0f;
mKeyFrame.angles[LEFTARM] = 0.0f;
mKeyFrame.angles[LEFTHAND] = 0.0f;
mKeyFrame.angles[GUN] = 0.0f;
mKeyFrame.duration = 10;
mWalkState = WALK1;
mWalkTime = 0.0f;
mWalkAngle = 0.0f;
mMuzzleFlashIndex = 0;
mMuzzleFlashAngle = 0.0f;
mMuzzleFlashTime = 0.0f;
mRadarTime = 0.0f;
mRadarX = 0.0f;
mRadarY = 0.0f;
mHasFlag = false;
mInvincibleTime = 0.0f;
/*JTexture* texture = mRenderer->LoadTexture("gfx/playerparts.png");
mPartQuads[BODY] = new JQuad(texture,0,0,32,16);
mPartQuads[BODY]->SetHotSpot(16,8);
mPartQuads[5] = new JQuad(texture,16,16,16,16);
mPartQuads[5]->SetHotSpot(8,8);
mPartQuads[RIGHTARM] = new JQuad(texture,0,16,16,8);
mPartQuads[RIGHTARM]->SetHotSpot(4.5f,3.5f);
mPartQuads[RIGHTHAND] = new JQuad(texture,0,24,16,8);
mPartQuads[RIGHTHAND]->SetHotSpot(3.5f,3.5f);
mPartQuads[LEFTARM] = new JQuad(texture,0,16,16,8);
mPartQuads[LEFTARM]->SetHotSpot(4.5f,3.5f);
mPartQuads[LEFTARM]->SetVFlip(true);
mPartQuads[LEFTHAND] = new JQuad(texture,0,24,16,8);
mPartQuads[LEFTHAND]->SetHotSpot(3.5f,3.5f);
mPartQuads[LEFTHAND]->SetVFlip(true);*/
mAllowRegeneration = true;
char* AR = GetConfig("data/MatchSettings.txt","AllowRegeneration");
if (AR != NULL) {
if (strcmp(AR,"true") == 0) {
mAllowRegeneration = true;
}
else if (strcmp(AR,"false") == 0) {
mAllowRegeneration = false;
}
delete AR;
}
}
//------------------------------------------------------------------------------------------------
Person::~Person()
{
//mPeople.clear();
/*if (mGuns[PRIMARY])
delete mGuns[PRIMARY];
if (mGuns[SECONDARY])
delete mGuns[SECONDARY];
if (mGuns[KNIFE])
delete mGuns[KNIFE];*/
for (int i=0; i<5; i++) {
if (mGuns[i]) {
delete mGuns[i];
}
}
for (int i=0; i<10; i++) {
if (mAnimations[i] != NULL) {
delete mAnimations[i];
}
}
//delete mKeyFrame;
mNodes.clear();
if (mSoundId != -1) {
mSoundSystem->StopSample(mSoundId);
mSoundId = -1;
}
//JGERelease();
}
//------------------------------------------------------------------------------------------------
void Person::PreUpdate(float dt)
{
if (mState == DEAD) {
return;
}
float dx = mOldX-mX;
float dy = mOldY-mY;
//UpdateAngle(mWalkAngle,mAngle, 0.01*dt);
float speed = sqrtf(dx*dx+dy*dy)/dt;
if (speed > 0.15f) speed = 0.15f;
if (mMoveState == NOTMOVING || speed < 0.03f) {
if (mWalkTime > 0.0f) {
mWalkTime -= dt;
if (mWalkTime < 0.0f) {
mWalkTime = 0.0f;
mWalkState = (mWalkState+2)%4;
}
}
}
else {//if (mMoveState == MOVING) {
//float speed = sqrtf(dx*dx+dy*dy)/dt;
if (mWalkState == WALK1 || mWalkState == WALK3) {
mWalkTime += dt*speed/0.1f;
if (mWalkTime >= WALKTIME) {
mWalkTime = WALKTIME-(mWalkTime-WALKTIME);
mWalkState = (mWalkState+1)%4;
}
}
else {
mWalkTime -= dt*speed/0.1f;
if (mWalkTime <= 0) {
mWalkTime = -mWalkTime;
mWalkState = (mWalkState+1)%4;
}
}
}
dx = mX-mWalkX;
dy = mY-mWalkY;
float d = sqrtf(dx*dx+dy*dy)/dt;
if (d > 2+rand()%2) {
mWalkX = mX;
mWalkY = mY;
//gSfxManager->PlaySample(gWalkSounds[rand()%2],mX,mY);
}
else if (speed > 0.06f) {
mStepTime += dt;
if (mStepTime > 480.0f + rand()%50 - 25.0f) {
gSfxManager->PlaySample(gWalkSounds[rand()%2],mX,mY);
mStepTime = 0.0f;
}
}
//if (fabs(dx) >= EPSILON || fabs(dy) >= EPSILON) {
/*if (speed > 0.06f) {
mStepTime += dt;
if (mStepTime > 480.0f + rand()%50 - 25.0f) {
gSfxManager->PlaySample(gWalkSounds[rand()%2],mX,mY);
mStepTime = 0.0f;
}
}*/
//}
}
//------------------------------------------------------------------------------------------------
void Person::Update(float dt)
{
if (mGuns[mGunIndex] == NULL) {
printf("isPlayerOnline: %i\n",mIsPlayerOnline);
printf("invalid gunindex: %i\n",mGunIndex);
return;
}
mStateTime += dt;
if (mState == DEAD) {
if (mStateTime >= 15000.0f) { //P: time for deadbody = 15 secs //orig : 2 sec
mFadeTime -= dt;
if (mFadeTime < 0.0f) {
mFadeTime = 0.0f;
}
}
return;
}
//P: HEALTH REGEN (adds as HP the mRegenPoints per desired mRegenTimer)
if (mAllowRegeneration == true) {
if (mMoveState == NOTMOVING && mHealth != 100) {
mRegen += dt/1000.0f;
if (mRegen >= mRegenTimer) { // + mRegenPoints HP per mRegenTimer second(s)
if (mHealth != 0) {
mRegenlol += dt/25.0f;
if (mRegenlol >= mRegenTimer){
mHealth += 1;
mRegenPoints -= 1;
mRegenlol = 0.0f;
if (mRegenPoints == 4) {
mRegenSfxType = 1;
}
}
if (mRegenPoints <= 0){
mRegen = 0.0f;
mRegenPoints = 5;
}
}
}
if (mHealth > 100) { //for safety and bug avoidance reasons, cause it could be done otherwise, but this is optimum.
mHealth = 100;
}
if (mHealth == 100) {
mRegen = 0.0f;
}
}
if (mMoveState != NOTMOVING) {
mRegen = 0.0f;
mRegenPoints = 5;
}
} // Regen End
mWalkAngle = mAngle;
if (mIsActive) {
if (mMoveState == NOTMOVING) {
if (!mIsPlayerOnline) {
mSpeed -= .0005f*dt;
if (mSpeed < 0) {
mSpeed = 0;
}
}
mStepTime = 240.0f;
}
else if (mMoveState == MOVING) {
if (!mIsPlayerOnline) {
mSpeed += .0005f*dt;
if (mSpeed > mMaxSpeed) {
mSpeed = mMaxSpeed;
}
}
if (mRecoilAngle < mGuns[mGunIndex]->mGun->mSpread*0.5f) { //HERE
mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/50.0f*dt;
if (mRecoilAngle > mGuns[mGunIndex]->mGun->mSpread*0.5f) {
mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread*0.5f;
}
}
}
}
if (!mIsPlayerOnline) {
mOldX = mX;
mOldY = mY;
mX += mSpeed * cosf(mAngle) * dt;
mY += mSpeed * sinf(mAngle) * dt;
}
//JSprite::Update(dt);
if (mGuns[mGunIndex]->mGun->mId == 7 || mGuns[mGunIndex]->mGun->mId == 8) { //HERE
mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread;
}
mLastFireAngle = mRotation;
if (mState == NORMAL) {
if (mGuns[mGunIndex]->mGun->mId != 7 && mGuns[mGunIndex]->mGun->mId != 8) {
mRecoilAngle -= mGuns[mGunIndex]->mGun->mSpread/100.0f*dt;
if (mRecoilAngle < 0) {
mRecoilAngle = 0.0f;
}
}
}
else if (mState == ATTACKING) {
if (mMoveState == NOTMOVING) {
mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/500.0f*dt;
}
else if (mMoveState == MOVING) {
mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/50.0f*dt;
}
if (mGuns[mGunIndex]->mGun->mId == 16 || mGuns[mGunIndex]->mGun->mId == 21 || mGuns[mGunIndex]->mGun->mId == 22 || mGuns[mGunIndex]->mGun->mId == 23) {
mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread;
}
if (mRecoilAngle > mGuns[mGunIndex]->mGun->mSpread) {
mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread;
}
if (mRecoilAngle*500.0f >= 0.1f && mStateTime < 100.0f) {
mLastFireAngle += (rand()%(int)ceilf(mRecoilAngle*500.0f))/1000.0f-(mRecoilAngle/4.0f);
}
if (mStateTime >= mGuns[mGunIndex]->mGun->mDelay) {
if (mGunIndex == GRENADE) {
mStateTime = mGuns[mGunIndex]->mGun->mDelay;
}
else {
SetState(NORMAL);
}
}
}
else if (mState == RELOADING) {
if (mStateTime >= mGuns[mGunIndex]->mGun->mReloadDelay) {
mGuns[mGunIndex]->mRemainingAmmo -= (mGuns[mGunIndex]->mGun->mClip-mGuns[mGunIndex]->mClipAmmo);
mGuns[mGunIndex]->mClipAmmo = mGuns[mGunIndex]->mGun->mClip;
if (mGuns[mGunIndex]->mRemainingAmmo < 0) {
mGuns[mGunIndex]->mClipAmmo = mGuns[mGunIndex]->mGun->mClip + mGuns[mGunIndex]->mRemainingAmmo ;
mGuns[mGunIndex]->mRemainingAmmo = 0;
}
SetState(NORMAL);
}
if (mGuns[mGunIndex]->mGun->mId != 7 && mGuns[mGunIndex]->mGun->mId != 8) {
mRecoilAngle -= mGuns[mGunIndex]->mGun->mSpread/100.0f*dt;
if (mRecoilAngle < 0.0f) {
mRecoilAngle = 0.0f;
}
}
}
else if (mState == DRYFIRING) {
if (mGunIndex == PRIMARY) {
if (mStateTime >= 250.0f) {
SetState(NORMAL);
mNumDryFire++;
}
}
else if (mGunIndex == SECONDARY) {
SetState(NORMAL);
mNumDryFire++;
}
else if (mGunIndex == KNIFE) {
if (mStateTime >= mGuns[mGunIndex]->mGun->mDelay) {
SetState(NORMAL);
}
}
}
else if (mState == SWITCHING) {
if (mGunIndex == PRIMARY || mGunIndex == SECONDARY) {
float delay = mGuns[mGunIndex]->mGun->mDelay*0.75f;
if (delay < 150.0f) delay = 150.0f;
if (mStateTime >= delay) {
SetState(NORMAL);
}
}
else {
if (mStateTime >= 150.0f) {
SetState(NORMAL);
}
}
}
if (!mIsPlayerOnline) {
if (mNumDryFire > 3) {
Reload();
}
}
if (mIsFlashed) {
mFlashTime -= dt/mFlashIntensity;
if (mFlashTime < 0.0f) {
mFlashTime = 0.0f;
mIsFlashed = false;
}
}
//P: Same thing as regen just add a timer
mMuzzleFlashTime -= dt;
if (mMuzzleFlashTime < 0.0f) {
mMuzzleFlashTime = 0.0f;
}
mRadarTime -= dt;
if (mRadarTime < 0.0f) {
mRadarTime = 0.0f;
}
mCurrentAnimation->Update(dt,mKeyFrame);
mInvincibleTime -= dt;
if (mInvincibleTime < 0.0f) {
mInvincibleTime = 0.0f;
}
}
//------------------------------------------------------------------------------------------------
void Person::Render(float x, float y)
{
float offsetX = (x-SCREEN_WIDTH_2);
float offsetY = (y-SCREEN_HEIGHT_2);
if (mState != DEAD) {
float rotation = mRotation+M_PI_2;
float centerx = mX-offsetX-4*cosf(rotation);
float centery = mY-offsetY-4*sinf(rotation);
float x = centerx;
float y = centery;
float offsetangle = mWalkTime/WALKTIME*(M_PI_2);
float offset = 7*sinf(offsetangle);
if (mWalkState == WALK3 || mWalkState == WALK4) {
//offset = -offset;
mQuads[LEGS]->SetHFlip(true);
}
else {
mQuads[LEGS]->SetHFlip(false);
}
float dx = offset*cosf(mAngle);
float dy = offset*sinf(mAngle);
float x2 = x+dx;
float y2 = y+dy;
//mRenderer->FillCircle(x,y,12,ARGB(100,0,0,0));
/*rotation = mAngle;
if (rotation < 2*M_PI) {
rotation += 2*M_PI;
}*/
mRenderer->RenderQuad(mQuads[LEGS],x,y,mWalkAngle-M_PI_2,1.0f,offset/7);
//mQuads[RIGHTLEG]->SetVFlip(true);
//mRenderer->RenderQuad(mQuads[LEFTLEG],x+4*cosf(mWalkAngle-M_PI_2),y+4*sinf(mWalkAngle-M_PI_2),mWalkAngle-M_PI_2,1.0f,-offset/7);
//mRenderer->FillCircle(x+4*cosf(mWalkAngle-M_PI_2) - offset*cosf(mWalkAngle),y+4*sinf(mWalkAngle-M_PI_2) - offset*sinf(mWalkAngle),3.0f,ARGB(255,0,0,0));
//mRenderer->FillCircle(x+4*cosf(mWalkAngle+M_PI_2) + offset*cosf(mWalkAngle),y+4*sinf(mWalkAngle+M_PI_2) + offset*sinf(mWalkAngle),3.0f,ARGB(255,0,0,0));
if (mGuns[mGunIndex] != NULL) {
//mRenderer->RenderQuad(mGuns[mGunIndex]->mGun->mHandQuad,mX-offsetX,mY-offsetY,mLastFireAngle);
if (mGunIndex == KNIFE && (mState == ATTACKING || mState == DRYFIRING)) {
float angle = 0;
if (mStateTime < (mGuns[KNIFE]->mGun->mDelay*0.2f)) {
angle = mStateTime/(mGuns[KNIFE]->mGun->mDelay*0.2f);
}
else if (mStateTime >= (mGuns[KNIFE]->mGun->mDelay*0.2f)) {
angle = (mGuns[KNIFE]->mGun->mDelay-mStateTime)/(mGuns[KNIFE]->mGun->mDelay*0.8f);
}
//mGuns[mGunIndex]->mGun->mHandQuad->SetColor(ARGB(200,255,255,255));
//mRenderer->RenderQuad(mGuns[mGunIndex]->mGun->mHandQuad,mX-offsetX,mY-offsetY,mLastFireAngle+angle);
//mGuns[mGunIndex]->mGun->mHandQuad->SetColor(ARGB(255,255,255,255));
}
}
//mRenderer->RenderQuad(mQuads[mGunIndex],mX-offsetX,mY-offsetY,mRotation);
rotation = mRotation+M_PI_2;
centerx = mX-offsetX-5*cosf(rotation);
centery = mY-offsetY-5*sinf(rotation);
x = centerx;
y = centery;
dx = 10*cosf(mRotation+mKeyFrame.angles[BODY]);
dy = 10*sinf(mRotation+mKeyFrame.angles[BODY]);
x2 = x+dx;
y2 = y+dy;
if (mHasFlag) {
float tempx = x-10*cosf(rotation);
float tempy = y-10*sinf(rotation);
if (mTeam == T) {
gFlagQuad->SetColor(ARGB(255,153,204,255));
}
else {
gFlagQuad->SetColor(ARGB(255,255,64,64));
}
mRenderer->RenderQuad(gFlagQuad,tempx,tempy,mRotation+mKeyFrame.angles[BODY]-M_PI_4*0.6f);
}
mRenderer->RenderQuad(mQuads[BODY],x,y,mRotation+mKeyFrame.angles[BODY]);
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
x = x2;
y = y2;
x2 = x+8*cosf(rotation+mKeyFrame.angles[LEFTARM]);
y2 = y+8*sinf(rotation+mKeyFrame.angles[LEFTARM]);
mRenderer->RenderQuad(mQuads[LEFTARM],x,y,mRotation+mKeyFrame.angles[LEFTARM]);
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
x = x2;
y = y2;
//x2 = x+10*cosf(mRotation+mKeyFrame.angles[LEFTHAND]);
//y2 = y+10*sinf(mRotation+mKeyFrame.angles[LEFTHAND]);
mRenderer->RenderQuad(mQuads[LEFTHAND],x,y,mRotation+mKeyFrame.angles[LEFTHAND]);
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
x = centerx;
y = centery;
x2 = x-dx;
y2 = y-dy;
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
x = x2;
y = y2;
x2 = x+8*cosf(rotation+mKeyFrame.angles[RIGHTARM]);
y2 = y+8*sinf(rotation+mKeyFrame.angles[RIGHTARM]);
mRenderer->RenderQuad(mQuads[RIGHTARM],x,y,mRotation+mKeyFrame.angles[RIGHTARM]);
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
x = x2;
y = y2;
x2 = x+10*cosf(rotation+mKeyFrame.angles[RIGHTHAND]);
y2 = y+10*sinf(rotation+mKeyFrame.angles[RIGHTHAND]);
mRenderer->RenderQuad(mQuads[RIGHTHAND],x,y,mRotation+mKeyFrame.angles[RIGHTHAND]);
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
x = x2;
y = y2;
//x2 = x+11*cosf(mRotation+mKeyFrame.angles[GUN]);
//y2 = y+11*sinf(mRotation+mKeyFrame.angles[GUN]);
mRenderer->RenderQuad(mGuns[mGunIndex]->mGun->mHandQuad,x,y,mLastFireAngle+mKeyFrame.angles[GUN]);
if (mMuzzleFlashTime > 0.0f) {
/*x2 = x+10*cosf(rotation+mKeyFrame.angles[GUN]);
y2 = y+10*sinf(rotation+mKeyFrame.angles[GUN]);
x = x2;
y = y2;*/
//int alpha = mMuzzleFlashTime/100.0f*255;
//gMuzzleFlashQuads[mMuzzleFlashIndex]->SetColor(ARGB(alpha,255,255,255));
float scale = 1.0f;
if (mMuzzleFlashIndex >= 3) {
scale = 0.5f;
}
mRenderer->RenderQuad(gMuzzleFlashQuads[mMuzzleFlashIndex%3],x,y,mMuzzleFlashAngle-M_PI_2,1.0f,scale);
}
mRenderer->RenderQuad(mQuads[5],centerx,centery,mRotation);
//mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255));
/*mAnimationAngles[BODY] = 0.0f;
mAnimationAngles[RIGHTARM] = 0.0f;
mAnimationAngles[RIGHTHAND] = 0.0f;
mAnimationAngles[LEFTARM] = 0.0f;
mAnimationAngles[LEFTHAND] = 0.0f;
mAnimationAngles[GUN] = 0.0f;*/
//mRenderer->DrawCircle(mOldX-offsetX,mOldY-offsetY,16,ARGB(255,0,0,0));
//mRenderer->DrawCircle(mX-offsetX,mY-offsetY,16,ARGB(255,255,255,255));
if (mInvincibleTime > 0.0f) {
mRenderer->DrawCircle(mX-offsetX,mY-offsetY,17,ARGB(200,0,0,0));
mRenderer->DrawCircle(mX-offsetX,mY-offsetY,16,ARGB(255,255,255,255));
}
}
else {
if (mFadeTime > 0) {
mDeadQuad->SetColor(ARGB((int)(mFadeTime*(255.0f/1000.0f)),255,255,255));
mRenderer->RenderQuad(mDeadQuad,mX-offsetX,mY-offsetY,mRotation);
}
}
}
//------------------------------------------------------------------------------------------------
void Person::Move(float speed, float angle)
{
if (!mIsActive) return;
SetMoveState(MOVING);
mMaxSpeed = speed*mGuns[mGunIndex]->mGun->mSpeed;
if (mMovementStyle == RELATIVE1) {
mAngle = mFacingAngle+angle;
}
else if (mMovementStyle == ABSOLUTE1) {
mAngle = angle-M_PI_2;
}
if (mAngle > M_PI) {
mAngle -= 2*M_PI;
}
if (mAngle < -M_PI) {
mAngle += 2*M_PI;
}
}
//------------------------------------------------------------------------------------------------
std::vector<Bullet*> Person::Fire()
{
std::vector<Bullet*> bullets;
if (!mIsActive) return bullets;
if (mState == NORMAL) {
mIsFiring = true;
mHasFired = true;
if (mGunIndex == KNIFE) {
SetState(ATTACKING);
gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY);
//return true;
}
else if (mGunIndex == GRENADE) {
if (mGuns[mGunIndex]->mClipAmmo != 0) {
SetState(ATTACKING);
gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY);
}
}
else {
if (mGuns[mGunIndex]->mClipAmmo != 0) {
Bullet* bullet;
float h = 24*sinf(mFacingAngle);
float w = 24*cosf(mFacingAngle);
float theta = mFacingAngle;
float speed = 0.3f*mGuns[mGunIndex]->mGun->mBulletSpeed;
if (mGuns[mGunIndex]->mGun->mId == 7) {
theta -= mGuns[mGunIndex]->mGun->mSpread/2;//m0.36f;
float step = mGuns[mGunIndex]->mGun->mSpread/5;
for (int i=0; i<6; i++) {
theta += (rand()%11)/100.0f-0.05f;
bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this);
bullets.push_back(bullet);
mBullets->push_back(bullet);
theta += step;//0.144f;
}
}
else if (mGuns[mGunIndex]->mGun->mId == 8) {
theta -= mGuns[mGunIndex]->mGun->mSpread/2;//0.36f;
float step = mGuns[mGunIndex]->mGun->mSpread/3;
for (int i=0; i<4; i++) {
theta += (rand()%10)/100.0f-0.05f;
bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this);
bullets.push_back(bullet);
mBullets->push_back(bullet);
theta += step; //0.24f;
}
}
else {
if (mRecoilAngle*1000.0f >= 0.1f) {
theta += (rand()%(int)ceilf(mRecoilAngle*1000.0f))/1000.0f-(mRecoilAngle*0.5f);
//theta = mFacingAngle + (rand()%100)/400.0f-0.125f;
}
bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this);
bullets.push_back(bullet);
mBullets->push_back(bullet);
}
gParticleEngine->GenerateParticles(BULLETSHELL,mX+10*cosf(mFacingAngle),mY+10*sinf(mFacingAngle),1);
SetState(ATTACKING);
mGuns[mGunIndex]->mClipAmmo--;
//JSample *test = mEngine->LoadSample("sfx/m249.wav");
gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY);
mMuzzleFlashTime = 50.0f;
mMuzzleFlashAngle = mFacingAngle;
mMuzzleFlashIndex = mGuns[mGunIndex]->mGun->mType*3 + rand()%3;
mRadarTime = 2000.0f;
mRadarX = mX;
mRadarY = mY;
//return true;
}
else {
SetState(DRYFIRING);
gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mDryFireSound,mX,mY);
//return;
}
}
}
return bullets;
//return false;
}
//------------------------------------------------------------------------------------------------
std::vector<Bullet*> Person::StopFire()
{
std::vector<Bullet*> bullets;
if (!mIsActive) return bullets;
mIsFiring = false;
mHasFired = false;
if (mState == ATTACKING) {
if (mGunIndex == GRENADE) {
if (mGuns[mGunIndex]->mClipAmmo != 0) {
float h = 24*sinf(mFacingAngle);
float w = 24*cosf(mFacingAngle);
float theta = mFacingAngle;
float speed = 0.2f * mStateTime/(float)mGuns[mGunIndex]->mGun->mDelay;
int type = HE;
if (mGuns[mGunIndex]->mGun->mId == 25) { //FLASH
type = FLASH;
}
else if (mGuns[mGunIndex]->mGun->mId == 26) { //HE
type = HE;
}
else if (mGuns[mGunIndex]->mGun->mId == 27) { //SMOKE
type = SMOKE;
}
Grenade* grenade = new Grenade(mX+w,mY+h,mX,mY,theta,speed,this,type);
bullets.push_back(grenade);
mBullets->push_back(grenade);
SetState(NORMAL);
gSfxManager->PlaySample(gFireInTheHoleSound,mX,mY);
mGuns[mGunIndex]->mClipAmmo--;
delete mGuns[mGunIndex];
mGuns[mGunIndex] = NULL;
SwitchNext();
}
}
}
return bullets;
}
//------------------------------------------------------------------------------------------------
bool Person::Reload()
{
if (mGunIndex == KNIFE || mGunIndex == GRENADE) return false;
if (mState != RELOADING && mGuns[mGunIndex]->mClipAmmo != mGuns[mGunIndex]->mGun->mClip && mGuns[mGunIndex]->mRemainingAmmo != 0) {
SetState(RELOADING);
mSoundId = gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mReloadSound,mX,mY);
mNumDryFire = 0;
return true;
}
return false;
}
//------------------------------------------------------------------------------------------------
void Person::Switch(int index)
{
if (mGuns[index] != NULL) {
mGunIndex = index;
if (mState == RELOADING) {
//SetState(NORMAL);
if (mSoundId != -1) {
mSoundSystem->StopSample(mSoundId);
mSoundId = -1;
}
}
else if (mState == ATTACKING) {
//SetState(NORMAL);
}
mRecoilAngle = 0.0f;
mNumDryFire = 0;
SetState(SWITCHING);
}
}
//------------------------------------------------------------------------------------------------
void Person::SwitchNext()
{
if (mState == RELOADING) {
//SetState(NORMAL);
if (mSoundId != -1) {
mSoundSystem->StopSample(mSoundId);
mSoundId = -1;
}
}
else if (mState == ATTACKING) {
//SetState(NORMAL);
}
int gunindex = mGunIndex;
for (int i=0; i<5; i++) {
gunindex++;
if (gunindex > 4) {
gunindex = 0;
}
if (mGuns[gunindex] != NULL) break;
}
if (gunindex == mGunIndex) return;
mGunIndex = gunindex;
if (mGunIndex == PRIMARY) {
gSfxManager->PlaySample(gDeploySound,mX,mY);
}
/*if (mGunIndex == PRIMARY) {
if (mGuns[SECONDARY] != NULL) {
mGunIndex = SECONDARY;
}
else {
mGunIndex = KNIFE;
}
}
else if (mGunIndex == SECONDARY) {
if (mGuns[KNIFE] != NULL) {
mGunIndex = KNIFE;
}
else {
mGunIndex = PRIMARY;
gSfxManager->PlaySample(gDeploySound,mX,mY);
}
}
else if (mGunIndex == KNIFE) {
if (mGuns[PRIMARY] != NULL) {
mGunIndex = PRIMARY;
gSfxManager->PlaySample(gDeploySound,mX,mY);
}
else if (mGuns[SECONDARY] != NULL) {
mGunIndex = SECONDARY;
}
}*/
mRecoilAngle = 0.0f;
mNumDryFire = 0;
SetState(SWITCHING);
}
//------------------------------------------------------------------------------------------------
bool Person::PickUp(GunObject* gunobject)
{
if (gunobject->mGun->mType == PRIMARY) {
if (mGuns[PRIMARY] == NULL) {
mGuns[PRIMARY] = gunobject;
gunobject->mOnGround = false;
/*if (mState == RELOADING) {
SetState(NORMAL);
if (mSoundId != -1) {
mSoundSystem->StopSample(mSoundId);
mSoundId = -1;
}
}
mGunIndex = PRIMARY;*/
Switch(PRIMARY);
gSfxManager->PlaySample(gPickUpSound, mX, mY);
return true;
}
}
else if (gunobject->mGun->mType == SECONDARY) {
if (mGuns[SECONDARY] == NULL) {
mGuns[SECONDARY] = gunobject;
gunobject->mOnGround = false;
if (mGuns[PRIMARY] == NULL) {
//mGunIndex = SECONDARY;
Switch(SECONDARY);
}
gSfxManager->PlaySample(gPickUpSound, mX, mY);
return true;
}
}
else if (gunobject->mGun->mType == KNIFE) {
if (mGuns[KNIFE] == NULL) {
mGuns[KNIFE] = gunobject;
gunobject->mOnGround = false;
return true;
}
}
else if (gunobject->mGun->mType == GRENADE) {
if (mGuns[GRENADE] == NULL) {
mGuns[GRENADE] = gunobject;
gunobject->mOnGround = false;
if (mGuns[PRIMARY] == NULL && mGuns[SECONDARY] == NULL) {
//mGunIndex = GRENADE;
Switch(GRENADE);
}
gSfxManager->PlaySample(gPickUpSound, mX, mY);
return true;
}
}
return false;
}
//------------------------------------------------------------------------------------------------
bool Person::Drop(int index, float speed)
{
if (index >= 5) return false;
if (index == KNIFE) return false;
GunObject* gunobject = mGuns[index];
if (gunobject == NULL) return false;
/*if (mState == RELOADING) {
SetState(NORMAL);
if (mSoundId != -1) {
mSoundSystem->StopSample(mSoundId);
mSoundId = -1;
}
}*/
gunobject->mX = mX;
gunobject->mY = mY;
gunobject->mOldX = mX;
gunobject->mOldY = mY;
gunobject->mRotation = mRotation;
gunobject->mAngle = mFacingAngle;
gunobject->mSpeed = speed;
gunobject->mOnGround = false;
mGunObjects->push_back(gunobject);
mGuns[index] = NULL;
if (mGuns[PRIMARY] != NULL) {
//mGunIndex = PRIMARY;
Switch(PRIMARY);
}
else if (mGuns[SECONDARY] != NULL) {
//mGunIndex = SECONDARY;
Switch(SECONDARY);
}
else if (mGuns[GRENADE] != NULL) {
//mGunIndex = GRENADE;
Switch(GRENADE);
}
else if (mGuns[KNIFE] != NULL) {
//mGunIndex = KNIFE;
Switch(KNIFE);
}
//mRecoilAngle = 0.0f;
//mNumDryFire = 0;
return true;
}
//------------------------------------------------------------------------------------------------
void Person::RotateFacing(float theta)
{
float thetaTemp = mRotation + theta;
if (thetaTemp > M_PI*2.0f) { // angles are in radian, so 2 PI is one full circle
thetaTemp -= M_PI*2.0f;
}
else if (thetaTemp < 0) {
thetaTemp += M_PI*2.0f;
}
mRotation = thetaTemp;
thetaTemp = mFacingAngle + theta;
if (thetaTemp > M_PI*2.0f) { // angles are in radian, so 2 PI is one full circle
thetaTemp -= M_PI*2.0f;
}
else if (thetaTemp < 0) {
thetaTemp += M_PI*2.0f;
}
mFacingAngle = thetaTemp;
}
//------------------------------------------------------------------------------------------------
void Person::SetMoveState(int state)
{
if (mMoveState != state) {
mMoveState = state;
}
}
//------------------------------------------------------------------------------------------------
void Person::SetState(int state)
{
if (mState != state) {
mState = state;
mStateTime = 0;
if (mState == NORMAL || mState == SWITCHING) {
if (mGunIndex == PRIMARY) {
SetAnimation(ANIM_PRIMARY);
}
else if (mGunIndex == SECONDARY) {
SetAnimation(ANIM_SECONDARY);
}
else if (mGunIndex == KNIFE) {
SetAnimation(ANIM_KNIFE);
}
else if (mGunIndex == GRENADE) {
SetAnimation(ANIM_GRENADE);
}
}
else if (mState == ATTACKING) {
if (mGunIndex == PRIMARY) {
SetAnimation(ANIM_PRIMARY_FIRE);
//mCurrentAnimation->Reset();
//mCurrentAnimation->Play();
mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mDelay);
}
else if (mGunIndex == SECONDARY) {
SetAnimation(ANIM_SECONDARY_FIRE);
//mCurrentAnimation->Reset();
//mCurrentAnimation->Play();
mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mDelay);
}
else if (mGunIndex == KNIFE) {
SetAnimation(ANIM_KNIFE_SLASH);
//mCurrentAnimation->Reset();
//mCurrentAnimation->Play();
mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mDelay);
}
else if (mGunIndex == GRENADE) {
SetAnimation(ANIM_GRENADE_PULLBACK);
}
}
else if (mState == RELOADING) {
if (mGunIndex == PRIMARY) {
SetAnimation(ANIM_PRIMARY_RELOAD);
mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mReloadDelay);
}
else if (mGunIndex == SECONDARY) {
SetAnimation(ANIM_SECONDARY_RELOAD);
mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mReloadDelay);
}
}
}
if (mState == SWITCHING) {
if (mGunIndex == PRIMARY) {
SetAnimation(ANIM_PRIMARY);
//mCurrentAnimation->SetSpeed(100.0f/(mGuns[mGunIndex]->mGun->mDelay*0.75f));
}
else if (mGunIndex == SECONDARY) {
SetAnimation(ANIM_SECONDARY);
//mCurrentAnimation->SetSpeed(100.0f/(mGuns[mGunIndex]->mGun->mDelay*0.75f));
}
else if (mGunIndex == KNIFE) {
SetAnimation(ANIM_KNIFE);
mCurrentAnimation->SetSpeed(1);
}
else if (mGunIndex == GRENADE) {
SetAnimation(ANIM_GRENADE);
mCurrentAnimation->SetSpeed(1);
}
mKeyFrame.angles[GUN] = mCurrentAnimation->GetKeyFrame(0)->angles[GUN];
}
}
//------------------------------------------------------------------------------------------------
void Person::SetAnimation(int animation)
{
if (mCurrentAnimation != mAnimations[animation]) {
mCurrentAnimation->Reset();
mCurrentAnimation = mAnimations[animation];
mCurrentAnimation->Play();
}
else {
//mCurrentAnimation->Reset();
//mCurrentAnimation->Play();
}
}
//------------------------------------------------------------------------------------------------
void Person::SetTotalRotation(float theta)
{
mFacingAngle = theta;
mLastFireAngle = theta-M_PI_2;
mRotation = theta-M_PI_2;
mAngle = theta;
mWalkAngle = theta;
}
//------------------------------------------------------------------------------------------------
void Person::Die()
{
mStateTime = 0.0f;
StopFire();
Drop(mGunIndex,0);
Drop(GRENADE,0);
if (mSoundId != -1) {
mSoundSystem->StopSample(mSoundId);
mSoundId = -1;
}
if (mGuns[PRIMARY] != NULL) {
delete mGuns[PRIMARY];
mGuns[PRIMARY] = NULL;
}
if (mGuns[SECONDARY] != NULL) {
delete mGuns[SECONDARY];
mGuns[SECONDARY] = NULL;
}
/*if (mGunIndex != KNIFE) {
mGuns[mGunIndex] = NULL;
}*/
if (mGuns[GRENADE] != NULL) {
delete mGuns[GRENADE];
mGuns[GRENADE] = NULL;
}
mGunIndex = KNIFE;
mNumDryFire = 0;
gSfxManager->PlaySample(gDieSounds[rand()%3],mX,mY);
SetState(DEAD);
mFadeTime = 1000.0f;
SetMoveState(NOTMOVING);
mSpeed = 0.0f;
}
//------------------------------------------------------------------------------------------------
void Person::Reset()
{
//mX = mSpawn->x;
//mY = mSpawn->y;
//SetPosition(mSpawn->x,mSpawn->y);
//mOldX = mSpawn->x;
//mOldY = mSpawn->y;
SetTotalRotation(M_PI_2);
SetMoveState(NOTMOVING);
mSpeed = 0.0f;
mHealth = 100;
if (mState == DEAD) {
SetState(NORMAL);
}
if (mState == ATTACKING || mState == DRYFIRING) {
SetState(NORMAL);
}
mIsActive = false;
mIsFlashed = false;
mIsFiring = false;
mHasFired = false;
mWalkState = WALK1;
mWalkTime = 0.0f;
mWalkAngle = 0.0f;
mMuzzleFlashTime = 0.0f;
mRadarTime = 0.0f;
mHasFlag = false;
mGunMode = 0;
}
void Person::TakeDamage(int damage) {
if (mInvincibleTime > 0.0f) return;
if (mState != DEAD) {
SetMoveState(NOTMOVING);
mSpeed *= 0.1f;
mHealth -= damage;
if (mHealth <= 0) {
mHealth = 0;
Die();
}
}
}
void Person::ReceiveFlash(float intensity) {
if (mInvincibleTime > 0.0f) return;
mIsFlashed = true;
mFlashTime = 15000.0f;
if (intensity < 0.01f) {
intensity = 0.01f;
}
mFlashIntensity = intensity;
}
void Person::SetQuads(JQuad* quads[], JQuad* deadquad) {
for (int i=0; i<NUM_QUADS; i++) {
mQuads[i] = quads[i];
}
mDeadQuad = deadquad;
}
void Person::UpdateAngle(float &angle, float targetangle, float speed) {
float diffangle = angle-targetangle;
if (diffangle > M_PI) {
diffangle -= 2*M_PI;
}
if (diffangle < -M_PI) {
diffangle += 2*M_PI;
}
if (diffangle >= 0) {
if (diffangle < speed) {
angle = targetangle;
}
else {
angle -= speed;
}
}
else {
if (diffangle > -speed) {
angle = targetangle;
}
else {
angle += speed;
}
}
}
void Person::Teleport(float x, float y) {
mX = x;
mY = y;
mOldX = x;
mOldY = y;
mWalkX = x;
mWalkY = y;
} | 25.756822 | 156 | 0.601034 | MasterMenOfficial |
dbdd6d99ee992b4585d632517f4f5fd627ded9f8 | 1,187 | cpp | C++ | oled/main.cpp | FaizalSupriadi/IPASS | a5543f5b6ddd5da799148f09d7e59ec14f2b14fa | [
"BSL-1.0"
] | null | null | null | oled/main.cpp | FaizalSupriadi/IPASS | a5543f5b6ddd5da799148f09d7e59ec14f2b14fa | [
"BSL-1.0"
] | null | null | null | oled/main.cpp | FaizalSupriadi/IPASS | a5543f5b6ddd5da799148f09d7e59ec14f2b14fa | [
"BSL-1.0"
] | null | null | null | #include "oled.hpp"
#include "ball.hpp"
#include <array>
int main( void ){
namespace target = hwlib::target;
auto scl = target::pin_oc( target::pins::scl );
auto sda = target::pin_oc( target::pins::sda );
auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda( scl,sda );
auto display = oled( i2c_bus, 0x3c );
hwlib::xy location_ball( 0,32 );
hwlib::xy ball_speed( 5, 0 );
line top( display, hwlib::xy( 0, 0 ), hwlib::xy( 128, 0 ) );
line right( display, hwlib::xy( 127, 0 ), hwlib::xy( 127, 63 ) );
line bottom( display, hwlib::xy( 0, 63 ), hwlib::xy( 127, 63 ) );
line left( display, hwlib::xy( 0, 0 ), hwlib::xy( 0, 63 ) );
ball b( display, location_ball, 4, ball_speed );
std::array< drawable *, 5 > objects = { &b, &top,&right,&bottom,&left};
for(;;){
display.clear();
for( auto & p : objects ){
p->draw();
}
display.flush();
hwlib::wait_ms( 100 );
for( auto & p : objects ){
p->update();
}
for( auto & p : objects ){
for( auto & other : objects ){
p->interact( *other, location_ball );
}
}
}
} | 26.377778 | 74 | 0.528222 | FaizalSupriadi |
dbe03d19ea3fb4556459dcbde7ba94c8739445a5 | 1,895 | cpp | C++ | main.cpp | nks5117/MyCalc | f2fa2b344da94065239cbd09ca85b1c25f00290d | [
"MIT"
] | null | null | null | main.cpp | nks5117/MyCalc | f2fa2b344da94065239cbd09ca85b1c25f00290d | [
"MIT"
] | null | null | null | main.cpp | nks5117/MyCalc | f2fa2b344da94065239cbd09ca85b1c25f00290d | [
"MIT"
] | null | null | null | // main.cpp
// Copyright (c) 2018 Ni Kesu. All rights reserved.
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include "bigint.h"
#include "token.h"
#include "expression.h"
#include "variable.h"
#ifdef TIME
#include <ctime>
#endif
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
using std::string;
#define PROMPT '$'
std::vector<Variable> variableList;
void title() {
cout << "MyCalc v1.5.0\n";
cout << "[Type \"exit\" to exit]\n";
}
int main()
{
title();
variableList.push_back(Variable("ans", V_NA, ZERO, 0.0));
variableList.push_back(Variable("pi", V_DOUBLE, ZERO, 3.1415926535897));
variableList.push_back(Variable("e", V_DOUBLE, ZERO, 2.7182818284590));
variableList.push_back(Variable("c", V_BIGINT, BigInt(299792458), 0.0));
cout.precision(10);
Value ans;
while (1) {
cout << PROMPT << ' ';
string s;
getline(cin, s);
if (s == "exit") {
break;
}
bool showAnswer = (s[s.size() - 1] != ';');
if (!showAnswer) {
s.erase(s.end()-1);
}
#ifdef TIME
auto startTime = clock();
#endif
ans = Expression(s).evaluate();
if (showAnswer) {
cout << "ans =\n\n ";
}
if (ans.type() == V_DOUBLE) {
if (showAnswer) {
cout << ans.doubleValue() << endl << endl;
}
*(variableList[0].doubleValue()) = ans.doubleValue();
}
else if(ans.type() == V_BIGINT) {
if (showAnswer) {
cout << ans.intValue().toString() << endl << endl;
#ifdef TIME
auto endTime = clock();
cout << "total use " << (double)(endTime - startTime) / CLOCKS_PER_SEC
<< 's' << endl << endl;
#endif
}
*(variableList[0].intValue()) = ans.intValue();
}
variableList[0].setType(ans.type());
}
return 0;
}
| 21.055556 | 79 | 0.553562 | nks5117 |
dbe457c9850da84925d57176ca89b390a9d32715 | 376 | cpp | C++ | dp/longest-increasing-subsequence.cpp | beet-aizu/library-2 | 51579421d2c695ae298eed3943ca90f5224f768a | [
"Unlicense"
] | null | null | null | dp/longest-increasing-subsequence.cpp | beet-aizu/library-2 | 51579421d2c695ae298eed3943ca90f5224f768a | [
"Unlicense"
] | null | null | null | dp/longest-increasing-subsequence.cpp | beet-aizu/library-2 | 51579421d2c695ae298eed3943ca90f5224f768a | [
"Unlicense"
] | 1 | 2020-10-14T20:51:44.000Z | 2020-10-14T20:51:44.000Z | template< typename T >
size_t longest_increasing_subsequence(const vector< T > &a, bool strict) {
vector< T > lis;
for(auto &p : a) {
typename vector< T >::iterator it;
if(strict) it = lower_bound(begin(lis), end(lis), p);
else it = upper_bound(begin(lis), end(lis), p);
if(end(lis) == it) lis.emplace_back(p);
else *it = p;
}
return lis.size();
}
| 28.923077 | 74 | 0.62234 | beet-aizu |
dbe77bfa29b3acaa6bab9cfc57dfee288b284139 | 6,127 | cpp | C++ | src/services/pcn-nat/src/RuleDnatEntry.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-16T04:49:29.000Z | 2020-07-16T04:49:29.000Z | src/services/pcn-nat/src/RuleDnatEntry.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/services/pcn-nat/src/RuleDnatEntry.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 The Polycube 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.
*/
// Modify these methods with your own implementation
#include "RuleDnatEntry.h"
#include "Nat.h"
using namespace polycube::service;
RuleDnatEntry::RuleDnatEntry(RuleDnat &parent,
const RuleDnatEntryJsonObject &conf)
: parent_(parent) {
logger()->info("Creating RuleDnatEntry instance: {0} -> {1}",
conf.getExternalIp(), conf.getInternalIp());
update(conf);
}
RuleDnatEntry::~RuleDnatEntry() {}
void RuleDnatEntry::update(const RuleDnatEntryJsonObject &conf) {
// This method updates all the object/parameter in RuleDnatEntry object
// specified in the conf JsonObject.
// You can modify this implementation.
if (conf.externalIpIsSet()) {
setExternalIp(conf.getExternalIp());
}
if (conf.internalIpIsSet()) {
setInternalIp(conf.getInternalIp());
}
}
RuleDnatEntryJsonObject RuleDnatEntry::toJsonObject() {
RuleDnatEntryJsonObject conf;
conf.setId(getId());
conf.setExternalIp(getExternalIp());
conf.setInternalIp(getInternalIp());
return conf;
}
void RuleDnatEntry::create(RuleDnat &parent, const uint32_t &id,
const RuleDnatEntryJsonObject &conf) {
// This method creates the actual RuleDnatEntry object given thee key param.
// Please remember to call here the create static method for all sub-objects
// of RuleDnatEntry.
auto newRule = new RuleDnatEntry(parent, conf);
if (newRule == nullptr) {
// Totally useless, but it is needed to avoid the compiler making wrong
// assumptions and reordering
throw std::runtime_error("I won't be thrown");
}
// Check for duplicates
for (int i = 0; i < parent.rules_.size(); i++) {
auto rule = parent.rules_[i];
if (rule->getExternalIp() == newRule->getExternalIp()) {
throw std::runtime_error("Cannot insert duplicate mapping");
}
}
parent.rules_.resize(parent.rules_.size() + 1);
parent.rules_[parent.rules_.size() - 1].reset(newRule);
parent.rules_[parent.rules_.size() - 1]->id = id;
// Inject rule in the datapath table
newRule->injectToDatapath();
}
std::shared_ptr<RuleDnatEntry> RuleDnatEntry::getEntry(RuleDnat &parent,
const uint32_t &id) {
// This method retrieves the pointer to RuleDnatEntry object specified by its
// keys.
for (int i = 0; i < parent.rules_.size(); i++) {
if (parent.rules_[i]->id == id) {
return parent.rules_[i];
}
}
throw std::runtime_error("There is no rule " + id);
}
void RuleDnatEntry::removeEntry(RuleDnat &parent, const uint32_t &id) {
// This method removes the single RuleDnatEntry object specified by its keys.
// Remember to call here the remove static method for all-sub-objects of
// RuleDnatEntry.
if (parent.rules_.size() < id || !parent.rules_[id]) {
throw std::runtime_error("There is no rule " + id);
}
for (int i = 0; i < parent.rules_.size(); i++) {
if (parent.rules_[i]->id == id) {
// Remove rule from data path
parent.rules_[i]->removeFromDatapath();
break;
}
}
for (uint32_t i = id; i < parent.rules_.size() - 1; ++i) {
parent.rules_[i] = parent.rules_[i + 1];
parent.rules_[i]->id = i;
}
parent.rules_.resize(parent.rules_.size() - 1);
parent.logger()->info("Removed DNAT entry {0}", id);
}
std::vector<std::shared_ptr<RuleDnatEntry>> RuleDnatEntry::get(
RuleDnat &parent) {
// This methods get the pointers to all the RuleDnatEntry objects in RuleDnat.
std::vector<std::shared_ptr<RuleDnatEntry>> rules;
for (auto it = parent.rules_.begin(); it != parent.rules_.end(); ++it) {
if (*it) {
rules.push_back(*it);
}
}
return rules;
}
void RuleDnatEntry::remove(RuleDnat &parent) {
// This method removes all RuleDnatEntry objects in RuleDnat.
// Remember to call here the remove static method for all-sub-objects of
// RuleDnatEntry.
RuleDnat::removeEntry(parent.parent_);
}
uint32_t RuleDnatEntry::getId() {
// This method retrieves the id value.
return id;
}
std::string RuleDnatEntry::getExternalIp() {
// This method retrieves the externalIp value.
struct IpAddr addr = {externalIp, 32};
return addr.toString();
}
void RuleDnatEntry::setExternalIp(const std::string &value) {
// This method set the externalIp value.
struct IpAddr addr;
addr.fromString(value);
this->externalIp = addr.ip;
}
std::string RuleDnatEntry::getInternalIp() {
// This method retrieves the internalIp value.
struct IpAddr addr = {internalIp, 32};
return addr.toString();
}
void RuleDnatEntry::setInternalIp(const std::string &value) {
// This method set the internalIp value.
struct IpAddr addr;
addr.fromString(value);
this->internalIp = addr.ip;
}
std::shared_ptr<spdlog::logger> RuleDnatEntry::logger() {
return parent_.logger();
}
void RuleDnatEntry::injectToDatapath() {
auto dp_rules = parent_.parent_.getParent().get_hash_table<dp_k, dp_v>(
"dp_rules", 0, ProgramType::INGRESS);
dp_k key{
.mask = 32, .external_ip = externalIp, .external_port = 0, .proto = 0,
};
dp_v value{
.internal_ip = internalIp,
.internal_port = 0,
.entry_type = (uint8_t)NattingTableOriginatingRuleEnum::DNAT,
};
dp_rules.set(key, value);
}
void RuleDnatEntry::removeFromDatapath() {
auto dp_rules = parent_.parent_.getParent().get_hash_table<dp_k, dp_v>(
"dp_rules", 0, ProgramType::INGRESS);
dp_k key{
.mask = 32, .external_ip = externalIp, .external_port = 0, .proto = 0,
};
dp_rules.remove(key);
}
| 30.944444 | 80 | 0.681573 | mbertrone |
dbebb4e9cbedf7bafba78905508e2ea789ac01fb | 1,418 | cpp | C++ | lib/colortwist_ipp.cpp | ptahmose/colortwist | 6234d952d2550ad8d4f1fdd89f351d06fcdc78db | [
"BSD-2-Clause"
] | null | null | null | lib/colortwist_ipp.cpp | ptahmose/colortwist | 6234d952d2550ad8d4f1fdd89f351d06fcdc78db | [
"BSD-2-Clause"
] | 1 | 2020-10-25T19:53:38.000Z | 2020-10-25T19:53:38.000Z | lib/colortwist_ipp.cpp | ptahmose/colortwist | 6234d952d2550ad8d4f1fdd89f351d06fcdc78db | [
"BSD-2-Clause"
] | null | null | null | #include "colortwist.h"
#include "colortwist_config.h"
#if COLORTWISTLIB_HASIPP
#include "utils.h"
#include <ipp.h>
using namespace colortwist;
StatusCode colorTwistRGB48_IPP(const void* pSrc, std::uint32_t width, std::uint32_t height, int strideSrc, void* pDst, std::int32_t strideDst, const float* twistMatrix)
{
StatusCode rc = checkArgumentsRgb48(pSrc, width, strideSrc, pDst, strideDst, twistMatrix);
if (rc != colortwist::StatusCode::OK)
{
return rc;
}
IppStatus status = ippiColorTwist32f_16u_C3R((const Ipp16u*)pSrc, strideSrc, (Ipp16u*)pDst, strideDst, IppiSize{ (int)width,(int)height }, (const Ipp32f(*)[4]) twistMatrix);
return (status == ippStsNoErr || status == ippStsNoOperation) ? StatusCode::OK : StatusCode::UnspecifiedError;
}
colortwist::StatusCode colorTwistRGB24_IPP(const void* pSrc, uint32_t width, uint32_t height, int strideSrc, void* pDst, int strideDst, const float* twistMatrix)
{
StatusCode rc = checkArgumentsRgb24(pSrc, width, strideSrc, pDst, strideDst, twistMatrix);
if (rc != colortwist::StatusCode::OK)
{
return rc;
}
IppStatus status = ippiColorTwist32f_8u_C3R((const Ipp8u*)pSrc, strideSrc, (Ipp8u*)pDst, strideDst, IppiSize{ (int)width,(int)height }, (const Ipp32f(*)[4]) twistMatrix);
return (status == ippStsNoErr || status == ippStsNoOperation) ? StatusCode::OK : StatusCode::UnspecifiedError;
}
#endif | 39.388889 | 177 | 0.723554 | ptahmose |
dbed25ed91935f7368b91c880e51a28ea3ba8fba | 6,823 | cpp | C++ | modules/tracktion_engine/model/edit/tracktion_PitchSequence.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | null | null | null | modules/tracktion_engine/model/edit/tracktion_PitchSequence.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | null | null | null | modules/tracktion_engine/model/edit/tracktion_PitchSequence.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | null | null | null | /*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
namespace tracktion_engine
{
struct PitchSequence::PitchList : public ValueTreeObjectList<PitchSetting>,
private juce::AsyncUpdater
{
PitchList (PitchSequence& s, const juce::ValueTree& parentTree)
: ValueTreeObjectList<PitchSetting> (parentTree), pitchSequence (s)
{
rebuildObjects();
}
~PitchList() override
{
freeObjects();
}
bool isSuitableType (const juce::ValueTree& v) const override
{
return v.hasType (IDs::PITCH);
}
PitchSetting* createNewObject (const juce::ValueTree& v) override
{
auto t = new PitchSetting (pitchSequence.getEdit(), v);
t->incReferenceCount();
return t;
}
void deleteObject (PitchSetting* t) override
{
jassert (t != nullptr);
t->decReferenceCount();
}
void newObjectAdded (PitchSetting*) override { sendChange(); }
void objectRemoved (PitchSetting*) override { sendChange(); }
void objectOrderChanged() override { sendChange(); }
void valueTreePropertyChanged (juce::ValueTree&, const juce::Identifier&) override { sendChange(); }
void sendChange()
{
if (! pitchSequence.getEdit().isLoading())
triggerAsyncUpdate();
}
void handleAsyncUpdate() override
{
pitchSequence.getEdit().sendTempoOrPitchSequenceChangedUpdates();
}
PitchSequence& pitchSequence;
};
//==============================================================================
PitchSequence::PitchSequence() {}
PitchSequence::~PitchSequence() {}
Edit& PitchSequence::getEdit() const
{
jassert (edit != nullptr);
return *edit;
}
juce::UndoManager* PitchSequence::getUndoManager() const
{
return &getEdit().getUndoManager();
}
void PitchSequence::clear()
{
if (auto first = getPitch (0))
{
auto pitch = first->getPitch();
state.removeAllChildren (getUndoManager());
insertPitch (0, pitch);
}
else
{
jassertfalse;
}
}
void PitchSequence::initialise (Edit& ed, const juce::ValueTree& v)
{
edit = &ed;
state = v;
list = std::make_unique<PitchList> (*this, state);
if (getNumPitches() == 0)
insertPitch (0, 60);
sortEvents();
}
void PitchSequence::freeResources()
{
list.reset();
}
void PitchSequence::copyFrom (const PitchSequence& other)
{
copyValueTree (state, other.state, nullptr);
}
const juce::Array<PitchSetting*>& PitchSequence::getPitches() const { return list->objects; }
int PitchSequence::getNumPitches() const { return list->objects.size(); }
PitchSetting* PitchSequence::getPitch (int index) const { return list->objects[index]; }
PitchSetting& PitchSequence::getPitchAt (double time) const { return *list->objects[indexOfPitchAt (time)]; }
PitchSetting& PitchSequence::getPitchAtBeat (double beat) const
{
for (int i = list->objects.size(); --i > 0;)
{
auto p = list->objects.getUnchecked (i);
if (p->getStartBeatNumber() <= beat)
return *p;
}
jassert (list->size() > 0);
return *list->objects.getFirst();
}
int PitchSequence::indexOfPitchAt (double t) const
{
for (int i = list->objects.size(); --i > 0;)
if (list->objects.getUnchecked (i)->getPosition().getStart() <= t)
return i;
jassert (list->size() > 0);
return 0;
}
int PitchSequence::indexOfNextPitchAt (double t) const
{
for (int i = 0; i < list->objects.size(); ++i)
if (list->objects.getUnchecked (i)->getPosition().getStart() >= t)
return i;
jassert (list->size() > 0);
return list->objects.size();
}
int PitchSequence::indexOfPitch (const PitchSetting* pitchSetting) const
{
return list->objects.indexOf ((PitchSetting*) pitchSetting);
}
PitchSetting::Ptr PitchSequence::insertPitch (double time)
{
return insertPitch (edit->tempoSequence.timeToBeats (time), -1);
}
PitchSetting::Ptr PitchSequence::insertPitch (double beatNum, int pitch)
{
int newIndex = -1;
if (list->size() > 0)
{
auto& prev = getPitchAtBeat (beatNum);
// don't add in the same place as another one
if (prev.getStartBeatNumber() == beatNum)
{
if (pitch >= 0)
prev.setPitch (pitch);
return prev;
}
if (pitch < 0)
pitch = prev.getPitch();
newIndex = indexOfPitch (&prev) + 1;
}
auto v = createValueTree (IDs::PITCH,
IDs::startBeat, beatNum,
IDs::pitch, pitch);
if (newIndex < 0)
newIndex = list->objects.size();
state.addChild (v, newIndex, getUndoManager());
jassert (list->objects[newIndex]->state == v);
return list->objects[newIndex];
}
void PitchSequence::movePitchStart (PitchSetting& p, double deltaBeats, bool snapToBeat)
{
auto index = indexOfPitch (&p);
if (index > 0 && deltaBeats != 0)
{
if (auto t = getPitch (index))
{
t->startBeat.forceUpdateOfCachedValue();
auto newBeat = t->getStartBeat() + deltaBeats;
t->setStartBeat (juce::jlimit (0.0, 1e10, snapToBeat ? juce::roundToInt (newBeat)
: newBeat));
}
}
}
void PitchSequence::insertSpaceIntoSequence (double time, double amountOfSpaceInSeconds, bool snapToBeat)
{
// there may be a temp change at this time so we need to find the tempo to the left of it hence the nudge
time = time - 0.00001;
auto beatsToInsert = getEdit().tempoSequence.getBeatsPerSecondAt (time) * amountOfSpaceInSeconds;
auto endIndex = indexOfNextPitchAt (time);
for (int i = getNumPitches(); --i >= endIndex;)
movePitchStart (*getPitch (i), beatsToInsert, snapToBeat);
}
void PitchSequence::sortEvents()
{
struct PitchSorter
{
static int compareElements (const juce::ValueTree& p1, const juce::ValueTree& p2) noexcept
{
const double beat1 = p1[IDs::startBeat];
const double beat2 = p2[IDs::startBeat];
return beat1 < beat2 ? -1 : (beat1 > beat2 ? 1 : 0);
}
};
PitchSorter sorter;
state.sort (sorter, getUndoManager(), true);
}
}
| 27.623482 | 120 | 0.5757 | jbloit |
dbf0eced071dc9d3cb472b01f0c0649e75d58148 | 2,709 | cpp | C++ | Source/Ui/TreeItems/OnexTreeZlibItem.cpp | Pumbaa98/OnexExplorer | eaee2aa9f0e71b9960da586f425f79e628013021 | [
"BSL-1.0"
] | 14 | 2019-06-19T18:49:55.000Z | 2020-05-30T12:09:12.000Z | Source/Ui/TreeItems/OnexTreeZlibItem.cpp | Pumbaa98/OnexExplorer | eaee2aa9f0e71b9960da586f425f79e628013021 | [
"BSL-1.0"
] | 34 | 2019-06-21T20:19:11.000Z | 2019-12-10T22:16:54.000Z | Source/Ui/TreeItems/OnexTreeZlibItem.cpp | Pumba98/OnexExplorer | eaee2aa9f0e71b9960da586f425f79e628013021 | [
"BSL-1.0"
] | 3 | 2020-08-30T03:09:12.000Z | 2021-12-26T18:01:20.000Z | #include "OnexTreeZlibItem.h"
#include <QDate>
OnexTreeZlibItem::OnexTreeZlibItem(const QString &name, NosZlibOpener *opener, QByteArray content, int id, int creationDate, bool compressed)
: OnexTreeItem(name, opener, content), id(id), creationDate(creationDate),
compressed(compressed) {
if (creationDate == 0)
setCreationDate(QDate::currentDate().toString("dd/MM/yyyy"), true);
}
OnexTreeZlibItem::~OnexTreeZlibItem() = default;
int OnexTreeZlibItem::getId() {
return id;
}
int OnexTreeZlibItem::getCreationDate() {
return creationDate;
}
QString OnexTreeZlibItem::getDateAsString() {
int year = (getCreationDate() & 0xFFFF0000) >> 0x10;
int month = (getCreationDate() & 0xFF00) >> 0x08;
int day = getCreationDate() & 0xFF;
return QString("%1/%2/%3").arg(day, 2, 16, QChar('0')).arg(month, 2, 16, QChar('0')).arg(year, 4, 16, QChar('0'));
}
bool OnexTreeZlibItem::isCompressed() {
return compressed;
}
void OnexTreeZlibItem::setName(QString name) {
OnexTreeItem::setName(name);
setId(name.toInt(), true);
}
void OnexTreeZlibItem::setId(int id, bool update) {
this->id = id;
OnexTreeItem::setName(QString::number(id));
if (update)
emit changeSignal("ID", id);
}
void OnexTreeZlibItem::setCreationDate(const QString &date, bool update) {
QStringList parts = date.split("/", QString::SplitBehavior::SkipEmptyParts);
if (parts.size() != 3)
this->creationDate = 0;
else {
int year = parts[2].toInt(nullptr, 16) << 0x10;
int month = parts[1].toInt(nullptr, 16) << 0x08;
int day = parts[0].toInt(nullptr, 16);
this->creationDate = year + month + day;
}
if (update)
emit changeSignal("Date", getDateAsString());
}
void OnexTreeZlibItem::setCompressed(bool compressed, bool update) {
this->compressed = compressed;
if (update)
emit changeSignal("isCompressed", compressed);
}
FileInfo *OnexTreeZlibItem::generateInfos() {
auto *infos = OnexTreeItem::generateInfos();
if (getId() == -1) {
infos->addStringLineEdit("Header", QString::fromUtf8(getContent(), getContent().size()))->setEnabled(false);
} else {
connect(infos->addIntLineEdit("ID", getId()), &QLineEdit::textChanged,
[=](const QString &value) { setId(value.toInt()); });
connect(infos->addStringLineEdit("Date", getDateAsString()), &QLineEdit::textChanged,
[=](const QString &value) { setCreationDate(value); });
connect(infos->addCheckBox("isCompressed", isCompressed()), &QCheckBox::clicked,
[=](const bool value) { setCompressed(value); });
}
return infos;
}
| 34.291139 | 141 | 0.647471 | Pumbaa98 |
dbf3ef314931c15334401a0c51b45759e4e63f13 | 458 | hh | C++ | include/Bina_RunAction.hh | fenu-exp/BINA.simulation | 11c32e5abcd117a9d79d550d8d90028a0cc05835 | [
"MIT"
] | null | null | null | include/Bina_RunAction.hh | fenu-exp/BINA.simulation | 11c32e5abcd117a9d79d550d8d90028a0cc05835 | [
"MIT"
] | null | null | null | include/Bina_RunAction.hh | fenu-exp/BINA.simulation | 11c32e5abcd117a9d79d550d8d90028a0cc05835 | [
"MIT"
] | null | null | null | #ifndef Bina_RunAction_h
#define Bina_RunAction_h 1
#include "G4UserRunAction.hh"
#include "globals.hh"
#include "time.h"
#include "g4root.hh"
class G4Run;
class Bina_RunAction : public G4UserRunAction
{
public:
Bina_RunAction(bool);
virtual ~Bina_RunAction();
virtual void BeginOfRunAction(const G4Run* );
virtual void EndOfRunAction(const G4Run* );
bool root=false;
private:
clock_t fbegin;
clock_t fend;
};
#endif
| 17.615385 | 49 | 0.716157 | fenu-exp |
dbffda099bb561610ccce893764c56a956320804 | 23,298 | hpp | C++ | src/metadata.hpp | olivia76/cpp-sas7bdat | 1cd22561a13ee3df6bcec0b057f928de2014b81f | [
"Apache-2.0"
] | 4 | 2021-12-23T13:24:03.000Z | 2022-02-24T10:20:12.000Z | src/metadata.hpp | olivia76/cpp-sas7bdat | 1cd22561a13ee3df6bcec0b057f928de2014b81f | [
"Apache-2.0"
] | 6 | 2022-02-23T14:05:53.000Z | 2022-03-17T13:47:46.000Z | src/metadata.hpp | olivia76/cpp-sas7bdat | 1cd22561a13ee3df6bcec0b057f928de2014b81f | [
"Apache-2.0"
] | null | null | null | /**
* \file src/metadata.hpp
*
* \brief Metadata reading
*
* \author Olivia Quinet
*/
#ifndef _CPP_SAS7BDAT_SRC_METADATA_HPP_
#define _CPP_SAS7BDAT_SRC_METADATA_HPP_
#include "formatters.hpp"
#include "page.hpp"
namespace cppsas7bdat {
namespace INTERNAL {
constexpr const std::string_view COLUMN_DATETIME_FORMAT[] = {
"DATETIME", "DTWKDATX", "B8601DN", "B8601DT", "B8601DX",
"B8601DZ", "B8601LX", "E8601DN", "E8601DT", "E8601DX",
"E8601DZ", "E8601LX", "DATEAMPM", "DTDATE", "DTMONYY",
"DTMONYY", "DTWKDATX", "DTYEAR", "TOD", "MDYAMPM"};
constexpr const std::string_view COLUMN_DATE_FORMAT[] = {
"DATE", "DAY", "DDMMYY", "DOWNAME", "JULDAY", "JULIAN",
"MMDDYY", "MMYY", "MMYYC", "MMYYD", "MMYYP", "MMYYS",
"MMYYN", "MONNAME", "MONTH", "MONYY", "QTR", "QTRR",
"NENGO", "WEEKDATE", "WEEKDATX", "WEEKDAY", "WEEKV", "WORDDATE",
"WORDDATX", "YEAR", "YYMM", "YYMMC", "YYMMD", "YYMMP",
"YYMMS", "YYMMN", "YYMON", "YYMMDD", "YYQ", "YYQC",
"YYQD", "YYQP", "YYQS", "YYQN", "YYQR", "YYQRC",
"YYQRD", "YYQRP", "YYQRS", "YYQRN", "YYMMDDP", "YYMMDDC",
"E8601DA", "YYMMDDN", "MMDDYYC", "MMDDYYS", "MMDDYYD", "YYMMDDS",
"B8601DA", "DDMMYYN", "YYMMDDD", "DDMMYYB", "DDMMYYP", "MMDDYYP",
"YYMMDDB", "MMDDYYN", "DDMMYYC", "DDMMYYD", "DDMMYYS", "MINGUO"};
constexpr const std::string_view COLUMN_TIME_FORMAT[] = {"TIME"};
template <Format _format> struct METADATA_CONSTANT;
template <> struct METADATA_CONSTANT<Format::bit64> {
static constexpr const size_t lcs_offset = 682;
static constexpr const size_t lcp_offset = 706;
static constexpr const size_t compression_offset = 20;
static constexpr BYTE ROW_SIZE_SUBHEADER[][8] = {
{0x00, 0x00, 0x00, 0x00, 0xF7, 0xF7, 0xF7, 0xF7},
{0xF7, 0xF7, 0xF7, 0xF7, 0x00, 0x00, 0x00, 0x00}};
static constexpr BYTE COLUMN_SIZE_SUBHEADER[][8] = {
{0x00, 0x00, 0x00, 0x00, 0xF6, 0xF6, 0xF6, 0xF6},
{0xF6, 0xF6, 0xF6, 0xF6, 0x00, 0x00, 0x00, 0x00}};
static constexpr BYTE SUBHEADER_COUNTS_SUBHEADER[][8] = {
{0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x00}};
static constexpr BYTE COLUMN_TEXT_SUBHEADER[][8] = {
{0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD}};
static constexpr BYTE COLUMN_NAME_SUBHEADER[][8] = {
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
static constexpr BYTE COLUMN_ATTRIBUTES_SUBHEADER[][8] = {
{0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC}};
static constexpr BYTE FORMAT_AND_LABEL_SUBHEADER[][8] = {
{0xFE, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFE}};
static constexpr BYTE COLUMN_LIST_SUBHEADER[][8] = {
{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE}};
};
template <> struct METADATA_CONSTANT<Format::bit32> {
static constexpr const size_t lcs_offset = 354;
static constexpr const size_t lcp_offset = 378;
static constexpr const size_t compression_offset = 16;
static constexpr BYTE ROW_SIZE_SUBHEADER[][4] = {{0xF7, 0xF7, 0xF7, 0xF7}};
static constexpr BYTE COLUMN_SIZE_SUBHEADER[][4] = {{0xF6, 0xF6, 0xF6, 0xF6}};
static constexpr BYTE SUBHEADER_COUNTS_SUBHEADER[][4] = {
{0x00, 0xFC, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFC, 0x00}};
static constexpr BYTE COLUMN_TEXT_SUBHEADER[][4] = {{0xFD, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFD}};
static constexpr BYTE COLUMN_NAME_SUBHEADER[][4] = {{0xFF, 0xFF, 0xFF, 0xFF}};
static constexpr BYTE COLUMN_ATTRIBUTES_SUBHEADER[][4] = {
{0xFC, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFC}};
static constexpr BYTE FORMAT_AND_LABEL_SUBHEADER[][4] = {
{0xFE, 0xFB, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFB, 0xFE}};
static constexpr BYTE COLUMN_LIST_SUBHEADER[][4] = {{0xFE, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFE}};
};
template <typename _DataSource, Endian _endian, Format _format>
struct READ_METADATA : public READ_PAGE<_DataSource, _endian, _format>,
public METADATA_CONSTANT<_format> {
using DataSource = _DataSource;
constexpr static auto endian = _endian;
constexpr static auto format = _format;
using CBUFFER = INTERNAL::BUFFER<_endian, _format>;
constexpr static size_t integer_size = CBUFFER::integer_size;
using METADATA_CONSTANT<_format>::lcs_offset;
using METADATA_CONSTANT<_format>::lcp_offset;
using METADATA_CONSTANT<_format>::compression_offset;
using METADATA_CONSTANT<_format>::ROW_SIZE_SUBHEADER;
using METADATA_CONSTANT<_format>::COLUMN_SIZE_SUBHEADER;
using METADATA_CONSTANT<_format>::SUBHEADER_COUNTS_SUBHEADER;
using METADATA_CONSTANT<_format>::COLUMN_TEXT_SUBHEADER;
using METADATA_CONSTANT<_format>::COLUMN_NAME_SUBHEADER;
using METADATA_CONSTANT<_format>::COLUMN_ATTRIBUTES_SUBHEADER;
using METADATA_CONSTANT<_format>::FORMAT_AND_LABEL_SUBHEADER;
using METADATA_CONSTANT<_format>::COLUMN_LIST_SUBHEADER;
static constexpr const char RLE_COMPRESSION[] = "SASYZCRL";
static constexpr const char RDC_COMPRESSION[] = "SASYZCR2";
DATASUBHEADERS data_subheaders;
std::vector<std::string> column_texts;
std::vector<std::string> column_names;
std::vector<std::string> column_formats;
std::vector<std::string> column_labels;
std::vector<size_t> column_data_offsets;
std::vector<size_t> column_data_lengths;
std::vector<Column::Type> column_data_types;
using READ_PAGE<_DataSource, _endian, _format>::read_page;
using READ_PAGE<_DataSource, _endian, _format>::process_page_subheaders;
using READ_PAGE<_DataSource, _endian, _format>::current_page_header;
using READ_PAGE<_DataSource, _endian, _format>::buf;
READ_METADATA(READ_HEADER<_DataSource, _endian, _format> &&_rh,
const Properties::Header *_header)
: READ_PAGE<_DataSource, _endian, _format>(std::move(_rh.is),
std::move(_rh.buf), _header) {}
void set_metadata(Properties::Metadata *_metadata,
const Reader::PFILTER &_filter) {
while (read_page()) {
if (process_page(_metadata))
break;
}
create_columns(_metadata, _filter);
}
bool process_page(Properties::Metadata *_metadata) {
D(spdlog::info("process_page: type={}\n", current_page_header.type));
bool data_reached = false;
if (is_page_meta_mix_amd(current_page_header.type))
data_reached = process_page_metadata(_metadata);
return is_page_data_mix(current_page_header.type) || data_reached;
}
bool process_page_metadata(Properties::Metadata *_metadata) {
bool data_reached = false;
auto psh = [&](const PAGE_SUBHEADER &_psh) {
if (process_subheader(_psh, _metadata))
data_reached = true;
};
process_page_subheaders(psh);
return data_reached;
}
bool process_subheader(const PAGE_SUBHEADER &_subheader,
Properties::Metadata *_metadata) {
// Match the subheader signature to the correct processing function
const auto subheader_signature =
buf.get_bytes(_subheader.offset, integer_size);
if (match_signature(ROW_SIZE_SUBHEADER, subheader_signature)) {
process_ROW_SIZE_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(COLUMN_SIZE_SUBHEADER, subheader_signature)) {
process_COLUMN_SIZE_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(SUBHEADER_COUNTS_SUBHEADER, subheader_signature)) {
process_SUBHEADER_COUNTS_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(COLUMN_TEXT_SUBHEADER, subheader_signature)) {
process_COLUMN_TEXT_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(COLUMN_NAME_SUBHEADER, subheader_signature)) {
process_COLUMN_NAME_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(COLUMN_ATTRIBUTES_SUBHEADER, subheader_signature)) {
process_COLUMN_ATTRIBUTES_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(FORMAT_AND_LABEL_SUBHEADER, subheader_signature)) {
process_FORMAT_AND_LABEL_SUBHEADER(_subheader, _metadata);
return false;
}
if (match_signature(COLUMN_LIST_SUBHEADER, subheader_signature)) {
process_COLUMN_LIST_SUBHEADER(_subheader, _metadata);
return false;
}
if (DataSubHeader::check(_metadata, _subheader)) {
process_DATA_SUBHEADER(_subheader);
return true;
}
// Unknown subheader...
spdlog::warn("Unknown subheader signature!");
return false;
}
template <size_t n, size_t m>
static bool match_signature(const BYTE (&_s)[n][m],
const BYTES _signature) noexcept {
return std::any_of(std::begin(_s), std::end(_s),
[sig = _signature.data()](auto s) {
return std::memcmp(s, sig, m) == 0;
});
}
void
process_ROW_SIZE_SUBHEADER([[maybe_unused]] const PAGE_SUBHEADER &_subheader,
Properties::Metadata *_metadata) const noexcept {
D(spdlog::info("READ_METADATA::process_ROW_SIZE_SUBHEADER: {}, {} : ",
_subheader.offset, _subheader.length));
buf.assert_check(_subheader.offset + lcp_offset, 4);
_metadata->lcs = buf.get_uint16(_subheader.offset + lcs_offset);
_metadata->lcp = buf.get_uint16(_subheader.offset + lcp_offset);
_metadata->row_length =
buf.get_uinteger(_subheader.offset + 5 * integer_size);
_metadata->row_count =
buf.get_uinteger(_subheader.offset + 6 * integer_size);
_metadata->col_count_p1 =
buf.get_uinteger(_subheader.offset + 9 * integer_size);
_metadata->col_count_p2 =
buf.get_uinteger(_subheader.offset + 10 * integer_size);
_metadata->mix_page_row_count =
buf.get_uinteger(_subheader.offset + 15 * integer_size);
D(spdlog::info("lcs={}, lcp={}, row_length={}, row_count={}, "
"col_count_p1={}, col_count_p2={}, mix_page_row_count={}\n",
_metadata->lcs, _metadata->lcp, _metadata->row_length,
_metadata->row_count, _metadata->col_count_p1,
_metadata->col_count_p2, _metadata->mix_page_row_count));
}
void process_COLUMN_SIZE_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
Properties::Metadata *_metadata) const noexcept {
D(spdlog::info("READ_METADATA::process_COLUMN_SIZE_SUBHEADER: {}, {} : ",
_subheader.offset, _subheader.length));
_metadata->column_count = buf.template get_uinteger<ASSERT::YES>(
_subheader.offset + integer_size);
D(spdlog::info("column_count={}\n", _metadata->column_count));
if (_metadata->col_count_p1 + _metadata->col_count_p2 !=
_metadata->column_count)
spdlog::warn("Column count mismatch\n");
}
void process_SUBHEADER_COUNTS_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
[[maybe_unused]] Properties::Metadata *_metadata) const noexcept {
D(spdlog::info(
"READ_METADATA::process_SUBHEADER_COUNTS_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
// spdlog::info("READ_METADATA::process_SUBHEADER_COUNTS_SUBHEADER: {}\n",
// buf.get_string_untrim(_subheader.offset, _subheader.length));
}
void process_COLUMN_TEXT_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
Properties::Metadata *_metadata) noexcept {
D(spdlog::info("READ_METADATA::process_COLUMN_TEXT_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
const size_t length =
buf.template get_uint16<ASSERT::YES>(_subheader.offset + integer_size);
const auto text = buf.template get_string_untrim<ASSERT::YES>(
_subheader.offset + integer_size, length);
D(spdlog::info("text: {}\n", text));
column_texts.emplace_back(text);
if (column_texts.size() == 1) {
if (text.find(RLE_COMPRESSION) != text.npos)
_metadata->compression = Compression::RLE;
else if (text.find(RDC_COMPRESSION) != text.npos)
_metadata->compression = Compression::RDC;
const auto compression = buf.template get_string<ASSERT::YES>(
_subheader.offset + compression_offset, 8);
if (compression == "") {
_metadata->lcs = 0;
_metadata->creator_proc = buf.template get_string<ASSERT::YES>(
_subheader.offset + compression_offset + 16, _metadata->lcp);
} else if (compression == RLE_COMPRESSION) {
_metadata->creator_proc = buf.template get_string<ASSERT::YES>(
_subheader.offset + compression_offset + 24, _metadata->lcp);
} else if (_metadata->lcs > 0) {
_metadata->lcp = 0;
_metadata->creator = buf.template get_string<ASSERT::YES>(
_subheader.offset + compression_offset, _metadata->lcs);
}
D(spdlog::info("compression: {}, creator: {}, creator_proc: {}\n",
_metadata->compression, _metadata->creator,
_metadata->creator_proc));
}
}
std::string get_column_text_substr(const size_t _idx, size_t _offset,
size_t _length) const noexcept {
if (_idx < column_texts.size()) {
const auto ct = column_texts[std::min(_idx, column_texts.size() - 1)];
const auto n = ct.size();
_offset = std::min(_offset, n);
_length = std::min(_length, n - _offset);
if (_length && std::isprint(ct[_offset])) {
while (_length && std::isspace(ct[_offset])) {
++_offset;
--_length;
}
while (_length && (!std::isprint(ct[_offset + _length - 1]) ||
std::isspace(ct[_offset + _length - 1]))) {
--_length;
}
return ct.substr(_offset, _length);
}
}
return {};
}
void process_COLUMN_NAME_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
[[maybe_unused]] Properties::Metadata *_metadata) noexcept {
D(spdlog::info("READ_METADATA::process_COLUMN_NAME_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
const size_t offset_max =
_subheader.offset + _subheader.length - 12 - integer_size;
for (size_t offset = _subheader.offset + integer_size + 8;
offset <= offset_max; offset += 8) {
const size_t idx = buf.get_uint16(offset + 0);
const size_t name_offset = buf.get_uint16(offset + 2);
const size_t name_length = buf.get_uint16(offset + 4);
const auto column_name =
get_column_text_substr(idx, name_offset, name_length);
column_names.emplace_back(column_name);
D(spdlog::info("column name: {},{},{}: {}\n", idx, name_offset,
name_length, column_name));
}
}
void process_COLUMN_ATTRIBUTES_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
[[maybe_unused]] Properties::Metadata *_metadata) noexcept {
D(spdlog::info(
"READ_METADATA::process_COLUMN_ATTRIBUTES_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
const size_t offset_max =
_subheader.offset + _subheader.length - 12 - integer_size;
for (size_t offset = _subheader.offset + integer_size + 8;
offset <= offset_max; offset += integer_size + 8) {
const size_t column_data_offset = buf.get_uinteger(offset + 0);
const size_t column_data_length = buf.get_uint32(offset + integer_size);
const uint8_t column_data_type = buf.get_byte(offset + integer_size + 6);
column_data_offsets.emplace_back(column_data_offset);
column_data_lengths.emplace_back(column_data_length);
column_data_types.emplace_back(
column_data_type == 1 ? Column::Type::number : Column::Type::string);
D(spdlog::info("column attribute: {}, {}, {}\n", column_data_offset,
column_data_length, column_data_type));
}
}
void process_FORMAT_AND_LABEL_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
[[maybe_unused]] Properties::Metadata *_metadata) noexcept {
D(spdlog::info(
"READ_METADATA::process_FORMAT_AND_LABEL_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
const size_t offset = _subheader.offset + 3 * integer_size;
buf.assert_check(offset + 32, 2);
const size_t format_idx = buf.get_uint16(offset + 22);
const size_t format_offset = buf.get_uint16(offset + 24);
const size_t format_length = buf.get_uint16(offset + 26);
const size_t label_idx = buf.get_uint16(offset + 28);
const size_t label_offset = buf.get_uint16(offset + 30);
const size_t label_length = buf.get_uint16(offset + 32);
D(spdlog::info("column format: {}, {}, {}: ", format_idx, format_offset,
format_length));
const auto column_format =
get_column_text_substr(format_idx, format_offset, format_length);
D(spdlog::info("{}\n", column_format));
D(spdlog::info("column_label: {}, {}, {}: ", label_idx, label_offset,
label_length));
const auto column_label =
get_column_text_substr(label_idx, label_offset, label_length);
D(spdlog::info("{}\n", column_label));
column_formats.emplace_back(column_format);
column_labels.emplace_back(column_label);
}
void process_COLUMN_LIST_SUBHEADER(
[[maybe_unused]] const PAGE_SUBHEADER &_subheader,
[[maybe_unused]] Properties::Metadata *_metadata) const noexcept {
D(spdlog::info("READ_METADATA::process_COLUMN_LIST_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
// spdlog::info("READ_METADATA::process_COLUMN_LIST_SUBHEADER: {}\n",
// buf.get_string_untrim(_subheader.offset, _subheader.length));
}
void process_DATA_SUBHEADER([
[maybe_unused]] const PAGE_SUBHEADER &_subheader) noexcept {
D(spdlog::info("READ_METADATA::process_DATA_SUBHEADER: {}, {}\n",
_subheader.offset, _subheader.length));
data_subheaders.emplace_back(_subheader);
}
void create_columns(Properties::Metadata *_metadata,
const Reader::PFILTER &_filter) {
const size_t ncols = _metadata->column_count;
_metadata->columns.reserve(ncols);
auto get_value = [&](auto arg, auto vals, const size_t icol) {
const auto n = std::min(ncols, vals.size());
if (n != ncols)
spdlog::info("Mismatch between the expected number of columns ({}) and "
"the number ({}) of '{}' values!\n",
ncols, vals.size(), arg);
return vals.at(icol);
};
using Type = Column::Type;
for (size_t icol = 0; icol < ncols; ++icol) {
D(spdlog::info("READ_METADATA::create_columns: {}/{}\n", icol, ncols));
const auto column_name = get_value("name", column_names, icol);
const auto column_label = get_value("label", column_labels, icol);
const auto column_format = get_value("format", column_formats, icol);
const auto column_offset =
get_value("data_offset", column_data_offsets, icol);
const auto column_length =
get_value("data_length", column_data_lengths, icol);
const auto column_type = get_value("data_type", column_data_types, icol);
bool column_type_not_supported = true;
auto add_column = [&](auto &&formatter) {
D(spdlog::info("add_column: {}, {}, {}, {}, {}, {}\n", column_name,
column_label, column_format, column_offset,
column_length, column_type));
column_type_not_supported = false;
Column column(column_name, column_label, column_format,
std::forward<decltype(formatter)>(formatter));
if (!_filter || _filter->accept(column))
_metadata->columns.emplace_back(
std::move(column)); // column_name, column_label, column_format,
// std::move(formatter));
};
if (column_type == Type::string)
add_column(FORMATTER::StringFormatter(column_offset, column_length));
else if (column_type == Type::number) {
if (column_length == 1)
add_column(
FORMATTER::SmallIntegerFormatter(column_offset, column_length));
else if (column_length == 2)
add_column(FORMATTER::IntegerFormatter<_endian, int16_t>(
column_offset, column_length));
else if (is_datetime_format(column_format))
add_column(FORMATTER::DateTimeFormatter<_endian>(column_offset,
column_length));
else if (is_date_format(column_format))
add_column(
FORMATTER::DateFormatter<_endian>(column_offset, column_length));
else if (is_time_format(column_format))
add_column(
FORMATTER::TimeFormatter<_endian>(column_offset, column_length));
else {
if (column_length == 8)
add_column(FORMATTER::DoubleFormatter<_endian>(column_offset,
column_length));
else if (column_length == 3)
add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 3>(
column_offset, column_length));
else if (column_length == 4)
add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 4>(
column_offset, column_length));
else if (column_length == 5)
add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 5>(
column_offset, column_length));
else if (column_length == 6)
add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 6>(
column_offset, column_length));
else if (column_length == 7)
add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 7>(
column_offset, column_length));
}
}
if (column_type_not_supported) {
D(spdlog::warn("NoFormatter: {}, {}: ", column_type, column_format));
add_column(FORMATTER::NoFormatter(column_offset, column_length));
}
}
}
template <size_t n>
static bool match_column_format(const std::string_view (&_list)[n],
const std::string_view &_f) noexcept {
return std::any_of(std::begin(_list), std::end(_list),
[_f](auto _g) { return _f == _g; });
}
static bool is_datetime_format(const std::string_view &_f) noexcept {
return match_column_format(COLUMN_DATETIME_FORMAT, _f);
}
static bool is_date_format(const std::string_view &_f) noexcept {
return match_column_format(COLUMN_DATE_FORMAT, _f);
}
static bool is_time_format(const std::string_view &_f) noexcept {
return match_column_format(COLUMN_TIME_FORMAT, _f);
}
};
} // namespace INTERNAL
} // namespace cppsas7bdat
#endif
| 44.546845 | 80 | 0.651687 | olivia76 |
e001a967cddba7e6a3bea2882b635095df873de8 | 1,846 | hpp | C++ | include/emr/detail/marked_ptr.hpp | mpoeter/emr | 390ee0c3b92b8ad0adb897177202e1dd2c53a1b7 | [
"MIT"
] | 43 | 2017-12-07T13:28:02.000Z | 2022-03-23T13:51:11.000Z | include/emr/detail/marked_ptr.hpp | mpoeter/emr | 390ee0c3b92b8ad0adb897177202e1dd2c53a1b7 | [
"MIT"
] | 1 | 2019-07-22T17:08:17.000Z | 2019-07-24T04:58:09.000Z | include/emr/detail/marked_ptr.hpp | mpoeter/emr | 390ee0c3b92b8ad0adb897177202e1dd2c53a1b7 | [
"MIT"
] | 2 | 2019-02-26T08:26:53.000Z | 2019-10-17T04:06:16.000Z | #pragma once
#include <cassert>
#include <cstdint>
#include <cstddef>
namespace emr { namespace detail {
template <class T, std::size_t N>
class marked_ptr {
public:
// Construct a marked ptr
marked_ptr(T* p = nullptr, uintptr_t mark = 0) noexcept
{
assert(mark <= MarkMask && "mark exceeds the number of bits reserved");
assert((reinterpret_cast<uintptr_t>(p) & MarkMask) == 0 &&
"bits reserved for masking are occupied by the pointer");
ptr = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) | mark);
}
// Set to nullptr
void reset() noexcept { ptr = nullptr; }
// Get mark bits
uintptr_t mark() const noexcept {
return reinterpret_cast<uintptr_t>(ptr) & MarkMask;
}
// Get underlying pointer (with mark bits stripped off).
T* get() const noexcept {
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(ptr) & ~MarkMask);
}
// True if get() != nullptr || mark() != 0
explicit operator bool() const noexcept { return ptr != nullptr; }
// Get pointer with mark bits stripped off.
T* operator->() const noexcept { return get(); }
// Get reference to target of pointer.
T& operator*() const noexcept { return *get(); }
inline friend bool operator==(const marked_ptr& l, const marked_ptr& r) { return l.ptr == r.ptr; }
inline friend bool operator!=(const marked_ptr& l, const marked_ptr& r) { return l.ptr != r.ptr; }
static constexpr std::size_t number_of_mark_bits = N;
private:
static constexpr uintptr_t MarkMask = (1 << N) - 1;
T* ptr;
#ifdef _MSC_VER
// These members are only for the VS debugger visualizer (natvis).
enum Masking { MarkMask_ = MarkMask };
using PtrType = T*;
#endif
};
}}
| 31.827586 | 103 | 0.619177 | mpoeter |
e003be90313c7870a28c28c1b5ce22ea1c04647c | 1,730 | cpp | C++ | Module4/AYonaty_MergeSort/Source.cpp | ariyonaty/ECE3310 | 845d7204c16e84712fab2e25f79c0f16cb1e7c99 | [
"MIT"
] | null | null | null | Module4/AYonaty_MergeSort/Source.cpp | ariyonaty/ECE3310 | 845d7204c16e84712fab2e25f79c0f16cb1e7c99 | [
"MIT"
] | null | null | null | Module4/AYonaty_MergeSort/Source.cpp | ariyonaty/ECE3310 | 845d7204c16e84712fab2e25f79c0f16cb1e7c99 | [
"MIT"
] | 1 | 2021-09-22T04:01:52.000Z | 2021-09-22T04:01:52.000Z | /*
* Ari Yonaty
* ECE3310
* MergeSort
*/
#include <iostream>
#define N 10
void display(double*, int);
void mergeSort(double*, double*, int);
void bubbleSort(double*, int n);
void swap(double* x, double* y);
int main()
{
int x1[N], y1[N], x2[N], y2[N];
double a[N], b[N];
for (int i = 0; i < N; i++)
{
x1[i] = rand() % 301;
y1[i] = -10 + rand() % 21;
x2[i] = rand() % 301;
y2[i] = -10 + rand() % 21;
a[i] = 7.03 + 0.05 * x1[i] + y1[i];
b[i] = 7.03 + 0.05 * x2[i] + y2[i];
}
std::cout << "Array A before sort: ";
display(a, N);
std::cout << "Array B before sort: ";
display(b, N);
bubbleSort(a, N);
bubbleSort(b, N);
std::cout << "Array A after sort: ";
display(a, N);
std::cout << "Array B after sort: ";
display(b, N);
mergeSort(a, b, N);
return 0;
}
void swap(double* x, double* y)
{
double temp = *x;
*x = *y;
*y = temp;
}
void bubbleSort(double* arr, int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
}
}
void mergeSort(double* arr1, double* arr2, int size)
{
double x = arr1[0];
double y = arr2[0];
double result[2 * N];
int i = 0, j = 0, k = 0;
while (i < size && j < size)
{
if (arr1[i] <= arr2[j])
{
result[k] = arr1[i];
i++;
}
else
{
result[k] = arr2[j];
j++;
}
k++;
}
while (i < size)
{
result[k] = arr1[i];
i++;
k++;
}
while (j < size)
{
result[k] = arr2[j];
j++;
k++;
}
std::cout << "Array A+B after sorted merge: ";
display(result, 2 * N);
}
void display(double* arr, int size)
{
std::cout << std::endl;
for (int i = 0; i < size; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl << std::endl;
} | 15.043478 | 52 | 0.500578 | ariyonaty |
e00444a132d9267e92c2dcec29f71e6c7b7a02e3 | 1,401 | cc | C++ | src/cut_tree/greedy_treepacking.cc | math314/cut-tree | 0332ba0907af9a900e8c0c29c51a66428d9bed4b | [
"MIT"
] | 11 | 2016-09-27T06:49:44.000Z | 2021-11-17T01:12:23.000Z | iwiwi/src/agl/cut_tree/greedy_treepacking.cc | imos/icfpc2017 | d50c76b1f44e9289a92f564f319750049d952a5d | [
"MIT"
] | null | null | null | iwiwi/src/agl/cut_tree/greedy_treepacking.cc | imos/icfpc2017 | d50c76b1f44e9289a92f564f319750049d952a5d | [
"MIT"
] | 2 | 2016-10-01T16:32:44.000Z | 2018-10-10T13:41:55.000Z | #include "greedy_treepacking.h"
DEFINE_int32(cut_tree_gtp_dfs_edge_max, 1000000000, "greedy tree packing breadth limit");
using namespace std;
namespace agl {
void greedy_treepacking::dfs(int v) {
used_revision_[v] = vertices_revision_;
auto& to_edges = edges_[v];
const int rem_edges = min(to_edges.size(), FLAGS_cut_tree_gtp_dfs_edge_max);
for (int i = 0; i < rem_edges; i++) {
V to = to_edges.current();
// logging::gtp_edge_count++;
if (used_revision_[to] == vertices_revision_) {
to_edges.advance();
// logging::gtp_edge_miss++;
} else {
to_edges.remove_current();
inedge_count_[to]++; // in-edgeの本数が増える
dfs(to);
// logging::gtp_edge_use++;
}
}
}
greedy_treepacking::greedy_treepacking(const vector<pair<V, V>>& edges, int num_vs) :
n_(num_vs), edges_(n_), inedge_count_(n_), used_revision_(n_), vertices_revision_(1) {
for (auto& e : edges) {
edges_[e.first].add(e.second);
edges_[e.second].add(e.first);
}
for (auto& e : edges_) {
auto& edges_ = this->edges_;
sort(e.to_.begin(), e.to_.end(), [&edges_](const V l, const V r) {
int a = edges_[l].size();
int b = edges_[r].size();
return a < b;
});
}
}
void greedy_treepacking::arborescence_packing(int from) {
for (int i = 0; i < edges_[from].size(); i++) {
dfs(from);
vertices_revision_++;
}
}
} // namespace agl | 28.02 | 89 | 0.638116 | math314 |
e0074d5e13c7c6e6017b47a8ff8e2a7a4efd3403 | 1,756 | cpp | C++ | server/util/pending_buffer_test.cpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | 7 | 2019-04-09T16:25:49.000Z | 2021-12-07T10:29:52.000Z | server/util/pending_buffer_test.cpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | null | null | null | server/util/pending_buffer_test.cpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | 4 | 2019-08-07T07:43:27.000Z | 2021-05-21T07:54:14.000Z | #include "glog/logging.h"
#include "gtest/gtest.h"
#include "server/util/pending_buffer.hpp"
namespace minips {
namespace {
class TestPendingBuffer : public testing::Test {
public:
TestPendingBuffer() {}
~TestPendingBuffer() {}
protected:
void SetUp() {}
void TearDown() {}
};
TEST_F(TestPendingBuffer, Construct) { PendingBuffer pending_buffer; }
TEST_F(TestPendingBuffer, PushAndPop) {
PendingBuffer pending_buffer;
// Message m1
Message m1;
m1.meta.flag = Flag::kAdd;
m1.meta.model_id = 0;
m1.meta.sender = 2;
m1.meta.recver = 0;
third_party::SArray<int> m1_keys({0});
third_party::SArray<int> m1_vals({1});
m1.AddData(m1_keys);
m1.AddData(m1_vals);
// Message m2
Message m2;
m2.meta.flag = Flag::kAdd;
m2.meta.model_id = 0;
m2.meta.sender = 2;
m2.meta.recver = 0;
third_party::SArray<int> m2_keys({0});
third_party::SArray<int> m2_vals({1});
m2.AddData(m1_keys);
m2.AddData(m1_vals);
pending_buffer.Push(0, m1);
pending_buffer.Push(0, m1);
pending_buffer.Push(1, m2);
EXPECT_EQ(pending_buffer.Size(0), 2);
EXPECT_EQ(pending_buffer.Size(1), 1);
std::vector<Message> messages_0 = pending_buffer.Pop(0);
std::vector<Message> messages_1 = pending_buffer.Pop(1);
EXPECT_EQ(messages_0.size(), 2);
EXPECT_EQ(messages_1.size(), 1);
}
} // namespace
} // namespace minips
| 27.4375 | 78 | 0.531891 | RickAi |
e00a4486dab6c5fca623b352aa77483c766abc0d | 228 | hpp | C++ | pythran/pythonic/include/string/digits.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/string/digits.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/string/digits.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_INCLUDE_STRING_DIGITS_HPP
#define PYTHONIC_INCLUDE_STRING_DIGITS_HPP
#include "pythonic/types/str.hpp"
namespace pythonic
{
namespace string
{
types::str constexpr digits("0123456789");
}
}
#endif
| 14.25 | 46 | 0.77193 | xmar |
e00caeb79471fbd2811df2c101ec23e660c1ad7f | 1,340 | cpp | C++ | LeetCode practice/Finite state machine/best-time-to-buy-and-sell-stock-iii.cpp | 19hkm/algorithms | 6b4494ca9165e77b9c2672d88e8a89838e8eef8f | [
"MIT"
] | null | null | null | LeetCode practice/Finite state machine/best-time-to-buy-and-sell-stock-iii.cpp | 19hkm/algorithms | 6b4494ca9165e77b9c2672d88e8a89838e8eef8f | [
"MIT"
] | null | null | null | LeetCode practice/Finite state machine/best-time-to-buy-and-sell-stock-iii.cpp | 19hkm/algorithms | 6b4494ca9165e77b9c2672d88e8a89838e8eef8f | [
"MIT"
] | null | null | null | class Solution {
public:
inline void prepLeftSell(vector<int> &prices, vector<vector<int>> &dp){
int n = prices.size(), mini =1e5+1, maxi =0, maxP=0;
for(int i=0; i<n; i++){
if(prices[i]<mini){
mini = prices[i];
maxi = 0;
} else if(prices[i]>maxi){
maxi = prices[i];
maxP = maxi - mini;
}
dp[0][i] = maxP;
}
return;
}
inline void prepRightSell(vector<int> &prices, vector<vector<int>> &dp) {
int n = prices.size(), mini =1e5+1, maxi =0, maxP=0;
for(int i=n-1; i>=0; i--){
if(prices[i]>maxi){
maxi = prices[i];
mini = 1e5+1;
} else if(prices[i]<mini){
mini = prices[i];
maxP = maxi - mini;
}
dp[1][i] = maxP;
}
return;
}
int maxProfit(vector<int>& prices) {
int n = prices.size(), mini =1e5+1, maxi =0, maxP=0;
vector<vector<int>> dp(2, vector<int>(n,0));
prepLeftSell(prices, dp);
prepRightSell(prices, dp);
// printVec(dp);
for(int i=0;i<n;i++)
maxP = max(maxP, dp[0][i]+dp[1][i]);
return maxP;
}
}; | 27.916667 | 77 | 0.420149 | 19hkm |
e00e5e489184811fd9226712410bf485eca208fd | 410 | hpp | C++ | libs/core/math/include/bksge/core/math/fwd/color_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/math/include/bksge/core/math/fwd/color_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/math/include/bksge/core/math/fwd/color_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file color_fwd.hpp
*
* @brief Color の前方宣言
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_MATH_FWD_COLOR_FWD_HPP
#define BKSGE_CORE_MATH_FWD_COLOR_FWD_HPP
#include <cstddef>
namespace bksge
{
namespace math
{
template <typename T, std::size_t N>
class Color;
} // namespace math
using math::Color;
} // namespace bksge
#endif // BKSGE_CORE_MATH_FWD_COLOR_FWD_HPP
| 13.666667 | 44 | 0.682927 | myoukaku |
e01026b722c20138f6ce9f273ec4ed1d1362477e | 277 | hpp | C++ | lib/state/parser.hpp | julienlopez/Aronda-RL | d93602d2ebab0a099f16d316b488f2d4a6713aaf | [
"MIT"
] | null | null | null | lib/state/parser.hpp | julienlopez/Aronda-RL | d93602d2ebab0a099f16d316b488f2d4a6713aaf | [
"MIT"
] | 1 | 2018-04-04T08:45:24.000Z | 2018-04-04T08:45:24.000Z | lib/state/parser.hpp | julienlopez/Aronda-RL | d93602d2ebab0a099f16d316b488f2d4a6713aaf | [
"MIT"
] | null | null | null | #pragma once
#include "state.hpp"
#include <nlohmann_json/json.hpp>
namespace Aronda::State
{
class Parser
{
public:
static GameState parse(const std::string& json_string);
static Square parseSquare(const nlohmann::json& square, const Player current_player);
};
}
| 15.388889 | 89 | 0.740072 | julienlopez |
e015742e016dd048e33cb43e397a4e076d9951ef | 1,660 | cpp | C++ | src/netpayload/BinaryNetPayloadBase.cpp | andriyadi/PulseOximeterLib | f93ddea3fdc506a9937c410be147d658e5fed62d | [
"MIT"
] | null | null | null | src/netpayload/BinaryNetPayloadBase.cpp | andriyadi/PulseOximeterLib | f93ddea3fdc506a9937c410be147d658e5fed62d | [
"MIT"
] | null | null | null | src/netpayload/BinaryNetPayloadBase.cpp | andriyadi/PulseOximeterLib | f93ddea3fdc506a9937c410be147d658e5fed62d | [
"MIT"
] | null | null | null | //
// Created by Andri Yadi on 1/25/17.
//
#include "BinaryNetPayloadBase.h"
BinaryNetPayloadBase::~BinaryNetPayloadBase() {
}
void BinaryNetPayloadBase::copyTo(uint8_t* buffer, size_t size) const
{
if (size < getSize()) {
// TODO failed sanity check!
return;
}
memcpy(buffer, getBuffer(), size);
}
void BinaryNetPayloadBase::copyFrom(const uint8_t* buffer, size_t size)
{
//if (size != getSize()) {
if (size > getSize()) {
// TODO failed sanity check!
return;
}
memcpy(getBuffer(), buffer, size);
}
uint16_t BinaryNetPayloadBase::getFieldStart(uint8_t fieldIndex) const
{
uint16_t result = 0;
for (uint8_t i = 0; i < fieldIndex; i++) {
result += getFieldSize(i);
}
return result;
}
uint8_t BinaryNetPayloadBase::getFieldValue(uint8_t fieldIndex, uint8_t* buffer, size_t size) const
{
uint8_t fieldSize = getFieldSize(fieldIndex);
if (fieldIndex > getFieldCount() || fieldSize > size) {
printf("getFieldValue(): sanity check failed!\r\n");
return 0;
}
uint16_t fieldStart = getFieldStart(fieldIndex);
memcpy(buffer, getBuffer() + fieldStart, fieldSize); // already checked buffer size >= getFieldSize(fieldIndex)
return fieldSize;
}
void BinaryNetPayloadBase::setFieldValue(uint8_t fieldIndex, const uint8_t* buffer, uint8_t size) const
{
if (fieldIndex > getFieldCount() || size > getFieldSize(fieldIndex)) {
printf("setFieldValue(): sanity check failed!\r\n");
return;
}
uint16_t fieldStart = getFieldStart(fieldIndex);
memcpy(getBuffer() + fieldStart, buffer, getFieldSize(fieldIndex));
}
| 24.776119 | 115 | 0.66988 | andriyadi |
e017d3db3377c8f32921357f19817e94a0bfda74 | 2,379 | cxx | C++ | HallA/THaVDCHit.cxx | chandabindu/analyzer | 889be785858769446662ddf9ba250cc9d203bc47 | [
"BSD-3-Clause"
] | null | null | null | HallA/THaVDCHit.cxx | chandabindu/analyzer | 889be785858769446662ddf9ba250cc9d203bc47 | [
"BSD-3-Clause"
] | null | null | null | HallA/THaVDCHit.cxx | chandabindu/analyzer | 889be785858769446662ddf9ba250cc9d203bc47 | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// //
// THaVDCHit //
// //
// Class representing a single hit for the VDC //
// //
///////////////////////////////////////////////////////////////////////////////
#include "THaVDCHit.h"
#include "THaVDCTimeToDistConv.h"
#include "TError.h"
const Double_t THaVDCHit::kBig = 1.e38; // Arbitrary large value
using namespace VDC;
//_____________________________________________________________________________
Double_t THaVDCHit::ConvertTimeToDist(Double_t slope)
{
// Converts TDC time to drift distance
// Takes the (estimated) slope of the track as an argument
VDC::TimeToDistConv* ttdConv = (fWire) ? fWire->GetTTDConv() : NULL;
if (ttdConv) {
// If a time to distance algorithm exists, use it to convert the TDC time
// to the drift distance
fDist = ttdConv->ConvertTimeToDist(fTime, slope, &fdDist);
return fDist;
}
Error("ConvertTimeToDist()", "No Time to dist algorithm available");
return 0.0;
}
//_____________________________________________________________________________
Int_t THaVDCHit::Compare( const TObject* obj ) const
{
// Used to sort hits
// A hit is "less than" another hit if it occurred on a lower wire number.
// Also, for hits on the same wire, the first hit on the wire (the one with
// the smallest time) is "less than" one with a higher time. If the hits
// are sorted according to this scheme, they will be in order of increasing
// wire number and, for each wire, will be in the order in which they hit
// the wire
assert( obj && IsA() == obj->IsA() );
if( obj == this )
return 0;
#ifndef NDEBUG
const THaVDCHit* other = dynamic_cast<const THaVDCHit*>( obj );
assert( other );
#else
const THaVDCHit* other = static_cast<const THaVDCHit*>( obj );
#endif
ByWireThenTime isless;
if( isless( this, other ) )
return -1;
if( isless( other, this ) )
return 1;
return 0;
}
//_____________________________________________________________________________
ClassImp(THaVDCHit)
| 33.985714 | 79 | 0.570408 | chandabindu |
e018e31589187c6fc952e9abd3dfc6967b20aa87 | 25,774 | cpp | C++ | foedus_code/experiments-core/src/foedus/graphlda/lda.cpp | sam1016yu/cicada-exp-sigmod2017 | 64e582370076b2923d37b279d1c32730babc15f8 | [
"Apache-2.0"
] | null | null | null | foedus_code/experiments-core/src/foedus/graphlda/lda.cpp | sam1016yu/cicada-exp-sigmod2017 | 64e582370076b2923d37b279d1c32730babc15f8 | [
"Apache-2.0"
] | null | null | null | foedus_code/experiments-core/src/foedus/graphlda/lda.cpp | sam1016yu/cicada-exp-sigmod2017 | 64e582370076b2923d37b279d1c32730babc15f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP.
* This program 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 2 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 General Public License for
* more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* HP designates this particular file as subject to the "Classpath" exception
* as provided by HP in the LICENSE.txt file that accompanied this code.
*/
/**
* @file foedus/graphlda/lda.cpp
* @brief Latent-Dirichlet Allocation experiment for Topic Modeling
* @author kimurhid
* @date 2014/11/22
* @details
* This is a port of Fei Chen's LDA topic modeling program to FOEDUS.
*/
#include <stdint.h>
#include <boost/math/special_functions/gamma.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "foedus/engine.hpp"
#include "foedus/engine_options.hpp"
#include "foedus/error_stack.hpp"
#include "foedus/debugging/debugging_supports.hpp"
#include "foedus/debugging/stop_watch.hpp"
#include "foedus/fs/filesystem.hpp"
#include "foedus/memory/engine_memory.hpp"
#include "foedus/proc/proc_manager.hpp"
#include "foedus/soc/shared_memory_repo.hpp"
#include "foedus/soc/soc_manager.hpp"
#include "foedus/storage/storage_id.hpp"
#include "foedus/storage/storage_manager.hpp"
#include "foedus/storage/array/array_storage.hpp"
#include "foedus/thread/numa_thread_scope.hpp"
#include "foedus/thread/thread.hpp"
#include "foedus/thread/thread_pool.hpp"
#include "foedus/thread/thread_pool_pimpl.hpp"
#include "foedus/xct/xct_id.hpp"
#include "foedus/xct/xct_manager.hpp"
namespace foedus {
namespace graphlda {
DEFINE_string(dictionary_fname, "dictionary.txt", "Dictionary file");
DEFINE_string(counts_fname, "counts.tsv", "Counts file");
DEFINE_int32(ntopics, 50, "Number of topics");
DEFINE_int32(nburnin, 50, "Number of burnin iterations");
DEFINE_int32(nsamples, 10, "Number of sampling iterations");
DEFINE_int32(nthreads, 16, "Total number of threads");
DEFINE_double(alpha, 1.0, "Alpha prior");
DEFINE_double(beta, 0.1, "Beta prior");
DEFINE_bool(fork_workers, false, "Whether to fork(2) worker threads in child processes rather"
" than threads in the same process. This is required to scale up to 100+ cores.");
DEFINE_bool(profile, false, "Whether to profile the execution with gperftools.");
typedef uint32_t WordId;
typedef uint32_t DocId;
typedef uint16_t TopicId;
typedef uint32_t Count;
const TopicId kNullTopicId = -1;
/** Used for overflow check */
const Count kUnreasonablyLargeUint32 = (0xFFFF0000U);
inline Count check_overflow(Count count) {
if (count > kUnreasonablyLargeUint32) {
return 0;
} else {
return count;
}
}
// storage names
/**
* n_td(t,d) [1d: d * ntopics + t] Number of occurences of topic t in document d.
* As an array storage, it's d records of ntopics Count.
*/
const char* kNtd = "n_td";
/**
* n_tw(t,w) [1d: w * ntopics + t] Number of occurences of word w in topic t.
* As an array storage, it's w records of ntopics Count.
*/
const char* kNtw = "n_tw";
/**
* n_t(t) [1d: t] The total number of words assigned to topic t.
* As an array storage, it's 1 record of ntopics Count.
*/
const char* kNt = "n_t";
struct Token {
WordId word;
DocId doc;
Token(WordId word = 0, DocId doc = 0) : word(word), doc(doc) { }
};
std::ostream& operator<<(std::ostream& out, const Token& tok) {
return out << "(" << tok.word << ", " << tok.doc << ")";
}
/** This object is held only by the driver thread. Individual worker uses SharedInputs. */
struct Corpus {
size_t nwords, ndocs, ntokens;
std::vector< Token > tokens;
std::vector<std::string> dictionary;
Corpus(const fs::Path& dictionary_fname, const fs::Path& counts_fname)
: nwords(0), ndocs(0), ntokens(0) {
dictionary.reserve(20000);
tokens.reserve(100000);
load_dictionary(dictionary_fname);
load_counts(counts_fname);
}
void load_dictionary(const fs::Path& fname) {
std::ifstream fin(fname.c_str());
std::string str;
while (fin.good()) {
std::getline(fin, str);
if (fin.good()) {
dictionary.push_back(str);
nwords++;
}
}
fin.close();
}
void load_counts(const fs::Path& fname) {
std::ifstream fin(fname.c_str());
while (fin.good()) {
// Read a collection of tokens
const size_t NULL_VALUE(-1);
size_t word = NULL_VALUE, doc = NULL_VALUE, count = NULL_VALUE;
fin >> doc >> word >> count;
if (fin.good()) {
ASSERT_ND(word != NULL_VALUE && doc != NULL_VALUE && count != NULL_VALUE);
// update the doc counter
ndocs = std::max(ndocs, doc + 1);
// Assert valid word
ASSERT_ND(word < nwords);
// Update the words in document counter
// Add all the tokens
Token tok; tok.word = word; tok.doc = doc;
for (size_t i = 0; i < count; ++i) {
tokens.push_back(tok);
}
}
}
fin.close();
ntokens = tokens.size();
}
};
/** A copy of essential parts of Corpus, which can be placed in shared memory. No vector/string */
struct SharedInputs {
uint32_t nwords;
uint32_t ndocs;
uint32_t ntokens;
uint32_t ntopics;
uint32_t niterations;
double alpha;
double beta;
/**
* Actually "Token tokens[ntokens]" and then "TopicId topics[ntokens]".
* Note that you can't do sizeof(SharedCorpus).
*/
char dynamic_data[8];
static uint64_t get_object_size(uint32_t ntokens) {
return sizeof(SharedInputs) + (sizeof(Token) + sizeof(TopicId)) * ntokens;
}
void init(const Corpus& original) {
nwords = original.nwords;
ndocs = original.ndocs;
ntokens = original.ntokens;
ntopics = FLAGS_ntopics;
niterations = 0; // set separately
alpha = FLAGS_alpha;
beta = FLAGS_beta;
std::memcpy(get_tokens_data(), &(original.tokens[0]), sizeof(Token) * ntokens);
std::memset(get_topics_data(), 0xFFU, sizeof(TopicId) * ntokens); // null topic ID
}
Token* get_tokens_data() {
return reinterpret_cast<Token*>(dynamic_data);
}
TopicId* get_topics_data() {
return reinterpret_cast<TopicId*>(dynamic_data + sizeof(Token) * ntokens);
}
};
/** Core implementation of LDA experiment. */
class LdaWorker {
public:
enum Constant {
kIntNormalizer = 1 << 24,
kNtApplyBatch = 1 << 8,
};
explicit LdaWorker(const proc::ProcArguments& args) {
engine = args.engine_;
context = args.context_;
shared_inputs = reinterpret_cast<SharedInputs*>(
engine->get_soc_manager()->get_shared_memory_repo()->get_global_user_memory());
*args.output_used_ = 0;
}
ErrorStack on_lda_worker_task() {
uint16_t thread_id = context->get_thread_global_ordinal();
LOG(INFO) << "Thread-" << thread_id << " started";
unirand.set_current_seed(thread_id);
Token* shared_tokens = shared_inputs->get_tokens_data();
ntopics = shared_inputs->ntopics;
ntopics_aligned = assorted::align8(ntopics);
numwords = shared_inputs->nwords;
TopicId* shared_topics = shared_inputs->get_topics_data();
const uint32_t numtokens = shared_inputs->ntokens;
const uint32_t niterations = shared_inputs->niterations;
const uint16_t all_threads = engine->get_options().thread_.get_total_thread_count();
tokens_per_core = numtokens / all_threads;
int_a = static_cast<uint64_t>(shared_inputs->alpha * kIntNormalizer);
int_b = static_cast<uint64_t>(shared_inputs->beta * kIntNormalizer);
// allocate tmp memory on local NUMA node.
// These are the only memory that need dynamic allocation in main_loop
uint64_t tmp_memory_size = ntopics_aligned * sizeof(uint64_t) // conditional
+ tokens_per_core * sizeof(Token) // assigned_tokens
+ ntopics_aligned * sizeof(Count) // record_td
+ ntopics_aligned * sizeof(Count) // record_tw
+ ntopics_aligned * sizeof(Count) // record_t
+ ntopics_aligned * sizeof(Count) // record_t_diff
+ tokens_per_core * sizeof(TopicId); // topics_tmp
tmp_memory.alloc(
tmp_memory_size,
1 << 21,
memory::AlignedMemory::kNumaAllocOnnode,
context->get_numa_node());
char* tmp_block = reinterpret_cast<char*>(tmp_memory.get_block());
int_conditional = reinterpret_cast<uint64_t*>(tmp_block);
tmp_block += ntopics_aligned * sizeof(uint64_t);
assigned_tokens = reinterpret_cast<Token*>(tmp_block);
tmp_block += tokens_per_core * sizeof(Token);
record_td = reinterpret_cast<Count*>(tmp_block);
tmp_block += ntopics_aligned * sizeof(Count);
record_tw = reinterpret_cast<Count*>(tmp_block);
tmp_block += ntopics_aligned * sizeof(Count);
record_t = reinterpret_cast<Count*>(tmp_block);
tmp_block += ntopics_aligned * sizeof(Count);
record_t_diff = reinterpret_cast<Count*>(tmp_block);
tmp_block += ntopics_aligned * sizeof(Count);
topics_tmp = reinterpret_cast<TopicId*>(tmp_block);
tmp_block += tokens_per_core * sizeof(TopicId);
uint64_t size_check = tmp_block - reinterpret_cast<char*>(tmp_memory.get_block());
ASSERT_ND(size_check == tmp_memory_size);
// initialize with previous result (if this is burnin, all null-topic)
uint64_t assign_pos = tokens_per_core * thread_id;
std::memcpy(topics_tmp, shared_topics + assign_pos, tokens_per_core * sizeof(TopicId));
std::memcpy(assigned_tokens, shared_tokens + assign_pos, tokens_per_core * sizeof(Token));
n_td = storage::array::ArrayStorage(engine, kNtd);
n_tw = storage::array::ArrayStorage(engine, kNtw);
n_t = storage::array::ArrayStorage(engine, kNt);
ASSERT_ND(n_td.exists());
ASSERT_ND(n_tw.exists());
ASSERT_ND(n_t.exists());
nchanges = 0;
std::memset(int_conditional, 0, sizeof(uint64_t) * ntopics_aligned);
std::memset(record_td, 0, sizeof(Count) * ntopics_aligned);
std::memset(record_tw, 0, sizeof(Count) * ntopics_aligned);
std::memset(record_t, 0, sizeof(Count) * ntopics_aligned);
std::memset(record_t_diff, 0, sizeof(Count) * ntopics_aligned);
// Loop over all the tokens
for (size_t gn = 0; gn < niterations; ++gn) {
LOG(INFO) << "Thread-" << thread_id << " iteration " << gn << "/" << niterations;
WRAP_ERROR_CODE(main_loop());
}
// copy back the topics to shared. it's per-core, so this is the only thread that modifies it.
std::memcpy(shared_topics + assign_pos, topics_tmp, tokens_per_core * sizeof(TopicId));
const uint64_t ntotal = niterations * tokens_per_core;
LOG(INFO) << "Thread-" << thread_id << " done. nchanges/ntotal="
<< nchanges << "/" << ntotal << "=" << (static_cast<double>(nchanges) / ntotal);
return kRetOk;
}
private:
Engine* engine;
thread::Thread* context;
SharedInputs* shared_inputs;
uint16_t ntopics;
uint16_t ntopics_aligned;
uint32_t numwords;
uint32_t tokens_per_core;
uint64_t nchanges;
uint64_t int_a;
uint64_t int_b;
storage::array::ArrayStorage n_td; // d records of ntopics Count
storage::array::ArrayStorage n_tw; // w records of ntopics Count
storage::array::ArrayStorage n_t; // 1 record of ntopics Count
assorted::UniformRandom unirand;
/** local memory to back the followings */
memory::AlignedMemory tmp_memory;
uint64_t* int_conditional; // [ntopics]
Token* assigned_tokens; // [tokens_per_core]
Count* record_td; // [ntopics]
Count* record_tw; // [ntopics]
Count* record_t; // [ntopics]
Count* record_t_diff; // [ntopics]. This batches changes to n_t, which is so contentious.
TopicId* topics_tmp; // [tokens_per_core]
ErrorCode main_loop() {
xct::XctManager* xct_manager = engine->get_xct_manager();
uint16_t batched_t = 0;
for (size_t i = 0; i < tokens_per_core; ++i) {
// Get the word and document for the ith token
const WordId w = assigned_tokens[i].word;
const DocId d = assigned_tokens[i].doc;
const TopicId old_topic = topics_tmp[i];
CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead));
// First, read from the global arrays
CHECK_ERROR_CODE(n_td.get_record(context, d, record_td));
CHECK_ERROR_CODE(n_tw.get_record(context, w, record_tw));
// Construct the conditional
uint64_t normalizer = 0;
// We do the following calculation without double/float to speed up.
// Notation: int_x := x * N (eg, int_ntd := ntd * N, int_alpha = alpha * N)
// where N is some big number, such as 2^24
// conditional[t] = (a + ntd) * (b + ntw) / (b * nwords + nt)
// <=> conditional[t] = (int_a + int_ntd) * (b + ntw) / (int_b * nwords + int_nt)
// <=> int_conditional[t] = (int_a + int_ntd) * (int_b + int_ntw) / (int_b * nwords + int_nt)
for (TopicId t = 0; t < ntopics; ++t) {
uint64_t int_ntd = record_td[t], int_ntw = record_tw[t], int_nt = record_t[t];
if (t == old_topic) {
// locally apply the decrements. we apply it to global array
// when we are sure that new_topic != old_topic
--int_ntd;
--int_ntw;
--int_nt;
}
int_ntd = check_overflow(int_ntd) * kIntNormalizer;
int_ntw = check_overflow(int_ntw) * kIntNormalizer;
int_nt = check_overflow(int_nt) * kIntNormalizer;
int_conditional[t] = (int_a + int_ntd) * (int_b + int_ntw) / (int_b * numwords + int_nt);
normalizer += int_conditional[t];
}
// Draw a new valuez
TopicId new_topic = topic_multinomial(normalizer);
// Update the topic assignment and counters
if (new_topic != old_topic) {
nchanges++;
topics_tmp[i] = new_topic;
// We apply the inc/dec to global array only in this case.
if (old_topic != kNullTopicId) {
// Remove the word from the old counters
uint16_t offset = old_topic * sizeof(Count);
CHECK_ERROR_CODE(n_td.increment_record_oneshot<Count>(context, d, -1, offset));
CHECK_ERROR_CODE(n_tw.increment_record_oneshot<Count>(context, w, -1, offset));
// change to t are batched. will be applied later
--record_t[old_topic];
--record_t_diff[old_topic];
}
// Add the word to the new counters
uint16_t offset = new_topic * sizeof(Count);
CHECK_ERROR_CODE(n_td.increment_record_oneshot<Count>(context, d, 1, offset));
CHECK_ERROR_CODE(n_tw.increment_record_oneshot<Count>(context, w, 1, offset));
++record_t[new_topic];
++record_t_diff[new_topic];
Epoch ep;
// because this is not serializable level and the only update is one-shot increment,
// no race is possible.
CHECK_ERROR_CODE(xct_manager->precommit_xct(context, &ep));
++batched_t;
if (batched_t >= kNtApplyBatch) {
CHECK_ERROR_CODE(sync_record_t());
batched_t = 0;
}
} else {
CHECK_ERROR_CODE(xct_manager->abort_xct(context));
}
}
CHECK_ERROR_CODE(sync_record_t());
return kErrorCodeOk;
}
TopicId topic_multinomial(uint64_t normalizer) {
uint64_t sample = unirand.next_uint64() % normalizer;
uint64_t cur_sum = 0;
for (TopicId t = 0; t < ntopics; ++t) {
cur_sum += int_conditional[t];
if (sample <= cur_sum) {
return t;
}
}
return ntopics - 1U;
}
ErrorCode sync_record_t() {
xct::XctManager* xct_manager = engine->get_xct_manager();
Epoch ep;
// first, "flush" batched increments/decrements to the global n_t
// this transactionally applies all the inc/dec.
CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead));
for (TopicId t = 0; t < ntopics_aligned; t += 4) {
// for each uint64_t. we reserved additional size (align8) for simplifying this.
uint64_t diff = *reinterpret_cast<uint64_t*>(&record_t_diff[t]);
if (diff != 0) {
uint16_t offset = t * sizeof(Count);
CHECK_ERROR_CODE(n_t.increment_record_oneshot<uint64_t>(context, 0, diff, offset));
}
}
CHECK_ERROR_CODE(xct_manager->precommit_xct(context, &ep));
// then, retrive a fresh new copy of record_t, which contains updates from other threads.
std::memset(record_t, 0, sizeof(Count) * ntopics_aligned);
std::memset(record_t_diff, 0, sizeof(Count) * ntopics_aligned);
CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead));
CHECK_ERROR_CODE(n_t.get_record(context, 0, record_t));
CHECK_ERROR_CODE(xct_manager->abort_xct(context));
return kErrorCodeOk;
}
};
ErrorStack lda_worker_task(const proc::ProcArguments& args) {
LdaWorker worker(args);
return worker.on_lda_worker_task();
}
void run_workers(Engine* engine, SharedInputs* shared_inputs, uint32_t niterations) {
const EngineOptions& options = engine->get_options();
auto* thread_pool = engine->get_thread_pool();
std::vector< thread::ImpersonateSession > sessions;
shared_inputs->niterations = niterations;
for (uint16_t node = 0; node < options.thread_.group_count_; ++node) {
for (uint16_t ordinal = 0; ordinal < options.thread_.thread_count_per_group_; ++ordinal) {
thread::ImpersonateSession session;
bool ret = thread_pool->impersonate_on_numa_node(
node,
"worker_task",
nullptr,
0,
&session);
if (!ret) {
LOG(FATAL) << "Couldn't impersonate";
}
sessions.emplace_back(std::move(session));
}
}
LOG(INFO) << "Started running! #iter=" << niterations;
for (uint32_t i = 0; i < sessions.size(); ++i) {
LOG(INFO) << "result[" << i << "]=" << sessions[i].get_result();
COERCE_ERROR(sessions[i].get_result());
sessions[i].release();
}
LOG(INFO) << "Completed";
}
ErrorStack lda_populate_array_task(const proc::ProcArguments& args) {
ASSERT_ND(args.input_len_ == sizeof(storage::StorageId));
storage::StorageId storage_id = *reinterpret_cast<const storage::StorageId*>(args.input_buffer_);
storage::array::ArrayStorage array(args.engine_, storage_id);
ASSERT_ND(array.exists());
thread::Thread* context = args.context_;
uint16_t nodes = args.engine_->get_options().thread_.group_count_;
uint16_t node = context->get_numa_node();
uint64_t records_per_node = array.get_array_size() / nodes;
storage::array::ArrayOffset begin = records_per_node * node;
storage::array::ArrayOffset end = records_per_node * (node + 1U);
WRAP_ERROR_CODE(array.prefetch_pages(context, true, false, begin, end));
LOG(INFO) << "Population of " << array.get_name() << " done in node-" << node;
return kRetOk;
}
void create_count_array(
Engine* engine,
const char* name,
uint64_t records,
uint64_t counts) {
Epoch ep;
uint64_t counts_aligned = assorted::align8(counts);
storage::array::ArrayMetadata meta(name, counts_aligned * sizeof(Count), records);
COERCE_ERROR(engine->get_storage_manager()->create_storage(&meta, &ep));
LOG(INFO) << "Populating empty " << name << "(id=" << meta.id_ << ")...";
// populate it with one thread per node.
const EngineOptions& options = engine->get_options();
auto* thread_pool = engine->get_thread_pool();
std::vector< thread::ImpersonateSession > sessions;
for (uint16_t node = 0; node < options.thread_.group_count_; ++node) {
thread::ImpersonateSession session;
bool ret = thread_pool->impersonate_on_numa_node(
node,
"populate_array_task",
&meta.id_,
sizeof(meta.id_),
&session);
if (!ret) {
LOG(FATAL) << "Couldn't impersonate";
}
sessions.emplace_back(std::move(session));
}
for (uint32_t i = 0; i < sessions.size(); ++i) {
LOG(INFO) << "populate result[" << i << "]=" << sessions[i].get_result();
COERCE_ERROR(sessions[i].get_result());
sessions[i].release();
}
LOG(INFO) << "Populated empty " << name;
}
double run_experiment(Engine* engine, const Corpus &corpus) {
const EngineOptions& options = engine->get_options();
// Input information placed in shared memory
SharedInputs* shared_inputs = reinterpret_cast<SharedInputs*>(
engine->get_soc_manager()->get_shared_memory_repo()->get_global_user_memory());
ASSERT_ND(options.soc_.shared_user_memory_size_kb_ * (1ULL << 10)
>= SharedInputs::get_object_size(corpus.ntokens));
shared_inputs->init(corpus);
// create empty tables.
create_count_array(engine, kNtd, corpus.ndocs, FLAGS_ntopics);
create_count_array(engine, kNtw, corpus.nwords, FLAGS_ntopics);
create_count_array(engine, kNt, 1, FLAGS_ntopics);
LOG(INFO) << "Created arrays";
if (FLAGS_profile) {
COERCE_ERROR(engine->get_debug()->start_profile("lda.prof"));
}
debugging::StopWatch watch;
run_workers(engine, shared_inputs, FLAGS_nburnin);
LOG(INFO) << "Completed burnin!";
run_workers(engine, shared_inputs, FLAGS_nsamples);
LOG(INFO) << "Completed final sampling!";
watch.stop();
LOG(INFO) << "Experiment ended. Elapsed time=" << watch.elapsed_sec() << "sec";
if (FLAGS_profile) {
engine->get_debug()->stop_profile();
LOG(INFO) << "Check out the profile result: pprof --pdf lda lda.prof > lda.pdf; okular lda.pdf";
}
LOG(INFO) << "Shutting down...";
LOG(INFO) << engine->get_memory_manager()->dump_free_memory_stat();
return watch.elapsed_sec();
}
int driver_main(int argc, char** argv) {
gflags::SetUsageMessage("LDA sampler code");
gflags::ParseCommandLineFlags(&argc, &argv, true);
fs::Path dictionary_fname(FLAGS_dictionary_fname);
fs::Path counts_fname(FLAGS_counts_fname);
if (!fs::exists(dictionary_fname)) {
std::cerr << "The dictionary file doesn't exist: " << dictionary_fname;
return 1;
} else if (!fs::exists(counts_fname)) {
std::cerr << "The count file doesn't exist: " << counts_fname;
return 1;
}
fs::Path folder("/dev/shm/foedus_lda");
if (fs::exists(folder)) {
fs::remove_all(folder);
}
if (!fs::create_directories(folder)) {
std::cerr << "Couldn't create " << folder << ". err=" << assorted::os_error();
return 1;
}
EngineOptions options;
fs::Path savepoint_path(folder);
savepoint_path /= "savepoint.xml";
options.savepoint_.savepoint_path_.assign(savepoint_path.string());
ASSERT_ND(!fs::exists(savepoint_path));
std::cout << "NUMA node count=" << static_cast<int>(options.thread_.group_count_) << std::endl;
uint16_t thread_count = FLAGS_nthreads;
if (thread_count < options.thread_.group_count_) {
std::cout << "nthreads less than socket count. Using subset of sockets" << std::endl;
options.thread_.group_count_ = thread_count;
options.thread_.thread_count_per_group_ = 1;
} else if (thread_count % options.thread_.group_count_ != 0) {
std::cout << "nthreads not multiply of #sockets. adjusting" << std::endl;
options.thread_.thread_count_per_group_ = thread_count / options.thread_.group_count_;
} else {
options.thread_.thread_count_per_group_ = thread_count / options.thread_.group_count_;
}
options.snapshot_.folder_path_pattern_ = "/dev/shm/foedus_lda/snapshot/node_$NODE$";
options.snapshot_.snapshot_interval_milliseconds_ = 100000000U;
options.log_.folder_path_pattern_ = "/dev/shm/foedus_lda/log/node_$NODE$/logger_$LOGGER$";
options.log_.loggers_per_node_ = 1;
options.log_.flush_at_shutdown_ = false;
options.log_.log_file_size_mb_ = 1 << 16;
options.log_.emulation_.null_device_ = true;
options.memory_.page_pool_size_mb_per_node_ = 1 << 8;
options.cache_.snapshot_cache_size_mb_per_node_ = 1 << 6;
if (FLAGS_fork_workers) {
std::cout << "Will fork workers in child processes" << std::endl;
options.soc_.soc_type_ = kChildForked;
}
options.debugging_.debug_log_min_threshold_
= debugging::DebuggingOptions::kDebugLogInfo;
// = debugging::DebuggingOptions::kDebugLogWarning;
options.debugging_.verbose_modules_ = "";
options.debugging_.verbose_log_level_ = -1;
std::cout << "Loading the corpus." << std::endl;
Corpus corpus(dictionary_fname, counts_fname);
std::cout << "Number of words: " << corpus.nwords << std::endl
<< "Number of docs: " << corpus.ndocs << std::endl
<< "Number of tokens: " << corpus.ntokens << std::endl
<< "Number of topics: " << FLAGS_ntopics << std::endl
<< "Number of threads: " << options.thread_.get_total_thread_count() << std::endl
<< "Alpha: " << FLAGS_alpha << std::endl
<< "Beta: " << FLAGS_beta << std::endl;
options.soc_.shared_user_memory_size_kb_
= (SharedInputs::get_object_size(corpus.ntokens) >> 10) + 64;
double elapsed;
{
Engine engine(options);
engine.get_proc_manager()->pre_register("worker_task", lda_worker_task);
engine.get_proc_manager()->pre_register("populate_array_task", lda_populate_array_task);
COERCE_ERROR(engine.initialize());
{
UninitializeGuard guard(&engine);
elapsed = run_experiment(&engine, corpus);
COERCE_ERROR(engine.uninitialize());
}
}
std::cout << "All done. elapsed time=" << elapsed << "sec" << std::endl;
return 0;
}
} // namespace graphlda
} // namespace foedus
int main(int argc, char **argv) {
return foedus::graphlda::driver_main(argc, argv);
}
| 36.767475 | 100 | 0.680376 | sam1016yu |
e0208280f335a12f6264e041e2da3936af6a783e | 371 | cpp | C++ | test/src/access.cpp | mathchq/rapidstring | b9cd820ebe3076797ff82c7a3ca741b4bef74961 | [
"MIT"
] | 1 | 2019-11-11T13:02:15.000Z | 2019-11-11T13:02:15.000Z | test/src/access.cpp | mathchq/rapidstring | b9cd820ebe3076797ff82c7a3ca741b4bef74961 | [
"MIT"
] | null | null | null | test/src/access.cpp | mathchq/rapidstring | b9cd820ebe3076797ff82c7a3ca741b4bef74961 | [
"MIT"
] | null | null | null | #include "utility.hpp"
#include <string>
TEST_CASE("data")
{
const std::string first{ "Short!" };
const std::string second{ "A very long string to get around SSO!" };
rapidstring s1;
rs_init_w(&s1, first.data());
REQUIRE(first == rs_data(&s1));
rapidstring s2;
rs_init_w(&s2, second.data());
REQUIRE(second == rs_data(&s2));
rs_free(&s1);
rs_free(&s2);
}
| 17.666667 | 69 | 0.657682 | mathchq |
e02082c49cb7e4edd96cf299c82dc2db5227dc98 | 2,425 | cpp | C++ | detail/os/reactor/kqueue/events/kqueue_recv_from.cpp | wembikon/baba.io | 87bec680c1febb64356af59e7e499c2b2b64d30c | [
"MIT"
] | null | null | null | detail/os/reactor/kqueue/events/kqueue_recv_from.cpp | wembikon/baba.io | 87bec680c1febb64356af59e7e499c2b2b64d30c | [
"MIT"
] | 1 | 2020-06-12T10:22:09.000Z | 2020-06-12T10:22:09.000Z | detail/os/reactor/kqueue/events/kqueue_recv_from.cpp | wembikon/baba.io | 87bec680c1febb64356af59e7e499c2b2b64d30c | [
"MIT"
] | null | null | null | /**
* MIT License
* Copyright (c) 2020 Adrian T. Visarra
**/
#include "os/reactor/kqueue/events/kqueue_recv_from.h"
#include "baba/semantics.h"
#include "os/common/event_registrar.h"
namespace baba::os {
kqueue_recv_from::kqueue_recv_from(const lifetime &scope,
const std::shared_ptr<reactor_io_descriptor> &io_desc,
const enqueue_for_initiation_fn &enqueue_for_initiation,
const register_to_reactor_fn ®ister_to_reactor,
const enqueue_for_completion_fn &enqueue_for_completion,
const recv_from_fn &do_recv_from) noexcept
: _do_recv_from(do_recv_from), _evt(event_registrar::take()) {
RUNTIME_ASSERT(scope);
RUNTIME_ASSERT(io_desc);
_evt->scope = scope;
_evt->descriptor = io_desc;
_evt->enqueue_for_initiation = enqueue_for_initiation;
_evt->register_to_reactor = register_to_reactor;
_evt->enqueue_for_completion = enqueue_for_completion;
}
kqueue_recv_from::~kqueue_recv_from() noexcept {
auto final_evt = event_registrar::take();
final_evt->initiate = [final_evt, evt = _evt](io_handle) {
final_evt->complete = [final_evt, evt]() {
event_registrar::give(evt);
event_registrar::give(final_evt);
};
evt->enqueue_for_completion(final_evt);
};
_evt->enqueue_for_initiation(final_evt);
}
void kqueue_recv_from::recv_from(const ip_endpoint &receiver_ep, uint8_t *buffer, int size,
ip_endpoint &peer_ep, const receive_finish_fn &cb) noexcept {
_evt->initiate = [evt = _evt, cb](io_handle kqueue_fd) {
const auto ec = evt->register_to_reactor(kqueue_fd, evt, EVFILT_READ, 0, 0);
if (ec != ec::OK) {
evt->complete = [ec, cb]() { cb(ec, 0); };
evt->enqueue_for_completion(evt);
}
};
_evt->react = [evt = _evt, do_recv_from = _do_recv_from, &receiver_ep, buffer, size, &peer_ep,
cb]() {
int bytes = 0;
const auto ec = do_recv_from(evt->descriptor->fd, receiver_ep, buffer, size, peer_ep, bytes);
evt->complete = [ec, bytes, cb]() { cb(ec, bytes); };
evt->enqueue_for_completion(evt);
};
_evt->enqueue_for_initiation(_evt);
}
void kqueue_recv_from::recv_from() noexcept { _evt->enqueue_for_initiation(_evt); }
} // namespace baba::os | 39.112903 | 98 | 0.641237 | wembikon |
e025e5f805617de080c45ae6a3949e93a36d99f2 | 1,879 | hpp | C++ | inst/include/spress/hilbert.hpp | UFOKN/spress | 8073fde53ced4f006634f761e6f90517ccf2f229 | [
"MIT"
] | 1 | 2021-12-09T22:16:27.000Z | 2021-12-09T22:16:27.000Z | inst/include/spress/hilbert.hpp | UFOKN/spress | 8073fde53ced4f006634f761e6f90517ccf2f229 | [
"MIT"
] | null | null | null | inst/include/spress/hilbert.hpp | UFOKN/spress | 8073fde53ced4f006634f761e6f90517ccf2f229 | [
"MIT"
] | null | null | null | #pragma once
#ifndef _SPRESS_HILBERT_H_
#define _SPRESS_HILBERT_H_
#include <numeric>
using std::size_t;
namespace spress
{
namespace hilbert
{
/**
* Rotate X/Y coordinates based on Hilbert Curve.
* @param n Dimensions of n x n grid. Must be a power of 2.
* @param x [out] Pointer to the X coordinate variable
* @param y [out] Pointer to the Y coordinate variable
* @param rx Numeric bool for determining if rotation is needed
* @param ry Numeric bool for determining if rotation is needed
*/
inline void rotate(size_t n, size_t *x, size_t *y, size_t rx, size_t ry)
{
if (ry == 0) {
if (rx == 1) {
*x = n - 1LL - *x;
*y = n - 1LL - *y;
}
size_t t = *x;
*x = *y;
*y = t;
}
}
/**
* Convert a grid position to a Hilbert Curve index.
* @param n Dimensions of n x n grid. Must be a power of 2.
* @param x X coordinate in grid form
* @param y Y coordinate in grid form
*/
inline size_t pos_index(size_t n, size_t x, size_t y)
{
size_t rx, ry;
size_t d = 0LL;
for (size_t s = n / 2LL; s > 0LL; s /= 2LL) {
rx = (x & s) > 0LL;
ry = (y & s) > 0LL;
d += s * s * ((3LL * rx) ^ ry);
rotate(n, &x, &y, rx, ry);
}
return d;
}
/**
* Convert a Hilbert Curve index to a grid position.
* @param n Dimensions of n x n grid. Must be a power of 2.
* @param d Hilbert Curve index/distance.
* @param x [out] Pointer to X coordinate variable
* @param y [out] Pointer to Y coordinate variable
*/
inline void index_pos(size_t n, size_t d, size_t *x, size_t *y)
{
size_t rx, ry;
size_t t = d;
*x = 0LL;
*y = 0LL;
for (size_t s = 1LL; s < n; s *= 2LL) {
rx = 1LL & (t / 2LL);
ry = 1LL & (t ^ rx);
rotate(s, x, y, rx, ry);
*x += s * rx;
*y += s * ry;
t /= 4LL;
}
}
}
}
#endif | 22.638554 | 72 | 0.557743 | UFOKN |
e028ab7a30e55a3b90c8a5fab3112bfa01ca55f0 | 8,931 | cpp | C++ | src/utils/fns.cpp | melchor629/node-flac-bindings | 584bd52ef12de4562dca0f198220f2c136666ce2 | [
"0BSD"
] | 13 | 2017-01-07T07:48:54.000Z | 2021-09-29T05:33:38.000Z | src/utils/fns.cpp | melchor629/node-flac-bindings | 584bd52ef12de4562dca0f198220f2c136666ce2 | [
"0BSD"
] | 27 | 2016-11-24T11:35:22.000Z | 2022-02-14T14:38:09.000Z | src/utils/fns.cpp | melchor629/node-flac-bindings | 584bd52ef12de4562dca0f198220f2c136666ce2 | [
"0BSD"
] | 3 | 2017-10-19T10:12:11.000Z | 2019-10-11T16:21:09.000Z | #include "converters.hpp"
#include "js_utils.hpp"
#include "pointer.hpp"
namespace flac_bindings {
static int64_t readI32(const void* buff) {
return *((const int32_t*) buff);
}
static void writeI32(void* buff, int64_t value) {
*((int32_t*) buff) = value;
}
static int64_t readI24(const void* buff) {
const auto tmp = (const uint8_t*) buff;
const uint64_t val = tmp[0] | (tmp[1] << 8) | (tmp[2] << 16);
return val | (val & 0x800000) * 0x1FE;
}
static void writeI24(void* buff, int64_t value) {
auto tmp = (uint8_t*) buff;
tmp[0] = value & 0xFF;
tmp[1] = (value >> 8) & 0xFF;
tmp[2] = (value >> 16) & 0xFF;
}
static int64_t readI16(const void* buff) {
return *((const int16_t*) buff);
}
static void writeI16(void* buff, int64_t value) {
*((int16_t*) buff) = value;
}
static int64_t readI8(const void* buff) {
return *((const int8_t*) buff);
}
static void writeI8(void* buff, int64_t value) {
*((int8_t*) buff) = value;
}
typedef int64_t (*BufferReader)(const void* buff);
static inline BufferReader getReader(uint64_t inBps, Napi::Env env) {
switch (inBps) {
case 1:
return readI8;
case 2:
return readI16;
case 3:
return readI24;
case 4:
return readI32;
default:
throw Napi::Error::New(env, "Unsupported "s + std::to_string(inBps) + " bits per sample"s);
}
}
typedef void (*BufferWriter)(void* buff, int64_t);
static inline BufferWriter getWriter(uint64_t outBps, Napi::Env env) {
switch (outBps) {
case 1:
return writeI8;
case 2:
return writeI16;
case 3:
return writeI24;
case 4:
return writeI32;
default:
throw Napi::Error::New(env, "Unsupported "s + std::to_string(outBps) + " bits per sample"s);
}
}
static Napi::Value zipAudio(const Napi::CallbackInfo& info) {
using namespace Napi;
EscapableHandleScope scope(info.Env());
if (!info[0].IsObject()) {
throw TypeError::New(info.Env(), "Expected first argument to be object");
}
auto obj = info[0].As<Object>();
auto samples = numberFromJs<uint64_t>(obj.Get("samples"));
auto inBps = maybeNumberFromJs<uint64_t>(obj.Get("inBps")).value_or(4);
auto outBps = maybeNumberFromJs<uint64_t>(obj.Get("outBps")).value_or(4);
auto buffers = arrayFromJs<char*>(obj.Get("buffers"), [&samples, &inBps](auto val) {
if (!val.IsBuffer()) {
throw TypeError::New(val.Env(), "Expected value in buffers to be a Buffer");
}
auto buffer = val.template As<Buffer<char>>();
if (buffer.ByteLength() < samples * inBps) {
throw RangeError::New(
val.Env(),
"Buffer has size "s + std::to_string(buffer.ByteLength())
+ " but expected to be at least "s + std::to_string(samples * inBps));
}
return buffer.Data();
});
auto channels = buffers.size();
if (samples == 0 || inBps == 0 || outBps == 0 || channels == 0) {
throw Error::New(info.Env(), "Invalid value for one of the given properties");
}
// NOTE: if outBps > inBps means that after one sample copy, there is some bytes that need
// to be cleared up. To be faster, all memory is cleared when allocated.
// the reader and writer functions are here to properly read and write ints.
auto reader = getReader(inBps, info.Env());
auto writer = getWriter(outBps, info.Env());
uint64_t outputBufferSize = samples * outBps * channels;
char* outputBuffer =
(char*) (outBps <= inBps ? malloc(outputBufferSize) : calloc(outputBufferSize, 1));
for (uint64_t sample = 0; sample < samples; sample++) {
for (uint64_t channel = 0; channel < channels; channel++) {
char* out = outputBuffer + (sample * channels + channel) * outBps;
char* in = buffers[channel] + sample * inBps;
auto value = reader(in);
writer(out, value);
}
}
return scope.Escape(
Buffer<char>::New(info.Env(), outputBuffer, outputBufferSize, [](auto, auto data) {
free(data);
}));
}
static Napi::Value unzipAudio(const Napi::CallbackInfo& info) {
using namespace Napi;
EscapableHandleScope scope(info.Env());
if (!info[0].IsObject()) {
throw TypeError::New(info.Env(), "Expected first argument to be object");
}
auto obj = info[0].As<Object>();
auto inBps = maybeNumberFromJs<uint64_t>(obj.Get("inBps")).value_or(4);
auto outBps = maybeNumberFromJs<uint64_t>(obj.Get("outBps")).value_or(4);
auto channels = maybeNumberFromJs<uint64_t>(obj.Get("channels")).value_or(2);
auto bufferPair = pointer::fromBuffer<char>(obj.Get("buffer"));
auto buffer = std::get<0>(bufferPair);
uint64_t samples = maybeNumberFromJs<uint64_t>(obj.Get("samples"))
.value_or(std::get<1>(bufferPair) / inBps / channels);
if (inBps == 0 || outBps == 0 || samples == 0 || channels == 0) {
throw Error::New(info.Env(), "Invalid value for one of the given properties");
}
if (std::get<1>(bufferPair) < samples * inBps * channels) {
throw RangeError::New(
info.Env(),
"Buffer has size "s + std::to_string(std::get<1>(bufferPair))
+ " but expected to be at least "s + std::to_string(samples * inBps * channels));
}
// NOTE: see above function note about the outputBuffer
auto reader = getReader(inBps, info.Env());
auto writer = getWriter(outBps, info.Env());
uint64_t outputBufferSize = samples * outBps;
std::vector<char*> outputBuffers(channels);
for (uint64_t channel = 0; channel < channels; channel += 1) {
outputBuffers[channel] =
(char*) (outBps <= inBps ? malloc(outputBufferSize) : calloc(outputBufferSize, 1));
}
for (uint64_t sample = 0; sample < samples; sample++) {
for (uint64_t channel = 0; channel < channels; channel += 1) {
char* out = outputBuffers[channel] + sample * outBps;
char* in = buffer + (sample * channels + channel) * inBps;
auto value = reader(in);
writer(out, value);
}
}
auto array = Napi::Array::New(info.Env(), channels);
for (uint64_t channel = 0; channel < channels; channel += 1) {
array[channel] = Buffer<char>::New(
info.Env(),
outputBuffers[channel],
outputBufferSize,
[](auto, auto data) { free(data); });
}
return scope.Escape(array);
}
static Napi::Value convertSampleFormat(const Napi::CallbackInfo& info) {
using namespace Napi;
EscapableHandleScope scope(info.Env());
if (!info[0].IsObject()) {
throw TypeError::New(info.Env(), "Expected first argument to be object");
}
auto obj = info[0].As<Object>();
auto inBps = maybeNumberFromJs<uint64_t>(obj.Get("inBps")).value_or(4);
auto outBps = maybeNumberFromJs<uint64_t>(obj.Get("outBps")).value_or(4);
if (inBps == outBps) {
return scope.Escape(obj.Get("buffer"));
}
auto bufferPair = pointer::fromBuffer<char>(obj.Get("buffer"));
auto buffer = std::get<0>(bufferPair);
uint64_t samples =
maybeNumberFromJs<uint64_t>(obj.Get("samples")).value_or(std::get<1>(bufferPair) / inBps);
if (inBps == 0 || outBps == 0 || samples == 0) {
throw Error::New(info.Env(), "Invalid value for one of the given properties");
}
if (std::get<1>(bufferPair) < samples * inBps) {
throw RangeError::New(
info.Env(),
"Buffer has size "s + std::to_string(std::get<1>(bufferPair))
+ " but expected to be at least "s + std::to_string(samples * inBps));
}
// NOTE: see above function note about the outputBuffer
auto reader = getReader(inBps, info.Env());
auto writer = getWriter(outBps, info.Env());
uint64_t outputBufferSize = samples * outBps;
char* outputBuffer =
(char*) (outBps <= inBps ? malloc(outputBufferSize) : calloc(outputBufferSize, 1));
for (uint64_t sample = 0; sample < samples; sample++) {
char* out = outputBuffer + sample * outBps;
char* in = buffer + sample * inBps;
auto value = reader(in);
writer(out, value);
}
return scope.Escape(
Buffer<char>::New(info.Env(), outputBuffer, outputBufferSize, [](auto, auto data) {
free(data);
}));
}
Napi::Object initFns(Napi::Env env) {
using namespace Napi;
EscapableHandleScope scope(env);
auto obj = Object::New(env);
obj.DefineProperties({
PropertyDescriptor::Function(env, obj, "zipAudio", zipAudio, napi_enumerable),
PropertyDescriptor::Function(env, obj, "unzipAudio", unzipAudio, napi_enumerable),
PropertyDescriptor::Function(
env,
obj,
"convertSampleFormat",
convertSampleFormat,
napi_enumerable),
});
return scope.Escape(objectFreeze(obj)).As<Object>();
}
}
| 34.218391 | 100 | 0.616504 | melchor629 |
e03130660378d31649865753bed09d77bdf8fa81 | 1,530 | hh | C++ | transformations/interpolation/SegmentWise.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | 5 | 2019-10-14T01:06:57.000Z | 2021-02-02T16:33:06.000Z | transformations/interpolation/SegmentWise.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | transformations/interpolation/SegmentWise.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | #pragma once
#include "GNAObject.hh"
/**
* @brief Determines the bins edges indices for a sorted array.
*
* For a given array of bin edges:
* ```python
* edges=(e1, e2, ..., eN)
* ```
*
* And for a given array of points:
* ```python
* points=(p1, p2, ..., pM)
* ```
*
* Determines the indices:
* ```python
* segments=(n1, n2, ..., nN)
* ```
*
* So that:
* ```python
* e1<=points[n1:n2]<e2
* e2<=points[n2:n3]<e3
* ...
* eN-1<=points[nN-1:nN]<eN
* ```
*
* Segments with no points have coinciding indices nI=nJ.
*
* The transformation is needed in order to implement interpolation,
* for example InterpExpoSorted.
*
* Inputs:
* - segments.points - array (to interpolate on).
* - segments.edges - edges.
*
* Outputs:
* - segments.segment - segment indices.
* - segments.widths - segment widths.
*
* @note If `edge-point<m_tolerance` is equivalent to `point==edge`.
*
* @author Maxim Gonchar
* @date 02.2018
*/
class SegmentWise: public GNAObject,
public TransformationBind<SegmentWise> {
public:
SegmentWise(); ///< Constructor.
void setTolerance(double value) { m_tolerance = value; } ///< Set tolerance.
void determineSegments(FunctionArgs& fargs); ///< Function that determines segments.
private:
double m_tolerance{1.e-16}; ///< Tolerance. If point is below left edge on less than m_tolerance, it is considered to belong to the bin anyway.
};
| 25.932203 | 176 | 0.598039 | gnafit |
e03a164c52cd7b4b6b1d88566f061dfc8a4c784b | 793 | hpp | C++ | test/node-gdal-async/src/geometry/gdal_multilinestring.hpp | mmomtchev/yatag | 37802e760a33939b65ceaa4379634529d0dc0092 | [
"0BSD"
] | 42 | 2021-03-26T17:34:52.000Z | 2022-03-18T14:15:31.000Z | test/node-gdal-async/src/geometry/gdal_multilinestring.hpp | mmomtchev/yatag | 37802e760a33939b65ceaa4379634529d0dc0092 | [
"0BSD"
] | 29 | 2021-06-03T14:24:01.000Z | 2022-03-23T15:43:58.000Z | test/node-gdal-async/src/geometry/gdal_multilinestring.hpp | mmomtchev/yatag | 37802e760a33939b65ceaa4379634529d0dc0092 | [
"0BSD"
] | 8 | 2021-05-14T19:26:37.000Z | 2022-03-21T13:44:42.000Z | #ifndef __NODE_OGR_MULTILINESTRING_H__
#define __NODE_OGR_MULTILINESTRING_H__
// node
#include <node.h>
#include <node_object_wrap.h>
// nan
#include "../nan-wrapper.h"
// ogr
#include <ogrsf_frmts.h>
#include "gdal_geometrycollectionbase.hpp"
using namespace v8;
using namespace node;
namespace node_gdal {
class MultiLineString : public GeometryCollectionBase<MultiLineString, OGRMultiLineString> {
public:
static Nan::Persistent<FunctionTemplate> constructor;
using GeometryCollectionBase<MultiLineString, OGRMultiLineString>::GeometryCollectionBase;
static void Initialize(Local<Object> target);
using GeometryCollectionBase<MultiLineString, OGRMultiLineString>::New;
static NAN_METHOD(toString);
static NAN_METHOD(polygonize);
};
} // namespace node_gdal
#endif
| 22.657143 | 92 | 0.796974 | mmomtchev |
e03ca583974d7223395140a16f5b6579c8fe9d2f | 12,762 | cpp | C++ | SVEngine/src/node/SVSpineNode.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 34 | 2018-09-28T08:28:27.000Z | 2022-01-15T10:31:41.000Z | SVEngine/src/node/SVSpineNode.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | null | null | null | SVEngine/src/node/SVSpineNode.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 8 | 2018-10-11T13:36:35.000Z | 2021-04-01T09:29:34.000Z | //
// SVSpineNode.cpp
// SVEngine
// Copyright 2017-2020
// yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li
//
#include <spine/Slot.h>
#include <spine/RegionAttachment.h>
#include <spine/MeshAttachment.h>
#include "SVSpineNode.h"
#include "SVCameraNode.h"
#include "SVScene.h"
#include "../rendercore/SVRenderMgr.h"
#include "../rendercore/SVRenderScene.h"
#include "../rendercore/SVRenderMesh.h"
#include "../rendercore/SVRenderObject.h"
#include "../core/SVSpine.h"
#include "../detect/SVDetectMgr.h"
#include "../detect/SVDetectBase.h"
#include "../event/SVEventMgr.h"
#include "../event/SVEvent.h"
#include "../event/SVOpEvent.h"
#include "../mtl/SVMtlAni2D.h"
#include "../mtl/SVTexMgr.h"
#include "../mtl/SVTexture.h"
#include "../basesys/SVConfig.h"
#include "../rendercore/SVRenderer.h"
//
SVSpineNode::SVSpineNode(SVInst *_app)
:SVNode(_app) {
ntype = "SVSpineNode";
m_spine = nullptr;
m_pRObj = nullptr;
m_spine_callback = nullptr;
m_p_cb_obj = nullptr;
m_visible = false;
m_loop = true;
m_immediatelyPlay = true;
m_state = tANI_STATE_WAIT;
m_rsType = RST_SOLID_3D;
m_cur_aniname = "animation";
m_canSelect = true;
m_aabbBox_scale = 1.0f;
}
SVSpineNode::~SVSpineNode() {
if(m_pRObj){
m_pRObj->clearMesh();
m_pRObj = nullptr;
}
clearSpine();
m_spine_callback = nullptr;
m_p_cb_obj = nullptr;
}
void SVSpineNode::setSpine(SVSpinePtr _spine) {
if (m_spine == _spine) {
return;
}
if (m_spine) {
clearSpine();
}
m_spine = _spine;
if(!m_pRObj){
m_pRObj = MakeSharedPtr<SVMultMeshMtlRenderObject>();
}
m_pRObj->clearMesh();
//回调函数
m_spine->m_cb_startListener = [this](s32 itrackId) -> void {
_spine_start();
};
//
m_spine->m_cb_completeListener = [this](s32 itrackId, s32 iLoopCount) -> void {
_spine_complete();
};
//
m_spine->m_cb_endListener = [this](s32 itrackId) -> void {
_spine_stop();
};
}
SVSpinePtr SVSpineNode::getSpine() {
return m_spine;
}
void SVSpineNode::clearSpine() {
m_spine = nullptr;
}
void SVSpineNode::setstate(E_ANISTATE _state){
m_state = _state;
}
E_ANISTATE SVSpineNode::getstate(){
return m_state;
}
cptr8 SVSpineNode::getCurAniName(){
return m_cur_aniname.c_str();
}
void SVSpineNode::setCurAniName(cptr8 _name){
m_cur_aniname = _name;
}
void SVSpineNode::setloop(bool _loop){
m_loop = _loop;
}
bool SVSpineNode::getloop(){
return m_loop;
}
bool SVSpineNode::isImmediatelyPlay(){
return m_immediatelyPlay;
}
void SVSpineNode::setSpineCallback(sv_spine_callback _cb,void* _obj) {
m_spine_callback = _cb;
m_p_cb_obj = _obj;
}
//
void SVSpineNode::update(f32 dt) {
if (!m_visible)
return;
if (m_state == E_ANISTATE::tANI_STATE_STOP) {
return;
}
if( m_pRObj && m_spine) {
//spine更新
m_spine->update(dt);
_computeAABBBox();
SVNode::update(dt);
//更新模型
m_pRObj->clearMesh();
for (s32 i = 0, n = m_spine->m_pSkeleton->slotsCount; i < n; i++) {
spSlot *t_slot = m_spine->m_pSkeleton->drawOrder[i];
if (!t_slot->attachment) {
continue; //没有挂在项目
}
SpineMeshDataPtr pMeshData = m_spine->m_spineDataPool[i];
SVMtlAni2DPtr t_mtl = MakeSharedPtr<SVMtlAni2D>(mApp);
t_mtl->setModelMatrix(m_absolutMat.get());
t_mtl->setTexture(0,pMeshData->m_pTex);
t_mtl->setBlendEnable(true);
t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_NORMAL);
switch (pMeshData->m_blendMode) {
case SP_BLEND_MODE_NORMAL:{
if(m_spine->m_preMultAlpha){
t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
}else{
t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
}
break;
}
case SP_BLEND_MODE_ADDITIVE:{
t_mtl->setBlendState(m_spine->m_preMultAlpha ? MTL_BLEND_ONE : MTL_BLEND_SRC_ALPHA, MTL_BLEND_ONE);
t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_ADDITIVE);
break;
}
case SP_BLEND_MODE_MULTIPLY:{
t_mtl->setBlendState(MTL_BLEND_DEST_COLOR, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_MULTIPLY);
break;
}
case SP_BLEND_MODE_SCREEN:{
t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_COLOR);
t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_SCREEN);
break;
}
default:{
t_mtl->setBlendState(m_spine->m_preMultAlpha ? MTL_BLEND_ONE : MTL_BLEND_SRC_ALPHA, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
break;
}
}
m_pRObj->addRenderObj(pMeshData->m_pRenderMesh,t_mtl);
}
}
}
void SVSpineNode::render() {
if (!m_visible)
return;
if (m_state == E_ANISTATE::tANI_STATE_STOP) {
return;
}
// if (!mApp->m_pGlobalParam->m_curScene)
// return;
SVRenderScenePtr t_rs = mApp->getRenderMgr()->getRenderScene();
if (m_pRObj) {
m_pRObj->pushCmd(t_rs, m_rsType, "SVSpineNode");
}
SVNode::render();
}
void SVSpineNode::play(cptr8 _actname) {
if( m_state != E_ANISTATE::tANI_STATE_PLAY ){
if (m_spine) {
m_state = E_ANISTATE::tANI_STATE_PLAY;
m_cur_aniname = _actname;
m_spine->setToSetupPose();
m_spine->setAnimationForTrack(0, _actname, m_loop);
m_visible = true;
}
}
}
void SVSpineNode::addAni(cptr8 _actname){
if (m_spine) {
m_spine->addAnimationForTrack(0, _actname, m_loop,0);
}
m_visible = true;
}
void SVSpineNode::pause() {
if( m_state != E_ANISTATE::tANI_STATE_PAUSE ){
m_state = E_ANISTATE::tANI_STATE_PAUSE;
_sendAniEvent("ani_pause");
}
}
void SVSpineNode::stop() {
if( m_state != E_ANISTATE::tANI_STATE_STOP ){
m_state = E_ANISTATE::tANI_STATE_STOP;
m_visible = false;
if (m_spine) {
m_spine->clearTrack(0);
}
}
}
//开始回调
void SVSpineNode::_spine_start() {
_sendAniEvent("ani_play");
//回调
if( m_spine_callback ){
(*m_spine_callback)(THIS_TO_SHAREPTR(SVSpineNode),m_p_cb_obj,1);
}
}
//完成回调
void SVSpineNode::_spine_complete() {
_sendAniEvent("ani_complete");
//回调
if( m_spine_callback ){
(*m_spine_callback)(THIS_TO_SHAREPTR(SVSpineNode),m_p_cb_obj,2);
}
}
//停止回调
void SVSpineNode::_spine_stop() {
if (m_state == E_ANISTATE::tANI_STATE_STOP) {
return;
}
m_visible = false;
m_state = E_ANISTATE::tANI_STATE_STOP;
_sendAniEvent("ani_stop");
//回调
if( m_spine_callback ){
(*m_spine_callback)(THIS_TO_SHAREPTR(SVSpineNode),m_p_cb_obj,3);
}
}
//发送事件
void SVSpineNode::_sendAniEvent(cptr8 _eventName) {
SVString t_eventName = m_name + SVString("_") + SVString(_eventName);
SVAnimateEventPtr t_event = MakeSharedPtr<SVAnimateEvent>();
t_event->personID = m_personID;
t_event->m_AnimateName = m_spine->getSpineName();
t_event->eventName = t_eventName;
mApp->getEventMgr()->pushEventToSecondPool(t_event);
}
void SVSpineNode::setAlpha(f32 _alpha){
if (_alpha < 0.0f || _alpha > 1.0f) {
return;
}
if(m_spine){
m_spine->setAlpha(_alpha);
}
}
bool SVSpineNode::getBonePosition(f32 &px, f32 &py, cptr8 bonename) {
spBone *m_bone = m_spine->findBone(bonename); //绑定的骨头
if (m_bone) {
px = m_bone->worldX*m_scale.x;
py = m_bone->worldY*m_scale.y;
//逐层找父节点,把本地坐标和世界坐标加上
SVNodePtr t_curNode = THIS_TO_SHAREPTR(SVSpineNode);
while (t_curNode) {
px = t_curNode->getPosition().x + px;
py = t_curNode->getPosition().y + py;
if (t_curNode->getParent()) {
t_curNode = t_curNode->getParent();
} else {
return true;
}
}
}
return false;
}
bool SVSpineNode::getBoneScale(f32 &sx, f32 &sy, cptr8 bonename){
spBone *m_bone = m_spine->findBone(bonename);//spSkeleton_findBone(,bonename); //绑定的骨头
if (m_bone) {
sx = m_bone->scaleX;
sy = m_bone->scaleY;
SVNodePtr t_curNode = THIS_TO_SHAREPTR(SVSpineNode);
while (t_curNode) {
sx = sx * t_curNode->getScale().x;
sy = sy * t_curNode->getScale().y;
if (t_curNode->getParent()) {
t_curNode = t_curNode->getParent();
} else {
return true;
}
}
}
return false;
}
bool SVSpineNode::getBoneRotation(f32 &rotation, cptr8 bonename){
spBone *m_bone = m_spine->findBone(bonename);//spSkeleton_findBone(,bonename); //绑定的骨头
if (m_bone) {
rotation = m_bone->rotation;
SVNodePtr t_curNode = THIS_TO_SHAREPTR(SVSpineNode);
while (t_curNode) {
rotation = rotation * t_curNode->getRotation().z;
if (t_curNode->getParent()) {
t_curNode = t_curNode->getParent();
} else {
return true;
}
}
}
return false;
}
f32 SVSpineNode::getSlotAlpha(cptr8 bonename) {
spSlot *t_slot = m_spine->findSlot(bonename);
f32 fAlpha = 1.0f;
if (t_slot == NULL) {
return fAlpha;
}
fAlpha = t_slot->color.a;
return fAlpha;
}
void SVSpineNode::setAABBBoxScale(f32 _scale){
m_aabbBox_scale = _scale;
}
void SVSpineNode::_computeAABBBox(){
if (m_spine) {
SVBoundBox t_boundingBox = m_spine->m_aabbBox;
FVec3 t_min = t_boundingBox.getMin();
FVec3 t_max = t_boundingBox.getMax();
m_aabbBox = SVBoundBox(FVec3(t_min.x*m_aabbBox_scale, t_min.y*m_aabbBox_scale, 1.0), FVec3(t_max.x*m_aabbBox_scale, t_max.y*m_aabbBox_scale, 1.0));
}
}
//序列化
void SVSpineNode::toJSON(RAPIDJSON_NAMESPACE::Document::AllocatorType &_allocator, RAPIDJSON_NAMESPACE::Value &_objValue){
RAPIDJSON_NAMESPACE::Value locationObj(RAPIDJSON_NAMESPACE::kObjectType);//创建一个Object类型的元素
_toJsonData(_allocator, locationObj);
//
locationObj.AddMember("aniname", RAPIDJSON_NAMESPACE::StringRef(m_cur_aniname.c_str()), _allocator);
bool m_hasSpine = false;
if(m_spine){
//有spine
m_hasSpine = true;
locationObj.AddMember("ske_atlas", RAPIDJSON_NAMESPACE::StringRef(m_spine->m_spine_atlas.c_str()), _allocator);
locationObj.AddMember("ske_json", RAPIDJSON_NAMESPACE::StringRef(m_spine->m_spine_json.c_str()), _allocator);
}
locationObj.AddMember("loop", m_loop, _allocator);
locationObj.AddMember("play", m_immediatelyPlay, _allocator);
locationObj.AddMember("spine", m_hasSpine, _allocator);
_objValue.AddMember("SVSpineNode", locationObj, _allocator);
}
void SVSpineNode::fromJSON(RAPIDJSON_NAMESPACE::Value &item){
_fromJsonData(item);
if (item.HasMember("aniname") && item["aniname"].IsString()) {
m_cur_aniname = item["aniname"].GetString();
}
if (item.HasMember("play") && item["play"].IsBool()) {
m_immediatelyPlay = item["play"].GetBool();
}
if (item.HasMember("loop") && item["loop"].IsBool()) {
m_loop = item["loop"].GetBool();
}
bool m_hasSpine = false;
if (item.HasMember("spine") && item["spine"].IsBool()) {
m_hasSpine = item["spine"].GetBool();
}
if(m_hasSpine){
//有spine
SVString t_atlas;
SVString t_json;
if (item.HasMember("ske_atlas") && item["ske_atlas"].IsString()) {
t_atlas = item["ske_atlas"].GetString();
}
if (item.HasMember("ske_json") && item["ske_json"].IsString()) {
t_json = item["ske_json"].GetString();
}
SVSpinePtr t_spine = SVSpine::createSpine(mApp, m_rootPath + t_json, m_rootPath + t_atlas, 1.0f, m_enableMipMap);
if ( t_spine ) {
s32 len = t_atlas.size();
s32 pos = t_atlas.rfind('.');
SVString t_spineName = SVString::substr(t_atlas.c_str(), 0, pos);
t_spine->setSpineName(t_spineName.c_str());
setSpine(t_spine);
}
//从特效包里加载的spine动画,写死了走这个渲染流!!
m_rsType = RST_SOLID_3D;
}
}
| 29.817757 | 155 | 0.609622 | SVEChina |
e03d76dc57e4aad695c5dd753863e741aefd8046 | 4,340 | cpp | C++ | src/lib/navigation/siteicon.cpp | pejakm/qupzilla | c1901cd81d9d3488a7dc1f25b777fb56f67cb39e | [
"BSD-3-Clause"
] | 1 | 2019-05-07T15:00:56.000Z | 2019-05-07T15:00:56.000Z | src/lib/navigation/siteicon.cpp | pejakm/qupzilla | c1901cd81d9d3488a7dc1f25b777fb56f67cb39e | [
"BSD-3-Clause"
] | null | null | null | src/lib/navigation/siteicon.cpp | pejakm/qupzilla | c1901cd81d9d3488a7dc1f25b777fb56f67cb39e | [
"BSD-3-Clause"
] | null | null | null | /* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2010-2014 David Rosca <[email protected]>
*
* This program 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.
*
* 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 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/>.
* ============================================================ */
#include "siteicon.h"
#include "siteinfowidget.h"
#include "locationbar.h"
#include "tabbedwebview.h"
#include "qztools.h"
#include <QDrag>
#include <QTimer>
#include <QMimeData>
#include <QApplication>
#include <QContextMenuEvent>
SiteIcon::SiteIcon(BrowserWindow* window, LocationBar* parent)
: ToolButton(parent)
, m_window(window)
, m_locationBar(parent)
, m_view(0)
{
setObjectName("locationbar-siteicon");
setToolButtonStyle(Qt::ToolButtonIconOnly);
setCursor(Qt::ArrowCursor);
setToolTip(LocationBar::tr("Show information about this page"));
setFocusPolicy(Qt::ClickFocus);
m_updateTimer = new QTimer(this);
m_updateTimer->setInterval(100);
m_updateTimer->setSingleShot(true);
connect(m_updateTimer, SIGNAL(timeout()), this, SLOT(updateIcon()));
}
void SiteIcon::setWebView(WebView* view)
{
m_view = view;
}
void SiteIcon::setIcon(const QIcon &icon)
{
bool wasNull = m_icon.isNull();
m_icon = icon;
if (wasNull) {
updateIcon();
}
else {
m_updateTimer->start();
}
}
void SiteIcon::updateIcon()
{
ToolButton::setIcon(m_icon);
}
void SiteIcon::popupClosed()
{
setDown(false);
}
void SiteIcon::contextMenuEvent(QContextMenuEvent* e)
{
// Prevent propagating to LocationBar
e->accept();
}
void SiteIcon::mousePressEvent(QMouseEvent* e)
{
if (e->buttons() == Qt::LeftButton) {
m_dragStartPosition = e->pos();
}
// Prevent propagating to LocationBar
e->accept();
ToolButton::mousePressEvent(e);
}
void SiteIcon::mouseReleaseEvent(QMouseEvent* e)
{
// Mouse release event is restoring Down state
// So we pause updates to prevent flicker
bool activated = false;
if (e->button() == Qt::LeftButton && rect().contains(e->pos())) {
// Popup may not be always shown, eg. on qupzilla: pages
activated = showPopup();
}
if (activated) {
setUpdatesEnabled(false);
}
ToolButton::mouseReleaseEvent(e);
if (activated) {
setDown(true);
setUpdatesEnabled(true);
}
}
void SiteIcon::mouseMoveEvent(QMouseEvent* e)
{
if (!m_locationBar || e->buttons() != Qt::LeftButton) {
ToolButton::mouseMoveEvent(e);
return;
}
int manhattanLength = (e->pos() - m_dragStartPosition).manhattanLength();
if (manhattanLength <= QApplication::startDragDistance()) {
ToolButton::mouseMoveEvent(e);
return;
}
const QUrl url = m_locationBar->webView()->url();
const QString title = m_locationBar->webView()->title();
if (url.isEmpty() || title.isEmpty()) {
ToolButton::mouseMoveEvent(e);
return;
}
QDrag* drag = new QDrag(this);
QMimeData* mime = new QMimeData;
mime->setUrls(QList<QUrl>() << url);
mime->setText(title);
mime->setImageData(icon().pixmap(16, 16).toImage());
drag->setMimeData(mime);
drag->setPixmap(QzTools::createPixmapForSite(icon(), title, url.toString()));
drag->exec();
// Restore Down state
setDown(false);
}
bool SiteIcon::showPopup()
{
if (!m_view || !m_window) {
return false;
}
QUrl url = m_view->url();
if (url.isEmpty() || url.scheme() == QLatin1String("qupzilla")) {
return false;
}
setDown(true);
SiteInfoWidget* info = new SiteInfoWidget(m_window);
info->showAt(parentWidget());
connect(info, SIGNAL(destroyed()), this, SLOT(popupClosed()));
return true;
}
| 24.8 | 81 | 0.641705 | pejakm |
e040071f6af73b3136a24b1d7340c97ae2d81c52 | 2,970 | cpp | C++ | Sources/Scenes/Entity.cpp | liuping1997/Acid | 0b28d63d03ead41047d5881f08e3b693a4e6e63f | [
"MIT"
] | null | null | null | Sources/Scenes/Entity.cpp | liuping1997/Acid | 0b28d63d03ead41047d5881f08e3b693a4e6e63f | [
"MIT"
] | null | null | null | Sources/Scenes/Entity.cpp | liuping1997/Acid | 0b28d63d03ead41047d5881f08e3b693a4e6e63f | [
"MIT"
] | null | null | null | #include "Entity.hpp"
#include "Files/FileSystem.hpp"
#include "Scenes.hpp"
#include "EntityPrefab.hpp"
namespace acid
{
Entity::Entity(const Transform &transform) :
m_name(""),
m_localTransform(transform),
m_parent(nullptr),
m_removed(false)
{
}
Entity::Entity(const std::string &filename, const Transform &transform) :
Entity(transform)
{
auto prefabObject = EntityPrefab::Create(filename);
for (const auto &child : prefabObject->GetParent()->GetChildren())
{
if (child->GetName().empty())
{
continue;
}
auto component = Scenes::Get()->GetComponentRegister().Create(child->GetName());
if (component == nullptr)
{
continue;
}
Scenes::Get()->GetComponentRegister().Decode(child->GetName(), *child, component);
AddComponent(component);
}
m_name = FileSystem::FileName(filename);
}
Entity::~Entity()
{
if (m_parent != nullptr)
{
m_parent->RemoveChild(this);
}
}
void Entity::Update()
{
for (auto it = m_components.begin(); it != m_components.end();)
{
if ((*it)->IsRemoved())
{
it = m_components.erase(it);
continue;
}
if ((*it)->GetParent() != this)
{
(*it)->SetParent(this);
}
if ((*it)->IsEnabled())
{
if (!(*it)->m_started)
{
(*it)->Start();
(*it)->m_started = true;
}
(*it)->Update();
}
++it;
}
}
Component *Entity::AddComponent(Component *component)
{
if (component == nullptr)
{
return nullptr;
}
component->SetParent(this);
m_components.emplace_back(component);
return component;
}
void Entity::RemoveComponent(Component *component)
{
m_components.erase(std::remove_if(m_components.begin(), m_components.end(), [component](std::unique_ptr<Component> &c)
{
return c.get() == component;
}), m_components.end());
}
void Entity::RemoveComponent(const std::string &name)
{
m_components.erase(std::remove_if(m_components.begin(), m_components.end(), [&](std::unique_ptr<Component> &c)
{
auto componentName = Scenes::Get()->GetComponentRegister().FindName(c.get());
return componentName && name == *componentName;
}), m_components.end());
}
Transform Entity::GetWorldTransform() const
{
if (m_localTransform.IsDirty())
{
if (m_parent != nullptr)
{
m_worldTransform = m_parent->GetWorldTransform() * m_localTransform;
}
else
{
m_worldTransform = m_localTransform;
}
for (const auto &child : m_children)
{
child->m_localTransform.SetDirty(true);
}
m_localTransform.SetDirty(false);
}
return m_worldTransform;
}
Matrix4 Entity::GetWorldMatrix() const
{
return GetWorldTransform().GetWorldMatrix();
}
void Entity::SetParent(Entity *parent)
{
if (m_parent != nullptr)
{
m_parent->RemoveChild(this);
}
m_parent = parent;
if (m_parent != nullptr)
{
m_parent->AddChild(this);
}
}
void Entity::AddChild(Entity *child)
{
m_children.emplace_back(child);
}
void Entity::RemoveChild(Entity *child)
{
m_children.erase(std::remove(m_children.begin(), m_children.end(), child), m_children.end());
}
}
| 18.109756 | 119 | 0.674747 | liuping1997 |
e042481d0fb9269219e36d3db4b5c63f73c049d7 | 2,700 | cpp | C++ | src/AnimatedObject.cpp | ArionasMC/TicTacToe | 998585ca415c7d263eeb73e43840fbf98d9a4c99 | [
"Apache-2.0"
] | 3 | 2019-02-23T18:20:24.000Z | 2019-02-23T18:30:18.000Z | src/AnimatedObject.cpp | ArionasMC/TicTacToe | 998585ca415c7d263eeb73e43840fbf98d9a4c99 | [
"Apache-2.0"
] | null | null | null | src/AnimatedObject.cpp | ArionasMC/TicTacToe | 998585ca415c7d263eeb73e43840fbf98d9a4c99 | [
"Apache-2.0"
] | null | null | null | #include "AnimatedObject.h"
using namespace std;
AnimatedObject::AnimatedObject(const char* textureSheet, SDL_Renderer* ren, double x, double y, vector<SDL_Rect> frameRects, int endFrame, int secondsToNext) : GameObject(textureSheet, ren, x, y)
{
this->show = true;
this->setSimpleTexture(true);
this->frameRects = frameRects;
this->endFrame = endFrame;
this->secondsToNext = secondsToNext;
this->maxFrames = frameRects.size();
this->playSoundEffect = false;
/*
this->destR.w = 75;
this->destR.h = 75;
this->srcR.x = this->frame * 50 ;
this->srcR.y = 0;
this->srcR.w = 49;
this->srcR.h = 50;
*/
}
void AnimatedObject::update() {
GameObject::update();
if(this->show) {
this->destR.x = this->x;
this->destR.y = this->y;
this->destR.w = this->width;
this->destR.h = this->height;
this->srcR.x = frameRects[frame].x;
this->srcR.y = frameRects[frame].y;
this->srcR.w = frameRects[frame].w;
this->srcR.h = frameRects[frame].h;
if(!animated) timer++;
}
}
void AnimatedObject::render() {
if(show) SDL_RenderCopyEx(renderer, texture, &srcR, &destR, degrees, NULL, SDL_FLIP_NONE);
}
void AnimatedObject::playAnimation() {
if(!animated) {
if(playSoundEffect) {
Mix_PlayChannel(-1, soundEffect, 0);
playSoundEffect = false;
}
if(frame < maxFrames) {
if(timer >= secondsToNext) {
timer = 0;
frame++;
//cout << "heyy";
//this->srcR.x = this->frame * 50;
}
if(frame == maxFrames) {
animated = true;
//cout << "hey!";
frame = endFrame;
}
}
//cout << frame << '\n';
}
}
void AnimatedObject::restartAnimation() {
this->frame = 0;
animated = false;
playAnimation();
}
void AnimatedObject::generateFrameRects(int times, int deltaX, int deltaY, int conW, int conH) {
for(int i = 0; i < times; i++) {
frameRects.push_back({i*deltaX, i*deltaY, conW, conH});
//cout << i*deltaX <<", "<<i*deltaY<<", "<<conW<<", "<<conH<<'\n';
}
this->maxFrames = frameRects.size();
}
bool AnimatedObject::getAnimated() {
return this->animated;
}
void AnimatedObject::setAnimated(bool a) {
this->animated = a;
}
void AnimatedObject::setPlaySoundEffect(bool p) {
this->playSoundEffect = p;
}
void AnimatedObject::setSoundEffectSource(string source) {
this->soundEffect = Mix_LoadWAV(source.c_str());
}
| 28.421053 | 196 | 0.554444 | ArionasMC |
e0447588f79276f223c96a4be21122dcde195285 | 3,313 | cpp | C++ | python/sedef.cpp | mateog4712/SEDEF | dc05b661854a96b934ee098bedb970a5040b697b | [
"MIT"
] | 21 | 2018-07-06T06:09:42.000Z | 2021-06-28T21:21:01.000Z | python/sedef.cpp | mateog4712/SEDEF | dc05b661854a96b934ee098bedb970a5040b697b | [
"MIT"
] | 21 | 2018-06-29T23:57:33.000Z | 2022-03-01T02:37:49.000Z | python/sedef.cpp | mateog4712/SEDEF | dc05b661854a96b934ee098bedb970a5040b697b | [
"MIT"
] | 9 | 2019-10-16T10:14:12.000Z | 2021-06-29T17:11:27.000Z | /// 786
#include <string>
using namespace std;
#include "src/common.h"
#include "src/search.h"
#include "src/chain.h"
#include "src/align.h"
class PyHit {
public:
int qs, qe;
int rs, re;
Alignment c;
// PyHit() = default;
int query_start() { return qs; }
int query_end() { return qe; }
int ref_start() { return rs; }
int ref_end() { return re; }
string cigar() { return c.cigar_string(); }
int alignment_size() { return c.span(); }
int gaps() { return c.gap_bases(); }
int mismatches() { return c.mismatches(); }
bool operator==(const PyHit &q) const {
return tie(qs, qe, rs, re) == tie(q.qs, q.qe, q.rs, q.re);
}
};
class PyAligner {
public:
vector<PyHit> jaccard_align(const string &q, const string &r);
vector<PyHit> chain_align(const string &q, const string &r);
vector<PyHit> full_align(const string &q, const string &r);
};
vector<PyHit> PyAligner::jaccard_align(const string &q, const string &r)
{
shared_ptr<Index> query_hash = make_shared<Index>(make_shared<Sequence>("qry", q), 12, 16);
shared_ptr<Index> ref_hash = make_shared<Index>(make_shared<Sequence>("ref", r), 12, 16);
Tree tree;
vector<PyHit> hits;
bool iterative = true;
if (iterative) {
for (int qi = 0; qi < query_hash->minimizers.size(); qi++) {
auto &qm = query_hash->minimizers[qi];
// eprn("search {}", qm.loc);
if (qm.hash.status != Hash::Status::HAS_UPPERCASE)
continue;
auto hi = search(qi, query_hash, ref_hash, tree, false,
max(q.size(), r.size()), true, false);
for (auto &pp: hi) {
hits.push_back(PyHit {
pp.query_start, pp.query_end,
pp.ref_start, pp.ref_end,
{}
});
}
}
} else {
// Disabled for now
auto hi = search(0, query_hash, ref_hash, tree,
false, max(q.size(), r.size()), false, false);
for (auto &pp: hi) {
hits.push_back({
pp.query_start, pp.query_end,
pp.ref_start, pp.ref_end,
{}
});
}
}
return hits;
}
vector<PyHit> PyAligner::chain_align(const string &q, const string &r)
{
vector<PyHit> hits;
Hit orig {
make_shared<Sequence>("A", q), 0, (int)q.size(),
make_shared<Sequence>("B", r), 0, (int)r.size()
};
auto hi = fast_align(q, r, orig, 11);
for (auto &pp: hi) {
hits.push_back({
pp.query_start, pp.query_end,
pp.ref_start, pp.ref_end,
pp.aln
});
}
return hits;
}
vector<PyHit> PyAligner::full_align(const string &q, const string &r)
{
auto aln = Alignment(q, r);
return vector<PyHit> {{
0, (int)q.size(),
0, (int)r.size(),
aln
}};
}
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
BOOST_PYTHON_MODULE(sedef)
{
using namespace boost::python;
class_<PyHit>("PyHit")
.def("cigar", &PyHit::cigar)
.def("alignment_size", &PyHit::alignment_size)
.def("gaps", &PyHit::gaps)
.def("mismatches", &PyHit::mismatches)
.def("query_start", &PyHit::query_start)
.def("query_end", &PyHit::query_end)
.def("ref_start", &PyHit::ref_start)
.def("ref_end", &PyHit::ref_end);
class_<std::vector<PyHit>>("vector")
.def(vector_indexing_suite<std::vector<PyHit>, true>());
class_<PyAligner>("PyAligner")
.def("jaccard_align", &PyAligner::jaccard_align)
.def("chain_align", &PyAligner::chain_align)
.def("full_align", &PyAligner::full_align)
;
} | 25.290076 | 92 | 0.638696 | mateog4712 |
e0462028989128bc82fc25982091e8b8a48f3869 | 355 | cpp | C++ | Source/Model.cpp | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | Source/Model.cpp | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | Source/Model.cpp | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | #include "Model.h"
Model::Model() {}
Model::~Model()
{
for(int i=0; i<meshes.size(); i++)
delete meshes[i];
}
void Model::draw(Program* program)
{
for (std::vector<Mesh*>::iterator mesh = this->meshes.begin(); mesh != this->meshes.end(); ++mesh)
{
(*mesh)->draw(program);
}
}
void Model::addMesh(Mesh* mesh)
{
this->meshes.push_back(mesh);
}
| 15.434783 | 99 | 0.616901 | RPKQ |
e046997443b3e543fb43151ef82eb3009d970a81 | 447 | cpp | C++ | pgm02_03.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | 1 | 2021-07-13T03:58:36.000Z | 2021-07-13T03:58:36.000Z | pgm02_03.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | pgm02_03.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | //
// This file contains the C++ code from Program 2.3 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm02_03.cpp
//
unsigned int Factorial (unsigned int n)
{
if (n == 0)
return 1;
else
return n * Factorial (n - 1);
}
| 24.833333 | 80 | 0.651007 | neharkarvishal |
e047b1720d51db02c5a4f7efba596675bf572a7a | 2,538 | cpp | C++ | listing_8.1.cpp | renc/CppConcurrencyInAction | e0261af587900c71d7cb2a31b56899e610be320e | [
"BSL-1.0"
] | 62 | 2016-10-14T23:11:14.000Z | 2022-03-20T08:32:15.000Z | listing_8.1.cpp | renc/CppConcurrencyInAction | e0261af587900c71d7cb2a31b56899e610be320e | [
"BSL-1.0"
] | 2 | 2017-11-16T08:17:44.000Z | 2021-10-14T06:49:41.000Z | listing_8.1.cpp | renc/CppConcurrencyInAction | e0261af587900c71d7cb2a31b56899e610be320e | [
"BSL-1.0"
] | 31 | 2017-01-04T12:32:40.000Z | 2022-03-28T12:19:20.000Z | template<typename T>
struct sorter
{
struct chunk_to_sort
{
std::list<T> data;
std::promise<std::list<T> > promise;
};
thread_safe_stack<chunk_to_sort> chunks;
std::vector<std::thread> threads;
unsigned const max_thread_count;
std::atomic<bool> end_of_data;
sorter():
max_thread_count(std::thread::hardware_concurrency()-1),
end_of_data(false)
{}
~sorter()
{
end_of_data=true;
for(unsigned i=0;i<threads.size();++i)
{
threads[i].join();
}
}
void try_sort_chunk()
{
boost::shared_ptr<chunk_to_sort > chunk=chunks.pop();
if(chunk)
{
sort_chunk(chunk);
}
}
std::list<T> do_sort(std::list<T>& chunk_data)
{
if(chunk_data.empty())
{
return chunk_data;
}
std::list<T> result;
result.splice(result.begin(),chunk_data,chunk_data.begin());
T const& partition_val=*result.begin();
typename std::list<T>::iterator divide_point=
std::partition(chunk_data.begin(),chunk_data.end(),
[&](T const& val){return val<partition_val;});
chunk_to_sort new_lower_chunk;
new_lower_chunk.data.splice(new_lower_chunk.data.end(),
chunk_data,chunk_data.begin(),
divide_point);
std::future<std::list<T> > new_lower=
new_lower_chunk.promise.get_future();
chunks.push(std::move(new_lower_chunk));
if(threads.size()<max_thread_count)
{
threads.push_back(std::thread(&sorter<T>::sort_thread,this));
}
std::list<T> new_higher(do_sort(chunk_data));
result.splice(result.end(),new_higher);
while(new_lower.wait_for(std::chrono::seconds(0)) !=
std::future_status::ready)
{
try_sort_chunk();
}
result.splice(result.begin(),new_lower.get());
return result;
}
void sort_chunk(boost::shared_ptr<chunk_to_sort > const& chunk)
{
chunk->promise.set_value(do_sort(chunk->data));
}
void sort_thread()
{
while(!end_of_data)
{
try_sort_chunk();
std::this_thread::yield();
}
}
};
template<typename T>
std::list<T> parallel_quick_sort(std::list<T> input)
{
if(input.empty())
{
return input;
}
sorter<T> s;
return s.do_sort(input);
}
| 24.640777 | 73 | 0.550827 | renc |
e04c85a0329210b5e84e7c4166cd0b2d80957b2f | 2,590 | hpp | C++ | pythran/pythonic/utils/numpy_traits.hpp | Pikalchemist/Pythran | 17d4108b56b3b365e089a4e1b01a09eb7e12942b | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/utils/numpy_traits.hpp | Pikalchemist/Pythran | 17d4108b56b3b365e089a4e1b01a09eb7e12942b | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/utils/numpy_traits.hpp | Pikalchemist/Pythran | 17d4108b56b3b365e089a4e1b01a09eb7e12942b | [
"BSD-3-Clause"
] | 1 | 2017-03-12T20:32:36.000Z | 2017-03-12T20:32:36.000Z | #ifndef PYTHONIC_UTILS_NUMPY_TRAITS_HPP
#define PYTHONIC_UTILS_NUMPY_TRAITS_HPP
namespace pythonic {
namespace types {
template<class T, size_t N>
class ndarray;
template<class A>
class numpy_iexpr;
template<class A, class F>
class numpy_fexpr;
template<class A, class ...S>
class numpy_gexpr;
template<class A>
class numpy_texpr;
template<class A>
class numpy_texpr_2;
template<class O, class... Args>
class numpy_expr;
template<class T>
class list;
template<class T, size_t N>
struct array;
template<class T>
struct is_ndarray {
static constexpr bool value = false;
};
template<class T, size_t N>
struct is_ndarray<ndarray<T,N>> {
static constexpr bool value = true;
};
/* Type trait that checks if a type is a potential numpy expression parameter
*
* Only used to write concise expression templates
*/
template<class T>
struct is_array {
static constexpr bool value = false;
};
template<class T, size_t N>
struct is_array<ndarray<T,N>> {
static constexpr bool value = true;
};
template<class A>
struct is_array<numpy_iexpr<A>> {
static constexpr bool value = true;
};
template<class A, class F>
struct is_array<numpy_fexpr<A,F>> {
static constexpr bool value = true;
};
template<class A, class... S>
struct is_array<numpy_gexpr<A,S...>> {
static constexpr bool value = true;
};
template<class A>
struct is_array<numpy_texpr<A>> {
static constexpr bool value = true;
};
template<class A>
struct is_array<numpy_texpr_2<A>> {
static constexpr bool value = true;
};
template<class O, class... Args>
struct is_array<numpy_expr<O,Args...>> {
static constexpr bool value = true;
};
template<class T>
struct is_numexpr_arg : is_array<T> {
};
template<class T>
struct is_numexpr_arg<list<T>> {
static constexpr bool value = true;
};
template<class T, size_t N>
struct is_numexpr_arg<array<T,N>> {
static constexpr bool value = true;
};
}
}
#endif
| 27.849462 | 85 | 0.535521 | Pikalchemist |
e05062ff88b45be93f2a4832f6fda5fcfea6ea79 | 1,211 | cpp | C++ | xfa/fxfa/parser/cxfa_nodelist.cpp | jamespayor/pdfium | 07b4727a34d2f4aff851f0dc420faf617caca220 | [
"BSD-3-Clause"
] | 1 | 2019-01-12T07:00:46.000Z | 2019-01-12T07:00:46.000Z | xfa/fxfa/parser/cxfa_nodelist.cpp | jamespayor/pdfium | 07b4727a34d2f4aff851f0dc420faf617caca220 | [
"BSD-3-Clause"
] | null | null | null | xfa/fxfa/parser/cxfa_nodelist.cpp | jamespayor/pdfium | 07b4727a34d2f4aff851f0dc420faf617caca220 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_nodelist.h"
#include <memory>
#include "core/fxcrt/fx_extension.h"
#include "fxjs/cfxjse_engine.h"
#include "fxjs/cjx_nodelist.h"
#include "xfa/fxfa/parser/cxfa_document.h"
#include "xfa/fxfa/parser/cxfa_node.h"
CXFA_NodeList::CXFA_NodeList(CXFA_Document* pDocument)
: CXFA_Object(pDocument,
XFA_ObjectType::NodeList,
XFA_Element::NodeList,
WideStringView(L"nodeList"),
pdfium::MakeUnique<CJX_NodeList>(this)) {
m_pDocument->GetScriptContext()->AddToCacheList(
std::unique_ptr<CXFA_NodeList>(this));
}
CXFA_NodeList::~CXFA_NodeList() {}
CXFA_Node* CXFA_NodeList::NamedItem(const WideStringView& wsName) {
uint32_t dwHashCode = FX_HashCode_GetW(wsName, false);
int32_t iCount = GetLength();
for (int32_t i = 0; i < iCount; i++) {
CXFA_Node* ret = Item(i);
if (dwHashCode == ret->GetNameHash())
return ret;
}
return nullptr;
}
| 31.051282 | 80 | 0.695293 | jamespayor |
e0611582d2ae2383e1455983130a81b56f6bf90f | 3,899 | cpp | C++ | tests/testOpenAddressingHash.cpp | tellproject/tellstore | 58fa57b4a62dcfed062aa8c191d3b0e49241ac60 | [
"Apache-2.0"
] | 49 | 2015-09-30T13:02:31.000Z | 2022-03-23T01:12:42.000Z | tests/testOpenAddressingHash.cpp | ngaut/tellstore | 58fa57b4a62dcfed062aa8c191d3b0e49241ac60 | [
"Apache-2.0"
] | 1 | 2016-07-18T03:21:56.000Z | 2016-07-27T05:07:29.000Z | tests/testOpenAddressingHash.cpp | ngaut/tellstore | 58fa57b4a62dcfed062aa8c191d3b0e49241ac60 | [
"Apache-2.0"
] | 10 | 2016-02-25T15:46:13.000Z | 2020-07-02T10:21:24.000Z | /*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <[email protected]>
* Simon Loesing <[email protected]>
* Thomas Etter <[email protected]>
* Kevin Bocksrocker <[email protected]>
* Lucas Braun <[email protected]>
*/
#include <util/OpenAddressingHash.hpp>
#include <gtest/gtest.h>
using namespace tell::store;
namespace {
class OpenAddressingTableTest : public ::testing::Test {
protected:
OpenAddressingTableTest()
: mTable(1024),
mElement1(0x1u), mElement2(0x2u), mElement3(0x3u) {
}
OpenAddressingTable mTable;
uint64_t mElement1;
uint64_t mElement2;
uint64_t mElement3;
};
/**
* @class OpenAddressingTable
* @test Check if a simple get after insert returns the element
*/
TEST_F(OpenAddressingTableTest, insertAndGet) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if multiple get and inserts return the correct elements
*/
TEST_F(OpenAddressingTableTest, insertAndGetMultiple) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_TRUE(mTable.insert(10u, 12u, &mElement2));
EXPECT_TRUE(mTable.insert(11u, 11u, &mElement3));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
EXPECT_EQ(&mElement2, mTable.get(10u, 12u));
EXPECT_EQ(&mElement3, mTable.get(11u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if inserting a duplicate fails
*/
TEST_F(OpenAddressingTableTest, insertDuplicate) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_FALSE(mTable.insert(10u, 11u, &mElement2));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if erasing an element works correctly
*/
TEST_F(OpenAddressingTableTest, erase) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
EXPECT_TRUE(mTable.erase(10u, 11u, &mElement1));
EXPECT_EQ(nullptr, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if erasing a non existing element works
*/
TEST_F(OpenAddressingTableTest, eraseNonExisting) {
EXPECT_EQ(nullptr, mTable.get(10u, 11u));
EXPECT_TRUE(mTable.erase(10u, 11u, &mElement1));
EXPECT_EQ(nullptr, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if erasing a changed element is prevented
*/
TEST_F(OpenAddressingTableTest, eraseChanged) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_FALSE(mTable.erase(10u, 11u, &mElement2));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if updating an element works
*/
TEST_F(OpenAddressingTableTest, update) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_TRUE(mTable.update(10u, 11u, &mElement1, &mElement2));
EXPECT_EQ(&mElement2, mTable.get(10u, 11u));
}
/**
* @class OpenAddressingTable
* @test Check if updating a changed element is prevented
*/
TEST_F(OpenAddressingTableTest, updateChanged) {
EXPECT_TRUE(mTable.insert(10u, 11u, &mElement1));
EXPECT_FALSE(mTable.update(10u, 11u, &mElement3, &mElement2));
EXPECT_EQ(&mElement1, mTable.get(10u, 11u));
}
}
| 28.459854 | 88 | 0.710439 | tellproject |
e068180c7c3841ca885196dbf2f2d2d7fd0b2bac | 4,729 | cpp | C++ | RTC/VolumeAdjust/src/VolumeAdjust.cpp | rsdlab/ConductorSystem | 0eff74f570f34f6f9a9d22c40c03c4030db12a4e | [
"MIT"
] | null | null | null | RTC/VolumeAdjust/src/VolumeAdjust.cpp | rsdlab/ConductorSystem | 0eff74f570f34f6f9a9d22c40c03c4030db12a4e | [
"MIT"
] | null | null | null | RTC/VolumeAdjust/src/VolumeAdjust.cpp | rsdlab/ConductorSystem | 0eff74f570f34f6f9a9d22c40c03c4030db12a4e | [
"MIT"
] | null | null | null | // -*- C++ -*-
/*!
* @file VolumeAdjust.cpp
* @brief ModuleDescription
* @date $Date$
*
* $Id$
*/
#include "VolumeAdjust.h"
// Module specification
// <rtc-template block="module_spec">
static const char* volumeadjust_spec[] =
{
"implementation_id", "VolumeAdjust",
"type_name", "VolumeAdjust",
"description", "ModuleDescription",
"version", "1.0.0",
"vendor", "VenderName",
"category", "Category",
"activity_type", "PERIODIC",
"kind", "DataFlowComponent",
"max_instance", "1",
"language", "C++",
"lang_type", "compile",
// Configuration variables
"conf.default.base", "4.5",
// Widget
"conf.__widget__.base", "text",
// Constraints
"conf.__type__.base", "double",
""
};
// </rtc-template>
/*!
* @brief constructor
* @param manager Maneger Object
*/
VolumeAdjust::VolumeAdjust(RTC::Manager* manager)
// <rtc-template block="initializer">
: RTC::DataFlowComponentBase(manager),
m_accIn("acc", m_acc),
m_baseaccIn("baseacc", m_baseacc),
m_volumesetOut("volumeset", m_volumeset)
// </rtc-template>
{
}
/*!
* @brief destructor
*/
VolumeAdjust::~VolumeAdjust()
{
}
RTC::ReturnCode_t VolumeAdjust::onInitialize()
{
// Registration: InPort/OutPort/Service
// <rtc-template block="registration">
// Set InPort buffers
addInPort("acc", m_accIn);
addInPort("baseacc", m_baseaccIn);
// Set OutPort buffer
addOutPort("volumeset", m_volumesetOut);
// Set service provider to Ports
// Set service consumers to Ports
// Set CORBA Service Ports
// </rtc-template>
// <rtc-template block="bind_config">
// Bind variables and configuration variable
bindParameter("base", m_base, "4.5");
// </rtc-template>
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t VolumeAdjust::onFinalize()
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onStartup(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onShutdown(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
RTC::ReturnCode_t VolumeAdjust::onActivated(RTC::UniqueId ec_id)
{
count = 1;
memset(data, 0, sizeof(data));
basedata = m_base;
return RTC::RTC_OK;
}
RTC::ReturnCode_t VolumeAdjust::onDeactivated(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
RTC::ReturnCode_t VolumeAdjust::onExecute(RTC::UniqueId ec_id)
{
if(m_accIn.isNew())
{
m_accIn.read();
accdata = m_acc.data;
if(count<(sizeof(data)/sizeof(data[0]))){
count += 1;
}else{
count = 1;
}
data[count] = accdata;
std::cout<<"accdata"<<accdata<<std::endl;
sum = 0;
ave= 0;
for(i=0;i<(sizeof(data)/sizeof(data[0]));i++){
sum += data[i];
}
ave = sum/(sizeof(data)/sizeof(data[0]));
changedata = ave*100/(basedata*2);
if(0<=changedata && changedata<=5){m_volumeset.data = 0;}
else if(5<changedata && changedata<=15){m_volumeset.data = 10;}
else if(15<changedata && changedata<=25){m_volumeset.data = 20;}
else if(25<changedata && changedata<=35){m_volumeset.data = 30;}
else if(35<changedata && changedata<=45){m_volumeset.data = 40;}
else if(45<changedata && changedata<=55){m_volumeset.data = 50;}
else if(55<changedata && changedata<=65){m_volumeset.data = 60;}
else if(65<changedata && changedata<=75){m_volumeset.data = 70;}
else if(75<changedata && changedata<=85){m_volumeset.data = 80;}
else if(85<changedata && changedata<=95){m_volumeset.data = 90;}
else if(95<changedata){m_volumeset.data = 100;}
std::cout<<"set volume :"<< m_volumeset.data <<std::endl;
m_volumesetOut.write();
}
if(m_baseaccIn.isNew())
{
m_baseaccIn.read();
basedata = m_baseacc.data;
}
if(basedata == 0){
return RTC::RTC_ERROR;
}
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t VolumeAdjust::onAborting(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onError(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onReset(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onStateUpdate(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t VolumeAdjust::onRateChanged(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
extern "C"
{
void VolumeAdjustInit(RTC::Manager* manager)
{
coil::Properties profile(volumeadjust_spec);
manager->registerFactory(profile,
RTC::Create<VolumeAdjust>,
RTC::Delete<VolumeAdjust>);
}
};
| 20.383621 | 70 | 0.618524 | rsdlab |
2fda1fbec701c99d237ea4c2bb3ff1f8226e6107 | 19,329 | cpp | C++ | sp/src/game/server/hl2/prop_gravity_ball.cpp | ntrf/blamod | d59b5f968264121d013a81ae1ba1f51432030170 | [
"Apache-2.0"
] | 12 | 2016-09-24T02:47:18.000Z | 2020-12-29T16:16:52.000Z | sp/src/game/server/hl2/prop_gravity_ball.cpp | Margen67/blamod | d59b5f968264121d013a81ae1ba1f51432030170 | [
"Apache-2.0"
] | 31 | 2016-11-27T14:38:02.000Z | 2020-06-03T11:11:29.000Z | sp/src/game/server/hl2/prop_gravity_ball.cpp | Margen67/blamod | d59b5f968264121d013a81ae1ba1f51432030170 | [
"Apache-2.0"
] | 3 | 2016-09-24T16:08:44.000Z | 2020-12-30T00:59:58.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: TE120 combine ball - launched by physconcussion
//
//
//=============================================================================//
#include "cbase.h"
#include "prop_combine_ball.h"
#include "prop_gravity_ball.h"
#include "props.h"
#include "explode.h"
#include "saverestore_utlvector.h"
#include "hl2_shareddefs.h"
#include "materialsystem/imaterial.h"
#include "beam_flags.h"
#include "physics_prop_ragdoll.h"
#include "soundent.h"
#include "soundenvelope.h"
#include "te_effect_dispatch.h"
#include "ai_basenpc.h"
#include "npc_bullseye.h"
#include "filters.h"
#include "SpriteTrail.h"
#include "decals.h"
#include "hl2_player.h"
#include "eventqueue.h"
#include "physics_collisionevent.h"
#include "gamestats.h"
#include "weapon_physcannon.h"
#include "util.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define PROP_GRAVITY_BALL_MODEL "models/effects/combineball.mdl"
#define PROP_GRAVITY_BALL_SPRITE_TRAIL "sprites/combineball_trail_black_1.vmt"
ConVar gravityball_tracelength( "gravityball_tracelength", "128" );
ConVar gravityball_magnitude( "gravityball_magnitude", "1.07f" );
ConVar gravityball_knockback("gravityball_knockback", "26000.0f");
ConVar gravityball_ignorewalls("gravityball_ignorewalls", "0", FCVAR_NOTIFY);
ConVar gravityball_response("gravityball_response", "2", FCVAR_NOTIFY);
// For our ring explosion
int s_nExplosionGBTexture = -1;
//-----------------------------------------------------------------------------
// Context think
//-----------------------------------------------------------------------------
static const char *s_pRemoveContext = "RemoveContext";
//-----------------------------------------------------------------------------
// Purpose:
// Input : radius -
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CBaseEntity *CreateGravityBall(const Vector &origin, const Vector &velocity, float radius, float mass, float lifetime, CBaseEntity *pOwner, class CWeaponPhysCannon *pWeapon)
{
CPropGravityBall *pBall = static_cast<CPropGravityBall*>( CreateEntityByName( "prop_gravity_ball" ) );
pBall->m_pWeaponPC = pWeapon;
pBall->SetRadius( radius );
pBall->SetAbsOrigin( origin );
pBall->SetOwnerEntity( pOwner );
pBall->SetOriginalOwner( pOwner );
pBall->SetAbsVelocity( velocity );
pBall->Spawn();
pBall->SetState( CPropCombineBall::STATE_THROWN );
pBall->SetSpeed( velocity.Length() );
pBall->EmitSound( "NPC_GravityBall.Launch" );
PhysSetGameFlags( pBall->VPhysicsGetObject(), FVPHYSICS_WAS_THROWN );
pBall->StartWhizSoundThink();
pBall->SetMass( mass );
pBall->StartLifetime( lifetime );
pBall->SetWeaponLaunched( true );
pBall->SetModel( PROP_GRAVITY_BALL_MODEL );
return pBall;
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether a physics object is a combine ball or not
// Input : *pObj - Object to test
// Output : Returns true on success, false on failure.
// Notes : This function cannot identify a combine ball that is held by
// the physcannon because any object held by the physcannon is
// COLLISIONGROUP_DEBRIS.
//-----------------------------------------------------------------------------
bool UTIL_IsGravityBall( CBaseEntity *pEntity )
{
// Must be the correct collision group
if ( pEntity->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether a physics object is an AR2 combine ball or not
// Input : *pEntity -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool UTIL_IsAR2GravityBall( CBaseEntity *pEntity )
{
// Must be the correct collision group
if ( pEntity->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return false;
CPropGravityBall *pBall = dynamic_cast<CPropGravityBall *>(pEntity);
if ( pBall && pBall->WasWeaponLaunched() )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Uses a deeper casting check to determine if pEntity is a combine
// ball. This function exists because the normal (much faster) check
// in UTIL_IsCombineBall() can never identify a combine ball held by
// the physcannon because the physcannon changes the held entity's
// collision group.
// Input : *pEntity - Entity to check
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool UTIL_IsGravityBallDefinite( CBaseEntity *pEntity )
{
CPropGravityBall *pBall = dynamic_cast<CPropGravityBall *>(pEntity);
return pBall != NULL;
}
//-----------------------------------------------------------------------------
// Implementation of CPropCombineBall
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( prop_gravity_ball, CPropGravityBall );
//-----------------------------------------------------------------------------
// Save/load:
//-----------------------------------------------------------------------------
BEGIN_DATADESC( CPropGravityBall )
DEFINE_FIELD( m_flLastBounceTime, FIELD_TIME ),
DEFINE_FIELD( m_flRadius, FIELD_FLOAT ),
DEFINE_FIELD( m_nState, FIELD_CHARACTER ),
DEFINE_FIELD( m_pGlowTrail, FIELD_CLASSPTR ),
DEFINE_SOUNDPATCH( m_pHoldingSound ),
DEFINE_FIELD( m_bFiredGrabbedOutput, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bEmit, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bHeld, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bLaunched, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bStruckEntity, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bWeaponLaunched, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bForward, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_flNextDamageTime, FIELD_TIME ),
DEFINE_FIELD( m_flLastCaptureTime, FIELD_TIME ),
DEFINE_FIELD( m_bCaptureInProgress, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nBounceCount, FIELD_INTEGER ),
DEFINE_FIELD( m_nMaxBounces, FIELD_INTEGER ),
DEFINE_FIELD( m_bBounceDie, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hSpawner, FIELD_EHANDLE ),
DEFINE_THINKFUNC( ExplodeThink ),
DEFINE_THINKFUNC( WhizSoundThink ),
DEFINE_THINKFUNC( DieThink ),
DEFINE_THINKFUNC( DissolveThink ),
DEFINE_THINKFUNC( DissolveRampSoundThink ),
DEFINE_THINKFUNC( AnimThink ),
DEFINE_THINKFUNC( CaptureBySpawner ),
DEFINE_INPUTFUNC( FIELD_VOID, "Explode", InputExplode ),
DEFINE_INPUTFUNC( FIELD_VOID, "FadeAndRespawn", InputFadeAndRespawn ),
DEFINE_INPUTFUNC( FIELD_VOID, "Kill", InputKill ),
DEFINE_INPUTFUNC( FIELD_VOID, "Socketed", InputSocketed ),
END_DATADESC()
IMPLEMENT_SERVERCLASS_ST( CPropGravityBall, DT_PropGravityBall )
SendPropBool( SENDINFO( m_bEmit ) ),
SendPropFloat( SENDINFO( m_flRadius ), 0, SPROP_NOSCALE ),
SendPropBool( SENDINFO( m_bHeld ) ),
SendPropBool( SENDINFO( m_bLaunched ) ),
END_SEND_TABLE()
//-----------------------------------------------------------------------------
// Precache
//-----------------------------------------------------------------------------
void CPropGravityBall::Precache( void )
{
// NOTENOTE: We don't call into the base class because it chains multiple
// precaches we don't need to incur
PrecacheModel( PROP_GRAVITY_BALL_MODEL );
PrecacheModel( PROP_GRAVITY_BALL_SPRITE_TRAIL);
s_nExplosionGBTexture = PrecacheModel( "sprites/lgtning.vmt" );
PrecacheScriptSound( "NPC_GravityBall.Launch" );
PrecacheScriptSound( "NPC_GravityBall.Explosion" );
PrecacheScriptSound( "NPC_GravityBall.WhizFlyby" );
if ( hl2_episodic.GetBool() )
{
PrecacheScriptSound( "NPC_CombineBall_Episodic.Impact" );
}
else
{
PrecacheScriptSound( "NPC_CombineBall.Impact" );
}
}
//-----------------------------------------------------------------------------
// Spawn:
//-----------------------------------------------------------------------------
void CPropGravityBall::Spawn( void )
{
CBaseAnimating::Spawn();
SetModel( PROP_GRAVITY_BALL_MODEL );
if( ShouldHitPlayer() )
{
// This allows the combine ball to hit the player.
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL_NPC );
}
else
{
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL );
}
CreateVPhysics();
Vector vecAbsVelocity = GetAbsVelocity();
VPhysicsGetObject()->SetVelocity( &vecAbsVelocity, NULL );
m_nState = STATE_NOT_THROWN;
m_flLastBounceTime = -1.0f;
m_bFiredGrabbedOutput = false;
m_bForward = true;
m_bCaptureInProgress = false;
// No shadow!
AddEffects( EF_NOSHADOW );
// Start up the eye trail
CSpriteTrail *pGlowTrail = CSpriteTrail::SpriteTrailCreate( PROP_GRAVITY_BALL_SPRITE_TRAIL, GetAbsOrigin(), false );
m_pGlowTrail = pGlowTrail;
if ( pGlowTrail != NULL )
{
pGlowTrail->FollowEntity( this );
pGlowTrail->SetTransparency( kRenderTransAdd, 0, 0, 0, 255, kRenderFxNone );
pGlowTrail->SetStartWidth( m_flRadius );
pGlowTrail->SetEndWidth( 0 );
pGlowTrail->SetLifeTime( 0.1f );
pGlowTrail->TurnOff();
}
m_bEmit = true;
m_bHeld = false;
m_bLaunched = false;
m_bStruckEntity = false;
m_bWeaponLaunched = false;
m_flNextDamageTime = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Create vphysics
//-----------------------------------------------------------------------------
bool CPropGravityBall::CreateVPhysics()
{
SetSolid( SOLID_BBOX );
float flSize = m_flRadius;
SetCollisionBounds( Vector(-flSize, -flSize, -flSize), Vector(flSize, flSize, flSize) );
objectparams_t params = g_PhysDefaultObjectParams;
params.pGameData = static_cast<void *>(this);
int nMaterialIndex = physprops->GetSurfaceIndex("metal_bouncy");
IPhysicsObject *pPhysicsObject = physenv->CreateSphereObject( flSize, nMaterialIndex, GetAbsOrigin(), GetAbsAngles(), ¶ms, false );
if ( !pPhysicsObject )
return false;
VPhysicsSetObject( pPhysicsObject );
SetMoveType( MOVETYPE_VPHYSICS );
pPhysicsObject->Wake();
pPhysicsObject->SetMass( 750.0f );
pPhysicsObject->EnableGravity( false );
pPhysicsObject->EnableDrag( false );
float flDamping = 0.0f;
float flAngDamping = 0.5f;
pPhysicsObject->SetDamping( &flDamping, &flAngDamping );
pPhysicsObject->SetInertia( Vector( 1e30, 1e30, 1e30 ) );
PhysSetGameFlags( pPhysicsObject, FVPHYSICS_NO_NPC_IMPACT_DMG );
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropGravityBall::DoImpactEffect( const Vector &preVelocity, int index, gamevcollisionevent_t *pEvent )
{
// Do that crazy impact effect!
trace_t tr;
CollisionEventToTrace( !index, pEvent, tr );
CBaseEntity *pTraceEntity = pEvent->pEntities[index];
UTIL_TraceLine( tr.startpos - preVelocity * 2.0f, tr.startpos + preVelocity * 2.0f, MASK_SOLID, pTraceEntity, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction < 1.0f )
{
// See if we hit the sky
if ( tr.surface.flags & SURF_SKY )
{
DoExplosion();
return;
}
// Send the effect over
CEffectData data;
data.m_flRadius = 16;
data.m_vNormal = tr.plane.normal;
data.m_vOrigin = tr.endpos + tr.plane.normal * 1.0f;
DispatchEffect( "gball_bounce", data );
// We need to affect ragdolls on the client
CEffectData dataRag;
dataRag.m_vOrigin = GetAbsOrigin();
dataRag.m_flRadius = gravityball_tracelength.GetFloat();
dataRag.m_flMagnitude = 1.0f;
DispatchEffect( "RagdollConcussion", dataRag );
}
if ( hl2_episodic.GetBool() )
{
EmitSound( "NPC_CombineBall_Episodic.Impact" );
}
else
{
EmitSound( "NPC_CombineBall.Impact" );
}
}
//-----------------------------------------------------------------------------
// Lighten the mass so it's zippy toget to the gun
//-----------------------------------------------------------------------------
void CPropGravityBall::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
{
/* Do nothing, don't want to allow phys gun pickup. */
CDefaultPlayerPickupVPhysics::OnPhysGunPickup( pPhysGunUser, reason );
}
//------------------------------------------------------------------------------
// Pow!
//------------------------------------------------------------------------------
void CPropGravityBall::DoExplosion( )
{
// don't do this twice
if ( GetMoveType() == MOVETYPE_NONE )
return;
if ( PhysIsInCallback() )
{
g_PostSimulationQueue.QueueCall( this, &CPropGravityBall::DoExplosion );
return;
}
//Shockring
CBroadcastRecipientFilter filter2;
EmitSound( "NPC_GravityBall.Explosion" );
UTIL_ScreenShake( GetAbsOrigin(), 20.0f, 150.0, 1.0, 1250.0f, SHAKE_START );
CEffectData data;
data.m_vOrigin = GetAbsOrigin();
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
m_flRadius, //start radius
gravityball_tracelength.GetFloat() + 128.0, //end radius
s_nExplosionGBTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.2f, //life
64, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
32, //a
0, //speed
FBEAM_FADEOUT
);
//Shockring
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
m_flRadius, //start radius
gravityball_tracelength.GetFloat() + 128.0, //end radius
s_nExplosionGBTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.5f, //life
64, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
64, //a
0, //speed
FBEAM_FADEOUT
);
if( hl2_episodic.GetBool() )
{
CSoundEnt::InsertSound( SOUND_COMBAT | SOUND_CONTEXT_EXPLOSION, WorldSpaceCenter(), 180.0f, 0.25, this );
}
// Turn us off and wait because we need our trails to finish up properly
SetAbsVelocity( vec3_origin );
SetMoveType( MOVETYPE_NONE );
AddSolidFlags( FSOLID_NOT_SOLID );
SetEmitState( false );
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player *>( GetOwnerEntity() );
if( !m_bStruckEntity && hl2_episodic.GetBool() && GetOwnerEntity() != NULL )
{
// Notify the player proxy that this combine ball missed so that it can fire an output.
if ( pPlayer )
{
pPlayer->MissedAR2AltFire();
}
}
SetContextThink( &CPropCombineBall::SUB_Remove, gpGlobals->curtime + 0.5f, s_pRemoveContext );
StopLoopingSounds();
// Gravity Push these mofos
CBaseEntity *list[512]; // An array to store all the nearby gravity affected entities
Vector start, end, forward; // Vectors for traces if valid entity
CBaseEntity *pEntity;
int count = UTIL_EntitiesInSphere(list, 512, GetAbsOrigin(), gravityball_tracelength.GetFloat(), 0);
start = GetAbsOrigin();
// Make sure we're not in the ground
if (UTIL_PointContents(start) & CONTENTS_SOLID)
start.z += 1;
// Loop through each entity and apply a force
for ( int i = 0; i < count; i++ )
{
// Make sure the entity is valid or not itself or not the firing weapon
pEntity = list[i];
// Make sure the entity is valid or not itself or not the firing weapon
if ( !pEntity || pEntity == this || pEntity == (CBaseEntity*)this->m_pWeaponPC )
continue;
// Make sure its a gravity touchable entity
if ( (pEntity->IsEFlagSet( EFL_NO_PHYSCANNON_INTERACTION ) || pEntity->GetMoveType() != MOVETYPE_VPHYSICS) && ( pEntity->m_takedamage == DAMAGE_NO ) )
{
continue;
}
// Check that the explosion can 'see' this entity.
end = pEntity->BodyTarget(start, false);
// direction of flight
forward = end - start;
// Skew the z direction upward
//forward.z += 44.0f;
trace_t tr;
UTIL_TraceLine(start, end, (MASK_SHOT | CONTENTS_GRATE), pEntity, COLLISION_GROUP_NONE, &tr);
// debugoverlay->AddLineOverlay( start, end, 0,255,0, true, 18.0 );
if (!gravityball_ignorewalls.GetBool() && !pEntity->IsPlayer() && tr.fraction != 1.0 && tr.m_pEnt != pEntity && !tr.allsolid)
continue;
if (pEntity->IsPlayer()) {
Vector fbellow = pEntity->GetAbsOrigin();
Vector fabove = fbellow;
fabove.z += 2.0f;
trace_t ptr;
UTIL_TraceLine(fbellow, fabove, MASK_PLAYERSOLID, pEntity, COLLISION_GROUP_NONE, &ptr);
if (ptr.startsolid)
forward.z += 44.0f;
}
// normalizing the vector
float len = forward.Length();
if (gravityball_response.GetInt() == 1) {
float pow_x = clamp(len / gravityball_tracelength.GetFloat(), 0.0f, 1.0f);
float pow_y = 1.0f - pow_x * pow_x;
forward *= pow_y * gravityball_magnitude.GetFloat() / len;
} else if (gravityball_response.GetInt() == 2) {
float pow_x = clamp(len / gravityball_tracelength.GetFloat(), 0.5f, 1.0f);
forward *= pow_x / len;
} else {
forward /= gravityball_tracelength.GetFloat();
}
forward *= gravityball_magnitude.GetFloat();
// DevMsg("Found valid gravity entity %s / forward %f %f %f\n", pEntity->GetClassname(),
// forward.x, forward.y, forward.z);
// Punt Non VPhysics Objects
if ( pEntity->GetMoveType() != MOVETYPE_VPHYSICS )
{
// Amplify the height of the push
forward.z *= 1.4f;
if ( pEntity->IsNPC() && !pEntity->IsEFlagSet( EFL_NO_MEGAPHYSCANNON_RAGDOLL ) && pEntity->MyNPCPointer()->CanBecomeRagdoll() )
{
// Necessary to cause it to do the appropriate death cleanup
Vector force = forward * gravityball_knockback.GetFloat();
CTakeDamageInfo ragdollInfo(pPlayer, pPlayer, force, end, 10000.0, DMG_PHYSGUN | DMG_BLAST);
pEntity->TakeDamage( ragdollInfo );
}
else if ( m_pWeaponPC )
{
PhysCannon_PuntConcussionNonVPhysics(m_pWeaponPC, pEntity, forward, tr);
}
}
else
{
if (PhysCannonEntityAllowsPunts(m_pWeaponPC, pEntity) == false )
{
continue;
}
if ( dynamic_cast<CRagdollProp*>(pEntity) )
{
// Amplify the height of the push
forward.z *= 1.4f;
if ( m_pWeaponPC )
PhysCannon_PuntConcussionRagdoll(m_pWeaponPC, pEntity, forward, tr);
}
else if ( m_pWeaponPC )
{
PhysCannon_PuntConcussionVPhysics(m_pWeaponPC, pEntity, forward, tr);
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CPropGravityBall::IsHittableEntity( CBaseEntity *pHitEntity )
{
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropGravityBall::OnHitEntity( CBaseEntity *pHitEntity, float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
DoExplosion();
}
//-----------------------------------------------------------------------------
// Deflects the ball toward enemies in case of a collision
//-----------------------------------------------------------------------------
void CPropGravityBall::DeflectTowardEnemy( float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
/* Do nothing, we just want this to explode. */
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropGravityBall::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )
{
CPropCombineBall::VPhysicsCollision( index, pEvent );
DoExplosion();
}
| 31.429268 | 173 | 0.62326 | ntrf |
2fded95ceaec827151e12e1f6f025b3732cd03d4 | 1,323 | cpp | C++ | tree/left_view_simple_recusion.cpp | kashyap99saksham/Code | 96658d0920eb79c007701d2a3cc9dbf453d78f96 | [
"MIT"
] | 16 | 2020-06-02T19:22:45.000Z | 2022-02-05T10:35:28.000Z | tree/left_view_simple_recusion.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | null | null | null | tree/left_view_simple_recusion.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 2 | 2020-08-27T17:40:06.000Z | 2022-02-05T10:33:52.000Z | /*
Given a Binary Tree, print left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from left side.
left-view
Examples:
Input :
1
/ \
2 3
/ \ \
4 5 6
Output : 1 2 4
Input :
1
/ \
2 3
\
4
\
5
\
6
Output :1 2 4 5 6
*/
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
void leftViewUtil(node* root,int level, int* maxLevel){
if(!root) return;
if(*maxLevel<level){
cout<<root->data<<" ";
*maxLevel=level;
}
leftViewUtil(root->left, level+1, maxLevel);
leftViewUtil(root->right, level+1, maxLevel);
}
struct node* newNode(int value){
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->data=value;
temp->left=temp->right=NULL;
return temp;
}
void leftView(struct node* root){
int maxLevel=0;
leftViewUtil(root, 1, &maxLevel);
}
int main(){
struct node* root=newNode(1);
root->left=newNode(2);
root->right=newNode(3);
root->right->left=newNode(4);
root->right->left->right=newNode(5);
leftView(root);
return 0;
}
| 16.5375 | 131 | 0.535903 | kashyap99saksham |
2fe43e6569d47f6f433679d35f420ed5e6eac3cd | 23,369 | cpp | C++ | src/widgets/numpad_debug.cpp | milostosic/rapp | 5fab06e6fb8e43dda62b4a86b1c4b3e71670b261 | [
"BSD-2-Clause"
] | 53 | 2017-11-08T06:23:47.000Z | 2022-03-25T20:14:38.000Z | src/widgets/numpad_debug.cpp | milostosic/rapp | 5fab06e6fb8e43dda62b4a86b1c4b3e71670b261 | [
"BSD-2-Clause"
] | null | null | null | src/widgets/numpad_debug.cpp | milostosic/rapp | 5fab06e6fb8e43dda62b4a86b1c4b3e71670b261 | [
"BSD-2-Clause"
] | 7 | 2018-09-07T02:27:48.000Z | 2022-03-25T20:14:40.000Z | //--------------------------------------------------------------------------//
/// Copyright (c) 2010-2016 Milos Tosic. All Rights Reserved. ///
/// License: http://www.opensource.org/licenses/BSD-2-Clause ///
//--------------------------------------------------------------------------//
#include <rapp_pch.h>
#include <rapp/inc/rapp.h>
#include <rapp/inc/widgets/numpad_debug.h>
#include <inttypes.h>
#if RAPP_WITH_BGFX
namespace rapp {
static inline uint32_t propertyGetSize(Property::Type _type)
{
switch (_type)
{
case Property::Uint8:
case Property::Int8: return 1;
case Property::Uint16:
case Property::Int16: return 2;
case Property::Uint32:
case Property::Int32: return 4;
case Property::Uint64:
case Property::Int64: return 8;
case Property::Float: return sizeof(float);
case Property::Double: return sizeof(double);
case Property::Bool: return sizeof(bool);
case Property::Color: return 16; // 4 floats
default: return 0;
};
}
inline void propertyCopyValue(Property::Type _type, void* _dest, void* _src)
{
uint32_t copySize = propertyGetSize(_type);
if (copySize)
memcpy(_dest, _src, copySize);
}
inline bool propertyIsGreater(Property::Type _type, void* _v1, void* _v2)
{
switch (_type)
{
case Property::Int8: return *(int8_t*)_v1 > *(int8_t*)_v2;
case Property::Int16: return *(int16_t*)_v1 > *(int16_t*)_v2;
case Property::Int32: return *(int32_t*)_v1 > *(int32_t*)_v2;
case Property::Int64: return *(int64_t*)_v1 > *(int64_t*)_v2;
case Property::Uint8: return *(uint8_t*)_v1 > *(uint8_t*)_v2;
case Property::Uint16: return *(uint16_t*)_v1 > *(uint16_t*)_v2;
case Property::Uint32: return *(uint32_t*)_v1 > *(uint32_t*)_v2;
case Property::Uint64: return *(uint64_t*)_v1 > *(uint64_t*)_v2;
case Property::Float: return *(float*)_v1 > *(float*)_v2;
case Property::Double: return *(double*)_v1 > *(double*)_v2;
};
return false;
}
void propertyClamp(DebugMenu* _menu)
{
if (propertyIsGreater(_menu->m_type, _menu->m_minMax.m_min, _menu->m_value))
memcpy(_menu->m_value, _menu->m_minMax.m_min, propertyGetSize(_menu->m_type));
if (propertyIsGreater(_menu->m_type, _menu->m_value, _menu->m_minMax.m_max))
memcpy(_menu->m_value, _menu->m_minMax.m_max, propertyGetSize(_menu->m_type));
}
void propertyPrintToBuffer(ImGuiDataType _type, void* _value, char _buffer[128])
{
switch (_type)
{
case ImGuiDataType_S8: sprintf(_buffer, "%" PRId8, *(int8_t*)_value); break;
case ImGuiDataType_S16: sprintf(_buffer, "%" PRId16, *(int16_t*)_value); break;
case ImGuiDataType_S32: sprintf(_buffer, "%" PRId32, *(int32_t*)_value); break;
case ImGuiDataType_S64: sprintf(_buffer, "%" PRId64, *(int64_t*)_value); break;
case ImGuiDataType_U8: sprintf(_buffer, "%" PRIu8, *(uint8_t*)_value); break;
case ImGuiDataType_U16: sprintf(_buffer, "%" PRIu16,*(uint16_t*)_value); break;
case ImGuiDataType_U32: sprintf(_buffer, "%" PRIu32,*(uint32_t*)_value); break;
case ImGuiDataType_U64: sprintf(_buffer, "%" PRIu64,*(uint64_t*)_value); break;
case ImGuiDataType_Float: sprintf(_buffer, "%f", *(float*)_value); break;
case ImGuiDataType_Double: sprintf(_buffer, "%lf", *(double*)_value); break;
};
}
DebugMenu g_rootMenu(0, "Home");
rapp::DebugMenu* g_currentDebugMenu = 0;
void initializeMenus()
{
g_rootMenu.m_type = Property::None;
g_currentDebugMenu = &g_rootMenu;
}
DebugMenu::DebugMenu(DebugMenu* _parent, const char* _label, uint32_t _width, Property::Type _type)
: m_parent(_parent)
, m_index(0)
, m_numChildren(0)
, m_label(_label)
, m_type(_type)
, m_width(_width)
, m_customEditor(0)
, m_customPreview(0)
, m_minmaxSet(false)
{
static int initialized = 0;
if (initialized++ == 1)
{
initializeMenus();
}
if (!_parent)
m_parent = g_currentDebugMenu;
for (int i=0; i<8; ++i)
m_children[i] = 0;
if (m_width > 1)
if (!((_type >= Property::Int8) && (_type <= Property::Double)))
{
RTM_BREAK;
}
if (m_parent)
{
if (m_parent->m_numChildren == 8) // ignore more than 8 child menus
return;
m_index = m_parent->m_numChildren;
if (m_parent)
m_parent->m_children[m_parent->m_numChildren++] = this;
}
else
m_index = 0;
}
DebugMenu::DebugMenu(DebugMenu* _parent, const char* _label, Property::Type _type, void* _pointer
, void* _defaultValue
, void* _minValue
, void* _maxValue
, CustomDfltFn _customDefault
, CustomEditFn _customEditor
, CustomPrevFn _customPreview)
: m_parent(_parent)
, m_index(0)
, m_numChildren(0)
, m_label(_label)
, m_type(_type)
, m_width(1)
, m_value(_pointer)
, m_customEditor(_customEditor)
, m_customPreview(_customPreview)
, m_minmaxSet(false)
{
if (m_parent->m_numChildren == 8) // ignore more than 8 child menus
return;
for (int i=0; i<8; ++i)
m_children[i] = 0;
m_index = m_parent->m_numChildren;
m_parent->m_children[m_parent->m_numChildren++] = this;
if (Property::Color == _type)
{
_defaultValue = (float*)*(float**)_defaultValue;
if (_minValue && _maxValue)
{
_minValue = (float*)*(float**)_minValue;
_maxValue = (float*)*(float**)_maxValue;
}
}
if (_defaultValue)
propertyCopyValue(_type, m_value, _defaultValue);
if (_customDefault)
_customDefault(m_value);
if (_minValue && _minValue)
{
propertyCopyValue(_type, m_minMax.m_min, _minValue);
propertyCopyValue(_type, m_minMax.m_max, _maxValue);
m_minmaxSet = true;
}
}
ImGuiDataType rappToImGuiScalarType(Property::Type _type)
{
switch (_type)
{
case Property::Int8: return ImGuiDataType_S8;
case Property::Int16: return ImGuiDataType_S16;
case Property::Int32: return ImGuiDataType_S32;
case Property::Int64: return ImGuiDataType_S64;
case Property::Uint8: return ImGuiDataType_U8;
case Property::Uint16: return ImGuiDataType_U16;
case Property::Uint32: return ImGuiDataType_U32;
case Property::Uint64: return ImGuiDataType_U64;
case Property::Float: return ImGuiDataType_Float;
case Property::Double: return ImGuiDataType_Double;
};
RTM_BREAK;
return ImGuiDataType_COUNT;
}
void rappPrintValueType(ImGuiDataType _type, void* _value)
{
char text[128];
propertyPrintToBuffer(_type, _value, text);
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT), text);
}
void rappAddCentered_text(const char* _text, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
float fontSizeNumber = ImGui::GetFontSize() * 1.35f;
ImVec2 text_size(1000.0f, 1000.0f);
while (text_size.y > _size.y)
{
fontSizeNumber *= 0.9f;
text_size = ImGui::GetFont()->CalcTextSizeA(fontSizeNumber, FLT_MAX, 0.0f, _text);
}
_drawList->PushClipRect(_minXY, ImVec2(_minXY.x + _size.x, _minXY.y + _size.y));
ImVec2 textPos(_minXY.x + (_size.x - text_size.x)/2, _minXY.y + (_size.y - text_size.y)/2);
_drawList->AddText(0, fontSizeNumber, textPos, RAPP_COLOR_TEXT, _text);
_drawList->PopClipRect();
}
static int cmdKey(rapp::App* /*_app*/, void* /*_userData*/, int /*_argc*/, char const* const* /*_argv*/)
{
return 0;
}
void rappDebugAddBindings()
{
static bool inputBindingsRegistered = false;
if (inputBindingsRegistered)
return;
inputBindingsRegistered = true;
static const rapp::InputBinding bindings[] =
{
{ 0, "num0", 1, { rapp::KeyboardState::Key::NumPad0, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num1", 1, { rapp::KeyboardState::Key::NumPad1, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num2", 1, { rapp::KeyboardState::Key::NumPad2, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num3", 1, { rapp::KeyboardState::Key::NumPad3, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num4", 1, { rapp::KeyboardState::Key::NumPad4, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num5", 1, { rapp::KeyboardState::Key::NumPad5, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num6", 1, { rapp::KeyboardState::Key::NumPad6, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num7", 1, { rapp::KeyboardState::Key::NumPad7, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num8", 1, { rapp::KeyboardState::Key::NumPad8, rapp::KeyboardState::Modifier::NoMods }},
{ 0, "num9", 1, { rapp::KeyboardState::Key::NumPad9, rapp::KeyboardState::Modifier::NoMods }},
RAPP_INPUT_BINDING_END
};
rapp::inputAddBindings("debug_bindings", bindings);
rapp::cmdAdd("num0", cmdKey, (void*)KeyboardState::Key::NumPad0, "");
rapp::cmdAdd("num1", cmdKey, (void*)KeyboardState::Key::NumPad1, "");
rapp::cmdAdd("num2", cmdKey, (void*)KeyboardState::Key::NumPad2, "");
rapp::cmdAdd("num3", cmdKey, (void*)KeyboardState::Key::NumPad3, "");
rapp::cmdAdd("num4", cmdKey, (void*)KeyboardState::Key::NumPad4, "");
rapp::cmdAdd("num5", cmdKey, (void*)KeyboardState::Key::NumPad5, "");
rapp::cmdAdd("num6", cmdKey, (void*)KeyboardState::Key::NumPad6, "");
rapp::cmdAdd("num7", cmdKey, (void*)KeyboardState::Key::NumPad7, "");
rapp::cmdAdd("num8", cmdKey, (void*)KeyboardState::Key::NumPad8, "");
rapp::cmdAdd("num9", cmdKey, (void*)KeyboardState::Key::NumPad9, "");
}
static void rappPropertyTypeEditor_scalar(DebugMenu* _menu, ImGuiDataType _type, int _cnt = -1)
{
if (!_menu->m_value)
{
for (uint32_t i=0; i<_menu->m_width; ++i)
rappPropertyTypeEditor_scalar(_menu->m_children[i], rappToImGuiScalarType(_menu->m_type), i);
}
else
{
if (_menu->m_minmaxSet)
{
char name1[6]; strcpy(name1, "##00"); name1[3] = (char)('0' + _cnt);
char name2[6]; strcpy(name2, "##10"); name2[3] = (char)('0' + _cnt);
ImGui::InputScalar(name1, _type, _menu->m_value);
propertyClamp(_menu);
ImGui::SliderScalar(name2, _type, _menu->m_value, _menu->m_minMax.m_min, _menu->m_minMax.m_max);
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT_HIGHLIGHT), "Min:");
ImGui::SameLine();
rappPrintValueType(_type, _menu->m_minMax.m_min);
ImGui::SameLine();
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT_HIGHLIGHT), "Max:");
ImGui::SameLine();
rappPrintValueType(_type, _menu->m_minMax.m_max);
}
else
ImGui::InputScalar("", _type, _menu->m_value);
}
}
static void rappPropertyPreview_scalar(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size, ImGuiDataType _type)
{
char text[128];
char textFull[128*4] = "";
if (!_menu->m_value)
{
for (uint32_t i=0; i<_menu->m_width; ++i)
{
propertyPrintToBuffer(_type, _menu->m_children[i]->m_value, text);
strcat(textFull, text);
if (i != _menu->m_width)
strcat(textFull, "\n");
}
}
else
propertyPrintToBuffer(_type, _menu->m_value, textFull);
rappAddCentered_text(textFull, _drawList, _minXY, _size);
}
static void rappPropertyTypeEditor_Bool(DebugMenu* _menu)
{
bool* valuePtr = (bool*)_menu->m_value;
int b = *valuePtr ? 1 : 0;
ImGui::RadioButton("False", &b, 0);
ImGui::SameLine();
ImGui::RadioButton("True", &b, 1);
*valuePtr = b == 1 ? true : false;
}
static void rappPropertyPreview_Bool(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
bool value = *(bool*)_menu->m_value;
rappAddCentered_text(value ? "True" : "False", _drawList, _minXY, _size);
}
static void rappPropertyTypeEditor_Color(DebugMenu* _menu)
{
float* valuesPtr = (float*)_menu->m_value;
float col[4] = {0};
for (int i=0; i<4; ++i) col[i] = valuesPtr[i];
ImGui::ColorPicker4("", col, ImGuiColorEditFlags_PickerHueWheel);
for (int i=0; i<4; ++i) valuesPtr[i] = col[i];
}
static void rappPropertyPreview_Color(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
float* rgb = (float*)_menu->m_value;
ImU32 color = ImColor(ImVec4(rgb[0], rgb[1], rgb[2], rgb[3]));
float extent = _size.x < _size.y ? _size.x : _size.y;
ImVec2 rectPos(_minXY.x + (_size.x- extent)/2, _minXY.y + (_size.y- extent)/2);
ImVec2 rectSize(rectPos.x + extent, rectPos.y + extent);
_drawList->AddRectFilled(rectPos, rectSize, RAPP_COLOR_WIDGET_OUTLINE);
rectPos.x += RAPP_WIDGET_OUTLINE; rectPos.y += RAPP_WIDGET_OUTLINE;
rectSize.x -= RAPP_WIDGET_OUTLINE; rectSize.y -= RAPP_WIDGET_OUTLINE;
_drawList->AddRectFilled(rectPos, rectSize, color);
}
static Property::Edit rappPropertyTypeEditorDispath(DebugMenu* _menu, ImVec2 _minXY, ImVec2 _size)
{
ImGui::OpenPopup("##propEditor");
ImGui::SetNextWindowPos(_minXY);
ImGui::SetNextWindowSize(_size, ImGuiCond_Always);
if (ImGui::BeginPopup("##propEditor", ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoBackground))
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ImVec2 maxXY(_minXY.x+_size.x, _minXY.y+_size.y);
draw_list->AddRectFilled(_minXY, maxXY, RAPP_COLOR_WIDGET_OUTLINE);
_minXY = ImVec2(_minXY.x + RAPP_WIDGET_OUTLINE*3, _minXY.y + RAPP_WIDGET_OUTLINE*2);
maxXY = ImVec2(maxXY.x - (RAPP_WIDGET_OUTLINE*3), maxXY.y - (RAPP_WIDGET_OUTLINE*2));
draw_list->AddRectFilled(_minXY, maxXY, RAPP_COLOR_WIDGET);
ImGui::TextColored(ImColor(RAPP_COLOR_TEXT_TITLE), " %s", _menu->m_label);
ImGui::Separator();
ImGui::BeginChild("##propEditorInner",ImVec2(),false,ImGuiWindowFlags_NoScrollbar);
switch (_menu->m_type)
{
case Property::Int8:
case Property::Int16:
case Property::Int32:
case Property::Int64:
case Property::Uint8:
case Property::Uint16:
case Property::Uint32:
case Property::Uint64:
case Property::Float:
case Property::Double: rappPropertyTypeEditor_scalar(_menu, rappToImGuiScalarType(_menu->m_type)); break;
case Property::Bool: rappPropertyTypeEditor_Bool(_menu); break;
case Property::Color: rappPropertyTypeEditor_Color(_menu); break;
#if RAPP_DEBUG_WITH_STD_STRING
case Property::StdString:
#endif // RAPP_DEBUG_WITH_STD_STRING
case Property::Custom: _menu->m_customEditor(_menu); break;
default:
RTM_BREAK;
break;
};
ImGui::EndChild();
ImGui::EndPopup();
}
if (rapp::inputGetKeyState(rapp::KeyboardState::Key::Esc))
return Property::Cancel;
if (rapp::inputGetKeyState(rapp::KeyboardState::Key::Return) ||
rapp::inputGetKeyState(rapp::KeyboardState::Key::NumPad5))
return Property::Accept;
return Property::Editing;
}
static bool rappPropertyTypePreviewDispath(DebugMenu* _menu, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
if (!_menu)
return false;
if (_menu->m_parent && (_menu->m_parent->m_width > 1))
return false;
switch (_menu->m_type)
{
case Property::Int8:
case Property::Int16:
case Property::Int32:
case Property::Int64:
case Property::Uint8:
case Property::Uint16:
case Property::Uint32:
case Property::Uint64:
case Property::Float:
case Property::Double: rappPropertyPreview_scalar(_menu, _drawList, _minXY, _size, rappToImGuiScalarType(_menu->m_type)); return true;
case Property::Bool: rappPropertyPreview_Bool(_menu, _drawList, _minXY, _size); return true;
case Property::Color: rappPropertyPreview_Color(_menu, _drawList, _minXY, _size); return true;
#if RAPP_DEBUG_WITH_STD_STRING
case Property::StdString:
#endif // RAPP_DEBUG_WITH_STD_STRING
case Property::Custom: if (_menu->m_customPreview)
{
_menu->m_customPreview(_menu, _drawList, _minXY, _size);
return true;
}
else
return false;
default:
return false;
};
}
#if RAPP_DEBUG_WITH_STD_STRING
void stringSetDefaultFn(void* _var)
{
*(std::string*)_var = "";
}
void stringEditorFn(void* _var)
{
std::string* var = (std::string*)_var;
char tempString[4096];
strcpy(tempString, var->c_str());
ImGui::InputText("", tempString, 4096);
*var = tempString;
}
void stringPreviewFn(void* _var, ImDrawList* _drawList, ImVec2 _minXY, ImVec2 _size)
{
std::string* value = (std::string*)_var;
rapp::rappAddCentered_text(value->c_str(), _drawList, _minXY, _size);
}
#endif // RAPP_DEBUG_WITH_STD_STRING
static bool rappRoundedButton(DebugMenu* _menu, ImDrawList* _drawList, ImVec2& _position, ImVec2& _size, int _button, const char* _label, bool _editingValue)
{
static uint64_t s_lastHoverTime[9] = {0};
static uint64_t s_lastClickTime[9] = {0};
static bool s_hovered[9] = {false};
ImVec2 maxC(_position.x + _size.x, _position.y + _size.y);
_drawList->AddRectFilled(_position, maxC, RAPP_COLOR_WIDGET_OUTLINE, RAPP_WIDGET_OUTLINE * 3, ImDrawCornerFlags_All);
_position.x += RAPP_WIDGET_OUTLINE;
_position.y += RAPP_WIDGET_OUTLINE;
maxC.x -= RAPP_WIDGET_OUTLINE;
maxC.y -= RAPP_WIDGET_OUTLINE;
ImU32 drawColor = RAPP_COLOR_WIDGET;
ImVec2 mousePos(ImGui::GetIO().MousePos);
uint64_t currTime = rtm::CPU::clock();
bool hover = false;
if (ImGui::IsMouseHoveringRect(_position, ImVec2(maxC.x, maxC.y)))
{
if (!s_hovered[_button])
s_lastHoverTime[_button] = currTime;
if (!_editingValue)
flashColor(drawColor, RAPP_COLOR_WIDGET_BLINK, currTime - s_lastHoverTime[_button]);
hover = true;
}
if (hover && ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered())
s_lastClickTime[_button] = currTime;
if (s_hovered[_button] && (hover == false))
s_lastHoverTime[_button] = 0;
s_hovered[_button] = hover;
uint64_t deltaTime = currTime - s_lastClickTime[_button];
if (!_editingValue)
flashColor(drawColor, RAPP_COLOR_WIDGET_HIGHLIGHT, deltaTime);
_drawList->AddRectFilled(_position, maxC, drawColor, RAPP_WIDGET_OUTLINE * 3);
ImU32 numberColor = _button == 5 ? RAPP_COLOR_WIDGET : RAPP_COLOR_TEXT_STATUS;
if (!_editingValue)
flashColor(numberColor, _button == 5 ? RAPP_COLOR_TEXT_SHADOW : RAPP_COLOR_TEXT, deltaTime*2);
char FK[] = "0";
FK[0] = (char)('0' + _button);
static float fontSizeNumber = ImGui::GetFontSize() * 1.66f;
static float fontSizeLabel = ImGui::GetFontSize() * 1.11f;
ImVec2 text_size = ImGui::GetFont()->CalcTextSizeA(fontSizeNumber, FLT_MAX, 0.0f, FK);
ImVec2 center = ImVec2(_position.x + _size.x/2, _position.y + _size.y/ 2);
ImVec2 text_pos = ImVec2(center.x - text_size.x/2, center.y - text_size.y);
ImVec2 previewPosition(center.x - _size.x/2 + 6, center.y - _size.y/2 + 6);
ImVec2 previewSize(_size.x - 12, _size.y/2 - 12);
bool previewDrawn = rappPropertyTypePreviewDispath(_menu, _drawList, previewPosition, previewSize);
if (!previewDrawn)
_drawList->AddText(0, fontSizeNumber, text_pos, numberColor, FK);
text_size = ImGui::GetFont()->CalcTextSizeA(fontSizeLabel, FLT_MAX, 0.0f, _label);
text_pos = ImVec2(center.x - text_size.x/2, center.y+4);
drawColor = RAPP_COLOR_TEXT_HIGHLIGHT;
flashColor(drawColor, IM_COL32_WHITE, deltaTime);
if (!_editingValue)
_drawList->AddText(0, fontSizeLabel, text_pos, drawColor, _label);
return s_lastClickTime[_button] == currTime;
}
void rappDebugMenu()
{
rappDebugAddBindings();
DebugMenu* ret = g_currentDebugMenu;
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0,0,0,0));
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0,0,0,0));
ImVec2 screenRes = ImGui::GetIO().DisplaySize;
ImVec2 buttonSize = ImVec2(128.0f,128.0f);
screenRes.x -= (buttonSize.x + RAPP_WIDGET_SPACING) * 3;
screenRes.y -= (buttonSize.y + RAPP_WIDGET_SPACING) * 3;
ImGui::SetNextWindowPos(screenRes);
static uint32_t remapIndex[] = {5, 6, 5, 4, 7, 5, 3, 0, 1, 2 };
static uint32_t remapIndexChild[] = {7,8,9,6,3,2,1,4};
bool editingValue = ((g_currentDebugMenu->m_numChildren == 0) && (g_currentDebugMenu->m_type != Property::None) ||
(g_currentDebugMenu->m_width > 1));
static bool oldEditingValue = editingValue;
ImGui::SetNextWindowSize(ImVec2(buttonSize.x * 3 + RAPP_WIDGET_SPACING * 3,buttonSize.y * 3 + RAPP_WIDGET_SPACING * 3));
if (ImGui::Begin("##rappDebugMenu", 0, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize))
{
const ImVec2 drag_delta = ImVec2(ImGui::GetIO().MousePos.x - screenRes.x, ImGui::GetIO().MousePos.y - screenRes.y);
const float drag_dist2 = drag_delta.x*drag_delta.x + drag_delta.y*drag_delta.y;
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRectFullScreen();
uint32_t editIndex = 0xffffffff;
static bool oldPressed[9] = {false};
for (uint32_t x=0; x<3; ++x)
for (uint32_t y=0; y<3; ++y)
{
ImVec2 minC(screenRes.x + buttonSize.x * x + RAPP_WIDGET_SPACING * x, screenRes.y + buttonSize.y * y + RAPP_WIDGET_SPACING * y);
uint32_t displayIndex = 9 - (y*3 + (2-x));
uint32_t childIndex = remapIndex[displayIndex];
DebugMenu* child = g_currentDebugMenu->m_numChildren > childIndex ? g_currentDebugMenu->m_children[childIndex] : 0;
bool validButton = false;
const char* label = "";
if (childIndex < (int)g_currentDebugMenu->m_numChildren)
{
validButton = true;
label = child->m_label;
}
if ((displayIndex == 5) && (g_currentDebugMenu->m_parent))
label = g_currentDebugMenu->m_parent->m_label;
if (editingValue && (displayIndex != 5) && (g_currentDebugMenu->m_index == childIndex))
{
editIndex = childIndex;
label = g_currentDebugMenu->m_label;
}
bool keyPressed = rapp::inputGetKeyState(rapp::KeyboardState::Key(rapp::KeyboardState::Key::NumPad0 + displayIndex));
if (rappRoundedButton(child, draw_list, minC, buttonSize, displayIndex, label, editingValue) && !editingValue)
{
if ((5 == displayIndex) && g_currentDebugMenu->m_parent) // 5, go up a level
ret = g_currentDebugMenu->m_parent;
else
if (childIndex < (int)g_currentDebugMenu->m_numChildren)
ret = child;
}
keyPressed = oldPressed[displayIndex];
}
draw_list->PopClipRect();
ImGui::End();
static uint8_t origValue[DebugMenu::MAX_STORAGE_SIZE][DebugMenu::MAX_VARIABLES]; // for undo
static DebugMenu* editedMenu = 0;
static bool undoNeeded = false;
if (editingValue && (oldEditingValue != editingValue)) // started to edit
{
editedMenu = g_currentDebugMenu;
if (g_currentDebugMenu->m_width > 1)
{
for (uint32_t i=0; i<g_currentDebugMenu->m_width; ++i)
propertyCopyValue(g_currentDebugMenu->m_type, origValue[i], g_currentDebugMenu->m_children[i]->m_value);
}
else
propertyCopyValue(g_currentDebugMenu->m_type, origValue, g_currentDebugMenu->m_value);
}
if (!editingValue && (oldEditingValue != editingValue)) // finished edit
{
if (undoNeeded)
{
if (editedMenu->m_width > 1)
{
for (uint32_t i=0; i<editedMenu->m_width; ++i)
propertyCopyValue(editedMenu->m_type, editedMenu->m_children[i]->m_value, origValue[i]);
}
else
propertyCopyValue(editedMenu->m_type, editedMenu->m_value, origValue);
}
editedMenu = 0;
undoNeeded = false;
}
Property::Edit editRet = Property::Editing;
if (editingValue && g_currentDebugMenu->m_index == editIndex)
editRet = rappPropertyTypeEditorDispath(g_currentDebugMenu, ImVec2(screenRes.x + RAPP_WIDGET_SPACING * 2, screenRes.y + RAPP_WIDGET_SPACING * 2),
ImVec2(buttonSize.x * 3 - RAPP_WIDGET_SPACING * 2, buttonSize.y * 3 - RAPP_WIDGET_SPACING * 2));
if (editRet == Property::Cancel)
undoNeeded = true;
if (editRet != Property::Editing)
ret = g_currentDebugMenu->m_parent;
oldEditingValue = editingValue;
}
ImGui::PopStyleColor(2);
g_currentDebugMenu = ret;
}
} // namespace rapp
#endif // RAPP_WITH_BGFX
| 34.879104 | 158 | 0.690102 | milostosic |
2fe4a45196ef837f7e4d1c6f4969fd58ed6d0163 | 1,475 | hpp | C++ | include/ML/Editor/Editor_MainMenuBar.hpp | Gurman8r/ML | 171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1 | [
"MIT"
] | 3 | 2019-10-09T19:03:05.000Z | 2019-12-15T14:22:38.000Z | include/ML/Editor/Editor_MainMenuBar.hpp | Gurman8r/ML | 171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1 | [
"MIT"
] | null | null | null | include/ML/Editor/Editor_MainMenuBar.hpp | Gurman8r/ML | 171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1 | [
"MIT"
] | null | null | null | #ifndef _ML_EDITOR_MAIN_MENU_HPP_
#define _ML_EDITOR_MAIN_MENU_HPP_
#include <ML/Editor/Editor_Widget.hpp>
namespace ml
{
/* * * * * * * * * * * * * * * * * * * * */
class ML_EDITOR_API Editor_MainMenuBar final : public Editor_Widget
{
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
friend class Editor;
Editor_MainMenuBar();
~Editor_MainMenuBar() {}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void onEvent(Event const & value) override;
bool beginDraw(int32_t flags) override;
bool draw() override;
bool endDraw() override;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
std::vector<std::pair<
String,
std::vector<std::function<void()>>
>> m_menus;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public:
inline Editor_MainMenuBar & addMenu(String const & name, const std::function<void()> & fun)
{
auto it{ std::find_if(m_menus.begin(), m_menus.end(), [&](auto elem)
{
return (elem.first == name);
}) };
if (it == m_menus.end())
{
m_menus.push_back({ name, {} });
it = (m_menus.end() - 1);
}
if (fun)
{
it->second.push_back(fun);
}
return (*this);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
};
/* * * * * * * * * * * * * * * * * * * * */
}
#endif // !_ML_EDITOR_MAIN_MENU_HPP_ | 23.046875 | 93 | 0.423051 | Gurman8r |
2fea1e25f312515fa2c33c3731c88c9339d6d3ee | 5,442 | hh | C++ | AVR/drv_misc_WS2812.hh | artraze/lillib | 543f9c511b68c83e9c5c34d4446d20b59e730d8f | [
"MIT"
] | null | null | null | AVR/drv_misc_WS2812.hh | artraze/lillib | 543f9c511b68c83e9c5c34d4446d20b59e730d8f | [
"MIT"
] | null | null | null | AVR/drv_misc_WS2812.hh | artraze/lillib | 543f9c511b68c83e9c5c34d4446d20b59e730d8f | [
"MIT"
] | null | null | null | #pragma once
#include "board_cfg.h"
#ifdef DEV_WS2812
#include "device.h"
#if BOARD_CFG_FREQ == 16000000
template<uint8_t kIoi>
void WS2812_send(uint8_t n, uint8_t *grb)
{
// 0: 400ns( 6.4) high, 850ns(13.6) low
// 1: 800ns(12.8) high, 450ns( 7.2) low
// Note that writing a bit to the PIN register toggles the bit in the PORT register
// which only takes 1 cycle versus, e.g., SBI which is 2 cycles
constexpr uint8_t out_reg = (kIoi >> 4); // PIN reg for IOI
constexpr uint8_t out_pin = IOI_MASK(kIoi); // bits to toggle
uint8_t v, bit;
IOI_PORT_SET(kIoi, 0);
__asm__ volatile (
" cli \n" /* Disable interrupts! */ \
" ld %2, %a0+ \n" /* v = *grb++ */ \
" ldi %3, 0x08 \n" /* bit = 8 */ \
/* High side, bit: 0=400ns(6.4=7), 1=800ns(12.8=13) */ \
"1: nop \n" /* 1 */ \
" out %7, %6 \n" /* 1 PINC, toggle high */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" lsl %2 \n" /* 1 Shift MSB into carry */ \
" brcc 3f \n" /* 1/2 Skip the delay if bit was 0 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
"2: nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
/* Low side: 0=850ns(13.6=14), 1=450ns(7.2=7) */ \
"3: out %7, %6 \n" /* 1 OUT LOW */ \
" brcs 4f \n" /* 1/2 Skip the delay if bit was 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
" nop \n" /* 1 */ \
"4: dec %3 \n" /* 1 bit-- */ \
" brne 1b \n" /* 1/2 while(bit) */ \
" dec %1 \n" /* 1 n-- */ \
" breq 9f \n" /* 1 if (!n) break */ \
/* High side, byte: 0=400ns(6.4=7), 1=800ns(12.8=13) */ \
" out %7, %6 \n" /* 1 OUT HIGH */ \
" ld %2, %a0+ \n" /* 2 v = *grb++ (2 clocks? The docs would say 1, but maybe the post-inc?) */ \
" ldi %3, 0x08 \n" /* 1 bit = 8 */ \
" lsl %2 \n" /* 1 Shift MSB into carry */ \
" brcc 3b \n" /* 1/2 Jump to long-low if bit was 0 as byte setup took all the short-high clocks */ \
" rjmp 2b \n" /* 2 Jump into long-high delay to burn the remaining long-high clocks */ \
"9: sei \n" /* End, restore interrupts */
: "=e"(grb), "=r"(n), "=&r"(v), "=&d"(bit)
: "0"(grb), "1"(n), "r"(out_pin), "M"(out_reg)
);
}
#else
#error Unsupported CPU clock
#endif
#endif // DEV_WS2812
| 71.605263 | 113 | 0.212238 | artraze |
2fef4489639e885cd1ccf3ab83099f1155306d7e | 534 | cpp | C++ | luogu/p1507.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1507.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1507.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#define maxn 60
#define maxm 410
using namespace std;
int Vmax,Mmax;
int n;
int v[maxn],m[maxn],cal[maxn];
int dp[maxm][maxm];
int main()
{
scanf("%d %d",&Vmax,&Mmax);
scanf("%d",&n);
for(int i = 1; i <= n; ++i)
{
scanf("%d %d %d",&v[i],&m[i],&cal[i]);
}
for(int i = 1; i <= n; ++i)
{
for(int j = Mmax; j >= m[i]; --j)
{
for(int k = Vmax; k >= v[i]; --k)
{
dp[j][k] = max(dp[j][k],dp[j-m[i]][k-v[i]]+cal[i]);
}
}
}
printf("%d",dp[Mmax][Vmax]);
return 0;
}
| 14.432432 | 55 | 0.490637 | ajidow |
2ff11fc42c7206551433943312a819d138d29b8e | 1,351 | cpp | C++ | demo/future.cpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | 5 | 2020-04-24T17:34:54.000Z | 2021-04-07T15:56:00.000Z | demo/future.cpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | 5 | 2021-05-13T14:16:35.000Z | 2021-08-15T15:11:55.000Z | demo/future.cpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | 1 | 2021-05-09T12:17:30.000Z | 2021-05-09T12:17:30.000Z | #include <bats.hpp>
#include <iostream>
#define FT ModP<int, 3>
int main() {
bats::future::Matrix A(5,5, FT(1));
A(1,0) = 0;
A(2,1) = 2;
A(3,2) = 2;
A.print();
// auto H1 = HessenbergTransform(A);
// H1.print();
// H1.prod().print();
//
// std::cout << "hessenberg_to_companion" << std::endl;
//
// hessenberg_to_companion(H1);
// H1.print();
// H1.prod().print();
auto F = bats::future::LU(A);
F.print();
std::cout << "product:" << std::endl;
auto P = F.prod();
P.print();
size_t test[2] = {1,2};
std::cout << test[0] << test[1] << std::endl;
P = bats::future::Matrix<FT>(P, bats::future::ColumnMajor());
P.append_column();
P.print();
auto r = bats::future::range(0, 4);
std::vector<size_t> c = {0,2,3} ;
// auto view = MatrixView(P, r, c);
auto view = P.view(r,c);
// auto view = MatrixView(P, range(0, 4), range(0, 3));
view.print();
auto S = bats::future::Span(2, FT());
S.Pt.print();
S.L.print();
std::vector<FT> v = {1,1};
std::cout << S.add(v) << std::endl;
S.Pt.print();
S.L.print();
std::cout << S.add(v) << std::endl;
S.Pt.print();
S.L.print();
v = {1,0};
std::cout << S.add(v) << std::endl;
S.Pt.print();
S.L.print();
// std::cout << S.L.column(0)[1] << std::endl;
std::cout << S.contains(v) << std::endl;
v = {0,1};
std::cout << S.contains(v) << std::endl;
return 0;
}
| 17.776316 | 62 | 0.541821 | YuanL12 |
2ff9d7d478df79adce264170d405ea95bbfcf349 | 569 | cpp | C++ | messagebuilder.cpp | vcato/sockets | 61badc4c7b5eb010a213467954d4064baea43116 | [
"MIT"
] | null | null | null | messagebuilder.cpp | vcato/sockets | 61badc4c7b5eb010a213467954d4064baea43116 | [
"MIT"
] | null | null | null | messagebuilder.cpp | vcato/sockets | 61badc4c7b5eb010a213467954d4064baea43116 | [
"MIT"
] | null | null | null | #include "messagebuilder.hpp"
#include <iostream>
using std::cerr;
void
MessageBuilder::addChunk(
const char *chunk,
size_t chunk_size,
const MessageHandler& message_handler
)
{
size_t i=0;
while (i!=chunk_size) {
size_t begin = i;
while (i!=chunk_size && chunk[i]!='\0') {
++i;
}
message_so_far.append(chunk+begin,i-begin);
if (i==chunk_size) {
// Got a partial message_so_far
return;
}
assert(chunk[i]=='\0');
message_handler(message_so_far);
message_so_far.clear();
++i;
}
}
| 14.589744 | 47 | 0.602812 | vcato |
64001866965efbaa045fa902d576df34e221d8fd | 990 | cpp | C++ | LilEngie/Core/src/Entity/SceneManager.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | LilEngie/Core/src/Entity/SceneManager.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | LilEngie/Core/src/Entity/SceneManager.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | #include <vector>
#include <Graphics/Renderer.h>
#include <Entity/Components/Camera.h>
#include <Game/SceneLoader.h>
#include "GameObject.h"
#include "Scene.h"
#include "SceneManager.h"
//Properties
namespace SceneManager
{
//Private
Scene *scene;
}
void SceneManager::SetScene(Scene *s)
{
if (scene != nullptr)
scene->Close();
scene = s;
Start();
Renderer::SetScene(scene);
}
Scene* SceneManager::GetCurrent()
{
return scene;
}
void SceneManager::SetCurrentCamera(Camera *cam)
{
scene->SetCurrentCamera(cam);
}
void SceneManager::Start()
{
if (scene != nullptr)
scene->Start();
}
void SceneManager::Update()
{
if (scene != nullptr)
scene->Update();
}
bool SceneManager::CheckScene()
{
return scene != nullptr;
}
void SceneManager::UnloadScene(Scene **s)
{
(*s)->Unload();
*s = nullptr;
}
void SceneManager::LoadScene(const char *path, Scene **inScene, bool setCurrent)
{
SceneLoader::LoadScene(path, inScene, setCurrent);
}
void SceneManager::Close()
{
}
| 14.347826 | 80 | 0.694949 | Nordaj |
64028553177bfa199627de11285bd3d494d40879 | 1,218 | cpp | C++ | source/polyvec/curve-tracer/curve_constraints.cpp | dedoardo/polyfit | fea3bb9f28c2a44a55825529198e5c3796ac1fa6 | [
"MIT"
] | 27 | 2020-08-17T17:25:59.000Z | 2022-03-01T05:49:12.000Z | source/polyvec/curve-tracer/curve_constraints.cpp | dedoardo/polyfit | fea3bb9f28c2a44a55825529198e5c3796ac1fa6 | [
"MIT"
] | 4 | 2020-08-26T13:54:59.000Z | 2020-09-21T07:19:22.000Z | source/polyvec/curve-tracer/curve_constraints.cpp | dedoardo/polyfit | fea3bb9f28c2a44a55825529198e5c3796ac1fa6 | [
"MIT"
] | 5 | 2020-08-26T23:26:48.000Z | 2021-01-04T09:06:07.000Z | #include <polyvec/curve-tracer/curve_constraints.hpp>
using namespace polyvec;
GlobFitConstraint_LineDirection::GlobFitConstraint_LineDirection(GlobFitLineParametrization* line, GlobFitCurveParametrization::ParameterAddress& target)
: line(line)
{
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 0));
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 1));
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 2));
this->source_params.push_back(GlobFitCurveParametrization::ParameterAddress(line, 3));
this->target_param = target;
}
std::pair<double, Eigen::VectorXd> GlobFitConstraint_LineDirection::f()
{
Eigen::Vector2d diff = line->get_curve()->pos(1.0) - line->get_curve()->pos(0.0);
auto dDiffdParams = line->dposdparams(1.0) - line->dposdparams(0.0);
double angle = std::atan2(diff.y(), diff.x());
double xSq = diff.x() * diff.x();
double ySq = diff.y() * diff.y();
double denom = xSq + ySq;
Eigen::Vector2d dAngledDiff(-diff.y() / denom, diff.x() / denom);
Eigen::VectorXd dAngledParams = (dAngledDiff.transpose() * dDiffdParams).transpose();
return std::make_pair(angle, dAngledParams);
} | 39.290323 | 153 | 0.759442 | dedoardo |
64041b31db8531435f261be78200fa5609186602 | 263 | hpp | C++ | src/test/CatchFormatters.hpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | 39 | 2020-07-15T13:36:44.000Z | 2022-03-21T00:46:00.000Z | src/test/CatchFormatters.hpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | 255 | 2020-07-16T17:54:59.000Z | 2022-03-27T20:16:51.000Z | src/test/CatchFormatters.hpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | 11 | 2020-07-15T21:46:48.000Z | 2022-03-24T22:19:17.000Z | #pragma once
#include <catch2/catch.hpp>
#include <fmt/format.h>
template <typename T>
requires fmt::has_formatter<T, fmt::format_context>::value struct Catch::StringMaker<T> {
static std::string convert(const T &value) { return fmt::to_string(value); }
};
| 26.3 | 89 | 0.726236 | frederic-tingaud-sonarsource |
6405f83ca701f14127c5b3f8483e53625a63617b | 27,962 | cpp | C++ | preview/MsixCore/msixmgr/AutoPlay.cpp | rooju/msix-packaging | da46d3b5fbdca03ba4603531bb287d9def9203be | [
"MIT"
] | null | null | null | preview/MsixCore/msixmgr/AutoPlay.cpp | rooju/msix-packaging | da46d3b5fbdca03ba4603531bb287d9def9203be | [
"MIT"
] | null | null | null | preview/MsixCore/msixmgr/AutoPlay.cpp | rooju/msix-packaging | da46d3b5fbdca03ba4603531bb287d9def9203be | [
"MIT"
] | null | null | null | #include <windows.h>
#include <iostream>
#include <algorithm>
#include "RegistryKey.hpp"
#include "AutoPlay.hpp"
#include "../GeneralUtil.hpp"
#include <TraceLoggingProvider.h>
#include "../MsixTraceLoggingProvider.hpp"
#include "Constants.hpp"
#include "CryptoProvider.hpp"
#include "Base32Encoding.hpp"
#include <StrSafe.h>
using namespace MsixCoreLib;
const PCWSTR AutoPlay::HandlerName = L"AutoPlay";
HRESULT AutoPlay::ExecuteForAddRequest()
{
for (auto autoPlay = m_autoPlay.begin(); autoPlay != m_autoPlay.end(); ++autoPlay)
{
RETURN_IF_FAILED(ProcessAutoPlayForAdd(*autoPlay));
}
return S_OK;
}
HRESULT AutoPlay::ExecuteForRemoveRequest()
{
for (auto autoPlay = m_autoPlay.begin(); autoPlay != m_autoPlay.end(); ++autoPlay)
{
RETURN_IF_FAILED(ProcessAutoPlayForRemove(*autoPlay));
}
return S_OK;
}
HRESULT AutoPlay::ProcessAutoPlayForRemove(AutoPlayObject& autoPlayObject)
{
RegistryKey explorerKey;
RETURN_IF_FAILED(explorerKey.Open(HKEY_LOCAL_MACHINE, explorerRegKeyName.c_str(), KEY_READ | KEY_WRITE));
RegistryKey handlerRootKey;
HRESULT hrCreateSubKey = explorerKey.CreateSubKey(handlerKeyName.c_str(), KEY_READ | KEY_WRITE, &handlerRootKey);
if (SUCCEEDED(hrCreateSubKey))
{
const HRESULT hrDeleteSubKeyTree = handlerRootKey.DeleteTree(autoPlayObject.generatedhandlerName.c_str());
if (FAILED(hrDeleteSubKeyTree) && hrDeleteSubKeyTree != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay generatedHandlerName",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrDeleteSubKeyTree, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
}
}
else
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrCreateSubKey, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
}
if (autoPlayObject.autoPlayType == DesktopAppxContent)
{
RegistryKey classesRootKey;
HRESULT hrCreateSubKey = classesRootKey.Open(HKEY_LOCAL_MACHINE, classesKeyPath.c_str(), KEY_READ | KEY_WRITE | WRITE_DAC);
if (SUCCEEDED(hrCreateSubKey))
{
const HRESULT hrDeleteSubKeyTree = classesRootKey.DeleteTree(autoPlayObject.generatedProgId.c_str());
if (FAILED(hrDeleteSubKeyTree) && hrDeleteSubKeyTree != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay progId reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrDeleteSubKeyTree, "HR"),
TraceLoggingValue(autoPlayObject.generatedProgId.c_str(), "GeneratedProgId"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
}
}
}
RegistryKey handleEventRootKey;
hrCreateSubKey = explorerKey.CreateSubKey(eventHandlerRootRegKeyName.c_str(), KEY_READ | KEY_WRITE, &handleEventRootKey);
if (SUCCEEDED(hrCreateSubKey))
{
RegistryKey handleEventKey;
HRESULT hrCreateHandleSubKey = handleEventRootKey.CreateSubKey(autoPlayObject.handleEvent.c_str(), KEY_READ | KEY_WRITE, &handleEventKey);
if (SUCCEEDED(hrCreateHandleSubKey))
{
const HRESULT hrDeleteValue = handleEventKey.DeleteValue(autoPlayObject.generatedhandlerName.c_str());
if (FAILED(hrDeleteValue) && hrDeleteValue != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay handleEventKey generatedHandlerName reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrDeleteValue, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
return hrDeleteValue;
}
}
else
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrCreateHandleSubKey, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
return hrCreateHandleSubKey;
}
}
else
{
// Log failure of creating the handleEventRootKey
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to delete autoplay reg key",
TraceLoggingLevel(WINEVENT_LEVEL_WARNING),
TraceLoggingValue(hrCreateSubKey, "HR"),
TraceLoggingValue(autoPlayObject.generatedhandlerName.c_str(), "GeneratedHandlerName"),
TraceLoggingValue(m_msixRequest->GetPackageFullName(), "PackageFullName "));
return hrCreateSubKey;
}
return S_OK;
}
HRESULT AutoPlay::ParseManifest()
{
ComPtr<IMsixDocumentElement> domElement;
RETURN_IF_FAILED(m_msixRequest->GetPackageInfo()->GetManifestReader()->QueryInterface(UuidOfImpl<IMsixDocumentElement>::iid, reinterpret_cast<void**>(&domElement)));
ComPtr<IMsixElement> element;
RETURN_IF_FAILED(domElement->GetDocumentElement(&element));
ComPtr<IMsixElementEnumerator> extensionEnum;
RETURN_IF_FAILED(element->GetElements(extensionQuery.c_str(), &extensionEnum));
BOOL hasCurrent = FALSE;
RETURN_IF_FAILED(extensionEnum->GetHasCurrent(&hasCurrent));
while (hasCurrent)
{
ComPtr<IMsixElement> extensionElement;
RETURN_IF_FAILED(extensionEnum->GetCurrent(&extensionElement));
Text<wchar_t> extensionCategory;
RETURN_IF_FAILED(extensionElement->GetAttributeValue(categoryAttribute.c_str(), &extensionCategory));
if (wcscmp(extensionCategory.Get(), desktopAppXExtensionCategory.c_str()) == 0)
{
BOOL hc_invokeAction = FALSE;
ComPtr<IMsixElementEnumerator> invokeActionEnum;
RETURN_IF_FAILED(extensionElement->GetElements(invokeActionQuery.c_str(), &invokeActionEnum));
RETURN_IF_FAILED(invokeActionEnum->GetHasCurrent(&hc_invokeAction));
while (hc_invokeAction)
{
ComPtr<IMsixElement> invokeActionElement;
RETURN_IF_FAILED(invokeActionEnum->GetCurrent(&invokeActionElement));
//desktop appx content element
BOOL has_DesktopAppxContent = FALSE;
ComPtr<IMsixElementEnumerator> desktopAppxContentEnum;
RETURN_IF_FAILED(invokeActionElement->GetElements(invokeActionContentQuery.c_str(), &desktopAppxContentEnum));
RETURN_IF_FAILED(desktopAppxContentEnum->GetHasCurrent(&has_DesktopAppxContent));
while (has_DesktopAppxContent)
{
ComPtr<IMsixElement> desktopAppxContentElement;
RETURN_IF_FAILED(desktopAppxContentEnum->GetCurrent(&desktopAppxContentElement));
AutoPlayObject autoPlay;
//autoplay type
autoPlay.autoPlayType = DesktopAppxContent;
//action
Text<wchar_t> action;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(actionAttributeName.c_str(), &action));
autoPlay.action = action.Get();
//provider
Text<wchar_t> provider;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(providerAttributeName.c_str(), &provider));
autoPlay.provider = provider.Get();
// Get the App's app user model id
autoPlay.appUserModelId = m_msixRequest->GetPackageInfo()->GetId();
//get the logo
std::wstring logoPath = m_msixRequest->GetPackageInfo()->GetPackageDirectoryPath() + m_msixRequest->GetPackageInfo()->GetRelativeLogoPath();
std::wstring iconPath;
RETURN_IF_FAILED(ConvertLogoToIcon(logoPath, iconPath));
autoPlay.defaultIcon = iconPath.c_str();
//verb
Text<wchar_t> id;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(idAttributeName.c_str(), &id));
autoPlay.id = id.Get();
//content event
Text<wchar_t> handleEvent;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(contentEventAttributeName.c_str(), &handleEvent));
autoPlay.handleEvent = handleEvent.Get();
//drop target handler
Text<wchar_t> dropTargetHandler;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(dropTargetHandlerAttributeName.c_str(), &dropTargetHandler));
if (dropTargetHandler.Get() != nullptr)
{
autoPlay.dropTargetHandler = dropTargetHandler.Get();
}
//parameters
Text<wchar_t> parameters;
RETURN_IF_FAILED(desktopAppxContentElement->GetAttributeValue(parametersAttributeName.c_str(), ¶meters));
if (parameters.Get() != nullptr)
{
autoPlay.parameters = parameters.Get();
}
//GenerateProgId
std::wstring uniqueProgId;
uniqueProgId.append(id.Get());
uniqueProgId.append(handleEvent.Get());
std::wstring generatedProgId;
RETURN_IF_FAILED(GenerateProgId(desktopAppXExtensionCategory.c_str(), uniqueProgId.c_str(), generatedProgId));
autoPlay.generatedProgId = generatedProgId.c_str();
//GenerateHandlerName
std::wstring uniqueHandlerName;
uniqueHandlerName.append(id.Get());
uniqueHandlerName.append(handleEvent.Get());
std::wstring generatedHandlerName;
RETURN_IF_FAILED(GenerateHandlerName(L"DesktopAppXContent", uniqueHandlerName.c_str(), generatedHandlerName));
autoPlay.generatedhandlerName = generatedHandlerName.c_str();
m_autoPlay.push_back(autoPlay);
RETURN_IF_FAILED(desktopAppxContentEnum->MoveNext(&has_DesktopAppxContent));
}
//desktop appx device element
BOOL has_DesktopAppxDevice = FALSE;
ComPtr<IMsixElementEnumerator> desktopAppxDeviceEnum;
RETURN_IF_FAILED(invokeActionElement->GetElements(invokeActionDeviceQuery.c_str(), &desktopAppxDeviceEnum));
RETURN_IF_FAILED(desktopAppxDeviceEnum->GetHasCurrent(&has_DesktopAppxDevice));
while (has_DesktopAppxDevice)
{
ComPtr<IMsixElement> desktopAppxDeviceElement;
RETURN_IF_FAILED(desktopAppxDeviceEnum->GetCurrent(&desktopAppxDeviceElement));
AutoPlayObject autoPlay;
//autoplay type
autoPlay.autoPlayType = DesktopAppxDevice;
//action
Text<wchar_t> action;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(actionAttributeName.c_str(), &action));
autoPlay.action = action.Get();
//provider
Text<wchar_t> provider;
RETURN_IF_FAILED(invokeActionElement->GetAttributeValue(providerAttributeName.c_str(), &provider));
autoPlay.provider = provider.Get();
// Get the App's app user model id
autoPlay.appUserModelId = m_msixRequest->GetPackageInfo()->GetId();
//get the logo
std::wstring logoPath = m_msixRequest->GetPackageInfo()->GetPackageDirectoryPath() + m_msixRequest->GetPackageInfo()->GetRelativeLogoPath();
std::wstring iconPath;
RETURN_IF_FAILED(ConvertLogoToIcon(logoPath, iconPath));
autoPlay.defaultIcon = iconPath.c_str();
//handle event
Text<wchar_t> handleEvent;
RETURN_IF_FAILED(desktopAppxDeviceElement->GetAttributeValue(deviceEventAttributeName.c_str(), &handleEvent));
autoPlay.handleEvent = handleEvent.Get();
//hwEventHandler
Text<wchar_t> hwEventHandler;
RETURN_IF_FAILED(desktopAppxDeviceElement->GetAttributeValue(hwEventHandlerAttributeName.c_str(), &hwEventHandler));
autoPlay.hwEventHandler = hwEventHandler.Get();
//init cmd line
Text<wchar_t> initCmdLine;
RETURN_IF_FAILED(desktopAppxDeviceElement->GetAttributeValue(InitCmdLineAttributeName.c_str(), &initCmdLine));
if (initCmdLine.Get() != nullptr)
{
autoPlay.initCmdLine = initCmdLine.Get();
}
//GenerateHandlerName
std::wstring uniqueHandlerName;
uniqueHandlerName.append(handleEvent.Get());
std::wstring generatedHandlerName;
RETURN_IF_FAILED(GenerateHandlerName(L"DesktopAppXDevice", uniqueHandlerName.c_str(), generatedHandlerName));
autoPlay.generatedhandlerName = generatedHandlerName.c_str();
m_autoPlay.push_back(autoPlay);
RETURN_IF_FAILED(desktopAppxDeviceEnum->MoveNext(&has_DesktopAppxDevice));
}
RETURN_IF_FAILED(invokeActionEnum->MoveNext(&hc_invokeAction));
}
}
RETURN_IF_FAILED(extensionEnum->MoveNext(&hasCurrent));
}
return S_OK;
}
HRESULT AutoPlay::GenerateProgId(std::wstring categoryName, std::wstring subCategory, std::wstring & generatedProgId)
{
std::wstring packageFamilyName = m_msixRequest->GetPackageInfo()->GetPackageFamilyName();
std::wstring applicationId = m_msixRequest->GetPackageInfo()->GetApplicationId();
if (packageFamilyName.empty() || applicationId.empty() || categoryName.empty())
{
return E_INVALIDARG;
}
// Constants
std::wstring AppXPrefix = L"AppX";
static const size_t MaxProgIDLength = 39;
// The maximum number of characters we can have as base32 encoded is 32.
// We arrive at this due to the interface presented by the GetChars function;
// it is byte only. Ideally, the MaxBase32EncodedStringLength would be
// 35 [39 total for the progID, minus 4 for the prefix]. 35 characters means
// a maximum of 22 bytes in the digest [ceil(35*5/8)]. However, 22 bytes of digest
// actually encodes 36 characters [ceil(22/8*5)]. So we have to reduce the
// character count of the encoded string. At 33 characters, this translates into
// a 21 byte buffer. A 21 byte buffer translates into 34 characters. Although
// this meets the requirements, it is confusing since a 33 character limit
// results in a 34 character long encoding. In comparison, a 32 character long
// encoding divides evenly and always results in a 20 byte digest.
static const size_t MaxBase32EncodedStringLength = 32;
// The maximum number of bytes the digest can be is 20. We arrive at this by:
// - The maximum count of characters [without prefix] in the encoding (32):
// - multiplied by 5 (since each character in base 32 encoding is based off of 5 bits)
// - divided by 8 (to find how many bytes are required)
// - The initial plus 7 is to enable integer math (equivalent of writing ceil)
static const ULONG MaxByteCountOfDigest = (MaxBase32EncodedStringLength * 5 + 7) / 8;
// Build the progIdSeed by appending the incoming strings
// The package family name and the application ID are case sensitive
std::wstring tempProgIDBuilder;
tempProgIDBuilder.append(packageFamilyName);
std::transform(tempProgIDBuilder.begin(), tempProgIDBuilder.end(), tempProgIDBuilder.begin(), ::tolower);
tempProgIDBuilder.append(applicationId);
// The category name and the subcategory are not case sensitive
// so we should lower case them
std::wstring tempLowerBuffer;
tempLowerBuffer.assign(categoryName);
std::transform(tempLowerBuffer.begin(), tempLowerBuffer.end(), tempLowerBuffer.begin(), ::tolower);
tempProgIDBuilder.append(tempLowerBuffer);
if (!subCategory.empty())
{
tempLowerBuffer.assign(subCategory);
std::transform(tempLowerBuffer.begin(), tempLowerBuffer.end(), tempLowerBuffer.begin(), ::tolower);
tempProgIDBuilder.append(tempLowerBuffer);
}
// Create the crypto provider and start the digest / hash
AutoPtr<CryptoProvider> cryptoProvider;
RETURN_IF_FAILED(CryptoProvider::Create(&cryptoProvider));
RETURN_IF_FAILED(cryptoProvider->StartDigest());
COMMON_BYTES data = { 0 };
data.length = (ULONG)tempProgIDBuilder.size() * sizeof(WCHAR);
data.bytes = (LPBYTE)tempProgIDBuilder.c_str();
RETURN_IF_FAILED(cryptoProvider->DigestData(&data));
// Grab the crypto digest
COMMON_BYTES digest = { 0 };
RETURN_IF_FAILED(cryptoProvider->GetDigest(&digest));
// Ensure the string buffer has enough capacity
std::wstring base32EncodedDigest;
base32EncodedDigest.resize(MaxBase32EncodedStringLength);
// Base 32 encode the bytes of the digest and put them into the string buffer
ULONG base32EncodedDigestCharCount = 0;
RETURN_IF_FAILED(Base32Encoding::GetChars(
digest.bytes,
std::min(digest.length, MaxByteCountOfDigest),
MaxBase32EncodedStringLength,
base32EncodedDigest.data(),
&base32EncodedDigestCharCount));
// Set the length of the string buffer to the appropriate value
base32EncodedDigest.resize(base32EncodedDigestCharCount);
// ProgID name is formed by appending the encoded digest to the "AppX" prefix string
tempProgIDBuilder.clear();
tempProgIDBuilder.append(AppXPrefix);
tempProgIDBuilder.append(base32EncodedDigest.c_str());
// Set the return value
generatedProgId.assign(tempProgIDBuilder.c_str());
return S_OK;
}
HRESULT AutoPlay::GenerateHandlerName(LPWSTR type, const std::wstring handlerNameSeed, std::wstring & generatedHandlerName)
{
// Constants
static const ULONG HashedByteCount = 32; // SHA256 generates 256 hashed bits, which is 32 bytes
static const ULONG Base32EncodedLength = 52; // SHA256 generates 256 hashed bits, which is 52 characters after base 32 encoding (5 bits per character)
std::wstring packageFamilyName = m_msixRequest->GetPackageInfo()->GetPackageFamilyName();
std::wstring applicationId = m_msixRequest->GetPackageInfo()->GetApplicationId();
std::wstring handlerNameBuilder;
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
DWORD hashLength;
BYTE bytes[HashedByteCount];
ULONG base32EncodedDigestCharCount;
std::wstring base32EncodedDigest;
size_t typeLength;
// First, append Package family name and App Id to a std::wstring variable for convenience - lowercase the values so that the comparison
// in future versions or other code will be case insensitive
handlerNameBuilder.append(packageFamilyName);
handlerNameBuilder.append(applicationId);
std::transform(handlerNameBuilder.begin(), handlerNameBuilder.end(), handlerNameBuilder.begin(), ::tolower);
// Next, SHA256 hash the Package family name and Application Id
if (!CryptAcquireContext(&hProv, nullptr, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (!CryptHashData(hHash, (BYTE *)handlerNameBuilder.c_str(), (DWORD)handlerNameBuilder.size() * sizeof(wchar_t), 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
hashLength = HashedByteCount;
if (!CryptGetHashParam(hHash, HP_HASHVAL, bytes, &hashLength, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Ensure the string has enough capacity for the string and a null terminator
base32EncodedDigest.resize(Base32EncodedLength + 1);
// Base 32 encode the bytes of the digest and put them into the string buffer
RETURN_IF_FAILED(Base32Encoding::GetChars(
bytes,
HashedByteCount,
Base32EncodedLength,
base32EncodedDigest.data(),
&base32EncodedDigestCharCount));
// Set the length of the string to the appropriate value
base32EncodedDigest.resize(base32EncodedDigestCharCount);
// Find the length of the type string
RETURN_IF_FAILED(StringCchLength(type, STRSAFE_MAX_CCH, &typeLength));
// Finally, construct the string
handlerNameBuilder.clear();
handlerNameBuilder.append(base32EncodedDigest.c_str());
handlerNameBuilder.append(L"!", 1);
handlerNameBuilder.append(type, (ULONG)typeLength);
handlerNameBuilder.append(L"!", 1);
handlerNameBuilder.append(handlerNameSeed);
// Set the return value
generatedHandlerName.assign(handlerNameBuilder.c_str());
std::transform(generatedHandlerName.begin(), generatedHandlerName.end(), generatedHandlerName.begin(), ::tolower);
return S_OK;
}
HRESULT AutoPlay::ProcessAutoPlayForAdd(AutoPlayObject& autoPlayObject)
{
RegistryKey explorerKey;
RETURN_IF_FAILED(explorerKey.Open(HKEY_LOCAL_MACHINE, explorerRegKeyName.c_str(), KEY_READ | KEY_WRITE));
RegistryKey handlerRootKey;
RETURN_IF_FAILED(explorerKey.CreateSubKey(handlerKeyName.c_str(), KEY_WRITE, &handlerRootKey));
//generatedhandlername
RegistryKey handlerKey;
RETURN_IF_FAILED(handlerRootKey.CreateSubKey(autoPlayObject.generatedhandlerName.c_str(), KEY_WRITE, &handlerKey));
// Keys associated with all types
RETURN_IF_FAILED(handlerKey.SetStringValue(L"Action", autoPlayObject.action));
RETURN_IF_FAILED(handlerKey.SetStringValue(L"Provider", autoPlayObject.provider));
//Get the default icon
RETURN_IF_FAILED(handlerKey.SetStringValue(L"DefaultIcon", autoPlayObject.defaultIcon));
RegistryKey handleEventRootKey;
RETURN_IF_FAILED(explorerKey.CreateSubKey(eventHandlerRootRegKeyName.c_str(), KEY_WRITE, &handleEventRootKey));
RegistryKey handleEventKey;
RETURN_IF_FAILED(handleEventRootKey.CreateSubKey(autoPlayObject.handleEvent.c_str(), KEY_WRITE, &handleEventKey));
RETURN_IF_FAILED(handleEventKey.SetStringValue(autoPlayObject.generatedhandlerName.c_str(), L""));
RETURN_IF_FAILED(handlerKey.SetUInt32Value(L"DesktopAppX", 1));
if (autoPlayObject.autoPlayType == DesktopAppxContent)
{
RETURN_IF_FAILED(handlerKey.SetStringValue(L"InvokeProgID", autoPlayObject.generatedProgId));
RETURN_IF_FAILED(handlerKey.SetStringValue(L"InvokeVerb", autoPlayObject.id));
RegistryKey verbRootKey;
RETURN_IF_FAILED(BuildVerbKey(autoPlayObject.generatedProgId, autoPlayObject.id, verbRootKey));
if (autoPlayObject.dropTargetHandler.size() > 0)
{
RegistryKey dropTargetKey;
RETURN_IF_FAILED(verbRootKey.CreateSubKey(dropTargetRegKeyName.c_str(), KEY_WRITE, &dropTargetKey));
std::wstring regDropTargetHandlerBuilder;
regDropTargetHandlerBuilder.append(L"{");
regDropTargetHandlerBuilder.append(autoPlayObject.dropTargetHandler);
regDropTargetHandlerBuilder.append(L"}");
RETURN_IF_FAILED(dropTargetKey.SetStringValue(L"CLSID", regDropTargetHandlerBuilder));
}
else
{
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"AppUserModelID", autoPlayObject.appUserModelId));
std::wstring resolvedExecutableFullPath = m_msixRequest->GetPackageDirectoryPath() + L"\\" + m_msixRequest->GetPackageInfo()->GetRelativeExecutableFilePath();
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"PackageRelativeExecutable", resolvedExecutableFullPath));
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"Parameters", autoPlayObject.parameters));
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"ContractId", L"Windows.File"));
RETURN_IF_FAILED(verbRootKey.SetUInt32Value(L"DesiredInitialViewState", 0));
RETURN_IF_FAILED(verbRootKey.SetStringValue(L"PackageId", m_msixRequest->GetPackageFullName()));
RegistryKey commandKey;
RETURN_IF_FAILED(verbRootKey.CreateSubKey(commandKeyRegName.c_str(), KEY_WRITE, &commandKey));
RETURN_IF_FAILED(commandKey.SetStringValue(L"DelegateExecute", desktopAppXProtocolDelegateExecuteValue));
}
}
else if (autoPlayObject.autoPlayType == DesktopAppxDevice)
{
std::wstring regHWEventHandlerBuilder;
regHWEventHandlerBuilder.append(L"{");
regHWEventHandlerBuilder.append(autoPlayObject.hwEventHandler);
regHWEventHandlerBuilder.append(L"}");
RETURN_IF_FAILED(handlerKey.SetStringValue(L"CLSID", regHWEventHandlerBuilder));
RETURN_IF_FAILED(handlerKey.SetStringValue(L"InitCmdLine", autoPlayObject.initCmdLine));
}
return S_OK;
}
HRESULT AutoPlay::BuildVerbKey(std::wstring generatedProgId, std::wstring id, RegistryKey & verbRootKey)
{
RegistryKey classesRootKey;
RETURN_IF_FAILED(classesRootKey.Open(HKEY_LOCAL_MACHINE, classesKeyPath.c_str(), KEY_READ | KEY_WRITE | WRITE_DAC));
RegistryKey progIdRootKey;
RETURN_IF_FAILED(classesRootKey.CreateSubKey(generatedProgId.c_str(), KEY_READ | KEY_WRITE, &progIdRootKey));
RegistryKey shellRootKey;
RETURN_IF_FAILED(progIdRootKey.CreateSubKey(shellKeyName.c_str(), KEY_READ | KEY_WRITE, &shellRootKey));
RETURN_IF_FAILED(shellRootKey.CreateSubKey(id.c_str(), KEY_READ | KEY_WRITE, &verbRootKey));
return S_OK;
}
HRESULT AutoPlay::CreateHandler(MsixRequest * msixRequest, IPackageHandler ** instance)
{
std::unique_ptr<AutoPlay > localInstance(new AutoPlay(msixRequest));
if (localInstance == nullptr)
{
return E_OUTOFMEMORY;
}
RETURN_IF_FAILED(localInstance->ParseManifest());
*instance = localInstance.release();
return S_OK;
} | 44.954984 | 171 | 0.664008 | rooju |
6408a78f1f877309787a70b763eee146d1036e86 | 2,573 | cc | C++ | source/src/Ht1SAction.cc | hiteshvvr/XrayEfficiency | 50cccf940f1458e83e6d8e1605e5c96478cad4cf | [
"MIT"
] | null | null | null | source/src/Ht1SAction.cc | hiteshvvr/XrayEfficiency | 50cccf940f1458e83e6d8e1605e5c96478cad4cf | [
"MIT"
] | null | null | null | source/src/Ht1SAction.cc | hiteshvvr/XrayEfficiency | 50cccf940f1458e83e6d8e1605e5c96478cad4cf | [
"MIT"
] | null | null | null | //--------------------------------------------------------//
//----------STEPPING ACTION-------------------------------//
//--------------------------------------------------------//
#include "Ht1RAction.hh"
#include "Ht1SAction.hh"
#include "Ht1EAction.hh"
#include "Ht1DetectorConstruction.hh"
#include "Ht1Run.hh"
#include "HistoManager.hh"
#include <fstream>
#include "G4Step.hh"
#include "G4Event.hh"
#include "G4RunManager.hh"
#include "G4LogicalVolume.hh"
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
//#include "G4PhysicalConstants.hh"
//#include "G4Material.hh"
//#include "G4Element.hh"
using namespace std;
Ht1SAction::Ht1SAction(Ht1RAction* runaction, Ht1EAction* EAction )
: G4UserSteppingAction(),
hRAction(runaction),
fEventAction(EAction),
fScoringVolume(0)
{
}
Ht1SAction::~Ht1SAction()
{}
void Ht1SAction::UserSteppingAction(const G4Step* step)
{
if (!fScoringVolume)
{
const Ht1DetectorConstruction* DConstruction
= static_cast<const Ht1DetectorConstruction*>
(G4RunManager::GetRunManager()->GetUserDetectorConstruction());
fScoringVolume = DConstruction->GetScoringVolume();
}
G4LogicalVolume* volume
= step->GetPreStepPoint()->GetTouchableHandle()
->GetVolume()->GetLogicalVolume();
//Getting track
G4Track *track =step->GetTrack();
//G4double stepl = step->GetStepLength();
//G4double stepid = track->GetCurrentStepNumber();
//Getting particle definition
G4ParticleDefinition *fpParticleDefinition = track->GetDefinition();
int PDGEncoding = fpParticleDefinition->GetPDGEncoding();
//if(PDGEncoding == 11 ){
// G4double Kenergy = track->GetKineticEnergy();
// fEventAction->output<<stepl/meter<<G4endl;
// G4cout<<Kenergy/keV<<"\t"<<stepid<<"\t"<<stepl/meter<<G4endl;
//}
//Kinetic Energy of X-rays:
if(PDGEncoding == 22 )
{
if(step->GetPreStepPoint()->GetTouchableHandle()->GetVolume()->GetName()=="Env" && step->GetPostStepPoint()->GetTouchableHandle()->GetVolume()->GetName() == "detector")
{
G4double Kenergy = track->GetKineticEnergy();
G4AnalysisManager::Instance()->FillH1(5,Kenergy);
// fEventAction->output<<"Track \t" <<trackid<< "\t" << track->GetCreatorProcess()->GetProcessName()<<G4endl;
// fEventAction->output<<"Step \t" <<stepid<<"\t"<< step->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessName()<<G4endl;
//fEventAction-> output << Kenergy << /*"\t" << mat1 << "\t" << mat2 << "\t" <<*/ G4endl;
}
}
// IF ITS NOT SCORING VOLUME THEN EXIT
if (volume != fScoringVolume) return;
} //======================================================//
| 31 | 169 | 0.652546 | hiteshvvr |
640a5a98c08ee9e54c620c8b4a67b07b596360d5 | 592 | hpp | C++ | src/ir_2_llvm.hpp | Sokolmish/coursework_3 | 3ce0f70f90b7e79b99f212d03ccacf8b370d54f1 | [
"MIT"
] | null | null | null | src/ir_2_llvm.hpp | Sokolmish/coursework_3 | 3ce0f70f90b7e79b99f212d03ccacf8b370d54f1 | [
"MIT"
] | null | null | null | src/ir_2_llvm.hpp | Sokolmish/coursework_3 | 3ce0f70f90b7e79b99f212d03ccacf8b370d54f1 | [
"MIT"
] | null | null | null | #ifndef IR_2_LLVM_HPP_INCLUDED__
#define IR_2_LLVM_HPP_INCLUDED__
#include <memory>
#include "ir/unit.hpp"
class IR2LLVM {
public:
explicit IR2LLVM(IntermediateUnit const &iunit);
IR2LLVM(IR2LLVM const&) = delete;
IR2LLVM& operator=(IR2LLVM const&) = delete;
[[nodiscard]] std::string getRes() const;
~IR2LLVM(); // Needed for unique_ptr to incomplete type
class IR2LLVM_Impl;
private:
friend class IR2LLVM_Impl;
std::unique_ptr<IR2LLVM_Impl> impl;
IntermediateUnit const &iunit;
std::string llvmIR;
};
#endif /* IR_2_LLVM_HPP_INCLUDED__ */
| 19.096774 | 59 | 0.714527 | Sokolmish |
640bd5b0256ba44923bd2097a770d6cf1bac4799 | 806 | cpp | C++ | src/VFXSampleBaseViewer/VFXCommonScene.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | 3 | 2019-03-05T13:05:30.000Z | 2019-12-16T05:56:21.000Z | src/VFXSampleBaseViewer/VFXCommonScene.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | src/VFXSampleBaseViewer/VFXCommonScene.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | #include "VFXCommonScene.h"
#include "LevSceneData.h"
#include "LevSceneNode.h"
#include "LevSceneObject.h"
#include "LevSceneObjectDescription.h"
#include "LevNormalScene.h"
#include "LevNumericalUniform.h"
#include "LevRAttrUniformManager.h"
namespace Leviathan
{
namespace Viewer
{
VFXCommonScene::VFXCommonScene()
: LevNormalScene()
{
Init(ELST_3D_SCENE);
}
bool VFXCommonScene::AddLightToLightRootNode(LSPtr<Scene::LevLight> light)
{
const LSPtr<Scene::LevSceneNode> m_light_node = new Scene::LevSceneNode(TryCast<Scene::LevLight, Scene::LevSceneObject>(light));
return GetSceneData().AddSceneNodeToParent(m_light_node, GetLightRootNode());
}
bool VFXCommonScene::SetMainCamera(LSPtr<Scene::LevCamera> camera)
{
return GetSceneData().SetMainCamera(camera);
}
}
} | 26 | 131 | 0.761787 | wakare |
640e25a5443bb2adfc95b094ae08051b0c92beac | 2,160 | cpp | C++ | practice/Data structures/Graph/Euler Path.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 2 | 2019-01-30T12:45:18.000Z | 2021-05-06T19:02:51.000Z | practice/Data structures/Graph/Euler Path.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | null | null | null | practice/Data structures/Graph/Euler Path.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 3 | 2020-10-02T15:42:04.000Z | 2022-03-27T15:14:16.000Z | #include<bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(false);cin.tie(0)
#define pb push_back
#define digit(x) floor(log10(x))+1
#define mod 1000000007
#define endl "\n"
#define int long long
#define matrix vector<vector<int> >
#define vi vector<int>
#define pii pair<int,int>
#define vs vector<string>
#define vp vector<pii>
#define test() int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define debug(x) cerr << #x << " is " << x << endl;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int N = 100005;
void showArr(int *arr, int n){for(int i=0;i<n;i++) cout<<arr[i]<<" ";}
//=================================================================//
vector<int> gr[N];
int tin[N], tout[N];
int timer;
void euler_tour_1(int curr, int par) {
//after entering to the curr vertex
cout<<curr<<" ";
for(auto x : gr[curr]) {
if( x!= par) {
euler_tour_1(x, curr);
//when coming back again curr vertex from other vertex
cout<<curr<<" ";
}
}
return;
}
void euler_tour_2(int curr, int par) {
//after entering to the curr vertex
cout<<curr<<" ";
tin[curr] = timer++;
for(auto x : gr[curr]) {
if( x!= par) {
euler_tour_2(x, curr);
}
}
//after leaving curr vertex
tout[curr] = timer++;
cout<<curr<<" ";
return;
}
void euler_tour_3(int curr, int par) {
//after entering to the curr vertex
cout<<curr<<" ";
tin[curr] = ++timer;
for(auto x : gr[curr]) {
if( x!= par) {
euler_tour_3(x, curr);
}
}
tout[curr] = timer;
return;
}
// whether x is ancestor of y or not
bool is_ancestor(int x, int y) {
return tin[x]<=tin[y] && tout[x]>=tout[y];
}
void solve() {
int n,m;
cin>>n;
for(int i=0;i<n-1;i++) {
int x, y;
cin>>x>>y;
gr[x].push_back(y);
gr[y].push_back(x);
}
timer = 0;
// euler_tour_1(1,0);
// euler_tour_2(1,0);
euler_tour_3(1,0);
for(int i=1;i<=n;i++) {
cout<<i<<" "<<tin[i]<<" "<<tout[i]<<endl;
}
}
int32_t main(){
fast;
return 0;
} | 22.736842 | 70 | 0.522222 | vkashkumar |
640f9dbc3b4c998391f88f9691a65f12ade5ca26 | 3,066 | hpp | C++ | include/dataflow/blocks/impl/GeneratorBlock.hpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | include/dataflow/blocks/impl/GeneratorBlock.hpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | include/dataflow/blocks/impl/GeneratorBlock.hpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | #include <future>
#include <utility>
#include "../GeneratorBlock.h"
namespace dataflow::blocks {
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::GeneratorBlock(
OPERATOR& op,
ChannelBundle<T_OUT...> outputChannels,
OUTPUT_PREDICATE outputPredicate)
: op_(op)
, outputChannels_(std::move(outputChannels))
, outputPredicate_(outputPredicate)
, execute_(false)
{
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
void GeneratorBlock<
OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::execute()
{
std::tuple<T_OUT...> output = op_();
const auto outputPredicate = evalOutputPredicate(output, std::index_sequence_for<T_OUT...> {});
outputChannels_.push(std::move(output), outputPredicate);
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
bool GeneratorBlock<
OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::readyForExecution() const
{
return execute_ && (maxExecutions_ == inf or executions_ < maxExecutions_);
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
template <class REP, class PERIOD>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::executionLoop(
std::chrono::duration<REP, PERIOD> period,
std::chrono::duration<REP, PERIOD> offset,
size_t maxExecutions)
{
maxExecutions_ = maxExecutions;
std::this_thread::sleep_for(offset);
while (readyForExecution()) {
execute();
++executions_;
std::this_thread::sleep_for(period);
};
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
template <class REP, class PERIOD>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::start(
std::chrono::duration<REP, PERIOD> period,
std::chrono::duration<REP, PERIOD> offset,
size_t count)
{
execute_ = true;
auto execLoopAsyncWrapper = [&](auto period, auto offset, auto count) {
executionLoop(period, offset, count);
};
executionHandle_ = std::async(std::launch::async, execLoopAsyncWrapper, period, offset, count);
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::stop()
{
execute_ = false;
executionHandle_.wait();
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
void GeneratorBlock<OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::wait()
{
executionHandle_.wait();
execute_ = false;
}
template <typename OPERATOR, typename... T_OUT, typename OUTPUT_PREDICATE>
template <size_t... Is>
[[nodiscard]] std::array<bool, sizeof...(T_OUT)> GeneratorBlock<
OPERATOR, ChannelBundle<T_OUT...>, OUTPUT_PREDICATE>::evalOutputPredicate(const std::tuple<T_OUT...>& output,
std::index_sequence<Is...> /*unused*/) const
{
return outputPredicate_(std::get<Is>(output)...);
}
} // namespace dataflow::blocks
// ns
| 32.273684 | 113 | 0.722766 | Klirxel |
64110b5df90cb18944554afc169a8d4d9f33a89a | 1,714 | cpp | C++ | Chapter6-Graph/src/exercise1_zhangming/6-1-13.cpp | caoshenghui/DataStructures | b028bbdb3156537637eed87d634313820b0f295a | [
"MIT"
] | 4 | 2021-03-01T13:24:24.000Z | 2022-03-06T10:58:34.000Z | Chapter6-Graph/src/exercise1_zhangming/6-1-13.cpp | caoshenghui/DataStructures | b028bbdb3156537637eed87d634313820b0f295a | [
"MIT"
] | null | null | null | Chapter6-Graph/src/exercise1_zhangming/6-1-13.cpp | caoshenghui/DataStructures | b028bbdb3156537637eed87d634313820b0f295a | [
"MIT"
] | 1 | 2021-03-01T13:24:32.000Z | 2021-03-01T13:24:32.000Z | // File: 6-1-13.cpp
// Author: csh
// Date: 2020/12/26
// ===================
// 无向图
void Graph::Apart(){
int i, j;
for(i = 0; i < numVertex; i++)
Mark[i] = UNVISITED;
for(i = 0; i < numVertex; i++){
// 检查所有顶点是否被标记,从未标记顶点开始周游
if(Mark[i] == UNVISITED){
do_traverse(i, j);
j++;
}
}
}
void Graph::do_traverse(int v, int mark){
Mark[i] = VISITED;
value[v] = mark;
// 访问v邻接到的未被访问的结点,并递归地按照深度优先的方式进行周游
for(Edge e = FirstEdge(v); IsEdge(e); e = NextEdge(e)){
if(Mark[ToVertices(e)] == UNVISITED)
do_traverse(ToVertices(e), mark));
}
}
// 有向图
// 判断u,v是否连通
bool Graph::connected(int u, int v){
for(int i = 0; i < numVertex; i++)
Mark[i] = UNVISITED;
using std::queue;
queue<int> Q;
Q.push(u);
while(!Q.empty()){
int temp = Q.front();
Q.pop();
Mark[temp] = VISITED;
if(temp == v)
return true;
for(Edge e = FirstEdge; IsEdge(e); e = NextEdge(e)){
// 相邻的未访问的结点入队
if(Mark[ToVertex(e)] == UNVISITED)
Q.push(ToVertex(e));
}
}
return false;
}
void Graph::Apart(){
memset(value 0, numVertex * sizeof(int));
int mark = 0;
for(int i = 0; i < numVertex-1; i++){
if(value[i] > 0) // 结点i已经属于某个连通分量
continue;
mark++;
value[i] = mark;
for(int j = i+1; j < numVertex; j++){
if(value[j] > 0) // 结点j已经属于某个连通分量
continue;
if(connected(i, j)){
if(connected(j, i))
value[j] = mark;
}
}
}
}
| 22.25974 | 60 | 0.452742 | caoshenghui |
64139d8a85b21b523f3c202a4ac876b16c35fd4e | 581 | cpp | C++ | kody_projektowe/sieci_tymczasowe_propagacja/sieci_tymczasowe_propagacja/Connections.cpp | sirsz/Elpis | 7bb5e77deb98c6b9da5a7c98025d92de9f6e29c2 | [
"Unlicense"
] | null | null | null | kody_projektowe/sieci_tymczasowe_propagacja/sieci_tymczasowe_propagacja/Connections.cpp | sirsz/Elpis | 7bb5e77deb98c6b9da5a7c98025d92de9f6e29c2 | [
"Unlicense"
] | null | null | null | kody_projektowe/sieci_tymczasowe_propagacja/sieci_tymczasowe_propagacja/Connections.cpp | sirsz/Elpis | 7bb5e77deb98c6b9da5a7c98025d92de9f6e29c2 | [
"Unlicense"
] | null | null | null | #include "StdAfx.h"
#include "Connections.h"
CConnections::CConnections(void)
: NumberConnections(0)
, From(NULL)
, Target(NULL)
{
}
CConnections::~CConnections(void)
{
Destroy();
}
int CConnections::Create(int N)
{
Destroy();
if(N>0)
{
NumberConnections = N;
From = new int [N];
Target = new int [N];
}
for(int n=0; n<N; n++)
{
From[n] = -3;
Target[n] = -3;
}
return 0;
}
int CConnections::Destroy(void)
{
if(From) delete [] From;
From = NULL;
if(Target) delete [] Target;
Target = NULL;
return 0;
}
| 12.630435 | 34 | 0.566265 | sirsz |
641f0847696f11c80a80a947cad10885eabd3359 | 7,191 | cpp | C++ | driver/pwm/imxpwm/file.cpp | pjgorka88/imx-iotcore | c73879479ed026e607bf8ac111c836940a7aca00 | [
"MIT"
] | 68 | 2018-12-16T11:03:08.000Z | 2021-09-30T19:14:02.000Z | driver/pwm/imxpwm/file.cpp | pjgorka88/imx-iotcore | c73879479ed026e607bf8ac111c836940a7aca00 | [
"MIT"
] | 72 | 2018-12-18T01:13:18.000Z | 2019-11-08T02:13:07.000Z | driver/pwm/imxpwm/file.cpp | pjgorka88/imx-iotcore | c73879479ed026e607bf8ac111c836940a7aca00 | [
"MIT"
] | 43 | 2018-12-14T21:38:49.000Z | 2021-10-01T02:17:22.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// Module Name:
//
// file.cpp
//
// Abstract:
//
// This module contains methods implementation for the file object create/close
// callbacks.
//
// Environment:
//
// Kernel mode only
//
#include "precomp.h"
#pragma hdrstop
#include "imxpwmhw.hpp"
#include "imxpwm.hpp"
#include "trace.h"
#include "file.tmh"
IMXPWM_PAGED_SEGMENT_BEGIN; //==================================================
_Use_decl_annotations_
VOID
ImxPwmEvtDeviceFileCreate (
WDFDEVICE WdfDevice,
WDFREQUEST WdfRequest,
WDFFILEOBJECT WdfFileObject
)
{
PAGED_CODE();
IMXPWM_ASSERT_MAX_IRQL(PASSIVE_LEVEL);
UNICODE_STRING* filenamePtr = WdfFileObjectGetFileName(WdfFileObject);
IMXPWM_DEVICE_CONTEXT* deviceContextPtr = ImxPwmGetDeviceContext(WdfDevice);
NTSTATUS status;
ULONG pinNumber = ULONG_MAX;
//
// Parse and validate the filename associated with the file object.
//
bool isPinInterface;
if (filenamePtr == nullptr) {
WdfRequestComplete(WdfRequest, STATUS_INVALID_DEVICE_REQUEST);
return;
} else if (filenamePtr->Length > 0) {
//
// A non-empty filename means to open a pin under the controller namespace.
//
status = PwmParsePinPath(filenamePtr, &pinNumber);
if (!NT_SUCCESS(status)) {
WdfRequestComplete(WdfRequest, status);
return;
}
NT_ASSERT(deviceContextPtr->ControllerInfo.PinCount == 1);
if (pinNumber >= deviceContextPtr->ControllerInfo.PinCount) {
IMXPWM_LOG_INFORMATION(
"Requested pin number out of bounds. (pinNumber = %lu)",
pinNumber);
WdfRequestComplete(WdfRequest, STATUS_NO_SUCH_FILE);
return;
}
isPinInterface = true;
} else {
//
// An empty filename means that the create is against the root controller.
//
isPinInterface = false;
}
ACCESS_MASK desiredAccess;
ULONG shareAccess;
ImxPwmCreateRequestGetAccess(WdfRequest, &desiredAccess, &shareAccess);
//
// ShareAccess will not be honored as it has no meaning currently in the
// PWM DDI.
//
if (shareAccess != 0) {
IMXPWM_LOG_INFORMATION(
"Requested share access is not supported and request ShareAccess "
"parameter should be zero. Access denied. (shareAccess = %lu)",
shareAccess);
WdfRequestComplete(WdfRequest, STATUS_SHARING_VIOLATION);
return;
}
//
// Verify request desired access.
//
const bool hasWriteAccess = ((desiredAccess & FILE_WRITE_DATA) != 0);
if (isPinInterface) {
IMXPWM_PIN_STATE* pinPtr = &deviceContextPtr->Pin;
WdfWaitLockAcquire(pinPtr->Lock, NULL);
if (hasWriteAccess) {
if (pinPtr->IsOpenForWrite) {
WdfWaitLockRelease(pinPtr->Lock);
IMXPWM_LOG_ERROR("Pin access denied.");
WdfRequestComplete(WdfRequest, STATUS_SHARING_VIOLATION);
return;
}
pinPtr->IsOpenForWrite = true;
}
IMXPWM_LOG_INFORMATION(
"Pin Opened. (IsOpenForWrite = %!bool!)",
pinPtr->IsOpenForWrite);
WdfWaitLockRelease(pinPtr->Lock);
} else {
WdfWaitLockAcquire(deviceContextPtr->ControllerLock, NULL);
if (hasWriteAccess) {
if (deviceContextPtr->IsControllerOpenForWrite) {
WdfWaitLockRelease(deviceContextPtr->ControllerLock);
IMXPWM_LOG_ERROR("Controller access denied.");
WdfRequestComplete(WdfRequest, STATUS_SHARING_VIOLATION);
return;
}
deviceContextPtr->IsControllerOpenForWrite = true;
}
IMXPWM_LOG_INFORMATION(
"Controller Opened. (IsControllerOpenForWrite = %!bool!)",
deviceContextPtr->IsControllerOpenForWrite);
WdfWaitLockRelease(deviceContextPtr->ControllerLock);
}
//
// Allocate and fill a file object context.
//
IMXPWM_FILE_OBJECT_CONTEXT* fileObjectContextPtr;
{
WDF_OBJECT_ATTRIBUTES wdfObjectAttributes;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(
&wdfObjectAttributes,
IMXPWM_FILE_OBJECT_CONTEXT);
void* contextPtr;
status = WdfObjectAllocateContext(
WdfFileObject,
&wdfObjectAttributes,
&contextPtr);
if (!NT_SUCCESS(status)) {
IMXPWM_LOG_ERROR(
"WdfObjectAllocateContext(...) failed. (status = %!STATUS!)",
status);
WdfRequestComplete(WdfRequest, status);
return;
}
fileObjectContextPtr =
static_cast<IMXPWM_FILE_OBJECT_CONTEXT*>(contextPtr);
NT_ASSERT(fileObjectContextPtr != nullptr);
fileObjectContextPtr->IsPinInterface = isPinInterface;
fileObjectContextPtr->IsOpenForWrite = hasWriteAccess;
}
WdfRequestComplete(WdfRequest, STATUS_SUCCESS);
}
_Use_decl_annotations_
VOID
ImxPwmEvtFileClose (
WDFFILEOBJECT WdfFileObject
)
{
PAGED_CODE();
IMXPWM_ASSERT_MAX_IRQL(PASSIVE_LEVEL);
WDFDEVICE wdfDevice = WdfFileObjectGetDevice(WdfFileObject);
IMXPWM_DEVICE_CONTEXT* deviceContextPtr = ImxPwmGetDeviceContext(wdfDevice);
IMXPWM_FILE_OBJECT_CONTEXT* fileObjectContextPtr = ImxPwmGetFileObjectContext(WdfFileObject);
if (fileObjectContextPtr->IsPinInterface) {
WdfWaitLockAcquire(deviceContextPtr->Pin.Lock, NULL);
if (fileObjectContextPtr->IsOpenForWrite) {
NTSTATUS status = ImxPwmResetPinDefaults(deviceContextPtr);
if (!NT_SUCCESS(status)) {
IMXPWM_LOG_ERROR(
"ImxPwmResetPinDefaults(...) failed. (status = %!STATUS!)",
status);
}
NT_ASSERT(deviceContextPtr->Pin.IsOpenForWrite);
deviceContextPtr->Pin.IsOpenForWrite = false;
}
IMXPWM_LOG_TRACE(
"Pin Closed. (IsOpenForWrite = %lu)",
(deviceContextPtr->Pin.IsOpenForWrite ? 1 : 0));
WdfWaitLockRelease(deviceContextPtr->Pin.Lock);
} else {
WdfWaitLockAcquire(deviceContextPtr->ControllerLock, NULL);
if (fileObjectContextPtr->IsOpenForWrite) {
NTSTATUS status = ImxPwmResetControllerDefaults(deviceContextPtr);
if (!NT_SUCCESS(status)) {
IMXPWM_LOG_ERROR(
"ImxPwmResetControllerDefaults(...) failed. (status = %!STATUS!)",
status);
}
NT_ASSERT(deviceContextPtr->IsControllerOpenForWrite);
deviceContextPtr->IsControllerOpenForWrite = false;
}
IMXPWM_LOG_TRACE(
"Controller Closed. (IsControllerOpenForWrite = %lu)",
(deviceContextPtr->IsControllerOpenForWrite ? 1 : 0));
WdfWaitLockRelease(deviceContextPtr->ControllerLock);
}
}
IMXPWM_PAGED_SEGMENT_END; //=================================================== | 30.470339 | 97 | 0.624531 | pjgorka88 |
6420821e1c120f18bc426ff2449745f8b9088127 | 10,826 | hpp | C++ | softlight/include/softlight/SL_BoundingBox.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 27 | 2019-04-22T01:51:51.000Z | 2022-02-11T06:12:17.000Z | softlight/include/softlight/SL_BoundingBox.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 1 | 2021-11-12T05:19:52.000Z | 2021-11-12T05:19:52.000Z | softlight/include/softlight/SL_BoundingBox.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 2 | 2020-09-07T03:04:39.000Z | 2021-11-09T06:08:37.000Z |
#ifndef SL_BOUNDING_BOX_HPP
#define SL_BOUNDING_BOX_HPP
#include "lightsky/math/vec3.h"
#include "lightsky/math/vec4.h"
#include "lightsky/math/vec_utils.h"
#include "lightsky/math/mat4.h"
/**
* @brief Bounding Box Class
*/
class SL_BoundingBox
{
private:
ls::math::vec4 mMaxPoint;
ls::math::vec4 mMinPoint;
public:
/**
* @brief Destructor
*
* Defaulted
*/
~SL_BoundingBox() noexcept = default;
/**
* @brief Constructor
*/
SL_BoundingBox() noexcept;
/**
* @brief Copy Constructor
*
* Copies data from another bounding box.
*
* @param bb
* A constant reference to a fully constructed bounding box
* object.
*/
SL_BoundingBox(const SL_BoundingBox& bb) noexcept;
/**
* @brief Move Constructor
*
* Copies data from another bounding box (no moves are performed).
*
* @param An r-value reference to a fully constructed bounding box
*/
SL_BoundingBox(SL_BoundingBox&&) noexcept;
/**
* @brief Copy Operator
*
* Copies data from another bounding box.
*
* @param A constant reference to a fully constructed bounding box
* object.
*
* @return A reference to *this.
*/
SL_BoundingBox& operator=(const SL_BoundingBox&) noexcept;
/**
* @brief Move Operator
*
* @param An R-Value reference to a bounding box that is about to go
* out of scope.
*
* @return A reference to *this.
*/
SL_BoundingBox& operator=(SL_BoundingBox&&) noexcept;
/**
* @brief Check if a point is within this box.
*
* @param A constant reference to a vec3 object.
*
* @return TRUE if the point is within *this, or FALSE if otherwise.
*/
bool is_in_box(const ls::math::vec3&) const noexcept;
/**
* @brief Check if a point is within this box.
*
* @param A constant reference to a vec4 object.
*
* @return TRUE if the point is within *this, or FALSE if otherwise.
*/
bool is_in_box(const ls::math::vec4&) const noexcept;
/**
* Check if a portion of another bounding box is within *this.
*
* @param A constant reference to another bounding box.
*
* @return TRUE if a portion of the bounding box is within *this, or
* FALSE if it isn't.
*/
bool is_in_box(const SL_BoundingBox&) const noexcept;
/**
* Set the maximum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the maximum
* ponit of this bounding box.
*/
void max_point(const ls::math::vec3& v) noexcept;
/**
* Set the tmaximum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the maximum
* point of this bounding box.
*/
void max_point(const ls::math::vec4& v) noexcept;
/**
* Get the maximum extent of this bounding box.
*
* @return A constant reference to the maximum point of this bounding box.
*/
const ls::math::vec4& max_point() const noexcept;
/**
* Get the maximum extent of this bounding box.
*
* @param m
* A model matrix which can be used to return a pre-translated maximum
* point.
*
* @return The max point of this bounding box with regards to a
* transformation.
*/
ls::math::vec4 max_point(const ls::math::mat4& m) const noexcept;
/**
* Set the minimum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the min
* point of this bounding box.
*/
void min_point(const ls::math::vec3& v) noexcept;
/**
* Set the minimum extent of this bounding box.
*
* @param A constant reference to a point that will be used as the min
* point of this bounding box.
*/
void min_point(const ls::math::vec4& v) noexcept;
/**
* Get the minimum extent of this bounding box.
*
* @return A constant reference to the min point of this bounding box.
*/
const ls::math::vec4& min_point() const noexcept;
/**
* Get the minimum extent of this bounding box.
*
* @param m
* A model matrix which can be used to return a pre-translated minimum
* point.
*
* @return The min point of this bounding box with regards to a
* transformation.
*/
ls::math::vec4 min_point(const ls::math::mat4& m) const noexcept;
/**
* Reset the bounds of this bounding box to their default values.
*/
void reset_size() noexcept;
/**
* Compare a point to the current set of vertices.
* If any of the components within the parameter are larger than the
* components of this box, the current set of points will be enlarged.
*
* @param point
* A point who's individual components should be used to update the
* size of this bounding box.
*/
void compare_and_update(const ls::math::vec3& point) noexcept;
/**
* Compare a point to the current set of vertices.
* If any of the components within the parameter are larger than the
* components of this box, the current set of points will be enlarged.
*
* @param point
* A point who's individual components should be used to update the
* size of this bounding box.
*/
void compare_and_update(const ls::math::vec4& point) noexcept;
};
/*-------------------------------------
Constructor
-------------------------------------*/
inline SL_BoundingBox::SL_BoundingBox() noexcept :
mMaxPoint{1.f, 1.f, 1.f, 1.f},
mMinPoint{-1.f, -1.f, -1.f, 1.f}
{}
/*-------------------------------------
Copy Constructor
-------------------------------------*/
inline SL_BoundingBox::SL_BoundingBox(const SL_BoundingBox& bb) noexcept :
mMaxPoint{bb.mMaxPoint},
mMinPoint{bb.mMinPoint}
{}
/*-------------------------------------
Move Constructor
-------------------------------------*/
inline SL_BoundingBox::SL_BoundingBox(SL_BoundingBox&& bb) noexcept :
mMaxPoint{std::move(bb.mMaxPoint)},
mMinPoint{std::move(bb.mMinPoint)}
{
bb.reset_size();
}
/*-------------------------------------
Copy Operator
-------------------------------------*/
inline SL_BoundingBox& SL_BoundingBox::operator=(const SL_BoundingBox& bb) noexcept
{
mMaxPoint = bb.mMaxPoint;
mMinPoint = bb.mMinPoint;
return *this;
}
/*-------------------------------------
Move Operator
-------------------------------------*/
inline SL_BoundingBox& SL_BoundingBox::operator=(SL_BoundingBox&& bb) noexcept
{
mMaxPoint = std::move(bb.mMaxPoint);
mMinPoint = std::move(bb.mMinPoint);
bb.reset_size();
return *this;
}
/*-------------------------------------
Check if a portion of another bounding box is within *this.
-------------------------------------*/
inline bool SL_BoundingBox::is_in_box(const ls::math::vec3& v) const noexcept
{
return
v[0] < mMaxPoint[0] && v[1] < mMaxPoint[1] && v[2] < mMaxPoint[2]
&&
v[0] >= mMinPoint[0] && v[1] >= mMinPoint[1] && v[2] >= mMinPoint[2];
}
/*-------------------------------------
Check if a portion of another bounding box is within *this.
-------------------------------------*/
inline bool SL_BoundingBox::is_in_box(const ls::math::vec4& v) const noexcept
{
return v < mMaxPoint && v >= mMinPoint;
}
/*-------------------------------------
Check if a point is within this box.
-------------------------------------*/
inline bool SL_BoundingBox::is_in_box(const SL_BoundingBox& bb) const noexcept
{
return is_in_box(bb.mMaxPoint) || is_in_box(bb.mMinPoint);
}
/*-------------------------------------
Set the max point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::max_point(const ls::math::vec3& v) noexcept
{
mMaxPoint = ls::math::vec4{v[0], v[1], v[2], 1.f};
}
/*-------------------------------------
Set the max point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::max_point(const ls::math::vec4& v) noexcept
{
mMaxPoint = v;
}
/*-------------------------------------
Get the max point of this bounding box.
-------------------------------------*/
inline ls::math::vec4 SL_BoundingBox::max_point(const ls::math::mat4& m) const noexcept
{
const ls::math::vec4& extMax = m * mMaxPoint;
const ls::math::vec4& extMin = m * mMinPoint;
return ls::math::max(extMax, extMin);
}
/*-------------------------------------
Get the max point of this bounding box.
-------------------------------------*/
inline const ls::math::vec4& SL_BoundingBox::max_point() const noexcept
{
return mMaxPoint;
}
/*-------------------------------------
Set the min point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::min_point(const ls::math::vec3& v) noexcept
{
mMinPoint = ls::math::vec4{v[0], v[1], v[2], 1.f};
}
/*-------------------------------------
Set the min point of this bounding box.
-------------------------------------*/
inline void SL_BoundingBox::min_point(const ls::math::vec4& v) noexcept
{
mMinPoint = v;
}
/*-------------------------------------
Get the min point of this bounding box.
-------------------------------------*/
inline const ls::math::vec4& SL_BoundingBox::min_point() const noexcept
{
return mMinPoint;
}
/*-------------------------------------
Get the min point of this bounding box.
-------------------------------------*/
inline ls::math::vec4 SL_BoundingBox::min_point(const ls::math::mat4& m) const noexcept
{
const ls::math::vec4& extMax = m * mMaxPoint;
const ls::math::vec4& extMin = m * mMinPoint;
return ls::math::min(extMax, extMin);
}
/*-------------------------------------
Reset the bounds of this bounding box to their default values.
-------------------------------------*/
inline void SL_BoundingBox::reset_size() noexcept
{
max_point(ls::math::vec4{1.f, 1.f, 1.f, 1.f});
min_point(ls::math::vec4{-1.f, -1.f, -1.f, 1.f});
}
/*-------------------------------------
Compare a point to the current set of vertices.
-------------------------------------*/
inline void SL_BoundingBox::compare_and_update(const ls::math::vec3& point) noexcept
{
compare_and_update(ls::math::vec4{point[0], point[1], point[2], 1.f});
}
/*-------------------------------------
Compare a point to the current set of vertices.
-------------------------------------*/
inline void SL_BoundingBox::compare_and_update(const ls::math::vec4& point) noexcept
{
mMaxPoint = ls::math::max(mMaxPoint, point);
mMinPoint = ls::math::min(mMinPoint, point);
}
#endif /* SL_BOUNDING_BOX_HPP */
| 26.086747 | 87 | 0.554776 | Kim-Du-Yeon |
64225a6536c7393dd05f0a83d328c12af8b3fda5 | 459 | cpp | C++ | level1 pro/p01.cpp | Randle-Github/c2021 | f08649b34b2db1fa548c187386e787acdd00de71 | [
"MIT"
] | null | null | null | level1 pro/p01.cpp | Randle-Github/c2021 | f08649b34b2db1fa548c187386e787acdd00de71 | [
"MIT"
] | null | null | null | level1 pro/p01.cpp | Randle-Github/c2021 | f08649b34b2db1fa548c187386e787acdd00de71 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include<cstring>
#include<windows.h>
using namespace std;
int main()
{
string s="x";
while(true){
for(int i=1;i<=30;i++){
cout<<s;
Sleep(100);
system("cls");
string k=" ";
s=k.append(s);
}
for(int i=1;i<=30;i++){
s.erase(s.begin());
cout<<s;
Sleep(100);
system("cls");
}
}
return 0;
} | 19.125 | 31 | 0.411765 | Randle-Github |
642c4a580020b110e07d7ed3938e43c59fbb95af | 2,420 | cpp | C++ | source/Library.Shared/Utility.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | 12 | 2019-08-18T19:28:55.000Z | 2022-03-29T12:55:20.000Z | str/wstring_convert/varcholik/Utility.cpp | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | null | null | null | str/wstring_convert/varcholik/Utility.cpp | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Utility.h"
using namespace std;
namespace Library
{
void Utility::GetFileName(const string& inputPath, string& filename)
{
string fullPath(inputPath);
replace(fullPath.begin(), fullPath.end(), '\\', '/');
string::size_type lastSlashIndex = fullPath.find_last_of('/');
if (lastSlashIndex == string::npos)
{
filename = fullPath;
}
else
{
filename = fullPath.substr(lastSlashIndex + 1, fullPath.size() - lastSlashIndex - 1);
}
}
void Utility::GetDirectory(const string& inputPath, string& directory)
{
string fullPath(inputPath);
replace(fullPath.begin(), fullPath.end(), '\\', '/');
string::size_type lastSlashIndex = fullPath.find_last_of('/');
if (lastSlashIndex == string::npos)
{
directory = "";
}
else
{
directory = fullPath.substr(0, lastSlashIndex);
}
}
tuple<string, string> Utility::GetFileNameAndDirectory(const string& inputPath)
{
string fullPath(inputPath);
replace(fullPath.begin(), fullPath.end(), '\\', '/');
string::size_type lastSlashIndex = fullPath.find_last_of('/');
string directory;
string filename;
if (lastSlashIndex == string::npos)
{
directory = "";
filename = fullPath;
}
else
{
directory = fullPath.substr(0, lastSlashIndex);
filename = fullPath.substr(lastSlashIndex + 1, fullPath.size() - lastSlashIndex - 1);
}
return make_tuple(filename, directory);
}
void Utility::LoadBinaryFile(const wstring& filename, vector<char>& data)
{
ifstream file(filename.c_str(), ios::binary);
if (!file.good())
{
throw exception("Could not open file.");
}
file.seekg(0, ios::end);
uint32_t size = (uint32_t)file.tellg();
if (size > 0)
{
data.resize(size);
file.seekg(0, ios::beg);
file.read(&data.front(), size);
}
file.close();
}
#pragma warning(push)
#pragma warning(disable: 4996)
void Utility::ToWideString(const string& source, wstring& dest)
{
dest = wstring_convert<codecvt_utf8<wchar_t>>().from_bytes(source);
}
wstring Utility::ToWideString(const string& source)
{
return wstring_convert<codecvt_utf8<wchar_t>>().from_bytes(source);
}
void Utility::Totring(const wstring& source, string& dest)
{
dest = wstring_convert<codecvt_utf8<wchar_t>>().to_bytes(source);
}
string Utility::ToString(const wstring& source)
{
return wstring_convert<codecvt_utf8<wchar_t>>().to_bytes(source);
}
#pragma warning(pop)
} | 22.201835 | 88 | 0.682645 | ssshammi |
643470cae896de052f1a6d5c1a9c45654b24b8bb | 1,162 | hpp | C++ | bat/msvc/private/test/cmdbit/msvc2019/tools/find_in.hpp | Kartonagnick/bat_engine-windows | 455e4a40c6df16520d5695a75752013b41340a83 | [
"MIT"
] | null | null | null | bat/msvc/private/test/cmdbit/msvc2019/tools/find_in.hpp | Kartonagnick/bat_engine-windows | 455e4a40c6df16520d5695a75752013b41340a83 | [
"MIT"
] | 22 | 2020-12-28T04:36:24.000Z | 2021-01-05T04:49:29.000Z | bat/msvc/private/test/garbage/msvc2019/tools/find_in.hpp | Kartonagnick/bat_engine-windows | 455e4a40c6df16520d5695a75752013b41340a83 | [
"MIT"
] | null | null | null |
#pragma once
#ifndef dFSYSTEM_FIND_IN_USED_
#define dFSYSTEM_FIND_IN_USED_ 1
#include <functional>
#include <string>
#include <list>
//==============================================================================
//==============================================================================
namespace fsystem
{
using str_t = ::std::string;
using list_t = ::std::list<str_t>;
// --- const bool is_directory
// --- const ::std::string& path
// --- const size_t depth
using call_t = ::std::function<
bool(const bool, const ::std::string&, const size_t)
>;
struct settings
{
list_t scan_include ;
list_t scan_exclude ;
list_t dirs_include ;
list_t dirs_exclude ;
list_t files_include ;
list_t files_exclude ;
};
void find_in(
const str_t& start,
const settings& params,
const call_t& call
);
} // namespace fsystem
//==============================================================================
//==============================================================================
#endif // !dFSYSTEM_FIND_IN_USED_
| 24.208333 | 80 | 0.437177 | Kartonagnick |
6435dedcd2519942859f49e672df56718525674f | 103 | cpp | C++ | pctg_complex.cpp | julky117/Prota | a9ff73e4db3de4577b5d93cdbf7785a5451a197b | [
"MIT"
] | null | null | null | pctg_complex.cpp | julky117/Prota | a9ff73e4db3de4577b5d93cdbf7785a5451a197b | [
"MIT"
] | null | null | null | pctg_complex.cpp | julky117/Prota | a9ff73e4db3de4577b5d93cdbf7785a5451a197b | [
"MIT"
] | null | null | null | #include "pctg_complex.h"
pctg_complex_t::pctg_complex_t(const int position) : position(position) {} | 34.333333 | 74 | 0.776699 | julky117 |
64371860c2204810ff38d9c47e07233a2c755006 | 1,599 | cpp | C++ | pronto/core/components/point_light.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/components/point_light.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/components/point_light.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | #include "point_light.h"
#include "platform/resource.h"
#include "core/entity.h"
#include "core/world.h"
#include "core/application.h"
#include "platform/renderer.h"
namespace pronto
{
PointLight::PointLight(Entity* ent) :
Component(ent),
attenuation_(100.f),
color_(glm::vec3(1, 1, 1)),
intensity_(5000.f)
{
entity_->world()->application()->renderer()->RegisterPointLight(this);
}
PointLight::~PointLight()
{
entity_->world()->application()->renderer()->UnRegisterPointLight(this);
}
void PointLight::Update()
{
}
void PointLight::set_attenuation(const float attenuation)
{
attenuation_ = attenuation;
}
void PointLight::set_color(const glm::vec3& color)
{
color_ = color;
}
void PointLight::set_intensity(const float intensity)
{
intensity_ = intensity;
}
float PointLight::attenuation()
{
return attenuation_;
}
const glm::vec3& PointLight::color()
{
return color_;
}
float PointLight::intensity()
{
return intensity_;
}
PointLightBuffer PointLight::CreateStruct()
{
return PointLightBuffer(
glm::vec4(entity_->transform()->position(), 1),
glm::vec4(1, 1, 1, 1),
glm::vec4(color_, 1),
attenuation_,
intensity_);
}
PointLightBuffer::PointLightBuffer(
const glm::vec4& world_pos,
const glm::vec4& view_pos,
const glm::vec4& color,
const float attenuation,
const float intensity) :
world_pos_(world_pos),
view_pos_(view_pos),
color_(color),
attenuation_(attenuation),
intensity_(intensity)
{
}
}
| 19.5 | 76 | 0.654159 | MgBag |
6438402a08ef58b7fccd04182984ed6d272e562e | 1,945 | hpp | C++ | mnist_vae_cnn/vae_utils.hpp | akhandait/models | 1ec71f34f8a9401825eb2f6f586012761b71584e | [
"BSD-3-Clause"
] | 54 | 2020-03-20T05:40:01.000Z | 2022-03-18T13:56:46.000Z | mnist_vae_cnn/vae_utils.hpp | akhandait/models | 1ec71f34f8a9401825eb2f6f586012761b71584e | [
"BSD-3-Clause"
] | 136 | 2020-03-19T18:23:18.000Z | 2022-03-31T09:08:10.000Z | mnist_vae_cnn/vae_utils.hpp | akhandait/models | 1ec71f34f8a9401825eb2f6f586012761b71584e | [
"BSD-3-Clause"
] | 47 | 2020-03-20T11:51:34.000Z | 2022-03-23T15:44:10.000Z | /**
* @file vae_utils.cpp
* @author Atharva Khandait
*
* Utility function necessary for training and working with VAE models.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MODELS_VAE_UTILS_HPP
#define MODELS_VAE_UTILS_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/ffn.hpp>
using namespace mlpack;
using namespace mlpack::ann;
// Calculates mean loss over batches.
template<typename NetworkType = FFN<MeanSquaredError<>, HeInitialization>,
typename DataType = arma::mat>
double MeanTestLoss(NetworkType& model, DataType& testSet, size_t batchSize)
{
double loss = 0;
size_t nofPoints = testSet.n_cols;
size_t i;
for (i = 0; i < ( size_t )nofPoints / batchSize; i++)
{
loss +=
model.Evaluate(testSet.cols(batchSize * i, batchSize * (i + 1) - 1),
testSet.cols(batchSize * i, batchSize * (i + 1) - 1));
}
if (nofPoints % batchSize != 0)
{
loss += model.Evaluate(testSet.cols(batchSize * i, nofPoints - 1),
testSet.cols(batchSize * i, nofPoints - 1));
loss /= ( int )nofPoints / batchSize + 1;
}
else
loss /= nofPoints / batchSize;
return loss;
}
// Sample from the output distribution and post-process the outputs(because
// we pre-processed it before passing it to the model).
template<typename DataType = arma::mat>
void GetSample(DataType &input, DataType& samples, bool isBinary)
{
if (isBinary)
{
samples = arma::conv_to<DataType>::from(
arma::randu<DataType>(input.n_rows, input.n_cols) <= input);
samples *= 255;
}
else
{
samples = input / 2 + 0.5;
samples *= 255;
samples = arma::clamp(samples, 0, 255);
}
}
#endif
| 28.188406 | 78 | 0.666324 | akhandait |
64384b178a8d27d119a2054dcd9134bb5307a8da | 2,985 | inl | C++ | include/Fission/Base/hsv_conversions.inl | lazergenixdev/Fission | da4151c37d81c19a77fe3d78d181da6c16ba4ddd | [
"MIT"
] | 1 | 2021-02-28T10:58:11.000Z | 2021-02-28T10:58:11.000Z | include/Fission/Base/hsv_conversions.inl | lazergenixdev/Fission | da4151c37d81c19a77fe3d78d181da6c16ba4ddd | [
"MIT"
] | 1 | 2021-07-06T17:34:48.000Z | 2021-09-16T20:41:57.000Z | include/Fission/Base/hsv_conversions.inl | lazergenixdev/Fission | da4151c37d81c19a77fe3d78d181da6c16ba4ddd | [
"MIT"
] | null | null | null | /**
*
* @file: hsv_conversions.inl
* @author: [email protected]
*
*
* This file is provided under the MIT License:
*
* Copyright (c) 2021 Lazergenix Software
*
* 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.
*
*/
/*
*
* I am not the creator of these algorithms;
* They are mostly copied from stackoverflow,
* then further edited for my needs.
*
* All values are assumed to be in the range: [0,1]
*
* These macros are for code written in C,
* but they are compatable with C++
*
* These defines don't require any dependencies.
*
* defines: HSV_TO_RGB() and RGB_TO_HSV()
*
* undefine when done using.
*
*/
/* HSV_TO_RGB: Convert HSV to RGB */
#define HSV_TO_RGB( _R, _G, _B, _H, _S, _V ) {\
float hh, p, q, t, ff; \
long i; \
if( _S <= 0.0f ) { \
_R = _V; \
_G = _V; \
_B = _V; \
return; \
} \
hh = _H; \
if( hh >= 1.0f ) hh = 0.0f; \
hh *= 6.0f; \
i = (long)hh; \
ff = hh - i; \
p = _V * ( 1.0f - _S ); \
q = _V * ( 1.0f - _S * ff ); \
t = _V * ( 1.0f - _S * ( 1.0f - ff ) ); \
switch( i ) { \
case 0: _R = _V, _G = t, _B = p; break; \
case 1: _R = q, _G = _V, _B = p; break; \
case 2: _R = p, _G = _V, _B = t; break; \
case 3: _R = p, _G = q, _B = _V; break; \
case 4: _R = t, _G = p, _B = _V; break; \
default: _R = _V, _G = p, _B = q; break; \
} }
/* RGB_TO_HSV: Convert RGB to HSV */
#define RGB_TO_HSV( _R, _G, _B, _H, _S, _V ) {\
float min, max, delta; \
if( _R > _G ) \
min = _B < _G ? _B : _G, \
max = _B > _R ? _B : _R; \
else \
min = _B < _R ? _B : _R, \
max = _B > _G ? _B : _G; \
_V = max; \
delta = max - min; \
if( delta > 0.00001 ) \
_S = delta / max; \
else { _S = 0.0f, _H = 0.0f; return; } \
if( _R == max ) \
_H = (_G - _B)/delta; \
else if( _G == max ) \
_H = 2.0f + (_B - _R)/delta; \
else \
_H = 4.0f + (_R - _G)/delta; \
_H = _H / 6.0f; \
if( _H < 0.0f ) _H += 1.0f; }
| 29.264706 | 80 | 0.59263 | lazergenixdev |
64385ac90f0bb810e26972f831b4f2ba5c967011 | 174 | cpp | C++ | Code/structure/structure5.cpp | capacitybuilding/Fundamentals-of-Programming-Source-Code | 76d9a70b6b36c7eb1992de3806d1a16584904f76 | [
"MIT"
] | null | null | null | Code/structure/structure5.cpp | capacitybuilding/Fundamentals-of-Programming-Source-Code | 76d9a70b6b36c7eb1992de3806d1a16584904f76 | [
"MIT"
] | null | null | null | Code/structure/structure5.cpp | capacitybuilding/Fundamentals-of-Programming-Source-Code | 76d9a70b6b36c7eb1992de3806d1a16584904f76 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
struct Student{
string name;
string id;
int year;
string dep;
float gpa;
}s2, s3;
int main(){
Student s1;
}
| 11.6 | 20 | 0.614943 | capacitybuilding |
643b0da1d1a79b461a9ab287360ad0f77b3f9b18 | 14,449 | cpp | C++ | src/RenderSystem/Vulkan/Managers/CDeviceMemoryManager.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | 1 | 2018-01-06T04:44:36.000Z | 2018-01-06T04:44:36.000Z | src/RenderSystem/Vulkan/Managers/CDeviceMemoryManager.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | src/RenderSystem/Vulkan/Managers/CDeviceMemoryManager.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | #include "RenderSystem/Vulkan/Managers/CDeviceMemoryManager.h"
#if VKE_VULKAN_RENDERER
#include "RenderSystem/CDeviceContext.h"
#include "RenderSystem/CDDI.h"
namespace VKE
{
namespace RenderSystem
{
CDeviceMemoryManager::CDeviceMemoryManager(CDeviceContext* pCtx) :
m_pCtx{ pCtx }
{
}
CDeviceMemoryManager::~CDeviceMemoryManager()
{
}
Result CDeviceMemoryManager::Create(const SDeviceMemoryManagerDesc& Desc)
{
m_Desc = Desc;
Result ret = VKE_OK;
// Add empty pool
m_PoolBuffer.Add( {} );
m_vPoolViews.PushBack( {} );
m_vSyncObjects.PushBack( {} );
m_lastPoolSize = Desc.defaultPoolSize;
return ret;
}
void CDeviceMemoryManager::Destroy()
{
}
handle_t CDeviceMemoryManager::_CreatePool( const SCreateMemoryPoolDesc& Desc )
{
handle_t ret = INVALID_HANDLE;
SAllocateMemoryDesc AllocDesc;
AllocDesc.size = Desc.size;
AllocDesc.usage = Desc.usage;
SAllocateMemoryData MemData;
Result res = m_pCtx->DDI().Allocate( AllocDesc, &MemData );
if( VKE_SUCCEEDED( res ) )
{
SPool Pool;
Pool.Data = MemData;
ret = m_PoolBuffer.Add( Pool );
if( ret != UNDEFINED_U32 )
{
CMemoryPoolView::SInitInfo Info;
Info.memory = (uint64_t)(MemData.hDDIMemory);
Info.offset = 0;
Info.size = Desc.size;
Info.allocationAlignment = Desc.alignment;
CMemoryPoolView View;
handle_t viewIdx = ret;
// There is a new pool to be added
if( ret >= m_vPoolViews.GetCount() )
{
viewIdx = m_vPoolViews.PushBack( View );
m_vSyncObjects.PushBack( {} );
}
{
m_vPoolViews[ viewIdx ].Init( Info );
}
m_totalMemAllocated += AllocDesc.size;
VKE_LOG_WARN("Created new device memory pool with size: " << VKE_LOG_MEM_SIZE(AllocDesc.size) << ".");
VKE_LOG("Total device memory allocated: " << VKE_LOG_MEM_SIZE(m_totalMemAllocated) << ".");
}
}
return ret;
}
uint32_t CalculateNewPoolSize(const uint32_t& newPoolSize, const uint32_t& lastPoolSize,
const SDeviceMemoryManagerDesc& Desc)
{
uint32_t ret = newPoolSize;
if (newPoolSize == 0)
{
switch (Desc.resizePolicy)
{
case DeviceMemoryResizePolicies::DEFAULT_SIZE:
{
ret = Desc.defaultPoolSize;
break;
}
case DeviceMemoryResizePolicies::TWO_TIMES_DEFAULT_SIZE:
{
ret = Desc.defaultPoolSize * 2;
break;
}
case DeviceMemoryResizePolicies::FOUR_TIMES_DEFAULT_SIZE:
{
ret = Desc.defaultPoolSize * 4;
break;
}
case DeviceMemoryResizePolicies::TWO_TIMES_LAST_SIZE:
{
ret = lastPoolSize * 2;
break;
}
case DeviceMemoryResizePolicies::FOUR_TIMES_LAST_SIZE:
{
ret = lastPoolSize * 4;
break;
}
}
}
return ret;
}
handle_t CDeviceMemoryManager::_CreatePool(const SAllocateDesc& Desc,
const SAllocationMemoryRequirementInfo& MemReq)
{
auto poolSize = std::max<uint32_t>(m_lastPoolSize, MemReq.size);
poolSize = std::max<uint32_t>(poolSize, Desc.poolSize);
SCreateMemoryPoolDesc PoolDesc;
PoolDesc.usage = Desc.Memory.memoryUsages;
PoolDesc.size = poolSize;
PoolDesc.alignment = MemReq.alignment;
handle_t hPool = _CreatePool(PoolDesc);
m_mPoolIndices[Desc.Memory.memoryUsages].PushBack(hPool);
m_lastPoolSize = poolSize;
return hPool;
}
handle_t CDeviceMemoryManager::_AllocateFromPool( const SAllocateDesc& Desc,
const SAllocationMemoryRequirementInfo& MemReq, SBindMemoryInfo* pBindInfoOut )
{
handle_t ret = INVALID_HANDLE;
//SPool* pPool = nullptr;
auto Itr = m_mPoolIndices.find( Desc.Memory.memoryUsages );
// If no pool is created for such memory usage create a new one
// and call this function again
if( Itr == m_mPoolIndices.end() )
{
const handle_t hPool = _CreatePool(Desc, MemReq);
VKE_ASSERT(hPool != INVALID_HANDLE, "");
ret = _AllocateFromPool( Desc, MemReq, pBindInfoOut );
}
else
{
const HandleVec& vHandles = Itr->second;
SAllocateMemoryInfo Info;
Info.alignment = MemReq.alignment;
Info.size = MemReq.size;
uint64_t memory = CMemoryPoolView::INVALID_ALLOCATION;
// Find firt pool with enough memory
for( uint32_t i = 0; i < vHandles.GetCount(); ++i )
{
const auto poolIdx = vHandles[ i ];
//auto& Pool = m_PoolBuffer[ poolIdx ];
auto& View = m_vPoolViews[ poolIdx ];
CMemoryPoolView::SAllocateData Data;
memory = View.Allocate( Info, &Data );
if( memory != CMemoryPoolView::INVALID_ALLOCATION )
{
pBindInfoOut->hDDIBuffer = Desc.Memory.hDDIBuffer;
pBindInfoOut->hDDITexture = Desc.Memory.hDDITexture;
pBindInfoOut->hDDIMemory = (DDIMemory)( Data.memory );
pBindInfoOut->offset = Data.offset;
pBindInfoOut->hMemory = poolIdx;
UAllocationHandle Handle;
SMemoryAllocationInfo AllocInfo;
AllocInfo.hMemory = Data.memory;
AllocInfo.offset = Data.offset;
AllocInfo.size = Info.size;
Handle.hAllocInfo = m_AllocBuffer.Add( AllocInfo );
Handle.hPool = static_cast< uint16_t >( poolIdx );
Handle.dedicated = false;
ret = Handle.handle;
break;
}
}
// If there is no free space in any of currently allocated pools
if (memory == CMemoryPoolView::INVALID_ALLOCATION)
{
// Create new memory pool
SAllocateDesc NewDesc = Desc;
NewDesc.poolSize = CalculateNewPoolSize(Desc.poolSize, m_lastPoolSize, m_Desc);
const float sizeMB = NewDesc.poolSize / 1024.0f / 1024.0f;
VKE_LOG_WARN("No device memory for allocation with requirements: " << VKE_LOG_MEM_SIZE(MemReq.size) << ", " << MemReq.alignment << " bytes alignment.");
//VKE_LOG_WARN("Create new device memory pool with size: " << VKE_LOG_MEM_SIZE(NewDesc.poolSize) << ".");
const handle_t hPool = _CreatePool(NewDesc, MemReq);
//VKE_LOG_WARN("Total device memory allocated: " << VKE_LOG_MEM_SIZE(m_totalMemAllocated) << "." );
VKE_ASSERT(hPool != INVALID_HANDLE, "");
ret = _AllocateFromPool(Desc, MemReq, pBindInfoOut);
}
}
m_totalMemUsed += MemReq.size;
return ret;
}
handle_t CDeviceMemoryManager::_AllocateMemory( const SAllocateDesc& Desc, SBindMemoryInfo* pOut )
{
handle_t ret = INVALID_HANDLE;
const auto dedicatedAllocation = Desc.Memory.memoryUsages & MemoryUsages::DEDICATED_ALLOCATION;
SAllocationMemoryRequirementInfo MemReq = {};
if( Desc.Memory.hDDIBuffer != DDI_NULL_HANDLE )
{
m_pCtx->DDI().GetBufferMemoryRequirements( Desc.Memory.hDDIBuffer, &MemReq );
}
else if( Desc.Memory.hDDITexture != DDI_NULL_HANDLE )
{
m_pCtx->DDI().GetTextureMemoryRequirements( Desc.Memory.hDDITexture, &MemReq );
}
if( !dedicatedAllocation )
{
ret =_AllocateFromPool( Desc, MemReq, pOut );
}
else
{
SAllocateMemoryData Data;
SAllocateMemoryDesc AllocDesc;
AllocDesc.size = MemReq.size;
AllocDesc.usage = Desc.Memory.memoryUsages;
Result res = m_pCtx->_GetDDI().Allocate( AllocDesc, &Data );
if( VKE_SUCCEEDED( res ) )
{
auto& BindInfo = *pOut;
BindInfo.hDDITexture = Desc.Memory.hDDITexture;
BindInfo.hDDIBuffer = Desc.Memory.hDDIBuffer;
BindInfo.hDDIMemory = Data.hDDIMemory;
BindInfo.hMemory = INVALID_HANDLE;
BindInfo.offset = 0;
SMemoryAllocationInfo AllocInfo;
AllocInfo.hMemory = ( handle_t )( Data.hDDIMemory );
AllocInfo.offset = 0;
AllocInfo.size = AllocDesc.size;
UAllocationHandle Handle;
Handle.dedicated = true;
Handle.hAllocInfo = m_AllocBuffer.Add( AllocInfo );
Handle.hPool = 0;
ret = Handle.handle;
VKE_LOG_WARN("Allocate new device memory with size: " << VKE_LOG_MEM_SIZE(AllocDesc.size) << ".");
m_totalMemAllocated += AllocDesc.size;
m_totalMemUsed += AllocDesc.size;
VKE_LOG_WARN("Total device memory allocated: " << VKE_LOG_MEM_SIZE(m_totalMemAllocated) << ".");
}
}
return ret;
}
handle_t CDeviceMemoryManager::AllocateBuffer( const SAllocateDesc& Desc )
{
SBindMemoryInfo BindInfo;
handle_t ret = _AllocateMemory( Desc, &BindInfo );
if( ret != INVALID_HANDLE )
{
{
m_pCtx->_GetDDI().Bind< ResourceTypes::BUFFER >( BindInfo );
}
}
return ret;
}
handle_t CDeviceMemoryManager::AllocateTexture(const SAllocateDesc& Desc )
{
SBindMemoryInfo BindInfo;
handle_t ret = _AllocateMemory( Desc, &BindInfo );
if( ret != INVALID_HANDLE )
{
{
m_pCtx->_GetDDI().Bind< ResourceTypes::TEXTURE >( BindInfo );
}
}
return ret;
}
Result CDeviceMemoryManager::UpdateMemory( const SUpdateMemoryInfo& DataInfo, const SBindMemoryInfo& BindInfo )
{
Result ret = VKE_ENOMEMORY;
SMapMemoryInfo MapInfo;
MapInfo.hMemory = BindInfo.hDDIMemory;
MapInfo.offset = BindInfo.offset + DataInfo.dstDataOffset;
MapInfo.size = DataInfo.dataSize;
void* pDst = m_pCtx->DDI().MapMemory( MapInfo );
if( pDst != nullptr )
{
Memory::Copy( pDst, DataInfo.dataSize, DataInfo.pData, DataInfo.dataSize );
ret = VKE_OK;
}
m_pCtx->DDI().UnmapMemory( BindInfo.hDDIMemory );
return ret;
}
Result CDeviceMemoryManager::UpdateMemory( const SUpdateMemoryInfo& DataInfo, const handle_t& hMemory )
{
UAllocationHandle Handle = hMemory;
const auto& AllocInfo = m_AllocBuffer[ Handle.hAllocInfo ];
Result ret = VKE_ENOMEMORY;
SMapMemoryInfo MapInfo;
MapInfo.hMemory = ( DDIMemory )( AllocInfo.hMemory );
MapInfo.offset = AllocInfo.offset + DataInfo.dstDataOffset;
MapInfo.size = DataInfo.dataSize;
{
Threads::ScopedLock l( m_vSyncObjects[Handle.hPool] );
void* pDst = m_pCtx->DDI().MapMemory( MapInfo );
if( pDst != nullptr )
{
Memory::Copy( pDst, DataInfo.dataSize, DataInfo.pData, DataInfo.dataSize );
ret = VKE_OK;
}
m_pCtx->DDI().UnmapMemory( MapInfo.hMemory );
}
return ret;
}
void* CDeviceMemoryManager::MapMemory(const SUpdateMemoryInfo& DataInfo, const handle_t& hMemory)
{
UAllocationHandle Handle = hMemory;
const auto& AllocInfo = m_AllocBuffer[Handle.hAllocInfo];
SMapMemoryInfo MapInfo;
MapInfo.hMemory = (DDIMemory)AllocInfo.hMemory;
MapInfo.offset = AllocInfo.offset + DataInfo.dstDataOffset;
MapInfo.size = DataInfo.dataSize;
Threads::ScopedLock l(m_vSyncObjects[Handle.hPool]);
void* pRet = m_pCtx->DDI().MapMemory(MapInfo);
return pRet;
}
void CDeviceMemoryManager::UnmapMemory(const handle_t& hMemory)
{
UAllocationHandle Handle = hMemory;
const auto& AllocInfo = m_AllocBuffer[Handle.hAllocInfo];
Threads::ScopedLock l(m_vSyncObjects[Handle.hPool]);
m_pCtx->DDI().UnmapMemory((DDIMemory)AllocInfo.hMemory);
}
const SMemoryAllocationInfo& CDeviceMemoryManager::GetAllocationInfo( const handle_t& hMemory )
{
UAllocationHandle Handle = hMemory;
return m_AllocBuffer[Handle.hAllocInfo];
}
} // RenderSystem
} // VKE
#endif // VKE_VULKAN_RENDERER | 40.247911 | 172 | 0.522181 | przemyslaw-szymanski |
643b2731e65bb36d7d7cac192ee3a77c4e702308 | 906 | hpp | C++ | src/holosuite-lib/holocapture/HoloCaptureOpenNI2Listener.hpp | itsermo/holosuite | 16659efec910a4050ddd6548b1310e3ed09636e0 | [
"BSD-3-Clause"
] | null | null | null | src/holosuite-lib/holocapture/HoloCaptureOpenNI2Listener.hpp | itsermo/holosuite | 16659efec910a4050ddd6548b1310e3ed09636e0 | [
"BSD-3-Clause"
] | null | null | null | src/holosuite-lib/holocapture/HoloCaptureOpenNI2Listener.hpp | itsermo/holosuite | 16659efec910a4050ddd6548b1310e3ed09636e0 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "../holocommon/CommonDefs.hpp"
#include <log4cxx/log4cxx.h>
#include <opencv2/opencv.hpp>
#include <OpenNI.h>
#include <mutex>
#include <condition_variable>
#define HOLO_CAPTURE_OPENNI2_MUTEX_TIMEOUT_MS 30
namespace holo
{
namespace capture
{
class HoloCaptureOpenNI2Listener : public openni::VideoStream::NewFrameListener
{
public:
HoloCaptureOpenNI2Listener();
~HoloCaptureOpenNI2Listener();
void onNewFrame(openni::VideoStream& stream);
void getDepthFrame(cv::Mat& depthOut);
void getColorFrame(cv::Mat& colorOut);
private:
openni::VideoFrameRef colorFrame_;
openni::VideoFrameRef depthFrame_;
bool haveNewColorFrame_;
bool haveNewDepthFrame_;
std::mutex colorFrameMutex_;
std::mutex depthFrameMutex_;
std::condition_variable colorFrameCV_;
std::condition_variable depthFrameCV_;
log4cxx::LoggerPtr logger_;
};
}
}
| 20.133333 | 81 | 0.756071 | itsermo |
643bd58227e5fc842f483310d28910448b8f85db | 3,207 | cpp | C++ | Classes/GameScene.cpp | danielgimenes/Frenzy | bf6aef2de3b4f22baef98ce08121fc1fdc3f5c53 | [
"MIT"
] | 2 | 2015-09-07T05:15:11.000Z | 2019-01-09T02:37:05.000Z | Classes/GameScene.cpp | danielgimenes/Frenzy | bf6aef2de3b4f22baef98ce08121fc1fdc3f5c53 | [
"MIT"
] | null | null | null | Classes/GameScene.cpp | danielgimenes/Frenzy | bf6aef2de3b4f22baef98ce08121fc1fdc3f5c53 | [
"MIT"
] | null | null | null | #include "GameScene.h"
#include "Colors.h"
USING_NS_CC;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = GameScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
if ( !Layer::init() )
{
return false;
}
auto colorLayer = LayerColor::create(GAME_SCENE_BACKGROUND_COLOR);
this->addChild(colorLayer, 0);
visibleSize = Director::getInstance()->getVisibleSize();
origin = Director::getInstance()->getVisibleOrigin();
board = new GameBoard();
board->spawnNewPiece();
drawer = new GameBoardDrawer(board, this, origin, visibleSize);
drawer->drawGameBoard();
int SCREEN_BORDER = 20;
auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
[] (Ref *sender) {
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
});
closeItem->setScaleX(4.0f);
closeItem->setScaleY(4.0f);
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->boundingBox().size.width/2 - SCREEN_BORDER,
origin.y + closeItem->boundingBox().size.height/2 + SCREEN_BORDER));
auto resetItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
[this] (Ref *sender) {
this->board->resetBoard();
this->drawer->drawGameBoard();
});
resetItem->setScaleX(4.0f);
resetItem->setScaleY(4.0f);
int SEPARATOR = 5;
resetItem->setPosition(Vec2(closeItem->getPosition().x - closeItem->boundingBox().size.width/2 - resetItem->boundingBox().size.width/2 - SEPARATOR,
origin.y + resetItem->boundingBox().size.height/2 + SCREEN_BORDER));
Vector<MenuItem*> menuItems;
menuItems.pushBack(closeItem);
menuItems.pushBack(resetItem);
auto menu = Menu::createWithArray(menuItems);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
touchListener->onTouchMoved = CC_CALLBACK_2(GameScene::onTouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto scheduler = Director::getInstance()->getScheduler();
scheduler->schedule(schedule_selector(GameScene::onBoardTimerTick), this, GAME_BOARD_TICK_IN_SECONDS, CC_REPEAT_FOREVER, 0.0f, false);
return true;
}
void GameScene::onBoardTimerTick(float delta)
{
board->processBoard();
drawer->drawGameBoard();
}
bool GameScene::onTouchBegan(Touch *touch, Event *event)
{
board->spawnNewPiece();
drawer->drawGameBoard();
return true;
}
void GameScene::onTouchMoved(Touch *touch, Event *event)
{
}
void GameScene::onTouchEnded(Touch *touch, Event *event)
{
}
| 29.971963 | 151 | 0.664484 | danielgimenes |
64423b92acd78d7636aad9ee0f9d39f4b190b3ed | 5,072 | cpp | C++ | gameOfLife/main.cpp | anAwesomeWave/sfmlGames | 6e262b80dbe625451125cc62e65113ca1ced542e | [
"MIT"
] | null | null | null | gameOfLife/main.cpp | anAwesomeWave/sfmlGames | 6e262b80dbe625451125cc62e65113ca1ced542e | [
"MIT"
] | null | null | null | gameOfLife/main.cpp | anAwesomeWave/sfmlGames | 6e262b80dbe625451125cc62e65113ca1ced542e | [
"MIT"
] | null | null | null | #include <SFML/GRAPHICS.hpp>
#include <iostream>
using namespace sf;
void createCube(int arrOfCubes[62][62]) {
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 0) {
int numberOfCubes = 0;
if(arrOfCubes[i-1][j-1] == 1 || arrOfCubes[i-1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j] == 1 || arrOfCubes[i-1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j+1] == 1 || arrOfCubes[i-1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j+1] == 1 || arrOfCubes[i][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j+1] == 1 || arrOfCubes[i+1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j] == 1 || arrOfCubes[i+1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j-1] == 1 || arrOfCubes[i+1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j-1] == 1 || arrOfCubes[i][j-1] == 3) {numberOfCubes += 1;}
if(numberOfCubes == 3) {
arrOfCubes[i][j] = 2;
}
}
}
}
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 3){
arrOfCubes[i][j] = 0;
}
}
}
}
void isCellAlive(int arrOfCubes[62][62]) {
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 1 || arrOfCubes[i][j] == 2) {
int numberOfCubes = 0;
if(arrOfCubes[i-1][j-1] == 1 || arrOfCubes[i-1][j-1] == 2 || arrOfCubes[i-1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j] == 1 || arrOfCubes[i-1][j] == 2 || arrOfCubes[i-1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i-1][j+1] == 1 || arrOfCubes[i-1][j+1] == 2 || arrOfCubes[i-1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j+1] == 1 || arrOfCubes[i][j+1] == 2 || arrOfCubes[i][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j+1] == 1 || arrOfCubes[i+1][j+1] == 2 || arrOfCubes[i+1][j+1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j] == 1 || arrOfCubes[i+1][j] == 2 || arrOfCubes[i+1][j] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i+1][j-1] == 1 || arrOfCubes[i+1][j-1] == 2 || arrOfCubes[i+1][j-1] == 3) {numberOfCubes += 1;}
if(arrOfCubes[i][j-1] == 1 || arrOfCubes[i][j-1] == 2 || arrOfCubes[i][j-1] == 3) {numberOfCubes += 1;}
if(numberOfCubes != 2 && numberOfCubes != 3) {
arrOfCubes[i][j] = 3;
}
}
}
}
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfCubes[i][j] == 2) {
arrOfCubes[i][j] = 1;
}
}
}
}
void drawLines(RenderWindow& window) {
for(int i = 10; i < 600; i += 10) {
RectangleShape rect1, rect2;
rect1.setPosition({i, 0});
rect1.setSize({2, 600});
rect1.setFillColor({Color::Black});
rect2.setPosition({0, i});
rect2.setSize({600, 2});
rect2.setFillColor({Color::Black});
window.draw(rect1);
window.draw(rect2);
}
}
int main() {
RenderWindow window({600, 600}, "GameOFLife");
int arrOfcubes[62][62] = {0}; // we will use arr 60x60, but our functions require more
// 0 - dead cell, 1 - old cell, 2 - new cell, 3 - dead cell
bool start = true;
Clock clock;
Time timer;
float delay = 0.1;
while(window.isOpen()) {
timer += clock.getElapsedTime();
clock.restart();
Event event;
while(window.pollEvent(event)) {
if(event.type == Event::Closed) {
window.close();
}
if(Mouse::isButtonPressed(Mouse::Left)) {
int y = Mouse::getPosition(window).y / 10;
int x = Mouse::getPosition(window).x / 10;
if(x > - 1 && x < 60 && y > -1 && y < 60){
arrOfcubes[y + 1][x + 1] = 2;
}
}
if(event.type == Event::KeyPressed) {
if(event.key.code == Keyboard::Space) {
start = false;
}
}
}
if(timer.asSeconds() >= delay && !start) {
timer = Time::Zero;
isCellAlive(arrOfcubes);
createCube(arrOfcubes);
}
window.clear({123, 159, 198});
drawLines(window);
for(int i = 1; i < 61; i ++) {
for(int j = 1; j < 61; j ++) {
if(arrOfcubes[i][j] == 1 || arrOfcubes[i][j] == 2) {
RectangleShape rect;
rect.setFillColor(Color::Black);
rect.setSize({10, 10});
rect.setPosition({j * 10 - 10, i * 10 - 10});
window.draw(rect);
}
}
}
window.display();
}
}
| 37.57037 | 125 | 0.440457 | anAwesomeWave |
6444adcd77313e5b74b96ba2b1c86d23c302bdd9 | 9,084 | hpp | C++ | Generated Files/Scenario5_MatsTexs.g.hpp | hot3dx/RotoDraw3D-DirectX-12 | be854c55ce784fe9ce6298ae962aa4eac08aa534 | [
"MIT"
] | null | null | null | Generated Files/Scenario5_MatsTexs.g.hpp | hot3dx/RotoDraw3D-DirectX-12 | be854c55ce784fe9ce6298ae962aa4eac08aa534 | [
"MIT"
] | null | null | null | Generated Files/Scenario5_MatsTexs.g.hpp | hot3dx/RotoDraw3D-DirectX-12 | be854c55ce784fe9ce6298ae962aa4eac08aa534 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
#include "pch.h"
#pragma warning(push)
#pragma warning(disable: 4100) // unreferenced formal parameter
#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
#endif
#include "Scenario5_MatsTexs.xaml.h"
void ::Hot3dxRotoDraw::Scenario5_MatsTexs::InitializeComponent()
{
if (_contentLoaded)
{
return;
}
_contentLoaded = true;
::Windows::Foundation::Uri^ resourceLocator = ref new ::Windows::Foundation::Uri(L"ms-appx:///Scenario5_MatsTexs.xaml");
::Windows::UI::Xaml::Application::LoadComponent(this, resourceLocator, ::Windows::UI::Xaml::Controls::Primitives::ComponentResourceLocation::Application);
}
void ::Hot3dxRotoDraw::Scenario5_MatsTexs::Connect(int __connectionId, ::Platform::Object^ __target)
{
switch (__connectionId)
{
case 2:
{
this->RootGrid = safe_cast<::Windows::UI::Xaml::Controls::Grid^>(__target);
}
break;
case 3:
{
this->IDC_PALETTE_FILE_NAME_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 4:
{
this->textBox = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 5:
{
this->filePath1TextBlock = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 6:
{
this->textureFileTextBlock1 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 7:
{
this->filePath2TextBlock = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 8:
{
this->textureFileTextBlock2 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 9:
{
this->IDC_CREATE_PALETTE_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 10:
{
this->IDC_OPEN_PALETTE_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 11:
{
this->IDC_ADD_MATERIAL_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 12:
{
this->IDC_SAVE_PALETTE_BUTTON2 = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 13:
{
this->IDC_SET_MATERIAL_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 14:
{
this->IDC_ADD_DELETEMATERIAL_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 15:
{
this->textBlock = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 16:
{
this->IDC_NUM_MATERIALS_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 17:
{
this->textBlock2 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 18:
{
this->IDC_CURRENT_MATERIAL_slider1 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 19:
{
this->IDC_CURRENT_MATERIAL_slider2 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 20:
{
this->IDC_CURRENT_MATERIAL_slider3 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 21:
{
this->IDC_CURRENT_MATERIAL_slider4 = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 22:
{
this->IDC_CURRENT_MATERIAL_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 23:
{
this->MaterialListControl = safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(this->MaterialListControl))->SelectionChanged += ref new ::Windows::UI::Xaml::Controls::SelectionChangedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::Controls::SelectionChangedEventArgs^))&Scenario5_MatsTexs::MaterialListControl_SelectionChanged);
}
break;
case 24:
{
this->MaterialListControlData = safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::ListBox^>(this->MaterialListControlData))->SelectionChanged += ref new ::Windows::UI::Xaml::Controls::SelectionChangedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::Controls::SelectionChangedEventArgs^))&Scenario5_MatsTexs::MaterialListControlData_SelectionChanged);
}
break;
case 25:
{
this->textBlock12 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 26:
{
this->IDC_NAME_SET_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 27:
{
this->IDC_NAME_SET_EDIT = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
}
break;
case 28:
{
this->IDC_TEXTURE_FILENAME_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 29:
{
this->IDC_CLEAR_TEXTURE_FILENAME_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 30:
{
this->textBlock13 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 31:
{
this->textBlock14 = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
}
break;
case 32:
{
this->IDC_POWER_SLIDER = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 33:
{
this->ID_COLOR_ADD_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
}
break;
case 34:
{
this->scrollBar = safe_cast<::Windows::UI::Xaml::Controls::Slider^>(__target);
}
break;
case 35:
{
this->TextureImage1 = safe_cast<::Windows::UI::Xaml::Controls::Image^>(__target);
}
break;
case 36:
{
this->IDC_TEXTURE_IMAGE1_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::Button^>(this->IDC_TEXTURE_IMAGE1_BUTTON))->Click += ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::RoutedEventArgs^))&Scenario5_MatsTexs::IDC_TEXTURE_IMAGE1_BUTTON_Click);
}
break;
case 37:
{
this->IDC_TEXTURE_IMAGE2_BUTTON = safe_cast<::Windows::UI::Xaml::Controls::Button^>(__target);
(safe_cast<::Windows::UI::Xaml::Controls::Button^>(this->IDC_TEXTURE_IMAGE2_BUTTON))->Click += ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Hot3dxRotoDraw::Scenario5_MatsTexs::*)
(::Platform::Object^, ::Windows::UI::Xaml::RoutedEventArgs^))&Scenario5_MatsTexs::IDC_TEXTURE_IMAGE2_BUTTON_Click);
}
break;
case 38:
{
this->TextureImage2 = safe_cast<::Windows::UI::Xaml::Controls::Image^>(__target);
}
break;
case 39:
{
this->matName = safe_cast<::Windows::UI::Xaml::Controls::ListBoxItem^>(__target);
}
break;
case 40:
{
this->rgba_A = safe_cast<::Windows::UI::Xaml::Controls::ListBoxItem^>(__target);
}
break;
}
_contentLoaded = true;
}
::Windows::UI::Xaml::Markup::IComponentConnector^ ::Hot3dxRotoDraw::Scenario5_MatsTexs::GetBindingConnector(int __connectionId, ::Platform::Object^ __target)
{
__connectionId; // unreferenced
__target; // unreferenced
return nullptr;
}
#pragma warning(pop)
| 36.336 | 239 | 0.561867 | hot3dx |
6446489f3bc7686b13790767d3634e2a0f2f0aa2 | 754 | cpp | C++ | src/simulator/vulkan/semaphore.cpp | happydpc/RobotSimulator | 0c09d09e802c3118a2beabc7999637ce1fa4e7a7 | [
"MIT"
] | 1 | 2021-12-22T18:24:08.000Z | 2021-12-22T18:24:08.000Z | src/simulator/vulkan/semaphore.cpp | happydpc/RobotSimulator | 0c09d09e802c3118a2beabc7999637ce1fa4e7a7 | [
"MIT"
] | null | null | null | src/simulator/vulkan/semaphore.cpp | happydpc/RobotSimulator | 0c09d09e802c3118a2beabc7999637ce1fa4e7a7 | [
"MIT"
] | null | null | null | //--------------------------------------------------
// Robot Simulator
// semaphore.cpp
// Date: 24/06/2020
// By Breno Cunha Queiroz
//--------------------------------------------------
#include "semaphore.h"
Semaphore::Semaphore(Device* device)
{
_device = device;
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if(vkCreateSemaphore(_device->handle(), &semaphoreInfo, nullptr, &_semaphore) != VK_SUCCESS)
{
std::cout << BOLDRED << "[Semaphore]" << RESET << RED << " Failed to create semaphore!" << RESET << std::endl;
exit(1);
}
}
Semaphore::~Semaphore()
{
if(_semaphore != nullptr)
{
vkDestroySemaphore(_device->handle(), _semaphore, nullptr);
_semaphore = nullptr;
}
}
| 23.5625 | 112 | 0.600796 | happydpc |
644798953569b9ef0bb7edf4ed78e2e4f7a17f15 | 8,707 | tcc | C++ | libiop/protocols/encoded/common/rational_linear_combination.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/protocols/encoded/common/rational_linear_combination.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/protocols/encoded/common/rational_linear_combination.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | #include "libiop/algebra/utils.hpp"
namespace libiop {
template<typename FieldT>
combined_denominator<FieldT>::combined_denominator(const std::size_t num_rationals) :
num_rationals_(num_rationals)
{
}
/* Returns the product of all the denominators */
template<typename FieldT>
std::shared_ptr<std::vector<FieldT>> combined_denominator<FieldT>::evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &constituent_oracle_evaluations) const
{
if (constituent_oracle_evaluations.size() != this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
std::shared_ptr<std::vector<FieldT>> result = std::make_shared<std::vector<FieldT>>(
*constituent_oracle_evaluations[0].get());
for (std::size_t i = 1; i < constituent_oracle_evaluations.size(); ++i)
{
if (constituent_oracle_evaluations[i]->size() != result->size())
{
throw std::invalid_argument("Vectors of mismatched size.");
}
for (std::size_t j = 0; j < result->size(); ++j)
{
result->operator[](j) *= constituent_oracle_evaluations[i]->operator[](j);
}
}
return result;
}
/* Takes a random linear combination of the constituent oracle evaluations. */
template<typename FieldT>
FieldT combined_denominator<FieldT>::evaluation_at_point(
const std::size_t evaluation_position,
const FieldT evaluation_point,
const std::vector<FieldT> &constituent_oracle_evaluations) const
{
libff::UNUSED(evaluation_position);
libff::UNUSED(evaluation_point);
if (constituent_oracle_evaluations.size() != this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
FieldT result = constituent_oracle_evaluations[0];
for (std::size_t i = 1; i < constituent_oracle_evaluations.size(); ++i)
{
result *= constituent_oracle_evaluations[i];
}
return result;
}
template<typename FieldT>
combined_numerator<FieldT>::combined_numerator(const std::size_t num_rationals) :
num_rationals_(num_rationals)
{
}
template<typename FieldT>
void combined_numerator<FieldT>::set_coefficients(const std::vector<FieldT>& coefficients)
{
if (coefficients.size() != this->num_rationals_)
{
throw std::invalid_argument("Expected same number of random coefficients as oracles.");
}
this->coefficients_ = coefficients;
}
template<typename FieldT>
std::shared_ptr<std::vector<FieldT>> combined_numerator<FieldT>::evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &constituent_oracle_evaluations) const{
if (constituent_oracle_evaluations.size() != 2*this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
const size_t codeword_domain_size = constituent_oracle_evaluations[0]->size();
std::shared_ptr<std::vector<FieldT>> result = std::make_shared<std::vector<FieldT>>(
codeword_domain_size, FieldT::zero());
for (size_t j = 0; j < codeword_domain_size; j++)
{
for (size_t i = 0; i < this->num_rationals_; i++)
{
FieldT cur = this->coefficients_[i];
/** Multiply by numerator */
cur *= constituent_oracle_evaluations[i]->operator[](j);
/** Multiply by all other denominators */
for (size_t k = this->num_rationals_; k < 2 * this->num_rationals_; k++)
{
if (k - this->num_rationals_ == i)
{
continue;
}
cur *= constituent_oracle_evaluations[k]->operator[](j);
}
result->operator[](j) += cur;
}
}
return result;
}
template<typename FieldT>
FieldT combined_numerator<FieldT>::evaluation_at_point(
const std::size_t evaluation_position,
const FieldT evaluation_point,
const std::vector<FieldT> &constituent_oracle_evaluations) const
{
libff::UNUSED(evaluation_position);
libff::UNUSED(evaluation_point);
if (constituent_oracle_evaluations.size() != 2*this->num_rationals_)
{
throw std::invalid_argument("Expected same number of evaluations as in registration.");
}
FieldT result = FieldT::zero();
for (size_t i = 0; i < this->num_rationals_; i++)
{
FieldT cur = this->coefficients_[i];
/** Multiply by numerator */
cur *= constituent_oracle_evaluations[i];
/** Multiply by all other denominators */
for (size_t j = this->num_rationals_; j < 2 * this->num_rationals_; j++)
{
if (j - this->num_rationals_ == i)
{
continue;
}
cur *= constituent_oracle_evaluations[j];
}
result += cur;
}
return result;
}
template<typename FieldT>
rational_linear_combination<FieldT>::rational_linear_combination(
iop_protocol<FieldT> &IOP,
const std::size_t num_rationals,
const std::vector<oracle_handle_ptr> numerator_handles,
const std::vector<oracle_handle_ptr> denominator_handles) :
IOP_(IOP),
num_rationals_(num_rationals)
{
if (numerator_handles.size() != this->num_rationals_ || denominator_handles.size() != this->num_rationals_)
{
throw std::invalid_argument("Rational Linear Combination: "
"#numerator handles passed in != #denominator handles passed in");
}
this->numerator_ = std::make_shared<combined_numerator<FieldT>>(this->num_rationals_);
this->denominator_ = std::make_shared<combined_denominator<FieldT>>(this->num_rationals_);
const domain_handle domain = this->IOP_.get_oracle_domain(numerator_handles[0]);
size_t denominator_degree = 1;
for (size_t i = 0; i < this->num_rationals_; i++)
{
denominator_degree += this->IOP_.get_oracle_degree(denominator_handles[i]) - 1;
}
this->combined_denominator_handle_ = this->IOP_.register_virtual_oracle(
domain, denominator_degree, denominator_handles, this->denominator_);
size_t numerator_degree = 0;
/** numerator degree = max(deg(N_i) + sum_{j \neq i} D_j)
* sum_{j \neq i} D_j = (sum D_i) - D_j
*/
for (size_t i = 0; i < this->num_rationals_; i++)
{
size_t candidate_numerator_degree =
this->IOP_.get_oracle_degree(numerator_handles[i])
+ denominator_degree - this->IOP_.get_oracle_degree(denominator_handles[i]);
if (candidate_numerator_degree > numerator_degree)
{
numerator_degree = candidate_numerator_degree;
}
}
std::vector<oracle_handle_ptr> all_handles(numerator_handles);
all_handles.insert(all_handles.end(), denominator_handles.begin(), denominator_handles.end());
this->combined_numerator_handle_ = this->IOP_.register_virtual_oracle(
domain, numerator_degree, all_handles, this->numerator_);
}
template<typename FieldT>
void rational_linear_combination<FieldT>::set_coefficients(
const std::vector<FieldT>& coefficients)
{
this->numerator_->set_coefficients(coefficients);
}
template<typename FieldT>
std::vector<FieldT> rational_linear_combination<FieldT>::evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &numerator_evals,
const std::vector<std::shared_ptr<std::vector<FieldT>>> &denominator_evals) const
{
std::vector<FieldT> combined_denominator_evals =
*this->denominator_->evaluated_contents(denominator_evals).get();
const bool denominator_can_contain_zeroes = false;
combined_denominator_evals = batch_inverse<FieldT>(
combined_denominator_evals, denominator_can_contain_zeroes);
std::vector<std::shared_ptr<std::vector<FieldT>>> all_evals;
for (size_t i = 0; i < this->num_rationals_; i++)
{
all_evals.emplace_back(numerator_evals[i]);
}
for (size_t i = 0; i < this->num_rationals_; i++)
{
all_evals.emplace_back(denominator_evals[i]);
}
std::vector<FieldT> result = *this->numerator_->evaluated_contents(all_evals).get();
for (size_t i = 0; i < numerator_evals[0]->size(); i++)
{
result[i] *= combined_denominator_evals[i];
}
return result;
}
template<typename FieldT>
oracle_handle_ptr rational_linear_combination<FieldT>::get_denominator_handle() const
{
return std::make_shared<virtual_oracle_handle>(this->combined_denominator_handle_);
}
template<typename FieldT>
oracle_handle_ptr rational_linear_combination<FieldT>::get_numerator_handle() const
{
return std::make_shared<virtual_oracle_handle>(this->combined_numerator_handle_);
}
} // libiop
| 36.279167 | 111 | 0.683932 | alexander-zw |
64489282c7c1649226ff6f3dfb5152fa25dd174d | 9,447 | cpp | C++ | BRE/GeometryPass/GeometryPass.cpp | nicolasbertoa/D3D12Base | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | 9 | 2016-07-14T05:43:45.000Z | 2016-10-31T15:21:53.000Z | BRE/GeometryPass/GeometryPass.cpp | yang-shuohao/BRE12 | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | null | null | null | BRE/GeometryPass/GeometryPass.cpp | yang-shuohao/BRE12 | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | null | null | null | #include "GeometryPass.h"
#include <d3d12.h>
#include <DirectXColors.h>
#include <tbb/parallel_for.h>
#include <CommandListExecutor/CommandListExecutor.h>
#include <DescriptorManager\CbvSrvUavDescriptorManager.h>
#include <DescriptorManager\RenderTargetDescriptorManager.h>
#include <DirectXManager\DirectXManager.h>
#include <DXUtils/D3DFactory.h>
#include <GeometryPass\Recorders\HeightMappingCommandListRecorder.h>
#include <GeometryPass\Recorders\NormalMappingCommandListRecorder.h>
#include <GeometryPass\Recorders\TextureMappingCommandListRecorder.h>
#include <ResourceManager\ResourceManager.h>
#include <ResourceStateManager\ResourceStateManager.h>
#include <ShaderUtils\CBuffers.h>
#include <Utils\DebugUtils.h>
using namespace DirectX;
namespace BRE {
namespace {
// Geometry buffer formats
const DXGI_FORMAT sGeometryBufferFormats[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]{
DXGI_FORMAT_R16G16B16A16_FLOAT,
DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_UNKNOWN
};
///
/// @brief Create geometry buffers and render target views
/// @param buffers Output list of geometry buffers
/// @param bufferRenderTargetViews Output geometry buffers render target views
///
void
CreateGeometryBuffersAndRenderTargetViews(ID3D12Resource* buffers[GeometryPass::BUFFERS_COUNT],
D3D12_CPU_DESCRIPTOR_HANDLE bufferRenderTargetViews[GeometryPass::BUFFERS_COUNT]) noexcept
{
// Set shared buffers properties
D3D12_RESOURCE_DESC resourceDescriptor = D3DFactory::GetResourceDescriptor(ApplicationSettings::sWindowWidth,
ApplicationSettings::sWindowHeight,
DXGI_FORMAT_UNKNOWN,
D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
D3D12_RESOURCE_DIMENSION_TEXTURE2D,
D3D12_TEXTURE_LAYOUT_UNKNOWN,
0U);
D3D12_CLEAR_VALUE clearValue[]
{
{ DXGI_FORMAT_UNKNOWN, 0.0f, 0.0f, 0.0f, 1.0f },
{ DXGI_FORMAT_UNKNOWN, 0.0f, 0.0f, 0.0f, 0.0f },
};
BRE_ASSERT(_countof(clearValue) == GeometryPass::BUFFERS_COUNT);
const D3D12_HEAP_PROPERTIES heapProperties = D3DFactory::GetHeapProperties();
// Create and store render target views
const wchar_t* resourceNames[GeometryPass::BUFFERS_COUNT] =
{
L"Normal_RoughnessTexture Buffer",
L"BaseColor_MetalnessTexture Buffer"
};
for (std::uint32_t i = 0U; i < GeometryPass::BUFFERS_COUNT; ++i) {
resourceDescriptor.Format = sGeometryBufferFormats[i];
clearValue[i].Format = resourceDescriptor.Format;
D3D12_RENDER_TARGET_VIEW_DESC rtvDescriptor{};
rtvDescriptor.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
rtvDescriptor.Format = resourceDescriptor.Format;
resourceDescriptor.MipLevels = 1U;
buffers[i] = &ResourceManager::CreateCommittedResource(heapProperties,
D3D12_HEAP_FLAG_NONE,
resourceDescriptor,
D3D12_RESOURCE_STATE_RENDER_TARGET,
&clearValue[i],
resourceNames[i],
ResourceManager::ResourceStateTrackingType::FULL_TRACKING);
RenderTargetDescriptorManager::CreateRenderTargetView(*buffers[i],
rtvDescriptor,
&bufferRenderTargetViews[i]);
}
}
}
GeometryPass::GeometryPass(GeometryCommandListRecorders& geometryPassCommandListRecorders)
: mGeometryCommandListRecorders(geometryPassCommandListRecorders)
{}
void
GeometryPass::Init(const D3D12_CPU_DESCRIPTOR_HANDLE& depthBufferView) noexcept
{
BRE_ASSERT(IsDataValid() == false);
BRE_ASSERT(mGeometryCommandListRecorders.empty() == false);
CreateGeometryBuffersAndRenderTargetViews(mGeometryBuffers, mGeometryBufferRenderTargetViews);
HeightMappingCommandListRecorder::InitSharedPSOAndRootSignature(sGeometryBufferFormats, BUFFERS_COUNT);
NormalMappingCommandListRecorder::InitSharedPSOAndRootSignature(sGeometryBufferFormats, BUFFERS_COUNT);
TextureMappingCommandListRecorder::InitSharedPSOAndRootSignature(sGeometryBufferFormats, BUFFERS_COUNT);
InitShaderResourceViews();
// Init geometry command list recorders
for (GeometryCommandListRecorders::value_type& recorder : mGeometryCommandListRecorders) {
BRE_ASSERT(recorder.get() != nullptr);
recorder->Init(mGeometryBufferRenderTargetViews,
BUFFERS_COUNT,
depthBufferView);
}
BRE_ASSERT(IsDataValid());
}
std::uint32_t
GeometryPass::Execute(const FrameCBuffer& frameCBuffer) noexcept
{
BRE_ASSERT(IsDataValid());
const std::uint32_t geometryPassCommandListCount = static_cast<std::uint32_t>(mGeometryCommandListRecorders.size());
std::uint32_t commandListCount = geometryPassCommandListCount;
commandListCount += RecordAndPushPrePassCommandLists();
// Execute tasks
std::uint32_t grainSize{ max(1U, (geometryPassCommandListCount) / ApplicationSettings::sCpuProcessorCount) };
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, geometryPassCommandListCount, grainSize),
[&](const tbb::blocked_range<size_t>& r) {
for (size_t i = r.begin(); i != r.end(); ++i)
mGeometryCommandListRecorders[i]->RecordAndPushCommandLists(frameCBuffer);
}
);
return commandListCount;
}
bool
GeometryPass::IsDataValid() const noexcept
{
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
if (mGeometryBuffers[i] == nullptr) {
return false;
}
}
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
if (mGeometryBufferRenderTargetViews[i].ptr == 0UL) {
return false;
}
}
return mGeometryCommandListRecorders.empty() == false;
}
std::uint32_t
GeometryPass::RecordAndPushPrePassCommandLists() noexcept
{
BRE_ASSERT(IsDataValid());
ID3D12GraphicsCommandList& commandList = mPrePassCommandListPerFrame.ResetCommandListWithNextCommandAllocator(nullptr);
D3D12_RESOURCE_BARRIER barriers[BUFFERS_COUNT];
std::uint32_t barrierCount = 0UL;
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
if (ResourceStateManager::GetResourceState(*mGeometryBuffers[i]) != D3D12_RESOURCE_STATE_RENDER_TARGET) {
barriers[barrierCount] = ResourceStateManager::ChangeResourceStateAndGetBarrier(*mGeometryBuffers[i],
D3D12_RESOURCE_STATE_RENDER_TARGET);
++barrierCount;
}
}
if (barrierCount > 0UL) {
commandList.ResourceBarrier(barrierCount, barriers);
}
commandList.RSSetViewports(1U, &ApplicationSettings::sScreenViewport);
commandList.RSSetScissorRects(1U, &ApplicationSettings::sScissorRect);
float zero[4U] = { 0.0f, 0.0f, 0.0f, 0.0f };
commandList.ClearRenderTargetView(mGeometryBufferRenderTargetViews[NORMAL_ROUGHNESS], Colors::Black, 0U, nullptr);
commandList.ClearRenderTargetView(mGeometryBufferRenderTargetViews[BASECOLOR_METALNESS], zero, 0U, nullptr);
BRE_CHECK_HR(commandList.Close());
CommandListExecutor::Get().PushCommandList(commandList);
return 1U;
}
void
GeometryPass::InitShaderResourceViews() noexcept
{
D3D12_SHADER_RESOURCE_VIEW_DESC srvDescriptors[BUFFERS_COUNT]{};
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
srvDescriptors[i].Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDescriptors[i].ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srvDescriptors[i].Texture2D.MostDetailedMip = 0;
srvDescriptors[i].Texture2D.ResourceMinLODClamp = 0.0f;
srvDescriptors[i].Format = mGeometryBuffers[i]->GetDesc().Format;
srvDescriptors[i].Texture2D.MipLevels = mGeometryBuffers[i]->GetDesc().MipLevels;
}
const D3D12_GPU_DESCRIPTOR_HANDLE shaderResourceViewBegin =
CbvSrvUavDescriptorManager::CreateShaderResourceViews(mGeometryBuffers,
srvDescriptors,
BUFFERS_COUNT);
// After creating all the contiguous descriptors, we need to initialize each
// shader resource view member variables
const std::size_t descriptorHandleIncrementSize =
DirectXManager::GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
for (std::uint32_t i = 0U; i < BUFFERS_COUNT; ++i) {
mGeometryBufferShaderResourceViews[i].ptr = shaderResourceViewBegin.ptr + i * descriptorHandleIncrementSize;
}
}
} | 41.986667 | 132 | 0.659998 | nicolasbertoa |
64495b0aa5d86ae44570c2d99cb6363e1d63ca9b | 526 | cpp | C++ | Source Code/05_functions_and_random/05_06_random_seed.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | 2 | 2017-03-18T22:04:47.000Z | 2017-03-30T23:24:53.000Z | Source Code/05_functions_and_random/05_06_random_seed.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | null | null | null | Source Code/05_functions_and_random/05_06_random_seed.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | null | null | null | /*
Random seed.
*** Try and execute the program
more than once to see results.
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// Sets the seed of the random number generator.
srand(static_cast<unsigned int>(time(0)));
for (int i = 1; i <= 40; ++i) {
//int d1 = 1 + rand() % 6;
//int d2 = 1 + rand() % 6;
//cout << d1 << " " << d2 << endl;
int d1 = rand() % 10 + 11;
cout << d1 << endl;
}
cout << endl;
cin.ignore();
cin.get();
return 0;
}
| 15.470588 | 50 | 0.551331 | rushone2010 |
644e8d460bfe9f3df6be2050b0aca3fc23bf59a5 | 10,094 | cc | C++ | DEM/Src/nebula2/src/gfx2/nd3d9server_resource.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | 2 | 2017-04-30T20:24:29.000Z | 2019-02-12T08:36:26.000Z | DEM/Src/nebula2/src/gfx2/nd3d9server_resource.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | DEM/Src/nebula2/src/gfx2/nd3d9server_resource.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// nd3d9server_resource.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gfx2/nd3d9server.h"
#include "resource/nresourceserver.h"
#include "gfx2/nmesh2.h"
#include "gfx2/nd3d9mesharray.h"
#include "gfx2/nd3d9shader.h"
#include "gfx2/nd3d9occlusionquery.h"
//------------------------------------------------------------------------------
/**
Create a new shared mesh object. If the object already exists, its refcount
is increment.
@param RsrcName a resource name (used for resource sharing)
@return pointer to a nD3D9Mesh2 object
*/
nMesh2*
nD3D9Server::NewMesh(const nString& RsrcName)
{
return (nMesh2*)nResourceServer::Instance()->NewResource("nd3d9mesh", RsrcName, nResource::Mesh);
}
//------------------------------------------------------------------------------
/**
Create a new mesh array object.
@return pointer to a nD3D9MeshArray object
*/
nMeshArray*
nD3D9Server::NewMeshArray(const nString& RsrcName)
{
return (nMeshArray*)nResourceServer::Instance()->NewResource("nd3d9mesharray", RsrcName, nResource::Mesh);
}
//------------------------------------------------------------------------------
/**
Create a new shared texture object. If the object already exists, its
refcount is incremented.
@param RsrcName a resource name (used for resource sharing)
@return pointer to a nD3D9Texture2 object
*/
nTexture2*
nD3D9Server::NewTexture(const nString& RsrcName)
{
return (nTexture2*)nResourceServer::Instance()->NewResource("nd3d9texture", RsrcName, nResource::Texture);
}
//------------------------------------------------------------------------------
/**
Create a new shared shader object. If the object already exists, its
refcount is incremented.
@param RsrcName a resource name (used for resource sharing)
@return pointer to a nD3D9Shader2 object
*/
nShader2*
nD3D9Server::NewShader(const nString& RsrcName)
{
return (nShader2*)nResourceServer::Instance()->NewResource("nd3d9shader", RsrcName, nResource::Shader);
}
//------------------------------------------------------------------------------
/**
Create a new render target object.
@param RsrcName a resource name for resource sharing
@param width width of render target
@param height height of render target
@param format pixel format of render target
@param usageFlags a combination of nTexture2::Usage flags
*/
nTexture2*
nD3D9Server::NewRenderTarget(const nString& RsrcName,
int width,
int height,
nTexture2::Format format,
int usageFlags)
{
nTexture2* renderTarget = (nTexture2*)nResourceServer::Instance()->NewResource("nd3d9texture", RsrcName, nResource::Texture);
n_assert(renderTarget);
if (!renderTarget->IsLoaded())
{
n_assert(0 != (usageFlags & (nTexture2::RenderTargetColor | nTexture2::RenderTargetDepth | nTexture2::RenderTargetStencil)));
renderTarget->SetUsage(usageFlags);
renderTarget->SetWidth(width);
renderTarget->SetHeight(height);
renderTarget->SetDepth(1);
renderTarget->SetFormat(format);
renderTarget->SetType(nTexture2::TEXTURE_2D);
bool success = renderTarget->Load();
if (!success)
{
renderTarget->Release();
return 0;
}
}
return renderTarget;
}
//------------------------------------------------------------------------------
/**
Create a new occlusion query object.
@return pointer to a new occlusion query object
*/
nOcclusionQuery*
nD3D9Server::NewOcclusionQuery()
{
return n_new(nD3D9OcclusionQuery);
}
//------------------------------------------------------------------------------
/**
Create a new occlusion query object.
-19-April-07 kims Fixed not to create a new vertex declaration if the declaration
is already created one. It was moved from nd3d9mesh to nd3d9server.
The patch from Trignarion.
@return pointer to a new d3d vertex declaration.
*/
IDirect3DVertexDeclaration9*
nD3D9Server::NewVertexDeclaration(const int vertexComponentMask)
{
IDirect3DVertexDeclaration9* d3d9vdecl(0);
if (this->vertexDeclarationCache.HasKey(vertexComponentMask))
{
d3d9vdecl = this->vertexDeclarationCache.GetElement(vertexComponentMask);
d3d9vdecl->AddRef();
return d3d9vdecl;
}
const int maxElements = nMesh2::NumVertexComponents;
D3DVERTEXELEMENT9 decl[maxElements];
int curElement = 0;
int curOffset = 0;
int index;
for (index = 0; index < maxElements; index++)
{
int mask = (1<<index);
if (vertexComponentMask & mask)
{
decl[curElement].Stream = 0;
n_assert( curOffset <= int( 0xffff ) );
decl[curElement].Offset = static_cast<WORD>( curOffset );
decl[curElement].Method = D3DDECLMETHOD_DEFAULT;
switch (mask)
{
case nMesh2::Coord:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_POSITION;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Coord4:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_POSITION;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
case nMesh2::Normal:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_NORMAL;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Tangent:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_TANGENT;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Binormal:
decl[curElement].Type = D3DDECLTYPE_FLOAT3;
decl[curElement].Usage = D3DDECLUSAGE_BINORMAL;
decl[curElement].UsageIndex = 0;
curOffset += 3 * sizeof(float);
break;
case nMesh2::Color:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_COLOR;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
case nMesh2::Uv0:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 0;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Uv1:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 1;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Uv2:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 2;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Uv3:
decl[curElement].Type = D3DDECLTYPE_FLOAT2;
decl[curElement].Usage = D3DDECLUSAGE_TEXCOORD;
decl[curElement].UsageIndex = 3;
curOffset += 2 * sizeof(float);
break;
case nMesh2::Weights:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_BLENDWEIGHT;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
case nMesh2::JIndices:
decl[curElement].Type = D3DDECLTYPE_FLOAT4;
decl[curElement].Usage = D3DDECLUSAGE_BLENDINDICES;
decl[curElement].UsageIndex = 0;
curOffset += 4 * sizeof(float);
break;
default:
n_error("Unknown vertex component in vertex component mask");
break;
}
curElement++;
}
}
// write vertex declaration terminator element, see D3DDECL_END() macro in d3d9types.h for details
decl[curElement].Stream = 0xff;
decl[curElement].Offset = 0;
decl[curElement].Type = D3DDECLTYPE_UNUSED;
decl[curElement].Method = 0;
decl[curElement].Usage = 0;
decl[curElement].UsageIndex = 0;
//n_dxverify(//gfxServer->pD3D9Device->CreateVertexDeclaration(decl, &(this->vertexDeclaration)),
HRESULT hr = this->pD3D9Device->CreateVertexDeclaration(decl, &d3d9vdecl);
d3d9vdecl->AddRef();
this->vertexDeclarationCache.Add(vertexComponentMask, d3d9vdecl);
return d3d9vdecl;
}
| 38.67433 | 134 | 0.518526 | moltenguy1 |
6450ffd44849c9ecceaac140a9e4e85d496b960b | 4,721 | hpp | C++ | include/mmu/api/utils.hpp | RUrlus/ModelMetricUncertainty | f401a25dd196d6e4edf4901fcfee4b56ebd7c10b | [
"Apache-2.0"
] | null | null | null | include/mmu/api/utils.hpp | RUrlus/ModelMetricUncertainty | f401a25dd196d6e4edf4901fcfee4b56ebd7c10b | [
"Apache-2.0"
] | 11 | 2021-12-08T10:34:17.000Z | 2022-01-20T13:40:05.000Z | include/mmu/api/utils.hpp | RUrlus/ModelMetricUncertainty | f401a25dd196d6e4edf4901fcfee4b56ebd7c10b | [
"Apache-2.0"
] | null | null | null | /* utils.hpp -- Utility function around type checking of py::array_t
* Copyright 2022 Ralph Urlus
*/
#ifndef INCLUDE_MMU_API_UTILS_HPP_
#define INCLUDE_MMU_API_UTILS_HPP_
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <string>
#include <mmu/api/numpy.hpp>
#include <mmu/core/common.hpp>
namespace py = pybind11;
namespace mmu {
namespace api {
namespace details {
/* Check if arr is 1D or two 1D with the second axis containing a single index.
* I.e. arr.shape ==
* * (n, )
* * (1, n)
* * (n, 1)
*
* Throws RuntimeError if condition is not met.
*
* --- Parameters ---
* - arr : the array to validate
* - name : the name of the parameter
*/
template <typename T>
inline int check_1d_soft(const py::array_t<T>& arr, const std::string& name) {
ssize_t n_dim = arr.ndim();
if (n_dim == 1) {
return 0;
}
if (n_dim == 2) {
if (arr.shape(1) == 1) {
return 0;
}
if (arr.shape(0) == 1) {
return 1;
}
}
throw std::runtime_error(name + " should be one dimensional");
}
/* Check x and y have the same length where we account for row and column orientation.
* We only consider the obs_axis_ for each array, the obs_axis_ is the 0 for an array shaped (n, m)
*
* Throws RuntimeError if condition is not met.
*/
template <typename T, typename V>
inline void check_equal_length(
const py::array_t<T>& x,
const py::array_t<V>& y,
const std::string& x_name,
const std::string& y_name,
const int obs_axis_x = 0,
const int obs_axis_y = 0) {
if (x.shape(obs_axis_x) != y.shape(obs_axis_y)) {
throw std::runtime_error(x_name + " and " + y_name + " should have equal number of observations");
}
}
template <typename T>
inline void check_contiguous(const py::array_t<T>& arr, const std::string& name) {
if (!npy::is_contiguous<T>(arr)) {
throw std::runtime_error(name + " should be C or F contiguous");
}
}
template <typename T, typename V>
inline void check_equal_shape(
const py::array_t<T>& x,
const py::array_t<V>& y,
const std::string& x_name,
const std::string& y_name) {
int x_dim = x.ndim();
int y_dim = y.ndim();
int pass = 0;
if (x_dim == y_dim) {
for (int i = 0; i < x_dim; i++) {
pass += x.shape(i) == y.shape(i);
}
}
if (pass != x_dim) {
throw std::runtime_error(x_name + " and " + y_name + " should have equal shape");
}
}
/* Check if order matches shape of the array and copy otherwhise.
* We expect the observations (rows or columns) to be contiguous in memory.
*
* --- Parameters ---
* - arr : the array to validate
* - name : the name of the parameter
*
* --- Returns ---
* - arr : the input array or the input array with the correct memory order
*/
template <typename T>
inline py::array_t<T> ensure_shape_order(py::array_t<T>& arr, const std::string& name, const int obs_axis = 0) {
const ssize_t n_dim = arr.ndim();
if (n_dim > 2) {
throw std::runtime_error(name + " must be at most two dimensional.");
}
if (obs_axis == 0) {
if (!is_f_contiguous(arr)) {
return py::array_t<T, py::array::f_style | py::array::forcecast>(arr);
}
return arr;
} else if (obs_axis == 1) {
if (!is_c_contiguous(arr)) {
return py::array_t<T, py::array::c_style | py::array::forcecast>(arr);
}
return arr;
} else {
throw std::runtime_error("``obs_axis`` must be zero or one.");
}
} // ensure_shape_order
/* Check if order matches shape of the array and the shape is as expected.
* We expect the observations (rows or columns) to be contiguous in memory.
*
* Array can be one or two dimensional.
* - If 1D it should have size == ``expected``
* - If 2D it should be:
* * C-Contiguous if shape (n, ``expected``)
* * F-Contiguous if shape (``expected``, n)
*
* --- Parameters ---
* - arr : the array to validate
* - name : the name of the parameter
* - expected : the size we expect of one the two dimensions to have
*/
template <typename T>
inline bool is_correct_shape_order(const py::array_t<T>& arr, ssize_t expected) {
ssize_t n_dim = arr.ndim();
bool state = false;
if (n_dim == 1 && arr.size() == expected) {
state = npy::is_c_contiguous(arr);
} else if (n_dim == 2) {
if (arr.shape(1) == expected) {
state = is_c_contiguous(arr);
} else if (arr.shape(0) == expected) {
state = is_f_contiguous(arr);
}
}
return state;
} // check_shape_order
} // namespace details
} // namespace api
} // namespace mmu
#endif // INCLUDE_MMU_API_UTILS_HPP_
| 29.50625 | 112 | 0.614912 | RUrlus |
645d06e94c928595ffdfe90ae8908889e0a7b7e2 | 15,349 | cpp | C++ | cocos2d/cocos/cornell/CUCapsuleObstacle.cpp | Mshnik/Pineapple | 378917353d22d8497769ed8e45d9a73b40d2717e | [
"MIT"
] | null | null | null | cocos2d/cocos/cornell/CUCapsuleObstacle.cpp | Mshnik/Pineapple | 378917353d22d8497769ed8e45d9a73b40d2717e | [
"MIT"
] | null | null | null | cocos2d/cocos/cornell/CUCapsuleObstacle.cpp | Mshnik/Pineapple | 378917353d22d8497769ed8e45d9a73b40d2717e | [
"MIT"
] | 1 | 2019-12-25T02:32:13.000Z | 2019-12-25T02:32:13.000Z | //
// CUCapsuleObstacle.cpp
// Cornell Extensions to Cocos2D
//
// This class implements a capsule physics object. A capsule is a box with semicircular
// ends along the major axis. They are a popular physics objects, particularly for
// character avatars. The rounded ends means they are less likely to snag, and they
// naturally fall off platforms when they go too far.
//
// This file is based on the CS 3152 PhysicsDemo Lab by Don Holden, 2007
//
// Author: Walker White
// Version: 11/24/15
//
#include "CUCapsuleObstacle.h"
NS_CC_BEGIN
/** How many line segments to use to draw a circle */
#define BODY_DEBUG_SEGS 12
/** Epsilon factor to prevent issues with the fixture seams */
#define DEFAULT_EPSILON 0.01
#pragma mark -
#pragma mark Static Constructors
/**
* Creates a new capsule object at the origin with no size.
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create() {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init()) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
/**
* Creates a new capsule object at the given point with no size.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create(const Vec2& pos) {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init(pos)) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
/**
* Creates a new capsule object of the given dimensions.
*
* The orientation of the capsule will be a full capsule along the
* major axis. If width == height, it will default to a vertical
* orientation.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The capsule size (width and height)
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create(const Vec2& pos, const Size& size) {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init(pos,size)) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
/**
* Creates a new capsule object of the given dimensions and orientation.
*
* The orientation must be consistent with the major axis (or else the
* two axes must be the same). If the orientation specifies a minor axis,
* then this constructor will return null.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The capsule size (width and height)
* @param orient The capsule orientation
*
* @return An autoreleased physics object
*/
CapsuleObstacle* CapsuleObstacle::create(const Vec2& pos, const Size& size, CapsuleObstacle::Orientation orient) {
CapsuleObstacle* capsule = new (std::nothrow) CapsuleObstacle();
if (capsule && capsule->init(pos,size,orient)) {
capsule->autorelease();
return capsule;
}
CC_SAFE_DELETE(capsule);
return nullptr;
}
#pragma mark -
#pragma mark Initialization Methods
/**
* Initializes a new capsule object of the given dimensions.
*
* The orientation of the capsule will be a full capsule along the
* major axis. If width == height, it will default to a vertical
* orientation.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The box size (width and height)
*
* @return true if the obstacle is initialized properly, false otherwise.
*/
bool CapsuleObstacle::init(const Vec2& pos, const Size& size) {
Orientation orient = (size.width > size.height ? Orientation::HORIZONTAL : Orientation::VERTICAL);
return init(pos,size,orient);
}
/**
* Initializes a new capsule object of the given dimensions.
*
* The orientation must be consistent with the major axis (or else the
* two axes must be the same). If the orientation specifies a minor axis,
* then this initializer will fail.
*
* The scene graph is completely decoupled from the physics system.
* The node does not have to be the same size as the physics body. We
* only guarantee that the scene graph node is positioned correctly
* according to the drawing scale.
*
* @param pos Initial position in world coordinates
* @param size The box size (width and height)
*
* @return true if the obstacle is initialized properly, false otherwise.
*/
bool CapsuleObstacle::init(const Vec2& pos, const Size& size, CapsuleObstacle::Orientation orient) {
Obstacle::init(pos);
_core = nullptr;
_cap1 = nullptr;
_cap2 = nullptr;
_orient = orient;
_seamEpsilon = DEFAULT_EPSILON;
resize(size);
return true;
}
#pragma mark -
#pragma mark Scene Graph Methods
/**
* Resets the polygon vertices in the shape to match the dimension.
*
* @param size The new dimension (width and height)
*/
bool CapsuleObstacle::resize(const Size& size) {
_dimension = size;
if (size.width < size.height && isHorizontal(_orient)) {
_orient = Orientation::VERTICAL; // OVERRIDE
} else if (size.width > size.height && !isHorizontal(_orient)) {
_orient = Orientation::HORIZONTAL; // OVERRIDE
}
// Get an AABB for the core
_center.upperBound.x = size.width/2.0f;
_center.upperBound.y = size.height/2.0f;
_center.lowerBound.x = -size.width/2.0f;
_center.lowerBound.y = -size.height/2.0f;
// Now adjust the core
float r = 0;
switch (_orient) {
case Orientation::TOP:
r = size.width/2.0f;
_center.upperBound.y -= r;
_center.lowerBound.x += _seamEpsilon;
_center.upperBound.x -= _seamEpsilon;
break;
case Orientation::VERTICAL:
r = size.width/2.0f;
_center.upperBound.y -= r;
_center.lowerBound.y += r;
_center.lowerBound.x += _seamEpsilon;
_center.upperBound.x -= _seamEpsilon;
break;
case Orientation::BOTTOM:
r = size.width/2.0f;
_center.lowerBound.y += r;
_center.lowerBound.x += _seamEpsilon;
_center.upperBound.x -= _seamEpsilon;
break;
case Orientation::LEFT:
r = size.height/2.0f;
_center.upperBound.x -= r;
_center.lowerBound.y += _seamEpsilon;
_center.upperBound.y -= _seamEpsilon;
break;
case Orientation::HORIZONTAL:
r = size.height/2.0f;
_center.upperBound.x -= r;
_center.lowerBound.x += r;
_center.lowerBound.y += _seamEpsilon;
_center.upperBound.y -= _seamEpsilon;
break;
case Orientation::RIGHT:
r = size.height/2.0f;
_center.lowerBound.x += r;
_center.lowerBound.y += _seamEpsilon;
_center.upperBound.y -= _seamEpsilon;
break;
}
// Handle degenerate polys
if (_center.lowerBound.x == _center.upperBound.x) {
_center.lowerBound.x -= _seamEpsilon;
_center.upperBound.x += _seamEpsilon;
}
if (_center.lowerBound.y == _center.upperBound.y) {
_center.lowerBound.y -= _seamEpsilon;
_center.upperBound.y += _seamEpsilon;
}
// Make the box for the core
b2Vec2 corners[4];
corners[0].x = _center.lowerBound.x;
corners[0].y = _center.lowerBound.y;
corners[1].x = _center.lowerBound.x;
corners[1].y = _center.upperBound.y;
corners[2].x = _center.upperBound.x;
corners[2].y = _center.upperBound.y;
corners[3].x = _center.upperBound.x;
corners[3].y = _center.lowerBound.y;
_shape.Set(corners, 4);
_ends.m_radius = r;
if (_debug != nullptr) {
resetDebugNode();
}
return true;
}
/**
* Redraws the outline of the physics fixtures to the debug node
*
* The debug node is use to outline the fixtures attached to this object.
* This is very useful when the fixtures have a very different shape than
* the texture (e.g. a circular shape attached to a square texture).
*
* Unfortunately, the current implementation is very inefficient. Cocos2d
* does not batch drawnode commands like it does Sprites or PolygonSprites.
* Therefore, every distinct DrawNode is a distinct OpenGL call. This can
* really hurt framerate when debugging mode is on. Ideally, we would refactor
* this so that we only draw to a single, master draw node. However, this
* means that we would have to handle our own vertex transformations, instead
* of relying on the transforms in the scene graph.
*/
void CapsuleObstacle::resetDebugNode() {
Rect bounds;
// Create a capsule polygon
const float coef = (float)M_PI/BODY_DEBUG_SEGS;
float rx = _ends.m_radius*_drawScale.x;
float ry = _ends.m_radius*_drawScale.y;
std::vector<Vec2> vertices;
Vec2 vert;
// Start at top left corner
vert.x = _center.lowerBound.x*_drawScale.x;
vert.y = _center.upperBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::TOP || _orient == Orientation::VERTICAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = M_PI-ii*coef;
vert.x = rx * cosf(rads);
vert.y = ry * sinf(rads) + _center.upperBound.y*_drawScale.y;
vertices.push_back(vert);
}
}
// Next corner
vert.x = _center.upperBound.x*_drawScale.x;
vert.y = _center.upperBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::RIGHT || _orient == Orientation::HORIZONTAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = M_PI/2-ii*coef;
vert.x = rx * cosf(rads) + _center.upperBound.x*_drawScale.x;
vert.y = ry * sinf(rads);
vertices.push_back(vert);
}
}
// Next corner
vert.x = _center.upperBound.x*_drawScale.x;
vert.y = _center.lowerBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::BOTTOM || _orient == Orientation::VERTICAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = 2*M_PI-ii*coef;
vert.x = rx * cosf(rads);
vert.y = ry * sinf(rads) + _center.lowerBound.y*_drawScale.y;
vertices.push_back(vert);
}
}
// Next corner
vert.x = _center.lowerBound.x*_drawScale.x;
vert.y = _center.lowerBound.y*_drawScale.y;
vertices.push_back(vert);
// Fan if necessary
if (_orient == Orientation::LEFT || _orient == Orientation::HORIZONTAL) {
for(unsigned int ii = 1; ii < BODY_DEBUG_SEGS; ii++) {
float rads = 3*M_PI/2-ii*coef;
vert.x = rx * cosf(rads) + _center.lowerBound.x*_drawScale.x;
vert.y = ry * sinf(rads);
vertices.push_back(vert);
}
}
// Create polygon
Poly2 poly(vertices);
poly.traverse(Poly2::Traversal::CLOSED);
_debug->setPolygon(poly);
}
#pragma mark -
#pragma mark Physics Methods
/**
* Sets the density of this body
*
* The density is typically measured in usually in kg/m^2. The density can be zero or
* positive. You should generally use similar densities for all your fixtures. This
* will improve stacking stability.
*
* @param value the density of this body
*/
void CapsuleObstacle::setDensity(float value) {
_fixture.density = value;
if (_body != nullptr) {
_core->SetDensity(value);
_cap1->SetDensity(value/2.0f);
_cap2->SetDensity(value/2.0f);
if (!_masseffect) {
_body->ResetMassData();
}
}
}
/**
* Create new fixtures for this body, defining the shape
*
* This is the primary method to override for custom physics objects
*/
void CapsuleObstacle::createFixtures() {
if (_body == nullptr) {
return;
}
releaseFixtures();
// Create the fixture
_fixture.shape = &_shape;
_core = _body->CreateFixture(&_fixture);
_fixture.density = _fixture.density/2.0f;
_ends.m_p.Set(0, 0);
switch (_orient) {
case Orientation::TOP:
_ends.m_p.y = _center.upperBound.y;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
case Orientation::VERTICAL:
_ends.m_p.y = _center.upperBound.y;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_ends.m_p.y = _center.lowerBound.y;
_fixture.shape = &_ends;
_cap2 = _body->CreateFixture(&_fixture);
break;
case Orientation::BOTTOM:
_ends.m_p.y = _center.lowerBound.y;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
case Orientation::LEFT:
_ends.m_p.x = _center.lowerBound.x;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
case Orientation::HORIZONTAL:
_ends.m_p.x = _center.lowerBound.x;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_ends.m_p.x = _center.upperBound.x;
_fixture.shape = &_ends;
_cap2 = _body->CreateFixture(&_fixture);
break;
case Orientation::RIGHT:
_ends.m_p.x = _center.upperBound.x;
_fixture.shape = &_ends;
_cap1 = _body->CreateFixture(&_fixture);
_cap2 = nullptr;
break;
}
markDirty(false);
}
/**
* Release the fixtures for this body, reseting the shape
*
* This is the primary method to override for custom physics objects
*/
void CapsuleObstacle::releaseFixtures() {
if (_core != nullptr) {
_body->DestroyFixture(_core);
_core = nullptr;
}
if (_cap1 != nullptr) {
_body->DestroyFixture(_cap1);
_cap1 = nullptr;
}
if (_cap2 != nullptr) {
_body->DestroyFixture(_cap2);
_cap2 = nullptr;
}
}
NS_CC_END | 32.727079 | 114 | 0.640302 | Mshnik |
646165866984e4c015898cbcc1d64dd6cdada5b7 | 7,010 | cpp | C++ | test/performance/distance.cpp | lf-shaw/operon | 09a6ac1932d552b8be505f235318e50e923b0da1 | [
"MIT"
] | 50 | 2020-10-14T10:08:21.000Z | 2022-03-10T12:55:05.000Z | test/performance/distance.cpp | lf-shaw/operon | 09a6ac1932d552b8be505f235318e50e923b0da1 | [
"MIT"
] | 16 | 2020-10-26T13:05:47.000Z | 2022-02-22T20:24:41.000Z | test/performance/distance.cpp | lf-shaw/operon | 09a6ac1932d552b8be505f235318e50e923b0da1 | [
"MIT"
] | 16 | 2020-10-26T13:05:38.000Z | 2022-01-14T02:52:13.000Z | // SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research
#include <doctest/doctest.h>
#include "core/dataset.hpp"
#include "core/format.hpp"
#include "core/metrics.hpp"
#include "core/distance.hpp"
#include "core/pset.hpp"
#include "analyzers/diversity.hpp"
#include "operators/creator.hpp"
#include "nanobench.h"
namespace Operon {
namespace Test {
template<typename Callable>
struct ComputeDistanceMatrix {
explicit ComputeDistanceMatrix(Callable&& f)
: f_(f) { }
template<typename T>
inline double operator()(std::vector<Operon::Vector<T>> const& hashes) const noexcept
{
double d = 0;
for (size_t i = 0; i < hashes.size() - 1; ++i) {
for (size_t j = i+1; j < hashes.size(); ++j) {
d += static_cast<double>(Operon::Distance::CountIntersect(hashes[i], hashes[j]));
}
}
return d;
}
Callable f_;
};
TEST_CASE("Intersection performance")
{
size_t n = 1000;
size_t maxLength = 200;
size_t maxDepth = 1000;
Operon::RandomGenerator rd(1234);
auto ds = Dataset("../data/Poly-10.csv", true);
auto target = "Y";
auto variables = ds.Variables();
std::vector<Variable> inputs;
std::copy_if(variables.begin(), variables.end(), std::back_inserter(inputs), [&](const auto& v) { return v.Name != target; });
std::uniform_int_distribution<size_t> sizeDistribution(1, maxLength);
PrimitiveSet grammar;
grammar.SetConfig(PrimitiveSet::Arithmetic | NodeType::Exp | NodeType::Log);
std::vector<Tree> trees(n);
auto btc = BalancedTreeCreator { grammar, inputs };
std::generate(trees.begin(), trees.end(), [&]() { return btc(rd, sizeDistribution(rd), 0, maxDepth); });
std::vector<Operon::Vector<Operon::Hash>> hashesStrict(trees.size());
std::vector<Operon::Vector<Operon::Hash>> hashesStruct(trees.size());
std::vector<Operon::Vector<uint32_t>> hashesStrict32(trees.size());
std::vector<Operon::Vector<uint32_t>> hashesStruct32(trees.size());
const auto hashFunc = [](auto& tree, Operon::HashMode mode) { return MakeHashes<Operon::HashFunction::XXHash>(tree, mode); };
std::transform(trees.begin(), trees.end(), hashesStrict.begin(), [&](Tree tree) { return hashFunc(tree, Operon::HashMode::Strict); });
std::transform(trees.begin(), trees.end(), hashesStruct.begin(), [&](Tree tree) { return hashFunc(tree, Operon::HashMode::Relaxed); });
auto convertVec = [](Operon::Vector<Operon::Hash> const& vec) {
Operon::Vector<uint32_t> vec32(vec.size());
std::transform(vec.begin(), vec.end(), vec32.begin(), [](auto h) { return (uint32_t)h; });
pdqsort(vec32.begin(), vec32.end());
return vec32;
};
std::transform(hashesStrict.begin(), hashesStrict.end(), hashesStrict32.begin(), convertVec);
std::transform(hashesStruct.begin(), hashesStruct.end(), hashesStruct32.begin(), convertVec);
std::uniform_int_distribution<size_t> dist(0u, trees.size()-1);
auto avgLen = std::transform_reduce(trees.begin(), trees.end(), 0.0, std::plus<>{}, [](auto const& t) { return t.Length(); }) / (double)n;
auto totalOps = trees.size() * (trees.size() - 1) / 2;
SUBCASE("Performance 64-bit") {
ankerl::nanobench::Bench b;
b.performanceCounters(true).relative(true);
auto s = (double)totalOps * avgLen;
double d = 0;
b.batch(s).run("intersect str[i]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict);
});
b.batch(s).run("intersect str[u]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct);
});
b.batch(s).run("jaccard str[i]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict);
});
b.batch(s).run("jaccard str[u]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct);
});
b.batch(s).run("jaccard str[i]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict);
});
b.batch(s).run("jaccard str[u]ct", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct);
});
}
SUBCASE("Performance 32-bit") {
ankerl::nanobench::Bench b;
b.performanceCounters(true).relative(true);
auto s = (double)totalOps * avgLen;
double d = 0;
b.batch(s).run("intersect str[i]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict32);
});
b.batch(s).run("intersect str[u]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::CountIntersect(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct32);
});
b.batch(s).run("jaccard str[i]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict32);
});
b.batch(s).run("jaccard str[u]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::Jaccard(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct32);
});
b.batch(s).run("jaccard str[i]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStrict32);
});
b.batch(s).run("jaccard str[u]ct 32", [&](){
auto f = [](auto const& lhs, auto const& rhs) { return Operon::Distance::SorensenDice(lhs, rhs); };
ComputeDistanceMatrix<decltype(f)> cdm(std::move(f));
d = cdm(hashesStruct32);
});
}
}
} // namespace Test
} // namespace Operon
| 39.162011 | 142 | 0.592297 | lf-shaw |
646196d8165d1709d1abeb6227ea4bde32c737ae | 193 | hpp | C++ | missions/12_A2CO_COOP_USMC_vs_GUE.lingor/ambience/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | missions/12_A2CO_COOP_USMC_vs_GUE.lingor/ambience/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | missions/12_A2CO_COOP_USMC_vs_GUE.lingor/ambience/modules/modules.hpp | amlr/Multi-Session-Operations | ebfa0520a151fb27ff79fa74b17548f8560ed0a9 | [
"Apache-2.0"
] | null | null | null | #define CRB_CIVILIANS
//#define CRB_DOGS
//#define CRB_EMERGENCY
//#define CRB_SHEPHERDS
//#define RMM_CTP
#define TUP_AIRTRAFFIC
#define TUP_SEATRAFFIC
//#define CRB_DESTROYCITY
//#define AEG
| 19.3 | 25 | 0.797927 | amlr |
6462b05d02741f58aa4986cbd534e071369dd649 | 273 | cpp | C++ | src/GameState.cpp | kurogit/arduino_pong | 1f16d8c9b90f5c7e75dbbf5cc1400f1e093208f6 | [
"MIT"
] | null | null | null | src/GameState.cpp | kurogit/arduino_pong | 1f16d8c9b90f5c7e75dbbf5cc1400f1e093208f6 | [
"MIT"
] | null | null | null | src/GameState.cpp | kurogit/arduino_pong | 1f16d8c9b90f5c7e75dbbf5cc1400f1e093208f6 | [
"MIT"
] | null | null | null | /*!
* \file
* \details This file is part of https://github.com/kurogit/arduino_pong which is licensed under the MIT License.
* \copyright 2016 Patrick Schwartz <[email protected]>
*/
#include "GameState.hpp"
namespace arduino_pong
{
} // namespace arduino_pong
| 21 | 113 | 0.736264 | kurogit |
647285c31cbc3b417b3305e3c8a46ae8e24c48c3 | 1,467 | cpp | C++ | 2017-08-22/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 3 | 2018-04-02T06:00:51.000Z | 2018-05-29T04:46:29.000Z | 2017-08-22/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-03-31T17:54:30.000Z | 2018-05-02T11:31:06.000Z | 2017-08-22/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-10-07T00:08:06.000Z | 2021-06-28T11:02:59.000Z | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int LMAX = 2600;
int T, N, M;
char A[LMAX], B[LMAX];
bool star[LMAX];
bool f[LMAX][LMAX][2];
bool match(char x, char y)
{
if(x == '.' || y == '.')
return true;
return x == y;
}
int main()
{
int t, i, j, k;
scanf("%d", &T);
for(t = 0;t < T;t += 1)
{
memset(f, 0, sizeof(f));
memset(star, 0, sizeof(star));
scanf("%s %s", A + 1, B + 1);
N = strlen(A + 1);
M = strlen(B + 1);
for(i = 1, j = 0;i <= M;i += 1)
{
if(B[i] == '*')
{
star[j] = true;
continue;
}
B[++j] = B[i];
}
M = j;
f[0][0][0] = true;
for(i = 0;i <= N;i += 1)
{
for(j = 0;j <= M;j += 1)
{
for(k = 0;k < 2;k += 1)
{
if(!f[i][j][k])
continue;
//printf("f[%d][%d][%d]\n", i, j, k);
if(j + 1 <= M)
{
if(i + 1 <= N)
{
if((!star[j + 1] || !k) && match(A[i + 1], B[j + 1]))
{
//printf("1 to %d %d %d\n", i + 1, j + 1, 0);
f[i + 1][j + 1][0] = true;
}
if(star[j + 1] && ((k && match(A[i + 1], A[i])) || (!k && match(A[i + 1], B[j + 1]))))
{
//printf("2 to %d %d %d\n", i + 1, j, 1);
f[i + 1][j][1] = true;
}
}
if(star[j + 1])
{
//printf("3 to %d %d %d\n", i, j + 1, 0);
f[i][j + 1][0] = true;
}
}
}
}
}
printf("%s\n", (f[N][M][0] || f[N][M][1])?"yes":"no");
}
exit(0);
}
| 18.111111 | 93 | 0.373551 | tangjz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.