hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6e85a589eb29cbcf2186b8f43bc18e1b3056ecf | 1,012 | cpp | C++ | infoarena/progr/main.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | 1 | 2017-01-25T18:07:49.000Z | 2017-01-25T18:07:49.000Z | infoarena/progr/main.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | infoarena/progr/main.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define N 2001
#define MOD 123567
using namespace std;
int t,n,a;
int tab[N];
vector<int> v[MOD];
void add(int val)
{
int k=val%MOD;
v[k].push_back(val);
}
int search(int val)
{
int k=val%MOD;
for(unsigned int i=0;i<v[k].size();++i)
if(v[k][i]==val)
return 1;
return 0;
}
void erase()
{
for(int i=0;i<MOD;++i)
v[i].clear();
}
int main()
{
freopen("progr.in","r",stdin);
freopen("progr.out","w",stdout);
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>t;
while(t--)
{
cin>>n;
for(int i=0;i<n;++i)
{
cin>>tab[i];
add(tab[i]);
}
sort(tab,tab+n);
int ans=0;
for(int i=0;i<n;++i)
{
int a=tab[i];
for(int j=i+1;j<n;++j)
{
if(!search((tab[j]<<1)-a))
ans++;
}
}
cout<<ans<<"\n";
erase();
}
return 0;
} | 16.590164 | 43 | 0.421937 | [
"vector"
] |
b6ea00a994742c55a52e03dfcd5c2d06e5d61a42 | 623 | cpp | C++ | leetcode/2020/december/practice/1089-DuplicateZeros.cpp | pol-alok/Solvify | c0f3913420a4a3a3faa34848038a3cc942628b08 | [
"MIT"
] | null | null | null | leetcode/2020/december/practice/1089-DuplicateZeros.cpp | pol-alok/Solvify | c0f3913420a4a3a3faa34848038a3cc942628b08 | [
"MIT"
] | null | null | null | leetcode/2020/december/practice/1089-DuplicateZeros.cpp | pol-alok/Solvify | c0f3913420a4a3a3faa34848038a3cc942628b08 | [
"MIT"
] | 2 | 2021-02-23T06:54:22.000Z | 2021-02-28T15:37:23.000Z | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
vector<int> ans;
int count=0;
for(int num : arr) {
if(num==0) {
ans.push_back(0);
count++;
}
ans.push_back(num);
}
while (count--){
ans.pop_back();
}
arr = move(ans);
}
};
int main () {
vector<int> arr{1,0,2,0,3,4,5,0};
Solution solution;
solution.duplicateZeros(arr);
for(int num : arr) {
cout << num << " ";
}
return 0;
} | 18.878788 | 43 | 0.467095 | [
"vector"
] |
b6eac0377c6fe81b2f01df49016681c4f931f4ea | 1,081 | cpp | C++ | engine/core/3D/New3D/CollisionHandler.cpp | TremaineDM/Engines | 88dacaddc633ad341b9a2559a9a80b9dd01b09de | [
"MIT"
] | 1 | 2020-10-16T06:39:35.000Z | 2020-10-16T06:39:35.000Z | engine/core/3D/New3D/CollisionHandler.cpp | TremaineDM/Engines | 88dacaddc633ad341b9a2559a9a80b9dd01b09de | [
"MIT"
] | null | null | null | engine/core/3D/New3D/CollisionHandler.cpp | TremaineDM/Engines | 88dacaddc633ad341b9a2559a9a80b9dd01b09de | [
"MIT"
] | 2 | 2021-02-10T21:28:59.000Z | 2021-04-19T07:34:43.000Z | #include "CollisionHandler.h"
#include "../Core/CoreEngine.h"
#include "core/Globals.h"
std::unique_ptr<CollisionHandler> CollisionHandler::collisionInstance = nullptr;
std::vector<MeshRenderer*> CollisionHandler::prevCollisions = std::vector<MeshRenderer*>();
OctSpatialPartition* CollisionHandler::scenePartition = nullptr;
CollisionHandler::CollisionHandler() {
prevCollisions.reserve(10);
}
CollisionHandler::~CollisionHandler() {
OnDestroy();
}
CollisionHandler* CollisionHandler::GetInstance() {
if (collisionInstance.get() == nullptr) {
collisionInstance.reset(new CollisionHandler);
}
return collisionInstance.get();
}
void CollisionHandler::OnCreate(float worldSize_) {
prevCollisions.clear();
scenePartition = new OctSpatialPartition(worldSize_);
}
void CollisionHandler::OnDestroy() {
delete scenePartition;
scenePartition = nullptr;
for (auto* entry : prevCollisions) {
entry = nullptr;
}
prevCollisions.clear();
}
void CollisionHandler::AddObject(MeshRenderer* go_) {
if (scenePartition != nullptr) {
scenePartition->AddObject(go_);
}
}
| 24.022222 | 91 | 0.763182 | [
"vector"
] |
b6f0fd28a9f3fe9f8c2958debd05a9afc5859886 | 16,447 | hpp | C++ | example/graphical_model.hpp | vlanore/tinycompo | c7acf325c84b68ec91eaf937ad49f17281e84079 | [
"CECILL-B"
] | null | null | null | example/graphical_model.hpp | vlanore/tinycompo | c7acf325c84b68ec91eaf937ad49f17281e84079 | [
"CECILL-B"
] | null | null | null | example/graphical_model.hpp | vlanore/tinycompo | c7acf325c84b68ec91eaf937ad49f17281e84079 | [
"CECILL-B"
] | null | null | null | /* Copyright or © or Copr. Centre National de la Recherche Scientifique (CNRS) (2017/05/03)
Contributors:
- Vincent Lanore <vincent.lanore@gmail.com>
This software is a computer program whose purpose is to provide the necessary classes to write ligntweight component-based
c++ applications.
This software is governed by the CeCILL-B license under French law and abiding by the rules of distribution of free software.
You can use, modify and/ or redistribute the software under the terms of the CeCILL-B license as circulated by CEA, CNRS and
INRIA at the following URL "http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users
are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive
licensors have only limited liability.
In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or
reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated
to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth
computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements
in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in
the same conditions as regards security.
The fact that you are presently reading this means that you have had knowledge of the CeCILL-B license and that you accept
its terms.*/
#ifndef GRAPHICAL_MODEL
#define GRAPHICAL_MODEL
#include <algorithm>
#include <fstream>
#include <functional>
#include <random>
#include "tinycompo.hpp"
using namespace std;
using namespace tc;
int factorial(int n) {
if (n < 2) {
return 1;
} else {
return n * factorial(n - 1);
}
}
template <typename... Args>
std::string sf(const std::string &format, Args... args) {
size_t size = snprintf(nullptr, 0, format.c_str(), args...) + 1;
std::unique_ptr<char[]> buf(new char[size]);
snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1);
}
std::random_device r;
std::default_random_engine generator(r());
std::uniform_real_distribution<double> uniform{0.0, 1.0};
/*
===================================================================================================
INTERFACES
=================================================================================================*/
struct Go : public Component {
Go() { port("go", &Go::go); }
virtual void go() = 0;
};
struct Move : public Go {}; // for typing purposes only
struct Sampler : public Go {
virtual std::vector<double> getSample() const = 0;
virtual std::string getVarList() const = 0;
};
struct Real : public Component {
virtual double getValue() const = 0;
virtual void setValue(double value) = 0;
};
struct LogDensity {
virtual double log_density() const = 0;
};
struct AbstractSuffStats : public LogDensity {
virtual void corrupt() const = 0;
};
class RandomNode : public Real, public LogDensity {
double clampedVal{0.0};
public:
RandomNode() = default;
virtual void sample() = 0;
void clamp(double val) {
is_clamped = true;
clampedVal = val;
}
double clamped_value() const { return clampedVal; }
virtual bool is_consistent() const { return clampedVal == getValue(); }
bool is_clamped{false};
};
class DataStream {
public:
virtual void header(const std::string &str) = 0;
virtual void dataLine(const std::vector<double> &line) = 0;
};
/*
===================================================================================================
Helper classes
=================================================================================================*/
class ConsoleOutput : public Component, public DataStream {
public:
std::string debug() const override { return "ConsoleOutput"; }
void header(const std::string &str) override { std::cout << str << std::endl; }
void dataLine(const std::vector<double> &line) override {
std::for_each(line.begin(), line.end(), [](double e) { std::cout << e << " "; });
std::cout << std::endl;
}
};
class FileOutput : public Component, public DataStream {
std::ofstream file{};
std::string filename;
public:
explicit FileOutput(const std::string &filename) : filename(filename) { file.open(filename); }
~FileOutput() { file.close(); }
std::string debug() const override { return sf("FileOutput(%s)", filename.c_str()); }
void header(const std::string &str) override { file << str << std::endl; }
void dataLine(const std::vector<double> &line) override {
std::for_each(line.begin(), line.end(), [this](double e) { file << e << "\t"; });
file << std::endl;
}
};
// little object to encapsulate having a constant OR a pointer to Real
class RealProp {
int mode{0}; // 0:unset, 1:constant, 2:pointer
Real *ptr{nullptr};
double value{0};
public:
RealProp() = default;
explicit RealProp(double value) : mode(1), value(value) {}
explicit RealProp(Real *ptr) : mode(2), ptr(ptr) {}
double getValue() const {
if (mode == 1) {
return value;
} else if (mode == 2) {
return ptr->getValue();
} else {
std::cerr << "Property is no set!\n";
exit(1);
}
}
};
/*
===================================================================================================
Graphical model nodes
=================================================================================================*/
class UnaryReal : public RandomNode {
protected:
RealProp param{};
template <class... Args>
void setParam(Args... args) {
param = RealProp(std::forward<Args>(args)...);
}
double value{0.0};
std::string name{};
public:
UnaryReal() = delete;
explicit UnaryReal(const std::string &name) : name(name) {
port("paramConst", &UnaryReal::setParam<double>);
port("paramPtr", &UnaryReal::setParam<Real *>);
port("sample", &UnaryReal::sample);
port("clamp", &UnaryReal::clamp);
port("value", &UnaryReal::setValue);
};
std::string debug() const override {
std::stringstream ss;
ss << name << "(" << param.getValue() << "):" << value << "[" << clamped_value() << "]";
return ss.str();
}
double getValue() const override { return value; }
void setValue(double valuein) override { value = valuein; }
};
class Exponential : public UnaryReal {
public:
explicit Exponential(double value = 0.0) : UnaryReal("Exponential") { setValue(value); }
void sample() override {
std::exponential_distribution<> d(param.getValue());
setValue(d(generator));
}
double log_density() const final {
auto lambda = param.getValue();
auto x = getValue();
return log(lambda) - x * lambda;
}
};
class Gamma : public UnaryReal {
public:
explicit Gamma() : UnaryReal("Gamma") {}
void sample() override {
std::gamma_distribution<double> d{param.getValue(), param.getValue()};
setValue(d(generator));
}
double log_density() const final {
auto alpha = param.getValue();
auto beta = alpha;
auto x = getValue();
return (alpha - 1) * log(x) - log(tgamma(alpha)) - alpha * log(beta) - x / beta;
}
};
class Poisson : public UnaryReal {
public:
explicit Poisson(double value = 0.0) : UnaryReal("Poisson") { setValue(value); }
void sample() override {
std::poisson_distribution<> d(param.getValue());
setValue(d(generator));
}
double log_density() const final {
double k = getValue(), lambda = param.getValue();
return k * log(lambda) - lambda - log(factorial(k));
}
};
template <class Op>
class BinaryOperation : public Real {
RealProp a{};
RealProp b{};
public:
BinaryOperation() {
port("aPtr", &BinaryOperation::setA<Real *>);
port("bPtr", &BinaryOperation::setB<Real *>);
port("bConst", &BinaryOperation::setB<double>);
}
template <class... Args>
void setA(Args... args) {
a = RealProp(std::forward<Args>(args)...);
}
template <class... Args>
void setB(Args... args) {
b = RealProp(std::forward<Args>(args)...);
}
void setA(Real *ptr) { a = RealProp(ptr); }
double getValue() const override { return Op()(a.getValue(), b.getValue()); }
void setValue(double) override { std::cerr << "-- Warning! Trying to set a deterministic node!\n"; }
std::string debug() const override {
std::stringstream ss;
ss << "BinaryOperation(" << a.getValue() << "," << b.getValue() << "):" << getValue();
return ss.str();
}
};
using Product = BinaryOperation<std::multiplies<double>>;
/*
===================================================================================================
Sampling and RS
=================================================================================================*/
class MultiSample : public Sampler {
std::vector<RandomNode *> nodes;
void registerNode(RandomNode *ptr) { nodes.push_back(ptr); }
public:
MultiSample() { port("register", &MultiSample::registerNode); }
void go() override {
std::for_each(nodes.begin(), nodes.end(), [](RandomNode *n) { n->sample(); });
}
std::string debug() const override { return "MultiSample"; }
std::string getVarList() const override {
return std::accumulate(nodes.begin(), nodes.end(), std::string("#"),
[](std::string acc, RandomNode *n) { return acc + n->get_name() + '\t'; });
}
std::vector<double> getSample() const override {
std::vector<double> tmp(nodes.size(), 0.);
std::transform(nodes.begin(), nodes.end(), tmp.begin(), [](RandomNode *n) { return n->getValue(); });
return tmp;
}
};
class RejectionSampling : public Go {
std::vector<RandomNode *> observedData;
void addData(RandomNode *ptr) { observedData.push_back(ptr); }
Sampler *sampler{nullptr};
int nbIter{0};
DataStream *output{nullptr};
public:
explicit RejectionSampling(int iter = 5) : nbIter(iter) {
port("sampler", &RejectionSampling::sampler);
port("data", &RejectionSampling::addData);
port("output", &RejectionSampling::output);
}
std::string debug() const override { return "RejectionSampling"; }
void go() override {
int accepted = 0;
std::cout << "-- Starting rejection sampling!\n";
output->header(sampler->getVarList());
for (auto i = 0; i < nbIter; i++) {
sampler->go();
bool valid = std::accumulate(observedData.begin(), observedData.end(), true,
[](bool acc, RandomNode *n) { return acc && n->is_consistent(); });
if (valid) { // accept
accepted++;
output->dataLine(sampler->getSample());
}
}
std::cout << "-- Done. Accepted " << accepted << " points.\n";
}
};
/*
===================================================================================================
MCMC-related things
=================================================================================================*/
struct Uniform {
static double move(RandomNode *v, double = 1.0) {
v->setValue(uniform(generator));
return 0.;
}
};
struct Scaling {
static double move(RandomNode *v, double tuning = 1.0) {
auto multiplier = tuning * (uniform(generator) - 0.5);
// cout << multiplier << '\n';
v->setValue(v->getValue() * exp(multiplier));
return multiplier;
}
};
template <class MoveFunctor>
class MHMove : public Move {
double tuning;
int ntot{0}, nacc{0}, nrep{0};
RandomNode *node{nullptr};
vector<LogDensity *> downward;
void addDownward(LogDensity *ptr) { downward.push_back(ptr); }
// suff stats corruption
vector<AbstractSuffStats *> corrupted_suff_stats;
void add_corrupted_suff_stats(AbstractSuffStats *ss) { corrupted_suff_stats.push_back(ss); }
void corrupt() const {
for (auto ss : corrupted_suff_stats) {
ss->corrupt();
}
}
public:
explicit MHMove(double tuning = 1.0, int nrep = 1) : tuning(tuning), nrep(nrep) {
port("node", &MHMove::node);
port("downward", &MHMove::addDownward);
port("corrupt", &MHMove::add_corrupted_suff_stats);
}
void go() override {
for (int i = 0; i < nrep; i++) {
double backup = node->getValue();
auto gather = [](const vector<LogDensity *> &v) {
return accumulate(v.begin(), v.end(), 0., [](double acc, LogDensity *b) { return acc + b->log_density(); });
};
double logprob_before = gather(downward) + node->log_density();
double hastings_ratio = MoveFunctor::move(node, tuning);
double logprob_after = gather(downward) + node->log_density();
bool accepted = exp(logprob_after - logprob_before + hastings_ratio) > uniform(generator);
if (!accepted) {
node->setValue(backup);
} else {
corrupt(); // corrupt suff stats only of move accepted
nacc++;
}
ntot++;
}
}
string debug() const override { return sf("MHMove[%.1f\%]", nacc * 100. / ntot); }
};
class MoveScheduler : public Component {
vector<Go *> move{};
void addMove(Go *ptr) { move.push_back(ptr); }
public:
MoveScheduler() {
port("go", &MoveScheduler::go);
port("move", &MoveScheduler::addMove);
}
void go() {
for (auto ptr : move) {
ptr->go();
}
}
};
class MCMCEngine : public Go {
MoveScheduler *scheduler{nullptr};
Sampler *sampler{nullptr};
DataStream *output{nullptr};
int iterations;
vector<Real *> variables_of_interest{};
void addVarOfInterest(Real *val) { variables_of_interest.push_back(val); }
public:
explicit MCMCEngine(int iterations = 10) : iterations(iterations) {
port("variables", &MCMCEngine::addVarOfInterest);
port("scheduler", &MCMCEngine::scheduler);
port("sampler", &MCMCEngine::sampler);
port("iterations", &MCMCEngine::iterations);
port("output", &MCMCEngine::output);
}
void go() {
cout << "-- Starting MCMC chain!\n";
sampler->go();
sampler->go();
string header = accumulate(variables_of_interest.begin(), variables_of_interest.end(), string("#"),
[](string acc, Real *v) { return acc + v->get_name() + "\t"; });
output->header(header);
for (int i = 0; i < iterations; i++) {
scheduler->go();
vector<double> vect;
for (auto v : variables_of_interest) {
vect.push_back(v->getValue());
}
output->dataLine(vect);
}
cout << "-- Done. Wrote " << iterations << " lines in trace file.\n";
}
};
class GammaSuffStat : public AbstractSuffStats, public Component {
mutable double sum_xi{0}, sum_log_xi{0};
mutable bool valid{false};
vector<RandomNode *> targets;
void add_target(RandomNode *target) { targets.push_back(target); }
RandomNode *parent;
void gather() const {
sum_xi = 0;
sum_log_xi = 0;
for (auto t : targets) {
sum_xi += t->getValue();
sum_log_xi += log(t->getValue());
}
valid = true;
}
public:
GammaSuffStat() {
port("target", &GammaSuffStat::add_target);
port("parent", &GammaSuffStat::parent);
}
double log_density() const final {
if (!valid) {
gather();
}
double p = parent->getValue();
int n = targets.size();
return -n * (log(tgamma(p)) + p * log(p)) + (p - 1) * sum_log_xi - (1 / p) * sum_xi;
}
void corrupt() const final { valid = false; }
};
#endif
| 32.95992 | 125 | 0.570986 | [
"object",
"vector",
"model",
"transform"
] |
b6f1516a97331b1ce71d3fa05f250e28af9398b8 | 435 | hpp | C++ | include/geometry/projection.hpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | include/geometry/projection.hpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | include/geometry/projection.hpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #pragma once
#include "geometry/line.hpp"
Point projection(const Point &a, const Point &b) { return a * (b / a).x; }
Point projection(const Line &line, const Point &point) {
return line.a + projection(line.vec(), point - line.a);
}
Point reflection(const Point &a, const Point &b) { return a * (b / a).conj(); }
Point reflection(const Line &line, const Point &point) {
return line.a + reflection(line.vec(), point - line.a);
}
| 29 | 79 | 0.668966 | [
"geometry"
] |
b6f1a4cccf2999806ef1d802746b39b48bfa48ed | 6,489 | cxx | C++ | LocalLabelingCorrection/LocalLabelingCorrection.cxx | CSIM-Toolkits/BabyBrain | ff9648e7f3be348bb736adfd32e3c08e7de076d8 | [
"Apache-2.0"
] | 1 | 2019-04-25T13:41:13.000Z | 2019-04-25T13:41:13.000Z | LocalLabelingCorrection/LocalLabelingCorrection.cxx | CSIM-Toolkits/BabyBrain | ff9648e7f3be348bb736adfd32e3c08e7de076d8 | [
"Apache-2.0"
] | 6 | 2018-01-09T19:20:19.000Z | 2018-03-06T18:32:28.000Z | LocalLabelingCorrection/LocalLabelingCorrection.cxx | CSIM-Toolkits/BabyBrain | ff9648e7f3be348bb736adfd32e3c08e7de076d8 | [
"Apache-2.0"
] | null | null | null | #include "itkImageFileWriter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkBinaryContourImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkNeighborhoodIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkSmoothingRecursiveGaussianImageFilter.h"
#include "itkPluginUtilities.h"
#include "LocalLabelingCorrectionCLP.h"
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <typename TPixel>
int DoIt( int argc, char * argv[], TPixel )
{
PARSE_ARGS;
typedef unsigned char LabelPixelType;
const unsigned int Dimension = 3;
typedef itk::Image<LabelPixelType, Dimension> LabelImageType;
//Read the input label
typedef itk::ImageFileReader<LabelImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputLabel.c_str() );
reader->Update();
//Creating output label
LabelImageType::Pointer output = LabelImageType::New();
output->CopyInformation(reader->GetOutput());
output->SetRegions(reader->GetOutput()->GetRequestedRegion());
output->Allocate();
output->FillBuffer(0);
//Apply a local decision rule in order to remove wrong segmentation definitions
typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> BinaryThresholdType;
typename BinaryThresholdType::Pointer thr = BinaryThresholdType::New();
thr->SetInput(reader->GetOutput());
thr->SetLowerThreshold( labelToCorrect );
thr->SetUpperThreshold( labelToCorrect );
thr->Update();
//Defining the path where the iterator should run
typedef itk::BinaryContourImageFilter<LabelImageType, LabelImageType> BinaryContourType;
typename BinaryContourType::Pointer maskContour = BinaryContourType::New();
maskContour->SetInput(thr->GetOutput());
maskContour->SetForegroundValue( labelToCorrect );
maskContour->Update();
typename LabelImageType::SizeType radius;
radius[0] = neighborRadius[0];
radius[1] = neighborRadius[1];
radius[2] = neighborRadius[2];
typedef itk::NeighborhoodIterator<LabelImageType, itk::ConstantBoundaryCondition<LabelImageType> > NeighborhoodIteratorType;
typedef itk::ImageRegionIterator<LabelImageType> ImageIteratorType;
ImageIteratorType contourIt(maskContour->GetOutput(),maskContour->GetOutput()->GetRequestedRegion());
ImageIteratorType outputIt(output, output->GetRequestedRegion());
NeighborhoodIteratorType inLabelIt(radius, reader->GetOutput(),reader->GetOutput()->GetRequestedRegion());
contourIt.GoToBegin();
inLabelIt.GoToBegin();
outputIt.GoToBegin();
unsigned int N = (neighborRadius[0]*2 + 1)*(neighborRadius[1]*2 + 1)*(neighborRadius[2]*2 + 1);
while (!inLabelIt.IsAtEnd()) {
if (contourIt.Get()!=static_cast<LabelPixelType>(0)) {
// Making a local statistics
double nErrors = 0; //Set the counter for the label errors. This will count how many errors in the local segmentation.
for (unsigned int p = 0; p < N; p++) {
if (inLabelIt.GetPixel(p) == static_cast<LabelPixelType>(labelError)){
nErrors++;
}
}
nErrors/=N;
if (nErrors>=tolerance) {
outputIt.Set(static_cast<LabelPixelType>(labelError));
}else{
outputIt.Set(inLabelIt.GetCenterPixel());
}
}else{
// If the iterator is not on the contour path, the output value is a copy of the input value
if (inLabelIt.GetCenterPixel()!=static_cast<LabelPixelType>(labelError)) {
outputIt.Set(inLabelIt.GetCenterPixel());
}
}
++contourIt;
++inLabelIt;
++outputIt;
}
typedef itk::ImageFileWriter<LabelImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputLabel.c_str() );
writer->SetInput( output );
writer->SetUseCompression(1);
writer->Update();
return EXIT_SUCCESS;
}
} // end of anonymous namespace
int main( int argc, char * argv[] )
{
PARSE_ARGS;
itk::ImageIOBase::IOPixelType pixelType;
itk::ImageIOBase::IOComponentType componentType;
try
{
itk::GetImageType(inputLabel, pixelType, componentType);
// This filter handles all types on input, but only produces
// signed types
switch( componentType )
{
case itk::ImageIOBase::UCHAR:
return DoIt( argc, argv, static_cast<unsigned char>(0) );
break;
case itk::ImageIOBase::CHAR:
return DoIt( argc, argv, static_cast<signed char>(0) );
break;
case itk::ImageIOBase::USHORT:
return DoIt( argc, argv, static_cast<unsigned short>(0) );
break;
case itk::ImageIOBase::SHORT:
return DoIt( argc, argv, static_cast<short>(0) );
break;
case itk::ImageIOBase::UINT:
return DoIt( argc, argv, static_cast<unsigned int>(0) );
break;
case itk::ImageIOBase::INT:
return DoIt( argc, argv, static_cast<int>(0) );
break;
case itk::ImageIOBase::ULONG:
return DoIt( argc, argv, static_cast<unsigned long>(0) );
break;
case itk::ImageIOBase::LONG:
return DoIt( argc, argv, static_cast<long>(0) );
break;
case itk::ImageIOBase::FLOAT:
return DoIt( argc, argv, static_cast<float>(0) );
break;
case itk::ImageIOBase::DOUBLE:
return DoIt( argc, argv, static_cast<double>(0) );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
std::cerr << "Unknown input image pixel component type: ";
std::cerr << itk::ImageIOBase::GetComponentTypeAsString( componentType );
std::cerr << std::endl;
return EXIT_FAILURE;
break;
}
}
catch( itk::ExceptionObject & excep )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 35.653846 | 130 | 0.642164 | [
"object"
] |
8e0039ca52b61b2dfbfd8f370139a423176d054a | 1,114 | cpp | C++ | solutions/79.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/79.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/79.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | #include <array>
#include <functional>
#include <utility>
#include <vector>
class Solution {
static inline constexpr std::array<std::pair<size_t, size_t>, 4> directions{
{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}};
public:
bool exist(std::vector<std::vector<char>>& board, std::string word) {
std::function<bool(size_t, size_t, size_t)> dfs =
[&dfs, &board, &word](size_t row, size_t col, size_t pos) -> bool {
if (pos == word.size()) {
return true;
}
if (row >= board.size() or col >= board.front().size()) {
return false;
}
if (board[row][col] != word[pos]) {
return false;
}
board[row][col] = 0;
for (const auto& [drow, dcol] : directions) {
if (dfs(row + drow, col + dcol, pos + 1)) {
return true;
}
}
board[row][col] = word[pos];
return false;
};
for (size_t row = 0; row < board.size(); ++row) {
for (size_t col = 0; col < board.front().size(); ++col) {
if (dfs(row, col, 0)) {
return true;
}
}
}
return false;
}
};
| 24.755556 | 78 | 0.508079 | [
"vector"
] |
8e02e656484566857e18245b4569175d1e502fc4 | 666 | hpp | C++ | 508 - A4-spbspu-labs-2020-904-3/1/common/shape.hpp | NekoSilverFox/CPP | c6797264fceda4a65ac3452acca496e468d1365a | [
"Apache-2.0"
] | 5 | 2020-02-08T20:57:21.000Z | 2021-12-23T06:24:41.000Z | 508 - A4-spbspu-labs-2020-904-3/1/common/shape.hpp | NekoSilverFox/CPP | c6797264fceda4a65ac3452acca496e468d1365a | [
"Apache-2.0"
] | 2 | 2020-03-02T14:44:55.000Z | 2020-11-11T16:25:33.000Z | 508 - A4-spbspu-labs-2020-904-3/1/common/shape.hpp | NekoSilverFox/CPP | c6797264fceda4a65ac3452acca496e468d1365a | [
"Apache-2.0"
] | 4 | 2020-09-27T17:30:03.000Z | 2022-02-16T09:48:23.000Z | #ifndef SAMOKHIN_IGOR_SHAPE_HPP
#define SAMOKHIN_IGOR_SHAPE_HPP
#include <memory>
namespace samokhin
{
struct rectangle_t;
struct point_t;
class Shape
{
public:
using SharedShapeArray = std::shared_ptr<Shape>[];
using SharedShape = std::shared_ptr<Shape>;
virtual ~Shape() = default;
virtual double getArea() const = 0;
virtual rectangle_t getFrameRect() const = 0;
virtual void move(double x, double y) = 0;
virtual void move(const point_t &pos) = 0;
virtual void scale(double k) = 0;
virtual void rotate(double angle) = 0;
virtual point_t getCenter() const = 0;
};
}
#endif //SAMOKHIN_IGOR_SHAPE_HPP
| 18.5 | 54 | 0.689189 | [
"shape"
] |
8e02fb69ef7216ab728e3ddc29d37a6cb97def59 | 2,470 | cpp | C++ | simulation/halsim_gui/src/main/native/cpp/AnalogOutputSimGui.cpp | gcjurgiel/allwpilib | 99f3a64dff0eba07be9b2e6c53753aafa0c852d8 | [
"BSD-3-Clause"
] | 707 | 2016-05-11T16:54:13.000Z | 2022-03-30T13:03:15.000Z | simulation/halsim_gui/src/main/native/cpp/AnalogOutputSimGui.cpp | gcjurgiel/allwpilib | 99f3a64dff0eba07be9b2e6c53753aafa0c852d8 | [
"BSD-3-Clause"
] | 2,308 | 2016-05-12T00:17:17.000Z | 2022-03-30T20:08:10.000Z | simulation/halsim_gui/src/main/native/cpp/AnalogOutputSimGui.cpp | gcjurgiel/allwpilib | 99f3a64dff0eba07be9b2e6c53753aafa0c852d8 | [
"BSD-3-Clause"
] | 539 | 2016-05-11T20:33:26.000Z | 2022-03-28T20:20:25.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "AnalogOutputSimGui.h"
#include <glass/hardware/AnalogOutput.h>
#include <glass/other/DeviceTree.h>
#include <memory>
#include <vector>
#include <hal/Ports.h>
#include <hal/simulation/AnalogOutData.h>
#include "HALDataSource.h"
#include "HALSimGui.h"
#include "SimDeviceGui.h"
using namespace halsimgui;
namespace {
HALSIMGUI_DATASOURCE_DOUBLE_INDEXED(AnalogOutVoltage, "AOut");
class AnalogOutputSimModel : public glass::AnalogOutputModel {
public:
explicit AnalogOutputSimModel(int32_t index)
: m_index{index}, m_voltageData{m_index} {}
void Update() override {}
bool Exists() override { return HALSIM_GetAnalogOutInitialized(m_index); }
glass::DataSource* GetVoltageData() override { return &m_voltageData; }
void SetVoltage(double val) override {
HALSIM_SetAnalogOutVoltage(m_index, val);
}
private:
int32_t m_index;
AnalogOutVoltageSource m_voltageData;
};
class AnalogOutputsSimModel : public glass::AnalogOutputsModel {
public:
AnalogOutputsSimModel() : m_models(HAL_GetNumAnalogOutputs()) {}
void Update() override;
bool Exists() override { return true; }
void ForEachAnalogOutput(
wpi::function_ref<void(glass::AnalogOutputModel& model, int index)> func)
override;
private:
// indexed by channel
std::vector<std::unique_ptr<AnalogOutputSimModel>> m_models;
};
} // namespace
void AnalogOutputsSimModel::Update() {
for (int32_t i = 0, iend = static_cast<int32_t>(m_models.size()); i < iend;
++i) {
auto& model = m_models[i];
if (HALSIM_GetAnalogOutInitialized(i)) {
if (!model) {
model = std::make_unique<AnalogOutputSimModel>(i);
}
} else {
model.reset();
}
}
}
void AnalogOutputsSimModel::ForEachAnalogOutput(
wpi::function_ref<void(glass::AnalogOutputModel& model, int index)> func) {
for (int32_t i = 0, iend = static_cast<int32_t>(m_models.size()); i < iend;
++i) {
if (auto model = m_models[i].get()) {
func(*model, i);
}
}
}
void AnalogOutputSimGui::Initialize() {
SimDeviceGui::GetDeviceTree().Add(
std::make_unique<AnalogOutputsSimModel>(), [](glass::Model* model) {
glass::DisplayAnalogOutputsDevice(
static_cast<AnalogOutputsSimModel*>(model));
});
}
| 26.276596 | 79 | 0.704049 | [
"vector",
"model"
] |
8e0eeccb9a2993da2dc9c339d1b0ecd80da769d6 | 9,952 | cc | C++ | euler/core/graph/edge.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 2,829 | 2019-01-12T09:16:03.000Z | 2022-03-29T14:00:58.000Z | euler/core/graph/edge.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 331 | 2019-01-17T21:07:49.000Z | 2022-03-30T06:38:17.000Z | euler/core/graph/edge.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 578 | 2019-01-16T10:48:53.000Z | 2022-03-21T13:41:34.000Z | /* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "euler/core/graph/edge.h"
#include "euler/common/logging.h"
#include "euler/common/bytes_io.h"
#include "euler/common/bytes_compute.h"
namespace euler {
bool Edge::Init(const std::vector<std::vector<uint64_t>>& uint64_features,
const std::vector<std::vector<float>>& float_features,
const std::vector<std::string>& binary_features) {
int32_t idx = 0;
for (size_t i = 0; i < uint64_features.size(); ++i) {
idx += uint64_features[i].size();
uint64_features_idx_.push_back(idx);
std::copy(uint64_features[i].begin(), uint64_features[i].end(),
back_inserter(uint64_features_));
}
idx = 0;
for (size_t i = 0; i < float_features.size(); ++i) {
idx += float_features[i].size();
float_features_idx_.push_back(idx);
std::copy(float_features[i].begin(), float_features[i].end(),
back_inserter(float_features_));
}
idx = 0;
for (size_t i = 0; i < binary_features.size(); ++i) {
idx += binary_features[i].size();
binary_features_idx_.push_back(idx);
std::copy(binary_features[i].begin(), binary_features[i].end(),
back_inserter(binary_features_));
}
return true;
}
#define GET_EDGE_FEATURE(F_NUMS_PTR, F_VALUES_PTR, FEATURES, \
FEATURES_IDX, FIDS) { \
for (size_t i = 0; i < FIDS.size(); ++i) { \
int32_t fid = FIDS[i]; \
if (fid >= 0 && fid < static_cast<int32_t>(FEATURES_IDX.size())) { \
int32_t pre = fid == 0 ? 0 : FEATURES_IDX[fid - 1]; \
F_NUMS_PTR->push_back(FEATURES_IDX[fid] - pre); \
} else { \
F_NUMS_PTR->push_back(0); \
} \
} \
for (size_t i = 0; i < FIDS.size(); ++i) { \
int32_t fid = FIDS[i]; \
if (fid >= 0 && fid < static_cast<int32_t>(FEATURES_IDX.size())) { \
int32_t pre = fid == 0 ? 0 : FEATURES_IDX[fid - 1]; \
int32_t now = FEATURES_IDX[fid]; \
F_VALUES_PTR->insert(F_VALUES_PTR->end(), \
FEATURES.begin() + pre, \
FEATURES.begin() + now); \
} \
} \
}
#define GET_EDGE_FEATURE_VEC(F_VALUES_PTR, FEATURES, \
FEATURES_IDX, FIDS, TYPE) { \
F_VALUES_PTR->resize(FIDS.size()); \
for (size_t i = 0; i < FIDS.size(); ++i) { \
int32_t fid = FIDS[i]; \
if (fid >= 0 && fid < static_cast<int32_t>(FEATURES_IDX.size())) { \
int32_t pre = fid == 0 ? 0 : FEATURES_IDX[fid - 1]; \
int32_t now = FEATURES_IDX[fid]; \
(*F_VALUES_PTR)[i] = TYPE(FEATURES.begin() + pre, \
FEATURES.begin() + now); \
} \
} \
}
void Edge::GetUint64Feature(
const std::vector<int32_t>& fids,
std::vector<uint32_t>* feature_nums,
std::vector<uint64_t>* feature_values) const {
GET_EDGE_FEATURE(feature_nums, feature_values, uint64_features_,
uint64_features_idx_, fids);
}
void Edge::GetUint64Feature(
const std::vector<int32_t>& fids,
std::vector<std::vector<uint64_t>>* feature_values) const {
GET_EDGE_FEATURE_VEC(feature_values, uint64_features_,
uint64_features_idx_, fids, std::vector<uint64_t>);
}
void Edge::GetFloat32Feature(
const std::vector<int32_t>& fids,
std::vector<uint32_t>* feature_nums,
std::vector<float>* feature_values) const {
GET_EDGE_FEATURE(feature_nums, feature_values, float_features_,
float_features_idx_, fids);
}
void Edge::GetFloat32Feature(
const std::vector<int32_t>& fids,
std::vector<std::vector<float>>* feature_values) const {
GET_EDGE_FEATURE_VEC(feature_values, float_features_,
float_features_idx_, fids, std::vector<float>);
}
void Edge::GetBinaryFeature(
const std::vector<int32_t>& fids,
std::vector<uint32_t>* feature_nums,
std::vector<char>* feature_values) const {
GET_EDGE_FEATURE(feature_nums, feature_values, binary_features_,
binary_features_idx_, fids);
}
void Edge::GetBinaryFeature(
const std::vector<int32_t>& fids,
std::vector<std::string>* feature_values) const {
GET_EDGE_FEATURE_VEC(feature_values, binary_features_,
binary_features_idx_, fids, std::string);
}
bool Edge::DeSerialize(const char* s, size_t size) {
uint64_t src_id = 0;
uint64_t dst_id = 0;
BytesReader bytes_reader(s, size);
// parse id
if (!bytes_reader.Read(&src_id) ||
!bytes_reader.Read(&dst_id)) {
EULER_LOG(ERROR) << "edge id error";
return false;
}
if (!bytes_reader.Read(&type_) || // parse type
!bytes_reader.Read(&weight_)) { // parse weight
EULER_LOG(ERROR) << "edge info error, edge_id: " << src_id << "," << dst_id;
return false;
}
id_ = std::make_tuple(src_id, dst_id, type_);
// parse uint64 feature
if (!bytes_reader.Read(&uint64_features_idx_)) {
EULER_LOG(ERROR) << "uint64 feature idx list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_reader.Read(&uint64_features_)) {
EULER_LOG(ERROR) << "uint64 feature value list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_reader.Read(&float_features_idx_)) {
EULER_LOG(ERROR) << "float feature idx list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_reader.Read(&float_features_)) {
EULER_LOG(ERROR) << "float feature value list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_reader.Read(&binary_features_idx_)) {
EULER_LOG(ERROR) << "binary feature idx list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_reader.Read(&binary_features_)) {
EULER_LOG(ERROR) << "binary feature value list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
return true;
}
bool Edge::Serialize(std::string* s) const {
BytesWriter bytes_writer;
uint64_t src_id = std::get<0>(id_);
uint64_t dst_id = std::get<1>(id_);
if (!bytes_writer.Write(src_id) ||
!bytes_writer.Write(dst_id)) {
EULER_LOG(ERROR) << "edge id error";
return false;
}
if (!bytes_writer.Write(type_) || !bytes_writer.Write(weight_)) {
EULER_LOG(ERROR) << "edge info error, edge_id: " << src_id << "," << dst_id;
return false;
}
if (!bytes_writer.Write(uint64_features_idx_)) {
EULER_LOG(ERROR) << "uint64 feature idx list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_writer.Write(uint64_features_)) {
EULER_LOG(ERROR) << "uint64 feature value list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_writer.Write(float_features_idx_)) {
EULER_LOG(ERROR) << "float feature idx list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_writer.Write(float_features_)) {
EULER_LOG(ERROR) << "float feature value list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_writer.Write(binary_features_idx_)) {
EULER_LOG(ERROR) << "binary feature idx list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
if (!bytes_writer.Write(binary_features_)) {
EULER_LOG(ERROR) << "binary feature value list error, edge_id: "
<< src_id << "," << dst_id << "," << type_;
return false;
}
*s = bytes_writer.data();
return true;
}
uint32_t Edge::SerializeSize() const {
uint32_t total = 0;
total+= BytesSize(std::get<0>(id_));
total+= BytesSize(std::get<1>(id_));
total+= BytesSize(type_);
total+= BytesSize(weight_);
total+= BytesSize(uint64_features_idx_);
total+= BytesSize(uint64_features_);
total+= BytesSize(float_features_idx_);
total+= BytesSize(float_features_);
total+= BytesSize(binary_features_idx_);
total+= BytesSize(binary_features_);
return total;
}
} // namespace euler
| 37.273408 | 80 | 0.546624 | [
"vector"
] |
8e1a45ba9cc09f940b7985690949611ba9455a54 | 3,446 | cpp | C++ | pgprogram.cpp | gusmccallum/potato-generator | 4985b431c2e8f4ea2069c22eaef75da51ee8eccc | [
"MIT"
] | null | null | null | pgprogram.cpp | gusmccallum/potato-generator | 4985b431c2e8f4ea2069c22eaef75da51ee8eccc | [
"MIT"
] | null | null | null | pgprogram.cpp | gusmccallum/potato-generator | 4985b431c2e8f4ea2069c22eaef75da51ee8eccc | [
"MIT"
] | null | null | null | /*
* This program is A Static Site Generator (SSG) Tool coded in C++ language.
* Author: Chi Kien Nguyen
* Git Hub: https://github.com/kiennguyenchi/potato-generator
*/
/* This is the file containing main function to run the program */
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include "MainPage.h"
using namespace std;
using std::filesystem::directory_iterator;
namespace fs = std::filesystem;
void createOneHTML(string filename, string lang);
void createManyHTML(string folderName, string lang);
string checkArguments(int argc, char** argv);
string checkLanguage(int argc, char** argv);
int main(int argc, char** argv)
{
if(argc >= 2){
string language = checkLanguage(argc, argv);
string name = checkArguments(argc, argv);
if (name != "terminate"){
if (name == "")
name = argv[1];
size_t folderOrFile = name.find(".txt");
size_t mdFile = name.find(".md");
fs::remove_all("./dist");
fs::current_path("./");
fs::create_directory("dist");
if (folderOrFile > name.size()){
if (mdFile > name.size()){
createManyHTML(name, language);
}else{
createOneHTML(name, language);
}
}else{
createOneHTML(name, language);
}
}
}else{
cout << "Failed arguments provided";
}
}
//this function creates a single HTML page
void createOneHTML(string filename, string lang){
HTMLFile newFile;
newFile.openFile(filename, lang);
newFile.setHtmlFile();
newFile.writeHTML();
}
//this function creates multiple HTML page
void createManyHTML(string folderName, string lang){
vector<string> fileNames;
for (const auto & file : directory_iterator(folderName))
fileNames.push_back(file.path().string());
MainPage newPage;
newPage.setMainPage(folderName, fileNames, lang);
newPage.writeHTML();
}
//this function checks for arguments input
string checkArguments(int argc, char** argv){
string fName = "";
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "--version" || string(argv[i]) == "-v") {
cout << "Potato Generator - Version 0.1";
fName = "terminate";
break;
}else if (string(argv[i]) == "--help" || string(argv[i]) == "-h"){
cout << "*Run the program with command: ./pgprogram inputName\n";
cout << "The inputName is a text file name or a folder name\n";
cout << "*To include a input file/folder, include --input or -i before the file/folder name in the arguments.\n";
cout << "*To see the version of the program, include --version or -v in the arguments.\n";
cout << "*To need help, include --help or -h in the arguments.\n";
fName = "terminate";
break;
}else if (string(argv[i]) == "--input" || string(argv[i]) == "-i"){
fName = argv[(i+1)];
break;
}
}
return fName;
}
//this function checks for language specified
string checkLanguage(int argc, char** argv){
string language = "";
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "--lang" || string(argv[i]) == "-l"){
language = argv[(i+1)];
break;
}
}
return language;
} | 32.819048 | 125 | 0.576901 | [
"vector"
] |
8e1c8be0e992a77a11d9fd8b64f54e55124d14db | 1,258 | inl | C++ | TAO/tao/Object_Ref_Table.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tao/Object_Ref_Table.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tao/Object_Ref_Table.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//
// $Id: Object_Ref_Table.inl 83527 2008-11-03 11:25:24Z johnnyw $
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_INLINE
TAO_Object_Ref_Table::TAO_Object_Ref_Table (void)
: table_ (TAO_DEFAULT_OBJECT_REF_TABLE_SIZE)
, lock_ ()
{
}
ACE_INLINE CORBA::Object_ptr
TAO_Object_Ref_Table::find_i (const char *id)
{
iterator const found =
this->table_.find (CORBA::String_var (id));
if (found == this->table_.end ())
return CORBA::Object::_nil ();
return CORBA::Object::_duplicate ((*found).second.in ());
}
ACE_INLINE void
TAO_Object_Ref_Table::destroy (void)
{
Table tmp;
ACE_GUARD (TAO_SYNCH_MUTEX,
guard,
this->lock_);
this->table_.swap (tmp); // Force release of memory held by our table.
}
ACE_INLINE TAO_Object_Ref_Table::iterator
TAO_Object_Ref_Table::begin (void)
{
return this->table_.begin ();
}
ACE_INLINE TAO_Object_Ref_Table::iterator
TAO_Object_Ref_Table::end (void)
{
return this->table_.end ();
}
ACE_INLINE size_t
TAO_Object_Ref_Table::current_size (void) const
{
return this->table_.size ();
}
ACE_INLINE int
TAO_Object_Ref_Table::unbind_i (const char *id)
{
return
(this->table_.erase (CORBA::String_var (id)) == 0 ? -1 : 0);
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 19.65625 | 73 | 0.706677 | [
"object"
] |
8e1e8bfce3bfdf8bfefaeddf2d10d84692948484 | 799 | cpp | C++ | regression/esbmc-cpp/algorithm/algorithm5/main.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 143 | 2015-06-22T12:30:01.000Z | 2022-03-21T08:41:17.000Z | regression/esbmc-cpp/algorithm/algorithm5/main.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 542 | 2017-06-02T13:46:26.000Z | 2022-03-31T16:35:17.000Z | regression/esbmc-cpp/algorithm/algorithm5/main.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 81 | 2015-10-21T22:21:59.000Z | 2022-03-24T14:07:55.000Z | // find_first_of example
#include <iostream>
#include <algorithm>
#include <cctype>
#include <vector>
using namespace std;
bool comp_case_insensitive (char c1, char c2) {
return (tolower(c1)==tolower(c2));
}
int main () {
int mychars[] = {'a','b','c','A','B','C'};
vector<char> myvector (mychars,mychars+6);
vector<char>::iterator it;
int match[] = {'A','B','C'};
// using default comparison:
it = find_first_of (myvector.begin(), myvector.end(), match, match+3);
if (it!=myvector.end())
cout << "first match is: " << *it << endl;
// using predicate comparison:
it = find_first_of (myvector.begin(), myvector.end(),
match, match+3, comp_case_insensitive);
if (it!=myvector.end())
cout << "first match is: " << *it << endl;
return 0;
}
| 23.5 | 72 | 0.613267 | [
"vector"
] |
8e23dd446df04304923a8832da90d3ad55d5ae8a | 1,042 | cpp | C++ | cpp/easy/min_stack_2.cpp | adamlm/leetcode-solutions | 1461058ea26a6a1debaec978e86b1b25f6cba9ea | [
"MIT"
] | null | null | null | cpp/easy/min_stack_2.cpp | adamlm/leetcode-solutions | 1461058ea26a6a1debaec978e86b1b25f6cba9ea | [
"MIT"
] | null | null | null | cpp/easy/min_stack_2.cpp | adamlm/leetcode-solutions | 1461058ea26a6a1debaec978e86b1b25f6cba9ea | [
"MIT"
] | null | null | null | class MinStack {
private:
class Node {
public:
int val;
int min;
Node *next;
Node(int val, int min) {this->val = val; this->min = min, this->next = nullptr;};
};
Node *head;
public:
/** initialize your data structure here. */
MinStack() {
this->head = nullptr;
}
void push(int x) {
if (this->head == nullptr) {
this->head = new Node(x, x);
} else {
auto tmp = this->head;
this->head = new Node(x, min(x, tmp->min));
this->head->next = tmp;
}
}
void pop() {
auto tmp = this->head->next;
delete(this->head);
this->head = tmp;
}
int top() {
return this->head->val;
}
int getMin() {
return this->head->min;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
| 20.84 | 89 | 0.481766 | [
"object"
] |
8e25f30c1743e64ee0a00abc30a33361c3b9d1b8 | 4,335 | cpp | C++ | VoxelEngine/Classes/SimplexNoise.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | VoxelEngine/Classes/SimplexNoise.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | VoxelEngine/Classes/SimplexNoise.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | // pch
#include "PreCompiled.h"
#include "SimplexNoise.h"
using namespace Voxel;
using namespace Voxel::Noise;
std::unique_ptr<SimplexNoise> Manager::worldNoise = nullptr;
std::unique_ptr<SimplexNoise> Manager::temperatureNoise = nullptr;
std::unique_ptr<SimplexNoise> Manager::moistureNoise = nullptr;
std::unique_ptr<SimplexNoise> Manager::colorNoise = nullptr;
const float SimplexNoise::F2 = 0.366025403f;
const float SimplexNoise::G2 = 0.211324865f;
const int SimplexNoise::grad3[12][3] =
{ { 1,1,0 },{ -1,1,0 },{ 1,-1,0 },{ -1,-1,0 },
{ 1,0,1 },{ -1,0,1 },{ 1,0,-1 },{ -1,0,-1 },
{ 0,1,1 },{ 0,-1,1 },{ 0,1,-1 },{ 0,-1,-1 } };
Voxel::Noise::SimplexNoise::SimplexNoise(const std::string& seed)
{
init(seed);
}
float Voxel::Noise::SimplexNoise::noise(const glm::vec2 & v)
{
// Reference: http://webstaff.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
// Noise contributions from the three corners
float n0, n1, n2;
// Skew the input space to determine which simplex cell we're in
float s = (v.x + v.y) * F2; // Hairy factor for 2D
int i = static_cast<int>(fastFloor(v.x + s));
int j = static_cast<int>(fastFloor(v.y + s));
float t = static_cast<float>(i + j) * G2;
float X0 = i - t; // Unskew the cell origin back to (x,y) space
float Y0 = j - t;
float x0 = v.x - X0; // The x,y distances from the cell origin
float y0 = v.y - Y0;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
if (x0 > y0)
{
// lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1 = 1;
j1 = 0;
}
else
{
// upper triangle, YX order: (0,0)->(0,1)->(1,1)
i1 = 0;
j1 = 1;
}
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
float y1 = y0 - j1 + G2;
float x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords
float y2 = y0 - 1.0f + 2.0f * G2;
// Work out the hashed gradient indices of the three simplex corners
int ii = i & 255;
int jj = j & 255;
int gi0 = perm[ii + perm[jj]] % 12;
int gi1 = perm[ii + i1 + perm[jj + j1]] % 12;
int gi2 = perm[ii + 1 + perm[jj + 1]] % 12;
// Calculate the contribution from the three corners
float t0 = 0.5f - (x0 * x0) - (y0 * y0);
if (t0 < 0.0f)
{
n0 = 0.0f;
}
else
{
t0 *= t0;
n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient
}
float t1 = 0.5f - (x1 * x1) - (y1 * y1);
if (t1 < 0)
{
n1 = 0.0;
}
else
{
t1 *= t1;
n1 = t1 * t1 * dot(grad3[gi1], x1, y1);
}
float t2 = 0.5f - (x2 * x2) - (y2 * y2);
if (t2 < 0)
{
n2 = 0.0;
}
else
{
t2 *= t2;
n2 = t2 * t2 * dot(grad3[gi2], x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70.0f * (n0 + n1 + n2);
}
void Voxel::Noise::SimplexNoise::init(const std::string & seed)
{
rand.setSeed(seed);
randomize();
}
void Voxel::Noise::SimplexNoise::randomize()
{
for (int i = 0; i < 256; i++)
{
perm[i] = perm[i + 256] = rand.randRangeInt(1, 255);
}
}
float Voxel::Noise::SimplexNoise::fastFloor(float value)
{
int result = value > 0 ? static_cast<int>(value) : static_cast<int>(value) - 1;
return static_cast<float>(result);
}
// Dot product
float Voxel::Noise::SimplexNoise::dot(const int* grad, const float x, const float y)
{
return grad[0] * x + grad[1] * y;
}
void Voxel::Noise::Manager::init(const std::string & seed)
{
worldNoise = std::unique_ptr<SimplexNoise>(new SimplexNoise(seed));
temperatureNoise = std::unique_ptr<SimplexNoise>(new SimplexNoise(seed + "TEMP"));
moistureNoise = std::unique_ptr<SimplexNoise>(new SimplexNoise(seed + "MOIS"));
colorNoise = std::unique_ptr<SimplexNoise>(new SimplexNoise(seed + "COLOR"));
}
SimplexNoise * Voxel::Noise::Manager::getWorldNoise()
{
return worldNoise.get();
}
SimplexNoise * Voxel::Noise::Manager::getTemperatureNoise()
{
return temperatureNoise.get();
}
SimplexNoise * Voxel::Noise::Manager::getMoistureNoise()
{
return moistureNoise.get();
}
SimplexNoise * Voxel::Noise::Manager::getColorNoise()
{
return colorNoise.get();
}
| 25.203488 | 86 | 0.631834 | [
"shape"
] |
8e2999dc3919fce259649861bef357a625411af8 | 1,852 | cpp | C++ | some-math-notes/std/square/square.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | 3 | 2019-07-30T10:43:58.000Z | 2019-07-30T10:46:05.000Z | some-math-notes/std/square/square.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | null | null | null | some-math-notes/std/square/square.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <bitset>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 500 + 5, MOD = (int) 1e9 + 7;
typedef bitset<MAXN> matrix[MAXN];
bool flag[MAXN];
int pow2[MAXN];
matrix A;
vector<int> pr;
int gauss(matrix A, int m, int n) {
int i = 0, j = 0;
while (i < m && j < n) {
int r = i;
for (int k = i; k < m; k++) {
if (A[k][j]) {
r = k;
break;
}
}
if (A[r][j]) {
if (r != i) {
swap(A[r], A[i]);
}
for (int u = i + 1; u < m; u++) {
if (A[u][j]) {
A[u] ^= A[i];
}
}
i++;
}
j++;
}
return i;
}
int main() {
freopen("square.in", "r", stdin);
freopen("square.out", "w", stdout);
pow2[0] = 1;
for (int i = 1; i < MAXN; i++) {
pow2[i] = pow2[i - 1] * 2 % MOD;
}
for (int i = 2; i < MAXN; i++) {
if (!flag[i]) {
pr.push_back(i);
for (int j = i + i; j < MAXN; j += i) {
flag[j] = true;
}
}
}
int T;
for (scanf("%d", &T); T--; ) {
int n;
scanf("%d", &n);
int max_prime = 0;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
for (int j = 0; j < pr.size(); j++) {
while (x % pr[j] == 0) {
max_prime = max(max_prime, j);
x /= pr[j];
A[j] ^= 1 << i;
}
}
}
int r = gauss(A, max_prime + 1, n);
printf("%d\n", (pow2[n - r] - 1 + MOD) % MOD);
for (int i = 0; i <= max_prime; i++) {
A[i] = 0;
}
}
return 0;
}
| 22.313253 | 54 | 0.339633 | [
"vector"
] |
8e2e044a4393c2ae471d9fdeb9aa7f08150a2fd4 | 1,646 | cpp | C++ | GLLights/GLLightSystem.cpp | chen0040/cpp-steering-behaviors | c73d2ae8037556d42440b54ba6eb6190e467fae9 | [
"MIT"
] | 2 | 2020-11-10T12:24:41.000Z | 2021-09-25T08:24:06.000Z | GLLights/GLLightSystem.cpp | chen0040/cpp-steering-behaviors | c73d2ae8037556d42440b54ba6eb6190e467fae9 | [
"MIT"
] | null | null | null | GLLights/GLLightSystem.cpp | chen0040/cpp-steering-behaviors | c73d2ae8037556d42440b54ba6eb6190e467fae9 | [
"MIT"
] | 1 | 2021-08-14T16:34:33.000Z | 2021-08-14T16:34:33.000Z | #include "GLLightSystem.h"
GLLightSystem::GLLightSystem()
{
}
GLLightSystem::~GLLightSystem()
{
ClearLights();
}
void GLLightSystem::SetLight(GLint id, GLLight* pLight)
{
std::map<GLint, GLLight*>::iterator light_pos=m_lights.find(id);
if(light_pos==m_lights.end())
{
m_lights[id]=pLight;
}
else
{
if(light_pos->second != NULL)
{
delete light_pos->second;
}
light_pos->second=pLight;
if(pLight != NULL)
{
pLight->id=id;
}
}
}
void GLLightSystem::ClearLights()
{
std::map<GLint, GLLight*>::iterator pos;
for(pos=m_lights.begin(); pos!=m_lights.end(); ++pos)
{
if(pos->second != NULL)
{
delete pos->second;
pos->second=NULL;
}
}
m_lights.clear();
}
bool GLLightSystem::NoLights() const
{
std::map<GLint, GLLight*>::const_iterator pos;
for(pos=m_lights.begin(); pos!=m_lights.end(); ++pos)
{
if(pos->second != NULL)
{
return false;
}
}
return true;
}
void GLLightSystem::Render()
{
if(NoLights())
{
return;
}
std::map<GLint, GLLight*>::iterator pos;
for(pos=m_lights.begin(); pos!=m_lights.end(); ++pos)
{
if(pos->second != NULL)
{
pos->second->Render();
}
}
}
void GLLightSystem::PreRender()
{
if(NoLights())
{
return;
}
glEnable(GL_LIGHTING);
std::map<GLint, GLLight*>::iterator pos;
for(pos=m_lights.begin(); pos!=m_lights.end(); ++pos)
{
if(pos->second != NULL)
{
pos->second->PreRender();
}
}
}
void GLLightSystem::PostRender()
{
if(NoLights())
{
return;
}
std::map<GLint, GLLight*>::iterator pos;
for(pos=m_lights.begin(); pos!=m_lights.end(); ++pos)
{
if(pos->second != NULL)
{
pos->second->PostRender();
}
}
} | 14.438596 | 65 | 0.623329 | [
"render"
] |
8e30cb63ee2a60aae8e4544d0f951b0f1c4c666b | 4,415 | cpp | C++ | QueuePP/tests/DataBaseProcessor_Test/DataBaseProcessor_Test.cpp | AntonPoturaev/QueuePP | 25ea571abdd62ab6409da6dbad5bfcd20898ffb1 | [
"Unlicense"
] | null | null | null | QueuePP/tests/DataBaseProcessor_Test/DataBaseProcessor_Test.cpp | AntonPoturaev/QueuePP | 25ea571abdd62ab6409da6dbad5bfcd20898ffb1 | [
"Unlicense"
] | null | null | null | QueuePP/tests/DataBaseProcessor_Test/DataBaseProcessor_Test.cpp | AntonPoturaev/QueuePP | 25ea571abdd62ab6409da6dbad5bfcd20898ffb1 | [
"Unlicense"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// Project MIB3 Radio2/Connectivity
/// Copyright (c) 2017
/// Company Luxoft
/// All rights reserved
///
////////////////////////////////////////////////////////////////////////////////
/// @file DataBaseProccessor_Test.cpp
/// @authors kgmalakhov
/// @date 3/9/17
///
/// @brief Implementation of DataBaseProccessor_Test
///
////////////////////////////////////////////////////////////////////////////////
//#include <CL/DataBaseProcessor/DataReader.hpp>
#include <thread>
#include <iostream>
#include <ctime>
#include <sys/time.h>
#include <CL/DataBaseProcessor/Interfaces.hpp>
#include <CL/vCardParser/MicrocardParser.hpp>
#include <SharedMemory/SharedMemoryDriver.hpp>
#include <Phone/Types/Types.hpp>
#include <CL/Logger.hpp>
#include <CL/Logging/Logger.hpp>
#include <Types.hpp>
#define SHMEM_NAME "Arrakis"
#define SHMEM_SIZE 4092
using namespace Bluetooth::Organizer::DataBaseProcessor;
using namespace Bluetooth::CL;
void _InitLogger() {
SET_LOGGING_INFORMATION_SETTINGS("BTPlatform", "bluetooth_launcher");
Logging::Logger::SetFilter("DBProcessor::");
}
static const std::string uri_db = "333.444.555.667";//getExamplePath() + "base/phonebook.sqlite3";
static const std::string vcard_test = "./vcards/contacts2.vcf";
void printContact(Contact& contact) {
LOG_INFORMATION(boost::format("We got next %1% %2% %3%") % contact.GetID() %
reinterpret_cast<wchar_t*>(contact.GetFirstName().firstName) %
static_cast<wchar_t*>(contact.GetLastName().lastName));
}
void printCallHistory(CallHistoryItem& contact) {
LOG_INFORMATION(boost::format("We got next %1% %2% %3%") % contact.GetID() %
reinterpret_cast<char*>(contact.GetPhoneNumber().phoneNumber) %
static_cast<uint32_t>(contact.GetStatus()));
}
void print(uint32_t test) {
cout << test << std::endl;
}
std::string epochTimeToStr(const std::time_t& t) {
std::tm* ptm = std::localtime(&t);
const int buff_size = 32;
char buffer[buff_size];
std::strftime(buffer, buff_size, "%F %T", ptm);
return std::string(buffer);
}
void getAllContactById() {
tCallbackFunctionForContact callbackFunction = printContact;
std::vector<ContactRaw*> contacts;
// GetAllConactById(uri_db, contacts, callbackFunction);
}
void writeToDB(std::string& vcards) {
uint32_t start_time = clock();
tCallbackFunctionForvCard callbackFunction = print;
//SendVCards(uri_db, vcards, "SIM", callbackFunction);
uint32_t stop_time = clock();
}
void writeToCallHistory() {
SharedMemoryDriver shDriver(SHMEM_NAME, sizeof(ContactRaw));
SharedMemoryContext<CallHistoryItemRaw> shmemContext;
shmemContext.m_pObject = reinterpret_cast<CallHistoryItemRaw*>(shDriver.GetShmemAdress());
CallHistoryItem contact(shmemContext);
contact.SetID(-1);
contact.SetContactID(-1);
BtIf::Interface::Phone::tPhoneNumber phone = {"222-2222-4444"};
// phone
contact.SetPhoneNumber(phone);
contact.SetStatus(eCallHistoryItemStatus::CALLSTACKELEMENT_DIALED);
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t(system_clock::now());
contact.SetDateTime(epochTimeToStr(tt).c_str());
tCallbackFunctionForCallHistory callbackFunction = printCallHistory;
// WriteCallHistory(uri_db,contact,callbackFunction);
}
int main() {
//SharedMemoryDriver shmemHandler(SHMEM_NAME, SHMEM_SIZE);
LOG_INFORMATION("Start proccesses");
std::ifstream in;
LOG_INFORMATION("Open file");
in.open(vcard_test);
std::string vcards = std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
uint32_t start_time = clock();
Database::InitMultiThread();
writeToDB(vcards);
//std::thread fourd(writeToDB,vcards);
// std::thread first(getAllContactById);
// std::thread second(getAllContactById);
// std::thread third(getAllContactById);
// first.join();
// second.join();
// third.join();
//fourd.join();
uint32_t stop_time = clock();
LOG_INFORMATION(boost::format("The time of all processes are: %1% s.") %
(static_cast<float>((stop_time - start_time)) / CLOCKS_PER_SEC));
return 1;
}
| 32.226277 | 108 | 0.64598 | [
"vector"
] |
8e3b0d51b02ea0ce20b36df203d1d6e0c730a226 | 2,883 | h++ | C++ | libAmbrosia/Ambrosia/typedefs.h++ | rubenvb/Ambrosia | 479604d2f7c6c80c8313b27f31d8d4f0c57f89f3 | [
"CC0-1.0"
] | 2 | 2017-02-02T11:05:15.000Z | 2019-11-07T06:00:54.000Z | libAmbrosia/Ambrosia/typedefs.h++ | rubenvb/Ambrosia | 479604d2f7c6c80c8313b27f31d8d4f0c57f89f3 | [
"CC0-1.0"
] | null | null | null | libAmbrosia/Ambrosia/typedefs.h++ | rubenvb/Ambrosia | 479604d2f7c6c80c8313b27f31d8d4f0c57f89f3 | [
"CC0-1.0"
] | null | null | null | /**
*
* Project Ambrosia: Ambrosia library
*
* Written in 2012 by Ruben Van Boxem <vanboxem.ruben@gmail.com>
*
* To the extent possible under law, the author(s) have dedicated all copyright and related
* and neighboring rights to this software to the public domain worldwide. This software is
* distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this software.
* If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*
* Ambrosia/typedefs.h++
* Handy typedefs used throughout Ambrosia code as shorthand notation.
*
**/
#ifndef AMBROSIA_TYPEDEFS_H
#define AMBROSIA_TYPEDEFS_H
// Global includes
#include "Ambrosia/global.h++"
// libAmbrosia includes
#include "Ambrosia/build_element.h++"
#include "Ambrosia/enums.h++"
#include "Ambrosia/file.h++"
// C++ includes
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
/*
* STL typedefs
***************/
namespace ambrosia
{
// Homogeneous typedefs
typedef std::pair<std::string, std::string> string_pair;
typedef std::map<std::string, std::string> string_map;
typedef std::vector<std::string> string_vector;
typedef std::unordered_set<std::string> string_set; // must be unordered: insertion order must be maintained!
// Heterogeneous typedefs
typedef std::pair<std::string, bool> pair_string_bool;
typedef std::pair<std::string, string_set> pair_string_string_set;
typedef std::map<std::string, string_set> map_string_set_string;
typedef std::map<std::string, string_vector> map_string_string_vector;
} // namespace ambrosia
/*
* libAmbrosia typedefs
***********************/
namespace ambrosia
{
namespace lib
{
// Forward declarations
class binary;
struct dependency_paths;
class external;
class project;
class target;
namespace platform
{
struct command;
} // namespace platform
// homogeneous typedefs
typedef std::unordered_set<file> file_set;
typedef std::unordered_map<file, file> build_file_map;
typedef std::unordered_map<file_type, build_file_map> file_map;
typedef std::unordered_set<external> external_dependency_set;
typedef std::unique_ptr<target> target_ptr;
typedef std::vector<target_ptr> target_ptr_vector;
typedef std::vector<platform::command> command_vector;
typedef std::set<dependency_paths> dependency_paths_set;
// heterogeneous typedefs
typedef std::map<file_type, string_set> map_file_type_string_set;
typedef std::map<std::string, file_set> map_string_file_set;
typedef std::map<target_type, std::set<target*>> dependency_map;
typedef std::map<toolchain_option, std::string> toolchain_option_map;
typedef std::map<language_option, std::string> language_option_map;
typedef std::map<os_option, std::string> os_option_map;
} // namespace lib
} // namespace ambrosia
#endif // AMBROSIA_TYPEDEFS_H
| 27.990291 | 109 | 0.764828 | [
"vector"
] |
8e43b231743b0afa1da67a924930aa909b3cc8d9 | 14,246 | cpp | C++ | src/segmentation.cpp | Kukanani/orp | ff8eff74e1776691dfa7474bbd1e6a3d0d015a91 | [
"BSD-3-Clause"
] | 2 | 2020-11-04T22:24:56.000Z | 2020-11-18T02:30:38.000Z | src/segmentation.cpp | Kukanani/orp | ff8eff74e1776691dfa7474bbd1e6a3d0d015a91 | [
"BSD-3-Clause"
] | null | null | null | src/segmentation.cpp | Kukanani/orp | ff8eff74e1776691dfa7474bbd1e6a3d0d015a91 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2015, Adam Allevato
// Copyright (c) 2017, The University of Texas at Austin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <pcl/ModelCoefficients.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/conditional_removal.h>
#include <pcl/features/normal_3d.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/common/transforms.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl_ros/transforms.h>
#include <pcl_conversions/pcl_conversions.h>
#include "orp/core/segmentation.h"
int main(int argc, char **argv)
{
// Start the segmentation node and all ROS publishers
ros::init(argc, argv, "segmentation");
pcl::console::setVerbosityLevel(pcl::console::L_ALWAYS);
ROS_INFO("Starting Segmentation");
Segmentation s;
s.run();
return 1;
} //main
Segmentation::Segmentation() :
node("segmentation"),
transformToFrame(),
listener(),
spinner(4),
maxClusters(100)
{
ros::NodeHandle privateNode("~");
if(!privateNode.getParam("clippingFrame", transformToFrame)) {
transformToFrame = "odom";
}
boundedScenePublisher =
privateNode.advertise<sensor_msgs::PointCloud2>("bounded_scene", 5);
voxelPublisher =
privateNode.advertise<sensor_msgs::PointCloud2>("voxel_scene", 5);
allPlanesPublisher =
privateNode.advertise<sensor_msgs::PointCloud2>("all_planes", 5);
largestObjectPublisher =
privateNode.advertise<sensor_msgs::PointCloud2>("largest_object", 5);
allObjectsPublisher =
privateNode.advertise<sensor_msgs::PointCloud2>("all_objects", 5);
segmentationServer =
node.advertiseService("segmentation", &Segmentation::cb_segment, this);
// dynamic reconfigure
reconfigureCallbackType =
boost::bind(&Segmentation::paramsChanged, this, _1, _2);
reconfigureServer.setCallback(reconfigureCallbackType);
}
void Segmentation::run() {
ROS_INFO("Segmentation running...");
spinner.start();
ros::waitForShutdown();
}
void Segmentation::paramsChanged(
orp::SegmentationConfig &config, uint32_t level)
{
//spatial bounds
minX = config.spatial_min_x;
maxX = config.spatial_max_x;
minY = config.spatial_min_y;
maxY = config.spatial_max_y;
minZ = config.spatial_min_z;
maxZ = config.spatial_max_z;
maxClusters = config.max_clusters;
//Segmentation
maxPlaneSegmentationIterations = config.max_plane_segmentation_iterations;
segmentationDistanceThreshold = config.segmentation_distance_threshold;
percentageToAnalyze = config.percentage_to_analyze;
//filtering
voxelLeafSize = config.voxel_leaf_size;
//clustering
clusterTolerance = config.cluster_tolerance;
minClusterSize = config.min_cluster_size;
maxClusterSize = config.max_cluster_size;
_publishAllObjects = config.publishAllObjects;
_publishAllPlanes = config.publishAllPlanes;
_publishBoundedScene = config.publishBoundedScene;
_publishLargestObject = config.publishLargestObject;
_publishVoxelScene = config.publishVoxelScene;
}
bool compareClusterSize(
const sensor_msgs::PointCloud2& a,
const sensor_msgs::PointCloud2& b)
{
return a.width > b.width;
}
bool Segmentation::cb_segment(orp::Segmentation::Request &req,
orp::Segmentation::Response &response) {
ROS_DEBUG("received segmentation request");
if(req.scene.height * req.scene.width < 3) {
ROS_DEBUG("Not segmenting cloud, it's too small.");
return false;
}
PC tmpCloud;
// processCloud = PCPtr(new PC());
// inputCloud->points.clear();
originalCloudFrame = req.scene.header.frame_id;
sensor_msgs::PointCloud2 transformedMessage;
sensor_msgs::PointCloud2 rawMessage;
if(transformToFrame == "") {
pcl::fromROSMsg(req.scene, tmpCloud);
rawMessage.header.frame_id = req.scene.header.frame_id;
}
else if(listener.waitForTransform(
req.scene.header.frame_id, transformToFrame, req.scene.header.stamp,
ros::Duration(0.5)))
{
pcl_ros::transformPointCloud(transformToFrame, req.scene,
transformedMessage, listener);
pcl::fromROSMsg(transformedMessage, tmpCloud);
}
else {
ROS_WARN_STREAM_THROTTLE(60,
"listen for transformation from " <<
req.scene.header.frame_id.c_str() <<
" to " << transformToFrame.c_str() <<
" timed out. Proceeding...");
pcl::fromROSMsg(req.scene, tmpCloud);
rawMessage.header.frame_id = req.scene.header.frame_id;
}
PCPtr inputCloud = PCPtr(new PC(tmpCloud));
if(inputCloud->points.size() <= minClusterSize) {
ROS_INFO_STREAM(
"point cloud is too small to segment: Min: " <<
minClusterSize << ", actual: " << inputCloud->points.size());
return false;
}
//clip
int preVoxel = inputCloud->points.size();
*inputCloud =
*(clipByDistance(inputCloud, minX, maxX, minY, maxY, minZ, maxZ));
if(_publishBoundedScene) {
pcl::toROSMsg(*inputCloud, transformedMessage);
transformedMessage.header.frame_id = transformToFrame;
boundedScenePublisher.publish(transformedMessage);
}
*inputCloud = *(voxelGridify(inputCloud, voxelLeafSize));
if(!inputCloud->points.empty() && inputCloud->points.size() < preVoxel) {
// Publish voxelized
if(_publishVoxelScene) {
sensor_msgs::PointCloud2 voxelized_cloud;
pcl::toROSMsg(*inputCloud, voxelized_cloud);
voxelized_cloud.header.frame_id = transformToFrame;
voxelPublisher.publish(voxelized_cloud);
}
//remove planes
inputCloud =
removePrimaryPlanes(inputCloud,maxPlaneSegmentationIterations,
segmentationDistanceThreshold, percentageToAnalyze, transformToFrame);
if(_publishAllObjects) {
pcl::toROSMsg(*inputCloud, transformedMessage);
transformedMessage.header.frame_id = transformToFrame;
allObjectsPublisher.publish(transformedMessage);
}
if(_publishLargestObject) {
response.clusters = cluster(inputCloud, clusterTolerance, minClusterSize,
maxClusterSize);
if(!response.clusters.empty()) {
largestObjectPublisher.publish(response.clusters[0]);
}
}
} else {
if(inputCloud->points.empty()) {
ROS_WARN_STREAM("After filtering, the cloud "
<< "contained no points. No segmentation will occur.");
}
else {
ROS_ERROR_STREAM(
"After filtering, the cloud contained "
<< inputCloud->points.size() << " points. This is more than BEFORE "
<< "the voxel filter was applied, so something is wrong. No "
<< "segmentation will occur.");
}
}
return true;
}
PCPtr Segmentation::clipByDistance(PCPtr &unclipped,
float minX, float maxX, float minY, float maxY, float minZ, float maxZ) {
PCPtr processCloud = PCPtr(new PC());
// processCloud->resize(0);
// We must build a condition.
// And "And" condition requires all tests to check true.
// "Or" conditions also available.
// Checks available: GT, GE, LT, LE, EQ.
pcl::ConditionAnd<ORPPoint>::Ptr clip_condition(
new pcl::ConditionAnd<ORPPoint>);
clip_condition->addComparison(pcl::FieldComparison<ORPPoint>::ConstPtr(
new pcl::FieldComparison<ORPPoint>("x", pcl::ComparisonOps::GT, minX)));
clip_condition->addComparison(pcl::FieldComparison<ORPPoint>::ConstPtr(
new pcl::FieldComparison<ORPPoint>("x", pcl::ComparisonOps::LT, maxX)));
clip_condition->addComparison(pcl::FieldComparison<ORPPoint>::ConstPtr(
new pcl::FieldComparison<ORPPoint>("y", pcl::ComparisonOps::GT, minY)));
clip_condition->addComparison(pcl::FieldComparison<ORPPoint>::ConstPtr(
new pcl::FieldComparison<ORPPoint>("y", pcl::ComparisonOps::LT, maxY)));
clip_condition->addComparison(pcl::FieldComparison<ORPPoint>::ConstPtr(
new pcl::FieldComparison<ORPPoint>("z", pcl::ComparisonOps::GT, minZ)));
clip_condition->addComparison(pcl::FieldComparison<ORPPoint>::ConstPtr(
new pcl::FieldComparison<ORPPoint>("z", pcl::ComparisonOps::LT, maxZ)));
// Filter object.
pcl::ConditionalRemoval<ORPPoint> filter;
filter.setCondition(clip_condition);
filter.setInputCloud(unclipped);
// If true, points that do not pass the filter will be set to a certain value
// (default NaN). If false, they will be just removed, but that could break
// the structure of the cloud (organized clouds are clouds taken from
// camera-like sensors that return a matrix-like image).
filter.setKeepOrganized(true);
// If keep organized was set true, points that failed the test will have
// their Z value set to this.
filter.setUserFilterValue(0.0);
filter.filter(*processCloud);
return processCloud;
}
PCPtr Segmentation::voxelGridify(PCPtr &loose, float gridSize) {
//ROS_INFO("Voxel grid filtering...");
PCPtr processCloud = PCPtr(new PC());
// processCloud->resize(0);
// Create the filtering object: downsample the dataset
pcl::VoxelGrid<ORPPoint> vg;
vg.setInputCloud(loose);
vg.setLeafSize(gridSize, gridSize, gridSize);
vg.filter(*processCloud);
return processCloud;
}
PCPtr Segmentation::removePrimaryPlanes(PCPtr &input, int maxIterations,
float thresholdDistance, float percentageGood, std::string parentFrame)
{
PCPtr planes(new PC());
PCPtr planeCloud(new PC());
PCPtr processCloud = PCPtr(new PC());
// processCloud->resize(0);
// Create the segmentation object for the planar model and set all the
// parameters
pcl::SACSegmentation<ORPPoint> seg;
seg.setOptimizeCoefficients (true);
seg.setModelType (pcl::SACMODEL_PLANE);
seg.setMethodType (pcl::SAC_RANSAC);
seg.setMaxIterations (maxIterations);
seg.setDistanceThreshold (thresholdDistance);
pcl::PointIndices::Ptr planeIndices(new pcl::PointIndices);
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
pcl::PCDWriter writer;
//how many points to get leave
int targetSize = percentageGood * input->points.size();
//ROS_INFO("target size: %d", targetSize);
while(input->points.size() > targetSize) {
seg.setInputCloud(input);
seg.segment (*planeIndices, *coefficients);
if(planeIndices->indices.size () == 0) {
ROS_ERROR_THROTTLE(10,
"Could not find any good planes in the point cloud (printed every 10s)...");
break;
}
// Segment the largest planar component from the remaining cloud
pcl::ExtractIndices<ORPPoint> extract;
extract.setInputCloud(input);
extract.setIndices(planeIndices);
//extract.setNegative(false);
extract.filter (*planeCloud);
//store it for the planes message
planes->insert(planes->end(), planeCloud->begin(), planeCloud->end());
//now actually take it out
extract.setNegative(true);
extract.filter(*processCloud);
input = processCloud;
//ROS_INFO("removed a plane.");
}
// Publish dominant planes
if(_publishAllPlanes) {
sensor_msgs::PointCloud2 planes_pc2;
pcl::toROSMsg(*planes, planes_pc2);
planes_pc2.header.frame_id = parentFrame;
allPlanesPublisher.publish(planes_pc2);
}
return input;
}
std::vector<sensor_msgs::PointCloud2> Segmentation::cluster(
PCPtr &input, float clusterTolerance,
int minClusterSize, int maxClusterSize)
{
// clusters.clear();
std::vector<sensor_msgs::PointCloud2> clusters;
// Creating the KdTree object for the search method of the extraction
pcl::search::KdTree<ORPPoint>::Ptr tree (new pcl::search::KdTree<ORPPoint>);
tree->setInputCloud (input);
IndexVector cluster_indices;
pcl::EuclideanClusterExtraction<ORPPoint> ec;
ec.setInputCloud(input);
ec.setClusterTolerance(clusterTolerance);
ec.setMinClusterSize(minClusterSize);
ec.setMaxClusterSize(maxClusterSize);
ec.setSearchMethod(tree);
ec.extract (cluster_indices);
if(cluster_indices.empty()) return clusters;
// go through the set of indices. Each set of indices is one cloud
for(IndexVector::const_iterator it = cluster_indices.begin();
it != cluster_indices.end(); ++it)
{
//extract all the points based on the set of indices
PCPtr processCloud = PCPtr(new PC());
for(std::vector<int>::const_iterator pit = it->indices.begin();
pit != it->indices.end (); ++pit)
{
processCloud->points.push_back (input->points[*pit]);
}
processCloud->width = processCloud->points.size();
processCloud->height = 1;
processCloud->is_dense = true;
//publish the cluster
sensor_msgs::PointCloud2 tempROSMsg;
pcl::toROSMsg(*processCloud, tempROSMsg);
tempROSMsg.header.frame_id = transformToFrame;
clusters.push_back(tempROSMsg);
}
if(clusters.size() > 0) {
std::sort(clusters.begin(), clusters.end(), compareClusterSize);
}
return clusters;
}
| 34.6618 | 84 | 0.727573 | [
"object",
"vector",
"model"
] |
8e4f1ff02f1b801a1499dfdf4ae9807153e35b8f | 4,295 | cc | C++ | KM/03code/cpp/chenshuo/muduo/muduo/net/inspect/Inspector.cc | wangcy6/weekly.github.io | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 10 | 2019-03-17T10:13:04.000Z | 2021-03-03T03:23:34.000Z | KM/03code/cpp/chenshuo/muduo/muduo/net/inspect/Inspector.cc | wangcy6/weekly.github.io | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 44 | 2018-12-14T02:35:47.000Z | 2021-02-06T09:12:10.000Z | KM/03code/cpp/chenshuo/muduo/muduo/net/inspect/Inspector.cc | wangcy6/weekly | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 1 | 2020-02-03T12:14:08.000Z | 2020-02-03T12:14:08.000Z | // Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
#include <muduo/net/inspect/Inspector.h>
#include <muduo/base/Thread.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/http/HttpRequest.h>
#include <muduo/net/http/HttpResponse.h>
#include <muduo/net/inspect/ProcessInspector.h>
//#include <iostream>
//#include <iterator>
//#include <sstream>
#include <boost/bind.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
using namespace muduo;
using namespace muduo::net;
namespace
{
Inspector* g_globalInspector = 0;
// Looks buggy
std::vector<string> split(const string& str)
{
std::vector<string> result;
size_t start = 0;
size_t pos = str.find('/');
while (pos != string::npos)
{
if (pos > start)
{
result.push_back(str.substr(start, pos-start));
}
start = pos+1;
pos = str.find('/', start);
}
if (start < str.length())
{
result.push_back(str.substr(start));
}
return result;
}
}
Inspector::Inspector(EventLoop* loop,
const InetAddress& httpAddr,
const string& name)
: server_(loop, httpAddr, "Inspector:"+name),
processInspector_(new ProcessInspector)
{
assert(CurrentThread::isMainThread());
assert(g_globalInspector == 0);
g_globalInspector = this;
server_.setHttpCallback(boost::bind(&Inspector::onRequest, this, _1, _2));
processInspector_->registerCommands(this);
loop->runAfter(0, boost::bind(&Inspector::start, this)); // little race condition
}
Inspector::~Inspector()
{
assert(CurrentThread::isMainThread());
g_globalInspector = NULL;
}
void Inspector::add(const string& module,
const string& command,
const Callback& cb,
const string& help)
{
MutexLockGuard lock(mutex_);
commands_[module][command] = cb;
helps_[module][command] = help;
}
void Inspector::start()
{
server_.start();
}
void Inspector::onRequest(const HttpRequest& req, HttpResponse* resp)
{
if (req.path() == "/")
{
string result;
MutexLockGuard lock(mutex_);
for (std::map<string, HelpList>::const_iterator helpListI = helps_.begin();
helpListI != helps_.end();
++helpListI)
{
const HelpList& list = helpListI->second;
for (HelpList::const_iterator it = list.begin();
it != list.end();
++it)
{
result += "/";
result += helpListI->first;
result += "/";
result += it->first;
result += "\t";
result += it->second;
result += "\n";
}
}
resp->setStatusCode(HttpResponse::k200Ok);
resp->setStatusMessage("OK");
resp->setContentType("text/plain");
resp->setBody(result);
}
else
{
std::vector<string> result = split(req.path());
// boost::split(result, req.path(), boost::is_any_of("/"));
//std::copy(result.begin(), result.end(), std::ostream_iterator<string>(std::cout, ", "));
//std::cout << "\n";
bool ok = false;
if (result.size() == 0)
{
}
else if (result.size() == 1)
{
string module = result[0];
}
else
{
string module = result[0];
std::map<string, CommandList>::const_iterator commListI = commands_.find(module);
if (commListI != commands_.end())
{
string command = result[1];
const CommandList& commList = commListI->second;
CommandList::const_iterator it = commList.find(command);
if (it != commList.end())
{
ArgList args(result.begin()+2, result.end());
if (it->second)
{
resp->setStatusCode(HttpResponse::k200Ok);
resp->setStatusMessage("OK");
resp->setContentType("text/plain");
const Callback& cb = it->second;
resp->setBody(cb(req.method(), args));
ok = true;
}
}
}
}
if (!ok)
{
resp->setStatusCode(HttpResponse::k404NotFound);
resp->setStatusMessage("Not Found");
}
//resp->setCloseConnection(true);
}
}
| 25.116959 | 94 | 0.602095 | [
"vector"
] |
8e4feb873815da19c06fa0f30cb129b0d454326d | 704 | cpp | C++ | Game/Source/SceneWin.cpp | MagiX7/BlackHole_Engine | eb32c1a3653be4d0cf369104261245e8db71f63d | [
"MIT"
] | null | null | null | Game/Source/SceneWin.cpp | MagiX7/BlackHole_Engine | eb32c1a3653be4d0cf369104261245e8db71f63d | [
"MIT"
] | null | null | null | Game/Source/SceneWin.cpp | MagiX7/BlackHole_Engine | eb32c1a3653be4d0cf369104261245e8db71f63d | [
"MIT"
] | 1 | 2022-02-16T07:10:47.000Z | 2022-02-16T07:10:47.000Z | #include "Input.h"
#include "Render.h"
#include "Texture.h"
#include "SceneWin.h"
SceneWin::SceneWin()
{
}
SceneWin::~SceneWin()
{
}
bool SceneWin::Load(Texture* tex)
{
LOG("Loading Win Scene");
bg = tex->Load("Assets/Textures/win.png");
return true;
}
update_status SceneWin::Update(Input* input, float dt)
{
if (input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) TransitionToScene(SceneType::INTRO);
return update_status::UPDATE_CONTINUE;
}
update_status SceneWin::Draw(Render* ren)
{
ren->DrawTexture(bg, -ren->camera.x, -ren->camera.y, NULL);
return update_status::UPDATE_CONTINUE;
}
bool SceneWin::Unload(Texture* tex)
{
LOG("Unloading Win Scene");
tex->UnLoad(bg);
return true;
} | 16 | 88 | 0.707386 | [
"render"
] |
8e5233a8db5af4dc512f6685cafb032888cb2618 | 19,711 | cpp | C++ | src/py/wrapper/wrapper_c047f2c3135554ceb57f166fd404cfc8.cpp | StatisKit/Containers | cf665a2a1f9d36d4ae618b18a40c112ee9f02ac6 | [
"Apache-2.0"
] | null | null | null | src/py/wrapper/wrapper_c047f2c3135554ceb57f166fd404cfc8.cpp | StatisKit/Containers | cf665a2a1f9d36d4ae618b18a40c112ee9f02ac6 | [
"Apache-2.0"
] | 2 | 2018-02-26T08:52:12.000Z | 2018-04-19T14:47:19.000Z | src/py/wrapper/wrapper_c047f2c3135554ceb57f166fd404cfc8.cpp | StatisKit/Containers | cf665a2a1f9d36d4ae618b18a40c112ee9f02ac6 | [
"Apache-2.0"
] | 11 | 2017-02-10T10:32:11.000Z | 2021-03-15T18:23:51.000Z | #include "_stl.h"
void (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_a7967f8e767754c5bb2a4a4052371685)(::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type , ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::value_type const &)= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::assign;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_c1f800ce071252f09449a5c04529e68d)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_84f98cd7a1a954a7b20c702ba31ee3af)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::max_size;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_d22351adf080548a8da6664cb7692cc3)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::capacity;
bool (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_d21db8339ef15d679723d862cb136452)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::empty;
void (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_c307a0ae856d579c9936274439d8aa1c)(::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type )= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reserve;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reference (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_ef7dce5e2268547fabb5bf655fe058a7)(::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type )= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::at;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::const_reference (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_6a7baa2cb5ec5b84b1164a172dc8285c)(::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type )const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::at;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reference (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_94e70d1afbe654acb6ffb60829d084e9)()= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::front;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::const_reference (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_9a0380d47fb15fb5a10831a2d938f60d)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::front;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reference (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_041189c9874b534a9acff0f5971a6e7e)()= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::back;
::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::const_reference (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_99d28d6c9117580e958bee01d4669e38)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::back;
class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > * (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_f283bc258f9c5afd81d1ebc6da188cce)()= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::data;
class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > const * (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_8bd6cae0a1195956b7bda20cc0758c10)()const= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::data;
void (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_80e4bd9c547a58cd834181f28c51f096)(::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::value_type const &)= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::push_back;
void (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_e0195fd91cbb544da94e2cc2802e9c3f)()= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::pop_back;
void (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_b1c5806478da532b9e5b0ea18dccf50b)(class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > > &)= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::swap;
void (::std::vector< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > >, ::std::allocator< ::std::basic_string< char, ::std::char_traits< char >, ::std::allocator< char > > > >::*method_pointer_43b2bb197eb45b98bed1a1bca3addafb)()= &::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::clear;
namespace autowig {
void method_decorator_ef7dce5e2268547fabb5bf655fe058a7(class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > > & instance, ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::size_type param_in_0, const ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reference param_out) { instance.at(param_in_0) = param_out; }
void method_decorator_94e70d1afbe654acb6ffb60829d084e9(class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > > & instance, const ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reference param_out) { instance.front() = param_out; }
void method_decorator_041189c9874b534a9acff0f5971a6e7e(class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > > & instance, const ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >::reference param_out) { instance.back() = param_out; }
}
void wrapper_c047f2c3135554ceb57f166fd404cfc8(pybind11::module& module)
{
pybind11::class_<class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > >, autowig::HolderType< class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > > >::Type > class_c047f2c3135554ceb57f166fd404cfc8(module, "_Vector_c047f2c3135554ceb57f166fd404cfc8", "");
class_c047f2c3135554ceb57f166fd404cfc8.def(pybind11::init< >());
class_c047f2c3135554ceb57f166fd404cfc8.def(pybind11::init< class ::std::vector< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > >, class ::std::allocator< class ::std::basic_string< char, struct ::std::char_traits< char >, class ::std::allocator< char > > > > const & >());
class_c047f2c3135554ceb57f166fd404cfc8.def("assign", method_pointer_a7967f8e767754c5bb2a4a4052371685, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("__len__", method_pointer_c1f800ce071252f09449a5c04529e68d, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("max_size", method_pointer_84f98cd7a1a954a7b20c702ba31ee3af, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("capacity", method_pointer_d22351adf080548a8da6664cb7692cc3, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("empty", method_pointer_d21db8339ef15d679723d862cb136452, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("reserve", method_pointer_c307a0ae856d579c9936274439d8aa1c, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("at", method_pointer_ef7dce5e2268547fabb5bf655fe058a7, pybind11::return_value_policy::reference_internal, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("at", autowig::method_decorator_ef7dce5e2268547fabb5bf655fe058a7);
class_c047f2c3135554ceb57f166fd404cfc8.def("at", method_pointer_6a7baa2cb5ec5b84b1164a172dc8285c, pybind11::return_value_policy::copy, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("front", method_pointer_94e70d1afbe654acb6ffb60829d084e9, pybind11::return_value_policy::reference_internal, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("front", autowig::method_decorator_94e70d1afbe654acb6ffb60829d084e9);
class_c047f2c3135554ceb57f166fd404cfc8.def("front", method_pointer_9a0380d47fb15fb5a10831a2d938f60d, pybind11::return_value_policy::copy, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("back", method_pointer_041189c9874b534a9acff0f5971a6e7e, pybind11::return_value_policy::reference_internal, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("back", autowig::method_decorator_041189c9874b534a9acff0f5971a6e7e);
class_c047f2c3135554ceb57f166fd404cfc8.def("back", method_pointer_99d28d6c9117580e958bee01d4669e38, pybind11::return_value_policy::copy, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("data", method_pointer_f283bc258f9c5afd81d1ebc6da188cce, pybind11::return_value_policy::reference_internal, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("data", method_pointer_8bd6cae0a1195956b7bda20cc0758c10, pybind11::return_value_policy::reference_internal, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("push_back", method_pointer_80e4bd9c547a58cd834181f28c51f096, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("pop_back", method_pointer_e0195fd91cbb544da94e2cc2802e9c3f, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("swap", method_pointer_b1c5806478da532b9e5b0ea18dccf50b, "");
class_c047f2c3135554ceb57f166fd404cfc8.def("clear", method_pointer_43b2bb197eb45b98bed1a1bca3addafb, "");
} | 351.982143 | 1,042 | 0.701081 | [
"vector"
] |
8e53b63080309197f82b48be4e8ae92cb01055d3 | 25,112 | hpp | C++ | MntoneUIFramework/include/win32define.hpp | mntone/MntoneUIFramework | 61a66977b2a1d8a9208d998493f8f99c6aa94380 | [
"MIT"
] | 12 | 2015-07-06T10:18:12.000Z | 2019-03-11T02:48:00.000Z | MntoneUIFramework/include/win32define.hpp | mntone/MntoneUIFramework | 61a66977b2a1d8a9208d998493f8f99c6aa94380 | [
"MIT"
] | null | null | null | MntoneUIFramework/include/win32define.hpp | mntone/MntoneUIFramework | 61a66977b2a1d8a9208d998493f8f99c6aa94380 | [
"MIT"
] | 4 | 2016-07-06T13:04:17.000Z | 2019-10-19T02:08:25.000Z | #pragma once
#include <Windows.h>
#define DEFINE_ENUM_BIT_CALC(_T_) \
using _T_ ## _t = ::std::underlying_type_t<_T_>; \
inline _T_ operator&(_T_ lhs, _T_ rhs) { return static_cast<_T_>(static_cast<_T_ ## _t>(lhs) & static_cast<_T_ ## _t>(rhs)); } \
inline _T_ operator&=(_T_& lhs, _T_ rhs) { lhs = static_cast<_T_>(static_cast<_T_ ## _t>(lhs) & static_cast<_T_ ## _t>(rhs)); return lhs; } \
inline _T_ operator|(_T_ lhs, _T_ rhs) { return static_cast<_T_>(static_cast<_T_ ## _t>(lhs) | static_cast<_T_ ## _t>(rhs)); } \
inline _T_ operator|=(_T_& lhs, _T_ rhs) { lhs = static_cast<_T_>(static_cast<_T_ ## _t>(lhs) | static_cast<_T_ ## _t>(rhs)); return lhs; } \
inline _T_ operator^(_T_ lhs, _T_ rhs) { return static_cast<_T_>(static_cast<_T_ ## _t>(lhs) ^ static_cast<_T_ ## _t>(rhs)); } \
inline _T_ operator^=(_T_& lhs, _T_ rhs) { lhs = static_cast<_T_>(static_cast<_T_ ## _t>(lhs) ^ static_cast<_T_ ## _t>(rhs)); return lhs; } \
inline _T_ operator~(_T_ one) { return static_cast<_T_>(~static_cast<_T_ ## _t>(one)); }
namespace mnfx {
#ifndef NOWINMESSAGES
enum class window_message : UINT
{
null = WM_NULL,
create = WM_CREATE,
destroy = WM_DESTROY,
move = WM_MOVE,
size = WM_SIZE,
activate = WM_ACTIVATE,
set_focus = WM_SETFOCUS,
kill_focus = WM_KILLFOCUS,
enable = WM_ENABLE,
set_redraw = WM_SETREDRAW,
set_text = WM_SETTEXT,
get_text = WM_GETTEXT,
get_text_length = WM_GETTEXTLENGTH,
paint = WM_PAINT,
close = WM_CLOSE,
#ifndef _WIN32_WCE
query_end_session = WM_QUERYENDSESSION,
query_open = WM_QUERYOPEN,
end_session = WM_ENDSESSION,
#endif
quit = WM_QUIT,
erase_background = WM_ERASEBKGND,
system_color_change = WM_SYSCOLORCHANGE,
show_window = WM_SHOWWINDOW,
winini_change = WM_WININICHANGE,
#if( WINVER >= 0x0400 )
setting_change = WM_SETTINGCHANGE,
#endif
device_mode_change = WM_DEVMODECHANGE,
activate_app = WM_ACTIVATEAPP,
font_change = WM_FONTCHANGE,
time_change = WM_TIMECHANGE,
cancel_mode = WM_CANCELMODE,
set_cursor = WM_SETCURSOR,
mouse_activate = WM_MOUSEACTIVATE,
child_activate = WM_CHILDACTIVATE,
queue_sync = WM_QUEUESYNC,
get_minmax_info = WM_GETMINMAXINFO,
paint_icon = WM_PAINTICON,
icon_erase_background = WM_ICONERASEBKGND,
next_dialog_control = WM_NEXTDLGCTL,
spooler_status = WM_SPOOLERSTATUS,
draw_item = WM_DRAWITEM,
measure_item = WM_MEASUREITEM,
delete_imte = WM_DELETEITEM,
virtual_key_to_item = WM_VKEYTOITEM,
char_to_item = WM_CHARTOITEM,
set_font = WM_SETFONT,
get_font = WM_GETFONT,
set_hotkey = WM_SETHOTKEY,
get_hotkey = WM_GETHOTKEY,
query_drag_icon = WM_QUERYDRAGICON,
compare_item = WM_COMPAREITEM,
#if( WINVER >= 0x0500 )
#ifndef _WIN32_WCE
get_object = WM_GETOBJECT,
#endif
#endif
compacting = WM_COMPACTING,
//comm_notify = WM_COMMNOTIFY, <- no longer support
window_position_changing = WM_WINDOWPOSCHANGING,
window_position_changed = WM_WINDOWPOSCHANGED,
power = WM_POWER,
copy_data = WM_COPYDATA,
cancel_journal = WM_CANCELJOURNAL,
#if( WINVER >= 0x0400 )
notify = WM_NOTIFY,
input_language_change_request = WM_INPUTLANGCHANGEREQUEST,
input_language_change = WM_INPUTLANGCHANGE,
tcard = WM_TCARD,
help = WM_HELP,
user_changed = WM_USERCHANGED,
notify_format = WM_NOTIFYFORMAT,
context_menu = WM_CONTEXTMENU,
style_changing = WM_STYLECHANGING,
style_changed = WM_STYLECHANGED,
display_change = WM_DISPLAYCHANGE,
get_icon = WM_GETICON,
set_icon = WM_SETICON,
#endif
nc_create = WM_NCCREATE,
nc_destroy = WM_NCDESTROY,
nc_calculate_size = WM_NCCALCSIZE,
nc_hittest = WM_NCHITTEST,
nc_paint = WM_NCPAINT,
nc_activate = WM_NCACTIVATE,
get_dialog_code = WM_GETDLGCODE,
#ifndef _WIN32_WCE
sync_paint = WM_SYNCPAINT,
#endif
nc_mouse_move = WM_NCMOUSEMOVE,
nc_left_button_down = WM_NCLBUTTONDOWN,
nc_left_button_up = WM_NCLBUTTONUP,
nc_left_button_double_click = WM_NCLBUTTONDBLCLK,
nc_right_button_down = WM_NCRBUTTONDOWN,
nc_right_button_up = WM_NCRBUTTONUP,
nc_right_button_double_click = WM_NCRBUTTONDBLCLK,
nc_middle_button_down = WM_NCMBUTTONDOWN,
nc_middle_button_up = WM_NCMBUTTONUP,
nc_middle_button_double_click = WM_NCMBUTTONDBLCLK,
#if( _WIN32_WINNT >= 0x0500 )
nc_x_button_down = WM_NCXBUTTONDOWN,
nc_x_button_up = WM_NCXBUTTONUP,
nc_x_button_double_click = WM_NCXBUTTONDBLCLK,
#endif
#if( _WIN32_WINNT >= 0x0501 )
input_device_change = WM_INPUT_DEVICE_CHANGE,
input = WM_INPUT,
#endif
key_first = WM_KEYFIRST,
key_down = WM_KEYDOWN,
key_up = WM_KEYUP,
wmchar = WM_CHAR,
dead_char = WM_DEADCHAR,
system_key_down = WM_SYSKEYDOWN,
system_key_up = WM_SYSKEYUP,
system_char = WM_SYSCHAR,
system_dead_char = WM_SYSDEADCHAR,
#if( _WIN32_WINNT >= 0x0501 )
unicode_char = WM_UNICHAR,
#endif
key_last = WM_KEYLAST,
#if( WINVER >= 0x0400 )
ime_start_composition = WM_IME_STARTCOMPOSITION,
ime_end_composition = WM_IME_ENDCOMPOSITION,
ime_composition = WM_IME_COMPOSITION,
ime_key_last = WM_IME_KEYLAST,
#endif
initialize_dialog = WM_INITDIALOG,
command = WM_COMMAND,
system_command = WM_SYSCOMMAND,
timer = WM_TIMER,
horizontal_scroll = WM_HSCROLL,
vertical_scroll = WM_VSCROLL,
initialize_menu = WM_INITMENU,
initialize_menu_popup = WM_INITMENUPOPUP,
#if( WINVER >= 0x0601 )
gesture = WM_GESTURE,
gesture_notify = WM_GESTURENOTIFY,
#endif
menu_selection = WM_MENUSELECT,
menu_char = WM_MENUCHAR,
enter_idle = WM_ENTERIDLE,
#if( WINVER >= 0x0500 )
#ifndef _WIN32_WCE
menu_right_button_up = WM_MENURBUTTONUP,
menu_drag = WM_MENUDRAG,
menu_get_object = WM_MENUGETOBJECT,
uninitialize_menu_popup = WM_UNINITMENUPOPUP,
menu_command = WM_MENUCOMMAND,
change_ui_state = WM_CHANGEUISTATE,
update_ui_state = WM_UPDATEUISTATE,
query_ui_state = WM_QUERYUISTATE,
#endif
#endif
control_color_message_box = WM_CTLCOLORMSGBOX,
control_color_edit_box = WM_CTLCOLOREDIT,
control_color_list_box = WM_CTLCOLORLISTBOX,
control_color_button = WM_CTLCOLORBTN,
control_color_dialog = WM_CTLCOLORDLG,
control_color_scroll_bar = WM_CTLCOLORSCROLLBAR,
control_color_static = WM_CTLCOLORSTATIC,
mouse_first = WM_MOUSEFIRST,
mouse_move = WM_MOUSEMOVE,
left_button_down = WM_LBUTTONDOWN,
left_button_up = WM_LBUTTONUP,
left_button_double_click = WM_LBUTTONDBLCLK,
right_button_down = WM_RBUTTONDOWN,
right_button_up = WM_RBUTTONUP,
right_button_double_click = WM_RBUTTONDBLCLK,
middle_button_down = WM_MBUTTONDOWN,
middle_button_up = WM_MBUTTONUP,
middle_button_double_click = WM_MBUTTONDBLCLK,
#if( _WIN32_WINNT >= 0x0400 ) || ( _WIN32_WINDOWS > 0x0400 )
mouse_wheel = WM_MOUSEWHEEL,
#endif
#if( _WIN32_WINNT >= 0x0500 )
x_button_down = WM_XBUTTONDOWN,
x_button_up = WM_XBUTTONUP,
x_button_double_click = WM_XBUTTONDBLCLK,
#endif
#if( _WIN32_WINNT >= 0x0600 )
mouse_horizontal_wheel = WM_MOUSEHWHEEL,
#endif
mouse_last = WM_MOUSELAST,
parent_notify = WM_PARENTNOTIFY,
enter_menu_loop = WM_ENTERMENULOOP,
exit_menu_loop = WM_EXITMENULOOP,
#if( WINVER >= 0x0400 )
next_menu = WM_NEXTMENU,
sizing = WM_SIZING,
capture_changed = WM_CAPTURECHANGED,
moving = WM_MOVING,
power_broadcast = WM_POWERBROADCAST,
device_change = WM_DEVICECHANGE,
#endif
#ifdef _USE_MDI
mdi_create = WM_MDICREATE,
mdi_destroy = WM_MDIDESTROY,
mdi_activate = WM_MDIACTIVATE,
mdi_restore = WM_MDIRESTORE,
mdi_next = WM_MDINEXT,
mdi_maximize = WM_MDIMAXIMIZE,
mdi_tile = WM_MDITILE,
mdi_cascade = WM_MDICASCADE,
mdi_icon_arrange = WM_MDIICONARRANGE,
mdi_get_active = WM_MDIGETACTIVE,
mdi_set_menu = WM_MDISETMENU,
#endif
enter_size_move = WM_ENTERSIZEMOVE,
exit_size_move = WM_EXITSIZEMOVE,
drop_files = WM_DROPFILES,
#ifdef _USE_MDI
mdi_refresh_menu = WM_MDIREFRESHMENU,
#endif
#if( WINVER >= 0x0602 )
pointer_device_change = WM_POINTERDEVICECHANGE,
pointer_device_in_range = WM_POINTERDEVICEINRANGE,
pointer_device_out_of_range = WM_POINTERDEVICEOUTOFRANGE,
#endif
#if( WINVER >= 0x0601 )
touch = WM_TOUCH,
#endif
#if( WINVER >= 0x0602 )
nc_pointer_update = WM_NCPOINTERUPDATE,
nc_pointer_down = WM_NCPOINTERDOWN,
nc_pointer_up = WM_NCPOINTERUP,
pointer_update = WM_POINTERUPDATE,
pointer_down = WM_POINTERDOWN,
pointer_up = WM_POINTERUP,
pointer_enter = WM_POINTERENTER,
pointer_leave = WM_POINTERLEAVE,
pointer_activate = WM_POINTERACTIVATE,
pointer_capture_changed = WM_POINTERCAPTURECHANGED,
touch_hittesting = WM_TOUCHHITTESTING,
pointer_wheel = WM_POINTERWHEEL,
pointer_horizontal_wheel = WM_POINTERHWHEEL,
#endif
#if( WINVER >= 0x0400 )
ime_set_context = WM_IME_SETCONTEXT,
ime_notify = WM_IME_NOTIFY,
ime_control = WM_IME_CONTROL,
ime_composition_full = WM_IME_COMPOSITIONFULL,
ime_selection = WM_IME_SELECT,
ime_char = WM_IME_CHAR,
#endif
#if( WINVER >= 0x0500 )
ime_request = WM_IME_REQUEST,
#endif
#if( WINVER >= 0x0400 )
ime_key_down = WM_IME_KEYDOWN,
ime_key_up = WM_IME_KEYUP,
#endif
#if( _WIN32_WINNT >= 0x0400 ) || ( WINVER >= 0x0500 )
mouse_hover = WM_MOUSEHOVER,
mouse_leave = WM_MOUSELEAVE,
#endif
#if( WINVER >= 0x0500 )
nc_mouse_hover = WM_NCMOUSEHOVER,
nc_mouse_leave = WM_NCMOUSELEAVE,
#endif
#if( WINVER >= 0x0501 )
wts_session_change = WM_WTSSESSION_CHANGE,
tablet_first = WM_TABLET_FIRST,
tablet_last = WM_TABLET_LAST,
#endif
#if( WINVER >= 0x0601 )
dpi_changed = WM_DPICHANGED,
#endif
cut = WM_CUT,
copy = WM_COPY,
paste = WM_PASTE,
clear = WM_CLEAR,
undo = WM_UNDO,
#ifdef _USE_CLIPBOARD
render_format = WM_RENDERFORMAT,
render_all_formats = WM_RENDERALLFORMATS,
destroy_clipboard = WM_DESTROYCLIPBOARD,
draw_clipboard = WM_DRAWCLIPBOARD,
paint_clipboard = WM_PAINTCLIPBOARD,
vertical_scroll_clipboard = WM_VSCROLLCLIPBOARD,
size_clipboard = WM_SIZECLIPBOARD,
ask_callback_format_name = WM_ASKCBFORMATNAME,
change_callback_chain = WM_CHANGECBCHAIN,
horizontal_scroll_clipboard = WM_HSCROLLCLIPBOARD,
#endif
query_new_palettle = WM_QUERYNEWPALETTE,
palette_is_changing = WM_PALETTEISCHANGING,
palette_changed = WM_PALETTECHANGED,
hotkey = WM_HOTKEY,
#if( _WIN32_WINNT >= 0x0500 )
wmpaint = WM_PAINT,
paint_client = WM_PRINTCLIENT,
#endif
#if( _WIN32_WINNT >= 0x0500 )
app_command = WM_APPCOMMAND,
#endif
#if( _WIN32_WINNT >= 0x0501 )
theme_changed = WM_THEMECHANGED,
#ifdef _USE_CLIPBOARD
clipboard_update = WM_CLIPBOARDUPDATE,
#endif
#endif
#if( _WIN32_WINNT >= 0x0600 )
dwm_composition_changed = WM_DWMCOMPOSITIONCHANGED,
dwm_nc_rendering_changed = WM_DWMNCRENDERINGCHANGED,
dwm_colorization_color_changed = WM_DWMCOLORIZATIONCOLORCHANGED,
dwm_window_maximized_change = WM_DWMWINDOWMAXIMIZEDCHANGE,
#endif
#if( _WIN32_WINNT >= 0x0601 )
dwm_send_iconic_thumbnail = WM_DWMSENDICONICTHUMBNAIL,
dwm_send_iconic_live_preview_bitmap = WM_DWMSENDICONICLIVEPREVIEWBITMAP,
#endif
#if( WINVER >= 0x0600 )
get_title_bar_info_extra = WM_GETTITLEBARINFOEX,
#endif
#if( WINVER >= 0x0400 )
hand_held_first = WM_HANDHELDFIRST,
hand_held_last = WM_HANDHELDLAST,
afx_first = WM_AFXFIRST,
afx_last = WM_AFXLAST,
#endif
pen_win_first = WM_PENWINFIRST,
pen_win_last = WM_PENWINLAST,
#if( WINVER >= 0x0400 )
app = WM_APP,
#endif
user = WM_USER,
edit_get_selection = EM_GETSEL,
edit_set_selection = EM_SETSEL,
edit_get_rectangle = EM_GETRECT,
edit_set_rectangle = EM_SETRECT,
edit_set_rectangle_nullptr = EM_SETRECTNP,
edit_scroll = EM_SCROLL,
edit_line_scroll = EM_LINESCROLL,
edit_scroll_caret = EM_SCROLLCARET,
edit_get_modify = EM_GETMODIFY,
edit_set_modify = EM_SETMODIFY,
edit_get_line_count = EM_GETLINECOUNT,
edit_line_index = EM_LINEINDEX,
edit_set_handle = EM_SETHANDLE,
edit_get_handle = EM_GETHANDLE,
edit_get_thumb = EM_GETTHUMB,
edit_line_length = EM_LINELENGTH,
edit_replace_selection = EM_REPLACESEL,
edit_get_line = EM_GETLINE,
edit_limit_text = EM_LIMITTEXT,
edit_can_undo = EM_CANUNDO,
edit_undo = EM_UNDO,
edit_flag_multiline = EM_FMTLINES,
edit_line_from_char = EM_LINEFROMCHAR,
edit_set_tabstops = EM_SETTABSTOPS,
edit_set_password_char = EM_SETPASSWORDCHAR,
edit_empty_undo_buffer = EM_EMPTYUNDOBUFFER,
edit_get_first_visible_line = EM_GETFIRSTVISIBLELINE,
edit_set_readonly = EM_SETREADONLY,
edit_set_word_break_procedure = EM_SETWORDBREAKPROC,
edit_get_word_break_procedure = EM_GETWORDBREAKPROC,
edit_get_password_char = EM_GETPASSWORDCHAR,
#if(WINVER >= 0x0400)
edit_set_margins = EM_SETMARGINS,
edit_get_margins = EM_GETMARGINS,
edit_set_limit_text = EM_SETLIMITTEXT, /* ;win40 Name change */
edit_get_limit_text = EM_GETLIMITTEXT,
edit_position_from_char = EM_POSFROMCHAR,
edit_char_from_position = EM_CHARFROMPOS,
#endif
#if(WINVER >= 0x0500)
edit_set_ime_status = EM_SETIMESTATUS,
edit_get_ime_status = EM_GETIMESTATUS,
#endif
list_box_add_string = LB_ADDSTRING,
list_box_insert_string = LB_INSERTSTRING,
list_box_delete_string = LB_DELETESTRING,
list_box_select_item_range_extra = LB_SELITEMRANGEEX,
list_box_reset_content = LB_RESETCONTENT,
list_box_set_selection = LB_SETSEL,
list_box_set_current_selection = LB_SETCURSEL,
list_box_get_selection = LB_GETSEL,
list_box_get_current_selection = LB_GETCURSEL,
list_box_get_text = LB_GETTEXT,
list_box_get_text_length = LB_GETTEXTLEN,
list_box_get_count = LB_GETCOUNT,
list_box_select_string = LB_SELECTSTRING,
list_box_direction = LB_DIR,
list_box_get_top_index = LB_GETTOPINDEX,
list_box_find_string = LB_FINDSTRING,
list_box_get_selection_count = LB_GETSELCOUNT,
list_box_get_selection_items = LB_GETSELITEMS,
list_box_selection_tabstops = LB_SETTABSTOPS,
list_box_get_horizontal_extent = LB_GETHORIZONTALEXTENT,
list_box_set_horizontal_extent = LB_SETHORIZONTALEXTENT,
list_box_set_column_width = LB_SETCOLUMNWIDTH,
list_box_add_file = LB_ADDFILE,
list_box_set_top_index = LB_SETTOPINDEX,
list_box_get_item_rectangle = LB_GETITEMRECT,
list_box_get_item_data = LB_GETITEMDATA,
list_box_set_item_data = LB_SETITEMDATA,
list_box_select_item_range = LB_SELITEMRANGE,
list_box_set_anchor_index = LB_SETANCHORINDEX,
list_box_get_anchor_index = LB_GETANCHORINDEX,
list_box_set_caret_index = LB_SETCARETINDEX,
list_box_get_caret_index = LB_GETCARETINDEX,
list_box_set_item_height = LB_SETITEMHEIGHT,
list_box_get_item_height = LB_GETITEMHEIGHT,
list_box_find_string_exact = LB_FINDSTRINGEXACT,
list_box_set_locale = LB_SETLOCALE,
list_box_get_locale = LB_GETLOCALE,
list_box_set_count = LB_SETCOUNT,
#if(WINVER >= 0x0400)
list_box_initialize_storage = LB_INITSTORAGE,
list_box_item_from_point = LB_ITEMFROMPOINT,
#endif
#if defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0400)
list_box_multiple_add_string = LB_MULTIPLEADDSTRING,
#endif
#if(_WIN32_WINNT >= 0x0501)
#define LB_GETLISTBOXINFO 0x01B2
#endif
#if(_WIN32_WINNT >= 0x0501)
#define LB_MSGMAX 0x01B3
#elif defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0400)
#define LB_MSGMAX 0x01B1
#elif(WINVER >= 0x0400)
#define LB_MSGMAX 0x01B0
#else
#define LB_MSGMAX 0x01A8
#endif
combo_box_get_edit_selection = CB_GETEDITSEL,
combo_box_limit_text = CB_LIMITTEXT,
combo_box_set_edit_selection = CB_SETEDITSEL,
combo_box_add_string = CB_ADDSTRING,
combo_box_delete_string = CB_DELETESTRING,
combo_box_directory = CB_DIR,
combo_box_get_count = CB_GETCOUNT,
combo_box_get_current_selection = CB_GETCURSEL,
combo_box_get_list_box_text = CB_GETLBTEXT,
combo_box_get_list_box_text_length = CB_GETLBTEXTLEN,
combo_box_insert_string = CB_INSERTSTRING,
combo_box_reset_content = CB_RESETCONTENT,
combo_box_find_string = CB_FINDSTRING,
combo_box_select_string = CB_SELECTSTRING,
combo_box_set_current_selection = CB_SETCURSEL,
combo_box_show_dropdown = CB_SHOWDROPDOWN,
combo_box_get_item_data = CB_GETITEMDATA,
combo_box_set_item_data = CB_SETITEMDATA,
combo_box_get_dropped_control_rectangle = CB_GETDROPPEDCONTROLRECT,
combo_box_set_item_height = CB_SETITEMHEIGHT,
combo_box_get_item_height = CB_GETITEMHEIGHT,
combo_box_set_extended_ui = CB_SETEXTENDEDUI,
combo_box_get_extended_ui = CB_GETEXTENDEDUI,
combo_box_get_dropped_state = CB_GETDROPPEDSTATE,
combo_box_find_string_exact = CB_FINDSTRINGEXACT,
combo_box_set_locale = CB_SETLOCALE,
combo_box_get_locale = CB_GETLOCALE,
#if(WINVER >= 0x0400)
combo_box_get_top_index = CB_GETTOPINDEX,
combo_box_set_top_index = CB_SETTOPINDEX,
combo_box_get_horizontal_extent = CB_GETHORIZONTALEXTENT,
combo_box_set_horzontal_extent = CB_SETHORIZONTALEXTENT,
combo_box_get_dropped_width = CB_GETDROPPEDWIDTH,
combo_box_set_dropped_width = CB_SETDROPPEDWIDTH,
combo_box_initialize_storage = CB_INITSTORAGE,
#if defined(_WIN32_WCE) &&(_WIN32_WCE >= 0x0400)
combo_box_multiple_add_string = CB_MULTIPLEADDSTRING,
#endif
#endif
#if(_WIN32_WINNT >= 0x0501)
combo_box_get_combo_box_information = CB_GETCOMBOBOXINFO,
#endif
#if(_WIN32_WINNT >= 0x0501)
combo_box_message_maximize = CB_MSGMAX,
#elif defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0400)
combo_box_message_maximize = CB_MSGMAX,
#elif(WINVER >= 0x0400)
combo_box_message_maximize = CB_MSGMAX,
#else
combo_box_message_maximize = CB_MSGMAX,
#endif
};
#ifndef NOWINSTYLES
enum class window_style : DWORD
{
overlapped = WS_OVERLAPPED,
popup = WS_POPUP,
child = WS_CHILD,
minimize = WS_MINIMIZE,
visible = WS_VISIBLE,
disabled = WS_DISABLED,
clip_siblings = WS_CLIPSIBLINGS,
clip_children = WS_CLIPCHILDREN,
maximize = WS_MAXIMIZE,
caption = WS_CAPTION,
border = WS_BORDER,
dialog_frame = WS_DLGFRAME,
vertical_scroll = WS_VSCROLL,
horizontal_scroll = WS_HSCROLL,
system_menu = WS_SYSMENU,
thick_frame = WS_THICKFRAME,
group = WS_GROUP,
tab_stop = WS_TABSTOP,
minimize_box = WS_MINIMIZEBOX,
maximize_box = WS_MAXIMIZEBOX,
tiled = WS_TILED,
iconic = WS_ICONIC,
size_box = WS_SIZEBOX,
tiled_window = WS_TILEDWINDOW,
overlapped_window = WS_OVERLAPPEDWINDOW,
popup_window = WS_POPUPWINDOW,
child_window = WS_CHILDWINDOW,
edit_left = ES_LEFT,
edit_center = ES_CENTER,
edit_right = ES_RIGHT,
edit_multiline = ES_MULTILINE,
edit_uppercase = ES_UPPERCASE,
edit_lowercase = ES_LOWERCASE,
edit_password = ES_PASSWORD,
edit_auto_vertical_scroll = ES_AUTOVSCROLL,
edit_auto_horizontal_scroll = ES_AUTOHSCROLL,
edit_no_hide_selection = ES_NOHIDESEL,
edit_oem_convert = ES_OEMCONVERT,
edit_readonly = ES_READONLY,
edit_want_return = ES_WANTRETURN,
#if(WINVER >= 0x0400)
edit_number = ES_NUMBER,
#endif
button_push_button = BS_PUSHBUTTON,
button_default_push_button = BS_DEFPUSHBUTTON,
button_checkbox = BS_CHECKBOX,
button_auto_checkbox = BS_AUTOCHECKBOX,
button_radio_button = BS_RADIOBUTTON,
button_three_state = BS_3STATE,
button_auto_three_state = BS_AUTO3STATE,
button_groupbox = BS_GROUPBOX,
button_user_button = BS_USERBUTTON,
button_auto_radio_button = BS_AUTORADIOBUTTON,
button_push_box = BS_PUSHBOX,
button_owner_draw = BS_OWNERDRAW,
button_type_mask = BS_TYPEMASK,
button_left_text = BS_LEFTTEXT,
#if(WINVER >= 0x0400)
button_text = BS_TEXT,
button_icon = BS_ICON,
button_bitmap = BS_BITMAP,
button_left = BS_LEFT,
button_right = BS_RIGHT,
button_center = BS_CENTER,
button_top = BS_TOP,
button_bottom = BS_BOTTOM,
button_vertical_center = BS_VCENTER,
button_push_like = BS_PUSHLIKE,
button_multiline = BS_MULTILINE,
button_notify = BS_NOTIFY,
button_flat = BS_FLAT,
button_right_button = BS_RIGHTBUTTON,
#endif
static_left = SS_LEFT,
static_center = SS_CENTER,
static_right = SS_RIGHT,
static_icon = SS_ICON,
static_black_rect = SS_BLACKRECT,
static_gray_rect = SS_GRAYRECT,
static_white_rect = SS_WHITERECT,
static_black_frame = SS_BLACKFRAME,
static_gray_frame = SS_GRAYFRAME,
static_white_frame = SS_WHITEFRAME,
static_user_item = SS_USERITEM,
static_simple = SS_SIMPLE,
static_left_no_wordwrap = SS_LEFTNOWORDWRAP,
#if(WINVER >= 0x0400)
static_owner_draw = SS_OWNERDRAW,
static_bitmap = SS_BITMAP,
static_enhanced_metafile = SS_ENHMETAFILE,
static_etched_horizontal_frame = SS_ETCHEDHORZ,
static_etched_vertical_frame = SS_ETCHEDVERT,
static_etched_frame = SS_ETCHEDFRAME,
static_type_mask = SS_TYPEMASK,
#endif
#if(WINVER >= 0x0501)
static_real_size_control = SS_REALSIZECONTROL,
#endif
static_no_prefix = SS_NOPREFIX,
static_notify = SS_NOTIFY,
static_center_image = SS_CENTERIMAGE,
static_real_size_image = SS_REALSIZEIMAGE,
static_sunken = SS_SUNKEN,
static_edit_control = SS_EDITCONTROL,
static_end_ellipsis = SS_ENDELLIPSIS,
static_path_ellipsis = SS_PATHELLIPSIS,
static_word_ellipsis = SS_WORDELLIPSIS,
static_ellipsis_mask = SS_ELLIPSISMASK,
list_box_notify = LBS_NOTIFY,
list_box_sort = LBS_SORT,
list_box_noredraw = LBS_NOREDRAW,
list_box_multiple_selection = LBS_MULTIPLESEL,
list_box_ownerdraw_fixed = LBS_OWNERDRAWFIXED,
list_box_ownerdraw_variable = LBS_OWNERDRAWVARIABLE,
list_box_has_strings = LBS_HASSTRINGS,
list_box_use_tabstops = LBS_USETABSTOPS,
list_box_no_integral_height = LBS_NOINTEGRALHEIGHT,
list_box_multi_column = LBS_MULTICOLUMN,
list_box_want_keyboard_input = LBS_WANTKEYBOARDINPUT,
list_box_extended_selection = LBS_EXTENDEDSEL,
list_box_disable_no_scroll = LBS_DISABLENOSCROLL,
list_box_no_data = LBS_NODATA,
#if(WINVER >= 0x0400)
list_box_no_selection = LBS_NOSEL,
#endif
list_box_combo_box = LBS_COMBOBOX,
list_box_standard = LBS_STANDARD,
combo_box_simple = CBS_SIMPLE,
combo_box_dropdown = CBS_DROPDOWN,
combo_box_dropdownlist = CBS_DROPDOWNLIST,
combo_box_ownerdraw_fixed = CBS_OWNERDRAWFIXED,
combo_box_ownerdraw_variable = CBS_OWNERDRAWVARIABLE,
combo_box_auto_horizontal_scroll = CBS_AUTOHSCROLL,
combo_box_oem_convert = CBS_OEMCONVERT,
combo_box_sort = CBS_SORT,
combo_box_has_strings = CBS_HASSTRINGS,
combo_box_no_intergral_height = CBS_NOINTEGRALHEIGHT,
combo_box_disable_no_scroll = CBS_DISABLENOSCROLL,
#if(WINVER >= 0x0400)
combo_box_uppercase = CBS_UPPERCASE,
combo_box_lowercase = CBS_LOWERCASE,
#endif
};
DEFINE_ENUM_BIT_CALC(window_style);
enum class extended_window_style : DWORD
{
dialog_modal_frame = WS_EX_DLGMODALFRAME,
no_parent_notify = WS_EX_NOPARENTNOTIFY,
top_most = WS_EX_TOPMOST,
accept_files = WS_EX_ACCEPTFILES,
transparent = WS_EX_TRANSPARENT,
#if(WINVER >= 0x0400)
mdi_child = WS_EX_MDICHILD,
tool_window = WS_EX_TOOLWINDOW,
window_edge = WS_EX_WINDOWEDGE,
client_edge = WS_EX_CLIENTEDGE,
context_help = WS_EX_CONTEXTHELP,
right = WS_EX_RIGHT,
left = WS_EX_LEFT,
rtl_reading = WS_EX_RTLREADING,
ltr_reading = WS_EX_LTRREADING,
left_scroll_bar = WS_EX_LEFTSCROLLBAR,
right_scroll_bar = WS_EX_RIGHTSCROLLBAR,
control_parent = WS_EX_CONTROLPARENT,
static_edge = WS_EX_STATICEDGE,
app_window = WS_EX_APPWINDOW,
overlapped_window = WS_EX_OVERLAPPEDWINDOW,
palette_window = WS_EX_PALETTEWINDOW,
#endif
#if(_WIN32_WINNT >= 0x0500)
layered = WS_EX_LAYERED,
#endif
#if(WINVER >= 0x0500)
no_inherit_layout = WS_EX_NOINHERITLAYOUT,
#endif
#if(WINVER >= 0x0602)
no_redirection_bitmap = WS_EX_NOREDIRECTIONBITMAP,
#endif
#if(WINVER >= 0x0500)
layout_rtl = WS_EX_LAYOUTRTL,
#endif
#if(_WIN32_WINNT >= 0x0501)
composited = WS_EX_COMPOSITED,
#endif
#if(_WIN32_WINNT >= 0x0500)
no_activate = WS_EX_NOACTIVATE,
#endif
};
DEFINE_ENUM_BIT_CALC(extended_window_style);
#endif
enum class edit_notify_code : int16_t
{
set_focus = EN_SETFOCUS,
kill_focus = EN_KILLFOCUS,
change = EN_CHANGE,
update = EN_UPDATE,
error_space = EN_ERRSPACE,
maximize_text = EN_MAXTEXT,
horizontal_scroll = EN_HSCROLL,
vertical_scroll = EN_VSCROLL,
#if(_WIN32_WINNT >= 0x0500)
align_ltr = EN_ALIGN_LTR_EC,
align_rtl = EN_ALIGN_RTL_EC,
#endif
};
DEFINE_ENUM_BIT_CALC(edit_notify_code);
enum class button_notify_code : int16_t
{
clicked = BN_CLICKED,
paint = BN_PAINT,
highlight = BN_HILITE,
unhighlight = BN_UNHILITE,
disable = BN_DISABLE,
double_clicked = BN_DOUBLECLICKED,
#if(WINVER >= 0x0400)
pushed = BN_PUSHED,
unpushed = BN_UNPUSHED,
set_focus = BN_SETFOCUS,
kill_focus = BN_KILLFOCUS,
#endif
};
DEFINE_ENUM_BIT_CALC(button_notify_code);
enum class list_box_notify_code : int16_t
{
error_space = LBN_ERRSPACE,
selection_change = LBN_SELCHANGE,
double_click = LBN_DBLCLK,
selection_cancel = LBN_SELCANCEL,
set_focus = LBN_SETFOCUS,
kill_focus = LBN_KILLFOCUS,
};
DEFINE_ENUM_BIT_CALC(list_box_notify_code);
enum class combo_box_notify_code : int16_t
{
error_space = CBN_ERRSPACE,
selection_change = CBN_SELCHANGE,
double_click = CBN_DBLCLK,
set_focus = CBN_SETFOCUS,
kill_focus = CBN_KILLFOCUS,
edit_change = CBN_EDITCHANGE,
edit_update = CBN_EDITUPDATE,
dropdown = CBN_DROPDOWN,
close_up = CBN_CLOSEUP,
selection_end_ok = CBN_SELENDOK,
selection_end_cancel = CBN_SELENDCANCEL,
};
DEFINE_ENUM_BIT_CALC(combo_box_notify_code);
#endif
enum class hit_test : int16_t
{
error = HTERROR,
transparent = HTTRANSPARENT,
no_where = HTNOWHERE,
client = HTCLIENT,
caption = HTCAPTION,
system_menu = HTSYSMENU,
grow_box = HTGROWBOX,
size = HTSIZE,
menu = HTMENU,
horizontal_scroll = HTHSCROLL,
vertical_scroll = HTVSCROLL,
minimize_button = HTMINBUTTON,
maximize_button = HTMAXBUTTON,
left = HTLEFT,
right = HTRIGHT,
top = HTTOP,
top_left = HTTOPLEFT,
top_right = HTTOPRIGHT,
bottom = HTBOTTOM,
bottom_left = HTBOTTOMLEFT,
bottom_right = HTBOTTOMRIGHT,
border = HTBORDER,
reduce = HTREDUCE,
zoom = HTZOOM,
size_first = HTSIZEFIRST,
size_last = HTSIZELAST,
#if(WINVER >= 0x0400)
object = HTOBJECT,
close = HTCLOSE,
help = HTHELP,
#endif
};
DEFINE_ENUM_BIT_CALC(hit_test);
} | 28.930876 | 141 | 0.802126 | [
"object"
] |
8e587f740efb28e35c65b8364116f975fff567c1 | 10,062 | cpp | C++ | Super Monaco GP/ModuleCourseSelect.cpp | gerardpf2/SuperMonacoGP | dbb46ffff701e9781d7975586a82ea8c56f8dd9f | [
"MIT"
] | null | null | null | Super Monaco GP/ModuleCourseSelect.cpp | gerardpf2/SuperMonacoGP | dbb46ffff701e9781d7975586a82ea8c56f8dd9f | [
"MIT"
] | null | null | null | Super Monaco GP/ModuleCourseSelect.cpp | gerardpf2/SuperMonacoGP | dbb46ffff701e9781d7975586a82ea8c56f8dd9f | [
"MIT"
] | null | null | null | #include "ModuleCourseSelect.h"
#include "Utils.h"
#include "Animation.h"
#include "ModuleFont.h"
#include "ModuleInput.h"
#include "ModuleAudio.h"
#include "ModuleSwitch.h"
#include "ModuleTexture.h"
#include "ModuleRenderer.h"
#include "ModuleRegistry.h"
#include "ModuleAnimation.h"
#include "ModuleCourseSelectUI.h"
using namespace std;
ModuleCourseSelect::ModuleCourseSelect(GameEngine* gameEngine) :
Module(gameEngine)
{
baseRect = BASE_RECT;
courseRect = COURSE_RECT;
backgroundRect = BACKGROUND_RECT;
courseNamePosition = COURSE_NAME_POSITION;
courseRoundPosition = COURSE_ROUND_POSITION;
courseRoundValuePosition = COURSE_ROUND_VALUE_POSITION;
courseLengthPosition = COURSE_LENGTH_POSITION;
courseLengthValuePosition = COURSE_LENGTH_VALUE_POSITION;
courseBestLapTimePosition = COURSE_BEST_LAP_TIME_POSITION;
courseBestLapTimeValuePosition = COURSE_BEST_LAP_TIME_VALUE_POSITION;
changeCourseAnimationRects.reserve(COURSE_CHANGE_ANIMATION_N_R * COURSE_CHANGE_ANIMATION_N_C + BACKGROUND_CHANGE_ANIMATION_N_R * BACKGROUND_CHANGE_ANIMATION_N_C);
addChangeAnimationRects(courseRect, COURSE_CHANGE_ANIMATION_N_R, COURSE_CHANGE_ANIMATION_N_C);
addChangeAnimationRects(backgroundRect, BACKGROUND_CHANGE_ANIMATION_N_R, BACKGROUND_CHANGE_ANIMATION_N_C);
}
ModuleCourseSelect::~ModuleCourseSelect()
{ }
bool ModuleCourseSelect::setUp()
{
assert(getGameEngine());
assert(getGameEngine()->getModuleAudio());
assert(getGameEngine()->getModuleRegistry());
assert(getGameEngine()->getModuleAnimation());
courseSelectAnimationGroupId = getGameEngine()->getModuleAnimation()->load("Resources/Configurations/Animations/CourseSelect.json");
changeCourseAnimation = getGameEngine()->getModuleAnimation()->getAnimation(courseSelectAnimationGroupId, 0);
changeCourseAnimation->setTimePercent(0.5f);
ModuleTexture* moduleTexture = getGameEngine()->getModuleTexture();
assert(moduleTexture);
coursesBackgroundsTextureGroupId = moduleTexture->load("Resources/Configurations/Textures/CoursesBackgrounds.json");
base = moduleTexture->get(courseSelectAnimationGroupId, 0);
courses.reserve(N_COURSES);
backgrounds.reserve(N_COURSES);
for(uint i = 0; i < N_COURSES; ++i)
{
courses.push_back(moduleTexture->get(coursesBackgroundsTextureGroupId, 4 * (i + 1) - 1));
backgrounds.push_back(moduleTexture->get(coursesBackgroundsTextureGroupId, 4 * i));
}
time(getGameEngine()->getModuleRegistry()->getPlayerBestLapTime(currentCourseId), currentBestLapTimeStr);
audioGroupId = getGameEngine()->getModuleAudio()->load("Resources/Configurations/Audios/CourseSelect.json");
getGameEngine()->getModuleAudio()->playMusic(audioGroupId, 0);
return true;
}
bool ModuleCourseSelect::update(float deltaTimeS)
{
if(!getBlocked())
{
checkGoMenu();
checkSelectOption();
checkChangeCourse();
updateBackground(deltaTimeS);
updateCourseChangeAnimation(deltaTimeS);
}
render();
return true;
}
void ModuleCourseSelect::cleanUp()
{
assert(getGameEngine());
assert(getGameEngine()->getModuleAudio());
assert(getGameEngine()->getModuleTexture());
assert(getGameEngine()->getModuleAnimation());
getGameEngine()->getModuleAudio()->unload(audioGroupId);
getGameEngine()->getModuleAnimation()->unload(courseSelectAnimationGroupId);
getGameEngine()->getModuleTexture()->unload(coursesBackgroundsTextureGroupId);
base = nullptr;
courses.clear();
backgrounds.clear();
changeCourseAnimation = nullptr;
changeCourseAnimationRects.clear();
}
void ModuleCourseSelect::addChangeAnimationRects(const SDL_Rect& rect, uint r, uint c)
{
SDL_Rect tmpRect;
tmpRect.y = rect.y;
float totalH = (float)rect.h;
for(uint rr = 0; rr < r; ++rr)
{
float totalW = (float)rect.w;
tmpRect.x = rect.x;
tmpRect.h = (int)(totalH / (r - rr));
for(uint cc = 0; cc < c; ++cc)
{
tmpRect.w = (int)(totalW / (c - cc));
changeCourseAnimationRects.push_back(tmpRect);
totalW -= tmpRect.w;
tmpRect.x += tmpRect.w;
}
totalH -= tmpRect.h;
tmpRect.y += tmpRect.h;
}
}
void ModuleCourseSelect::updateBackground(float deltaTimeS)
{
assert((int)backgrounds.size() > currentCourseId);
const Texture* backgroundT = backgrounds[currentCourseId];
assert(backgroundT);
assert(backgroundT->r);
backgroundOffsetX = mod0L(backgroundOffsetX + 40.0f * deltaTimeS, (float)backgroundT->r->w);
}
void ModuleCourseSelect::updateCourseChangeAnimation(float deltaTimeS)
{
if(showChangeCourseAnimation)
{
assert(changeCourseAnimation);
if(changeCourseAnimation->hasEnded()) showChangeCourseAnimation = false;
else changeCourseAnimation->update(deltaTimeS);
}
}
void ModuleCourseSelect::checkGoMenu() const
{
assert(getGameEngine());
assert(getGameEngine()->getModuleInput());
assert(getGameEngine()->getModuleSwitch());
if(getGameEngine()->getModuleInput()->getKeyState(SDL_SCANCODE_ESCAPE) == KeyState::DOWN)
getGameEngine()->getModuleSwitch()->setNewGameModule(GameModule::START);
}
void ModuleCourseSelect::checkSelectOption() const
{
assert(getGameEngine());
assert(getGameEngine()->getModuleInput());
assert(getGameEngine()->getModuleSwitch());
assert(getGameEngine()->getModuleRegistry());
if(getGameEngine()->getModuleInput()->getKeyState(SDL_SCANCODE_RETURN) == KeyState::DOWN)
{
getGameEngine()->getModuleRegistry()->setCurrentCourseId(currentCourseId);
getGameEngine()->getModuleSwitch()->setNewGameModule(GameModule::FREE_PRACTICE);
}
}
void ModuleCourseSelect::checkChangeCourse()
{
assert(getGameEngine());
assert(getGameEngine()->getModuleInput());
int tmpCurrentCourseId = currentCourseId;
if(getGameEngine()->getModuleInput()->getKeyState(SDL_SCANCODE_RIGHT) == KeyState::DOWN)
currentCourseId = mod0L(currentCourseId + 1, N_COURSES);
if(getGameEngine()->getModuleInput()->getKeyState(SDL_SCANCODE_LEFT) == KeyState::DOWN)
currentCourseId = mod0L(currentCourseId - 1, N_COURSES);
if(currentCourseId != tmpCurrentCourseId)
{
assert(changeCourseAnimation);
assert(getGameEngine()->getModuleAudio());
assert(getGameEngine()->getModuleRegistry());
backgroundOffsetX = 0.0f;
changeCourseAnimation->reset();
showChangeCourseAnimation = true;
getGameEngine()->getModuleAudio()->playFx(audioGroupId, 0);
time(getGameEngine()->getModuleRegistry()->getPlayerBestLapTime(currentCourseId), currentBestLapTimeStr);
}
}
void ModuleCourseSelect::render() const
{
renderBase();
renderCourseInfo();
renderCourseBackground();
renderChangeCourseAnimations();
}
void ModuleCourseSelect::renderBase() const
{
assert(base);
assert(getGameEngine());
assert(getGameEngine()->getModuleRenderer());
getGameEngine()->getModuleRenderer()->renderTexture(base->t, base->r, &baseRect, base->hFlipped);
}
void ModuleCourseSelect::renderCourseInfo() const
{
assert(getGameEngine());
ModuleFont* moduleFont = getGameEngine()->getModuleFont();
assert(moduleFont);
// Name
moduleFont->renderText(COURSE_NAMES[currentCourseId], courseNamePosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_NAME_POSITION_SCALE, COURSE_NAME_POSITION_SCALE, 248, 216, 0);
// Round
moduleFont->renderText("< ROUND >", courseRoundPosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_INFO_VALUE_POSITION_SCALE_W, COURSE_INFO_VALUE_POSITION_SCALE_H, 248, 252, 252);
moduleFont->renderText(to_string(currentCourseId + 1), courseRoundValuePosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_INFO_VALUE_POSITION_SCALE_W, COURSE_INFO_VALUE_POSITION_SCALE_H, 248, 216, 0);
// Length
moduleFont->renderText("LENGTH", courseLengthPosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_INFO_VALUE_POSITION_SCALE_W, COURSE_INFO_VALUE_POSITION_SCALE_H, 248, 252, 252);
string courseLengthStr = to_string((int)COURSE_LENGHTS[currentCourseId]); courseLengthStr += "M";
moduleFont->renderText(courseLengthStr, courseLengthValuePosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_INFO_VALUE_POSITION_SCALE_W, COURSE_INFO_VALUE_POSITION_SCALE_H, 248, 216, 0);
// Best lap time
moduleFont->renderText("BEST LAP", courseBestLapTimePosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_INFO_VALUE_POSITION_SCALE_W, COURSE_INFO_VALUE_POSITION_SCALE_H, 248, 252, 252);
moduleFont->renderText(currentBestLapTimeStr, courseBestLapTimeValuePosition, HAlignment::LEFT, VAlignment::BOTTOM, COURSE_INFO_VALUE_POSITION_SCALE_W, COURSE_INFO_VALUE_POSITION_SCALE_H, 248, 216, 0);
}
void ModuleCourseSelect::renderCourseBackground() const
{
assert(getGameEngine());
assert(getGameEngine()->getModuleRenderer());
assert((int)courses.size() > currentCourseId);
assert((int)backgrounds.size() > currentCourseId);
// Course
const Texture* course = courses[currentCourseId];
assert(course);
getGameEngine()->getModuleRenderer()->renderTexture(course->t, course->r, &courseRect, course->hFlipped);
// Background
const Texture* background = backgrounds[currentCourseId];
assert(background);
SDL_Rect textureRect{ background->r->x, background->r->y, COURSE_BACKGROUND_REGION_X, COURSE_BACKGROUND_REGION_Y };
SDL_Rect rect0, rect1, renderRect0, renderRect1;
if(!getRectsEndlessTexture(background, textureRect, backgroundRect, false, backgroundOffsetX, rect0, renderRect0, rect1, renderRect1))
getGameEngine()->getModuleRenderer()->renderTexture(background->t, &rect0, &renderRect0, background->hFlipped);
else
{
getGameEngine()->getModuleRenderer()->renderTexture(background->t, &rect0, &renderRect0, background->hFlipped);
getGameEngine()->getModuleRenderer()->renderTexture(background->t, &rect1, &renderRect1, background->hFlipped);
}
}
void ModuleCourseSelect::renderChangeCourseAnimations() const
{
if(showChangeCourseAnimation)
{
assert(getGameEngine());
ModuleRenderer* moduleRenderer = getGameEngine()->getModuleRenderer();
assert(moduleRenderer);
assert(changeCourseAnimation);
const Texture* animationT = changeCourseAnimation->getCurrentFrame();
assert(animationT);
for(SDL_Rect rect : changeCourseAnimationRects)
moduleRenderer->renderTexture(animationT->t, animationT->r, &rect, animationT->hFlipped);
}
} | 29.946429 | 205 | 0.779765 | [
"render"
] |
769dca7d04608c1d8d4b4a2656ea89c18f536530 | 6,616 | cpp | C++ | test/grammar/grammar_test.cpp | TheSYNcoder/JuCC | 4765f9dd93349de93c09d53594721af0fea0acc0 | [
"Apache-2.0"
] | 31 | 2021-05-03T11:49:32.000Z | 2022-03-03T03:07:57.000Z | test/grammar/grammar_test.cpp | TheSYNcoder/JuCC | 4765f9dd93349de93c09d53594721af0fea0acc0 | [
"Apache-2.0"
] | 45 | 2021-04-24T13:36:13.000Z | 2021-05-27T05:51:42.000Z | test/grammar/grammar_test.cpp | TheSYNcoder/JuCC | 4765f9dd93349de93c09d53594721af0fea0acc0 | [
"Apache-2.0"
] | 1 | 2021-04-25T12:35:55.000Z | 2021-04-25T12:35:55.000Z | #include "grammar/grammar.h"
#include "gtest/gtest.h"
using jucc::grammar::Parser;
TEST(grammar, Parser0) {
Parser parser = Parser("../test/grammar/grammar_test_0.g");
ASSERT_EQ(true, parser.Parse());
ASSERT_EQ("<primary_expression>", parser.GetStartSymbol());
std::vector<std::string> terminals = {"else",
"float",
"if",
"int",
"void",
"(",
")",
"{",
"}",
"*",
"+",
"-",
"/",
"%",
"<<",
">>",
"<",
">",
"<=",
">=",
"=",
"==",
"!=",
";",
"identifier",
"integer_constant",
"float_constant"};
ASSERT_EQ(terminals, parser.GetTerminals());
std::vector<std::string> non_terminals = {"<primary_expression>", "<constant>"};
ASSERT_EQ(non_terminals, parser.GetNonTerminals());
ASSERT_EQ(2, parser.GetProductions().size());
ASSERT_EQ("<constant>", parser.GetProductions()[0].GetParent());
ASSERT_EQ("<primary_expression>", parser.GetProductions()[1].GetParent());
ASSERT_EQ(3, parser.GetProductions()[1].GetRules().size());
std::vector<std::string> rule0 = {"identifier", "<constant>"};
std::vector<std::string> rule1 = {"<constant>"};
std::vector<std::string> rule2 = {"EPSILON"};
ASSERT_EQ(rule0, parser.GetProductions()[1].GetRules()[0].GetEntities());
ASSERT_EQ(rule1, parser.GetProductions()[1].GetRules()[1].GetEntities());
ASSERT_EQ(rule2, parser.GetProductions()[1].GetRules()[2].GetEntities());
ASSERT_EQ(1, parser.GetProductions()[0].GetRules().size());
std::vector<std::string> rule3 = {"integer_constant"};
ASSERT_EQ(rule3, parser.GetProductions()[0].GetRules()[0].GetEntities());
}
TEST(grammar, Parser1) {
Parser parser = Parser("../test/grammar/grammar_test_1.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: invalid token %terminals", parser.GetError());
}
TEST(grammar, Parser2) {
Parser parser = Parser("../test/grammar/grammar_test_2.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: invalid token %non_terminals", parser.GetError());
}
TEST(grammar, Parser3) {
Parser parser = Parser("../test/grammar/grammar_test_3.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: invalid token %rules", parser.GetError());
}
TEST(grammar, Parser4) {
Parser parser = Parser("../test/grammar/grammar_test_4.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: invalid token %start", parser.GetError());
}
TEST(grammar, Parser5) {
Parser parser = Parser("../test/grammar/grammar_test_5.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: invalid token %", parser.GetError());
}
TEST(grammar, Parser6) {
Parser parser = Parser("../test/grammar/grammar_test_6.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: invalid token outside block: bruh", parser.GetError());
}
TEST(grammar, Parser7) {
Parser parser = Parser("../test/grammar/grammar_test_7.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: EPSILON is reserved", parser.GetError());
}
TEST(grammar, Parser8) {
Parser parser = Parser("../test/grammar/grammar_test_8.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: EPSILON is reserved", parser.GetError());
}
TEST(grammar, Parser9) {
Parser parser = Parser("../test/grammar/grammar_test_9.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: ambiguous start symbol", parser.GetError());
}
TEST(grammar, Parser10) {
Parser parser = Parser("../test/grammar/grammar_test_10.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: production cannot start with EPSILON", parser.GetError());
}
TEST(grammar, Parser11) {
Parser parser = Parser("../test/grammar/grammar_test_11.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: rules syntax error ':' expected: bruh", parser.GetError());
}
TEST(grammar, Parser12) {
Parser parser = Parser("../test/grammar/grammar_test_12.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: rules syntax error ':' expected", parser.GetError());
}
TEST(grammar, Parser13) {
Parser parser = Parser("../test/grammar/grammar_test_13.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: block is incomplete '%' expected", parser.GetError());
}
TEST(grammar, Parser14) {
Parser parser = Parser("../test/grammar/grammar_test_14.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: inconsistent or duplicate terminals", parser.GetError());
}
TEST(grammar, Parser15) {
Parser parser = Parser("../test/grammar/grammar_test_15.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: inconsistent or duplicate non_terminals", parser.GetError());
}
TEST(grammar, Parser16) {
Parser parser = Parser("../test/grammar/grammar_test_16.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: terminals and non_terminals not disjoint", parser.GetError());
}
TEST(grammar, Parser17) {
Parser parser = Parser("../test/grammar/grammar_test_17.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: non_terminal not found: <bruh>", parser.GetError());
}
TEST(grammar, Parser18) {
Parser parser = Parser("../test/grammar/grammar_test_18.g");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: rule token is not defined: bruh", parser.GetError());
}
TEST(grammar, Parser19) {
Parser parser = Parser("invalid_file_path");
ASSERT_EQ(false, parser.Parse());
ASSERT_EQ("grammar parsing error: file not found", parser.GetError());
}
| 38.465116 | 98 | 0.590992 | [
"vector"
] |
769fb2c24a02f020e44154542ed145a1f44bafbf | 2,369 | cpp | C++ | examples/ros/RosNodeTalker.cpp | RicoPauli/eeros | 3cc2802253c764b16c6368ad7bdaef1e3c683367 | [
"Apache-2.0"
] | null | null | null | examples/ros/RosNodeTalker.cpp | RicoPauli/eeros | 3cc2802253c764b16c6368ad7bdaef1e3c683367 | [
"Apache-2.0"
] | null | null | null | examples/ros/RosNodeTalker.cpp | RicoPauli/eeros | 3cc2802253c764b16c6368ad7bdaef1e3c683367 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <ros/ros.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Float64MultiArray.h>
#include <sensor_msgs/Joy.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/BatteryState.h>
using namespace std;
int main(int argc, char *argv[])
{
cout << "'rosNodeTalker' started" << endl;
ros::init(argc, argv, "rosNodeTalker");
ros::NodeHandle n;
ros::Publisher chatter_topic1 = n.advertise<std_msgs::Float64>("rosNodeTalker/val", 1000);
ros::Publisher chatter_topic2 = n.advertise<std_msgs::Float64MultiArray>("rosNodeTalker/vector", 1000);
ros::Publisher chatter_topic3 = n.advertise<sensor_msgs::Joy>("rosNodeTalker/TestTopic3", 1000);
ros::Publisher chatter_topic4 = n.advertise<sensor_msgs::LaserScan>("rosNodeTalker/TestTopic4", 1000);
ros::Publisher chatter_topic5 = n.advertise<sensor_msgs::BatteryState>("rosNodeTalker/batteryState", 1000);
ros::Rate loop_rate(5); // 5Hz
cout << "'rosNodeTalker' initialized" << endl;
int count = 0;
while (ros::ok())
{
std_msgs::Float64 msg1;
std_msgs::Float64MultiArray msg2;
sensor_msgs::Joy msg3;
sensor_msgs::LaserScan msg4;
sensor_msgs::BatteryState msg5;
msg1.data = static_cast<double>( static_cast<int>(count) % 17 );
msg2.data = {static_cast<double>(static_cast<int>(count) % 37), static_cast<double>( static_cast<int>(count) % 73 )};
msg3.header.stamp = ros::Time::now();
sensor_msgs::Joy::_axes_type axes {(float)(count/10), (float)((count+1)/10), (float)((count+2)/10)};
msg3.axes = axes;
sensor_msgs::Joy::_buttons_type buttons {count, count+1, count+2, count+3, count+4};
msg3.buttons = buttons;
msg4.header.stamp = ros::Time::now();
msg4.angle_min = (count+10)/10;
msg4.angle_max = (count+11)/10;
msg4.angle_increment = (count+12)/10;
msg4.scan_time = (count+13)/10;
msg4.range_min = (count+14)/10;
msg4.range_max = (count+15)/10;
msg4.ranges = axes;
msg4.intensities = axes;
msg5.header.stamp = ros::Time::now();
msg5.present = static_cast<bool>( static_cast<int>(count)%3 );
chatter_topic1.publish(msg1);
chatter_topic2.publish(msg2);
chatter_topic3.publish(msg3);
chatter_topic4.publish(msg4);
chatter_topic5.publish(msg5);
std::cout << count+1 << ". message sent" << std::endl;
ros::spinOnce();
loop_rate.sleep();
count++;
}
cout << "'rosNodeTalker' finished" << endl;
return 0;
}
| 29.987342 | 119 | 0.704517 | [
"vector"
] |
76a3127b721a3b9d57bd614891da5e87044bacad | 9,807 | cpp | C++ | cpp-restsdk/model/SimAccess.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/SimAccess.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/SimAccess.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | /**
* PowerMeter API
* API
*
* The version of the OpenAPI document: 2021.4.1
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.3.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "SimAccess.h"
namespace powermeter {
namespace model {
SimAccess::SimAccess()
{
m_Master = 0;
m_MasterIsSet = false;
m_Master_name = utility::conversions::to_string_t("");
m_Master_nameIsSet = false;
m_Project = 0;
m_ProjectIsSet = false;
m_Project_name = utility::conversions::to_string_t("");
m_Project_nameIsSet = false;
m_Timestamp = utility::datetime();
m_TimestampIsSet = false;
m_Current_version = 0;
m_Current_versionIsSet = false;
}
SimAccess::~SimAccess()
{
}
void SimAccess::validate()
{
// TODO: implement validation
}
web::json::value SimAccess::toJson() const
{
web::json::value val = web::json::value::object();
if(m_MasterIsSet)
{
val[utility::conversions::to_string_t("master")] = ModelBase::toJson(m_Master);
}
if(m_Master_nameIsSet)
{
val[utility::conversions::to_string_t("master_name")] = ModelBase::toJson(m_Master_name);
}
if(m_ProjectIsSet)
{
val[utility::conversions::to_string_t("project")] = ModelBase::toJson(m_Project);
}
if(m_Project_nameIsSet)
{
val[utility::conversions::to_string_t("project_name")] = ModelBase::toJson(m_Project_name);
}
if(m_TimestampIsSet)
{
val[utility::conversions::to_string_t("timestamp")] = ModelBase::toJson(m_Timestamp);
}
if(m_Current_versionIsSet)
{
val[utility::conversions::to_string_t("current_version")] = ModelBase::toJson(m_Current_version);
}
return val;
}
bool SimAccess::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("master")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("master"));
if(!fieldValue.is_null())
{
int32_t refVal_master;
ok &= ModelBase::fromJson(fieldValue, refVal_master);
setMaster(refVal_master);
}
}
if(val.has_field(utility::conversions::to_string_t("master_name")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("master_name"));
if(!fieldValue.is_null())
{
utility::string_t refVal_master_name;
ok &= ModelBase::fromJson(fieldValue, refVal_master_name);
setMasterName(refVal_master_name);
}
}
if(val.has_field(utility::conversions::to_string_t("project")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("project"));
if(!fieldValue.is_null())
{
int32_t refVal_project;
ok &= ModelBase::fromJson(fieldValue, refVal_project);
setProject(refVal_project);
}
}
if(val.has_field(utility::conversions::to_string_t("project_name")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("project_name"));
if(!fieldValue.is_null())
{
utility::string_t refVal_project_name;
ok &= ModelBase::fromJson(fieldValue, refVal_project_name);
setProjectName(refVal_project_name);
}
}
if(val.has_field(utility::conversions::to_string_t("timestamp")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("timestamp"));
if(!fieldValue.is_null())
{
utility::datetime refVal_timestamp;
ok &= ModelBase::fromJson(fieldValue, refVal_timestamp);
setTimestamp(refVal_timestamp);
}
}
if(val.has_field(utility::conversions::to_string_t("current_version")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("current_version"));
if(!fieldValue.is_null())
{
int32_t refVal_current_version;
ok &= ModelBase::fromJson(fieldValue, refVal_current_version);
setCurrentVersion(refVal_current_version);
}
}
return ok;
}
void SimAccess::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m_MasterIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("master"), m_Master));
}
if(m_Master_nameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("master_name"), m_Master_name));
}
if(m_ProjectIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("project"), m_Project));
}
if(m_Project_nameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("project_name"), m_Project_name));
}
if(m_TimestampIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("timestamp"), m_Timestamp));
}
if(m_Current_versionIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("current_version"), m_Current_version));
}
}
bool SimAccess::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
bool ok = true;
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("master")))
{
int32_t refVal_master;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("master")), refVal_master );
setMaster(refVal_master);
}
if(multipart->hasContent(utility::conversions::to_string_t("master_name")))
{
utility::string_t refVal_master_name;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("master_name")), refVal_master_name );
setMasterName(refVal_master_name);
}
if(multipart->hasContent(utility::conversions::to_string_t("project")))
{
int32_t refVal_project;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("project")), refVal_project );
setProject(refVal_project);
}
if(multipart->hasContent(utility::conversions::to_string_t("project_name")))
{
utility::string_t refVal_project_name;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("project_name")), refVal_project_name );
setProjectName(refVal_project_name);
}
if(multipart->hasContent(utility::conversions::to_string_t("timestamp")))
{
utility::datetime refVal_timestamp;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("timestamp")), refVal_timestamp );
setTimestamp(refVal_timestamp);
}
if(multipart->hasContent(utility::conversions::to_string_t("current_version")))
{
int32_t refVal_current_version;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("current_version")), refVal_current_version );
setCurrentVersion(refVal_current_version);
}
return ok;
}
int32_t SimAccess::getMaster() const
{
return m_Master;
}
void SimAccess::setMaster(int32_t value)
{
m_Master = value;
m_MasterIsSet = true;
}
bool SimAccess::masterIsSet() const
{
return m_MasterIsSet;
}
void SimAccess::unsetMaster()
{
m_MasterIsSet = false;
}
utility::string_t SimAccess::getMasterName() const
{
return m_Master_name;
}
void SimAccess::setMasterName(const utility::string_t& value)
{
m_Master_name = value;
m_Master_nameIsSet = true;
}
bool SimAccess::masterNameIsSet() const
{
return m_Master_nameIsSet;
}
void SimAccess::unsetMaster_name()
{
m_Master_nameIsSet = false;
}
int32_t SimAccess::getProject() const
{
return m_Project;
}
void SimAccess::setProject(int32_t value)
{
m_Project = value;
m_ProjectIsSet = true;
}
bool SimAccess::projectIsSet() const
{
return m_ProjectIsSet;
}
void SimAccess::unsetProject()
{
m_ProjectIsSet = false;
}
utility::string_t SimAccess::getProjectName() const
{
return m_Project_name;
}
void SimAccess::setProjectName(const utility::string_t& value)
{
m_Project_name = value;
m_Project_nameIsSet = true;
}
bool SimAccess::projectNameIsSet() const
{
return m_Project_nameIsSet;
}
void SimAccess::unsetProject_name()
{
m_Project_nameIsSet = false;
}
utility::datetime SimAccess::getTimestamp() const
{
return m_Timestamp;
}
void SimAccess::setTimestamp(const utility::datetime& value)
{
m_Timestamp = value;
m_TimestampIsSet = true;
}
bool SimAccess::timestampIsSet() const
{
return m_TimestampIsSet;
}
void SimAccess::unsetTimestamp()
{
m_TimestampIsSet = false;
}
int32_t SimAccess::getCurrentVersion() const
{
return m_Current_version;
}
void SimAccess::setCurrentVersion(int32_t value)
{
m_Current_version = value;
m_Current_versionIsSet = true;
}
bool SimAccess::currentVersionIsSet() const
{
return m_Current_versionIsSet;
}
void SimAccess::unsetCurrent_version()
{
m_Current_versionIsSet = false;
}
}
}
| 27.860795 | 143 | 0.678189 | [
"object",
"model"
] |
76a487207aa88195a25e4a9259fc3e96a3b30092 | 803 | cpp | C++ | MPI2Send/MPI2Send24.cpp | bru1t/pt-for-mpi-2-answers | 81595465725db4cce848a1c45b3695203d97db03 | [
"Unlicense"
] | 2 | 2021-12-26T20:18:24.000Z | 2021-12-28T10:49:42.000Z | MPI2Send/MPI2Send24.cpp | bru1t/pt-for-mpi-2-answers | 81595465725db4cce848a1c45b3695203d97db03 | [
"Unlicense"
] | null | null | null | MPI2Send/MPI2Send24.cpp | bru1t/pt-for-mpi-2-answers | 81595465725db4cce848a1c45b3695203d97db03 | [
"Unlicense"
] | null | null | null | #include "pt4.h"
#include "mpi.h"
#include <vector>
template<typename T>
void sendrecv(int rank, int size, MPI_Datatype datatype, int step) {
MPI_Status status;
int next = (rank + step) % size,
N = size / 2;
std::vector<T> vector(N);
if (next < 0)
next += size;
for (int i = 0; i < N; ++i)
pt >> vector[i];
MPI_Sendrecv_replace(&vector[0], N, datatype, next, 0, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
for (auto &index : vector)
pt << index;
}
void Solve()
{
Task("MPI2Send24");
int flag;
MPI_Initialized(&flag);
if (flag == 0)
return;
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
(rank % 2 != 0) ? sendrecv<int>(rank, size, MPI_INT, -2) : sendrecv<float>(rank, size, MPI_FLOAT, 2);
}
| 19.585366 | 105 | 0.620174 | [
"vector"
] |
76a50f26b65985fc75b516a73631fbb0006649bb | 7,998 | cpp | C++ | ukpsummarizer-be/cplex/cpoptimizer/examples/src/cpp/sched_state.cpp | UKPLab/vldb2018-sherlock | 74f34ca074e72ad9137b60f921588585256e0eac | [
"Apache-2.0"
] | 2 | 2018-11-26T01:49:30.000Z | 2019-01-31T10:04:00.000Z | ukpsummarizer-be/cplex/cpoptimizer/examples/src/cpp/sched_state.cpp | AIPHES/vldb2018-sherlock | 3746efa35c4c1769cc4aaeb15aeb9453564e1226 | [
"Apache-2.0"
] | null | null | null | ukpsummarizer-be/cplex/cpoptimizer/examples/src/cpp/sched_state.cpp | AIPHES/vldb2018-sherlock | 3746efa35c4c1769cc4aaeb15aeb9453564e1226 | [
"Apache-2.0"
] | 4 | 2018-11-06T16:12:55.000Z | 2019-08-21T13:22:32.000Z | // -------------------------------------------------------------- -*- C++ -*-
// File: ./examples/src/cpp/sched_state.cpp
// --------------------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5725-A06 5725-A29
// Copyright IBM Corporation 1990, 2014. All Rights Reserved.
//
// Note to U.S. Government Users Restricted Rights:
// Use, duplication or disclosure restricted by GSA ADP Schedule
// Contract with IBM Corp.
// --------------------------------------------------------------------------
/* ------------------------------------------------------------
Problem Description
-------------------
This is a problem of building five houses. The masonry, roofing,
painting, etc. must be scheduled. Some tasks must necessarily take
place before others and these requirements are expressed through
precedence constraints.
A pool of two workers is available for building the houses. For a
given house, some tasks (namely: plumbing, ceiling and painting)
require the house to be clean whereas other tasks (namely: masonry,
carpentry, roofing and windows) put the house in a dirty state. A
transition time of 1 is needed to clean the house so to change from
state 'dirty' to state 'clean'.
The objective is to minimize the makespan.
------------------------------------------------------------ */
#include <ilcp/cp.h>
#include <sstream>
const IloInt NbHouses = 5;
const IloInt NbTasks = 10;
const IloInt NbWorkers = 2;
enum Tasks {
masonry = 0,
carpentry = 1,
plumbing = 2,
ceiling = 3,
roofing = 4,
painting = 5,
windows = 6,
facade = 7,
garden = 8,
moving = 9
};
const char* TaskNames [] = {
"masonry ",
"carpentry",
"plumbing ",
"ceiling ",
"roofing ",
"painting ",
"windows ",
"facade ",
"garden ",
"moving "
};
const IloInt TaskDurations [] = {
35,
15,
40,
15,
05,
10,
05,
10,
05,
05,
};
/* POSSIBLE HOUSE STATE. */
const IloInt Clean = 0;
const IloInt Dirty = 1;
void MakeHouse(IloModel model,
IloInt id,
IloIntExprArray ends,
IloIntervalVarArray allTasks,
IloCumulFunctionExpr& workers,
IloStateFunction houseState) {
IloEnv env = model.getEnv();
/* CREATE THE INTERVAL VARIABLES. */
IloIntervalVarArray tasks(env, NbTasks);
for (IloInt i=0; i<NbTasks; ++i) {
std::ostringstream name;
name << "H" << id << "-" << TaskNames[i];
tasks[i] = IloIntervalVar(env, TaskDurations[i], name.str().c_str());
workers += IloPulse(tasks[i], 1);
allTasks.add(tasks[i]);
}
/* PRECEDENCE CONSTRAINTS. */
model.add(IloEndBeforeStart(env, tasks[masonry], tasks[carpentry]));
model.add(IloEndBeforeStart(env, tasks[masonry], tasks[plumbing]));
model.add(IloEndBeforeStart(env, tasks[masonry], tasks[ceiling]));
model.add(IloEndBeforeStart(env, tasks[carpentry], tasks[roofing]));
model.add(IloEndBeforeStart(env, tasks[ceiling], tasks[painting]));
model.add(IloEndBeforeStart(env, tasks[roofing], tasks[windows]));
model.add(IloEndBeforeStart(env, tasks[roofing], tasks[facade]));
model.add(IloEndBeforeStart(env, tasks[plumbing], tasks[facade]));
model.add(IloEndBeforeStart(env, tasks[roofing], tasks[garden]));
model.add(IloEndBeforeStart(env, tasks[plumbing], tasks[garden]));
model.add(IloEndBeforeStart(env, tasks[windows], tasks[moving]));
model.add(IloEndBeforeStart(env, tasks[facade], tasks[moving]));
model.add(IloEndBeforeStart(env, tasks[garden], tasks[moving]));
model.add(IloEndBeforeStart(env, tasks[painting], tasks[moving]));
/* STATE CONSTRAINTS. */
model.add(IloAlwaysEqual(env, houseState, tasks[masonry], Dirty));
model.add(IloAlwaysEqual(env, houseState, tasks[carpentry], Dirty));
model.add(IloAlwaysEqual(env, houseState, tasks[plumbing], Clean));
model.add(IloAlwaysEqual(env, houseState, tasks[ceiling], Clean));
model.add(IloAlwaysEqual(env, houseState, tasks[roofing], Dirty));
model.add(IloAlwaysEqual(env, houseState, tasks[painting], Clean));
model.add(IloAlwaysEqual(env, houseState, tasks[windows], Dirty));
/* MAKESPAN. */
ends.add(IloEndOf(tasks[moving]));
}
int main(int, const char * []) {
IloEnv env;
try {
IloInt i;
IloModel model(env);
IloIntExprArray ends(env);
IloIntervalVarArray allTasks(env);
IloCumulFunctionExpr workers(env);
IloTransitionDistance ttime(env, 2);
ttime.setValue(Dirty, Clean, 1);
IloStateFunctionArray houseState(env, NbHouses);
for (i=0; i<NbHouses; ++i) {
houseState[i] = IloStateFunction(env, ttime);
MakeHouse(model, i, ends, allTasks, workers, houseState[i]);
}
model.add(workers <= NbWorkers);
model.add(IloMinimize(env, IloMax(ends)));
IloCP cp(model);
cp.setParameter(IloCP::FailLimit, 10000);
if (cp.solve()) {
cp.out() << "Solution with objective " << cp.getObjValue() << ":" << std::endl;
for (i=0; i<allTasks.getSize(); ++i) {
cp.out() << cp.domain(allTasks[i]) << std::endl;
}
for (IloInt h = 0; h < NbHouses; h++) {
for (i = 0; i < cp.getNumberOfSegments(houseState[h]); i++) {
cp.out() << "House " << h << " has state ";
IloInt s = cp.getSegmentValue(houseState[h], i);
if (s == Clean) cp.out() << "Clean";
else if (s == Dirty) cp.out() << "Dirty";
else if (s == IloCP::NoState) cp.out() << "None";
else cp.out() << "Unknown (problem)";
cp.out() << " from ";
if (cp.getSegmentStart(houseState[h], i) == IloIntervalMin) cp.out() << "Min";
else cp.out() << cp.getSegmentStart(houseState[h], i);
cp.out() << " to ";
if (cp.getSegmentEnd(houseState[h], i) == IloIntervalMax) cp.out() << "Max";
else cp.out() << cp.getSegmentEnd(houseState[h], i) - 1;
cp.out() << std::endl;
}
}
} else {
cp.out() << "No solution found. " << std::endl;
}
} catch (IloException& ex) {
env.out() << "Error: " << ex << std::endl;
}
env.end();
return 0;
}
/*
Solution with objective 365:
H0-masonry [1: 0 -- 35 --> 35]
H0-carpentry[1: 70 -- 15 --> 85]
H0-plumbing [1: 145 -- 40 --> 185]
H0-ceiling [1: 120 -- 15 --> 135]
H0-roofing [1: 195 -- 5 --> 200]
H0-painting [1: 340 -- 10 --> 350]
H0-windows [1: 290 -- 5 --> 295]
H0-facade [1: 320 -- 10 --> 330]
H0-garden [1: 285 -- 5 --> 290]
H0-moving [1: 350 -- 5 --> 355]
H1-masonry [1: 70 -- 35 --> 105]
H1-carpentry[1: 105 -- 15 --> 120]
H1-plumbing [1: 205 -- 40 --> 245]
H1-ceiling [1: 130 -- 15 --> 145]
H1-roofing [1: 175 -- 5 --> 180]
H1-painting [1: 310 -- 10 --> 320]
H1-windows [1: 280 -- 5 --> 285]
H1-facade [1: 305 -- 10 --> 315]
H1-garden [1: 265 -- 5 --> 270]
H1-moving [1: 360 -- 5 --> 365]
H2-masonry [1: 35 -- 35 --> 70]
H2-carpentry[1: 115 -- 15 --> 130]
H2-plumbing [1: 245 -- 40 --> 285]
H2-ceiling [1: 250 -- 15 --> 265]
H2-roofing [1: 200 -- 5 --> 205]
H2-painting [1: 335 -- 10 --> 345]
H2-windows [1: 345 -- 5 --> 350]
H2-facade [1: 290 -- 10 --> 300]
H2-garden [1: 305 -- 5 --> 310]
H2-moving [1: 350 -- 5 --> 355]
H3-masonry [1: 35 -- 35 --> 70]
H3-carpentry[1: 100 -- 15 --> 115]
H3-plumbing [1: 205 -- 40 --> 245]
H3-ceiling [1: 180 -- 15 --> 195]
H3-roofing [1: 245 -- 5 --> 250]
H3-painting [1: 325 -- 10 --> 335]
H3-windows [1: 300 -- 5 --> 305]
H3-facade [1: 315 -- 10 --> 325]
H3-garden [1: 330 -- 5 --> 335]
H3-moving [1: 355 -- 5 --> 360]
H4-masonry [1: 0 -- 35 --> 35]
H4-carpentry[1: 85 -- 15 --> 100]
H4-plumbing [1: 135 -- 40 --> 175]
H4-ceiling [1: 185 -- 15 --> 200]
H4-roofing [1: 200 -- 5 --> 205]
H4-painting [1: 295 -- 10 --> 305]
H4-windows [1: 285 -- 5 --> 290]
H4-facade [1: 270 -- 10 --> 280]
H4-garden [1: 335 -- 5 --> 340]
H4-moving [1: 355 -- 5 --> 360]
*/
| 33.464435 | 98 | 0.574519 | [
"model"
] |
76a6a3853bccc565c1ce307ca7f78611f231729f | 26,976 | cpp | C++ | src/dplyr.cpp | krlmlr/dplyr | 9128dddd245592092e68703d8cbc181b492ed69b | [
"MIT"
] | null | null | null | src/dplyr.cpp | krlmlr/dplyr | 9128dddd245592092e68703d8cbc181b492ed69b | [
"MIT"
] | 5 | 2016-09-28T20:10:06.000Z | 2017-09-14T05:44:45.000Z | src/dplyr.cpp | krlmlr/dplyr | 9128dddd245592092e68703d8cbc181b492ed69b | [
"MIT"
] | 1 | 2017-09-21T14:14:26.000Z | 2017-09-21T14:14:26.000Z | #define R_NOREMAP
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Rdynload.h>
#include <algorithm>
#include <vector>
#include <string>
#include "dplyr/symbols.h"
namespace dplyr {
SEXP get_classes_vctrs_list_of() {
SEXP klasses = Rf_allocVector(STRSXP, 3);
R_PreserveObject(klasses);
SET_STRING_ELT(klasses, 0, Rf_mkChar("vctrs_list_of"));
SET_STRING_ELT(klasses, 1, Rf_mkChar("vctrs_vctr"));
SET_STRING_ELT(klasses, 2, Rf_mkChar("list"));
return klasses;
}
SEXP get_classes_tbl_df() {
SEXP klasses = Rf_allocVector(STRSXP, 3);
R_PreserveObject(klasses);
SET_STRING_ELT(klasses, 0, Rf_mkChar("tbl_df"));
SET_STRING_ELT(klasses, 1, Rf_mkChar("tbl"));
SET_STRING_ELT(klasses, 2, Rf_mkChar("data.frame"));
return klasses;
}
SEXP get_empty_int_vector() {
SEXP x = Rf_allocVector(INTSXP, 0);
R_PreserveObject(x);
return x;
}
SEXP symbols::ptype = Rf_install("ptype");
SEXP symbols::levels = Rf_install("levels");
SEXP symbols::groups = Rf_install("groups");
SEXP symbols::vars = Rf_install("vars");
SEXP symbols::current_group = Rf_install("current_group");
SEXP symbols::rows = Rf_install("rows");
SEXP symbols::dot_dot_group_size = Rf_install("..group_size");
SEXP symbols::dot_dot_group_number = Rf_install("..group_number");
SEXP symbols::mask = Rf_install("mask");
SEXP symbols::caller = Rf_install("caller");
SEXP vectors::classes_vctrs_list_of = get_classes_vctrs_list_of();
SEXP vectors::classes_tbl_df = get_classes_tbl_df();
SEXP vectors::empty_int_vector = get_empty_int_vector();
} // dplyr
namespace rlang {
// *INDENT-OFF*
struct rlang_api_ptrs_t {
SEXP (*eval_tidy)(SEXP expr, SEXP data, SEXP env);
rlang_api_ptrs_t() {
eval_tidy = (SEXP (*)(SEXP, SEXP, SEXP)) R_GetCCallable("rlang", "rlang_eval_tidy");
}
};
// *INDENT-ON*
const rlang_api_ptrs_t& rlang_api() {
static rlang_api_ptrs_t ptrs;
return ptrs;
}
inline SEXP eval_tidy(SEXP expr, SEXP data, SEXP env) {
return rlang_api().eval_tidy(expr, data, env);
}
}
namespace vctrs {
// *INDENT-OFF*
struct vctrs_api_ptrs_t {
bool (*vec_is_vector)(SEXP x);
R_len_t (*short_vec_size)(SEXP x);
vctrs_api_ptrs_t() {
vec_is_vector = (bool (*)(SEXP)) R_GetCCallable("vctrs", "vec_is_vector");
short_vec_size = (R_len_t (*)(SEXP)) R_GetCCallable("vctrs", "short_vec_size");
}
};
// *INDENT-ON*
const vctrs_api_ptrs_t& vctrs_api() {
static vctrs_api_ptrs_t ptrs;
return ptrs;
}
inline bool vec_is_vector(SEXP x) {
return vctrs_api().vec_is_vector(x);
}
inline R_len_t short_vec_size(SEXP x) {
return vctrs_api().short_vec_size(x);
}
}
// support for expand_groups()
class ExpanderCollecter;
struct ExpanderResult {
ExpanderResult(R_xlen_t start_, R_xlen_t end_, R_xlen_t index_) :
start(start_),
end(end_),
index(index_)
{}
R_xlen_t start;
R_xlen_t end;
R_xlen_t index;
inline R_xlen_t size() const {
return end - start;
}
};
class Expander {
public:
virtual ~Expander() {};
virtual R_xlen_t size() const = 0;
virtual ExpanderResult collect(ExpanderCollecter& results, int depth) const = 0;
};
class ExpanderCollecter {
public:
ExpanderCollecter(int nvars_, SEXP new_indices_, int new_size_, SEXP new_rows_, SEXP old_rows_) :
nvars(nvars_),
old_rows(old_rows_),
new_size(new_size_),
new_indices(new_indices_),
new_rows(new_rows_),
leaf_index(0),
vec_new_indices(nvars)
{
Rf_classgets(new_rows, dplyr::vectors::classes_vctrs_list_of);
Rf_setAttrib(new_rows, dplyr::symbols::ptype, dplyr::vectors::empty_int_vector);
for (int i = 0; i < nvars; i++) {
SEXP new_indices_i = Rf_allocVector(INTSXP, new_size);
SET_VECTOR_ELT(new_indices, i, new_indices_i);
vec_new_indices[i] = INTEGER(new_indices_i);
}
}
ExpanderResult collect_leaf(R_xlen_t start, R_xlen_t end, R_xlen_t index) {
if (start == end) {
SET_VECTOR_ELT(new_rows, leaf_index++, dplyr::vectors::empty_int_vector);
} else {
SET_VECTOR_ELT(new_rows, leaf_index++, VECTOR_ELT(old_rows, start));
}
return ExpanderResult(leaf_index - 1, leaf_index, index);
}
ExpanderResult collect_node(int depth, R_xlen_t index, const std::vector<Expander*>& expanders) {
int n = expanders.size();
if (n == 0) {
return ExpanderResult(NA_INTEGER, NA_INTEGER, index);
}
R_xlen_t nr = 0;
ExpanderResult first = expanders[0]->collect(*this, depth + 1);
R_xlen_t start = first.start;
R_xlen_t end = first.end;
fill_indices(depth, start, end, first.index);
nr += first.size();
for (R_xlen_t i = 1; i < n; i++) {
ExpanderResult exp_i = expanders[i]->collect(*this, depth + 1);
fill_indices(depth, exp_i.start, exp_i.end, exp_i.index);
nr += exp_i.size();
end = exp_i.end;
}
return ExpanderResult(start, end, index);
}
private:
int nvars;
SEXP old_rows;
R_xlen_t new_size;
SEXP new_indices;
SEXP new_rows;
int leaf_index;
std::vector<int*> vec_new_indices;
void fill_indices(int depth, R_xlen_t start, R_xlen_t end, R_xlen_t index) {
std::fill(vec_new_indices[depth] + start, vec_new_indices[depth] + end, index);
}
ExpanderCollecter(const ExpanderCollecter&);
};
Expander* expander(const std::vector<SEXP>& data, const std::vector<int*>& positions, int depth, R_xlen_t index, R_xlen_t start, R_xlen_t end);
inline R_xlen_t expanders_size(const std::vector<Expander*> expanders) {
R_xlen_t n = 0;
for (int i = 0; i < expanders.size(); i++) {
n += expanders[i]->size();
}
return n;
}
class FactorExpander : public Expander {
public:
FactorExpander(const std::vector<SEXP>& data_, const std::vector<int*>& positions_, int depth_, R_xlen_t index_, R_xlen_t start_, R_xlen_t end_) :
data(data_),
positions(positions_),
index(index_),
start(start_),
end(end_)
{
SEXP fac = data[depth_];
SEXP levels = Rf_getAttrib(fac, dplyr::symbols::levels);
R_xlen_t n_levels = XLENGTH(levels);
expanders.resize(n_levels);
int* fac_pos = positions[depth_];
// for each level, setup an expander for `depth + 1`
R_xlen_t j = start;
for (R_xlen_t i = 0; i < n_levels; i++) {
R_xlen_t start_i = j;
while (j < end && fac_pos[j] == i + 1) j++;
expanders[i] = expander(data, positions, depth_ + 1, i + 1, start_i, j);
}
// implicit NA
if (j < end) {
expanders.push_back(expander(data, positions, depth_ + 1, NA_INTEGER, j, end));
}
}
~FactorExpander() {
for (int i = expanders.size() - 1; i >= 0; i--) delete expanders[i];
}
virtual R_xlen_t size() const {
return expanders_size(expanders);
}
ExpanderResult collect(ExpanderCollecter& results, int depth) const {
return results.collect_node(depth, index, expanders);
}
private:
const std::vector<SEXP>& data;
const std::vector<int*>& positions;
R_xlen_t index;
R_xlen_t start;
R_xlen_t end;
std::vector<Expander*> expanders;
};
class VectorExpander : public Expander {
public:
VectorExpander(const std::vector<SEXP>& data_, const std::vector<int*>& positions_, int depth_, R_xlen_t index_, R_xlen_t start, R_xlen_t end) :
index(index_)
{
// edge case no data, we need a fake expander with NA index
if (start == end) {
expanders.push_back(expander(data_, positions_, depth_ + 1, NA_INTEGER, start, end));
} else {
int* vec_pos = positions_[depth_];
for (R_xlen_t j = start; j < end;) {
R_xlen_t current = vec_pos[j];
R_xlen_t start_idx = j;
while (j < end && vec_pos[++j] == current);
expanders.push_back(expander(data_, positions_, depth_ + 1, current, start_idx, j));
}
}
}
~VectorExpander() {
for (int i = expanders.size() - 1; i >= 0; i--) delete expanders[i];
}
virtual R_xlen_t size() const {
return expanders_size(expanders);
}
ExpanderResult collect(ExpanderCollecter& results, int depth) const {
return results.collect_node(depth, index, expanders);
}
private:
int index;
std::vector<Expander*> expanders;
};
class LeafExpander : public Expander {
public:
LeafExpander(const std::vector<SEXP>& data_, const std::vector<int*>& positions_, int depth_, int index_, int start_, int end_) :
index(index_),
start(start_),
end(end_)
{}
~LeafExpander() {}
virtual R_xlen_t size() const {
return 1;
}
ExpanderResult collect(ExpanderCollecter& results, int depth) const {
return results.collect_leaf(start, end, index);
}
private:
R_xlen_t index;
R_xlen_t start;
R_xlen_t end;
};
Expander* expander(const std::vector<SEXP>& data, const std::vector<int*>& positions, int depth, R_xlen_t index, R_xlen_t start, R_xlen_t end) {
if (depth == positions.size()) {
return new LeafExpander(data, positions, depth, index, start, end);
} else if (Rf_isFactor(data[depth])) {
return new FactorExpander(data, positions, depth, index, start, end);
} else {
return new VectorExpander(data, positions, depth, index, start, end);
}
}
SEXP dplyr_expand_groups(SEXP old_groups, SEXP positions, SEXP s_nr) {
int nr = INTEGER(s_nr)[0];
R_xlen_t nvars = XLENGTH(old_groups) - 1;
SEXP old_rows = VECTOR_ELT(old_groups, nvars);
std::vector<SEXP> vec_data(nvars);
std::vector<int*> vec_positions(nvars);
for (R_xlen_t i = 0; i < nvars; i++) {
vec_data[i] = VECTOR_ELT(old_groups, i);
vec_positions[i] = INTEGER(VECTOR_ELT(positions, i));
}
Expander* exp = expander(vec_data, vec_positions, 0, NA_INTEGER, 0, nr);
SEXP new_indices = PROTECT(Rf_allocVector(VECSXP, nvars));
SEXP new_rows = PROTECT(Rf_allocVector(VECSXP, exp->size()));
ExpanderCollecter results(nvars, new_indices, exp->size(), new_rows, old_rows);
exp->collect(results, 0);
SEXP out = PROTECT(Rf_allocVector(VECSXP, 2));
SET_VECTOR_ELT(out, 0, new_indices);
SET_VECTOR_ELT(out, 1, new_rows);
delete exp;
UNPROTECT(3);
return out;
}
SEXP dplyr_filter_update_rows(SEXP s_n_rows, SEXP group_indices, SEXP keep, SEXP new_rows_sizes) {
int n_rows = INTEGER(s_n_rows)[0];
R_xlen_t n_groups = XLENGTH(new_rows_sizes);
SEXP new_rows = PROTECT(Rf_allocVector(VECSXP, n_groups));
Rf_setAttrib(new_rows, R_ClassSymbol, dplyr::vectors::classes_vctrs_list_of);
Rf_setAttrib(new_rows, dplyr::symbols::ptype, dplyr::vectors::empty_int_vector);
// allocate each new_rows element
int* p_new_rows_sizes = INTEGER(new_rows_sizes);
std::vector<int> tracks(n_groups);
std::vector<int*> p_new_rows(n_groups);
for (R_xlen_t i = 0; i < n_groups; i++) {
SEXP new_rows_i = Rf_allocVector(INTSXP, p_new_rows_sizes[i]);
SET_VECTOR_ELT(new_rows, i, new_rows_i);
p_new_rows[i] = INTEGER(new_rows_i);
}
// traverse group_indices and keep to fill new_rows
int* p_group_indices = INTEGER(group_indices);
int* p_keep = LOGICAL(keep);
R_xlen_t j = 1;
for (R_xlen_t i = 0; i < n_rows; i++) {
if (p_keep[i] == TRUE) {
int g = p_group_indices[i];
int track = tracks[g - 1]++;
p_new_rows[g - 1][track] = j++;
}
}
UNPROTECT(1);
return new_rows;
}
SEXP dplyr_mask_eval_all(SEXP quo, SEXP env_private, SEXP env_context) {
SEXP rows = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::rows));
R_xlen_t ngroups = XLENGTH(rows);
SEXP mask = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::mask));
SEXP caller = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::caller));
SEXP chunks = PROTECT(Rf_allocVector(VECSXP, ngroups));
for (R_xlen_t i = 0; i < ngroups; i++) {
SEXP current_group = PROTECT(Rf_ScalarInteger(i + 1));
Rf_defineVar(dplyr::symbols::current_group, current_group, env_private);
Rf_defineVar(dplyr::symbols::dot_dot_group_size, Rf_ScalarInteger(XLENGTH(VECTOR_ELT(rows, i))), env_context);
Rf_defineVar(dplyr::symbols::dot_dot_group_number, current_group, env_context);
SET_VECTOR_ELT(chunks, i, rlang::eval_tidy(quo, mask, caller));
UNPROTECT(1);
}
UNPROTECT(4);
return chunks;
}
SEXP dplyr_mask_eval_all_summarise(SEXP quo, SEXP env_private, SEXP env_context, SEXP dots_names, SEXP sexp_i) {
SEXP rows = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::rows));
R_xlen_t ngroups = XLENGTH(rows);
SEXP mask = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::mask));
SEXP caller = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::caller));
SEXP chunks = PROTECT(Rf_allocVector(VECSXP, ngroups));
for (R_xlen_t i = 0; i < ngroups; i++) {
SEXP rows_i = VECTOR_ELT(rows, i);
R_xlen_t n_i = XLENGTH(rows_i);
SEXP current_group = PROTECT(Rf_ScalarInteger(i + 1));
Rf_defineVar(dplyr::symbols::current_group, current_group, env_private);
Rf_defineVar(dplyr::symbols::dot_dot_group_size, Rf_ScalarInteger(n_i), env_context);
Rf_defineVar(dplyr::symbols::dot_dot_group_number, current_group, env_context);
SEXP result_i = PROTECT(rlang::eval_tidy(quo, mask, caller));
if (!vctrs::vec_is_vector(result_i)) {
if (!Rf_isNull(dots_names)) {
SEXP name = STRING_ELT(dots_names, i);
if (XLENGTH(name) > 0) {
Rf_errorcall(R_NilValue, "Unsupported type for result `%s`", CHAR(name));
}
}
int i = INTEGER(sexp_i)[0];
Rf_errorcall(R_NilValue, "Unsupported type at index %d", i);
}
SET_VECTOR_ELT(chunks, i, result_i);
UNPROTECT(2);
}
UNPROTECT(4);
return chunks;
}
SEXP dplyr_mask_eval_all_mutate(SEXP quo, SEXP env_private, SEXP env_context, SEXP dots_names, SEXP sexp_i) {
SEXP rows = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::rows));
R_xlen_t ngroups = XLENGTH(rows);
SEXP mask = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::mask));
SEXP caller = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::caller));
SEXP res = PROTECT(Rf_allocVector(VECSXP, 2));
SEXP chunks = PROTECT(Rf_allocVector(VECSXP, ngroups));
bool seen_vec = false;
bool needs_recycle = false;
for (R_xlen_t i = 0; i < ngroups; i++) {
SEXP rows_i = VECTOR_ELT(rows, i);
R_xlen_t n_i = XLENGTH(rows_i);
SEXP current_group = PROTECT(Rf_ScalarInteger(i + 1));
Rf_defineVar(dplyr::symbols::current_group, current_group, env_private);
Rf_defineVar(dplyr::symbols::dot_dot_group_size, Rf_ScalarInteger(n_i), env_context);
Rf_defineVar(dplyr::symbols::dot_dot_group_number, current_group, env_context);
SEXP result_i = PROTECT(rlang::eval_tidy(quo, mask, caller));
if (Rf_isNull(result_i)) {
if (seen_vec) {
// the current chunk is NULL but there were some non NULL
// chunks, so this is an error
Rf_errorcall(R_NilValue, "incompatible results for mutate(), some results are NULL");
} else {
UNPROTECT(2);
continue;
}
} else {
seen_vec = true;
}
if (!vctrs::vec_is_vector(result_i)) {
if (!Rf_isNull(dots_names)) {
SEXP name = STRING_ELT(dots_names, i);
if (XLENGTH(name) > 0) {
Rf_errorcall(R_NilValue, "Unsupported type for result `%s`", CHAR(name));
}
}
int i = INTEGER(sexp_i)[0];
Rf_errorcall(R_NilValue, "Unsupported type at index %d", i);
}
if (!needs_recycle && vctrs::short_vec_size(result_i) != n_i) {
needs_recycle = true;
}
SET_VECTOR_ELT(chunks, i, result_i);
UNPROTECT(2);
}
// there was only NULL results
if (ngroups > 0 && !seen_vec) {
chunks = R_NilValue;
}
SET_VECTOR_ELT(res, 0, chunks);
SET_VECTOR_ELT(res, 1, Rf_ScalarLogical(needs_recycle));
UNPROTECT(5);
return res;
}
SEXP dplyr_mask_eval_all_filter(SEXP quo, SEXP env_private, SEXP env_context, SEXP s_n) {
SEXP rows = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::rows));
R_xlen_t ngroups = XLENGTH(rows);
SEXP mask = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::mask));
SEXP caller = PROTECT(Rf_findVarInFrame(env_private, dplyr::symbols::caller));
R_xlen_t n = Rf_asInteger(s_n);
SEXP keep = PROTECT(Rf_allocVector(LGLSXP, n));
int* p_keep = LOGICAL(keep);
SEXP new_group_sizes = PROTECT(Rf_allocVector(INTSXP, ngroups));
int* p_new_group_sizes = INTEGER(new_group_sizes);
SEXP group_indices = PROTECT(Rf_allocVector(INTSXP, n));
int* p_group_indices = INTEGER(group_indices);
SEXP res = PROTECT(Rf_allocVector(VECSXP, 3));
SET_VECTOR_ELT(res, 0, keep);
SET_VECTOR_ELT(res, 1, new_group_sizes);
SET_VECTOR_ELT(res, 2, group_indices);
for (R_xlen_t i = 0; i < ngroups; i++) {
SEXP rows_i = VECTOR_ELT(rows, i);
R_xlen_t n_i = XLENGTH(rows_i);
SEXP current_group = PROTECT(Rf_ScalarInteger(i + 1));
Rf_defineVar(dplyr::symbols::current_group, current_group, env_private);
Rf_defineVar(dplyr::symbols::dot_dot_group_size, Rf_ScalarInteger(n_i), env_context);
Rf_defineVar(dplyr::symbols::dot_dot_group_number, current_group, env_context);
SEXP result_i = PROTECT(rlang::eval_tidy(quo, mask, caller));
if (TYPEOF(result_i) != LGLSXP) {
Rf_errorcall(R_NilValue, "filter() expressions should return logical vectors of the same size as the group");
}
R_xlen_t n_result_i = XLENGTH(result_i);
// sprinkle
int* p_rows_i = INTEGER(rows_i);
if (n_i == n_result_i) {
int* p_result_i = LOGICAL(result_i);
int nkeep = 0;
for (R_xlen_t j = 0; j < n_i; j++, ++p_rows_i, ++p_result_i) {
p_keep[*p_rows_i - 1] = *p_result_i == TRUE;
p_group_indices[*p_rows_i - 1] = i + 1;
nkeep += (*p_result_i == TRUE);
}
p_new_group_sizes[i] = nkeep;
} else if (n_result_i == 1) {
int constant_result_i = *LOGICAL(result_i);
for (R_xlen_t j = 0; j < n_i; j++, ++p_rows_i) {
p_keep[*p_rows_i - 1] = constant_result_i;
p_group_indices[*p_rows_i - 1] = i + 1;
}
p_new_group_sizes[i] = n_i * (constant_result_i == TRUE);
} else {
Rf_errorcall(R_NilValue, "filter() expressions should return logical vectors of the same size as the group");
}
UNPROTECT(2);
}
UNPROTECT(7);
return res;
}
SEXP dplyr_vec_sizes(SEXP chunks) {
R_xlen_t n = XLENGTH(chunks);
SEXP res = PROTECT(Rf_allocVector(INTSXP, n));
int* p_res = INTEGER(res);
for (R_xlen_t i = 0; i < n; i++, ++p_res) {
*p_res = vctrs::short_vec_size(VECTOR_ELT(chunks, i));
}
UNPROTECT(1);
return res;
}
SEXP dplyr_validate_summarise_sizes(SEXP size, SEXP chunks) {
R_xlen_t nchunks = XLENGTH(chunks);
if (XLENGTH(size) == 1 && INTEGER(size)[0] == 1) {
// we might not have to allocate the vector of sizes if
// all the chunks are of size 1
R_xlen_t i = 0;
for (; i < nchunks; i++) {
if (vctrs::short_vec_size(VECTOR_ELT(chunks, i)) != 1) {
break;
}
}
if (i == nchunks) {
// we can just return the input size
return size;
}
// we need to return a vector to track the new sizes
size = PROTECT(Rf_allocVector(INTSXP, nchunks));
int* p_size = INTEGER(size);
// until i, all sizes are 1
for (R_xlen_t j = 0; j < i; j++, ++p_size) {
*p_size = 1;
}
// then finish with i
for (; i < nchunks; i++, ++p_size) {
*p_size = vctrs::short_vec_size(VECTOR_ELT(chunks, i));
}
UNPROTECT(1);
return size;
} else {
// size is already a vector, we need to check if the sizes of chunks
// matches
int* p_size = INTEGER(size);
for (R_xlen_t i = 0; i < nchunks; i++, ++p_size) {
if (*p_size != vctrs::short_vec_size(VECTOR_ELT(chunks, i))) {
Rf_errorcall(R_NilValue, "Result does not respect vec_size() == .size");
}
}
return size;
}
}
// ------- funs
SEXP dplyr_between(SEXP x, SEXP s_left, SEXP s_right) {
R_xlen_t n = XLENGTH(x);
double left = REAL(s_left)[0], right = REAL(s_right)[0];
SEXP out = PROTECT(Rf_allocVector(LGLSXP, n));
// Assume users know what they're doing with date/times. In the future
// should ensure that left and right are the correct class too.
if (!Rf_isNull(Rf_getAttrib(x, R_ClassSymbol)) && !Rf_inherits(x, "Date") && !Rf_inherits(x, "POSIXct")) {
Rf_warningcall(R_NilValue, "between() called on numeric vector with S3 class");
}
if (R_IsNA(left) || R_IsNA(right)) {
std::fill(LOGICAL(out), LOGICAL(out) + n, NA_LOGICAL);
} else {
int* p_out = LOGICAL(out);
double* p_x = REAL(x);
for (R_xlen_t i = 0; i < n; ++i, ++p_x, ++p_out) {
*p_out = R_IsNA(*p_x) ? NA_LOGICAL : (*p_x >= left) && (*p_x <= right);
}
}
UNPROTECT(1);
return out;
}
SEXP dplyr_cumall(SEXP x) {
R_xlen_t n = XLENGTH(x);
SEXP out = PROTECT(Rf_allocVector(LGLSXP, n));
int* p_x = LOGICAL(x);
int* p_out = LOGICAL(out);
// set out[i] to TRUE as long as x[i] is TRUE
R_xlen_t i = 0 ;
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == TRUE) {
*p_out = TRUE;
} else {
break;
}
}
if (i != n) {
// set to NA as long as x[i] is NA or TRUE
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == FALSE) {
break;
}
*p_out = NA_LOGICAL;
}
// set remaining to FALSE
if (i != n) {
for (; i < n; i++, ++p_x, ++p_out) {
*p_out = FALSE;
}
}
}
UNPROTECT(1);
return out;
}
SEXP dplyr_cumany(SEXP x) {
R_xlen_t n = XLENGTH(x);
SEXP out = PROTECT(Rf_allocVector(LGLSXP, n));
int* p_x = LOGICAL(x);
int* p_out = LOGICAL(out);
// nothing to do as long as x[i] is FALSE
R_xlen_t i = 0 ;
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == FALSE) {
*p_out = FALSE;
} else {
break;
}
}
if (i < n) {
// set to NA as long as x[i] is NA or FALSE
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == TRUE) {
break;
}
*p_out = NA_LOGICAL;
}
if (i < n) {
// then if we are here, the rest is TRUE
for (; i < n; i++, ++p_out) {
*p_out = TRUE;
}
}
}
UNPROTECT(1);
return out;
}
SEXP dplyr_cummean(SEXP x) {
R_xlen_t n = XLENGTH(x);
SEXP out = PROTECT(Rf_allocVector(REALSXP, n));
double* p_out = REAL(out);
double* p_x = REAL(x);
double sum = *p_out++ = *p_x;
for (R_xlen_t i = 1; i < n; i++, ++p_x, ++p_out) {
sum += *p_x;
*p_out = sum / (i + 1.0);
}
UNPROTECT(1);
return out;
}
SEXP dplyr_validate_grouped_df(SEXP df, SEXP s_nr_df, SEXP s_check_bounds) {
if (!Rf_inherits(df, "grouped_df")) {
return Rf_mkString("not a `grouped_df` object");
}
SEXP vars = Rf_getAttrib(df, dplyr::symbols::vars);
SEXP groups = Rf_getAttrib(df, dplyr::symbols::groups);
if (!Rf_isNull(vars) && Rf_isNull(groups)) {
return Rf_mkString("Corrupt grouped_df data using the old format");
}
if (!Rf_inherits(groups, "data.frame") || XLENGTH(groups) < 1) {
return Rf_mkString("The `groups` attribute is not a data frame with its last column called `.rows`");
}
SEXP groups_names = Rf_getAttrib(groups, R_NamesSymbol);
if (Rf_isNull(groups_names) || TYPEOF(groups_names) != STRSXP || ::strcmp(CHAR(STRING_ELT(groups_names, XLENGTH(groups_names) - 1)), ".rows")) {
return Rf_mkString("The `groups` attribute is not a data frame with its last column called `.rows`");
}
SEXP dot_rows = VECTOR_ELT(groups, XLENGTH(groups) - 1);
if (TYPEOF(dot_rows) != VECSXP) {
return Rf_mkString("The `groups` attribute is not a data frame with its last column called `.rows`");
}
R_xlen_t nr = XLENGTH(dot_rows);
for (R_xlen_t i = 0; i < nr; i++) {
SEXP rows_i = VECTOR_ELT(dot_rows, i);
if (TYPEOF(rows_i) != INTSXP) {
return Rf_mkString("`.rows` column is not a list of one-based integer vectors");
}
}
if (LOGICAL(s_check_bounds)[0]) {
R_xlen_t nr_df = TYPEOF(s_nr_df) == INTSXP ? (R_xlen_t)(INTEGER(s_nr_df)[0]) : (R_xlen_t)(REAL(s_nr_df)[0]);
for (R_xlen_t i = 0; i < nr; i++) {
SEXP rows_i = VECTOR_ELT(dot_rows, i);
R_xlen_t n_i = XLENGTH(rows_i);
int* p_rows_i = INTEGER(rows_i);
for (R_xlen_t j = 0; j < n_i; j++, ++p_rows_i) {
if (*p_rows_i < 1 || *p_rows_i > nr_df) {
return Rf_mkString("out of bounds indices");
}
}
}
}
return R_NilValue;
}
SEXP dplyr_group_keys_impl(SEXP data) {
SEXP keys;
SEXP keys_names;
SEXP groups = Rf_getAttrib(data, dplyr::symbols::groups);
R_xlen_t nr;
if (Rf_isNull(groups)) {
nr = 1;
keys_names = PROTECT(Rf_allocVector(STRSXP, 0));
keys = PROTECT(Rf_allocVector(VECSXP, 0));
} else {
R_xlen_t nc = XLENGTH(groups) - 1;
nr = XLENGTH(VECTOR_ELT(groups, nc));
SEXP groups_names = Rf_getAttrib(groups, R_NamesSymbol);
keys = PROTECT(Rf_allocVector(VECSXP, nc));
keys_names = PROTECT(Rf_allocVector(STRSXP, nc));
for (R_xlen_t i = 0; i < nc; i++) {
SET_VECTOR_ELT(keys, i, VECTOR_ELT(groups, i));
SET_STRING_ELT(keys_names, i, STRING_ELT(groups_names, i));
}
}
SEXP rn = PROTECT(Rf_allocVector(INTSXP, 2));
INTEGER(rn)[0] = NA_INTEGER;
INTEGER(rn)[1] = -nr;
Rf_setAttrib(keys, R_RowNamesSymbol, rn);
Rf_setAttrib(keys, R_NamesSymbol, keys_names);
Rf_setAttrib(keys, R_ClassSymbol, dplyr::vectors::classes_tbl_df);
UNPROTECT(3);
return keys;
}
SEXP dplyr_group_indices(SEXP data, SEXP s_nr) {
SEXP groups = Rf_getAttrib(data, dplyr::symbols::groups);
SEXP rows = VECTOR_ELT(groups, XLENGTH(groups) - 1);
R_xlen_t nr = INTEGER(s_nr)[0];
R_xlen_t ng = XLENGTH(rows);
SEXP indices = PROTECT(Rf_allocVector(INTSXP, nr));
int* p_indices = INTEGER(indices);
for (R_xlen_t i = 0; i < ng; i++) {
SEXP rows_i = VECTOR_ELT(rows, i);
R_xlen_t n_i = XLENGTH(rows_i);
int* p_rows_i = INTEGER(rows_i);
for (R_xlen_t j = 0; j < n_i; j++, ++p_rows_i) {
p_indices[*p_rows_i - 1] = i + 1;
}
}
UNPROTECT(1);
return indices;
}
static const R_CallMethodDef CallEntries[] = {
{"dplyr_expand_groups", (DL_FUNC)& dplyr_expand_groups, 3},
{"dplyr_filter_update_rows", (DL_FUNC)& dplyr_filter_update_rows, 4},
{"dplyr_between", (DL_FUNC)& dplyr_between, 3},
{"dplyr_cumall", (DL_FUNC)& dplyr_cumall, 1},
{"dplyr_cumany", (DL_FUNC)& dplyr_cumany, 1},
{"dplyr_cummean", (DL_FUNC)& dplyr_cummean, 1},
{"dplyr_validate_grouped_df", (DL_FUNC)& dplyr_validate_grouped_df, 3},
{"dplyr_group_keys_impl", (DL_FUNC)& dplyr_group_keys_impl, 1},
{"dplyr_mask_eval_all", (DL_FUNC)& dplyr_mask_eval_all, 3},
{"dplyr_mask_eval_all_summarise", (DL_FUNC)& dplyr_mask_eval_all_summarise, 5},
{"dplyr_mask_eval_all_mutate", (DL_FUNC)& dplyr_mask_eval_all_mutate, 5},
{"dplyr_mask_eval_all_filter", (DL_FUNC)& dplyr_mask_eval_all_filter, 4},
{"dplyr_vec_sizes", (DL_FUNC)& dplyr_vec_sizes, 1},
{"dplyr_validate_summarise_sizes", (DL_FUNC)& dplyr_validate_summarise_sizes, 2},
{"dplyr_group_indices", (DL_FUNC)& dplyr_group_indices, 2},
{NULL, NULL, 0}
};
extern "C" void R_init_dplyr(DllInfo* dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| 29.417666 | 148 | 0.662107 | [
"object",
"vector"
] |
76a7bcfb5e0d8805e1e80193a627207785c6bc9c | 8,745 | cpp | C++ | src/gvs/vis-client/scene/opengl_scene.cpp | LoganBarnes/geometry-visualization-server | 3ea890d760ada4e5a248e98dded2e27ba6bd5dde | [
"MIT"
] | 1 | 2019-01-09T12:17:40.000Z | 2019-01-09T12:17:40.000Z | src/gvs/vis-client/scene/opengl_scene.cpp | LoganBarnes/geometry-visualization-server | 3ea890d760ada4e5a248e98dded2e27ba6bd5dde | [
"MIT"
] | 1 | 2019-04-03T17:10:59.000Z | 2019-04-03T17:10:59.000Z | src/gvs/vis-client/scene/opengl_scene.cpp | LoganBarnes/geometry-visualization-server | 3ea890d760ada4e5a248e98dded2e27ba6bd5dde | [
"MIT"
] | 1 | 2019-04-03T16:24:18.000Z | 2019-04-03T16:24:18.000Z | // ///////////////////////////////////////////////////////////////////////////////////////
// Geometry Visualization Server
// Copyright (c) 2019 Logan Barnes - All Rights Reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// ///////////////////////////////////////////////////////////////////////////////////////
#include "opengl_scene.hpp"
#include "gvs/util/container_util.hpp"
#include "gvs/vis-client/scene/drawables.hpp"
#include <gvs/gvs_paths.hpp>
#include <Corrade/Containers/ArrayViewStl.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/MeshTools/CompressIndices.h>
#include <Magnum/MeshTools/Interleave.h>
#include <Magnum/Primitives/Cube.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/Trade/MeshData3D.h>
#include <imgui.h>
namespace gvs::vis {
namespace {
Magnum::MeshPrimitive from_proto(gvs::proto::GeometryFormat format) {
switch (format) {
case proto::POINTS:
return Magnum::MeshPrimitive::Points;
case proto::LINES:
return Magnum::MeshPrimitive::Lines;
case proto::LINE_STRIP:
return Magnum::MeshPrimitive::LineStrip;
case proto::TRIANGLES:
return Magnum::MeshPrimitive::Triangles;
case proto::TRIANGLE_STRIP:
return Magnum::MeshPrimitive::TriangleStrip;
case proto::TRIANGLE_FAN:
return Magnum::MeshPrimitive::TriangleFan;
/* Safe to ignore */
case proto::GeometryFormat_INT_MIN_SENTINEL_DO_NOT_USE_:
break;
case proto::GeometryFormat_INT_MAX_SENTINEL_DO_NOT_USE_:
break;
}
throw std::invalid_argument("Invalid GeometryFormat enum provided");
}
} // namespace
using namespace Magnum;
using namespace Math::Literals;
OpenGLScene::ObjectMeshPackage::ObjectMeshPackage(Object3D* obj,
Magnum::SceneGraph::DrawableGroup3D* drawables,
GeneralShader3D& shader)
: object(obj) {
mesh.setCount(0).setPrimitive(Magnum::MeshPrimitive::Points);
drawable = new OpaqueDrawable(*object, drawables, mesh, shader);
}
OpenGLScene::OpenGLScene(const SceneInitializationInfo& /*initialization_info*/) {
camera_object_.setParent(&scene_);
camera_ = new SceneGraph::Camera3D(camera_object_); // Memory control is handled elsewhere
/* Setup renderer and shader defaults */
GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);
shader_.set_uniform_color({1.f, 0.5f, 0.1f});
reset({});
}
void OpenGLScene::update(const Vector2i& /*viewport*/) {}
void OpenGLScene::render(const CameraPackage& camera_package) {
camera_object_.setTransformation(camera_package.transformation);
camera_->setProjectionMatrix(camera_package.camera->projectionMatrix());
camera_->draw(drawables_);
}
void OpenGLScene::configure_gui(const Vector2i& /*viewport*/) {
ImGui::TextColored({1.f, 1.f, 0.f, 1.f}, "TODO: Display Scene Items");
}
void OpenGLScene::reset(const proto::SceneItems& items) {
// Remove all items from the scene
if (root_object_) {
scene_.children().erase(root_object_);
}
objects_.clear();
// Add root
root_object_ = &scene_.addChild<Object3D>();
objects_.emplace("", std::make_unique<ObjectMeshPackage>(root_object_, &drawables_, shader_));
for (const auto& item : items.items()) {
objects_.emplace(item.first,
std::make_unique<ObjectMeshPackage>(&scene_.addChild<Object3D>(), &drawables_, shader_));
}
// Add new items to scene
for (const auto& item : items.items()) {
update_item(item.second);
}
}
void OpenGLScene::add_item(const proto::SceneItemInfo& info) {
assert(info.has_geometry_info());
objects_.emplace(info.id().value(),
std::make_unique<ObjectMeshPackage>(&scene_.addChild<Object3D>(), &drawables_, shader_));
update_item(info);
}
void OpenGLScene::update_item(const proto::SceneItemInfo& info) {
ObjectMeshPackage& mesh_package = *objects_.at(info.id().value());
// TODO: Make it so individual parts of the geometry can be updated
if (info.has_geometry_info()) {
const proto::GeometryInfo3D& geometry = info.geometry_info();
std::vector<float> buffer_data;
GLintptr offset = 0;
mesh_package.mesh.setCount(0);
if (geometry.has_positions()) {
const proto::FloatList& positions = geometry.positions();
buffer_data.insert(buffer_data.end(), positions.value().begin(), positions.value().end());
mesh_package.mesh.setCount(positions.value_size() / 3);
mesh_package.mesh.addVertexBuffer(mesh_package.vertex_buffer, offset, GeneralShader3D::Position{});
offset += positions.value_size() * static_cast<int>(sizeof(float));
}
if (geometry.has_normals()) {
const proto::FloatList& normals = geometry.normals();
buffer_data.insert(buffer_data.end(), normals.value().begin(), normals.value().end());
mesh_package.mesh.addVertexBuffer(mesh_package.vertex_buffer, offset, GeneralShader3D::Normal{});
offset += normals.value_size() * static_cast<int>(sizeof(float));
}
if (geometry.has_tex_coords()) {
const proto::FloatList& tex_coords = geometry.tex_coords();
buffer_data.insert(buffer_data.end(), tex_coords.value().begin(), tex_coords.value().end());
mesh_package.mesh.addVertexBuffer(mesh_package.vertex_buffer, offset, GeneralShader3D::TextureCoordinate{});
offset += tex_coords.value_size() * static_cast<int>(sizeof(float));
}
if (geometry.has_vertex_colors()) {
const proto::FloatList& vertex_colors = geometry.vertex_colors();
buffer_data.insert(buffer_data.end(), vertex_colors.value().begin(), vertex_colors.value().end());
mesh_package.mesh.addVertexBuffer(mesh_package.vertex_buffer, offset, GeneralShader3D::VertexColor{});
}
mesh_package.vertex_buffer.setData(buffer_data, GL::BufferUsage::StaticDraw);
if (info.geometry_info().has_indices() and info.geometry_info().indices().value_size() > 0) {
std::vector<unsigned> indices{info.geometry_info().indices().value().begin(),
info.geometry_info().indices().value().end()};
Containers::Array<char> index_data;
MeshIndexType index_type;
UnsignedInt index_start, index_end;
std::tie(index_data, index_type, index_start, index_end) = MeshTools::compressIndices(indices);
mesh_package.index_buffer.setData(index_data, GL::BufferUsage::StaticDraw);
mesh_package.mesh.setCount(static_cast<int>(indices.size()))
.setIndexBuffer(mesh_package.index_buffer, 0, index_type, index_start, index_end);
}
}
if (info.has_display_info()) {
const proto::DisplayInfo& display = info.display_info();
if (display.has_geometry_format()) {
mesh_package.mesh.setPrimitive(from_proto(display.geometry_format().value()));
}
}
if (not util::has_key(objects_, info.parent().value())) {
objects_.erase(info.id().value());
throw std::invalid_argument("Parent id '" + info.parent().value() + "' not found in scene");
}
mesh_package.object->setParent(objects_.at(info.parent().value())->object);
if (info.has_display_info()) {
mesh_package.drawable->update_display_info(info.display_info());
}
}
void OpenGLScene::resize(const Vector2i& /*viewport*/) {}
} // namespace gvs::vis
| 40.486111 | 120 | 0.668611 | [
"mesh",
"geometry",
"render",
"object",
"vector"
] |
76a984a4e871b502e1a4ad4752bc7dba555cd862 | 5,618 | cpp | C++ | MumbleCommunicator.cpp | robozman/mumsi | adc077d41fc424a1c46279eed8aabe718c77a5d1 | [
"Apache-2.0"
] | 6 | 2020-04-11T07:09:26.000Z | 2020-10-22T16:22:05.000Z | MumbleCommunicator.cpp | robozman/mumsi | adc077d41fc424a1c46279eed8aabe718c77a5d1 | [
"Apache-2.0"
] | null | null | null | MumbleCommunicator.cpp | robozman/mumsi | adc077d41fc424a1c46279eed8aabe718c77a5d1 | [
"Apache-2.0"
] | 1 | 2020-06-11T11:13:56.000Z | 2020-06-11T11:13:56.000Z | #include "MumbleCommunicator.hpp"
#include <cstring>
#include <functional>
namespace mumble {
class MumlibCallback : public mumlib::BasicCallback {
public:
std::shared_ptr<mumlib::Mumlib> mum;
MumbleCommunicator *communicator;
// called by Mumlib when receiving audio from mumble server
virtual void audio(
int target,
int sessionId,
int sequenceNumber,
int16_t *pcm_data,
uint32_t pcm_data_size) override {
communicator->onIncomingPcmSamples(communicator->callId, sessionId, sequenceNumber, pcm_data, pcm_data_size);
}
virtual void channelState(
std::string name,
int32_t channel_id,
int32_t parent,
std::string description,
std::vector<uint32_t> links,
std::vector<uint32_t> inks_add,
std::vector<uint32_t> links_remove,
bool temporary,
int32_t position) override {
communicator->onIncomingChannelState(name, channel_id);
}
virtual void serverSync(
std::string welcome_text,
int32_t session,
int32_t max_bandwidth,
int64_t permissions) override {
communicator->onServerSync();
};
/*
virtual void onUserState(
int32_t session,
int32_t actor,
std::string name,
int32_t user_id,
int32_t channel_id,
int32_t mute,
int32_t deaf,
int32_t suppress,
int32_t self_mute,
int32_t self_deaf,
std::string comment,
int32_t priority_speaker,
int32_t recording
) override {
communicator->onUserState();
};
*/
};
}
mumble::MumbleCommunicator::MumbleCommunicator(boost::asio::io_service &ioService)
: ioService(ioService),
logger(log4cpp::Category::getInstance("MumbleCommunicator")) {
}
void mumble::MumbleCommunicator::connect(MumbleCommunicatorConfig &config) {
callback.reset(new MumlibCallback());
mumbleConf = config;
mumConfig = mumlib::MumlibConfiguration();
mumConfig.opusEncoderBitrate = config.opusEncoderBitrate;
mumConfig.cert_file = config.cert_file;
mumConfig.privkey_file = config.privkey_file;
mum.reset(new mumlib::Mumlib(*callback, ioService, mumConfig));
callback->communicator = this;
callback->mum = mum;
// IMPORTANT: comment these out when experimenting with onConnect
if ( ! MUM_DELAYED_CONNECT ) {
mum->connect(config.host, config.port, config.user, config.password);
if ( mumbleConf.autodeaf ) {
mum->sendUserState(mumlib::UserState::SELF_DEAF, true);
}
}
}
void mumble::MumbleCommunicator::onConnect(const std::string& address) {
if ( MUM_DELAYED_CONNECT ) {
std::string user = mumbleConf.user;
std::size_t p1 = address.find_first_of('"');
std::size_t p2 = address.find_first_of('"', p1 + 1);
if (p2 != std::string::npos) {
user = address.substr(p1+1, p2-(p1+1));
}
else {
p1 = address.find("sip:");
p2 = address.find_first_of('@', p1+4);
if (p2 != std::string::npos) {
user = address.substr(p1+4, p2-(p1+4));
}
}
logger.notice("Logging in as " + user + ".");
mum->connect(mumbleConf.host, mumbleConf.port, user, mumbleConf.password);
}
if ( mumbleConf.comment.size() > 0 ) {
mum->sendUserState(mumlib::UserState::COMMENT, mumbleConf.comment);
}
if ( mumbleConf.autodeaf ) {
mum->sendUserState(mumlib::UserState::SELF_DEAF, true);
}
}
void mumble::MumbleCommunicator::onDisconnect() {
if ( MUM_DELAYED_CONNECT ) {
mum->disconnect();
} else {
}
}
void mumble::MumbleCommunicator::onCallerAuth() {
//onServerSync();
}
void mumble::MumbleCommunicator::sendPcmSamples(int16_t *samples, unsigned int length) {
mum->sendAudioData(samples, length);
}
mumble::MumbleCommunicator::~MumbleCommunicator() {
mum->disconnect();
}
void mumble::MumbleCommunicator::sendTextMessage(std::string message) {
mum->sendTextMessage(message);
}
/*
void mumble::MumbleCommunicator::onUserState(
int32_t session,
int32_t actor,
std::string name,
int32_t user_id,
int32_t channel_id,
int32_t mute,
int32_t deaf,
int32_t suppress,
int32_t self_mute,
int32_t self_deaf,
std::string comment,
int32_t priority_speaker,
int32_t recording) {
logger::notice("Entered onUserState(...)");
userState.mute = mute;
userState.deaf = deaf;
userState.suppress = suppress;
userState.self_mute = self_mute;
userState.self_deaf = self_deaf;
userState.priority_speaker = priority_speaker;
userState.recording = recording;
}
*/
void mumble::MumbleCommunicator::joinChannel(int channel_id) {
mum->joinChannel(channel_id);
if ( mumbleConf.autodeaf ) {
mum->sendUserState(mumlib::UserState::SELF_DEAF, true);
}
}
void mumble::MumbleCommunicator::sendUserState(mumlib::UserState field, bool val) {
mum->sendUserState(field, val);
}
void mumble::MumbleCommunicator::sendUserState(mumlib::UserState field, std::string val) {
mum->sendUserState(field, val);
}
| 29.260417 | 121 | 0.605376 | [
"vector"
] |
76b9f1314bdbb8744d115b248d42b98d8802ea9c | 6,791 | cpp | C++ | dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L1/examples/channelcombine/xf_channel_combine_accel.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 1 | 2021-05-28T06:37:15.000Z | 2021-05-28T06:37:15.000Z | dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L1/examples/channelcombine/xf_channel_combine_accel.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L1/examples/channelcombine/xf_channel_combine_accel.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "xf_channel_combine_config.h"
static constexpr int __XF_DEPTH = (HEIGHT * WIDTH * (XF_PIXELWIDTH(IN_TYPE, NPC1)) / 8) / (INPUT_PTR_WIDTH / 8);
static constexpr int __XF_DEPTH_OUT = (HEIGHT * WIDTH * (XF_PIXELWIDTH(OUT_TYPE, NPC1)) / 8) / (OUTPUT_PTR_WIDTH / 8);
#if FOUR_INPUT
void channel_combine_accel(ap_uint<INPUT_PTR_WIDTH>* img_in1,
ap_uint<INPUT_PTR_WIDTH>* img_in2,
ap_uint<INPUT_PTR_WIDTH>* img_in3,
ap_uint<INPUT_PTR_WIDTH>* img_in4,
ap_uint<OUTPUT_PTR_WIDTH>* img_out,
int height,
int width) {
// clang-format off
#pragma HLS INTERFACE m_axi port=img_in1 offset=slave bundle=gmem0 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_in2 offset=slave bundle=gmem1 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_in3 offset=slave bundle=gmem2 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_in4 offset=slave bundle=gmem3 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_out offset=slave bundle=gmem4 depth=__XF_DEPTH_OUT
#pragma HLS interface s_axilite port=height
#pragma HLS interface s_axilite port=width
#pragma HLS interface s_axilite port=return
// clang-format on
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput1(height, width);
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput2(height, width);
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput3(height, width);
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput4(height, width);
xf::cv::Mat<OUT_TYPE, HEIGHT, WIDTH, NPC1> imgOutput(height, width);
// clang-format off
#pragma HLS DATAFLOW
// clang-format on
// Retrieve xf::cv::Mat objects from img_in data:
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in1, imgInput1);
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in2, imgInput2);
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in3, imgInput3);
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in4, imgInput4);
// Run xfOpenCV kernel:
xf::cv::merge<IN_TYPE, OUT_TYPE, HEIGHT, WIDTH, NPC1>(imgInput1, imgInput2, imgInput3, imgInput4, imgOutput);
// Convert imgOutput xf::cv::Mat object to output array:
xf::cv::xfMat2Array<OUTPUT_PTR_WIDTH, OUT_TYPE, HEIGHT, WIDTH, NPC1>(imgOutput, img_out);
return;
} // End of kernel
#endif
#if THREE_INPUT
void channel_combine_accel(ap_uint<INPUT_PTR_WIDTH>* img_in1,
ap_uint<INPUT_PTR_WIDTH>* img_in2,
ap_uint<INPUT_PTR_WIDTH>* img_in3,
ap_uint<OUTPUT_PTR_WIDTH>* img_out,
int height,
int width) {
// clang-format off
#pragma HLS INTERFACE m_axi port=img_in1 offset=slave bundle=gmem0 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_in2 offset=slave bundle=gmem1 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_in3 offset=slave bundle=gmem2 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_out offset=slave bundle=gmem4 depth=__XF_DEPTH_OUT
#pragma HLS interface s_axilite port=height
#pragma HLS interface s_axilite port=width
#pragma HLS interface s_axilite port=return
// clang-format on
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput1(height, width);
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput2(height, width);
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput3(height, width);
xf::cv::Mat<OUT_TYPE, HEIGHT, WIDTH, NPC1> imgOutput(height, width);
// clang-format off
#pragma HLS DATAFLOW
// clang-format on
// Retrieve xf::cv::Mat objects from img_in data:
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in1, imgInput1);
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in2, imgInput2);
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in3, imgInput3);
// Run xfOpenCV kernel:
xf::cv::merge<IN_TYPE, OUT_TYPE, HEIGHT, WIDTH, NPC1>(imgInput1, imgInput2, imgInput3, imgOutput);
// Convert imgOutput xf::cv::Mat object to output array:
xf::cv::xfMat2Array<OUTPUT_PTR_WIDTH, OUT_TYPE, HEIGHT, WIDTH, NPC1>(imgOutput, img_out);
return;
}
#endif
#if TWO_INPUT
void channel_combine_accel(ap_uint<INPUT_PTR_WIDTH>* img_in1,
ap_uint<INPUT_PTR_WIDTH>* img_in2,
ap_uint<OUTPUT_PTR_WIDTH>* img_out,
int height,
int width) {
// clang-format off
#pragma HLS INTERFACE m_axi port=img_in1 offset=slave bundle=gmem0 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_in2 offset=slave bundle=gmem1 depth=__XF_DEPTH
#pragma HLS INTERFACE m_axi port=img_out offset=slave bundle=gmem4 depth=__XF_DEPTH_OUT
#pragma HLS interface s_axilite port=height
#pragma HLS interface s_axilite port=width
#pragma HLS interface s_axilite port=return
// clang-format on
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput1(height, width);
xf::cv::Mat<IN_TYPE, HEIGHT, WIDTH, NPC1> imgInput2(height, width);
xf::cv::Mat<OUT_TYPE, HEIGHT, WIDTH, NPC1> imgOutput(height, width);
// clang-format off
#pragma HLS DATAFLOW
// clang-format on
// Retrieve xf::cv::Mat objects from img_in data:
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in1, imgInput1);
xf::cv::Array2xfMat<INPUT_PTR_WIDTH, IN_TYPE, HEIGHT, WIDTH, NPC1>(img_in2, imgInput2);
// Run xfOpenCV kernel:
xf::cv::merge<IN_TYPE, OUT_TYPE, HEIGHT, WIDTH, NPC1>(imgInput1, imgInput2, imgOutput);
// Convert imgOutput xf::cv::Mat object to output array:
xf::cv::xfMat2Array<OUTPUT_PTR_WIDTH, OUT_TYPE, HEIGHT, WIDTH, NPC1>(imgOutput, img_out);
return;
}
#endif
| 46.513699 | 118 | 0.666176 | [
"object"
] |
76c423110a482eb15050e8e545738e7beba16213 | 16,170 | cpp | C++ | src/bFst.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 379 | 2016-01-29T00:01:51.000Z | 2022-03-21T21:07:03.000Z | src/bFst.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 245 | 2016-01-31T19:05:29.000Z | 2022-03-31T13:17:17.000Z | src/bFst.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 168 | 2016-02-11T19:30:52.000Z | 2022-02-10T09:20:34.000Z | /*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2020 Erik Garrison
Copyright © 2020 Pjotr Prins
This software is published under the MIT License. See the LICENSE file.
*/
#include "Variant.h"
#include "split.h"
#include "pdflib.hpp"
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <getopt.h>
#include "gpatInfo.hpp"
using namespace std;
using namespace vcflib;
struct pop{
double nalt ;
double nref ;
double af ;
double nhomr;
double nhoma;
double nhet ;
double ngeno;
double fis ;
vector<int> questionable;
vector<int> geno_index ;
vector< vector< double > > unphred_p;
};
double unphred(string phred){
double unphred = atof(phred.c_str());
unphred = unphred / -10;
return unphred;
}
void initPop(pop & population){
population.nalt = 0;
population.nref = 0;
population.af = 0;
population.nhomr = 0;
population.nhoma = 0;
population.nhet = 0;
population.ngeno = 0;
population.fis = 0;
}
void loadPop( vector< map< string, vector<string> > >& group, pop & population){
vector< map< string, vector<string> > >::iterator targ_it = group.begin();
int index = 0;
for(; targ_it != group.end(); targ_it++){
string genotype = (*targ_it)["GT"].front();
vector<double> phreds;
phreds.push_back( unphred((*targ_it)["PL"][0]));
phreds.push_back( unphred((*targ_it)["PL"][1]));
phreds.push_back( unphred((*targ_it)["PL"][2]));
double scaled ;
double norm = log(exp(phreds[0]) + exp(phreds[1]) + exp(phreds[2]));
population.unphred_p.push_back(phreds);
while(1){
if(genotype == "0/0"){
population.ngeno += 1;
population.nhomr += 1;
population.nref += 2;
population.geno_index.push_back(0);
scaled = exp(phreds[0] - norm);
break;
}
if(genotype == "0/1"){
population.ngeno += 1;
population.nhet += 1;
population.nref += 1;
population.nalt += 1;
population.geno_index.push_back(1);
scaled = exp(phreds[1] - norm);
break;
}
if(genotype == "1/1"){
population.ngeno += 1;
population.nhoma += 1;
population.nalt += 2;
population.geno_index.push_back(2);
scaled = exp(phreds[2] - norm);
break;
}
if(genotype == "0|0"){
population.ngeno += 1;
population.nhomr += 1;
population.nref += 2;
population.geno_index.push_back(0);
scaled = exp(phreds[0] - norm);
break;
}
if(genotype == "0|1"){
population.ngeno += 1;
population.nhet += 1;
population.nref += 1;
population.nalt += 1;
population.geno_index.push_back(1);
scaled = exp(phreds[1] - norm);
break;
}
if(genotype == "1|1"){
population.ngeno += 1;
population.nhoma += 1;
population.nalt += 2;
population.geno_index.push_back(2);
scaled = exp(phreds[2] - norm);
break;
}
cerr << "FATAL: unknown genotype" << endl;
exit(1);
}
if(scaled < 0.75){
population.questionable.push_back(index);
}
index += 1;
}
if(population.nalt == 0 && population.nref == 0){
population.af = -1;
}
else{
population.af = (population.nalt / (population.nref + population.nalt));
if(population.nhet > 0){
population.fis = ( 1 - ((population.nhet/population.ngeno) / (2*population.af*(1 - population.af))));
}
else{
population.fis = 1;
}
if(population.fis < 0){
population.fis = 0.00001;
}
}
}
double bound(double v){
if(v <= 0.00001){
return 0.00001;
}
if(v >= 0.99999){
return 0.99999;
}
return v;
}
void phardy(vector<double>& results, double af, double fis){
double p0 = pow((1 - af),2) + ((1 - af)*af*fis);
double p1 = 2*(1 - af)*af*(1 - fis);
double p2 = pow(af,2) + ((1 - af)*af*fis);
results.push_back(p0);
results.push_back(p1);
results.push_back(p2);
}
double likelihood(pop & population, double af, double fis){
af = bound(af);
fis = bound(fis);
double het;
double all;
double ref;
double alt;
double loglikelihood = 0;
vector<double> genotypeProbs;
phardy(genotypeProbs, af, fis);
vector<int>::iterator it = population.geno_index.begin();
int geno_indx = 0;
for(; it != population.geno_index.end(); it++){
double aa = population.unphred_p[geno_indx][0] + log(genotypeProbs[0]);
double ab = population.unphred_p[geno_indx][1] + log(genotypeProbs[1]);
double bb = population.unphred_p[geno_indx][2] + log(genotypeProbs[2]);
double norm = exp(aa) + exp(ab) + exp(bb);
double prop = population.unphred_p[geno_indx][*it] + log(genotypeProbs[*it]);
loglikelihood += (prop - norm);
geno_indx++;
}
return loglikelihood;
}
double FullProb(pop & target, pop & back, vector<double>& p)
{
// parameters targetAf backgroundAf targetFis backgroundFis totalAf fst
double alpha = ( (1-p[5])/p[5] ) * p[4];
double beta = ( (1-p[5])/p[5] ) * (1 - p[4]);
double afprior = log( r8_normal_pdf (p[6], 0.1, p[4]));
double afpriorT = log( r8_normal_pdf (target.af, 0.05, p[0]));
double afpriorB = log( r8_normal_pdf (back.af, 0.05, p[1]));
if(std::isinf(afprior) || std::isnan(afprior)){
return -100000;
}
double ptaf = log( r8_beta_pdf(alpha, beta, p[0]) );
double pbaf = log( r8_beta_pdf(alpha, beta, p[1]) );
if( std::isinf(ptaf) || std::isnan(ptaf) || std::isinf(pbaf) || std::isnan(pbaf) ){
return -100000;
}
double llt = likelihood(target, p[0], p[2]);
double llb = likelihood(back, p[1], p[3]);
double full = llt + llb + ptaf + pbaf + afprior + afpriorT + afpriorB;
return full;
}
void updateParameters(pop & target, pop & background, vector<double>& parameters, int pindx){
// parameters targetAf backgroundAf targetFis backgroundFis totalAf fst
double origpar = parameters[pindx];
double accept = ((double)rand() / (double)(RAND_MAX));
double up = ((double)rand() / (double)(RAND_MAX))/10 - 0.05;
double updatep = parameters[pindx] + up;
// cerr << accept << "\t" << up << endl;
if(updatep >= 1 || updatep <= 0){
return;
}
double llB = FullProb(target, background, parameters);
parameters[pindx] = updatep;
double llT = FullProb(target, background, parameters);
if((llT - llB) > accept){
return;
}
else{
parameters[pindx] = origpar;
}
}
void updateGenotypes(pop & target, pop & background, vector<double>& parameters, int gindex, int tbindex){
// tbindex indicates if the subroutine will update the target or background genotype;
double accept = ((double)rand() / (double)(RAND_MAX));
int newGindex = rand() % 3;
//cerr << newGindex << endl;
//cerr << "gindex " << gindex << endl;
//cerr << "gsize t:" << target.geno_index.size() << endl;
//cerr << "gsize b:" << background.geno_index.size() << endl;
int oldtindex = target.geno_index[gindex] ;
int oldbindex = background.geno_index[gindex] ;
double llB = FullProb(target, background, parameters);
if(tbindex == 0){
//udate target
target.geno_index[gindex] = newGindex;
}
else{
// update background
background.geno_index[gindex] = newGindex;
}
double llT = FullProb(target, background, parameters);
if((llT - llB) > accept){
return;
}
else{
if(tbindex == 0){
target.geno_index[gindex] = oldtindex;
}
else{
target.geno_index[gindex] = oldbindex;
}
}
}
int cmp(const void *x, const void *y)
{
double xx = *(double*)x, yy = *(double*)y;
if (xx < yy) return -1;
if (xx > yy) return 1;
return 0;
}
void loadIndices(map<int, int> & index, string set){
vector<string> indviduals = split(set, ",");
vector<string>::iterator it = indviduals.begin();
for(; it != indviduals.end(); it++){
index[ atoi( (*it).c_str() ) ] = 1;
}
}
int main(int argc, char** argv) {
// set the random seed for MCMC
srand((unsigned)time(NULL));
// the filename
string filename = "NA";
// using vcflib; thanks to Erik Garrison
VariantCallFile variantFile ;
// zero based index for the target and background indivudals
map<int, int> it, ib;
// deltaaf is the difference of allele frequency we bother to look at
string deltaaf ;
double daf = -1;
const struct option longopts[] =
{
{"version" , 0, 0, 'v'},
{"help" , 0, 0, 'h'},
{"file" , 1, 0, 'f'},
{"target" , 1, 0, 't'},
{"background", 1, 0, 'b'},
{"deltaaf" , 1, 0, 'd'},
{0,0,0,0}
};
int index;
int iarg = 0;
while(iarg != -1)
{
iarg = getopt_long(argc, argv, "d:t:b:f:hv", longopts, &index);
switch (iarg)
{
case 0:
break;
case 'h':
cerr << endl;
cerr << "INFO: help" << endl << endl;
cerr << " bFst is a Bayesian approach to Fst. Importantly bFst accounts for genotype uncertainty in the model using genotype likelihoods." << endl;
cerr << " For a more detailed description see: `A Bayesian approach to inferring population structure from dominant markers' by Holsinger et al. Molecular Ecology Vol 11, issue 7 2002. The likelihood function has been " << endl;
cerr << " modified to use genotype likelihoods provided by variant callers. There are five free parameters estimated in the model: each " << endl;
cerr << " subpopulation's allele frequency and Fis (fixation index, within each subpopulation), a free parameter for the total population\'s " << endl;
cerr << " allele frequency, and Fst. " << endl << endl;
cerr << "Output : 11 columns : " << endl;
cerr << " 1. Seqid " << endl;
cerr << " 2. Position " << endl;
cerr << " 3. Observed allele frequency in target. " << endl;
cerr << " 4. Estimated allele frequency in target. " << endl;
cerr << " 5. Observed allele frequency in background. " << endl;
cerr << " 6. Estimated allele frequency in background. " << endl;
cerr << " 7. Observed allele frequency combined. " << endl;
cerr << " 8. Estimated allele frequency in combined. " << endl;
cerr << " 9. ML estimate of Fst (mean) " << endl;
cerr << " 10. Lower bound of the 95% credible interval " << endl;
cerr << " 11. Upper bound of the 95% credible interval " << endl << endl;
cerr << "INFO: usage: bFst --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf --deltaaf 0.1" << endl;
cerr << endl;
cerr << "INFO: required: t,target -- a zero bases comma separated list of target individuals corrisponding to VCF columns" << endl;
cerr << "INFO: required: b,background -- a zero bases comma separated list of background individuals corrisponding to VCF columns" << endl;
cerr << "INFO: required: f,file a -- a proper formatted VCF file. the FORMAT field MUST contain \"PL\"" << endl;
cerr << "INFO: required: d,deltaaf -- skip sites were the difference in allele frequency is less than deltaaf" << endl;
cerr << endl << endl << "Type: statistics" << endl;
printVersion();
cerr << endl << endl;
return 0;
case 'v':
printVersion();
return 0;
case 't':
loadIndices(ib, optarg);
cerr << "INFO: There are " << ib.size() << " individuals in the target" << endl;
break;
case 'b':
loadIndices(it, optarg);
cerr << "INFO: There are " << it.size() << " individuals in the background" << endl;
break;
case 'f':
cerr << "INFO: File: " << optarg << endl;
filename = optarg;
break;
case 'd':
cerr << "INFO: difference in allele frequency : " << optarg << endl;
deltaaf = optarg;
daf = atof(deltaaf.c_str());
break;
default:
break;
cerr << endl;
cerr << "FATAL: unknown command line option " << optarg << endl << endl ;
cerr << "INFO: please use bFst --help " << endl;
cerr << endl;
return(1);
}
}
if(daf == -1){
cerr << endl;
cerr << "FATAL: did not specify deltaaf" << endl;
cerr << "INFO: please use bFst --help " << endl;
cerr << endl;
return(1);
}
if(filename == "NA"){
cerr << endl;
cerr << "FATAL: did not specify VCF file" << endl;
cerr << "INFO: please use bFst --help " << endl;
cerr << endl;
return(1);
}
variantFile.open(filename);
if (!variantFile.is_open()) {
cerr << endl;
cerr << "FATAL: could not open VCF file" << endl;
cerr << "INFO: please use bFst --help" << endl;
cerr << endl;
return(1);
}
if(it.size() < 2){
cerr << endl;
cerr << "FATAL: target not specified or less than two indviduals" << endl;
cerr << "INFO: please use bFst --help " << endl;
cerr << endl;
}
if(ib.size() < 2){
cerr << endl;
cerr << "FATAL: target not specified or less than two indviduals"<< endl;
cerr << "INFO: please use bFst --help " << endl;
cerr << endl;
}
Variant var(variantFile);
vector<string> samples = variantFile.sampleNames;
int nsamples = samples.size();
while (variantFile.getNextVariant(var)) {
// biallelic sites naturally
if(var.alt.size() > 1){
continue;
}
vector < map< string, vector<string> > > target, background, total;
int index = 0;
for(int nsamp = 0; nsamp < nsamples; nsamp++){
map<string, vector<string> > sample = var.samples[ samples[nsamp]];
if(sample["GT"].front() != "./."){
if(it.find(index) != it.end() ){
target.push_back(sample);
total.push_back(sample);
}
if(ib.find(index) != ib.end()){
background.push_back(sample);
total.push_back(sample);
}
}
index += 1;
}
if(target.size() < 2 || background.size() < 2 ){
continue;
}
pop popt, popb, popTotal;
initPop(popt);
initPop(popb);
initPop(popTotal);
loadPop(target, popt);
loadPop(background, popb);
loadPop(total, popTotal);
if(popt.af == -1 || popb.af == -1){
continue;
}
if(popt.af == 1 && popb.af == 1){
continue;
}
if(popt.af == 0 && popb.af == 0){
continue;
}
double afdiff = abs(popt.af - popb.af);
if(afdiff < daf){
continue;
}
cerr << "INFO: target has " << popt.questionable.size() << " questionable genotypes " << endl;
cerr << "INFO: background has " << popb.questionable.size() << " questionable genotypes " << endl;
// Parameters- targetAf backgroundAf targetFis backgroundFis totalAf fst
vector<double> parameters;
parameters.push_back(popt.af);
parameters.push_back(popb.af);
parameters.push_back(popt.fis);
parameters.push_back(popb.fis);
parameters.push_back(popTotal.af);
parameters.push_back(0.1);
parameters.push_back(popTotal.af);
double sums [6] = {0};
double fsts [10000] ;
for(int i = 0; i < 15000; i++){
// update each of j parameters
for(int j = 0; j < 6; j++ ){
updateParameters(popt, popb, parameters, j);
if(i > 4999){
sums[j] += parameters[j];
}
}
if(i > 4999){
fsts[i - 5000] = parameters[5];
}
for(vector<int>::iterator itt = popt.questionable.begin(); itt != popt.questionable.end(); itt++){
updateGenotypes(popt, popb, parameters, (*itt), 0);
}
for(vector<int>::iterator itb = popb.questionable.begin(); itb != popb.questionable.end(); itb++){
updateGenotypes(popt, popb, parameters, (*itb) , 1);
}
}
qsort (fsts, sizeof(fsts)/sizeof(fsts[0]), sizeof(fsts[0]), cmp );
double lcredint = fsts[500];
double hcredint = fsts[9500];
cout << var.sequenceName << "\t" << var.position
<< "\t" << popt.af
<< "\t" << sums[0]/10000
<< "\t" << popb.af
<< "\t" << sums[1]/10000
<< "\t" << popTotal.af
<< "\t" << sums[4]/10000
<< "\t" << sums[5]/10000
<< "\t" << lcredint
<< "\t" << hcredint
<< endl;
}
return 0;
}
| 25.62599 | 243 | 0.587075 | [
"vector",
"model"
] |
76c7c8f4deed137162609ac998dacdd55af8647a | 57,777 | cc | C++ | thirdparty/google/api/servicecontrol/v1/metric_value.pb.cc | kobeya/GVA-demo | 41a57bfff01ab0de2f56ddcd7611514e550472ff | [
"Apache-2.0"
] | 2 | 2019-03-29T07:20:43.000Z | 2019-08-13T04:47:27.000Z | thirdparty/google/api/servicecontrol/v1/metric_value.pb.cc | kobeya/GVA-demo | 41a57bfff01ab0de2f56ddcd7611514e550472ff | [
"Apache-2.0"
] | null | null | null | thirdparty/google/api/servicecontrol/v1/metric_value.pb.cc | kobeya/GVA-demo | 41a57bfff01ab0de2f56ddcd7611514e550472ff | [
"Apache-2.0"
] | 1 | 2019-08-09T05:26:50.000Z | 2019-08-09T05:26:50.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/servicecontrol/v1/metric_value.proto
#include "google/api/servicecontrol/v1/metric_value.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace protobuf_google_2fapi_2fservicecontrol_2fv1_2fdistribution_2eproto {
extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fapi_2fservicecontrol_2fv1_2fdistribution_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_Distribution;
} // namespace protobuf_google_2fapi_2fservicecontrol_2fv1_2fdistribution_2eproto
namespace protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto {
extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_MetricValue_LabelsEntry_DoNotUse;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_MetricValue;
} // namespace protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto
namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto {
extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftimestamp_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp;
} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto
namespace google {
namespace api {
namespace servicecontrol {
namespace v1 {
class MetricValue_LabelsEntry_DoNotUseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<MetricValue_LabelsEntry_DoNotUse>
_instance;
} _MetricValue_LabelsEntry_DoNotUse_default_instance_;
class MetricValueDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<MetricValue>
_instance;
bool bool_value_;
::google::protobuf::int64 int64_value_;
double double_value_;
::google::protobuf::internal::ArenaStringPtr string_value_;
const ::google::api::servicecontrol::v1::Distribution* distribution_value_;
} _MetricValue_default_instance_;
class MetricValueSetDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<MetricValueSet>
_instance;
} _MetricValueSet_default_instance_;
} // namespace v1
} // namespace servicecontrol
} // namespace api
} // namespace google
namespace protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto {
static void InitDefaultsMetricValue_LabelsEntry_DoNotUse() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::api::servicecontrol::v1::_MetricValue_LabelsEntry_DoNotUse_default_instance_;
new (ptr) ::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse();
}
::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_MetricValue_LabelsEntry_DoNotUse =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMetricValue_LabelsEntry_DoNotUse}, {}};
static void InitDefaultsMetricValue() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::api::servicecontrol::v1::_MetricValue_default_instance_;
new (ptr) ::google::api::servicecontrol::v1::MetricValue();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::api::servicecontrol::v1::MetricValue::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<3> scc_info_MetricValue =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsMetricValue}, {
&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValue_LabelsEntry_DoNotUse.base,
&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base,
&protobuf_google_2fapi_2fservicecontrol_2fv1_2fdistribution_2eproto::scc_info_Distribution.base,}};
static void InitDefaultsMetricValueSet() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::api::servicecontrol::v1::_MetricValueSet_default_instance_;
new (ptr) ::google::api::servicecontrol::v1::MetricValueSet();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::api::servicecontrol::v1::MetricValueSet::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_MetricValueSet =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMetricValueSet}, {
&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValue.base,}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_MetricValue_LabelsEntry_DoNotUse.base);
::google::protobuf::internal::InitSCC(&scc_info_MetricValue.base);
::google::protobuf::internal::InitSCC(&scc_info_MetricValueSet.base);
}
::google::protobuf::Metadata file_level_metadata[3];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse, key_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse, value_),
0,
1,
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue, _internal_metadata_),
~0u, // no _extensions_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue, _oneof_case_[0]),
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue, labels_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue, start_time_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue, end_time_),
offsetof(::google::api::servicecontrol::v1::MetricValueDefaultTypeInternal, bool_value_),
offsetof(::google::api::servicecontrol::v1::MetricValueDefaultTypeInternal, int64_value_),
offsetof(::google::api::servicecontrol::v1::MetricValueDefaultTypeInternal, double_value_),
offsetof(::google::api::servicecontrol::v1::MetricValueDefaultTypeInternal, string_value_),
offsetof(::google::api::servicecontrol::v1::MetricValueDefaultTypeInternal, distribution_value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValue, value_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValueSet, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValueSet, metric_name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::api::servicecontrol::v1::MetricValueSet, metric_values_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 7, sizeof(::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse)},
{ 9, -1, sizeof(::google::api::servicecontrol::v1::MetricValue)},
{ 23, -1, sizeof(::google::api::servicecontrol::v1::MetricValueSet)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::api::servicecontrol::v1::_MetricValue_LabelsEntry_DoNotUse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::api::servicecontrol::v1::_MetricValue_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::api::servicecontrol::v1::_MetricValueSet_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"google/api/servicecontrol/v1/metric_value.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n/google/api/servicecontrol/v1/metric_va"
"lue.proto\022\034google.api.servicecontrol.v1\032"
"\034google/api/annotations.proto\032/google/ap"
"i/servicecontrol/v1/distribution.proto\032\037"
"google/protobuf/timestamp.proto\032\027google/"
"type/money.proto\"\221\003\n\013MetricValue\022E\n\006labe"
"ls\030\001 \003(\01325.google.api.servicecontrol.v1."
"MetricValue.LabelsEntry\022.\n\nstart_time\030\002 "
"\001(\0132\032.google.protobuf.Timestamp\022,\n\010end_t"
"ime\030\003 \001(\0132\032.google.protobuf.Timestamp\022\024\n"
"\nbool_value\030\004 \001(\010H\000\022\025\n\013int64_value\030\005 \001(\003"
"H\000\022\026\n\014double_value\030\006 \001(\001H\000\022\026\n\014string_val"
"ue\030\007 \001(\tH\000\022H\n\022distribution_value\030\010 \001(\0132*"
".google.api.servicecontrol.v1.Distributi"
"onH\000\032-\n\013LabelsEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005valu"
"e\030\002 \001(\t:\0028\001B\007\n\005value\"g\n\016MetricValueSet\022\023"
"\n\013metric_name\030\001 \001(\t\022@\n\rmetric_values\030\002 \003"
"(\0132).google.api.servicecontrol.v1.Metric"
"ValueB\210\001\n com.google.api.servicecontrol."
"v1B\023MetricValueSetProtoP\001ZJgoogle.golang"
".org/genproto/googleapis/api/servicecont"
"rol/v1;servicecontrol\370\001\001b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 872);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/api/servicecontrol/v1/metric_value.proto", &protobuf_RegisterTypes);
::protobuf_google_2fapi_2fannotations_2eproto::AddDescriptors();
::protobuf_google_2fapi_2fservicecontrol_2fv1_2fdistribution_2eproto::AddDescriptors();
::protobuf_google_2fprotobuf_2ftimestamp_2eproto::AddDescriptors();
::protobuf_google_2ftype_2fmoney_2eproto::AddDescriptors();
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto
namespace google {
namespace api {
namespace servicecontrol {
namespace v1 {
// ===================================================================
MetricValue_LabelsEntry_DoNotUse::MetricValue_LabelsEntry_DoNotUse() {}
MetricValue_LabelsEntry_DoNotUse::MetricValue_LabelsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {}
void MetricValue_LabelsEntry_DoNotUse::MergeFrom(const MetricValue_LabelsEntry_DoNotUse& other) {
MergeFromInternal(other);
}
::google::protobuf::Metadata MetricValue_LabelsEntry_DoNotUse::GetMetadata() const {
::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::file_level_metadata[0];
}
void MetricValue_LabelsEntry_DoNotUse::MergeFrom(
const ::google::protobuf::Message& other) {
::google::protobuf::Message::MergeFrom(other);
}
// ===================================================================
void MetricValue::InitAsDefaultInstance() {
::google::api::servicecontrol::v1::_MetricValue_default_instance_._instance.get_mutable()->start_time_ = const_cast< ::google::protobuf::Timestamp*>(
::google::protobuf::Timestamp::internal_default_instance());
::google::api::servicecontrol::v1::_MetricValue_default_instance_._instance.get_mutable()->end_time_ = const_cast< ::google::protobuf::Timestamp*>(
::google::protobuf::Timestamp::internal_default_instance());
::google::api::servicecontrol::v1::_MetricValue_default_instance_.bool_value_ = false;
::google::api::servicecontrol::v1::_MetricValue_default_instance_.int64_value_ = GOOGLE_LONGLONG(0);
::google::api::servicecontrol::v1::_MetricValue_default_instance_.double_value_ = 0;
::google::api::servicecontrol::v1::_MetricValue_default_instance_.string_value_.UnsafeSetDefault(
&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::google::api::servicecontrol::v1::_MetricValue_default_instance_.distribution_value_ = const_cast< ::google::api::servicecontrol::v1::Distribution*>(
::google::api::servicecontrol::v1::Distribution::internal_default_instance());
}
void MetricValue::unsafe_arena_set_allocated_start_time(
::google::protobuf::Timestamp* start_time) {
if (GetArenaNoVirtual() == NULL) {
delete start_time_;
}
start_time_ = start_time;
if (start_time) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.api.servicecontrol.v1.MetricValue.start_time)
}
void MetricValue::clear_start_time() {
if (GetArenaNoVirtual() == NULL && start_time_ != NULL) {
delete start_time_;
}
start_time_ = NULL;
}
void MetricValue::unsafe_arena_set_allocated_end_time(
::google::protobuf::Timestamp* end_time) {
if (GetArenaNoVirtual() == NULL) {
delete end_time_;
}
end_time_ = end_time;
if (end_time) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.api.servicecontrol.v1.MetricValue.end_time)
}
void MetricValue::clear_end_time() {
if (GetArenaNoVirtual() == NULL && end_time_ != NULL) {
delete end_time_;
}
end_time_ = NULL;
}
void MetricValue::set_allocated_distribution_value(::google::api::servicecontrol::v1::Distribution* distribution_value) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_value();
if (distribution_value) {
::google::protobuf::Arena* submessage_arena =
reinterpret_cast<::google::protobuf::MessageLite*>(distribution_value)->GetArena();
if (message_arena != submessage_arena) {
distribution_value = ::google::protobuf::internal::GetOwnedMessage(
message_arena, distribution_value, submessage_arena);
}
set_has_distribution_value();
value_.distribution_value_ = distribution_value;
}
// @@protoc_insertion_point(field_set_allocated:google.api.servicecontrol.v1.MetricValue.distribution_value)
}
void MetricValue::clear_distribution_value() {
if (has_distribution_value()) {
if (GetArenaNoVirtual() == NULL) {
delete value_.distribution_value_;
}
clear_has_value();
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MetricValue::kLabelsFieldNumber;
const int MetricValue::kStartTimeFieldNumber;
const int MetricValue::kEndTimeFieldNumber;
const int MetricValue::kBoolValueFieldNumber;
const int MetricValue::kInt64ValueFieldNumber;
const int MetricValue::kDoubleValueFieldNumber;
const int MetricValue::kStringValueFieldNumber;
const int MetricValue::kDistributionValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MetricValue::MetricValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.api.servicecontrol.v1.MetricValue)
}
MetricValue::MetricValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
labels_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.api.servicecontrol.v1.MetricValue)
}
MetricValue::MetricValue(const MetricValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
labels_.MergeFrom(from.labels_);
if (from.has_start_time()) {
start_time_ = new ::google::protobuf::Timestamp(*from.start_time_);
} else {
start_time_ = NULL;
}
if (from.has_end_time()) {
end_time_ = new ::google::protobuf::Timestamp(*from.end_time_);
} else {
end_time_ = NULL;
}
clear_has_value();
switch (from.value_case()) {
case kBoolValue: {
set_bool_value(from.bool_value());
break;
}
case kInt64Value: {
set_int64_value(from.int64_value());
break;
}
case kDoubleValue: {
set_double_value(from.double_value());
break;
}
case kStringValue: {
set_string_value(from.string_value());
break;
}
case kDistributionValue: {
mutable_distribution_value()->::google::api::servicecontrol::v1::Distribution::MergeFrom(from.distribution_value());
break;
}
case VALUE_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:google.api.servicecontrol.v1.MetricValue)
}
void MetricValue::SharedCtor() {
::memset(&start_time_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_time_) -
reinterpret_cast<char*>(&start_time_)) + sizeof(end_time_));
clear_has_value();
}
MetricValue::~MetricValue() {
// @@protoc_insertion_point(destructor:google.api.servicecontrol.v1.MetricValue)
SharedDtor();
}
void MetricValue::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
if (this != internal_default_instance()) delete start_time_;
if (this != internal_default_instance()) delete end_time_;
if (has_value()) {
clear_value();
}
}
void MetricValue::ArenaDtor(void* object) {
MetricValue* _this = reinterpret_cast< MetricValue* >(object);
(void)_this;
}
void MetricValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MetricValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MetricValue::descriptor() {
::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const MetricValue& MetricValue::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValue.base);
return *internal_default_instance();
}
void MetricValue::clear_value() {
// @@protoc_insertion_point(one_of_clear_start:google.api.servicecontrol.v1.MetricValue)
switch (value_case()) {
case kBoolValue: {
// No need to clear
break;
}
case kInt64Value: {
// No need to clear
break;
}
case kDoubleValue: {
// No need to clear
break;
}
case kStringValue: {
value_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
break;
}
case kDistributionValue: {
if (GetArenaNoVirtual() == NULL) {
delete value_.distribution_value_;
}
break;
}
case VALUE_NOT_SET: {
break;
}
}
_oneof_case_[0] = VALUE_NOT_SET;
}
void MetricValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.api.servicecontrol.v1.MetricValue)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
labels_.Clear();
if (GetArenaNoVirtual() == NULL && start_time_ != NULL) {
delete start_time_;
}
start_time_ = NULL;
if (GetArenaNoVirtual() == NULL && end_time_ != NULL) {
delete end_time_;
}
end_time_ = NULL;
clear_value();
_internal_metadata_.Clear();
}
bool MetricValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.api.servicecontrol.v1.MetricValue)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, string> labels = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
MetricValue_LabelsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField<
MetricValue_LabelsEntry_DoNotUse,
::std::string, ::std::string,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
0 >,
::google::protobuf::Map< ::std::string, ::std::string > > parser(&labels_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), static_cast<int>(parser.key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.api.servicecontrol.v1.MetricValue.LabelsEntry.key"));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.value().data(), static_cast<int>(parser.value().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.api.servicecontrol.v1.MetricValue.LabelsEntry.value"));
} else {
goto handle_unusual;
}
break;
}
// .google.protobuf.Timestamp start_time = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_start_time()));
} else {
goto handle_unusual;
}
break;
}
// .google.protobuf.Timestamp end_time = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_end_time()));
} else {
goto handle_unusual;
}
break;
}
// bool bool_value = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
clear_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &value_.bool_value_)));
set_has_bool_value();
} else {
goto handle_unusual;
}
break;
}
// int64 int64_value = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
clear_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &value_.int64_value_)));
set_has_int64_value();
} else {
goto handle_unusual;
}
break;
}
// double double_value = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) {
clear_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &value_.double_value_)));
set_has_double_value();
} else {
goto handle_unusual;
}
break;
}
// string string_value = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_string_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->string_value().data(), static_cast<int>(this->string_value().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.api.servicecontrol.v1.MetricValue.string_value"));
} else {
goto handle_unusual;
}
break;
}
// .google.api.servicecontrol.v1.Distribution distribution_value = 8;
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_distribution_value()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.api.servicecontrol.v1.MetricValue)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.api.servicecontrol.v1.MetricValue)
return false;
#undef DO_
}
void MetricValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.api.servicecontrol.v1.MetricValue)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, string> labels = 1;
if (!this->labels().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValue.LabelsEntry.key");
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->second.data(), static_cast<int>(p->second.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValue.LabelsEntry.value");
}
};
if (output->IsSerializationDeterministic() &&
this->labels().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->labels().size()]);
typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->labels().begin();
it != this->labels().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<MetricValue_LabelsEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(labels_.NewEntryWrapper(
items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
::std::unique_ptr<MetricValue_LabelsEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->labels().begin();
it != this->labels().end(); ++it) {
entry.reset(labels_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// .google.protobuf.Timestamp start_time = 2;
if (this->has_start_time()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->_internal_start_time(), output);
}
// .google.protobuf.Timestamp end_time = 3;
if (this->has_end_time()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->_internal_end_time(), output);
}
// bool bool_value = 4;
if (has_bool_value()) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->bool_value(), output);
}
// int64 int64_value = 5;
if (has_int64_value()) {
::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->int64_value(), output);
}
// double double_value = 6;
if (has_double_value()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->double_value(), output);
}
// string string_value = 7;
if (has_string_value()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->string_value().data(), static_cast<int>(this->string_value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValue.string_value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
7, this->string_value(), output);
}
// .google.api.servicecontrol.v1.Distribution distribution_value = 8;
if (has_distribution_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
8, this->_internal_distribution_value(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:google.api.servicecontrol.v1.MetricValue)
}
::google::protobuf::uint8* MetricValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.api.servicecontrol.v1.MetricValue)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, string> labels = 1;
if (!this->labels().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValue.LabelsEntry.key");
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->second.data(), static_cast<int>(p->second.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValue.LabelsEntry.value");
}
};
if (deterministic &&
this->labels().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->labels().size()]);
typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->labels().begin();
it != this->labels().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<MetricValue_LabelsEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(labels_.NewEntryWrapper(
items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
::std::unique_ptr<MetricValue_LabelsEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->labels().begin();
it != this->labels().end(); ++it) {
entry.reset(labels_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// .google.protobuf.Timestamp start_time = 2;
if (this->has_start_time()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->_internal_start_time(), deterministic, target);
}
// .google.protobuf.Timestamp end_time = 3;
if (this->has_end_time()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->_internal_end_time(), deterministic, target);
}
// bool bool_value = 4;
if (has_bool_value()) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->bool_value(), target);
}
// int64 int64_value = 5;
if (has_int64_value()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->int64_value(), target);
}
// double double_value = 6;
if (has_double_value()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->double_value(), target);
}
// string string_value = 7;
if (has_string_value()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->string_value().data(), static_cast<int>(this->string_value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValue.string_value");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
7, this->string_value(), target);
}
// .google.api.servicecontrol.v1.Distribution distribution_value = 8;
if (has_distribution_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
8, this->_internal_distribution_value(), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.api.servicecontrol.v1.MetricValue)
return target;
}
size_t MetricValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.api.servicecontrol.v1.MetricValue)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// map<string, string> labels = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->labels_size());
{
::std::unique_ptr<MetricValue_LabelsEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->labels().begin();
it != this->labels().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(labels_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// .google.protobuf.Timestamp start_time = 2;
if (this->has_start_time()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*start_time_);
}
// .google.protobuf.Timestamp end_time = 3;
if (this->has_end_time()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*end_time_);
}
switch (value_case()) {
// bool bool_value = 4;
case kBoolValue: {
total_size += 1 + 1;
break;
}
// int64 int64_value = 5;
case kInt64Value: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->int64_value());
break;
}
// double double_value = 6;
case kDoubleValue: {
total_size += 1 + 8;
break;
}
// string string_value = 7;
case kStringValue: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->string_value());
break;
}
// .google.api.servicecontrol.v1.Distribution distribution_value = 8;
case kDistributionValue: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*value_.distribution_value_);
break;
}
case VALUE_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void MetricValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.api.servicecontrol.v1.MetricValue)
GOOGLE_DCHECK_NE(&from, this);
const MetricValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const MetricValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.api.servicecontrol.v1.MetricValue)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.api.servicecontrol.v1.MetricValue)
MergeFrom(*source);
}
}
void MetricValue::MergeFrom(const MetricValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.api.servicecontrol.v1.MetricValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
labels_.MergeFrom(from.labels_);
if (from.has_start_time()) {
mutable_start_time()->::google::protobuf::Timestamp::MergeFrom(from.start_time());
}
if (from.has_end_time()) {
mutable_end_time()->::google::protobuf::Timestamp::MergeFrom(from.end_time());
}
switch (from.value_case()) {
case kBoolValue: {
set_bool_value(from.bool_value());
break;
}
case kInt64Value: {
set_int64_value(from.int64_value());
break;
}
case kDoubleValue: {
set_double_value(from.double_value());
break;
}
case kStringValue: {
set_string_value(from.string_value());
break;
}
case kDistributionValue: {
mutable_distribution_value()->::google::api::servicecontrol::v1::Distribution::MergeFrom(from.distribution_value());
break;
}
case VALUE_NOT_SET: {
break;
}
}
}
void MetricValue::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.api.servicecontrol.v1.MetricValue)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MetricValue::CopyFrom(const MetricValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.api.servicecontrol.v1.MetricValue)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MetricValue::IsInitialized() const {
return true;
}
void MetricValue::Swap(MetricValue* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
MetricValue* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void MetricValue::UnsafeArenaSwap(MetricValue* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MetricValue::InternalSwap(MetricValue* other) {
using std::swap;
labels_.Swap(&other->labels_);
swap(start_time_, other->start_time_);
swap(end_time_, other->end_time_);
swap(value_, other->value_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata MetricValue::GetMetadata() const {
protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void MetricValueSet::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MetricValueSet::kMetricNameFieldNumber;
const int MetricValueSet::kMetricValuesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MetricValueSet::MetricValueSet()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValueSet.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.api.servicecontrol.v1.MetricValueSet)
}
MetricValueSet::MetricValueSet(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
metric_values_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValueSet.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.api.servicecontrol.v1.MetricValueSet)
}
MetricValueSet::MetricValueSet(const MetricValueSet& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
metric_values_(from.metric_values_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
metric_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.metric_name().size() > 0) {
metric_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.metric_name(),
GetArenaNoVirtual());
}
// @@protoc_insertion_point(copy_constructor:google.api.servicecontrol.v1.MetricValueSet)
}
void MetricValueSet::SharedCtor() {
metric_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
MetricValueSet::~MetricValueSet() {
// @@protoc_insertion_point(destructor:google.api.servicecontrol.v1.MetricValueSet)
SharedDtor();
}
void MetricValueSet::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
metric_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void MetricValueSet::ArenaDtor(void* object) {
MetricValueSet* _this = reinterpret_cast< MetricValueSet* >(object);
(void)_this;
}
void MetricValueSet::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MetricValueSet::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* MetricValueSet::descriptor() {
::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const MetricValueSet& MetricValueSet::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::scc_info_MetricValueSet.base);
return *internal_default_instance();
}
void MetricValueSet::Clear() {
// @@protoc_insertion_point(message_clear_start:google.api.servicecontrol.v1.MetricValueSet)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
metric_values_.Clear();
metric_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
_internal_metadata_.Clear();
}
bool MetricValueSet::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.api.servicecontrol.v1.MetricValueSet)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string metric_name = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_metric_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->metric_name().data(), static_cast<int>(this->metric_name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.api.servicecontrol.v1.MetricValueSet.metric_name"));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.api.servicecontrol.v1.MetricValue metric_values = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_metric_values()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.api.servicecontrol.v1.MetricValueSet)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.api.servicecontrol.v1.MetricValueSet)
return false;
#undef DO_
}
void MetricValueSet::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.api.servicecontrol.v1.MetricValueSet)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string metric_name = 1;
if (this->metric_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->metric_name().data(), static_cast<int>(this->metric_name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValueSet.metric_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->metric_name(), output);
}
// repeated .google.api.servicecontrol.v1.MetricValue metric_values = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->metric_values_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2,
this->metric_values(static_cast<int>(i)),
output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:google.api.servicecontrol.v1.MetricValueSet)
}
::google::protobuf::uint8* MetricValueSet::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.api.servicecontrol.v1.MetricValueSet)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string metric_name = 1;
if (this->metric_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->metric_name().data(), static_cast<int>(this->metric_name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.api.servicecontrol.v1.MetricValueSet.metric_name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->metric_name(), target);
}
// repeated .google.api.servicecontrol.v1.MetricValue metric_values = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->metric_values_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->metric_values(static_cast<int>(i)), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.api.servicecontrol.v1.MetricValueSet)
return target;
}
size_t MetricValueSet::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.api.servicecontrol.v1.MetricValueSet)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated .google.api.servicecontrol.v1.MetricValue metric_values = 2;
{
unsigned int count = static_cast<unsigned int>(this->metric_values_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->metric_values(static_cast<int>(i)));
}
}
// string metric_name = 1;
if (this->metric_name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->metric_name());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void MetricValueSet::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.api.servicecontrol.v1.MetricValueSet)
GOOGLE_DCHECK_NE(&from, this);
const MetricValueSet* source =
::google::protobuf::internal::DynamicCastToGenerated<const MetricValueSet>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.api.servicecontrol.v1.MetricValueSet)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.api.servicecontrol.v1.MetricValueSet)
MergeFrom(*source);
}
}
void MetricValueSet::MergeFrom(const MetricValueSet& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.api.servicecontrol.v1.MetricValueSet)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
metric_values_.MergeFrom(from.metric_values_);
if (from.metric_name().size() > 0) {
set_metric_name(from.metric_name());
}
}
void MetricValueSet::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.api.servicecontrol.v1.MetricValueSet)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MetricValueSet::CopyFrom(const MetricValueSet& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.api.servicecontrol.v1.MetricValueSet)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MetricValueSet::IsInitialized() const {
return true;
}
void MetricValueSet::Swap(MetricValueSet* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
MetricValueSet* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void MetricValueSet::UnsafeArenaSwap(MetricValueSet* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MetricValueSet::InternalSwap(MetricValueSet* other) {
using std::swap;
CastToBase(&metric_values_)->InternalSwap(CastToBase(&other->metric_values_));
metric_name_.Swap(&other->metric_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata MetricValueSet::GetMetadata() const {
protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2fapi_2fservicecontrol_2fv1_2fmetric_5fvalue_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace v1
} // namespace servicecontrol
} // namespace api
} // namespace google
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::api::servicecontrol::v1::MetricValue_LabelsEntry_DoNotUse >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::api::servicecontrol::v1::MetricValue* Arena::CreateMaybeMessage< ::google::api::servicecontrol::v1::MetricValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::api::servicecontrol::v1::MetricValue >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::api::servicecontrol::v1::MetricValueSet* Arena::CreateMaybeMessage< ::google::api::servicecontrol::v1::MetricValueSet >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::api::servicecontrol::v1::MetricValueSet >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| 40.947555 | 227 | 0.707825 | [
"object"
] |
76cb7fe149d2e42779d81b4fead0c4456cf6c238 | 2,063 | cpp | C++ | Programacion Competitiva/UVA/10650.cpp | Angel1612/Computer_Science_UNSA | e1696fd2cb7c66f6af9aa14dbd96b4f67c787425 | [
"MIT"
] | null | null | null | Programacion Competitiva/UVA/10650.cpp | Angel1612/Computer_Science_UNSA | e1696fd2cb7c66f6af9aa14dbd96b4f67c787425 | [
"MIT"
] | null | null | null | Programacion Competitiva/UVA/10650.cpp | Angel1612/Computer_Science_UNSA | e1696fd2cb7c66f6af9aa14dbd96b4f67c787425 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#include <time.h>
#include <fstream>
#include <limits>
#include <iomanip>
#define mx 35000
bool is_prime[mx + 10];
std::vector <int> prime , ana;
void sieve() {
is_prime[0] = 1 ;
is_prime[1] = 1 ;
for(int i = 4 ; i <= mx ; i += 2)
is_prime[i] = 1 ;
for(int i = 3 ; i * i <= mx ; i += 2) {
if( !is_prime[i] ) {
for(int j = i * i ; j <= mx ; j += i + i) {
is_prime[j] = 1 ;
}
}
}
prime.push_back(2) ;
for(int i = 3 ; i <= mx ; i += 2 ) {
if(!is_prime[i] ) {
prime.push_back(i) ;
}
}
}
int main() {
sieve() ;
int x , y ;
while(std::cin >> x >> y) {
if(x == 0 && y == 0)
break ;
if( x > y)
std::swap(x , y) ;
int i = 0 ;
while(prime[i] < x)
i++ ;
while(prime[i + 2] <= y) {
if(prime[i + 2] - prime[i + 1] == prime[i + 1] - prime[i]) {
int start = i ;
int end = i + 2 ;
int diff = prime[i + 1] - prime[i] ;
while( i + 3 < prime.size() && prime[i + 3] - prime[i + 2] == diff) {
end++ ;
i++ ;
}
if(prime[end] <= y) {
if(start == 0 || prime[start] - prime[start - 1] != diff) {
std::cout << prime[start] ;
for(int i = start + 1 ; i <= end ; i++) {
std::cout << " " << prime[i] ;
}
std::cout << "\n" ;
}
}
else
break ;
}
i++ ;
}
}
return 0 ;
} | 24.559524 | 85 | 0.379544 | [
"vector"
] |
76ce8736beca4db1aa0a6141732c75ff1e2cb43d | 45,709 | cpp | C++ | src/Graphics/OGL/OGL33.cpp | liavt/MACE | 9a4e83b2b5cb39d9a69b2e699b57c05d9dd94aad | [
"MIT"
] | 9 | 2016-03-01T03:10:50.000Z | 2021-04-15T09:17:14.000Z | src/Graphics/OGL/OGL33.cpp | liavt/The-Poor-Plebs-Engine | 9a4e83b2b5cb39d9a69b2e699b57c05d9dd94aad | [
"MIT"
] | 10 | 2016-07-09T04:00:27.000Z | 2019-12-09T09:14:49.000Z | src/Graphics/OGL/OGL33.cpp | liavt/The-Poor-Plebs-Engine | 9a4e83b2b5cb39d9a69b2e699b57c05d9dd94aad | [
"MIT"
] | 3 | 2017-05-24T04:07:40.000Z | 2019-10-11T20:31:25.000Z | /*
Copyright (c) 2016-2019 Liav Turkia
See LICENSE.md for full copyright information
*/
#include <MACE/Graphics/OGL/OGL33.h>
#include <memory>
#include <string>
namespace mc {
namespace gfx {
namespace ogl33 {
namespace {
Shader createShader(const Enum type, const char* sources[], const GLsizei sourceSize) {
Shader s = Shader(type);
s.init();
s.setSource(sourceSize, sources, nullptr);
s.compile();
return s;
}
void throwShaderError(const unsigned int shaderId, const Enum type, const std::string& message) {
#ifdef MACE_DEBUG_OPENGL
std::unique_ptr<GLchar[]> log_string = std::unique_ptr<GLchar[]>(new char[1024]);
glGetShaderInfoLog(shaderId, 1024, 0, log_string.get());
std::string friendlyType = "UNKNOWN SHADER TYPE " + std::to_string(type);//a more human friendly name for type, like VERTEX_SHADER instead of 335030
if (type == GL_VERTEX_SHADER) {
friendlyType = "VERTEX SHADER";
} else if (type == GL_FRAGMENT_SHADER) {
friendlyType = "FRAGMENT SHADER";
} else if (type == GL_COMPUTE_SHADER) {
friendlyType = "COMPUTE SHADER";
} else if (type == GL_GEOMETRY_SHADER) {
friendlyType = "GEOMETERY SHADER";
} else if (type == GL_TESS_CONTROL_SHADER) {
friendlyType = "TESSELLATION CONTROL SHADER";
} else if (type == GL_TESS_EVALUATION_SHADER) {
friendlyType = "TESSELLATION EVALUATION SHADER";
} else if (type == GL_PROGRAM) {
friendlyType = "SHADER PROGRAM";
glGetProgramInfoLog(shaderId, 1024, 0, log_string.get());
}
MACE__THROW(Shader, "Error generating " + friendlyType + ": " + message + ": " + log_string.get());
#else
MACE__THROW(Shader, "Error generating shader of type " + std::to_string(type));
#endif
}
}//anon namespace
void forceCheckGLError(const unsigned int line, const char* file, const char* message) {
std::vector<Error> errors;
Enum result = GL_NO_ERROR;
while ((result = glGetError()) != GL_NO_ERROR) {
switch (result) {
case GL_INVALID_ENUM:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_INVALID_ENUM: An unacceptable value is specified for an enumerated argument", line, file));
break;
case GL_INVALID_VALUE:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_INVALID_VALUE: A numeric argument is out of range", line, file));
break;
case GL_INVALID_OPERATION:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_INVALID_OPERATION: The specified operation is not allowed in the current state", line, file));
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_INVALID_FRAMEBUFFER_OPERATION: The command is trying to render to or read from the framebuffer while the currently bound framebuffer is not framebuffer complete (i.e. the return value from glCheckFramebufferStatus is not GL_FRAMEBUFFER_COMPLETE)", line, file));
break;
case GL_STACK_OVERFLOW:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_STACK_OVERFLOW: A stack pushing operation cannot be done because it would overflow the limit of that stack's size", line, file));
break;
case GL_STACK_UNDERFLOW:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_STACK_UNDERFLOW: A stack popping operation cannot be done because the stack is already at its lowest point", line, file));
break;
case GL_OUT_OF_MEMORY:
errors.push_back(MACE__GET_ERROR_NAME(OutOfMemory) (std::string(message) + ": GL_OUT_OF_MEMORY: There is not enough memory left to execute the command", line, file));
break;
#ifdef GL_CONTEXT_LOST
case GL_CONTEXT_LOST:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": GL_CONTEXT_LOST: The GL Context has been lost due to a graphics card reset", line, file));
break;
#endif
default:
errors.push_back(MACE__GET_ERROR_NAME(OpenGL) (std::string(message) + ": OpenGL has errored with an error code of " + std::to_string(result), line, file));
break;
}
}
if (errors.size() == 1) {
throw errors[0];
} else if (!errors.empty()) {
throw MultipleErrors(errors.data(), errors.size(), line, file);
}
}
void VertexArray::destroy() {
Object::destroy();
if (indices.isCreated()) {
indices.destroy();
}
for (Index i = 0; i < buffers.size(); ++i) {
if (buffers[i].isCreated()) {
buffers[i].destroy();
}
}
}
bool VertexArray::isCreated() const {
return glIsVertexArray(id) == 1;
}
void VertexArray::loadVertices(const unsigned int verticeSize, const float* vertices, const GLuint location, const Byte attributeSize, const Enum type, const bool normalized) {
vertexNumber = verticeSize;
storeDataInAttributeList(vertexNumber * sizeof(float), vertices, location, attributeSize, type, normalized);
}
void VertexArray::storeDataInAttributeList(const unsigned int dataSize, const GLvoid * data, const GLuint location, const Byte attributeSize, const Enum type, const bool normalized) {
bind();
VertexBuffer buffer = VertexBuffer();
buffer.init();
buffer.bind();
buffer.setLocation(location);
// Give our data to opengl
buffer.setData(static_cast<ptrdiff_t>(attributeSize) * static_cast<ptrdiff_t>(dataSize), data, GL_DYNAMIC_DRAW);
buffer.setAttributePointer(attributeSize, type, normalized, 0, 0);
addBuffer(buffer);
}
void VertexArray::loadIndices(const unsigned int indiceNum, const unsigned int* indiceData) {
indices = ElementBuffer(indiceNum);
indices.init();
indices.bind();
indices.setData(static_cast<ptrdiff_t>(sizeof(unsigned int) * indiceNum), indiceData, GL_STATIC_DRAW);
}
void VertexArray::addBuffer(const VertexBuffer & newBuffer) {
bind();
newBuffer.bind();
newBuffer.enable();
buffers.push_back(newBuffer);
}
void VertexArray::setVertexNumber(const GLsizei vertexNum) {
vertexNumber = vertexNum;
}
GLsizei VertexArray::getVertexNumber() {
return vertexNumber;
}
const GLsizei VertexArray::getVertexNumber() const {
return vertexNumber;
}
void VertexArray::setIndices(const ElementBuffer & buffer) {
indices = buffer;
}
ElementBuffer& VertexArray::getIndices() {
return indices;
}
const ElementBuffer& VertexArray::getIndices() const {
return indices;
}
void VertexArray::setBuffers(const std::vector<VertexBuffer> & newBuffers) {
buffers = newBuffers;
}
std::vector<VertexBuffer>& VertexArray::getBuffers() {
return buffers;
}
const std::vector<VertexBuffer>& VertexArray::getBuffers() const {
return buffers;
}
bool VertexArray::operator==(const VertexArray & other) const {
return vertexNumber == other.vertexNumber && indices == other.indices && Object::operator==(other);
}
bool VertexArray::operator!=(const VertexArray & other) const {
return !operator==(other);
}
void VertexArray::bindIndex(const GLuint ID) const {
glBindVertexArray(ID);
}
void VertexArray::initIndices(GLuint ids[], const GLsizei length) const {
glGenVertexArrays(length, ids);
}
void VertexArray::destroyIndices(const GLuint ids[], const GLsizei length) const {
glDeleteVertexArrays(length, ids);
}
UniformBuffer::UniformBuffer() noexcept : UniformBuffer("") {}
UniformBuffer::UniformBuffer(const char* n) noexcept : Buffer(GL_UNIFORM_BUFFER), name(n) {}
const char* UniformBuffer::getName() const {
return name;
}
void UniformBuffer::setName(const char* na) {
this->name = na;
}
bool UniformBuffer::operator==(const UniformBuffer & other) const {
return name == other.name && Buffer::operator==(other);
}
bool UniformBuffer::operator!=(const UniformBuffer & other) const {
return !(*this == other);
}
void FrameBuffer::setClearColor(const float r, const float g, const float b, const float a) {
glClearColor(r, g, b, a);
}
void FrameBuffer::attachTexture(const Enum target, const Enum attachment, const Texture2D & tex, const int level) {
glFramebufferTexture(target, attachment, tex.getID(), level);
}
void FrameBuffer::attachTexture1D(const Enum target, const Enum attachment, const Texture2D & tex, const int level) {
glFramebufferTexture1D(target, attachment, tex.getTarget(), tex.getID(), level);
}
void FrameBuffer::attachTexture2D(const Enum target, const Enum attachment, const Texture2D & tex, const int level) {
glFramebufferTexture2D(target, attachment, tex.getTarget(), tex.getID(), level);
}
void FrameBuffer::attachTexture3D(const Enum target, const Enum attachment, const Texture2D & tex, const int level, const int layer) {
glFramebufferTexture3D(target, attachment, tex.getTarget(), tex.getID(), level, layer);
}
void FrameBuffer::attachTextureLayer(const Enum target, const Enum attachment, const Texture2D & texture, const int level, const int layer) {
glFramebufferTextureLayer(target, attachment, level, static_cast<GLint>(texture.getID()), layer);
}
void FrameBuffer::attachRenderbuffer(const Enum target, const Enum attachment, const RenderBuffer & buffer) {
glFramebufferRenderbuffer(target, attachment, GL_RENDERBUFFER, buffer.getID());
}
void FrameBuffer::setDrawBuffers(const Size arrSize, const Enum * buffers) {
glDrawBuffers(static_cast<GLsizei>(arrSize), buffers);
}
void FrameBuffer::setReadBuffer(const Enum mode) {
glReadBuffer(mode);
}
void FrameBuffer::setDrawBuffer(const Enum mode) {
glDrawBuffer(mode);
}
FrameBuffer FrameBuffer::getDefaultFramebuffer() {
FrameBuffer def = FrameBuffer();
def.id = 0;
return def;
}
void FrameBuffer::clear(const unsigned int field) {
glClear(field);
}
void FrameBuffer::readPixels(const int x, const int y, const Size width, const Size height, const Enum format, const Enum type, void* data) const {
glReadPixels(x, y, static_cast<GLsizei>(width), static_cast<GLsizei>(height), format, type, data);
}
void FrameBuffer::setPixelStorage(const Enum name, const float param) {
glPixelStoref(name, param);
}
void FrameBuffer::setPixelStorage(const Enum name, const int param) {
glPixelStorei(name, param);
}
bool FrameBuffer::isCreated() const {
return glIsFramebuffer(id) == 1;
}
Enum FrameBuffer::checkStatus(const Enum target) {
return glCheckFramebufferStatus(target);
}
void FrameBuffer::bindIndex(const GLuint ID) const {
glBindFramebuffer(GL_FRAMEBUFFER, ID);
}
void FrameBuffer::initIndices(GLuint ids[], const GLsizei length) const {
glGenFramebuffers(length, ids);
}
void FrameBuffer::destroyIndices(const GLuint ids[], const GLsizei length) const {
glDeleteFramebuffers(length, ids);
}
void RenderBuffer::setStorage(const Enum format, const GLsizei width, const GLsizei height) {
glRenderbufferStorage(GL_RENDERBUFFER, format, width, height);
}
void RenderBuffer::setStorageMultisampled(const GLsizei samples, const Enum format, const GLsizei width, const GLsizei height) {
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, format, width, height);
}
bool RenderBuffer::isCreated() const {
return glIsRenderbuffer(id) == 1;
}
void RenderBuffer::bindIndex(const GLuint ID) const {
glBindRenderbuffer(GL_RENDERBUFFER, ID);
}
void RenderBuffer::initIndices(GLuint ids[], const GLsizei length) const {
glGenRenderbuffers(length, ids);
}
void RenderBuffer::destroyIndices(const GLuint ids[], const GLsizei length) const {
glDeleteRenderbuffers(length, ids);
}
void Object::init() {
initIndices(&id, 1);
}
void Object::destroy() {
destroyIndices(&id, 1);
id = 0;
}
void Object::bind() const {
bindIndex(id);
}
void Object::unbind() const {
bindIndex(0);
}
GLuint Object::getID() const {
return id;
}
void Object::init(Object * objects[], const GLsizei length) {
if (length <= 0) {
return;
}
std::vector<GLuint> ids = std::vector<GLuint>(length);
for (Index i = 0; i < length; ++i) {
ids.push_back(0);
}
objects[0]->initIndices(ids.data(), length);
for (Index i = 0; i < length; ++i) {
objects[i]->id = ids[i];
}
}
void Object::destroy(Object * objects[], const GLsizei length) {
if (length <= 0) {
return;
}
std::vector<GLuint> ids = std::vector<GLuint>(length);
for (Index i = 0; i < length; ++i) {
ids.push_back(objects[i]->id);
}
objects[0]->destroyIndices(ids.data(), length);
for (Index i = 0; i < length; ++i) {
objects[i]->id = 0;
}
}
bool Object::operator==(const Object & other) const {
return this->id == other.id;
}
bool Object::operator!=(const Object & other) const {
return !operator==(other);
}
Texture2D::Texture2D() noexcept {}
void Texture2D::bind() const {
Object::bind();
}
void Texture2D::bind(const unsigned int location) const {
glActiveTexture(GL_TEXTURE0 + location);
Object::bind();
}
void Texture2D::setData(const void* data, GLsizei width, GLsizei height, Enum type, Enum format, Enum internalFormat, GLint mipmapLevel) {
glTexImage2D(target, mipmapLevel, internalFormat, width, height, 0, format, type, data);
}
void Texture2D::setMultisampledData(const GLsizei samples, const GLsizei width, const GLsizei height, const Enum internalFormat, const bool fixedSamples) {
glTexImage2DMultisample(target, samples, internalFormat, width, height, fixedSamples);
}
void Texture2D::setPixelStorage(const Enum alignment, const int number) {
glPixelStorei(alignment, number);
}
void Texture2D::setPixelStorage(const Enum alignment, const bool value) {
setPixelStorage(alignment, value ? 1 : 0);
}
void Texture2D::setPixelStorage(const Enum alignment, const float number) {
glPixelStoref(alignment, number);
}
void Texture2D::generateMipmap() {
glGenerateMipmap(target);
}
void Texture2D::setTarget(Enum targ) {
this->target = targ;
}
Enum& Texture2D::getTarget() {
return target;
}
const Enum& Texture2D::getTarget() const {
return target;
}
bool Texture2D::isCreated() const {
return glIsTexture(id) == 1;
}
void Texture2D::setParameter(const Enum name, const int value) {
glTexParameteri(target, name, value);
}
void Texture2D::getImage(const Enum format, const Enum type, void* data) const {
glGetTexImage(target, 0, format, type, data);
}
bool Texture2D::operator==(const Texture2D & other) const {
return target == other.target && Object::operator==(other);
}
bool Texture2D::operator!=(const Texture2D & other) const {
return !operator==(other);
}
void Texture2D::bindIndex(const GLuint ID) const {
glBindTexture(target, ID);
}
void Texture2D::initIndices(GLuint ids[], const GLsizei length) const {
glGenTextures(length, ids);
}
void Texture2D::destroyIndices(const GLuint ids[], const GLsizei length) const {
glDeleteTextures(length, ids);
}
Buffer::Buffer(const Enum type) noexcept : bufferType(type) {}
bool Buffer::isCreated() const {
return glIsBuffer(id) == 1;
}
void Buffer::setData(const ptrdiff_t & dataSize, const void* data, const Enum drawType) {
glBufferData(bufferType, dataSize, data, drawType);
}
void Buffer::setDataRange(const Index offset, const ptrdiff_t & dataSize, const void* data) {
glBufferSubData(GL_UNIFORM_BUFFER, offset, dataSize, data);
}
void Buffer::copyData(Buffer & other, const ptrdiff_t & size, const Index readOffset, const Index writeOffset) {
glCopyBufferSubData(id, other.id, readOffset, writeOffset, size);
}
void* Buffer::map(const Enum access) {
return glMapBuffer(bufferType, access);
}
void* Buffer::mapRange(const Index offset, const Size length, const unsigned int access) {
return glMapBufferRange(bufferType, offset, length, access);
}
bool Buffer::unmap() {
return glUnmapBuffer(bufferType) == 1;
}
void Buffer::flushRange(const Index offset, const Size length) {
glFlushMappedBufferRange(bufferType, offset, length);
}
void Buffer::getPointer(void** param) {
glGetBufferPointerv(bufferType, GL_BUFFER_MAP_POINTER, param);
}
void Buffer::getParameter(const Enum pname, int* data) const {
glGetBufferParameteriv(bufferType, pname, data);
}
void Buffer::getParameter(const Enum pname, GLint64 * data) const {
glGetBufferParameteri64v(bufferType, pname, data);
}
bool Buffer::isMapped() const {
int out;
getParameter(GL_BUFFER_MAPPED, &out);
return out != 0;
}
GLint64 Buffer::getMapLength() const {
GLint64 out;
getParameter(GL_BUFFER_MAP_LENGTH, &out);
return out;
}
GLint64 Buffer::getMapOffset() const {
GLint64 out;
getParameter(GL_BUFFER_MAP_OFFSET, &out);
return out;
}
bool Buffer::isImmutable() const {
int out;
getParameter(GL_BUFFER_IMMUTABLE_STORAGE, &out);
return out != 0;
}
Enum Buffer::getAccess() const {
int out;
getParameter(GL_BUFFER_ACCESS, &out);
return static_cast<Enum>(out);
}
Enum Buffer::getAccessFlags() const {
int out;
getParameter(GL_BUFFER_ACCESS_FLAGS, &out);
return static_cast<Enum>(out);
}
Enum Buffer::getStorageFlags() const {
int out;
getParameter(GL_BUFFER_STORAGE_FLAGS, &out);
return static_cast<Enum>(out);
}
Enum Buffer::getUsage() const {
int out;
getParameter(GL_BUFFER_USAGE, &out);
return static_cast<Enum>(out);
}
const Enum Buffer::getBufferType() const {
return bufferType;
}
int Buffer::getSize() const {
int out;
getParameter(GL_BUFFER_SIZE, &out);
return out;
}
bool Buffer::operator==(const Buffer & other) const {
return this->bufferType == other.bufferType && Object::operator==(other);
}
bool Buffer::operator!=(const Buffer & other) const {
return !operator==(other);
}
void Buffer::bindIndex(const GLuint ID) const {
glBindBuffer(bufferType, ID);
}
void Buffer::initIndices(GLuint ids[], const GLsizei length) const {
glGenBuffers(length, ids);
}
void Buffer::destroyIndices(const GLuint ids[], const GLsizei length) const {
glDeleteBuffers(length, ids);
}
VertexBuffer::VertexBuffer() noexcept : Buffer(GL_ARRAY_BUFFER) {}
void VertexBuffer::setAttributePointer(const GLint attribSize, const Enum type, const bool normalized, const GLsizei stride, const void* pointer) {
if (!normalized && (
type == GL_BYTE ||
type == GL_UNSIGNED_BYTE ||
type == GL_SHORT ||
type == GL_UNSIGNED_SHORT ||
type == GL_INT ||
type == GL_UNSIGNED_INT
)) {
glVertexAttribIPointer(location, attribSize, type, stride, pointer);
} else {
glVertexAttribPointer(location, attribSize, type, normalized, stride, pointer);
}
}
void VertexBuffer::setDivisor(const GLuint divisor) {
glVertexAttribDivisor(location, divisor);
}
void VertexBuffer::enable() const {
glEnableVertexAttribArray(location);
}
void VertexBuffer::disable() const {
glDisableVertexAttribArray(location);
}
GLuint VertexBuffer::getLocation() {
return location;
}
const GLuint VertexBuffer::getLocation() const {
return location;
}
void VertexBuffer::setLocation(const GLuint newLocation) {
location = newLocation;
}
bool VertexBuffer::operator==(const VertexBuffer & other) const {
return Buffer::operator==(other) && location == other.location;
}
bool VertexBuffer::operator!=(const VertexBuffer & other) const {
return !operator==(other);
}
ElementBuffer::ElementBuffer() noexcept : Buffer(0) {}
ElementBuffer::ElementBuffer(const int indiceNum) noexcept : Buffer(GL_ELEMENT_ARRAY_BUFFER), indiceNumber(indiceNum) {}
void ElementBuffer::setIndiceNumber(const int indices) {
indiceNumber = indices;
}
int ElementBuffer::getIndiceNumber() {
return indiceNumber;
}
const int ElementBuffer::getIndiceNumber() const {
return indiceNumber;
}
bool ElementBuffer::operator==(const ElementBuffer & other) const {
return Buffer::operator==(other) && indiceNumber == other.indiceNumber;
}
bool ElementBuffer::operator!=(const ElementBuffer & other) const {
return !operator==(other);
}
CopyReadBuffer::CopyReadBuffer() noexcept : Buffer(GL_COPY_READ_BUFFER) {}
CopyWriteBuffer::CopyWriteBuffer() noexcept : Buffer(GL_COPY_WRITE_BUFFER) {}
void QueryObject::begin(const Enum target) {
glBeginQuery(target, id);
}
void QueryObject::end(const Enum target) {
glEndQuery(target);
}
void QueryObject::get(const Enum name, int* data) const {
glGetQueryObjectiv(id, name, data);
}
void QueryObject::get(const Enum name, unsigned int* data) const {
glGetQueryObjectuiv(id, name, data);
}
void QueryObject::get(const Enum name, int64_t * data) const {
glGetQueryObjecti64v(id, name, data);
}
void QueryObject::get(const Enum name, uint64_t * data) const {
glGetQueryObjectui64v(id, name, data);
}
void QueryObject::counter() {
glQueryCounter(id, GL_TIMESTAMP);
}
bool QueryObject::isCreated() const {
return glIsQuery(id) == 1;
}
void QueryObject::bind() const {}
void QueryObject::unbind() const {}
void QueryObject::bindIndex(const GLuint) const {}
void QueryObject::initIndices(GLuint ids[], const GLsizei length) const {
glGenQueries(length, ids);
}
void QueryObject::destroyIndices(const GLuint ids[], const GLsizei length) const {
glDeleteQueries(length, ids);
}
PixelUnpackBuffer::PixelUnpackBuffer() noexcept : Buffer(GL_PIXEL_UNPACK_BUFFER) {}
PixelPackBuffer::PixelPackBuffer() noexcept : Buffer(GL_PIXEL_PACK_BUFFER) {}
Shader::Shader() noexcept : Shader(GL_FALSE) {}
Shader::Shader(const Enum shaderType) noexcept : type(shaderType) {}
void Shader::init() {
if (type == GL_FALSE) {
MACE__THROW(InitializationFailed, "Must assign a type to the shader before init() is called!");
}
id = glCreateShader(type);
}
void Shader::destroy() {
glDeleteShader(id);
}
void Shader::setSource(const GLsizei count, const char* strings[], const int lengths[]) {
if (type == GL_FALSE) {
MACE__THROW(Shader, "Shader must have a type before compile() is called");
}
glShaderSource(id, count, strings, lengths);
}
void Shader::setSource(const char string[], const int length) {
const int lengths[1] = {length};
const char* strings[1] = {string};
setSource(1, strings, lengths);
}
void Shader::setSource(const std::string & string) {
//length() returns size_t which could be larger than unsigned in on some systems, causing problems. static_cast will fix it
setSource(string.c_str(), static_cast<int>(string.length()));
}
char* Shader::getSource(const GLsizei length, char* characters, int amount) const {
glGetShaderSource(id, length, &amount, characters);
return characters;
}
int Shader::getParameter(const Enum param) const {
int result;
glGetShaderiv(id, param, &result);
return result;
}
int Shader::getInfoLogLength() const {
return getParameter(GL_INFO_LOG_LENGTH);
}
int Shader::getSourceLength() const {
return getParameter(GL_SHADER_SOURCE_LENGTH);
}
bool Shader::isDeleted() const {
return getParameter(GL_DELETE_STATUS) == GL_TRUE;
}
bool Shader::isCompiled() const {
return getParameter(GL_COMPILE_STATUS) == GL_TRUE;
}
void Shader::compile() {
if (type == GL_FALSE) {
MACE__THROW(Shader, "Shader must have a type before compile() is called");
}
glCompileShader(id);
if (!isCompiled()) {
throwShaderError(id, type, "The shader failed to compile");
}
}
bool Shader::isCreated() const {
return glIsShader(id) == 1;
}
void Shader::setType(const Enum newType) {
type = newType;
}
Enum Shader::getType() {
return type;
}
const Enum Shader::getType() const {
return type;
}
bool Shader::operator==(const Shader & other) const {
return Object::operator==(other) && type == other.type;
}
bool Shader::operator!=(const Shader & other) const {
return !operator==(other);
}
void Shader::bind() const {}
void Shader::unbind() const {}
void Shader::bindIndex(const GLuint) const {}
void Shader::initIndices(GLuint[], const GLsizei) const {}
void Shader::destroyIndices(const GLuint[], const GLsizei) const {}
void ShaderProgram::bindIndex(const GLuint ID) const {
glUseProgram(ID);
}
void ShaderProgram::initIndices(GLuint[], const GLsizei) const {}
void ShaderProgram::destroyIndices(const GLuint[], const GLsizei) const {}
void ShaderProgram::init() {
id = glCreateProgram();
if (id == 0) {
throwShaderError(id, GL_PROGRAM, "Failed to create program ID");
}
}
void ShaderProgram::destroy() {
if (id > 0) {
unbind();
for (auto s : shaders) {
if (s.second.isCreated()) {
s.second.destroy();
}
}
glDeleteProgram(id);
}
}
void ShaderProgram::link() {
glLinkProgram(id);
if (!isLinked()) {
throwShaderError(id, GL_PROGRAM, "The shader program was unable to link");
}
checkGLError(__LINE__, __FILE__, "Error linking shader program");
validate();
if (!isValidated()) {
throwShaderError(id, GL_PROGRAM, "The shader program failed to validate");
}
checkGLError(__LINE__, __FILE__, "Error validating shader program");
for (auto s : shaders) {
if (s.second.isCreated()) {
detachShader(s.second);
}
}
checkGLError(__LINE__, __FILE__, "Error detaching shader program");
}
bool ShaderProgram::isCreated() const {
return glIsProgram(id) == GL_TRUE;
}
int ShaderProgram::getParameter(const Enum param) const {
int result;
glGetProgramiv(id, param, &result);
return result;
}
int ShaderProgram::getInfoLogLength() const {
return getParameter(GL_INFO_LOG_LENGTH);
}
int ShaderProgram::getAttachedShaders() const {
return getParameter(GL_ATTACHED_SHADERS);
}
bool ShaderProgram::isDeleted() const {
//some compilers emit warnings saying conversion from int to bool, making it explicit silences those
return getParameter(GL_DELETE_STATUS) == GL_TRUE;
}
bool ShaderProgram::isLinked() const {
return getParameter(GL_LINK_STATUS) == GL_TRUE;
}
bool ShaderProgram::isValidated() const {
return getParameter(GL_VALIDATE_STATUS) == GL_TRUE;
}
void ShaderProgram::detachShader(const GLuint shaderId) {
glDetachShader(id, shaderId);
}
void ShaderProgram::detachShader(const Shader & sh) {
detachShader(sh.getID());
}
void ShaderProgram::validate() {
glValidateProgram(id);
}
void ShaderProgram::attachShader(const Shader shader) {
glAttachShader(id, shader.getID());
shaders.insert(std::pair<Enum, Shader>(shader.getType(), shader));
}
void ShaderProgram::createFragment(const char shader[]) {
createFragment(1, &shader);
}
void ShaderProgram::createFragment(const GLsizei count, const char* strings[]) {
attachShader(createShader(GL_FRAGMENT_SHADER, strings, count));
}
void ShaderProgram::createVertex(const char shader[]) {
createVertex(1, &shader);
}
void ShaderProgram::createVertex(const GLsizei count, const char* strings[]) {
attachShader(createShader(GL_VERTEX_SHADER, strings, count));
}
void ShaderProgram::createUniform(const std::string & name) {
int location = glGetUniformLocation(id, name.data());
if (location < 0) {
MACE__THROW(Shader, "Error finding uniform with name " + std::string(name));
}
uniforms[name] = location;
}
void ShaderProgram::createUniform(const char* name) {
createUniform(std::string(name));
}
void ShaderProgram::createUniformBuffer(const char* name, const GLint location) {
UniformBufferData out = UniformBufferData();
if (location >= 0) {
glUniformBlockBinding(id, glGetUniformBlockIndex(id, name), location);
out.index = location;
} else {
out.index = glGetUniformBlockIndex(id, name);
}
glGetActiveUniformBlockiv(id, out.index, GL_UNIFORM_BLOCK_DATA_SIZE, &out.size);
GLint activeUniforms = 0;
glGetActiveUniformBlockiv(id, out.index, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &activeUniforms);
std::vector<GLuint> indices(activeUniforms);
{
std::vector<GLint> tempIndices(activeUniforms);
glGetActiveUniformBlockiv(id, out.index, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &tempIndices[0]);
#pragma omp parallel for
for (Index i = 0; i < activeUniforms; ++i) {
indices[i] = static_cast<GLuint>(tempIndices[i]);
}
}
std::vector<GLint> nameLengths(activeUniforms);
std::vector<GLint> sizes(activeUniforms);
std::vector<GLint> offsets(activeUniforms);
std::vector<GLint> types(activeUniforms);
glGetActiveUniformsiv(id, activeUniforms, &indices[0], GL_UNIFORM_NAME_LENGTH, &nameLengths[0]);
glGetActiveUniformsiv(id, activeUniforms, &indices[0], GL_UNIFORM_SIZE, &sizes[0]);
glGetActiveUniformsiv(id, activeUniforms, &indices[0], GL_UNIFORM_OFFSET, &offsets[0]);
glGetActiveUniformsiv(id, activeUniforms, &indices[0], GL_UNIFORM_TYPE, &types[0]);
for (Index i = 0; i < activeUniforms; ++i) {
std::string bufferName(static_cast<Size>(nameLengths[i]), '_');
glGetActiveUniformName(id, out.index, nameLengths[i], nullptr, &bufferName[0]);
UniformBufferData::Field field{};
field.index = indices[i];
field.size = sizes[i];
field.offset = offsets[i];
field.type = types[i];
out.fields[bufferName] = field;
}
uniformBuffers[name] = out;
}
void ShaderProgram::createUniformBuffer(const UniformBuffer & buf, const GLint location) {
createUniformBuffer(buf.getName(), location);
}
ShaderProgram::UniformBufferData& ShaderProgram::getUniformBuffer(const std::string name) {
return uniformBuffers[name];
}
ShaderProgram::UniformBufferData& ShaderProgram::getUniformBuffer(const UniformBuffer & buf) {
return getUniformBuffer(std::string(buf.getName()));
}
void ShaderProgram::setUniformBufferField(UniformBuffer & buf, const std::string name, const void* data, const ptrdiff_t size) {
const UniformBufferData& bufferData = getUniformBuffer(buf);
buf.setDataRange(bufferData.fields.at(name).offset, size, data);
}
void ShaderProgram::bindUniformBuffer(const UniformBuffer & buf) {
const UniformBuffer* buffer[] = {
&buf
};
bindUniformBuffers(buffer, 1);
}
void ShaderProgram::bindUniformBuffers(const UniformBuffer* bufs[], const Size size) {
for (Index i = 0; i < size; ++i) {
const UniformBufferData& bufferData = getUniformBuffer(*bufs[i]);
glBindBufferBase(GL_UNIFORM_BUFFER, bufferData.index, bufs[i]->getID());
}
}
int ShaderProgram::getUniformLocation(const std::string & name) const {
return uniforms.find(name)->second;
}
int ShaderProgram::getUniformLocation(const char* name) const {
return uniforms.find(name)->second;
}
/*
void ShaderProgram::getUniformIndices(const char * indices[], const Size count) {
std::vector<unsigned int> counts = std::vector<unsigned int>();
counts.reserve(count);
glGetUniformIndices(id, count, indices, counts.data());
for (Index i = 0; i < count; ++i) {
if (counts[i] != GL_INVALID_INDEX) {
uniforms[indices[i]] = counts[i];
}
}
}
*/
bool ShaderProgram::operator==(const ShaderProgram & other) const {
return Object::operator==(other) && uniforms == other.uniforms && shaders == other.shaders;
}
bool ShaderProgram::operator!=(const ShaderProgram & other) const {
return !operator==(other);
}
//Autogenerated definitions.
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 4, 4> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 4, 4> & m) {
float flattenedData[4 * 4]; glUniformMatrix4fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 3, 3> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 3, 3> & m) {
float flattenedData[3 * 3]; glUniformMatrix3fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 2, 2> & m) {
setUniform(name, true, m);
}
//setUniform with float matrices
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 2, 2> & m) {
float flattenedData[2 * 2]; glUniformMatrix2fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 2, 3> & m) {
float flattenedData[2 * 3]; glUniformMatrix2x3fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 2, 3> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 3, 2> & m) {
float flattenedData[3 * 2]; glUniformMatrix3x2fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 3, 2> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 2, 4> & m) {
float flattenedData[2 * 4]; glUniformMatrix2x4fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 2, 4> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 3, 4> & m) {
float flattenedData[3 * 4]; glUniformMatrix3x4fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 3, 4> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<float, 4, 3> & m) {
float flattenedData[4 * 3]; glUniformMatrix4x3fv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<float, 4, 3> & m) {
setUniform(name, true, m);
}
//setUniform with double matrices
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 2, 2> & m) {
double flattenedData[2 * 2]; glUniformMatrix2dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 2, 2> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 3, 3> & m) {
double flattenedData[3 * 3]; glUniformMatrix3dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 3, 3> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 4, 4> & m) {
double flattenedData[4 * 4]; glUniformMatrix4dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 4, 4> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 2, 3> & m) {
double flattenedData[2 * 3]; glUniformMatrix2x3dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 2, 3> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 3, 2> & m) {
double flattenedData[3 * 2]; glUniformMatrix3x2dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 3, 2> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 2, 4> & m) {
double flattenedData[2 * 4]; glUniformMatrix2x4dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 2, 4> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 3, 4> & m) {
double flattenedData[3 * 4]; glUniformMatrix3x4dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 3, 4> & m) {
setUniform(name, true, m);
}
void ShaderProgram::setUniform(const char* name, const bool transpose, const mc::Matrix<double, 4, 3> & m) {
double flattenedData[4 * 3]; glUniformMatrix4x3dv(uniforms[name], 1, transpose, m.flatten(flattenedData));
}
void ShaderProgram::setUniform(const char* name, const mc::Matrix<double, 4, 3> & m) {
setUniform(name, true, m);
}
//setUniform with float
void ShaderProgram::setUniform(const char* name, const float a) {
glUniform1f(uniforms[name], a);
}
void ShaderProgram::setUniform(const char* name, const float a, const float b) {
glUniform2f(uniforms[name], a, b);
}
void ShaderProgram::setUniform(const char* name, const float a, const float b, const float c) {
glUniform3f(uniforms[name], a, b, c);
}
void ShaderProgram::setUniform(const char* name, const float a, const float b, const float c, const float d) {
glUniform4f(uniforms[name], a, b, c, d);
}
void ShaderProgram::setUniform(const char* name, const GLsizei arraySize, const float* a) {
glUniform1fv(uniforms[name], arraySize, a);
}
void ShaderProgram::setUniform(const char* name, const GLsizei componentSize, const GLsizei arraySize, const float* a) {
if (componentSize == 1) glUniform1fv(uniforms[name], arraySize, a); else if (componentSize == 2) glUniform2fv(uniforms[name], arraySize, a); else if (componentSize == 3) glUniform3fv(uniforms[name], arraySize, a); else if (componentSize == 4) glUniform4fv(uniforms[name], arraySize, a);
}
//setUniform with double
void ShaderProgram::setUniform(const char* name, const double a) {
glUniform1d(uniforms[name], a);
}
void ShaderProgram::setUniform(const char* name, const double a, const double b) {
glUniform2d(uniforms[name], a, b);
}
void ShaderProgram::setUniform(const char* name, const double a, const double b, const double c) {
glUniform3d(uniforms[name], a, b, c);
}
void ShaderProgram::setUniform(const char* name, const double a, const double b, const double c, const double d) {
glUniform4d(uniforms[name], a, b, c, d);
}
void ShaderProgram::setUniform(const char* name, const GLsizei arraySize, const double* a) {
glUniform1dv(uniforms[name], arraySize, a);
}
void ShaderProgram::setUniform(const char* name, const GLsizei componentSize, const GLsizei arraySize, const double* a) {
if (componentSize == 1) glUniform1dv(uniforms[name], arraySize, a); else if (componentSize == 2) glUniform2dv(uniforms[name], arraySize, a); else if (componentSize == 3) glUniform3dv(uniforms[name], arraySize, a); else if (componentSize == 4) glUniform4dv(uniforms[name], arraySize, a);
}
//setUniform with int
void ShaderProgram::setUniform(const char* name, const int a) {
glUniform1i(uniforms[name], a);
}
void ShaderProgram::setUniform(const char* name, const int a, const int b) {
glUniform2i(uniforms[name], a, b);
}
void ShaderProgram::setUniform(const char* name, const int a, const int b, const int c) {
glUniform3i(uniforms[name], a, b, c);
}
void ShaderProgram::setUniform(const char* name, const int a, const int b, const int c, const int d) {
glUniform4i(uniforms[name], a, b, c, d);
}
void ShaderProgram::setUniform(const char* name, const GLsizei arraySize, const int* a) {
glUniform1iv(uniforms[name], arraySize, a);
}
void ShaderProgram::setUniform(const char* name, const GLsizei componentSize, const GLsizei arraySize, const int* a) {
if (componentSize == 1) glUniform1iv(uniforms[name], arraySize, a); else if (componentSize == 2) glUniform2iv(uniforms[name], arraySize, a); else if (componentSize == 3) glUniform3iv(uniforms[name], arraySize, a); else if (componentSize == 4) glUniform4iv(uniforms[name], arraySize, a);
}
//setUniform with unsigned int
void ShaderProgram::setUniform(const char* name, const unsigned int a) {
glUniform1ui(uniforms[name], a);
}
void ShaderProgram::setUniform(const char* name, const unsigned int a, const unsigned int b) {
glUniform2ui(uniforms[name], a, b);
}
void ShaderProgram::setUniform(const char* name, const unsigned int a, const unsigned int b, const unsigned int c) {
glUniform3ui(uniforms[name], a, b, c);
}
void ShaderProgram::setUniform(const char* name, const unsigned int a, const unsigned int b, const unsigned int c, const unsigned int d) {
glUniform4ui(uniforms[name], a, b, c, d);
}
void ShaderProgram::setUniform(const char* name, const GLsizei arraySize, const unsigned int* a) {
glUniform1uiv(uniforms[name], arraySize, a);
}
void ShaderProgram::setUniform(const char* name, const GLsizei componentSize, const GLsizei arraySize, const unsigned int* a) {
if (componentSize == 1) glUniform1uiv(uniforms[name], arraySize, a); else if (componentSize == 2) glUniform2uiv(uniforms[name], arraySize, a); else if (componentSize == 3) glUniform3uiv(uniforms[name], arraySize, a); else if (componentSize == 4) glUniform4uiv(uniforms[name], arraySize, a);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<unsigned int, 4> v) {
glUniform4ui(uniforms[name], v[0], v[1], v[2], v[3]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<unsigned int, 3> v) {
glUniform3ui(uniforms[name], v[0], v[1], v[2]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<unsigned int, 2> v) {
glUniform2ui(uniforms[name], v[0], v[1]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<unsigned int, 1> v) {
glUniform1ui(uniforms[name], v[0]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<int, 4> v) {
glUniform4i(uniforms[name], v[0], v[1], v[2], v[3]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<int, 3> v) {
glUniform3i(uniforms[name], v[0], v[1], v[2]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<int, 2> v) {
glUniform2i(uniforms[name], v[0], v[1]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<int, 1> v) {
glUniform1i(uniforms[name], v[0]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<double, 4> v) {
glUniform4d(uniforms[name], v[0], v[1], v[2], v[3]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<double, 3> v) {
glUniform3d(uniforms[name], v[0], v[1], v[2]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<double, 2> v) {
glUniform2d(uniforms[name], v[0], v[1]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<double, 1> v) {
glUniform1d(uniforms[name], v[0]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<float, 4> v) {
glUniform4f(uniforms[name], v[0], v[1], v[2], v[3]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<float, 3> v) {
glUniform3f(uniforms[name], v[0], v[1], v[2]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<float, 2> v) {
glUniform2f(uniforms[name], v[0], v[1]);
}
void ShaderProgram::setUniform(const char* name, const mc::Vector<float, 1> v) {
glUniform1f(uniforms[name], v[0]);
}
void ShaderProgram::setShaders(const std::unordered_map<Enum, Shader> & newShaders) {
shaders = newShaders;
}
const std::unordered_map<Enum, Shader>& ShaderProgram::getShaders() const {
return shaders;
}
std::unordered_map<Enum, Shader>& ShaderProgram::getShaders() {
return shaders;
}
void ShaderProgram::setUniforms(const std::unordered_map<std::string, int> & newUniforms) {
uniforms = newUniforms;
}
const std::unordered_map<std::string, int>& ShaderProgram::getUniforms() const {
return uniforms;
}
std::unordered_map<std::string, int>& ShaderProgram::getUniforms() {
return uniforms;
}
}//ogl33
}//gfx
}//mc
| 34.445365 | 343 | 0.68457 | [
"render",
"object",
"vector"
] |
76cef857a1cd91462cc341a60b64dae84fb28c7d | 1,576 | cpp | C++ | lib/mis/kernel/modified.cpp | Ya-Za/KaMIS | 82a39d695b370776111fbb0563212d22e85676ed | [
"MIT"
] | 30 | 2020-06-18T09:52:51.000Z | 2022-01-27T03:30:45.000Z | lib/mis/kernel/modified.cpp | Ya-Za/KaMIS | 82a39d695b370776111fbb0563212d22e85676ed | [
"MIT"
] | 13 | 2020-06-15T09:43:47.000Z | 2022-01-31T14:02:42.000Z | lib/mis/kernel/modified.cpp | Ya-Za/KaMIS | 82a39d695b370776111fbb0563212d22e85676ed | [
"MIT"
] | 17 | 2020-06-15T09:33:34.000Z | 2022-02-27T21:03:57.000Z |
// local includes
#include "modified.h"
#include "branch_and_reduce_algorithm.h"
// system includes
#include <vector>
modified::modified(int const _add, std::vector<int> &_removed, std::vector<int> &_vs, std::vector<std::vector<int>> &newAdj, branch_and_reduce_algorithm *_pAlg)
: add(_add)
, pAlg(_pAlg)
{
removed.swap(_removed);
vs.swap(_vs);
oldAdj.resize(vs.size());
pAlg->crt += add;
for (int i = 0; i < static_cast<int>(removed.size()); i++) pAlg->vRestore[--(pAlg->rn)] = -1;
for (int v : removed) {
assert(pAlg->x[v] < 0);
pAlg->x[v] = 2;
}
for (int i = 0; i < static_cast<int>(vs.size()); i++) {
oldAdj[i].swap(pAlg->adj[vs[i]]);
pAlg->adj[vs[i]].swap(newAdj[i]);
}
}
modified::modified(std::vector<int> &_removed, std::vector<int> &_vs, branch_and_reduce_algorithm *_pAlg)
: add(0)
, pAlg(_pAlg)
{
removed.swap(_removed);
vs.swap(_vs);
}
void modified::restore() {
pAlg->crt -= add;
pAlg->rn += removed.size();
for (int v : removed) pAlg->x[v] = -1;
for (int i = 0; i < static_cast<int>(vs.size()); i++) {
pAlg->adj[vs[i]] = oldAdj[i];
int inV = pAlg->in[vs[i]], outV = pAlg->out[vs[i]];
for (int u : pAlg->adj[vs[i]]) {
if (u == inV) inV = -1;
if (u == outV) outV = -1;
}
if (inV >= 0) {
pAlg->out[pAlg->in[vs[i]]] = -1;
pAlg->in[vs[i]] = -1;
}
if (outV >= 0) {
pAlg->in[pAlg->out[vs[i]]] = -1;
pAlg->out[vs[i]] = -1;
}
}
}
| 26.711864 | 160 | 0.51967 | [
"vector"
] |
76d4973610e26cf53c27b52237bec61474d04a4d | 6,735 | cpp | C++ | TouchMindLib_Test/touchmind/model/node/Test_NodeModel.cpp | yohei-yoshihara/TouchMind | 3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa | [
"MIT"
] | 15 | 2015-07-10T05:03:27.000Z | 2021-06-08T08:24:46.000Z | TouchMindLib_Test/touchmind/model/node/Test_NodeModel.cpp | yohei-yoshihara/TouchMind | 3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa | [
"MIT"
] | null | null | null | TouchMindLib_Test/touchmind/model/node/Test_NodeModel.cpp | yohei-yoshihara/TouchMind | 3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa | [
"MIT"
] | 10 | 2015-01-04T01:23:56.000Z | 2020-12-29T11:35:47.000Z | #include "stdafx.h"
#include "touchmind/model/node/NodeModel.h"
#include "touchmind/text/FontAttribute.h"
using namespace touchmind::model;
using namespace touchmind::model::node;
using namespace touchmind::text;
/*
class Test : public ::testing::Test
{
public:
Test() {
}
virtual ~Test() {
}
virtual void SetUp() {
node = std::make_shared<NodeModel>();
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
virtual void TearDown() {
}
std::shared_ptr<NodeModel> node;
};
TEST_F(Test, id_001)
{
node->SetId(node->GetId());
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetId(1);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
TEST_F(Test, position_001)
{
node->SetPosition(node->GetPosition());
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetPosition(touchmind::NODE_SIDE_LEFT);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
TEST_F(Test, createdTime_001)
{
node->SetCreatedTime(node->GetCreatedTime());
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
SYSTEMTIME time;
node->SetCreatedTime(time);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
/*
TEST_F(Test, createdTime_002)
{
LONGLONG t = node->GetCreatedTimeAsJavaTime();
node->SetCreatedTime(t);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
LONGLONG time = 0;
node->SetCreatedTime(time);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
*/
/*
TEST_F(Test, parent_001)
{
std::shared_ptr<NodeModel> parent(std::make_shared<NodeModel>());
node->SetParent(parent);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->SetParent(parent);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
std::shared_ptr<NodeModel> parent1(std::make_shared<NodeModel>());
node->SetParent(parent1);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
TEST_F(Test, AddChild_001)
{
std::shared_ptr<NodeModel> child(std::make_shared<NodeModel>());
node->AddChild(child);
ASSERT_EQ(1, node->GetChildrenCount());
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->AddChild(child);
ASSERT_EQ(1, node->GetChildrenCount());
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
TEST_F(Test, RemoveChild_001)
{
std::shared_ptr<NodeModel> child(std::make_shared<NodeModel>());
node->AddChild(child);
ASSERT_EQ(1, node->GetChildrenCount());
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
std::shared_ptr<NodeModel> child2(std::make_shared<NodeModel>());
node->RemoveChild(child2);
ASSERT_EQ(1, node->GetChildrenCount());
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->RemoveChild(child);
ASSERT_EQ(0, node->GetChildrenCount());
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
TEST_F(Test, RemoveAllChildren_001)
{
std::shared_ptr<NodeModel> child(std::make_shared<NodeModel>());
node->AddChild(child);
ASSERT_EQ(1, node->GetChildrenCount());
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->RemoveAllChildren();
ASSERT_EQ(0, node->GetChildrenCount());
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
TEST_F(Test, collapsed_001)
{
std::shared_ptr<NodeModel> child1(std::make_shared<NodeModel>());
std::shared_ptr<NodeModel> child2(std::make_shared<NodeModel>());
node->AddChild(child1);
child1->AddChild(child2);
ASSERT_FALSE(child1->IsCollapsed());
child1->SetRepaintRequired(false);
child1->SetSaveRequired(false);
child1->SetCollapsed(true);
ASSERT_TRUE(child1->IsRepaintRequired());
ASSERT_FALSE(child1->IsSaveRequired());
}
TEST_F(Test, x_001)
{
node->SetX(1.0f);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->SetX(1.0f);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
TEST_F(Test, y_001)
{
node->SetY(1.0f);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->SetY(1.0f);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
TEST_F(Test, width_001)
{
node->SetWidth(1.0f);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->SetWidth(1.0f);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
TEST_F(Test, height_001)
{
node->SetHeight(1.0f);
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->SetHeight(1.0f);
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
TEST_F(Test, fontAttribute_001)
{
node->AddFontAttribute(FontAttribute());
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
}
TEST_F(Test, backgroundcolor_001)
{
node->SetBackgroundColor(D2D1::ColorF(1.0, 1.0, 1.0, 0.5));
ASSERT_TRUE(node->IsRepaintRequired());
ASSERT_TRUE(node->IsSaveRequired());
node->SetRepaintRequired(false);
node->SetSaveRequired(false);
node->SetBackgroundColor(D2D1::ColorF(1.0, 1.0, 1.0, 0.5));
ASSERT_FALSE(node->IsRepaintRequired());
ASSERT_FALSE(node->IsSaveRequired());
}
*/ | 25.903846 | 70 | 0.692502 | [
"model"
] |
76da3401eb2ab468907f576935f573b0ef987e1f | 523 | hpp | C++ | Source/Engine/src/include/audio/sound.hpp | DatZach/Swift | b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7 | [
"MIT"
] | null | null | null | Source/Engine/src/include/audio/sound.hpp | DatZach/Swift | b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7 | [
"MIT"
] | null | null | null | Source/Engine/src/include/audio/sound.hpp | DatZach/Swift | b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7 | [
"MIT"
] | 1 | 2021-10-30T20:43:01.000Z | 2021-10-30T20:43:01.000Z | /*
* sound.hpp
* Sound
*/
#ifndef __AUDIO_SOUND_HPP
#define __AUDIO_SOUND_HPP
#include <vector>
#include <string>
#include <mutex>
#include <Audio/AudioStream.hpp>
#include <Audio/AudioFile.hpp>
namespace Audio
{
class Sound : public AudioStream
{
private:
std::mutex mutex;
AudioFile file;
std::vector<short> samples;
protected:
virtual bool OnGetData(Chunk& chunk);
virtual void OnSeek(unsigned int offset);
public:
Sound();
~Sound();
bool Open(const std::string& filename);
};
}
#endif
| 14.135135 | 44 | 0.699809 | [
"vector"
] |
76dcb7e6fe01b401a3d6b7af0f6fcf23a2b17468 | 8,174 | hpp | C++ | include/boost/astronomy/io/header.hpp | nitink25/astronomy | 0a1d137171b08d1014d4ff138b2a40a146f4f39b | [
"BSL-1.0"
] | 75 | 2019-05-14T13:53:02.000Z | 2022-03-03T20:37:18.000Z | include/boost/astronomy/io/header.hpp | Zyro9922/astronomy | 56be0f8dfb103520ffbec0b793a92a531cd4b714 | [
"BSL-1.0"
] | 96 | 2019-05-28T17:46:00.000Z | 2021-01-09T07:59:17.000Z | include/boost/astronomy/io/header.hpp | Zyro9922/astronomy | 56be0f8dfb103520ffbec0b793a92a531cd4b714 | [
"BSL-1.0"
] | 29 | 2019-05-13T21:09:50.000Z | 2022-03-04T06:24:39.000Z | /*=============================================================================
Copyright 2018 Pranam Lashkari <plashkari628@gmail.com>
Copyright 2020 Gopi Krishna Menon <krishnagopi487.github@outlook.com>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_ASTRONOMY_IO_HDU_HPP
#define BOOST_ASTRONOMY_IO_HDU_HPP
#include <string>
#include <vector>
#include <cstddef>
#include <unordered_map>
#include <memory>
#include <fstream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/astronomy/io/bitpix.hpp>
#include <boost/astronomy/io/image.hpp>
#include <boost/astronomy/exception/fits_exception.hpp>
#include <boost/astronomy/io/card.hpp>
#include <boost/astronomy/io/column.hpp>
namespace boost { namespace astronomy { namespace io {
/**
* @brief Used to store Header Related Information of FITS HDU ( Header Data Unit )
* @details This structure also provides additional methods for querying some of the common but important keyword values
* along with a general function ( value_of ) for querying the value associated with any keyword in an HDU
* @author Pranam Lashkari
* @author Sarthak Singhal
* @note To learn more about HDU please refer
* <a href="http://archive.stsci.edu/fits/users_guide/node5.html#SECTION00320000000000000000">FITS</a>
*/
template<typename CardPolicy>
struct header
{
protected:
boost::astronomy::io::bitpix bitpix_value; //! stores the BITPIX value (enum bitpix)
std::vector<std::size_t> naxis_; //! values of all naxis (NAXIS, NAXIS1, NAXIS2...)
std::string hdu_name;
//! Stores the each card in header unit (80 char key value pair)
std::vector<card<CardPolicy>> cards;
//! stores the card-key index (used for faster searching)
std::unordered_map<std::string, std::size_t> key_index;
public:
/**
* @todo Take note of whether to make it templated or not
*/
bool operator == (const header& other) {
return bitpix_value == other.bitpix_value &&
this->naxis_ == other.naxis_ &&
this->hdu_name == other.hdu_name &&
this->cards == other.cards &&
this->key_index == other.key_index;
}
/**
* @brief Reads the header portion of an HDU using file reader
* @param[in] file_reader Reader used to access the FITS file
*/
template<typename FileReader>
void read_header(FileReader& file_reader) {
cards.reserve(36); //reserves the space of atleast 1 HDU unit
std::string card_buffer;
//reading file card by card until END card is found
while (true)
{
//read from file and create push card into the vector
card_buffer = file_reader.read(80);
cards.emplace_back(card_buffer);
//store the index of the card in map
this->key_index[this->cards.back().keyword()] = this->cards.size() - 1;
//check if end card is found
if (this->cards.back().keyword(true) == "END ")
{
break;
}
}
//finding and storing bitpix value
switch (cards[key_index["BITPIX"]]. template value<int>())
{
case 8:
this->bitpix_value = io::bitpix::B8;
break;
case 16:
this->bitpix_value = io::bitpix::B16;
break;
case 32:
this->bitpix_value = io::bitpix::B32;
break;
case -32:
this->bitpix_value = io::bitpix::_B32;
break;
case -64:
this->bitpix_value = io::bitpix::_B64;
break;
default:
throw fits_exception();
break;
}
//setting naxis values
std::size_t total_dimensions = cards[key_index["NAXIS"]].template value<std::size_t>();
naxis_.reserve(total_dimensions);
for (std::size_t i = 1; i <= total_dimensions; i++)
{
naxis_.emplace_back(cards[key_index["NAXIS" +
boost::lexical_cast<std::string>(i)]].template value<std::size_t>());
}
}
/**
* @brief Writes the entire HDU header into the file
* @param[in] file_writer File Writer object for facilitating the writing of data
* @tparam FileWriter Type of file_writer object
*/
template<typename FileWriter>
void write_header(FileWriter& file_writer) {
std::string temp_buffer;
for (auto& header_card : this->cards) {
temp_buffer += header_card.raw_card();
}
file_writer.write(temp_buffer);
auto current_write_pos = file_writer.get_current_pos();
auto logical_record_end_pos = file_writer.find_unit_end();
file_writer.write(std::string(logical_record_end_pos - current_write_pos, ' '));
}
/**
* @brief Returns the name of the HDU
*/
std::string get_hdu_name() {
// Check if its a extension
try {
hdu_name = value_of < std::string>("XTENSION");
return hdu_name;
}
catch (...) {}
// Test if its primary header ( otherwise exception propagated)
value_of<bool>("SIMPLE");
return "primary_hdu";
}
/**
* @brief Searches for the given keyword is present in the Header
* @param[in] keyword Keyword to be searched for
*/
bool contains_keyword(const std::string& keyword) {
auto keyword_found = std::find_if(cards.begin(), cards.end(), [&keyword](const card<CardPolicy>& h_card) {
return h_card.keyword() == keyword;
});
return keyword_found != cards.end();
}
/**
* @brief Gets the bitpix value associated with the HDU
* @return io::bitpix
*/
io::bitpix bitpix() const
{
return this->bitpix_value;
}
/**
* @brief Gets the value(number of elements) of all dimensions associated with the HDU data
* @return Returns a vector<size_t> containing the number of elements for each dimension
*/
std::vector<std::size_t> all_naxis() const
{
return this->naxis_;
}
/**
* @brief Gets the number of elements for a perticular dimension in HDU data
* @return Returns a std::size_t containing the number of elements in a perticular dimension
*/
std::size_t naxis(std::size_t n = 0) const
{
return this->naxis_[n - 1]; // 1 Based indexing
}
/**
* @brief Returns the total number of dimensions of an HDU data
*/
std::size_t total_dimensions() const { return all_naxis().size(); }
/**
* @brief Returns the total number of elements in HDU data
*/
std::size_t data_size() {
if (naxis_.empty()) { return 0; }
return std::accumulate(naxis_.begin(), naxis_.end(), static_cast<std::size_t > (1), std::multiplies<std::size_t>());
}
/**
* @brief Gets the value associated with a perticular keyword
* @param[in] key Keyword whose value is to be queried
* @tparam ReturnType The type in which the value associated with the keyword needs to be obtained
* @return Returns the value associated with keyword in the required type
* @throws boost::bad_lexical_cast If the conversion of value to the specific type was not successul
*/
template <typename ReturnType>
ReturnType value_of(std::string const& key)// const
{
return this->cards[key_index.at(key)].template value<ReturnType>();
}
/**
* @brief Gets the number of cards in HDU header
* @return total number of cards in HDU header
*/
std::size_t card_count() {
return cards.size() - 1; // Last one is END Card ( It will not be counted )
}
friend bool operator == (const header<CardPolicy>& lhs, const header<CardPolicy>& rhs);
};
}}} //namespace boost::astronomy::io
#endif // !BOOST_ASTRONOMY_IO_HDU_HPP
| 33.227642 | 124 | 0.610962 | [
"object",
"vector"
] |
76dfd909843b7f6fae13d8720c16dd9e8b37b493 | 18,143 | cpp | C++ | samples/shadertoy/Application.cpp | azhirnov/FrameGraph-Samples | 7dc7966276fd479e43405ea29942cbdfc512d416 | [
"BSD-2-Clause"
] | 15 | 2019-08-09T13:54:33.000Z | 2022-01-21T06:17:43.000Z | samples/shadertoy/Application.cpp | azhirnov/FrameGraph-Samples | 7dc7966276fd479e43405ea29942cbdfc512d416 | [
"BSD-2-Clause"
] | 2 | 2019-12-02T17:00:59.000Z | 2019-12-05T14:00:11.000Z | samples/shadertoy/Application.cpp | azhirnov/FrameGraph-Samples | 7dc7966276fd479e43405ea29942cbdfc512d416 | [
"BSD-2-Clause"
] | 2 | 2020-12-17T11:49:29.000Z | 2021-08-06T15:59:50.000Z | // Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE'
#include "Application.h"
#include "Shaders.h"
#include "stl/Algorithms/StringUtils.h"
#include "stl/Algorithms/StringUtils.h"
#include "stl/Stream/FileStream.h"
#include "video/FFmpegRecorder.h"
#include "scene/Loader/DevIL/DevILSaver.h"
#include "scene/Loader/DDS/DDSSaver.h"
#include "scene/Loader/Intermediate/IntermImage.h"
namespace FG
{
/*
=================================================
_InitSamples
=================================================
*/
void Application::_InitSamples ()
{
_samples.push_back( Shaders::Shadertoy::Auroras );
_samples.push_back( Shaders::Shadertoy::AlienBeacon );
_samples.push_back( Shaders::Shadertoy::CloudFlight );
_samples.push_back( Shaders::Shadertoy::CloudyTerrain );
_samples.push_back( Shaders::Shadertoy::Canyon );
_samples.push_back( Shaders::Shadertoy::CanyonPass );
_samples.push_back( Shaders::Shadertoy::Dwarf );
_samples.push_back( Shaders::Shadertoy::DesertPassage );
_samples.push_back( Shaders::Shadertoy::DesertSand );
_samples.push_back( Shaders::Shadertoy::Glowballs );
_samples.push_back( Shaders::Shadertoy::GlowCity );
_samples.push_back( Shaders::Shadertoy::Generators );
_samples.push_back( Shaders::Shadertoy::Insect );
_samples.push_back( Shaders::Shadertoy::Luminescence );
_samples.push_back( Shaders::Shadertoy::Mesas );
_samples.push_back( Shaders::Shadertoy::NovaMarble );
_samples.push_back( Shaders::Shadertoy::Organix );
_samples.push_back( Shaders::Shadertoy::PlasmaGlobe );
_samples.push_back( Shaders::Shadertoy::SpaceEgg );
_samples.push_back( Shaders::Shadertoy::SculptureIII );
_samples.push_back( Shaders::Shadertoy::StructuredVolSampling );
_samples.push_back( Shaders::Shadertoy::ServerRoom );
_samples.push_back( Shaders::Shadertoy::Volcanic );
_samples.push_back( Shaders::ShadertoyVR::AncientMars );
_samples.push_back( Shaders::ShadertoyVR::Apollonian );
_samples.push_back( Shaders::ShadertoyVR::AtTheMountains );
_samples.push_back( Shaders::ShadertoyVR::Catacombs );
_samples.push_back( Shaders::ShadertoyVR::CavePillars );
_samples.push_back( Shaders::ShadertoyVR::DesertCanyon );
_samples.push_back( Shaders::ShadertoyVR::FrozenWasteland );
_samples.push_back( Shaders::ShadertoyVR::FractalExplorer );
_samples.push_back( Shaders::ShadertoyVR::IveSeen );
_samples.push_back( Shaders::ShadertoyVR::NebulousTunnel );
_samples.push_back( Shaders::ShadertoyVR::NightMist );
_samples.push_back( Shaders::ShadertoyVR::OpticalDeconstruction );
_samples.push_back( Shaders::ShadertoyVR::ProteanClouds );
_samples.push_back( Shaders::ShadertoyVR::PeacefulPostApocalyptic );
_samples.push_back( Shaders::ShadertoyVR::SirenianDawn );
_samples.push_back( Shaders::ShadertoyVR::SphereFBM );
_samples.push_back( Shaders::ShadertoyVR::Skyline );
_samples.push_back( Shaders::ShadertoyVR::Xyptonjtroz );
//_samples.push_back( Shaders::My::ConvexShape2D );
_samples.push_back( Shaders::My::OptimizedSDF );
//_samples.push_back( Shaders::My::PrecalculatedRays );
_samples.push_back( Shaders::My::VoronoiRecursion );
_samples.push_back( Shaders::My::ThousandsOfStars );
//_samples.push_back( Shaders::MyVR::ConvexShape3D );
//_samples.push_back( Shaders::MyVR::Building_1 );
//_samples.push_back( Shaders::MyVR::Building_2 );
}
/*
=================================================
constructor
=================================================
*/
Application::Application ()
{
}
/*
=================================================
destructor
=================================================
*/
Application::~Application ()
{
_view.reset();
if ( _videoRecorder )
{
CHECK( _videoRecorder->End() );
_videoRecorder.reset();
}
}
/*
=================================================
Initialize
=================================================
*/
bool Application::Initialize ()
{
{
AppConfig cfg;
cfg.surfaceSize = uint2(1024, 768);
cfg.windowTitle = "Shadertoy";
cfg.shaderDirectories = { FG_DATA_PATH "../shaderlib", FG_DATA_PATH };
cfg.dbgOutputPath = FG_DATA_PATH "_debug_output";
//cfg.vrMode = AppConfig::EVRMode::OpenVR;
//cfg.enableDebugLayers = false;
CHECK_ERR( _CreateFrameGraph( cfg ));
}
CHECK_ERR( _InitUI() );
_screenshotDir = FG_DATA_PATH "screenshots";
_view.reset( new ShaderView{_frameGraph} );
_InitSamples();
_viewMode = EViewMode::Mono;
_targetSize = _ScaleSurface( GetSurfaceSize(), _sufaceScaleIdx );
_ResetPosition();
_ResetOrientation();
_SetupCamera( 60_deg, { 0.1f, 100.0f });
_view->SetMode( _targetSize, _viewMode );
_view->SetCamera( GetFPSCamera() );
_view->SetFov( GetCameraFov() );
_view->SetImageFormat( _imageFormat );
return true;
}
/*
=================================================
OnKey
=================================================
*/
void Application::OnKey (StringView key, EKeyAction action)
{
BaseSample::OnKey( key, action );
if ( action == EKeyAction::Down )
{
if ( key == "[" ) --_nextSample; else
if ( key == "]" ) ++_nextSample;
if ( key == "R" ) _recompile = true;
if ( key == "T" ) _frameCounter = 0;
if ( key == "P" ) _ResetPosition();
if ( key == "F" ) { _skipLastTime = _freeze; _freeze = not _freeze; }
if ( key == "space" ) { _skipLastTime = _pause; _pause = not _pause; }
if ( key == "M" ) _vrMirror = not _vrMirror;
if ( key == "I" ) _makeScreenshot = true;
// profiling
if ( key == "G" ) _view->RecordShaderTrace( GetMousePos() / vec2{GetSurfaceSize().x, GetSurfaceSize().y} );
if ( key == "H" ) _view->RecordShaderProfiling( GetMousePos() / vec2{GetSurfaceSize().x, GetSurfaceSize().y} );
if ( key == "J" ) _showTimemap = not _showTimemap;
}
if ( action == EKeyAction::Up )
{
if ( key == "Y" ) _StartStopRecording();
}
}
/*
=================================================
DrawScene
=================================================
*/
bool Application::DrawScene ()
{
CHECK_ERR( _view );
if ( _pause )
{
std::this_thread::sleep_for(SecondsF{0.01f});
return true;
}
// select sample
if ( _currSample != _nextSample )
{
_nextSample = _nextSample % _samples.size();
_currSample = _nextSample;
_frameCounter = 0;
_ResetPosition();
_ResetOrientation();
_view->ResetShaders();
_samples[_currSample]( _view.get() );
}
// update camera & view mode
{
_UpdateCamera();
if ( IsActiveVR() )
{
_viewMode = EViewMode::HMD_VR;
_targetSize = _ScaleSurface( GetVRDevice()->GetRenderTargetDimension(), _vrSufaceScaleIdx );
_view->SetCamera( GetVRCamera() );
auto& vr_cont = GetVRDevice()->GetControllers();
auto left = vr_cont.find( ControllerID::LeftHand );
auto right = vr_cont.find( ControllerID::RightHand );
bool l_valid = left != vr_cont.end() and left->second.isValid;
bool r_valid = right != vr_cont.end() and right->second.isValid;
mat4x4 l_mvp, r_mvp;
if ( l_valid )
{
l_mvp = mat4x4(MatCast(left->second.pose));
l_mvp[3] = vec4(VecCast(left->second.position), 1.0);
}
if ( r_valid )
{
r_mvp = mat4x4(MatCast(right->second.pose));
r_mvp[3] = vec4(VecCast(right->second.position), 1.0);
}
_view->SetControllerPose( l_mvp, r_mvp, (l_valid ? 1 : 0) | (r_valid ? 2 : 0) );
}
else
{
_viewMode = EViewMode::Mono;
_targetSize = _ScaleSurface( GetSurfaceSize(), _sufaceScaleIdx );
_view->SetCamera( GetFPSCamera() );
}
_view->SetMode( _targetSize, _viewMode );
_view->SetMouse( GetMousePos() / vec2(VecCast(GetSurfaceSize())), IsMousePressed() );
_view->SetSliderState( _sliders );
}
// draw
Task task;
RawImageID image_l, image_r;
CommandBuffer cmdbuf = _frameGraph->Begin( CommandBufferDesc{ EQueueType::Graphics });
CHECK_ERR( cmdbuf );
if ( _recompile )
{
_recompile = false;
_view->Recompile( cmdbuf );
}
if ( _viewMode != EViewMode::HMD_VR and _showTimemap )
cmdbuf->BeginShaderTimeMap( _targetSize, EShaderStages::Fragment );
// draw shader viewer
{
const auto time = TimePoint_t::clock::now();
if ( _frameCounter == 0 )
_shaderTime = {};
const SecondsF app_dt = std::chrono::duration_cast<SecondsF>( _shaderTime );
const SecondsF frame_dt = std::chrono::duration_cast<SecondsF>( time - _lastUpdateTime );
std::tie(task, image_l, image_r) = _view->Draw( cmdbuf, _frameCounter, app_dt, frame_dt );
CHECK_ERR( task and image_l );
if ( _skipLastTime )
{
_skipLastTime = false;
}
else
if ( not _freeze )
{
++_frameCounter;
_shaderTime += std::chrono::duration_cast<Microsec>(time - _lastUpdateTime);
}
_lastUpdateTime = time;
}
// present
if ( _viewMode == EViewMode::HMD_VR )
{
if ( _vrMirror )
cmdbuf->AddTask( Present{ GetSwapchain(), image_l }.DependsOn( task ));
CHECK_ERR( _frameGraph->Execute( cmdbuf ));
CHECK_ERR( _frameGraph->Flush() );
_VRPresent( GetVulkan().GetVkQueues()[0], image_l, image_r, false );
}
else
{
if ( _showTimemap )
task = cmdbuf->EndShaderTimeMap( image_l, Default, Default, {task} );
const auto& desc = _frameGraph->GetDescription( image_l );
const uint2 point = { uint((desc.dimension.x * GetMousePos().x) / GetSurfaceSize().x + 0.5f),
uint((desc.dimension.y * GetMousePos().y) / GetSurfaceSize().y + 0.5f) };
// read pixel
if ( point.x < desc.dimension.x and point.y < desc.dimension.y )
{
task = cmdbuf->AddTask( ReadImage{}.SetImage( image_l, point, uint2{1,1} )
.SetCallback( [this, point] (const ImageView &view) { _OnPixelReadn( point, view ); })
.DependsOn( task ));
}
// add video frame
if ( _videoRecorder )
{
task = cmdbuf->AddTask( ReadImage{}.SetImage( image_l, uint2(0), _targetSize )
.SetCallback( [this] (const ImageView &view)
{
if ( _videoRecorder )
CHECK( _videoRecorder->AddFrame( view ));
})
.DependsOn( task ));
}
else
// make screenshot
if ( _makeScreenshot )
{
_makeScreenshot = false;
task = cmdbuf->AddTask( ReadImage{}.SetImage( image_l, uint2(0), _targetSize )
.SetCallback( [this] (const ImageView &view)
{
_SaveImage( view );
})
.DependsOn( task ));
}
// copy to swapchain image
{
RawImageID sw_image = cmdbuf->GetSwapchainImage( GetSwapchain() );
uint2 img_dim = _frameGraph->GetDescription( image_l ).dimension.xy();
uint2 sw_dim = _frameGraph->GetDescription( sw_image ).dimension.xy();
task = cmdbuf->AddTask( BlitImage{}.From( image_l ).To( sw_image ).SetFilter( EFilter::Linear )
.AddRegion( {}, int2(0), int2(img_dim), {}, int2(0), int2(sw_dim) )
.DependsOn( task ));
_DrawUI( cmdbuf, sw_image, {task} );
}
CHECK_ERR( _frameGraph->Execute( cmdbuf ));
CHECK_ERR( _frameGraph->Flush() );
}
_SetLastCommandBuffer( cmdbuf );
return true;
}
/*
=================================================
_OnPixelReadn
=================================================
*/
void Application::_OnPixelReadn (const uint2 &, const ImageView &view)
{
view.Load( uint3{0,0,0}, OUT _selectedPixel );
}
/*
=================================================
_StartStopRecording
=================================================
*/
void Application::_StartStopRecording ()
{
if ( _videoRecorder )
{
CHECK( _videoRecorder->End() );
_videoRecorder.reset();
}
else
{
#if defined(FG_ENABLE_FFMPEG)
_videoRecorder.reset( new FFmpegVideoRecorder{} );
#endif
if ( _videoRecorder )
{
IVideoRecorder::Config cfg;
cfg.format = EVideoFormat::YUV420P;
cfg.codec = EVideoCodec::H264;
cfg.hwAccelerated= true;
cfg.preset = EVideoPreset::Fast;
cfg.bitrate = 7552ull << 10;
cfg.fps = 30;
cfg.size = _targetSize;
String vname = "video"s << _videoRecorder->GetExtension( cfg.codec );
CHECK( _videoRecorder->Begin( cfg, vname ));
}
}
}
/*
=================================================
_ResetPosition
=================================================
*/
void Application::_ResetPosition ()
{
GetFPSCamera().SetPosition({ 0.0f, 0.0f, 0.0f });
}
/*
=================================================
_ResetOrientation
=================================================
*/
void Application::_ResetOrientation ()
{
GetFPSCamera().SetRotation( Quat_Identity );
}
/*
=================================================
_SaveImage
=================================================
*/
void Application::_SaveImage (const ImageView &view)
{
#ifdef FS_HAS_FILESYSTEM
FS::create_directory( FS::path{ _screenshotDir });
#endif
#ifdef FS_HAS_FILESYSTEM
const auto IsExists = [] (StringView path) { return FS::exists(FS::path{ path }); };
#else
const auto IsExists = [] (StringView path) { return false; }; // TODO
#endif
#ifdef FG_ENABLE_DEVIL
const char ext[] = ".png";
const auto SaveImage = [] (StringView fname, const IntermImagePtr &image)
{
DevILSaver saver;
return saver.SaveImage( fname, image );
};
#else
const char ext[] = ".dds";
const auto SaveImage = [] (StringView fname, const IntermImagePtr &image)
{
DDSSaver saver;
return saver.SaveImage( fname, image );
};
#endif
String fname;
const auto BuildName = [this, &fname, &ext] (uint index)
{
fname = String(_screenshotDir) << "/scr_" << ToString(index) << ext;
};
auto image = MakeShared<IntermImage>( view );
uint min_index = 0;
uint max_index = 1;
const uint step = 100;
for (; min_index < max_index;)
{
BuildName( max_index );
if ( not IsExists( fname ))
break;
min_index = max_index;
max_index += step;
}
for (uint index = min_index; index <= max_index; ++index)
{
BuildName( index );
if ( IsExists( fname ))
continue;
CHECK( SaveImage( fname, image ));
FG_LOGI( "screenshot saved to '"s << fname << "'" );
break;
}
}
/*
=================================================
OnUpdateUI
=================================================
*/
void Application::OnUpdateUI ()
{
#ifdef FG_ENABLE_IMGUI
const ImVec4 red_col { 0.5f, 0.0f, 0.0f, 1.0f };
const ImVec4 green_col { 0.0f, 0.7f, 0.0f, 1.0f };
// camera
{
ImGui::Text( "W/S - move camera forward/backward" );
ImGui::Text( "A/D - move camera left/right" );
ImGui::Text( "V/C - move camera up/down" );
ImGui::Text( "Y - show/hide UI" );
}
ImGui::Separator();
// shader
{
ImGui::Text( "Switch shader" );
if ( ImGui::Button( " << ##PrevShader" ))
--_nextSample;
ImGui::SameLine();
if ( ImGui::Button( " >> ##NextShader" ))
++_nextSample;
// pause
{
String text;
if ( _freeze ) {
text = "Resume (F)";
ImGui::PushStyleColor( ImGuiCol_Button, red_col );
} else {
text = "Pause (F)";
ImGui::PushStyleColor( ImGuiCol_Button, green_col );
}
if ( ImGui::Button( text.c_str() ))
{
_skipLastTime = _freeze;
_freeze = not _freeze;
}
ImGui::PopStyleColor(1);
}
// pause rendering
if ( ImGui::Button( "Stop rendering (space)" ))
{
_skipLastTime = _pause;
_pause = not _pause;
}
if ( ImGui::Button( "Reload (R)" ))
_recompile = true;
if ( ImGui::Button( "Restart (T)" ))
_frameCounter = 0;
if ( ImGui::Button( "Reset position (P)" ))
_ResetPosition();
ImGui::SameLine();
if ( ImGui::Button( "Reset orientation" ))
_ResetOrientation();
const float old_fov = float(GetCameraFov());
float new_fov = glm::degrees( old_fov );
ImGui::Text( "Camera FOV (for some shaders)" );
ImGui::SliderFloat( "##FOV", &new_fov, 10.0f, 110.0f );
new_fov = glm::radians( round( new_fov ));
if ( not Equals( new_fov, old_fov, _fovStep ))
{
_SetupCamera( Rad{ new_fov }, GetViewRange() );
_view->SetFov( Rad{ new_fov });
}
int surf = _sufaceScaleIdx;
ImGui::Text( "Surface scale" );
ImGui::SliderInt( "##SurfaceScaleSlider", INOUT &surf, -2, 1, _SurfaceScaleName( _sufaceScaleIdx ));
// can't change surface scale when capturing video
if ( not _videoRecorder )
_sufaceScaleIdx = surf;
}
ImGui::Separator();
// custom sliders
{
ImGui::Text( "Custom sliders:" );
ImGui::SliderFloat( "##CustomSlider0", INOUT &_sliders[0], 0.0f, 1.0f );
ImGui::SliderFloat( "##CustomSlider1", INOUT &_sliders[1], 0.0f, 1.0f );
ImGui::SliderFloat( "##CustomSlider2", INOUT &_sliders[2], 0.0f, 1.0f );
ImGui::SliderFloat( "##CustomSlider3", INOUT &_sliders[3], 0.0f, 1.0f );
}
ImGui::Separator();
// capture
{
// video
{
String text;
if ( _videoRecorder ) {
text = "Stop capture (U)";
ImGui::PushStyleColor( ImGuiCol_Button, red_col );
} else {
text = "Start capture (U)";
ImGui::PushStyleColor( ImGuiCol_Button, green_col );
}
if ( ImGui::Button( text.c_str() ))
_StartStopRecording();
ImGui::PopStyleColor(1);
}
if ( ImGui::Button( "Screenshot (I)" ))
_makeScreenshot = true;
}
ImGui::Separator();
// debugger
{
ImGui::Text( "G - run shader debugger for pixel under cursor" );
ImGui::Text( "H - run shader profiler for pixel under cursor" );
if ( _showTimemap )
ImGui::PushStyleColor( ImGuiCol_Button, red_col );
else
ImGui::PushStyleColor( ImGuiCol_Button, green_col );
if ( ImGui::Button( "Timemap" ))
_showTimemap = not _showTimemap;
ImGui::PopStyleColor(1);
}
ImGui::Separator();
// params
{
ImGui::Text( ("position: "s << ToString( GetCamera().transform.position )).c_str() );
ImGui::Text( ("rotation: "s << ToString( GetCamera().transform.orientation )).c_str() );
ImGui::Text( ("mouse coord: "s << ToString( GetMousePos() )).c_str() );
ImGui::Text( ("pixel color: "s << ToString( _selectedPixel )).c_str() );
}
#endif
}
} // FG
| 27.282707 | 115 | 0.604806 | [
"transform"
] |
76e2c7b88c43ef3f8b261c1a4fe1b70d4c370ea4 | 17,751 | cpp | C++ | main/source/mod/AvHTechTree.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 27 | 2015-01-05T19:25:14.000Z | 2022-03-20T00:34:34.000Z | main/source/mod/AvHTechTree.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 9 | 2015-01-14T06:51:46.000Z | 2021-03-19T12:07:18.000Z | main/source/mod/AvHTechTree.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 5 | 2015-01-11T10:31:24.000Z | 2021-01-06T01:32:58.000Z | //======== (C) Copyright 2002 Charles G. Cleveland All rights reserved. =========
//
// The copyright to the contents herein is the property of Charles G. Cleveland.
// The contents may be used and/or copied only with the written permission of
// Charles G. Cleveland, or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: AvHTechTree.cpp $
// $Date: 2002/09/23 22:36:08 $
//
//===============================================================================
#include "AvHTechTree.h"
bool AvHSHUGetIsResearchTech(AvHMessageID inMessageID);
AvHTechTree::AvHTechTree(void) { Init(); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AvHTechTree::AvHTechTree(const AvHTechTree& other)
{
//because pointers in mNodesByMsg are deleted by
//destruction, we need to make our own copy on
//construction
TechNodeMap::const_iterator current, end = other.mNodesByMsg.end();
for( current = other.mNodesByMsg.begin(); current != end; ++current )
{
mNodesByMsg[current->first] = current->second->clone();
}
Init();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AvHTechTree::~AvHTechTree(void) { Clear(); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::Init(void)
{
#ifdef SERVER
BALANCE_LISTENER(this);
compoundChangeInProgress = false;
#endif
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::swap(AvHTechTree& other)
{
TechNodeMap tempMap = mNodesByMsg; mNodesByMsg = other.mNodesByMsg; other.mNodesByMsg = tempMap;
TechIDMap tempIDMap = mNodesByTech; mNodesByTech = other.mNodesByTech; other.mNodesByTech = tempIDMap;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::InsertNode(const AvHTechNode* inTechNode)
{
this->RemoveNode(inTechNode->getMessageID()); //remove old node to prevent memory leak
this->mNodesByMsg[inTechNode->getMessageID()] = inTechNode->clone();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::RemoveNode(const AvHMessageID inMessageID)
{
AvHTechNode* node = GetNode(inMessageID);
if( node )
{
mNodesByMsg.erase(node->getMessageID());
//remove from tech map if it's a match before we delete it!
TechIDMap::iterator item = mNodesByTech.find(node->getTechID());
if( item != mNodesByTech.end() && item->second == node )
{ mNodesByTech.erase(item); }
delete node;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::Clear(void)
{
TechNodeMap::iterator current, end = mNodesByMsg.end();
for( current = mNodesByMsg.begin(); current != end; ++current )
{
delete current->second;
}
mNodesByMsg.clear();
mNodesByTech.clear();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AvHTechNode* AvHTechTree::GetNode(const AvHMessageID message)
{
AvHTechNode* returnVal = NULL;
TechNodeMap::iterator item = mNodesByMsg.find(message);
if( item != mNodesByMsg.end() )
{ returnVal = item->second; }
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const AvHTechNode* AvHTechTree::GetNode(const AvHMessageID message) const
{
const AvHTechNode* returnVal = NULL;
TechNodeMap::const_iterator item = mNodesByMsg.find(message);
if( item != mNodesByMsg.end() )
{ returnVal = item->second; }
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AvHTechNode* AvHTechTree::GetNodeByTech(const AvHTechID inTech)
{
AvHTechNode* returnVal = NULL;
TechIDMap::iterator item = mNodesByTech.find(inTech);
if( item != mNodesByTech.end() )
{ returnVal = item->second; }
else
{
TechNodeMap::iterator current, end = mNodesByMsg.end();
for( current = mNodesByMsg.begin(); current != end; ++current )
{
if( current->second->getTechID() == inTech )
{
mNodesByTech[inTech] = current->second;
returnVal = current->second;
break;
}
}
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const AvHTechNode* AvHTechTree::GetNodeByTech(const AvHTechID inTech) const
{
const AvHTechNode* returnVal = NULL;
TechIDMap::const_iterator item = mNodesByTech.find(inTech);
if( item != mNodesByTech.end() )
{ returnVal = item->second; }
else
{
TechNodeMap::const_iterator current, end = mNodesByMsg.end();
for( current = mNodesByMsg.begin(); current != end; ++current )
{
if( current->second->getTechID() == inTech )
{
mNodesByTech[inTech] = current->second;
returnVal = current->second;
break;
}
}
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const int AvHTechTree::GetSize(void) const
{
return (int)mNodesByTech.size();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetAllowMultiples(const AvHMessageID inMessageID) const
{
const AvHTechNode* Node = GetNode(inMessageID);
return (Node != NULL) && Node->getAllowMultiples();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetIsMessageInTechTree(const AvHMessageID inMessageID) const
{
const AvHTechNode* Node = GetNode(inMessageID);
return (Node != NULL);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetIsMessageAvailable(const AvHMessageID inMessageID) const
{
bool returnVal = true;
const AvHTechNode* Subnode;
const AvHTechNode* Node = GetNode(inMessageID);
// : 73
// HACK to bypass the node checks when issuing one of the CC UI impulses
// Could probably be reworked prettier by assigning nodes to each of these
// messages, but this will have to do for now
if (inMessageID == COMMANDER_SELECTALL ||
inMessageID == COMMANDER_NEXTAMMO ||
inMessageID == COMMANDER_NEXTHEALTH ||
inMessageID == COMMANDER_NEXTIDLE ||
inMessageID == GROUP_SELECT_1 ||
inMessageID == GROUP_SELECT_2 ||
inMessageID == GROUP_SELECT_3 ||
inMessageID == GROUP_SELECT_4 ||
inMessageID == GROUP_SELECT_5)
return true;
// :
if( Node == NULL ) //not found
{ returnVal = false; }
else if( Node->getIsResearched() && !Node->getAllowMultiples() ) //can only research once?
{ returnVal = false; }
else
{
AvHTechID prereq = Node->getPrereqTechID1();
if( prereq != TECH_NULL && ( (Subnode = GetNodeByTech(prereq)) == NULL || !Subnode->getIsResearched() ) )
{ returnVal = false; }
else
{
prereq = Node->getPrereqTechID2();
if( prereq != TECH_NULL && ( (Subnode = GetNodeByTech(prereq)) == NULL || !Subnode->getIsResearched() ) )
{ returnVal = false; }
}
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetIsMessageAvailableForSelection(const AvHMessageID inMessageID, const EntityListType& inSelection) const
{
return GetIsMessageAvailable(inMessageID);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetIsTechResearched(AvHTechID inTech) const
{
const AvHTechNode* Node = GetNodeByTech(inTech);
return (Node != NULL) && Node->getIsResearched();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::SetFirstNodeWithTechResearchState(const AvHTechID inTech, bool inState)
{
bool returnVal = false;
AvHTechNode* Node = GetNodeByTech(inTech);
if( Node != NULL )
{
Node->setResearchState(inState);
returnVal = true;
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetMessageForTech(const AvHTechID inTech, AvHMessageID& outMessageID) const
{
bool returnVal = false;
const AvHTechNode* Node = GetNodeByTech(inTech);
if( Node != NULL )
{
outMessageID = Node->getMessageID();
returnVal = true;
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AvHMessageID AvHTechTree::GetNextMessageNeededFor(const AvHMessageID inMessageID) const
{
//perform depth first search for item that hasn't been researched but can be; returns
//original ID if no match is found... would be better to return boolean false with an
//output AvHMessageID specified as a parameter.
AvHMessageID returnVal = inMessageID;
const AvHTechNode* Node = GetNode(inMessageID);
bool prereq1_researched = false;
if( Node != NULL && !Node->getIsResearched() )
{
vector<const AvHTechNode*> ParentStack;
ParentStack.push_back(Node);
const AvHTechNode* Child;
AvHTechID prereq;
while(!ParentStack.empty())
{
Node = ParentStack.back();
ParentStack.pop_back();
//First child
prereq1_researched = false;
prereq = Node->getPrereqTechID1();
if( prereq == TECH_NULL )
{ prereq1_researched = true; }
else
{
Child = GetNodeByTech(prereq);
if( Child != NULL )
{
if( Child->getIsResearched() )
{ prereq1_researched = true; }
else
{ ParentStack.push_back(Child); }
}
}
//Second child
prereq = Node->getPrereqTechID2();
if( prereq == TECH_NULL && prereq1_researched )
{
returnVal = Node->getMessageID();
break;
}
else
{
Child = GetNodeByTech(prereq);
if( Child != NULL )
{
if( Child->getIsResearched() )
{
if( prereq1_researched )
{
returnVal = Node->getMessageID();
break;
}
}
else
{ ParentStack.push_back(Child); }
}
}
}
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::GetResearchNodesDependentOn(AvHTechID inTechID, TechNodeMap& outTechNodes) const
{
//move up tree from supplied base tech; this won't be a cheap operation - worst case is (tree size)^2
if(inTechID != TECH_NULL)
{
TechNodeMap::const_iterator current, end = mNodesByMsg.end();
for( current = mNodesByMsg.begin(); current != end; ++current )
{
if( !AvHSHUGetIsResearchTech(current->first) || current->second->getTechID() == TECH_NULL )
{ continue; }
if( current->second->getPrereqTechID1() == inTechID || current->second->getPrereqTechID2() == inTechID )
{
outTechNodes[current->first] = current->second; //don't clone here, caller not responsible for deletion
GetResearchNodesDependentOn(current->second->getTechID(), outTechNodes); //recurse
}
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetTechForMessage(const AvHMessageID inMessageID, AvHTechID& outTechID) const
{
bool returnVal = false;
const AvHTechNode* Node = GetNode(inMessageID);
if( Node != NULL )
{
outTechID = Node->getTechID();
returnVal = true;
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetPrequisitesForMessage(const AvHMessageID inMessageID, AvHTechID& outTech1, AvHTechID& outTech2) const
{
bool returnVal = false;
const AvHTechNode* Node = GetNode(inMessageID);
if( Node != NULL )
{
outTech1 = Node->getPrereqTechID1();
outTech2 = Node->getPrereqTechID2();
returnVal = (outTech1 != TECH_NULL) || (outTech2 != TECH_NULL);
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::GetResearchInfo(AvHMessageID inMessageID, bool& outIsResearchable, int& outCost, float& outTime) const
{
bool returnVal = false;
const AvHTechNode* Node = GetNode(inMessageID);
if( Node != NULL )
{
outIsResearchable = Node->getIsResearchable();
outCost = Node->getCost();
outTime = Node->getBuildTime();
returnVal = true;
}
else
{
outIsResearchable = false;
outCost = -1;
outTime = -1;
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::SetIsResearchable(AvHMessageID inMessageID, bool inState)
{
bool returnVal = false;
AvHTechNode* Node = GetNode(inMessageID);
if( Node != NULL )
{
Node->setResearchable(inState);
returnVal = true;
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::SetResearchDone(AvHMessageID inMessageID, bool inState)
{
bool returnVal = false;
AvHTechNode* Node = GetNode(inMessageID);
if( Node != NULL )
{
Node->setResearchState(inState);
returnVal = true;
}
return returnVal;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::TriggerAddTech(AvHTechID inTechID)
{
AvHTechNode* Node = GetNodeByTech(inTechID);
if( Node != NULL )
{
Node->setResearchState(true);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::TriggerRemoveTech(AvHTechID inTechID)
{
AvHTechNode* Node = GetNodeByTech(inTechID);
if( Node != NULL )
{
Node->setResearchState(false);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AvHTechTree::GetDelta(const AvHTechTree& other, MessageIDListType& delta) const
{
delta.clear();
TechNodeMap::const_iterator current = mNodesByMsg.begin();
TechNodeMap::const_iterator end = mNodesByMsg.end();
TechNodeMap::const_iterator other_current = other.mNodesByMsg.begin();
TechNodeMap::const_iterator other_end = other.mNodesByMsg.end();
while( current != end && other_current != other_end )
{
if( current->first < other_current->first )
{
delta.push_back(current->first);
++current;
continue;
}
if( current->first > other_current->first )
{
delta.push_back(current->first);
++other_current;
continue;
}
if( *current->second != *other_current->second )
{
delta.push_back(current->first);
}
++current;
++other_current;
}
while( current != end )
{
delta.push_back(current->first);
++current;
}
while( other_current != other_end )
{
delta.push_back(other_current->first);
++other_current;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::operator!=(const AvHTechTree& inTree) const
{
return !this->operator==(inTree);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool AvHTechTree::operator==(const AvHTechTree& inTree) const
{
return mNodesByMsg == inTree.mNodesByMsg;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AvHTechTree& AvHTechTree::operator=(const AvHTechTree& inTree)
{
AvHTechTree temp(inTree);
swap(temp);
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ifdef AVH_SERVER
bool AvHTechTree::shouldNotify(const string& name, const BalanceValueType type) const { return true; }
void AvHTechTree::balanceCleared(void) const {}
void AvHTechTree::balanceValueInserted(const string& name, const float value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueInserted(const string& name, const int value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueInserted(const string& name, const string& value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueRemoved(const string& name, const float old_value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueRemoved(const string& name, const int old_value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueRemoved(const string& name, const string& old_value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueChanged(const string& name, const float old_value, const float new_value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueChanged(const string& name, const int old_value, const int new_value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceValueChanged(const string& name, const string& old_value, const string& default_value) const
{
if( !compoundChangeInProgress )
{ const_cast<AvHTechTree*>(this)->processBalanceChange(); }
}
void AvHTechTree::balanceStartCompoundChange(void) const
{ compoundChangeInProgress = true; }
void AvHTechTree::balanceEndCompoundChange(void) const
{ compoundChangeInProgress = false; }
#include "../dlls/extdll.h"
#include "../dlls/util.h"
#include "AvHGamerules.h"
void AvHTechTree::processBalanceChange(void)
{
// Run through our tech nodes and update cost and build time
TechNodeMap::iterator current, end = mNodesByMsg.end();
for( current = mNodesByMsg.begin(); current != end; ++current )
{
current->second->setBuildTime(GetGameRules()->GetBuildTimeForMessageID(current->first));
current->second->setCost(GetGameRules()->GetCostForMessageID(current->first));
}
}
#endif | 28.676898 | 125 | 0.595178 | [
"vector"
] |
76ecd6de7b68721ad03ed3d7bd19b74999c4197b | 298 | cpp | C++ | Practica Semanal 7/E.cpp | Tresillo2017/IOE2 | 6d191f0085a67b0b187851ad2d73b61040b74e87 | [
"MIT"
] | null | null | null | Practica Semanal 7/E.cpp | Tresillo2017/IOE2 | 6d191f0085a67b0b187851ad2d73b61040b74e87 | [
"MIT"
] | null | null | null | Practica Semanal 7/E.cpp | Tresillo2017/IOE2 | 6d191f0085a67b0b187851ad2d73b61040b74e87 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int suma = 0;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
suma+= i*j;
}
}
cout << suma;
} | 15.684211 | 37 | 0.456376 | [
"vector"
] |
76f9d0c15d1eeed7507d956cc34f366a616266f6 | 616 | cpp | C++ | examples/surfaces/fsurf/fsurf_8.cpp | dendisuhubdy/matplotplusplus | 3781773832306e5571376f29f0c1d1389eb82af0 | [
"MIT"
] | 1 | 2022-03-22T11:09:19.000Z | 2022-03-22T11:09:19.000Z | examples/surfaces/fsurf/fsurf_8.cpp | dendisuhubdy/matplotplusplus | 3781773832306e5571376f29f0c1d1389eb82af0 | [
"MIT"
] | null | null | null | examples/surfaces/fsurf/fsurf_8.cpp | dendisuhubdy/matplotplusplus | 3781773832306e5571376f29f0c1d1389eb82af0 | [
"MIT"
] | 1 | 2022-03-22T11:46:39.000Z | 2022-03-22T11:46:39.000Z | #include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
auto funx = [](double s, double t) { return sin(s); };
auto funy = [](double s, double t) { return cos(s); };
auto funz = [](double s, double t) { return t / 10 * sin(1. / s); };
tiledlayout(2, 1);
nexttile();
fsurf(funx, funy, funz, std::array<double, 2>{-5, +5}, "", 20);
view(-172, 25);
title("Decreased Mesh Density");
nexttile();
fsurf(funx, funy, funz, std::array<double, 2>{-5, +5}, "", 80);
view(-172, 25);
title("Increased Mesh Density");
wait();
return 0;
} | 25.666667 | 72 | 0.555195 | [
"mesh"
] |
76fc29697243e7054618ed58fb202e1cf9cc2fe9 | 697 | cpp | C++ | src/menu/MainMenu.cpp | wwizz/example_snake_cpp | 2e8420407dd1bc70e1d985ee2438ad340aeb32ee | [
"MIT"
] | null | null | null | src/menu/MainMenu.cpp | wwizz/example_snake_cpp | 2e8420407dd1bc70e1d985ee2438ad340aeb32ee | [
"MIT"
] | null | null | null | src/menu/MainMenu.cpp | wwizz/example_snake_cpp | 2e8420407dd1bc70e1d985ee2438ad340aeb32ee | [
"MIT"
] | null | null | null | #include "Action.h"
#include "MainMenu.h"
MainMenu::MainMenu() :
Menu(std::string("MainMenu"), std::vector<std::string> { "Start Game", "Quit"}) {
}
MainMenu::~MainMenu() {
}
Action MainMenu::Process(InputCommand command) {
switch(command) {
case InputCommand_Escape: break;
case InputCommand_Option1:return Action_Play;
case InputCommand_Option2:return Action_Quit;
case InputCommand_Option3:break;
case InputCommand_Option4:break;
case InputCommand_Option5:break;
case InputCommand_None:break;
case InputCommand_Left:break;
case InputCommand_Right:break;
case InputCommand_Up:break;
case InputCommand_Down:break;
}
return Action_None;
}
| 24.892857 | 85 | 0.731707 | [
"vector"
] |
76fd3a3b601145afd554440d8684a68533d15562 | 5,248 | cpp | C++ | server/mini-client/preasure_test.cpp | ArCan314/Memo | 06778e9ecf01c57abbfa7198b40da7cd13aecd5a | [
"MIT"
] | null | null | null | server/mini-client/preasure_test.cpp | ArCan314/Memo | 06778e9ecf01c57abbfa7198b40da7cd13aecd5a | [
"MIT"
] | null | null | null | server/mini-client/preasure_test.cpp | ArCan314/Memo | 06778e9ecf01c57abbfa7198b40da7cd13aecd5a | [
"MIT"
] | null | null | null | #include <boost/asio.hpp>
#include <boost/locale.hpp>
#include <string>
#include <vector>
#include <iostream>
#include <locale>
#include <codecvt>
#include <cstring>
#include <cstdlib>
#include <random>
#include <chrono>
#include <thread>
#include "../include/cpp-base64/base64.h"
using namespace boost::asio;
static const char *kHost = "localhost";
static const char *kPort = "12345";
static constexpr std::size_t kRanVecSize = 102400;
std::string random_strs[kRanVecSize];
std::string GenRandomStr()
{
constexpr char dict[] = "1234567890-=qwertyuiop[]asdfghjkl;'zxcvbnm,./\\`~!@#$%^&*()_+QWERTYUIOP{}ASDFGHJKL:|ZXCVBNM<>?";
std::default_random_engine dre(std::clock() +
std::hash<std::thread::id>()(std::this_thread::get_id()));
std::uniform_int_distribution<int> uid(1, 512);
std::uniform_int_distribution<int> dict_sel(0, sizeof(dict) - 2);
int len = uid(dre);
std::string res(len, '\0');
for (int i = 0; i < len; i++)
{
res[i] = dict[dict_sel(dre)];
}
return res;
}
void InitRandomVec()
{
for (int i = 0; i < kRanVecSize; i++)
{
random_strs[i] = GenRandomStr();
}
}
std::string GenRandom()
{
std::default_random_engine dre(std::clock() +
std::hash<std::thread::id>()(std::this_thread::get_id()));
std::uniform_int_distribution<int> uid(0, 10240 - 1);
return random_strs[uid(dre)];
// return GenRandomStr();
}
std::string GenLogIn()
{
constexpr char pre[] = "{\"EventGroup\":\"Account\",\"Event\":\"CreateAccount\",\"ID\":\"";
constexpr char mid[] = "\",\"Pswd\":\"";
constexpr char tail[] = "\"}";
std::string id = GenRandom();
std::string pswd = GenRandom();
return std::string(pre) + id + mid + pswd + tail;
}
std::string GenCreate()
{
constexpr char pre[] = "{\"EventGroup\":\"Account\",\"Event\":\"LogIn\",\"ID\":\"";
constexpr char mid[] = "\",\"Pswd\":\"";
constexpr char tail[] = "\"}";
std::string id = GenRandom();
std::string pswd = GenRandom();
return std::string(pre) + id + mid + pswd + tail;
}
std::string GenClient()
{
constexpr char pre[] = "{\"EventGroup\":\"Data\",\"Event\":\"SyncFromClient\",\"ID\":\"";
constexpr char tail[] = "\"}";
std::string id = GenRandom();
return std::string(pre) + id + tail;
}
std::string GenServer()
{
constexpr char pre[] = "{\"EventGroup\":\"Data\",\"Event\":\"SyncFromServer\",\"ID\":\"";
constexpr char tail[] = "\"}";
std::string id = GenRandom();
return std::string(pre) + id + tail;
}
std::string GenStr()
{
enum {LOGIN, CREATE, SYNC_CLIENT, SYNC_SERVER, RANDOM};
static constexpr int max_option_no = RANDOM;
std::default_random_engine dre(std::clock() +
std::hash<std::thread::id>()(std::this_thread::get_id()));
std::uniform_int_distribution<int> uid(0, max_option_no);
std::string res;
switch (uid(dre))
{
case LOGIN:
res = GenLogIn();
break;
case CREATE:
res = GenCreate();
break;
case SYNC_CLIENT:
res = GenClient();
break;
case SYNC_SERVER:
res = GenServer();
break;
case RANDOM:
res = GenRandom();
break;
default:
assert(1 == 0);
}
return res;
}
constexpr int max_request = 20000;
void RunRandomSender()
{
try
{
io_context ioc;
ip::tcp::resolver resolver(ioc);
auto ep = resolver.resolve(ip::tcp::v4(), kHost, kPort);
ip::tcp::socket socket(ioc);
socket.open(ip::tcp::v4());
socket.set_option(ip::tcp::socket::reuse_address(true));
connect(socket, ep);
for (int req_num = 0; req_num < max_request; req_num++)
{
try
{
std::string request = GenStr();
// std::cout << "raw: " << request << std::endl;
// request = ToUTF8(request);
// std::cout << "UTF8" << request << std::endl;
request = base64_encode(reinterpret_cast<const unsigned char *>(request.c_str()), request.size());
// std::cout << "b64: " << request << std::endl;
write(socket, buffer(request, request.size()));
std::vector<unsigned char> buf(10240);
std::string reply;
auto len = socket.read_some(buffer(buf));
for (int i = 0; i < len; i++)
reply.push_back(buf[i]);
// std::cout << "b64_reply: " << reply << std::endl;
//std::cout << "reply: " << base64_decode(reply) << std::endl;
}
catch (const std::exception & e)
{
std::cerr << e.what() << std::endl;
}
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
}
}
class Timer
{
public:
using RetType = unsigned long long;
Timer() = default;
void start() noexcept
{
start_ = std::chrono::steady_clock::now().time_since_epoch();
}
void end() noexcept
{
end_ = std::chrono::steady_clock::now().time_since_epoch();
}
RetType count() const noexcept
{
return (end_ - start_).count();
}
private:
std::chrono::nanoseconds start_;
std::chrono::nanoseconds end_;
};
int main()
{
std::cout << "Init Random Vec" << std::endl;
InitRandomVec();
std::vector<std::thread> tvec;
constexpr int max_tvec_size = 4;
Timer tm;
std::cout << "Start timer" << std::endl;
tm.start();
for (int i = 0; i < max_tvec_size; i++)
{
tvec.emplace_back(RunRandomSender);
}
for (int i = 0; i < tvec.size(); i++)
{
tvec[i].join();
}
tm.end();
std::cout << "Send " << (max_tvec_size * max_request) << " requests in " <<
tm.count() / 1000000.0 << " ms." << std::endl;
return 0;
} | 22.42735 | 122 | 0.620427 | [
"vector"
] |
0a014d621c165f78fe9c6152405307313fef8692 | 6,922 | cpp | C++ | PrioEngineStaticLibrary/Engine/Rain.cpp | SamConnolly94/PrioEngineStaticLibrary | f9be61923a08a3a6e4d3e09a11f0f9479975ab4a | [
"Apache-2.0"
] | null | null | null | PrioEngineStaticLibrary/Engine/Rain.cpp | SamConnolly94/PrioEngineStaticLibrary | f9be61923a08a3a6e4d3e09a11f0f9479975ab4a | [
"Apache-2.0"
] | null | null | null | PrioEngineStaticLibrary/Engine/Rain.cpp | SamConnolly94/PrioEngineStaticLibrary | f9be61923a08a3a6e4d3e09a11f0f9479975ab4a | [
"Apache-2.0"
] | null | null | null | #include "Rain.h"
CRain::CRain()
{
mpRandomResourceView = nullptr;
}
CRain::~CRain()
{
}
bool CRain::Initialise(ID3D11Device* device, std::string rainTexture, unsigned int numberOfParticles)
{
//Shutdown();
mFirstRun = true;
mNumberOfParticles = numberOfParticles;
mEmitterDirection = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
mpRainDropTexture = new CTexture();
if (!mpRainDropTexture->Initialise(device, rainTexture))
{
logger->GetInstance().WriteLine("Failed to initialise the texture with name " + rainTexture + " in rain object.");
return false;
}
mpRandomResourceView = CreateRandomTexture(device);
if (mpRandomResourceView == nullptr)
{
logger->GetInstance().WriteLine("Failed to create the random texture in rain object.");
return false;
}
if (!InitialiseBuffers(device))
{
logger->GetInstance().WriteLine("Failed to initialise the buffers for rain object.");
return false;
}
return true;
}
bool CRain::InitialiseBuffers(ID3D11Device * device)
{
D3D11_BUFFER_DESC vertexBufferDesc;
HRESULT result;
// Set up the descriptor of the static vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType);
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Define our particle.
VertexType particle;
D3D11_SUBRESOURCE_DATA vertexData;
particle.Age = 0.0f;
particle.Type = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = &particle;
// Create the vertex buffer.
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &mpInitialBuffer);
if (FAILED(result))
{
logger->GetInstance().WriteLine("Failed to create the initial vertex buffer from the buffer description in Rain class.");
return false;
}
// Modify the vertex buffer desc to accomodate for multiple particles.
vertexBufferDesc.ByteWidth = sizeof(VertexType) * mNumberOfParticles;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_STREAM_OUTPUT;
// Define a vertex buffer without any initial data.
result = device->CreateBuffer(&vertexBufferDesc, 0, &mpDrawBuffer);
if (FAILED(result))
{
logger->GetInstance().WriteLine("Failed to create the draw vertex buffer from the buffer description in Rain class.");
return false;
}
// Define a vertex buffer without any initial data.
result = device->CreateBuffer(&vertexBufferDesc, 0, &mpStreamBuffer);
if (FAILED(result))
{
logger->GetInstance().WriteLine("Failed to create the stream buffer from the buffer description in Rain class.");
return false;
}
return true;
}
void CRain::Shutdown()
{
ShutdownBuffers();
if (mpRainDropTexture)
{
mpRainDropTexture->Shutdown();
delete mpRainDropTexture;
mpRainDropTexture = nullptr;
}
if (mpRandomResourceView)
{
mpRandomResourceView->Release();
mpRandomResourceView = nullptr;
}
}
void CRain::Update(float updateTime)
{
mAge += updateTime;
}
void CRain::UpdateRender(ID3D11DeviceContext * deviceContext)
{
unsigned int stride;
unsigned int offset;
// Set the vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
// Tell directx we've passed it a point list.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
if (mFirstRun)
{
// Set the vertex buffer to active in the input assembler.
deviceContext->IASetVertexBuffers(0, 1, &mpInitialBuffer, &stride, &offset);
}
else
{
// Set the vertex buffer to active in the input assembler.
deviceContext->IASetVertexBuffers(0, 1, &mpDrawBuffer, &stride, &offset);
}
// Set the stream buffer render target.
deviceContext->SOSetTargets(1, &mpStreamBuffer, &offset);
}
void CRain::Render(ID3D11DeviceContext * deviceContext)
{
unsigned int stride;
unsigned int offset;
// Set the vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
//Unbind the vertex buffer
ID3D11Buffer* buffer = 0;
deviceContext->SOSetTargets(1, &buffer, &offset);
std::swap(mpDrawBuffer, mpStreamBuffer);
// Tell directx we've passed it a point list.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
deviceContext->IASetVertexBuffers(0, 1, &mpDrawBuffer, &stride, &offset);
}
void CRain::ShutdownBuffers()
{
if (mpDrawBuffer)
{
mpDrawBuffer->Release();
mpDrawBuffer = nullptr;
}
if (mpInitialBuffer)
{
mpInitialBuffer->Release();
mpInitialBuffer = nullptr;
}
if (mpStreamBuffer)
{
mpStreamBuffer->Release();
mpStreamBuffer = nullptr;
}
}
ID3D11ShaderResourceView* CRain::CreateRandomTexture(ID3D11Device* device)
{
D3DXVECTOR4 randomValues[1024];
for (int i = 0; i < 1024; i++)
{
randomValues[i].x = ((((float)rand() - (float)rand()) / RAND_MAX));
randomValues[i].y = ((((float)rand() - (float)rand()) / RAND_MAX));
randomValues[i].z = ((((float)rand() - (float)rand()) / RAND_MAX));
randomValues[i].w = ((((float)rand() - (float)rand()) / RAND_MAX));
}
D3D11_SUBRESOURCE_DATA initData;
initData.pSysMem = randomValues;
initData.SysMemPitch = 1024 * sizeof(D3DXVECTOR4);
initData.SysMemSlicePitch = 0;
D3D11_TEXTURE1D_DESC texDesc;
texDesc.Width = 1024;
texDesc.MipLevels = 1;
texDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
texDesc.Usage = D3D11_USAGE_IMMUTABLE;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
texDesc.ArraySize = 1;
ID3D11Texture1D* randomTex = 0;
device->CreateTexture1D(&texDesc, &initData, &randomTex);
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
viewDesc.Texture1D.MipLevels = texDesc.MipLevels;
viewDesc.Texture1D.MostDetailedMip = 0;
ID3D11ShaderResourceView* randomTexture = 0;
device->CreateShaderResourceView(randomTex, &viewDesc, &randomTexture);
randomTex->Release();
return randomTexture;
}
void CRain::SetNumberOfParticles(unsigned int numParticles)
{
mNumberOfParticles = numParticles;
}
void CRain::SetFirstRun(bool firstRun)
{
mFirstRun = firstRun;
}
void CRain::SetAge(float age)
{
mAge = age;
}
void CRain::SetGameTime(float gameTime)
{
mGameTime = gameTime;
}
void CRain::SetEmitterPos(D3DXVECTOR3 pos)
{
mEmiterPosition = pos;
}
void CRain::SetEmitterDir(D3DXVECTOR3 dir)
{
mEmitterDirection = dir;
}
unsigned int CRain::GetNumberOfParticles()
{
return mNumberOfParticles;
}
bool CRain::GetIsFirstRun()
{
return mFirstRun;
}
float CRain::GetAge()
{
return mAge;
}
float CRain::GetGameTime()
{
return mGameTime;
}
D3DXVECTOR3 CRain::GetEmitterPos()
{
return mEmiterPosition;
}
D3DXVECTOR3 CRain::GetEmitterDir()
{
return mEmitterDirection;
}
ID3D11ShaderResourceView * CRain::GetRainTexture()
{
return mpRainDropTexture->GetTexture();
}
ID3D11ShaderResourceView * CRain::GetRandomTexture()
{
return mpRandomResourceView;
}
| 22.92053 | 123 | 0.747038 | [
"render",
"object"
] |
0a07d1b8d43b73410e9f03569389dc915633e3c8 | 1,617 | cpp | C++ | src/plugins/opencv/calibration_points.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 232 | 2017-10-09T11:45:28.000Z | 2022-03-28T11:14:46.000Z | src/plugins/opencv/calibration_points.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | 26 | 2019-01-20T21:38:25.000Z | 2021-10-16T03:57:17.000Z | src/plugins/opencv/calibration_points.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | 33 | 2017-10-26T19:20:38.000Z | 2022-03-16T11:21:43.000Z | #include "calibration_points.h"
namespace possumwood {
namespace opencv {
void CalibrationPoints::Layer::add(const cv::Vec3f& objectPoint, const cv::Vec2f& cameraPoint) {
m_objectPoints.push_back(objectPoint);
m_cameraPoints.push_back(cameraPoint);
}
CalibrationPoints::CalibrationPoints(const cv::Size& imageSize) : m_imageSize(imageSize) {
}
void CalibrationPoints::addLayer(const Layer& l) {
m_cameraPoints.push_back(l.m_cameraPoints);
m_objectPoints.push_back(l.m_objectPoints);
}
const std::vector<std::vector<cv::Vec3f>>& CalibrationPoints::objectPoints() const {
return m_objectPoints;
}
const std::vector<std::vector<cv::Vec2f>>& CalibrationPoints::cameraPoints() const {
return m_cameraPoints;
}
const cv::Size& CalibrationPoints::imageSize() const {
return m_imageSize;
}
bool CalibrationPoints::empty() const {
return m_cameraPoints.empty();
}
std::size_t CalibrationPoints::size() const {
return m_cameraPoints.size();
}
bool CalibrationPoints::operator==(const CalibrationPoints& f) const {
return m_objectPoints == f.m_objectPoints && m_cameraPoints == f.m_cameraPoints && m_imageSize == f.m_imageSize;
}
bool CalibrationPoints::operator!=(const CalibrationPoints& f) const {
return m_objectPoints != f.m_objectPoints || m_cameraPoints != f.m_cameraPoints || m_imageSize != f.m_imageSize;
}
std::ostream& operator<<(std::ostream& out, const CalibrationPoints& f) {
out << "(" << f.size() << " calibration point set(s), image size=" << f.imageSize().width << "x"
<< f.imageSize().height << ")" << std::endl;
return out;
}
} // namespace opencv
} // namespace possumwood
| 28.875 | 113 | 0.739641 | [
"vector"
] |
0a08ebd00c76d2948c4117aa773569bf2b87db05 | 3,012 | cc | C++ | tensorflow/lite/tools/strip_buffers/reconstitute_buffers_into_fb.cc | EricRemmerswaal/tensorflow | 141ff27877579c81a213fa113bd1b474c1749aca | [
"Apache-2.0"
] | 190,993 | 2015-11-09T13:17:30.000Z | 2022-03-31T23:05:27.000Z | tensorflow/lite/tools/strip_buffers/reconstitute_buffers_into_fb.cc | EricRemmerswaal/tensorflow | 141ff27877579c81a213fa113bd1b474c1749aca | [
"Apache-2.0"
] | 48,461 | 2015-11-09T14:21:11.000Z | 2022-03-31T23:17:33.000Z | tensorflow/lite/tools/strip_buffers/reconstitute_buffers_into_fb.cc | EricRemmerswaal/tensorflow | 141ff27877579c81a213fa113bd1b474c1749aca | [
"Apache-2.0"
] | 104,981 | 2015-11-09T13:40:17.000Z | 2022-03-31T19:51:54.000Z | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Binary to test strip_buffers/reconstitution.h.
#include <fstream> // NOLINT
#include <iostream>
#include <sstream>
#include <string>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/tools/command_line_flags.h"
#include "tensorflow/lite/tools/strip_buffers/stripping_lib.h"
#define TFLITE_SCHEMA_VERSION 3
namespace tflite {
using ::flatbuffers::FlatBufferBuilder;
constexpr char kInputFlatbufferFlag[] = "input_flatbuffer";
constexpr char kOutputFlatbufferFlag[] = "output_flatbuffer";
int Main(int argc, char* argv[]) {
// Command Line Flags.
std::string input_flatbuffer_path;
std::string output_flatbuffer_path;
std::vector<Flag> flag_list = {
tflite::Flag::CreateFlag(kInputFlatbufferFlag, &input_flatbuffer_path,
"Path to input TFLite flatbuffer."),
tflite::Flag::CreateFlag(kOutputFlatbufferFlag, &output_flatbuffer_path,
"Path to output TFLite flatbuffer."),
};
Flags::Parse(&argc, const_cast<const char**>(argv), flag_list);
// Read in input flatbuffer.
auto input_model =
FlatBufferModel::BuildFromFile(input_flatbuffer_path.c_str());
if (!FlatbufferHasStrippedWeights(input_model->GetModel())) {
LOG(ERROR) << "The weights are already available in the input model!";
return 0;
}
// Reconstitute flatbuffer with appropriate random constant tensors
FlatBufferBuilder builder(/*initial_size=*/10240);
if (ReconstituteConstantTensorsIntoFlatbuffer(input_model->GetModel(),
&builder) != kTfLiteOk) {
return 0;
}
LOG(INFO) << "Flatbuffer size (KB) BEFORE: "
<< input_model->allocation()->bytes() / 1000.0;
LOG(INFO) << "Flatbuffer size (KB) AFTER: " << builder.GetSize() / 1000.0;
// Write the output model to file.
std::string output_model_content(
reinterpret_cast<const char*>(builder.GetBufferPointer()),
builder.GetSize());
std::ofstream output_file_stream(output_flatbuffer_path);
output_file_stream << output_model_content;
output_file_stream.close();
return 0;
}
} // namespace tflite
int main(int argc, char* argv[]) { return tflite::Main(argc, argv); }
| 36.289157 | 80 | 0.700531 | [
"vector",
"model"
] |
0a0b829bc60a109dcd27555c1a000942c0bf6ff2 | 26,929 | cpp | C++ | modules/importancesamplingcl/processors/minmaxuniformgrid3dimportanceclprocessor.cpp | danjobanjo/Correlated-Photon-Mapping-for-Interactive-Global-Illumination-of-Time-Varying-Volumetric-Data | bb9bd0a79b111a609e4548326d64aede07fd3a5e | [
"MIT"
] | 14 | 2016-10-27T12:42:25.000Z | 2021-05-24T08:14:24.000Z | modules/importancesamplingcl/processors/minmaxuniformgrid3dimportanceclprocessor.cpp | danjobanjo/Correlated-Photon-Mapping-for-Interactive-Global-Illumination-of-Time-Varying-Volumetric-Data | bb9bd0a79b111a609e4548326d64aede07fd3a5e | [
"MIT"
] | 7 | 2017-09-07T08:36:08.000Z | 2019-12-06T16:02:16.000Z | modules/importancesamplingcl/processors/minmaxuniformgrid3dimportanceclprocessor.cpp | danjobanjo/Correlated-Photon-Mapping-for-Interactive-Global-Illumination-of-Time-Varying-Volumetric-Data | bb9bd0a79b111a609e4548326d64aede07fd3a5e | [
"MIT"
] | 5 | 2016-10-30T05:16:15.000Z | 2020-03-10T10:52:19.000Z | /*********************************************************************************
*
* Copyright (c) 2016, Daniel Jönsson
* All rights reserved.
*
* This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
* http://creativecommons.org/licenses/by-nc/4.0/
*
* You are free to:
*
* Share — copy and redistribute the material in any medium or format
* Adapt — remix, transform, and build upon the material
* The licensor cannot revoke these freedoms as long as you follow the license terms.
* Under the following terms:
*
* Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
* NonCommercial — You may not use the material for commercial purposes.
* No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "minmaxuniformgrid3dimportanceclprocessor.h"
#include <inviwo/core/util/colorconversion.h>
#include <modules/opencl/buffer/buffercl.h>
#include <modules/opencl/syncclgl.h>
#include <glm/gtc/epsilon.hpp>
#define IVW_DETAILED_PROFILING
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming
// scheme
const ProcessorInfo MinMaxUniformGrid3DImportanceCLProcessor::processorInfo_{
"org.inviwo.MinMaxUniformGrid3DImportanceCLProcessor", // Class identifier
"MinMaxUniformGrid3DImportance", // Display name
"UniformGrid3D", // Category
CodeState::Experimental, // Code state
Tags::CL, // Tags
};
const ProcessorInfo MinMaxUniformGrid3DImportanceCLProcessor::getProcessorInfo() const {
return processorInfo_;
}
MinMaxUniformGrid3DImportanceCLProcessor::MinMaxUniformGrid3DImportanceCLProcessor()
: Processor()
, ProcessorKernelOwner(this)
, incrementalImportance("incrementalImportance", "Incremental importance", true)
, minMaxUniformGrid3DInport_("minMaxUniformGrid3D")
, volumeDifferenceInfoInport_("volumeDifferenceInfo")
, importanceUniformGrid3DOutport_("importanceUniformGrid3D")
, opacityWeight_("constantWeight", "Opacity weight", 1.f, 0.f, 1.f)
, opacityDiffWeight_("opacityDiffWeight", "Opacity difference weight", 0.f, 0.f, 1.f)
, colorWeight_("colorWeight", "Color weight", 0.f, 0.f, 1.f)
, colorDiffWeight_("colorDiffWeight", "Color difference weight", 0.f, 0.f, 1.f)
, useAssociatedColor_("useAssociatedColor", "Associated color", false)
, TFPointEpsilon_("TFPointEpsilon", "Minimum change threshold", 1e-4f, 0.f, 1e-2f, 1e-3f)
, transferFunction_("transferfunction", "Transfer function")
, workGroupSize_("wgsize", "Work group size", 128, 1, 4096)
, useGLSharing_("glsharing", "Use OpenGL sharing", true)
, importanceUniformGrid3D_(std::make_shared<ImportanceUniformGrid3D>()) {
addPort(minMaxUniformGrid3DInport_);
minMaxUniformGrid3DInport_.onChange(
[this]() { setInvalidationReason(InvalidationReason::Volume); });
volumeDifferenceInfoInport_.setOptional(true);
addPort(volumeDifferenceInfoInport_);
addPort(importanceUniformGrid3DOutport_);
addProperty(incrementalImportance);
addProperty(opacityWeight_);
addProperty(opacityDiffWeight_);
addProperty(colorWeight_);
addProperty(colorDiffWeight_);
addProperty(useAssociatedColor_);
addProperty(TFPointEpsilon_);
// opacityWeight_.onChange([this](){
// setInvalidationReason(InvalidationReason::TransferFunction); });
// opacityDiffWeight_.onChange([this](){
// setInvalidationReason(InvalidationReason::TransferFunction); });
// colorDiffWeight_.onChange([this](){
// setInvalidationReason(InvalidationReason::TransferFunction); });
useAssociatedColor_.onChange(
[this]() { setInvalidationReason(InvalidationReason::TransferFunction); });
addProperty(transferFunction_);
transferFunction_.onChange(
[this]() { setInvalidationReason(InvalidationReason::TransferFunction); });
addProperty(workGroupSize_);
addProperty(useGLSharing_);
kernel_ =
addKernel("minmaxuniformgrid3dimportance.cl", "classifyMinMaxUniformGrid3DImportanceKernel",
"", " -D INCREMENTAL_TF_IMPORTANCE");
timeVaryingKernel_ = addKernel("minmaxuniformgrid3dimportance.cl",
"classifyTimeVaryingMinMaxUniformGrid3DImportanceKernel");
importanceUniformGrid3DOutport_.setData(importanceUniformGrid3D_);
// Count as unused if cleared
prevTransferFunction_.clear();
}
void MinMaxUniformGrid3DImportanceCLProcessor::process() {
if (!kernel_ || !timeVaryingKernel_) {
return;
}
const MinMaxUniformGrid3D *minMaxUniformGrid3D =
dynamic_cast<const MinMaxUniformGrid3D *>(minMaxUniformGrid3DInport_.getData().get());
if (!minMaxUniformGrid3D) {
LogError("minMaxUniformGrid3DInport_ expects MinMaxUniformGrid3D as input");
return;
}
if (glm::any(glm::notEqual(minMaxUniformGrid3D->getDimensions(),
importanceUniformGrid3D_->getDimensions()))) {
importanceUniformGrid3D_->setDimensions(minMaxUniformGrid3D->getDimensions());
importanceUniformGrid3D_->setCellDimension(minMaxUniformGrid3D->getCellDimension());
importanceUniformGrid3D_->setModelMatrix(minMaxUniformGrid3D->getModelMatrix());
importanceUniformGrid3D_->setWorldMatrix(minMaxUniformGrid3D->getWorldMatrix());
}
if (static_cast<int>(invalidationFlag_) &
static_cast<int>(InvalidationReason::TransferFunction)) {
if (prevTransferFunction_.size() == 0 || !incrementalImportance) {
updateTransferFunctionData();
} else {
updateTransferFunctionDifferenceData();
}
prevTransferFunction_ = transferFunction_.get();
} else if (static_cast<int>(invalidationFlag_) & static_cast<int>(InvalidationReason::Volume)) {
updateTransferFunctionData();
}
size3_t dim = importanceUniformGrid3D_->getDimensions();
size_t nElements = dim.x * dim.y * dim.z;
size_t localWorkGroupSize(workGroupSize_.get());
size_t globalWorkGroupSize(getGlobalWorkGroupSize(nElements, localWorkGroupSize));
#ifdef IVW_DETAILED_PROFILING
IVW_OPENCL_PROFILING(profilingEvent, "")
#else
cl::Event *profilingEvent = nullptr;
#endif
if (volumeDifferenceInfoInport_.isReady() && prevMinMaxUniformGrid3D_ != nullptr &&
prevMinMaxUniformGrid3D_.get() != minMaxUniformGrid3D) {
// Time varying data changed
auto volumeDifferenceData = dynamic_cast<const DynamicVolumeInfoUniformGrid3D *>(
volumeDifferenceInfoInport_.getData().get());
if (!volumeDifferenceData) {
LogError(
"volumeDifferenceInfoInport_ expects "
"DynamicVolumeInfoUniformGrid3D as input");
return;
}
if (useGLSharing_) {
SyncCLGL glSync;
auto minMaxUniformGrid3DCL = minMaxUniformGrid3D->data.getRepresentation<BufferCLGL>();
auto prevMinMaxUniformGrid3DCL =
prevMinMaxUniformGrid3D_->data.getRepresentation<BufferCLGL>();
auto volumeDifferenceInfoCL =
volumeDifferenceData->data.getRepresentation<BufferCLGL>();
auto importanceUniformGrid3DCL =
importanceUniformGrid3D_->data.getEditableRepresentation<BufferCLGL>();
glSync.addToAquireGLObjectList(minMaxUniformGrid3DCL);
glSync.addToAquireGLObjectList(prevMinMaxUniformGrid3DCL);
glSync.addToAquireGLObjectList(volumeDifferenceInfoCL);
glSync.addToAquireGLObjectList(importanceUniformGrid3DCL);
glSync.aquireAllObjects();
computeImportance(minMaxUniformGrid3DCL, prevMinMaxUniformGrid3DCL,
volumeDifferenceInfoCL, nElements, importanceUniformGrid3DCL,
globalWorkGroupSize, localWorkGroupSize, profilingEvent);
} else {
auto minMaxUniformGrid3DCL = minMaxUniformGrid3D->data.getRepresentation<BufferCL>();
auto volumeDifferenceInfoCL = volumeDifferenceData->data.getRepresentation<BufferCL>();
auto prevMinMaxUniformGrid3DCL =
prevMinMaxUniformGrid3D_->data.getRepresentation<BufferCL>();
auto importanceUniformGrid3DCL =
importanceUniformGrid3D_->data.getEditableRepresentation<BufferCL>();
computeImportance(minMaxUniformGrid3DCL, prevMinMaxUniformGrid3DCL,
volumeDifferenceInfoCL, nElements, importanceUniformGrid3DCL,
globalWorkGroupSize, localWorkGroupSize, profilingEvent);
}
} else {
// Transfer function changed
if (useGLSharing_) {
SyncCLGL glSync;
auto minMaxUniformGrid3DCL = minMaxUniformGrid3D->data.getRepresentation<BufferCLGL>();
auto importanceUniformGrid3DCL =
importanceUniformGrid3D_->data.getEditableRepresentation<BufferCLGL>();
glSync.addToAquireGLObjectList(minMaxUniformGrid3DCL);
glSync.addToAquireGLObjectList(importanceUniformGrid3DCL);
glSync.aquireAllObjects();
computeImportance(minMaxUniformGrid3DCL, nElements, importanceUniformGrid3DCL,
globalWorkGroupSize, localWorkGroupSize, profilingEvent);
} else {
auto minMaxUniformGrid3DCL = minMaxUniformGrid3D->data.getRepresentation<BufferCL>();
auto importanceUniformGrid3DCL =
importanceUniformGrid3D_->data.getEditableRepresentation<BufferCL>();
computeImportance(minMaxUniformGrid3DCL, nElements, importanceUniformGrid3DCL,
globalWorkGroupSize, localWorkGroupSize, profilingEvent);
}
}
prevMinMaxUniformGrid3D_ =
std::dynamic_pointer_cast<const MinMaxUniformGrid3D>(minMaxUniformGrid3DInport_.getData());
invalidationFlag_ = InvalidationReason(0);
}
void MinMaxUniformGrid3DImportanceCLProcessor::computeImportance(
const BufferCLBase *minMaxUniformGridCL, size_t nElements,
BufferCLBase *importanceUniformGridCL, const size_t &globalWorkGroupSize,
const size_t &localWorkgroupSize, cl::Event *event) {
// Transfer function parameters
try {
auto positionsCL = tfPointPositions_.getRepresentation<BufferCL>();
auto colorsCL = tfPointColors_.getRepresentation<BufferCL>();
// Make weights sum to 1
auto weightNormalization = colorWeight_.get() + colorDiffWeight_.get() +
opacityDiffWeight_.get() + opacityWeight_.get();
if (weightNormalization <= 0.f) {
weightNormalization = 1.f;
}
auto labColorNormalizationFactor = getLabColorNormalizationFactor();
int argIndex = 0;
kernel_->setArg(argIndex++, *minMaxUniformGridCL);
kernel_->setArg(argIndex++, static_cast<int>(nElements));
kernel_->setArg(argIndex++, *positionsCL);
kernel_->setArg(argIndex++, *colorsCL);
kernel_->setArg(argIndex++,
std::min(static_cast<int>(positionsCL->getSize()), tfPointImportanceSize_));
kernel_->setArg(argIndex++,
colorWeight_.get() * labColorNormalizationFactor / (weightNormalization));
kernel_->setArg(argIndex++, colorDiffWeight_.get() * labColorNormalizationFactor /
(weightNormalization));
kernel_->setArg(argIndex++, opacityDiffWeight_.get() / weightNormalization);
kernel_->setArg(argIndex++, opacityWeight_.get() / weightNormalization);
kernel_->setArg(argIndex++, *importanceUniformGridCL);
OpenCL::getPtr()->getQueue().enqueueNDRangeKernel(
*kernel_, cl::NullRange, globalWorkGroupSize, localWorkgroupSize, NULL, event);
} catch (cl::Error &err) {
LogError(getCLErrorString(err));
}
}
void MinMaxUniformGrid3DImportanceCLProcessor::computeImportance(
const BufferCLBase *minMaxUniformGridCL, const BufferCLBase *prevMinMaxUniformGridCL,
const BufferCLBase *volumeDifferenceInfoUniformGridCL, size_t nElements,
BufferCLBase *importanceUniformGridCL, const size_t &globalWorkGroupSize,
const size_t &localWorkgroupSize, cl::Event *event) {
try {
auto positionsCL = tfPointPositions_.getRepresentation<BufferCL>();
auto colorsCL = tfPointColors_.getRepresentation<BufferCL>();
// Make weights sum to 1
auto weightNormalization = colorWeight_.get() + colorDiffWeight_.get() +
opacityDiffWeight_.get() + opacityWeight_.get();
if (weightNormalization <= 0.f) {
weightNormalization = 1.f;
}
auto labColorNormalizationFactor = getLabColorNormalizationFactor();
int argIndex = 0;
timeVaryingKernel_->setArg(argIndex++, *minMaxUniformGridCL);
timeVaryingKernel_->setArg(argIndex++, *prevMinMaxUniformGridCL);
timeVaryingKernel_->setArg(argIndex++, *volumeDifferenceInfoUniformGridCL);
timeVaryingKernel_->setArg(argIndex++, static_cast<int>(nElements));
timeVaryingKernel_->setArg(argIndex++, *positionsCL);
timeVaryingKernel_->setArg(argIndex++, *colorsCL);
timeVaryingKernel_->setArg(argIndex++, static_cast<int>(tfPointImportanceSize_));
timeVaryingKernel_->setArg(
argIndex++, colorWeight_.get() * labColorNormalizationFactor / (weightNormalization));
timeVaryingKernel_->setArg(
argIndex++,
colorDiffWeight_.get() * labColorNormalizationFactor / (weightNormalization));
timeVaryingKernel_->setArg(argIndex++, opacityDiffWeight_.get() / weightNormalization);
timeVaryingKernel_->setArg(argIndex++, opacityWeight_.get() / weightNormalization);
timeVaryingKernel_->setArg(argIndex++, *importanceUniformGridCL);
OpenCL::getPtr()->getQueue().enqueueNDRangeKernel(*timeVaryingKernel_, cl::NullRange,
globalWorkGroupSize, localWorkgroupSize,
NULL, event);
} catch (cl::Error &err) {
LogError(getCLErrorString(err));
}
}
float MinMaxUniformGrid3DImportanceCLProcessor::getLabColorNormalizationFactor() const {
vec3 labColorSpaceExtent{100.f, 500.f, 400.f};
return 1.f / glm::length(labColorSpaceExtent);
}
void MinMaxUniformGrid3DImportanceCLProcessor::updateTransferFunctionData() {
if (transferFunction_.get().size() == 0) {
tfPointImportanceSize_ = 2;
if (static_cast<int>(tfPointPositions_.getSize()) < tfPointImportanceSize_) {
tfPointPositions_.setSize(tfPointImportanceSize_);
tfPointColors_.setSize(tfPointImportanceSize_);
}
auto positions = tfPointPositions_.getEditableRAMRepresentation();
auto colors = tfPointColors_.getEditableRAMRepresentation();
(*positions)[0] = 0;
(*colors)[0] = vec4(0.f);
(*positions)[1] = 1;
(*colors)[1] = vec4(0.f);
} else {
auto firstPoint = transferFunction_.get().get(0);
auto lastPoint =
transferFunction_.get().get(static_cast<int>(transferFunction_.get().size() - 1));
tfPointImportanceSize_ = static_cast<int>(transferFunction_.get().size());
if (firstPoint.getPosition() > 0.f) {
++tfPointImportanceSize_;
}
if (lastPoint.getPosition() < 1.f) {
++tfPointImportanceSize_;
}
if (static_cast<int>(tfPointPositions_.getSize()) < tfPointImportanceSize_) {
tfPointPositions_.setSize(tfPointImportanceSize_);
tfPointColors_.setSize(tfPointImportanceSize_);
}
auto positions = tfPointPositions_.getEditableRAMRepresentation();
auto colors = tfPointColors_.getEditableRAMRepresentation();
int pointId = 0;
if (firstPoint.getPosition() > 0.f) {
(*positions)[0] = 0;
if (useAssociatedColor_)
(*colors)[0] = firstPoint.getColor() * firstPoint.getAlpha();
else
(*colors)[0] = firstPoint.getColor();
++pointId;
}
for (auto i = 0u; i < transferFunction_.get().size(); ++i, ++pointId) {
auto point = transferFunction_.get().get(i);
(*positions)[pointId] = static_cast<float>(point.getPosition());
if (useAssociatedColor_)
(*colors)[pointId] = point.getColor() * point.getAlpha();
else
(*colors)[pointId] = point.getColor();
}
if (lastPoint.getPosition() < 1.) {
(*positions)[pointId] = 1.f;
if (useAssociatedColor_)
(*colors)[pointId++] = lastPoint.getColor() * lastPoint.getAlpha();
else
(*colors)[pointId++] = lastPoint.getColor();
}
}
}
void MinMaxUniformGrid3DImportanceCLProcessor::updateTransferFunctionDifferenceData() {
if (transferFunction_.get().size() == 0 && prevTransferFunction_.size() == 0) {
tfPointImportanceSize_ = 2;
if (static_cast<int>(tfPointPositions_.getSize()) < tfPointImportanceSize_) {
tfPointPositions_.setSize(tfPointImportanceSize_);
tfPointColors_.setSize(tfPointImportanceSize_);
}
auto positions = tfPointPositions_.getEditableRAMRepresentation();
auto colors = tfPointColors_.getEditableRAMRepresentation();
(*positions)[0] = 0;
(*colors)[0] = vec4(0.f);
(*positions)[1] = 0;
(*colors)[1] = vec4(0.f);
} else {
auto maxSize = transferFunction_.get().size() + prevTransferFunction_.size() + 2;
if (tfPointPositions_.getSize() < maxSize) {
tfPointPositions_.setSize(maxSize);
tfPointColors_.setSize(maxSize);
}
auto positions = tfPointPositions_.getEditableRAMRepresentation();
auto colors = tfPointColors_.getEditableRAMRepresentation();
auto firstPoint = transferFunction_.get().get(0);
//auto lastPoint =
// transferFunction_.get().get(static_cast<int>(transferFunction_.get().size() - 1));
auto prevFirstPoint = prevTransferFunction_.get(0);
//auto prevLastPoint =
// prevTransferFunction_.get(static_cast<int>(prevTransferFunction_.size() - 1));
int outId = 0;
int id = 0, prevId = 0;
TFPrimitive p1, p2;
p1 = p2 = TFPrimitive(firstPoint < prevFirstPoint ? firstPoint.getPosition()
: prevFirstPoint.getPosition(),
tfPointColorDiff(firstPoint.getColor(), prevFirstPoint.getColor()));
if (firstPoint.getPosition() != prevFirstPoint.getPosition() &&
firstPoint.getAlpha() == 0.f && prevFirstPoint.getAlpha() == 0.f) {
// Moved first point with zero opacity
if (firstPoint < prevFirstPoint) {
auto a2 = transferFunction_.get().get(
std::min(1, static_cast<int>(transferFunction_.get().size() - 1)));
auto p = mix(firstPoint, a2, prevFirstPoint);
p2 = TFPrimitive(prevFirstPoint.getPosition(),
tfPointColorDiff(prevFirstPoint.getColor(), p.getColor()));
} else {
auto a2 = prevTransferFunction_.get(
std::min(1, static_cast<int>(prevTransferFunction_.size() - 1)));
auto p = mix(prevFirstPoint, a2, firstPoint);
p2 = TFPrimitive(firstPoint.getPosition(),
tfPointColorDiff(firstPoint.getColor(), p.getColor()));
}
}
if (p1.getPosition() > 0.f &&
(firstPoint.getAlpha() > 0.f || prevFirstPoint.getAlpha() > 0.f) &&
glm::any(glm::epsilonNotEqual(p1.getColor(), vec4(0), TFPointEpsilon_.get()))) {
(*positions)[outId] = 0.f;
(*colors)[outId] = p1.getColor();
++outId;
// This point will be added in the loop
//(*positions)[outId] = p1.getPosition().x;
//(*colors)[outId] = p1.getColor();
//++outId;
} else {
// Add a point with zero difference
(*positions)[outId] = 0.f;
(*colors)[outId] = vec4(0.f);
++outId;
}
while (id < static_cast<int>(transferFunction_.get().size()) || prevId < static_cast<int>(prevTransferFunction_.size())) {
// Only store point if difference is non-zero
// And the opacity is greater than zero
if ((glm::any(glm::epsilonNotEqual(p1.getColor(), vec4(0), TFPointEpsilon_.get())) ||
glm::any(glm::epsilonNotEqual(p2.getColor(), vec4(0), TFPointEpsilon_.get()))) &&
(p1.getAlpha() > 0. || p2.getAlpha() > 0.)) {
if (outId == 1) {
// Add point if all previous have been equal.
(*positions)[outId] = static_cast<float>(p1.getPosition());
(*colors)[outId] = p1.getColor();
++outId;
}
(*positions)[outId] = static_cast<float>(p2.getPosition());
(*colors)[outId] = p2.getColor();
++outId;
}
// Advance to next point
const auto a1 = transferFunction_.get().get(
std::min(id, static_cast<int>(transferFunction_.get().size()) - 1));
TFPrimitive a2;
if (id + 1 < static_cast<int>(transferFunction_.get().size()) - 1) {
a2 = transferFunction_.get().get(id + 1);
} else {
const auto a = transferFunction_.get().get(transferFunction_.get().size() - 1);
a2 = TFPrimitive(1., a.getColor());
}
const auto b1 = prevTransferFunction_.get(
std::min(prevId, static_cast<int>(prevTransferFunction_.size()) - 1));
TFPrimitive b2;
if (prevId + 1 < static_cast<int>(prevTransferFunction_.size()) - 1) {
b2 = prevTransferFunction_.get(prevId + 1);
} else {
const auto b = prevTransferFunction_.get(prevTransferFunction_.size() - 1);
b2 = TFPrimitive(1., b.getColor());
}
p1 = p2;
if (a2 < b2) {
// Interpolate point in prev TF
auto p = mix(b1, b2, a2);
p2 = TFPrimitive(a2.getPosition(), tfPointColorDiff(a2.getColor(), p.getColor()));
++id;
} else if (b2 < a2) {
auto p = mix(a1, a2, b2);
p2 = TFPrimitive(b2.getPosition(), tfPointColorDiff(b2.getColor(), p.getColor()));
++prevId;
} else {
p2 =
TFPrimitive(a2.getAlpha() < b2.getAlpha() ? b2.getPosition() : a2.getPosition(),
tfPointColorDiff(a2.getColor(), b2.getColor()));
++id;
++prevId;
}
}
if (p2.getPosition() < 1. && p2.getAlpha() > 0.) {
(*positions)[outId] = static_cast<float>(p2.getPosition());
(*colors)[outId] = p2.getColor();
++outId;
}
if ((*positions)[outId - 1] < 1.) {
// Add a point with zero difference
(*positions)[outId] = 1.;
(*colors)[outId] = vec4(0.f);
++outId;
}
tfPointImportanceSize_ = outId;
}
}
inviwo::vec4 MinMaxUniformGrid3DImportanceCLProcessor::tfPointColorDiff(const vec4 &p1,
const vec4 &p2) {
return glm::abs(p2 * (useAssociatedColor_ ? p2.w : 1.f) -
p1 * (useAssociatedColor_ ? p1.w : 1.f));
}
void MinMaxUniformGrid3DImportanceCLProcessor::setInvalidationReason(
InvalidationReason invalidationFlag) {
invalidationFlag_ |= invalidationFlag;
}
TFPrimitive MinMaxUniformGrid3DImportanceCLProcessor::mix(const TFPrimitive &a,
const TFPrimitive &b,
const TFPrimitive &t) {
return mix(a, b, (t.getPosition() - a.getPosition()) / (b.getPosition() - a.getPosition()));
}
inviwo::TFPrimitive MinMaxUniformGrid3DImportanceCLProcessor::mix(const TFPrimitive &a,
const TFPrimitive &b, double t) {
return TFPrimitive(glm::mix(a.getPosition(), b.getPosition(), t),
glm::mix(a.getColor(), b.getColor(), t));
}
} // namespace inviwo
| 51.098672 | 228 | 0.612091 | [
"transform"
] |
0a0cc4a052e82a208d67dbef15fa17d297777164 | 4,358 | cpp | C++ | samples/Windows/MainDlg.cpp | jonetomtom/mars | 3f11714e0aee826eb12bfd52496b59675125204a | [
"BSD-2-Clause",
"Apache-2.0"
] | 17,104 | 2016-12-28T07:45:54.000Z | 2022-03-31T07:02:52.000Z | samples/Windows/MainDlg.cpp | wblzu/mars | 4396e753aee627a92b55ae7a1bc12b4d6f4f6445 | [
"Apache-2.0"
] | 964 | 2016-12-28T08:13:33.000Z | 2022-03-31T13:36:40.000Z | samples/Windows/MainDlg.cpp | pengjinning/mars | 227aff64a5b819555091a7d6eae6727701e9fff0 | [
"Apache-2.0",
"BSD-2-Clause"
] | 3,568 | 2016-12-28T07:47:46.000Z | 2022-03-31T02:13:19.000Z | #include "stdafx.h"
#include "MainDlg.h"
#include "AboutDlg.h"
#include "Business/MarsWrapper.h"
#include <comutil.h>
BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL CMainDlg::OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// center the dialog on the screen
CenterWindow();
// set icons
HICON hIcon = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON));
SetIcon(hIcon, TRUE);
HICON hIconSmall = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON));
SetIcon(hIconSmall, FALSE);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
RECT rc;
GetClientRect(&rc);
m_tabView.Create(m_hWnd, rc, NULL, WS_CHILD | WS_VISIBLE, WS_EX_STATICEDGE);
m_pingServerDlg = boost::shared_ptr<CPingServerDlg>(new CPingServerDlg());
m_pingServerDlg->Create(m_tabView.m_hWnd);
m_tabView.AddPage(m_pingServerDlg->m_hWnd, _T("Ping Server"));
m_pingServerDlg->SetHostWnd(this);
/*HWND hTabCtrl = GetDlgItem(IDC_TAB1);
TCITEM item;
item.mask = TCIF_TEXT;
item.iImage = 0;
item.lParam = 0;
item.pszText = _T("PingServer");
item.cchTextMax = 10;
SendMessage(hTabCtrl, TCM_INSERTITEM, 0, (LPARAM)&item);
item.pszText = _T("Chat");
item.cchTextMax = 10;
SendMessage(hTabCtrl, TCM_INSERTITEM, 1, (LPARAM)&item);
HWND hChildWnd = CreateDialogParam(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDD_DIALOGPINGSERVER), hTabCtrl, NULL, 0);
::ShowWindow(hChildWnd, SW_SHOWDEFAULT);*/
//HWND hChildWnd = CreateDialogParam(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDD_DIALOGPINGSERVER), hTabCtrl, NULL, 0);
//ShowWindow(hChildWnd, SW_SHOWDEFAULT);
MarsWrapper::Instance().start();
MarsWrapper::Instance().setChatMsgObserver(this);
return TRUE;
}
LRESULT CMainDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
MarsWrapper::Instance().setChatMsgObserver(nullptr);
m_pingServerDlg->SetHostWnd(nullptr);
DestoryAllChatTab();
return 0;
}
LRESULT CMainDlg::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
LRESULT CMainDlg::OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
// TODO: Add validation code
CloseDialog(wID);
return 0;
}
LRESULT CMainDlg::OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CloseDialog(wID);
return 0;
}
void CMainDlg::CloseDialog(int nVal)
{
DestroyWindow();
::PostQuitMessage(nVal);
}
LRESULT CMainDlg::OnGetConversationList(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DestoryAllChatTab();
std::vector<ConversationInfo>* conversationList = (std::vector<ConversationInfo>*)wParam;
int size = conversationList->size();
if (size > 5)size = 5;
std::string name = (char*)(_bstr_t)m_pingServerDlg->GetUserName().c_str();
for (int i = 0; i < size; ++i)
{
const ConversationInfo& item = (*conversationList)[i];
CChatDlg* dlg = new CChatDlg();
dlg->Create(m_tabView.m_hWnd);
dlg->SetChatInfo(name, item.topic_);
m_tabView.AddPage(dlg->m_hWnd, (wchar_t*)(_bstr_t)item.notice_.c_str());
m_chatDlgList[item.topic_] = dlg;
}
delete conversationList;
return 0;
}
void CMainDlg::DestoryAllChatTab()
{
int size = m_tabView.GetPageCount();
for (int i = size - 1; i > 0; i--)m_tabView.RemovePage(i);
for (auto it = m_chatDlgList.begin(); it != m_chatDlgList.end(); ++it)
{
delete it->second;
}
m_chatDlgList.clear();
}
void CMainDlg::OnRecvChatMsg(const ChatMsg& msg)
{
auto it = m_chatDlgList.find(msg.topic_);
if (it != m_chatDlgList.end()) it->second->OnRecvChatMsg(msg);
} | 29.849315 | 136 | 0.704222 | [
"object",
"vector"
] |
0a0e59d74e7cdec3b5326a6a5ff59c15d5cc68d5 | 674 | cc | C++ | src/codeforces/229635/G/G.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | 2 | 2019-09-07T17:00:26.000Z | 2020-08-05T02:08:35.000Z | src/codeforces/229635/G/G.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | src/codeforces/229635/G/G.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define FR(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
int f[40];
int fib(int n) {
if (n < 2) return n;
if (f[n]) return f[n];
int k = (n + 1) / 2;
f[n] = (n & 1)
? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1))
: (2 * fib(k - 1) + fib(k)) * fib(k);
return f[n];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
set<int> s;
FR(i, 20) s.insert(fib(i));
int n;
cin >> n;
for (int i = 1; i <= n; i++)
if (s.find(i) == s.end())
cout << "o";
else
cout << "O";
cout << endl;
}
| 16.439024 | 49 | 0.473294 | [
"vector"
] |
0a134a603fdd8b63bbd887856c44dc7fbd49a2b9 | 1,783 | cpp | C++ | Asteroids/src/application/Application.cpp | DatDarkAlpaca/Asteroids | ae65a1a82790dc058dbda6d1f3b00edbc936c5d3 | [
"MIT"
] | 1 | 2021-11-09T01:06:45.000Z | 2021-11-09T01:06:45.000Z | Asteroids/src/application/Application.cpp | DatDarkAlpaca/Asteroids | ae65a1a82790dc058dbda6d1f3b00edbc936c5d3 | [
"MIT"
] | null | null | null | Asteroids/src/application/Application.cpp | DatDarkAlpaca/Asteroids | ae65a1a82790dc058dbda6d1f3b00edbc936c5d3 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Core.h"
#include "Application.h"
#include "scenes/SceneMainMenu.h"
#include "scenes/SceneSinglePlayer.h"
#include "utils/Random.h"
void ast::Application::Run()
{
// Initializing the font:
fontHolder.font = std::make_shared<sf::Font>();
if (!fontHolder.font->loadFromFile("res/pixelated.ttf"))
std::cout << "Failed to load font free-pixel.ttf\n";
InitializeSeed();
CreateScenes();
sf::Clock clock;
while (m_WindowHandler.GetWindow().isOpen())
{
float dt = clock.restart().asSeconds();
PollEvents();
Update(dt);
Render();
}
}
void ast::Application::PollEvents()
{
sf::Event e;
while (m_WindowHandler.GetWindow().pollEvent(e))
{
if (e.type == sf::Event::Closed)
m_WindowHandler.GetWindow().close();
if (e.type == sf::Event::Resized)
m_WindowHandler.ApplyResizedView(e);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::F11))
m_WindowHandler.ToggleFullscreen();
m_SceneManager.PollEvents(e);
}
}
void ast::Application::Update(float dt)
{
m_SceneManager.Update(dt);
}
void ast::Application::Render()
{
m_WindowHandler.GetWindow().clear();
m_WindowHandler.SetView();
m_SceneManager.Render(m_WindowHandler.GetWindow());
m_WindowHandler.GetWindow().display();
}
void ast::Application::InitializeSeed()
{
rand.seed(std::random_device{}());
}
void ast::Application::CreateScenes()
{
// MainMenu:
auto mainMenu = std::make_shared<SceneMainMenu>();
mainMenu->SetManager(&m_SceneManager);
// SinglePlayer:
auto single = std::make_shared<SceneSinglePlayer>();
single->SetManager(&m_SceneManager);
// Adding scenes:
m_SceneManager.AddScene(SceneType::MainMenu, mainMenu);
m_SceneManager.AddScene(SceneType::SinglePlay, single);
// First scene:
m_SceneManager.SelectScene(SceneType::MainMenu);
}
| 20.261364 | 57 | 0.715648 | [
"render"
] |
0a13faf81f5d2ef513a094b90a2a08fab688ca52 | 1,803 | hh | C++ | gazebo/gui/DiagnosticsPrivate.hh | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-14T19:36:51.000Z | 2020-04-01T06:47:59.000Z | gazebo/gui/DiagnosticsPrivate.hh | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | gazebo/gui/DiagnosticsPrivate.hh | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015-2016 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GAZEBO_GUI_DIAGNOSTICSPRIVATE_HH_
#define _GAZEBO_GUI_DIAGNOSTICSPRIVATE_HH_
#include <list>
#include <map>
#include <mutex>
#include <vector>
#include "gazebo/gui/qt.h"
#include "gazebo/transport/TransportTypes.hh"
namespace gazebo
{
namespace gui
{
class IncrementalPlot;
/// \brief Private data for the Diagnostics class
class DiagnosticsPrivate
{
/// \def PointMap
public: using PointMap = std::map<QString, std::list<QPointF> >;
/// \brief Node for communications.
public: transport::NodePtr node;
/// \brief Subscribes to diagnostic info.
public: transport::SubscriberPtr sub;
/// \brief The list of diagnostic labels.
public: QListWidget *labelList;
/// \brief The currently selected label.
public: PointMap selectedLabels;
/// \brief True when plotting is paused.
public: bool paused;
/// \brief Mutex to protect the point map
public: std::mutex mutex;
/// \brief Plotting widget
public: std::vector<IncrementalPlot *> plots;
/// \brief Layout to hold all the plots.
public: QVBoxLayout *plotLayout;
};
}
}
#endif
| 26.910448 | 75 | 0.69107 | [
"vector"
] |
0a247bdcfc4fdf0a6788f6ece21f485ba516edae | 1,611 | hpp | C++ | include/bridgingcommands.hpp | dcao-ampere/ampere-ipmi-oem | e71dce5b4a6dfd195c539360cdc98c2d2e2c2880 | [
"Apache-2.0"
] | 1 | 2022-03-09T05:51:47.000Z | 2022-03-09T05:51:47.000Z | include/bridgingcommands.hpp | ampere-openbmc/ampere-ipmi-oem | 308491a1649c464cf39029ee42bcf8674948bf09 | [
"Apache-2.0"
] | null | null | null | include/bridgingcommands.hpp | ampere-openbmc/ampere-ipmi-oem | 308491a1649c464cf39029ee42bcf8674948bf09 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2018-2021 Ampere Computing LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <ipmid/api.hpp>
#include <sdbusplus/message.hpp>
#include <sdbusplus/server/interface.hpp>
struct IpmbResponse
{
uint8_t address;
uint8_t netFn;
uint8_t rqLun;
uint8_t rsSA;
uint8_t seq;
uint8_t rsLun;
uint8_t cmd;
uint8_t completionCode;
std::vector<uint8_t> data;
IpmbResponse(uint8_t address, uint8_t netFn, uint8_t rqLun, uint8_t rsSA,
uint8_t seq, uint8_t rsLun, uint8_t cmd,
uint8_t completionCode, std::vector<uint8_t>& inputData);
void ipmbToi2cConstruct(uint8_t* buffer, size_t* bufferLength);
};
/** @class Bridging
*
* @brief Implement commands to support IPMI bridging.
*/
class Bridging
{
public:
Bridging() = default;
std::size_t getResponseQueueSize();
void clearResponseQueue();
void insertMessageInQueue(IpmbResponse msg);
IpmbResponse getMessageFromQueue();
void eraseMessageFromQueue();
private:
std::vector<IpmbResponse> responseQueue;
};
| 27.775862 | 77 | 0.713222 | [
"vector"
] |
0a32583b2efacd1025553fb466926a176d78046a | 8,078 | cpp | C++ | BGE/assign.cpp | KeithCa/BGE3 | e196be96859539970563689acf27042b6107f171 | [
"MIT"
] | null | null | null | BGE/assign.cpp | KeithCa/BGE3 | e196be96859539970563689acf27042b6107f171 | [
"MIT"
] | null | null | null | BGE/assign.cpp | KeithCa/BGE3 | e196be96859539970563689acf27042b6107f171 | [
"MIT"
] | null | null | null | #include "Content.h"
#include "VectorDrawer.h"
#include "GravityController.h"
#include "Box.h"
#include "Sphere.h"
#include "Capsule.h"
#include "Cylinder.h"
#include "Steerable2DController.h"
#include "Steerable3DController.h"
#include "PhysicsFactory.h"
#include <btBulletDynamicsCommon.h>
#include "Utils.h"
#include "assign.h"
using namespace BGE;
assign::assign(void)
{
}
assign::~assign(void)
{
}
bool assign::Initialise()
{
physicsFactory->CreateGroundPhysics();
physicsFactory->CreateCameraPhysics();
dynamicsWorld->setGravity(btVector3(0, -9.0f, 0));
CreateMan(glm::vec3(20, 9, 0));
CreateDog(glm::vec3(0, 0, 0));
return Game::Initialise();
}
void BGE::assign::Update()
{
}
void BGE::assign::Cleanup()
{
Game::Cleanup();
}
void BGE::assign::CreateMan(glm::vec3 position){
float bodyX = 4.0f;
float bodyY = 7.0f;
glm::quat q = glm::angleAxis(-90.0f, glm::vec3(0, 1, 0));
glm::quat q2 = glm::angleAxis(-90.0f, glm::vec3(0, 0, 1));
std::shared_ptr<GameComponent> base_ = make_shared<Box>(bodyX, bodyY, 2.0f);
std::shared_ptr<PhysicsController> base = physicsFactory->CreateBox(bodyX, bodyY, 2.0f, position, base_->transform->orientation, false, true);
std::shared_ptr<PhysicsController> rleg = physicsFactory->CreateCapsule(.5, 1.5f, glm::vec3(position.x + 3, position.y - 4.5f, position.z), q);
std::shared_ptr<PhysicsController> lleg = physicsFactory->CreateCapsule(.5, 1.5f, glm::vec3(position.x - 3, position.y - 4.5f, position.z), q);
std::shared_ptr<PhysicsController> rhand = physicsFactory->CreateCapsule(.5, 1.5f, glm::vec3(position.x + 5, position.y + 2.5f, position.z), q2);
std::shared_ptr<PhysicsController> lhand = physicsFactory->CreateCapsule(.5, 1.5f, glm::vec3(position.x - 5, position.y + 2.5f, position.z), q2);
std::shared_ptr<PhysicsController> head = physicsFactory->CreateSphere(2.0f, glm::vec3(position.x, position.y + 5.5f, position.z), glm::quat());
btTransform t1, t2;
t1.setIdentity();
t2.setIdentity();
t1.setOrigin(btVector3(0, -2, 0));
t2.setOrigin(btVector3(0, 4, 0));
btFixedConstraint * headfixed = new btFixedConstraint(*head->rigidBody, *base->rigidBody, t1, t2);
btHingeConstraint *rleghinge = new btHingeConstraint(*rleg->rigidBody, *base->rigidBody, btVector3(0, 1.5f, 0), btVector3(3, -3, 0), btVector3(1, 0, 0), btVector3(1, 0, 0), false);
btHingeConstraint *lleghinge = new btHingeConstraint(*lleg->rigidBody, *base->rigidBody, btVector3(0, 1.5f, 0), btVector3(-3, -3, 0), btVector3(1, 0, 0), btVector3(1, 0, 0), false);
btHingeConstraint *rhandhinge = new btHingeConstraint(*rhand->rigidBody, *base->rigidBody, btVector3(0, -1.5f, 0), btVector3(3, 3, 0), btVector3(1, 1, 1), btVector3(1, 1, 1), false);
btHingeConstraint *lhandhinge = new btHingeConstraint(*lhand->rigidBody, *base->rigidBody, btVector3(0, 1.5f, 0), btVector3(-3, 3, 0), btVector3(1, 1, 1), btVector3(1, 1, 1), false);
rleghinge->enableAngularMotor(true, 20.0f, 20.0f);
lleghinge->enableAngularMotor(true, 20.0f, 20.0f);
dynamicsWorld->addConstraint(headfixed);
dynamicsWorld->addConstraint(lleghinge);
dynamicsWorld->addConstraint(rleghinge);
dynamicsWorld->addConstraint(lhandhinge);
dynamicsWorld->addConstraint(rhandhinge);
}
void BGE::assign::CreateDog(glm::vec3 position)
{
float x = -10;
float z = 20;
glm::quat q = glm::angleAxis(-90.0f, glm::vec3(1, 0, 0));
shared_ptr<PhysicsController> body = physicsFactory->CreateCapsule(2, 2.5, glm::vec3(x, 7, z), q);
shared_ptr<PhysicsController> head = physicsFactory->CreateSphere(2.0f, glm::vec3(x, 7, z), glm::quat());
btTransform t1, t2;
t1.setIdentity();
t2.setIdentity();
t1.setOrigin(btVector3(0, -3, 0));
t2.setRotation(GLToBtQuat(glm::angleAxis(-10.0f, glm::vec3(2.5, 1, 0))));
t2.setOrigin(btVector3(0, 3, 0));
btFixedConstraint * headfixed = new btFixedConstraint(*head->rigidBody, *body->rigidBody, t1, t2);
dynamicsWorld->addConstraint(headfixed);
shared_ptr<PhysicsController> frontleftshoulderjoint = physicsFactory->CreateCylinder(.5, .5, glm::vec3(x, 13, z), glm::quat());
shared_ptr<PhysicsController> frontleftleg = physicsFactory->CreateCapsule(.75f, 1, glm::vec3(x + 2.5, 7, z), glm::quat());
shared_ptr<PhysicsController> frontrightshoulderjoint = physicsFactory->CreateCylinder(.5, .5, glm::vec3(x, 13, z), glm::quat());
shared_ptr<PhysicsController> frontrightleg = physicsFactory->CreateCapsule(.75f, 1, glm::vec3(x + 2.5, 7, z), glm::quat());
shared_ptr<PhysicsController> backleftshoulderjoint = physicsFactory->CreateCylinder(.5, .5, glm::vec3(x, 13, z), glm::quat());
shared_ptr<PhysicsController> backleftleg = physicsFactory->CreateCapsule(.75, 1, glm::vec3(x + 2.5, 7, z), glm::quat());
shared_ptr<PhysicsController> backrightshoulderjoint = physicsFactory->CreateCylinder(.5, .5, glm::vec3(x, 13, z), glm::quat());
shared_ptr<PhysicsController> backrightleg = physicsFactory->CreateCapsule(.75, 1, glm::vec3(x + 2.5, 7, z), glm::quat());
btHingeConstraint *frontleftshoulder = new btHingeConstraint(*frontleftshoulderjoint->rigidBody, *body->rigidBody, btVector3(0, .5, 0), btVector3(2, 3.5, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *frontleftshoulderleg = new btHingeConstraint(*frontleftleg->rigidBody, *frontleftshoulderjoint->rigidBody, btVector3(0, 3.5, 0), btVector3(1, 1, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *frontrightshoulder = new btHingeConstraint(*frontrightshoulderjoint->rigidBody, *body->rigidBody, btVector3(0, -.5, 0), btVector3(-2, 3.5, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *frontrightshoulderleg = new btHingeConstraint(*frontrightleg->rigidBody, *frontrightshoulderjoint->rigidBody, btVector3(0, 3.5, 0), btVector3(1, -1, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *backleftshoulder = new btHingeConstraint(*backleftshoulderjoint->rigidBody, *body->rigidBody, btVector3(0, -.5, 0), btVector3(-2, -3.5, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *backleftshoulderleg = new btHingeConstraint(*backleftleg->rigidBody, *backleftshoulderjoint->rigidBody, btVector3(0, 3.5, 0), btVector3(1, -1, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *backrightshoulder = new btHingeConstraint(*backrightshoulderjoint->rigidBody, *body->rigidBody, btVector3(0, .5, 0), btVector3(2, -3.5, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
btHingeConstraint *backrightshoulderleg = new btHingeConstraint(*backrightleg->rigidBody, *backrightshoulderjoint->rigidBody, btVector3(0, 3.5, 0), btVector3(1, 1, 0), btVector3(0, 1, 0), btVector3(1, 0, 0), false);
float MaxMotor = -50.0f;
bool IsEnabled = true;
float Low = -1.5f;
float High = 1.5f;
frontleftshoulder->enableMotor(IsEnabled);
frontleftshoulder->setMaxMotorImpulse(MaxMotor);
frontleftshoulder->setLimit(Low, High);
frontrightshoulder->enableMotor(IsEnabled);
frontrightshoulder->setMaxMotorImpulse(MaxMotor);
frontrightshoulder->setLimit(Low, High);
backleftshoulder->enableMotor(IsEnabled);
backleftshoulder->setMaxMotorImpulse(MaxMotor);
backleftshoulder->setLimit(Low, High);
backrightshoulder->enableMotor(IsEnabled);
backrightshoulder->setMaxMotorImpulse(MaxMotor);
backrightshoulder->setLimit(Low, High);
dynamicsWorld->addConstraint(frontleftshoulder);
dynamicsWorld->addConstraint(frontleftshoulderleg);
dynamicsWorld->addConstraint(frontrightshoulder);
dynamicsWorld->addConstraint(frontrightshoulderleg);
dynamicsWorld->addConstraint(backleftshoulder);
dynamicsWorld->addConstraint(backleftshoulderleg);
dynamicsWorld->addConstraint(backrightshoulder);
dynamicsWorld->addConstraint(backrightshoulderleg);
shared_ptr<PhysicsController> tail = physicsFactory->CreateCapsule(.5, .5, glm::vec3(x + 2.5, 4, z - 2.5), glm::quat());
btHingeConstraint * hingetail = new btHingeConstraint(*tail->rigidBody, *body->rigidBody, btVector3(0, 2, 0), btVector3(0, -5, 0), btVector3(1, 1, 1), btVector3(0, 1, 0), false);
dynamicsWorld->addConstraint(hingetail);
//hingetail->enableAngularMotor(true, 20.0f, 20.0f);
} | 50.4875 | 220 | 0.732855 | [
"transform"
] |
0a39e05d00144178d7ccb350810603d523ab196d | 3,453 | cpp | C++ | Sources/Constructors.cpp | SalnikovDE/CppObject | 9e52f599a9d9ea31c074b40636c45ad20649d66a | [
"MIT"
] | null | null | null | Sources/Constructors.cpp | SalnikovDE/CppObject | 9e52f599a9d9ea31c074b40636c45ad20649d66a | [
"MIT"
] | null | null | null | Sources/Constructors.cpp | SalnikovDE/CppObject | 9e52f599a9d9ea31c074b40636c45ad20649d66a | [
"MIT"
] | null | null | null | //
// Created by danil on 04.11.2021.
//
#include "../Headers/Object.h"
namespace CppObject
{
Object::Object()
{
type = None;
}
Object::Object(int n) :
type(Int),
container((void *) new int(n))
{}
Object::Object(double d) :
type(Double),
container((void *) new double(d))
{}
Object::Object(const std::string &s) :
type(String),
container((void *) new std::string(s))
{}
Object::Object(const List &list) :
type(ListType),
container((void *) new List(list))
{}
Object::Object(const MapType &map) :
type(ObjectType),
container((void *) new MapType(map))
{
}
Object::Object(const Object &obj) :
type(obj.type),
container(allocateObject(obj))
{
}
Object::Object(const Callable &f) :
type(CallableType),
container((void *) new Callable(f))
{
}
void *Object::allocateObject(const Object &obj)
{
switch (obj.type)
{
case None:
return nullptr;
case Int:
return new int(*((int *) obj.container));
case Double:
return new double(*((double *) obj.container));
case String:
return (void *) new std::string(*((std::string *) obj.container));
case ObjectType:
return (void *) new MapType(
*((MapType *) obj.container));
case ListType:
return (void *) new List(*((List *) obj.container));
case CallableType:
return (void *) new Callable(*((Callable *)obj.container));
}
return nullptr;
}
Object::~Object()
{
switch (type)
{
case None:
return;
case Int:
delete (int *) container;
break;
case Double:
delete (double *) container;
break;
case String:
delete (std::string *) container;
break;
case ObjectType:
delete (MapType *) container;
break;
case ListType:
delete (List *) container;
break;
case CallableType:
delete (Callable *) container;
break;
}
}
Object &Object::operator=(const Object &a)
{
switch (type)
{
case None:
break;
case Int:
delete (int *) container;
break;
case Double:
delete (double *) container;
break;
case String:
delete (std::string *) container;
break;
case ObjectType:
delete (MapType *) container;
break;
case ListType:
delete (std::vector<Object> *) container;
break;
}
type = a.type;
container = allocateObject(a);
return *this;
}
Object &Object::operator=(const char *s)
{
return operator=(std::string(s));
}
} | 25.20438 | 83 | 0.427454 | [
"object",
"vector"
] |
0a3cce9e4191ee209e5968dd1568640de2fe4731 | 3,136 | hpp | C++ | include/codegen/include/GlobalNamespace/VRsenalLogger.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/VRsenalLogger.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/VRsenalLogger.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: ScenesTransitionSetupDataSO
class ScenesTransitionSetupDataSO;
// Forward declaring type: StringSignal
class StringSignal;
// Forward declaring type: VRsenalScoreLogger
class VRsenalScoreLogger;
// Forward declaring type: GameScenesManager
class GameScenesManager;
}
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: VRsenalLogger
class VRsenalLogger : public UnityEngine::MonoBehaviour {
public:
// private ScenesTransitionSetupDataSO _standardLevelScenesTransitionSetupData
// Offset: 0x18
GlobalNamespace::ScenesTransitionSetupDataSO* standardLevelScenesTransitionSetupData;
// private ScenesTransitionSetupDataSO _tutorialScenesTransitionSetupData
// Offset: 0x20
GlobalNamespace::ScenesTransitionSetupDataSO* tutorialScenesTransitionSetupData;
// private StringSignal _playerNameWasEnteredSignal
// Offset: 0x28
GlobalNamespace::StringSignal* playerNameWasEnteredSignal;
// private VRsenalScoreLogger _vRsenalScoreLoggerPrefab
// Offset: 0x30
GlobalNamespace::VRsenalScoreLogger* vRsenalScoreLoggerPrefab;
// private GameScenesManager _gameScenesManager
// Offset: 0x38
GlobalNamespace::GameScenesManager* gameScenesManager;
// protected System.Void Awake()
// Offset: 0xC54DE0
void Awake();
// protected System.Void OnDestroy()
// Offset: 0xC54EC8
void OnDestroy();
// private System.Void HandleGameScenesManagerInstallEarlyBindings(ScenesTransitionSetupDataSO scenesTransitionSetupData, Zenject.DiContainer container)
// Offset: 0xC54FB0
void HandleGameScenesManagerInstallEarlyBindings(GlobalNamespace::ScenesTransitionSetupDataSO* scenesTransitionSetupData, Zenject::DiContainer* container);
// private System.Void HandlePlayerNameWasEntered(System.String playerName)
// Offset: 0xC55108
void HandlePlayerNameWasEntered(::Il2CppString* playerName);
// public System.Void .ctor()
// Offset: 0xC55190
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static VRsenalLogger* New_ctor();
}; // VRsenalLogger
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::VRsenalLogger*, "", "VRsenalLogger");
#pragma pack(pop)
| 41.813333 | 159 | 0.755102 | [
"object"
] |
0a40120efe4ee3d293973cc469d2d0a693dc06d1 | 12,906 | cpp | C++ | src/test/fir_filter_bank.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | 12 | 2021-07-07T14:37:20.000Z | 2022-03-07T16:43:47.000Z | src/test/fir_filter_bank.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | null | null | null | src/test/fir_filter_bank.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | 3 | 2021-04-03T13:36:02.000Z | 2021-12-28T20:21:10.000Z | #include <iostream>
#include <vector>
#include <sstream>
#include <chrono>
#include <string>
#include <stdexcept>
#include <random>
#include "gtest/gtest.h"
#include "bakuage/utils.h"
#include "bakuage/delay_filter.h"
#include "bakuage/fir_design.h"
#include "bakuage/fir_filter.h"
#include "bakuage/fir_filter_bank.h"
namespace {
struct FirFilterBankTestParam {
int process_size;
int fir_size;
int decimation;
float bg_freq;
float ed_freq;
// 2は他のバンドの影響を受けないかの確認用。結果の確認には使わない
int fir_size2;
int decimation2;
const char *name;
friend std::ostream& operator<<(std::ostream& os, const FirFilterBankTestParam& param) {
os << "FirFilterBankTestParam"
<< " name " << (param.name ? param.name : "no name")
<< " process_size " << param.process_size
<< " fir_size " << param.fir_size
<< " decimation " << param.decimation
<< " bg_freq " << param.bg_freq
<< " ed_freq " << param.ed_freq
<< " fir_size2 " << param.fir_size2
<< " decimation2 " << param.decimation2
;
return os;
}
};
const FirFilterBankTestParam test_params[] = {
#if 1
{ 1, 1, 1, 0, 0.5, 1, 1, "trivial" },
{ 2, 1, 1, 0, 0.5, 1, 1, "trivial + process size" },
{ 256, 1, 1, 0, 0.5, 1, 1, "trivial + large process size" },
{ 128, 3, 1, 0, 0.5, 1, 1, "trivial + fir size" },
{ 1, 65, 1, 0, 0.5, 1, 1, "trivial + large fir size" },
{ 1, 1, 1, 0.1, 0.2, 1, 1, "trivial + freq" },
{ 2, 1, 1, 0, 0.5, 1, 2, "trivial + band2 decimation" }, // ここでanalysis_output_bufferがおかしくなることがある (多分すでに修正済みのメモリ破壊)
{ 1, 1, 1, 0, 0.5, 3, 1, "trivial + band2 fir size" },
{ 2, 1, 1, 0, 0.5, 3, 2, "trivial + band2 fir size + decimation" },
{ 1, 65, 1, 0.0, 0.5, 1, 1, "large flat fir" },
{ 1, 65, 1, 0.0, 0.1, 1, 1, "large lowpass fir" },
{ 1, 65, 1, 0.4, 0.5, 1, 1, "large highpass fir" },
{ 1, 65, 1, 0.5, 1.0, 1, 1, "large hilbert fir" },
{ 1, 65, 1, 0.1, 0.2, 1, 1, "large band pass fir" },
{ 1, 65, 1, 0.1, 0.2, 1, 1, "large band pass fir 2" },
{ 256, 65, 1, 0.1, 0.2, 1, 1, "large band pass fir + large process size" },
{ 2, 65, 2, 0.1, 0.2, 1, 1, "large band pass fir + decimation" },
{ 4, 129, 4, 0.1, 0.2, 1, 1, "large band pass fir + decimation 4" },
#endif
};
class FirFilterBankTest : public ::testing::TestWithParam<FirFilterBankTestParam> {};
template <class Float>
std::vector<std::complex<Float>> HilbertTransform(const std::vector<std::complex<Float>> &input) {
std::vector<std::complex<Float>> output(input);
std::vector<std::complex<Float>> temp(input);
const int len = input.size();
bakuage::Dft<Float> dft(len);
dft.Forward((Float *)input.data(), (Float *)temp.data());
temp[0] *= 0.5;
if (len % 2 == 0) {
temp[len / 2] *= 0.5;
}
for (int i = len / 2 + 1; i < len; i++) temp[i] = 0;
for (int i = 0; i < len; i++) temp[i] /= len;
dft.Backward((Float *)temp.data(), (Float *)output.data());
return output;
}
}
// テスト補足
// filter設計
// keiser窓で窓関数法で設計している。decimationのテストもしているので、
// エイリアシングノイズが意図通りのレベルになっているかも確認できているはず。
// analysis
// ランダムな信号を入力し、通常のFirFilterの出力と比較するテスト
#if 1
TEST_P(FirFilterBankTest, Analysis) {
typedef float Float;
using namespace bakuage;
typedef FirFilterBank<Float> FilterBank;
const auto param = GetParam();
FilterBank::Config config;
FilterBank::BandConfig band;
// http://www.mk.ecei.tohoku.ac.jp/jspmatlab/pdf/matdsp4.pdf
const auto fir = CalculateBandPassFirComplex<Float>(param.bg_freq, param.ed_freq, param.fir_size, 7);
// 一つ目のバンドを作る
band.decimation = param.decimation;
band.analysis_fir = AlignedPodVector<std::complex<Float>>(fir.begin(), fir.end());
band.nonzero_base_normalized_freq = (param.bg_freq + param.ed_freq) / 2 - 0.5 / param.decimation; // 帯域がdecimate後の領域の真ん中にくるようにする
config.bands.emplace_back(band);
// 適当に二つ目のバンドを作る
band.decimation = param.decimation2;
band.analysis_fir.resize(param.fir_size2);
for (int i = 0; i < param.fir_size2; i++) band.analysis_fir[i] = i;
band.nonzero_base_normalized_freq = (param.bg_freq + param.ed_freq) / 2;
config.bands.emplace_back(band);
FilterBank filter_bank(config);
FirFilter<std::complex<Float>> reference_filter(fir.begin(), fir.end());
const int process_size = param.process_size;
std::mt19937 engine(1);
std::uniform_real_distribution<> dist(-1.0, 1.0);
for (int i = 0; i < 100 * param.fir_size / process_size + 1; i++) {
std::vector<Float> input(process_size);
for (int j = 0; j < process_size; j++) {
input[j] = dist(engine);
}
std::vector<std::complex<Float>> reference_output(process_size);
for (int j = 0; j < process_size; j++) {
reference_output[j] = reference_filter.Clock(input[j]);
}
std::vector<std::complex<Float>> output(process_size / param.decimation);
std::vector<std::complex<Float>> output2(process_size / param.decimation2);
std::complex<Float> *output_ptr[2];
output_ptr[0] = output.data();
output_ptr[1] = output2.data();
filter_bank.AnalysisClock(input.data(), input.data() + process_size, output_ptr);
for (int j = 0; j < process_size / param.decimation; j++) {
EXPECT_LT(std::abs(reference_output[param.decimation * j] - output[j]), 1e-6);
}
}
}
#endif
// synthesis
// ランダムな信号を入力し、通常のFirFilterの出力と比較するテスト
#if 1
TEST_P(FirFilterBankTest, Synthesis) {
typedef float Float;
using namespace bakuage;
typedef FirFilterBank<Float> FilterBank;
const auto param = GetParam();
FilterBank::Config config;
FilterBank::BandConfig band;
// http://www.mk.ecei.tohoku.ac.jp/jspmatlab/pdf/matdsp4.pdf
const auto fir = CalculateBandPassFirComplex<Float>(param.bg_freq, param.ed_freq, param.fir_size, 7);
// 一つ目のバンドを作る
band.decimation = param.decimation;
#if 0
band.fir = AlignedPodVector<std::complex<Float>>(fir_hilbert.begin(), fir_hilbert.end());
#else
band.synthesis_fir = AlignedPodVector<std::complex<Float>>(fir.begin(), fir.end());
#endif
band.nonzero_base_normalized_freq = (param.bg_freq + param.ed_freq) / 2 - 0.5 / param.decimation; // 帯域がdecimate後の領域の真ん中にくるようにする
config.bands.emplace_back(band);
// 適当に二つ目のバンドを作る
band.decimation = param.decimation2;
band.synthesis_fir.resize(param.fir_size2);
for (int i = 0; i < param.fir_size2; i++) band.synthesis_fir[i] = i;
band.nonzero_base_normalized_freq = (param.bg_freq + param.ed_freq) / 2;
config.bands.emplace_back(band);
FilterBank filter_bank(config);
#if 0
FirFilter<std::complex<Float>> reference_filter(fir_hilbert.begin(), fir_hilbert.end());
#else
FirFilter<std::complex<Float>> reference_filter(fir.begin(), fir.end());
#endif
const int process_size = param.process_size;
std::mt19937 engine(1);
std::uniform_real_distribution<> dist(-1.0, 1.0);
for (int i = 0; i < 100 * param.fir_size / process_size + 1; i++) {
std::vector<std::complex<Float>> input(process_size);
std::vector<std::complex<Float>> input2(process_size);
for (int j = 0; j < process_size / param.decimation; j++) {
input[j] = std::complex<Float>(dist(engine), dist(engine));
}
for (int j = 0; j < process_size / param.decimation2; j++) {
input2[j] = 0; // std::complex<Float>(dist(engine), dist(engine));
}
std::vector<Float> reference_output(process_size);
for (int j = 0; j < process_size; j++) {
if (j % param.decimation == 0) {
reference_output[j] = reference_filter.Clock(input[j / param.decimation]).real() * param.decimation;
} else {
reference_output[j] = reference_filter.Clock(std::complex<Float>(0.0f, 0.0f)).real() * param.decimation;
}
}
std::vector<Float> output(process_size);
const std::complex<Float> *input_ptr[2];
input_ptr[0] = input.data();
input_ptr[1] = input2.data();
filter_bank.SynthesisClock(input_ptr, process_size, output.data());
for (int j = 0; j < process_size / param.decimation; j++) {
EXPECT_LT(std::abs(reference_output[j] - output[j]), 1e-6);
}
}
}
#endif
#if 1
// reconstruction test
// 完全再構成のフィルタバンクを作って
// ランダムな信号を与えて、analysis -> synthesisとやって、元に戻るか観察するテスト
// バンド境界でちゃんと戻るかがポイント
TEST(FirFilterBank, Reconstruction) {
typedef float Float;
using namespace bakuage;
typedef FirFilterBank<Float> FilterBank;
FilterBank::Config config;
const int fir_size = 129;
const int delay = 2 * ((fir_size - 1) / 2);
const float freqs[] = { 0, 0.5, 1.0 };
std::vector<std::complex<Float>> sum_fir(fir_size);
for (int i = 0; i < 2; i++) {
FilterBank::BandConfig band;
// http://www.mk.ecei.tohoku.ac.jp/jspmatlab/pdf/matdsp4.pdf
const auto fir = CalculateBandPassFirComplex<Float>(freqs[i], freqs[i + 1], fir_size, 7);
const float band_width = freqs[i + 1] - freqs[i];
const float center_freq = (freqs[i + 1] + freqs[i]) / 2;
band.decimation = std::max<int>(1, std::floor(1.0 / (1.2 * band_width)));
const float min_freq = center_freq - 0.5 / band.decimation;
const float max_freq = center_freq + 0.5 / band.decimation;
band.analysis_fir = AlignedPodVector<std::complex<Float>>(fir.begin(), fir.end());
const auto synthesis_fir = CalculateBandPassFirComplex<Float>((freqs[i] + min_freq) / 2, (freqs[i + 1] + max_freq) / 2, fir_size, 7);
band.synthesis_fir = AlignedPodVector<std::complex<Float>>(synthesis_fir.begin(), synthesis_fir.end());
band.nonzero_base_normalized_freq = min_freq; // 帯域がdecimate後の領域の真ん中にくるようにする
config.bands.emplace_back(band);
for (int i = 0; i < fir_size; i++) {
sum_fir[i] += fir[i];
}
}
for (int i = 0; i < fir_size; i++) {
if (i == fir_size / 2) {
EXPECT_LT(std::abs(sum_fir[i] - std::complex<Float>(1, 0)), 1e-6);
} else {
EXPECT_LT(std::abs(sum_fir[i]), 1e-6);
}
}
FilterBank filter_bank(config);
DelayFilter<Float> delay_filter(delay);
DelayFilter<Float> half_delay_filter(delay / 2);
const int process_size = 256;
std::mt19937 engine(1);
std::uniform_real_distribution<> dist(-1.0, 1.0);
for (int i = 0; i < 10 * fir_size / process_size + 1; i++) {
std::vector<Float> input(process_size);
for (int j = 0; j < process_size; j++) {
input[j] = dist(engine);
}
std::vector<Float> reference_output(process_size);
std::vector<Float> reference_output_half(process_size);
for (int j = 0; j < process_size; j++) {
reference_output[j] = delay_filter.Clock(input[j]);
reference_output_half[j] = half_delay_filter.Clock(input[j]);
}
std::vector<std::vector<std::complex<Float>>> outputs;
std::vector<std::complex<Float> *> output_ptr;
std::vector<const std::complex<Float> *> const_output_ptr;
for (int k = 0; k < config.bands.size(); k++) {
outputs.emplace_back(process_size / config.bands[k].decimation);
}
for (int k = 0; k < config.bands.size(); k++) {
output_ptr.emplace_back(outputs[k].data());
const_output_ptr.emplace_back(outputs[k].data());
}
filter_bank.AnalysisClock(input.data(), input.data() + process_size, output_ptr.data());
#if 1
std::vector<std::complex<Float>> sum_output(process_size);
for (int k = 0; k < outputs.size(); k++) {
for (int j = 0; j < process_size; j++) {
sum_output[j] += outputs[k][j];
}
}
for (int j = 0; j < process_size; j++) {
EXPECT_LT(std::abs(reference_output_half[j] - sum_output[j]), 1e-6);
}
#endif
std::vector<Float> reconstruct(process_size);
filter_bank.SynthesisClock(const_output_ptr.data(), process_size, reconstruct.data());
for (int j = 0; j < process_size; j++) {
EXPECT_LT(std::abs(reference_output[j] - reconstruct[j]), 1e-6);
}
}
}
#endif
INSTANTIATE_TEST_CASE_P(FirFilterBankTestInstance,
FirFilterBankTest,
::testing::ValuesIn(test_params));
| 39.227964 | 141 | 0.594762 | [
"vector"
] |
0a4146ea5ef5bedbeec0b29cea6e0a03374d5da2 | 9,220 | cpp | C++ | src/fifo-query.cpp | eggeek/RoutingKit | 677fec8f1712e6de95844c14035683358cb92842 | [
"BSD-2-Clause"
] | null | null | null | src/fifo-query.cpp | eggeek/RoutingKit | 677fec8f1712e6de95844c14035683358cb92842 | [
"BSD-2-Clause"
] | null | null | null | src/fifo-query.cpp | eggeek/RoutingKit | 677fec8f1712e6de95844c14035683358cb92842 | [
"BSD-2-Clause"
] | null | null | null | #include <sys/stat.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <csignal>
#include <omp.h>
#include <fstream>
#include <iostream>
#include <routingkit/vector_io.h>
#include <routingkit/permutation.h>
#include <routingkit/inverse_vector.h>
#include <routingkit/customizable_contraction_hierarchy.h>
#include <routingkit/nested_dissection.h>
#include <routingkit/graph_util.h>
#include <routingkit/min_max.h>
#include <routingkit/timer.h>
#include <routingkit/permutation.h>
#include "cfg.h"
#include "log.h"
#include "warthog_timer.h"
#include "json_config.h"
#include "json.h"
using namespace RoutingKit;
using namespace std;
// get the index of an edge <u, v>
map<pair<unsigned, unsigned>, unsigned> idx;
vector<unsigned> first_out, tail, head, weight, order;
vector<CustomizableContractionHierarchyQuery> algos;
string first_out_file, head_file, weight_file, order_file;
string fifo = "/tmp/cchfifo";
CustomizableContractionHierarchy cch;
CustomizableContractionHierarchyMetric metric;
CustomizableContractionHierarchyPartialCustomization partial_update;
warthog::util::cfg cfg;
void
signalHandler(int signum)
{
warning(true, "Interrupt signal", signum, "received.");
remove(fifo.c_str());
exit(signum);
}
struct Query {
int s, t;
};
struct Perturb {
unsigned u, v, w;
};
double run_customization(config& conf, vector<Perturb>& diffs) {
trace(conf.verbose, "Preparing to perturb", diffs.size(), "edges.");
warthog::timer t;
double custnano = 0;
t.start();
partial_update.reset();
for (auto& diff: diffs) {
auto eid = idx[{diff.u, diff.v}];
weight[eid] = diff.w;
partial_update.update_arc(eid);
}
partial_update.customize(metric);
t.stop();
custnano = t.elapsed_time_nano();
trace(conf.verbose, "Processed", diffs.size(), "edges in ", t.elapsed_time_nano(), "us.");
return custnano;
}
void run_experiment(config& conf,
vector<Query>& queries, string& fifo_out,
const double& custnano, const double& pertubnano, const double& t_read) {
size_t n_results = queries.size();
vector<vector<unsigned>> paths;
warthog::timer t, tquery;
long long t_query = 0, t_ext = 0;
streambuf* buf;
ofstream of;
if (fifo_out == "-")
{
buf = std::cout.rdbuf();
}
else
{
of.open(fifo_out);
buf = of.rdbuf();
}
ostream out(buf);
#ifdef SINGLE_THREADED
unsigned int threads = 1;
#else
unsigned int threads = conf.threads;
#endif
user(conf.verbose, "Preparing to process", queries.size(), "queries using",
(int)threads, "threads.");
paths.resize(algos.size());
t.start();
#pragma omp parallel num_threads(threads) \
reduction(+ : t_query, t_ext)
{
// Parallel data
unsigned int thread_count = omp_get_num_threads();
unsigned int thread_id = omp_get_thread_num();
warthog::timer t_thread;
size_t from = 0;
size_t to = n_results;
if (!conf.thread_alloc)
{
// Instead of bothering with manual conversion (think 'ceil()'), we
// use the magic of "usual arithmetic" to achieve the right from/to
// values.
size_t step = n_results * thread_id;
from = step / thread_count;
to = (step + n_results) / thread_count;
}
CustomizableContractionHierarchyQuery& algo = algos[thread_id];
auto& path = paths[thread_id];
t_thread.start();
for (size_t i=from; i<to; i++) {
const Query& q = queries[i];
tquery.start();
algo.reset().add_source(q.s).add_target(q.t).run();
auto d = algo.get_distance();
tquery.stop();
t_query += tquery.elapsed_time_nano();
tquery.start();
path = algo.get_node_path();
tquery.stop();
t_query += tquery.elapsed_time_nano();
t_ext += tquery.elapsed_time_nano();
}
t_thread.stop();
#pragma omp critical
trace(conf.verbose, "[", thread_id, "] Processed", to - from,
"trips in", t_thread.elapsed_time_nano(), "us.");
}
t.stop();
user(conf.verbose, "Processed", n_results, "in", t.elapsed_time_nano(), "us.");
out << (long long)t_query << "," // time cost on query
<< (long long)t_ext << "," // time cost on path extraction
<< (long long)t.elapsed_time_nano() << "," // time cost on entire function
<< (long long)custnano << "," // time cost on customize
<< (long long)pertubnano << "," // time cost on perturbation
<< (long long)t_read // time cost on reading
<< endl;
if (fifo_out != "-") { of.close(); }
}
void load_queries(string& qfile, config& conf, vector<Query>& queries) {
if (qfile == "-") {
debug(conf.verbose, "No query file, skip.");
return;
}
debug(conf.verbose, "Reading queries from", qfile);
size_t s = 0;
ifstream fd(qfile);
fd >> s;
debug(conf.verbose, "Preparing to read", s, "items.");
queries.resize(s);
for (size_t i=0; i<s; i++)
fd >> queries[i].s >> queries[i].t;
trace(conf.verbose, "Read", queries.size(), "queries.");
fd.close();
}
void load_diff(string& dfile, config& conf, vector<Perturb>& diffs) {
if (dfile == "-") {
debug(conf.verbose, "No diff file, skip.");
return;
}
debug(conf.verbose, "Reading diff from", dfile);
size_t s = 0;
ifstream fd(dfile);
fd >> s;
debug(conf.verbose, "Preparing to read", s, "perturbations.");
diffs.resize(s);
for (size_t i=0; i<s; i++) {
fd >> diffs[i].u >> diffs[i].v >> diffs[i].w;
}
trace(conf.verbose, "Read", s, "perturbations.");
fd.close();
}
void run_cch() {
warthog::timer t;
fstream fd;
config conf;
string fifo_out, qfile, dfile;
vector<Query> queries;
vector<Perturb> diffs;
double custnano = 0;
double pertubnano = 0;
cch = CustomizableContractionHierarchy(order, tail, head, [](const std::string&){}, true);
metric = CustomizableContractionHierarchyMetric(cch, weight);
partial_update = CustomizableContractionHierarchyPartialCustomization(cch);
t.start();
metric.customize();
t.stop();
custnano = t.elapsed_time_nano();
for (auto& algo: algos) {
algo = CustomizableContractionHierarchyQuery(metric);
}
debug(true, "Customization:", t.elapsed_time_nano(), " us");
while (true) {
fd.open(fifo);
debug(VERBOSE, "waiting for writers...");
if (fd.good())
{
debug(VERBOSE, "Got a writer");
}
t.start();
// Start by reading config
try
{
fd >> conf;
} // Ignore bad parsing and fall back on default conf
catch (std::exception& e)
{
debug(conf.verbose, e.what());
}
trace(conf.verbose, conf);
fd >> qfile >> dfile >> fifo_out;
debug(conf.verbose, "Output to", fifo_out);
load_queries(qfile, conf, queries);
load_diff(dfile, conf, diffs);
t.stop();
if (diffs.size()) {
pertubnano = run_customization(conf, diffs);
}
if (queries.size()) {
run_experiment(conf, queries, fifo_out, custnano, pertubnano, t.elapsed_time_nano());
}
}
}
int main(int argc, char* argv[]) {
// run command
// ./fifo --input <first_out_file> [head_file] [weight_file] [order_file] [--fifo fifo name]
// parse arguments
warthog::util::param valid_args[] =
{
{"input", required_argument, 0, 1},
{"fifo", required_argument, 0, 1},
{"alg", required_argument, 0, 1},
{"div", required_argument, 0, 1},
{"mod", required_argument, 0, 1},
{"num", required_argument, 0, 1},
// {"problem", required_argument, 0, 1},
{0, 0, 0, 0}
};
cfg.parse_args(argc, argv, "-f", valid_args);
first_out_file = cfg.get_param_value("input");
if (first_out_file == "") {
std::cerr << "parameter is missing: --input\n";
return EXIT_FAILURE;
}
head_file = cfg.get_param_value("input");
if (head_file == "") {
head_file = first_out_file.substr(0, first_out_file.find_last_of(".")) + ".head";
}
weight_file = cfg.get_param_value("input");
if (weight_file== "") {
weight_file = first_out_file.substr(0, first_out_file.find_last_of(".")) + ".weight";
}
order_file = cfg.get_param_value("input");
if (order_file == "") {
order_file = first_out_file.substr(0, first_out_file.find_last_of(".")) + ".cch_order";
}
#ifdef SINGLE_THREADED
algos.resize(1);
#else
algos.resize(omp_get_max_threads());
#endif
string other = cfg.get_param_value("fifo");
if (other != "") {
fifo = other;
}
// create fifo
int status = mkfifo(fifo.c_str(), S_IFIFO | 0666);
if (status < 0)
{
perror("mkfifo");
return EXIT_FAILURE;
}
debug(true, "Reading from", fifo);
// Register signal handlers
signal(SIGINT, signalHandler);
signal(SIGTERM, signalHandler);
signal(SIGABRT, signalHandler);
first_out = load_vector<unsigned>(first_out_file);
tail = invert_inverse_vector(first_out);
head = load_vector<unsigned>(head_file);
weight = load_vector<unsigned>(weight_file);
order = load_vector<unsigned>(order_file);
// init index
for (size_t i=0; i<tail.size(); i++) {
idx[{tail[i], head[i]}] = i;
}
run_cch();
signalHandler(EXIT_FAILURE);
}
| 27.60479 | 94 | 0.634056 | [
"vector"
] |
0a4270788a3d5c1beb617f24a3c525d5c9384001 | 2,280 | cpp | C++ | src/app/qranker-barista/BipartiteGraph.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | 8 | 2018-02-26T00:56:14.000Z | 2021-10-31T03:45:53.000Z | src/app/qranker-barista/BipartiteGraph.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | src/app/qranker-barista/BipartiteGraph.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | #include "BipartiteGraph.h"
void BipartiteGraph::create_bipartite_graph(map<int, set<int> > data)
{
int n = data.size();
//allocate the range array
ranges = new Range[n];
nranges = 0;
nindices = 0;
int max_len = 0;
for(map <int, set<int> >::iterator it = data.begin(); it != data.end(); it++)
{
int len = 0;
for(set<int>::iterator itp = (it->second).begin(); itp != (it->second).end(); itp++)
{
len++;
nindices++;
}
if(len > max_len)
max_len = len;
int ind = it->first;
ranges[ind].len = len;
nranges++;
}
indices = new int[nindices];
vector<int> t;
t.reserve(max_len);
set<int> s;
int pos = 0;
for (int i = 0; i < nranges; i++)
{
s = data[i];
t.erase(t.begin(),t.end());
for(set<int>::iterator itp = s.begin(); itp != s.end(); itp++)
t.push_back(*itp);
sort(t.begin(),t.end());
assert((int)t.size() == ranges[i].len);
ranges[i].p = pos;
for (unsigned int k = 0; k < t.size(); k++)
{
indices[pos] = t[k];
pos++;
}
}
}
void BipartiteGraph::save(ofstream &os)
{
os.write((char*)(&nranges),sizeof(int));
os.write((char*)(&nindices),sizeof(int));
os.write((char*)ranges,sizeof(Range)*nranges);
os.write((char*)indices,sizeof(int)*nindices);
}
void BipartiteGraph::load(ifstream &is)
{
is.read((char*)(&nranges),sizeof(int));
is.read((char*)(&nindices),sizeof(int));
ranges = new Range[nranges];
indices = new int[nindices];
is.read((char*)ranges,sizeof(Range)*nranges);
is.read((char*)indices,sizeof(int)*nindices);
}
bool BipartiteGraph::is_index_in_range(int index, int range)
{
assert(range < nranges);
for(int i = 0; i < ranges[range].len; i++)
{
int ofst = ranges[range].p+i;
if(indices[ofst] == index)
return true;
}
return false;
}
bool BipartiteGraph :: is_subset(int r1, int r2)
{
assert(r1 < nranges);
assert(r2 < nranges);
int len1 = ranges[r1].len;
int len2 = ranges[r2].len;
int *inds1 = indices+ranges[r1].p;
int *inds2 = indices+ranges[r2].p;
int i1 = 0;
int i2 = 0;
while(i1 < len1 && i2 < len2)
{
if(inds1[i1] == inds2[i2])
{
i1++;
i2++;
}
else if(inds1[i1] < inds2[i2])
i1++;
else
return false;
}
return true;
}
| 21.308411 | 90 | 0.574561 | [
"vector"
] |
0a45c764db8ceafad5930afdb07bafec468f3adc | 3,744 | cpp | C++ | src/graphics/Quad.cpp | RamilHinshaw/LotusEngine | 2bdd6ba9c67b70c6e0f4d5fea213ca113b869a5e | [
"MIT"
] | 1 | 2019-11-07T14:57:04.000Z | 2019-11-07T14:57:04.000Z | src/graphics/Quad.cpp | RamilHinshaw/LotusEngine | 2bdd6ba9c67b70c6e0f4d5fea213ca113b869a5e | [
"MIT"
] | null | null | null | src/graphics/Quad.cpp | RamilHinshaw/LotusEngine | 2bdd6ba9c67b70c6e0f4d5fea213ca113b869a5e | [
"MIT"
] | null | null | null | // #include "Quad.hpp"
// #include <iostream>
// Quad::Quad()
// {
// std::cout << "Quad Constructor Called" << std::endl;
// m_shader = generateShader();
// m_mesh = generatePrimative();
// }
// Quad::Quad(glm::vec3 position) : Quad()
// {
// m_transform->translate(position);
// }
// Quad::Quad(const Rect rect) : rect(rect)
// {
// m_shader = new Shader("./assets/shaders/basicShader");
// Vertex vertices[] = {
// //Positions //Colors //Texture Coordinates
// Vertex(glm::vec3(0.5, 0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 1.0f)),
// Vertex(glm::vec3(0.5, -0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)),
// Vertex(glm::vec3(-0.5, -0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.0f, 0.0f)),
// Vertex(glm::vec3(-0.5, 0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.0f, 1.0f)),
// //Vertex(glm::vec3(0.5, -0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)),
// //Vertex(glm::vec3(0.5, 0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 1.0f))
// };
// //Turn into class container (indice holding 3 ints)
// unsigned int indices[] = {
// 0, 2, 3, //first triangle
// 0, 1, 2 //second triangle
// };
// // m_mesh = new Mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), indices, sizeof(indices)/sizeof(indices[0]));
// // mesh = generatePrimative();
// // shader = generateShader();
// // std::cout << "Quad Generated!" << std::endl;
// }
// // Quad::Quad(const Rect rect, const Shader &shader) : rect(rect)//, shader(shader)
// // {
// // m_shader = &shader;
// // m_mesh = generatePrimative();
// // }
// // Shader& Quad::getShader()
// // {
// // return *m_shader;
// // }
// Quad::~Quad()
// {
// std::cout << "Quad out of scope!" << std::endl;
// }
// // void Quad::dispose()
// // {
// // std::cout << "Disposed Quad!" << std::endl;
// // m_mesh->dispose();
// // m_shader->dispose();
// // delete m_mesh;
// // m_mesh = nullptr;
// // delete m_shader;
// // m_shader = nullptr;
// // // std::cout << "Quad DISPOSED!" << std::endl;
// // }
// Mesh* Quad::generatePrimative()
// {
// Vertex vertices[] = {
// //Positions //Colors //Texture Coordinates
// Vertex(glm::vec3(0.5, 0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5f, 0.5f)),
// Vertex(glm::vec3(0.5, -0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5f, 0.0f)),
// Vertex(glm::vec3(-0.5, -0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.0f, 0.0f)),
// Vertex(glm::vec3(-0.5, 0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.0f, 0.5f)),
// //Vertex(glm::vec3(0.5, -0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)),
// //Vertex(glm::vec3(0.5, 0.5, 0), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 1.0f))
// };
// //Turn into class container (indice holding 3 ints)
// unsigned int indices[] = {
// 0, 2, 3, //first triangle
// 0, 1, 2 //second triangle
// };
// // return new Mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), indices, sizeof(indices)/sizeof(indices[0]));
// //return Mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), 0,0); //Unoptimized!
// //return Mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), GL_Triangle_Strip); //Optimized
// }
// // void Quad::draw()
// // {
// // m_shader->bind();
// // m_mesh->draw();
// // // std::cout << "Quad DRAWING!" << std::endl;
// // }
// Shader* Quad::generateShader()
// {
// //ToDo: PUT THIS IN SHADER STATEMANAGER SO WE DON'T BIND IDENTICAL SHADERS!
// return new Shader("./assets/shaders/basicShader");
// } | 29.714286 | 118 | 0.535791 | [
"mesh"
] |
0a4b3681af975b43b9fec367b7ab43077b540baf | 6,053 | hpp | C++ | src/resources/Program.hpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 8 | 2020-06-09T00:43:39.000Z | 2021-09-27T13:55:46.000Z | src/resources/Program.hpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 1 | 2020-06-09T02:38:55.000Z | 2020-06-09T13:28:13.000Z | src/resources/Program.hpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 3 | 2020-06-09T00:28:11.000Z | 2020-12-30T08:07:34.000Z | #pragma once
#include <glad/glad.h>
#include <type_traits>
#include <string>
#include <glm/glm.hpp>
#include <vector>
#include <memory>
#include "Shader.hpp"
namespace gl
{
class ProgramException : public std::runtime_error
{
public:
ProgramException(std::string what) : std::runtime_error(what) {}
};
class Program
{
static thread_local GLuint lastUsedProgram;
GLuint program;
void relink();
public:
Program() : program(0) {}
template <typename... Params>
Program(const Params&... params) : program(glCreateProgram())
{
static_assert((std::is_same_v<Params, Shader> && ...));
(glAttachShader(program, params.shader), ...);
relink();
}
Program(const std::vector<std::shared_ptr<Shader>>& shaders) : program(glCreateProgram())
{
for (auto shader : shaders)
glAttachShader(program, shader->shader);
relink();
}
// Disallow copying
Program(const Program&) = delete;
Program& operator=(const Program&) = delete;
// Enable moving
Program(Program&& o) noexcept : program(o.program) { o.program = 0; }
Program& operator=(Program&& o) noexcept
{
std::swap(program, o.program);
return *this;
}
void use() const;
bool isValid() const;
std::string getInfoLog() const;
void setName(const std::string& name) const;
// Attribute and uniform data
auto getAttributeLocation(const char* name) const { return glGetAttribLocation(program, name); }
auto getUniformLocation(const char* name) const { return glGetUniformLocation(program, name); }
auto getUniformBlockIndex(const char* name) const { return glGetUniformBlockIndex(program, name); }
// All uniform setting functons
void setUniform(const char* name, float value);
void setUniform(const char* name, const glm::vec1& value);
void setUniform(const char* name, const glm::vec2& value);
void setUniform(const char* name, const glm::vec3& value);
void setUniform(const char* name, const glm::vec4& value);
void setUniform(const char* name, int value);
void setUniform(const char* name, const glm::ivec1& value);
void setUniform(const char* name, const glm::ivec2& value);
void setUniform(const char* name, const glm::ivec3& value);
void setUniform(const char* name, const glm::ivec4& value);
void setUniform(const char* name, unsigned int value);
void setUniform(const char* name, const glm::uvec1& value);
void setUniform(const char* name, const glm::uvec2& value);
void setUniform(const char* name, const glm::uvec3& value);
void setUniform(const char* name, const glm::uvec4& value);
void setUniform(const char* name, const glm::mat2& value, bool transpose = false);
void setUniform(const char* name, const glm::mat3& value, bool transpose = false);
void setUniform(const char* name, const glm::mat4& value, bool transpose = false);
void setUniform(const char* name, const glm::mat2x3& value, bool transpose = false);
void setUniform(const char* name, const glm::mat3x2& value, bool transpose = false);
void setUniform(const char* name, const glm::mat2x4& value, bool transpose = false);
void setUniform(const char* name, const glm::mat4x2& value, bool transpose = false);
void setUniform(const char* name, const glm::mat3x4& value, bool transpose = false);
void setUniform(const char* name, const glm::mat4x3& value, bool transpose = false);
// Vector uniform setting functions
void setUniform(const char* name, const std::vector<float>& value);
void setUniform(const char* name, const std::vector<glm::vec1>& value);
void setUniform(const char* name, const std::vector<glm::vec2>& value);
void setUniform(const char* name, const std::vector<glm::vec3>& value);
void setUniform(const char* name, const std::vector<glm::vec4>& value);
void setUniform(const char* name, const std::vector<int>& value);
void setUniform(const char* name, const std::vector<glm::ivec1>& value);
void setUniform(const char* name, const std::vector<glm::ivec2>& value);
void setUniform(const char* name, const std::vector<glm::ivec3>& value);
void setUniform(const char* name, const std::vector<glm::ivec4>& value);
void setUniform(const char* name, const std::vector<unsigned int>& value);
void setUniform(const char* name, const std::vector<glm::uvec1>& value);
void setUniform(const char* name, const std::vector<glm::uvec2>& value);
void setUniform(const char* name, const std::vector<glm::uvec3>& value);
void setUniform(const char* name, const std::vector<glm::uvec4>& value);
void setUniform(const char* name, const std::vector<glm::mat2>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat3>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat4>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat2x3>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat3x2>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat2x4>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat4x2>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat3x4>& value, bool transpose = false);
void setUniform(const char* name, const std::vector<glm::mat4x3>& value, bool transpose = false);
void bindUniformBlock(const char* name, int index);
// Destructor
~Program();
};
}
| 48.424 | 107 | 0.646952 | [
"vector"
] |
aea7693e8d812ea462b49e5ce0ac37e0dd39a336 | 9,374 | cpp | C++ | src/states/PlayGameState_Render.cpp | Press-Play-On-Tape/PiCross_Pokitto | 8a08ac65d232c8457b2ee323be58c52f09757ced | [
"BSD-3-Clause"
] | null | null | null | src/states/PlayGameState_Render.cpp | Press-Play-On-Tape/PiCross_Pokitto | 8a08ac65d232c8457b2ee323be58c52f09757ced | [
"BSD-3-Clause"
] | null | null | null | src/states/PlayGameState_Render.cpp | Press-Play-On-Tape/PiCross_Pokitto | 8a08ac65d232c8457b2ee323be58c52f09757ced | [
"BSD-3-Clause"
] | null | null | null | #include "PlayGameState.h"
#include "../puzzles/Puzzles.h"
#include "../images/Images.h"
#include "../utils/Utils.h"
#include "../utils/Enums.h"
using PC = Pokitto::Core;
using PD = Pokitto::Display;
// ---------------------------------------------------------------------------------------------------------------------------
// Render the state ..
// ---------------------------------------------------------------------------------------------------------------------------
//
void PlayGameState::render(StateMachine & machine) {
uint8_t const solidLines[] = {
0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, // 1
0, 2, 0, 0, 0, // 2
0, 3, 0, 0, 0, // 3
0, 4, 0, 0, 0, // 4
0, 5, 0, 0, 0, // 5
0, 3, 6, 0, 0, // 6
0, 7, 0, 0, 0, // 7
0, 4, 8, 0, 0, // 8
0, 3, 6, 9, 0, // 9
0, 5, 10, 0, 0, // 10
0, 11, 0, 0, 0, // 11
0, 4, 8, 12, 0, // 12
0, 13, 0, 0, 0, // 13
0, 7, 14, 0, 0, // 14
0, 5, 10, 15, 0, // 15
0, 4, 8, 12, 16, // 16
};
auto & puzzle = machine.getContext().puzzle;
// Flash the cursor?
bool flash = true;
this->flashCount++;
switch (this->flashCount) {
case 0 ... 23:
flash = true;
break;
case 24 ... 47:
flash = false;
break;
case 48:
flash = true;
this->flashCount = 0;
break;
}
// Render puzzle ..
uint8_t size = puzzle.getSize();
uint8_t completedRows = 0;
PD::fillScreen(7);
PD::setColor(5, 7);
// Render binder left and right ..
if (puzzle.getSize() < 15) {
PD::drawBitmap(0, 0, Images::Binder_Left);
}
for (uint8_t x = 0; x <= size; x++) {
// Horizontal and Vertical lines ..
for (uint8_t z = size * 5; z < (size * 5) + 5; z++) {
if (x == solidLines[z]) {
PD::drawColumn(this->puzzleLeft + this->marginLeft + (x * Constants::GridWidthX) - this->xOffset, this->puzzleTop + this->marginTop - this->yOffset, this->puzzleTop + this->marginTop - this->yOffset + (size * Constants::GridWidthY));
PD::drawRow(this->puzzleLeft + this->marginLeft - this->xOffset, this->puzzleLeft + this->marginLeft - this->xOffset + (size * Constants::GridWidthX), this->puzzleTop + this->marginTop + (x * Constants::GridWidthY) - this->yOffset);
}
}
drawDottedColumn(this->puzzleLeft + this->marginLeft + (x * Constants::GridWidthX) - this->xOffset, this->puzzleTop, this->puzzleTop + this->marginTop - this->yOffset + (size * Constants::GridWidthY));
drawDottedRow(this->puzzleLeft, this->puzzleLeft + this->marginLeft + (size * Constants::GridWidthX) - this->xOffset, this->puzzleTop + this->marginTop + (x * Constants::GridWidthY) - this->yOffset);
}
for (uint8_t x = 0; x < size; x++) {
for (uint8_t y = 0; y < size; y++) {
GridValue gridValue = puzzle.getGrid(x, y, FilterValue::PlayerSelection);
switch (gridValue) {
case GridValue::Blank:
break;
case GridValue::Selected:
PD::setColor(5);
PD::fillRectangle(this->puzzleLeft + this->marginLeft + (x * Constants::GridWidthX) + 2 - this->xOffset, this->puzzleTop + this->marginTop + (y * Constants::GridWidthY) + 2 - this->yOffset, 7, 6);
break;
case GridValue::Marked:
PD::setColor(6);
PD::fillRectangle(this->puzzleLeft + this->marginLeft + (x * Constants::GridWidthX) + 2 - this->xOffset, this->puzzleTop + this->marginTop + (y * Constants::GridWidthY) + 2 - this->yOffset, 7, 6);
break;
}
}
}
// Render column headers ..
for (uint8_t x = 0; x < size; x++) {
if (puzzle.isColMatch(x)) {
PD::setColor(5);
PD::fillRect(this->puzzleLeft + this->marginLeft + (x * Constants::GridWidthX) + 1 - this->xOffset, this->puzzleTop - this->yOffset, 9, this->marginTop - 2);
PD::setColor(7, 5);
completedRows++;
}
else {
PD::setColor(5, 7);
}
for (uint8_t y = 0; y < Constants::NumberOfNumbers; y++) {
uint8_t val = puzzle.getCol(x, y);
if (val != 0) {
PD::setCursor(this->puzzleLeft + this->marginLeft + (x * Constants::GridWidthX) + 3 - (val >= 10 ? 3 : 0) - this->xOffset, this->puzzleTop + 1 - this->yOffset + (y * 10));
PD::print(static_cast<int8_t>(val));
}
}
}
// Render row headers ..
for (uint8_t y = 0; y < size; y++) {
if (puzzle.isRowMatch(y)) {
PD::setColor(5);
PD::fillRect(this->puzzleLeft + this->xOffset, this->puzzleTop + this->marginTop + (y * Constants::GridWidthY) + 1 - this->yOffset, this->marginLeft - 1, 8);
PD::setColor(7, 5);
completedRows++;
}
else {
PD::setColor(5, 7);
}
uint8_t largerThan10 = 0;
for (uint8_t x = 0; x < Constants::NumberOfNumbers; x++) {
uint8_t val = puzzle.getRow(y, x);
if (val != 0) {
if (val >= 10) largerThan10++;
PD::setCursor(this->puzzleLeft + 1 + (x * 7) - this->xOffset, this->puzzleTop + this->marginTop + (y * Constants::GridWidthY) + 2 - this->yOffset);
PD::print(static_cast<int8_t>(val));
}
}
}
PD::setColor(1);
// Game over?
if (completedRows == 2 * size && this->viewState != ViewState::GameOver) {
this->viewState = ViewState::GameOver;
// Increase hint counter if the puzzle hasn't been solved before ..
if (!puzzle.getPuzzlesSolved(puzzle.getPuzzleIndex())) {
this->showHintGraphic = puzzle.incHintCounter();
}
puzzle.setPuzzlesSolved(puzzle.getPuzzleIndex(), true);
}
switch (this->viewState) {
case ViewState::GameOver:
switch (this->counter) {
case 1:
puzzle.saveCookie();
break;
case 2:
uint8_t width = puzzle.getSize();
uint8_t height = puzzle.getSize();
uint8_t scale = Constants::Scale[puzzle.getPuzzleIndex() / 25];
uint8_t offset = Constants::Offset[puzzle.getPuzzleIndex() / 25];
PD::drawBitmap(18, 60, Images::Congratulations);
renderPuzzleImage(176, 68, Puzzles::puzzles[puzzle.getPuzzleIndex()], scale, puzzle.getPuzzleIndex() % Constants::RenderPuzzle_NoOfColours);
if (this->showHintGraphic) PD::drawBitmap(42, 110, Images::Hint);
break;
}
break;
case ViewState::Menu:
PD::drawBitmap(107, 75, Images::Binder_Folded);
if (puzzle.getHintCount() > 0) PD::drawBitmap(159, 147, Images::Give_Hint);
PD::drawBitmap(214, 147 + (this->menuOption * 9), Images::ArrowLeft);
break;
case ViewState::Normal:
if (flash) {
PD::setColor(9, 8);
PD::drawBitmap(this->puzzleLeft + this->marginLeft + (puzzle.getX() * Constants::GridWidthX) - this->xOffset + 1, this->puzzleTop + this->marginTop + (puzzle.getY() * Constants::GridWidthY) - this->yOffset + 1, Images::Cursor);
PD::drawRect(this->puzzleLeft + this->marginLeft + (puzzle.getX() * Constants::GridWidthX) - this->xOffset, this->puzzleTop + this->marginTop + (puzzle.getY() * Constants::GridWidthY) - this->yOffset, 10, 10);
}
break;
case ViewState::Hint:
if (flash) {
PD::setColor(10);
if (this->hintType == HintType::Col) {
PD::drawRect(this->puzzleLeft + this->marginLeft + (this->hintIndexCol * Constants::GridWidthX) - this->xOffset, this->puzzleTop + this->marginTop - this->yOffset, Constants::GridWidthX, (size * Constants::GridWidthY));
}
else {
PD::drawRect(this->puzzleLeft + this->marginLeft - this->xOffset, this->puzzleTop + this->marginTop + (this->hintIndexRow * Constants::GridWidthY) - this->yOffset, (size * Constants::GridWidthY), Constants::GridWidthY);
}
}
break;
}
}
| 31.668919 | 250 | 0.463196 | [
"render"
] |
aea904e78ee56eae7d84edc1206f75f770fd59f3 | 5,733 | cc | C++ | ui/base/clipboard/scoped_clipboard_writer.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/base/clipboard/scoped_clipboard_writer.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/base/clipboard/scoped_clipboard_writer.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "base/pickle.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/escape.h"
#include "ui/base/clipboard/clipboard_format_type.h"
#include "ui/gfx/geometry/size.h"
// Documentation on the format of the parameters for each clipboard target can
// be found in clipboard.h.
namespace ui {
ScopedClipboardWriter::ScopedClipboardWriter(ClipboardBuffer buffer)
: buffer_(buffer) {}
ScopedClipboardWriter::~ScopedClipboardWriter() {
static constexpr size_t kMaxRepresentations = 1 << 12;
DCHECK(objects_.empty() || platform_representations_.empty())
<< "Portable and Platform representations should not be written on the "
"same write.";
DCHECK(platform_representations_.size() < kMaxRepresentations);
if (!objects_.empty()) {
Clipboard::GetForCurrentThread()->WritePortableRepresentations(buffer_,
objects_);
}
if (!platform_representations_.empty()) {
Clipboard::GetForCurrentThread()->WritePlatformRepresentations(
buffer_, std::move(platform_representations_));
}
}
void ScopedClipboardWriter::WriteText(const base::string16& text) {
std::string utf8_text = base::UTF16ToUTF8(text);
Clipboard::ObjectMapParams parameters;
parameters.push_back(
Clipboard::ObjectMapParam(utf8_text.begin(), utf8_text.end()));
objects_[Clipboard::PortableFormat::kText] = parameters;
}
void ScopedClipboardWriter::WriteHTML(const base::string16& markup,
const std::string& source_url) {
std::string utf8_markup = base::UTF16ToUTF8(markup);
Clipboard::ObjectMapParams parameters;
parameters.push_back(
Clipboard::ObjectMapParam(utf8_markup.begin(),
utf8_markup.end()));
if (!source_url.empty()) {
parameters.push_back(Clipboard::ObjectMapParam(source_url.begin(),
source_url.end()));
}
objects_[Clipboard::PortableFormat::kHtml] = parameters;
}
void ScopedClipboardWriter::WriteRTF(const std::string& rtf_data) {
Clipboard::ObjectMapParams parameters;
parameters.push_back(Clipboard::ObjectMapParam(rtf_data.begin(),
rtf_data.end()));
objects_[Clipboard::PortableFormat::kRtf] = parameters;
}
void ScopedClipboardWriter::WriteBookmark(const base::string16& bookmark_title,
const std::string& url) {
if (bookmark_title.empty() || url.empty())
return;
std::string utf8_markup = base::UTF16ToUTF8(bookmark_title);
Clipboard::ObjectMapParams parameters;
parameters.push_back(Clipboard::ObjectMapParam(utf8_markup.begin(),
utf8_markup.end()));
parameters.push_back(Clipboard::ObjectMapParam(url.begin(), url.end()));
objects_[Clipboard::PortableFormat::kBookmark] = parameters;
}
void ScopedClipboardWriter::WriteHyperlink(const base::string16& anchor_text,
const std::string& url) {
if (anchor_text.empty() || url.empty())
return;
// Construct the hyperlink.
std::string html = "<a href=\"";
html += net::EscapeForHTML(url);
html += "\">";
html += net::EscapeForHTML(base::UTF16ToUTF8(anchor_text));
html += "</a>";
WriteHTML(base::UTF8ToUTF16(html), std::string());
}
void ScopedClipboardWriter::WriteWebSmartPaste() {
objects_[Clipboard::PortableFormat::kWebkit] = Clipboard::ObjectMapParams();
}
void ScopedClipboardWriter::WriteImage(const SkBitmap& bitmap) {
if (bitmap.drawsNothing())
return;
DCHECK(bitmap.getPixels());
bitmap_ = bitmap;
// TODO(dcheng): This is slightly less horrible than what we used to do, but
// only very slightly less.
SkBitmap* bitmap_pointer = &bitmap_;
Clipboard::ObjectMapParam packed_pointer;
packed_pointer.resize(sizeof(bitmap_pointer));
*reinterpret_cast<SkBitmap**>(&*packed_pointer.begin()) = bitmap_pointer;
Clipboard::ObjectMapParams parameters;
parameters.push_back(packed_pointer);
objects_[Clipboard::PortableFormat::kBitmap] = parameters;
}
void ScopedClipboardWriter::WritePickledData(
const base::Pickle& pickle,
const ClipboardFormatType& format) {
std::string format_string = format.Serialize();
Clipboard::ObjectMapParam format_parameter(format_string.begin(),
format_string.end());
Clipboard::ObjectMapParam data_parameter;
data_parameter.resize(pickle.size());
memcpy(const_cast<char*>(&data_parameter.front()),
pickle.data(), pickle.size());
Clipboard::ObjectMapParams parameters;
parameters.push_back(format_parameter);
parameters.push_back(data_parameter);
objects_[Clipboard::PortableFormat::kData] = parameters;
}
void ScopedClipboardWriter::WriteData(const base::string16& format,
mojo_base::BigBuffer data) {
// Conservative limit to maximum format and data string size, to avoid
// potential attacks with long strings. Callers should implement similar
// checks.
constexpr size_t kMaxFormatSize = 1024;
constexpr size_t kMaxDataSize = 1 << 30; // 1 GB
DCHECK_LT(format.size(), kMaxFormatSize);
DCHECK_LT(data.size(), kMaxDataSize);
platform_representations_.push_back(
{base::UTF16ToUTF8(format), std::move(data)});
}
void ScopedClipboardWriter::Reset() {
objects_.clear();
platform_representations_.clear();
bitmap_.reset();
}
} // namespace ui
| 36.75 | 79 | 0.689342 | [
"geometry"
] |
aeb123abd1c85aa47bfe111e7779dc11afd7fa60 | 20,472 | cpp | C++ | tests/bench_upcxx_depspawn.cpp | UDC-GAC/upcxx_depspawn | 01007cb329f702e92fefafc44b21c03ed6c38c94 | [
"MIT"
] | null | null | null | tests/bench_upcxx_depspawn.cpp | UDC-GAC/upcxx_depspawn | 01007cb329f702e92fefafc44b21c03ed6c38c94 | [
"MIT"
] | null | null | null | tests/bench_upcxx_depspawn.cpp | UDC-GAC/upcxx_depspawn | 01007cb329f702e92fefafc44b21c03ed6c38c94 | [
"MIT"
] | null | null | null | /*
UPCxx_DepSpawn: UPC++ Data Dependent Spawn library
Copyright (C) 2021-2022 Basilio B. Fraguela. Universidade da Coruna
Distributed under the MIT License. (See accompanying file LICENSE)
*/
/// \file bench_upcxx_depspawn.cpp
/// \brief Benchmarking
/// \author Basilio B. Fraguela <basilio.fraguela@udc.es>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <chrono>
#include "upcxx_depspawn/upcxx_depspawn.h"
#include "SharedArray.h"
#include "common_io.cpp" // This is only for serializing parallel prints
constexpr size_t N = 32768;
using namespace depspawn;
typedef void (*voidfptr)();
std::chrono::high_resolution_clock::time_point t0, t1, t2;
double total_time = 0.;
int Myrank, Nranks;
constexpr size_t BCK = 128/sizeof(int);
SharedArray<int> mx;
struct log_line_t { char buffer[128]; };
SharedArray<log_line_t> Log;
size_t nsize = N;
int nthreads = -1;
int queue_limit = -1;
int retstate = 0;
int global_ntest; ///Used by pr()
upcxx::persona_scope *ps_master = nullptr;
void disable_ps_master()
{
if (ps_master) {
delete ps_master;
ps_master = nullptr;
}
}
void enable_ps_master()
{
if (!upcxx::master_persona().active_with_caller()) {
//std::cerr << 'P' << upcxx::rank_me() << "takes\n"; //std
ps_master = new upcxx::persona_scope(upcxx::master_persona());
} else {
//std::cerr << 'P' << upcxx::rank_me() << "owns\n"; // used for myrank !=0 at startup
}
}
void cleanmx()
{
for (size_t i = 0; i < nsize * BCK; i++) {
auto ptr = mx[i];
if (ptr.where() == Myrank) {
*(ptr.local()) = 0;
}
}
upcxx::barrier();
}
void pr(const char * s)
{
char * const buff = Log[Myrank].local()->buffer;
const double spawn_time = std::chrono::duration <double>(t1 - t0).count();
const double running_time = std::chrono::duration <double>(t2 - t1).count();
const double tot_time = std::chrono::duration <double>(t2 - t0).count();
int tmp = sprintf(buff, "T%2d P%2d %31s. ", global_ntest, Myrank, s);
sprintf(buff + tmp, "Spawning : %8lf Running: %8lf T:%8lf", spawn_time, running_time, tot_time);
upcxx::barrier();
if(!Myrank) {
for (int i = 0; i < Nranks; i++) {
log_line_t tmp = upcxx::rget(Log[i]).wait();
puts(tmp.buffer);
}
}
upcxx::barrier();
total_time += tot_time;
}
void doerror()
{
retstate = -1;
std::cerr << "Error\n";
}
void check_global_error()
{
int global_retstate = upcxx::reduce_all(retstate, upcxx::op_fast_add).wait();
if (global_retstate < 0) {
if (!Myrank) {
std::cerr << "Exiting due to errors in " << (-global_retstate) << " ranks\n";
}
upcxx::finalize();
exit(EXIT_FAILURE);
}
}
/****************************************************************/
int test_0_grain;
void fvec(upcxx::global_ptr<int> r)
{
assert(r.where() == Myrank);
int * const p = r.local();
for (int i = 0; i < test_0_grain; i++) {
p[i] = p[i] + 1;
}
}
constexpr bool isPowerOf2(int i) noexcept {
return !(i & (i-1));
}
void check_and_zero(const bool global = true)
{
if (global) {
for(size_t i = 0; i < (nsize * BCK); i++) {
auto ptr = mx[i];
if (ptr.where() == Myrank) {
if( (*(ptr.local())) != 1 ) {
doerror();
break;
}
*(ptr.local()) = 0;
}
}
} else {
upcxx::global_ptr<int> my_ptr = mx[Myrank * BCK];
int * const p = my_ptr.local();
const size_t max_grain = (nsize * BCK) / Nranks;
for(size_t i = 0; i < max_grain; i++) {
if( p[i] != 1 ) {
doerror();
break;
}
p[i] = 0;
}
}
}
/**
Each invocation to fvec processes test_0_grain elements, so it sweeps on all the
nsize * BCK elements of mx with test_0_grain step so that all the elements are processed.
max_grain is the number of elements per rank, and thus the total size of the memory chunk
owned by each rank, while ptr[i] gives the pointer to the shared chunk of rank i.
*/
void body_test_0(int max_grain,
const upcxx::global_ptr<int> * const ptr,
std::vector<double>& t_upcxx,
std::vector<double>& t_threads)
{ char msg[128];
if (max_grain % test_0_grain) {
if(!Myrank) {
printf("max_grain=%d not divisible by grain %d\n", max_grain, test_0_grain);
}
return;
}
upcxx::barrier();
disable_ps_master();
t0 = std::chrono::high_resolution_clock::now();
if (!isPowerOf2(max_grain)) {
for(size_t i = 0; i < (nsize * BCK); i += test_0_grain) {
upcxx_spawn(fvec, ptr[i/max_grain] + (i % max_grain));
}
} else {
for(size_t i = 0; i < (nsize * BCK); i += test_0_grain) {
upcxx_spawn(fvec, ptr[i/max_grain] + (i & (max_grain - 1)));
}
}
t1 = std::chrono::high_resolution_clock::now();
upcxx_wait_for_all();
t2 = std::chrono::high_resolution_clock::now();
enable_ps_master();
t_upcxx.push_back(std::chrono::duration <double>(t2 - t0).count());
check_and_zero(false);
sprintf(msg, "DepSpawn parallel f grain %d", test_0_grain);
pr(msg);
upcxx::barrier();
t0 = t1 = std::chrono::high_resolution_clock::now();
if (test_0_grain < max_grain) {
get_task_pool().parallel_for(0, max_grain, test_0_grain, [ptr](int begin) {
int * const p = ptr[Myrank].local() + begin;
for (int i = 0; i < test_0_grain; i++) {
p[i] = p[i] + 1;
}
}, false);
} else {
int * const p = ptr[Myrank].local();
for (int i = 0; i < max_grain; i++) {
p[i] = p[i] + 1;
}
}
upcxx::barrier();
t2 = std::chrono::high_resolution_clock::now();
t_threads.push_back(std::chrono::duration <double>(t2 - t0).count());
check_and_zero(false);
sprintf(msg, "parallel_for f grain %d", test_0_grain);
pr(msg);
}
/**
Measures the cost of spawning independent tasks on a distributed vector compared
to doing it by hand with SPMD + threads. Different task granularities are tried
and the best results are provided.
*/
void test0()
{ std::vector<double> t_upcxx, t_threads;
if (nsize % Nranks) {
if(!Myrank) {
printf("TEST 0 skipped because problem size %zu is not divisible by %d NRanks\n", nsize, Nranks);
}
return;
}
const int max_grain = (nsize * BCK) / Nranks; // Number of elements per rank
if(!Myrank) {
printf("nsize=%zu BCK=%zu TOT=%zu Nranks=%d max_grain=%d\n", nsize, BCK, nsize * BCK, Nranks, max_grain);
}
upcxx::global_ptr<int> * const ptr = new upcxx::global_ptr<int>[Nranks];
for (int i = 0; i < Nranks; i++) {
ptr[i] = mx[i * BCK];
}
for (test_0_grain = 32; test_0_grain <= max_grain; test_0_grain = test_0_grain * 2) {
body_test_0(max_grain, ptr, t_upcxx, t_threads);
}
// tries other test_0_grain for cases where max_grain / nthreads is not a power of 2
if( (nthreads > 1) && !(max_grain % nthreads) ) {
test_0_grain = max_grain / nthreads;
if (!isPowerOf2(test_0_grain)) {
test_0_grain = test_0_grain * 16; // Try from 16 times equal grain down to up to 512
do {
body_test_0(max_grain, ptr, t_upcxx, t_threads);
if(test_0_grain & 1) {
break;
}
test_0_grain = test_0_grain / 2;
} while (test_0_grain >= 512);
}
}
if(!Myrank) {
printf("Global best times P0: DepSpawn: %lf Threads: %lf\n", *std::min_element(t_upcxx.begin(), t_upcxx.end()), *std::min_element(t_threads.begin(), t_threads.end()));
}
delete [] ptr;
}
void f(upcxx::global_ptr<int> r)
{
int tmp = upcxx::rget(r).wait();
upcxx::rput(tmp + 1, r).wait();
}
/// TRANSFORMED TO BE BASED ON INDEPENDENT TASKS
/** A single main thread spawns nsize tasks with a single independent input */
void test1()
{
disable_ps_master();
t0 = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < nsize; i++)
upcxx_spawn(f, mx[i * BCK]);
t1 = std::chrono::high_resolution_clock::now();
upcxx_wait_for_all();
t2 = std::chrono::high_resolution_clock::now();
enable_ps_master();
for(size_t i = 0; i < nsize; i++) {
auto ptr = mx[i * BCK];
if (ptr.where() == Myrank) {
if( (*(ptr.local())) != 1 ) {
doerror();
break;
}
*(ptr.local()) = 0;
}
}
pr("f(int&) without overlaps");
}
void g(upcxx::global_ptr<int> i0, upcxx::global_ptr<int> i1, upcxx::global_ptr<int> i2, upcxx::global_ptr<int> i3, upcxx::global_ptr<int> i4, upcxx::global_ptr<int> i5, upcxx::global_ptr<int> i6, upcxx::global_ptr<int> i7) {
auto fi0 = upcxx::rget(i0);
auto fi1 = upcxx::rget(i1);
auto fi2 = upcxx::rget(i2);
auto fi3 = upcxx::rget(i3);
auto fi4 = upcxx::rget(i4);
auto fi5 = upcxx::rget(i5);
auto fi6 = upcxx::rget(i6);
auto fi7 = upcxx::rget(i7);
auto fi01 = fi0.then([i0](int i){ return upcxx::rput(i + 1, i0); });
auto fi11 = fi1.then([i1](int i){ return upcxx::rput(i + 1, i1); });
auto fi21 = fi2.then([i2](int i){ return upcxx::rput(i + 1, i2); });
auto fi31 = fi3.then([i3](int i){ return upcxx::rput(i + 1, i3); });
auto fi41 = fi4.then([i4](int i){ return upcxx::rput(i + 1, i4); });
auto fi51 = fi5.then([i5](int i){ return upcxx::rput(i + 1, i5); });
auto fi61 = fi6.then([i6](int i){ return upcxx::rput(i + 1, i6); });
auto fi71 = fi7.then([i7](int i){ return upcxx::rput(i + 1, i7); });
upcxx::when_all(fi01, fi11, fi21, fi31, fi41, fi51, fi61, fi71).wait();
}
/** A single main thread spawns nsize tasks with 8 arguments by reference.
All the tasks are independent.
*/
void test2()
{
disable_ps_master();
t0 = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < nsize; i++)
upcxx_spawn(g, mx[i * BCK], mx[i * BCK + 7], mx[i * BCK + 1], mx[i * BCK + 6], mx[i * BCK + 2], mx[i * BCK + 5], mx[i * BCK + 3], mx[i * BCK + 4]);
t1 = std::chrono::high_resolution_clock::now();
upcxx_wait_for_all();
t2 = std::chrono::high_resolution_clock::now();
enable_ps_master();
for(size_t i = 0; i < nsize; i++) {
for (size_t j = 0; j < 8; ++j) {
auto ptr = mx[i * BCK + j];
if (ptr.where() == Myrank) {
if( (*(ptr.local())) != 1) {
doerror();
i = nsize; //Break outer loop too
break;
}
*(ptr.local()) = 0;
}
}
}
pr("f(8 int&) without overlaps");
}
void depprev(upcxx::cached_global_ptr<const int> prev, upcxx::global_ptr<int> out) {
int tmp = upcxx::rget(prev).wait();
upcxx::rput(tmp + 1, out).wait();
}
//#define DEBUG
#ifdef DEBUG
void depprev_dbg(upcxx::cached_global_ptr<const int> prev, upcxx::global_ptr<int> out, const int i) {
int tmp = upcxx::rget(prev).wait();
if (tmp != i) {
fprintf(stderr, "err at task %d\n", i);
abort();
}
upcxx::rput(tmp + 1, out).wait();
}
#endif
/** A single main thread spawns nsize tasks in which task i depends
on task i-1 (on an arg it writes by reference).
*/
void test3()
{
const bool default_run = (nsize == N);
if(default_run) { //Shorten problem size because of slow test
nsize = 20000;
if(!Myrank) {
printf("RUNNING T3 WITH PROBLEM SIZE %zu\n", nsize);
}
}
///First a simple run in UPC++, for comparison
t0 = std::chrono::high_resolution_clock::now();
if (!Myrank) {
int tmp = upcxx::rget(mx[0]).wait();
upcxx::rput(tmp + 1, mx[0]).wait();
}
for(size_t i = 1; i < nsize; i++) {
upcxx::barrier();
int tmp = upcxx::rget(mx[(i-1) * BCK]).wait();
upcxx::rput(tmp + 1, mx[i * BCK]).wait();
}
t1 = std::chrono::high_resolution_clock::now();
upcxx::barrier();
t2 = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < nsize; i++) {
auto ptr = mx[i * BCK];
if (ptr.where() == Myrank) {
int tmp = *(ptr.local());
if(tmp != (i+1)) {
fprintf(stderr, "%zu -> %d\n", i, tmp);
doerror();
break;
}
*(ptr.local()) = 0;
}
}
pr("UPC++ f(int, int&) dep->");
upcxx::barrier();
/// Actual upcxx_spawn test
if((nthreads < 0) || (nthreads > 2)) {
if (!Myrank) {
printf("**RUNNING T3 WITH 2 THREADS INSTEAD OF %d**\n", nthreads);
}
set_threads(2);
}
disable_ps_master();
t0 = std::chrono::high_resolution_clock::now();
#ifdef DEBUG
upcxx_spawn(depprev_dbg, mx[0], mx[0], 0);
for(size_t i = 1; i < nsize; i++) {
upcxx_spawn(depprev_dbg, mx[(i-1) * BCK], mx[i * BCK], std::move(i));
}
#else
upcxx_spawn(depprev, mx[0], mx[0]);
for(size_t i = 1; i < nsize; i++) {
upcxx_spawn(depprev, mx[(i-1) * BCK], mx[i * BCK]);
}
#endif
t1 = std::chrono::high_resolution_clock::now();
upcxx_wait_for_all();
t2 = std::chrono::high_resolution_clock::now();
enable_ps_master();
if((nthreads < 0) || (nthreads > 2)) { //restore threads
set_threads(nthreads);
}
for(size_t i = 0; i < nsize; i++) {
auto ptr = mx[i * BCK];
if (ptr.where() == Myrank) {
int tmp = *(ptr.local());
if(tmp != (i+1)) {
fprintf(stderr, "%zu -> %d\n", i, tmp);
doerror();
break;
}
*(ptr.local()) = 0;
}
}
pr("f(int, int&) dep->");
if (default_run) { //Restore default problem size
nsize = N;
}
}
void depsame(upcxx::global_ptr<int> iout) {
//LOG("B " << (&out - (int*)mx) / (128/sizeof(int)) );
int tmp = upcxx::rget(iout).wait();
upcxx::rput(tmp + 1, iout).wait();
//LOG("E " << (&out - (int*)mx) / (128/sizeof(int)) );
}
/** A single main thread spawns nsize tasks all of which depend on the same element by reference */
void test4()
{
disable_ps_master();
t0 = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < nsize; i++) {
upcxx_spawn(depsame, mx[0]);
}
t1 = std::chrono::high_resolution_clock::now();
upcxx_wait_for_all();
t2 = std::chrono::high_resolution_clock::now();
enable_ps_master();
if(!Myrank){
int result = upcxx::rget(mx[0]).wait();
if( result != nsize ) {
std::cerr << " -> " << result;
doerror();
}
upcxx::rput(0, mx[0]).wait();
}
pr("f(int&) depsame");
}
/** Simulates pattern of matrix_inverse */
void test5()
{ size_t dim;
const bool default_run = (nsize == N);
if(default_run) { //Shorten problem size because of slow test
nsize = 1000;
if(!Myrank) {
printf("RUNNING T5 WITH PROBLEM SIZE %zu\n", nsize);
}
}
for(dim = 1; (dim * dim) <= nsize; dim++);
dim--;
if(!Myrank) {
printf("%zu x %zu blocks\n", dim, dim);
}
auto index_mx = [dim](int i, int j) { return mx[(i * dim + j) * BCK]; };
disable_ps_master();
t0 = std::chrono::high_resolution_clock::now();
for(size_t n = 0; n < dim; n++) {
auto pivot_inverse = index_mx(n, n);
upcxx_spawn( [](upcxx::global_ptr<int> pivot) {
int tmp = upcxx::rget(pivot).wait();
upcxx::rput(tmp + 1, pivot).wait();
}, pivot_inverse);
for (int j = 0; j < dim; j++)
{
if (j == n) continue;
upcxx_spawn( [](upcxx::global_ptr<int> dest_and_right, upcxx::cached_global_ptr<const int> left) {
int tmp = upcxx::rget(left).wait();
int tmp2 = upcxx::rget(dest_and_right).wait();
upcxx::rput(tmp + tmp2, dest_and_right).wait();
}, index_mx(n, j), pivot_inverse);
}
for (int i = 0; i < dim; i++)
{
if (i == n) continue;
auto tin = index_mx(i, n); //This is a upcxx::global_ptr<int>
for (int j = 0; j < dim; j++)
{
if (j == n) continue;
//spawn(&tile::multiply_subtract_in_place, b.m_tiles[dim*i+j], tin, b.m_tiles[dim*n+j]);
upcxx_spawn( [](upcxx::global_ptr<int> dest, upcxx::cached_global_ptr<const int> left, upcxx::cached_global_ptr<const int> right) {
int tmp = upcxx::rget(left).wait();
int tmp2 = upcxx::rget(right).wait();
int tmp3 = upcxx::rget(dest).wait();
upcxx::rput(tmp + tmp2 + tmp3, dest).wait();
}, index_mx(i, j), tin, index_mx(n, j));
}
//spawn(dsp_multiply_negate, tin, pivot_inverse);
upcxx_spawn( [](upcxx::global_ptr<int> dest, upcxx::cached_global_ptr<const int> right) {
int tmp2 = upcxx::rget(right).wait();
int tmp3 = upcxx::rget(dest).wait();
upcxx::rput(tmp2 + tmp3, dest).wait();
}, tin, pivot_inverse);
}
}
t1 = std::chrono::high_resolution_clock::now();
upcxx_wait_for_all();
t2 = std::chrono::high_resolution_clock::now();
enable_ps_master();
for(size_t i = 0; i < (dim * dim); i++) {
auto ptr = mx[i * BCK];
if (ptr.where() == Myrank) {
*(ptr.local()) = 0;
}
}
pr("matrix_inverse sim (no test)");
if (default_run) { //Restore default problem size
nsize = N;
}
}
//////////////////////////////////////////////////////
///// Common part /////
//////////////////////////////////////////////////////
constexpr voidfptr tests[] =
{test0, test1, test2, test3, test4, test5};
constexpr int NTESTS = sizeof(tests) / sizeof(tests[0]);
bool dotest[NTESTS];
void show_help()
{
puts("bench_spawn [-h] [-q limit] [-t nthreads] [-T ntest] [problemsize]");
puts("-h Display help and exit");
puts("-q limit # of pending ready tasks that makes a spawning thread steal one");
puts("-t nthreads Run with nthreads threads. Default is automatic (-1)");
printf("-T ntest Run test ntest in [0, %u]\n", NTESTS - 1);
puts(" Can be used multiple times to select several tests");
puts(" By default all the tests except 0 are run\n");
printf("problemsize defaults to %zu\n", N);
}
int process_arguments(int argc, char **argv)
{ int c;
bool tests_specified = false;
upcxx::init();
Myrank = upcxx::rank_me();
Nranks = upcxx::rank_n();
std::fill(dotest, dotest + NTESTS, false);
while ( -1 != (c = getopt(argc, argv, "hq:t:T:")) ) {
switch (c) {
case 'q' : /* queue limit */
queue_limit = atoi(optarg);
break;
case 't': /* threads */
nthreads = atoi(optarg);
break;
case 'T': /* tests */
c = atoi(optarg);
if(c < 0 || c >= NTESTS) {
if (!Myrank) printf("The test number must be in [0, %u]\n", NTESTS - 1);
return -1;
}
dotest[c] = true;
tests_specified = true;
break;
case 'h':
if (!Myrank) show_help();
default: /* unknown or missing argument */
return -1;
}
}
if (optind < argc) {
nsize = atoi(argv[optind]); /* first non-option argument */
}
// if(nsize > N) {
// if (!Myrank) printf("The problem size cannot exceed %zu\n", N);
// return -1;
// }
if(!tests_specified) {
// By default do not runt Test 0
std::fill(dotest + 1, dotest + NTESTS, true);
}
set_threads(nthreads); //You must set the number of threads before default runtime setup happens
if (!Myrank) {
printf("Running problem size %zu with %i procs x %i threads (sizeof(int)=%zu) Cache: %s\n", nsize, Nranks, nthreads, sizeof(int), upcxx::cached_global_ptr<const int>::cacheTypeName());
print_upcxx_depspawn_runtime_setup(); // This gives place to the default runtime setup in rank 0
}
enable_ps_master();
upcxx::barrier();
return 0;
}
int main(int argc, char **argv)
{
if(process_arguments(argc, argv) == -1) {
return -1;
}
assert(upcxx::master_persona().active_with_caller());
if (queue_limit >= 0) {
if (!Myrank) printf("Setting queue limit to %d\n", queue_limit);
set_task_queue_limit(queue_limit);
}
assert(upcxx::master_persona().active_with_caller());
mx.init(nsize * BCK, BCK);
Log.init(Nranks);
cleanmx();
for(global_ntest = 0; global_ntest < NTESTS; global_ntest++) {
if(dotest[global_ntest]) {
if (!Myrank) { printf("NO EXACT_MATCH TEST %d:\n", global_ntest); }
set_UPCXX_DEPSPAWN_EXACT_MATCH(false);
enable_ps_master();
assert(upcxx::master_persona().active_with_caller());
(*tests[global_ntest])();
check_global_error(); //upcxx::barrier();
if (!Myrank) { printf("EXACT_MATCH TEST %d:\n", global_ntest); }
set_UPCXX_DEPSPAWN_EXACT_MATCH(true);
enable_ps_master();
assert(upcxx::master_persona().active_with_caller());
(*tests[global_ntest])();
check_global_error(); //upcxx::barrier();
}
}
if (!Myrank) printf("Total : %8lf\n", total_time);
upcxx::finalize();
return retstate;
}
| 26.552529 | 224 | 0.582747 | [
"vector"
] |
aeb33f012623ad27f07436f611c1fd3997112915 | 5,269 | cpp | C++ | demon_test/marginGeometryClass.cpp | simon22014/visiontool | a6c1d68f00fd97e7f42fb49bd1247d44f1841472 | [
"MIT"
] | null | null | null | demon_test/marginGeometryClass.cpp | simon22014/visiontool | a6c1d68f00fd97e7f42fb49bd1247d44f1841472 | [
"MIT"
] | null | null | null | demon_test/marginGeometryClass.cpp | simon22014/visiontool | a6c1d68f00fd97e7f42fb49bd1247d44f1841472 | [
"MIT"
] | 1 | 2020-12-13T13:28:43.000Z | 2020-12-13T13:28:43.000Z | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: marginGeometryClass.cpp
* Author: aqq
*
* Created on 2017年4月27日, 下午4:47
*/
#include "marginGeometryClass.h"
marginGeometryClass::marginGeometryClass() {
}
void marginGeometryClass::marginGeomrtryType()
{
cout << "0:hoff,1:LSD,2:circle"<<endl;
int choiceNum;
cin >> choiceNum;
switch(choiceNum)
{
case HOFFGLEOMRTRY:
marginHoffGeomrtry();
break;
case LSDFASTGEOMRTRY:
LSDFastGeomrtry();
break;
case CIRCLEGEOMRTRY:
circleGeomrtry();
break;
default:
break;
}
}
void marginGeometryClass::circleGeomrtry()
{
Mat srcImage = beforeImage.clone();
Mat src_canny;
CV_Assert(srcImage.data != NULL);
gerMouse = new GeroetryMouse (srcImage);
gerMouse->LineGetStartEndPoint();
Point startPoint = gerMouse ->getStartPoint();
Point endPoint = gerMouse ->getEndPoint();
if(srcImage.channels() == 1)
{
cout << "the image channels is 1 ,so you can take the line"<<endl;
return;
}
findLine = new imageFindLineClass(startPoint,endPoint,srcImage);
findLine->imageEnlarge();
int bestCannyPos = findLine->getBestCannyPos();
src_canny = findLine -> getCraveImage();
Canny(src_canny,src_canny,bestCannyPos,bestCannyPos*3,3);
vector<Vec3f> circles;
HoughCircles(src_canny,circles,CV_HOUGH_GRADIENT,1,100,200,10,0,0);
cout << "the circles size :"<<circles.size()<<endl;
#if 0
CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles,
int method, double dp, double minDist,
double param1=100, double param2=100,
int minRadius=0, int maxRadius=0 );
#endif
for(size_t i = 0; i < circles.size(); i++ )
{
Vec3f circlesCenter;
char str_lx[20];
Point center(cvRound(circles[i][0] + startPoint.x) ,cvRound(circles[i][1] + startPoint.y));
int radius = cvRound(circles[i][2]);
circlesCenter[0] = cvRound(circles[i][0] + startPoint.x);
circlesCenter[1] = cvRound(circles[i][1] + startPoint.y);
circlesCenter[2] = cvRound(circles[i][2]);
sprintf(str_lx,"C[%.2f,%.2f] R=%d",circlesCenter[0], circlesCenter[1] ,radius);
putText(srcImage,str_lx,Point(circlesCenter[0], circlesCenter[1]),CV_FONT_HERSHEY_PLAIN,1,
Scalar(0,255,0));
circle(srcImage,center,2,Scalar(0,0,255),-1,8,1);
circle(srcImage,center,radius,Scalar(255,0,0),2,8,0);
Findcircles.push_back(circlesCenter);
}
imshow("srcImage",srcImage);
waitKey(0);
}
void marginGeometryClass::LSDFastGeomrtry()
{
cout << "the LSD is opecv3.0 above ,but now is opencv2.4.8"<<endl;
return ;
#if 0
Mat srcImage = beforeImage.clone();
CV_Assert(srcImage.data != NULL);
Canny(srcImage,srcImage,50,200,3);
#if 1
Ptr<LineSegmentDetector> lsd =
createLineSegmentDetector(LSD_REFINE_NONE);
#else
Ptr<LineSegmentDetector> lsd =
createLineSegmentDetector(LSD_REFINE_NONE);
#endif
double start = double (getTickCount());
vector<Vec4f> vecLines;
lsd ->detect(srcImage,vecLines);
double times = (double(getTickCount()) - start ) * 1000 /
getTickFrequency();
cout <<"times: "<<times<<" ms "<<endl;
Mat resLineMat(srcImage);
lsd-> drawSegments(resLineMat,vecLines);
imshow("resLineMat",resLineMat);
waitKey(0);
#endif
}
void marginGeometryClass::marginHoffGeomrtry()
{
Mat srcImage = beforeImage.clone();
CV_Assert(srcImage.data != NULL);
Mat edgeMat,houghMat;
Canny(srcImage,edgeMat,50,200,3);
cvtColor(edgeMat,houghMat,CV_GRAY2BGR);
#if 0
vector <Vec2f> lines;
HoughLines(edgeMat,lines,1,CV_PI/180,100,0,0);
for(size_t i = 0; i <lines.size(); i)
{
float rho = lines[i][0], theta = lines[i][1];
Point pt1,pt2;
double a = cos(theta) ,b = sin(theta);
double x0 = a * rho ,y0 = b *rho;
pt1.x = cvRound(x0 + 10 *(-b));
pt1.y = cvRound(y0 + 10 * (a));
pt2.x = cvRound(x0 - 10 *(-b));
pt2.y = cvRound(y0 - 10 * (a));
line(houghMat,pt1,pt2,Scalar(0,0,255),3,CV_AA);
}
#else
HoughLinesP(edgeMat,lines,1,CV_PI/180,50,50,10);
for(size_t i = 0; i < lines.size() ; i++ )
{
Vec4i linePoint = lines[i];
cout << "the line : "<< linePoint <<endl;
line(srcImage,Point(linePoint[0],linePoint[1]),Point(linePoint[2],linePoint[3]),Scalar(0,0,255),3,CV_AA);
}
#endif
changeImage = srcImage.clone();
imshow("changeImage",changeImage);
imshow("srcImage",beforeImage);
waitKey(0);
}
marginGeometryClass::marginGeometryClass(Mat &beforeImage)
:beforeImage(beforeImage)
{
}
marginGeometryClass::~marginGeometryClass() {
delete findLine;
findLine = NULL;
delete gerMouse;
gerMouse = NULL;
}
| 30.812865 | 113 | 0.607895 | [
"vector"
] |
aeb3db75f91b687a0274c47ad1ea9e9e85453244 | 3,064 | cpp | C++ | common/common.cpp | cea-ufmg/fdas | 654f1acfab9bfc52a3e25fdd7656eeb78218cb86 | [
"MIT"
] | null | null | null | common/common.cpp | cea-ufmg/fdas | 654f1acfab9bfc52a3e25fdd7656eeb78218cb86 | [
"MIT"
] | null | null | null | common/common.cpp | cea-ufmg/fdas | 654f1acfab9bfc52a3e25fdd7656eeb78218cb86 | [
"MIT"
] | null | null | null | /**
* Common infrastructure for the FDAS.
*/
#include "common.hpp"
#include <string>
#include <vector>
namespace po = boost::program_options;
using std::list;
using std::shared_ptr;
using std::string;
using std::vector;
namespace fdas {
void TextFileDataSink::Take(Datum<int8_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<int16_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<int32_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<int64_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<uint8_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<uint16_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<uint32_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<uint64_t> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<double> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
void TextFileDataSink::Take(Datum<float> datum) {
this->ostream << '"' << datum.id->StrId() << '"' << '\t';
this->ostream << datum.data << '\t';
this->ostream << datum.timestamp << std::endl;
}
po::options_description GeneralOptions() {
po::options_description desc("General program options, help and logging");
desc.add_options()
("help,h", "Print help and argument usage");
return desc;
}
po::options_description DataSinkOptions() {
po::options_description desc("Common FDAS data sinking options");
desc.add_options()
("log-data-text-file", po::value< vector<string> >(),
"Log data into text file");
return desc;
}
DataSinkPtrList BuildDataSinks(const po::variables_map &vm) {
DataSinkPtrList ret;
// Build text file data sinks
if (vm.count("log-data-text-file")) {
for (const auto& name: vm["log-data-text-file"].as<vector<string>>()) {
ret.push_back(DataSinkPtr(new TextFileDataSink(name)));
}
}
return ret;
}
}
| 28.110092 | 76 | 0.615862 | [
"vector"
] |
aeb430b4b35fdfdf261188a41476280f237098f5 | 26,384 | cc | C++ | src/DetectionSystemTestPlastics.cc | hbidaman/detectorSimulations_v10 | 6ceae8e9561638d5a3c886571f60141abc09922c | [
"MIT"
] | null | null | null | src/DetectionSystemTestPlastics.cc | hbidaman/detectorSimulations_v10 | 6ceae8e9561638d5a3c886571f60141abc09922c | [
"MIT"
] | null | null | null | src/DetectionSystemTestPlastics.cc | hbidaman/detectorSimulations_v10 | 6ceae8e9561638d5a3c886571f60141abc09922c | [
"MIT"
] | null | null | null | #include "DetectorConstruction.hh"
#include "DetectorMessenger.hh"
#include "G4Material.hh"
#include "G4Tubs.hh"
#include "G4Box.hh"
#include "G4Cons.hh"
#include "G4Sphere.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4Polyhedra.hh"
#include "G4SubtractionSolid.hh"
#include "G4UnionSolid.hh"
#include "G4IntersectionSolid.hh"
#include "G4GeometryManager.hh"
#include "G4PhysicalVolumeStore.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4SolidStore.hh"
#include "G4AssemblyVolume.hh"
#include "G4VisAttributes.hh"
#include "G4Colour.hh"
//// Added /// G4MaterialTable.hh is alreadu elsewhere
#include "G4OpticalSurface.hh"
#include "G4OpticalPhysics.hh"
#include "G4LogicalSkinSurface.hh"
////////
#include "DetectionSystemTestPlastics.hh"
#include "G4SystemOfUnits.hh"
#include <string>
DetectionSystemTestPlastics::DetectionSystemTestPlastics(G4double thickness, G4int material, G4double numDet)
{
fPMTWidth = 1.*mm;
fScintillatorWidth = 1.*mm;
fDiameter = 25.*mm;
fRadialDistance = 5.*mm; //Says in GRIFFIN nim can move from a few mm to 5 cm. At closest covers roughly 25% of 4pi
fStartPhi = 0.;
fDeltaPhi = 2*M_PI;
fWrapThickness = 0.5 * mm; //Factor of 10 should be applied later for visualization purposes. 0.05 for simulations, 0.5 for visualization
fAirGap = 0.;
fWrapMaterial = "Teflon";
fPMTMaterial = "G4_SILICON_DIOXIDE";
fZDSMaterial = "BC422";
//fZDSMaterial = "Dense"; // for Solid Angle test
//blue=G4Color(0.,0.,1.);
bronze=G4Color(0.8,0.5,0.2);
//cyan=G4Color(0.,1.,1.);
silver=G4Color(0.75,0.75,0.75);
black=G4Color(0.,0.,0.);
if(material == 1) fPlasticMaterial = "BC408";
else if (material == 2) fPlasticMaterial = "BC404";
else if (material == 3) fPlasticMaterial = "deuterium";
else if (material == 4) fPlasticMaterial = "Hydrogen";
else if (material == 5) fPlasticMaterial = "Carbon";
else if (material == 6) fPlasticMaterial = "Deuterated Scintillator";
else if (material == 7) fPlasticMaterial = "Dense";
else if (material == 8) fPlasticMaterial = "BC537";
else G4cout<< "Material Unknown" << G4endl;
G4cout << "Calling Constructor" << G4endl;
}
/////
///////
DetectionSystemTestPlastics::~DetectionSystemTestPlastics() {
// LogicalVolumes
delete fPlasticLog;
delete fWrapLog;
delete fPMTLog;
delete fZDSLog;
delete fZDSPMTLog;
G4cout << "Calling Destructor" << G4endl;
}
////////
/////////
G4int DetectionSystemTestPlastics::Build() {
fAssemblyTestPlastics = new G4AssemblyVolume();
G4cout << "Calling Build function" << G4endl;
BuildTestPlastics();
return 1;
}
////////
///////
G4int DetectionSystemTestPlastics::PlaceDetector(G4LogicalVolume* expHallLog) {
G4RotationMatrix * rotate = new G4RotationMatrix;
G4ThreeVector move = G4ThreeVector(0., 0., 0.);
//To not check overlaps
// fAssemblyPlastics->MakeImprint(expHallLog, move, rotate);
//To check overlaps
fAssemblyTestPlastics->MakeImprint(expHallLog, move, rotate, 0, true);
G4cout << "Calling place detector" << G4endl;
return 1;
}
///////////
/////////
G4int DetectionSystemTestPlastics::BuildTestPlastics() {
G4cout << "Calling Build PLastics" << G4endl;
G4ThreeVector move, direction;
G4RotationMatrix* rotate;
G4Material* plasticG4material = G4Material::GetMaterial(fPlasticMaterial);
if( !plasticG4material ) {
G4cout << " ----> Material " << fPlasticMaterial << " not found, cannot build! " << G4endl;
return 0;
}
else {
G4cout << plasticG4material->GetName() << " is the name of the detector material" << G4endl;
}
G4Material* wrapG4material = G4Material::GetMaterial(fWrapMaterial);
if( !wrapG4material ) {
G4cout << " ----> Material " << fWrapMaterial << " not found, cannot build! " << G4endl;
return 0;
}
else {
G4cout << wrapG4material->GetName() << " is the name of the wrapping material" << G4endl;
}
G4Material* PMTG4material = G4Material::GetMaterial(fPMTMaterial);
if( !PMTG4material ) {
G4cout << " ----> Material " << fPMTMaterial << " not found, cannot build! " << G4endl;
return 0;
}
else {
G4cout << PMTG4material->GetName() << " is the name of the pmt material" << G4endl;
}
G4Material* zdsG4material = G4Material::GetMaterial(fZDSMaterial);
if( !zdsG4material ) {
G4cout << " ----> Material " << fZDSMaterial << " not found, cannot build! " << G4endl;
return 0;
}
else {
G4cout << zdsG4material->GetName() << " is the name of the detector material" << G4endl;
}
////////Scintillation Properties //////// --------- Might have to be put before the material is constructed
//Based on BC408 data
G4MaterialPropertiesTable * scintillatorMPT = new G4MaterialPropertiesTable();
//If no scintillation yield for p,d,t,a,C then they all default to the electron yield.
//Have to uncomment line in ConstructOp that allows for this to work with boolean (true)
//The following data is for BC400, very similar in properties and composition then BC408.
/* const G4int num2 = 4;
G4double e_range[num2] = {1.*keV, 0.1*MeV, 1.*MeV, 10.*MeV};
G4double yield_e[num2] = {10., 1000., 10000., 100000.};//More realistic
//G4double yield_e[num2] = {1000., 10000., 10000., 100000.}; //testing
G4double yield_p[num2] = {1., 65., 1500., 45000.};
G4double yield_d[num2] = {1., 65., 1500., 45000.};//no data provided, assume same order of magnitude as proton
G4double yield_t[num2] = {1., 65., 1500., 45000.};//no data provided, assume same order of magnitude as proton
G4double yield_a[num2] = {1., 20., 200., 14000.};
G4double yield_C[num2] = {1., 10., 70., 600.};
assert(sizeof(e_test) == sizeof(num_test));
assert(sizeof(p_test) == sizeof(num_test));
assert(sizeof(d_test) == sizeof(num_test));
assert(sizeof(t_test) == sizeof(num_test));
assert(sizeof(a_test) == sizeof(num_test));
assert(sizeof(C_test) == sizeof(num_test));
scintillatorMPT->AddProperty("ELECTRONSCINTILLATIONYIELD", e_range, yield_e, num2)->SetSpline(true);
scintillatorMPT->AddProperty("PROTONSCINTILLATIONYIELD", e_range, yield_p, num2)->SetSpline(true);
scintillatorMPT->AddProperty("DEUTERONSCINTILLATIONYIELD", e_range, yield_d, num2)->SetSpline(true);
scintillatorMPT->AddProperty("TRITONSCINTILLATIONYIELD", e_range, yield_t, num2)->SetSpline(true);
scintillatorMPT->AddProperty("ALPHASCINTILLATIONYIELD", e_range, yield_a, num2)->SetSpline(true);
scintillatorMPT->AddProperty("IONSCINTILLATIONYIELD", e_range, yield_C, num2)->SetSpline(true);
*/
int energyPoints = 26;
G4double pEF = 0.4; //SiPM efficiency (TODO - discuss it)
//G4double protonScalingFact = 1.35;
G4double protonScalingFact = 1;
G4double psF = protonScalingFact;
//light yield - data taken form V.V. Verbinski et al, Nucl. Instrum. & Meth. 65 (1968) 8-25
G4double particleEnergy[] = { 0.001*MeV, 0.1*MeV, 0.13*MeV, 0.17*MeV,
0.2*MeV, 0.24*MeV, 0.3*MeV, 0.34*MeV,
0.4*MeV, 0.48*MeV, 0.6*MeV, 0.72*MeV, 0.84*MeV,
1.*MeV, 1.3*MeV, 1.7*MeV, 2.*MeV,
2.4*MeV, 3.*MeV, 3.4*MeV, 4.*MeV, 4.8*MeV,
6.*MeV, 7.2*MeV, 8.4*MeV, 10.*MeV };
G4double electronYield[] = {1*pEF, 1000*pEF, 1300*pEF, 1700*pEF,
2000*pEF, 2400*pEF, 3000*pEF, 3400*pEF,
4000*pEF, 4800*pEF, 6000*pEF, 7200*pEF,
8400*pEF,10000*pEF, 13000*pEF, 17000*pEF,
20000*pEF, 24000*pEF, 30000*pEF, 34000*pEF,
40000*pEF, 48000*pEF, 60000*pEF, 72000*pEF,
84000*pEF, 100000*pEF };
G4double protonYield[] = { 0.6*pEF*psF, 67.1*pEF*psF, 88.6*pEF*psF,
120.7*pEF*psF,
146.5*pEF*psF, 183.8*pEF*psF, 246*pEF*psF, 290*pEF*psF,
365*pEF*psF, 483*pEF*psF, 678*pEF*psF, 910*pEF*psF,
1175*pEF*psF, 1562*pEF*psF, 2385*pEF*psF, 3660*pEF*psF,
4725*pEF*psF,6250*pEF*psF, 8660*pEF*psF, 10420*pEF*psF,
13270*pEF*psF,17180*pEF*psF, 23100*pEF*psF,
29500*pEF*psF, 36200*pEF*psF, 45500*pEF*psF};
G4double alphaYield[] = { 0.2*pEF, 16.4*pEF, 20.9*pEF, 27.2*pEF,
32*pEF, 38.6*pEF, 49*pEF, 56.4*pEF,
67.5*pEF, 83*pEF, 108*pEF, 135*pEF,
165.6*pEF, 210*pEF, 302*pEF, 441*pEF,
562*pEF, 750*pEF, 1100*pEF, 1365*pEF,
1815*pEF, 2555*pEF, 4070*pEF, 6070*pEF,
8700*pEF, 13200*pEF };
G4double ionYield[] = { 0.2*pEF, 10.4*pEF, 12.7*pEF, 15.7*pEF,
17.9*pEF, 20.8*pEF, 25.1*pEF, 27.9*pEF,
31.9*pEF, 36.8*pEF, 43.6*pEF, 50.2*pEF,
56.9*pEF, 65.7*pEF, 81.3*pEF, 101.6*pEF,
116.5*pEF, 136.3*pEF, 166.15*pEF, 187.1*pEF,
218.6*pEF, 260.54*pEF, 323.5*pEF, 387.5*pEF,
451.54*pEF, 539.9*pEF };
scintillatorMPT->AddProperty("ELECTRONSCINTILLATIONYIELD", particleEnergy, electronYield, energyPoints)->SetSpline(true);
scintillatorMPT->AddProperty("PROTONSCINTILLATIONYIELD", particleEnergy, protonYield, energyPoints)->SetSpline(true);
scintillatorMPT->AddProperty("DEUTERONSCINTILLATIONYIELD", particleEnergy, protonYield, energyPoints)->SetSpline(true);
scintillatorMPT->AddProperty("TRITONSCINTILLATIONYIELD", particleEnergy, protonYield, energyPoints)->SetSpline(true);
scintillatorMPT->AddProperty("ALPHASCINTILLATIONYIELD", particleEnergy, alphaYield, energyPoints)->SetSpline(true);
scintillatorMPT->AddProperty("IONSCINTILLATIONYIELD", particleEnergy, ionYield, energyPoints)->SetSpline(true);
//scintillatorMPT->AddConstProperty("SCINTILLATIONYIELD", 10000./MeV); //Scintillation Efficiency - characteristic light yield //10000./MeV
///////
//
if (fPlasticMaterial == "BC408"){
const G4int num = 12; //BC408
G4cout << "BC408 and num = " << num << G4endl;
G4double photonEnergy[num] = {1.7*eV, 2.38*eV, 2.48*eV, 2.58*eV, 2.70*eV, 2.76*eV, 2.82*eV, 2.91*eV, 2.95*eV, 3.1*eV, 3.26*eV, 3.44*eV}; //BC408 emission spectra & corresponding energies
G4double RIndex1[num] = {1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58}; //BC408
G4double absorption[num] = {380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm, 380.*cm}; ///light attenuation BC408
G4double scint[num] = {3., 3., 8., 18., 43., 55., 80., 100., 80., 20., 7., 3. }; ///// Based off emission spectra for BC408
assert(sizeof(RIndex1) == sizeof(photonEnergy));
const G4int nEntries = sizeof(photonEnergy)/sizeof(G4double);
assert(sizeof(absorption) == sizeof(photonEnergy));
assert(sizeof(scint) == sizeof(photonEnergy));
G4cout << "nEntries = " << nEntries << G4endl;
scintillatorMPT->AddProperty("FASTCOMPONENT", photonEnergy, scint, nEntries)->SetSpline(true); // BC408 emission spectra
scintillatorMPT->AddProperty("SLOWCOMPONENT", photonEnergy, scint, nEntries)->SetSpline(true); // BC408 emission spectra
scintillatorMPT->AddProperty("RINDEX", photonEnergy, RIndex1, nEntries); //refractive index can change with energy
//note if photon is created outside of energy range it will have no index of refraction
scintillatorMPT->AddProperty("ABSLENGTH", photonEnergy, absorption, nEntries)->SetSpline(true); //absorption length doesnt change with energy - examples showing it can...
//scintillatorMPT->AddConstProperty("ABSLENGTH", 380.*cm); //Bulk light attenuation
scintillatorMPT->AddConstProperty("FASTTIMECONSTANT", 2.1*ns); //only one decay constant given - BC408
scintillatorMPT->AddConstProperty("SLOWTIMECONSTANT", 2.1*ns); //only one decay constant given - BC408
//scintillatorMPT->AddConstProperty("FASTTIMECONSTANT", 0.00000000000000000*ns); // for testing the effective speed of light
//scintillatorMPT->AddConstProperty("SLOWTIMECONSTANT", 0.00000000000000000*ns); // for testing the effective speed of light
//Should these be in the physics list?
//G4OpticalPhysics * opticalPhysics = new G4OpticalPhysics();
//opticalPhysics->SetFiniteRiseTime(true);
scintillatorMPT->AddConstProperty("FASTSCINTILLATIONRISETIME", 0.9*ns); //default rise time is 0ns, have to set manually BC408
scintillatorMPT->AddConstProperty("SLOWSCINTILLATIONRISETIME", 0.9*ns); //default rise time is 0ns, have to set manually BC408
//scintillatorMPT->AddConstProperty("FASTSCINTILLATIONRISETIME", 0.*ns); // For testing speed of light
//scintillatorMPT->AddConstProperty("SLOWSCINTILLATIONRISETIME", 0.*ns); // For testing speed of light
}
if(fPlasticMaterial == "BC404"){
const G4int num = 20; //BC404
G4cout << "BC404 and num = " << num << G4endl;
G4double photonEnergy[num] = {1.7*eV, 2.38*eV, 2.48*eV, 2.58*eV, 2.70*eV, 2.76*eV, 2.82*eV, 2.91*eV, 2.95*eV, 2.97*eV, 3.0*eV, 3.02*eV, 3.04*eV, 3.06*eV, 3.1*eV, 3.14*eV, 3.18*eV, 3.21*eV, 3.26*eV, 3.44*eV}; //BC404 emission spectra & corresponding energies
G4double RIndex1[num] = {1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58, 1.58}; //BC404
G4double absorption[num] = {160.*cm, 160*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm, 160.*cm}; ///light attenuation BC404
G4double scint[num] = {0., 1., 2., 5., 13., 20., 35., 50., 55., 60., 85., 93., 100., 96., 87., 70., 38., 18., 5., 1. }; ///// Based off emission spectra for BC404
assert(sizeof(RIndex1) == sizeof(photonEnergy));
const G4int nEntries = sizeof(photonEnergy)/sizeof(G4double);
assert(sizeof(absorption) == sizeof(photonEnergy));
assert(sizeof(scint) == sizeof(photonEnergy));
G4cout << "nEntries = " << nEntries << G4endl;
scintillatorMPT->AddProperty("FASTCOMPONENT", photonEnergy, scint, nEntries)->SetSpline(true); // BC408 emission spectra
scintillatorMPT->AddProperty("SLOWCOMPONENT", photonEnergy, scint, nEntries)->SetSpline(true); // BC408 emission spectra
scintillatorMPT->AddProperty("RINDEX", photonEnergy, RIndex1, nEntries); //refractive index can change with energy
//note if photon is created outside of energy range it will have no index of refraction
scintillatorMPT->AddProperty("ABSLENGTH", photonEnergy, absorption, nEntries)->SetSpline(true); //absorption length doesnt change with energy - examples showing it can...
//scintillatorMPT->AddConstProperty("ABSLENGTH", 160.*cm); //Bulk light attenuation
scintillatorMPT->AddConstProperty("FASTTIMECONSTANT", 1.8*ns); //only one decay constant given - BC404
scintillatorMPT->AddConstProperty("SLOWTIMECONSTANT", 1.8*ns); //only one decay constant given - BC404
//scintillatorMPT->AddConstProperty("FASTTIMECONSTANT", 0.00000000000000000*ns); // for testing the effective speed of light
//scintillatorMPT->AddConstProperty("SLOWTIMECONSTANT", 0.00000000000000000*ns); // for testing the effective speed of light
//Should these be in the physics list?
//G4OpticalPhysics * opticalPhysics = new G4OpticalPhysics();
//opticalPhysics->SetFiniteRiseTime(true);
scintillatorMPT->AddConstProperty("FASTSCINTILLATIONRISETIME", 0.7*ns); //default rise time is 0ns, have to set manually BC404
scintillatorMPT->AddConstProperty("SLOWSCINTILLATIONRISETIME", 0.7*ns); //default rise time is 0ns, have to set manually BC404
//scintillatorMPT->AddConstProperty("FASTSCINTILLATIONRISETIME", 0.*ns); // For testing speed of light
//scintillatorMPT->AddConstProperty("SLOWSCINTILLATIONRISETIME", 0.*ns); // For testing speed of light
}
// The number of photons produced per interaction is sampled from a Gaussian distribution with a full-width at half-maximum set to 20% of the number of produced photons. From Joeys Thesis
scintillatorMPT->AddConstProperty("RESOLUTIONSCALE", 1.2); // broadens the statistical distribution of generated photons, sqrt(num generated)* resScale, gaussian based on SCINTILLATIONYIELD, >1 broadens, 0 no distribution. 20%
scintillatorMPT->AddConstProperty("YIELDRATIO", 1.0); //The relative strength of the fast component as a fraction of total scintillation yield is given by the YIELDRATIO.
//properties I may be missing: scintillation, rayleigh
plasticG4material->SetMaterialPropertiesTable(scintillatorMPT);
const G4int numShort =3;
G4double photonEnergyShort[numShort] = {1.7*eV, 2.82*eV, 3.44*eV}; //BC408 emission spectra & corresponding energies
const G4int nEntriesShort = sizeof(photonEnergyShort)/sizeof(G4double);
//////Optical Surface - Teflon wrapping //////
G4OpticalSurface * ScintWrapper = new G4OpticalSurface("wrapper");
G4MaterialPropertiesTable * ScintWrapperMPT = new G4MaterialPropertiesTable();
ScintWrapper->SetModel(unified); // unified or glisur
ScintWrapper->SetType(dielectric_dielectric); // dielectric and dielectric or metal?
// teflon wrapping on polished surface->front/back painted // Teflon should be Lambertian in air, specular in optical grease
//polished front painted is more simplified. Only specular spike reflection
ScintWrapper->SetFinish(polishedfrontpainted);
//ground front painted is more simplified. Only lambertain reflection
//ScintWrapper->SetFinish(groundfrontpainted);
/* //poished back painted is maybe more realistic, need to then include sigma alpha (angle of the micro facet to the average normal surface)
//ScintWrapper->SetFinish(polishedbackpainted);
ScintWrapper->SetFinish(groundbackpainted);
ScintWrapper->SetSigmaAlpha(0.1); // 0 for smooth, 1 for max roughness
const G4int NUM =3;
G4double pp[NUM] = {2.038*eV, 4.144*eV};
G4double specularlobe[NUM] = {0.033, 0.033};
G4double specularspike[NUM] = {0.9, 0.9};
G4double backscatter[NUM] = {0.033, 0.033};
//Diffuse lobe constant is implicit, but spec lobe, spec spike, and backscatter all need to add up to 1. //diffuse lobe constant is the probability of internal lambertian refection
ScintWrapperMPT->AddProperty("SPECULARLOBECONSTANT",pp,specularlobe,NUM); //reflection probability about the normal of the micro facet
ScintWrapperMPT->AddProperty("SPECULARSPIKECONSTANT",pp,specularspike,NUM); //reflection probability about average surface normal
ScintWrapperMPT->AddProperty("BACKSCATTERCONSTANT",pp,backscatter,NUM); //probability of exact back scatter based on mutiple reflections within the deep groove
//end of polished back painted
*/
G4double rIndex_Teflon[numShort] = {1.35, 1.35, 1.35}; //Taken from wikipedia
ScintWrapperMPT->AddProperty("RINDEX", photonEnergyShort, rIndex_Teflon, nEntriesShort)->SetSpline(true); //refractive index can change with energy
//G4double reflectivity[numShort] = {0.95, 0.95, 0.95};
G4double reflectivity[numShort] = {0.99, 0.99, 0.99};
ScintWrapperMPT->AddProperty("REFLECTIVITY", photonEnergyShort, reflectivity, nEntriesShort)->SetSpline(true); // light reflected / incident light.
//G4double efficiency[numShort] = {0.95, 0.95, 0.95};
//ScintWrapperMPT->AddProperty("EFFICIENCY",photonEnergyShort,efficiency,nEntriesShort); //This is the Quantum Efficiency of the photocathode = # electrons / # of incident photons
ScintWrapper->SetMaterialPropertiesTable(ScintWrapperMPT);
ScintWrapper->DumpInfo();
//////// Quartz ////////////
G4MaterialPropertiesTable * QuartzMPT = new G4MaterialPropertiesTable();
G4double rIndex_Quartz[numShort] = {1.474, 1.474, 1.474}; //Taken from Joey github
QuartzMPT->AddProperty("RINDEX", photonEnergyShort, rIndex_Quartz, nEntriesShort)->SetSpline(true); //refractive index can change with energy
QuartzMPT->AddConstProperty("ABSLENGTH", 40.*cm); //from Joeys github
PMTG4material->SetMaterialPropertiesTable(QuartzMPT);
G4RotationMatrix *rot1 = new G4RotationMatrix(0,0,0);
///////// ZDS and 1x1x1 with 1 SiPM ///////////////////
double length = 5.*cm;
G4VSolid * Scint = new G4Box("Scint", 1.*cm/2., length/2. , 1.*cm/2.);
//G4VSolid * Scint = new G4Box("Scint", 1.*cm/2., 1.*cm/2. , 1.*cm/2.);
G4VSolid * Wrap_Bigger = new G4Box("Wrap_Bigger", 1.*cm/2.+fWrapThickness, length/2.+fWrapThickness, 1.*cm/2.+fWrapThickness);
G4SubtractionSolid * subtractWrap = new G4SubtractionSolid("subtractWrap", Wrap_Bigger, Scint, rot1, G4ThreeVector(0,0,0));
//G4VSolid * Wrap_Bigger = new G4Box("Wrap_Bigger", 1.*cm/2.+fWrapThickness, 1.*cm/2.+fWrapThickness, 1.*cm/2.+fWrapThickness);
//G4SubtractionSolid * subtractWrap = new G4SubtractionSolid("subtractWrap", Wrap_Bigger, Scint, rot1, G4ThreeVector(0,0,0));
G4VSolid * PMT = new G4Box("PMT", 0.4*cm/2., 0.4*cm/2. , 0.4*cm/2.);
G4SubtractionSolid * subtractWrap2 = new G4SubtractionSolid("subtractWrap2", subtractWrap, PMT, rot1, G4ThreeVector(0,-0.5*length-fWrapThickness,0));
//G4SubtractionSolid * subtractWrap2 = new G4SubtractionSolid("subtractWrap2", subtractWrap, PMT, rot1, G4ThreeVector(0,-0.5*cm-fWrapThickness,0));
///// Building the ZDS Geometry /////
G4Tubs * zds = new G4Tubs("zds", 0., fDiameter/2., fScintillatorWidth/2., fStartPhi, fDeltaPhi);
G4Tubs * pmt = new G4Tubs("pmt", 0., fDiameter/2., fPMTWidth/2., fStartPhi, fDeltaPhi);
//For placing volume
rotate = new G4RotationMatrix;
//Set visual attributes
G4VisAttributes * plastic_vis = new G4VisAttributes(silver);
plastic_vis->SetVisibility(true);
G4VisAttributes * wrapper_vis = new G4VisAttributes(black);
wrapper_vis->SetVisibility(true);
G4VisAttributes * zds_vis = new G4VisAttributes(silver);
zds_vis->SetVisibility(true);
G4VisAttributes * pmt_vis = new G4VisAttributes(bronze);
pmt_vis->SetVisibility(true);
//Names
G4String nameLog = "TestPlastic";
G4String nameWrapper = "wrapper";
G4String namePMT = "TestPMT1";
G4String nameZDS = "ZDS";
G4String nameZDSPMT = "zdsWindow";
//Assign Logical Volume for detectors and wrapping affected by beamline
fPlasticLog = new G4LogicalVolume(Scint, plasticG4material, nameLog,0,0,0);
fWrapLog = new G4LogicalVolume(subtractWrap2, wrapG4material, nameWrapper,0,0,0);
fPMTLog = new G4LogicalVolume(PMT, PMTG4material, namePMT,0,0,0);
fZDSLog = new G4LogicalVolume(zds, zdsG4material, nameZDS,0,0,0);
fZDSPMTLog = new G4LogicalVolume(pmt, PMTG4material, nameZDSPMT,0,0,0);
//Set Logical Skin for optical photons on wrapping
G4LogicalSkinSurface * Surface = new G4LogicalSkinSurface(nameWrapper, fWrapLog, ScintWrapper);
//Give everything colour
fZDSLog->SetVisAttributes(zds_vis);
fPMTLog->SetVisAttributes(pmt_vis);
fPlasticLog->SetVisAttributes(plastic_vis);
fWrapLog->SetVisAttributes(wrapper_vis);
fZDSPMTLog->SetVisAttributes(pmt_vis);
//Place Detectors
move = G4ThreeVector(0., -length/2. - fRadialDistance, 0.);
fAssemblyTestPlastics->AddPlacedVolume(fPlasticLog, move, rotate);
move = G4ThreeVector(0., -length/2. - fRadialDistance, 0.);
fAssemblyTestPlastics->AddPlacedVolume(fWrapLog, move, rotate);
move = G4ThreeVector(0., -length-0.2*cm-fRadialDistance, 0.);
fAssemblyTestPlastics->AddPlacedVolume(fPMTLog, move, rotate);
move = G4ThreeVector(0., 0., fRadialDistance);
move.rotateX(-M_PI/2.);
rotate = new G4RotationMatrix;
rotate->rotateX(M_PI/2.); // flip the detector so that the face is pointing upstream.
fAssemblyTestPlastics->AddPlacedVolume(fZDSLog, move, rotate);
move = G4ThreeVector(0., 0., fRadialDistance+fScintillatorWidth);
move.rotateX(-M_PI/2.);
rotate = new G4RotationMatrix;
rotate->rotateX(M_PI/2.); // flip the detector so that the face is pointing upstream.
fAssemblyTestPlastics->AddPlacedVolume(fZDSPMTLog, move, rotate);
///////// 1x1xlength and 2 SiPm ///////////////////
/*
double length = 3.*cm;
G4VSolid * Scint = new G4Box("Scint", 1.*cm/2., length/2. , 1.*cm/2.);
G4VSolid * Wrap_Bigger = new G4Box("Wrap_Bigger", 1.*cm/2.+fWrapThickness, length/2.+fWrapThickness, 1.*cm/2.+fWrapThickness);
G4SubtractionSolid * subtractWrap = new G4SubtractionSolid("subtractWrap", Wrap_Bigger, Scint, rot1, G4ThreeVector(0,0,0));
G4VSolid * PMT1 = new G4Box("PMT1", 0.4*cm/2., 0.4*cm/2. , 0.4*cm/2.);
G4VSolid * PMT2 = new G4Box("PMT2", 0.4*cm/2., 0.4*cm/2. , 0.4*cm/2.);
// For SiPM on either end ie on square face
//G4SubtractionSolid * subtractWrap2 = new G4SubtractionSolid("subtractWrap2", subtractWrap, PMT1, rot1, G4ThreeVector(0,-0.5*length-fWrapThickness,0));
//G4SubtractionSolid * subtractWrap3 = new G4SubtractionSolid("subtractWrap3", subtractWrap2, PMT2, rot1, G4ThreeVector(0,0.5*length+fWrapThickness,0));
// For SiPM on either end but on same long rectangular face
G4SubtractionSolid * subtractWrap2 = new G4SubtractionSolid("subtractWrap2", subtractWrap, PMT1, rot1, G4ThreeVector(0, -0.5*length + 0.2*cm, 0.5*cm + fWrapThickness));
G4SubtractionSolid * subtractWrap3 = new G4SubtractionSolid("subtractWrap3", subtractWrap2, PMT2, rot1, G4ThreeVector(0, 0.5*length - 0.2*cm, 0.5*cm + fWrapThickness));
//For placing volume
rotate = new G4RotationMatrix;
//Set visual attributes
G4VisAttributes * plastic_vis = new G4VisAttributes(silver);
plastic_vis->SetVisibility(true);
G4VisAttributes * wrapper_vis = new G4VisAttributes(black);
wrapper_vis->SetVisibility(true);
G4VisAttributes * pmt_vis = new G4VisAttributes(bronze);
pmt_vis->SetVisibility(true);
//Names
G4String nameLog = "TestPlastic";
G4String nameWrapper = "wrapper";
G4String namePMT1 = "TestPMT1";
G4String namePMT2 = "TestPMT2";
//Assign Logical Volume for detectors and wrapping affected by beamline
fPlasticLog = new G4LogicalVolume(Scint, plasticG4material, nameLog,0,0,0);
fWrapLog = new G4LogicalVolume(subtractWrap3, wrapG4material, nameWrapper,0,0,0);
fPMT1Log = new G4LogicalVolume(PMT1, PMTG4material, namePMT1,0,0,0);
fPMT2Log = new G4LogicalVolume(PMT2, PMTG4material, namePMT2,0,0,0);
//Set Logical Skin for optical photons on wrapping
G4LogicalSkinSurface * Surface = new G4LogicalSkinSurface(nameWrapper, fWrapLog, ScintWrapper);
//Give everything colour
fPMT1Log->SetVisAttributes(pmt_vis);
fPMT2Log->SetVisAttributes(pmt_vis);
fPlasticLog->SetVisAttributes(plastic_vis);
fWrapLog->SetVisAttributes(wrapper_vis);
//Place Detectors
//double yOffset = length/2. - 0.5*cm;
double yOffset = 0.;
double zOffset = 1.*cm;
move = G4ThreeVector(0., yOffset, zOffset);
fAssemblyTestPlastics->AddPlacedVolume(fPlasticLog, move, rotate);
move = G4ThreeVector(0., yOffset, zOffset);
fAssemblyTestPlastics->AddPlacedVolume(fWrapLog, move, rotate);
// For SiPM on either end ie on square face
// move = G4ThreeVector(0., yOffset + 0.5*length+0.2*cm, zOffset);
// fAssemblyTestPlastics->AddPlacedVolume(fPMT1Log, move, rotate);
// move = G4ThreeVector(0., yOffset - 0.5*length-0.2*cm, zOffset);
// fAssemblyTestPlastics->AddPlacedVolume(fPMT2Log, move, rotate);
// For SiPM on either end but on same long rectangular face
move = G4ThreeVector(0., yOffset + 0.5*length - 0.2*cm, zOffset + 0.2*cm + 0.5*cm);
fAssemblyTestPlastics->AddPlacedVolume(fPMT1Log, move, rotate);
move = G4ThreeVector(0., yOffset - 0.5*length + 0.2*cm, zOffset + 0.2*cm + 0.5*cm);
fAssemblyTestPlastics->AddPlacedVolume(fPMT2Log, move, rotate);
*/
return 1;
}
| 51.032882 | 260 | 0.728244 | [
"geometry",
"solid"
] |
aeb56833e937fd3a6a7ab7f72dd24aca40217296 | 5,560 | cpp | C++ | widget.cpp | ic3man5/KeyControl | 4129c2a0aae013ae78964edabb260c7a14fb31e9 | [
"Unlicense"
] | null | null | null | widget.cpp | ic3man5/KeyControl | 4129c2a0aae013ae78964edabb260c7a14fb31e9 | [
"Unlicense"
] | null | null | null | widget.cpp | ic3man5/KeyControl | 4129c2a0aae013ae78964edabb260c7a14fb31e9 | [
"Unlicense"
] | null | null | null | #include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QSettings>
auto construct_name = [](auto* w) -> auto {
auto* parent = w->parent();
if (auto* temp = qobject_cast<QGroupBox*>(parent))
return QString("%1 %2").arg(temp->title(), w->text());
qDebug() << "NOPE!";
return w->text();
};
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
QSettings settings;
ui->setupUi(this);
mTrayIcon = new QSystemTrayIcon(QIcon(":/icons/default_icon"), this);
connect(mTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
mTrayIcon->show();
mKeyControlThread = new QThread(this);
mKeyControl = new KeyControl(this);
mKeyControl->moveToThread(mKeyControlThread);
mKeyControlTimer = new QTimer();
connect(this, SIGNAL(capsOptionChanged(KeyControl::Option)), mKeyControl, SLOT(setCapsOption(Option)), Qt::QueuedConnection);
connect(mKeyControlThread, SIGNAL(finished()), mKeyControl, SLOT(deleteLater()));
connect(mKeyControlTimer, SIGNAL(timeout()), mKeyControl, SLOT(process_keys()));
mKeyControlThread->start();
mKeyControlTimer->start(10);
QList<QRadioButton*> caps_widgets =
{ ui->radioButtonCapsNone, ui->radioButtonCapsOn, ui->radioButtonCapsOff };
for (auto* widget : caps_widgets) {
connect(widget, SIGNAL(clicked()), this, SLOT(caps_lock_option_changed()));
if (settings.value(construct_name(widget), true).toBool()) {
widget->setChecked(true);
}
}
QList<QRadioButton*> num_widgets =
{ ui->radioButtonNumNone, ui->radioButtonNumOn, ui->radioButtonNumOff };
for (auto* widget : num_widgets) {
connect(widget, SIGNAL(clicked()), this, SLOT(num_lock_option_changed()));
if (settings.value(construct_name(widget), true).toBool()) {
widget->setChecked(true);
}
}
QList<QRadioButton*> scroll_widgets =
{ ui->radioButtonScrollNone, ui->radioButtonScrollOn, ui->radioButtonScrollOff };
for (auto* widget : scroll_widgets) {
connect(widget, SIGNAL(clicked()), this, SLOT(scoll_lock_option_changed()));
if (settings.value(construct_name(widget), true).toBool()) {
widget->setChecked(true);
}
}
restoreGeometry(settings.value("WindowGeometry", geometry()).toByteArray());
caps_lock_option_changed();
num_lock_option_changed();
scroll_lock_option_changed();
}
Widget::~Widget()
{
QSettings settings;
mKeyControlTimer->stop();
mKeyControlThread->quit();
mKeyControlThread->wait(5);
settings.setValue("WindowGeometry", saveGeometry());
// Copied from constructor...
QList<QRadioButton*> caps_widgets =
{ ui->radioButtonCapsNone, ui->radioButtonCapsOn, ui->radioButtonCapsOff };
for (auto* widget : caps_widgets) {
connect(widget, SIGNAL(clicked()), this, SLOT(caps_lock_option_changed()));
settings.setValue(construct_name(widget), widget->isChecked());
}
QList<QRadioButton*> num_widgets =
{ ui->radioButtonNumNone, ui->radioButtonNumOn, ui->radioButtonNumOff };
for (auto* widget : num_widgets) {
connect(widget, SIGNAL(clicked()), this, SLOT(num_lock_option_changed()));
settings.setValue(construct_name(widget), widget->isChecked());
}
QList<QRadioButton*> scroll_widgets =
{ ui->radioButtonScrollNone, ui->radioButtonScrollOn, ui->radioButtonScrollOff };
for (auto* widget : scroll_widgets) {
connect(widget, SIGNAL(clicked()), this, SLOT(scoll_lock_option_changed()));
settings.setValue(construct_name(widget), widget->isChecked());
}
delete ui;
}
void Widget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Context:
qDebug() << "Context";
break;
case QSystemTrayIcon::DoubleClick:
qDebug() << "Double Click";
break;
case QSystemTrayIcon::Trigger:
qDebug() << "Trigger";
if (isVisible())
this->hide();
else
this->show();
break;
case QSystemTrayIcon::MiddleClick:
qDebug() << "Middle Click";
qApp->quit();
break;
default:
qDebug() << "Unknown Reason...";
}
}
void Widget::caps_lock_option_changed()
{
if (ui->radioButtonCapsNone->isChecked()) {
mKeyControl->setCapsOption(KeyControl::DONT_TOUCH);
} else if (ui->radioButtonCapsOn->isChecked()) {
mKeyControl->setCapsOption(KeyControl::ON);
} else if (ui->radioButtonCapsOff->isChecked()) {
mKeyControl->setCapsOption(KeyControl::OFF);
}
}
void Widget::num_lock_option_changed()
{
if (ui->radioButtonNumNone->isChecked()) {
mKeyControl->setNumOption(KeyControl::DONT_TOUCH);
} else if (ui->radioButtonNumOn->isChecked()) {
mKeyControl->setNumOption(KeyControl::ON);
} else if (ui->radioButtonNumOff->isChecked()) {
mKeyControl->setNumOption(KeyControl::OFF);
}
}
void Widget::scroll_lock_option_changed()
{
if (ui->radioButtonScrollNone->isChecked()) {
mKeyControl->setScrollOption(KeyControl::DONT_TOUCH);
} else if (ui->radioButtonScrollOn->isChecked()) {
mKeyControl->setScrollOption(KeyControl::ON);
} else if (ui->radioButtonScrollOff->isChecked()) {
mKeyControl->setScrollOption(KeyControl::OFF);
}
}
void Widget::on_pushButtonHide_clicked()
{
hide();
}
| 34.968553 | 129 | 0.660252 | [
"geometry"
] |
aec06d4b23c9b9f61812d3d2faee6546c8eef08c | 1,031 | cpp | C++ | examples/image_live_view/image_processor.cpp | zhujun98/EXtra-foam | 680d6d7fd4afdcbc41eb8e440feac54b6cecab33 | [
"BSD-3-Clause"
] | 7 | 2019-11-27T09:31:37.000Z | 2022-02-12T21:28:49.000Z | examples/image_live_view/image_processor.cpp | zhujun98/EXtra-foam | 680d6d7fd4afdcbc41eb8e440feac54b6cecab33 | [
"BSD-3-Clause"
] | 172 | 2019-12-03T07:56:02.000Z | 2022-03-25T15:46:45.000Z | examples/image_live_view/image_processor.cpp | zhujun98/EXtra-foam | 680d6d7fd4afdcbc41eb8e440feac54b6cecab33 | [
"BSD-3-Clause"
] | 9 | 2019-11-27T09:32:38.000Z | 2022-01-05T09:56:10.000Z | /**
* Distributed under the terms of the BSD 3-Clause License.
*
* The full license is in the file LICENSE, distributed with this software.
*
* Author: Jun Zhu <jun.zhu@xfel.eu>
* Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
* All rights reserved.
*/
#include <QThread>
#include <QImage>
#include <QPixmap>
#include <QDebug>
#include <xtensor/xarray.hpp>
#include "image_processor.hpp"
ImageProcessor::ImageProcessor(const std::shared_ptr<ImageQueue>& queue, QObject* parent)
: queue_(queue), processing_(false)
{
Q_UNUSED(parent)
}
void ImageProcessor::process()
{
processing_ = true;
while(processing_)
{
xt::xarray<float> arr;
if (queue_->try_pop(arr))
{
auto data = reinterpret_cast<unsigned char*>(arr.data());
QImage img(data, arr.shape()[1], arr.shape()[0], QImage::Format_ARGB32);
qDebug() << "Image processed";
emit newFrame(QPixmap::fromImage(img));
}
QThread::msleep(1);
}
}
void ImageProcessor::stop()
{
processing_ = false;
}
| 21.479167 | 89 | 0.678952 | [
"shape"
] |
aecb7c6ed5c027a8979d8936139718205befea8e | 3,287 | cxx | C++ | smtk/extension/qt/qtSMTKUtilities.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 40 | 2015-02-21T19:55:54.000Z | 2022-01-06T13:13:05.000Z | smtk/extension/qt/qtSMTKUtilities.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 127 | 2015-01-15T20:55:45.000Z | 2021-08-19T17:34:15.000Z | smtk/extension/qt/qtSMTKUtilities.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 27 | 2015-03-04T14:17:51.000Z | 2021-12-23T01:05:42.000Z | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/extension/qt/qtSMTKUtilities.h"
#include "smtk/common/UUID.h"
#include "smtk/extension/qt/qtResourceBrowser.h"
#include "smtk/extension/qt/qtUIManager.h"
#include "smtk/model/EntityRef.h"
using qtItemConstructor = smtk::extension::qtItemConstructor;
using qtModelViewConstructor = smtk::extension::qtModelViewConstructor;
using qtResourceBrowser = smtk::extension::qtResourceBrowser;
SMTKItemConstructorMap qtSMTKUtilities::s_itemConstructors;
SMTKModelViewConstructorMap qtSMTKUtilities::s_modelViewConstructors;
const SMTKItemConstructorMap& qtSMTKUtilities::itemConstructors()
{
return qtSMTKUtilities::s_itemConstructors;
}
const SMTKModelViewConstructorMap& qtSMTKUtilities::modelViewConstructors()
{
auto& ctors = qtSMTKUtilities::s_modelViewConstructors;
auto defEntry = ctors.find("");
if (defEntry == ctors.end())
{
ctors[""] = qtResourceBrowser::createDefaultView;
}
return ctors;
}
void qtSMTKUtilities::registerItemConstructor(const std::string& itemName, qtItemConstructor itemc)
{
// this will overwrite the existing constructor if the itemName exists in the map
qtSMTKUtilities::s_itemConstructors[itemName] = itemc;
}
void qtSMTKUtilities::registerModelViewConstructor(
const std::string& viewName,
smtk::extension::qtModelViewConstructor viewc)
{
qtSMTKUtilities::s_modelViewConstructors[viewName] = viewc;
}
void qtSMTKUtilities::updateItemConstructors(smtk::extension::qtUIManager* uiMan)
{
if (!uiMan || qtSMTKUtilities::itemConstructors().empty())
return;
SMTKItemConstructorMap::const_iterator it;
for (it = qtSMTKUtilities::itemConstructors().begin();
it != qtSMTKUtilities::itemConstructors().end();
++it)
{
uiMan->registerItemConstructor(it->first, it->second);
}
}
QVariant qtSMTKUtilities::UUIDToQVariant(const smtk::common::UUID& uuid)
{
QVariant vdata(QByteArray(
reinterpret_cast<const char*>(uuid.begin()), static_cast<int>(smtk::common::UUID::size())));
return vdata;
}
QVariant qtSMTKUtilities::entityRefToQVariant(const smtk::model::EntityRef& ent)
{
return qtSMTKUtilities::UUIDToQVariant(ent.entity());
}
smtk::common::UUID qtSMTKUtilities::QVariantToUUID(QVariant variant)
{
QByteArray uuidData = variant.toByteArray();
if (uuidData.size() != static_cast<int>(smtk::common::UUID::size()))
{
return smtk::common::UUID();
}
smtk::common::UUID uuid(
reinterpret_cast<smtk::common::UUID::const_iterator>(uuidData.constData()),
reinterpret_cast<smtk::common::UUID::const_iterator>(uuidData.constData() + uuidData.size()));
return uuid;
}
smtk::model::EntityRef qtSMTKUtilities::QVariantToEntityRef(
QVariant variant,
smtk::model::ResourcePtr mResource)
{
smtk::common::UUID uuid = qtSMTKUtilities::QVariantToUUID(variant);
return smtk::model::EntityRef(mResource, uuid);
}
| 33.20202 | 99 | 0.726498 | [
"model"
] |
aecc69eca3807d105dba5855b89df59d2e39c50f | 209 | hpp | C++ | src/victoryconnect/headers/victoryconnect.hpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | src/victoryconnect/headers/victoryconnect.hpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | src/victoryconnect/headers/victoryconnect.hpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | #ifndef _VC_HEADER__
#define _VC_HEADER__
#include <vector>
#include <string>
#include "packet.hpp"
#include "client.hpp"
#include "packet_parser.hpp"
#include "utils.hpp"
#include "tcp_connection.hpp"
#endif
| 19 | 29 | 0.770335 | [
"vector"
] |
aed89f4a6dd409c4381e356626e390b17b76d8c9 | 3,535 | hpp | C++ | src/Renderers/OIT/WBOITRenderer.hpp | chrismile/LineVis | f0e20c0f138bc9ee9c7da07cc39a235527af7e2d | [
"Apache-2.0"
] | 25 | 2021-09-14T12:24:27.000Z | 2022-03-24T10:57:03.000Z | src/Renderers/OIT/WBOITRenderer.hpp | chrismile/LineVis | f0e20c0f138bc9ee9c7da07cc39a235527af7e2d | [
"Apache-2.0"
] | 1 | 2021-09-07T09:07:35.000Z | 2021-09-07T09:07:35.000Z | src/Renderers/OIT/WBOITRenderer.hpp | chrismile/LineVis | f0e20c0f138bc9ee9c7da07cc39a235527af7e2d | [
"Apache-2.0"
] | 3 | 2021-09-01T21:39:15.000Z | 2022-03-18T14:18:05.000Z | /*
* BSD 2-Clause License
*
* Copyright (c) 2021, Christoph Neuhauser
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LINEVIS_WBOITRENDERER_HPP
#define LINEVIS_WBOITRENDERER_HPP
#include "Renderers/LineRenderer.hpp"
/**
* Renders all lines with transparency values determined by the transfer function set by the user.
* For this, the order-independent transparency (OIT) technique Weighted Blended Order-Independent Transparency (WBOIT)
* is used. For more details see: Morgan McGuire and Louis Bavoil. 2013. Weighted Blended Order-Independent
* Transparency. Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 122-141, 2013.
*
* For more details regarding the implementation see:
* http://casual-effects.blogspot.com/2015/03/implemented-weighted-blended-order.html
*/
class WBOITRenderer : public LineRenderer {
public:
WBOITRenderer(SceneData& sceneData, sgl::TransferFunctionWindow& transferFunctionWindow);
~WBOITRenderer() override {}
RenderingMode getRenderingMode() override { return RENDERING_MODE_WBOIT; }
/**
* Re-generates the visualization mapping.
* @param lineData The render data.
*/
void setLineData(LineDataPtr& lineData, bool isNewData) override;
/// Called when the resolution of the application window has changed.
void onResolutionChanged() override;
// Renders the object to the scene framebuffer.
void render() override;
// Renders the GUI. The "dirty" and "reRender" flags might be set depending on the user's actions.
void renderGui() override;
private:
void setUniformData();
void reloadShaders();
void reloadGatherShader(bool canCopyShaderAttributes = true) override;
void reloadResolveShader();
// Shaders.
sgl::ShaderProgramPtr gatherShader;
sgl::ShaderProgramPtr resolveShader;
// Render data.
sgl::ShaderAttributesPtr shaderAttributes;
// Blit data (ignores model-view-projection matrix and uses normalized device coordinates).
sgl::ShaderAttributesPtr blitRenderData;
// Render data of depth peeling
sgl::FramebufferObjectPtr gatherPassFBO;
sgl::TexturePtr accumulationRenderTexture;
sgl::TexturePtr revealageRenderTexture;
};
#endif //LINEVIS_WBOITRENDERER_HPP
| 41.588235 | 119 | 0.758982 | [
"render",
"object",
"model"
] |
aed8f74b71eea9540d8e7c479e0128f20b032cb4 | 30,048 | cpp | C++ | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXMETAL/Interfaces/CCryDXMETALDevice.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXMETAL/Interfaces/CCryDXMETALDevice.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DXMETAL/Interfaces/CCryDXMETALDevice.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Definition of the DXGL wrapper for ID3D11Device
#include "StdAfx.h"
#include "CCryDXMETALBlendState.hpp"
#include "CCryDXMETALBuffer.hpp"
#include "CCryDXMETALDepthStencilState.hpp"
#include "CCryDXMETALDepthStencilView.hpp"
#include "CCryDXMETALDevice.hpp"
#include "CCryDXMETALDeviceContext.hpp"
#include "CCryDXMETALDevice.hpp"
#include "CCryDXMETALInputLayout.hpp"
#include "CCryDXMETALQuery.hpp"
#include "CCryDXMETALRasterizerState.hpp"
#include "CCryDXMETALRenderTargetView.hpp"
#include "CCryDXMETALSamplerState.hpp"
#include "CCryDXMETALSwapChain.hpp"
#include "CCryDXMETALShader.hpp"
#include "CCryDXMETALShaderResourceView.hpp"
#include "CCryDXMETALTexture1D.hpp"
#include "CCryDXMETALTexture2D.hpp"
#include "CCryDXMETALTexture3D.hpp"
#include "CCryDXMETALUnorderedAccessView.hpp"
#include "../Implementation/MetalDevice.hpp"
#include "../Implementation/GLFormat.hpp"
#include "../Implementation/GLResource.hpp"
#include "../Implementation/GLShader.hpp"
CCryDXGLDevice::CCryDXGLDevice(CCryDXGLGIAdapter* pAdapter, D3D_FEATURE_LEVEL eFeatureLevel)
: m_spAdapter(pAdapter)
, m_eFeatureLevel(eFeatureLevel)
{
DXGL_INITIALIZE_INTERFACE(DXGIDevice)
DXGL_INITIALIZE_INTERFACE(D3D11Device)
CCryDXGLDeviceContext * pImmediateContext(new CCryDXGLDeviceContext());
m_spImmediateContext = pImmediateContext;
pImmediateContext->Release();
}
CCryDXGLDevice::~CCryDXGLDevice()
{
m_spImmediateContext->Shutdown();
}
#if !DXGL_FULL_EMULATION
HRESULT CCryDXGLDevice::QueryInterface(REFIID riid, void** ppvObject)
{
if (SingleInterface<ID3D11Device>::Query(this, riid, ppvObject) ||
SingleInterface<CCryDXGLDevice>::Query(this, riid, ppvObject))
{
return S_OK;
}
#if DXGL_VIRTUAL_DEVICE_AND_CONTEXT
return E_NOINTERFACE;
#else
return CCryDXGLBase::QueryInterface(riid, ppvObject);
#endif
}
#endif //!DXGL_FULL_EMULATION
bool CCryDXGLDevice::Initialize(const DXGI_SWAP_CHAIN_DESC* pDesc, IDXGISwapChain** ppSwapChain)
{
if (!pDesc || !ppSwapChain || !m_spAdapter || !m_spAdapter->GetGLAdapter())
{
return false;
}
m_spGLDevice = new NCryMetal::CDevice();
if (!m_spGLDevice->Initialize(pDesc->OutputWindow))
{
return false;
}
CCryDXGLSwapChain* pDXGLSwapChain(new CCryDXGLSwapChain(this, *pDesc));
CCryDXGLSwapChain::ToInterface(ppSwapChain, pDXGLSwapChain);
if (!pDXGLSwapChain->Initialize())
{
return false;
}
return m_spImmediateContext->Initialize(this);
}
NCryMetal::CDevice* CCryDXGLDevice::GetGLDevice()
{
return m_spGLDevice;
}
////////////////////////////////////////////////////////////////////////////////
// IDXGIObject overrides
////////////////////////////////////////////////////////////////////////////////
HRESULT CCryDXGLDevice::GetParent(REFIID riid, void** ppParent)
{
IUnknown* pAdapterInterface;
CCryDXGLBase::ToInterface(&pAdapterInterface, m_spAdapter);
if (pAdapterInterface->QueryInterface(riid, ppParent) == S_OK && ppParent != NULL)
{
return S_OK;
}
#if DXGL_VIRTUAL_DEVICE_AND_CONTEXT && !DXGL_FULL_EMULATION
return E_FAIL;
#else
return CCryDXGLGIObject::GetParent(riid, ppParent);
#endif
}
////////////////////////////////////////////////////////////////////////////////
// IDXGIDevice implementation
////////////////////////////////////////////////////////////////////////////////
HRESULT CCryDXGLDevice::GetAdapter(IDXGIAdapter** pAdapter)
{
if (m_spAdapter == NULL)
{
return E_FAIL;
}
CCryDXGLGIAdapter::ToInterface(pAdapter, m_spAdapter);
return S_OK;
}
HRESULT CCryDXGLDevice::CreateSurface(const DXGI_SURFACE_DESC* pDesc, UINT NumSurfaces, DXGI_USAGE Usage, const DXGI_SHARED_RESOURCE* pSharedResource, IDXGISurface** ppSurface)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::QueryResourceResidency(IUnknown* const* ppResources, DXGI_RESIDENCY* pResidencyStatus, UINT NumResources)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::SetGPUThreadPriority(INT Priority)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::GetGPUThreadPriority(INT* pPriority)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
////////////////////////////////////////////////////////////////////////////////
// ID3D11Device implementation
////////////////////////////////////////////////////////////////////////////////
HRESULT CCryDXGLDevice::CreateBuffer(const D3D11_BUFFER_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Buffer** ppBuffer)
{
if (ppBuffer == NULL)
{
// In this case the method should perform parameter validation and return the result
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
NCryMetal::SBufferPtr spGLBuffer(NCryMetal::CreateBuffer(*pDesc, pInitialData, m_spGLDevice));
if (spGLBuffer == NULL)
{
return E_FAIL;
}
CCryDXGLBuffer::ToInterface(ppBuffer, new CCryDXGLBuffer(*pDesc, spGLBuffer, this));
return S_OK;
}
HRESULT CCryDXGLDevice::CreateTexture1D(const D3D11_TEXTURE1D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture1D** ppTexture1D)
{
if (ppTexture1D == NULL)
{
// In this case the method should perform parameter validation and return the result
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
NCryMetal::STexturePtr spGLTexture(NCryMetal::CreateTexture1D(*pDesc, pInitialData, m_spGLDevice));
if (spGLTexture == NULL)
{
return E_FAIL;
}
CCryDXGLTexture1D::ToInterface(ppTexture1D, new CCryDXGLTexture1D(*pDesc, spGLTexture, this));
return S_OK;
}
HRESULT CCryDXGLDevice::CreateTexture2D(const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D)
{
if (ppTexture2D == NULL)
{
// In this case the method should perform parameter validation and return the result
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
NCryMetal::STexturePtr spGLTexture(NCryMetal::CreateTexture2D(*pDesc, pInitialData, m_spGLDevice));
if (spGLTexture == NULL)
{
return E_FAIL;
}
CCryDXGLTexture2D::ToInterface(ppTexture2D, new CCryDXGLTexture2D(*pDesc, spGLTexture, this));
return S_OK;
}
HRESULT CCryDXGLDevice::CreateTexture3D(const D3D11_TEXTURE3D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture3D** ppTexture3D)
{
if (ppTexture3D == NULL)
{
// In this case the method should perform parameter validation and return the result
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
NCryMetal::STexturePtr spGLTexture(NCryMetal::CreateTexture3D(*pDesc, pInitialData, m_spGLDevice));
if (spGLTexture == NULL)
{
return E_FAIL;
}
CCryDXGLTexture3D::ToInterface(ppTexture3D, new CCryDXGLTexture3D(*pDesc, spGLTexture, this));
return S_OK;
}
bool GetStandardViewDesc(CCryDXGLTexture1D* pTexture, D3D11_SHADER_RESOURCE_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE1D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
if (kTextureDesc.ArraySize > 0)
{
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
kStandardDesc.Texture1DArray.MostDetailedMip = 0;
kStandardDesc.Texture1DArray.MipLevels = -1;
kStandardDesc.Texture1DArray.FirstArraySlice = 0;
kStandardDesc.Texture1DArray.ArraySize = kTextureDesc.ArraySize;
}
else
{
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
kStandardDesc.Texture1D.MostDetailedMip = 0;
kStandardDesc.Texture1DArray.MipLevels = -1;
}
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLTexture2D* pTexture, D3D11_SHADER_RESOURCE_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE2D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
if (kTextureDesc.ArraySize > 1)
{
if (kTextureDesc.SampleDesc.Count > 1)
{
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY;
kStandardDesc.Texture2DMSArray.FirstArraySlice = 0;
kStandardDesc.Texture2DMSArray.ArraySize = kTextureDesc.ArraySize;
}
else
{
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
kStandardDesc.Texture2DArray.MostDetailedMip = 0;
kStandardDesc.Texture2DArray.MipLevels = -1;
kStandardDesc.Texture2DArray.FirstArraySlice = 0;
kStandardDesc.Texture2DArray.ArraySize = kTextureDesc.ArraySize;
}
}
else if (kTextureDesc.SampleDesc.Count > 1)
{
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS;
}
else
{
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
kStandardDesc.Texture2D.MostDetailedMip = 0;
kStandardDesc.Texture2D.MipLevels = -1;
}
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLTexture3D* pTexture, D3D11_SHADER_RESOURCE_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE3D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
kStandardDesc.Texture3D.MostDetailedMip = 0;
kStandardDesc.Texture3D.MipLevels = -1;
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLBuffer* pBuffer, D3D11_SHADER_RESOURCE_VIEW_DESC& kStandardDesc)
{
D3D11_BUFFER_DESC kBufferDesc;
pBuffer->GetDesc(&kBufferDesc);
bool bSuccess((kBufferDesc.MiscFlags | D3D11_RESOURCE_MISC_BUFFER_STRUCTURED) != 0);
if (bSuccess)
{
kStandardDesc.Format = DXGI_FORMAT_UNKNOWN;
kStandardDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
kStandardDesc.Buffer.FirstElement = 0;
kStandardDesc.Buffer.NumElements = kBufferDesc.StructureByteStride;
}
else
{
DXGL_ERROR("Default shader resource view for a buffer requires element size specification");
}
pBuffer->Release();
return bSuccess;
}
bool GetStandardViewDesc(CCryDXGLTexture1D* pTexture, D3D11_RENDER_TARGET_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE1D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
if (kTextureDesc.ArraySize > 0)
{
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY;
kStandardDesc.Texture1DArray.MipSlice = 0;
kStandardDesc.Texture1DArray.FirstArraySlice = 0;
kStandardDesc.Texture1DArray.ArraySize = kTextureDesc.ArraySize;
}
else
{
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D;
kStandardDesc.Texture1D.MipSlice = 0;
}
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLTexture2D* pTexture, D3D11_RENDER_TARGET_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE2D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
if (kTextureDesc.ArraySize > 1)
{
if (kTextureDesc.SampleDesc.Count > 1)
{
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
kStandardDesc.Texture2DMSArray.FirstArraySlice = 0;
kStandardDesc.Texture2DMSArray.ArraySize = kTextureDesc.ArraySize;
}
else
{
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
kStandardDesc.Texture2DArray.MipSlice = 0;
kStandardDesc.Texture2DArray.FirstArraySlice = 0;
kStandardDesc.Texture2DArray.ArraySize = kTextureDesc.ArraySize;
}
}
else if (kTextureDesc.SampleDesc.Count > 1)
{
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
}
else
{
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
kStandardDesc.Texture2D.MipSlice = 0;
}
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLTexture3D* pTexture, D3D11_RENDER_TARGET_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE3D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
kStandardDesc.Texture3D.MipSlice = 0;
kStandardDesc.Texture3D.FirstWSlice = 0;
kStandardDesc.Texture3D.WSize = -1;
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLBuffer* pBuffer, D3D11_RENDER_TARGET_VIEW_DESC& kStandardDesc)
{
D3D11_BUFFER_DESC kBufferDesc;
pBuffer->GetDesc(&kBufferDesc);
bool bSuccess((kBufferDesc.MiscFlags | D3D11_RESOURCE_MISC_BUFFER_STRUCTURED) != 0);
if (bSuccess)
{
kStandardDesc.Format = DXGI_FORMAT_UNKNOWN;
kStandardDesc.ViewDimension = D3D11_RTV_DIMENSION_BUFFER;
kStandardDesc.Buffer.FirstElement = 0;
kStandardDesc.Buffer.NumElements = kBufferDesc.StructureByteStride;
}
else
{
DXGL_ERROR("Default render target view for a buffer requires element size specification");
}
pBuffer->Release();
return bSuccess;
}
bool GetStandardViewDesc(CCryDXGLTexture1D* pTexture, D3D11_DEPTH_STENCIL_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE1D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
kStandardDesc.Flags = 0;
if (kTextureDesc.ArraySize > 0)
{
kStandardDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1DARRAY;
kStandardDesc.Texture1DArray.MipSlice = 0;
kStandardDesc.Texture1DArray.FirstArraySlice = 0;
kStandardDesc.Texture1DArray.ArraySize = kTextureDesc.ArraySize;
}
else
{
kStandardDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1D;
kStandardDesc.Texture1D.MipSlice = 0;
}
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLTexture2D* pTexture, D3D11_DEPTH_STENCIL_VIEW_DESC& kStandardDesc)
{
D3D11_TEXTURE2D_DESC kTextureDesc;
pTexture->GetDesc(&kTextureDesc);
kStandardDesc.Format = kTextureDesc.Format;
kStandardDesc.Flags = 0;
if (kTextureDesc.ArraySize > 0)
{
if (kTextureDesc.SampleDesc.Count > 1)
{
kStandardDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
kStandardDesc.Texture2DMSArray.FirstArraySlice = 0;
kStandardDesc.Texture2DMSArray.ArraySize = kTextureDesc.ArraySize;
}
else
{
kStandardDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
kStandardDesc.Texture2DArray.MipSlice = 0;
kStandardDesc.Texture2DArray.FirstArraySlice = 0;
kStandardDesc.Texture2DArray.ArraySize = kTextureDesc.ArraySize;
}
}
else if (kTextureDesc.SampleDesc.Count > 1)
{
kStandardDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
}
else
{
kStandardDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
kStandardDesc.Texture2D.MipSlice = 0;
}
pTexture->Release();
return true;
}
bool GetStandardViewDesc(CCryDXGLTexture3D* pTexture, D3D11_DEPTH_STENCIL_VIEW_DESC&)
{
DXGL_ERROR("Cannot bind a depth stencil view to a 3D texture");
pTexture->Release();
return false;
}
bool GetStandardViewDesc(CCryDXGLBuffer* pBuffer, D3D11_DEPTH_STENCIL_VIEW_DESC&)
{
DXGL_ERROR("Cannot bind a depth stencil view to a buffer");
pBuffer->Release();
return false;
}
template <typename ViewDesc>
bool GetStandardViewDesc(ID3D11Resource* pResource, ViewDesc& kStandardDesc)
{
memset(&kStandardDesc, 0, sizeof(kStandardDesc));
void* pvData(NULL);
if (!FAILED(pResource->QueryInterface(__uuidof(ID3D11Texture1D), &pvData)) && pvData != NULL)
{
return GetStandardViewDesc(CCryDXGLTexture1D::FromInterface(reinterpret_cast<ID3D11Texture1D*>(pvData)), kStandardDesc);
}
if (!FAILED(pResource->QueryInterface(__uuidof(ID3D11Texture2D), &pvData)) && pvData != NULL)
{
return GetStandardViewDesc(CCryDXGLTexture2D::FromInterface(reinterpret_cast<ID3D11Texture2D*>(pvData)), kStandardDesc);
}
if (!FAILED(pResource->QueryInterface(__uuidof(ID3D11Texture3D), &pvData)) && pvData != NULL)
{
return GetStandardViewDesc(CCryDXGLTexture3D::FromInterface(reinterpret_cast<ID3D11Texture3D*>(pvData)), kStandardDesc);
}
if (!FAILED(pResource->QueryInterface(__uuidof(ID3D11Buffer), &pvData)) && pvData != NULL)
{
return GetStandardViewDesc(CCryDXGLBuffer::FromInterface(reinterpret_cast<ID3D11Buffer*>(pvData)), kStandardDesc);
}
DXGL_ERROR("Unknown resource type for standard view description");
return false;
}
HRESULT CCryDXGLDevice::CreateShaderResourceView(ID3D11Resource* pResource, const D3D11_SHADER_RESOURCE_VIEW_DESC* pDesc, ID3D11ShaderResourceView** ppSRView)
{
D3D11_SHADER_RESOURCE_VIEW_DESC kStandardDesc;
if (pDesc == NULL)
{
if (!GetStandardViewDesc(pResource, kStandardDesc))
{
return E_INVALIDARG;
}
pDesc = &kStandardDesc;
}
CRY_ASSERT(pDesc != NULL);
CCryDXGLShaderResourceView* pSRView(new CCryDXGLShaderResourceView(CCryDXGLResource::FromInterface(pResource), *pDesc, this));
if (pSRView->Initialize(m_spGLDevice))
{
CCryDXGLShaderResourceView::ToInterface(ppSRView, pSRView);
return S_OK;
}
pSRView->Release();
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateUnorderedAccessView(ID3D11Resource* pResource, const D3D11_UNORDERED_ACCESS_VIEW_DESC* pDesc, ID3D11UnorderedAccessView** ppUAView)
{
CCryDXGLUnorderedAccessView::ToInterface(ppUAView, new CCryDXGLUnorderedAccessView(CCryDXGLResource::FromInterface(pResource), *pDesc, this));
return S_OK;
}
HRESULT CCryDXGLDevice::CreateRenderTargetView(ID3D11Resource* pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView)
{
D3D11_RENDER_TARGET_VIEW_DESC kStandardDesc;
if (pDesc == NULL)
{
if (!GetStandardViewDesc(pResource, kStandardDesc))
{
return E_INVALIDARG;
}
pDesc = &kStandardDesc;
}
CRY_ASSERT(pDesc != NULL);
CCryDXGLRenderTargetView* pRTView(new CCryDXGLRenderTargetView(CCryDXGLResource::FromInterface(pResource), *pDesc, this));
if (pRTView->Initialize(m_spGLDevice))
{
CCryDXGLRenderTargetView::ToInterface(ppRTView, pRTView);
return S_OK;
}
pRTView->Release();
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateDepthStencilView(ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView)
{
D3D11_DEPTH_STENCIL_VIEW_DESC kStandardDesc;
if (pDesc == NULL)
{
if (!GetStandardViewDesc(pResource, kStandardDesc))
{
return E_INVALIDARG;
}
pDesc = &kStandardDesc;
}
CRY_ASSERT(pDesc != NULL);
CCryDXGLDepthStencilView* pDSView(new CCryDXGLDepthStencilView(CCryDXGLResource::FromInterface(pResource), *pDesc, this));
if (pDSView->Initialize(m_spGLDevice))
{
CCryDXGLDepthStencilView::ToInterface(ppDepthStencilView, pDSView);
return S_OK;
}
pDSView->Release();
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC* pInputElementDescs, UINT NumElements, const void* pShaderBytecodeWithInputSignature, SIZE_T BytecodeLength, ID3D11InputLayout** ppInputLayout)
{
NCryMetal::TShaderReflection kShaderReflection;
if (!InitializeShaderReflection(&kShaderReflection, pShaderBytecodeWithInputSignature))
{
return 0;
}
_smart_ptr<NCryMetal::SInputLayout> spGLInputLayout(NCryMetal::CreateInputLayout(pInputElementDescs, NumElements, kShaderReflection));
if (spGLInputLayout == NULL)
{
return E_FAIL;
}
CCryDXGLInputLayout::ToInterface(ppInputLayout, new CCryDXGLInputLayout(spGLInputLayout, this));
return S_OK;
}
_smart_ptr<NCryMetal::SShader> CreateGLShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, NCryMetal::EShaderType eType, NCryMetal::CDevice* pDevice)
{
if (pClassLinkage != NULL)
{
DXGL_ERROR("Class linkage not supported");
return NULL;
}
_smart_ptr<NCryMetal::SShader> spGLShader(new NCryMetal::SShader());
spGLShader->m_eType = eType;
if (!NCryMetal::InitializeShader(spGLShader, pShaderBytecode, BytecodeLength, pDevice->GetMetalDevice()))
{
return NULL;
}
return spGLShader;
}
template <typename DXGLShader, typename D3DShader>
HRESULT CreateShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, D3DShader** ppShader, NCryMetal::EShaderType eType, CCryDXGLDevice* pDevice)
{
_smart_ptr<NCryMetal::SShader> spGLShader(CreateGLShader(pShaderBytecode, BytecodeLength, pClassLinkage, eType, pDevice->GetGLDevice()));
if (spGLShader == NULL)
{
return E_FAIL;
}
DXGLShader::ToInterface(ppShader, new DXGLShader(spGLShader, pDevice));
return S_OK;
}
HRESULT CCryDXGLDevice::CreateVertexShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11VertexShader** ppVertexShader)
{
return CreateShader<CCryDXGLVertexShader, ID3D11VertexShader>(pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader, NCryMetal::eST_Vertex, this);
}
HRESULT CCryDXGLDevice::CreateGeometryShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11GeometryShader** ppGeometryShader)
{
DXGL_ERROR("Geometry shaders are not supported by this GL implementation.");
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateGeometryShaderWithStreamOutput(const void* pShaderBytecode, SIZE_T BytecodeLength, const D3D11_SO_DECLARATION_ENTRY* pSODeclaration, UINT NumEntries, const UINT* pBufferStrides, UINT NumStrides, UINT RasterizedStream, ID3D11ClassLinkage* pClassLinkage, ID3D11GeometryShader** ppGeometryShader)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreatePixelShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11PixelShader** ppPixelShader)
{
return CreateShader<CCryDXGLPixelShader, ID3D11PixelShader>(pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader, NCryMetal::eST_Fragment, this);
}
HRESULT CCryDXGLDevice::CreateHullShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11HullShader** ppHullShader)
{
DXGL_ERROR("Hull shaders are not supported by this GL implementation.");
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateDomainShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11DomainShader** ppDomainShader)
{
DXGL_ERROR("Domain shaders are not supported by this GL implementation.");
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateComputeShader(const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11ComputeShader** ppComputeShader)
{
#if DXGL_SUPPORT_COMPUTE
return CreateShader<CCryDXGLComputeShader, ID3D11ComputeShader>(pShaderBytecode, BytecodeLength, pClassLinkage, ppComputeShader, NCryMetal::eST_Compute, this);
#else
DXGL_ERROR("Compute shaders are not supported by this GL implementation.");
return E_FAIL;
#endif
}
HRESULT CCryDXGLDevice::CreateClassLinkage(ID3D11ClassLinkage** ppLinkage)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateBlendState(const D3D11_BLEND_DESC* pBlendStateDesc, ID3D11BlendState** ppBlendState)
{
CCryDXGLBlendState* pState(new CCryDXGLBlendState(*pBlendStateDesc, this));
if (!pState->Initialize(this))
{
pState->Release();
return E_FAIL;
}
CCryDXGLBlendState::ToInterface(ppBlendState, pState);
return S_OK;
}
HRESULT CCryDXGLDevice::CreateDepthStencilState(const D3D11_DEPTH_STENCIL_DESC* pDepthStencilDesc, ID3D11DepthStencilState** ppDepthStencilState)
{
CCryDXGLDepthStencilState* pState(new CCryDXGLDepthStencilState(*pDepthStencilDesc, this));
if (!pState->Initialize(this))
{
pState->Release();
return E_FAIL;
}
CCryDXGLDepthStencilState::ToInterface(ppDepthStencilState, pState);
return S_OK;
}
HRESULT CCryDXGLDevice::CreateRasterizerState(const D3D11_RASTERIZER_DESC* pRasterizerDesc, ID3D11RasterizerState** ppRasterizerState)
{
CCryDXGLRasterizerState* pState(new CCryDXGLRasterizerState(*pRasterizerDesc, this));
if (!pState->Initialize(this))
{
pState->Release();
return E_FAIL;
}
CCryDXGLRasterizerState::ToInterface(ppRasterizerState, pState);
return S_OK;
}
HRESULT CCryDXGLDevice::CreateSamplerState(const D3D11_SAMPLER_DESC* pSamplerDesc, ID3D11SamplerState** ppSamplerState)
{
CCryDXGLSamplerState* pState(new CCryDXGLSamplerState(*pSamplerDesc, this));
if (!pState->Initialize(this))
{
pState->Release();
return E_FAIL;
}
CCryDXGLSamplerState::ToInterface(ppSamplerState, pState);
return S_OK;
}
HRESULT CCryDXGLDevice::CreateQuery(const D3D11_QUERY_DESC* pQueryDesc, ID3D11Query** ppQuery)
{
NCryMetal::SQueryPtr spGLQuery(NCryMetal::CreateQuery(*pQueryDesc, m_spGLDevice));
if (spGLQuery == NULL)
{
return E_FAIL;
}
CCryDXGLQuery::ToInterface(ppQuery, new CCryDXGLQuery(*pQueryDesc, spGLQuery, this));
return S_OK;
}
HRESULT CCryDXGLDevice::CreatePredicate(const D3D11_QUERY_DESC* pPredicateDesc, ID3D11Predicate** ppPredicate)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateCounter(const D3D11_COUNTER_DESC* pCounterDesc, ID3D11Counter** ppCounter)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::CreateDeferredContext(UINT ContextFlags, ID3D11DeviceContext** ppDeferredContext)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::OpenSharedResource(HANDLE hResource, REFIID ReturnedInterface, void** ppResource)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::CheckFormatSupport(DXGI_FORMAT Format, UINT* pFormatSupport)
{
NCryMetal::EGIFormat eGIFormat(NCryMetal::GetGIFormat(Format));
if (eGIFormat == NCryMetal::eGIF_NUM)
{
DXGL_ERROR("Unknown DXGI format");
return E_FAIL;
}
(*pFormatSupport) = m_spAdapter->GetGLAdapter()->m_giFormatSupport[eGIFormat];
return S_OK;
}
HRESULT CCryDXGLDevice::CheckMultisampleQualityLevels(DXGI_FORMAT Format, UINT SampleCount, UINT* pNumQualityLevels)
{
NCryMetal::EGIFormat eGIFormat(NCryMetal::GetGIFormat(Format));
if (eGIFormat != NCryMetal::eGIF_NUM && (SampleCount <= m_spAdapter->GetGLAdapter()->m_maxSamples))
{
*pNumQualityLevels = 1;
}
else
{
*pNumQualityLevels = 0;
}
DXGL_TODO("Check if there's a way to query for specific quality levels");
return S_OK;
}
void CCryDXGLDevice::CheckCounterInfo(D3D11_COUNTER_INFO* pCounterInfo)
{
DXGL_NOT_IMPLEMENTED
}
HRESULT CCryDXGLDevice::CheckCounter(const D3D11_COUNTER_DESC* pDesc, D3D11_COUNTER_TYPE* pType, UINT* pActiveCounters, LPSTR szName, UINT* pNameLength, LPSTR szUnits, UINT* pUnitsLength, LPSTR szDescription, UINT* pDescriptionLength)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
HRESULT CCryDXGLDevice::CheckFeatureSupport(D3D11_FEATURE Feature, void* pFeatureSupportData, UINT FeatureSupportDataSize)
{
switch (Feature)
{
case D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS:
{
D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS* pData(static_cast<D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS*>(pFeatureSupportData));
bool bComputeShaderSupported(m_spAdapter->GetGLAdapter()->m_features.Get(NCryMetal::eF_ComputeShader));
pData->ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x = bComputeShaderSupported ? TRUE : FALSE;
return S_OK;
}
break;
default:
DXGL_TODO("Add supported 11.1 features")
return E_FAIL;
}
}
HRESULT CCryDXGLDevice::GetPrivateData(REFGUID guid, UINT* pDataSize, void* pData)
{
return m_kPrivateDataContainer.GetPrivateData(guid, pDataSize, pData);
}
HRESULT CCryDXGLDevice::SetPrivateData(REFGUID guid, UINT DataSize, const void* pData)
{
return m_kPrivateDataContainer.SetPrivateData(guid, DataSize, pData);
}
HRESULT CCryDXGLDevice::SetPrivateDataInterface(REFGUID guid, const IUnknown* pData)
{
return m_kPrivateDataContainer.SetPrivateDataInterface(guid, pData);
}
D3D_FEATURE_LEVEL CCryDXGLDevice::GetFeatureLevel(void)
{
DXGL_NOT_IMPLEMENTED
return D3D_FEATURE_LEVEL_11_0;
}
UINT CCryDXGLDevice::GetCreationFlags(void)
{
DXGL_NOT_IMPLEMENTED
return 0;
}
HRESULT CCryDXGLDevice::GetDeviceRemovedReason(void)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
void CCryDXGLDevice::GetImmediateContext(ID3D11DeviceContext** ppImmediateContext)
{
m_spImmediateContext->AddRef();
CCryDXGLDeviceContext::ToInterface(ppImmediateContext, m_spImmediateContext);
}
HRESULT CCryDXGLDevice::SetExceptionMode(UINT RaiseFlags)
{
DXGL_NOT_IMPLEMENTED
return E_FAIL;
}
UINT CCryDXGLDevice::GetExceptionMode(void)
{
DXGL_NOT_IMPLEMENTED
return 0;
}
| 33.01978 | 323 | 0.73103 | [
"geometry",
"render",
"3d"
] |
aedc3f873175afe74cb31e2283c733e7c962b2e5 | 546 | hpp | C++ | graphics/Mesh.hpp | wendellbrito/engine | 8543eb19cdd9ed73224a111a98955f2319a1c3f2 | [
"MIT"
] | 2 | 2022-03-21T12:50:56.000Z | 2022-03-27T02:35:03.000Z | graphics/Mesh.hpp | wendellbrito/engine | 8543eb19cdd9ed73224a111a98955f2319a1c3f2 | [
"MIT"
] | null | null | null | graphics/Mesh.hpp | wendellbrito/engine | 8543eb19cdd9ed73224a111a98955f2319a1c3f2 | [
"MIT"
] | null | null | null | #ifndef MESH_HPP
#define MESH_HPP
#include "glm/mat4x4.hpp"
#include <vector>
#include <string>
class Mesh
{
private:
unsigned int vertexArray;
unsigned int vertexBuffer;
unsigned int elementBuffer;
glm::mat4 modelMatrix;
uint32_t indiceNumber;
public:
Mesh(float* vertices, uint32_t verticeNumber, int* indices, uint32_t indiceNumber);
~Mesh();
void draw();
void setModelMatrix(glm::mat4 modelMatrix);
glm::mat4 getModelMatrix();
};
#endif//MESH_HPP
| 18.827586 | 91 | 0.644689 | [
"mesh",
"vector"
] |
aeddc27519dd91655aef0f03ff4e4f339f870426 | 11,514 | cpp | C++ | backup/some old code and slides/sample/costtest.cpp | rwang0417/d2c_mujoco200 | 84609fbb14dc38dadf35193d0c7c4431e6f22913 | [
"MIT"
] | 2 | 2020-02-24T00:15:39.000Z | 2020-09-02T03:20:46.000Z | backup/some old code and slides/sample/costtest.cpp | rwang0417/d2c_mujoco200 | 84609fbb14dc38dadf35193d0c7c4431e6f22913 | [
"MIT"
] | null | null | null | backup/some old code and slides/sample/costtest.cpp | rwang0417/d2c_mujoco200 | 84609fbb14dc38dadf35193d0c7c4431e6f22913 | [
"MIT"
] | 3 | 2019-08-05T20:21:04.000Z | 2020-09-02T03:20:49.000Z | //---------------------------------//
// This file is part of MuJoCo //
// Written by Emo Todorov //
// Copyright (C) 2017 Roboti LLC //
//---------------------------------//
#include "mujoco.h"
#include "mjxmacro.h"
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <chrono>
#include <math.h>
#include <time.h>
using namespace std;
//-------------------------------- global variables -------------------------------------
// model
mjModel* m = 0;
mjData* d = 0;
mjtNum t_init = -0.2;
static mjtNum top_flag = 0;
char lastfile[1000] = "";
char error[1000];
static int trial = 0;
static int tri_num = 0;
static mjtNum cal_flag = 1;
const mjtNum t_step = 0.1;
const int32_t step_max = 1;
const int N1 = 5;
const int ctrl_num = 4;
const int32_t roll_max = step_max * ctrl_num;
const long N = step_max * ctrl_num;
const double PI = 3.141592654;
mjtNum cost[roll_max+1] = { 0 };
mjtNum u[step_max * ctrl_num] = { 0 };
mjtNum gradient[step_max * ctrl_num] = { 0 };
mjtNum delta_u[roll_max][step_max*ctrl_num] = { 0 };
mjtNum delta_j[roll_max] = { 0 };
mjtNum res[step_max * ctrl_num][step_max * ctrl_num];
mjtNum resp[5][5];
mjtNum res4[step_max * ctrl_num][step_max * ctrl_num];
mjtNum record[step_max + 2][4];
mjtNum u_init[step_max * ctrl_num];
char para_buff[20];
char glstr[10];
FILE *fp;
FILE *fop;
FILE *fop1;
mjtNum x_goal[4] = {
(mjtNum)(1.6),
(mjtNum)(0.5),
(mjtNum)(-3.14),
(mjtNum)(0),
};
/* Parameters read from file fop */
mjtNum Q;
mjtNum QT;
mjtNum ptb_coef;
mjtNum step_coef;
mjtNum step_coef_init;
mjtNum R;
// timer
double gettm(void)
{
static chrono::system_clock::time_point _start = chrono::system_clock::now();
chrono::duration<double> elapsed = chrono::system_clock::now() - _start;
return elapsed.count();
}
// help
const char helpstring[] =
"\n Usage: test modelfile option [duration]\n"
" option can contain: 'x'- xml save/load, 's'- speed\n"
" if 's' is included, the simulation runs for the specified duration in seconds\n\n"
" Example: test model.xml xs 10\n";
// deallocate and print message
int finish(const char* msg = 0, mjModel* m = 0, mjData* d = 0)
{
// deallocated everything
if( d )
mj_deleteData(d);
if( m )
mj_deleteModel(m);
mj_deactivate();
// print message
if( msg )
printf("%s\n", msg);
return 0;
}
/* Calculate Determinant of the Matrix */
mjtNum determinant(mjtNum fh[N][N], mjtNum r)
{
long z, j, i;
mjtNum m = 1, k, a[N][N], det = 1.0;
for (i = 0; i < r; i++)
{
for (j = 0; j < r; j++)
{
a[i][j] = fh[i][j];
}
}
for (z = 0; z<r - 1; z++)
for (i = z; i<r - 1; i++)
{
if (a[z][z] == 0)
{
for (j = 0; j<r; j++)
{
a[z][j] = a[z][j] + a[i + 1][j];
}
}
if (a[z][z] != 0) {
k = -a[i + 1][z] / a[z][z];
for (j = z; j<r; j++)a[i + 1][j] = k * a[z][j] + a[i + 1][j];
}
}
for (z = 0; z<r; z++)
{
det = det * (a[z][z]);
}
return (det);
}
/* Find transpose of matrix */
void transpose(mjtNum num[N][N], mjtNum fac[N][N], mjtNum r)
{
long i, j;
mjtNum b[N][N], d;
for (i = 0; i < r; i++)
{
for (j = 0; j < r; j++)
{
b[i][j] = fac[j][i];
}
}
d = determinant(num, r);
for (i = 0; i < r; i++)
{
for (j = 0; j < r; j++)
{
res[i][j] = b[i][j] / d;
}
}
}
/* Inverse */
void cofactor(mjtNum num[N][N], mjtNum f)
{
mjtNum b[N][N] = { 0 }, fac[N][N];
long p, q, m, n, i, j;
for (q = 0; q < f; q++)
{
for (p = 0; p < f; p++)
{
m = 0;
n = 0;
for (i = 0; i < f; i++)
{
for (j = 0; j < f; j++)
{
if (i != q && j != p)
{
b[m][n] = num[i][j];
if (n < (f - 2)) n++;
else {
n = 0;
m++;
}
}
}
}
fac[q][p] = pow(mjtNum(-1), q + p) * determinant(b, f - 1);
}
}
transpose(num, fac, f);
}
double gaussrand()
{
static double U, V;
static int phase = 0;
double Z;
if (phase == 0)
{
U = rand() / (RAND_MAX + 1.0);
V = rand() / (RAND_MAX + 1.0);
if (U == 0) U = 0.0001;
Z = sqrt(-2.0 * log(U)) * sin(2.0 * PI * V);
}
else
{
Z = sqrt(-2.0 * log(U)) * cos(2.0 * PI * V);
}
phase = 1 - phase;
return Z;
}
void setcontrol(mjtNum time, mjtNum* ctrl, int nu)
{
mjtNum res3[step_max * ctrl_num], avg_j;
static int index = 0;
static mjtNum sum = 0;
static mjtNum gra_max = 3;
static mjtNum last_tri = 6000;
FILE *fop2;
char *str, *str3;
{
if (time - t_init <= 0.1)
{
for (int ci = 0; ci < ctrl_num; ci++)
{
/*if ((index * ctrl_num + ci) == trial) ctrl[ci] = u[index * ctrl_num + ci] + ptb_coef;
else ctrl[ci] = u[index * ctrl_num + ci];*/
ctrl[ci] = 0;
}
}
else {
//record[index][1] = d->qpos[1] - x_goal[1];
//record[index][0] = d->qvel[0] - x_goal[0];
//if(index == step_max - 1) cost[trial] += QT * (record[index][1] * record[index][1]) + R * (ctrl[0] * ctrl[0] + ctrl[1] * ctrl[1] + ctrl[2] * ctrl[2] + ctrl[3] * ctrl[3]);
////else if(index <= 15) cost[trial] += 2 * Q * (record[index][1] * record[index][1]) + R * (ctrl[0] * ctrl[0] + ctrl[1] * ctrl[1] + ctrl[2] * ctrl[2] + ctrl[3] * ctrl[3]);
//else cost[trial] += Q * (record[index][1] * record[index][1]) + R * (ctrl[0] * ctrl[0] + ctrl[1] * ctrl[1] + ctrl[2] * ctrl[2] + ctrl[3] * ctrl[3]);
cost[0] = 100000 * d->qpos[1];
t_init = time;
index++;
if (index >= step_max)
{
str = glstr;
sprintf(str, "%5.0f", cost[0]);
fwrite(str, 5, 1, fp);
fputs(" ", fp);
index = 0;
//trial++;
//if (trial >= roll_max)
//{
// trial = 0;
// /*str = glstr;
// sprintf(str, "%5.0f", cost[roll_max]);
// fwrite(str, 5, 1, fp);
// fputs(" ", fp);*/
// for (int j = 0; j < roll_max; j++)
// {
// //delta_j[j] = cost[j] - cost[roll_max];
// cost[j] = 0;
// }
// //cost[roll_max] = 0;
//}
// // print control pos vel
// if ((fop2 = fopen("../../../data/result.txt", "wt+")) != NULL)
// {
// str3 = glstr;
// fputs("Control: ", fop2);
// for (long h = 0; h < step_max * ctrl_num; h++)
// {
// sprintf(str3, "%2.4f", u[h]);
// fwrite(str3, 6, 1, fop2);
// fputs(" ", fop2);
// }
// fputs("\n", fop2);
// fputs("Control Init: ", fop2);
// for (long d = 0; d < step_max * ctrl_num; d++)
// {
// sprintf(str3, "%2.4f", u_init[d]);
// fwrite(str3, 6, 1, fop2);
// fputs(" ", fop2);
// }
// fputs("\n", fop2);
// fputs("Height: ", fop2);
// for (int d = 0; d < step_max; d++)
// {
// sprintf(str3, "%2.4f", record[d][1]);
// fwrite(str3, 6, 1, fop2);
// fputs(" ", fop2);
// }
// fputs("\n", fop2);
//
// fputs("Q: ", fop2);
// sprintf(str3, "%2.4f", Q);
// fwrite(str3, 6, 1, fop2);
// fputs("\n", fop2);
// fputs("QT ", fop2);
// sprintf(str3, "%2.4f", QT);
// fwrite(str3, 6, 1, fop2);
// fputs("\n", fop2);
// fputs("R: ", fop2);
// sprintf(str3, "%2.4f", R);
// fwrite(str3, 6, 1, fop2);
// fputs("\n", fop2);
// fputs("ptb_coef: ", fop2);
// sprintf(str3, "%2.4f", ptb_coef);
// fwrite(str3, 6, 1, fop2);
// fputs("\nstep_coef: ", fop2);
// sprintf(str3, "%2.4f", step_coef);
// fwrite(str3, 6, 1, fop2);
// fclose(fop2);
// }
// /*for (int h = 0; h < step_max * ctrl_num; h++)
// {
// if (step_coef * delta_j[h] > 0.1) u[h] -= 0.1;
// else if (step_coef * delta_j[h] < -0.1) u[h] -= -0.1;
// else u[h] -= step_coef * delta_j[h];
// }*/
// tri_num++;
// step_coef = step_coef_init;// *pow(0.991, tri_num);
// // ptb_coef = 0.13 * pow(1, tri_num);
// //if ((step_coef < 0.0004) && (step_coef > 0) || tri_num > 1500) step_coef = step_coef_init/20;
// //if (tri_num > 400) step_coef = step_coef_init/20;
// /*if (tri_num > 1400) step_coef = step_coef_init/100;*/
//}
// reset
t_init = time;
mju_zero(d->qpos, m->nq);
mju_zero(d->qvel, m->nv);
mju_zero(d->act, m->na);
//mj_forward(m, d);
}
}
}
}
// main function
int main(int argc, const char** argv)
{
// print help if arguments are missing
if( argc<3 )
return finish(helpstring);
// activate MuJoCo Pro license (this must be *your* activation key)
mj_activate("mjkey.txt");
// get filename, determine file type
std::string filename(argv[1]);
bool binary = (filename.find(".mjb")!=std::string::npos);
// load model
char error[1000] = "Could not load binary model";
if( binary )
m = mj_loadModel(argv[1], 0);
else
m = mj_loadXML(argv[1], 0, error, 1000);
if( !m )
return finish(error);
// make data
d = mj_makeData(m);
if( !d )
return finish("Could not allocate mjData", m);
// get option
std::string option(argv[2]);
// speed test
if( option.find_first_of('s')!=std::string::npos )
{
// require duration
if( argc<4 )
return finish("Duration argument is required for speed test", m, d);
// read duration
double duration = 0;
if( sscanf(argv[3], "%lf", &duration)!=1 || duration<=0 )
return finish("Invalid duration argument", m, d);
srand((unsigned)time(NULL));
if ((fp = fopen("../../../data/cost.txt", "wt+")) == NULL) {
return 0;
}
//if ((fop = fopen("../../../data/parameters.txt", "r")) != NULL) {
// while (!feof(fop))
// {
// fscanf(fop, "%s", para_buff);
// if (para_buff[1] == '_')
// {
// fscanf(fop, "%s", para_buff);
// Q = atof(para_buff);
// }
// if (para_buff[0] == 'R')
// {
// fscanf(fop, "%s", para_buff);
// R = atof(para_buff);
// }
// if (para_buff[1] == 'T')
// {
// fscanf(fop, "%s", para_buff);
// QT = atof(para_buff);
// }
// if (para_buff[0] == 'p')
// {
// fscanf(fop, "%s", para_buff);
// ptb_coef = atof(para_buff);
// }
// if (para_buff[0] == 's')
// {
// fscanf(fop, "%s", para_buff);
// step_coef_init = atof(para_buff);
// }
// }
// fclose(fop);
//}
//for (int b = 0; b < step_max; b++)
//{
// //u[b][0] = 1 * mju_sin(3.0*b / step_max * PI);
// //u_init[b] = 0 * gaussrand();
// //u[b][0] = u_init[b];
//}
// time simulation
int steps = 0, contacts = 0, constraints = 0;
double printfraction = 0.1;
printf("\nSimulation ");
double start = gettm();
t_init = d->time;
while( d->time<duration )
{
setcontrol(d->time, d->ctrl, m->nu);
// advance simulation
mj_step(m, d);
// accumulate statistics
steps++;
contacts += d->ncon;
constraints += d->nefc;
// print '.' every 10% of duration
if( d->time >= duration*printfraction )
{
printf(".");
printfraction += 0.1;
}
}
double end = gettm();
// print results
printf("\n Simulation time : %.2f s\n", end-start);
printf(" Realtime factor : %.2f x\n", duration/mjMAX(1E-10,(end-start)));
printf(" Time per step : %.3f ms\n", 1000.0*(end-start)/mjMAX(1,steps));
printf(" Contacts per step : %d\n", contacts/mjMAX(1,steps));
printf(" Constraints per step : %d\n", constraints/mjMAX(1,steps));
printf(" Degrees of freedom : %d\n\n", m->nv);
}
// finalize
return finish();
}
| 24.655246 | 175 | 0.496265 | [
"model"
] |
aede64aabe08d9d06a03ae69bf8556670feb9902 | 2,466 | cpp | C++ | SyntacticSemanticParsing/src/semantic_parser/nodes-argmax-proj.cpp | Noahs-ARK/SPIGOT | f1e74019cb568420aacd7e30e21064756c725ca1 | [
"MIT"
] | 21 | 2018-05-19T09:58:49.000Z | 2022-02-27T13:07:51.000Z | SDPClassification/src/semantic_parser/nodes-argmax-proj.cpp | Noahs-ARK/SPIGOT | f1e74019cb568420aacd7e30e21064756c725ca1 | [
"MIT"
] | 1 | 2019-05-02T03:36:48.000Z | 2019-05-02T03:36:48.000Z | SyntacticSemanticParsing/src/semantic_parser/nodes-argmax-proj.cpp | Noahs-ARK/SPIGOT | f1e74019cb568420aacd7e30e21064756c725ca1 | [
"MIT"
] | 3 | 2019-04-16T20:46:40.000Z | 2019-08-26T09:57:14.000Z | //
// Created by hpeng on 1/12/18.
//
#include "nodes-argmax-proj.h"
using namespace std;
namespace dynet {
// ************* ArgmaxProj *************
#ifndef __CUDACC__
string ArgmaxProj::as_string(const vector<string> &arg_names) const {
ostringstream s;
s << "ArgmaxProj: (" << arg_names[0] << ")";
return s.str();
}
Dim ArgmaxProj::dim_forward(const vector<Dim> &xs) const {
DYNET_ARG_CHECK(xs.size() == 2,
"Failed input count check in ArgmaxProj");
DYNET_ARG_CHECK(xs[0].nd <= 2,
"Bad input dimensions in ArgmaxProj, must be 2 or fewer: "
<< xs);
return xs[0];
}
int
ArgmaxProj::autobatch_sig(const ComputationGraph &cg, SigMap &sm) const {
DYNET_ASSERT(false, "not implemented");
}
std::vector<int>
ArgmaxProj::autobatch_concat(const ComputationGraph &cg) const {
return vector<int>(1, 1);
}
#endif
// x[0]: score
// x[1]: pred
// x[2]: 1 - pred
template<class MyDevice>
void ArgmaxProj::forward_dev_impl(const MyDevice &dev,
const vector<const Tensor *> &xs,
Tensor &fx) const {
// this is a fake foward prop.
// just copying the results solved outside into the graph
// this avoids potential mess caused by calling ArgmaxProj inside dynet cg
DYNET_ASSERT(xs.size() == 3,
"Failed dimension check in ArgmaxProj::forward");
if (xs[0]->d.bd == 1) {
tvec(fx).device(*dev.edevice) = tvec(*xs[1]);
} else {
DYNET_ASSERT(false, "Mini-batch support not implemented");
}
}
template<class MyDevice>
void ArgmaxProj::backward_dev_impl(const MyDevice &dev,
const vector<const Tensor *> &xs,
const Tensor &fx,
const Tensor &dEdf,
unsigned i,
Tensor &dEdxi) const {
DYNET_ASSERT(i == 0, "Failed dimension check in ArgmaxProj::backward");
DYNET_ASSERT(xs[1]->d.bd == xs[0]->d.bd,
"Failed dimension check in ArgmaxProj::backward");
DYNET_ASSERT(xs[0]->d.bd == 1,
"Failed dimension check in ArgmaxProj::backward");
if (dEdxi.d.bd == 1 && (dEdf.d.bd == xs[1]->d.bd)) {
ProjectSimplex(slen_, fx.d.size(), fx.v, dEdf.v, dEdxi.v);
} else {
DYNET_ASSERT(false, "Mini-batch support not implemented");
}
}
DYNET_NODE_INST_DEV_IMPL(ArgmaxProj)
}
| 30.444444 | 76 | 0.579481 | [
"vector"
] |
aeeed85dc071b5f93474c9f5e6d2135309a2f039 | 4,715 | cxx | C++ | Loadable/ParticlesDisplay/qSlicerParticlesDisplayModule.cxx | aiycko/SlicerCIP | 5d3e9f1c72c96be85d4ca8244315a1cfa7e2da1d | [
"BSD-3-Clause"
] | null | null | null | Loadable/ParticlesDisplay/qSlicerParticlesDisplayModule.cxx | aiycko/SlicerCIP | 5d3e9f1c72c96be85d4ca8244315a1cfa7e2da1d | [
"BSD-3-Clause"
] | null | null | null | Loadable/ParticlesDisplay/qSlicerParticlesDisplayModule.cxx | aiycko/SlicerCIP | 5d3e9f1c72c96be85d4ca8244315a1cfa7e2da1d | [
"BSD-3-Clause"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
==============================================================================*/
// Qt includes
#include <QDebug>
#include <QtPlugin>
// Slicer includes
#include <qSlicerCoreApplication.h>
#include <qSlicerModuleManager.h>
#include <qSlicerCoreIOManager.h>
#include <qSlicerNodeWriter.h>
// ParticlesDisplay Logic includes
#include <vtkSlicerCLIModuleLogic.h>
#include <vtkSlicerParticlesDisplayLogic.h>
#include <vtkSlicerVolumesLogic.h>
// ParticlesDisplay includes
#include "qSlicerParticlesDisplayModule.h"
#include "qSlicerParticlesDisplayModuleWidget.h"
#include "qSlicerParticlesReader.h"
//-----------------------------------------------------------------------------
Q_EXPORT_PLUGIN2(qSlicerParticlesDisplayModule, qSlicerParticlesDisplayModule);
//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_ExtensionTemplate
class qSlicerParticlesDisplayModulePrivate
{
public:
qSlicerParticlesDisplayModulePrivate();
};
//-----------------------------------------------------------------------------
// qSlicerParticlesDisplayModulePrivate methods
//-----------------------------------------------------------------------------
qSlicerParticlesDisplayModulePrivate
::qSlicerParticlesDisplayModulePrivate()
{
}
//-----------------------------------------------------------------------------
// qSlicerParticlesDisplayModule methods
//-----------------------------------------------------------------------------
qSlicerParticlesDisplayModule
::qSlicerParticlesDisplayModule(QObject* _parent)
: Superclass(_parent)
, d_ptr(new qSlicerParticlesDisplayModulePrivate)
{
}
//-----------------------------------------------------------------------------
qSlicerParticlesDisplayModule::~qSlicerParticlesDisplayModule()
{
}
//-----------------------------------------------------------------------------
QString qSlicerParticlesDisplayModule::helpText()const
{
return "This is a loadable module to display selected region and type";
}
//-----------------------------------------------------------------------------
QString qSlicerParticlesDisplayModule::acknowledgementText()const
{
return "This module was developed by Pietro Nardelli";
}
//-----------------------------------------------------------------------------
QStringList qSlicerParticlesDisplayModule::contributors()const
{
QStringList moduleContributors;
moduleContributors << QString("Pietro Nardelli (UCC)");
return moduleContributors;
}
//-----------------------------------------------------------------------------
QIcon qSlicerParticlesDisplayModule::icon()const
{
return QIcon(":/Icons/ParticlesDisplay.png");
}
//-----------------------------------------------------------------------------
QStringList qSlicerParticlesDisplayModule::categories() const
{
return QStringList() << "Converters";
}
//-----------------------------------------------------------------------------
QStringList qSlicerParticlesDisplayModule::dependencies() const
{
return QStringList() << "RegionType" << "TractographyDisplay";
}
//-----------------------------------------------------------------------------
void qSlicerParticlesDisplayModule::setup()
{
this->Superclass::setup();
vtkSlicerParticlesDisplayLogic* particlesDisplayLogic =
vtkSlicerParticlesDisplayLogic::SafeDownCast(this->logic());
qSlicerCoreIOManager* coreIOManager =
qSlicerCoreApplication::application()->coreIOManager();
coreIOManager->registerIO(
new qSlicerParticlesReader(particlesDisplayLogic, this));
coreIOManager->registerIO(new qSlicerNodeWriter(
"Particles", QString("ParticlesFile"),
QStringList() << "vtkMRMLParticlesNode", true, this));
}
//-----------------------------------------------------------------------------
qSlicerAbstractModuleRepresentation * qSlicerParticlesDisplayModule
::createWidgetRepresentation()
{
return new qSlicerParticlesDisplayModuleWidget;
}
//-----------------------------------------------------------------------------
vtkMRMLAbstractLogic* qSlicerParticlesDisplayModule::createLogic()
{
return vtkSlicerParticlesDisplayLogic::New();
}
| 33.439716 | 80 | 0.559279 | [
"3d"
] |
aef70b55eecadd0d5101e25ac575fc3749a1f815 | 3,930 | cpp | C++ | source/examples/gpu-particles/ComputeShaderParticles.cpp | kateyy/globjects | 4c5fc073063ca52ea32ce0adb57009a3c52f72a8 | [
"MIT"
] | null | null | null | source/examples/gpu-particles/ComputeShaderParticles.cpp | kateyy/globjects | 4c5fc073063ca52ea32ce0adb57009a3c52f72a8 | [
"MIT"
] | null | null | null | source/examples/gpu-particles/ComputeShaderParticles.cpp | kateyy/globjects | 4c5fc073063ca52ea32ce0adb57009a3c52f72a8 | [
"MIT"
] | null | null | null |
#include "ComputeShaderParticles.h"
#include <glbinding/gl/gl.h>
#include <globjects/base/AbstractStringSource.h>
#include <globjects/globjects.h>
#include <globjects/Buffer.h>
#include <globjects/Program.h>
#include <globjects/VertexArray.h>
#include <globjects/Shader.h>
#include <globjects/Texture.h>
#include <globjects/VertexAttributeBinding.h>
#include <globjects/base/File.h>
#include <common/ScreenAlignedQuad.h>
#include <common/Camera.h>
#include <globjects/base/StringTemplate.h>
using namespace gl;
using namespace glm;
using namespace globjects;
ComputeShaderParticles::ComputeShaderParticles(
const std::vector<vec4> & positions
, const std::vector<vec4> & velocities
, const Texture & forces
, const Camera & camera)
: AbstractParticleTechnique(positions, velocities, forces, camera)
{
}
ComputeShaderParticles::~ComputeShaderParticles()
{
}
void ComputeShaderParticles::initialize()
{
static const int max_invocations = getInteger(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS);
static const ivec3 max_count = ivec3(
getInteger(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0)
, getInteger(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1)
, getInteger(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2));
const int groups = static_cast<int>(ceil(static_cast<float>(m_numParticles) / static_cast<float>(max_invocations)));
ivec3 workGroupSize;
workGroupSize.x = max(groups % max_count.x, 1);
workGroupSize.y = max(max(groups - workGroupSize.x * max_count.x, 1) % max_count.y, 1);
workGroupSize.z = max(max((groups - workGroupSize.x * max_count.x) - workGroupSize.y * max_count.y, 1) % max_count.z, 1);
m_workGroupSize = workGroupSize;
assert(m_workGroupSize.x * m_workGroupSize.y * m_workGroupSize.z * max_invocations >= m_numParticles);
assert(m_workGroupSize.x * m_workGroupSize.y * m_workGroupSize.z * max_invocations < m_numParticles + max_invocations);
m_computeProgram = new Program();
StringTemplate * stringTemplate = new StringTemplate(
new File("data/gpu-particles/particle.comp"));
stringTemplate->replace("MAX_INVOCATION", max_invocations);
stringTemplate->update();
m_computeProgram->attach(new Shader(GL_COMPUTE_SHADER, stringTemplate));
m_positionsSSBO = new Buffer();
m_velocitiesSSBO = new Buffer();
reset();
m_vao = new VertexArray();
m_vao->bind();
auto positionsBinding = m_vao->binding(0);
positionsBinding->setAttribute(0);
positionsBinding->setBuffer(m_positionsSSBO, 0, sizeof(vec4));
positionsBinding->setFormat(4, GL_FLOAT, GL_FALSE, 0);
m_vao->enable(0);
auto velocitiesBinding = m_vao->binding(1);
velocitiesBinding->setAttribute(1);
velocitiesBinding->setBuffer(m_velocitiesSSBO, 0, sizeof(vec4));
velocitiesBinding->setFormat(4, GL_FLOAT, GL_FALSE, 0);
m_vao->enable(1);
m_vao->unbind();
AbstractParticleTechnique::initialize("data/gpu-particles/points.vert");
}
void ComputeShaderParticles::reset()
{
m_positionsSSBO->setData(m_positions, GL_STATIC_DRAW);
m_velocitiesSSBO->setData(m_velocities, GL_STATIC_DRAW);
AbstractParticleTechnique::reset();
}
void ComputeShaderParticles::step(const float elapsed)
{
m_positionsSSBO->bindBase(GL_SHADER_STORAGE_BUFFER, 0);
m_velocitiesSSBO->bindBase(GL_SHADER_STORAGE_BUFFER, 1);
m_forces.bind();
m_computeProgram->setUniform("forces", 0);
m_computeProgram->setUniform("elapsed", elapsed);
m_computeProgram->use();
m_computeProgram->dispatchCompute(m_workGroupSize);
m_computeProgram->release();
m_forces.unbind();
m_positionsSSBO->unbind(GL_SHADER_STORAGE_BUFFER, 0);
m_velocitiesSSBO->unbind(GL_SHADER_STORAGE_BUFFER, 1);
}
void ComputeShaderParticles::draw_impl()
{
m_drawProgram->use();
m_vao->bind();
m_vao->drawArrays(GL_POINTS, 0, m_numParticles);
m_vao->unbind();
m_drawProgram->release();
}
| 29.328358 | 125 | 0.736387 | [
"vector"
] |
aefe48bd7157edf000795a309f75eb5b76bd0ddc | 12,166 | cpp | C++ | dialog/dialogflight.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | 5 | 2018-01-08T22:20:07.000Z | 2021-06-19T17:42:29.000Z | dialog/dialogflight.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | null | null | null | dialog/dialogflight.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | 2 | 2017-08-07T23:07:42.000Z | 2021-05-09T13:02:39.000Z | #include "dialogflight.h"
#include "ui_dialogflight.h"
DialogFlight::DialogFlight(ATCSimulation *sim, ATCAirspace *airspace, ATC::SimCreationMode m, QWidget *parent) :
simulation(sim),
airspace(airspace),
mode(m),
ATCDialog(parent, "Simulation Creator", 600, 650),
uiInner(new Ui::DialogFlight)
{
uiInner->setupUi(this);
windowSetup();
dialogFlightSetup();
}
DialogFlight::~DialogFlight()
{
if(model != nullptr) delete model;
if(procedureDelegate != nullptr) delete procedureDelegate;
delete uiInner;
}
ATCSimulation *DialogFlight::getSimulation()
{
return simulation;
}
void DialogFlight::slotUpdateFlightList(ATCFlight *flight)
{
if(rowToEdit == -1)
{
appendRow(flight, model);
}
else
{
modifyRow(flight, rowToEdit, model);
rowToEdit = -1;
}
slotAdjustUI();
uiInner->tableViewFlights->sortByColumn(0, Qt::AscendingOrder);
}
void DialogFlight::on_buttonCreateFlight_clicked()
{
emit signalConstructDialogFlightCreator();
}
void DialogFlight::on_buttonReady_clicked()
{
if(mode == ATC::New)
{
emit signalSimulation(simulation);
emit signalSetFlagSimulationValid(true);
}
emit signalActiveScenarioPath("From simulation creator, not saved yet");
emit closed();
close();
}
void DialogFlight::on_buttonCancel_clicked()
{
emit closed();
close();
}
void DialogFlight::dialogFlightSetup()
{
model = new QStandardItemModel(this);
model->setColumnCount(12);
QStringList labelList;
labelList << "T+" << "CS" << "TYPE" << "W" << "ADEP" << "R" << "SID" << "ADES" << "R" << "STAR" << "AFL" << "TAS";
model->setHorizontalHeaderLabels(labelList);
uiInner->tableViewFlights->setModel(model);
uiInner->tableViewFlights->setGridStyle(Qt::NoPen);
uiInner->tableViewFlights->setFocusPolicy(Qt::NoFocus);
uiInner->tableViewFlights->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
uiInner->tableViewFlights->horizontalHeader()->setHighlightSections(false);
uiInner->tableViewFlights->verticalHeader()->setHidden(true);
uiInner->tableViewFlights->setColumnWidth(0, 60); //Start time
uiInner->tableViewFlights->setColumnWidth(1, 80); //Callsign
uiInner->tableViewFlights->setColumnWidth(2, 40); //Type
uiInner->tableViewFlights->setColumnWidth(3, 30); //Weight category
uiInner->tableViewFlights->setColumnWidth(4, 40); //ADEP
uiInner->tableViewFlights->setColumnWidth(5, 33); //DEP RWY
uiInner->tableViewFlights->setColumnWidth(6, 70); //SID ID
uiInner->tableViewFlights->setColumnWidth(7, 40); //ADES
uiInner->tableViewFlights->setColumnWidth(8, 33); //ARR RWY
uiInner->tableViewFlights->setColumnWidth(9, 70); //STAR ID
uiInner->tableViewFlights->setColumnWidth(10, 40); //AFL
uiInner->tableViewFlights->setColumnWidth(11, 40); //TAS
uiInner->tableViewFlights->setSelectionBehavior(QAbstractItemView::SelectRows);
procedureDelegate = new ATCComboDelegate(airspace, simulation, simulation->getActiveRunways(), DelegateLocation::DialogFlight, uiInner->tableViewFlights);
uiInner->tableViewFlights->setItemDelegate(procedureDelegate);
uiInner->tableViewFlights->setEditTriggers(QAbstractItemView::NoEditTriggers);
connect(uiInner->tableViewFlights, SIGNAL(clicked(QModelIndex)), this, SLOT(slotEdit(QModelIndex)));
if(mode == ATC::Edit)
{
for(int i = 0; i < simulation->getFlightsVectorSize(); i++)
{
appendRow(simulation->getFlight(i), model);
}
}
uiInner->tableViewFlights->sortByColumn(0, Qt::AscendingOrder);
slotAdjustUI();
connect(uiInner->tableViewFlights->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(slotAdjustUI(QItemSelection,QItemSelection)));
}
void DialogFlight::appendRow(ATCFlight *flight, QStandardItemModel *model)
{
QList<QStandardItem*> row;
QStandardItem *startTime = new QStandardItem(flight->getSimStartTime().toString("HH:mm:ss"));
startTime->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
startTime->setTextAlignment(Qt::AlignCenter);
row.append(startTime);
QStandardItem *callsign = new QStandardItem(flight->getFlightPlan()->getCompany()->getCode() + flight->getFlightPlan()->getFlightNumber());
callsign->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
callsign->setTextAlignment(Qt::AlignCenter);
row.append(callsign);
QStandardItem *type = new QStandardItem(flight->getFlightPlan()->getType()->getAcType().ICAOcode);
type->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
type->setTextAlignment(Qt::AlignCenter);
row.append(type);
QStandardItem *wtc;
ATC::WakeCategory wake = flight->getFlightPlan()->getType()->getAcType().wake;
switch(wake)
{
case ATC::L:
wtc = new QStandardItem("L");
break;
case ATC::M:
wtc = new QStandardItem("M");
break;
case ATC::H:
wtc = new QStandardItem("H");
break;
case ATC::J:
wtc = new QStandardItem("J");
break;
default:
wtc = new QStandardItem();
break;
}
wtc->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
wtc->setTextAlignment(Qt::AlignCenter);
row.append(wtc);
QStandardItem *adep = new QStandardItem(flight->getFlightPlan()->getRoute().getDeparture());
adep->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
adep->setTextAlignment(Qt::AlignCenter);
row.append(adep);
QStandardItem *depRwy = new QStandardItem(flight->getRunwayDeparture());
depRwy->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
depRwy->setTextAlignment(Qt::AlignCenter);
row.append(depRwy);
QStandardItem *sid = new QStandardItem(flight->getSID());
sid->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
sid->setTextAlignment(Qt::AlignCenter);
row.append(sid);
QStandardItem *ades = new QStandardItem(flight->getFlightPlan()->getRoute().getDestination());
ades->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
ades->setTextAlignment(Qt::AlignCenter);
row.append(ades);
QStandardItem *desRwy = new QStandardItem(flight->getRunwayDestination());
desRwy->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
desRwy->setTextAlignment(Qt::AlignCenter);
row.append(desRwy);
QStandardItem *star = new QStandardItem(flight->getSTAR());
star->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
star->setTextAlignment(Qt::AlignCenter);
row.append(star);
QStandardItem *afl;
double height = ATCMath::m2ft(flight->getState().h) / 100;
if(height < 10)
{
afl = new QStandardItem("00" + QString::number(height).left(3));
}
else if(height < 100)
{
afl = new QStandardItem("0" + QString::number(height).left(3));
}
else
{
afl = new QStandardItem(QString::number(height).left(3));
}
afl->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
afl->setTextAlignment(Qt::AlignCenter);
row.append(afl);
QStandardItem *tas = new QStandardItem(QString::number(qRound(ATCMath::mps2kt(flight->getState().v))));
tas->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
tas->setTextAlignment(Qt::AlignCenter);
row.append(tas);
model->appendRow(row);
for(int i = 0; i < model->rowCount(); i++)
{
uiInner->tableViewFlights->setRowHeight(i, 20);
}
}
void DialogFlight::modifyRow(ATCFlight *flight, int row, QStandardItemModel *model)
{
model->item(row, 0)->setText(flight->getSimStartTime().toString("HH:mm:ss"));
model->item(row, 1)->setText(flight->getFlightPlan()->getCompany()->getCode() + flight->getFlightPlan()->getFlightNumber());
model->item(row, 2)->setText(flight->getFlightPlan()->getType()->getAcType().ICAOcode);
switch(flight->getFlightPlan()->getType()->getAcType().wake)
{
case ATC::L:
model->item(row, 3)->setText("L");
break;
case ATC::M:
model->item(row, 3)->setText("M");
break;
case ATC::H:
model->item(row, 3)->setText("H");
break;
case ATC::J:
model->item(row, 3)->setText("J");
break;
}
model->item(row, 4)->setText(flight->getFlightPlan()->getRoute().getDeparture());
model->item(row, 5)->setText(flight->getRunwayDeparture());
model->item(row, 6)->setText(flight->getSID());
model->item(row, 7)->setText(flight->getFlightPlan()->getRoute().getDestination());
model->item(row, 8)->setText(flight->getRunwayDestination());
model->item(row, 9)->setText(flight->getSTAR());
double height = ATCMath::m2ft(flight->getState().h) / 100;
if(height < 10)
{
model->item(row, 10)->setText("00" + QString::number(height).left(3));
}
else if(height < 100)
{
model->item(row, 10)->setText("0" + QString::number(height).left(3));
}
else
{
model->item(row, 10)->setText(QString::number(height).left(3));
}
model->item(row, 11)->setText(QString::number(ATCMath::mps2kt(flight->getState().v)));
}
void DialogFlight::on_buttonEditFlight_clicked()
{
QModelIndexList selectionList = uiInner->tableViewFlights->selectionModel()->selectedRows();
if(selectionList.size() > 0)
{
emit signalConstructDialogFlightCreator(simulation->getFlight(model->index(selectionList.at(0).row(), 1).data().toString()));
rowToEdit = selectionList.at(0).row();
}
}
void DialogFlight::on_buttonDeleteFlight_clicked()
{
QModelIndexList selectionList = uiInner->tableViewFlights->selectionModel()->selectedRows();
for(int i = selectionList.size() - 1; i >= 0; i--)
{
QString callsign = model->index(selectionList.at(i).row(), 1).data().toString();
simulation->removeFlight(callsign);
model->removeRow(selectionList.at(i).row());
}
slotAdjustUI();
emit signalUpdateFlightList();
}
void DialogFlight::on_buttonDeleteAll_clicked()
{
QVector<ATCFlight*> flights = simulation->getFlightsVector();
for(int i = 0; i < flights.size(); i++)
{
delete flights.at(i);
}
simulation->clearFlights();
model->removeRows(0, model->rowCount());
slotAdjustUI();
emit signalUpdateFlightList();
}
void DialogFlight::on_buttonActiveRunways_clicked()
{
emit signalConstructDialogActiveRunways(mode);
}
void DialogFlight::slotAdjustUI()
{
QItemSelection selection = uiInner->tableViewFlights->selectionModel()->selection();
if(model->rowCount() == 0)
{
uiInner->buttonEditFlight->setEnabled(false);
uiInner->buttonDeleteFlight->setEnabled(false);
uiInner->buttonDeleteAll->setEnabled(false);
uiInner->buttonReady->setEnabled(false);
}
else
{
if(selection.isEmpty())
{
uiInner->buttonEditFlight->setEnabled(false);
uiInner->buttonDeleteFlight->setEnabled(false);
}
else
{
if(selection.size() == 1) uiInner->buttonEditFlight->setEnabled(true);
uiInner->buttonDeleteFlight->setEnabled(true);
}
uiInner->buttonReady->setEnabled(true);
uiInner->buttonDeleteAll->setEnabled(true);
}
}
void DialogFlight::slotAdjustUI(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(selected)
Q_UNUSED(deselected)
slotAdjustUI();
}
void DialogFlight::slotEdit(QModelIndex index)
{
if((index.column() == 5) ||
(index.column() == 6) ||
(index.column() == 8) ||
(index.column() == 9))
{
uiInner->tableViewFlights->edit(index);
}
}
void DialogFlight::on_tableViewFlights_clicked(const QModelIndex &index)
{
if(index.column() == 2)
{
ATCFlight *flight = simulation->getFlight(model->index(index.row(), 1).data().toString());
flight->slotDisplayRoute();
}
}
| 31.35567 | 171 | 0.660365 | [
"model"
] |
4e02da48c526e4cd081f7a740dabbbd3aee80073 | 2,262 | hpp | C++ | include/GlobalNamespace/StandardLevelLoader.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/StandardLevelLoader.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/StandardLevelLoader.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: StandardLevelInfoSaveData
class StandardLevelInfoSaveData;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: StandardLevelLoader
class StandardLevelLoader;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::StandardLevelLoader);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::StandardLevelLoader*, "", "StandardLevelLoader");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: StandardLevelLoader
// [TokenAttribute] Offset: FFFFFFFF
class StandardLevelLoader : public ::Il2CppObject {
public:
// static public StandardLevelInfoSaveData LoadStandardLevelSaveData(System.String levelInfoFilenamePath)
// Offset: 0x13351AC
static ::GlobalNamespace::StandardLevelInfoSaveData* LoadStandardLevelSaveData(::StringW levelInfoFilenamePath);
}; // StandardLevelLoader
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::StandardLevelLoader::LoadStandardLevelSaveData
// Il2CppName: LoadStandardLevelSaveData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::StandardLevelInfoSaveData* (*)(::StringW)>(&GlobalNamespace::StandardLevelLoader::LoadStandardLevelSaveData)> {
static const MethodInfo* get() {
static auto* levelInfoFilenamePath = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardLevelLoader*), "LoadStandardLevelSaveData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{levelInfoFilenamePath});
}
};
| 46.163265 | 202 | 0.748011 | [
"vector"
] |
4e0991f3ffc1834adbeea17db7340de1be2bc96a | 4,313 | cpp | C++ | src/Driver.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | 1 | 2016-09-28T02:14:30.000Z | 2016-09-28T02:14:30.000Z | src/Driver.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | null | null | null | src/Driver.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include "Driver.h"
#include "Utils.h"
using namespace std;
using namespace llvm;
constexpr int BUFSIZE = 4096 * 1024;
char buf[BUFSIZE];
Driver::Driver(string s, LLVMCodeGen *codegen)
: _file_name(s), _codegen(codegen)
{
FILE *fp = popen(("/usr/bin/expand " + s).c_str(),"r");
fread(buf, sizeof(char), BUFSIZE, fp);
_in_stream << buf;
initializeLexer();
initializeParser();
}
void Driver::initializeLexer()
{
_lexer = make_shared<yy::Lexer>(&_in_stream);
}
void Driver::initializeParser()
{
// Pass reference to current object to enable the parser to access
// source and report errors.
_parser = make_shared<yy::Parser>(*this);
}
void Driver::parse()
{
/// \todo Add error handling.
_parser->parse();
}
void Driver::codegen(string output_file)
{
/// \todo CodeGen to different target according to parameters.
_codegen->codegen(*this, output_file);
}
void Driver::error(string err, ErrorLevel level) const
{
string err_color;
string err_type;
switch (level) {
case Error:
err_color = "\033[31;1m";
err_type = "Error";
break;
case Warning:
err_color = "\033[33;1m";
err_type = "Warning";
break;
case Info:
err_color = "\033[30;1m";
err_type = "Info";
break;
}
stringstream err_text;
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
unsigned int w1 = 16, w2 = w.ws_col - w1 - 3;
err_text << fit_text(file_name, w1) << " ! "
<< fit_text(err, w2, true);
cerr << err_text.str() << endl;
}
void Driver::error(string err, const yy::location &loc,
ErrorLevel level) const
{
string err_color;
string err_type;
switch (level) {
case Error:
err_color = "\033[31;1m";
err_type = "Error";
break;
case Warning:
err_color = "\033[33;1m";
err_type = "Warning";
break;
case Info:
err_color = "\033[30;1m";
err_type = "Info";
break;
}
// store current line text
string line;
// record current position in stream
auto cur = _in_stream.tellg();
_in_stream.seekg(_lexer->markers[loc.end.line - 1]);
getline(_in_stream, line);
// recover stream
_in_stream.seekg(cur);
stringstream err_text;
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
unsigned int w1 = 16, w2 = w.ws_col - w1 - 3;
int beg_line = loc.begin.line, beg_col = loc.begin.column;
int end_line = loc.end.line, end_col = loc.end.column;
if (end_col > 0)
--end_col;
string indicator;
if (beg_line != end_line || beg_col >= end_col)
indicator = string(end_col, ' ') + "^";
else
indicator = string(beg_col, ' ') + "^" +
string(end_col - beg_col, '~');
err_text << fit_text(file_name, w1) << " ! "
<< fit_text(err, w2, true) << "\n"
<< fit_text(to_string(end_line) + ":" +
to_string(end_col), w1)
<< " | " << fit_text(line, w2, true) << "\n"
<< err_color << fit_text(err_type, w1)
<< "\033[0m !\033[32;1m"
<< fit_text(indicator, w2 + 1, true) << "\033[0m";
cerr << err_text.str() << endl;
}
void Driver::warning(string err) const
{
error(err, Warning);
}
void Driver::warning(string err, const yy::location &loc) const
{
error(err, loc, Warning);
}
void Driver::info(string err) const
{
error(err, Info);
}
void Driver::info(string err, const yy::location &loc) const
{
error(err, loc, Info);
}
string Driver::fit_text(string text, size_t width, bool left) const
{
auto l = text.length();
if (width > l) {
if (left)
return text + string(width - l, ' ');
else
return string(width - l, ' ') + text;
} else {
if (left) {
string rv(text, 0, width);
if (width > 3)
rv[width - 1] = rv[width - 2] = rv[width - 3] = '.';
return rv;
} else {
string rv(text, l - width, width);
if (width > 2)
rv[0] = rv[1] = '.';
return rv;
}
}
}
| 23.313514 | 70 | 0.558544 | [
"object"
] |
4e0f77ce06ca71372d43fdd51fef4e3f8f567e5b | 38,538 | cpp | C++ | services/Car/vehicle_network_service/VehicleNetworkService.cpp | Keneral/apackages | af6a7ffde2e52d8d4e073b4030244551246248ad | [
"Unlicense"
] | null | null | null | services/Car/vehicle_network_service/VehicleNetworkService.cpp | Keneral/apackages | af6a7ffde2e52d8d4e073b4030244551246248ad | [
"Unlicense"
] | null | null | null | services/Car/vehicle_network_service/VehicleNetworkService.cpp | Keneral/apackages | af6a7ffde2e52d8d4e073b4030244551246248ad | [
"Unlicense"
] | null | null | null | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.
*/
#define LOG_TAG "VehicleNetwork"
#include <binder/PermissionCache.h>
#include <utils/Errors.h>
#include <utils/SystemClock.h>
#include <private/android_filesystem_config.h>
#include <vehicle-internal.h>
#include "VehicleHalPropertyUtil.h"
#include "VehicleNetworkService.h"
//#define DBG_EVENT
//#define DBG_VERBOSE
#ifdef DBG_EVENT
#define EVENT_LOG(x...) ALOGD(x)
#else
#define EVENT_LOG(x...)
#endif
#ifdef DBG_VERBOSE
#define LOG_VERBOSE(x...) ALOGD(x)
#else
#define LOG_VERBOSE(x...)
#endif
namespace android {
VehicleHalMessageHandler::VehicleHalMessageHandler(const sp<Looper>& looper,
VehicleNetworkService& service)
: mLooper(looper),
mService(service),
mFreeListIndex(0),
mLastDispatchTime(0) {
}
VehicleHalMessageHandler::~VehicleHalMessageHandler() {
Mutex::Autolock autoLock(mLock);
for (int i = 0; i < NUM_PROPERTY_EVENT_LISTS; i++) {
for (auto& e : mHalPropertyList[i]) {
VehiclePropValueUtil::deleteMembers(e);
delete e;
}
}
for (VehicleHalError* e : mHalErrors) {
delete e;
}
}
static const int MS_TO_NS = 1000000;
void VehicleHalMessageHandler::handleHalEvent(vehicle_prop_value_t *eventData) {
EVENT_LOG("handleHalEvent 0x%x", eventData->prop);
Mutex::Autolock autoLock(mLock);
List<vehicle_prop_value_t*>& propList = mHalPropertyList[mFreeListIndex];
propList.push_back(eventData);
int64_t deltaFromLast = elapsedRealtime() - mLastDispatchTime;
if (deltaFromLast > DISPATCH_INTERVAL_MS) {
mLooper->sendMessage(this, Message(HAL_EVENT));
} else {
mLooper->sendMessageDelayed((DISPATCH_INTERVAL_MS - deltaFromLast) * MS_TO_NS,
this, Message(HAL_EVENT));
}
}
void VehicleHalMessageHandler::handleHalError(VehicleHalError* error) {
Mutex::Autolock autoLock(mLock);
mHalErrors.push_back(error);
mLooper->sendMessage(this, Message(HAL_ERROR));
}
void VehicleHalMessageHandler::handleMockStart() {
Mutex::Autolock autoLock(mLock);
mHalPropertyList[0].clear();
mHalPropertyList[1].clear();
sp<MessageHandler> self(this);
mLooper->removeMessages(self);
}
void VehicleHalMessageHandler::doHandleHalEvent() {
// event dispatching can take time, so do it outside lock and that requires double buffering.
// inside lock, free buffer is swapped with non-free buffer.
List<vehicle_prop_value_t*>* events = NULL;
do {
Mutex::Autolock autoLock(mLock);
mLastDispatchTime = elapsedRealtime();
int nonFreeListIndex = mFreeListIndex ^ 0x1;
List<vehicle_prop_value_t*>* nonFreeList = &(mHalPropertyList[nonFreeListIndex]);
List<vehicle_prop_value_t*>* freeList = &(mHalPropertyList[mFreeListIndex]);
if (nonFreeList->size() > 0) {
for (auto& e : *freeList) {
nonFreeList->push_back(e);
}
freeList->clear();
events = nonFreeList;
} else if (freeList->size() > 0) {
events = freeList;
mFreeListIndex = nonFreeListIndex;
}
} while (false);
if (events != NULL) {
EVENT_LOG("doHandleHalEvent, num events:%d", events->size());
mService.dispatchHalEvents(*events);
//TODO implement return to memory pool
for (auto& e : *events) {
VehiclePropValueUtil::deleteMembers(e);
delete e;
}
events->clear();
}
}
void VehicleHalMessageHandler::doHandleHalError() {
VehicleHalError* error = NULL;
do {
Mutex::Autolock autoLock(mLock);
if (mHalErrors.size() > 0) {
auto itr = mHalErrors.begin();
error = *itr;
mHalErrors.erase(itr);
}
} while (false);
if (error != NULL) {
mService.dispatchHalError(error);
}
}
void VehicleHalMessageHandler::handleMessage(const Message& message) {
switch (message.what) {
case HAL_EVENT:
doHandleHalEvent();
break;
case HAL_ERROR:
doHandleHalError();
break;
}
}
// ----------------------------------------------------------------------------
void MockDeathHandler::binderDied(const wp<IBinder>& who) {
mService.handleHalMockDeath(who);
}
// ----------------------------------------------------------------------------
PropertyValueCache::PropertyValueCache() {
}
PropertyValueCache::~PropertyValueCache() {
for (size_t i = 0; i < mCache.size(); i++) {
vehicle_prop_value_t* v = mCache.editValueAt(i);
VehiclePropValueUtil::deleteMembers(v);
delete v;
}
mCache.clear();
}
void PropertyValueCache::writeToCache(const vehicle_prop_value_t& value) {
vehicle_prop_value_t* v;
ssize_t index = mCache.indexOfKey(value.prop);
if (index < 0) {
v = VehiclePropValueUtil::allocVehicleProp(value);
ASSERT_OR_HANDLE_NO_MEMORY(v, return);
mCache.add(value.prop, v);
} else {
v = mCache.editValueAt(index);
VehiclePropValueUtil::copyVehicleProp(v, value, true /* deleteOldData */);
}
}
bool PropertyValueCache::readFromCache(vehicle_prop_value_t* value) {
ssize_t index = mCache.indexOfKey(value->prop);
if (index < 0) {
ALOGE("readFromCache 0x%x, not found", value->prop);
return false;
}
const vehicle_prop_value_t* cached = mCache.valueAt(index);
//TODO this can be improved by just passing pointer and not deleting members.
status_t r = VehiclePropValueUtil::copyVehicleProp(value, *cached);
if (r != NO_ERROR) {
ALOGD("readFromCache 0x%x, copy failed %d", value->prop, r);
return false;
}
return true;
}
// ----------------------------------------------------------------------------
VehicleNetworkService* VehicleNetworkService::sInstance = NULL;
status_t VehicleNetworkService::dump(int fd, const Vector<String16>& /*args*/) {
static const String16 sDump("android.permission.DUMP");
String8 msg;
if (!PermissionCache::checkCallingPermission(sDump)) {
msg.appendFormat("Permission Denial: "
"can't dump VNS from pid=%d, uid=%d\n",
IPCThreadState::self()->getCallingPid(),
IPCThreadState::self()->getCallingUid());
write(fd, msg.string(), msg.size());
return NO_ERROR;
}
msg.append("MockingEnabled=%d\n", mMockingEnabled ? 1 : 0);
msg.append("*Properties\n");
for (auto& prop : mProperties->getList()) {
VechilePropertyUtil::dumpProperty(msg, *prop);
}
if (mMockingEnabled) {
msg.append("*Mocked Properties\n");
for (auto& prop : mPropertiesForMocking->getList()) {
//TODO dump more info
msg.appendFormat("property 0x%x\n", prop->prop);
}
}
msg.append("*Active clients*\n");
for (size_t i = 0; i < mBinderToClientMap.size(); i++) {
msg.appendFormat("pid %d uid %d\n", mBinderToClientMap.valueAt(i)->getPid(),
mBinderToClientMap.valueAt(i)->getUid());
}
msg.append("*Active clients per property*\n");
for (size_t i = 0; i < mPropertyToClientsMap.size(); i++) {
msg.appendFormat("prop 0x%x, pids:", mPropertyToClientsMap.keyAt(i));
sp<HalClientSpVector> clients = mPropertyToClientsMap.valueAt(i);
for (size_t j = 0; j < clients->size(); j++) {
msg.appendFormat("%d,", clients->itemAt(j)->getPid());
}
msg.append("\n");
}
msg.append("*Subscription info per property*\n");
for (size_t i = 0; i < mSubscriptionInfos.size(); i++) {
const SubscriptionInfo& info = mSubscriptionInfos.valueAt(i);
msg.appendFormat("prop 0x%x, sample rate %f Hz, zones 0x%x\n", mSubscriptionInfos.keyAt(i),
info.sampleRate, info.zones);
}
msg.append("*Event counts per property*\n");
for (size_t i = 0; i < mEventsCount.size(); i++) {
msg.appendFormat("prop 0x%x: %d\n", mEventsCount.keyAt(i),
mEventsCount.valueAt(i));
}
msg.append("*Vehicle Network Service Permissions*\n");
mVehiclePropertyAccessControl.dump(msg);
write(fd, msg.string(), msg.size());
return NO_ERROR;
}
bool VehicleNetworkService::isOperationAllowed(int32_t property, bool isWrite) {
const uid_t uid = IPCThreadState::self()->getCallingUid();
bool allowed = mVehiclePropertyAccessControl.testAccess(property, uid, isWrite);
if (!allowed) {
ALOGW("Property 0x%x: access not allowed for uid %d, isWrite %d", property, uid, isWrite);
}
return allowed;
}
VehicleNetworkService::VehicleNetworkService()
: mModule(NULL),
mMockingEnabled(false) {
sInstance = this;
// Load vehicle network services policy file
if(!mVehiclePropertyAccessControl.init()) {
LOG_ALWAYS_FATAL("Vehicle property access policy could not be initialized.");
}
}
VehicleNetworkService::~VehicleNetworkService() {
sInstance = NULL;
for (size_t i = 0; i < mPropertyToClientsMap.size(); i++) {
sp<HalClientSpVector> clients = mPropertyToClientsMap.editValueAt(i);
clients->clear();
}
mBinderToClientMap.clear();
mPropertyToClientsMap.clear();
mSubscriptionInfos.clear();
}
void VehicleNetworkService::binderDied(const wp<IBinder>& who) {
List<int32_t> propertiesToUnsubscribe;
do {
Mutex::Autolock autoLock(mLock);
sp<IBinder> ibinder = who.promote();
ibinder->unlinkToDeath(this);
ssize_t index = mBinderToClientMap.indexOfKey(ibinder);
if (index < 0) {
// already removed. ignore
return;
}
sp<HalClient> currentClient = mBinderToClientMap.editValueAt(index);
ALOGW("client binder death, pid: %d, uid:%d", currentClient->getPid(),
currentClient->getUid());
mBinderToClientMap.removeItemsAt(index);
for (size_t i = 0; i < mPropertyToClientsMap.size(); i++) {
sp<HalClientSpVector>& clients = mPropertyToClientsMap.editValueAt(i);
clients->remove(currentClient);
// TODO update frame rate
if (clients->size() == 0) {
int32_t property = mPropertyToClientsMap.keyAt(i);
propertiesToUnsubscribe.push_back(property);
mSubscriptionInfos.removeItem(property);
}
}
for (int32_t property : propertiesToUnsubscribe) {
mPropertyToClientsMap.removeItem(property);
}
} while (false);
for (int32_t property : propertiesToUnsubscribe) {
mDevice->unsubscribe(mDevice, property);
}
}
void VehicleNetworkService::handleHalMockDeath(const wp<IBinder>& who) {
ALOGE("Hal mock binder died");
sp<IBinder> ibinder = who.promote();
stopMocking(IVehicleNetworkHalMock::asInterface(ibinder));
}
int VehicleNetworkService::eventCallback(const vehicle_prop_value_t *eventData) {
EVENT_LOG("eventCallback 0x%x");
sInstance->onHalEvent(eventData);
return NO_ERROR;
}
int VehicleNetworkService::errorCallback(int32_t errorCode, int32_t property, int32_t operation) {
status_t r = sInstance->onHalError(errorCode, property, operation);
if (r != NO_ERROR) {
ALOGE("VehicleNetworkService::errorCallback onHalError failed with %d", r);
}
return NO_ERROR;
}
extern "C" {
vehicle_prop_config_t const * getInternalProperties();
int getNumInternalProperties();
};
void VehicleNetworkService::onFirstRef() {
Mutex::Autolock autoLock(mLock);
status_t r = loadHal();
if (r!= NO_ERROR) {
ALOGE("cannot load HAL, error:%d", r);
return;
}
mHandlerThread = new HandlerThread();
r = mHandlerThread->start("HAL.NATIVE_LOOP");
if (r != NO_ERROR) {
ALOGE("cannot start handler thread, error:%d", r);
return;
}
sp<VehicleHalMessageHandler> handler(new VehicleHalMessageHandler(mHandlerThread->getLooper(),
*this));
ASSERT_ALWAYS_ON_NO_MEMORY(handler.get());
mHandler = handler;
r = mDevice->init(mDevice, eventCallback, errorCallback);
if (r != NO_ERROR) {
ALOGE("HAL init failed:%d", r);
return;
}
int numConfigs = 0;
vehicle_prop_config_t const* configs = mDevice->list_properties(mDevice, &numConfigs);
mProperties = new VehiclePropertiesHolder(false /* deleteConfigsInDestructor */);
ASSERT_ALWAYS_ON_NO_MEMORY(mProperties);
for (int i = 0; i < numConfigs; i++) {
mProperties->getList().push_back(&configs[i]);
}
configs = getInternalProperties();
for (int i = 0; i < getNumInternalProperties(); i++) {
mProperties->getList().push_back(&configs[i]);
}
}
void VehicleNetworkService::release() {
do {
Mutex::Autolock autoLock(mLock);
mHandlerThread->quit();
} while (false);
mDevice->release(mDevice);
}
vehicle_prop_config_t const * VehicleNetworkService::findConfigLocked(int32_t property) {
for (auto& config : (mMockingEnabled ?
mPropertiesForMocking->getList() : mProperties->getList())) {
if (config->prop == property) {
return config;
}
}
ALOGW("property not found 0x%x", property);
return NULL;
}
bool VehicleNetworkService::isGettableLocked(int32_t property) {
vehicle_prop_config_t const * config = findConfigLocked(property);
if (config == NULL) {
return false;
}
if ((config->access & VEHICLE_PROP_ACCESS_READ) == 0) {
ALOGI("cannot get, property 0x%x is write only", property);
return false;
}
return true;
}
bool VehicleNetworkService::isSettableLocked(int32_t property, int32_t valueType) {
vehicle_prop_config_t const * config = findConfigLocked(property);
if (config == NULL) {
return false;
}
if ((config->access & VEHICLE_PROP_ACCESS_WRITE) == 0) {
ALOGI("cannot set, property 0x%x is read only", property);
return false;
}
if (config->value_type != valueType) {
ALOGW("cannot set, property 0x%x expects type 0x%x while got 0x%x", property,
config->value_type, valueType);
return false;
}
return true;
}
bool VehicleNetworkService::isSubscribableLocked(int32_t property) {
vehicle_prop_config_t const * config = findConfigLocked(property);
if (config == NULL) {
return false;
}
if ((config->access & VEHICLE_PROP_ACCESS_READ) == 0) {
ALOGI("cannot subscribe, property 0x%x is write only", property);
return false;
}
if (config->change_mode == VEHICLE_PROP_CHANGE_MODE_STATIC) {
ALOGI("cannot subscribe, property 0x%x is static", property);
return false;
}
return true;
}
bool VehicleNetworkService::isZonedProperty(vehicle_prop_config_t const * config) {
if (config == NULL) {
return false;
}
switch (config->value_type) {
case VEHICLE_VALUE_TYPE_ZONED_INT32:
case VEHICLE_VALUE_TYPE_ZONED_FLOAT:
case VEHICLE_VALUE_TYPE_ZONED_BOOLEAN:
case VEHICLE_VALUE_TYPE_ZONED_INT32_VEC2:
case VEHICLE_VALUE_TYPE_ZONED_INT32_VEC3:
case VEHICLE_VALUE_TYPE_ZONED_FLOAT_VEC2:
case VEHICLE_VALUE_TYPE_ZONED_FLOAT_VEC3:
return true;
}
return false;
}
sp<VehiclePropertiesHolder> VehicleNetworkService::listProperties(int32_t property) {
Mutex::Autolock autoLock(mLock);
if (property == 0) {
if (!mMockingEnabled) {
return mProperties;
} else {
return mPropertiesForMocking;
}
} else {
sp<VehiclePropertiesHolder> p;
const vehicle_prop_config_t* config = findConfigLocked(property);
if (config != NULL) {
p = new VehiclePropertiesHolder(false /* deleteConfigsInDestructor */);
p->getList().push_back(config);
ASSERT_OR_HANDLE_NO_MEMORY(p.get(), return p);
}
return p;
}
}
status_t VehicleNetworkService::getProperty(vehicle_prop_value_t *data) {
bool inMocking = false;
do { // for lock scoping
Mutex::Autolock autoLock(mLock);
if (!isGettableLocked(data->prop)) {
ALOGW("getProperty, cannot get 0x%x", data->prop);
return BAD_VALUE;
}
if ((data->prop >= (int32_t)VEHICLE_PROPERTY_INTERNAL_START) &&
(data->prop <= (int32_t)VEHICLE_PROPERTY_INTERNAL_END)) {
if (!mCache.readFromCache(data)) {
return BAD_VALUE;
}
return NO_ERROR;
}
//TODO caching for static, on-change type?
if (mMockingEnabled) {
inMocking = true;
}
} while (false);
// set done outside lock to allow concurrent access
if (inMocking) {
status_t r = mHalMock->onPropertyGet(data);
if (r != NO_ERROR) {
ALOGW("getProperty 0x%x failed, mock returned %d", data->prop, r);
}
return r;
}
/*
* get call can return -EAGAIN error when hal has not fetched all data. In that case,
* keep retrying for certain time with some sleep. This will happen only at initial stage.
*/
status_t r = -EAGAIN;
int retryCount = 0;
while (true) {
r = mDevice->get(mDevice, data);
if (r == NO_ERROR) {
break;
}
if (r != -EAGAIN) {
break;
}
retryCount++;
if (retryCount > MAX_GET_RETRY_FOR_NOT_READY) {
ALOGE("Vehicle hal keep retrying not ready after multiple retries");
break;
}
usleep(GET_WAIT_US);
}
if (r != NO_ERROR) {
ALOGW("getProperty 0x%x failed, HAL returned %d", data->prop, r);
}
return r;
}
void VehicleNetworkService::releaseMemoryFromGet(vehicle_prop_value_t* value) {
switch (value->prop) {
case VEHICLE_VALUE_TYPE_STRING:
case VEHICLE_VALUE_TYPE_BYTES: {
Mutex::Autolock autoLock(mLock);
mDevice->release_memory_from_get(mDevice, value);
} break;
}
}
status_t VehicleNetworkService::setProperty(const vehicle_prop_value_t& data) {
bool isInternalProperty = false;
bool inMocking = false;
do { // for lock scoping
Mutex::Autolock autoLock(mLock);
if (!isSettableLocked(data.prop, data.value_type)) {
ALOGW("setProperty, cannot set 0x%x", data.prop);
return BAD_VALUE;
}
if ((data.prop >= (int32_t)VEHICLE_PROPERTY_INTERNAL_START) &&
(data.prop <= (int32_t)VEHICLE_PROPERTY_INTERNAL_END)) {
isInternalProperty = true;
mCache.writeToCache(data);
}
if (mMockingEnabled) {
inMocking = true;
}
} while (false);
if (inMocking) {
status_t r = mHalMock->onPropertySet(data);
if (r != NO_ERROR) {
ALOGW("setProperty 0x%x failed, mock returned %d", data.prop, r);
return r;
}
}
if (isInternalProperty) {
// for internal property, just publish it.
onHalEvent(&data, inMocking);
return NO_ERROR;
}
if (inMocking) {
return NO_ERROR;
}
//TODO add value check requires auto generated code to return value range for enum types
// set done outside lock to allow concurrent access
status_t r = mDevice->set(mDevice, &data);
if (r != NO_ERROR) {
ALOGW("setProperty 0x%x failed, HAL returned %d", data.prop, r);
}
return r;
}
status_t VehicleNetworkService::subscribe(const sp<IVehicleNetworkListener> &listener, int32_t prop,
float sampleRate, int32_t zones) {
bool shouldSubscribe = false;
bool inMock = false;
int32_t newZones = zones;
do {
Mutex::Autolock autoLock(mLock);
if (!isSubscribableLocked(prop)) {
return BAD_VALUE;
}
vehicle_prop_config_t const * config = findConfigLocked(prop);
if (config->change_mode == VEHICLE_PROP_CHANGE_MODE_ON_CHANGE) {
if (sampleRate != 0) {
ALOGW("Sample rate set to non-zeo for on change type. Ignore it");
sampleRate = 0;
}
} else {
if (sampleRate > config->max_sample_rate) {
ALOGW("sample rate %f higher than max %f. limit to max", sampleRate,
config->max_sample_rate);
sampleRate = config->max_sample_rate;
}
if (sampleRate < config->min_sample_rate) {
ALOGW("sample rate %f lower than min %f. limit to min", sampleRate,
config->min_sample_rate);
sampleRate = config->min_sample_rate;
}
}
if (isZonedProperty(config)) {
if ((zones != 0) && ((zones & config->vehicle_zone_flags) != zones)) {
ALOGE("subscribe requested zones 0x%x out of range, supported:0x%x", zones,
config->vehicle_zone_flags);
return BAD_VALUE;
}
} else { // ignore zone
zones = 0;
}
sp<IBinder> ibinder = IInterface::asBinder(listener);
LOG_VERBOSE("subscribe, binder 0x%x prop 0x%x", ibinder.get(), prop);
sp<HalClient> client = findOrCreateClientLocked(ibinder, listener);
if (client.get() == NULL) {
ALOGE("subscribe, no memory, cannot create HalClient");
return NO_MEMORY;
}
sp<HalClientSpVector> clientsForProperty = findOrCreateClientsVectorForPropertyLocked(prop);
if (clientsForProperty.get() == NULL) {
ALOGE("subscribe, no memory, cannot create HalClientSpVector");
return NO_MEMORY;
}
clientsForProperty->add(client);
ssize_t index = mSubscriptionInfos.indexOfKey(prop);
if (index < 0) {
// first time subscription for this property
shouldSubscribe = true;
} else {
const SubscriptionInfo& info = mSubscriptionInfos.valueAt(index);
if (info.sampleRate < sampleRate) {
shouldSubscribe = true;
}
newZones = (info.zones == 0) ? 0 : ((zones == 0) ? 0 : (info.zones | zones));
if (info.zones != newZones) {
shouldSubscribe = true;
}
}
client->setSubscriptionInfo(prop, sampleRate, zones);
if (shouldSubscribe) {
inMock = mMockingEnabled;
SubscriptionInfo info(sampleRate, newZones);
mSubscriptionInfos.add(prop, info);
if ((prop >= (int32_t)VEHICLE_PROPERTY_INTERNAL_START) &&
(prop <= (int32_t)VEHICLE_PROPERTY_INTERNAL_END)) {
LOG_VERBOSE("subscribe to internal property, prop 0x%x", prop);
return NO_ERROR;
}
}
} while (false);
if (shouldSubscribe) {
status_t r;
if (inMock) {
r = mHalMock->onPropertySubscribe(prop, sampleRate, newZones);
if (r != NO_ERROR) {
ALOGW("subscribe 0x%x failed, mock returned %d", prop, r);
}
} else {
LOG_VERBOSE("subscribe to HAL, prop 0x%x sample rate:%f zones:0x%x", prop, sampleRate,
newZones);
r = mDevice->subscribe(mDevice, prop, sampleRate, newZones);
if (r != NO_ERROR) {
ALOGW("subscribe 0x%x failed, HAL returned %d", prop, r);
}
}
return r;
}
return NO_ERROR;
}
void VehicleNetworkService::unsubscribe(const sp<IVehicleNetworkListener> &listener, int32_t prop) {
bool shouldUnsubscribe = false;
bool inMocking = false;
do {
Mutex::Autolock autoLock(mLock);
if (!isSubscribableLocked(prop)) {
return;
}
sp<IBinder> ibinder = IInterface::asBinder(listener);
LOG_VERBOSE("unsubscribe, binder 0x%x, prop 0x%x", ibinder.get(), prop);
sp<HalClient> client = findClientLocked(ibinder);
if (client.get() == NULL) {
ALOGD("unsubscribe client not found in binder map");
return;
}
shouldUnsubscribe = removePropertyFromClientLocked(ibinder, client, prop);
if ((prop >= (int32_t)VEHICLE_PROPERTY_INTERNAL_START) &&
(prop <= (int32_t)VEHICLE_PROPERTY_INTERNAL_END)) {
LOG_VERBOSE("unsubscribe to internal property, prop 0x%x", prop);
return;
}
if (mMockingEnabled) {
inMocking = true;
}
} while (false);
if (shouldUnsubscribe) {
if (inMocking) {
mHalMock->onPropertyUnsubscribe(prop);
} else {
mDevice->unsubscribe(mDevice, prop);
}
}
}
sp<HalClient> VehicleNetworkService::findClientLocked(sp<IBinder>& ibinder) {
sp<HalClient> client;
ssize_t index = mBinderToClientMap.indexOfKey(ibinder);
if (index < 0) {
return client;
}
return mBinderToClientMap.editValueAt(index);
}
sp<HalClient> VehicleNetworkService::findOrCreateClientLocked(sp<IBinder>& ibinder,
const sp<IVehicleNetworkListener> &listener) {
sp<HalClient> client;
ssize_t index = mBinderToClientMap.indexOfKey(ibinder);
if (index < 0) {
IPCThreadState* self = IPCThreadState::self();
pid_t pid = self->getCallingPid();
uid_t uid = self->getCallingUid();
client = new HalClient(listener, pid, uid);
ASSERT_OR_HANDLE_NO_MEMORY(client.get(), return client);
ibinder->linkToDeath(this);
LOG_VERBOSE("add binder 0x%x to map", ibinder.get());
mBinderToClientMap.add(ibinder, client);
} else {
client = mBinderToClientMap.editValueAt(index);
}
return client;
}
sp<HalClientSpVector> VehicleNetworkService::findClientsVectorForPropertyLocked(int32_t property) {
sp<HalClientSpVector> clientsForProperty;
ssize_t index = mPropertyToClientsMap.indexOfKey(property);
if (index >= 0) {
clientsForProperty = mPropertyToClientsMap.editValueAt(index);
}
return clientsForProperty;
}
sp<HalClientSpVector> VehicleNetworkService::findOrCreateClientsVectorForPropertyLocked(
int32_t property) {
sp<HalClientSpVector> clientsForProperty;
ssize_t index = mPropertyToClientsMap.indexOfKey(property);
if (index >= 0) {
clientsForProperty = mPropertyToClientsMap.editValueAt(index);
} else {
clientsForProperty = new HalClientSpVector();
ASSERT_OR_HANDLE_NO_MEMORY(clientsForProperty.get(), return clientsForProperty);
mPropertyToClientsMap.add(property, clientsForProperty);
}
return clientsForProperty;
}
/**
* remove given property from client and remove HalCLient if necessary.
* @return true if the property should be unsubscribed from HAL (=no more clients).
*/
bool VehicleNetworkService::removePropertyFromClientLocked(sp<IBinder>& ibinder,
sp<HalClient>& client, int32_t property) {
if(!client->removePropertyAndCheckIfActive(property)) {
// client is no longer necessary
mBinderToClientMap.removeItem(ibinder);
ibinder->unlinkToDeath(this);
}
sp<HalClientSpVector> clientsForProperty = findClientsVectorForPropertyLocked(property);
if (clientsForProperty.get() == NULL) {
// no subscription
return false;
}
clientsForProperty->remove(client);
//TODO reset sample rate. do not care for now.
if (clientsForProperty->size() == 0) {
mPropertyToClientsMap.removeItem(property);
mSubscriptionInfos.removeItem(property);
return true;
}
return false;
}
status_t VehicleNetworkService::injectEvent(const vehicle_prop_value_t& value) {
ALOGI("injectEvent property:0x%x", value.prop);
return onHalEvent(&value, true);
}
status_t VehicleNetworkService::startMocking(const sp<IVehicleNetworkHalMock>& mock) {
sp<VehicleHalMessageHandler> handler;
List<sp<HalClient> > clientsToDispatch;
do {
Mutex::Autolock autoLock(mLock);
if (mMockingEnabled) {
ALOGW("startMocking while already enabled");
// allow it as test can fail without clearing
if (mHalMock != NULL) {
IInterface::asBinder(mHalMock)->unlinkToDeath(mHalMockDeathHandler.get());
}
}
ALOGW("starting vehicle HAL mocking");
sp<IBinder> ibinder = IInterface::asBinder(mock);
if (mHalMockDeathHandler.get() == NULL) {
mHalMockDeathHandler = new MockDeathHandler(*this);
}
ibinder->linkToDeath(mHalMockDeathHandler);
mHalMock = mock;
mMockingEnabled = true;
// Mock implementation should make sure that its startMocking call is not blocking its
// onlistProperties call. Otherwise, this will lead into dead-lock.
mPropertiesForMocking = mock->onListProperties();
handleHalRestartAndGetClientsToDispatchLocked(clientsToDispatch);
//TODO handle binder death
handler = mHandler;
} while (false);
handler->handleMockStart();
for (auto& client : clientsToDispatch) {
client->dispatchHalRestart(true);
}
clientsToDispatch.clear();
return NO_ERROR;
}
void VehicleNetworkService::stopMocking(const sp<IVehicleNetworkHalMock>& mock) {
List<sp<HalClient> > clientsToDispatch;
do {
Mutex::Autolock autoLock(mLock);
if (mHalMock.get() == NULL) {
return;
}
sp<IBinder> ibinder = IInterface::asBinder(mock);
if (ibinder != IInterface::asBinder(mHalMock)) {
ALOGE("stopMocking, not the one started");
return;
}
ALOGW("stopping vehicle HAL mocking");
ibinder->unlinkToDeath(mHalMockDeathHandler.get());
mHalMock = NULL;
mMockingEnabled = false;
handleHalRestartAndGetClientsToDispatchLocked(clientsToDispatch);
} while (false);
for (auto& client : clientsToDispatch) {
client->dispatchHalRestart(false);
}
clientsToDispatch.clear();
}
void VehicleNetworkService::handleHalRestartAndGetClientsToDispatchLocked(
List<sp<HalClient> >& clientsToDispatch) {
// all subscriptions are invalid
mPropertyToClientsMap.clear();
mSubscriptionInfos.clear();
mEventsCount.clear();
List<sp<HalClient> > clientsToRemove;
for (size_t i = 0; i < mBinderToClientMap.size(); i++) {
sp<HalClient> client = mBinderToClientMap.valueAt(i);
client->removeAllProperties();
if (client->isMonitoringHalRestart()) {
clientsToDispatch.push_back(client);
}
if (!client->isActive()) {
clientsToRemove.push_back(client);
}
}
for (auto& client : clientsToRemove) {
// client is no longer necessary
sp<IBinder> ibinder = IInterface::asBinder(client->getListener());
mBinderToClientMap.removeItem(ibinder);
ibinder->unlinkToDeath(this);
}
clientsToRemove.clear();
}
status_t VehicleNetworkService::injectHalError(int32_t errorCode, int32_t property,
int32_t operation) {
return onHalError(errorCode, property, operation, true /*isInjection*/);
}
status_t VehicleNetworkService::startErrorListening(const sp<IVehicleNetworkListener> &listener) {
sp<IBinder> ibinder = IInterface::asBinder(listener);
sp<HalClient> client;
do {
Mutex::Autolock autoLock(mLock);
client = findOrCreateClientLocked(ibinder, listener);
} while (false);
if (client.get() == NULL) {
ALOGW("startErrorListening failed, no memory");
return NO_MEMORY;
}
client->setHalErrorMonitoringState(true);
return NO_ERROR;
}
void VehicleNetworkService::stopErrorListening(const sp<IVehicleNetworkListener> &listener) {
sp<IBinder> ibinder = IInterface::asBinder(listener);
sp<HalClient> client;
do {
Mutex::Autolock autoLock(mLock);
client = findClientLocked(ibinder);
} while (false);
if (client.get() != NULL) {
client->setHalErrorMonitoringState(false);
}
}
status_t VehicleNetworkService::startHalRestartMonitoring(
const sp<IVehicleNetworkListener> &listener) {
sp<IBinder> ibinder = IInterface::asBinder(listener);
sp<HalClient> client;
do {
Mutex::Autolock autoLock(mLock);
client = findOrCreateClientLocked(ibinder, listener);
} while (false);
if (client.get() == NULL) {
ALOGW("startHalRestartMonitoring failed, no memory");
return NO_MEMORY;
}
client->setHalRestartMonitoringState(true);
return NO_ERROR;
}
void VehicleNetworkService::stopHalRestartMonitoring(const sp<IVehicleNetworkListener> &listener) {
sp<IBinder> ibinder = IInterface::asBinder(listener);
sp<HalClient> client;
do {
Mutex::Autolock autoLock(mLock);
client = findClientLocked(ibinder);
} while (false);
if (client.get() != NULL) {
client->setHalRestartMonitoringState(false);
}
}
status_t VehicleNetworkService::onHalEvent(const vehicle_prop_value_t* eventData, bool isInjection)
{
sp<VehicleHalMessageHandler> handler;
do {
Mutex::Autolock autoLock(mLock);
if (!isInjection) {
if (mMockingEnabled) {
// drop real HAL event if mocking is enabled
return NO_ERROR;
}
}
ssize_t index = mEventsCount.indexOfKey(eventData->prop);
if (index < 0) {
mEventsCount.add(eventData->prop, 1);
} else {
int count = mEventsCount.valueAt(index);
count++;
mEventsCount.add(eventData->prop, count);
}
handler = mHandler;
} while (false);
//TODO add memory pool
vehicle_prop_value_t* copy = VehiclePropValueUtil::allocVehicleProp(*eventData);
ASSERT_OR_HANDLE_NO_MEMORY(copy, return NO_MEMORY);
handler->handleHalEvent(copy);
return NO_ERROR;
}
status_t VehicleNetworkService::onHalError(int32_t errorCode, int32_t property, int32_t operation,
bool isInjection) {
sp<VehicleHalMessageHandler> handler;
VehicleHalError* error = NULL;
do {
Mutex::Autolock autoLock(mLock);
if (!isInjection) {
if (mMockingEnabled) {
// drop real HAL error if mocking is enabled
return NO_ERROR;
}
}
error = new VehicleHalError(errorCode, property, operation);
if (error == NULL) {
return NO_MEMORY;
}
handler = mHandler;
} while (false);
ALOGI("HAL error, error code:%d, property:0x%x, operation:%d, isInjection:%d",
errorCode, property, operation, isInjection? 1 : 0);
handler->handleHalError(error);
return NO_ERROR;
}
void VehicleNetworkService::dispatchHalEvents(List<vehicle_prop_value_t*>& events) {
HalClientSpVector activeClients;
do { // for lock scoping
Mutex::Autolock autoLock(mLock);
for (vehicle_prop_value_t* e : events) {
ssize_t index = mPropertyToClientsMap.indexOfKey(e->prop);
if (index < 0) {
EVENT_LOG("HAL event for not subscribed property 0x%x", e->prop);
continue;
}
sp<HalClientSpVector>& clients = mPropertyToClientsMap.editValueAt(index);
EVENT_LOG("dispatchHalEvents, prop 0x%x, active clients %d", e->prop, clients->size());
for (size_t i = 0; i < clients->size(); i++) {
sp<HalClient>& client = clients->editItemAt(i);
activeClients.add(client);
client->addEvent(e);
}
}
} while (false);
EVENT_LOG("dispatchHalEvents num events %d, active clients:%d", events.size(),
activeClients.size());
for (size_t i = 0; i < activeClients.size(); i++) {
sp<HalClient> client = activeClients.editItemAt(i);
client->dispatchEvents();
}
activeClients.clear();
}
void VehicleNetworkService::dispatchHalError(VehicleHalError* error) {
List<sp<HalClient> > clientsToDispatch;
do {
Mutex::Autolock autoLock(mLock);
if (error->property != 0) {
sp<HalClientSpVector> clientsForProperty = findClientsVectorForPropertyLocked(
error->property);
if (clientsForProperty.get() != NULL) {
for (size_t i = 0; i < clientsForProperty->size(); i++) {
sp<HalClient> client = clientsForProperty->itemAt(i);
clientsToDispatch.push_back(client);
}
}
}
// Send to global error handler if property is 0 or if no client subscribing.
if (error->property == 0 || clientsToDispatch.size() == 0) {
for (size_t i = 0; i < mBinderToClientMap.size(); i++) {
sp<HalClient> client = mBinderToClientMap.valueAt(i);
if (client->isMonitoringHalError()) {
clientsToDispatch.push_back(client);
}
}
}
} while (false);
ALOGI("dispatchHalError error:%d, property:0x%x, operation:%d, num clients to dispatch:%d",
error->errorCode, error->property, error->operation, clientsToDispatch.size());
for (auto& client : clientsToDispatch) {
client->dispatchHalError(error->errorCode, error->property, error->operation);
}
clientsToDispatch.clear();
}
status_t VehicleNetworkService::loadHal() {
int r = hw_get_module(VEHICLE_HARDWARE_MODULE_ID, (hw_module_t const**)&mModule);
if (r != NO_ERROR) {
ALOGE("cannot load HAL module, error:%d", r);
return r;
}
r = mModule->common.methods->open(&mModule->common, VEHICLE_HARDWARE_DEVICE,
(hw_device_t**)&mDevice);
return r;
}
void VehicleNetworkService::closeHal() {
mDevice->common.close(&mDevice->common);
}
};
| 35.551661 | 100 | 0.628237 | [
"vector"
] |
4e11ba60363a744b6c49b5e50ba80deae1d2603c | 3,704 | hpp | C++ | pwiz/data/vendor_readers/Bruker/Reader_Bruker.hpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/data/vendor_readers/Bruker/Reader_Bruker.hpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/data/vendor_readers/Bruker/Reader_Bruker.hpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef _READER_BRUKER_HPP_
#define _READER_BRUKER_HPP_
#include "pwiz/utility/misc/Export.hpp"
#include "pwiz/data/msdata/Reader.hpp"
namespace pwiz {
namespace msdata {
class PWIZ_API_DECL Reader_Bruker : public Reader
{
public:
virtual std::string identify(const std::string& filename,
const std::string& head) const;
virtual void read(const std::string& filename,
const std::string& head,
MSData& result,
int runIndex = 0,
const Config& config = Config()) const;
virtual void read(const std::string& filename,
const std::string& head,
std::vector<MSDataPtr>& results,
const Config& config = Config()) const
{
results.push_back(MSDataPtr(new MSData));
read(filename, head, *results.back(), 0, config);
}
virtual const char * getType() const {return "Bruker Analysis";}
};
class PWIZ_API_DECL Reader_Bruker_BAF : public Reader_Bruker
{
virtual const char * getType() const {return "Bruker BAF";}
virtual CVID getCvType() const {return MS_Bruker_BAF_format;}
virtual std::vector<std::string> getFileExtensions() const {return {".d", ".baf"};}
};
class PWIZ_API_DECL Reader_Bruker_Dummy : public Reader_Bruker
{
// no-op function: Reader_Bruker_BAF is the only one that should do any work (and it just uses Reader_Bruker::identify)
virtual std::string identify(const std::string& filename, const std::string& head) const {return "";}
};
class PWIZ_API_DECL Reader_Bruker_YEP : public Reader_Bruker_Dummy
{
virtual const char * getType() const {return "Bruker YEP";}
virtual CVID getCvType() const {return MS_Bruker_Agilent_YEP_format;}
virtual std::vector<std::string> getFileExtensions() const {return {".d", ".yep"};}
};
class PWIZ_API_DECL Reader_Bruker_FID : public Reader_Bruker_Dummy
{
virtual const char * getType() const {return "Bruker FID";}
virtual CVID getCvType() const {return MS_Bruker_FID_format;}
virtual std::vector<std::string> getFileExtensions() const {return {"fid"};} // not an extension, fid is the whole filename
};
class PWIZ_API_DECL Reader_Bruker_U2 : public Reader_Bruker_Dummy
{
virtual const char * getType() const {return "Bruker U2";}
virtual CVID getCvType() const {return MS_Bruker_U2_format;}
virtual std::vector<std::string> getFileExtensions() const {return {".d", ".u2"};}
};
class PWIZ_API_DECL Reader_Bruker_TDF : public Reader_Bruker_Dummy
{
virtual const char * getType() const {return "Bruker TDF";}
virtual CVID getCvType() const {return MS_Bruker_TDF_format;}
virtual std::vector<std::string> getFileExtensions() const {return {".d", ".tdf"};}
};
} // namespace msdata
} // namespace pwiz
#endif // _READER_BRUKER_HPP_
| 34.616822 | 128 | 0.666847 | [
"vector"
] |
4e19dee9134301145367546d475f26a6c3fd6a40 | 19,685 | cpp | C++ | src/backend_python.cpp | junefish/hdf5-udf | 0961e0caf579fa148ca49792aa9b488547ea6e46 | [
"MIT"
] | null | null | null | src/backend_python.cpp | junefish/hdf5-udf | 0961e0caf579fa148ca49792aa9b488547ea6e46 | [
"MIT"
] | null | null | null | src/backend_python.cpp | junefish/hdf5-udf | 0961e0caf579fa148ca49792aa9b488547ea6e46 | [
"MIT"
] | null | null | null | /*
* HDF5-UDF: User-Defined Functions for HDF5
*
* File: backend_python.cpp
*
* Python code parser and bytecode generation/execution.
*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <errno.h>
#include <fstream>
#include <sstream>
#include <string>
#include <locale>
#include <codecvt>
#include <algorithm>
#include "udf_template_py.h"
#include "backend_python.h"
#include "backend_cpp.h"
#include "file_search.h"
#include "anon_mmap.h"
#include "dataset.h"
#include "os.h"
// Dataset names, sizes, and types
static std::vector<DatasetInfo> dataset_info;
// Buffer used to hold the compound-to-struct name produced by pythonGetCast()
static char compound_cast_name[256];
/* Functions exported to the Python template library */
extern "C" void *pythonGetData(const char *element)
{
for (size_t i=0; i<dataset_info.size(); ++i)
if (dataset_info[i].name.compare(element) == 0)
return dataset_info[i].data;
fprintf(stderr, "%s: dataset %s not found\n", __func__, element);
return NULL;
}
extern "C" const char *pythonGetType(const char *element)
{
for (size_t i=0; i<dataset_info.size(); ++i)
if (dataset_info[i].name.compare(element) == 0)
return dataset_info[i].getDatatypeName();
fprintf(stderr, "%s: dataset %s not found\n", __func__, element);
return NULL;
}
extern "C" const char *pythonGetCast(const char *element)
{
for (size_t i=0; i<dataset_info.size(); ++i) {
if (dataset_info[i].name.compare(element) == 0)
{
auto cast = dataset_info[i].getCastDatatype();
if (! strcmp(cast, "void*") || ! strcmp(cast, "char*"))
{
// Cast compound structure or the structure that supports
// the declaration of string datasets
PythonBackend backend;
memset(compound_cast_name, 0, sizeof(compound_cast_name));
snprintf(compound_cast_name, sizeof(compound_cast_name)-1,
"struct %s_t *", backend.sanitizedName(element).c_str());
return compound_cast_name;
}
return cast;
}
}
fprintf(stderr, "%s: dataset %s not found\n", __func__, element);
return NULL;
}
extern "C" const char *pythonGetDims(const char *element)
{
for (size_t i=0; i<dataset_info.size(); ++i)
if (dataset_info[i].name.compare(element) == 0)
return dataset_info[i].dimensions_str.c_str();
fprintf(stderr, "%s: dataset %s not found\n", __func__, element);
return NULL;
}
/* This backend's name */
std::string PythonBackend::name()
{
return "CPython";
}
/* Extension managed by this backend */
std::string PythonBackend::extension()
{
return ".py";
}
/* Compile Python to a bytecode. Returns the bytecode as a string object. */
std::string PythonBackend::compile(
std::string udf_file,
std::string compound_declarations,
std::string &source_code,
std::vector<DatasetInfo> &datasets)
{
AssembleData data = {
.udf_file = udf_file,
.template_string = std::string((char *) udf_template_py),
.compound_placeholder = "// compound_declarations_placeholder",
.compound_decl = compound_declarations,
.methods_decl_placeholder = "",
.methods_decl = "",
.methods_impl_placeholder = "",
.methods_impl = "",
.callback_placeholder = "# user_callback_placeholder",
.extension = this->extension()
};
auto py_file = Backend::assembleUDF(data);
if (py_file.size() == 0)
{
fprintf(stderr, "Will not be able to compile the UDF code\n");
return "";
}
char *cmd[] = {
(char *) "python3",
(char *) "-m",
(char *) "compileall",
(char *) "-q", // output error messages only
(char *) "-l", // don't recurse into subdirectories
(char *) "-f", // force rebuild even if timestamps are up to date
(char *) py_file.c_str(),
(char *) NULL
};
if (os::execCommand(cmd[0], cmd, NULL) == false)
{
fprintf(stderr, "Failed to build the UDF\n");
unlink(py_file.c_str());
return "";
}
// Find the bytecode
auto sep = py_file.find_last_of('/');
if (sep == std::string::npos)
{
fprintf(stderr, "Failed to identify directory where assembled file was saved\n");
unlink(py_file.c_str());
return "";
}
std::string parentdir = py_file.substr(0, sep);
std::string filename = py_file.substr(sep + 1);
sep = filename.find_last_of(".");
filename = filename.substr(0, sep);
// Find the generated bytecode file
std::vector<std::string> results;
std::stringstream pycache, pattern;
pycache << parentdir << "/__pycache__";
pattern << filename << ".cpython-*.pyc";
bool ret = findByPattern(pycache.str(), pattern.str(), results);
if (ret == false || results.size() == 0)
{
fprintf(stderr, "No bytecode found under %s\n", pattern.str().c_str());
unlink(py_file.c_str());
rmdir(pycache.str().c_str());
return "";
}
// Assume the very first match is the one we're looking for
std::string pyc_file = results[0];
// Read generated bytecode
std::string bytecode;
std::ifstream datastream(pyc_file, std::ifstream::binary);
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(datastream), {});
bytecode.assign(buffer.begin(), buffer.end());
datastream.close();
// Read source file
std::ifstream ifs(py_file.c_str());
source_code = std::string((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
ifs.close();
unlink(py_file.c_str());
unlink(pyc_file.c_str());
rmdir(pycache.str().c_str());
return bytecode;
}
/* Helper class: manage Python interpreter lifecycle */
struct PythonInterpreter {
PythonInterpreter() :
libpython(NULL),
nested_session(false),
interpreter(NULL),
my_state(NULL)
{
}
bool init() {
// We currently depend on Python 3
if (PY_MAJOR_VERSION != 3)
{
fprintf(stderr, "Error: Python3 is required\n");
return false;
}
nested_session = Py_IsInitialized();
if (nested_session)
{
// Create a new thread state object and make it current
interpreter = PyInterpreterState_Main();
my_state = PyThreadState_New(interpreter);
PyEval_AcquireThread(my_state);
}
else
{
// Initialize the interpreter
Py_InitializeEx(0);
// Workaround for CFFI import errors due to missing symbols. We force libpython
// to be loaded and for all symbols to be resolved by dlopen()
std::string libpython_path = os::sharedLibraryName("python3");
void *libpython = dlopen(libpython_path.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (! libpython)
{
char libname[64];
snprintf(libname, sizeof(libname)-1, "python3.%d", PY_MINOR_VERSION);
libpython_path = os::sharedLibraryName(libname);
libpython = dlopen(libpython_path.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (! libpython)
fprintf(stderr, "Warning: could not load %s\n", libpython_path.c_str());
}
}
return true;
}
~PythonInterpreter() {
PyErr_Clear();
for (auto mod = decref.rbegin(); mod != decref.rend(); ++mod)
Py_XDECREF(*mod);
if (nested_session)
{
PyEval_ReleaseThread(my_state);
PyThreadState_Clear(my_state);
PyThreadState_Delete(my_state);
}
else
Py_Finalize();
if (libpython)
dlclose(libpython);
dataset_info.clear();
}
// dlopen handle
void *libpython;
// Have we been invoked from an existing Python session?
bool nested_session;
// List of objects we have to Py_DECREF() on exit
std::vector<PyObject *> decref;
// Python thread state
PyInterpreterState *interpreter;
PyThreadState *my_state;
};
/* Execute the user-defined-function embedded in the given buffer */
bool PythonBackend::run(
const std::string libpath,
const std::vector<DatasetInfo> &input_datasets,
const DatasetInfo &output_dataset,
const char *output_cast_datatype,
const char *bytecode,
size_t bytecode_size,
const json &rules)
{
if (bytecode_size < 16)
{
fprintf(stderr, "Error: Python bytecode is too small to be valid\n");
return false;
}
/*
* We want to make the output dataset writeable by the UDF. Because
* the UDF is run under a separate process we have to use a shared
* memory segment which both processes can read and write to.
*/
size_t room_size = output_dataset.getGridSize() * output_dataset.getStorageSize();
AnonymousMemoryMap mm(room_size);
if (! mm.createMapFor(output_dataset.data))
return false;
// Let output_dataset.data point to the shared memory segment
DatasetInfo output_dataset_copy(output_dataset);
output_dataset_copy.data = mm.mm;
// Populate global vector of dataset names, sizes, and types
dataset_info.push_back(std::move(output_dataset_copy));
dataset_info.insert(
dataset_info.end(), input_datasets.begin(), input_datasets.end());
// Init Python interpreter if needed
PythonInterpreter python;
if (python.init() == false)
return false;
// The offset to the actual bytecode may change across Python versions.
// Please look under $python_sources/Lib/importlib/_bootstrap_external.py
// for the implementation of _validate_*() so you can identify the right
// offset for a version of Python not featured in the list below.
size_t bytecode_start;
switch (PY_MINOR_VERSION)
{
case 1 ... 2:
bytecode_start = 8;
break;
case 3 ... 6:
bytecode_start = 12;
break;
case 7 ... 8:
default:
bytecode_start = 16;
break;
}
bytecode = &bytecode[bytecode_start];
bytecode_size -= bytecode_start;
// Get a reference to the code object we compiled before
PyObject *obj = PyMarshal_ReadObjectFromString(bytecode, bytecode_size);
if (! obj)
{
PyObject *err = PyErr_Occurred();
if (err)
PyErr_Print();
return false;
}
python.decref.push_back(obj);
PyObject *module = PyImport_ExecCodeModule("udf_module", obj);
if (! module)
{
fprintf(stderr, "Failed to import code object\n");
PyErr_Print();
return false;
}
python.decref.push_back(module);
// Load essential modules prior to the launch of the user-defined-function
// so we can keep strict sandbox rules for third-party code.
PyObject *module_name = PyUnicode_FromString("cffi");
python.decref.push_back(module_name);
PyObject *cffi_module = PyImport_Import(module_name);
if (! cffi_module)
{
fprintf(stderr, "Failed to import the cffi module\n");
return false;
}
python.decref.push_back(cffi_module);
// From the documentation: unlike other functions that steal references,
// PyModule_AddObject() only decrements the reference count of value on success
Py_INCREF(cffi_module);
if (PyModule_AddObject(module, "cffi", cffi_module) < 0)
{
Py_DECREF(cffi_module);
return false;
}
// Construct an instance of cffi.FFI()
PyObject *cffi_dict = PyModule_GetDict(cffi_module);
PyObject *ffi = cffi_dict ? PyDict_GetItemString(cffi_dict, "FFI") : NULL;
PyObject *ffi_instance = ffi ? PyObject_CallObject(ffi, NULL) : NULL;
python.decref.push_back(ffi_instance);
// Get a reference to cffi.FFI().dlopen()
PyObject *ffi_dlopen = ffi_instance ? PyObject_GetAttrString(ffi_instance, "dlopen") : NULL;
if (! ffi_dlopen)
{
fprintf(stderr, "Failed to retrieve method cffi.FFI().dlopen()\n");
return false;
}
python.decref.push_back(ffi_dlopen);
// Get handles for lib.load() and for the dynamic_dataset() UDF entry point
bool retval = false;
PyObject *dict = PyModule_GetDict(module);
PyObject *lib = dict ? PyDict_GetItemString(dict, "lib") : NULL;
PyObject *loadlib = lib ? PyObject_GetAttrString(lib, "load") : NULL;
PyObject *udf = dict ? PyDict_GetItemString(dict, "dynamic_dataset") : NULL;
if (! lib)
fprintf(stderr, "Failed to find symbol 'lib' in code object\n");
else if (! loadlib)
fprintf(stderr, "Failed to find symbol 'lib.load()' in code object\n");
else if (! udf)
fprintf(stderr, "Failed to find entry point 'dynamic_dataset()' in code object\n");
else if (! PyCallable_Check(loadlib))
fprintf(stderr, "Error: lib.load is not a callable function\n");
else if (! PyCallable_Check(udf))
fprintf(stderr, "Error: dynamic_dataset is not a callable function\n");
else
{
// lib.ffi = cffi.FFI()
if (PyObject_SetAttrString(lib, "ffi", ffi_instance) < 0)
{
fprintf(stderr, "Failed to initialize lib.ffi\n");
return false;
}
// lib.udflib = lib.ffi.dlopen(libpath)
PyObject *pyargs = PyTuple_New(1);
PyObject *pypath = Py_BuildValue("s", libpath.c_str());
PyTuple_SetItem(pyargs, 0, pypath);
PyObject *dlopen_ret = PyObject_CallObject(ffi_dlopen, pyargs);
python.decref.push_back(pyargs);
if (dlopen_ret)
{
python.decref.push_back(dlopen_ret);
if (PyObject_SetAttrString(lib, "udflib", dlopen_ret) < 0)
{
fprintf(stderr, "Failed to initialize lib.ffi\n");
return false;
}
}
// Execute the user-defined function
retval = executeUDF(loadlib, udf, libpath, rules);
if (retval == true)
{
// Update output HDF5 dataset with data from shared memory segment
memcpy(output_dataset.data, mm.mm, room_size);
}
}
return retval;
}
/* Coordinate the execution of the UDF under a separate process */
bool PythonBackend::executeUDF(
PyObject *loadlib,
PyObject *udf,
std::string libpath,
const json &rules)
{
/*
* Execute the user-defined-function under a separate process so that
* seccomp can kill it (if needed) without crashing the entire program
*
* Support for Windows is still experimental; there is no sandboxing as of
* yet, and the OS doesn't provide a fork()-like API with similar semantics.
* In that case we just let the UDF run in the same process space as the parent.
* Note that we define fork() as a no-op that returns 0 so we can reduce the
* amount of #ifdef blocks in the body of this function.
*/
bool retval = false;
pid_t pid = fork();
if (pid == 0)
{
bool ready = true;
#ifdef ENABLE_SANDBOX
if (rules.contains("sandbox") && rules["sandbox"].get<bool>() == true)
ready = os::initChildSandbox(libpath, rules);
#endif
if (ready)
{
// Run 'lib.load(libpath)' from udf_template_py
PyObject *pyargs = PyTuple_New(1);
PyObject *pypath = Py_BuildValue("s", libpath.c_str());
PyTuple_SetItem(pyargs, 0, pypath);
PyObject *loadret = PyObject_CallObject(loadlib, pyargs);
// Run 'dynamic_dataset()' defined by the user
PyObject *callret = PyObject_CallObject(udf, NULL);
if (! callret)
{
// Function call terminated by an exception
PyErr_Print();
PyErr_Clear();
ready = false;
}
Py_XDECREF(loadret);
Py_XDECREF(callret);
Py_XDECREF(pyargs);
// Flush stdout buffer so we don't miss any messages echoed by the UDF
fflush(stdout);
}
// Exit the process without invoking any callbacks registered with atexit()
if (os::isWindows()) { retval = ready; } else { _exit(ready ? 0 : 1); }
}
else if (pid > 0)
{
bool need_waitpid = true;
#ifdef ENABLE_SANDBOX
if (rules.contains("sandbox") && rules["sandbox"].get<bool>() == true)
{
retval = os::initParentSandbox(libpath, rules, pid);
need_waitpid = false;
}
#endif
if (need_waitpid)
{
int status;
waitpid(pid, &status, 0);
retval = WIFEXITED(status) ? WEXITSTATUS(status) == 0 : false;
}
}
return retval;
}
/* Scan the UDF file for references to HDF5 dataset names */
std::vector<std::string> PythonBackend::udfDatasetNames(std::string udf_file)
{
std::string input;
std::ifstream data(udf_file, std::ifstream::binary);
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(data), {});
input.assign(buffer.begin(), buffer.end());
std::string line;
std::istringstream iss(input);
std::vector<std::string> output;
auto ltrim = [](std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
};
while (std::getline(iss, line))
{
ltrim(line);
auto n = line.find("lib.getData");
auto c = line.find("#");
if (n != std::string::npos && (c == std::string::npos || c > n))
{
auto start = line.substr(n).find_first_of("\"");
auto end = line.substr(n+start+1).find_first_of("\"");
if (start == std::string::npos && end == std::string::npos)
{
start = line.substr(n).find_first_of("'");
end = line.substr(n+start+1).find_first_of("'");
}
auto name = line.substr(n).substr(start+1, end);
output.push_back(name);
}
}
return output;
}
// Create a textual declaration of a struct given a compound map
std::string PythonBackend::compoundToStruct(const DatasetInfo &info, bool hardcoded_name)
{
// Python's CFFI cdef() does not recognize packing attributes
// such as __attribute__((pack)) or #pragma pack. Rather, it
// provides a special argument 'packed=True' that instructs
// the parser to align all structure fields at a byte boundary.
// Packing is needed so that UDFs can iterate over the binary
// data retrieved by H5Dread() with just a struct pointer.
std::string cstruct = "struct " + sanitizedName(info.name) + "_t {\n";
ssize_t current_offset = 0, pad = 0;
for (auto &member: info.members)
{
if (member.offset > current_offset)
{
auto size = member.offset - current_offset;
cstruct += " char _pad" + std::to_string(pad++) +"["+ std::to_string(size) +"];\n";
}
current_offset = member.offset + member.size;
cstruct += " " + member.type + " " + (hardcoded_name ? "value" : sanitizedName(member.name));
if (member.is_char_array)
cstruct += "[" + std::to_string(member.size) + "]";
cstruct += ";\n";
}
cstruct += "};\n";
return cstruct;
}
| 33.939655 | 102 | 0.606706 | [
"object",
"vector"
] |
4e1bd6cc7db8c22848f0872c6b927a6b1494da2f | 2,239 | cpp | C++ | atcoder/past/past002/g.cpp | zaurus-yusya/atcoder | 5fc345b3da50222fa1366d1ce52ae58799488cef | [
"MIT"
] | 3 | 2020-05-27T16:27:12.000Z | 2021-01-27T12:47:12.000Z | atcoder/past/past002/g.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | atcoder/past/past002/g.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
#define rep(i,n) for(ll i=0;i<(n);i++)
#define repr(i,n) for(ll i=(n-1);i>=0;i--)
#define all(x) x.begin(),x.end()
#define br cout << "\n";
using namespace std;
const int INF = 1e9;
const int MOD = 1e9+7;
using Graph = vector<vector<ll>>;
template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;}
// 0 false, 1 true
// string to int : -48
// ceil(a) 1.2->2.0
// c++17 g++ -std=c++17 a.cpp
int main() {
std::cout << std::fixed << std::setprecision(15);
ll q;
cin >> q;
deque<pair<char,ll>> deq;
rep(i,q){
ll t;
cin >> t;
if(t == 1){
char c;
ll x;
cin >> c >> x;
//deq.push_back(make_pair(c, x));
if(!deq.empty()){
char b = deq.back().first;
ll num = deq.back().second;
if(b == c){
deq.pop_back();
deq.push_back({c,x+num});
}else{
deq.push_back({c,x});
}
}else{
deq.push_back({c,x});
}
}else{
ll d;
ll ans = 0;
cin >> d;
if(deq.empty()){
cout << 0 << endl;
}else{
map<char, ll> mp;
while(!deq.empty()){
char now = deq.front().first;
ll num = deq.front().second;
deq.pop_front();
if(num > d){
mp[now] += d;
deq.push_front({now,num-d});
break;
}else if(num == d){
mp[now] += d;
break;
}else{
mp[now] += num;
d = d - num;
}
}
for(auto i: mp){
ans += i.second*i.second;
}
cout << ans << endl;
}
}
}
} | 26.654762 | 95 | 0.367575 | [
"vector"
] |
4e258dbf03ed4c554b468540ffce3604c24dbd94 | 20,869 | inl | C++ | libpoisson/poisson_screened/MultiGridOctreeData.WeightedSamples.inl | janm31415/PoissonRecon | e3b1c743577670bd1437cf527129d5eb6c5be4e9 | [
"MIT"
] | null | null | null | libpoisson/poisson_screened/MultiGridOctreeData.WeightedSamples.inl | janm31415/PoissonRecon | e3b1c743577670bd1437cf527129d5eb6c5be4e9 | [
"MIT"
] | null | null | null | libpoisson/poisson_screened/MultiGridOctreeData.WeightedSamples.inl | janm31415/PoissonRecon | e3b1c743577670bd1437cf527129d5eb6c5be4e9 | [
"MIT"
] | 1 | 2022-03-14T06:47:24.000Z | 2022-03-14T06:47:24.000Z | /*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the Johns Hopkins University nor the names of its contributors
may be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/
namespace libpoisson
{
// evaluate the result of splatting along a plane and then evaluating at a point on the plane.
template< int Degree > double GetScaleValue( void )
{
double centerValues[Degree+1];
Polynomial< Degree >::BSplineComponentValues( 0.5 , centerValues );
double scaleValue = 0;
for( int i=0 ; i<=Degree ; i++ ) scaleValue += centerValues[i] * centerValues[i];
return 1./ scaleValue;
}
template< class Real >
template< int WeightDegree >
void Octree< Real >::_addWeightContribution( DensityEstimator< WeightDegree >& densityWeights , TreeOctNode* node , Point3D< Real > position , PointSupportKey< WeightDegree >& weightKey , Real weight )
{
static const double ScaleValue = GetScaleValue< WeightDegree >();
double dx[ DIMENSION ][ PointSupportKey< WeightDegree >::Size ];
typename TreeOctNode::Neighbors< PointSupportKey< WeightDegree >::Size >& neighbors = weightKey.template getNeighbors< true >( node , _NodeInitializer );
densityWeights.reserve( NodeCount() );
Point3D< Real > start;
Real w;
_startAndWidth( node , start , w );
for( int dim=0 ; dim<DIMENSION ; dim++ ) Polynomial< WeightDegree >::BSplineComponentValues( ( position[dim]-start[dim] ) / w , dx[dim] );
weight *= (Real)ScaleValue;
for( int i=0 ; i<PointSupportKey< WeightDegree >::Size ; i++ ) for( int j=0 ; j<PointSupportKey< WeightDegree >::Size ; j++ )
{
double dxdy = dx[0][i] * dx[1][j] * weight;
TreeOctNode** _neighbors = neighbors.neighbors[i][j];
for( int k=0 ; k<PointSupportKey< WeightDegree >::Size ; k++ ) if( _neighbors[k] ) densityWeights[ _neighbors[k] ] += Real( dxdy * dx[2][k] );
}
}
template< class Real >
template< int WeightDegree , class PointSupportKey >
Real Octree< Real >::_getSamplesPerNode( const DensityEstimator< WeightDegree >& densityWeights , const TreeOctNode* node , Point3D< Real > position , PointSupportKey& weightKey ) const
{
Real weight = 0;
double dx[ DIMENSION ][ PointSupportKey::Size ];
const typename PointSupportKey::template Neighbors< PointSupportKey::Size >& neighbors = weightKey.getNeighbors( node );
Point3D< Real > start;
Real w;
_startAndWidth( node , start , w );
for( int dim=0 ; dim<DIMENSION ; dim++ ) Polynomial< WeightDegree >::BSplineComponentValues( ( position[dim]-start[dim] ) / w , dx[dim] );
for( int i=0 ; i<PointSupportKey::Size ; i++ ) for( int j=0 ; j<PointSupportKey::Size ; j++ )
{
double dxdy = dx[0][i] * dx[1][j];
for( int k=0 ; k<PointSupportKey::Size ; k++ ) if( neighbors.neighbors[i][j][k] )
{
const Real* w = densityWeights( neighbors.neighbors[i][j][k] );
if( w ) weight += Real( dxdy * dx[2][k] * (*w) );
}
}
return weight;
}
template< class Real >
template< int WeightDegree , class PointSupportKey >
void Octree< Real >::_getSampleDepthAndWeight( const DensityEstimator< WeightDegree >& densityWeights , const TreeOctNode* node , Point3D< Real > position , PointSupportKey& weightKey , Real& depth , Real& weight ) const
{
const TreeOctNode* temp = node;
while( _localDepth( temp )>densityWeights.kernelDepth() ) temp = temp->parent;
weight = _getSamplesPerNode( densityWeights , temp , position , weightKey );
if( weight>=(Real)1. ) depth = Real( _localDepth( temp ) + log( weight ) / log(double(1<<(DIMENSION-1))) );
else
{
Real oldWeight , newWeight;
oldWeight = newWeight = weight;
while( newWeight<(Real)1. && temp->parent )
{
temp=temp->parent;
oldWeight = newWeight;
newWeight = _getSamplesPerNode( densityWeights , temp , position , weightKey );
}
depth = Real( _localDepth( temp ) + log( newWeight ) / log( newWeight / oldWeight ) );
}
weight = Real( pow( double(1<<(DIMENSION-1)) , -double(depth) ) );
}
template< class Real >
template< int WeightDegree , class PointSupportKey >
void Octree< Real >::_getSampleDepthAndWeight( const DensityEstimator< WeightDegree >& densityWeights , Point3D< Real > position , PointSupportKey& weightKey , Real& depth , Real& weight ) const
{
TreeOctNode* temp;
Point3D< Real > myCenter( (Real)0.5 , (Real)0.5 , (Real)0.5 );
Real myWidth = Real( 1. );
// Get the finest node with depth less than or equal to the splat depth that contains the point
temp = _spaceRoot;
while( _localDepth( temp )<densityWeights.kernelDepth() )
{
if( !IsActiveNode( temp->children ) ) break;// fprintf( stderr , "[ERROR] Octree::GetSampleDepthAndWeight\n" ) , exit( 0 );
int cIndex = TreeOctNode::CornerIndex( myCenter , position );
temp = temp->children + cIndex;
myWidth /= 2;
if( cIndex&1 ) myCenter[0] += myWidth/2;
else myCenter[0] -= myWidth/2;
if( cIndex&2 ) myCenter[1] += myWidth/2;
else myCenter[1] -= myWidth/2;
if( cIndex&4 ) myCenter[2] += myWidth/2;
else myCenter[2] -= myWidth/2;
}
return _getSampleDepthAndWeight( densityWeights , temp , position , weightKey , depth , weight );
}
template< class Real >
template< bool CreateNodes , int DataDegree , class V >
void Octree< Real >::_splatPointData( TreeOctNode* node , Point3D< Real > position , V v , SparseNodeData< V , DataDegree >& dataInfo , PointSupportKey< DataDegree >& dataKey )
{
double dx[ DIMENSION ][ PointSupportKey< DataDegree >::Size ];
typename TreeOctNode::Neighbors< PointSupportKey< DataDegree >::Size >& neighbors = dataKey.template getNeighbors< CreateNodes >( node , _NodeInitializer );
Point3D< Real > start;
Real w;
_startAndWidth( node , start , w );
for( int dd=0 ; dd<DIMENSION ; dd++ ) Polynomial< DataDegree >::BSplineComponentValues( ( position[dd]-start[dd] ) / w , dx[dd] );
for( int i=0 ; i<PointSupportKey< DataDegree >::Size ; i++ ) for( int j=0 ; j<PointSupportKey< DataDegree >::Size ; j++ )
{
double dxdy = dx[0][i] * dx[1][j];
for( int k=0 ; k<PointSupportKey< DataDegree >::Size ; k++ )
if( IsActiveNode( neighbors.neighbors[i][j][k] ) )
{
TreeOctNode* _node = neighbors.neighbors[i][j][k];
double dxdydz = dxdy * dx[2][k];
dataInfo[ _node ] += v * (Real)dxdydz;
}
}
}
template< class Real >
template< bool CreateNodes , int WeightDegree , int DataDegree , class V >
Real Octree< Real >::_splatPointData( const DensityEstimator< WeightDegree >& densityWeights , Point3D< Real > position , V v , SparseNodeData< V , DataDegree >& dataInfo , PointSupportKey< WeightDegree >& weightKey , PointSupportKey< DataDegree >& dataKey , LocalDepth minDepth , LocalDepth maxDepth , int dim )
{
double dx;
V _v;
TreeOctNode* temp;
int cnt=0;
double width;
Point3D< Real > myCenter( (Real)0.5 , (Real)0.5 , (Real)0.5 );
Real myWidth = (Real)1.;
temp = _spaceRoot;
while( _localDepth( temp )<densityWeights.kernelDepth() )
{
if( !IsActiveNode( temp->children ) ) break;
int cIndex = TreeOctNode::CornerIndex( myCenter , position );
temp = temp->children + cIndex;
myWidth /= 2;
if( cIndex&1 ) myCenter[0] += myWidth/2;
else myCenter[0] -= myWidth/2;
if( cIndex&2 ) myCenter[1] += myWidth/2;
else myCenter[1] -= myWidth/2;
if( cIndex&4 ) myCenter[2] += myWidth/2;
else myCenter[2] -= myWidth/2;
}
Real weight , depth;
_getSampleDepthAndWeight( densityWeights , temp , position , weightKey , depth , weight );
if( depth<minDepth ) depth = Real(minDepth);
if( depth>maxDepth ) depth = Real(maxDepth);
int topDepth = int(ceil(depth));
dx = 1.0-(topDepth-depth);
if ( topDepth<=minDepth ) topDepth = minDepth , dx = 1;
else if( topDepth> maxDepth ) topDepth = maxDepth , dx = 1;
while( _localDepth( temp )>topDepth ) temp=temp->parent;
while( _localDepth( temp )<topDepth )
{
if( !temp->children ) temp->initChildren( _NodeInitializer );
int cIndex = TreeOctNode::CornerIndex( myCenter , position );
temp = &temp->children[cIndex];
myWidth/=2;
if( cIndex&1 ) myCenter[0] += myWidth/2;
else myCenter[0] -= myWidth/2;
if( cIndex&2 ) myCenter[1] += myWidth/2;
else myCenter[1] -= myWidth/2;
if( cIndex&4 ) myCenter[2] += myWidth/2;
else myCenter[2] -= myWidth/2;
}
width = 1.0 / ( 1<<_localDepth( temp ) );
_v = v * weight / Real( pow( width , dim ) ) * Real( dx );
_splatPointData< CreateNodes >( temp , position , _v , dataInfo , dataKey );
if( fabs(1.0-dx) > EPSILON )
{
dx = Real(1.0-dx);
temp = temp->parent;
width = 1.0 / ( 1<<_localDepth( temp ) );
_v = v * weight / Real( pow( width , dim ) ) * Real( dx );
_splatPointData< CreateNodes >( temp , position , _v , dataInfo , dataKey );
}
return weight;
}
template< class Real >
template< bool CreateNodes , int WeightDegree , int DataDegree , class V >
Real Octree< Real >::_multiSplatPointData( const DensityEstimator< WeightDegree >* densityWeights , TreeOctNode* node , Point3D< Real > position , V v , SparseNodeData< V , DataDegree >& dataInfo , PointSupportKey< WeightDegree >& weightKey , PointSupportKey< DataDegree >& dataKey , int dim )
{
Real _depth , weight;
if( densityWeights ) _getSampleDepthAndWeight( *densityWeights , position , weightKey , _depth , weight );
else weight = (Real)1.;
V _v = v * weight;
double dx[ DIMENSION ][ PointSupportKey< DataDegree >::Size ];
dataKey.template getNeighbors< CreateNodes >( node , _NodeInitializer );
for( TreeOctNode* _node=node ; _localDepth( _node )>=0 ; _node=_node->parent )
{
V __v = _v * (Real)pow( 1<<_localDepth( _node ) , dim );
Point3D< Real > start;
Real w;
_startAndWidth( _node , start , w );
for( int dd=0 ; dd<DIMENSION ; dd++ ) Polynomial< DataDegree >::BSplineComponentValues( ( position[dd]-start[dd] ) / w , dx[dd] );
typename TreeOctNode::Neighbors< PointSupportKey< DataDegree >::Size >& neighbors = dataKey.neighbors[ _localToGlobal( _localDepth( _node ) ) ];
for( int i=0 ; i<PointSupportKey< DataDegree >::Size ; i++ ) for( int j=0 ; j<PointSupportKey< DataDegree >::Size ; j++ )
{
double dxdy = dx[0][i] * dx[1][j];
for( int k=0 ; k<PointSupportKey< DataDegree >::Size ; k++ )
if( IsActiveNode( neighbors.neighbors[i][j][k] ) )
{
TreeOctNode* _node = neighbors.neighbors[i][j][k];
double dxdydz = dxdy * dx[2][k];
dataInfo[ _node ] += __v * (Real)dxdydz;
}
}
}
return weight;
}
template< class Real >
template< class V , int DataDegree , BoundaryType BType , class Coefficients >
V Octree< Real >::_evaluate( const Coefficients& coefficients , Point3D< Real > p , const BSplineData< DataDegree , BType >& bsData , const ConstPointSupportKey< DataDegree >& dataKey ) const
{
V value = V(0);
for( int d=_localToGlobal( 0 ) ; d<=dataKey.depth() ; d++ )
{
double dx[ DIMENSION ][ PointSupportKey< DataDegree >::Size ];
memset( dx , 0 , sizeof( double ) * DIMENSION * PointSupportKey< DataDegree >::Size );
{
const TreeOctNode* n = dataKey.neighbors[d].neighbors[ PointSupportKey< DataDegree >::LeftRadius ][ PointSupportKey< DataDegree >::LeftRadius ][ PointSupportKey< DataDegree >::LeftRadius ];
if( !n ) fprintf( stderr , "[ERROR] Point is not centered on a node\n" ) , exit( 0 );
int fIdx[3];
functionIndex< DataDegree , BType >( n , fIdx );
int fStart , fEnd;
BSplineData< DataDegree , BType >::FunctionSpan( _localDepth( n ) , fStart , fEnd );
for( int dd=0 ; dd<DIMENSION ; dd++ ) for( int i=-PointSupportKey< DataDegree >::LeftRadius ; i<=PointSupportKey< DataDegree >::RightRadius ; i++ )
if( fIdx[dd]+i>=fStart && fIdx[dd]+i<fEnd ) dx[dd][i] = bsData.baseBSplines[ fIdx[dd]+i ][ -i+PointSupportKey< DataDegree >::RightRadius ]( p[dd] );
}
for( int i=0 ; i<PointSupportKey< DataDegree >::Size ; i++ ) for( int j=0 ; j<PointSupportKey< DataDegree >::Size ; j++ ) for( int k=0 ; k<PointSupportKey< DataDegree >::Size ; k++ )
{
const TreeOctNode* n = dataKey.neighbors[d].neighbors[i][j][k];
if( isValidFEMNode< DataDegree , BType >( n ) )
{
const V* v = coefficients( n );
if( v ) value += (*v) * (Real) ( dx[0][i] * dx[1][j] * dx[2][k] );
}
}
}
return value;
}
template< class Real >
template< class V , int DataDegree , BoundaryType BType >
Pointer( V ) Octree< Real >::voxelEvaluate( const DenseNodeData< V , DataDegree >& coefficients , int& res , Real isoValue , LocalDepth depth , bool primal )
{
int begin , end , dim;
if( depth<=0 || depth>_maxDepth ) depth = _maxDepth;
// Initialize the coefficients at the coarsest level
Pointer( V ) _coefficients = NullPointer( V );
{
LocalDepth d = 0;
begin = _BSplineBegin< DataDegree , BType >( d ) , end = _BSplineEnd< DataDegree , BType >( d ) , dim = end - begin;
_coefficients = NewPointer< V >( dim * dim * dim );
memset( _coefficients , 0 , sizeof( V ) * dim * dim * dim );
#pragma omp parallel for num_threads( threads )
for( int i=_sNodesBegin(d) ; i<_sNodesEnd(d) ; i++ ) if( !_outOfBounds< DataDegree , BType >( _sNodes.treeNodes[i] ) )
{
LocalDepth _d ; LocalOffset _off;
_localDepthAndOffset( _sNodes.treeNodes[i] , _d , _off );
_off[0] -= begin , _off[1] -= begin , _off[2] -= begin;
_coefficients[ _off[0] + _off[1]*dim + _off[2]*dim*dim ] = coefficients[i];
}
}
// Up-sample and add in the existing coefficients
for( LocalDepth d=1 ; d<=depth ; d++ )
{
begin = _BSplineBegin< DataDegree , BType >( d ) , end = _BSplineEnd< DataDegree , BType >( d ) , dim = end - begin;
Pointer( V ) __coefficients = NewPointer< V >( dim * dim *dim );
memset( __coefficients , 0 , sizeof( V ) * dim * dim * dim );
#pragma omp parallel for num_threads( threads )
for( int i=_sNodesBegin(d) ; i<_sNodesEnd(d) ; i++ ) if( !_outOfBounds< DataDegree , BType >( _sNodes.treeNodes[i] ) )
{
LocalDepth _d ; LocalOffset _off;
_localDepthAndOffset( _sNodes.treeNodes[i] , _d , _off );
_off[0] -= begin , _off[1] -= begin , _off[2] -= begin;
__coefficients[ _off[0] + _off[1]*dim + _off[2]*dim*dim ] = coefficients[i];
}
_UpSample< V , DataDegree , BType >( d , ( ConstPointer(V) )_coefficients , __coefficients , threads );
DeletePointer( _coefficients );
_coefficients = __coefficients;
}
res = 1<<depth;
if( primal ) res++;
Pointer( V ) values = NewPointer< V >( res*res*res );
memset( values , 0 , sizeof(V)*res*res*res );
if( primal )
{
// evaluate at the cell corners
typename BSplineEvaluationData< DataDegree , BType >::CornerEvaluator::Evaluator evaluator;
BSplineEvaluationData< DataDegree , BType >::SetCornerEvaluator( evaluator , depth );
#pragma omp parallel for num_threads( threads )
for( int k=0 ; k<res ; k++ ) for( int j=0 ; j<res ; j++ ) for( int i=0 ; i<res ; i++ )
{
V value = values[ i + j*res + k*res*res ];
for( int kk=-BSplineSupportSizes< DataDegree >::CornerEnd ; kk<=-BSplineSupportSizes< DataDegree >::CornerStart ; kk++ ) if( k+kk>=begin && k+kk<end )
for( int jj=-BSplineSupportSizes< DataDegree >::CornerEnd ; jj<=-BSplineSupportSizes< DataDegree >::CornerStart ; jj++ ) if( j+jj>=begin && j+jj<end )
{
double weight = evaluator.value( k+kk , k , false ) * evaluator.value( j+jj , j , false );
int idx = (j+jj-begin)*dim + (k+kk-begin)*dim*dim;
for( int ii=-BSplineSupportSizes< DataDegree >::CornerEnd ; ii<=-BSplineSupportSizes< DataDegree >::CornerStart ; ii++ ) if( i+ii>=begin && i+ii<end )
value += _coefficients[ i + ii - begin + idx ] * Real( weight * evaluator.value( i + ii , i , false ) );
}
values[ i + j*res + k*res*res ] = value;
}
}
else
{
// evaluate at the cell centers
typename BSplineEvaluationData< DataDegree , BType >::CenterEvaluator::Evaluator evaluator;
BSplineEvaluationData< DataDegree , BType >::SetCenterEvaluator( evaluator , depth );
#pragma omp parallel for num_threads( threads )
for( int k=0 ; k<res ; k++ ) for( int j=0 ; j<res ; j++ ) for( int i=0 ; i<res ; i++ )
{
V& value = values[ i + j*res + k*res*res ];
for( int kk=-BSplineSupportSizes< DataDegree >::SupportEnd ; kk<=-BSplineSupportSizes< DataDegree >::SupportStart ; kk++ ) if( k+kk>=begin && k+kk<end )
for( int jj=-BSplineSupportSizes< DataDegree >::SupportEnd ; jj<=-BSplineSupportSizes< DataDegree >::SupportStart ; jj++ ) if( j+jj>=begin && j+jj<end )
{
double weight = evaluator.value( k+kk , k , false ) * evaluator.value( j+jj , j , false );
int idx = (j+jj-begin)*dim + (k+kk-begin)*dim*dim;
for( int ii=-BSplineSupportSizes< DataDegree >::SupportEnd ; ii<=-BSplineSupportSizes< DataDegree >::SupportStart ; ii++ ) if( i+ii>=begin && i+ii<end )
value += _coefficients[ i + ii - begin + idx ] * Real( weight * evaluator.value( i+ii , i , false ) );
}
}
}
memoryUsage();
DeletePointer( _coefficients );
for( int i=0 ; i<res*res*res ; i++ ) values[i] -= isoValue;
return values;
}
template< class Real >
template< int FEMDegree , BoundaryType BType >
SparseNodeData< Real , 0 > Octree< Real >::leafValues( const DenseNodeData< Real , FEMDegree >& coefficients ) const
{
SparseNodeData< Real , 0 > values;
DenseNodeData< Real , FEMDegree > _coefficients( _sNodesEnd(_maxDepth-1) );
memset( &_coefficients[0] , 0 , sizeof(Real)*_sNodesEnd(_maxDepth-1) );
for( int i=_sNodes.begin( _localToGlobal( 0 ) ) ; i<_sNodesEnd(_maxDepth-1) ; i++ ) _coefficients[i] = coefficients[i];
for( LocalDepth d=1 ; d<_maxDepth ; d++ ) _upSample( d , _coefficients );
for( LocalDepth d=_maxDepth ; d>=0 ; d-- )
{
_Evaluator< FEMDegree , BType > evaluator;
evaluator.set( d );
std::vector< ConstPointSupportKey< FEMDegree > > neighborKeys( std::max< int >( 1 , threads ) );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d ) );
for( int i=_sNodesBegin(d) ; i<_sNodesEnd(d) ; i++ ) if( _isValidSpaceNode( _sNodes.treeNodes[i] ) )
{
ConstPointSupportKey< FEMDegree >& neighborKey = neighborKeys[ omp_get_thread_num() ];
TreeOctNode* node = _sNodes.treeNodes[i];
if( !IsActiveNode( node->children ) )
{
neighborKey.getNeighbors( node );
bool isInterior = _IsInteriorlySupported< FEMDegree >( node->parent );
values[ node ] = _getCenterValue( neighborKey , node , coefficients , _coefficients , evaluator , isInterior );
}
}
}
return values;
}
template< class Real >
template< int FEMDegree , BoundaryType BType >
SparseNodeData< Point3D< Real > , 0 > Octree< Real >::leafGradients( const DenseNodeData< Real , FEMDegree >& coefficients ) const
{
SparseNodeData< Point3D< Real > , 0 > gradients;
DenseNodeData< Real , FEMDegree > _coefficients( _sNodesEnd(_maxDepth-1 ) );
memset( &_coefficients[0] , 0 , sizeof(Real)*_sNodesEnd(_maxDepth-1) );
for( int i=_sNodesBegin(0) ; i<_sNodesEnd(_maxDepth-1) ; i++ ) _coefficients[i] = coefficients[i];
for( LocalDepth d=1 ; d<_maxDepth ; d++ ) _upSample( d , _coefficients );
for( LocalDepth d=_maxDepth ; d>=0 ; d-- )
{
_Evaluator< FEMDegree , BType > evaluator;
evaluator.set( d );
std::vector< ConstPointSupportKey< FEMDegree > > neighborKeys( std::max< int >( 1 , threads ) );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d ) );
for( int i=_sNodesBegin(d) ; i<_sNodesEnd(d) ; i++ ) if( _isValidSpaceNode( _sNodes.treeNodes[i] ) )
{
ConstPointSupportKey< FEMDegree >& neighborKey = neighborKeys[ omp_get_thread_num() ];
TreeOctNode* node = _sNodes.treeNodes[i];
if( !IsActiveNode( node->children ) )
{
neighborKey.getNeighbors( node );
bool isInterior = _IsInteriorlySupported< FEMDegree >( node->parent );
gradients[ node ] = _getCenterValueAndGradient( neighborKey , node , coefficients , _coefficients , evaluator , isInterior ).second;
}
}
}
return gradients;
}
}
| 46.79148 | 312 | 0.679429 | [
"vector"
] |
4e260fd5ee1279d8cb4a9fb413434a9f66901f03 | 6,151 | cpp | C++ | libwfs/RequestParameterMap.cpp | nakkim/smartmet-plugin-wfs | 851334dd3be1a24b9708f66696f088fdc857a999 | [
"MIT"
] | null | null | null | libwfs/RequestParameterMap.cpp | nakkim/smartmet-plugin-wfs | 851334dd3be1a24b9708f66696f088fdc857a999 | [
"MIT"
] | 2 | 2018-04-17T10:02:46.000Z | 2019-10-21T08:57:55.000Z | libwfs/RequestParameterMap.cpp | nakkim/smartmet-plugin-wfs | 851334dd3be1a24b9708f66696f088fdc857a999 | [
"MIT"
] | 2 | 2017-05-10T12:03:51.000Z | 2021-07-06T07:05:25.000Z | #include "RequestParameterMap.h"
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <macgyver/Exception.h>
#include <algorithm>
namespace bw = SmartMet::Plugin::WFS;
bw::RequestParameterMap::RequestParameterMap() : params() {}
bw::RequestParameterMap::RequestParameterMap(
const std::multimap<std::string, SmartMet::Spine::Value>& params)
: params(params)
{
}
bw::RequestParameterMap::~RequestParameterMap() {}
void bw::RequestParameterMap::clear()
{
try
{
params.clear();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::size_t bw::RequestParameterMap::size() const
{
try
{
return params.size();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::size_t bw::RequestParameterMap::count(const std::string& name) const
{
try
{
return params.count(name);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void bw::RequestParameterMap::insert_value(const std::string& name,
const SmartMet::Spine::Value& value)
{
try
{
params.insert(std::make_pair(name, value));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::set<std::string> bw::RequestParameterMap::get_keys() const
{
try
{
std::set<std::string> result;
std::transform(params.begin(),
params.end(),
std::inserter(result, result.begin()),
boost::bind(&std::pair<const std::string, SmartMet::Spine::Value>::first, ::_1));
return result;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::vector<SmartMet::Spine::Value> bw::RequestParameterMap::get_values(
const std::string& name) const
{
try
{
std::vector<SmartMet::Spine::Value> result;
auto range = params.equal_range(name);
std::transform(
range.first,
range.second,
std::back_inserter(result),
boost::bind(&std::pair<const std::string, SmartMet::Spine::Value>::second, ::_1));
return result;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void bw::RequestParameterMap::dump_params(CTPP::CDT& hash) const
{
try
{
const auto keys = get_keys();
for (auto it1 = keys.begin(); it1 != keys.end(); ++it1)
{
int ind = 0;
const std::string& key = *it1;
auto range = params.equal_range(key);
for (auto it2 = range.first; it2 != range.second; ++it2)
{
const auto str = it2->second.to_string();
hash[key][ind++] = str;
}
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void bw::RequestParameterMap::remove(const std::string& name)
{
try
{
params.erase(name);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::string bw::RequestParameterMap::as_string() const
{
try
{
const auto keys = get_keys();
std::ostringstream output;
output << "(PARAMETERS";
BOOST_FOREACH (const auto& key, keys)
{
output << " (" << key;
auto range = params.equal_range(key);
for (auto map_it = range.first; map_it != range.second; ++map_it)
{
output << " " << map_it->second;
}
output << ')';
}
output << ')';
return output.str();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::string bw::RequestParameterMap::subst(const std::string& input) const
{
try
{
std::ostringstream result;
bool fail = false;
const char* src = input.c_str();
while (*src and not fail)
{
if (src[0] == '\\')
{
if (not src[1])
{
throw Fmi::Exception(BCP, "Unexpected end of source string '" + input + "'!");
}
result << src[1];
src += 2;
}
else if (src[0] == '$')
{
bool is_optional = false;
bool is_array = false;
if (src[1] != '{')
{
throw Fmi::Exception(BCP, "Missing '{' after '$' in '" + input + "'!");
}
src += 2;
if (*src == '?')
{
is_optional = true;
src++;
}
else if (*src == '*')
{
is_array = true;
src++;
}
const char* name = src;
while (std::isalnum(*src) or *src == '_')
{
src++;
}
if (*src != '}')
{
throw Fmi::Exception(
BCP, "Invalid parameter name after '${' or closing '}' missing in '" + input + "'!");
}
const std::string ref_name(name, src);
src++;
std::vector<SmartMet::Spine::Value> data;
auto range = params.equal_range(ref_name);
std::transform(
range.first,
range.second,
std::back_inserter(data),
boost::bind(&std::pair<const std::string, SmartMet::Spine::Value>::second, ::_1));
if (is_array)
{
std::string sep = "";
for (auto it = data.begin(); it != data.end(); ++it)
{
result << sep << it->to_string();
sep = ",";
}
}
else
{
if (data.size() > 1)
{
std::ostringstream msg;
msg << "Too many (" << data.size() << ") values of"
<< " '" << ref_name << "' in '" << input << "'";
throw Fmi::Exception(BCP, msg.str());
}
if (not is_optional and data.empty())
{
std::ostringstream msg;
msg << ": mandatory value of '" << ref_name << "' missing"
<< " in '" << input << "'";
throw Fmi::Exception(BCP, msg.str());
}
if (not data.empty())
{
result << data.begin()->to_string();
}
}
}
else
{
result << *src++;
}
}
return result.str();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
| 22.125899 | 100 | 0.513738 | [
"vector",
"transform"
] |
89ed6fa725baecb44cf048deb239330a881f00a2 | 1,907 | cpp | C++ | uva/10801.cpp | larc/competitive_programming | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | 1 | 2019-05-23T19:05:39.000Z | 2019-05-23T19:05:39.000Z | uva/10801.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | uva/10801.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <sstream>
#define E 5 // elevators
#define N 100 // floors
struct floor_t
{
int e, n; // elevator, floor
unsigned int d; // distance
};
bool operator<(const floor_t & a, const floor_t & b)
{
return a.d > b.d;
}
unsigned int T[E];
int G[E][N][2];
unsigned int dist[E][N];
bool visited[E][N];
bool stop(const int & e, const int & n)
{
return G[e][n][0] >= 0 || G[e][n][1] >= 0;
}
void relax(const int & e, const int & n, const int & fe, const int & fn, std::priority_queue<floor_t> & q)
{
if(fn < 0) return;
if(!stop(fe, fn)) return;
if(visited[fe][fn]) return;
unsigned int d = dist[e][n];
if(e == fe) d += T[e] * abs(fn - n);
else d += 60;
if(d < dist[fe][fn])
{
dist[fe][fn] = d;
q.push({fe, fn, d});
}
}
unsigned int dijkstra(const int & k)
{
memset(visited, 0, sizeof(visited));
memset(dist, -1, sizeof(dist));
std::priority_queue<floor_t> q;
int n, e, fe;
for(e = 0; e < E; ++e)
if(stop(e, 0))
{
dist[e][0] = 0;
q.push({e, 0, 0});
}
unsigned int d;
while(!q.empty())
{
e = q.top().e;
n = q.top().n;
q.pop();
if(!visited[e][n])
{
visited[e][n] = 1;
if(n == k) return dist[e][n];
relax(e, n, e, G[e][n][0], q);
relax(e, n, e, G[e][n][1], q);
for(int fe = 0; fe < E; ++fe)
relax(e, n, fe, n, q);
}
}
return -1;
}
int main()
{
int n, k, u, v;
char line[256];
std::stringstream ss;
unsigned int d;
while(scanf("%d %d", &n, &k) != EOF)
{
memset(G, -1, sizeof(G));
for(int i = 0; i < n; ++i)
scanf("%u", T + i);
getchar();
for(int i = 0; i < n; ++i)
{
fgets(line, sizeof(line), stdin);
ss.clear();
ss << line;
ss >> u;
while(ss >> v)
{
G[i][u][1] = v;
G[i][v][0] = u;
u = v;
}
}
d = dijkstra(k);
if(d < -1) printf("%u\n", d);
else printf("IMPOSSIBLE\n");
}
return 0;
}
| 15.379032 | 106 | 0.515994 | [
"vector"
] |
89fcc5d9d5e0ac362d3e7d89fd16851f14c0789b | 962 | cpp | C++ | 645_find_error_nums/find_error_nums.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | 645_find_error_nums/find_error_nums.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | 645_find_error_nums/find_error_nums.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | /*
* @Date: 2021-07-04 10:22:59
* @Author: Mengsen Wang
* @LastEditors: Mengsen Wang
* @LastEditTime: 2021-07-04 12:29:44
*/
#include <cassert>
#include <vector>
using namespace std;
vector<int> findErrorNums(vector<int>& nums) {
int n = nums.size();
int xorSum = 0;
for (int num : nums) xorSum ^= num;
for (int i = 1; i <= n; i++) xorSum ^= i;
int lowbit = xorSum & (-xorSum);
int num1 = 0, num2 = 0;
for (int& num : nums)
if ((num & lowbit) == 0)
num1 ^= num;
else
num2 ^= num;
for (int i = 1; i <= n; i++)
if ((i & lowbit) == 0)
num1 ^= i;
else
num2 ^= i;
for (int num : nums)
if (num == num1) return vector<int>{num1, num2};
return vector<int>{num2, num1};
}
int main() {
{
vector<int> nums{1, 2, 2, 4};
assert(findErrorNums(nums) == std::move(vector<int>{2, 3}));
}
{
vector<int> nums{1, 1};
assert(findErrorNums(nums) == std::move(vector<int>{1, 2}));
}
} | 20.041667 | 64 | 0.545738 | [
"vector"
] |
d60b2c9c9f41770ca26787cbb9d072863525fcaa | 6,264 | cpp | C++ | clang/lib/cpp_lowering/ConstructorLowering.cpp | compiler-tree-technologies/cil | 195acc33e14715da9f5a1746b489814d56c015f7 | [
"BSD-2-Clause"
] | 21 | 2021-02-08T15:42:18.000Z | 2022-02-23T03:25:10.000Z | clang/lib/cpp_lowering/ConstructorLowering.cpp | compiler-tree-technologies/cil | 195acc33e14715da9f5a1746b489814d56c015f7 | [
"BSD-2-Clause"
] | 3 | 2021-02-20T14:24:45.000Z | 2021-08-04T04:20:05.000Z | clang/lib/cpp_lowering/ConstructorLowering.cpp | compiler-tree-technologies/cil | 195acc33e14715da9f5a1746b489814d56c015f7 | [
"BSD-2-Clause"
] | 6 | 2021-02-08T16:57:07.000Z | 2022-01-13T11:32:34.000Z | // Copyright (c) 2019, Compiler Tree Technologies Pvt Ltd.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===----------------------------------------------------------------------===//
// Pass to convert the constructor call as normal class member function call.
//===----------------------------------------------------------------------===//
#include "clang/cil/dialect/CIL/CILBuilder.h"
#include "clang/cil/dialect/CIL/CILOps.h"
#include "mlir/Dialect/AffineOps/AffineOps.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "llvm/ADT/Sequence.h"
#define PASS_NAME "ConstructorLowering"
#define DEBUG_TYPE PASS_NAME
// TODO: Add DEBUG WITH TYPE and STATISTIC
static constexpr const char *globalConstructorFnName = "__cxx_global_var_init";
using namespace mlir;
struct ConstructorLoweringPass : public ModulePass<ConstructorLoweringPass> {
private:
public:
virtual void runOnModule();
};
// Generates the loop depth same as array dimensions.
// Returns the array access op to the contained type.
static mlir::Value prepareLoopForArray(mlir::Value baseval,
CIL::ArrayType arrType,
CIL::CILBuilder &builder) {
auto shape = arrType.getShape();
assert(shape.size() == 1);
assert(arrType.hasStaticShape());
auto loc = baseval.getLoc();
auto lb = builder.getCILLongConstant(loc, 0);
auto ub = builder.getCILLongConstant(loc, shape[0]);
auto one = builder.getCILLongConstant(loc, 1);
auto forLoopOp = builder.create<CIL::ForLoopOp>(loc, lb, ub, one,
builder.getCILLongIntType());
builder.setInsertionPointToStart(forLoopOp.getBody());
baseval =
builder.create<CIL::CILArrayIndexOp>(loc, baseval, forLoopOp.getIndVar());
auto newArrType = arrType.getEleTy().dyn_cast<CIL::ArrayType>();
if (!newArrType)
return baseval;
return prepareLoopForArray(baseval, newArrType, builder);
}
static bool handleClassAlloca(CIL::AllocaOp op) {
auto constructRef = op.constructSym();
if (!constructRef.hasValue()) {
return true;
}
auto symRef = constructRef.getValue();
auto args = op.constructArgs();
llvm::SmallVector<mlir::Value, 2> argsList(args.begin(), args.end());
auto allocatedType = op.getAllocatedType();
CIL::CILBuilder builder(op.getContext());
builder.setInsertionPointAfter(op);
auto newAlloca =
builder.create<CIL::AllocaOp>(op.getLoc(), op.getName(), allocatedType);
auto baseValue = newAlloca.getResult();
if (auto arrType = allocatedType.dyn_cast<CIL::ArrayType>()) {
baseValue = prepareLoopForArray(baseValue, arrType, builder);
}
builder.create<CIL::MemberCallOp>(op.getLoc(), baseValue, symRef, llvm::None,
argsList);
op.replaceAllUsesWith(newAlloca.getResult());
op.erase();
return true;
}
static mlir::FuncOp getGlobalConstructorFunc(ModuleOp module) {
auto func = module.lookupSymbol<mlir::FuncOp>(globalConstructorFnName);
if (func) {
return func;
}
CIL::CILBuilder builder(module.getContext());
auto funcType = builder.getFunctionType({}, {});
func = mlir::FuncOp::create(builder.getUnknownLoc(), globalConstructorFnName,
funcType);
module.push_back(func);
auto block = func.addEntryBlock();
builder.setInsertionPointToStart(block);
builder.create<mlir::ReturnOp>(builder.getUnknownLoc());
// Create global ctor operation
builder.setInsertionPointToStart(module.getBody());
builder.create<CIL::GlobalCtorOp>(func.getLoc(),
builder.getSymbolRefAttr(func));
return func;
}
static void handleGlobalVariables(CIL::GlobalOp op) {
if (!op.constructSymAttr()) {
return;
}
auto symRef = op.constructSymAttr();
auto module = op.getParentOfType<mlir::ModuleOp>();
assert(module);
auto func = getGlobalConstructorFunc(module);
assert(func);
CIL::CILBuilder builder(op.getContext());
builder.setInsertionPoint(func.getBlocks().front().getTerminator());
auto addrOfOp = builder.create<CIL::GlobalAddressOfOp>(op.getLoc(), op);
builder.create<CIL::MemberCallOp>(
op.getLoc(), addrOfOp,
builder.getSymbolRefAttr(symRef.getRootReference()), llvm::None,
llvm::None);
Attribute val;
builder.setInsertionPoint(op);
builder.create<CIL::GlobalOp>(op.getLoc(), op.getType(), false, op.getName(),
val);
op.erase();
}
void ConstructorLoweringPass::runOnModule() {
auto module = getModule();
module.walk([&](mlir::Operation *op) {
if (auto alloca = dyn_cast<CIL::AllocaOp>(op)) {
handleClassAlloca(alloca);
return;
}
if (auto global = dyn_cast<CIL::GlobalOp>(op)) {
handleGlobalVariables(global);
return;
}
});
}
namespace CIL {
std::unique_ptr<mlir::Pass> createConstructorLoweringPass() {
return std::make_unique<ConstructorLoweringPass>();
}
} // namespace CIL | 37.963636 | 80 | 0.688538 | [
"shape"
] |
d612378c75d2051aa79a82876a90992948c0834d | 20,844 | cpp | C++ | src/atlas/graphics/Mesh.cpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 5 | 2018-12-13T03:41:12.000Z | 2020-08-27T04:45:11.000Z | src/atlas/graphics/Mesh.cpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 1 | 2020-09-08T07:26:59.000Z | 2020-09-08T09:21:44.000Z | src/atlas/graphics/Mesh.cpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 5 | 2018-12-20T10:31:09.000Z | 2021-09-07T07:38:49.000Z | #include "RenderingOptions.hpp"
#include "Mesh.hpp"
#include "Time.hpp"
#include "atlas/core/Math.hpp"
#include <glm/gtc/matrix_transform.hpp>
namespace atlas
{
namespace graphics
{
Mesh::Mesh(uint32_t vertexCount) :
vertexCount(vertexCount)
{
_vertices.resize(vertexCount);
_flags |= 1 << (uint32_t)NodeFlags::Drawable;
BubbleEvent(SceneGraphEvent::MeshAdded);
}
Mesh::~Mesh()
{
Renderer::device.destroyBuffer(buffer);
Renderer::device.freeMemory(bufferMemory);
Renderer::device.destroyBuffer(indices);
Renderer::device.freeMemory(indicesMemory);
BubbleEvent(SceneGraphEvent::MeshDeleted);
}
void Mesh::Draw(DrawContext context)
{
//_localTransform = glm::rotate(_localTransform, static_cast<float>(Time::dt * 0.4), glm::vec3(1, 0, 0));
//if (_currentPolygonMode != RenderingOptions::PolygonMode)
//{
// DestroyPipeline();
// CreatePipeline(_vertexShader.module, _fragmentShader.module);
//}
struct MVP mvp;
mvp.model = _transform;
mvp.view = context.viewMatrix;
mvp.proj = context.projectionMatrix;
vk::CommandBuffer cmdBuffer = context.cmdBuffer;
cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, _material->pipeline);
cmdBuffer.pushConstants(_material->pipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, sizeof(MVP), &mvp);
cmdBuffer.setLineWidth(_material->lineWidth);
//buffer.pushConstants(_material.pipelineLayout, vk::ShaderStageFlagBits::eVertex, sizeof(MVP), sizeof(glm::vec3), &_color);
//buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, _material.pipelineLayout, 0, 1, _descriptorSets.data(), 0, nullptr);
vk::DeviceSize offsets[] = { 0 };
cmdBuffer.bindVertexBuffers(0, 1, &buffer, offsets);
if (topology == vk::PrimitiveTopology::eTriangleList)
{
cmdBuffer.bindIndexBuffer(indices, 0, vk::IndexType::eUint16);
cmdBuffer.drawIndexed(indexCount, 1, 0, 0, 0);
}
else
{
cmdBuffer.draw(vertexCount, 1, 0, 0);
}
}
void Mesh::SendSignal(Signal signal)
{
if (signal == Signal::WindowResized)
{
//TODO
}
}
void Mesh::SetPositions(std::vector<glm::vec3> &data)
{
if (data.size() != _vertices.size())
{
throw std::runtime_error("invalid size of buffer");
}
for (size_t i = 0; i < _vertices.size(); ++i)
{
_vertices[i].position = data[i];
}
}
void Mesh::SetNormals(std::vector<glm::vec3>& data)
{
if (data.size() != _vertices.size())
{
throw std::runtime_error("invalid size of buffer");
}
for (size_t i = 0; i < _vertices.size(); ++i)
{
_vertices[i].normal = data[i];
}
}
void Mesh::SetUV(std::vector<glm::vec2>& data)
{
if (data.size() != _vertices.size())
{
throw std::runtime_error("invalid size of buffer");
}
for (size_t i = 0; i < _vertices.size(); ++i)
{
_vertices[i].uv = glm::packHalf2x16(data[i]);
}
}
void Mesh::Apply()
{
CreateBuffer(_vertices.data(), _vertices.size() * sizeof(Vertex), vk::BufferUsageFlagBits::eVertexBuffer, buffer, bufferMemory);
}
Mesh* Mesh::MakePoint(vec3 color, vec3 position)
{
Mesh* point = new Mesh(1);
point->_flags |= 1 << (uint32_t)NodeFlags::Debug;
point->topology = vk::PrimitiveTopology::ePointList;
std::vector<glm::vec3> positions{ position };
point->SetPositions(positions);
std::vector<glm::vec3> colors{ color };
point->SetNormals(colors);
point->Apply();
point->_material = std::make_shared<Material>(
"unlitPoint",
std::vector<Semantic>{Semantic::Position, Semantic::Color},
std::vector<Descriptor>(),
Shader::Get("unlit.vert"),
Shader::Get("unlit.frag"),
point->topology);
point->_material->lineWidth = 3;
return point;
}
Mesh* Mesh::MakeLine(vec3 color, vec3 start, vec3 end)
{
Mesh* line = new Mesh(2);
line->_flags |= 1 << (uint32_t)NodeFlags::Debug;
line->topology = vk::PrimitiveTopology::eLineList;
std::vector<glm::vec3> positions{ start, end };
line->SetPositions(positions);
std::vector<glm::vec3> colors{ color, color };
line->SetNormals(colors);
line->Apply();
line->_material = Material::Get("unlitLines");
return line;
}
Mesh * Mesh::MakeEquirectangularRegion(vec2 min, vec2 max)
{
std::vector<glm::vec3> positions
{
vec3(0, min.x, min.y),
vec3(0, min.x, max.y),
vec3(0, max.x, max.y),
vec3(0, max.x, min.y),
};
std::vector<glm::vec3> colors
{
Color::white,
Color::white,
Color::white,
Color::white
};
std::vector<uint16_t> indices
{
0,2,1,
0,3,2
};
Mesh* region = new Mesh(4);
region->topology = vk::PrimitiveTopology::eTriangleList;
region->_flags |= (uint32_t)NodeFlags::Compositing;
region->SetPositions(positions);
region->SetNormals(colors);
region->SetIndices(indices);
region->Apply();
region->_material = Material::Get("unlitTriangles");
return region;
}
Mesh* Mesh::MakePlane(vec3 color)
{
uint32_t subdivs = 20;
Mesh* plane = new Mesh((subdivs + 1) * 2 * 2);
plane->_flags |= 1 << (uint32_t)NodeFlags::Debug;
plane->topology = vk::PrimitiveTopology::eLineList;
std::vector<glm::vec3> positions;
std::vector<glm::vec3> colors;
for (uint32_t i = 0; i <= subdivs; i++)
{
float y = (i / (subdivs / 2.0f)) - 1;
vec3 start = vec3(-1, y, 0);
vec3 end = vec3(1, y, 0);
positions.push_back(start);
positions.push_back(end);
colors.push_back(color);
colors.push_back(color);
}
for (uint32_t i = 0; i <= subdivs; i++)
{
float x = (i / (subdivs / 2.0f)) - 1;
vec3 start = vec3(x, -1, 0);
vec3 end = vec3(x, 1, 0);
positions.push_back(start);
positions.push_back(end);
colors.push_back(color);
colors.push_back(color);
}
plane->SetPositions(positions);
plane->SetNormals(colors);
plane->Apply();
plane->_material = Material::Get("unlitLines");
return plane;
}
Mesh* Mesh::MakeParallel(vec3 color, double lat, Ellipsoid& ellipsoid)
{
std::vector<glm::vec3> positions;
std::vector<glm::vec3> colors;
double lonDelta = PI * 2 / 64;
for (size_t i = 0; i <= 64; i++)
{
double lon = (i * lonDelta) - PI;
auto xyz = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(xyz);
colors.push_back(color);
}
Mesh* parallel = new Mesh(static_cast<uint32_t>(positions.size()));
parallel->_flags |= 1 << (uint32_t)NodeFlags::Debug;
parallel->topology = vk::PrimitiveTopology::eLineStrip;
parallel->SetPositions(positions);
parallel->SetNormals(colors);
parallel->Apply();
parallel->_material = Material::Get("unlitLineStrip");
return parallel;
}
Mesh* Mesh::MakeMeridian(vec3 color, double lon, Ellipsoid& ellipsoid)
{
std::vector<glm::vec3> positions;
std::vector<glm::vec3> colors;
double latDelta = PI / 64;
for (size_t i = 0; i <= 64; i++)
{
double lat = (i * latDelta) - PI / 2;
auto xyz = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(xyz);
colors.push_back(color);
}
Mesh* ellipse = new Mesh(static_cast<uint32_t>(positions.size()));
ellipse->_flags |= 1 << (uint32_t)NodeFlags::Debug;
ellipse->topology = vk::PrimitiveTopology::eLineStrip;
ellipse->SetPositions(positions);
ellipse->SetNormals(colors);
ellipse->Apply();
ellipse->_material = Material::Get("unlitLineStrip");
return ellipse;
}
Mesh* Mesh::MakeEllipsoid(vec3 color, uint32_t subdivs, Ellipsoid& ellipsoid)
{
std::vector<glm::vec3> positions;
std::vector<glm::vec3> colors;
double lonDelta, latDelta;
double lat, lon;
lonDelta = PI * 2 / subdivs;
latDelta = PI / 64;
// meridians
for (size_t i = 0; i < subdivs; i += 2)
{
lon = (i * lonDelta) - PI;
// meridians are drawn by pairs (m0, m1)
// m0 is drawn from the south pole to the north pole.
// m1 is drawn from the north pole to the south pole.
// This scheme enables using a single line strip to draw all
// meridians without visual artifacts.
for (int j = 0; j <= 64; j++)
{
lat = (j * latDelta) - PI / 2;
auto xyz = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(xyz);
colors.push_back(color);
}
lon = ((i + 1) * lonDelta) - PI;
for (int j = 64; j >= 0; j--)
{
lat = (j * latDelta) - PI / 2;
auto xyz = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(xyz);
colors.push_back(color);
}
}
lonDelta = PI * 2 / 64;
latDelta = PI / subdivs;
// parallels
for (size_t j = 0; j < subdivs; j++)
{
lat = (j * latDelta) - PI / 2;
for (size_t i = 0; i <= 64; i++)
{
lon = (i * lonDelta) - PI;
auto xyz = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(xyz);
colors.push_back(color);
}
}
Mesh* ellipse = new Mesh(static_cast<uint32_t>(positions.size()));
ellipse->_flags |= 1 << (uint32_t)NodeFlags::Debug;
ellipse->topology = vk::PrimitiveTopology::eLineStrip;
ellipse->SetPositions(positions);
ellipse->SetNormals(colors);
ellipse->Apply();
ellipse->_material = Material::Get("unlitLineStrip");
return ellipse;
}
Mesh* Mesh::MakeSolidEllipsoid(vec3 color, uint32_t subdivs, Ellipsoid& ellipsoid)
{
const double minX = 0;
const double maxX = PI * 2;
const double minY = -PI / 2;
const double maxY = PI / 2;
const uint16_t subdivX = subdivs * 2;
const uint16_t subdivY = subdivs;
const double xStep = (maxX - minX) / subdivX;
const double yStep = (maxY - minY) / subdivY;
const uint16_t vertexPerRow = subdivY + 1;
const uint16_t vertexPerCol = subdivX + 1;
const int size = vertexPerRow * vertexPerCol;
std::vector<glm::vec3> positions;
std::vector<glm::vec3> colors;
std::vector<uint16_t> indices;
positions.resize(size);
colors.resize(size);
int i = 0;
for (uint16_t row = 0; row < vertexPerRow; ++row)
{
uint16_t jww = row * vertexPerCol;
uint16_t j1ww = (row + 1) * vertexPerCol;
for (uint16_t col = 0; col < vertexPerCol; ++col)
{
double lat = minY + row * yStep;
double lon = minX + col * xStep;
positions[i] = Math::LatLonToECEF(lat, lon, ellipsoid);
colors[i] = color;
++i;
if (row < subdivY && col < subdivX)
{
uint16_t a = col + jww;
uint16_t b = (col + 1) + jww;
uint16_t c = (col + 1) + j1ww;
uint16_t d = col + j1ww;
indices.push_back(a);
indices.push_back(b);
indices.push_back(c);
indices.push_back(c);
indices.push_back(d);
indices.push_back(a);
}
}
}
Mesh* result = new Mesh(static_cast<uint32_t>(positions.size()));
result->SetPositions(positions);
result->SetNormals(colors);
result->SetIndices(indices);
result->topology = vk::PrimitiveTopology::eTriangleList;
result->Apply();
result->_flags |= 1 << (uint32_t)NodeFlags::Debug;
result->_material = Material::Get("unlitTriangles");
return result;
}
Mesh* Mesh::MakeRegion(vec3 color, vec2 min, vec2 max, Ellipsoid& ellipsoid)
{
const double minX = min.x;
const double maxX = max.x;
const double minY = min.y;
const double maxY = max.y;
std::vector<glm::vec3> positions;
std::vector<glm::vec3> colors;
uint32_t subdivs = 10;
double w = std::abs(max.x - min.x);
double h = std::abs(max.y - min.y);
// top edge
for (uint32_t i = 0; i < subdivs; i++)
{
double lat = max.y;
double lon = min.x + (w / subdivs) * i;
vec3 pos = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(pos);
colors.push_back(color);
}
// right edge
for (uint32_t i = 0; i < subdivs; i++)
{
double lon = max.x;
double lat = max.y - (h / subdivs) * i;
vec3 pos = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(pos);
colors.push_back(color);
}
// bottom edge
for (uint32_t i = 0; i < subdivs; i++)
{
double lon = max.x - (w / subdivs) * i;
double lat = min.y;
vec3 pos = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(pos);
colors.push_back(color);
}
// left edge
for (uint32_t i = 0; i <= subdivs; i++)
{
double lon = min.x;
double lat = min.y + (h / subdivs) * i;
vec3 pos = Math::LatLonToECEF(lat, lon, ellipsoid);
positions.push_back(pos);
colors.push_back(color);
}
Mesh* result = new Mesh(static_cast<uint32_t>(positions.size()));
result->SetPositions(positions);
result->SetNormals(colors);
result->topology = vk::PrimitiveTopology::eLineStrip;
result->Apply();
result->_flags |= 1 << (uint32_t)NodeFlags::Debug;
result->_material = Material::Get("unlitLineStrip");
return result;
}
Mesh* Mesh::MakeFrustum(vec3 color, mat4 direction, vec3 origin, float aspect, float fovRadians, float nearClip, float farClip)
{
std::vector<glm::vec3> colors;
vec3 axis_x = direction[0];
vec3 axis_y = direction[1];
vec3 axis_z = direction[2];
vec3 near_center = axis_z * nearClip;
vec3 far_center = axis_z * farClip;
float e0 = std::tanf(fovRadians * 0.5f);
float near_ext_y = e0 * nearClip;
float near_ext_x = near_ext_y * aspect;
float far_ext_y = e0 * farClip;
float far_ext_x = far_ext_y * aspect;
vec3 a = origin + (near_center - axis_x * near_ext_x - axis_y * near_ext_y);
vec3 b = origin + (near_center - axis_x * near_ext_x + axis_y * near_ext_y);
vec3 c = origin + (near_center + axis_x * near_ext_x + axis_y * near_ext_y);
vec3 d = origin + (near_center + axis_x * near_ext_x - axis_y * near_ext_y);
vec3 e = origin + (far_center - axis_x * far_ext_x - axis_y * far_ext_y);
vec3 f = origin + (far_center - axis_x * far_ext_x + axis_y * far_ext_y);
vec3 g = origin + (far_center + axis_x * far_ext_x + axis_y * far_ext_y);
vec3 h = origin + (far_center + axis_x * far_ext_x - axis_y * far_ext_y);
std::vector<glm::vec3> positions{
a,b,b,c,c,d,d,a,
e,f,f,g,g,h,h,e,
a,e,b,f,c,g,d,h
};
for (size_t i = 0; i < positions.size(); i++)
{
colors.push_back(color);
}
Mesh* result = new Mesh(static_cast<uint32_t>(positions.size()));
result->SetPositions(positions);
result->SetNormals(colors);
result->topology = vk::PrimitiveTopology::eLineList;
result->Apply();
result->_flags |= 1 << (uint32_t)NodeFlags::Debug;
result->_material = Material::Get("unlitLines");
return result;
}
void Mesh::SetIndices(std::vector<uint16_t>& data)
{
indexCount = static_cast<uint32_t>(data.size());
CreateBuffer(data.data(), data.size() * sizeof(uint16_t), vk::BufferUsageFlagBits::eIndexBuffer, indices, indicesMemory);
}
uint32_t FindMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties)
{
vk::PhysicalDeviceMemoryProperties memory = Renderer::gpu.getMemoryProperties();
for (uint32_t i = 0; i < memory.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memory.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("no memory type found");
}
void Mesh::CreateBuffer(void* data, size_t size, vk::BufferUsageFlags usage,
vk::Buffer& buf, vk::DeviceMemory& memory)
{
auto const info = vk::BufferCreateInfo()
.setSize(size)
.setUsage(usage)
.setSharingMode(vk::SharingMode::eExclusive);
auto result = Renderer::device.createBuffer(&info, nullptr, &buf);
CHECK_SUCCESS(result);
auto const reqs = Renderer::device.getBufferMemoryRequirements(buf);
auto const alloc = vk::MemoryAllocateInfo()
.setAllocationSize(reqs.size)
.setMemoryTypeIndex(
FindMemoryType(reqs.memoryTypeBits,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent));
void* tmp;
CHECK_SUCCESS(Renderer::device.allocateMemory(&alloc, nullptr, &memory));
Renderer::device.bindBufferMemory(buf, memory, 0);
CHECK_SUCCESS(Renderer::device.mapMemory(memory, 0, info.size, vk::MemoryMapFlags(), &tmp));
memcpy(tmp, data, static_cast<size_t>(info.size));
Renderer::device.unmapMemory(memory);
}
}
}
| 34.282895 | 142 | 0.498417 | [
"mesh",
"vector",
"model"
] |
d61a9e4a18ebd983d1659265f3043f647f98bd7c | 1,917 | cpp | C++ | leetcode/311.sparse-matrix-multiplication.cpp | geemaple/algorithm | 68bc5032e1ee52c22ef2f2e608053484c487af54 | [
"MIT"
] | 177 | 2017-08-21T08:57:43.000Z | 2020-06-22T03:44:22.000Z | leetcode/311.sparse-matrix-multiplication.cpp | geemaple/algorithm | 68bc5032e1ee52c22ef2f2e608053484c487af54 | [
"MIT"
] | 2 | 2018-09-06T13:39:12.000Z | 2019-06-03T02:54:45.000Z | leetcode/311.sparse-matrix-multiplication.cpp | geemaple/algorithm | 68bc5032e1ee52c22ef2f2e608053484c487af54 | [
"MIT"
] | 23 | 2017-08-23T06:01:28.000Z | 2020-04-20T03:17:36.000Z | class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
if (A.size() == 0 || B.size() == 0)
{
return vector<vector<int>>();
}
vector<vector<pair<int, int>>> sparseB(B.size(), vector<pair<int, int>>());
for (auto i = 0; i < B.size(); ++i)
{
for (auto j = 0; j < B[i].size(); ++j)
{
if (B[i][j] != 0){
sparseB[i].push_back(make_pair(j, B[i][j]));
}
}
}
int m = A.size();
int n = B[0].size();
vector<vector<int>> res(m, vector<int>(n, 0));
for (auto i = 0; i < m; ++i)
{
for (auto k = 0; k < A[i].size(); ++k)
{
if (A[i][k] != 0){
for (auto p = 0; p < sparseB[k].size(); ++p)
{
int j = sparseB[k][p].first;
int val = sparseB[k][p].second;
res[i][j] += A[i][k] * val;
}
}
}
}
return res;
}
};
class Solution2 {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
if (A.size() == 0 || B.size() == 0)
{
return vector<vector<int>>();
}
int m = A.size();
int n = B[0].size();
int t = A[0].size();
vector<vector<int>> res(m, vector<int>(n, 0));
for (auto i = 0; i < m; ++i)
{
for (auto j = 0; j < n; ++j)
{
for(auto k = 0; k < t; ++k)
{
res[i][j] += A[i][k] * B[k][j];
}
}
}
return res;
}
}; | 24.896104 | 83 | 0.3229 | [
"vector"
] |
d61dc42c029dadc7e501ef58910a01986a03ed26 | 5,590 | cpp | C++ | src/lua/Eigenfaces.cpp | dacap/loseface | 677f46b9da3e11be3b75e3a35f5ca3f1b8df6d52 | [
"MIT"
] | 2 | 2017-11-01T09:09:20.000Z | 2020-01-22T04:56:46.000Z | src/lua/Eigenfaces.cpp | dacap/loseface | 677f46b9da3e11be3b75e3a35f5ca3f1b8df6d52 | [
"MIT"
] | null | null | null | src/lua/Eigenfaces.cpp | dacap/loseface | 677f46b9da3e11be3b75e3a35f5ca3f1b8df6d52 | [
"MIT"
] | 1 | 2019-01-24T12:13:24.000Z | 2019-01-24T12:13:24.000Z | // Copyright (C) 2008-2010 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#include "lua/imglib.h"
#define LUAOBJ_EIGENFACES "Eigenfaces"
using namespace std;
using namespace imglib::details;
lua_Eigenfaces** imglib::details::toEigenfaces(lua_State* L, int pos)
{
return ((lua_Eigenfaces**)luaL_checkudata(L, pos, LUAOBJ_EIGENFACES));
}
static lua_Eigenfaces** neweigenfaces(lua_State* L)
{
lua_Eigenfaces** eig = (lua_Eigenfaces**)lua_newuserdata(L, sizeof(lua_Eigenfaces**));
*eig = new lua_Eigenfaces;
luaL_getmetatable(L, LUAOBJ_EIGENFACES);
lua_setmetatable(L, -2);
return eig;
}
static int eigenfaces__reserve(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (!eig)
return luaL_error(L, "No Eigenfaces user-data specified");
int size = 0;
if (lua_isnumber(L, 2))
size = lua_tonumber(L, 2);
if (size <= 0)
return luaL_error(L, "'size' argument expected with a value greater than zero");
(*eig)->reserve(size);
return 0;
}
static int eigenfaces__add_image(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (!eig)
return luaL_error(L, "No Eigenfaces user-data specified");
int n = lua_gettop(L); // number of arguments
for (int i=2; i<=n; ++i) {
lua_Image* img = *toImage(L, i); // get argument "i"
if (img) {
Vector imgVector;
imglib::details::image2vector(img, imgVector);
(*eig)->addImage(imgVector);
}
}
return 0;
}
static int eigenfaces__calculate_eigenfaces(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (!eig)
return luaL_error(L, "No Eigenfaces user-data specified");
luaL_checktype(L, 2, LUA_TTABLE);
size_t components = -1;
double variance = -1.0;
lua_getfield(L, 2, "components");
lua_getfield(L, 2, "variance");
if (lua_isstring(L, -1)) variance = lua_tonumber(L, -1);
if (lua_isstring(L, -2)) components = lua_tonumber(L, -2);
lua_pop(L, 2);
if (!(*eig)->calculateEigenvalues())
return luaL_error(L, "Error calculating eigenvalues/eigenvectors of covariance matrix");
if (variance > 0.0)
components = (*eig)->getNumComponentsFor(variance);
if (components < 1)
return luaL_error(L, "You have to specified the number of eigenfaces to create (at least 1)");
else if (components > (*eig)->getEigenvaluesCount()) {
char buf[1024];
std::sprintf(buf, "You have to specified a number of eigenfaces greater than %d",
(*eig)->getEigenvaluesCount());
return luaL_error(L, buf);
}
(*eig)->calculateEigenfaces(components);
lua_pushnumber(L, components);
return 1;
}
static int eigenfaces__save(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (!eig)
return luaL_error(L, "No Eigenfaces user-data specified");
string file;
if (lua_isstring(L, 2))
file = lua_tostring(L, 2);
else
return luaL_error(L, "File-name expected in Eigenfaces:save() as first argument");
(*eig)->save(file.c_str());
// TODO error
return 0;
}
static int eigenfaces__eigenvalues_count(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (!eig)
return luaL_error(L, "No Eigenfaces user-data specified");
lua_pushnumber(L, (*eig)->getEigenvaluesCount());
return 1;
}
///
/// @code
/// { output1, output2, output3,... } =
/// Eigenfaces:project_in_eigenspace({ image1, image2, image3... })
/// @endcode
///
static int eigenfaces__project_in_eigenspace(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (!eig)
return luaL_error(L, "No Eigenfaces user-data specified");
luaL_checktype(L, 2, LUA_TTABLE);
vector<Vector> outputs;
// iterate table
lua_pushnil(L); // push nil for first element of table
while (lua_next(L, 2) != 0) {
lua_Image* img = *toImage(L, -1); // get value
if (img) {
Vector imgVector, output;
imglib::details::image2vector(img, imgVector);
(*eig)->projectInEigenspace(imgVector, output);
outputs.push_back(output);
}
lua_pop(L, 1); // remove value, the key is in stack for next iteration
}
// Create table of converted images
lua_newtable(L);
size_t i = 1;
for (vector<Vector>::iterator it =
outputs.begin(); it != outputs.end(); ++it, ++i) {
// a new table in the stack
lua_pushinteger(L, i);
lua_newtable(L);
Vector& output(*it);
for (size_t j=0; j<output.size(); ++j) {
lua_pushinteger(L, j+1);
lua_pushnumber(L, output(j));
lua_settable(L, -3);
}
lua_settable(L, -3);
}
return 1;
}
static int eigenfaces__gc(lua_State* L)
{
lua_Eigenfaces** eig = toEigenfaces(L, 1);
if (eig) {
delete *eig;
*eig = NULL;
}
return 0;
}
static const luaL_Reg eigenfaces_metatable[] = {
{ "reserve", eigenfaces__reserve },
{ "add_image", eigenfaces__add_image },
{ "calculate_eigenfaces", eigenfaces__calculate_eigenfaces },
{ "project_in_eigenspace", eigenfaces__project_in_eigenspace },
{ "save", eigenfaces__save },
{ "eigenvalues_count", eigenfaces__eigenvalues_count },
{ "__gc", eigenfaces__gc },
{ NULL, NULL }
};
void imglib::details::registerEigenfaces(lua_State* L)
{
// Eigenfaces user data
luaL_newmetatable(L, LUAOBJ_EIGENFACES); // create metatable for Eigenfaces
lua_pushvalue(L, -1); // push metatable
lua_setfield(L, -2, "__index"); // metatable.__index = metatable
luaL_register(L, NULL, eigenfaces_metatable); // Eigenfaces methods
}
int imglib::details::EigenfacesCtor(lua_State* L)
{
lua_Eigenfaces* e = *neweigenfaces(L);
return 1;
}
| 26.121495 | 98 | 0.672809 | [
"vector"
] |
d631141ba9b68abafa6533479b008e9a61f966a5 | 8,138 | hh | C++ | include/mmvae.hh | YPARK/mm-vae | 371e60821b0d0bf866bf465a8bc7bfa048bbf32c | [
"MIT"
] | 1 | 2021-03-18T02:01:31.000Z | 2021-03-18T02:01:31.000Z | include/mmvae.hh | YPARK/mm-vae | 371e60821b0d0bf866bf465a8bc7bfa048bbf32c | [
"MIT"
] | null | null | null | include/mmvae.hh | YPARK/mm-vae | 371e60821b0d0bf866bf465a8bc7bfa048bbf32c | [
"MIT"
] | null | null | null | #ifndef MMVAE_HH_
#define MMVAE_HH_
#include <iostream>
#include "util.hh"
#include "gzstream.hh"
#include "io_visitor.hh"
#include "io_alg.hh"
#include "eigen_util.hh"
#include "std_util.hh"
#include "math.hh"
#include "check.hh"
#include "io.hh"
#include "gzstream.hh"
#include "mmutil_index.hh"
#include "mmutil_bgzf_util.hh"
#ifndef TORCH_INC_H_ // Prevent torch
#define TORCH_INC_H_ // from reloading
#include <torch/torch.h> //
#include <torch/csrc/autograd/variable.h> //
#include <torch/csrc/autograd/function.h> //
#include <torch/csrc/autograd/VariableTypeUtils.h> //
#include <torch/csrc/autograd/functions/utils.h> //
#endif // End of torch
#include <getopt.h>
struct mmvae_options_t {
explicit mmvae_options_t()
{
// default options
batch_size = 100;
kl_discount = .1;
kl_min = 1e-2;
kl_max = 1.;
}
std::string mtx;
std::string idx;
std::string out;
std::string row;
std::string col;
std::string annot;
std::string covar_mtx;
std::string covar_idx;
int64_t batch_size;
float kl_discount;
float kl_min;
float kl_max;
};
int
parse_mmvae_options(const int argc,
const char *_argv[],
mmvae_options_t &options)
{
const char *_usage =
"\n"
"[options]\n"
"\n"
"--mtx : a matrix market mtx file\n"
"--idx : an index file for the mtx (default: ${mtx}.index)\n"
"--row : the rows (line = one string)\n"
"--col : the columns (line = one string)\n"
"--annot : the list of column annotations (line = ${col} <space> ${k})\n"
"--out : output file header\n"
"--covar : a separate matrix market mtx for other covariates\n"
"--covar_idx : an index file for the covar mtx (default: ${covar}.index)\n"
"--batch_size : #samples in each batch (default: 100)\n"
"\n"
"--kl_discount : KL divergence discount (default: 0)\n"
" : Loss = likelihood_loss + beta * KL_loss\n"
" : where beta = exp(- ${discount} * epoch)\n"
"--kl_max : max KL divergence penalty (default: 1)\n"
"--kl_min : min KL divergence penalty (default: 1e-2)\n"
"\n";
const char *const short_opts = "M:I:O:V:J:r:c:a:b:K:L:l:h?";
const option long_opts[] = {
{ "mtx", required_argument, nullptr, 'M' }, //
{ "idx", required_argument, nullptr, 'I' }, //
{ "out", required_argument, nullptr, 'O' }, //
{ "output", required_argument, nullptr, 'O' }, //
{ "cov", required_argument, nullptr, 'V' }, //
{ "covar", required_argument, nullptr, 'V' }, //
{ "cov_idx", required_argument, nullptr, 'J' }, //
{ "covar_idx", required_argument, nullptr, 'J' }, //
{ "row", required_argument, nullptr, 'r' }, //
{ "col", required_argument, nullptr, 'c' }, //
{ "column", required_argument, nullptr, 'c' }, //
{ "annot", required_argument, nullptr, 'a' }, //
{ "annotation", required_argument, nullptr, 'a' }, //
{ "batch_size", required_argument, nullptr, 'b' }, //
{ "batch", required_argument, nullptr, 'b' }, //
{ "kl_discount", required_argument, nullptr, 'K' }, //
{ "kl_max", required_argument, nullptr, 'L' }, //
{ "kl_min", required_argument, nullptr, 'l' }, //
{ "help", no_argument, nullptr, 'h' }, //
{ nullptr, no_argument, nullptr, 0 }
};
optind = 1;
opterr = 0;
// copy argv and run over this instead of dealing with the actual ones.
std::vector<const char *> _argv_org(_argv, _argv + argc);
std::vector<const char *> argv_copy;
std::transform(std::begin(_argv_org),
std::end(_argv_org),
std::back_inserter(argv_copy),
str2char);
const char **argv = &argv_copy[0];
while (true) {
const auto opt = getopt_long(argc, //
const_cast<char **>(argv), //
short_opts, //
long_opts, //
nullptr);
if (-1 == opt)
break;
switch (opt) {
case 'M':
options.mtx = std::string(optarg);
break;
case 'I':
options.idx = std::string(optarg);
break;
case 'V':
options.covar_mtx = std::string(optarg);
break;
case 'J':
options.covar_idx = std::string(optarg);
break;
case 'O':
options.out = std::string(optarg);
break;
case 'r':
options.row = std::string(optarg);
break;
case 'c':
options.col = std::string(optarg);
break;
case 'a':
options.annot = std::string(optarg);
break;
case 'b':
options.batch_size = std::stol(optarg);
break;
case 'K':
options.kl_discount = std::stof(optarg);
break;
case 'l':
options.kl_min = std::stof(optarg);
break;
case 'L':
options.kl_max = std::stof(optarg);
break;
case 'h': // -h or --help
std::cerr << _usage << std::endl;
for (std::size_t i = 0; i < argv_copy.size(); i++)
delete[] argv_copy[i];
return EXIT_SUCCESS;
case '?': // Unrecognized option
default: //
;
}
}
for (std::size_t i = 0; i < argv_copy.size(); i++)
delete[] argv_copy[i];
ERR_RET(!file_exists(options.mtx), "missing mtx file");
ERR_RET(options.out.size() == 0, "need output file header");
if (options.idx.size() == 0) {
options.idx = options.mtx + ".index";
}
if (options.covar_idx.size() == 0) {
options.covar_idx = options.covar_mtx + ".index";
}
return EXIT_SUCCESS;
}
struct annotation_t {
using Str = std::string;
struct FEAT {
Str s;
};
struct ANNOT {
Str s;
};
explicit annotation_t(const ANNOT annot, const FEAT feat);
torch::Tensor operator()();
const std::string annot_file;
const std::string feature_file;
private:
std::vector<std::tuple<std::string, std::string>> annot_;
std::unordered_map<std::string, int64_t> feature2id;
std::vector<std::string> features;
std::unordered_map<std::string, int64_t> label_pos;
std::vector<std::string> labels;
int64_t D, K;
};
annotation_t::annotation_t(const annotation_t::ANNOT annot,
const annotation_t::FEAT feat)
: annot_file(annot.s)
, feature_file(feat.s)
{
CHK(read_pair_file(annot_file, annot_));
CHK(read_vector_file(feature_file, features));
feature2id = make_position_dict<std::string, int64_t>(features);
{
int64_t j = 0;
for (auto pp : annot_) {
if (feature2id.count(std::get<0>(pp)) > 0) {
if (label_pos.count(std::get<1>(pp)) == 0) {
label_pos[std::get<1>(pp)] = j++;
labels.push_back(std::get<1>(pp));
}
}
}
}
D = feature2id.size();
K = std::max(label_pos.size(), (std::size_t)1);
}
torch::Tensor
annotation_t::operator()()
{
torch::Tensor L(torch::zeros({ D, K }));
for (auto pp : annot_) {
if (feature2id.count(std::get<0>(pp)) > 0) {
const int64_t k = label_pos[std::get<1>(pp)];
const int64_t j = feature2id[std::get<0>(pp)];
L[j][k] = 1.;
}
}
return L;
}
#endif
| 28.65493 | 87 | 0.505652 | [
"vector",
"transform"
] |
d6323469e45154d21609c8d18795408136fe10bb | 9,032 | cpp | C++ | src/ui/ds_capture.cpp | JohanSmet/kinect_webcam | 7728be2dd575404b5ec43a0867ebba9ca0595d4c | [
"MIT"
] | 21 | 2015-01-28T06:47:26.000Z | 2022-03-27T15:31:08.000Z | src/ui/ds_capture.cpp | JohanSmet/kinect_webcam | 7728be2dd575404b5ec43a0867ebba9ca0595d4c | [
"MIT"
] | 1 | 2017-07-17T22:56:45.000Z | 2017-07-22T13:34:35.000Z | src/ui/ds_capture.cpp | JohanSmet/kinect_webcam | 7728be2dd575404b5ec43a0867ebba9ca0595d4c | [
"MIT"
] | 3 | 2019-04-04T14:56:12.000Z | 2021-02-22T13:22:02.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// File : ds_capture.cpp
//
// Purpose : Preview a DirectShow capture filter
//
// Copyright (c) 2014 Contributors as noted in the AUTHORS file
//
// This file is licensed under the terms of the MIT license,
// for more details please see LICENSE.txt in the root directory
// of the provided source or http://opensource.org/licenses/MIT
//
///////////////////////////////////////////////////////////////////////////////
#include "ds_capture.h"
#include "com_utils.h"
DSVideoCapture::DSVideoCapture() : m_graph(nullptr),
m_builder(nullptr),
m_control(nullptr),
m_video_window(nullptr),
m_source(nullptr),
m_config(nullptr)
{
}
bool DSVideoCapture::initialize(GUID p_capture_guid)
{
if (!create_capture_filter(p_capture_guid))
return false;
return true;
}
bool DSVideoCapture::shutdown()
{
com_safe_release(&m_source);
return true;
}
void DSVideoCapture::preview_device(RECT p_window, HWND p_video_parent)
{
// graph
if (!graph_initialize())
return;
// video window
if (!video_window_initialize(p_window, p_video_parent))
return;
// start the preview
m_control->Run();
}
void DSVideoCapture::preview_shutdown()
{
if (m_control)
m_control->Stop();
graph_shutdown();
}
bool DSVideoCapture::graph_initialize()
{
HRESULT f_result = S_OK;
CoInitialize(nullptr);
// create a FilterGraph
if (SUCCEEDED(f_result))
{
f_result = CoCreateInstance(CLSID_FilterGraph, nullptr, CLSCTX_INPROC_SERVER, IID_IFilterGraph2, reinterpret_cast<void **> (&m_graph));
}
// create a CaptureGraphBuilder
if (SUCCEEDED(f_result))
{
f_result = CoCreateInstance(CLSID_CaptureGraphBuilder2, nullptr, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, reinterpret_cast<void **> (&m_builder));
}
if (SUCCEEDED(f_result))
{
m_builder->SetFiltergraph(m_graph);
}
// get interface to be used later
if (SUCCEEDED(f_result))
{
f_result = m_graph->QueryInterface(IID_IMediaControl, reinterpret_cast<void**> (&m_control));
}
if (SUCCEEDED(f_result))
{
f_result = m_graph->QueryInterface(IID_IVideoWindow, reinterpret_cast<void **> (&m_video_window));
}
// add the capture device to the graph
if (SUCCEEDED (f_result))
{
m_graph->AddFilter(m_source, L"Video Capture");
}
// create the video renderer
if (SUCCEEDED (f_result))
{
f_result = CoCreateInstance(CLSID_VideoRenderer, nullptr, CLSCTX_INPROC_SERVER, IID_IBaseFilter, reinterpret_cast<void **> (&m_renderer));
}
if (SUCCEEDED (f_result))
{
f_result = m_graph->AddFilter(m_renderer, L"Video Renderer");
}
// render the preview pin on the video capture filter
if (SUCCEEDED (f_result))
{
f_result = m_builder->RenderStream (&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, m_source, nullptr, m_renderer);
}
#ifdef _DEBUG
if (SUCCEEDED(f_result))
{
rot_add_graph();
}
#endif
return SUCCEEDED (f_result);
}
bool DSVideoCapture::graph_shutdown()
{
// close the video window
if (m_video_window)
{
m_video_window->put_Owner(NULL);
m_video_window->put_Visible(OAFALSE);
}
// remove the graph from the running object table
#ifdef _DEBUG
rot_remove_graph();
#endif
// release the interface
com_safe_release(&m_renderer);
com_safe_release(&m_control);
com_safe_release(&m_config);
com_safe_release(&m_video_window);
com_safe_release(&m_graph);
com_safe_release(&m_builder);
return true;
}
bool DSVideoCapture::create_capture_filter(GUID p_guid)
{
// create the source filter
HRESULT f_result = CoCreateInstance(p_guid, nullptr, CLSCTX_INPROC_SERVER, IID_IBaseFilter, reinterpret_cast<void **>(&m_source));
// get an interface to configure the stream
if (SUCCEEDED (f_result))
{
f_result = m_source->QueryInterface(IID_IAMStreamConfig, reinterpret_cast<void **>(&m_config));
}
// retrieve the list of supported resolutions
int f_caps_count;
int f_caps_size;
if (SUCCEEDED (f_result))
{
m_config->GetNumberOfCapabilities(&f_caps_count, &f_caps_size);
}
for (int f_idx=0; SUCCEEDED(f_result) && f_idx < f_caps_count; ++f_idx)
{
VIDEO_STREAM_CONFIG_CAPS f_scc;
AM_MEDIA_TYPE * f_mt;
f_result = m_config->GetStreamCaps(f_idx, &f_mt, (BYTE*) &f_scc);
VIDEOINFOHEADER *f_vi = reinterpret_cast<VIDEOINFOHEADER *> (f_mt->pbFormat);
m_resolutions.push_back({f_idx, f_vi->bmiHeader.biWidth, f_vi->bmiHeader.biHeight, f_vi->bmiHeader.biBitCount});
}
return SUCCEEDED(f_result);
}
bool DSVideoCapture::video_window_initialize(RECT p_window, HWND p_video_parent)
{
HRESULT f_result = S_OK;
// set the video window to be a child of specified parent window
if (SUCCEEDED(f_result) && p_video_parent)
{
f_result = m_video_window->put_Owner(reinterpret_cast<OAHWND>(p_video_parent));
}
// window style
if (SUCCEEDED(f_result) && p_video_parent)
{
f_result = m_video_window->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
}
// size
if (SUCCEEDED(f_result) && p_video_parent)
{
m_preview_parent = p_video_parent;
video_window_resize(p_window);
}
// show the video window
if (SUCCEEDED(f_result))
{
f_result = m_video_window->put_Visible(OATRUE);
}
return SUCCEEDED(f_result);
}
void DSVideoCapture::video_window_resize(RECT p_dimension)
{
if (!m_video_window || !m_preview_parent)
return;
m_video_window->SetWindowPosition(p_dimension.left, p_dimension.top, p_dimension.right, p_dimension.bottom);
}
void DSVideoCapture::video_change_resolution(int p_resolution)
{
HRESULT f_result = S_OK;
// stop the preview
if (SUCCEEDED(f_result))
{
f_result = m_control->Stop();
m_video_window->put_Visible(OAFALSE);
}
// disconnect the source and remove the filters between the source and the renderer
if (SUCCEEDED(f_result))
{
graph_remove_downstream(m_source, m_renderer);
}
// change the resolution
VIDEO_STREAM_CONFIG_CAPS f_scc;
AM_MEDIA_TYPE * f_mt;
f_result = m_config->GetStreamCaps(p_resolution, &f_mt, (BYTE*) &f_scc);
if (SUCCEEDED(f_result))
{
f_result = m_config->SetFormat(f_mt);
}
// reconnect the source with the renderer
if (SUCCEEDED(f_result))
{
f_result = m_builder->RenderStream (&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, m_source, nullptr, m_renderer);
}
// restart the preview
if (SUCCEEDED(f_result))
{
m_video_window->put_Visible(OATRUE);
m_control->Run();
}
}
void DSVideoCapture::graph_remove_downstream(IBaseFilter *p_start, IBaseFilter *p_end)
{
com_safe_ptr_t<IEnumPins> f_pins = nullptr;
PIN_INFO f_pininfo;
if (!p_start)
return;
HRESULT f_result = p_start->EnumPins(&f_pins);
f_pins->Reset();
while (f_result == NOERROR)
{
com_safe_ptr_t<IPin> f_pin;
f_result = f_pins->Next(1, &f_pin, nullptr);
if (f_result == S_OK && f_pin.get())
{
com_safe_ptr_t<IPin> f_pin_to;
f_pin->ConnectedTo(&f_pin_to);
if (f_pin_to.get())
{
f_result = f_pin_to->QueryPinInfo(&f_pininfo);
com_safe_ptr_t<IBaseFilter> f_filter = f_pininfo.pFilter;
if (f_result == NOERROR && f_pininfo.dir == PINDIR_INPUT && f_pininfo.pFilter != p_end)
{
graph_remove_downstream(f_pininfo.pFilter, p_end);
m_graph->Disconnect(f_pin.get());
m_graph->Disconnect(f_pin_to.get());
m_graph->RemoveFilter(f_pininfo.pFilter);
}
}
}
}
}
#ifdef _DEBUG
void DSVideoCapture::rot_add_graph()
{
IMoniker * pMoniker;
IRunningObjectTable *pROT;
WCHAR wsz[128];
HRESULT hr;
if (m_graph == nullptr)
return;
if (FAILED(GetRunningObjectTable(0, &pROT)))
return;
hr = StringCchPrintfW(wsz, NUMELMS(wsz), L"FilterGraph %08x pid %08x\0", (DWORD_PTR) m_graph, GetCurrentProcessId());
hr = CreateItemMoniker(L"!", wsz, &pMoniker);
if (SUCCEEDED(hr))
{
// Use the ROTFLAGS_REGISTRATIONKEEPSALIVE to ensure a strong reference
// to the object. Using this flag will cause the object to remain
// registered until it is explicitly revoked with the Revoke() method.
//
// Not using this flag means that if GraphEdit remotely connects
// to this graph and then GraphEdit exits, this object registration
// will be deleted, causing future attempts by GraphEdit to fail until
// this application is restarted or until the graph is registered again.
hr = pROT->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, m_graph, pMoniker, &m_rot_id);
pMoniker->Release();
}
pROT->Release();
}
void DSVideoCapture::rot_remove_graph()
{
IRunningObjectTable *pROT;
if (SUCCEEDED(GetRunningObjectTable(0, &pROT)))
{
pROT->Revoke(m_rot_id);
pROT->Release();
}
}
#endif | 25.370787 | 161 | 0.674601 | [
"render",
"object"
] |
d63453b630688d454efbd46aaedd236537b0007a | 595 | cc | C++ | src/corpus.cc | DeepAINet/expboost | df409046065d9827f21bba5049108389caed0e63 | [
"Apache-2.0"
] | null | null | null | src/corpus.cc | DeepAINet/expboost | df409046065d9827f21bba5049108389caed0e63 | [
"Apache-2.0"
] | null | null | null | src/corpus.cc | DeepAINet/expboost | df409046065d9827f21bba5049108389caed0e63 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class corpus{
protected:
string file;
// ifstream in;
public:
corpus(string filename):file(filename){
read();
}
~corpus(){
// if (in.is_open()) in.close();
}
void read(){
ifstream in(file);
if (in.is_open()) std::cout << " opened." << std::endl;
string line;
while(getline(in, line)){
std::cout << line << std::endl;
}
}
};
| 19.833333 | 68 | 0.465546 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.