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
34508de8d8933af064f1d7066adfcb68ff31a767
2,380
cpp
C++
app/anax/anaxBenchmarkRunner.cpp
abeimler/ecs_benchmark
539b243f6e5faf2c4af9fc2da6dca4742978f386
[ "MIT" ]
44
2017-03-01T15:47:50.000Z
2022-03-25T16:39:11.000Z
app/anax/anaxBenchmarkRunner.cpp
abeimler/ecs_benchmark
539b243f6e5faf2c4af9fc2da6dca4742978f386
[ "MIT" ]
7
2017-03-27T19:39:33.000Z
2022-02-01T02:20:43.000Z
app/anax/anaxBenchmarkRunner.cpp
abeimler/ecs_benchmark
539b243f6e5faf2c4af9fc2da6dca4742978f386
[ "MIT" ]
11
2016-12-02T03:07:50.000Z
2021-03-20T15:53:21.000Z
#include <benchpress/benchpress.hpp> #include <anax/AnaxBenchmark.h> #include <BaseBenchmark.h> namespace anax_benchmark { BENCHMARK("anax create destroy entity with components", [](benchpress::context *ctx) { EntityManager entities; ctx->reset_timer(); for (size_t i = 0; i < ctx->num_iterations(); ++i) { auto entity = entities.createEntity(); entity.addComponent<PositionComponent>(); entity.addComponent<DirectionComponent>(); entity.addComponent<ComflabulationComponent>(); entity.kill(); } }) inline void init_entities(EntityManager &entities, size_t nentities) { for (size_t i = 0; i < nentities; i++) { auto entity = entities.createEntity(); entity.addComponent<PositionComponent>(); entity.addComponent<DirectionComponent>(); if (i % 2 != 0) { entity.addComponent<ComflabulationComponent>(); } entity.activate(); } } class AnaxBenchmark { private: static constexpr TimeDelta fakeDeltaTime = 1.0 / 60; static const std::vector<int> ENTITIES; static inline void makeBenchmarks(const std::string &name) { makeBenchmarks(name, ENTITIES); } static void makeBenchmarks(const std::string &name, const std::vector<int> &entities) { for (int nentities : entities) { std::string tag = fmt::format("[{}]", nentities); std::string benchmark_name = fmt::format("{:>12} {:<10} {:>12} entities component systems update", tag, name, nentities); std::function<void(benchpress::context *)> bench_func = [nentities = nentities](benchpress::context *ctx) { Application app; init_entities(app, nentities); ctx->reset_timer(); for (size_t i = 0; i < ctx->num_iterations(); ++i) { app.update(fakeDeltaTime); } }; BENCHMARK(benchmark_name, bench_func) } } public: AnaxBenchmark(const std::string &name) { makeBenchmarks(name); } }; const std::vector<int> AnaxBenchmark::ENTITIES = { 10, 25, 50, 100, 200, 400, 800, 1600, 3200, 5000, 10'000, 30'000, 100'000, 500'000, 1'000'000, 2'000'000}; AnaxBenchmark anaxbenchmarks("anax"); } // namespace anax_benchmark
28
79
0.60084
[ "vector" ]
345204a1ea07a6c9e6cec943fc4c33b1c74ea1d3
6,631
cpp
C++
drivers/gps_mocap.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
12
2016-07-12T10:26:47.000Z
2021-12-14T10:03:11.000Z
drivers/gps_mocap.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
183
2015-01-22T12:35:18.000Z
2017-06-09T10:11:26.000Z
drivers/gps_mocap.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
25
2015-02-03T15:15:48.000Z
2021-12-14T08:55:04.000Z
/******************************************************************************* * Copyright (c) 2009-2016, MAV'RIC Development Team * 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. ******************************************************************************/ /******************************************************************************* * \file gps_mocap.cpp * * \author MAV'RIC Team * \author Julien Lecoeur * * \brief Expose data received from motion capture system as GPS data * ******************************************************************************/ #include "drivers/gps_mocap.hpp" #include "hal/common/time_keeper.hpp" #include "util/constants.hpp" #include "util/quick_trig.hpp" //------------------------------------------------------------------------------ // PRIVATE FUNCTIONS DECLARATION //------------------------------------------------------------------------------ /** * \brief Callback function used to update the gps when a mavlink message is received * * \param gps_mocap Pointer to Gps_mocap object * \param sysid ID of the system * \param msg Pointer to the incoming message */ static void gps_mocap_callback(Gps_mocap* gps_mocap, uint32_t sysid, const mavlink_message_t* msg); //------------------------------------------------------------------------------ // PRIVATE FUNCTIONS IMPLEMENTATION //------------------------------------------------------------------------------ static void gps_mocap_callback(Gps_mocap* gps_mocap, uint32_t sysid, const mavlink_message_t* msg) { gps_mocap->callback(sysid, msg); } //------------------------------------------------------------------------------ // PUBLIC FUNCTIONS IMPLEMENTATION //------------------------------------------------------------------------------ Gps_mocap::Gps_mocap(Mavlink_message_handler& message_handler, conf_t config): message_handler_(message_handler), config_(config), is_init_(false), last_update_us_(0.0f) { local_position_[X] = 0.0f; local_position_[Y] = 0.0f; local_position_[Z] = 0.0f; velocity_lf_[X] = 0.0f; velocity_lf_[Y] = 0.0f; velocity_lf_[Z] = 0.0f; heading_ = 0.0f; } bool Gps_mocap::init(void) { if (is_init_ == false) { // Add callbacks for waypoint handler messages requests is_init_ = message_handler_.add_msg_callback( MAVLINK_MSG_ID_ATT_POS_MOCAP, // 69 MAVLINK_BASE_STATION_ID, MAV_COMP_ID_ALL, &gps_mocap_callback, this ); } return is_init_; } void Gps_mocap::callback(uint32_t __attribute__((unused)) sysid, const mavlink_message_t* msg) { mavlink_att_pos_mocap_t packet; mavlink_msg_att_pos_mocap_decode(msg, &packet); // Get timing float t = time_keeper_get_us(); // Update velocity float dt_s = (t - last_update_us_) / 1000000; if (dt_s > 0.0f) { velocity_lf_[X] = (packet.x - local_position_[X]) / dt_s; velocity_lf_[Y] = (packet.y - local_position_[Y]) / dt_s; velocity_lf_[Z] = (packet.z - local_position_[Z]) / dt_s; if (velocity_lf_[X] != 0.0f) { heading_ = quick_trig_atan(velocity_lf_[Y] / velocity_lf_[X]); } } // Update position local_position_[X] = packet.x; local_position_[Y] = packet.y; local_position_[Z] = packet.z; // Update timing last_update_us_ = t; } bool Gps_mocap::update(void) { return true; } void Gps_mocap::configure(void) { ; } float Gps_mocap::last_update_us(void) const { return last_update_us_; } float Gps_mocap::last_position_update_us(void) const { return last_update_us_; } float Gps_mocap::last_velocity_update_us(void) const { return last_update_us_; } global_position_t Gps_mocap::position_gf(void) const { global_position_t global_position; coord_conventions_local_to_global_position(local_position_, config_.origin, global_position); return global_position; } float Gps_mocap::horizontal_position_accuracy(void) const { return config_.horizontal_position_accuracy; } float Gps_mocap::vertical_position_accuracy(void) const { return config_.vertical_position_accuracy; } std::array<float, 3> Gps_mocap::velocity_lf(void) const { return velocity_lf_; } float Gps_mocap::velocity_accuracy(void) const { return config_.velocity_accuracy; } float Gps_mocap::heading(void) const { return heading_; } float Gps_mocap::heading_accuracy(void) const { return config_.heading_accuracy; } uint8_t Gps_mocap::num_sats(void) const { return 16; } gps_fix_t Gps_mocap::fix(void) const { gps_fix_t fix = FIX_ERR; if (healthy()) { fix = FIX_RTK; } return fix; } bool Gps_mocap::healthy(void) const { bool is_healthy = true; float t = time_keeper_get_us(); if ( (t - last_update_us()) > 1000000 ) { is_healthy = false; } return is_healthy; }
26.846154
99
0.603076
[ "object" ]
345a0e7750a2d59633bcfd5848bb1a84d41312f8
582
cpp
C++
#0049.group-anagrams.cpp
hosomi/LeetCode
aba8fae8e37102b33dba8fd4adf1f018c395a4db
[ "MIT" ]
null
null
null
#0049.group-anagrams.cpp
hosomi/LeetCode
aba8fae8e37102b33dba8fd4adf1f018c395a4db
[ "MIT" ]
null
null
null
#0049.group-anagrams.cpp
hosomi/LeetCode
aba8fae8e37102b33dba8fd4adf1f018c395a4db
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> result; unordered_map<string, vector<int>> m; int size = strs.size(); string s; for (int i = 0; i < size; ++i) { s = strs[i]; sort(begin(s), end(s)); m[s].push_back(i); } for (const auto& v : m) { result.push_back({}); for (int i : v.second) { result.back().push_back(strs[i]); } } return result; } };
23.28
64
0.457045
[ "vector" ]
345e2ba933293cc29ded298cf58e6002beead01d
8,228
cpp
C++
experiments/gamma.cpp
noeld/cpp
572a145f8c79f7292b7b0611822ed34792df4e9c
[ "Unlicense" ]
null
null
null
experiments/gamma.cpp
noeld/cpp
572a145f8c79f7292b7b0611822ed34792df4e9c
[ "Unlicense" ]
null
null
null
experiments/gamma.cpp
noeld/cpp
572a145f8c79f7292b7b0611822ed34792df4e9c
[ "Unlicense" ]
null
null
null
#include <iostream> #include <algorithm> #include <tuple> #include <complex> #include <array> #include <vector> #include <memory> #include <numeric> #include <string> #include <boost/format.hpp> using namespace std; using myfloat_t = double; using c_t = complex<myfloat_t>; template<typename T> struct Rect { Rect(const T& xmin = T(), const T& ymin = T(), const T& xmax = T(), const T& ymax = T()) : xmin_{xmin}, ymin_{ymin}, xmax_{xmax}, ymax_{ymax} { normalize(); } Rect(const Rect&) = default; Rect& operator=(const Rect&) = default; friend bool operator==(const Rect<T>& a, const Rect<T>& b) { return std::tie(a.xmin_, a.ymin_, a.xmax_, a.ymax_) == std::tie(b.xmin_, b.ymin_, b.xmax_, b.ymax_); } friend bool operator<(const Rect<T>& a, const Rect<T>& b) { return std::tie(a.xmin_, a.ymin_, a.xmax_, a.ymax_) < std::tie(b.xmin_, b.ymin_, b.xmax_, b.ymax_); } friend bool operator<=(const Rect<T>& a, const Rect<T>& b) { return (a < b) || (a == b); } friend bool operator>(const Rect<T>& a, const Rect<T>& b) { return (b < a); } friend bool operator>=(const Rect<T>& a, const Rect<T>& b) { return (b < a) || (a == b); } friend bool operator!=(const Rect<T>& a, const Rect<T>& b) { return !(a == b); } friend std::ostream& operator<<(std::ostream& o, const Rect<T>& r) { std::string fmts = "[%6.5f, %6.5f, %6.5f, %6.5f]"; if (std::is_integral<T>::value) { fmts = "[%d, %d, %d, %d]"; } boost::format fmt{fmts}; o << fmt % r.xmin_ % r.ymin_ % r.xmax_ % r.ymax_; return o; } void normalize() { if (xmax_ < xmin_) swap(xmax_, xmin_); if (ymax_ < ymin_) swap(ymax_, ymin_); } T width() const { if (std::is_integral<T>::value) return xmax_ - xmin_ + 1; else return xmax_ - xmin_; } T height() const { if (std::is_integral<T>::value) return ymax_ - ymin_ + 1; else return ymax_ - ymin_; } void zoom(myfloat_t f) { auto w = width(); auto h = height(); auto centerx = xmin_ + w/2.0; auto centery = ymin_ + h/2.0; auto nw = w * f; auto nh = h * f; xmin_ = centerx - nw/2.0; ymin_ = centery - nh/2.0; xmax_ = centerx + nw/2.0; ymax_ = centery + nh/2.0; } void move(const T& x, const T& y) { xmin_ += x; ymin_ += y; xmax_ += x; ymax_ += y; } T xmin_, ymin_, xmax_, ymax_; }; using FRect = Rect<myfloat_t>; using URect = Rect<unsigned>; struct RenderParams { unsigned maxit_ { 2000 }; myfloat_t test_ { 4.0 }; unsigned width_ { 61 }; unsigned height_ { 23 }; myfloat_t gamma_ { 0.6 }; std::vector<char> alpha_ // { ' ', '.', ':', '-', '+', 'i', 'o', 'x', 'I', 'X', 'N', 'M', 'W', '%'}; { ' ', '.', '\'', '`', '^', '"', ',', ':', ';', 'I', 'l', '!', 'i', '>', '<', '~', '+', '_', '-', '?' , ']', '[', '}', '{', '1', ')', '(', '|', '\\', '/', 't', 'f', 'j', 'r', 'x', 'n', 'u', 'v', 'c', 'z' , 'X', 'Y', 'U', 'J', 'C', 'L', 'Q', '0', 'O', 'Z', 'm', 'w', 'q', 'p', 'd', 'b', 'k', 'h', 'a', 'o' , '*', '#', 'M', 'W', '&', '8', '%', 'B', '@', '$'}; friend std::ostream& operator<<(std::ostream& o, const RenderParams& rp) { boost::format fmt{"Iterations: %d Test:%4.2f Gamma: %4.3f"}; o << fmt % rp.maxit_ % rp.test_ % rp.gamma_; return o; } }; class MImage { public: explicit MImage(unsigned width, unsigned height) : width_{width}, height_{height}, rpp_{nullptr} , px_(width_ * height_, 0) {} unsigned& operator()(unsigned x, unsigned y) { return px_[y * width_ + x]; } const unsigned& operator()(unsigned x, unsigned y) const { return px_[y * width_ + x]; } unsigned width() const { return width_; } unsigned height() const { return height_; } MImage render(const RenderParams& param = RenderParams()) { MImage out(width(), height()); out.rpp_ = std::unique_ptr<RenderParams>(new RenderParams(param)); myfloat_t maxa = static_cast<myfloat_t>(param.alpha_.size() - 1); myfloat_t maxi = static_cast<myfloat_t>(param.maxit_); std::transform(cbegin(), cend(), out.begin() , [maxa, maxi, param](const decltype(*cbegin())& i) { return static_cast<unsigned>(pow(static_cast<myfloat_t>(i)/maxi, param.gamma_) * maxa); } ); return out; } myfloat_t average() { auto acc = std::accumulate(cbegin(), cend(), 0); return static_cast<myfloat_t>(acc)/px_.size(); } myfloat_t standard_derivation() { auto avg = average(); myfloat_t res = 0; for(const auto& e : px_) { res += std::pow(static_cast<myfloat_t>(e) - avg, 2.0); } return std::sqrt(res); } friend std::ostream& operator<<(std::ostream& o, MImage& img) { if (img.rpp_) { unsigned n = 0; for(const auto& e : img) { o << img.rpp_->alpha_[e]; ++n; if (n % img.width() == 0) o << std::endl; } } else { unsigned n = 0; for(const auto& e : img) { o << e << ' '; ++n; if (n % img.width() == 0) o << std::endl; } } return o; } private: unsigned width_, height_; std::vector<unsigned> px_; std::unique_ptr<RenderParams> rpp_; public: decltype(px_.begin()) begin() { return px_.begin(); } decltype(px_.end()) end() { return px_.end(); } decltype(px_.cbegin()) cbegin() { return px_.cbegin(); } decltype(px_.cend()) cend() { return px_.cend(); } }; struct Mandelbrot { // Mandelbrot(const FRect& r) FRect r_ { -2.5, -1.5, 1.0, 1.5}; MImage compute(const RenderParams& param = RenderParams()) const { MImage img(param.width_, param.height_); double fcols = r_.width() / param.width_; double frows = r_.height() / param.height_; auto iit = img.begin(); for(unsigned iy = 0; iy < param.height_; ++iy) { double y = r_.ymax_ - frows/2.0 - iy * frows; double x = r_.xmin_ + fcols/2.0; for(unsigned ix = 0; ix < param.width_; ++ix) { x += fcols; c_t c(x, y), cc(c); unsigned i; for(i = 0; norm(c) < param.test_ && i < param.maxit_ - 1; ++i) { c = c * c + cc; //c = pow(c, 2.6) + cc; } //img(ix, iy) = i; *iit = i; ++iit; } } return img; } }; int main(int argn, char* argv[]) { ios_base::sync_with_stdio(false); boost::format fmt{"gamma: %6.3f standard_derivation: %8.4f"}; Mandelbrot m; RenderParams rp; bool ok = true; std::string s; do { auto img = m.compute(rp); auto img2 = img.render(rp); std::cout << img2 << std::endl << m.r_ << rp << std::endl; std::cout << "Zoom + - Move a w s d Params t T i I g G r R c C Quit q:"; std::cin >> s; for (auto c : s) { switch(c) { case '+': m.r_.zoom(0.5); break; case '-': m.r_.zoom(2.0); break; case 'a': m.r_.move(- m.r_.width() * 0.25, 0); break; case 'd': m.r_.move(m.r_.width() * 0.25, 0); break; case 'w': m.r_.move(0, m.r_.height() * 0.25); break; case 's': m.r_.move(0, -m.r_.height() * 0.25); break; case 't': rp.test_ *= 2.0; break; case 'T': rp.test_ *= 0.5; break; case 'i': rp.maxit_ *= 2.0; break; case 'I': rp.maxit_ *= 0.5; break; case 'g': if (rp.gamma_ < 2.0) rp.gamma_ += 0.1; break; case 'G': if (rp.gamma_ > 0.1) rp.gamma_ -= 0.1; break; case 'c': rp.width_ += 4; break; case 'C': rp.width_ -= 4; break; case 'r': rp.height_ += 2; break; case 'R': rp.height_ -= 2; break; case 'q': ok = false; break; } } if(!ok) break; } while(1); // for(myfloat_t g = 1.2; g > 0.0; g-=0.1) { // rp.gamma_ = g; // auto img2 = img.render(rp); // std::cout << fmt % g % img2.standard_derivation() << std::endl; // std::cout << img2 << std::endl; // } return 0; }
28.569444
149
0.503525
[ "render", "vector", "transform" ]
345fd9db36a6cd9a863b79f52a6487998ec675ee
12,957
cpp
C++
SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLGrassRenderer.cpp
phoenixzz/VoronoiMapGen
5afd852f8bb0212baba9d849178eb135f62df903
[ "MIT" ]
11
2017-03-03T03:31:15.000Z
2019-03-01T17:09:12.000Z
SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLGrassRenderer.cpp
phoenixzz/VoronoiMapGen
5afd852f8bb0212baba9d849178eb135f62df903
[ "MIT" ]
null
null
null
SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLGrassRenderer.cpp
phoenixzz/VoronoiMapGen
5afd852f8bb0212baba9d849178eb135f62df903
[ "MIT" ]
2
2017-03-03T03:31:17.000Z
2021-05-27T21:50:43.000Z
COpenGLRenderDevice* COpenGLGrassRenderer::Sorter::m_pRD = NULL; int COpenGLGrassRenderer::Sorter::compareElements( SGPVertex_GRASS_Cluster first, SGPVertex_GRASS_Cluster second ) noexcept { float firstDistance = -(m_pRD->getOpenGLCamera()->m_CameraPos - Vector4D(first.vPosition[0], first.vPosition[1], first.vPosition[2])).GetLengthSquared(); float secondDistance = -(m_pRD->getOpenGLCamera()->m_CameraPos - Vector4D(second.vPosition[0], second.vPosition[1], second.vPosition[2])).GetLengthSquared(); if( firstDistance < secondDistance ) return -1; if( firstDistance > secondDistance ) return 1; return 0; } COpenGLGrassRenderer::COpenGLGrassRenderer(COpenGLRenderDevice *pRenderDevice) : m_pRenderDevice(pRenderDevice), m_GrassTextureID(0), m_vDefaultGrassSize(0.5f, 1.0f, 0.0f), m_nGrassClusterVBOID(0), m_nGrassClusterIndexVBOID(0), m_nGrassClusterVAOID(0), m_GrassClusterInstanceVBID(0) { m_GrassClusterInstanceArray.ensureStorageAllocated(INIT_GRASSCLUSTERINSTANCE_NUM); // Local Grass Cluster Vertex and Index /* 0 1 |-----------| | | | | | | |-----------| 3 2 */ uint16 grassIndex[6*3] = { 0, 2, 1, 0, 3, 2, 4, 6, 5, 4, 7, 6, 8, 10, 9, 8, 11, 10 }; SGPVertex_GRASS grassLocalVertex[4*3]; Vector3D OffsetVector(m_vDefaultGrassSize.x, 0, 0); Matrix4x4 RotMat; for( int i=-1; i<=1; i++ ) { RotMat.RotationY( i * 60.0f * pi_over_180 ); OffsetVector.RotateWith(RotMat); if( i == 0 ) OffsetVector.Set(m_vDefaultGrassSize.x, 0, 0); grassLocalVertex[(i+1)*4 + 0].x = -OffsetVector.x; grassLocalVertex[(i+1)*4 + 0].y = -OffsetVector.y; grassLocalVertex[(i+1)*4 + 0].z = -OffsetVector.z; grassLocalVertex[(i+1)*4 + 0].tu = 0; grassLocalVertex[(i+1)*4 + 0].tv = 0; grassLocalVertex[(i+1)*4 + 1].x = OffsetVector.x; grassLocalVertex[(i+1)*4 + 1].y = OffsetVector.y; grassLocalVertex[(i+1)*4 + 1].z = OffsetVector.z; grassLocalVertex[(i+1)*4 + 1].tu = 1; grassLocalVertex[(i+1)*4 + 1].tv = 0; grassLocalVertex[(i+1)*4 + 2].x = OffsetVector.x; grassLocalVertex[(i+1)*4 + 2].y = OffsetVector.y; grassLocalVertex[(i+1)*4 + 2].z = OffsetVector.z; grassLocalVertex[(i+1)*4 + 2].tu = 1; grassLocalVertex[(i+1)*4 + 2].tv = 1; grassLocalVertex[(i+1)*4 + 3].x = -OffsetVector.x; grassLocalVertex[(i+1)*4 + 3].y = -OffsetVector.y; grassLocalVertex[(i+1)*4 + 3].z = -OffsetVector.z; grassLocalVertex[(i+1)*4 + 3].tu = 0; grassLocalVertex[(i+1)*4 + 3].tv = 1; } GLsizei nStride = sizeof(SGPVertex_GRASS); // create one GrassCluster VAO and VBO m_pRenderDevice->extGlGenVertexArray(1, &m_nGrassClusterVAOID); m_pRenderDevice->extGlBindVertexArray(m_nGrassClusterVAOID); m_pRenderDevice->extGlGenBuffers(1, &m_nGrassClusterVBOID); m_pRenderDevice->extGlBindBuffer(GL_ARRAY_BUFFER, m_nGrassClusterVBOID); m_pRenderDevice->extGlBufferData(GL_ARRAY_BUFFER, 4*3*nStride, grassLocalVertex, GL_STATIC_DRAW); m_pRenderDevice->extGlEnableVertexAttribArray(0); m_pRenderDevice->extGlVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, nStride, (GLvoid *)BUFFER_OFFSET(0)); m_pRenderDevice->extGlEnableVertexAttribArray(1); m_pRenderDevice->extGlVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, nStride, (GLvoid *)BUFFER_OFFSET(3*sizeof(float))); // Instance VertexBuffer nStride = sizeof(SGPVertex_GRASS_Cluster); m_pRenderDevice->extGlGenBuffers(1, &m_GrassClusterInstanceVBID); m_pRenderDevice->extGlBindBuffer(GL_ARRAY_BUFFER, m_GrassClusterInstanceVBID); m_pRenderDevice->extGlBufferData(GL_ARRAY_BUFFER, INIT_GRASSCLUSTERINSTANCE_NUM * nStride, NULL, GL_STREAM_DRAW); m_pRenderDevice->extGlEnableVertexAttribArray(2); m_pRenderDevice->extGlVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, nStride, (GLvoid *)BUFFER_OFFSET(0)); m_pRenderDevice->extGlVertexAttribDivisor(2, 1); m_pRenderDevice->extGlEnableVertexAttribArray(3); m_pRenderDevice->extGlVertexAttribPointer(3, 4, GL_UNSIGNED_BYTE, GL_TRUE, nStride, (GLvoid *)BUFFER_OFFSET(4*sizeof(float))); m_pRenderDevice->extGlVertexAttribDivisor(3, 1); m_pRenderDevice->extGlEnableVertexAttribArray(4); m_pRenderDevice->extGlVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, nStride, (GLvoid *)BUFFER_OFFSET(4*sizeof(float)+4*sizeof(uint8))); m_pRenderDevice->extGlVertexAttribDivisor(4, 1); m_pRenderDevice->extGlEnableVertexAttribArray(5); m_pRenderDevice->extGlVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, nStride, (GLvoid *)BUFFER_OFFSET(8*sizeof(float)+4*sizeof(uint8))); m_pRenderDevice->extGlVertexAttribDivisor(5, 1); m_pRenderDevice->extGlGenBuffers(1, &m_nGrassClusterIndexVBOID); m_pRenderDevice->extGlBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_nGrassClusterIndexVBOID); m_pRenderDevice->extGlBufferData(GL_ELEMENT_ARRAY_BUFFER, 6*3*sizeof(uint16), grassIndex, GL_STATIC_DRAW); m_pRenderDevice->extGlBindVertexArray(0); } COpenGLGrassRenderer::~COpenGLGrassRenderer() { // Delete GrassCluster Dynamic instance VB m_pRenderDevice->extGlDeleteBuffers(1, &m_GrassClusterInstanceVBID); // Delete GrassCluster VAO and VBO m_pRenderDevice->extGlDeleteBuffers(1, &m_nGrassClusterVBOID); m_pRenderDevice->extGlDeleteBuffers(1, &m_nGrassClusterIndexVBOID); m_pRenderDevice->extGlDeleteVertexArray(1, &m_nGrassClusterVAOID); releaseGrassTexture(); } void COpenGLGrassRenderer::initializeFromGrass(CSGPGrass* pGrass) { releaseGrassTexture(); createGrassTexture( pGrass->GetGrassTextureName() ); } void COpenGLGrassRenderer::update(float fDeltaTimeInSecond, const Vector4D& camPos, const Frustum& viewFrustum, CSGPGrass* pGrass) { m_vCameraPos = camPos; m_GrassClusterInstanceArray.clearQuick(); if( !pGrass ) return; SGPVertex_GRASS_Cluster tempData; CSGPTerrainChunk** pChunkEnd = pGrass->m_TerrainGrassChunks.end(); for( CSGPTerrainChunk** pChunkStart = pGrass->m_TerrainGrassChunks.begin(); pChunkStart < pChunkEnd; pChunkStart++ ) { if( !m_pRenderDevice->GetWorldSystemManager()->isTerrainChunkVisible( *pChunkStart ) ) continue; for(uint32 i=0; i<(*pChunkStart)->GetGrassClusterDataCount(); i++ ) { // None Flag, skip this Cluster uint32 nGrassSetFlag = (*pChunkStart)->GetGrassClusterData()[i].nData; if( nGrassSetFlag == 0 ) continue; tempData.vPosition[0] = (*pChunkStart)->GetGrassClusterData()[i].fPositionX; tempData.vPosition[1] = (*pChunkStart)->GetGrassClusterData()[i].fPositionY; tempData.vPosition[2] = (*pChunkStart)->GetGrassClusterData()[i].fPositionZ; tempData.vPosition[3] = float( (nGrassSetFlag & 0x00FF0000) >> 16 ); // GrassCluster is not inside the camera Frustum, skip this Cluster AABBox GrassClusterAABB; GrassClusterAABB += Vector3D(tempData.vPosition[0] - m_vDefaultGrassSize.x, tempData.vPosition[1], tempData.vPosition[2] - m_vDefaultGrassSize.x); GrassClusterAABB += Vector3D(tempData.vPosition[0] + m_vDefaultGrassSize.x, tempData.vPosition[1] + m_vDefaultGrassSize.y, tempData.vPosition[2] + m_vDefaultGrassSize.x); if( !GrassClusterAABB.Intersects(viewFrustum) ) continue; // GrassCluster is too far from the Grass Far Fading distance, skip this Cluster float fGrassDis = (m_vCameraPos - Vector4D(tempData.vPosition[0], tempData.vPosition[1], tempData.vPosition[2])).GetLength(); if( fGrassDis > CSGPWorldConfig::getInstance()->m_fGrassFarFadingEnd ) continue; // Too many grass Cluster if( m_GrassClusterInstanceArray.size() + 1 > INIT_GRASSCLUSTERINSTANCE_NUM ) continue; tempData.vPackedNormal[0] = (uint8)(((*pChunkStart)->GetGrassClusterData()[i].nPackedNormal & 0xFF000000) >> 24); tempData.vPackedNormal[1] = (uint8)(((*pChunkStart)->GetGrassClusterData()[i].nPackedNormal & 0x00FF0000) >> 16); tempData.vPackedNormal[2] = (uint8)(((*pChunkStart)->GetGrassClusterData()[i].nPackedNormal & 0x0000FF00) >> 8); tempData.vPackedNormal[3] = (uint8)((nGrassSetFlag & 0xFF000000) >> 24); tempData.vColor[0] = tempData.vColor[1] = tempData.vColor[2] = 1.0f; tempData.vColor[3] = 1.0f - jlimit(0.0f, 1.0f, (fGrassDis - CSGPWorldConfig::getInstance()->m_fGrassFarFadingStart) / (CSGPWorldConfig::getInstance()->m_fGrassFarFadingEnd - CSGPWorldConfig::getInstance()->m_fGrassFarFadingStart)); tempData.vWindParams[0] = ((nGrassSetFlag & 0x0000FF00) >> 8) / 255.0f; tempData.vWindParams[1] = 0.0f; tempData.vWindParams[2] = (nGrassSetFlag & 0x000000FF) / 255.0f; tempData.vWindParams[3] = 0.0f; m_GrassClusterInstanceArray.add( tempData ); } } // update grass rendering params m_vTimeParams.x += fDeltaTimeInSecond; m_vTimeParams.y = pGrass->m_fGrassPeriod; m_vLightMapTextureDimision.Set( 1.0f / m_pRenderDevice->GetWorldSystemManager()->getTerrain()->GetTerrainWidth(), 1.0f / m_pRenderDevice->GetWorldSystemManager()->getTerrain()->GetTerrainWidth() ); m_vWindDirForce = pGrass->m_vWindDirectionAndStrength; } void COpenGLGrassRenderer::render(CSGPGrass* pGrass) { if( m_GrassClusterInstanceArray.size() > 0 ) { COpenGLGrassRenderer::Sorter CompareGrassInstance(m_pRenderDevice); m_GrassClusterInstanceArray.sort(CompareGrassInstance); uint32 nSizeData = sizeof(SGPVertex_GRASS_Cluster) * m_GrassClusterInstanceArray.size(); // update Dynamic Instance Buffer m_pRenderDevice->extGlBindBuffer(GL_ARRAY_BUFFER, m_GrassClusterInstanceVBID); SGPVertex_GRASS_Cluster* pData = (SGPVertex_GRASS_Cluster*)m_pRenderDevice->extGlMapBufferRange(GL_ARRAY_BUFFER, 0, nSizeData, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); // copy data into the buffer memcpy(pData, m_GrassClusterInstanceArray.getRawDataPointer(), nSizeData); m_pRenderDevice->extGlUnmapBuffer(GL_ARRAY_BUFFER); } m_vTextureAtlas.Set( pGrass->m_fTextureAtlasNbX, pGrass->m_fTextureAtlasNbY, pGrass->m_fTextureAtlasW, pGrass->m_fTextureAtlasH ); } void COpenGLGrassRenderer::DoDrawGrassInstance() { if( m_GrassClusterInstanceArray.size() > 0 ) { COpenGLShaderManager *pShaderManager = static_cast<COpenGLShaderManager*>(m_pRenderDevice->GetShaderManager()); Matrix4x4 MVP = m_pRenderDevice->getOpenGLCamera()->m_mViewProjMatrix; ISGPMaterialSystem::MaterialList &Mat_List = m_pRenderDevice->GetMaterialSystem()->GetMaterialList(); const ISGPMaterialSystem::SGPMaterialInfo &GrassMaterial_info = Mat_List.getReference(ISGPMaterialSystem::eMaterial_grass); m_pRenderDevice->getOpenGLMaterialRenderer()->PushMaterial( GrassMaterial_info.m_material, MM_Add ); m_pRenderDevice->getOpenGLMaterialRenderer()->ComputeMaterialPass(); m_pRenderDevice->getOpenGLMaterialRenderer()->OnePassPreRenderMaterial(0); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->useProgram(); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("ViewProjMatrix", MVP); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("TextureAtlas", m_vTextureAtlas); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("vTimeParams", m_vTimeParams); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("vLightMapTextureDimision", m_vLightMapTextureDimision); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("vWindDirAndStrength", m_vWindDirForce); //pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("fFarPlane", m_pRenderDevice->getOpenGLCamera()->m_fFar); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("SunDirection", -m_pRenderDevice->GetWorldSystemManager()->getWorldSun()->getNormalizedSunDirection()); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("SunColor", m_pRenderDevice->getOpenGLSkydomeRenderer()->getSunColorAndIntensity()); m_pRenderDevice->GetTextureManager()->getTextureByID(m_GrassTextureID)->pSGPTexture->BindTexture2D(0); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("gSampler0", 0); m_pRenderDevice->GetTextureManager()->getTextureByID( m_pRenderDevice->getOpenGLTerrainRenderer()->getLightmapTextureID() )->pSGPTexture->BindTexture2D(1); pShaderManager->GetGLSLShaderProgram(SGPST_GRASS_INSTANCING)->setShaderUniform("gSamplerLightmap", 1); m_pRenderDevice->extGlBindVertexArray(m_nGrassClusterVAOID); m_pRenderDevice->extGlDrawElementsInstanced( GL_TRIANGLES, 6*3, GL_UNSIGNED_SHORT, (void*)0, m_GrassClusterInstanceArray.size() ); m_pRenderDevice->extGlBindVertexArray(0); m_pRenderDevice->getOpenGLMaterialRenderer()->OnePassPostRenderMaterial(0); m_pRenderDevice->getOpenGLMaterialRenderer()->PopMaterial(); } } void COpenGLGrassRenderer::createGrassTexture(const String& GrassTextureName) { // register Grass texture m_GrassTextureID = m_pRenderDevice->GetTextureManager()->registerTexture(GrassTextureName); } void COpenGLGrassRenderer::releaseGrassTexture() { // unregister Grass texture if( m_GrassTextureID != 0 ) m_pRenderDevice->GetTextureManager()->unRegisterTextureByID(m_GrassTextureID); m_GrassTextureID = 0; }
46.275
234
0.772247
[ "render" ]
34636e49980cb6f6ac321c7de20751b714b2bbb3
17,919
cc
C++
cpp/src/gandiva/interval_holder_test.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2021-12-03T13:50:32.000Z
2021-12-03T13:50:32.000Z
cpp/src/gandiva/interval_holder_test.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
3
2022-02-09T03:24:57.000Z
2022-02-14T22:26:27.000Z
cpp/src/gandiva/interval_holder_test.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2020-08-27T22:54:09.000Z
2020-08-27T22:54:09.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "gandiva/interval_holder.h" #include <gtest/gtest.h> #include <memory> #include <vector> #include "gandiva/execution_context.h" namespace gandiva { class TestIntervalHolder : public ::testing::Test { protected: ExecutionContext execution_context_; }; TEST_F(TestIntervalHolder, TestMatchAllPeriods) { std::shared_ptr<IntervalDaysHolder> interval_days_holder; std::shared_ptr<IntervalYearsHolder> interval_years_holder; auto status = IntervalDaysHolder::Make(0, &interval_days_holder); EXPECT_EQ(status.ok(), true) << status.message(); status = IntervalYearsHolder::Make(0, &interval_years_holder); EXPECT_EQ(status.ok(), true) << status.message(); auto& cast_interval_day = *interval_days_holder; auto& cast_interval_year = *interval_years_holder; // Pass only numbers to cast bool out_valid; std::string data("73834992"); int64_t response = cast_interval_day(&execution_context_, data.data(), 8, true, &out_valid); int64_t qty_days_in_response = 0; int64_t qty_millis_in_response = 73834992; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); int32_t response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 8, true, &out_valid); EXPECT_EQ(response_interval_yrs, 73834992); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); // Pass only years and days to cast data = "P12Y15D"; response = cast_interval_day(&execution_context_, data.data(), 7, true, &out_valid); qty_days_in_response = 15; qty_millis_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 7, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 144); // Pass years and days and months to cast data = "P12Y2M15D"; response = cast_interval_day(&execution_context_, data.data(), 9, true, &out_valid); qty_days_in_response = 15; qty_millis_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 9, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 146); // Pass days and months to cast data = "P5M13D"; response = cast_interval_day(&execution_context_, data.data(), 6, true, &out_valid); qty_days_in_response = 13; qty_millis_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 6, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 5); // Pass all possible fields cast data = "P2Y5M13DT10H42M21S"; response = cast_interval_day(&execution_context_, data.data(), 18, true, &out_valid); qty_days_in_response = 13; qty_millis_in_response = 38541000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 18, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 29); // Pass only time fields cast data = "PT10H42M21S"; response = cast_interval_day(&execution_context_, data.data(), 11, true, &out_valid); qty_days_in_response = 0; qty_millis_in_response = 38541000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 11, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 0); // Pass only time fields to cast without hours data = "PT42M21S"; response = cast_interval_day(&execution_context_, data.data(), 8, true, &out_valid); qty_days_in_response = 0; qty_millis_in_response = 2541000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 8, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 0); // Pass only weeks to cast data = "P25W"; response = cast_interval_day(&execution_context_, data.data(), 4, true, &out_valid); qty_days_in_response = 175; qty_millis_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 4, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 0); execution_context_.Reset(); // Pass all possible fields using real values data = "P2,5Y5,5M13,5DT10,5H42,5M21,5S"; response = cast_interval_day(&execution_context_, data.data(), 30, true, &out_valid); qty_days_in_response = 13; qty_millis_in_response = 40371500; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 30, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 35); // Pass all possible fields using real values data = "P2.5Y5.5M13.5DT10.5H42.5M21.5S"; response = cast_interval_day(&execution_context_, data.data(), 30, true, &out_valid); qty_days_in_response = 13; qty_millis_in_response = 40371500; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 30, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response_interval_yrs, 35); } TEST_F(TestIntervalHolder, TestMatchErrorsForCastIntervalDay) { std::shared_ptr<IntervalDaysHolder> interval_days_holder; std::shared_ptr<IntervalYearsHolder> interval_years_holder; auto status = IntervalDaysHolder::Make(0, &interval_days_holder); EXPECT_EQ(status.ok(), true) << status.message(); status = IntervalYearsHolder::Make(0, &interval_years_holder); EXPECT_EQ(status.ok(), true) << status.message(); auto& cast_interval_day = *interval_days_holder; auto& cast_interval_year = *interval_years_holder; // Pass an empty string bool out_valid; std::string data(" "); int64_t response = cast_interval_day(&execution_context_, data.data(), 1, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); int32_t response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 1, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); data = ""; response = cast_interval_day(&execution_context_, data.data(), 0, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 0, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); // Pass only days before years data = "P15D12Y"; response = cast_interval_day(&execution_context_, data.data(), 7, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 7, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); // Pass years and days and months in wrong order data = "P12M15D2Y"; response = cast_interval_day(&execution_context_, data.data(), 9, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 9, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); // Forget the P in the first position data = "5M13D"; response = cast_interval_day(&execution_context_, data.data(), 5, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 5, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); // Use m instead M in the period format data = "P2Y5M13DT10H42m21S"; response = cast_interval_day(&execution_context_, data.data(), 18, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 18, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); // Does not pass the T when defining only time fields data = "P10H42M21S"; response = cast_interval_day(&execution_context_, data.data(), 10, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 10, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); // Pass weeks with other variables data = "P2Y25W2M3D"; response = cast_interval_day(&execution_context_, data.data(), 10, true, &out_valid); EXPECT_EQ(response, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); response_interval_yrs = cast_interval_year(&execution_context_, data.data(), 10, true, &out_valid); EXPECT_EQ(response_interval_yrs, 0); EXPECT_FALSE(out_valid); EXPECT_TRUE(execution_context_.has_error()); execution_context_.Reset(); } TEST_F(TestIntervalHolder, TestUsingWeekFormatterForCastIntervalDay) { std::shared_ptr<IntervalDaysHolder> interval_holder; auto status = IntervalDaysHolder::Make(0, &interval_holder); EXPECT_EQ(status.ok(), true) << status.message(); auto& cast_interval_day = *interval_holder; bool out_valid; std::string data("P1W"); int64_t response = cast_interval_day(&execution_context_, data.data(), 3, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, 7); data = "P10W"; response = cast_interval_day(&execution_context_, data.data(), 4, true, &out_valid); EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, 70); execution_context_.Reset(); } TEST_F(TestIntervalHolder, TestUsingCompleteFormatterForCastIntervalDay) { std::shared_ptr<IntervalDaysHolder> interval_holder; auto status = IntervalDaysHolder::Make(0, &interval_holder); EXPECT_EQ(status.ok(), true) << status.message(); auto& cast_interval_day = *interval_holder; bool out_valid; std::string data("1742461111"); int64_t response = cast_interval_day(&execution_context_, data.data(), 10, true, &out_valid); int64_t qty_days_in_response = 20; int64_t qty_millis_in_response = 14461111; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); data = "P1Y1M1DT1H1M1S"; response = cast_interval_day(&execution_context_, data.data(), 14, true, &out_valid); qty_days_in_response = 1; qty_millis_in_response = 3661000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); data = "PT48H1M1S"; response = cast_interval_day(&execution_context_, data.data(), 9, true, &out_valid); qty_days_in_response = 2; qty_millis_in_response = 61000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); data = "PT1S"; response = cast_interval_day(&execution_context_, data.data(), 4, true, &out_valid); qty_days_in_response = 0; qty_millis_in_response = 1000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); data = "P10DT1S"; response = cast_interval_day(&execution_context_, data.data(), 7, true, &out_valid); qty_days_in_response = 10; qty_millis_in_response = 1000; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); execution_context_.Reset(); data = "P0DT0S"; response = cast_interval_day(&execution_context_, data.data(), 6, true, &out_valid); qty_days_in_response = 0; qty_millis_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_millis_in_response << 32) | qty_days_in_response); execution_context_.Reset(); } TEST_F(TestIntervalHolder, TestUsingCompleteFormatterForCastIntervalYear) { std::shared_ptr<IntervalYearsHolder> interval_years_holder; auto status = IntervalYearsHolder::Make(0, &interval_years_holder); EXPECT_EQ(status.ok(), true) << status.message(); auto& cast_interval_years = *interval_years_holder; bool out_valid; std::string data("65851111"); int32_t response = cast_interval_years(&execution_context_, data.data(), 8, true, &out_valid); int32_t qty_yrs_in_response = 0; int32_t qty_months_in_response = 65851111; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_yrs_in_response * 12) + qty_months_in_response); data = "P1Y1M1DT1H1M1S"; response = cast_interval_years(&execution_context_, data.data(), 14, true, &out_valid); qty_yrs_in_response = 1; qty_months_in_response = 1; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_yrs_in_response * 12) + qty_months_in_response); data = "PT48H1M1S"; response = cast_interval_years(&execution_context_, data.data(), 9, true, &out_valid); qty_yrs_in_response = 0; qty_months_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_yrs_in_response * 12) + qty_months_in_response); data = "P1Y"; response = cast_interval_years(&execution_context_, data.data(), 3, true, &out_valid); qty_yrs_in_response = 1; qty_months_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_yrs_in_response * 12) + qty_months_in_response); data = "P10MT1S"; response = cast_interval_years(&execution_context_, data.data(), 7, true, &out_valid); qty_yrs_in_response = 0; qty_months_in_response = 10; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_yrs_in_response * 12) + qty_months_in_response); execution_context_.Reset(); data = "P0Y0M"; response = cast_interval_years(&execution_context_, data.data(), 5, true, &out_valid); qty_yrs_in_response = 0; qty_months_in_response = 0; EXPECT_TRUE(out_valid); EXPECT_FALSE(execution_context_.has_error()); EXPECT_EQ(response, (qty_yrs_in_response * 12) + qty_months_in_response); execution_context_.Reset(); } } // namespace gandiva
35.553571
89
0.757297
[ "vector" ]
3463a7f841daa5ed2cf3f24c9ee626e88cf5ed42
5,960
hpp
C++
SU2-Quantum/Common/include/interface_interpolation/CRadialBasisFunction.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/include/interface_interpolation/CRadialBasisFunction.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/include/interface_interpolation/CRadialBasisFunction.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CRadialBasisFunction.hpp * \brief Radial basis function interpolation. * \author Joel Ho, P. Gomes * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "CInterpolator.hpp" #include "../option_structure.hpp" #include "../toolboxes/C2DContainer.hpp" /*! * \brief Radial basis function interpolation. */ class CRadialBasisFunction final : public CInterpolator { static_assert(su2passivematrix::Storage == StorageType::RowMajor, "This class relies on row major storage throughout."); private: unsigned long MinDonors = 0, AvgDonors = 0, MaxDonors = 0; passivedouble Density = 0.0, AvgCorrection = 0.0, MaxCorrection = 0.0; public: /*! * \brief Constructor of the class. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] iZone - index of the donor zone * \param[in] jZone - index of the target zone */ CRadialBasisFunction(CGeometry ****geometry_container, const CConfig* const* config, unsigned int iZone, unsigned int jZone); /*! * \brief Set up transfer matrix defining relation between two meshes * \param[in] config - Definition of the particular problem. */ void SetTransferCoeff(const CConfig* const* config) override; /*! * \brief Print information about the interpolation. */ void PrintStatistics(void) const override; /*! * \brief Compute the value of a radial basis function, this is static so it can be re-used. * \param[in] type - of radial basis function * \param[in] radius - the characteristic dimension * \param[in] dist - distance * \return value of the RBF. */ static su2double Get_RadialBasisValue(ENUM_RADIALBASIS type, const su2double radius, const su2double dist); /*! * \brief Compute the RBF "generator" matrix with or without polynomial terms. * \note Multiplying C_inv_trunc by a column vector gives specific coefficients for given "known values", * conversely, multiplying (on the left) by a row vector of polynomial and RBF values gives generic * interpolation coefficients for a given target evaluation point. * \param[in] type - Type of radial basis function. * \param[in] usePolynomial - Whether to use polynomial terms. * \param[in] radius - Normalizes point-to-point distance when computing RBF values. * \param[in] coords - Coordinates of the donor points. * \param[out] nPolynomial - Num of poly terms, -1 if !usePolynomial, nDim-1 if coords lie on plane, else nDim. * \param[out] keepPolynomialRow - Size nDim, signals which (if any) iDim was removed from polynomial term. * \param[out] C_inv_trunc - The generator matrix as described above. */ static void ComputeGeneratorMatrix(ENUM_RADIALBASIS type, bool usePolynomial, su2double radius, const su2activematrix& coords, int& nPolynomial, vector<int>& keepPolynomialRow, su2passivematrix& C_inv_trunc); /*! * \brief If the polynomial term is included in the interpolation, and the points lie on a plane, the matrix * becomes rank deficient and cannot be inverted. This method detects that condition and corrects it by * removing a row from P (the polynomial part of the interpolation matrix). * \param[in] max_diff_tol - Tolerance to detect whether points are on a plane. * \param[out] keep_row - Marks the dimensions of P kept. * \param[in,out] P - Polynomial part of the interpolation matrix, one row may be eliminated. * \return n_polynomial - Size of the polynomial part on exit (in practice nDim or nDim-1). */ static int CheckPolynomialTerms(su2double max_diff_tol, vector<int>& keep_row, su2passivematrix &P); private: /*! * \brief Helper function, prunes (by setting to zero) small interpolation coefficients, * i.e. <= tolerance*max(abs(coeffs)). The vector is re-scaled such that sum(coeffs)==1. * \param[in] tolerance - Relative pruning tolerance. * \param[in] size - Size of the coefficient vector. * \param[in,out] coeffs - Iterator to start of vector of interpolation coefficients. * \return Number of non-zero coefficients after pruning and correction factor. */ template<typename Float, typename Int, class ForwardIt> static pair<Int,Float> PruneSmallCoefficients(Float tolerance, Int size, ForwardIt coeffs) { /*--- Determine the pruning threshold. ---*/ Float thresh = 0.0; auto end = coeffs; for (Int i = 0; i < size; ++i) thresh = max(thresh, fabs(*(end++))); thresh *= tolerance; /*--- Prune and count non-zeros. ---*/ Int numNonZeros = 0; Float coeffSum = 0.0; for (auto it = coeffs; it != end; ++it) { if (fabs(*it) > thresh) { // keep coeffSum += *it; ++numNonZeros; } else { *it = 0.0; } // prune } /*--- Correct remaining coefficients, sum must be 1 for conservation. ---*/ Float correction = 1.0 / coeffSum; while (coeffs != end) *(coeffs++) *= correction; return make_pair(numNonZeros, correction); } };
42.571429
113
0.694295
[ "geometry", "vector" ]
3466abfd61da707163756585862f84a18ce44d58
406
cpp
C++
src/main.cpp
Roboy/roboy_realsense
7bc00290d02d456cd210b8614731a1534a5b5065
[ "BSD-3-Clause" ]
3
2019-05-12T08:36:02.000Z
2019-11-14T01:50:51.000Z
src/main.cpp
Roboy/roboy_realsense
7bc00290d02d456cd210b8614731a1534a5b5065
[ "BSD-3-Clause" ]
1
2019-07-26T11:05:17.000Z
2021-02-01T09:14:38.000Z
src/main.cpp
Roboy/roboy_realsense
7bc00290d02d456cd210b8614731a1534a5b5065
[ "BSD-3-Clause" ]
3
2019-01-08T10:43:05.000Z
2021-09-13T05:37:43.000Z
#include "roboy_realsense/roboyRealsense.hpp" int main(int argc, char* argv[]) { if (!ros::isInitialized()) { int argc = 0; char **argv = NULL; ros::init(argc, argv, "roboyRealsense"); } RoboyRealsense realsense; // vector<int> arucoIDs = {233,553,627,628,1010,153,292,62}; // RoboyRealsense realsense(arucoIDs); realsense.arucoDetection(); return 0; }
22.555556
63
0.623153
[ "vector" ]
3468582c02c4a29e97a0c274b4dfd3aef4f8ef62
376
cpp
C++
modules/recognition/src/recognition_pipeline.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
modules/recognition/src/recognition_pipeline.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
modules/recognition/src/recognition_pipeline.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
#include <pcl/impl/instantiate.hpp> #include <v4r/recognition/recognition_pipeline.h> namespace v4r { template<typename PointT> std::vector<std::pair<std::string,float> > RecognitionPipeline<PointT>::elapsed_time_; #define PCL_INSTANTIATE_RecognitionPipeline(T) template class V4R_EXPORTS RecognitionPipeline<T>; PCL_INSTANTIATE(RecognitionPipeline, (pcl::PointXYZRGB)) }
26.857143
97
0.81383
[ "vector" ]
346c4585a2409056601b07f2373ff228fd7dd7c7
6,606
cpp
C++
dev/Gems/WhiteBox/Code/Tests/WhiteBoxComponentTest.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/WhiteBox/Code/Tests/WhiteBoxComponentTest.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/WhiteBox/Code/Tests/WhiteBoxComponentTest.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "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. * */ #include "WhiteBox_precompiled.h" #include "Viewport/WhiteBoxManipulatorViews.h" #include "WhiteBoxTestFixtures.h" #include "WhiteBoxTestUtil.h" #include <AzFramework/Entity/EntityDebugDisplayBus.h> #include <AzToolsFramework/Entity/EditorEntityHelpers.h> #include <AzToolsFramework/Manipulators/LinearManipulator.h> #include <AzToolsFramework/Manipulators/ManipulatorManager.h> namespace UnitTest { static const AzToolsFramework::ManipulatorManagerId TestManipulatorManagerId = AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId")); class NullDebugDisplayRequests : public AzFramework::DebugDisplayRequests { }; class WhiteBoxManipulatorFixture : public WhiteBoxTestFixture { public: void SetUpEditorFixtureImpl() override; void TearDownEditorFixtureImpl() override; AZStd::unique_ptr<AzToolsFramework::ManipulatorManager> m_manipulatorManager; }; void WhiteBoxManipulatorFixture::SetUpEditorFixtureImpl() { m_manipulatorManager = AZStd::make_unique<AzToolsFramework::ManipulatorManager>(TestManipulatorManagerId); } void WhiteBoxManipulatorFixture::TearDownEditorFixtureImpl() { m_manipulatorManager.reset(); } TEST_F(WhiteBoxManipulatorFixture, ManipulatorBoundsRefreshedAfterBeingMarkedDirty) { namespace Api = WhiteBox::Api; // create and register the manipulator with the test manipulator manager auto manipulator = AzToolsFramework::LinearManipulator::MakeShared(AZ::Transform::CreateIdentity()); manipulator->Register(TestManipulatorManagerId); // create a simple white box mesh Api::InitializeAsUnitQuad(*m_whiteBox); // create polygon manipulator view from white box const Api::PolygonHandle polygonHandle = Api::FacePolygonHandle(*m_whiteBox, Api::FaceHandle{0}); const Api::VertexPositionsCollection outlines = Api::PolygonBorderVertexPositions(*m_whiteBox, polygonHandle); const AZStd::vector<AZ::Vector3> triangles = Api::PolygonFacesPositions(*m_whiteBox, polygonHandle); auto polygonView = WhiteBox::CreateManipulatorViewPolygon(triangles, outlines); AzToolsFramework::ManipulatorViews views; views.emplace_back(AZStd::move(polygonView)); manipulator->SetViews(views); // position the manipulator offset down the y axis const AZ::Vector3& initialPosition = AZ::Vector3::CreateAxisY(10.0f); manipulator->SetLocalPosition(initialPosition); // simple callback to update the manipulator's current position manipulator->InstallMouseMoveCallback( [initialPosition, &manipulator](const AzToolsFramework::LinearManipulator::Action& action) { manipulator->SetLocalPosition(initialPosition + action.LocalPositionOffset()); }); // center the camera at the origin AzFramework::CameraState cameraState; cameraState.m_position = AZ::Vector3::CreateZero(); // create a 'mock' mouse interaction simulating a ray firing down the positive y axis AzToolsFramework::ViewportInteraction::MouseInteraction mouseInteraction; mouseInteraction.m_mousePick.m_rayOrigin = AZ::Vector3::CreateZero(); mouseInteraction.m_mousePick.m_rayDirection = AZ::Vector3::CreateAxisY(); mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast<AZ::u32>(AzToolsFramework::ViewportInteraction::MouseButton::Left); // dummy debug display bus NullDebugDisplayRequests nullDebugDisplayRequests; // 'draw' manipulators to refresh and register bounds m_manipulatorManager->DrawManipulators(nullDebugDisplayRequests, cameraState, mouseInteraction); // move to a valid position so the mouse pick ray intersects the manipulator bound (view) m_manipulatorManager->ConsumeViewportMouseMove(mouseInteraction); // verify precondition - the manipulator recognizes is has the mouse over it EXPECT_TRUE(manipulator->MouseOver()); // simulate a click and drag motion (click and then move the camera to the right) m_manipulatorManager->ConsumeViewportMousePress(mouseInteraction); // next position mouseInteraction.m_mousePick.m_rayOrigin = AZ::Vector3::CreateAxisX(10.0f); mouseInteraction.m_mousePick.m_rayDirection = AZ::Vector3::CreateAxisY(); // move with mouse button down m_manipulatorManager->ConsumeViewportMouseMove(mouseInteraction); // simulate refreshing the bound while rendering m_manipulatorManager->DrawManipulators(nullDebugDisplayRequests, cameraState, mouseInteraction); // mouse up after (ending drag) m_manipulatorManager->ConsumeViewportMouseRelease(mouseInteraction); // simulate event from Qt (immediate mouse move after mouse up) m_manipulatorManager->ConsumeViewportMouseMove(mouseInteraction); // potential bound refresh while rendering m_manipulatorManager->DrawManipulators(nullDebugDisplayRequests, cameraState, mouseInteraction); EXPECT_TRUE(manipulator->MouseOver()); } TEST_F(EditorWhiteBoxComponentTestFixture, EditorWhiteBoxComponentRespectsEntityHiddenVisibility) { // given (precondition) EXPECT_TRUE(m_whiteBoxComponent->HasRenderMesh()); // when AzToolsFramework::SetEntityVisibility(m_whiteBoxEntityId, false); // then EXPECT_FALSE(m_whiteBoxComponent->HasRenderMesh()); } TEST_F(EditorWhiteBoxComponentTestFixture, EditorWhiteBoxComponentRespectsEntityHiddenVisibilityWhenActivated) { // given (precondition) EXPECT_TRUE(m_whiteBoxComponent->HasRenderMesh()); m_whiteBoxComponent->Deactivate(); // when AzToolsFramework::SetEntityVisibility(m_whiteBoxEntityId, false); // then m_whiteBoxComponent->Activate(); EXPECT_FALSE(m_whiteBoxComponent->HasRenderMesh()); } } // namespace UnitTest
43.460526
118
0.733727
[ "mesh", "vector", "transform" ]
34750803af5388b1a1095907d8c95aee4afe5a7d
2,939
hpp
C++
ql/experimental/models/cclgmpiecewise.hpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
4
2016-03-28T15:05:23.000Z
2020-02-17T23:05:57.000Z
ql/experimental/models/cclgmpiecewise.hpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
1
2015-02-02T20:32:43.000Z
2015-02-02T20:32:43.000Z
ql/experimental/models/cclgmpiecewise.hpp
pcaspers/quantlib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
10
2015-01-26T14:50:24.000Z
2015-10-23T07:41:30.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2015 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file cclgmpiecewise.hpp \brief cross currency parametrization using piecewise alpha, constant kappa, piecewise fx sigma, constant correlation */ #ifndef quantlib_cclgm_piecewise_hpp #define quantlib_cclgm_piecewise_hpp #include <ql/experimental/models/cclgmparametrization.hpp> #include <ql/experimental/models/lgmpiecewisealphaconstantkappa.hpp> #include <ql/experimental/models/lgmfxpiecewisesigma.hpp> #include <ql/experimental/math/piecewiseintegral.hpp> #include <ql/math/matrix.hpp> namespace QuantLib { namespace detail { class CcLgmPiecewise : public CcLgmParametrization<CcLgmPiecewise, LgmFxPiecewiseSigma, LgmPiecewiseAlphaConstantKappa> { public: CcLgmPiecewise( const std::vector<boost::shared_ptr< LgmFxParametrization<LgmFxPiecewiseSigma> > > &fxParametrizations, const std::vector<boost::shared_ptr<LgmParametrization< LgmPiecewiseAlphaConstantKappa> > > &lgmParametrizations, const Matrix &correlation); //! interface (required) const Real rho_alpha_alpha_impl(const Size i, const Size j) const; const Real rho_alpha_sigma_impl(const Size i, const Size j) const; const Real rho_sigma_sigma_impl(const Size i, const Size j) const; private: const Matrix &correlation_; const Size n_; }; //! interface (required) inline const Real CcLgmPiecewise::rho_alpha_alpha_impl(const Size i, const Size j) const { return correlation_[n_ + i][n_ + j]; } inline const Real CcLgmPiecewise::rho_alpha_sigma_impl(const Size i, const Size j) const { return correlation_[n_ + i][j]; } inline const Real CcLgmPiecewise::rho_sigma_sigma_impl(const Size i, const Size j) const { return correlation_[i][j]; } /*! TODO implement closed form solutions for the interface methods replacing the standard implementation which uses numerical integration */ /* ... */ } // namespace detail } // namespace QuantLib #endif
34.174419
80
0.700919
[ "vector" ]
3477288a0fb6802479eb816c4c10bfa1f44a6107
104,612
cpp
C++
src/gl.cpp
Romejanic/node-game-kit
5cf375200c4ab2dfe1fad0f9a4e69cad74a15723
[ "MIT" ]
1
2020-11-28T01:39:05.000Z
2020-11-28T01:39:05.000Z
src/gl.cpp
Romejanic/node-game-kit
5cf375200c4ab2dfe1fad0f9a4e69cad74a15723
[ "MIT" ]
1
2021-08-31T19:57:18.000Z
2021-08-31T19:57:18.000Z
src/gl.cpp
Romejanic/node-game-kit
5cf375200c4ab2dfe1fad0f9a4e69cad74a15723
[ "MIT" ]
null
null
null
/* * ====================== WARNING ======================== * This file is (mostly) autogenerated. It should NOT be edited * unless there are errors to fix or something has gone wrong. * * Instead, you should run: * npm run gen-src * * to automatically regenerate this file based on the associated * header file. */ #include <config.h> #include <native-helper.h> #include <GL/gl.h> //==========================STRUCTS==========================// #pragma region #pragma endregion //==========================METHODS==========================// #pragma region NATIVE_FUNCTION(TexPageCommitmentARB) { v8::Isolate* isolate = args.GetIsolate(); if(args.Length() < 9) { THROW_ERROR(" takes 9 arguments."); } if(!args[0]->IsNumber()) { THROW_TYPE_ERROR("target is of type number!"); } GLenum target = args[0]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[1]->IsNumber()) { THROW_TYPE_ERROR("level is of type number!"); } GLint level = args[1]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[2]->IsNumber()) { THROW_TYPE_ERROR("xoffset is of type number!"); } GLint xoffset = args[2]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[3]->IsNumber()) { THROW_TYPE_ERROR("yoffset is of type number!"); } GLint yoffset = args[3]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[4]->IsNumber()) { THROW_TYPE_ERROR("zoffset is of type number!"); } GLint zoffset = args[4]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[5]->IsNumber()) { THROW_TYPE_ERROR("width is of type number!"); } GLint width = args[4]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[6]->IsNumber()) { THROW_TYPE_ERROR("height is of type number!"); } GLint height = args[4]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[7]->IsNumber()) { THROW_TYPE_ERROR("depth is of type number!"); } GLint depth = args[4]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); if(!args[8]->IsNumber()) { THROW_TYPE_ERROR("commit is of type number!"); } GLint commit = args[4]->IntegerValue(isolate->GetCurrentContext()).FromMaybe(0); glTexPageCommitmentARB(target, level, xoffset, yoffset, zoffset, width, height, depth, commit); } #pragma endregion //==========================INIT==========================// void ExportModule(v8::Local<v8::Object> exports) { v8::Isolate* isolate = exports->GetIsolate(); // Consts #pragma region EXPORT_CONST("VERSION_1_0", GL_VERSION_1_0); EXPORT_CONST("VERSION_1_1", GL_VERSION_1_1); EXPORT_CONST("DEPTH_BUFFER_BIT", GL_DEPTH_BUFFER_BIT); EXPORT_CONST("STENCIL_BUFFER_BIT", GL_STENCIL_BUFFER_BIT); EXPORT_CONST("COLOR_BUFFER_BIT", GL_COLOR_BUFFER_BIT); EXPORT_CONST("FALSE", GL_FALSE); EXPORT_CONST("TRUE", GL_TRUE); EXPORT_CONST("POINTS", GL_POINTS); EXPORT_CONST("LINES", GL_LINES); EXPORT_CONST("LINE_LOOP", GL_LINE_LOOP); EXPORT_CONST("LINE_STRIP", GL_LINE_STRIP); EXPORT_CONST("TRIANGLES", GL_TRIANGLES); EXPORT_CONST("TRIANGLE_STRIP", GL_TRIANGLE_STRIP); EXPORT_CONST("TRIANGLE_FAN", GL_TRIANGLE_FAN); EXPORT_CONST("QUADS", GL_QUADS); EXPORT_CONST("NEVER", GL_NEVER); EXPORT_CONST("LESS", GL_LESS); EXPORT_CONST("EQUAL", GL_EQUAL); EXPORT_CONST("LEQUAL", GL_LEQUAL); EXPORT_CONST("GREATER", GL_GREATER); EXPORT_CONST("NOTEQUAL", GL_NOTEQUAL); EXPORT_CONST("GEQUAL", GL_GEQUAL); EXPORT_CONST("ALWAYS", GL_ALWAYS); EXPORT_CONST("ZERO", GL_ZERO); EXPORT_CONST("ONE", GL_ONE); EXPORT_CONST("SRC_COLOR", GL_SRC_COLOR); EXPORT_CONST("ONE_MINUS_SRC_COLOR", GL_ONE_MINUS_SRC_COLOR); EXPORT_CONST("SRC_ALPHA", GL_SRC_ALPHA); EXPORT_CONST("ONE_MINUS_SRC_ALPHA", GL_ONE_MINUS_SRC_ALPHA); EXPORT_CONST("DST_ALPHA", GL_DST_ALPHA); EXPORT_CONST("ONE_MINUS_DST_ALPHA", GL_ONE_MINUS_DST_ALPHA); EXPORT_CONST("DST_COLOR", GL_DST_COLOR); EXPORT_CONST("ONE_MINUS_DST_COLOR", GL_ONE_MINUS_DST_COLOR); EXPORT_CONST("SRC_ALPHA_SATURATE", GL_SRC_ALPHA_SATURATE); EXPORT_CONST("NONE", GL_NONE); EXPORT_CONST("FRONT_LEFT", GL_FRONT_LEFT); EXPORT_CONST("FRONT_RIGHT", GL_FRONT_RIGHT); EXPORT_CONST("BACK_LEFT", GL_BACK_LEFT); EXPORT_CONST("BACK_RIGHT", GL_BACK_RIGHT); EXPORT_CONST("FRONT", GL_FRONT); EXPORT_CONST("BACK", GL_BACK); EXPORT_CONST("LEFT", GL_LEFT); EXPORT_CONST("RIGHT", GL_RIGHT); EXPORT_CONST("FRONT_AND_BACK", GL_FRONT_AND_BACK); EXPORT_CONST("NO_ERROR", GL_NO_ERROR); EXPORT_CONST("INVALID_ENUM", GL_INVALID_ENUM); EXPORT_CONST("INVALID_VALUE", GL_INVALID_VALUE); EXPORT_CONST("INVALID_OPERATION", GL_INVALID_OPERATION); EXPORT_CONST("OUT_OF_MEMORY", GL_OUT_OF_MEMORY); EXPORT_CONST("CW", GL_CW); EXPORT_CONST("CCW", GL_CCW); EXPORT_CONST("POINT_SIZE", GL_POINT_SIZE); EXPORT_CONST("POINT_SIZE_RANGE", GL_POINT_SIZE_RANGE); EXPORT_CONST("POINT_SIZE_GRANULARITY", GL_POINT_SIZE_GRANULARITY); EXPORT_CONST("LINE_SMOOTH", GL_LINE_SMOOTH); EXPORT_CONST("LINE_WIDTH", GL_LINE_WIDTH); EXPORT_CONST("LINE_WIDTH_RANGE", GL_LINE_WIDTH_RANGE); EXPORT_CONST("LINE_WIDTH_GRANULARITY", GL_LINE_WIDTH_GRANULARITY); EXPORT_CONST("POLYGON_MODE", GL_POLYGON_MODE); EXPORT_CONST("POLYGON_SMOOTH", GL_POLYGON_SMOOTH); EXPORT_CONST("CULL_FACE", GL_CULL_FACE); EXPORT_CONST("CULL_FACE_MODE", GL_CULL_FACE_MODE); EXPORT_CONST("FRONT_FACE", GL_FRONT_FACE); EXPORT_CONST("DEPTH_RANGE", GL_DEPTH_RANGE); EXPORT_CONST("DEPTH_TEST", GL_DEPTH_TEST); EXPORT_CONST("DEPTH_WRITEMASK", GL_DEPTH_WRITEMASK); EXPORT_CONST("DEPTH_CLEAR_VALUE", GL_DEPTH_CLEAR_VALUE); EXPORT_CONST("DEPTH_FUNC", GL_DEPTH_FUNC); EXPORT_CONST("STENCIL_TEST", GL_STENCIL_TEST); EXPORT_CONST("STENCIL_CLEAR_VALUE", GL_STENCIL_CLEAR_VALUE); EXPORT_CONST("STENCIL_FUNC", GL_STENCIL_FUNC); EXPORT_CONST("STENCIL_VALUE_MASK", GL_STENCIL_VALUE_MASK); EXPORT_CONST("STENCIL_FAIL", GL_STENCIL_FAIL); EXPORT_CONST("STENCIL_PASS_DEPTH_FAIL", GL_STENCIL_PASS_DEPTH_FAIL); EXPORT_CONST("STENCIL_PASS_DEPTH_PASS", GL_STENCIL_PASS_DEPTH_PASS); EXPORT_CONST("STENCIL_REF", GL_STENCIL_REF); EXPORT_CONST("STENCIL_WRITEMASK", GL_STENCIL_WRITEMASK); EXPORT_CONST("VIEWPORT", GL_VIEWPORT); EXPORT_CONST("DITHER", GL_DITHER); EXPORT_CONST("BLEND_DST", GL_BLEND_DST); EXPORT_CONST("BLEND_SRC", GL_BLEND_SRC); EXPORT_CONST("BLEND", GL_BLEND); EXPORT_CONST("LOGIC_OP_MODE", GL_LOGIC_OP_MODE); EXPORT_CONST("COLOR_LOGIC_OP", GL_COLOR_LOGIC_OP); EXPORT_CONST("DRAW_BUFFER", GL_DRAW_BUFFER); EXPORT_CONST("READ_BUFFER", GL_READ_BUFFER); EXPORT_CONST("SCISSOR_BOX", GL_SCISSOR_BOX); EXPORT_CONST("SCISSOR_TEST", GL_SCISSOR_TEST); EXPORT_CONST("COLOR_CLEAR_VALUE", GL_COLOR_CLEAR_VALUE); EXPORT_CONST("COLOR_WRITEMASK", GL_COLOR_WRITEMASK); EXPORT_CONST("DOUBLEBUFFER", GL_DOUBLEBUFFER); EXPORT_CONST("STEREO", GL_STEREO); EXPORT_CONST("LINE_SMOOTH_HINT", GL_LINE_SMOOTH_HINT); EXPORT_CONST("POLYGON_SMOOTH_HINT", GL_POLYGON_SMOOTH_HINT); EXPORT_CONST("UNPACK_SWAP_BYTES", GL_UNPACK_SWAP_BYTES); EXPORT_CONST("UNPACK_LSB_FIRST", GL_UNPACK_LSB_FIRST); EXPORT_CONST("UNPACK_ROW_LENGTH", GL_UNPACK_ROW_LENGTH); EXPORT_CONST("UNPACK_SKIP_ROWS", GL_UNPACK_SKIP_ROWS); EXPORT_CONST("UNPACK_SKIP_PIXELS", GL_UNPACK_SKIP_PIXELS); EXPORT_CONST("UNPACK_ALIGNMENT", GL_UNPACK_ALIGNMENT); EXPORT_CONST("PACK_SWAP_BYTES", GL_PACK_SWAP_BYTES); EXPORT_CONST("PACK_LSB_FIRST", GL_PACK_LSB_FIRST); EXPORT_CONST("PACK_ROW_LENGTH", GL_PACK_ROW_LENGTH); EXPORT_CONST("PACK_SKIP_ROWS", GL_PACK_SKIP_ROWS); EXPORT_CONST("PACK_SKIP_PIXELS", GL_PACK_SKIP_PIXELS); EXPORT_CONST("PACK_ALIGNMENT", GL_PACK_ALIGNMENT); EXPORT_CONST("MAX_TEXTURE_SIZE", GL_MAX_TEXTURE_SIZE); EXPORT_CONST("MAX_VIEWPORT_DIMS", GL_MAX_VIEWPORT_DIMS); EXPORT_CONST("SUBPIXEL_BITS", GL_SUBPIXEL_BITS); EXPORT_CONST("TEXTURE_1D", GL_TEXTURE_1D); EXPORT_CONST("TEXTURE_2D", GL_TEXTURE_2D); EXPORT_CONST("POLYGON_OFFSET_UNITS", GL_POLYGON_OFFSET_UNITS); EXPORT_CONST("POLYGON_OFFSET_POINT", GL_POLYGON_OFFSET_POINT); EXPORT_CONST("POLYGON_OFFSET_LINE", GL_POLYGON_OFFSET_LINE); EXPORT_CONST("POLYGON_OFFSET_FILL", GL_POLYGON_OFFSET_FILL); EXPORT_CONST("POLYGON_OFFSET_FACTOR", GL_POLYGON_OFFSET_FACTOR); EXPORT_CONST("TEXTURE_BINDING_1D", GL_TEXTURE_BINDING_1D); EXPORT_CONST("TEXTURE_BINDING_2D", GL_TEXTURE_BINDING_2D); EXPORT_CONST("TEXTURE_WIDTH", GL_TEXTURE_WIDTH); EXPORT_CONST("TEXTURE_HEIGHT", GL_TEXTURE_HEIGHT); EXPORT_CONST("TEXTURE_INTERNAL_FORMAT", GL_TEXTURE_INTERNAL_FORMAT); EXPORT_CONST("TEXTURE_BORDER_COLOR", GL_TEXTURE_BORDER_COLOR); EXPORT_CONST("TEXTURE_RED_SIZE", GL_TEXTURE_RED_SIZE); EXPORT_CONST("TEXTURE_GREEN_SIZE", GL_TEXTURE_GREEN_SIZE); EXPORT_CONST("TEXTURE_BLUE_SIZE", GL_TEXTURE_BLUE_SIZE); EXPORT_CONST("TEXTURE_ALPHA_SIZE", GL_TEXTURE_ALPHA_SIZE); EXPORT_CONST("DONT_CARE", GL_DONT_CARE); EXPORT_CONST("FASTEST", GL_FASTEST); EXPORT_CONST("NICEST", GL_NICEST); EXPORT_CONST("BYTE", GL_BYTE); EXPORT_CONST("UNSIGNED_BYTE", GL_UNSIGNED_BYTE); EXPORT_CONST("SHORT", GL_SHORT); EXPORT_CONST("UNSIGNED_SHORT", GL_UNSIGNED_SHORT); EXPORT_CONST("INT", GL_INT); EXPORT_CONST("UNSIGNED_INT", GL_UNSIGNED_INT); EXPORT_CONST("FLOAT", GL_FLOAT); EXPORT_CONST("DOUBLE", GL_DOUBLE); EXPORT_CONST("STACK_OVERFLOW", GL_STACK_OVERFLOW); EXPORT_CONST("STACK_UNDERFLOW", GL_STACK_UNDERFLOW); EXPORT_CONST("CLEAR", GL_CLEAR); EXPORT_CONST("AND", GL_AND); EXPORT_CONST("AND_REVERSE", GL_AND_REVERSE); EXPORT_CONST("COPY", GL_COPY); EXPORT_CONST("AND_INVERTED", GL_AND_INVERTED); EXPORT_CONST("NOOP", GL_NOOP); EXPORT_CONST("XOR", GL_XOR); EXPORT_CONST("OR", GL_OR); EXPORT_CONST("NOR", GL_NOR); EXPORT_CONST("EQUIV", GL_EQUIV); EXPORT_CONST("INVERT", GL_INVERT); EXPORT_CONST("OR_REVERSE", GL_OR_REVERSE); EXPORT_CONST("COPY_INVERTED", GL_COPY_INVERTED); EXPORT_CONST("OR_INVERTED", GL_OR_INVERTED); EXPORT_CONST("NAND", GL_NAND); EXPORT_CONST("SET", GL_SET); EXPORT_CONST("TEXTURE", GL_TEXTURE); EXPORT_CONST("COLOR", GL_COLOR); EXPORT_CONST("DEPTH", GL_DEPTH); EXPORT_CONST("STENCIL", GL_STENCIL); EXPORT_CONST("STENCIL_INDEX", GL_STENCIL_INDEX); EXPORT_CONST("DEPTH_COMPONENT", GL_DEPTH_COMPONENT); EXPORT_CONST("RED", GL_RED); EXPORT_CONST("GREEN", GL_GREEN); EXPORT_CONST("BLUE", GL_BLUE); EXPORT_CONST("ALPHA", GL_ALPHA); EXPORT_CONST("RGB", GL_RGB); EXPORT_CONST("RGBA", GL_RGBA); EXPORT_CONST("POINT", GL_POINT); EXPORT_CONST("LINE", GL_LINE); EXPORT_CONST("FILL", GL_FILL); EXPORT_CONST("KEEP", GL_KEEP); EXPORT_CONST("REPLACE", GL_REPLACE); EXPORT_CONST("INCR", GL_INCR); EXPORT_CONST("DECR", GL_DECR); EXPORT_CONST("VENDOR", GL_VENDOR); EXPORT_CONST("RENDERER", GL_RENDERER); EXPORT_CONST("VERSION", GL_VERSION); EXPORT_CONST("EXTENSIONS", GL_EXTENSIONS); EXPORT_CONST("NEAREST", GL_NEAREST); EXPORT_CONST("LINEAR", GL_LINEAR); EXPORT_CONST("NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST); EXPORT_CONST("LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST); EXPORT_CONST("NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR); EXPORT_CONST("LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR); EXPORT_CONST("TEXTURE_MAG_FILTER", GL_TEXTURE_MAG_FILTER); EXPORT_CONST("TEXTURE_MIN_FILTER", GL_TEXTURE_MIN_FILTER); EXPORT_CONST("TEXTURE_WRAP_S", GL_TEXTURE_WRAP_S); EXPORT_CONST("TEXTURE_WRAP_T", GL_TEXTURE_WRAP_T); EXPORT_CONST("PROXY_TEXTURE_1D", GL_PROXY_TEXTURE_1D); EXPORT_CONST("PROXY_TEXTURE_2D", GL_PROXY_TEXTURE_2D); EXPORT_CONST("REPEAT", GL_REPEAT); EXPORT_CONST("R3_G3_B2", GL_R3_G3_B2); EXPORT_CONST("RGB4", GL_RGB4); EXPORT_CONST("RGB5", GL_RGB5); EXPORT_CONST("RGB8", GL_RGB8); EXPORT_CONST("RGB10", GL_RGB10); EXPORT_CONST("RGB12", GL_RGB12); EXPORT_CONST("RGB16", GL_RGB16); EXPORT_CONST("RGBA2", GL_RGBA2); EXPORT_CONST("RGBA4", GL_RGBA4); EXPORT_CONST("RGB5_A1", GL_RGB5_A1); EXPORT_CONST("RGBA8", GL_RGBA8); EXPORT_CONST("RGB10_A2", GL_RGB10_A2); EXPORT_CONST("RGBA12", GL_RGBA12); EXPORT_CONST("RGBA16", GL_RGBA16); EXPORT_CONST("VERTEX_ARRAY", GL_VERTEX_ARRAY); EXPORT_CONST("VERSION_1_2", GL_VERSION_1_2); EXPORT_CONST("UNSIGNED_BYTE_3_3_2", GL_UNSIGNED_BYTE_3_3_2); EXPORT_CONST("UNSIGNED_SHORT_4_4_4_4", GL_UNSIGNED_SHORT_4_4_4_4); EXPORT_CONST("UNSIGNED_SHORT_5_5_5_1", GL_UNSIGNED_SHORT_5_5_5_1); EXPORT_CONST("UNSIGNED_INT_8_8_8_8", GL_UNSIGNED_INT_8_8_8_8); EXPORT_CONST("UNSIGNED_INT_10_10_10_2", GL_UNSIGNED_INT_10_10_10_2); EXPORT_CONST("TEXTURE_BINDING_3D", GL_TEXTURE_BINDING_3D); EXPORT_CONST("PACK_SKIP_IMAGES", GL_PACK_SKIP_IMAGES); EXPORT_CONST("PACK_IMAGE_HEIGHT", GL_PACK_IMAGE_HEIGHT); EXPORT_CONST("UNPACK_SKIP_IMAGES", GL_UNPACK_SKIP_IMAGES); EXPORT_CONST("UNPACK_IMAGE_HEIGHT", GL_UNPACK_IMAGE_HEIGHT); EXPORT_CONST("TEXTURE_3D", GL_TEXTURE_3D); EXPORT_CONST("PROXY_TEXTURE_3D", GL_PROXY_TEXTURE_3D); EXPORT_CONST("TEXTURE_DEPTH", GL_TEXTURE_DEPTH); EXPORT_CONST("TEXTURE_WRAP_R", GL_TEXTURE_WRAP_R); EXPORT_CONST("MAX_3D_TEXTURE_SIZE", GL_MAX_3D_TEXTURE_SIZE); EXPORT_CONST("UNSIGNED_BYTE_2_3_3_REV", GL_UNSIGNED_BYTE_2_3_3_REV); EXPORT_CONST("UNSIGNED_SHORT_5_6_5", GL_UNSIGNED_SHORT_5_6_5); EXPORT_CONST("UNSIGNED_SHORT_5_6_5_REV", GL_UNSIGNED_SHORT_5_6_5_REV); EXPORT_CONST("UNSIGNED_SHORT_4_4_4_4_REV", GL_UNSIGNED_SHORT_4_4_4_4_REV); EXPORT_CONST("UNSIGNED_SHORT_1_5_5_5_REV", GL_UNSIGNED_SHORT_1_5_5_5_REV); EXPORT_CONST("UNSIGNED_INT_8_8_8_8_REV", GL_UNSIGNED_INT_8_8_8_8_REV); EXPORT_CONST("UNSIGNED_INT_2_10_10_10_REV", GL_UNSIGNED_INT_2_10_10_10_REV); EXPORT_CONST("BGR", GL_BGR); EXPORT_CONST("BGRA", GL_BGRA); EXPORT_CONST("MAX_ELEMENTS_VERTICES", GL_MAX_ELEMENTS_VERTICES); EXPORT_CONST("MAX_ELEMENTS_INDICES", GL_MAX_ELEMENTS_INDICES); EXPORT_CONST("CLAMP_TO_EDGE", GL_CLAMP_TO_EDGE); EXPORT_CONST("TEXTURE_MIN_LOD", GL_TEXTURE_MIN_LOD); EXPORT_CONST("TEXTURE_MAX_LOD", GL_TEXTURE_MAX_LOD); EXPORT_CONST("TEXTURE_BASE_LEVEL", GL_TEXTURE_BASE_LEVEL); EXPORT_CONST("TEXTURE_MAX_LEVEL", GL_TEXTURE_MAX_LEVEL); EXPORT_CONST("SMOOTH_POINT_SIZE_RANGE", GL_SMOOTH_POINT_SIZE_RANGE); EXPORT_CONST("SMOOTH_POINT_SIZE_GRANULARITY", GL_SMOOTH_POINT_SIZE_GRANULARITY); EXPORT_CONST("SMOOTH_LINE_WIDTH_RANGE", GL_SMOOTH_LINE_WIDTH_RANGE); EXPORT_CONST("SMOOTH_LINE_WIDTH_GRANULARITY", GL_SMOOTH_LINE_WIDTH_GRANULARITY); EXPORT_CONST("ALIASED_LINE_WIDTH_RANGE", GL_ALIASED_LINE_WIDTH_RANGE); EXPORT_CONST("VERSION_1_3", GL_VERSION_1_3); EXPORT_CONST("TEXTURE0", GL_TEXTURE0); EXPORT_CONST("TEXTURE1", GL_TEXTURE1); EXPORT_CONST("TEXTURE2", GL_TEXTURE2); EXPORT_CONST("TEXTURE3", GL_TEXTURE3); EXPORT_CONST("TEXTURE4", GL_TEXTURE4); EXPORT_CONST("TEXTURE5", GL_TEXTURE5); EXPORT_CONST("TEXTURE6", GL_TEXTURE6); EXPORT_CONST("TEXTURE7", GL_TEXTURE7); EXPORT_CONST("TEXTURE8", GL_TEXTURE8); EXPORT_CONST("TEXTURE9", GL_TEXTURE9); EXPORT_CONST("TEXTURE10", GL_TEXTURE10); EXPORT_CONST("TEXTURE11", GL_TEXTURE11); EXPORT_CONST("TEXTURE12", GL_TEXTURE12); EXPORT_CONST("TEXTURE13", GL_TEXTURE13); EXPORT_CONST("TEXTURE14", GL_TEXTURE14); EXPORT_CONST("TEXTURE15", GL_TEXTURE15); EXPORT_CONST("TEXTURE16", GL_TEXTURE16); EXPORT_CONST("TEXTURE17", GL_TEXTURE17); EXPORT_CONST("TEXTURE18", GL_TEXTURE18); EXPORT_CONST("TEXTURE19", GL_TEXTURE19); EXPORT_CONST("TEXTURE20", GL_TEXTURE20); EXPORT_CONST("TEXTURE21", GL_TEXTURE21); EXPORT_CONST("TEXTURE22", GL_TEXTURE22); EXPORT_CONST("TEXTURE23", GL_TEXTURE23); EXPORT_CONST("TEXTURE24", GL_TEXTURE24); EXPORT_CONST("TEXTURE25", GL_TEXTURE25); EXPORT_CONST("TEXTURE26", GL_TEXTURE26); EXPORT_CONST("TEXTURE27", GL_TEXTURE27); EXPORT_CONST("TEXTURE28", GL_TEXTURE28); EXPORT_CONST("TEXTURE29", GL_TEXTURE29); EXPORT_CONST("TEXTURE30", GL_TEXTURE30); EXPORT_CONST("TEXTURE31", GL_TEXTURE31); EXPORT_CONST("ACTIVE_TEXTURE", GL_ACTIVE_TEXTURE); EXPORT_CONST("MULTISAMPLE", GL_MULTISAMPLE); EXPORT_CONST("SAMPLE_ALPHA_TO_COVERAGE", GL_SAMPLE_ALPHA_TO_COVERAGE); EXPORT_CONST("SAMPLE_ALPHA_TO_ONE", GL_SAMPLE_ALPHA_TO_ONE); EXPORT_CONST("SAMPLE_COVERAGE", GL_SAMPLE_COVERAGE); EXPORT_CONST("SAMPLE_BUFFERS", GL_SAMPLE_BUFFERS); EXPORT_CONST("SAMPLES", GL_SAMPLES); EXPORT_CONST("SAMPLE_COVERAGE_VALUE", GL_SAMPLE_COVERAGE_VALUE); EXPORT_CONST("SAMPLE_COVERAGE_INVERT", GL_SAMPLE_COVERAGE_INVERT); EXPORT_CONST("TEXTURE_CUBE_MAP", GL_TEXTURE_CUBE_MAP); EXPORT_CONST("TEXTURE_BINDING_CUBE_MAP", GL_TEXTURE_BINDING_CUBE_MAP); EXPORT_CONST("TEXTURE_CUBE_MAP_POSITIVE_X", GL_TEXTURE_CUBE_MAP_POSITIVE_X); EXPORT_CONST("TEXTURE_CUBE_MAP_NEGATIVE_X", GL_TEXTURE_CUBE_MAP_NEGATIVE_X); EXPORT_CONST("TEXTURE_CUBE_MAP_POSITIVE_Y", GL_TEXTURE_CUBE_MAP_POSITIVE_Y); EXPORT_CONST("TEXTURE_CUBE_MAP_NEGATIVE_Y", GL_TEXTURE_CUBE_MAP_NEGATIVE_Y); EXPORT_CONST("TEXTURE_CUBE_MAP_POSITIVE_Z", GL_TEXTURE_CUBE_MAP_POSITIVE_Z); EXPORT_CONST("TEXTURE_CUBE_MAP_NEGATIVE_Z", GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); EXPORT_CONST("PROXY_TEXTURE_CUBE_MAP", GL_PROXY_TEXTURE_CUBE_MAP); EXPORT_CONST("MAX_CUBE_MAP_TEXTURE_SIZE", GL_MAX_CUBE_MAP_TEXTURE_SIZE); EXPORT_CONST("COMPRESSED_RGB", GL_COMPRESSED_RGB); EXPORT_CONST("COMPRESSED_RGBA", GL_COMPRESSED_RGBA); EXPORT_CONST("TEXTURE_COMPRESSION_HINT", GL_TEXTURE_COMPRESSION_HINT); EXPORT_CONST("TEXTURE_COMPRESSED_IMAGE_SIZE", GL_TEXTURE_COMPRESSED_IMAGE_SIZE); EXPORT_CONST("TEXTURE_COMPRESSED", GL_TEXTURE_COMPRESSED); EXPORT_CONST("NUM_COMPRESSED_TEXTURE_FORMATS", GL_NUM_COMPRESSED_TEXTURE_FORMATS); EXPORT_CONST("COMPRESSED_TEXTURE_FORMATS", GL_COMPRESSED_TEXTURE_FORMATS); EXPORT_CONST("CLAMP_TO_BORDER", GL_CLAMP_TO_BORDER); EXPORT_CONST("VERSION_1_4", GL_VERSION_1_4); EXPORT_CONST("BLEND_DST_RGB", GL_BLEND_DST_RGB); EXPORT_CONST("BLEND_SRC_RGB", GL_BLEND_SRC_RGB); EXPORT_CONST("BLEND_DST_ALPHA", GL_BLEND_DST_ALPHA); EXPORT_CONST("BLEND_SRC_ALPHA", GL_BLEND_SRC_ALPHA); EXPORT_CONST("POINT_FADE_THRESHOLD_SIZE", GL_POINT_FADE_THRESHOLD_SIZE); EXPORT_CONST("DEPTH_COMPONENT16", GL_DEPTH_COMPONENT16); EXPORT_CONST("DEPTH_COMPONENT24", GL_DEPTH_COMPONENT24); EXPORT_CONST("DEPTH_COMPONENT32", GL_DEPTH_COMPONENT32); EXPORT_CONST("MIRRORED_REPEAT", GL_MIRRORED_REPEAT); EXPORT_CONST("MAX_TEXTURE_LOD_BIAS", GL_MAX_TEXTURE_LOD_BIAS); EXPORT_CONST("TEXTURE_LOD_BIAS", GL_TEXTURE_LOD_BIAS); EXPORT_CONST("INCR_WRAP", GL_INCR_WRAP); EXPORT_CONST("DECR_WRAP", GL_DECR_WRAP); EXPORT_CONST("TEXTURE_DEPTH_SIZE", GL_TEXTURE_DEPTH_SIZE); EXPORT_CONST("TEXTURE_COMPARE_MODE", GL_TEXTURE_COMPARE_MODE); EXPORT_CONST("TEXTURE_COMPARE_FUNC", GL_TEXTURE_COMPARE_FUNC); EXPORT_CONST("FUNC_ADD", GL_FUNC_ADD); EXPORT_CONST("FUNC_SUBTRACT", GL_FUNC_SUBTRACT); EXPORT_CONST("FUNC_REVERSE_SUBTRACT", GL_FUNC_REVERSE_SUBTRACT); EXPORT_CONST("MIN", GL_MIN); EXPORT_CONST("MAX", GL_MAX); EXPORT_CONST("CONSTANT_COLOR", GL_CONSTANT_COLOR); EXPORT_CONST("ONE_MINUS_CONSTANT_COLOR", GL_ONE_MINUS_CONSTANT_COLOR); EXPORT_CONST("CONSTANT_ALPHA", GL_CONSTANT_ALPHA); EXPORT_CONST("ONE_MINUS_CONSTANT_ALPHA", GL_ONE_MINUS_CONSTANT_ALPHA); EXPORT_CONST("VERSION_1_5", GL_VERSION_1_5); EXPORT_CONST("BUFFER_SIZE", GL_BUFFER_SIZE); EXPORT_CONST("BUFFER_USAGE", GL_BUFFER_USAGE); EXPORT_CONST("QUERY_COUNTER_BITS", GL_QUERY_COUNTER_BITS); EXPORT_CONST("CURRENT_QUERY", GL_CURRENT_QUERY); EXPORT_CONST("QUERY_RESULT", GL_QUERY_RESULT); EXPORT_CONST("QUERY_RESULT_AVAILABLE", GL_QUERY_RESULT_AVAILABLE); EXPORT_CONST("ARRAY_BUFFER", GL_ARRAY_BUFFER); EXPORT_CONST("ELEMENT_ARRAY_BUFFER", GL_ELEMENT_ARRAY_BUFFER); EXPORT_CONST("ARRAY_BUFFER_BINDING", GL_ARRAY_BUFFER_BINDING); EXPORT_CONST("ELEMENT_ARRAY_BUFFER_BINDING", GL_ELEMENT_ARRAY_BUFFER_BINDING); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING); EXPORT_CONST("READ_ONLY", GL_READ_ONLY); EXPORT_CONST("WRITE_ONLY", GL_WRITE_ONLY); EXPORT_CONST("READ_WRITE", GL_READ_WRITE); EXPORT_CONST("BUFFER_ACCESS", GL_BUFFER_ACCESS); EXPORT_CONST("BUFFER_MAPPED", GL_BUFFER_MAPPED); EXPORT_CONST("BUFFER_MAP_POINTER", GL_BUFFER_MAP_POINTER); EXPORT_CONST("STREAM_DRAW", GL_STREAM_DRAW); EXPORT_CONST("STREAM_READ", GL_STREAM_READ); EXPORT_CONST("STREAM_COPY", GL_STREAM_COPY); EXPORT_CONST("STATIC_DRAW", GL_STATIC_DRAW); EXPORT_CONST("STATIC_READ", GL_STATIC_READ); EXPORT_CONST("STATIC_COPY", GL_STATIC_COPY); EXPORT_CONST("DYNAMIC_DRAW", GL_DYNAMIC_DRAW); EXPORT_CONST("DYNAMIC_READ", GL_DYNAMIC_READ); EXPORT_CONST("DYNAMIC_COPY", GL_DYNAMIC_COPY); EXPORT_CONST("SAMPLES_PASSED", GL_SAMPLES_PASSED); EXPORT_CONST("SRC1_ALPHA", GL_SRC1_ALPHA); EXPORT_CONST("VERSION_2_0", GL_VERSION_2_0); EXPORT_CONST("BLEND_EQUATION_RGB", GL_BLEND_EQUATION_RGB); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_ENABLED", GL_VERTEX_ATTRIB_ARRAY_ENABLED); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_SIZE", GL_VERTEX_ATTRIB_ARRAY_SIZE); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_STRIDE", GL_VERTEX_ATTRIB_ARRAY_STRIDE); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_TYPE", GL_VERTEX_ATTRIB_ARRAY_TYPE); EXPORT_CONST("CURRENT_VERTEX_ATTRIB", GL_CURRENT_VERTEX_ATTRIB); EXPORT_CONST("VERTEX_PROGRAM_POINT_SIZE", GL_VERTEX_PROGRAM_POINT_SIZE); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_POINTER", GL_VERTEX_ATTRIB_ARRAY_POINTER); EXPORT_CONST("STENCIL_BACK_FUNC", GL_STENCIL_BACK_FUNC); EXPORT_CONST("STENCIL_BACK_FAIL", GL_STENCIL_BACK_FAIL); EXPORT_CONST("STENCIL_BACK_PASS_DEPTH_FAIL", GL_STENCIL_BACK_PASS_DEPTH_FAIL); EXPORT_CONST("STENCIL_BACK_PASS_DEPTH_PASS", GL_STENCIL_BACK_PASS_DEPTH_PASS); EXPORT_CONST("MAX_DRAW_BUFFERS", GL_MAX_DRAW_BUFFERS); EXPORT_CONST("DRAW_BUFFER0", GL_DRAW_BUFFER0); EXPORT_CONST("DRAW_BUFFER1", GL_DRAW_BUFFER1); EXPORT_CONST("DRAW_BUFFER2", GL_DRAW_BUFFER2); EXPORT_CONST("DRAW_BUFFER3", GL_DRAW_BUFFER3); EXPORT_CONST("DRAW_BUFFER4", GL_DRAW_BUFFER4); EXPORT_CONST("DRAW_BUFFER5", GL_DRAW_BUFFER5); EXPORT_CONST("DRAW_BUFFER6", GL_DRAW_BUFFER6); EXPORT_CONST("DRAW_BUFFER7", GL_DRAW_BUFFER7); EXPORT_CONST("DRAW_BUFFER8", GL_DRAW_BUFFER8); EXPORT_CONST("DRAW_BUFFER9", GL_DRAW_BUFFER9); EXPORT_CONST("DRAW_BUFFER10", GL_DRAW_BUFFER10); EXPORT_CONST("DRAW_BUFFER11", GL_DRAW_BUFFER11); EXPORT_CONST("DRAW_BUFFER12", GL_DRAW_BUFFER12); EXPORT_CONST("DRAW_BUFFER13", GL_DRAW_BUFFER13); EXPORT_CONST("DRAW_BUFFER14", GL_DRAW_BUFFER14); EXPORT_CONST("DRAW_BUFFER15", GL_DRAW_BUFFER15); EXPORT_CONST("BLEND_EQUATION_ALPHA", GL_BLEND_EQUATION_ALPHA); EXPORT_CONST("MAX_VERTEX_ATTRIBS", GL_MAX_VERTEX_ATTRIBS); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_NORMALIZED", GL_VERTEX_ATTRIB_ARRAY_NORMALIZED); EXPORT_CONST("MAX_TEXTURE_IMAGE_UNITS", GL_MAX_TEXTURE_IMAGE_UNITS); EXPORT_CONST("FRAGMENT_SHADER", GL_FRAGMENT_SHADER); EXPORT_CONST("VERTEX_SHADER", GL_VERTEX_SHADER); EXPORT_CONST("MAX_FRAGMENT_UNIFORM_COMPONENTS", GL_MAX_FRAGMENT_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_VERTEX_UNIFORM_COMPONENTS", GL_MAX_VERTEX_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_VARYING_FLOATS", GL_MAX_VARYING_FLOATS); EXPORT_CONST("MAX_VERTEX_TEXTURE_IMAGE_UNITS", GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS); EXPORT_CONST("MAX_COMBINED_TEXTURE_IMAGE_UNITS", GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS); EXPORT_CONST("SHADER_TYPE", GL_SHADER_TYPE); EXPORT_CONST("FLOAT_VEC2", GL_FLOAT_VEC2); EXPORT_CONST("FLOAT_VEC3", GL_FLOAT_VEC3); EXPORT_CONST("FLOAT_VEC4", GL_FLOAT_VEC4); EXPORT_CONST("INT_VEC2", GL_INT_VEC2); EXPORT_CONST("INT_VEC3", GL_INT_VEC3); EXPORT_CONST("INT_VEC4", GL_INT_VEC4); EXPORT_CONST("BOOL", GL_BOOL); EXPORT_CONST("BOOL_VEC2", GL_BOOL_VEC2); EXPORT_CONST("BOOL_VEC3", GL_BOOL_VEC3); EXPORT_CONST("BOOL_VEC4", GL_BOOL_VEC4); EXPORT_CONST("FLOAT_MAT2", GL_FLOAT_MAT2); EXPORT_CONST("FLOAT_MAT3", GL_FLOAT_MAT3); EXPORT_CONST("FLOAT_MAT4", GL_FLOAT_MAT4); EXPORT_CONST("SAMPLER_1D", GL_SAMPLER_1D); EXPORT_CONST("SAMPLER_2D", GL_SAMPLER_2D); EXPORT_CONST("SAMPLER_3D", GL_SAMPLER_3D); EXPORT_CONST("SAMPLER_CUBE", GL_SAMPLER_CUBE); EXPORT_CONST("SAMPLER_1D_SHADOW", GL_SAMPLER_1D_SHADOW); EXPORT_CONST("SAMPLER_2D_SHADOW", GL_SAMPLER_2D_SHADOW); EXPORT_CONST("DELETE_STATUS", GL_DELETE_STATUS); EXPORT_CONST("COMPILE_STATUS", GL_COMPILE_STATUS); EXPORT_CONST("LINK_STATUS", GL_LINK_STATUS); EXPORT_CONST("VALIDATE_STATUS", GL_VALIDATE_STATUS); EXPORT_CONST("INFO_LOG_LENGTH", GL_INFO_LOG_LENGTH); EXPORT_CONST("ATTACHED_SHADERS", GL_ATTACHED_SHADERS); EXPORT_CONST("ACTIVE_UNIFORMS", GL_ACTIVE_UNIFORMS); EXPORT_CONST("ACTIVE_UNIFORM_MAX_LENGTH", GL_ACTIVE_UNIFORM_MAX_LENGTH); EXPORT_CONST("SHADER_SOURCE_LENGTH", GL_SHADER_SOURCE_LENGTH); EXPORT_CONST("ACTIVE_ATTRIBUTES", GL_ACTIVE_ATTRIBUTES); EXPORT_CONST("ACTIVE_ATTRIBUTE_MAX_LENGTH", GL_ACTIVE_ATTRIBUTE_MAX_LENGTH); EXPORT_CONST("FRAGMENT_SHADER_DERIVATIVE_HINT", GL_FRAGMENT_SHADER_DERIVATIVE_HINT); EXPORT_CONST("SHADING_LANGUAGE_VERSION", GL_SHADING_LANGUAGE_VERSION); EXPORT_CONST("CURRENT_PROGRAM", GL_CURRENT_PROGRAM); EXPORT_CONST("POINT_SPRITE_COORD_ORIGIN", GL_POINT_SPRITE_COORD_ORIGIN); EXPORT_CONST("LOWER_LEFT", GL_LOWER_LEFT); EXPORT_CONST("UPPER_LEFT", GL_UPPER_LEFT); EXPORT_CONST("STENCIL_BACK_REF", GL_STENCIL_BACK_REF); EXPORT_CONST("STENCIL_BACK_VALUE_MASK", GL_STENCIL_BACK_VALUE_MASK); EXPORT_CONST("STENCIL_BACK_WRITEMASK", GL_STENCIL_BACK_WRITEMASK); EXPORT_CONST("VERSION_2_1", GL_VERSION_2_1); EXPORT_CONST("PIXEL_PACK_BUFFER", GL_PIXEL_PACK_BUFFER); EXPORT_CONST("PIXEL_UNPACK_BUFFER", GL_PIXEL_UNPACK_BUFFER); EXPORT_CONST("PIXEL_PACK_BUFFER_BINDING", GL_PIXEL_PACK_BUFFER_BINDING); EXPORT_CONST("PIXEL_UNPACK_BUFFER_BINDING", GL_PIXEL_UNPACK_BUFFER_BINDING); EXPORT_CONST("FLOAT_MAT2x3", GL_FLOAT_MAT2x3); EXPORT_CONST("FLOAT_MAT2x4", GL_FLOAT_MAT2x4); EXPORT_CONST("FLOAT_MAT3x2", GL_FLOAT_MAT3x2); EXPORT_CONST("FLOAT_MAT3x4", GL_FLOAT_MAT3x4); EXPORT_CONST("FLOAT_MAT4x2", GL_FLOAT_MAT4x2); EXPORT_CONST("FLOAT_MAT4x3", GL_FLOAT_MAT4x3); EXPORT_CONST("SRGB", GL_SRGB); EXPORT_CONST("SRGB8", GL_SRGB8); EXPORT_CONST("SRGB_ALPHA", GL_SRGB_ALPHA); EXPORT_CONST("SRGB8_ALPHA8", GL_SRGB8_ALPHA8); EXPORT_CONST("COMPRESSED_SRGB", GL_COMPRESSED_SRGB); EXPORT_CONST("COMPRESSED_SRGB_ALPHA", GL_COMPRESSED_SRGB_ALPHA); EXPORT_CONST("VERSION_3_0", GL_VERSION_3_0); EXPORT_CONST("COMPARE_REF_TO_TEXTURE", GL_COMPARE_REF_TO_TEXTURE); EXPORT_CONST("CLIP_DISTANCE0", GL_CLIP_DISTANCE0); EXPORT_CONST("CLIP_DISTANCE1", GL_CLIP_DISTANCE1); EXPORT_CONST("CLIP_DISTANCE2", GL_CLIP_DISTANCE2); EXPORT_CONST("CLIP_DISTANCE3", GL_CLIP_DISTANCE3); EXPORT_CONST("CLIP_DISTANCE4", GL_CLIP_DISTANCE4); EXPORT_CONST("CLIP_DISTANCE5", GL_CLIP_DISTANCE5); EXPORT_CONST("CLIP_DISTANCE6", GL_CLIP_DISTANCE6); EXPORT_CONST("CLIP_DISTANCE7", GL_CLIP_DISTANCE7); EXPORT_CONST("MAX_CLIP_DISTANCES", GL_MAX_CLIP_DISTANCES); EXPORT_CONST("MAJOR_VERSION", GL_MAJOR_VERSION); EXPORT_CONST("MINOR_VERSION", GL_MINOR_VERSION); EXPORT_CONST("NUM_EXTENSIONS", GL_NUM_EXTENSIONS); EXPORT_CONST("CONTEXT_FLAGS", GL_CONTEXT_FLAGS); EXPORT_CONST("COMPRESSED_RED", GL_COMPRESSED_RED); EXPORT_CONST("COMPRESSED_RG", GL_COMPRESSED_RG); EXPORT_CONST("CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT", GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT); EXPORT_CONST("RGBA32F", GL_RGBA32F); EXPORT_CONST("RGB32F", GL_RGB32F); EXPORT_CONST("RGBA16F", GL_RGBA16F); EXPORT_CONST("RGB16F", GL_RGB16F); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_INTEGER", GL_VERTEX_ATTRIB_ARRAY_INTEGER); EXPORT_CONST("MAX_ARRAY_TEXTURE_LAYERS", GL_MAX_ARRAY_TEXTURE_LAYERS); EXPORT_CONST("MIN_PROGRAM_TEXEL_OFFSET", GL_MIN_PROGRAM_TEXEL_OFFSET); EXPORT_CONST("MAX_PROGRAM_TEXEL_OFFSET", GL_MAX_PROGRAM_TEXEL_OFFSET); EXPORT_CONST("CLAMP_READ_COLOR", GL_CLAMP_READ_COLOR); EXPORT_CONST("FIXED_ONLY", GL_FIXED_ONLY); EXPORT_CONST("MAX_VARYING_COMPONENTS", GL_MAX_VARYING_COMPONENTS); EXPORT_CONST("TEXTURE_1D_ARRAY", GL_TEXTURE_1D_ARRAY); EXPORT_CONST("PROXY_TEXTURE_1D_ARRAY", GL_PROXY_TEXTURE_1D_ARRAY); EXPORT_CONST("TEXTURE_2D_ARRAY", GL_TEXTURE_2D_ARRAY); EXPORT_CONST("PROXY_TEXTURE_2D_ARRAY", GL_PROXY_TEXTURE_2D_ARRAY); EXPORT_CONST("TEXTURE_BINDING_1D_ARRAY", GL_TEXTURE_BINDING_1D_ARRAY); EXPORT_CONST("TEXTURE_BINDING_2D_ARRAY", GL_TEXTURE_BINDING_2D_ARRAY); EXPORT_CONST("R11F_G11F_B10F", GL_R11F_G11F_B10F); EXPORT_CONST("UNSIGNED_INT_10F_11F_11F_REV", GL_UNSIGNED_INT_10F_11F_11F_REV); EXPORT_CONST("RGB9_E5", GL_RGB9_E5); EXPORT_CONST("UNSIGNED_INT_5_9_9_9_REV", GL_UNSIGNED_INT_5_9_9_9_REV); EXPORT_CONST("TEXTURE_SHARED_SIZE", GL_TEXTURE_SHARED_SIZE); EXPORT_CONST("TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH", GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_MODE", GL_TRANSFORM_FEEDBACK_BUFFER_MODE); EXPORT_CONST("MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS); EXPORT_CONST("TRANSFORM_FEEDBACK_VARYINGS", GL_TRANSFORM_FEEDBACK_VARYINGS); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_START", GL_TRANSFORM_FEEDBACK_BUFFER_START); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_SIZE", GL_TRANSFORM_FEEDBACK_BUFFER_SIZE); EXPORT_CONST("PRIMITIVES_GENERATED", GL_PRIMITIVES_GENERATED); EXPORT_CONST("TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN); EXPORT_CONST("RASTERIZER_DISCARD", GL_RASTERIZER_DISCARD); EXPORT_CONST("MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS); EXPORT_CONST("MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS); EXPORT_CONST("INTERLEAVED_ATTRIBS", GL_INTERLEAVED_ATTRIBS); EXPORT_CONST("SEPARATE_ATTRIBS", GL_SEPARATE_ATTRIBS); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER", GL_TRANSFORM_FEEDBACK_BUFFER); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_BINDING", GL_TRANSFORM_FEEDBACK_BUFFER_BINDING); EXPORT_CONST("RGBA32UI", GL_RGBA32UI); EXPORT_CONST("RGB32UI", GL_RGB32UI); EXPORT_CONST("RGBA16UI", GL_RGBA16UI); EXPORT_CONST("RGB16UI", GL_RGB16UI); EXPORT_CONST("RGBA8UI", GL_RGBA8UI); EXPORT_CONST("RGB8UI", GL_RGB8UI); EXPORT_CONST("RGBA32I", GL_RGBA32I); EXPORT_CONST("RGB32I", GL_RGB32I); EXPORT_CONST("RGBA16I", GL_RGBA16I); EXPORT_CONST("RGB16I", GL_RGB16I); EXPORT_CONST("RGBA8I", GL_RGBA8I); EXPORT_CONST("RGB8I", GL_RGB8I); EXPORT_CONST("RED_INTEGER", GL_RED_INTEGER); EXPORT_CONST("GREEN_INTEGER", GL_GREEN_INTEGER); EXPORT_CONST("BLUE_INTEGER", GL_BLUE_INTEGER); EXPORT_CONST("RGB_INTEGER", GL_RGB_INTEGER); EXPORT_CONST("RGBA_INTEGER", GL_RGBA_INTEGER); EXPORT_CONST("BGR_INTEGER", GL_BGR_INTEGER); EXPORT_CONST("BGRA_INTEGER", GL_BGRA_INTEGER); EXPORT_CONST("SAMPLER_1D_ARRAY", GL_SAMPLER_1D_ARRAY); EXPORT_CONST("SAMPLER_2D_ARRAY", GL_SAMPLER_2D_ARRAY); EXPORT_CONST("SAMPLER_1D_ARRAY_SHADOW", GL_SAMPLER_1D_ARRAY_SHADOW); EXPORT_CONST("SAMPLER_2D_ARRAY_SHADOW", GL_SAMPLER_2D_ARRAY_SHADOW); EXPORT_CONST("SAMPLER_CUBE_SHADOW", GL_SAMPLER_CUBE_SHADOW); EXPORT_CONST("UNSIGNED_INT_VEC2", GL_UNSIGNED_INT_VEC2); EXPORT_CONST("UNSIGNED_INT_VEC3", GL_UNSIGNED_INT_VEC3); EXPORT_CONST("UNSIGNED_INT_VEC4", GL_UNSIGNED_INT_VEC4); EXPORT_CONST("INT_SAMPLER_1D", GL_INT_SAMPLER_1D); EXPORT_CONST("INT_SAMPLER_2D", GL_INT_SAMPLER_2D); EXPORT_CONST("INT_SAMPLER_3D", GL_INT_SAMPLER_3D); EXPORT_CONST("INT_SAMPLER_CUBE", GL_INT_SAMPLER_CUBE); EXPORT_CONST("INT_SAMPLER_1D_ARRAY", GL_INT_SAMPLER_1D_ARRAY); EXPORT_CONST("INT_SAMPLER_2D_ARRAY", GL_INT_SAMPLER_2D_ARRAY); EXPORT_CONST("UNSIGNED_INT_SAMPLER_1D", GL_UNSIGNED_INT_SAMPLER_1D); EXPORT_CONST("UNSIGNED_INT_SAMPLER_2D", GL_UNSIGNED_INT_SAMPLER_2D); EXPORT_CONST("UNSIGNED_INT_SAMPLER_3D", GL_UNSIGNED_INT_SAMPLER_3D); EXPORT_CONST("UNSIGNED_INT_SAMPLER_CUBE", GL_UNSIGNED_INT_SAMPLER_CUBE); EXPORT_CONST("UNSIGNED_INT_SAMPLER_1D_ARRAY", GL_UNSIGNED_INT_SAMPLER_1D_ARRAY); EXPORT_CONST("UNSIGNED_INT_SAMPLER_2D_ARRAY", GL_UNSIGNED_INT_SAMPLER_2D_ARRAY); EXPORT_CONST("QUERY_WAIT", GL_QUERY_WAIT); EXPORT_CONST("QUERY_NO_WAIT", GL_QUERY_NO_WAIT); EXPORT_CONST("QUERY_BY_REGION_WAIT", GL_QUERY_BY_REGION_WAIT); EXPORT_CONST("QUERY_BY_REGION_NO_WAIT", GL_QUERY_BY_REGION_NO_WAIT); EXPORT_CONST("BUFFER_ACCESS_FLAGS", GL_BUFFER_ACCESS_FLAGS); EXPORT_CONST("BUFFER_MAP_LENGTH", GL_BUFFER_MAP_LENGTH); EXPORT_CONST("BUFFER_MAP_OFFSET", GL_BUFFER_MAP_OFFSET); EXPORT_CONST("DEPTH_COMPONENT32F", GL_DEPTH_COMPONENT32F); EXPORT_CONST("DEPTH32F_STENCIL8", GL_DEPTH32F_STENCIL8); EXPORT_CONST("FLOAT_32_UNSIGNED_INT_24_8_REV", GL_FLOAT_32_UNSIGNED_INT_24_8_REV); EXPORT_CONST("INVALID_FRAMEBUFFER_OPERATION", GL_INVALID_FRAMEBUFFER_OPERATION); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_RED_SIZE", GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE); EXPORT_CONST("FRAMEBUFFER_DEFAULT", GL_FRAMEBUFFER_DEFAULT); EXPORT_CONST("FRAMEBUFFER_UNDEFINED", GL_FRAMEBUFFER_UNDEFINED); EXPORT_CONST("DEPTH_STENCIL_ATTACHMENT", GL_DEPTH_STENCIL_ATTACHMENT); EXPORT_CONST("MAX_RENDERBUFFER_SIZE", GL_MAX_RENDERBUFFER_SIZE); EXPORT_CONST("DEPTH_STENCIL", GL_DEPTH_STENCIL); EXPORT_CONST("UNSIGNED_INT_24_8", GL_UNSIGNED_INT_24_8); EXPORT_CONST("DEPTH24_STENCIL8", GL_DEPTH24_STENCIL8); EXPORT_CONST("TEXTURE_STENCIL_SIZE", GL_TEXTURE_STENCIL_SIZE); EXPORT_CONST("TEXTURE_RED_TYPE", GL_TEXTURE_RED_TYPE); EXPORT_CONST("TEXTURE_GREEN_TYPE", GL_TEXTURE_GREEN_TYPE); EXPORT_CONST("TEXTURE_BLUE_TYPE", GL_TEXTURE_BLUE_TYPE); EXPORT_CONST("TEXTURE_ALPHA_TYPE", GL_TEXTURE_ALPHA_TYPE); EXPORT_CONST("TEXTURE_DEPTH_TYPE", GL_TEXTURE_DEPTH_TYPE); EXPORT_CONST("UNSIGNED_NORMALIZED", GL_UNSIGNED_NORMALIZED); EXPORT_CONST("FRAMEBUFFER_BINDING", GL_FRAMEBUFFER_BINDING); EXPORT_CONST("DRAW_FRAMEBUFFER_BINDING", GL_DRAW_FRAMEBUFFER_BINDING); EXPORT_CONST("RENDERBUFFER_BINDING", GL_RENDERBUFFER_BINDING); EXPORT_CONST("READ_FRAMEBUFFER", GL_READ_FRAMEBUFFER); EXPORT_CONST("DRAW_FRAMEBUFFER", GL_DRAW_FRAMEBUFFER); EXPORT_CONST("READ_FRAMEBUFFER_BINDING", GL_READ_FRAMEBUFFER_BINDING); EXPORT_CONST("RENDERBUFFER_SAMPLES", GL_RENDERBUFFER_SAMPLES); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER); EXPORT_CONST("FRAMEBUFFER_COMPLETE", GL_FRAMEBUFFER_COMPLETE); EXPORT_CONST("FRAMEBUFFER_INCOMPLETE_ATTACHMENT", GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT); EXPORT_CONST("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT); EXPORT_CONST("FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER", GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER); EXPORT_CONST("FRAMEBUFFER_INCOMPLETE_READ_BUFFER", GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER); EXPORT_CONST("FRAMEBUFFER_UNSUPPORTED", GL_FRAMEBUFFER_UNSUPPORTED); EXPORT_CONST("MAX_COLOR_ATTACHMENTS", GL_MAX_COLOR_ATTACHMENTS); EXPORT_CONST("COLOR_ATTACHMENT0", GL_COLOR_ATTACHMENT0); EXPORT_CONST("COLOR_ATTACHMENT1", GL_COLOR_ATTACHMENT1); EXPORT_CONST("COLOR_ATTACHMENT2", GL_COLOR_ATTACHMENT2); EXPORT_CONST("COLOR_ATTACHMENT3", GL_COLOR_ATTACHMENT3); EXPORT_CONST("COLOR_ATTACHMENT4", GL_COLOR_ATTACHMENT4); EXPORT_CONST("COLOR_ATTACHMENT5", GL_COLOR_ATTACHMENT5); EXPORT_CONST("COLOR_ATTACHMENT6", GL_COLOR_ATTACHMENT6); EXPORT_CONST("COLOR_ATTACHMENT7", GL_COLOR_ATTACHMENT7); EXPORT_CONST("COLOR_ATTACHMENT8", GL_COLOR_ATTACHMENT8); EXPORT_CONST("COLOR_ATTACHMENT9", GL_COLOR_ATTACHMENT9); EXPORT_CONST("COLOR_ATTACHMENT10", GL_COLOR_ATTACHMENT10); EXPORT_CONST("COLOR_ATTACHMENT11", GL_COLOR_ATTACHMENT11); EXPORT_CONST("COLOR_ATTACHMENT12", GL_COLOR_ATTACHMENT12); EXPORT_CONST("COLOR_ATTACHMENT13", GL_COLOR_ATTACHMENT13); EXPORT_CONST("COLOR_ATTACHMENT14", GL_COLOR_ATTACHMENT14); EXPORT_CONST("COLOR_ATTACHMENT15", GL_COLOR_ATTACHMENT15); EXPORT_CONST("COLOR_ATTACHMENT16", GL_COLOR_ATTACHMENT16); EXPORT_CONST("COLOR_ATTACHMENT17", GL_COLOR_ATTACHMENT17); EXPORT_CONST("COLOR_ATTACHMENT18", GL_COLOR_ATTACHMENT18); EXPORT_CONST("COLOR_ATTACHMENT19", GL_COLOR_ATTACHMENT19); EXPORT_CONST("COLOR_ATTACHMENT20", GL_COLOR_ATTACHMENT20); EXPORT_CONST("COLOR_ATTACHMENT21", GL_COLOR_ATTACHMENT21); EXPORT_CONST("COLOR_ATTACHMENT22", GL_COLOR_ATTACHMENT22); EXPORT_CONST("COLOR_ATTACHMENT23", GL_COLOR_ATTACHMENT23); EXPORT_CONST("COLOR_ATTACHMENT24", GL_COLOR_ATTACHMENT24); EXPORT_CONST("COLOR_ATTACHMENT25", GL_COLOR_ATTACHMENT25); EXPORT_CONST("COLOR_ATTACHMENT26", GL_COLOR_ATTACHMENT26); EXPORT_CONST("COLOR_ATTACHMENT27", GL_COLOR_ATTACHMENT27); EXPORT_CONST("COLOR_ATTACHMENT28", GL_COLOR_ATTACHMENT28); EXPORT_CONST("COLOR_ATTACHMENT29", GL_COLOR_ATTACHMENT29); EXPORT_CONST("COLOR_ATTACHMENT30", GL_COLOR_ATTACHMENT30); EXPORT_CONST("COLOR_ATTACHMENT31", GL_COLOR_ATTACHMENT31); EXPORT_CONST("DEPTH_ATTACHMENT", GL_DEPTH_ATTACHMENT); EXPORT_CONST("STENCIL_ATTACHMENT", GL_STENCIL_ATTACHMENT); EXPORT_CONST("FRAMEBUFFER", GL_FRAMEBUFFER); EXPORT_CONST("RENDERBUFFER", GL_RENDERBUFFER); EXPORT_CONST("RENDERBUFFER_WIDTH", GL_RENDERBUFFER_WIDTH); EXPORT_CONST("RENDERBUFFER_HEIGHT", GL_RENDERBUFFER_HEIGHT); EXPORT_CONST("RENDERBUFFER_INTERNAL_FORMAT", GL_RENDERBUFFER_INTERNAL_FORMAT); EXPORT_CONST("STENCIL_INDEX1", GL_STENCIL_INDEX1); EXPORT_CONST("STENCIL_INDEX4", GL_STENCIL_INDEX4); EXPORT_CONST("STENCIL_INDEX8", GL_STENCIL_INDEX8); EXPORT_CONST("STENCIL_INDEX16", GL_STENCIL_INDEX16); EXPORT_CONST("RENDERBUFFER_RED_SIZE", GL_RENDERBUFFER_RED_SIZE); EXPORT_CONST("RENDERBUFFER_GREEN_SIZE", GL_RENDERBUFFER_GREEN_SIZE); EXPORT_CONST("RENDERBUFFER_BLUE_SIZE", GL_RENDERBUFFER_BLUE_SIZE); EXPORT_CONST("RENDERBUFFER_ALPHA_SIZE", GL_RENDERBUFFER_ALPHA_SIZE); EXPORT_CONST("RENDERBUFFER_DEPTH_SIZE", GL_RENDERBUFFER_DEPTH_SIZE); EXPORT_CONST("RENDERBUFFER_STENCIL_SIZE", GL_RENDERBUFFER_STENCIL_SIZE); EXPORT_CONST("FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE); EXPORT_CONST("MAX_SAMPLES", GL_MAX_SAMPLES); EXPORT_CONST("FRAMEBUFFER_SRGB", GL_FRAMEBUFFER_SRGB); EXPORT_CONST("HALF_FLOAT", GL_HALF_FLOAT); EXPORT_CONST("MAP_READ_BIT", GL_MAP_READ_BIT); EXPORT_CONST("MAP_WRITE_BIT", GL_MAP_WRITE_BIT); EXPORT_CONST("MAP_INVALIDATE_RANGE_BIT", GL_MAP_INVALIDATE_RANGE_BIT); EXPORT_CONST("MAP_INVALIDATE_BUFFER_BIT", GL_MAP_INVALIDATE_BUFFER_BIT); EXPORT_CONST("MAP_FLUSH_EXPLICIT_BIT", GL_MAP_FLUSH_EXPLICIT_BIT); EXPORT_CONST("MAP_UNSYNCHRONIZED_BIT", GL_MAP_UNSYNCHRONIZED_BIT); EXPORT_CONST("COMPRESSED_RED_RGTC1", GL_COMPRESSED_RED_RGTC1); EXPORT_CONST("COMPRESSED_SIGNED_RED_RGTC1", GL_COMPRESSED_SIGNED_RED_RGTC1); EXPORT_CONST("COMPRESSED_RG_RGTC2", GL_COMPRESSED_RG_RGTC2); EXPORT_CONST("COMPRESSED_SIGNED_RG_RGTC2", GL_COMPRESSED_SIGNED_RG_RGTC2); EXPORT_CONST("RG", GL_RG); EXPORT_CONST("RG_INTEGER", GL_RG_INTEGER); EXPORT_CONST("R8", GL_R8); EXPORT_CONST("R16", GL_R16); EXPORT_CONST("RG8", GL_RG8); EXPORT_CONST("RG16", GL_RG16); EXPORT_CONST("R16F", GL_R16F); EXPORT_CONST("R32F", GL_R32F); EXPORT_CONST("RG16F", GL_RG16F); EXPORT_CONST("RG32F", GL_RG32F); EXPORT_CONST("R8I", GL_R8I); EXPORT_CONST("R8UI", GL_R8UI); EXPORT_CONST("R16I", GL_R16I); EXPORT_CONST("R16UI", GL_R16UI); EXPORT_CONST("R32I", GL_R32I); EXPORT_CONST("R32UI", GL_R32UI); EXPORT_CONST("RG8I", GL_RG8I); EXPORT_CONST("RG8UI", GL_RG8UI); EXPORT_CONST("RG16I", GL_RG16I); EXPORT_CONST("RG16UI", GL_RG16UI); EXPORT_CONST("RG32I", GL_RG32I); EXPORT_CONST("RG32UI", GL_RG32UI); EXPORT_CONST("VERTEX_ARRAY_BINDING", GL_VERTEX_ARRAY_BINDING); EXPORT_CONST("VERSION_3_1", GL_VERSION_3_1); EXPORT_CONST("SAMPLER_2D_RECT", GL_SAMPLER_2D_RECT); EXPORT_CONST("SAMPLER_2D_RECT_SHADOW", GL_SAMPLER_2D_RECT_SHADOW); EXPORT_CONST("SAMPLER_BUFFER", GL_SAMPLER_BUFFER); EXPORT_CONST("INT_SAMPLER_2D_RECT", GL_INT_SAMPLER_2D_RECT); EXPORT_CONST("INT_SAMPLER_BUFFER", GL_INT_SAMPLER_BUFFER); EXPORT_CONST("UNSIGNED_INT_SAMPLER_2D_RECT", GL_UNSIGNED_INT_SAMPLER_2D_RECT); EXPORT_CONST("UNSIGNED_INT_SAMPLER_BUFFER", GL_UNSIGNED_INT_SAMPLER_BUFFER); EXPORT_CONST("TEXTURE_BUFFER", GL_TEXTURE_BUFFER); EXPORT_CONST("MAX_TEXTURE_BUFFER_SIZE", GL_MAX_TEXTURE_BUFFER_SIZE); EXPORT_CONST("TEXTURE_BINDING_BUFFER", GL_TEXTURE_BINDING_BUFFER); EXPORT_CONST("TEXTURE_BUFFER_DATA_STORE_BINDING", GL_TEXTURE_BUFFER_DATA_STORE_BINDING); EXPORT_CONST("TEXTURE_RECTANGLE", GL_TEXTURE_RECTANGLE); EXPORT_CONST("TEXTURE_BINDING_RECTANGLE", GL_TEXTURE_BINDING_RECTANGLE); EXPORT_CONST("PROXY_TEXTURE_RECTANGLE", GL_PROXY_TEXTURE_RECTANGLE); EXPORT_CONST("MAX_RECTANGLE_TEXTURE_SIZE", GL_MAX_RECTANGLE_TEXTURE_SIZE); EXPORT_CONST("R8_SNORM", GL_R8_SNORM); EXPORT_CONST("RG8_SNORM", GL_RG8_SNORM); EXPORT_CONST("RGB8_SNORM", GL_RGB8_SNORM); EXPORT_CONST("RGBA8_SNORM", GL_RGBA8_SNORM); EXPORT_CONST("R16_SNORM", GL_R16_SNORM); EXPORT_CONST("RG16_SNORM", GL_RG16_SNORM); EXPORT_CONST("RGB16_SNORM", GL_RGB16_SNORM); EXPORT_CONST("RGBA16_SNORM", GL_RGBA16_SNORM); EXPORT_CONST("SIGNED_NORMALIZED", GL_SIGNED_NORMALIZED); EXPORT_CONST("PRIMITIVE_RESTART", GL_PRIMITIVE_RESTART); EXPORT_CONST("PRIMITIVE_RESTART_INDEX", GL_PRIMITIVE_RESTART_INDEX); EXPORT_CONST("COPY_READ_BUFFER", GL_COPY_READ_BUFFER); EXPORT_CONST("COPY_WRITE_BUFFER", GL_COPY_WRITE_BUFFER); EXPORT_CONST("UNIFORM_BUFFER", GL_UNIFORM_BUFFER); EXPORT_CONST("UNIFORM_BUFFER_BINDING", GL_UNIFORM_BUFFER_BINDING); EXPORT_CONST("UNIFORM_BUFFER_START", GL_UNIFORM_BUFFER_START); EXPORT_CONST("UNIFORM_BUFFER_SIZE", GL_UNIFORM_BUFFER_SIZE); EXPORT_CONST("MAX_VERTEX_UNIFORM_BLOCKS", GL_MAX_VERTEX_UNIFORM_BLOCKS); EXPORT_CONST("MAX_GEOMETRY_UNIFORM_BLOCKS", GL_MAX_GEOMETRY_UNIFORM_BLOCKS); EXPORT_CONST("MAX_FRAGMENT_UNIFORM_BLOCKS", GL_MAX_FRAGMENT_UNIFORM_BLOCKS); EXPORT_CONST("MAX_COMBINED_UNIFORM_BLOCKS", GL_MAX_COMBINED_UNIFORM_BLOCKS); EXPORT_CONST("MAX_UNIFORM_BUFFER_BINDINGS", GL_MAX_UNIFORM_BUFFER_BINDINGS); EXPORT_CONST("MAX_UNIFORM_BLOCK_SIZE", GL_MAX_UNIFORM_BLOCK_SIZE); EXPORT_CONST("MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS", GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS); EXPORT_CONST("UNIFORM_BUFFER_OFFSET_ALIGNMENT", GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT); EXPORT_CONST("ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH", GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH); EXPORT_CONST("ACTIVE_UNIFORM_BLOCKS", GL_ACTIVE_UNIFORM_BLOCKS); EXPORT_CONST("UNIFORM_TYPE", GL_UNIFORM_TYPE); EXPORT_CONST("UNIFORM_SIZE", GL_UNIFORM_SIZE); EXPORT_CONST("UNIFORM_NAME_LENGTH", GL_UNIFORM_NAME_LENGTH); EXPORT_CONST("UNIFORM_BLOCK_INDEX", GL_UNIFORM_BLOCK_INDEX); EXPORT_CONST("UNIFORM_OFFSET", GL_UNIFORM_OFFSET); EXPORT_CONST("UNIFORM_ARRAY_STRIDE", GL_UNIFORM_ARRAY_STRIDE); EXPORT_CONST("UNIFORM_MATRIX_STRIDE", GL_UNIFORM_MATRIX_STRIDE); EXPORT_CONST("UNIFORM_IS_ROW_MAJOR", GL_UNIFORM_IS_ROW_MAJOR); EXPORT_CONST("UNIFORM_BLOCK_BINDING", GL_UNIFORM_BLOCK_BINDING); EXPORT_CONST("UNIFORM_BLOCK_DATA_SIZE", GL_UNIFORM_BLOCK_DATA_SIZE); EXPORT_CONST("UNIFORM_BLOCK_NAME_LENGTH", GL_UNIFORM_BLOCK_NAME_LENGTH); EXPORT_CONST("UNIFORM_BLOCK_ACTIVE_UNIFORMS", GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS); EXPORT_CONST("UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES); EXPORT_CONST("UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER); EXPORT_CONST("UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER", GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER); EXPORT_CONST("UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER); EXPORT_CONST("INVALID_INDEX", GL_INVALID_INDEX); EXPORT_CONST("VERSION_3_2", GL_VERSION_3_2); EXPORT_CONST("CONTEXT_CORE_PROFILE_BIT", GL_CONTEXT_CORE_PROFILE_BIT); EXPORT_CONST("CONTEXT_COMPATIBILITY_PROFILE_BIT", GL_CONTEXT_COMPATIBILITY_PROFILE_BIT); EXPORT_CONST("LINES_ADJACENCY", GL_LINES_ADJACENCY); EXPORT_CONST("LINE_STRIP_ADJACENCY", GL_LINE_STRIP_ADJACENCY); EXPORT_CONST("TRIANGLES_ADJACENCY", GL_TRIANGLES_ADJACENCY); EXPORT_CONST("TRIANGLE_STRIP_ADJACENCY", GL_TRIANGLE_STRIP_ADJACENCY); EXPORT_CONST("PROGRAM_POINT_SIZE", GL_PROGRAM_POINT_SIZE); EXPORT_CONST("MAX_GEOMETRY_TEXTURE_IMAGE_UNITS", GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS); EXPORT_CONST("FRAMEBUFFER_ATTACHMENT_LAYERED", GL_FRAMEBUFFER_ATTACHMENT_LAYERED); EXPORT_CONST("FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS", GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS); EXPORT_CONST("GEOMETRY_SHADER", GL_GEOMETRY_SHADER); EXPORT_CONST("GEOMETRY_VERTICES_OUT", GL_GEOMETRY_VERTICES_OUT); EXPORT_CONST("GEOMETRY_INPUT_TYPE", GL_GEOMETRY_INPUT_TYPE); EXPORT_CONST("GEOMETRY_OUTPUT_TYPE", GL_GEOMETRY_OUTPUT_TYPE); EXPORT_CONST("MAX_GEOMETRY_UNIFORM_COMPONENTS", GL_MAX_GEOMETRY_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_GEOMETRY_OUTPUT_VERTICES", GL_MAX_GEOMETRY_OUTPUT_VERTICES); EXPORT_CONST("MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS", GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS); EXPORT_CONST("MAX_VERTEX_OUTPUT_COMPONENTS", GL_MAX_VERTEX_OUTPUT_COMPONENTS); EXPORT_CONST("MAX_GEOMETRY_INPUT_COMPONENTS", GL_MAX_GEOMETRY_INPUT_COMPONENTS); EXPORT_CONST("MAX_GEOMETRY_OUTPUT_COMPONENTS", GL_MAX_GEOMETRY_OUTPUT_COMPONENTS); EXPORT_CONST("MAX_FRAGMENT_INPUT_COMPONENTS", GL_MAX_FRAGMENT_INPUT_COMPONENTS); EXPORT_CONST("CONTEXT_PROFILE_MASK", GL_CONTEXT_PROFILE_MASK); EXPORT_CONST("DEPTH_CLAMP", GL_DEPTH_CLAMP); EXPORT_CONST("QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION", GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION); EXPORT_CONST("FIRST_VERTEX_CONVENTION", GL_FIRST_VERTEX_CONVENTION); EXPORT_CONST("LAST_VERTEX_CONVENTION", GL_LAST_VERTEX_CONVENTION); EXPORT_CONST("PROVOKING_VERTEX", GL_PROVOKING_VERTEX); EXPORT_CONST("TEXTURE_CUBE_MAP_SEAMLESS", GL_TEXTURE_CUBE_MAP_SEAMLESS); EXPORT_CONST("MAX_SERVER_WAIT_TIMEOUT", GL_MAX_SERVER_WAIT_TIMEOUT); EXPORT_CONST("OBJECT_TYPE", GL_OBJECT_TYPE); EXPORT_CONST("SYNC_CONDITION", GL_SYNC_CONDITION); EXPORT_CONST("SYNC_STATUS", GL_SYNC_STATUS); EXPORT_CONST("SYNC_FLAGS", GL_SYNC_FLAGS); EXPORT_CONST("SYNC_FENCE", GL_SYNC_FENCE); EXPORT_CONST("SYNC_GPU_COMMANDS_COMPLETE", GL_SYNC_GPU_COMMANDS_COMPLETE); EXPORT_CONST("UNSIGNALED", GL_UNSIGNALED); EXPORT_CONST("SIGNALED", GL_SIGNALED); EXPORT_CONST("ALREADY_SIGNALED", GL_ALREADY_SIGNALED); EXPORT_CONST("TIMEOUT_EXPIRED", GL_TIMEOUT_EXPIRED); EXPORT_CONST("CONDITION_SATISFIED", GL_CONDITION_SATISFIED); EXPORT_CONST("WAIT_FAILED", GL_WAIT_FAILED); EXPORT_CONST("TIMEOUT_IGNORED", GL_TIMEOUT_IGNORED); EXPORT_CONST("SYNC_FLUSH_COMMANDS_BIT", GL_SYNC_FLUSH_COMMANDS_BIT); EXPORT_CONST("SAMPLE_POSITION", GL_SAMPLE_POSITION); EXPORT_CONST("SAMPLE_MASK", GL_SAMPLE_MASK); EXPORT_CONST("SAMPLE_MASK_VALUE", GL_SAMPLE_MASK_VALUE); EXPORT_CONST("MAX_SAMPLE_MASK_WORDS", GL_MAX_SAMPLE_MASK_WORDS); EXPORT_CONST("TEXTURE_2D_MULTISAMPLE", GL_TEXTURE_2D_MULTISAMPLE); EXPORT_CONST("PROXY_TEXTURE_2D_MULTISAMPLE", GL_PROXY_TEXTURE_2D_MULTISAMPLE); EXPORT_CONST("TEXTURE_2D_MULTISAMPLE_ARRAY", GL_TEXTURE_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY", GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("TEXTURE_BINDING_2D_MULTISAMPLE", GL_TEXTURE_BINDING_2D_MULTISAMPLE); EXPORT_CONST("TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY", GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("TEXTURE_SAMPLES", GL_TEXTURE_SAMPLES); EXPORT_CONST("TEXTURE_FIXED_SAMPLE_LOCATIONS", GL_TEXTURE_FIXED_SAMPLE_LOCATIONS); EXPORT_CONST("SAMPLER_2D_MULTISAMPLE", GL_SAMPLER_2D_MULTISAMPLE); EXPORT_CONST("INT_SAMPLER_2D_MULTISAMPLE", GL_INT_SAMPLER_2D_MULTISAMPLE); EXPORT_CONST("UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE", GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE); EXPORT_CONST("SAMPLER_2D_MULTISAMPLE_ARRAY", GL_SAMPLER_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("INT_SAMPLER_2D_MULTISAMPLE_ARRAY", GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY", GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("MAX_COLOR_TEXTURE_SAMPLES", GL_MAX_COLOR_TEXTURE_SAMPLES); EXPORT_CONST("MAX_DEPTH_TEXTURE_SAMPLES", GL_MAX_DEPTH_TEXTURE_SAMPLES); EXPORT_CONST("MAX_INTEGER_SAMPLES", GL_MAX_INTEGER_SAMPLES); EXPORT_CONST("VERSION_3_3", GL_VERSION_3_3); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_DIVISOR", GL_VERTEX_ATTRIB_ARRAY_DIVISOR); EXPORT_CONST("SRC1_COLOR", GL_SRC1_COLOR); EXPORT_CONST("ONE_MINUS_SRC1_COLOR", GL_ONE_MINUS_SRC1_COLOR); EXPORT_CONST("ONE_MINUS_SRC1_ALPHA", GL_ONE_MINUS_SRC1_ALPHA); EXPORT_CONST("MAX_DUAL_SOURCE_DRAW_BUFFERS", GL_MAX_DUAL_SOURCE_DRAW_BUFFERS); EXPORT_CONST("ANY_SAMPLES_PASSED", GL_ANY_SAMPLES_PASSED); EXPORT_CONST("SAMPLER_BINDING", GL_SAMPLER_BINDING); EXPORT_CONST("RGB10_A2UI", GL_RGB10_A2UI); EXPORT_CONST("TEXTURE_SWIZZLE_R", GL_TEXTURE_SWIZZLE_R); EXPORT_CONST("TEXTURE_SWIZZLE_G", GL_TEXTURE_SWIZZLE_G); EXPORT_CONST("TEXTURE_SWIZZLE_B", GL_TEXTURE_SWIZZLE_B); EXPORT_CONST("TEXTURE_SWIZZLE_A", GL_TEXTURE_SWIZZLE_A); EXPORT_CONST("TEXTURE_SWIZZLE_RGBA", GL_TEXTURE_SWIZZLE_RGBA); EXPORT_CONST("TIME_ELAPSED", GL_TIME_ELAPSED); EXPORT_CONST("TIMESTAMP", GL_TIMESTAMP); EXPORT_CONST("INT_2_10_10_10_REV", GL_INT_2_10_10_10_REV); EXPORT_CONST("VERSION_4_0", GL_VERSION_4_0); EXPORT_CONST("SAMPLE_SHADING", GL_SAMPLE_SHADING); EXPORT_CONST("MIN_SAMPLE_SHADING_VALUE", GL_MIN_SAMPLE_SHADING_VALUE); EXPORT_CONST("MIN_PROGRAM_TEXTURE_GATHER_OFFSET", GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET); EXPORT_CONST("MAX_PROGRAM_TEXTURE_GATHER_OFFSET", GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET); EXPORT_CONST("TEXTURE_CUBE_MAP_ARRAY", GL_TEXTURE_CUBE_MAP_ARRAY); EXPORT_CONST("TEXTURE_BINDING_CUBE_MAP_ARRAY", GL_TEXTURE_BINDING_CUBE_MAP_ARRAY); EXPORT_CONST("PROXY_TEXTURE_CUBE_MAP_ARRAY", GL_PROXY_TEXTURE_CUBE_MAP_ARRAY); EXPORT_CONST("SAMPLER_CUBE_MAP_ARRAY", GL_SAMPLER_CUBE_MAP_ARRAY); EXPORT_CONST("SAMPLER_CUBE_MAP_ARRAY_SHADOW", GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW); EXPORT_CONST("INT_SAMPLER_CUBE_MAP_ARRAY", GL_INT_SAMPLER_CUBE_MAP_ARRAY); EXPORT_CONST("UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY", GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY); EXPORT_CONST("DRAW_INDIRECT_BUFFER", GL_DRAW_INDIRECT_BUFFER); EXPORT_CONST("DRAW_INDIRECT_BUFFER_BINDING", GL_DRAW_INDIRECT_BUFFER_BINDING); EXPORT_CONST("GEOMETRY_SHADER_INVOCATIONS", GL_GEOMETRY_SHADER_INVOCATIONS); EXPORT_CONST("MAX_GEOMETRY_SHADER_INVOCATIONS", GL_MAX_GEOMETRY_SHADER_INVOCATIONS); EXPORT_CONST("MIN_FRAGMENT_INTERPOLATION_OFFSET", GL_MIN_FRAGMENT_INTERPOLATION_OFFSET); EXPORT_CONST("MAX_FRAGMENT_INTERPOLATION_OFFSET", GL_MAX_FRAGMENT_INTERPOLATION_OFFSET); EXPORT_CONST("FRAGMENT_INTERPOLATION_OFFSET_BITS", GL_FRAGMENT_INTERPOLATION_OFFSET_BITS); EXPORT_CONST("MAX_VERTEX_STREAMS", GL_MAX_VERTEX_STREAMS); EXPORT_CONST("DOUBLE_VEC2", GL_DOUBLE_VEC2); EXPORT_CONST("DOUBLE_VEC3", GL_DOUBLE_VEC3); EXPORT_CONST("DOUBLE_VEC4", GL_DOUBLE_VEC4); EXPORT_CONST("DOUBLE_MAT2", GL_DOUBLE_MAT2); EXPORT_CONST("DOUBLE_MAT3", GL_DOUBLE_MAT3); EXPORT_CONST("DOUBLE_MAT4", GL_DOUBLE_MAT4); EXPORT_CONST("DOUBLE_MAT2x3", GL_DOUBLE_MAT2x3); EXPORT_CONST("DOUBLE_MAT2x4", GL_DOUBLE_MAT2x4); EXPORT_CONST("DOUBLE_MAT3x2", GL_DOUBLE_MAT3x2); EXPORT_CONST("DOUBLE_MAT3x4", GL_DOUBLE_MAT3x4); EXPORT_CONST("DOUBLE_MAT4x2", GL_DOUBLE_MAT4x2); EXPORT_CONST("DOUBLE_MAT4x3", GL_DOUBLE_MAT4x3); EXPORT_CONST("ACTIVE_SUBROUTINES", GL_ACTIVE_SUBROUTINES); EXPORT_CONST("ACTIVE_SUBROUTINE_UNIFORMS", GL_ACTIVE_SUBROUTINE_UNIFORMS); EXPORT_CONST("ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS", GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS); EXPORT_CONST("ACTIVE_SUBROUTINE_MAX_LENGTH", GL_ACTIVE_SUBROUTINE_MAX_LENGTH); EXPORT_CONST("ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH", GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH); EXPORT_CONST("MAX_SUBROUTINES", GL_MAX_SUBROUTINES); EXPORT_CONST("MAX_SUBROUTINE_UNIFORM_LOCATIONS", GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS); EXPORT_CONST("NUM_COMPATIBLE_SUBROUTINES", GL_NUM_COMPATIBLE_SUBROUTINES); EXPORT_CONST("COMPATIBLE_SUBROUTINES", GL_COMPATIBLE_SUBROUTINES); EXPORT_CONST("PATCHES", GL_PATCHES); EXPORT_CONST("PATCH_VERTICES", GL_PATCH_VERTICES); EXPORT_CONST("PATCH_DEFAULT_INNER_LEVEL", GL_PATCH_DEFAULT_INNER_LEVEL); EXPORT_CONST("PATCH_DEFAULT_OUTER_LEVEL", GL_PATCH_DEFAULT_OUTER_LEVEL); EXPORT_CONST("TESS_CONTROL_OUTPUT_VERTICES", GL_TESS_CONTROL_OUTPUT_VERTICES); EXPORT_CONST("TESS_GEN_MODE", GL_TESS_GEN_MODE); EXPORT_CONST("TESS_GEN_SPACING", GL_TESS_GEN_SPACING); EXPORT_CONST("TESS_GEN_VERTEX_ORDER", GL_TESS_GEN_VERTEX_ORDER); EXPORT_CONST("TESS_GEN_POINT_MODE", GL_TESS_GEN_POINT_MODE); EXPORT_CONST("ISOLINES", GL_ISOLINES); EXPORT_CONST("FRACTIONAL_ODD", GL_FRACTIONAL_ODD); EXPORT_CONST("FRACTIONAL_EVEN", GL_FRACTIONAL_EVEN); EXPORT_CONST("MAX_PATCH_VERTICES", GL_MAX_PATCH_VERTICES); EXPORT_CONST("MAX_TESS_GEN_LEVEL", GL_MAX_TESS_GEN_LEVEL); EXPORT_CONST("MAX_TESS_CONTROL_UNIFORM_COMPONENTS", GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_TESS_EVALUATION_UNIFORM_COMPONENTS", GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS", GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS); EXPORT_CONST("MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS", GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS); EXPORT_CONST("MAX_TESS_CONTROL_OUTPUT_COMPONENTS", GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS); EXPORT_CONST("MAX_TESS_PATCH_COMPONENTS", GL_MAX_TESS_PATCH_COMPONENTS); EXPORT_CONST("MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS", GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS); EXPORT_CONST("MAX_TESS_EVALUATION_OUTPUT_COMPONENTS", GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS); EXPORT_CONST("MAX_TESS_CONTROL_UNIFORM_BLOCKS", GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS); EXPORT_CONST("MAX_TESS_EVALUATION_UNIFORM_BLOCKS", GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS); EXPORT_CONST("MAX_TESS_CONTROL_INPUT_COMPONENTS", GL_MAX_TESS_CONTROL_INPUT_COMPONENTS); EXPORT_CONST("MAX_TESS_EVALUATION_INPUT_COMPONENTS", GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS); EXPORT_CONST("MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS", GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS", GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS); EXPORT_CONST("UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER", GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER); EXPORT_CONST("UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER", GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER); EXPORT_CONST("TESS_EVALUATION_SHADER", GL_TESS_EVALUATION_SHADER); EXPORT_CONST("TESS_CONTROL_SHADER", GL_TESS_CONTROL_SHADER); EXPORT_CONST("TRANSFORM_FEEDBACK", GL_TRANSFORM_FEEDBACK); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_PAUSED", GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_ACTIVE", GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE); EXPORT_CONST("TRANSFORM_FEEDBACK_BINDING", GL_TRANSFORM_FEEDBACK_BINDING); EXPORT_CONST("MAX_TRANSFORM_FEEDBACK_BUFFERS", GL_MAX_TRANSFORM_FEEDBACK_BUFFERS); EXPORT_CONST("VERSION_4_1", GL_VERSION_4_1); EXPORT_CONST("FIXED", GL_FIXED); EXPORT_CONST("IMPLEMENTATION_COLOR_READ_TYPE", GL_IMPLEMENTATION_COLOR_READ_TYPE); EXPORT_CONST("IMPLEMENTATION_COLOR_READ_FORMAT", GL_IMPLEMENTATION_COLOR_READ_FORMAT); EXPORT_CONST("LOW_FLOAT", GL_LOW_FLOAT); EXPORT_CONST("MEDIUM_FLOAT", GL_MEDIUM_FLOAT); EXPORT_CONST("HIGH_FLOAT", GL_HIGH_FLOAT); EXPORT_CONST("LOW_INT", GL_LOW_INT); EXPORT_CONST("MEDIUM_INT", GL_MEDIUM_INT); EXPORT_CONST("HIGH_INT", GL_HIGH_INT); EXPORT_CONST("SHADER_COMPILER", GL_SHADER_COMPILER); EXPORT_CONST("SHADER_BINARY_FORMATS", GL_SHADER_BINARY_FORMATS); EXPORT_CONST("NUM_SHADER_BINARY_FORMATS", GL_NUM_SHADER_BINARY_FORMATS); EXPORT_CONST("MAX_VERTEX_UNIFORM_VECTORS", GL_MAX_VERTEX_UNIFORM_VECTORS); EXPORT_CONST("MAX_VARYING_VECTORS", GL_MAX_VARYING_VECTORS); EXPORT_CONST("MAX_FRAGMENT_UNIFORM_VECTORS", GL_MAX_FRAGMENT_UNIFORM_VECTORS); EXPORT_CONST("RGB565", GL_RGB565); EXPORT_CONST("PROGRAM_BINARY_RETRIEVABLE_HINT", GL_PROGRAM_BINARY_RETRIEVABLE_HINT); EXPORT_CONST("PROGRAM_BINARY_LENGTH", GL_PROGRAM_BINARY_LENGTH); EXPORT_CONST("NUM_PROGRAM_BINARY_FORMATS", GL_NUM_PROGRAM_BINARY_FORMATS); EXPORT_CONST("PROGRAM_BINARY_FORMATS", GL_PROGRAM_BINARY_FORMATS); EXPORT_CONST("VERTEX_SHADER_BIT", GL_VERTEX_SHADER_BIT); EXPORT_CONST("FRAGMENT_SHADER_BIT", GL_FRAGMENT_SHADER_BIT); EXPORT_CONST("GEOMETRY_SHADER_BIT", GL_GEOMETRY_SHADER_BIT); EXPORT_CONST("TESS_CONTROL_SHADER_BIT", GL_TESS_CONTROL_SHADER_BIT); EXPORT_CONST("TESS_EVALUATION_SHADER_BIT", GL_TESS_EVALUATION_SHADER_BIT); EXPORT_CONST("ALL_SHADER_BITS", GL_ALL_SHADER_BITS); EXPORT_CONST("PROGRAM_SEPARABLE", GL_PROGRAM_SEPARABLE); EXPORT_CONST("ACTIVE_PROGRAM", GL_ACTIVE_PROGRAM); EXPORT_CONST("PROGRAM_PIPELINE_BINDING", GL_PROGRAM_PIPELINE_BINDING); EXPORT_CONST("MAX_VIEWPORTS", GL_MAX_VIEWPORTS); EXPORT_CONST("VIEWPORT_SUBPIXEL_BITS", GL_VIEWPORT_SUBPIXEL_BITS); EXPORT_CONST("VIEWPORT_BOUNDS_RANGE", GL_VIEWPORT_BOUNDS_RANGE); EXPORT_CONST("LAYER_PROVOKING_VERTEX", GL_LAYER_PROVOKING_VERTEX); EXPORT_CONST("VIEWPORT_INDEX_PROVOKING_VERTEX", GL_VIEWPORT_INDEX_PROVOKING_VERTEX); EXPORT_CONST("UNDEFINED_VERTEX", GL_UNDEFINED_VERTEX); EXPORT_CONST("VERSION_4_2", GL_VERSION_4_2); EXPORT_CONST("COPY_READ_BUFFER_BINDING", GL_COPY_READ_BUFFER_BINDING); EXPORT_CONST("COPY_WRITE_BUFFER_BINDING", GL_COPY_WRITE_BUFFER_BINDING); EXPORT_CONST("TRANSFORM_FEEDBACK_ACTIVE", GL_TRANSFORM_FEEDBACK_ACTIVE); EXPORT_CONST("TRANSFORM_FEEDBACK_PAUSED", GL_TRANSFORM_FEEDBACK_PAUSED); EXPORT_CONST("UNPACK_COMPRESSED_BLOCK_WIDTH", GL_UNPACK_COMPRESSED_BLOCK_WIDTH); EXPORT_CONST("UNPACK_COMPRESSED_BLOCK_HEIGHT", GL_UNPACK_COMPRESSED_BLOCK_HEIGHT); EXPORT_CONST("UNPACK_COMPRESSED_BLOCK_DEPTH", GL_UNPACK_COMPRESSED_BLOCK_DEPTH); EXPORT_CONST("UNPACK_COMPRESSED_BLOCK_SIZE", GL_UNPACK_COMPRESSED_BLOCK_SIZE); EXPORT_CONST("PACK_COMPRESSED_BLOCK_WIDTH", GL_PACK_COMPRESSED_BLOCK_WIDTH); EXPORT_CONST("PACK_COMPRESSED_BLOCK_HEIGHT", GL_PACK_COMPRESSED_BLOCK_HEIGHT); EXPORT_CONST("PACK_COMPRESSED_BLOCK_DEPTH", GL_PACK_COMPRESSED_BLOCK_DEPTH); EXPORT_CONST("PACK_COMPRESSED_BLOCK_SIZE", GL_PACK_COMPRESSED_BLOCK_SIZE); EXPORT_CONST("NUM_SAMPLE_COUNTS", GL_NUM_SAMPLE_COUNTS); EXPORT_CONST("MIN_MAP_BUFFER_ALIGNMENT", GL_MIN_MAP_BUFFER_ALIGNMENT); EXPORT_CONST("ATOMIC_COUNTER_BUFFER", GL_ATOMIC_COUNTER_BUFFER); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_BINDING", GL_ATOMIC_COUNTER_BUFFER_BINDING); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_START", GL_ATOMIC_COUNTER_BUFFER_START); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_SIZE", GL_ATOMIC_COUNTER_BUFFER_SIZE); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_DATA_SIZE", GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS", GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES", GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER", GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER", GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER", GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER", GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER", GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER); EXPORT_CONST("MAX_VERTEX_ATOMIC_COUNTER_BUFFERS", GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS", GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS", GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS", GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS", GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_COMBINED_ATOMIC_COUNTER_BUFFERS", GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_VERTEX_ATOMIC_COUNTERS", GL_MAX_VERTEX_ATOMIC_COUNTERS); EXPORT_CONST("MAX_TESS_CONTROL_ATOMIC_COUNTERS", GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS); EXPORT_CONST("MAX_TESS_EVALUATION_ATOMIC_COUNTERS", GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS); EXPORT_CONST("MAX_GEOMETRY_ATOMIC_COUNTERS", GL_MAX_GEOMETRY_ATOMIC_COUNTERS); EXPORT_CONST("MAX_FRAGMENT_ATOMIC_COUNTERS", GL_MAX_FRAGMENT_ATOMIC_COUNTERS); EXPORT_CONST("MAX_COMBINED_ATOMIC_COUNTERS", GL_MAX_COMBINED_ATOMIC_COUNTERS); EXPORT_CONST("MAX_ATOMIC_COUNTER_BUFFER_SIZE", GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE); EXPORT_CONST("MAX_ATOMIC_COUNTER_BUFFER_BINDINGS", GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS); EXPORT_CONST("ACTIVE_ATOMIC_COUNTER_BUFFERS", GL_ACTIVE_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX", GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX); EXPORT_CONST("UNSIGNED_INT_ATOMIC_COUNTER", GL_UNSIGNED_INT_ATOMIC_COUNTER); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_BARRIER_BIT", GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT); EXPORT_CONST("ELEMENT_ARRAY_BARRIER_BIT", GL_ELEMENT_ARRAY_BARRIER_BIT); EXPORT_CONST("UNIFORM_BARRIER_BIT", GL_UNIFORM_BARRIER_BIT); EXPORT_CONST("TEXTURE_FETCH_BARRIER_BIT", GL_TEXTURE_FETCH_BARRIER_BIT); EXPORT_CONST("SHADER_IMAGE_ACCESS_BARRIER_BIT", GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); EXPORT_CONST("COMMAND_BARRIER_BIT", GL_COMMAND_BARRIER_BIT); EXPORT_CONST("PIXEL_BUFFER_BARRIER_BIT", GL_PIXEL_BUFFER_BARRIER_BIT); EXPORT_CONST("TEXTURE_UPDATE_BARRIER_BIT", GL_TEXTURE_UPDATE_BARRIER_BIT); EXPORT_CONST("BUFFER_UPDATE_BARRIER_BIT", GL_BUFFER_UPDATE_BARRIER_BIT); EXPORT_CONST("FRAMEBUFFER_BARRIER_BIT", GL_FRAMEBUFFER_BARRIER_BIT); EXPORT_CONST("TRANSFORM_FEEDBACK_BARRIER_BIT", GL_TRANSFORM_FEEDBACK_BARRIER_BIT); EXPORT_CONST("ATOMIC_COUNTER_BARRIER_BIT", GL_ATOMIC_COUNTER_BARRIER_BIT); EXPORT_CONST("ALL_BARRIER_BITS", GL_ALL_BARRIER_BITS); EXPORT_CONST("MAX_IMAGE_UNITS", GL_MAX_IMAGE_UNITS); EXPORT_CONST("MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS", GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS); EXPORT_CONST("IMAGE_BINDING_NAME", GL_IMAGE_BINDING_NAME); EXPORT_CONST("IMAGE_BINDING_LEVEL", GL_IMAGE_BINDING_LEVEL); EXPORT_CONST("IMAGE_BINDING_LAYERED", GL_IMAGE_BINDING_LAYERED); EXPORT_CONST("IMAGE_BINDING_LAYER", GL_IMAGE_BINDING_LAYER); EXPORT_CONST("IMAGE_BINDING_ACCESS", GL_IMAGE_BINDING_ACCESS); EXPORT_CONST("IMAGE_1D", GL_IMAGE_1D); EXPORT_CONST("IMAGE_2D", GL_IMAGE_2D); EXPORT_CONST("IMAGE_3D", GL_IMAGE_3D); EXPORT_CONST("IMAGE_2D_RECT", GL_IMAGE_2D_RECT); EXPORT_CONST("IMAGE_CUBE", GL_IMAGE_CUBE); EXPORT_CONST("IMAGE_BUFFER", GL_IMAGE_BUFFER); EXPORT_CONST("IMAGE_1D_ARRAY", GL_IMAGE_1D_ARRAY); EXPORT_CONST("IMAGE_2D_ARRAY", GL_IMAGE_2D_ARRAY); EXPORT_CONST("IMAGE_CUBE_MAP_ARRAY", GL_IMAGE_CUBE_MAP_ARRAY); EXPORT_CONST("IMAGE_2D_MULTISAMPLE", GL_IMAGE_2D_MULTISAMPLE); EXPORT_CONST("IMAGE_2D_MULTISAMPLE_ARRAY", GL_IMAGE_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("INT_IMAGE_1D", GL_INT_IMAGE_1D); EXPORT_CONST("INT_IMAGE_2D", GL_INT_IMAGE_2D); EXPORT_CONST("INT_IMAGE_3D", GL_INT_IMAGE_3D); EXPORT_CONST("INT_IMAGE_2D_RECT", GL_INT_IMAGE_2D_RECT); EXPORT_CONST("INT_IMAGE_CUBE", GL_INT_IMAGE_CUBE); EXPORT_CONST("INT_IMAGE_BUFFER", GL_INT_IMAGE_BUFFER); EXPORT_CONST("INT_IMAGE_1D_ARRAY", GL_INT_IMAGE_1D_ARRAY); EXPORT_CONST("INT_IMAGE_2D_ARRAY", GL_INT_IMAGE_2D_ARRAY); EXPORT_CONST("INT_IMAGE_CUBE_MAP_ARRAY", GL_INT_IMAGE_CUBE_MAP_ARRAY); EXPORT_CONST("INT_IMAGE_2D_MULTISAMPLE", GL_INT_IMAGE_2D_MULTISAMPLE); EXPORT_CONST("INT_IMAGE_2D_MULTISAMPLE_ARRAY", GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("UNSIGNED_INT_IMAGE_1D", GL_UNSIGNED_INT_IMAGE_1D); EXPORT_CONST("UNSIGNED_INT_IMAGE_2D", GL_UNSIGNED_INT_IMAGE_2D); EXPORT_CONST("UNSIGNED_INT_IMAGE_3D", GL_UNSIGNED_INT_IMAGE_3D); EXPORT_CONST("UNSIGNED_INT_IMAGE_2D_RECT", GL_UNSIGNED_INT_IMAGE_2D_RECT); EXPORT_CONST("UNSIGNED_INT_IMAGE_CUBE", GL_UNSIGNED_INT_IMAGE_CUBE); EXPORT_CONST("UNSIGNED_INT_IMAGE_BUFFER", GL_UNSIGNED_INT_IMAGE_BUFFER); EXPORT_CONST("UNSIGNED_INT_IMAGE_1D_ARRAY", GL_UNSIGNED_INT_IMAGE_1D_ARRAY); EXPORT_CONST("UNSIGNED_INT_IMAGE_2D_ARRAY", GL_UNSIGNED_INT_IMAGE_2D_ARRAY); EXPORT_CONST("UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY", GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY); EXPORT_CONST("UNSIGNED_INT_IMAGE_2D_MULTISAMPLE", GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE); EXPORT_CONST("UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY", GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY); EXPORT_CONST("MAX_IMAGE_SAMPLES", GL_MAX_IMAGE_SAMPLES); EXPORT_CONST("IMAGE_BINDING_FORMAT", GL_IMAGE_BINDING_FORMAT); EXPORT_CONST("IMAGE_FORMAT_COMPATIBILITY_TYPE", GL_IMAGE_FORMAT_COMPATIBILITY_TYPE); EXPORT_CONST("IMAGE_FORMAT_COMPATIBILITY_BY_SIZE", GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE); EXPORT_CONST("IMAGE_FORMAT_COMPATIBILITY_BY_CLASS", GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS); EXPORT_CONST("MAX_VERTEX_IMAGE_UNIFORMS", GL_MAX_VERTEX_IMAGE_UNIFORMS); EXPORT_CONST("MAX_TESS_CONTROL_IMAGE_UNIFORMS", GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS); EXPORT_CONST("MAX_TESS_EVALUATION_IMAGE_UNIFORMS", GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS); EXPORT_CONST("MAX_GEOMETRY_IMAGE_UNIFORMS", GL_MAX_GEOMETRY_IMAGE_UNIFORMS); EXPORT_CONST("MAX_FRAGMENT_IMAGE_UNIFORMS", GL_MAX_FRAGMENT_IMAGE_UNIFORMS); EXPORT_CONST("MAX_COMBINED_IMAGE_UNIFORMS", GL_MAX_COMBINED_IMAGE_UNIFORMS); EXPORT_CONST("COMPRESSED_RGBA_BPTC_UNORM", GL_COMPRESSED_RGBA_BPTC_UNORM); EXPORT_CONST("COMPRESSED_SRGB_ALPHA_BPTC_UNORM", GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM); EXPORT_CONST("COMPRESSED_RGB_BPTC_SIGNED_FLOAT", GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT); EXPORT_CONST("COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT", GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT); EXPORT_CONST("TEXTURE_IMMUTABLE_FORMAT", GL_TEXTURE_IMMUTABLE_FORMAT); EXPORT_CONST("VERSION_4_3", GL_VERSION_4_3); EXPORT_CONST("NUM_SHADING_LANGUAGE_VERSIONS", GL_NUM_SHADING_LANGUAGE_VERSIONS); EXPORT_CONST("VERTEX_ATTRIB_ARRAY_LONG", GL_VERTEX_ATTRIB_ARRAY_LONG); EXPORT_CONST("COMPRESSED_RGB8_ETC2", GL_COMPRESSED_RGB8_ETC2); EXPORT_CONST("COMPRESSED_SRGB8_ETC2", GL_COMPRESSED_SRGB8_ETC2); EXPORT_CONST("COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2", GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2); EXPORT_CONST("COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2", GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2); EXPORT_CONST("COMPRESSED_RGBA8_ETC2_EAC", GL_COMPRESSED_RGBA8_ETC2_EAC); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ETC2_EAC", GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC); EXPORT_CONST("COMPRESSED_R11_EAC", GL_COMPRESSED_R11_EAC); EXPORT_CONST("COMPRESSED_SIGNED_R11_EAC", GL_COMPRESSED_SIGNED_R11_EAC); EXPORT_CONST("COMPRESSED_RG11_EAC", GL_COMPRESSED_RG11_EAC); EXPORT_CONST("COMPRESSED_SIGNED_RG11_EAC", GL_COMPRESSED_SIGNED_RG11_EAC); EXPORT_CONST("PRIMITIVE_RESTART_FIXED_INDEX", GL_PRIMITIVE_RESTART_FIXED_INDEX); EXPORT_CONST("ANY_SAMPLES_PASSED_CONSERVATIVE", GL_ANY_SAMPLES_PASSED_CONSERVATIVE); EXPORT_CONST("MAX_ELEMENT_INDEX", GL_MAX_ELEMENT_INDEX); EXPORT_CONST("COMPUTE_SHADER", GL_COMPUTE_SHADER); EXPORT_CONST("MAX_COMPUTE_UNIFORM_BLOCKS", GL_MAX_COMPUTE_UNIFORM_BLOCKS); EXPORT_CONST("MAX_COMPUTE_TEXTURE_IMAGE_UNITS", GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS); EXPORT_CONST("MAX_COMPUTE_IMAGE_UNIFORMS", GL_MAX_COMPUTE_IMAGE_UNIFORMS); EXPORT_CONST("MAX_COMPUTE_SHARED_MEMORY_SIZE", GL_MAX_COMPUTE_SHARED_MEMORY_SIZE); EXPORT_CONST("MAX_COMPUTE_UNIFORM_COMPONENTS", GL_MAX_COMPUTE_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS", GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS); EXPORT_CONST("MAX_COMPUTE_ATOMIC_COUNTERS", GL_MAX_COMPUTE_ATOMIC_COUNTERS); EXPORT_CONST("MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS", GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS); EXPORT_CONST("MAX_COMPUTE_WORK_GROUP_INVOCATIONS", GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS); EXPORT_CONST("MAX_COMPUTE_WORK_GROUP_COUNT", GL_MAX_COMPUTE_WORK_GROUP_COUNT); EXPORT_CONST("MAX_COMPUTE_WORK_GROUP_SIZE", GL_MAX_COMPUTE_WORK_GROUP_SIZE); EXPORT_CONST("COMPUTE_WORK_GROUP_SIZE", GL_COMPUTE_WORK_GROUP_SIZE); EXPORT_CONST("UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER", GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER", GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER); EXPORT_CONST("DISPATCH_INDIRECT_BUFFER", GL_DISPATCH_INDIRECT_BUFFER); EXPORT_CONST("DISPATCH_INDIRECT_BUFFER_BINDING", GL_DISPATCH_INDIRECT_BUFFER_BINDING); EXPORT_CONST("COMPUTE_SHADER_BIT", GL_COMPUTE_SHADER_BIT); EXPORT_CONST("DEBUG_OUTPUT_SYNCHRONOUS", GL_DEBUG_OUTPUT_SYNCHRONOUS); EXPORT_CONST("DEBUG_NEXT_LOGGED_MESSAGE_LENGTH", GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH); EXPORT_CONST("DEBUG_CALLBACK_FUNCTION", GL_DEBUG_CALLBACK_FUNCTION); EXPORT_CONST("DEBUG_CALLBACK_USER_PARAM", GL_DEBUG_CALLBACK_USER_PARAM); EXPORT_CONST("DEBUG_SOURCE_API", GL_DEBUG_SOURCE_API); EXPORT_CONST("DEBUG_SOURCE_WINDOW_SYSTEM", GL_DEBUG_SOURCE_WINDOW_SYSTEM); EXPORT_CONST("DEBUG_SOURCE_SHADER_COMPILER", GL_DEBUG_SOURCE_SHADER_COMPILER); EXPORT_CONST("DEBUG_SOURCE_THIRD_PARTY", GL_DEBUG_SOURCE_THIRD_PARTY); EXPORT_CONST("DEBUG_SOURCE_APPLICATION", GL_DEBUG_SOURCE_APPLICATION); EXPORT_CONST("DEBUG_SOURCE_OTHER", GL_DEBUG_SOURCE_OTHER); EXPORT_CONST("DEBUG_TYPE_ERROR", GL_DEBUG_TYPE_ERROR); EXPORT_CONST("DEBUG_TYPE_DEPRECATED_BEHAVIOR", GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR); EXPORT_CONST("DEBUG_TYPE_UNDEFINED_BEHAVIOR", GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR); EXPORT_CONST("DEBUG_TYPE_PORTABILITY", GL_DEBUG_TYPE_PORTABILITY); EXPORT_CONST("DEBUG_TYPE_PERFORMANCE", GL_DEBUG_TYPE_PERFORMANCE); EXPORT_CONST("DEBUG_TYPE_OTHER", GL_DEBUG_TYPE_OTHER); EXPORT_CONST("MAX_DEBUG_MESSAGE_LENGTH", GL_MAX_DEBUG_MESSAGE_LENGTH); EXPORT_CONST("MAX_DEBUG_LOGGED_MESSAGES", GL_MAX_DEBUG_LOGGED_MESSAGES); EXPORT_CONST("DEBUG_LOGGED_MESSAGES", GL_DEBUG_LOGGED_MESSAGES); EXPORT_CONST("DEBUG_SEVERITY_HIGH", GL_DEBUG_SEVERITY_HIGH); EXPORT_CONST("DEBUG_SEVERITY_MEDIUM", GL_DEBUG_SEVERITY_MEDIUM); EXPORT_CONST("DEBUG_SEVERITY_LOW", GL_DEBUG_SEVERITY_LOW); EXPORT_CONST("DEBUG_TYPE_MARKER", GL_DEBUG_TYPE_MARKER); EXPORT_CONST("DEBUG_TYPE_PUSH_GROUP", GL_DEBUG_TYPE_PUSH_GROUP); EXPORT_CONST("DEBUG_TYPE_POP_GROUP", GL_DEBUG_TYPE_POP_GROUP); EXPORT_CONST("DEBUG_SEVERITY_NOTIFICATION", GL_DEBUG_SEVERITY_NOTIFICATION); EXPORT_CONST("MAX_DEBUG_GROUP_STACK_DEPTH", GL_MAX_DEBUG_GROUP_STACK_DEPTH); EXPORT_CONST("DEBUG_GROUP_STACK_DEPTH", GL_DEBUG_GROUP_STACK_DEPTH); EXPORT_CONST("BUFFER", GL_BUFFER); EXPORT_CONST("SHADER", GL_SHADER); EXPORT_CONST("PROGRAM", GL_PROGRAM); EXPORT_CONST("QUERY", GL_QUERY); EXPORT_CONST("PROGRAM_PIPELINE", GL_PROGRAM_PIPELINE); EXPORT_CONST("SAMPLER", GL_SAMPLER); EXPORT_CONST("MAX_LABEL_LENGTH", GL_MAX_LABEL_LENGTH); EXPORT_CONST("DEBUG_OUTPUT", GL_DEBUG_OUTPUT); EXPORT_CONST("CONTEXT_FLAG_DEBUG_BIT", GL_CONTEXT_FLAG_DEBUG_BIT); EXPORT_CONST("MAX_UNIFORM_LOCATIONS", GL_MAX_UNIFORM_LOCATIONS); EXPORT_CONST("FRAMEBUFFER_DEFAULT_WIDTH", GL_FRAMEBUFFER_DEFAULT_WIDTH); EXPORT_CONST("FRAMEBUFFER_DEFAULT_HEIGHT", GL_FRAMEBUFFER_DEFAULT_HEIGHT); EXPORT_CONST("FRAMEBUFFER_DEFAULT_LAYERS", GL_FRAMEBUFFER_DEFAULT_LAYERS); EXPORT_CONST("FRAMEBUFFER_DEFAULT_SAMPLES", GL_FRAMEBUFFER_DEFAULT_SAMPLES); EXPORT_CONST("FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS", GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS); EXPORT_CONST("MAX_FRAMEBUFFER_WIDTH", GL_MAX_FRAMEBUFFER_WIDTH); EXPORT_CONST("MAX_FRAMEBUFFER_HEIGHT", GL_MAX_FRAMEBUFFER_HEIGHT); EXPORT_CONST("MAX_FRAMEBUFFER_LAYERS", GL_MAX_FRAMEBUFFER_LAYERS); EXPORT_CONST("MAX_FRAMEBUFFER_SAMPLES", GL_MAX_FRAMEBUFFER_SAMPLES); EXPORT_CONST("INTERNALFORMAT_SUPPORTED", GL_INTERNALFORMAT_SUPPORTED); EXPORT_CONST("INTERNALFORMAT_PREFERRED", GL_INTERNALFORMAT_PREFERRED); EXPORT_CONST("INTERNALFORMAT_RED_SIZE", GL_INTERNALFORMAT_RED_SIZE); EXPORT_CONST("INTERNALFORMAT_GREEN_SIZE", GL_INTERNALFORMAT_GREEN_SIZE); EXPORT_CONST("INTERNALFORMAT_BLUE_SIZE", GL_INTERNALFORMAT_BLUE_SIZE); EXPORT_CONST("INTERNALFORMAT_ALPHA_SIZE", GL_INTERNALFORMAT_ALPHA_SIZE); EXPORT_CONST("INTERNALFORMAT_DEPTH_SIZE", GL_INTERNALFORMAT_DEPTH_SIZE); EXPORT_CONST("INTERNALFORMAT_STENCIL_SIZE", GL_INTERNALFORMAT_STENCIL_SIZE); EXPORT_CONST("INTERNALFORMAT_SHARED_SIZE", GL_INTERNALFORMAT_SHARED_SIZE); EXPORT_CONST("INTERNALFORMAT_RED_TYPE", GL_INTERNALFORMAT_RED_TYPE); EXPORT_CONST("INTERNALFORMAT_GREEN_TYPE", GL_INTERNALFORMAT_GREEN_TYPE); EXPORT_CONST("INTERNALFORMAT_BLUE_TYPE", GL_INTERNALFORMAT_BLUE_TYPE); EXPORT_CONST("INTERNALFORMAT_ALPHA_TYPE", GL_INTERNALFORMAT_ALPHA_TYPE); EXPORT_CONST("INTERNALFORMAT_DEPTH_TYPE", GL_INTERNALFORMAT_DEPTH_TYPE); EXPORT_CONST("INTERNALFORMAT_STENCIL_TYPE", GL_INTERNALFORMAT_STENCIL_TYPE); EXPORT_CONST("MAX_WIDTH", GL_MAX_WIDTH); EXPORT_CONST("MAX_HEIGHT", GL_MAX_HEIGHT); EXPORT_CONST("MAX_DEPTH", GL_MAX_DEPTH); EXPORT_CONST("MAX_LAYERS", GL_MAX_LAYERS); EXPORT_CONST("MAX_COMBINED_DIMENSIONS", GL_MAX_COMBINED_DIMENSIONS); EXPORT_CONST("COLOR_COMPONENTS", GL_COLOR_COMPONENTS); EXPORT_CONST("DEPTH_COMPONENTS", GL_DEPTH_COMPONENTS); EXPORT_CONST("STENCIL_COMPONENTS", GL_STENCIL_COMPONENTS); EXPORT_CONST("COLOR_RENDERABLE", GL_COLOR_RENDERABLE); EXPORT_CONST("DEPTH_RENDERABLE", GL_DEPTH_RENDERABLE); EXPORT_CONST("STENCIL_RENDERABLE", GL_STENCIL_RENDERABLE); EXPORT_CONST("FRAMEBUFFER_RENDERABLE", GL_FRAMEBUFFER_RENDERABLE); EXPORT_CONST("FRAMEBUFFER_RENDERABLE_LAYERED", GL_FRAMEBUFFER_RENDERABLE_LAYERED); EXPORT_CONST("FRAMEBUFFER_BLEND", GL_FRAMEBUFFER_BLEND); EXPORT_CONST("READ_PIXELS", GL_READ_PIXELS); EXPORT_CONST("READ_PIXELS_FORMAT", GL_READ_PIXELS_FORMAT); EXPORT_CONST("READ_PIXELS_TYPE", GL_READ_PIXELS_TYPE); EXPORT_CONST("TEXTURE_IMAGE_FORMAT", GL_TEXTURE_IMAGE_FORMAT); EXPORT_CONST("TEXTURE_IMAGE_TYPE", GL_TEXTURE_IMAGE_TYPE); EXPORT_CONST("GET_TEXTURE_IMAGE_FORMAT", GL_GET_TEXTURE_IMAGE_FORMAT); EXPORT_CONST("GET_TEXTURE_IMAGE_TYPE", GL_GET_TEXTURE_IMAGE_TYPE); EXPORT_CONST("MIPMAP", GL_MIPMAP); EXPORT_CONST("MANUAL_GENERATE_MIPMAP", GL_MANUAL_GENERATE_MIPMAP); EXPORT_CONST("AUTO_GENERATE_MIPMAP", GL_AUTO_GENERATE_MIPMAP); EXPORT_CONST("COLOR_ENCODING", GL_COLOR_ENCODING); EXPORT_CONST("SRGB_READ", GL_SRGB_READ); EXPORT_CONST("SRGB_WRITE", GL_SRGB_WRITE); EXPORT_CONST("FILTER", GL_FILTER); EXPORT_CONST("VERTEX_TEXTURE", GL_VERTEX_TEXTURE); EXPORT_CONST("TESS_CONTROL_TEXTURE", GL_TESS_CONTROL_TEXTURE); EXPORT_CONST("TESS_EVALUATION_TEXTURE", GL_TESS_EVALUATION_TEXTURE); EXPORT_CONST("GEOMETRY_TEXTURE", GL_GEOMETRY_TEXTURE); EXPORT_CONST("FRAGMENT_TEXTURE", GL_FRAGMENT_TEXTURE); EXPORT_CONST("COMPUTE_TEXTURE", GL_COMPUTE_TEXTURE); EXPORT_CONST("TEXTURE_SHADOW", GL_TEXTURE_SHADOW); EXPORT_CONST("TEXTURE_GATHER", GL_TEXTURE_GATHER); EXPORT_CONST("TEXTURE_GATHER_SHADOW", GL_TEXTURE_GATHER_SHADOW); EXPORT_CONST("SHADER_IMAGE_LOAD", GL_SHADER_IMAGE_LOAD); EXPORT_CONST("SHADER_IMAGE_STORE", GL_SHADER_IMAGE_STORE); EXPORT_CONST("SHADER_IMAGE_ATOMIC", GL_SHADER_IMAGE_ATOMIC); EXPORT_CONST("IMAGE_TEXEL_SIZE", GL_IMAGE_TEXEL_SIZE); EXPORT_CONST("IMAGE_COMPATIBILITY_CLASS", GL_IMAGE_COMPATIBILITY_CLASS); EXPORT_CONST("IMAGE_PIXEL_FORMAT", GL_IMAGE_PIXEL_FORMAT); EXPORT_CONST("IMAGE_PIXEL_TYPE", GL_IMAGE_PIXEL_TYPE); EXPORT_CONST("SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST", GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST); EXPORT_CONST("SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST", GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST); EXPORT_CONST("SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE", GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE); EXPORT_CONST("SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE", GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE); EXPORT_CONST("TEXTURE_COMPRESSED_BLOCK_WIDTH", GL_TEXTURE_COMPRESSED_BLOCK_WIDTH); EXPORT_CONST("TEXTURE_COMPRESSED_BLOCK_HEIGHT", GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT); EXPORT_CONST("TEXTURE_COMPRESSED_BLOCK_SIZE", GL_TEXTURE_COMPRESSED_BLOCK_SIZE); EXPORT_CONST("CLEAR_BUFFER", GL_CLEAR_BUFFER); EXPORT_CONST("TEXTURE_VIEW", GL_TEXTURE_VIEW); EXPORT_CONST("VIEW_COMPATIBILITY_CLASS", GL_VIEW_COMPATIBILITY_CLASS); EXPORT_CONST("FULL_SUPPORT", GL_FULL_SUPPORT); EXPORT_CONST("CAVEAT_SUPPORT", GL_CAVEAT_SUPPORT); EXPORT_CONST("IMAGE_CLASS_4_X_32", GL_IMAGE_CLASS_4_X_32); EXPORT_CONST("IMAGE_CLASS_2_X_32", GL_IMAGE_CLASS_2_X_32); EXPORT_CONST("IMAGE_CLASS_1_X_32", GL_IMAGE_CLASS_1_X_32); EXPORT_CONST("IMAGE_CLASS_4_X_16", GL_IMAGE_CLASS_4_X_16); EXPORT_CONST("IMAGE_CLASS_2_X_16", GL_IMAGE_CLASS_2_X_16); EXPORT_CONST("IMAGE_CLASS_1_X_16", GL_IMAGE_CLASS_1_X_16); EXPORT_CONST("IMAGE_CLASS_4_X_8", GL_IMAGE_CLASS_4_X_8); EXPORT_CONST("IMAGE_CLASS_2_X_8", GL_IMAGE_CLASS_2_X_8); EXPORT_CONST("IMAGE_CLASS_1_X_8", GL_IMAGE_CLASS_1_X_8); EXPORT_CONST("IMAGE_CLASS_11_11_10", GL_IMAGE_CLASS_11_11_10); EXPORT_CONST("IMAGE_CLASS_10_10_10_2", GL_IMAGE_CLASS_10_10_10_2); EXPORT_CONST("VIEW_CLASS_128_BITS", GL_VIEW_CLASS_128_BITS); EXPORT_CONST("VIEW_CLASS_96_BITS", GL_VIEW_CLASS_96_BITS); EXPORT_CONST("VIEW_CLASS_64_BITS", GL_VIEW_CLASS_64_BITS); EXPORT_CONST("VIEW_CLASS_48_BITS", GL_VIEW_CLASS_48_BITS); EXPORT_CONST("VIEW_CLASS_32_BITS", GL_VIEW_CLASS_32_BITS); EXPORT_CONST("VIEW_CLASS_24_BITS", GL_VIEW_CLASS_24_BITS); EXPORT_CONST("VIEW_CLASS_16_BITS", GL_VIEW_CLASS_16_BITS); EXPORT_CONST("VIEW_CLASS_8_BITS", GL_VIEW_CLASS_8_BITS); EXPORT_CONST("VIEW_CLASS_S3TC_DXT1_RGB", GL_VIEW_CLASS_S3TC_DXT1_RGB); EXPORT_CONST("VIEW_CLASS_S3TC_DXT1_RGBA", GL_VIEW_CLASS_S3TC_DXT1_RGBA); EXPORT_CONST("VIEW_CLASS_S3TC_DXT3_RGBA", GL_VIEW_CLASS_S3TC_DXT3_RGBA); EXPORT_CONST("VIEW_CLASS_S3TC_DXT5_RGBA", GL_VIEW_CLASS_S3TC_DXT5_RGBA); EXPORT_CONST("VIEW_CLASS_RGTC1_RED", GL_VIEW_CLASS_RGTC1_RED); EXPORT_CONST("VIEW_CLASS_RGTC2_RG", GL_VIEW_CLASS_RGTC2_RG); EXPORT_CONST("VIEW_CLASS_BPTC_UNORM", GL_VIEW_CLASS_BPTC_UNORM); EXPORT_CONST("VIEW_CLASS_BPTC_FLOAT", GL_VIEW_CLASS_BPTC_FLOAT); EXPORT_CONST("UNIFORM", GL_UNIFORM); EXPORT_CONST("UNIFORM_BLOCK", GL_UNIFORM_BLOCK); EXPORT_CONST("PROGRAM_INPUT", GL_PROGRAM_INPUT); EXPORT_CONST("PROGRAM_OUTPUT", GL_PROGRAM_OUTPUT); EXPORT_CONST("BUFFER_VARIABLE", GL_BUFFER_VARIABLE); EXPORT_CONST("SHADER_STORAGE_BLOCK", GL_SHADER_STORAGE_BLOCK); EXPORT_CONST("VERTEX_SUBROUTINE", GL_VERTEX_SUBROUTINE); EXPORT_CONST("TESS_CONTROL_SUBROUTINE", GL_TESS_CONTROL_SUBROUTINE); EXPORT_CONST("TESS_EVALUATION_SUBROUTINE", GL_TESS_EVALUATION_SUBROUTINE); EXPORT_CONST("GEOMETRY_SUBROUTINE", GL_GEOMETRY_SUBROUTINE); EXPORT_CONST("FRAGMENT_SUBROUTINE", GL_FRAGMENT_SUBROUTINE); EXPORT_CONST("COMPUTE_SUBROUTINE", GL_COMPUTE_SUBROUTINE); EXPORT_CONST("VERTEX_SUBROUTINE_UNIFORM", GL_VERTEX_SUBROUTINE_UNIFORM); EXPORT_CONST("TESS_CONTROL_SUBROUTINE_UNIFORM", GL_TESS_CONTROL_SUBROUTINE_UNIFORM); EXPORT_CONST("TESS_EVALUATION_SUBROUTINE_UNIFORM", GL_TESS_EVALUATION_SUBROUTINE_UNIFORM); EXPORT_CONST("GEOMETRY_SUBROUTINE_UNIFORM", GL_GEOMETRY_SUBROUTINE_UNIFORM); EXPORT_CONST("FRAGMENT_SUBROUTINE_UNIFORM", GL_FRAGMENT_SUBROUTINE_UNIFORM); EXPORT_CONST("COMPUTE_SUBROUTINE_UNIFORM", GL_COMPUTE_SUBROUTINE_UNIFORM); EXPORT_CONST("TRANSFORM_FEEDBACK_VARYING", GL_TRANSFORM_FEEDBACK_VARYING); EXPORT_CONST("ACTIVE_RESOURCES", GL_ACTIVE_RESOURCES); EXPORT_CONST("MAX_NAME_LENGTH", GL_MAX_NAME_LENGTH); EXPORT_CONST("MAX_NUM_ACTIVE_VARIABLES", GL_MAX_NUM_ACTIVE_VARIABLES); EXPORT_CONST("MAX_NUM_COMPATIBLE_SUBROUTINES", GL_MAX_NUM_COMPATIBLE_SUBROUTINES); EXPORT_CONST("NAME_LENGTH", GL_NAME_LENGTH); EXPORT_CONST("TYPE", GL_TYPE); EXPORT_CONST("ARRAY_SIZE", GL_ARRAY_SIZE); EXPORT_CONST("OFFSET", GL_OFFSET); EXPORT_CONST("BLOCK_INDEX", GL_BLOCK_INDEX); EXPORT_CONST("ARRAY_STRIDE", GL_ARRAY_STRIDE); EXPORT_CONST("MATRIX_STRIDE", GL_MATRIX_STRIDE); EXPORT_CONST("IS_ROW_MAJOR", GL_IS_ROW_MAJOR); EXPORT_CONST("ATOMIC_COUNTER_BUFFER_INDEX", GL_ATOMIC_COUNTER_BUFFER_INDEX); EXPORT_CONST("BUFFER_BINDING", GL_BUFFER_BINDING); EXPORT_CONST("BUFFER_DATA_SIZE", GL_BUFFER_DATA_SIZE); EXPORT_CONST("NUM_ACTIVE_VARIABLES", GL_NUM_ACTIVE_VARIABLES); EXPORT_CONST("ACTIVE_VARIABLES", GL_ACTIVE_VARIABLES); EXPORT_CONST("REFERENCED_BY_VERTEX_SHADER", GL_REFERENCED_BY_VERTEX_SHADER); EXPORT_CONST("REFERENCED_BY_TESS_CONTROL_SHADER", GL_REFERENCED_BY_TESS_CONTROL_SHADER); EXPORT_CONST("REFERENCED_BY_TESS_EVALUATION_SHADER", GL_REFERENCED_BY_TESS_EVALUATION_SHADER); EXPORT_CONST("REFERENCED_BY_GEOMETRY_SHADER", GL_REFERENCED_BY_GEOMETRY_SHADER); EXPORT_CONST("REFERENCED_BY_FRAGMENT_SHADER", GL_REFERENCED_BY_FRAGMENT_SHADER); EXPORT_CONST("REFERENCED_BY_COMPUTE_SHADER", GL_REFERENCED_BY_COMPUTE_SHADER); EXPORT_CONST("TOP_LEVEL_ARRAY_SIZE", GL_TOP_LEVEL_ARRAY_SIZE); EXPORT_CONST("TOP_LEVEL_ARRAY_STRIDE", GL_TOP_LEVEL_ARRAY_STRIDE); EXPORT_CONST("LOCATION", GL_LOCATION); EXPORT_CONST("LOCATION_INDEX", GL_LOCATION_INDEX); EXPORT_CONST("IS_PER_PATCH", GL_IS_PER_PATCH); EXPORT_CONST("SHADER_STORAGE_BUFFER", GL_SHADER_STORAGE_BUFFER); EXPORT_CONST("SHADER_STORAGE_BUFFER_BINDING", GL_SHADER_STORAGE_BUFFER_BINDING); EXPORT_CONST("SHADER_STORAGE_BUFFER_START", GL_SHADER_STORAGE_BUFFER_START); EXPORT_CONST("SHADER_STORAGE_BUFFER_SIZE", GL_SHADER_STORAGE_BUFFER_SIZE); EXPORT_CONST("MAX_VERTEX_SHADER_STORAGE_BLOCKS", GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_GEOMETRY_SHADER_STORAGE_BLOCKS", GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS", GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS", GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_FRAGMENT_SHADER_STORAGE_BLOCKS", GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_COMPUTE_SHADER_STORAGE_BLOCKS", GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_COMBINED_SHADER_STORAGE_BLOCKS", GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS); EXPORT_CONST("MAX_SHADER_STORAGE_BUFFER_BINDINGS", GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS); EXPORT_CONST("MAX_SHADER_STORAGE_BLOCK_SIZE", GL_MAX_SHADER_STORAGE_BLOCK_SIZE); EXPORT_CONST("SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT", GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT); EXPORT_CONST("SHADER_STORAGE_BARRIER_BIT", GL_SHADER_STORAGE_BARRIER_BIT); EXPORT_CONST("MAX_COMBINED_SHADER_OUTPUT_RESOURCES", GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES); EXPORT_CONST("DEPTH_STENCIL_TEXTURE_MODE", GL_DEPTH_STENCIL_TEXTURE_MODE); EXPORT_CONST("TEXTURE_BUFFER_OFFSET", GL_TEXTURE_BUFFER_OFFSET); EXPORT_CONST("TEXTURE_BUFFER_SIZE", GL_TEXTURE_BUFFER_SIZE); EXPORT_CONST("TEXTURE_BUFFER_OFFSET_ALIGNMENT", GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT); EXPORT_CONST("TEXTURE_VIEW_MIN_LEVEL", GL_TEXTURE_VIEW_MIN_LEVEL); EXPORT_CONST("TEXTURE_VIEW_NUM_LEVELS", GL_TEXTURE_VIEW_NUM_LEVELS); EXPORT_CONST("TEXTURE_VIEW_MIN_LAYER", GL_TEXTURE_VIEW_MIN_LAYER); EXPORT_CONST("TEXTURE_VIEW_NUM_LAYERS", GL_TEXTURE_VIEW_NUM_LAYERS); EXPORT_CONST("TEXTURE_IMMUTABLE_LEVELS", GL_TEXTURE_IMMUTABLE_LEVELS); EXPORT_CONST("VERTEX_ATTRIB_BINDING", GL_VERTEX_ATTRIB_BINDING); EXPORT_CONST("VERTEX_ATTRIB_RELATIVE_OFFSET", GL_VERTEX_ATTRIB_RELATIVE_OFFSET); EXPORT_CONST("VERTEX_BINDING_DIVISOR", GL_VERTEX_BINDING_DIVISOR); EXPORT_CONST("VERTEX_BINDING_OFFSET", GL_VERTEX_BINDING_OFFSET); EXPORT_CONST("VERTEX_BINDING_STRIDE", GL_VERTEX_BINDING_STRIDE); EXPORT_CONST("MAX_VERTEX_ATTRIB_RELATIVE_OFFSET", GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET); EXPORT_CONST("MAX_VERTEX_ATTRIB_BINDINGS", GL_MAX_VERTEX_ATTRIB_BINDINGS); EXPORT_CONST("VERTEX_BINDING_BUFFER", GL_VERTEX_BINDING_BUFFER); EXPORT_CONST("VERSION_4_4", GL_VERSION_4_4); EXPORT_CONST("MAX_VERTEX_ATTRIB_STRIDE", GL_MAX_VERTEX_ATTRIB_STRIDE); EXPORT_CONST("PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED", GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED); EXPORT_CONST("TEXTURE_BUFFER_BINDING", GL_TEXTURE_BUFFER_BINDING); EXPORT_CONST("MAP_PERSISTENT_BIT", GL_MAP_PERSISTENT_BIT); EXPORT_CONST("MAP_COHERENT_BIT", GL_MAP_COHERENT_BIT); EXPORT_CONST("DYNAMIC_STORAGE_BIT", GL_DYNAMIC_STORAGE_BIT); EXPORT_CONST("CLIENT_STORAGE_BIT", GL_CLIENT_STORAGE_BIT); EXPORT_CONST("CLIENT_MAPPED_BUFFER_BARRIER_BIT", GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT); EXPORT_CONST("BUFFER_IMMUTABLE_STORAGE", GL_BUFFER_IMMUTABLE_STORAGE); EXPORT_CONST("BUFFER_STORAGE_FLAGS", GL_BUFFER_STORAGE_FLAGS); EXPORT_CONST("CLEAR_TEXTURE", GL_CLEAR_TEXTURE); EXPORT_CONST("LOCATION_COMPONENT", GL_LOCATION_COMPONENT); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_INDEX", GL_TRANSFORM_FEEDBACK_BUFFER_INDEX); EXPORT_CONST("TRANSFORM_FEEDBACK_BUFFER_STRIDE", GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE); EXPORT_CONST("QUERY_BUFFER", GL_QUERY_BUFFER); EXPORT_CONST("QUERY_BUFFER_BARRIER_BIT", GL_QUERY_BUFFER_BARRIER_BIT); EXPORT_CONST("QUERY_BUFFER_BINDING", GL_QUERY_BUFFER_BINDING); EXPORT_CONST("QUERY_RESULT_NO_WAIT", GL_QUERY_RESULT_NO_WAIT); EXPORT_CONST("MIRROR_CLAMP_TO_EDGE", GL_MIRROR_CLAMP_TO_EDGE); EXPORT_CONST("VERSION_4_5", GL_VERSION_4_5); EXPORT_CONST("CONTEXT_LOST", GL_CONTEXT_LOST); EXPORT_CONST("NEGATIVE_ONE_TO_ONE", GL_NEGATIVE_ONE_TO_ONE); EXPORT_CONST("ZERO_TO_ONE", GL_ZERO_TO_ONE); EXPORT_CONST("CLIP_ORIGIN", GL_CLIP_ORIGIN); EXPORT_CONST("CLIP_DEPTH_MODE", GL_CLIP_DEPTH_MODE); EXPORT_CONST("QUERY_WAIT_INVERTED", GL_QUERY_WAIT_INVERTED); EXPORT_CONST("QUERY_NO_WAIT_INVERTED", GL_QUERY_NO_WAIT_INVERTED); EXPORT_CONST("QUERY_BY_REGION_WAIT_INVERTED", GL_QUERY_BY_REGION_WAIT_INVERTED); EXPORT_CONST("QUERY_BY_REGION_NO_WAIT_INVERTED", GL_QUERY_BY_REGION_NO_WAIT_INVERTED); EXPORT_CONST("MAX_CULL_DISTANCES", GL_MAX_CULL_DISTANCES); EXPORT_CONST("MAX_COMBINED_CLIP_AND_CULL_DISTANCES", GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES); EXPORT_CONST("TEXTURE_TARGET", GL_TEXTURE_TARGET); EXPORT_CONST("QUERY_TARGET", GL_QUERY_TARGET); EXPORT_CONST("GUILTY_CONTEXT_RESET", GL_GUILTY_CONTEXT_RESET); EXPORT_CONST("INNOCENT_CONTEXT_RESET", GL_INNOCENT_CONTEXT_RESET); EXPORT_CONST("UNKNOWN_CONTEXT_RESET", GL_UNKNOWN_CONTEXT_RESET); EXPORT_CONST("RESET_NOTIFICATION_STRATEGY", GL_RESET_NOTIFICATION_STRATEGY); EXPORT_CONST("LOSE_CONTEXT_ON_RESET", GL_LOSE_CONTEXT_ON_RESET); EXPORT_CONST("NO_RESET_NOTIFICATION", GL_NO_RESET_NOTIFICATION); EXPORT_CONST("CONTEXT_FLAG_ROBUST_ACCESS_BIT", GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT); EXPORT_CONST("CONTEXT_RELEASE_BEHAVIOR", GL_CONTEXT_RELEASE_BEHAVIOR); EXPORT_CONST("CONTEXT_RELEASE_BEHAVIOR_FLUSH", GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH); EXPORT_CONST("ARB_ES2_compatibility", GL_ARB_ES2_compatibility); EXPORT_CONST("ARB_ES3_1_compatibility", GL_ARB_ES3_1_compatibility); EXPORT_CONST("ARB_ES3_compatibility", GL_ARB_ES3_compatibility); EXPORT_CONST("ARB_arrays_of_arrays", GL_ARB_arrays_of_arrays); EXPORT_CONST("ARB_base_instance", GL_ARB_base_instance); EXPORT_CONST("ARB_bindless_texture", GL_ARB_bindless_texture); EXPORT_CONST("UNSIGNED_INT64_ARB", GL_UNSIGNED_INT64_ARB); EXPORT_CONST("ARB_blend_func_extended", GL_ARB_blend_func_extended); EXPORT_CONST("ARB_buffer_storage", GL_ARB_buffer_storage); EXPORT_CONST("ARB_cl_event", GL_ARB_cl_event); EXPORT_CONST("SYNC_CL_EVENT_ARB", GL_SYNC_CL_EVENT_ARB); EXPORT_CONST("SYNC_CL_EVENT_COMPLETE_ARB", GL_SYNC_CL_EVENT_COMPLETE_ARB); EXPORT_CONST("ARB_clear_buffer_object", GL_ARB_clear_buffer_object); EXPORT_CONST("ARB_clear_texture", GL_ARB_clear_texture); EXPORT_CONST("ARB_clip_control", GL_ARB_clip_control); EXPORT_CONST("ARB_compressed_texture_pixel_storage", GL_ARB_compressed_texture_pixel_storage); EXPORT_CONST("ARB_compute_shader", GL_ARB_compute_shader); EXPORT_CONST("ARB_compute_variable_group_size", GL_ARB_compute_variable_group_size); EXPORT_CONST("MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB", GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB); EXPORT_CONST("MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB", GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB); EXPORT_CONST("MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB", GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB); EXPORT_CONST("MAX_COMPUTE_FIXED_GROUP_SIZE_ARB", GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB); EXPORT_CONST("ARB_conditional_render_inverted", GL_ARB_conditional_render_inverted); EXPORT_CONST("ARB_conservative_depth", GL_ARB_conservative_depth); EXPORT_CONST("ARB_copy_buffer", GL_ARB_copy_buffer); EXPORT_CONST("ARB_copy_image", GL_ARB_copy_image); EXPORT_CONST("ARB_cull_distance", GL_ARB_cull_distance); EXPORT_CONST("ARB_debug_output", GL_ARB_debug_output); EXPORT_CONST("DEBUG_OUTPUT_SYNCHRONOUS_ARB", GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); EXPORT_CONST("DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB", GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB); EXPORT_CONST("DEBUG_CALLBACK_FUNCTION_ARB", GL_DEBUG_CALLBACK_FUNCTION_ARB); EXPORT_CONST("DEBUG_CALLBACK_USER_PARAM_ARB", GL_DEBUG_CALLBACK_USER_PARAM_ARB); EXPORT_CONST("DEBUG_SOURCE_API_ARB", GL_DEBUG_SOURCE_API_ARB); EXPORT_CONST("DEBUG_SOURCE_WINDOW_SYSTEM_ARB", GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB); EXPORT_CONST("DEBUG_SOURCE_SHADER_COMPILER_ARB", GL_DEBUG_SOURCE_SHADER_COMPILER_ARB); EXPORT_CONST("DEBUG_SOURCE_THIRD_PARTY_ARB", GL_DEBUG_SOURCE_THIRD_PARTY_ARB); EXPORT_CONST("DEBUG_SOURCE_APPLICATION_ARB", GL_DEBUG_SOURCE_APPLICATION_ARB); EXPORT_CONST("DEBUG_SOURCE_OTHER_ARB", GL_DEBUG_SOURCE_OTHER_ARB); EXPORT_CONST("DEBUG_TYPE_ERROR_ARB", GL_DEBUG_TYPE_ERROR_ARB); EXPORT_CONST("DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB", GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB); EXPORT_CONST("DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB", GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB); EXPORT_CONST("DEBUG_TYPE_PORTABILITY_ARB", GL_DEBUG_TYPE_PORTABILITY_ARB); EXPORT_CONST("DEBUG_TYPE_PERFORMANCE_ARB", GL_DEBUG_TYPE_PERFORMANCE_ARB); EXPORT_CONST("DEBUG_TYPE_OTHER_ARB", GL_DEBUG_TYPE_OTHER_ARB); EXPORT_CONST("MAX_DEBUG_MESSAGE_LENGTH_ARB", GL_MAX_DEBUG_MESSAGE_LENGTH_ARB); EXPORT_CONST("MAX_DEBUG_LOGGED_MESSAGES_ARB", GL_MAX_DEBUG_LOGGED_MESSAGES_ARB); EXPORT_CONST("DEBUG_LOGGED_MESSAGES_ARB", GL_DEBUG_LOGGED_MESSAGES_ARB); EXPORT_CONST("DEBUG_SEVERITY_HIGH_ARB", GL_DEBUG_SEVERITY_HIGH_ARB); EXPORT_CONST("DEBUG_SEVERITY_MEDIUM_ARB", GL_DEBUG_SEVERITY_MEDIUM_ARB); EXPORT_CONST("DEBUG_SEVERITY_LOW_ARB", GL_DEBUG_SEVERITY_LOW_ARB); EXPORT_CONST("ARB_depth_buffer_float", GL_ARB_depth_buffer_float); EXPORT_CONST("ARB_depth_clamp", GL_ARB_depth_clamp); EXPORT_CONST("ARB_derivative_control", GL_ARB_derivative_control); EXPORT_CONST("ARB_direct_state_access", GL_ARB_direct_state_access); EXPORT_CONST("ARB_draw_buffers_blend", GL_ARB_draw_buffers_blend); EXPORT_CONST("ARB_draw_elements_base_vertex", GL_ARB_draw_elements_base_vertex); EXPORT_CONST("ARB_draw_indirect", GL_ARB_draw_indirect); EXPORT_CONST("ARB_enhanced_layouts", GL_ARB_enhanced_layouts); EXPORT_CONST("ARB_explicit_attrib_location", GL_ARB_explicit_attrib_location); EXPORT_CONST("ARB_explicit_uniform_location", GL_ARB_explicit_uniform_location); EXPORT_CONST("ARB_fragment_coord_conventions", GL_ARB_fragment_coord_conventions); EXPORT_CONST("ARB_fragment_layer_viewport", GL_ARB_fragment_layer_viewport); EXPORT_CONST("ARB_framebuffer_no_attachments", GL_ARB_framebuffer_no_attachments); EXPORT_CONST("ARB_framebuffer_object", GL_ARB_framebuffer_object); EXPORT_CONST("ARB_framebuffer_sRGB", GL_ARB_framebuffer_sRGB); EXPORT_CONST("ARB_get_program_binary", GL_ARB_get_program_binary); EXPORT_CONST("ARB_get_texture_sub_image", GL_ARB_get_texture_sub_image); EXPORT_CONST("ARB_gpu_shader5", GL_ARB_gpu_shader5); EXPORT_CONST("ARB_gpu_shader_fp64", GL_ARB_gpu_shader_fp64); EXPORT_CONST("ARB_half_float_vertex", GL_ARB_half_float_vertex); EXPORT_CONST("ARB_imaging", GL_ARB_imaging); EXPORT_CONST("BLEND_COLOR", GL_BLEND_COLOR); EXPORT_CONST("BLEND_EQUATION", GL_BLEND_EQUATION); EXPORT_CONST("ARB_indirect_parameters", GL_ARB_indirect_parameters); EXPORT_CONST("PARAMETER_BUFFER_ARB", GL_PARAMETER_BUFFER_ARB); EXPORT_CONST("PARAMETER_BUFFER_BINDING_ARB", GL_PARAMETER_BUFFER_BINDING_ARB); EXPORT_CONST("ARB_internalformat_query", GL_ARB_internalformat_query); EXPORT_CONST("ARB_internalformat_query2", GL_ARB_internalformat_query2); EXPORT_CONST("SRGB_DECODE_ARB", GL_SRGB_DECODE_ARB); EXPORT_CONST("ARB_invalidate_subdata", GL_ARB_invalidate_subdata); EXPORT_CONST("ARB_map_buffer_alignment", GL_ARB_map_buffer_alignment); EXPORT_CONST("ARB_map_buffer_range", GL_ARB_map_buffer_range); EXPORT_CONST("ARB_multi_bind", GL_ARB_multi_bind); EXPORT_CONST("ARB_multi_draw_indirect", GL_ARB_multi_draw_indirect); EXPORT_CONST("ARB_occlusion_query2", GL_ARB_occlusion_query2); EXPORT_CONST("ARB_pipeline_statistics_query", GL_ARB_pipeline_statistics_query); EXPORT_CONST("VERTICES_SUBMITTED_ARB", GL_VERTICES_SUBMITTED_ARB); EXPORT_CONST("PRIMITIVES_SUBMITTED_ARB", GL_PRIMITIVES_SUBMITTED_ARB); EXPORT_CONST("VERTEX_SHADER_INVOCATIONS_ARB", GL_VERTEX_SHADER_INVOCATIONS_ARB); EXPORT_CONST("TESS_CONTROL_SHADER_PATCHES_ARB", GL_TESS_CONTROL_SHADER_PATCHES_ARB); EXPORT_CONST("TESS_EVALUATION_SHADER_INVOCATIONS_ARB", GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB); EXPORT_CONST("GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB", GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB); EXPORT_CONST("FRAGMENT_SHADER_INVOCATIONS_ARB", GL_FRAGMENT_SHADER_INVOCATIONS_ARB); EXPORT_CONST("COMPUTE_SHADER_INVOCATIONS_ARB", GL_COMPUTE_SHADER_INVOCATIONS_ARB); EXPORT_CONST("CLIPPING_INPUT_PRIMITIVES_ARB", GL_CLIPPING_INPUT_PRIMITIVES_ARB); EXPORT_CONST("CLIPPING_OUTPUT_PRIMITIVES_ARB", GL_CLIPPING_OUTPUT_PRIMITIVES_ARB); EXPORT_CONST("ARB_program_interface_query", GL_ARB_program_interface_query); EXPORT_CONST("ARB_provoking_vertex", GL_ARB_provoking_vertex); EXPORT_CONST("ARB_query_buffer_object", GL_ARB_query_buffer_object); EXPORT_CONST("ARB_robust_buffer_access_behavior", GL_ARB_robust_buffer_access_behavior); EXPORT_CONST("ARB_robustness", GL_ARB_robustness); EXPORT_CONST("CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB", GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB); EXPORT_CONST("LOSE_CONTEXT_ON_RESET_ARB", GL_LOSE_CONTEXT_ON_RESET_ARB); EXPORT_CONST("GUILTY_CONTEXT_RESET_ARB", GL_GUILTY_CONTEXT_RESET_ARB); EXPORT_CONST("INNOCENT_CONTEXT_RESET_ARB", GL_INNOCENT_CONTEXT_RESET_ARB); EXPORT_CONST("UNKNOWN_CONTEXT_RESET_ARB", GL_UNKNOWN_CONTEXT_RESET_ARB); EXPORT_CONST("RESET_NOTIFICATION_STRATEGY_ARB", GL_RESET_NOTIFICATION_STRATEGY_ARB); EXPORT_CONST("NO_RESET_NOTIFICATION_ARB", GL_NO_RESET_NOTIFICATION_ARB); EXPORT_CONST("ARB_robustness_isolation", GL_ARB_robustness_isolation); EXPORT_CONST("ARB_sample_shading", GL_ARB_sample_shading); EXPORT_CONST("SAMPLE_SHADING_ARB", GL_SAMPLE_SHADING_ARB); EXPORT_CONST("MIN_SAMPLE_SHADING_VALUE_ARB", GL_MIN_SAMPLE_SHADING_VALUE_ARB); EXPORT_CONST("ARB_sampler_objects", GL_ARB_sampler_objects); EXPORT_CONST("ARB_seamless_cube_map", GL_ARB_seamless_cube_map); EXPORT_CONST("ARB_seamless_cubemap_per_texture", GL_ARB_seamless_cubemap_per_texture); EXPORT_CONST("ARB_separate_shader_objects", GL_ARB_separate_shader_objects); EXPORT_CONST("ARB_shader_atomic_counters", GL_ARB_shader_atomic_counters); EXPORT_CONST("ARB_shader_bit_encoding", GL_ARB_shader_bit_encoding); EXPORT_CONST("ARB_shader_draw_parameters", GL_ARB_shader_draw_parameters); EXPORT_CONST("ARB_shader_group_vote", GL_ARB_shader_group_vote); EXPORT_CONST("ARB_shader_image_load_store", GL_ARB_shader_image_load_store); EXPORT_CONST("ARB_shader_image_size", GL_ARB_shader_image_size); EXPORT_CONST("ARB_shader_precision", GL_ARB_shader_precision); EXPORT_CONST("ARB_shader_stencil_export", GL_ARB_shader_stencil_export); EXPORT_CONST("ARB_shader_storage_buffer_object", GL_ARB_shader_storage_buffer_object); EXPORT_CONST("ARB_shader_subroutine", GL_ARB_shader_subroutine); EXPORT_CONST("ARB_shader_texture_image_samples", GL_ARB_shader_texture_image_samples); EXPORT_CONST("ARB_shading_language_420pack", GL_ARB_shading_language_420pack); EXPORT_CONST("ARB_shading_language_include", GL_ARB_shading_language_include); EXPORT_CONST("SHADER_INCLUDE_ARB", GL_SHADER_INCLUDE_ARB); EXPORT_CONST("NAMED_STRING_LENGTH_ARB", GL_NAMED_STRING_LENGTH_ARB); EXPORT_CONST("NAMED_STRING_TYPE_ARB", GL_NAMED_STRING_TYPE_ARB); EXPORT_CONST("ARB_shading_language_packing", GL_ARB_shading_language_packing); EXPORT_CONST("ARB_sparse_buffer", GL_ARB_sparse_buffer); EXPORT_CONST("SPARSE_STORAGE_BIT_ARB", GL_SPARSE_STORAGE_BIT_ARB); EXPORT_CONST("SPARSE_BUFFER_PAGE_SIZE_ARB", GL_SPARSE_BUFFER_PAGE_SIZE_ARB); EXPORT_CONST("ARB_sparse_texture", GL_ARB_sparse_texture); EXPORT_CONST("TEXTURE_SPARSE_ARB", GL_TEXTURE_SPARSE_ARB); EXPORT_CONST("VIRTUAL_PAGE_SIZE_INDEX_ARB", GL_VIRTUAL_PAGE_SIZE_INDEX_ARB); EXPORT_CONST("NUM_SPARSE_LEVELS_ARB", GL_NUM_SPARSE_LEVELS_ARB); EXPORT_CONST("NUM_VIRTUAL_PAGE_SIZES_ARB", GL_NUM_VIRTUAL_PAGE_SIZES_ARB); EXPORT_CONST("VIRTUAL_PAGE_SIZE_X_ARB", GL_VIRTUAL_PAGE_SIZE_X_ARB); EXPORT_CONST("VIRTUAL_PAGE_SIZE_Y_ARB", GL_VIRTUAL_PAGE_SIZE_Y_ARB); EXPORT_CONST("VIRTUAL_PAGE_SIZE_Z_ARB", GL_VIRTUAL_PAGE_SIZE_Z_ARB); EXPORT_CONST("MAX_SPARSE_TEXTURE_SIZE_ARB", GL_MAX_SPARSE_TEXTURE_SIZE_ARB); EXPORT_CONST("MAX_SPARSE_3D_TEXTURE_SIZE_ARB", GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB); EXPORT_CONST("MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB", GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB); EXPORT_CONST("SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB", GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB); EXPORT_CONST("ARB_stencil_texturing", GL_ARB_stencil_texturing); EXPORT_CONST("ARB_sync", GL_ARB_sync); EXPORT_CONST("ARB_tessellation_shader", GL_ARB_tessellation_shader); EXPORT_CONST("ARB_texture_barrier", GL_ARB_texture_barrier); EXPORT_CONST("ARB_texture_buffer_object_rgb32", GL_ARB_texture_buffer_object_rgb32); EXPORT_CONST("ARB_texture_buffer_range", GL_ARB_texture_buffer_range); EXPORT_CONST("ARB_texture_compression_bptc", GL_ARB_texture_compression_bptc); EXPORT_CONST("COMPRESSED_RGBA_BPTC_UNORM_ARB", GL_COMPRESSED_RGBA_BPTC_UNORM_ARB); EXPORT_CONST("COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB", GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB); EXPORT_CONST("COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB", GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB); EXPORT_CONST("COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB", GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB); EXPORT_CONST("ARB_texture_compression_rgtc", GL_ARB_texture_compression_rgtc); EXPORT_CONST("ARB_texture_cube_map_array", GL_ARB_texture_cube_map_array); EXPORT_CONST("TEXTURE_CUBE_MAP_ARRAY_ARB", GL_TEXTURE_CUBE_MAP_ARRAY_ARB); EXPORT_CONST("TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB", GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB); EXPORT_CONST("PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB", GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB); EXPORT_CONST("SAMPLER_CUBE_MAP_ARRAY_ARB", GL_SAMPLER_CUBE_MAP_ARRAY_ARB); EXPORT_CONST("SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB", GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB); EXPORT_CONST("INT_SAMPLER_CUBE_MAP_ARRAY_ARB", GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB); EXPORT_CONST("UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB", GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB); EXPORT_CONST("ARB_texture_gather", GL_ARB_texture_gather); EXPORT_CONST("MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB", GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB); EXPORT_CONST("MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB", GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB); EXPORT_CONST("MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB", GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB); EXPORT_CONST("ARB_texture_mirror_clamp_to_edge", GL_ARB_texture_mirror_clamp_to_edge); EXPORT_CONST("ARB_texture_multisample", GL_ARB_texture_multisample); EXPORT_CONST("ARB_texture_query_levels", GL_ARB_texture_query_levels); EXPORT_CONST("ARB_texture_query_lod", GL_ARB_texture_query_lod); EXPORT_CONST("ARB_texture_rg", GL_ARB_texture_rg); EXPORT_CONST("ARB_texture_rgb10_a2ui", GL_ARB_texture_rgb10_a2ui); EXPORT_CONST("ARB_texture_stencil8", GL_ARB_texture_stencil8); EXPORT_CONST("ARB_texture_storage", GL_ARB_texture_storage); EXPORT_CONST("ARB_texture_storage_multisample", GL_ARB_texture_storage_multisample); EXPORT_CONST("ARB_texture_swizzle", GL_ARB_texture_swizzle); EXPORT_CONST("ARB_texture_view", GL_ARB_texture_view); EXPORT_CONST("ARB_timer_query", GL_ARB_timer_query); EXPORT_CONST("ARB_transform_feedback2", GL_ARB_transform_feedback2); EXPORT_CONST("ARB_transform_feedback3", GL_ARB_transform_feedback3); EXPORT_CONST("ARB_transform_feedback_instanced", GL_ARB_transform_feedback_instanced); EXPORT_CONST("ARB_transform_feedback_overflow_query", GL_ARB_transform_feedback_overflow_query); EXPORT_CONST("TRANSFORM_FEEDBACK_OVERFLOW_ARB", GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB); EXPORT_CONST("TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB", GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB); EXPORT_CONST("ARB_uniform_buffer_object", GL_ARB_uniform_buffer_object); EXPORT_CONST("ARB_vertex_array_bgra", GL_ARB_vertex_array_bgra); EXPORT_CONST("ARB_vertex_array_object", GL_ARB_vertex_array_object); EXPORT_CONST("ARB_vertex_attrib_64bit", GL_ARB_vertex_attrib_64bit); EXPORT_CONST("ARB_vertex_attrib_binding", GL_ARB_vertex_attrib_binding); EXPORT_CONST("ARB_vertex_type_10f_11f_11f_rev", GL_ARB_vertex_type_10f_11f_11f_rev); EXPORT_CONST("ARB_vertex_type_2_10_10_10_rev", GL_ARB_vertex_type_2_10_10_10_rev); EXPORT_CONST("ARB_viewport_array", GL_ARB_viewport_array); EXPORT_CONST("KHR_context_flush_control", GL_KHR_context_flush_control); EXPORT_CONST("KHR_debug", GL_KHR_debug); EXPORT_CONST("KHR_no_error", GL_KHR_no_error); EXPORT_CONST("CONTEXT_FLAG_NO_ERROR_BIT_KHR", GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR); EXPORT_CONST("KHR_robust_buffer_access_behavior", GL_KHR_robust_buffer_access_behavior); EXPORT_CONST("KHR_robustness", GL_KHR_robustness); EXPORT_CONST("CONTEXT_ROBUST_ACCESS", GL_CONTEXT_ROBUST_ACCESS); EXPORT_CONST("KHR_texture_compression_astc_hdr", GL_KHR_texture_compression_astc_hdr); EXPORT_CONST("COMPRESSED_RGBA_ASTC_4x4_KHR", GL_COMPRESSED_RGBA_ASTC_4x4_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_5x4_KHR", GL_COMPRESSED_RGBA_ASTC_5x4_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_5x5_KHR", GL_COMPRESSED_RGBA_ASTC_5x5_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_6x5_KHR", GL_COMPRESSED_RGBA_ASTC_6x5_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_6x6_KHR", GL_COMPRESSED_RGBA_ASTC_6x6_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_8x5_KHR", GL_COMPRESSED_RGBA_ASTC_8x5_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_8x6_KHR", GL_COMPRESSED_RGBA_ASTC_8x6_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_8x8_KHR", GL_COMPRESSED_RGBA_ASTC_8x8_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_10x5_KHR", GL_COMPRESSED_RGBA_ASTC_10x5_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_10x6_KHR", GL_COMPRESSED_RGBA_ASTC_10x6_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_10x8_KHR", GL_COMPRESSED_RGBA_ASTC_10x8_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_10x10_KHR", GL_COMPRESSED_RGBA_ASTC_10x10_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_12x10_KHR", GL_COMPRESSED_RGBA_ASTC_12x10_KHR); EXPORT_CONST("COMPRESSED_RGBA_ASTC_12x12_KHR", GL_COMPRESSED_RGBA_ASTC_12x12_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR); EXPORT_CONST("COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR", GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR); EXPORT_CONST("KHR_texture_compression_astc_ldr", GL_KHR_texture_compression_astc_ldr); EXPORT_CONST("KHR_texture_compression_astc_sliced_3d", GL_KHR_texture_compression_astc_sliced_3d); #pragma endregion // Methods #pragma region NODE_SET_METHOD(exports, "texPageCommitmentARB", TexPageCommitmentARB); #pragma endregion } NODE_MODULE(NODE_GYP_MODULE_NAME, ExportModule);
62.981337
139
0.85385
[ "object" ]
3477bbfca326285e78c373a4bd725e93f3b397dd
2,063
cpp
C++
Solutions to exercises/Ch21/Ch21 Soln 4/OrderDetailsSet.cpp
salomarx/Visual_studio_2008_for_C_plus
5ff62b7e7f6232df38152390cc56c2d394567cab
[ "MIT" ]
null
null
null
Solutions to exercises/Ch21/Ch21 Soln 4/OrderDetailsSet.cpp
salomarx/Visual_studio_2008_for_C_plus
5ff62b7e7f6232df38152390cc56c2d394567cab
[ "MIT" ]
null
null
null
Solutions to exercises/Ch21/Ch21 Soln 4/OrderDetailsSet.cpp
salomarx/Visual_studio_2008_for_C_plus
5ff62b7e7f6232df38152390cc56c2d394567cab
[ "MIT" ]
null
null
null
// OrderDetailsSet.cpp : implementation of the COrderDetailsSet class // #include "stdafx.h" #include "DBSimpleUpdate.h" #include "OrderDetailsSet.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // COrderDetailsSet implementation // code generated on 8 October 2005, 20:05 IMPLEMENT_DYNAMIC(COrderDetailsSet, CRecordset) COrderDetailsSet::COrderDetailsSet(CDatabase* pdb) : CRecordset(pdb) { m_OrderID = 0; m_ProductID = 0; m_UnitPrice = 0.0; m_Quantity = 0; m_Discount = 0.0; m_nFields = 5; m_nDefaultType = dynaset; } //#error Security Issue: The connection string may contain a password // The connection string below may contain plain text passwords and/or // other sensitive information. Please remove the #error after reviewing // the connection string for any security related issues. You may want to // store the password in some other form or use a different user authentication. CString COrderDetailsSet::GetDefaultConnect() { return _T("DSN=Northwind;DBQ=D:\\Beginning Visual C++ 2005\\Model Access DB\\Northwind.mdb;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;UID=admin;"); } CString COrderDetailsSet::GetDefaultSQL() { return _T("[Order Details]"); } void COrderDetailsSet::DoFieldExchange(CFieldExchange* pFX) { pFX->SetFieldType(CFieldExchange::outputColumn); // Macros such as RFX_Text() and RFX_Int() are dependent on the // type of the member variable, not the type of the field in the database. // ODBC will try to automatically convert the column value to the requested type RFX_Long(pFX, _T("[OrderID]"), m_OrderID); RFX_Long(pFX, _T("[ProductID]"), m_ProductID); RFX_Double(pFX, _T("[UnitPrice]"), m_UnitPrice); RFX_Int(pFX, _T("[Quantity]"), m_Quantity); RFX_Single(pFX, _T("[Discount]"), m_Discount); } ///////////////////////////////////////////////////////////////////////////// // COrderDetailsSet diagnostics #ifdef _DEBUG void COrderDetailsSet::AssertValid() const { CRecordset::AssertValid(); } void COrderDetailsSet::Dump(CDumpContext& dc) const { CRecordset::Dump(dc); } #endif //_DEBUG
28.260274
164
0.729035
[ "model" ]
34799a21c30ec1cbbbe9f7a9f3231033154570af
8,106
cpp
C++
src/mif/application/config/json.cpp
paceholder/mif
ff3c18f577048c94887220bb92477ce102f01599
[ "MIT" ]
4
2018-03-26T11:49:13.000Z
2019-12-22T06:18:35.000Z
src/mif/application/config/json.cpp
paceholder/mif
ff3c18f577048c94887220bb92477ce102f01599
[ "MIT" ]
null
null
null
src/mif/application/config/json.cpp
paceholder/mif
ff3c18f577048c94887220bb92477ce102f01599
[ "MIT" ]
1
2018-10-01T09:16:29.000Z
2018-10-01T09:16:29.000Z
//------------------------------------------------------------------- // MetaInfo Framework (MIF) // https://github.com/tdv/mif // Created: 03.2017 // Copyright (C) 2016-2017 tdv //------------------------------------------------------------------- // STD #include <istream> #include <list> #include <memory> #include <stdexcept> #include <string> #include <utility> // BOOST #include <boost/algorithm/string.hpp> // JSONCPP #include <json/json.h> #include <json/reader.h> // MIF #include "mif/application/iconfig.h" #include "mif/application/id/config.h" #include "mif/service/creator.h" #include "mif/service/make.h" namespace Mif { namespace Application { namespace Detail { namespace { class Collection : public Service::Inherit<Common::ICollection> { public: Collection(::Json::Value array) : m_array{std::move(array)} , m_cur{std::begin(m_array)} , m_end{std::end(m_array)} { } private: ::Json::Value m_array; ::Json::Value::const_iterator m_cur; ::Json::Value::const_iterator m_end; // ICollection virtual bool Next() override final { if (m_cur != m_end) { ++m_cur; return true; } return false; } virtual bool IsEmpty() const override final { return m_array.empty(); } virtual void Reset() override final { m_cur = std::begin(m_array); } virtual Service::IServicePtr Get() override final; }; class Config : public Service::Inherit<IConfig> { public: using StreamPtr = std::shared_ptr<std::istream>; Config(StreamPtr stream) { if (!stream) throw std::invalid_argument{"[Mif::Application::Detail::Config] Empty input stream."}; ::Json::Reader reader; if (!reader.parse(*stream, m_root)) { throw std::invalid_argument{"[Mif::Application::Detail::Config] Empty input stream. " "Failed to parse json. Error: " + reader.getFormattedErrorMessages()}; } } Config(::Json::Value const &root) : m_root{root} { } private: ::Json::Value m_root; using StringList = std::list<std::string>; StringList PathToList(std::string path) const { boost::algorithm::trim(path); StringList list; boost::algorithm::split(list, path, boost::algorithm::is_any_of(".")); return list; } bool FindItem(std::string const &path, ::Json::Value &value) const { StringList const list = PathToList(path); ::Json::Value item = m_root; for (auto const &i : list) { if (!item.isMember(i)) return false; item = item.get(i, ::Json::Value{}); } std::swap(item, value); return true; } // IConfig virtual bool Exists(std::string const &path) const override final { ::Json::Value item; return FindItem(path, item); } virtual std::string GetValue(std::string const &path) const override final { ::Json::Value item; if (!FindItem(path, item)) { throw std::invalid_argument{"[Mif::Application::Detail::Config::GetValue] " "Failed to get value. Bad path \"" + path + "\""}; } if (item.type() == ::Json::nullValue) return {}; if (item.type() != ::Json::stringValue && !item.isConvertibleTo(::Json::stringValue)) { throw std::invalid_argument{"[Mif::Application::Detail::Config::GetValue] " "Failed to get value by path \"" + path + "\". Can not convert to a string type."}; } return item.asString(); } virtual Service::TIntrusivePtr<IConfig> GetConfig(std::string const &path) const override final { ::Json::Value item; if (!FindItem(path, item)) { throw std::invalid_argument{"[Mif::Application::Detail::Config::GetConfig] " "Failed to get config. Bad path \"" + path + "\""}; } if (item.type() == ::Json::nullValue) return {}; if (!item.isObject()) { throw std::invalid_argument{"[Mif::Application::Detail::Config::GetConfig] " "Failed to get config by path \"" + path + "\". The value is not an object."}; } return Service::Make<Config, IConfig>(item); } virtual Common::ICollectionPtr GetCollection(std::string const &path) const override final { ::Json::Value item; if (!FindItem(path, item)) { throw std::invalid_argument{"[Mif::Application::Detail::Config::GetCollection] " "Failed to get collection. Bad path \"" + path + "\""}; } if (item.type() == ::Json::nullValue) return {}; if (!item.isArray()) { throw std::invalid_argument{"[Mif::Application::Detail::Config::GetCollection] " "Failed to get config by path \"" + path + "\". The value is not an object."}; } return Service::Make<Collection, Common::ICollection>(std::move(item)); } }; Service::IServicePtr Collection::Get() { if (!IsEmpty() || m_cur == m_end) { throw std::runtime_error{"[Mif::Application::Detail::Collection::Get] " "Failed to get item. No item."}; } return Service::Make<Config>(*m_cur); } } // namespace } // namespace Detail } // namespace Application } // namespace Mif MIF_SERVICE_CREATOR ( Mif::Application::Id::Service::Config::Json, Mif::Application::Detail::Config, Mif::Application::Detail::Config::StreamPtr )
35.39738
119
0.393042
[ "object" ]
347c83c9b322427e58cd24ae16e62fe06357813e
4,237
cpp
C++
uwsim_resources/underwater_simulation/uwsim/interface_examples/gotoAbsolutePose.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
1
2020-11-30T09:55:33.000Z
2020-11-30T09:55:33.000Z
uwsim_resources/underwater_simulation/uwsim/interface_examples/gotoAbsolutePose.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
null
null
null
uwsim_resources/underwater_simulation/uwsim/interface_examples/gotoAbsolutePose.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
2
2020-11-21T19:50:54.000Z
2020-12-27T09:35:29.000Z
/* * Copyright (c) 2013 University of Jaume-I. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Mario Prats * Javier Perez */ /* Move a vehicle with a velocity proportional to the distance * between the current pose and a desired absolute pose */ #include <stdlib.h> #include <string.h> #include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <osg/Quat> #include <osg/Vec3d> #include <osg/Matrix> bool firstpass=false; osg::Quat initialQ, goalQ, currentQ; osg::Vec3d initialT, goalT, currentT; double totalDistance, currentDistance; void vehiclePoseCallback(const nav_msgs::Odometry& odom) { if (!firstpass) { initialT.set(odom.pose.pose.position.x,odom.pose.pose.position.y,odom.pose.pose.position.z); initialQ.set(odom.pose.pose.orientation.x, odom.pose.pose.orientation.y, odom.pose.pose.orientation.z, odom.pose.pose.orientation.w); totalDistance=(goalT-initialT).length(); firstpass=true; } currentT.set(odom.pose.pose.position.x,odom.pose.pose.position.y,odom.pose.pose.position.z); currentDistance=(goalT-currentT).length(); } int main(int argc, char **argv) { if (argc!=9) { std::cerr << "USAGE: " << argv[0] << " <vehiclePoseTopic> <vehicleControlTopic> <x> <y> <z> <roll> <pitch> <yaw>" << std::endl; std::cerr << "units are meters and radians." << std::endl; return 0; } std::string poseTopic(argv[1]); std::string controlTopic(argv[2]); double x=atof(argv[3]); double y=atof(argv[4]); double z=atof(argv[5]); double roll=atof(argv[6]); double pitch=atof(argv[7]); double yaw=atof(argv[8]); std::string nodeName=controlTopic; nodeName.replace(0,1,"a"); ros::init(argc, argv, nodeName); ros::NodeHandle nh; osg::Matrixd T, Rx, Ry, Rz, transform; T.makeTranslate(x,y,z); Rx.makeRotate(roll,1,0,0); Ry.makeRotate(pitch,0,1,0); Rz.makeRotate(yaw,0,0,1); transform=Rz*Ry*Rx*T; goalT=transform.getTrans(); goalQ=transform.getRotate(); ros::Publisher position_pub=nh.advertise<nav_msgs::Odometry>(controlTopic,1); ros::Subscriber position_sub = nh.subscribe(poseTopic, 1, vehiclePoseCallback); ros::Rate r(30); while (ros::ok()) { if (firstpass) { osg::Vec3d vT=(goalT-currentT)*0.15; double vScale=(vT.length()>0.1) ? 0.1/vT.length() : 1; /* std::cerr << "Initial Q: " << initialQ.x() << " " << initialQ.y() << " " << initialQ.z() << " " << initialQ.w() << std::endl; std::cerr << "Goal Q: " << goalQ.x() << " " << goalQ.y() << " " << goalQ.z() << " " << goalQ.w() << std::endl; std::cerr << "Goal Q: " << currentQ.x() << " " << currentQ.y() << " " << currentQ.z() << " " << currentQ.w() << std::endl; std::cerr << "Goal T: " << goalT.x() << " " << goalT.y() << " " << goalT.z() << std::endl; std::cerr << "Current T: " << currentT.x() << " " << currentT.y() << " " << currentT.z() << std::endl; std::cerr << "Goal-Current" << (goalT-currentT).x() << " " << (goalT-currentT).y() << " " << (goalT-currentT).z() << std::endl; std::cerr << "Current dist: " << currentDistance << " Total: " << totalDistance << std::endl; std::cerr << "current/total: " << currentDistance/totalDistance << std::endl; std::cerr << "Slerp: " << 1 - currentDistance/totalDistance << std::endl; std::cerr << std::endl; */ currentQ.slerp(1-currentDistance/totalDistance,initialQ, goalQ); nav_msgs::Odometry odom; odom.pose.pose.position.x=currentT.x()+vT.x()*vScale; odom.pose.pose.position.y=currentT.y()+vT.y()*vScale; odom.pose.pose.position.z=currentT.z()+vT.z()*vScale; odom.pose.pose.orientation.x=currentQ.x(); odom.pose.pose.orientation.y=currentQ.y(); odom.pose.pose.orientation.z=currentQ.z(); odom.pose.pose.orientation.w=currentQ.w(); odom.twist.twist.linear.x=0; odom.twist.twist.linear.y=0; odom.twist.twist.linear.z=0; odom.twist.twist.angular.x=0; odom.twist.twist.angular.y=0; odom.twist.twist.angular.z=0; for (int i=0; i<36; i++) { odom.twist.covariance[i]=0; odom.pose.covariance[i]=0; } position_pub.publish(odom); } ros::spinOnce(); r.sleep(); } return 0; }
34.169355
135
0.652584
[ "transform" ]
348285285dc7df2b1f3b3c9e0acb4a0fdb4a8e0f
1,031
cpp
C++
system/zombie/imp.cpp
dnartz/PvZ-Emulator
3954f36f4e0f22cee07d6a86003d3892f0938b8b
[ "BSD-2-Clause" ]
1
2022-03-29T23:49:55.000Z
2022-03-29T23:49:55.000Z
system/zombie/imp.cpp
dnartz/PvZ-Emulator
3954f36f4e0f22cee07d6a86003d3892f0938b8b
[ "BSD-2-Clause" ]
2
2021-03-10T18:17:07.000Z
2021-05-11T13:59:22.000Z
system/zombie/imp.cpp
dnartz/PvZ-Emulator
3954f36f4e0f22cee07d6a86003d3892f0938b8b
[ "BSD-2-Clause" ]
1
2021-10-18T18:29:47.000Z
2021-10-18T18:29:47.000Z
#include "zombie.h" namespace pvz_emulator::system { using namespace::pvz_emulator::object; void zombie_imp::update(object::zombie& z) { if (z.status == zombie_status::imp_flying) { z.d2y -= 0.05000000074505806; z.dy += z.d2y; z.x -= z.dx; auto new_y = zombie_init_y(scene.type, z, z.row); auto new_dy = z.dy + new_y - z.y; z.y = new_y; z.dy = new_dy; if (z.dy <= 0) { z.dy = 0; z.status = zombie_status::imp_landing; reanim.set(z, zombie_reanim_name::anim_land, reanim_type::once, 24); } } else if (z.status == zombie_status::imp_landing && z.reanim.n_repeated > 0) { z.status = zombie_status::walking; reanim.update_status(z); } } void zombie_imp::init(zombie &z, unsigned int row) { z._ground = _ground.data(); zombie_base::init(z, zombie_type::imp, row); reanim.set(z, zombie_reanim_name::anim_walk, reanim_type::repeat, 12); set_common_fields(z); } }
23.976744
80
0.587779
[ "object" ]
348328ded84b1ce2755841cd4b887448fe7bf436
19,826
cpp
C++
src/server/RelevanceServer.cpp
scivey/relevanced
8f0fe67f48ea1da7468a70eef026ed23b4298a27
[ "MIT" ]
10
2015-12-02T01:41:52.000Z
2020-05-11T04:05:56.000Z
src/server/RelevanceServer.cpp
scivey/relevanced
8f0fe67f48ea1da7468a70eef026ed23b4298a27
[ "MIT" ]
null
null
null
src/server/RelevanceServer.cpp
scivey/relevanced
8f0fe67f48ea1da7468a70eef026ed23b4298a27
[ "MIT" ]
3
2017-05-20T19:31:44.000Z
2019-04-14T03:47:07.000Z
#include <string> #include <memory> #include <folly/futures/Promise.h> #include <folly/futures/Future.h> #include <folly/futures/helpers.h> #include <folly/futures/Try.h> #include <folly/Optional.h> #include <folly/Format.h> #include <folly/ExceptionWrapper.h> #include <glog/logging.h> #include "centroid_update_worker/CentroidUpdateWorker.h" #include "document_processing_worker/DocumentProcessor.h" #include "document_processing_worker/DocumentProcessingWorker.h" #include "models/Document.h" #include "models/Centroid.h" #include "models/ProcessedDocument.h" #include "gen-cpp2/RelevancedProtocol_types.h" #include "persistence/Persistence.h" #include "persistence/CentroidMetadataDb.h" #include "release_metadata/release_metadata.h" #include "serialization/serializers.h" #include "server/RelevanceServer.h" #include "similarity_score_worker/SimilarityScoreWorker.h" #include "util/util.h" #include "util/Clock.h" namespace relevanced { namespace server { using namespace std; using namespace folly; using namespace relevanced::thrift_protocol; using similarity_score_worker::SimilarityScoreWorkerIf; using centroid_update_worker::CentroidUpdateWorkerIf; using document_processing_worker::DocumentProcessingWorkerIf; using models::Document; using models::ProcessedDocument; using models::Centroid; using util::UniquePointer; RelevanceServer::RelevanceServer( shared_ptr<persistence::PersistenceIf> persistenceSv, shared_ptr<persistence::CentroidMetadataDbIf> metadataDb, shared_ptr<util::ClockIf> clock, shared_ptr<SimilarityScoreWorkerIf> scoreWorker, shared_ptr<DocumentProcessingWorkerIf> docProcessor, shared_ptr<CentroidUpdateWorkerIf> centroidUpdater) : persistence_(persistenceSv), centroidMetadataDb_(metadataDb), clock_(clock), scoreWorker_(scoreWorker), processingWorker_(docProcessor), centroidUpdateWorker_(centroidUpdater) {} void RelevanceServer::ping() {} void RelevanceServer::initialize() { centroidUpdateWorker_->initialize(); scoreWorker_->initialize(); centroidUpdateWorker_->onUpdate( [this](const string &id) { scoreWorker_->reloadCentroid(id); }); } Future<Try<double>> RelevanceServer::getDocumentSimilarity( unique_ptr<string> centroidId, unique_ptr<string> docId) { string cId = *centroidId; return persistence_->loadDocument(*docId) .then([this, cId]( Try<shared_ptr<ProcessedDocument>> doc) { if (doc.hasException()) { return makeFuture<Try<double>>( Try<double>(doc.exception()) ); } return scoreWorker_->getDocumentSimilarity( cId, doc.value() ); }); } Future<Try<double>> RelevanceServer::getCentroidSimilarity( unique_ptr<string> centroid1Id, unique_ptr<string> centroid2Id) { return scoreWorker_->getCentroidSimilarity( *centroid1Id, *centroid2Id ); } Future<Try<unique_ptr<map<string, double>>>> RelevanceServer::internalMultiGetDocumentSimilarity( shared_ptr<vector<string>> centroidIds, shared_ptr<ProcessedDocument> doc) { vector<Future<Try<double>>> scores; for (size_t i = 0; i < centroidIds->size(); i++) { scores.push_back( scoreWorker_->getDocumentSimilarity( centroidIds->at(i), doc ) ); } return collect(scores) .then([this, centroidIds](Try<vector<Try<double>>> scores) { if (scores.hasException()) { return Try<unique_ptr<map<string, double>>>( scores.exception() ); } auto scoreVals = scores.value(); auto response = folly::make_unique<map<string, double>>(); for (size_t i = 0; i < centroidIds->size(); i++) { auto currentScoreVal = scoreVals.at(i); if (currentScoreVal.hasException()) { return Try<unique_ptr<map<string, double>>>( currentScoreVal.exception() ); } response->insert(make_pair( centroidIds->at(i), currentScoreVal.value() )); } return Try<unique_ptr<map<string, double>>>( std::move(response) ); }); } Future<Try<unique_ptr<map<string, double>>>> RelevanceServer::multiGetTextSimilarity( unique_ptr<vector<string>> centroidIds, unique_ptr<string> text, Language lang) { auto doc = std::make_shared<Document>("no-id", *text, lang); auto cIds = std::make_shared<vector<string>>(*centroidIds); return processingWorker_->processNew(doc) .then([this, cIds](shared_ptr<ProcessedDocument> processed) { return internalMultiGetDocumentSimilarity(cIds, processed); }); } Future<Try<unique_ptr<map<string, double>>>> RelevanceServer::multiGetDocumentSimilarity( unique_ptr<vector<string>> centroidIds, unique_ptr<string> docId) { auto cIds = std::make_shared<vector<string>>(*centroidIds); return persistence_->loadDocument(*docId) .then([this, cIds](Try<shared_ptr<ProcessedDocument>> doc) { if (doc.hasException()) { Try<unique_ptr<map<string, double>>> toReturn(doc.exception()); return makeFuture<Try<unique_ptr<map<string, double>>>> (std::move(toReturn) ); } return this->internalMultiGetDocumentSimilarity( cIds, doc.value() ); }); } Future<Try<double>> RelevanceServer::getTextSimilarity( unique_ptr<string> centroidId, unique_ptr<string> text, Language lang) { auto doc = std::make_shared<Document>("no-id", *text, lang); auto cId = *centroidId; return processingWorker_->processNew(doc) .then([this, cId](shared_ptr<ProcessedDocument> processed) { return scoreWorker_->getDocumentSimilarity(cId, processed); }); } Future<Try<unique_ptr<string>>> RelevanceServer::createDocument( unique_ptr<string> text, Language lang) { return internalCreateDocumentWithID(util::getUuid(), *text, lang); } Future<Try<unique_ptr<string>>> RelevanceServer::internalCreateDocumentWithID( string id, string text, Language lang) { auto doc = std::make_shared<Document>(id, text, lang); return processingWorker_->processNew(doc) .then([this, id](shared_ptr<ProcessedDocument> processed) { return persistence_->saveNewDocument(processed) .then([this, id](Try<bool> result) { if (result.hasException()) { return Try<unique_ptr<string>>( result.exception() ); } return Try<unique_ptr<string>>( folly::make_unique<string>(id) ); }); }); } Future<Try<unique_ptr<string>>> RelevanceServer::createDocumentWithID( unique_ptr<string> id, unique_ptr<string> text, Language lang) { return internalCreateDocumentWithID(*id, *text, lang); } Future<Try<bool>> RelevanceServer::deleteDocument( unique_ptr<string> id, bool ignoreMissing) { return persistence_->deleteDocument(*id) .then([ignoreMissing](Try<bool> result) { if (result.hasException<EDocumentDoesNotExist>() && ignoreMissing) { return Try<bool>(false); } return result; }); } Future<vector<Try<bool>>> RelevanceServer::multiDeleteDocuments( unique_ptr<vector<string>> documentIds, bool ignoreMissing) { vector<Future<Try<bool>>> tasks; for (auto id: *documentIds) { tasks.push_back(deleteDocument(folly::make_unique<string>(id), ignoreMissing)); } return collect(tasks); } Future<Try<unique_ptr<string>>> RelevanceServer::getDocument( unique_ptr<string> id) { return persistence_->loadDocument(*id) .then([](Try<shared_ptr<ProcessedDocument>> doc) { if (doc.hasException()) { return Try<unique_ptr<string>>(doc.exception()); } string serialized; serialization::jsonSerialize(serialized, doc.value().get()); auto uniq = folly::make_unique<string>(serialized); return Try<unique_ptr<string>>(std::move(uniq)); }); } Future<vector<Try<bool>>> RelevanceServer::multiCreateCentroids( unique_ptr<vector<string>> centroidIds, bool ignoreExisting) { vector<Future<Try<bool>>> results; for (auto id: *centroidIds) { results.push_back(persistence_->createNewCentroid(id) .then([ignoreExisting](Try<bool> response) { if (response.hasException<ECentroidAlreadyExists>() && ignoreExisting) { return Try<bool>(false); } return response; }) ); } return collect(results); } Future<Try<bool>> RelevanceServer::createCentroid( unique_ptr<string> centroidId, bool ignoreExisting) { auto id = *centroidId; return persistence_->createNewCentroid(id).then([ignoreExisting](Try<bool> response) { if (response.hasException<ECentroidAlreadyExists>() && ignoreExisting) { return Try<bool>(false); } return response; }); } Future<Try<bool>> RelevanceServer::deleteCentroid( unique_ptr<string> centroidId, bool ignoreMissing) { auto cId = *centroidId; return persistence_->deleteCentroid(cId) .then([ignoreMissing](Try<bool> result) { if (result.hasException<ECentroidDoesNotExist>() && ignoreMissing) { return Try<bool>(false); } return result; }); } Future<vector<Try<bool>>> RelevanceServer::multiDeleteCentroids( unique_ptr<vector<string>> centroidIds, bool ignoreMissing) { vector<Future<Try<bool>>> tasks; for (auto id: *centroidIds) { tasks.push_back(deleteCentroid(folly::make_unique<string>(id), ignoreMissing)); } return collect(tasks); } Future<Try<unique_ptr<vector<string>>>> RelevanceServer::listAllDocumentsForCentroid( unique_ptr<string> centroidId) { return persistence_->listAllDocumentsForCentroid(*centroidId) .then([](Try<vector<string>> docIds) { if (docIds.hasException()) { return Try<unique_ptr<vector<string>>>( docIds.exception() ); } vector<string> docs = docIds.value(); return Try<unique_ptr<vector<string>>>( folly::make_unique<vector<string>>(std::move(docs)) ); }); } Future<Try<unique_ptr<vector<string>>>> RelevanceServer::listCentroidDocumentRange( unique_ptr<string> centroidId, size_t offset, size_t count) { return persistence_->listCentroidDocumentRangeFromOffset( *centroidId, offset, count ).then([](Try<vector<string>> docIds) { if (docIds.hasException()) { return Try<unique_ptr<vector<string>>>(docIds.exception()); } return Try<unique_ptr<vector<string>>>( folly::make_unique<vector<string>>(std::move(docIds.value())) ); }); } Future<Try<unique_ptr<vector<string>>>> RelevanceServer::listCentroidDocumentRangeFromID( unique_ptr<string> centroidId, unique_ptr<string> documentId, size_t count) { return persistence_->listCentroidDocumentRangeFromDocumentId( *centroidId, *documentId, count ).then([](Try<vector<string>> docIds) { if (docIds.hasException()) { return Try<unique_ptr<vector<string>>>(docIds.exception()); } return Try<unique_ptr<vector<string>>>( folly::make_unique<vector<string>>(std::move(docIds.value())) ); }); } Future<Try<unique_ptr<AddDocumentsToCentroidResponse>>> RelevanceServer::addDocumentsToCentroid( unique_ptr<AddDocumentsToCentroidRequest> request) { vector<Future<Try<bool>>> tasks; for (auto docId: request->documentIds) { tasks.push_back(addOneDocumentToCentroid( request->centroidId, docId, request->ignoreMissingDocument, request->ignoreAlreadyInCentroid )); } auto docIds = std::make_shared<vector<string>>(request->documentIds); string cId = request->centroidId; return collect(tasks) .then([docIds, cId](vector<Try<bool>> results) { vector<bool> successes; for (auto elem: results) { if (elem.hasException()) { return Try<unique_ptr<AddDocumentsToCentroidResponse>>(elem.exception()); } successes.push_back(elem.value()); } auto response = folly::make_unique<AddDocumentsToCentroidResponse>(); response->centroidId = cId; response->documentIds = *docIds; response->added = successes; return Try<unique_ptr<AddDocumentsToCentroidResponse>>( std::move(response) ); }); } Future<Try<unique_ptr<RemoveDocumentsFromCentroidResponse>>> RelevanceServer::removeDocumentsFromCentroid( unique_ptr<RemoveDocumentsFromCentroidRequest> request) { vector<Future<Try<bool>>> tasks; for (auto docId: request->documentIds) { tasks.push_back(removeOneDocumentFromCentroid( request->centroidId, docId, request->ignoreMissingDocument, request->ignoreNotInCentroid )); } auto docIds = std::make_shared<vector<string>>(request->documentIds); string cId = request->centroidId; return collect(tasks) .then([docIds, cId](vector<Try<bool>> results) { vector<bool> successes; for (auto elem: results) { if (elem.hasException()) { return Try<unique_ptr<RemoveDocumentsFromCentroidResponse>>(elem.exception()); } successes.push_back(elem.value()); } auto response = folly::make_unique<RemoveDocumentsFromCentroidResponse>(); response->centroidId = cId; response->documentIds = *docIds; response->removed = successes; return Try<unique_ptr<RemoveDocumentsFromCentroidResponse>>( std::move(response) ); }); } Future<Try<bool>> RelevanceServer::addOneDocumentToCentroid( string centroidId, string docId, bool ignoreMissingDoc, bool ignoreAlreadyInCentroid) { return persistence_->addDocumentToCentroid(centroidId, docId) .then([this, centroidId, ignoreMissingDoc, ignoreAlreadyInCentroid] (Try<bool> result) { if (!result.hasException()) { centroidMetadataDb_->setLastDocumentChangeTimestamp( centroidId, clock_->getEpochTime() ); centroidUpdateWorker_->triggerUpdate(centroidId); } if (ignoreMissingDoc && result.hasException<EDocumentDoesNotExist>()) { return Try<bool>(false); } if (ignoreAlreadyInCentroid && result.hasException<EDocumentAlreadyInCentroid>()) { return Try<bool>(false); } return result; }); } Future<Try<bool>> RelevanceServer::removeOneDocumentFromCentroid( string centroidId, string docId, bool ignoreMissingDoc, bool ignoreNotInCentroid) { return persistence_->removeDocumentFromCentroid(centroidId, docId) .then([this, centroidId, ignoreMissingDoc, ignoreNotInCentroid] (Try<bool> result) { if (!result.hasException()) { centroidMetadataDb_->setLastDocumentChangeTimestamp( centroidId, clock_->getEpochTime() ); centroidUpdateWorker_->triggerUpdate(centroidId); } if (ignoreMissingDoc && result.hasException<EDocumentDoesNotExist>()) { return Try<bool>(false); } if (ignoreNotInCentroid && result.hasException<EDocumentNotInCentroid>()) { return Try<bool>(false); } return result; }); } Future<Try<bool>> RelevanceServer::joinCentroid( string centroidId, bool ignoreMissing) { return centroidMetadataDb_->isCentroidUpToDate(centroidId) .then([ignoreMissing, this, centroidId](Try<bool> isUpToDate) { if (ignoreMissing && isUpToDate.hasException<ECentroidDoesNotExist>()) { Try<bool> result(false); return makeFuture(result); } if (isUpToDate.hasException()) { Try<bool> result(isUpToDate.exception()); return makeFuture(result); } if (isUpToDate.value()) { bool recomputed = false; Try<bool> result(recomputed); return makeFuture(result); } return centroidUpdateWorker_->joinUpdate(centroidId) .then([this, centroidId](Try<string> result) { if (result.hasException()) { Try<bool> toReturn(result.exception()); return makeFuture(toReturn); } return scoreWorker_->reloadCentroid(centroidId).then([](){ bool recomputed = true; return Try<bool>(recomputed); }); }); }); } Future<Try<bool>> RelevanceServer::joinCentroid( unique_ptr<string> centroidId, bool ignoreMissing) { return joinCentroid(*centroidId, ignoreMissing); } Future<unique_ptr<vector<Try<bool>>>> RelevanceServer::multiJoinCentroids( unique_ptr<vector<string>> centroidIds, bool ignoreMissing) { vector<Future<Try<bool>>> tasks; for (auto cId: *centroidIds) { tasks.push_back(joinCentroid(cId, ignoreMissing)); } return collect(tasks).then([](vector<Try<bool>> results) { return std::move(folly::make_unique<vector<Try<bool>>>(std::move(results))); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listAllCentroids() { return persistence_->listAllCentroids() .then([](vector<string> centroidIds) { return std::move(folly::make_unique<vector<string>>(centroidIds)); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listCentroidRange( size_t offset, size_t count) { return persistence_->listCentroidRangeFromOffset(offset, count) .then([](vector<string> centroidIds) { return std::move(folly::make_unique<vector<string>>( std::move(centroidIds) )); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listCentroidRangeFromID( unique_ptr<string> centroidId, size_t count) { return persistence_->listCentroidRangeFromId(*centroidId, count) .then([](vector<string> centroidIds) { return std::move(folly::make_unique<vector<string>>( std::move(centroidIds) )); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listAllDocuments() { return persistence_->listAllDocuments() .then([](vector<string> docIds) { return std::move( folly::make_unique<vector<string>>(docIds) ); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listUnusedDocuments( size_t count) { return persistence_->listUnusedDocuments(count) .then([](vector<string> docIds) { return std::move( folly::make_unique<vector<string>>(docIds) ); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listDocumentRange( size_t offset, size_t count) { return persistence_->listDocumentRangeFromOffset(offset, count) .then([](vector<string> docIds) { return std::move(folly::make_unique<vector<string>>( std::move(docIds) )); }); } Future<unique_ptr<vector<string>>> RelevanceServer::listDocumentRangeFromID( unique_ptr<string> docId, size_t count) { return persistence_->listDocumentRangeFromId(*docId, count) .then([](vector<string> docIds) { return std::move(folly::make_unique<vector<string>>( std::move(docIds) )); }); } Future<unique_ptr<map<string, string>>> RelevanceServer::getServerMetadata() { string revision = release_metadata::getGitRevisionSha(); string version = release_metadata::getGitVersion(); auto metadata = folly::make_unique<map<string, string>>(); metadata->insert(make_pair( "relevanced_git_revision", revision )); metadata->insert(make_pair( "relevanced_version", version )); metadata->insert(make_pair( "relevanced_utc_build_timestamp", release_metadata::getUtcBuildTimestamp() )); return makeFuture(std::move(metadata)); } Future<folly::Unit> RelevanceServer::debugEraseAllData() { return persistence_->debugEraseAllData(); } Future<Try<shared_ptr<Centroid>>> RelevanceServer::debugGetFullCentroid( unique_ptr<string> centroidId) { return persistence_->loadCentroid(*centroidId); } Future<Try<shared_ptr<ProcessedDocument>>> RelevanceServer::debugGetFullProcessedDocument( unique_ptr<string> documentId) { return persistence_->loadDocument(*documentId); } } // server } // relevanced
32.289902
106
0.688994
[ "vector" ]
3493e5e1848b01a7a863cf4495cbdb2d3f44a099
1,069
cpp
C++
C++/1305-All-Elements-in-Two-Binary-Search-Trees/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/1305-All-Elements-in-Two-Binary-Search-Trees/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/1305-All-Elements-in-Two-Binary-Search-Trees/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> getAllElements(TreeNode* root1, TreeNode* root2) { vector<int> vals1, vals2; Inorder(root1, &vals1); Inorder(root2, &vals2); int i = 0, j = 0; vector<int> ans; const int kN1 = vals1.size(), kN2 = vals2.size(); while (i < kN1 && j < kN2) { if (vals1[i] < vals2[j]) { ans.push_back(vals1[i++]); } else { ans.push_back(vals2[j++]); } } while (i < kN1) ans.push_back(vals1[i++]); while (j < kN2) ans.push_back(vals2[j++]); return ans; } private: void Inorder(TreeNode * node, vector<int> * vals) { if (node != nullptr) { Inorder(node->left, vals); vals->push_back(node->val); Inorder(node->right, vals); } } };
26.725
66
0.489242
[ "vector" ]
349b3ce7fb574dd7737049bb1a4c7f86087a0388
12,066
hpp
C++
StrategyLib/include/Strategies.hpp
lucasguesserts/prisoners_dilemma
a786af699c95c99797b074b1b73a2a3f7ef68436
[ "MIT" ]
null
null
null
StrategyLib/include/Strategies.hpp
lucasguesserts/prisoners_dilemma
a786af699c95c99797b074b1b73a2a3f7ef68436
[ "MIT" ]
null
null
null
StrategyLib/include/Strategies.hpp
lucasguesserts/prisoners_dilemma
a786af699c95c99797b074b1b73a2a3f7ef68436
[ "MIT" ]
null
null
null
#ifndef STRATEGIES_HPP #define STRATEGIES_HPP // Based on http://www.prisoners-dilemma.com/strategies.html #include <cstddef> #include <utility> #include <vector> #include <string> #include "Strategy.hpp" #include "Decision.hpp" namespace PrisonersDilemma { class AlwaysCooperate: public Strategy { public: AlwaysCooperate(void) : Strategy( "Always Cooperate", "AllC", "Always cooperate."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class AlwaysDefect: public Strategy { public: AlwaysDefect(void) : Strategy( "Always Defect", "AllD", "Always defect."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class Lunatic: public Strategy { public: Lunatic(void) : Strategy( "Lunatic", "Moon", "Cooperate or defect with equal probabilities."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class GrimTrigger: public Strategy { public: GrimTrigger(void) : Strategy( "Grim Trigger", "Grim", "Cooperates until the partner defects. Thereafter it only defects."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class Pavlov: public Strategy { public: Pavlov(void) : Strategy( "Pavlov", "PVL", "Start cooperating. Repeat decision if a reward or temptation is received. Change last decision otherwise (if sucker's or punishment is received)."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: static Decision decideBasedOnPayoff( const Decision & thisLastDecision, const Decision & partnerLastDecision); }; class Gradual: public Strategy { public: Gradual(void) : Strategy( "Gradual", "Gradual", "Start cooperating. When the partner defects, it defects as many times as the partner has defected and then cooperates twice."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: static std::pair<size_t,size_t> lastTurnsWhenDefectionTriggedReaction(const std::vector<Decision> & partnerDecision); static size_t countDefectsUntil(const size_t turn, const std::vector<Decision> & partnerDecision); static bool isTimeToDefect(const size_t currentTurn, const std::pair<size_t,size_t> & turnAndDefectionCount); }; class SoftMajority: public Strategy { public: SoftMajority(void) : Strategy( "Soft Majority", "SM", "Cooperates as long as the number of cooperations of the partner is greater or equals to the number of defections."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class HardMajority: public Strategy { public: HardMajority(void) : Strategy( "Hard Majority", "HM", "Defects as long as the number of defections of the partner is greater than or equals to the number of cooperations."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class SoftGrudger: public Strategy { // TODO: remove the magic numbers 4 and 6 from its implementation. public: SoftGrudger(void) : Strategy( "Soft Grudger", "SG", "After a partner defection, react with D,D,D,D,C,C."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: static const std::vector<Decision> reactionToDefection; static size_t lastTurnsWhenDefectionTriggedReaction(const std::vector<Decision> & partnerDecision); static bool isTimeToReact(const size_t currentTurn, const size_t lastTurnsOfReactionTrigged); }; class Prober: public Strategy { public: Prober(void) : Strategy( "Prober", "PB", "Start with D,C,C. If the partner cooperated in the second and third move, always defect afterward. Play tit for tat otherwise."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: static bool isTurnOfInitialDecision(const size_t turn); static bool defectionBehavior(const std::vector<Decision> & partnerDecision); static const std::vector<Decision> initialDecisions; }; class FirmButFair: public Strategy { public: FirmButFair(void) : Strategy( "Firm But Fair", "FBF", "Defects only after receiving a sucker's payoff."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: static bool gotAsuckers(const Decision & thisLastDecision, const Decision & partnerLastDecision); }; class TitForTat: public Strategy { public: TitForTat(void) : Strategy( "Tit For Tat", "TFT", "Start cooperating. Copy opponent's last move afterwards."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class TitForTwoTats: public Strategy { public: TitForTwoTats(void) : Strategy( "Tit For Two Tats", "TFTT", "Start cooperating. Defects when the partner defects twice in a row."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class TwoTitsForTat: public Strategy { public: TwoTitsForTat(void) : Strategy( "Two Tits For Tat", "TTFT", "Start cooperating. Defects if any of the two last decisions of the partner was to defect."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class NaiveProber: public Strategy { public: NaiveProber(double probabilityOfDefecting = 0.10); Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: const double probabilityOfDefecting; bool decidedRandomlyToDefect(void) const; }; class RemorsefulProber: public Strategy { public: RemorsefulProber(double probabilityOfProbing = 0.10); Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: const double probabilityOfProbing; bool wasProbing( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const; bool probePartner(void) const; }; class GenerousTitForTat: public Strategy { public: GenerousTitForTat(double probabilityOfCooperating = 0.1); Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: double probabilityOfCooperating; bool decidedRandomlyToCooperate(void) const; }; class SuspiciousTitForTat: public Strategy { public: SuspiciousTitForTat(void) : Strategy( "Suspicious Tit For Tat", "STFT", "Start defecting. Copy opponent's last move afterwards."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class HardTitForTat: public Strategy { public: HardTitForTat(void) : Strategy( "Hard Tit For Tat", "HTFT", "Start cooperating. Defects if the partner has defected in any of the three previous turns."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class ReverseTitForTat: public Strategy { public: ReverseTitForTat(void) : Strategy( "Reverse Tit For Tat", "RTFT", "Start defecting, then plays the reverse of the partner last decision."){} Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; }; class AdaptativeTitForTat: public Strategy { public: AdaptativeTitForTat(const double worldZero = 0.50, const double adaptationRate = 0.20); Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: const double worldZero; const double adaptationRate; double computeWorld(const std::vector<Decision> & partnerDecision) const; }; class MetaRegulatedAdaptativeTitForTat: public Strategy { public: MetaRegulatedAdaptativeTitForTat( const double worldZero = 0.50, const double adaptationRateCooperationZero = 0.20, const double adaptationRateDefectionZero = 0.20, const double adaptationRateMinimum = 0.10, const double adaptationRateMaximum = 0.30, const size_t adaptationWindow = 10, const size_t adaptationThreshold = 2); Decision makeDecision( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const override final; private: const double worldZero; const double adaptationRateCooperationZero; const double adaptationRateDefectionZero; const double adaptationRateMinimum; const double adaptationRateMaximum; const size_t adaptationWindow; const size_t adaptationThreshold; double computeWorld( const std::vector<Decision> & thisDecision, const std::vector<Decision> & partnerDecision) const; void updateAdaptationRate( const size_t turn, const size_t thresholdCount, double & adaptationRateCooperation, double & adaptationRateDefection) const; void updateThresholdCount( const size_t turn, size_t & thresholdCount, const Decision & thisDecision, const Decision & partnerDecision) const; double updateWorld( double world, const Decision & partnerDecision, const double adaptationRateCooperation, const double adaptationRateDefection) const; }; extern AlwaysCooperate allC; extern AlwaysDefect allD; extern Lunatic moon; extern GrimTrigger grim; extern Pavlov pvl; extern Gradual gradual; extern SoftMajority sm; extern HardMajority hm; extern NaiveProber np; extern RemorsefulProber rp; extern SoftGrudger sg; extern Prober pb; extern FirmButFair fbf; extern TitForTat tft; extern TitForTwoTats tftt; extern TwoTitsForTat ttft; extern ReverseTitForTat rtft; extern GenerousTitForTat gtft; extern SuspiciousTitForTat stft; extern HardTitForTat htft; extern AdaptativeTitForTat atft; extern MetaRegulatedAdaptativeTitForTat mratft; extern const std::vector<const Strategy *> allStrategies; const Strategy * findStrategy( std::string name, std::string shortName, std::string description); } #endif
31.421875
156
0.684651
[ "vector" ]
349b464bc3130d67326c72018aec830804dbb31e
8,264
hpp
C++
include/aw/util/spatial/intersectors/triangle.hpp
AlexAUT/awEngine
8db7840da71d608de82adc543f71024775c68f22
[ "MIT" ]
null
null
null
include/aw/util/spatial/intersectors/triangle.hpp
AlexAUT/awEngine
8db7840da71d608de82adc543f71024775c68f22
[ "MIT" ]
null
null
null
include/aw/util/spatial/intersectors/triangle.hpp
AlexAUT/awEngine
8db7840da71d608de82adc543f71024775c68f22
[ "MIT" ]
null
null
null
#include "aw/util/math/vector.hpp" #include "glm/geometric.hpp" constexpr float epsilion = 0.000001f; constexpr bool useEpsilonTest = true; namespace aw { struct TriTriIntersector { // Source: http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/code/opttritri.txt auto operator()(aw::Vec3 v0, aw::Vec3 v1, aw::Vec3 v2, aw::Vec3 u0, aw::Vec3 u1, aw::Vec3 u2) -> bool { /* compute plane equation of triangle(V0,V1,V2) */ auto n1 = glm::cross(v1 - v0, v2 - v0); auto d1 = -glm::dot(n1, v0); /* plane equation 1: N1.X+d1=0 */ /* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/ auto du0 = glm::dot(n1, u0) + d1; auto du1 = glm::dot(n1, u1) + d1; auto du2 = glm::dot(n1, u2) + d1; /* coplanarity robustness check */ if constexpr (useEpsilonTest) { if (glm::abs(du0) < epsilion) { du0 = 0.0; } if (glm::abs(du1) < epsilion) { du1 = 0.0; } if (glm::abs(du2) < epsilion) { du2 = 0.0; } } auto du0du1 = du0 * du1; auto du0du2 = du0 * du2; if (du0du1 > 0.0f && du0du2 > 0.0f) { /* same sign on all of them + not equal 0 ? */ return false; /* no intersection occurs */ } /* compute plane of triangle (U0,U1,U2) */ auto n2 = glm::cross(u1 - u0, u2 - u0); auto d2 = -glm::dot(n2, u0); /* plane equation 2: N2.X+d2=0 */ /* put V0,V1,V2 into plane equation 2 */ auto dv0 = glm::dot(n2, v0) + d2; auto dv1 = glm::dot(n2, v1) + d2; auto dv2 = glm::dot(n2, v2) + d2; if constexpr (useEpsilonTest) { if (glm::abs(dv0) < epsilion) { dv0 = 0.0; } if (glm::abs(dv1) < epsilion) { dv1 = 0.0; } if (glm::abs(dv2) < epsilion) { dv2 = 0.0; } } auto dv0dv1 = dv0 * dv1; auto dv0dv2 = dv0 * dv2; if (dv0dv1 > 0.0f && dv0dv2 > 0.0f) { /* same sign on all of them + not equal 0 ? */ return false; /* no intersection occurs */ } return true; /* compute direction of intersection line */ auto D = glm::cross(n1, n2); /* compute and index to the largest component of D */ auto max = glm::abs(D[0]); auto bb = glm::abs(D[1]); auto cc = glm::abs(D[2]); auto index = 0; if (bb > max) { max = bb, index = 1; } if (cc > max) { max = cc, index = 2; } /* this is the simplified projection onto L*/ auto vp0 = v0[index]; auto vp1 = v1[index]; auto vp2 = v2[index]; auto up0 = u0[index]; auto up1 = u1[index]; auto up2 = u2[index]; /* compute interval for triangle 1 */ float a; float b; float c; float x0; float x1; if (newIntervals(n1, v0, v1, v2, u0, u1, u2, vp0, vp1, vp2, dv0, dv1, dv2, dv0dv1, dv0dv2, a, b, c, x0, x1)) { return true; } /* compute interval for triangle 2 */ float d; float e; float f; float y0; float y1; if (newIntervals(n1, v0, v1, v2, u0, u1, u2, up0, up1, up2, du0, du1, du2, du0du1, du0du2, d, e, f, y0, y1)) { return true; } float xx; float yy; float xxyy; float tmp; xx = x0 * x1; yy = y0 * y1; xxyy = xx * yy; tmp = a * xxyy; aw::Vec2 isect1; isect1[0] = tmp + b * x1 * yy; isect1[1] = tmp + c * x0 * yy; tmp = d * xxyy; aw::Vec2 isect2; isect2[0] = tmp + e * xx * y1; isect2[1] = tmp + f * xx * y0; sort(isect1[0], isect1[1]); sort(isect2[0], isect2[1]); return !(isect1[1] < isect2[0] || isect2[1] < isect1[0]); } bool newIntervals(aw::Vec3 N1, aw::Vec3 V0, aw::Vec3 V1, aw::Vec3 V2, aw::Vec3 U0, aw::Vec3 U1, aw::Vec3 U2, float& VV0, float& VV1, float& VV2, float& D0, float& D1, float& D2, float& D0D1, float& D0D2, float& A, float& B, float& C, float& X0, float& X1) { if (D0D1 > 0.0f) { /* here we know that D0D2<=0.0 */ /* that is D0, D1 are on the same side, D2 on the other or on the plane */ A = VV2; B = (VV0 - VV2) * D2; C = (VV1 - VV2) * D2; X0 = D2 - D0; X1 = D2 - D1; } else if (D0D2 > 0.0f) { /* here we know that d0d1<=0.0 */ A = VV1; B = (VV0 - VV1) * D1; C = (VV2 - VV1) * D1; X0 = D1 - D0; X1 = D1 - D2; } else if (D1 * D2 > 0.0f || D0 != 0.0f) { /* here we know that d0d1<=0.0 or that D0!=0.0 */ A = VV0; B = (VV1 - VV0) * D0; C = (VV2 - VV0) * D0; X0 = D0 - D1; X1 = D0 - D2; } else if (D1 != 0.0f) { A = VV1; B = (VV0 - VV1) * D1; C = (VV2 - VV1) * D1; X0 = D1 - D0; X1 = D1 - D2; } else if (D2 != 0.0f) { A = VV2; B = (VV0 - VV2) * D2; C = (VV1 - VV2) * D2; X0 = D2 - D0; X1 = D2 - D1; } else { /* triangles are coplanar */ return coplanarTriTri(N1, V0, V1, V2, U0, U1, U2); } return false; } void sort(float& a, float& b) { if (a > b) { std::swap(a, b); } } auto coplanarTriTri(aw::Vec3 N, aw::Vec3 V0, aw::Vec3 V1, aw::Vec3 V2, aw::Vec3 U0, aw::Vec3 U1, aw::Vec3 U2) -> bool { /* first project onto an axis-aligned plane, that maximizes the area */ /* of the triangles, compute indices: i0,i1. */ aw::Vec3 A = glm::abs(N); int i0; int i1; if (A[0] > A[1]) { if (A[0] > A[2]) { i0 = 1; /* A[0] is greatest */ i1 = 2; } else { i0 = 0; /* A[2] is greatest */ i1 = 1; } } else /* A[0]<=A[1] */ { if (A[2] > A[1]) { i0 = 0; /* A[2] is greatest */ i1 = 1; } else { i0 = 0; /* A[1] is greatest */ i1 = 2; } } /* test all edges of triangle 1 against the edges of triangle 2 */ if (edgeAgainstTriEdges(V0, V1, U0, U1, U2, i0, i1)) { return true; } if (edgeAgainstTriEdges(V1, V2, U0, U1, U2, i0, i1)) { return true; } if (edgeAgainstTriEdges(V2, V0, U0, U1, U2, i0, i1)) { return true; } /* finally, test if tri1 is totally contained in tri2 or vice versa */ if (pointInsideTri(V0, U0, U1, U2, i0, i1)) { return true; } if (pointInsideTri(U0, V0, V1, V2, i0, i1)) { return true; } return false; } auto edgeAgainstTriEdges(aw::Vec3 V0, aw::Vec3 V1, aw::Vec3 U0, aw::Vec3 U1, aw::Vec3 U2, int i0, int i1) -> bool { auto Ax = V1[i0] - V0[i0]; auto Ay = V1[i1] - V0[i1]; /* test edge U0,U1 against V0,V1 */ if (edgeEdgeTest(V0, U0, U1, Ax, Ay, i0, i1)) { /* test edge U1,U2 against V0,V1 */ return true; } if (edgeEdgeTest(V0, U1, U2, Ax, Ay, i0, i1)) { /* test edge U2,U1 against V0,V1 */ return true; } if (edgeEdgeTest(V0, U2, U0, Ax, Ay, i0, i1)) { return true; } return false; } bool edgeEdgeTest(aw::Vec3 V0, aw::Vec3 U0, aw::Vec3 U1, float Ax, float Ay, int i0, int i1) { auto Bx = U0[i0] - U1[i0]; auto By = U0[i1] - U1[i1]; auto Cx = V0[i0] - U0[i0]; auto Cy = V0[i1] - U0[i1]; auto f = Ay * Bx - Ax * By; auto d = By * Cx - Bx * Cy; if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) { auto e = Ax * Cy - Ay * Cx; if (f > 0) { if (e >= 0 && e <= f) { return true; } } else { if (e <= 0 && e >= f) { return true; } } } return false; } auto pointInsideTri(aw::Vec3 V0, aw::Vec3 U0, aw::Vec3 U1, aw::Vec3 U2, int i0, int i1) -> bool { float a; float b; float c; float d0; float d1; float d2; /* is T1 completly inside T2? */ /* check if V0 is inside tri(U0,U1,U2) */ a = U1[i1] - U0[i1]; b = -(U1[i0] - U0[i0]); c = -a * U0[i0] - b * U0[i1]; d0 = a * V0[i0] + b * V0[i1] + c; a = U2[i1] - U1[i1]; b = -(U2[i0] - U1[i0]); c = -a * U1[i0] - b * U1[i1]; d1 = a * V0[i0] + b * V0[i1] + c; a = U0[i1] - U2[i1]; b = -(U0[i0] - U2[i0]); c = -a * U2[i0] - b * U2[i1]; d2 = a * V0[i0] + b * V0[i1] + c; if (d0 * d1 > 0.0) { if (d0 * d2 > 0.0) { return true; } } return false; } }; } // namespace aw
27.006536
119
0.481849
[ "vector" ]
34a1dcc40aaef03b789657719201f12398700fbc
3,812
cc
C++
src/server/traffic_generator.cc
atxutegi/maril-in-monroe-Model-based
105a633b884fc92780f2dc0900bc165b1a0d323c
[ "Apache-2.0" ]
null
null
null
src/server/traffic_generator.cc
atxutegi/maril-in-monroe-Model-based
105a633b884fc92780f2dc0900bc165b1a0d323c
[ "Apache-2.0" ]
null
null
null
src/server/traffic_generator.cc
atxutegi/maril-in-monroe-Model-based
105a633b884fc92780f2dc0900bc165b1a0d323c
[ "Apache-2.0" ]
null
null
null
/** * ***************************************************************************** * Code adaptation and development based on * https://github.com/m-lab/mbm * * This code includes an adaptation and simplication of the software developed at: * M-Lab (http://www.measurementlab.net), * gflags library (google-gflags@googlegroups.com), * gtest (http://code.google.com/p/googletest/) * and pthreads-win32 (LGPL). * * * 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 "server/traffic_generator.h" #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <iostream> #include <vector> #include "mlab/accepted_socket.h" #include "mlab/packet.h" #include "common/constants.h" #include "common/time.h" #include "gflags/gflags.h" #ifdef USE_WEB100 #include "server/web100.h" #endif // !USE_WEB100 DECLARE_bool(verbose); namespace mbm { TrafficGenerator::TrafficGenerator(const mlab::AcceptedSocket *test_socket, uint32_t bytes_per_chunk, uint32_t max_pkt) : test_socket_(test_socket), max_packets_(max_pkt), bytes_per_chunk_(bytes_per_chunk), total_bytes_sent_(0), packets_sent_(0), last_percent_(0), buffer_(std::vector<char>(bytes_per_chunk,'x')) { nonce_.reserve(max_pkt); timestamps_.reserve(max_pkt); } bool TrafficGenerator::Send(uint32_t num_chunks, ssize_t& num_bytes){ num_bytes = 0; ssize_t local_num_bytes; for(uint32_t i=0; i<num_chunks; ++i){ uint32_t seq_no = htonl(packets_sent_); memcpy(&buffer_[0], &seq_no, sizeof(packets_sent_)); uint32_t nonce = htonl(rand()); memcpy(&buffer_[0]+sizeof(packets_sent_), &nonce, sizeof(nonce)); mlab::Packet chunk_packet(&buffer_[0], bytes_per_chunk_); if (!test_socket_->Send(chunk_packet, &local_num_bytes)) { num_bytes = -1; return false; } nonce_.push_back(ntohl(nonce)); timestamps_.push_back(GetTimeNS()); num_bytes += chunk_packet.length(); ++packets_sent_; if (FLAGS_verbose) { std::cout << " s: " << std::hex << ntohl(seq_no) << " " << std::dec << ntohl(seq_no) << "\n"; std::cout << " nonce: " << std::hex << ntohl(nonce) << " " << std::dec << ntohl(nonce) << "\n"; if (max_packets_ != 0) { uint32_t percent = static_cast<uint32_t>( static_cast<float>(100 * packets_sent_) / max_packets_); if (percent > last_percent_) { last_percent_ = percent; std::cout << "\r" << percent << "%" << std::flush; } } } } // for loop total_bytes_sent_ += num_bytes; return (static_cast<unsigned>(num_bytes) == num_chunks * bytes_per_chunk_); } bool TrafficGenerator::Send(uint32_t num_chunks) { ssize_t num_bytes; return Send(num_chunks, num_bytes); } uint32_t TrafficGenerator::packets_sent(){ return packets_sent_; } uint64_t TrafficGenerator::total_bytes_sent(){ return total_bytes_sent_; } uint32_t TrafficGenerator::bytes_per_chunk(){ return bytes_per_chunk_; } const std::vector<uint32_t>& TrafficGenerator::nonce() { return nonce_; } const std::vector<uint64_t>& TrafficGenerator::timestamps() { return timestamps_; } } // namespace mbm
28.447761
82
0.647692
[ "vector" ]
34a3e3d1c07690828dff097fc8e712b60985d0af
6,908
cpp
C++
tests/unit/ItemView.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
257
2020-01-03T10:13:29.000Z
2022-03-26T14:55:12.000Z
tests/unit/ItemView.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
116
2020-01-09T18:13:13.000Z
2022-03-15T18:32:02.000Z
tests/unit/ItemView.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
58
2020-01-09T03:07:02.000Z
2022-03-22T17:21:36.000Z
/*********************************************************************** * created: Sun May 25 2014 * author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 <boost/test/unit_test.hpp> #include "CEGUI/views/ListView.h" #include "CEGUI/WindowManager.h" #include "ItemModelStub.h" using namespace CEGUI; //----------------------------------------------------------------------------// struct ItemViewFixture { ItemViewFixture() { view = static_cast<ListView*>(WindowManager::getSingleton().createWindow("TaharezLook/ListView", "lv")); view->setWindowRenderer("Core/ListView"); view->setModel(&model); } ItemModelStub model; ItemView* view; }; BOOST_FIXTURE_TEST_SUITE(ItemViewTestSuite, ItemViewFixture) //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetModel_SetsTheModel) { BOOST_CHECK_EQUAL(&model, view->getModel()); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetModel_SameModel_DoesNotSetDirtyState) { view->setIsDirty(false); view->setModel(&model); BOOST_CHECK(!view->isDirty()); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetModel_DifferentModel_SetsDirtyState) { ItemModelStub model2; view->setIsDirty(false); view->setModel(&model2); BOOST_CHECK(view->isDirty()); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetModel_ModelHasNewChildren_SetsDirtyState) { model.d_items.push_back("item"); { view->setIsDirty(false); model.notifyChildrenAdded(model.getRootIndex(), 0, 1); BOOST_CHECK(view->isDirty()); } { model.notifyChildrenWillBeRemoved(model.getRootIndex(), 0, 1); view->setIsDirty(false); model.notifyChildrenRemoved(model.getRootIndex(), 0, 1); BOOST_CHECK(view->isDirty()); } } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetModel_DifferentModel_UnhooksPreviousModelEvents) { model.d_items.push_back("item"); ItemModelStub model2; view->setModel(&model2); view->setIsDirty(false); model.notifyChildrenAdded(model.getRootIndex(), 0, 1); BOOST_CHECK(!view->isDirty()); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetModel_DifferentModel_RemovesSelection) { model.d_items.push_back("item"); view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); BOOST_CHECK_EQUAL(1, view->getIndexSelectionStates().size()); ItemModelStub model2; view->setModel(&model2); BOOST_REQUIRE_EQUAL(0, view->getIndexSelectionStates().size()); } BOOST_AUTO_TEST_CASE(ClearSelection) { model.d_items.push_back("item"); view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); view->clearSelections(); BOOST_REQUIRE_EQUAL(0, view->getIndexSelectionStates().size()); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetSelectedItem_ReplacesSelection) { model.d_items.push_back("item1"); model.d_items.push_back("item2"); view->setModel(&model); view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); BOOST_CHECK_EQUAL(1, view->getIndexSelectionStates().size()); view->setSelectedIndex(model.makeIndex(1, model.getRootIndex())); BOOST_REQUIRE_EQUAL(1, view->getIndexSelectionStates().size()); BOOST_REQUIRE_EQUAL("item2", *(static_cast<String*>( view->getIndexSelectionStates().at(0).d_selectedIndex.d_modelData))); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(SetItemSelectionState_MultiSelectToggled_ModifiesSelectionAccordingly) { model.d_items.push_back("item1"); model.d_items.push_back("item2"); view->setModel(&model); view->setMultiSelectEnabled(true); view->setIndexSelectionState(model.makeIndex(0, model.getRootIndex()), true); view->setIndexSelectionState(model.makeIndex(1, model.getRootIndex()), true); BOOST_REQUIRE_EQUAL(2, view->getIndexSelectionStates().size()); BOOST_REQUIRE_EQUAL("item2", *(static_cast<String*>( view->getIndexSelectionStates().at(1).d_selectedIndex.d_modelData))); view->setMultiSelectEnabled(false); BOOST_REQUIRE_EQUAL(1, view->getIndexSelectionStates().size()); BOOST_REQUIRE_EQUAL("item1", *(static_cast<String*>( view->getIndexSelectionStates().at(0).d_selectedIndex.d_modelData))); } //----------------------------------------------------------------------------// BOOST_AUTO_TEST_CASE(EnsureItemIsVisible_ScrollsHorizontallyAndVertically) { for (int i = 0; i < 10; ++i) model.d_items.push_back("1"); model.d_items.push_back(String(100, 'x')); view->setSize(USize(cegui_absdim(10), cegui_absdim(10))); view->prepareForRender(); view->getVertScrollbar()->setScrollPosition(view->getRenderedTotalHeight()); view->getHorzScrollbar()->setScrollPosition(view->getRenderedMaxWidth()); view->ensureIndexIsVisible(model.makeIndex(0, model.getRootIndex())); BOOST_REQUIRE_CLOSE(0.0f, view->getVertScrollbar()->getScrollPosition(), 1.0f); BOOST_REQUIRE_CLOSE(0.0f, view->getHorzScrollbar()->getScrollPosition(), 1.0f); } BOOST_AUTO_TEST_SUITE_END()
35.06599
112
0.605819
[ "model" ]
34a97b8557547203fcaf6400f62b38dc5dc1c3c0
11,065
hpp
C++
include/gtkQRmm.hpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
1
2022-03-13T14:21:23.000Z
2022-03-13T14:21:23.000Z
include/gtkQRmm.hpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
null
null
null
include/gtkQRmm.hpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
null
null
null
#ifndef GTKQR_HPP #define GTKQR_HPP #include <gtkmm.h> #include "QrDefinitions.hpp" #include "QrUtils.hpp" namespace GtkQR { class PrivateClass; /** \brief QR widget */ class QR : public Gtk::Widget { public: /** \brief Creates a new empty widget GtkQR without any image */ QR(); /** \brief copy constructor * */ QR(const QR &); /** \brief move constructor * */ QR(QR &&); /** \brief Creates a new widget GtkQR with text * \param text : text you want to encode */ QR(const char *text); /** \brief Creates a new widget GtkQR with text and error correction level * \param text : text you want to encode * \param error_level_correction : #QRErrorCorrectionLevel for qr image */ QR(const char *text,QRErrorCorrectionLevel error_level_correction); /** \brief destructor * */ ~QR(); /** \brief assignment operator * */ QR& operator=(const QR &); /** \brief move assignment operator * */ QR& operator=(QR &&); /** \brief set text of the widget and regenerates it * \param text : text you want to encode */ void set_text(Glib::ustring &text); /** \brief set text of the widget and regenerates it * \param text : text you want to encode */ void set_text(const char *text); /** \brief set text and error correction level of the widget and regenerates it * * \param text :text you want to encode * \param error_level_correction : #QRErrorCorrectionLevel for qr image */ void set_text_and_correction(Glib::ustring &text,QRErrorCorrectionLevel error_level_correction); /** \brief set text and error correction level of the widget and regenerates it * * \param text :text you want to encode * \param error_level_correction : #QRErrorCorrectionLevel for qr image */ void set_text_and_correction(const char *text,QRErrorCorrectionLevel error_level_correction); /** \brief the micro QR ,default:false * \param set_micro :true to use Micro QR, false to use QR * */ void set_micro(bool set_micro); /** \brief Allows the encoding of characters in UTF8 ,default:true * \param set_UTF8 :true to allow UTF8, false otherwise * \details In <a href="https://en.wikipedia.org/wiki/Extended_Channel_Interpretation">Extended Channel Interpretation</a> allows the encoding of characters in <a href="https://en.wikipedia.org/wiki/UTF-8">UTF8</a> when using characters not included in <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1">ISO/IEC 8859-1</a>, * if you disable this option then it will use the following encoding : * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-2">ISO/IEC 8859-2</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-3">ISO/IEC 8859-3</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-4">ISO/IEC 8859-4</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-5">ISO/IEC 8859-5</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-6">ISO/IEC 8859-6</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-7">ISO/IEC 8859-7</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-8">ISO/IEC 8859-8</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-9">ISO/IEC 8859-9</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-10">ISO/IEC 8859-10</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-11">ISO/IEC 8859-11</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-13">ISO/IEC 8859-13</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-14">ISO/IEC 8859-14</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-15">ISO/IEC 8859-15</a>, * <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-16">ISO/IEC 8859-16</a> or * <a href="https://en.wikipedia.org/wiki/Shift_JIS"> JIS X 0201</a> * \n.With UTF8 you will have all the characters but occupying more space for the encoding, in case of using ISO/IEC 8859-2 to JIS X 0201 the encoding uses less space but not all the characters are possible */ void set_UTF8(bool set_UTF8); /** \brief Save text in GtkQR ,default:true * * \param set_save_text :true to save text, false otherwise * \details Not saving the text in memory we save memory but it has the disadvantage that when using the * \ref set_dynamic_margin(bool set_dynamic) "set_dynamic_margin" , * \ref set_extra_margin(unsigned short size_margin) "set_extra_margin" , * \ref set_micro(bool set_micro) "set_micro" or * \ref set_UTF8(bool set_UTF8) "set_UTF8" or * change color functions you have to re-enter the text to regenerate the image * */ void set_save_text(bool set_save_text); /** \brief sets whether the margin is always the same ,default:true * \param set_dynamic: false is is always the same , true otherwise * \details The QR standard establishes that at least 4 image margin modules are necessary * ,but the number of modules varies from 21x21 in version 1 to 170x170 in version 40 .if the parameter is set to false the margin is calculated in the worst case 21x 21 , * if it is set to true the margin will depend on the number of modules or qr version * */ void set_dynamic_margin(bool set_dynamic); #if (GTKMM_MAJOR_VERSION >= 3 ) /** \brief change the background color * * \param color : * */ void set_background_color(Gdk::RGBA color); /** \brief change the foreground color * * \param color : * */ void set_foreground_color(Gdk::RGBA color); #else /** \brief change the background color * * \param color : * */ void set_background_color(Gdk::Color color); /** \brief change the foreground color * * \param color : * */ void set_foreground_color(Gdk::Color color); #endif /** \brief regenerate qr image * \details Some functions like * \ref set_dynamic_margin(bool set_dynamic) "set_dynamic_margin" , * \ref set_extra_margin(unsigned short size_margin) "set_extra_margin" , * \ref set_micro(bool set_micro) "set_micro" or * \ref set_UTF8(bool set_UTF8) "set_UTF8", * don't regenerate the image they only change options , if you use the above functions before * \ref set_text(Glib::ustring &text) "set_text" , * \ref set_text(const char *text) "set_text", * \ref set_text_and_correction(Glib::ustring &text,QRErrorCorrectionLevel error_level_correction) "set_text_and_correction" or * \ref set_text_and_correction(const char *text,QRErrorCorrectionLevel error_level_correction) "set_text_and_correction" * no need to regenerate the image */ void regenerate(); /** \brief Save the qr image to png * * \param filename : file name to save image * \param _size : size of image */ void save_png_image(const Glib::ustring &filename,int _size); /** \brief Get version enum for qr image * * \return #QRVersion * */ QRVersion get_version(); /** \brief Get version number of the widget GtkQR according to the encrypted text * * \return version number * \details Version number are 1 to 40 for QR and #QR_VERSION_NUMBER_M1 , #QR_VERSION_NUMBER_M2 , * #QR_VERSION_NUMBER_M3 and #QR_VERSION_NUMBER_M4 for micro QR * .If QR can't render the image return #QR_NO_VERSION */ short get_version_number(); /** \brief Get mask pattern for qr image * * \return number 0 to 7 * */ unsigned short get_mask(); /** \brief Get type of data for qr image * * \return #QRData * */ QRData get_data_coding(); /** \brief Get text of the widget * * \return text of widget GtkQR , * if you disable save text with function * \ref set_save_text(bool set_save_text) "set_save_text" * text of widget is empty */ std::string & get_text(); /** \brief extra space added to the margins ,default:0 * \param size_margin: extra margin to add * */ void set_extra_margin(unsigned short size_margin); /** \brief Get number character encoding * \return number of character encoding * \details Obtains the character encoding number, if the encodings * that are default (NUMERIC,ALPHANUMERIC,ISO/IEC 8859-1 or KANJI) returns 0. * Returning a number >=1 indicates that the <a href="https://en.wikipedia.org/wiki/Extended_Channel_Interpretation">Extended Channel Interpretation</a> is used */ int get_number_character_encoding(); /** \brief Get character encoding used in the QR * * \param position :position of character enconding ,starts with 0 * \return character encoding * \details Get character encoding used in the QR starting position 0 to * \ref get_number_character_encoding() "get_number_character_encoding" -1 * , if number of character_encoding is 0 always return QR_ECI_MODE_ISO_8859_1 * */ QREciMode get_character_encoding(int position); /** \brief Get the character matrix representing the QR * \return character matrix * \details A QR image is made up of a series of rectangles called modules, * each value of the matrix is a coordinate (X,Y) that represents the different modules, being value '1' * for foreground color and '0' for background color. * \see \ref QrMatrix::GetQrMatrix(std::string &text,QRDataContainer *data) "GetQrMatrix" * \note the (0,0) coordinate is at the top left . */ QrMatrix get_qrmatrix(); protected: #if (GTKMM_MAJOR_VERSION >= 3 ) /// @private bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override; #else /// @private bool on_expose_event(GdkEventExpose* event) override; #endif /// @private void on_realize() override; private: PrivateClass *privateclass; void copyqr(const QR &); void clear_variables(); void set_matrix(); void draworder(); Glib::RefPtr<Gdk::Window> m_refGdkWindow; }; } #endif // GTKQR++_HPP
37.130872
335
0.612743
[ "render" ]
34abfc35b068f062be661b1a4995a221fd709e43
10,219
hpp
C++
compressor/include/s2s/corpus/dict_set.hpp
kamigaito/SLAHAN
5ef981f1713f4586e2ec42c226555e95d7904147
[ "MIT" ]
15
2020-05-24T16:03:20.000Z
2021-09-07T21:52:32.000Z
compressor/include/s2s/corpus/dict_set.hpp
kamigaito/SLAHAN
5ef981f1713f4586e2ec42c226555e95d7904147
[ "MIT" ]
6
2020-05-31T18:41:09.000Z
2022-02-27T16:16:22.000Z
compressor/include/s2s/corpus/dict_set.hpp
kamigaito/SLAHAN
5ef981f1713f4586e2ec42c226555e95d7904147
[ "MIT" ]
4
2021-05-26T01:53:58.000Z
2022-01-25T07:13:31.000Z
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/program_options.hpp> #include <boost/regex.hpp> #include <boost/algorithm/string/regex.hpp> #include "s2s/dynet/dict.h" #include "s2s/corpus/comp.hpp" #include "s2s/corpus/utils.hpp" #ifndef INCLUDE_GUARD_S2S_DICT_SET_HPP #define INCLUDE_GUARD_S2S_DICT_SET_HPP namespace s2s { class dict_set_token { public: dynet::Dict d_word; dynet::Dict d_char; std::vector<dynet::Dict> d_feat; unsigned int start_id_word; unsigned int end_id_word; unsigned int unk_id_word; unsigned int pad_id_word; unsigned int start_id_char; unsigned int end_id_char; unsigned int unk_id_char; unsigned int pad_id_char; std::vector<unsigned int> start_id_feat; std::vector<unsigned int> end_id_feat; std::vector<unsigned int> unk_id_feat; std::vector<unsigned int> pad_id_feat; std::vector<unsigned int> word_freq; std::vector<unsigned int> char_freq; std::vector<std::vector<unsigned int>> feat_freq; void init(const unsigned int feature_size){ // opts.enc_feature_vocab_size.size() /* resize vectors */ d_feat.resize(feature_size); start_id_feat.resize(feature_size); end_id_feat.resize(feature_size); unk_id_feat.resize(feature_size); pad_id_feat.resize(feature_size); } /* set start and end of sentence id */ void set_id(const s2s_options &opts){ // word start_id_word = d_word.convert(opts.start_symbol); end_id_word = d_word.convert(opts.end_symbol); pad_id_word = d_word.convert(opts.pad_symbol); // char start_id_char = d_char.convert(opts.start_symbol); end_id_char = d_char.convert(opts.end_symbol); pad_id_char = d_char.convert(opts.pad_symbol); // feat for(unsigned int feat_id = 0; feat_id < d_feat.size(); feat_id++){ start_id_feat[feat_id] = d_feat[feat_id].convert(opts.start_symbol); end_id_feat[feat_id] = d_feat[feat_id].convert(opts.end_symbol); pad_id_feat[feat_id] = d_feat[feat_id].convert(opts.pad_symbol); } } void set_unk_id(const s2s_options &opts){ unk_id_word = d_word.convert(opts.unk_symbol); unk_id_char = d_char.convert(opts.unk_symbol); for(unsigned int feat_id = 0; feat_id < d_feat.size(); feat_id++){ unk_id_feat[feat_id] = d_feat[feat_id].convert(opts.unk_symbol); } } std::string fname_d_word(const s2s_options &opts, std::string file_prefix){ std::string file_name = file_prefix + "word.txt"; return file_name; } std::string fname_d_char(const s2s_options &opts, std::string file_prefix){ std::string file_name = file_prefix + "char.txt"; return file_name; } std::string fname_d_feat(const s2s_options &opts, const unsigned int feat_id, std::string file_prefix){ std::string file_name = file_prefix + "feat_" + std::to_string(feat_id) + ".txt"; return file_name; } void load(const s2s_options &opts, std::string file_prefix){ { std::string file_name = fname_d_word(opts, file_prefix); std::cerr << "Loading word dictionary from " << file_name << "...\n"; std::ifstream in(file_name); boost::archive::text_iarchive ia(in); ia >> d_word; in.close(); } { std::string file_name = fname_d_char(opts, file_prefix); std::cerr << "Loading character dictionary from " << file_name << "...\n"; std::ifstream in(file_name); boost::archive::text_iarchive ia(in); ia >> d_char; in.close(); } for(unsigned int feat_id=0; feat_id < d_feat.size(); feat_id++){ // std::string file_name = opts.rootdir + "/" + opts.dict_prefix + "src_" + std::to_string(i) + ".txt"; std::string file_name = fname_d_feat(opts, feat_id, file_prefix); std::cerr << "Loading feature dictionary from " << file_name << "...\n"; std::ifstream in(file_name); boost::archive::text_iarchive ia(in); ia >> d_feat[feat_id]; in.close(); } set_id(opts); set_unk_id(opts); } void save(const s2s_options &opts, std::string file_prefix){ { std::string file_name = fname_d_word(opts, file_prefix); std::cerr << "Saving word dictionary from " << file_name << "...\n"; std::ofstream out(file_name); boost::archive::text_oarchive oa(out); oa << d_word; out.close(); } { std::string file_name = fname_d_char(opts, file_prefix); std::cerr << "Saving character dictionary from " << file_name << "...\n"; std::ofstream out(file_name); boost::archive::text_oarchive oa(out); oa << d_char; out.close(); } for(unsigned int feat_id=0; feat_id < d_feat.size(); feat_id++){ std::string file_name = fname_d_feat(opts, feat_id, file_prefix); std::cerr << "Saving feature dictionary to " << file_name << "...\n"; std::ofstream out(file_name); boost::archive::text_oarchive oa(out); oa << d_feat[feat_id]; out.close(); } } void freq_cut(const s2s_options &opts, const std::string file_path, const int word_vocab_size, const int char_vocab_size, const std::vector<int>& feature_vocab_size){ std::ifstream in(file_path); assert(in); set_id(opts); std::vector<std::map<std::string, unsigned int> > vec_str_freq; std::map<std::string, unsigned int> str_char_freq; std::string line; // count frequencies while(getline(in, line)) { std::vector<std::string> tokens; boost::algorithm::split_regex(tokens, line, boost::regex(" ")); for(const std::string token : tokens){ std::vector<std::string> col; boost::algorithm::split_regex(col, token, boost::regex("-\\|-")); assert(col.size() == d_feat.size() + 1); if(col.size() != vec_str_freq.size()){ vec_str_freq.resize(col.size()); } for(unsigned int col_id = 0; col_id < col.size(); col_id++){ vec_str_freq[col_id][col.at(col_id)]++; } std::vector<std::string> chars = split_to_char(col.at(0)); for(auto elem : chars){ str_char_freq[elem]++; } } } in.close(); // cutting words and features for(unsigned int col_id = 0; col_id < d_feat.size() + 1; col_id++){ std::vector<std::pair<std::string, unsigned int> > str_vec; for(auto& p1: vec_str_freq.at(col_id)){ str_vec.push_back(std::pair<std::string, unsigned int>(p1.first, p1.second)); } CompareString comp; sort(str_vec.begin(), str_vec.end(), comp); if(col_id > 0){ for(auto& p1 : str_vec){ if(feature_vocab_size.at(col_id-1) >= 0 && d_feat[col_id-1].size() + 1 >= (unsigned int)(feature_vocab_size.at(col_id-1))){ // -1 for <UNK> break; } d_feat[col_id-1].convert(p1.first); } }else{ for(auto& p1 : str_vec){ if(word_vocab_size >= 0 && d_word.size() + 1 >= (unsigned int)(word_vocab_size)){ // -1 for <UNK> break; } d_word.convert(p1.first); } } } // cutting chars { std::vector<std::pair<std::string, unsigned int> > str_vec; for(auto& p1: str_char_freq){ str_vec.push_back(std::pair<std::string, unsigned int>(p1.first, p1.second)); } CompareString comp; sort(str_vec.begin(), str_vec.end(), comp); for(auto& p1 : str_vec){ if(char_vocab_size >= 0 && d_char.size() + 1 >= (unsigned int)(char_vocab_size)){ // -1 for <UNK> break; } d_char.convert(p1.first); } } // fix the vocabulary sizes d_word.freeze(); d_word.set_unk(opts.unk_symbol); d_char.freeze(); d_char.set_unk(opts.unk_symbol); for(unsigned int feat_id = 0; feat_id < d_feat.size(); feat_id++){ d_feat[feat_id].freeze(); // no new word types allowed d_feat[feat_id].set_unk(opts.unk_symbol); } set_unk_id(opts); // set freq word_freq.resize(d_word.size()); for(auto& p1: vec_str_freq.at(0)){ word_freq[d_word.convert(p1.first)] = p1.second; } char_freq.resize(d_char.size()); for(auto& p1: str_char_freq){ char_freq[d_char.convert(p1.first)] = p1.second; } feat_freq.resize(d_feat.size()); for(unsigned int feat_id = 0; feat_id < d_feat.size(); feat_id++){ feat_freq[feat_id].resize(d_feat.at(feat_id).size()); for(auto& p1: vec_str_freq.at(feat_id + 1)){ feat_freq[feat_id][d_feat[feat_id].convert(p1.first)] = p1.second; } } } }; class dict_set_label { public: dynet::Dict d_word; unsigned int start_id_word; unsigned int keep_id_word; unsigned int delete_id_word; unsigned int end_id_word; /* set start and end of sentence id */ void set_id(const s2s_options &opts){ // word start_id_word = d_word.convert(opts.start_symbol); keep_id_word = d_word.convert(opts.keep_symbol); delete_id_word = d_word.convert(opts.delete_symbol); end_id_word = d_word.convert(opts.end_symbol); d_word.freeze(); } }; }; #endif
36.891697
170
0.573735
[ "vector" ]
34b29a1c587f79308f5cb2d514b8cda25d1d0937
7,134
cpp
C++
OpenGL_3DJV1/CarreTexture01/CarreTexture01.cpp
Epono/5A-3DJV-OpenGL_Project
59ea1aac67780f4b53687beb46085e10c2ca4d4c
[ "MIT" ]
null
null
null
OpenGL_3DJV1/CarreTexture01/CarreTexture01.cpp
Epono/5A-3DJV-OpenGL_Project
59ea1aac67780f4b53687beb46085e10c2ca4d4c
[ "MIT" ]
null
null
null
OpenGL_3DJV1/CarreTexture01/CarreTexture01.cpp
Epono/5A-3DJV-OpenGL_Project
59ea1aac67780f4b53687beb46085e10c2ca4d4c
[ "MIT" ]
null
null
null
// Triangle01.cpp : Defines the entry point for the console application. // // Specifique a Windows #if _WIN32 #include <Windows.h> #define FREEGLUT_LIB_PRAGMAS 0 #pragma comment(lib, "freeglut.lib") #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glew32s.lib") #endif // Entete OpenGL #define GLEW_STATIC 1 #include <GL/glew.h> //#include <gl/GL.h> //#include "GL/glext.h" // FreeGLUT #include "GL/freeglut.h" // STB #define STB_IMAGE_IMPLEMENTATION #include "stb-master/stb_image.h" #include <cstdio> #include <cmath> #include "../common/EsgiShader.h" EsgiShader basicShader; int previousTime = 0; GLuint carreVBO; GLuint carreEBO; GLuint textureObj; struct Sprite { float x, y; } g_Sprite[100]; struct Camera { float x, y; } g_Camera; void Initialize() { printf("Version Pilote OpenGL : %s\n", glGetString(GL_VERSION)); printf("Type de GPU : %s\n", glGetString(GL_RENDERER)); printf("Fabricant : %s\n", glGetString(GL_VENDOR)); printf("Version GLSL : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); int numExtensions; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); GLenum error = glewInit(); if (error != GL_NO_ERROR) { // TODO } for (int index = 0; index < numExtensions; ++index) { printf("Extension[%d] : %s\n", index, glGetStringi(GL_EXTENSIONS, index)); } basicShader.LoadVertexShader("basic.vs"); basicShader.LoadFragmentShader("basic.fs"); basicShader.Create(); static const float g_Carre[] = { // x,y intens. s,t -32.0f, 32.0f, 1.0f, 0.0f, 1.0f, -32.0f, -32.0f, 0.5f, 0.0f, 0.0f, 32.0f, -32.0f, 0.5f, 1.0f, 0.0f, 32.0f, 32.0f, 0.0f, 1.f, 1.f, }; glGenBuffers(1, &carreVBO); glBindBuffer(GL_ARRAY_BUFFER, carreVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*20, g_Carre, GL_STATIC_DRAW); //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*9, nullptr, GL_STATIC_DRAW); //glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*9, g_Triangle); glBindBuffer(GL_ARRAY_BUFFER, 0); static const unsigned short indicesCarre[] = { 0, 1, 2, 2, 3, 0 }; glGenBuffers(1, &carreEBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, carreEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short)*6, indicesCarre, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); static unsigned char image[] = { 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255 }; glGenTextures(1, &textureObj); glBindTexture(GL_TEXTURE_2D, textureObj); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); static const int worldSize = 3000; for (int index = 0; index < 100; ++index) { g_Sprite[index].x = (float(rand())/RAND_MAX - 0.5f) * worldSize/2; g_Sprite[index].y = (float(rand())/RAND_MAX - 0.5f) * worldSize/2; } previousTime = glutGet(GLUT_ELAPSED_TIME); } void Terminate() { glDeleteTextures(1, &textureObj); glDeleteBuffers(1, &carreVBO); basicShader.Destroy(); } void Orthographic(float *matrix, float L, float R, float T, float B, float N, float F) { #if 0 const float mat4[] = { 2.f / (R-L), 0.0f, 0.0f, 0.0f, 0.0f, 2.f / (T-B), 0.0f, 0.0f, 0.0f, 0.0f, -2.f / (F-N), 0.0f, -(R+L)/(R-L), -(T+B)/(T-B), -(F+N)/(F-N), 1.0f }; memcpy(matrix, mat4, sizeof(float) * 16); #else memset(matrix, 0, sizeof(float) * 16); matrix[0] = 2.f / (R-L); matrix[5] = 2.f / (T-B); matrix[10] = -2.f / (F-N); matrix[12] = -(R+L) / (R-L); matrix[13] = -(T+B) / (T-B); matrix[14] = -(F+N) / (F-N); matrix[15] = 1.f; #endif } void Translate(float *matrix, float tx, float ty, float tz = 0.f) { memset(matrix, 0, sizeof(float) * 16); matrix[0] = 1.f; matrix[5] = 1.f; matrix[10] = 1.f; matrix[12] = tx; matrix[13] = ty; matrix[14] = tz; matrix[15] = 1.f; } void Render() { glViewport(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); glClearColor(0.f, 0.5f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); GLuint program = basicShader.GetProgram(); glUseProgram(program); float w = (float)glutGet(GLUT_WINDOW_WIDTH); float h = (float)glutGet(GLUT_WINDOW_HEIGHT); float projection[16]; //Orthographic(projection, -w/2, w/2, -h/2, h/2, -1.f, 1.f); Orthographic(projection, 0, w, h, 0, -1.f, 1.f); GLint projLocation = glGetUniformLocation(program, "u_projectionMatrix"); glUniformMatrix4fv(projLocation, 1, GL_FALSE, projection); glBindBuffer(GL_ARRAY_BUFFER, carreVBO); int TailleVertex = 5*sizeof(float); GLint positionLocation = glGetAttribLocation(program, "a_position"); glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE,TailleVertex, 0); glEnableVertexAttribArray(positionLocation); GLint intensityLocation = glGetAttribLocation(program, "a_intensity"); glVertexAttribPointer(intensityLocation, 1, GL_FLOAT, GL_FALSE, TailleVertex, (void*)(2*sizeof(float))); glEnableVertexAttribArray(intensityLocation); GLint texCoordsLocation = glGetAttribLocation(program, "a_texCoords"); glVertexAttribPointer(texCoordsLocation, 2, GL_FLOAT, GL_FALSE, TailleVertex, (void*)(3*sizeof(float))); glEnableVertexAttribArray(texCoordsLocation); // variables uniformes (constantes) durant le rendu de la primitive GLint offsetLocation = glGetUniformLocation(program, "u_offset"); glUniform3f(offsetLocation, 0.0f, 0.0f, 0.0f); GLint colorLocation = glGetUniformLocation(program, "u_constantColor"); glUniform4f(colorLocation, 1.0f, 0.0f, 0.0f, 1.0f); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureObj); GLint textureLocation = glGetUniformLocation(program, "u_texture0"); glUniform1i(textureLocation, 0); int currentTime = glutGet(GLUT_ELAPSED_TIME); int delta = currentTime - previousTime; previousTime = currentTime; static float time = 1.f; time += delta/1000.f; GLint timeLocation = glGetUniformLocation(program, "u_time"); glUniform1f(timeLocation, time); float viewTransform[16]; Translate(viewTransform, -time*60.f, 0.f); GLint viewLocation = glGetUniformLocation(program, "u_viewMatrix"); glUniformMatrix4fv(viewLocation, 1, GL_FALSE, viewTransform); //glUniform3f(offsetLocation, cos(time), sin(time), 0.0f); glUniform4f(colorLocation, 1.0f, 1.0f, 0.0f, 1.0f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, carreEBO); float worldTranslate[16]; GLint worldLocation = glGetUniformLocation(program, "u_worldMatrix"); for (int index = 0; index < 100; index++) { Translate(worldTranslate, g_Sprite[index].x, g_Sprite[index].y); glUniformMatrix4fv(worldLocation, 1, GL_FALSE, worldTranslate); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr/*indicesTriangle*/); }; glUseProgram(0); glutSwapBuffers(); glutPostRedisplay(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(800, 600); glutCreateWindow("Basic"); #ifdef FREEGLUT // Note: glutSetOption n'est disponible qu'avec freeGLUT glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif Initialize(); glutDisplayFunc(Render); glutMainLoop(); Terminate(); return 0; }
28.309524
105
0.716288
[ "render" ]
34b5eae7d54feb0d624111fe4b2e8cd691c9ab36
1,751
hpp
C++
caffe/include/caffe/layers/energy_loss_layer.hpp
JulianYG/redeye_sim
eaf2ccf9370f5fcfa2bfcc9ba60e3e0fcc319f54
[ "CNRI-Python" ]
11
2016-06-28T15:42:12.000Z
2021-03-07T04:17:47.000Z
src/energy_loss_layer.hpp
JulianYG/RedEye
eaf2ccf9370f5fcfa2bfcc9ba60e3e0fcc319f54
[ "CNRI-Python" ]
1
2016-06-28T15:46:50.000Z
2016-07-01T12:09:56.000Z
src/energy_loss_layer.hpp
JulianYG/RedEye
eaf2ccf9370f5fcfa2bfcc9ba60e3e0fcc319f54
[ "CNRI-Python" ]
10
2016-06-19T21:23:24.000Z
2020-10-05T08:52:56.000Z
#ifndef CAFFE_ENERGY_LOSS_LAYER_HPP_ #define CAFFE_ENERGY_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" namespace caffe { /** * Computes the energy loss based on the noise type and magnitude. Used * to train caffe for a better combination of both prediction accuracy * and noise tolerance, which reduces processing energy. */ template <typename Dtype> class EnergyLossLayer: public Layer<Dtype> { public: explicit EnergyLossLayer(const LayerParameter& param):Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline int ExactNumTopBlobs() const { return 1; } virtual inline const char* type() const { return "EnergyLoss"; } virtual inline int MinBottomBlobs() const { return 1; } virtual inline int ExactNumBottomBlobs() const { return -1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); EnergyLossParameter_ModelType _model; Dtype _alpha; vector<int> _param_types; }; } #endif // CAFFE_ENERGY_LOSS_LAYER_HPP_
33.673077
81
0.70988
[ "vector" ]
34bd588505a9978f40b6c652357f3dfbc356c806
1,771
cpp
C++
src/cpp/lib/QtWidgets/QGroupBox/qgroupbox_wrap.cpp
TheRakeshPurohit/nodegui
9fcc5e99d30ff0dc208f045abeeab50e59a73f22
[ "MIT" ]
null
null
null
src/cpp/lib/QtWidgets/QGroupBox/qgroupbox_wrap.cpp
TheRakeshPurohit/nodegui
9fcc5e99d30ff0dc208f045abeeab50e59a73f22
[ "MIT" ]
1
2019-11-05T11:00:17.000Z
2019-11-05T11:00:17.000Z
src/cpp/lib/QtWidgets/QGroupBox/qgroupbox_wrap.cpp
master-atul/nodegui
123524d1265ec9c9737596cfb475308c56a06750
[ "MIT" ]
null
null
null
#include "QtWidgets/QGroupBox/qgroupbox_wrap.h" #include <QWidget> #include "Extras/Utils/nutils.h" #include "QtWidgets/QWidget/qwidget_wrap.h" Napi::FunctionReference QGroupBoxWrap::constructor; Napi::Object QGroupBoxWrap::init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); char CLASSNAME[] = "QGroupBox"; Napi::Function func = DefineClass( env, CLASSNAME, {QWIDGET_WRAPPED_METHODS_EXPORT_DEFINE(QGroupBoxWrap)}); constructor = Napi::Persistent(func); QOBJECT_REGISTER_WRAPPER(QGroupBox, QGroupBoxWrap); exports.Set(CLASSNAME, func); return exports; } QGroupBox* QGroupBoxWrap::getInternalInstance() { return this->instance; } QGroupBoxWrap::QGroupBoxWrap(const Napi::CallbackInfo& info) : Napi::ObjectWrap<QGroupBoxWrap>(info) { Napi::Env env = info.Env(); size_t argCount = info.Length(); if (argCount == 0) { // --- Construct a new instance this->instance = new NGroupBox(); } else if (argCount == 1) { if (info[0].IsExternal()) { // --- Wrap a given C++ instance this->instance = info[0].As<Napi::External<QGroupBox>>().Data(); } else { // --- Construct a new instance and pass a parent Napi::Object parentObject = info[0].As<Napi::Object>(); NodeWidgetWrap* parentWidgetWrap = Napi::ObjectWrap<NodeWidgetWrap>::Unwrap(parentObject); this->instance = new NGroupBox(parentWidgetWrap->getInternalInstance()); } } else { Napi::TypeError::New( env, "NodeGui: QGroupBoxWrap: Wrong number of arguments to constructor") .ThrowAsJavaScriptException(); } this->rawData = extrautils::configureQWidget(this->getInternalInstance(), false); } QGroupBoxWrap::~QGroupBoxWrap() { extrautils::safeDelete(this->instance); }
34.72549
80
0.695652
[ "object" ]
34bddcc135fbc7d07622b62e351c7f7746627439
37,931
cpp
C++
dpcpp/particlefilter/ex_particle_SYCL_float_seq.dp.cpp
CR-G/rodinia-dpct-dpcpp
a0e80bd715c3cc7c3356e1e00245b91e15927d2c
[ "MIT" ]
1
2022-03-28T18:13:13.000Z
2022-03-28T18:13:13.000Z
dpcpp/particlefilter/ex_particle_SYCL_float_seq.dp.cpp
artecs-group/rodinia-dpct-dpcpp
a0e80bd715c3cc7c3356e1e00245b91e15927d2c
[ "MIT" ]
7
2021-04-15T11:53:20.000Z
2021-05-15T08:58:30.000Z
dpcpp/particlefilter/ex_particle_SYCL_float_seq.dp.cpp
artecs-group/rodinia-dpct-dpcpp
a0e80bd715c3cc7c3356e1e00245b91e15927d2c
[ "MIT" ]
null
null
null
#include <CL/sycl.hpp> #include <dpct/dpct.hpp> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <math.h> #include <unistd.h> #include <fcntl.h> #include <float.h> #include <sys/time.h> #include <time.h> #include "../common.hpp" #define BLOCK_X 16 #define BLOCK_Y 16 #define PI 3.1415926535897932 //const int threads_per_block = 512; const int threads_per_block = 128; /** @var M value for Linear Congruential Generator (LCG); use GCC's value */ long M = INT_MAX; /** @var A value for LCG */ int A = 1103515245; /** @var C value for LCG */ int C = 12345; /***************************** *GET_TIME *returns a long int representing the time *****************************/ long long get_time() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000000) +tv.tv_usec; } // Returns the number of seconds elapsed between the two specified times double elapsed_time(long long start_time, long long end_time) { return (double) (end_time - start_time) / (1000 * 1000); } /***************************** * CHECK_ERROR * Checks for CUDA errors and prints them to the screen to help with * debugging of CUDA related programming *****************************/ void check_error(int e) { } void cuda_print_double_array(double *array_GPU, size_t size) { //allocate temporary array for printing double* mem = (double*) malloc(sizeof (double) *size); //transfer data from device dpct::get_default_queue() .memcpy(mem, array_GPU, sizeof(double) * size) .wait(); printf("PRINTING ARRAY VALUES\n"); //print values in memory for (size_t i = 0; i < size; ++i) { printf("[%lu]:%0.6f\n", i, mem[i]); } printf("FINISHED PRINTING ARRAY VALUES\n"); //clean up memory free(mem); mem = NULL; } /******************************** * CALC LIKELIHOOD SUM * DETERMINES THE LIKELIHOOD SUM BASED ON THE FORMULA: SUM( (IK[IND] - 100)^2 - (IK[IND] - 228)^2)/ 100 * param 1 I 3D matrix * param 2 current ind array * param 3 length of ind array * returns a double representing the sum ********************************/ double calcLikelihoodSum(unsigned char * I, int * ind, int numOnes, int index) { double likelihoodSum = 0.0; int x; for (x = 0; x < numOnes; x++) likelihoodSum += ((double)(I[ind[index * numOnes + x]] - 100) * (double)(I[ind[index * numOnes + x]] - 100) - (double)(I[ind[index * numOnes + x]] - 228) * (double)(I[ind[index * numOnes + x]] - 228)) / 50.0; return likelihoodSum; } /**************************** CDF CALCULATE CALCULATES CDF param1 CDF param2 weights param3 Nparticles *****************************/ void cdfCalc(double * CDF, double * weights, int Nparticles) { int x; CDF[0] = weights[0]; for (x = 1; x < Nparticles; x++) { CDF[x] = weights[x] + CDF[x - 1]; } } /***************************** * RANDU * GENERATES A UNIFORM DISTRIBUTION * returns a double representing a randomily generated number from a uniform distribution with range [0, 1) ******************************/ double d_randu(int * seed, int index) { int M = INT_MAX; int A = 1103515245; int C = 12345; int num = A * seed[index] + C; seed[index] = num % M; return sycl::fabs(seed[index] / ((double)M)); }/** * Generates a uniformly distributed random number using the provided seed and GCC's settings for the Linear Congruential Generator (LCG) * @see http://en.wikipedia.org/wiki/Linear_congruential_generator * @note This function is thread-safe * @param seed The seed array * @param index The specific index of the seed to be advanced * @return a uniformly distributed number [0, 1) */ double randu(int * seed, int index) { int num = A * seed[index] + C; seed[index] = num % M; return fabs(seed[index] / ((double) M)); } /** * Generates a normally distributed random number using the Box-Muller transformation * @note This function is thread-safe * @param seed The seed array * @param index The specific index of the seed to be advanced * @return a double representing random number generated using the Box-Muller algorithm * @see http://en.wikipedia.org/wiki/Normal_distribution, section computing value for normal random distribution */ double randn(int * seed, int index) { /*Box-Muller algorithm*/ double u = randu(seed, index); double v = randu(seed, index); double cosine = cos(2 * PI * v); double rt = -2 * log(u); return sqrt(rt) * cosine; } double test_randn(int * seed, int index) { //Box-Muller algortihm double pi = 3.14159265358979323846; double u = randu(seed, index); double v = randu(seed, index); double cosine = cos(2 * pi * v); double rt = -2 * log(u); return sqrt(rt) * cosine; } double d_randn(int * seed, int index) { //Box-Muller algortihm double pi = 3.14159265358979323846; double u = d_randu(seed, index); double v = d_randu(seed, index); double cosine = sycl::cos(2 * pi * v); double rt = -2 * sycl::log(u); return sycl::sqrt(rt) * cosine; } /**************************** UPDATE WEIGHTS UPDATES WEIGHTS param1 weights param2 likelihood param3 Nparcitles ****************************/ double updateWeights(double * weights, double * likelihood, int Nparticles) { int x; double sum = 0; for (x = 0; x < Nparticles; x++) { weights[x] = weights[x] * sycl::exp(likelihood[x]); sum += weights[x]; } return sum; } int findIndexBin(double * CDF, int beginIndex, int endIndex, double value) { if (endIndex < beginIndex) return -1; int middleIndex; while (endIndex > beginIndex) { middleIndex = beginIndex + ((endIndex - beginIndex) / 2); if (CDF[middleIndex] >= value) { if (middleIndex == 0) return middleIndex; else if (CDF[middleIndex - 1] < value) return middleIndex; else if (CDF[middleIndex - 1] == value) { while (CDF[middleIndex] == value && middleIndex >= 0) middleIndex--; middleIndex++; return middleIndex; } } if (CDF[middleIndex] > value) endIndex = middleIndex - 1; else beginIndex = middleIndex + 1; } return -1; } /** added this function. was missing in original double version. * Takes in a double and returns an integer that approximates to that double * @return if the mantissa < .5 => return value < input value; else return value > input value */ double dev_round_double(double value) { int newValue = (int) (value); if (value - newValue < .5f) return newValue; else return newValue++; } /***************************** * CUDA Find Index Kernel Function to replace FindIndex * param1: arrayX * param2: arrayY * param3: CDF * param4: u * param5: xj * param6: yj * param7: weights * param8: Nparticles *****************************/ void find_index_kernel(double * arrayX, double * arrayY, double * CDF, double * u, double * xj, double * yj, double * weights, int Nparticles, sycl::nd_item<3> item_ct1) { int block_id = item_ct1.get_group(2); int i = item_ct1.get_local_range().get(2) * block_id + item_ct1.get_local_id(2); if (i < Nparticles) { int index = -1; int x; for (x = 0; x < Nparticles; x++) { if (CDF[x] >= u[i]) { index = x; break; } } if (index == -1) { index = Nparticles - 1; } xj[i] = arrayX[index]; yj[i] = arrayY[index]; //weights[i] = 1 / ((double) (Nparticles)); //moved this code to the beginning of likelihood kernel } item_ct1.barrier(); } void normalize_weights_kernel(double * weights, int Nparticles, double* partial_sums, double * CDF, double * u, int * seed, sycl::nd_item<3> item_ct1, double *u1, double *sumWeights) { int block_id = item_ct1.get_group(2); int i = item_ct1.get_local_range().get(2) * block_id + item_ct1.get_local_id(2); if (0 == item_ct1.get_local_id(2)) *sumWeights = partial_sums[0]; item_ct1.barrier(); if (i < Nparticles) { weights[i] = weights[i] / *sumWeights; } item_ct1.barrier(); if (i == 0) { cdfCalc(CDF, weights, Nparticles); u[0] = (1 / ((double) (Nparticles))) * d_randu(seed, i); // do this to allow all threads in all blocks to use the same u1 } item_ct1.barrier(); if (0 == item_ct1.get_local_id(2)) *u1 = u[0]; item_ct1.barrier(); if (i < Nparticles) { u[i] = *u1 + i / ((double)(Nparticles)); } } void sum_kernel(double* partial_sums, int Nparticles, sycl::nd_item<3> item_ct1) { int block_id = item_ct1.get_group(2); int i = item_ct1.get_local_range().get(2) * block_id + item_ct1.get_local_id(2); if (i == 0) { int x; double sum = 0.0; int num_blocks = sycl::ceil((double)Nparticles / (double)threads_per_block); for (x = 0; x < num_blocks; x++) { sum += partial_sums[x]; } partial_sums[0] = sum; } } /***************************** * CUDA Likelihood Kernel Function to replace FindIndex * param1: arrayX * param2: arrayY * param2.5: CDF * param3: ind * param4: objxy * param5: likelihood * param6: I * param6.5: u * param6.75: weights * param7: Nparticles * param8: countOnes * param9: max_size * param10: k * param11: IszY * param12: Nfr *****************************/ void likelihood_kernel(double * arrayX, double * arrayY, double * xj, double * yj, double * CDF, int * ind, int * objxy, double * likelihood, unsigned char * I, double * u, double * weights, int Nparticles, int countOnes, int max_size, int k, int IszY, int Nfr, int *seed, double* partial_sums, sycl::nd_item<3> item_ct1, double *buffer) { int block_id = item_ct1.get_group(2); int i = item_ct1.get_local_range().get(2) * block_id + item_ct1.get_local_id(2); int y; int indX, indY; if (i < Nparticles) { arrayX[i] = xj[i]; arrayY[i] = yj[i]; weights[i] = 1 / ((double) (Nparticles)); //Donnie - moved this line from end of find_index_kernel to prevent all weights from being reset before calculating position on final iteration. arrayX[i] = arrayX[i] + 1.0 + 5.0 * d_randn(seed, i); arrayY[i] = arrayY[i] - 2.0 + 2.0 * d_randn(seed, i); } item_ct1.barrier(); if (i < Nparticles) { for (y = 0; y < countOnes; y++) { //added dev_round_double() to be consistent with roundDouble indX = dev_round_double(arrayX[i]) + objxy[y * 2 + 1]; indY = dev_round_double(arrayY[i]) + objxy[y * 2]; ind[i * countOnes + y] = sycl::abs(indX * IszY * Nfr + indY * Nfr + k); if (ind[i * countOnes + y] >= max_size) ind[i * countOnes + y] = 0; } likelihood[i] = calcLikelihoodSum(I, ind, countOnes, i); likelihood[i] = likelihood[i] / countOnes; weights[i] = weights[i] * sycl::exp(likelihood[i]); // Donnie Newell - added the missing // exponential function call } buffer[item_ct1.get_local_id(2)] = 0.0; item_ct1.barrier(); if (i < Nparticles) { buffer[item_ct1.get_local_id(2)] = weights[i]; } item_ct1.barrier(); //this doesn't account for the last block that isn't full for (unsigned int s = item_ct1.get_local_range().get(2) / 2; s > 0; s >>= 1) { if (item_ct1.get_local_id(2) < s) { buffer[item_ct1.get_local_id(2)] += buffer[item_ct1.get_local_id(2) + s]; } item_ct1.barrier(); } if (item_ct1.get_local_id(2) == 0) { partial_sums[item_ct1.get_group(2)] = buffer[0]; } item_ct1.barrier(); } /** * Takes in a double and returns an integer that approximates to that double * @return if the mantissa < .5 => return value < input value; else return value > input value */ double roundDouble(double value) { int newValue = (int) (value); if (value - newValue < .5) return newValue; else return newValue++; } /** * Set values of the 3D array to a newValue if that value is equal to the testValue * @param testValue The value to be replaced * @param newValue The value to replace testValue with * @param array3D The image vector * @param dimX The x dimension of the frame * @param dimY The y dimension of the frame * @param dimZ The number of frames */ void setIf(int testValue, int newValue, unsigned char * array3D, int * dimX, int * dimY, int * dimZ) { int x, y, z; for (x = 0; x < *dimX; x++) { for (y = 0; y < *dimY; y++) { for (z = 0; z < *dimZ; z++) { if (array3D[x * *dimY * *dimZ + y * *dimZ + z] == testValue) array3D[x * *dimY * *dimZ + y * *dimZ + z] = newValue; } } } } /** * Sets values of 3D matrix using randomly generated numbers from a normal distribution * @param array3D The video to be modified * @param dimX The x dimension of the frame * @param dimY The y dimension of the frame * @param dimZ The number of frames * @param seed The seed array */ void addNoise(unsigned char * array3D, int * dimX, int * dimY, int * dimZ, int * seed) { int x, y, z; for (x = 0; x < *dimX; x++) { for (y = 0; y < *dimY; y++) { for (z = 0; z < *dimZ; z++) { array3D[x * *dimY * *dimZ + y * *dimZ + z] = array3D[x * *dimY * *dimZ + y * *dimZ + z] + (unsigned char) (5 * randn(seed, 0)); } } } } /** * Fills a radius x radius matrix representing the disk * @param disk The pointer to the disk to be made * @param radius The radius of the disk to be made */ void strelDisk(int * disk, int radius) { int diameter = radius * 2 - 1; int x, y; for (x = 0; x < diameter; x++) { for (y = 0; y < diameter; y++) { double distance = sqrt(pow((double)(x - radius + 1), 2) + pow((double)(y - radius + 1), 2)); if (distance < radius) disk[x * diameter + y] = 1; else disk[x * diameter + y] = 0; } } } /** * Dilates the provided video * @param matrix The video to be dilated * @param posX The x location of the pixel to be dilated * @param posY The y location of the pixel to be dilated * @param poxZ The z location of the pixel to be dilated * @param dimX The x dimension of the frame * @param dimY The y dimension of the frame * @param dimZ The number of frames * @param error The error radius */ void dilate_matrix(unsigned char * matrix, int posX, int posY, int posZ, int dimX, int dimY, int dimZ, int error) { int startX = posX - error; while (startX < 0) startX++; int startY = posY - error; while (startY < 0) startY++; int endX = posX + error; while (endX > dimX) endX--; int endY = posY + error; while (endY > dimY) endY--; int x, y; for (x = startX; x < endX; x++) { for (y = startY; y < endY; y++) { double distance = sqrt(pow((double)(x - posX), 2) + pow((double)(y - posY), 2)); if (distance < error) matrix[x * dimY * dimZ + y * dimZ + posZ] = 1; } } } /** * Dilates the target matrix using the radius as a guide * @param matrix The reference matrix * @param dimX The x dimension of the video * @param dimY The y dimension of the video * @param dimZ The z dimension of the video * @param error The error radius to be dilated * @param newMatrix The target matrix */ void imdilate_disk(unsigned char * matrix, int dimX, int dimY, int dimZ, int error, unsigned char * newMatrix) { int x, y, z; for (z = 0; z < dimZ; z++) { for (x = 0; x < dimX; x++) { for (y = 0; y < dimY; y++) { if (matrix[x * dimY * dimZ + y * dimZ + z] == 1) { dilate_matrix(newMatrix, x, y, z, dimX, dimY, dimZ, error); } } } } } /** * Fills a 2D array describing the offsets of the disk object * @param se The disk object * @param numOnes The number of ones in the disk * @param neighbors The array that will contain the offsets * @param radius The radius used for dilation */ void getneighbors(int * se, int numOnes, int * neighbors, int radius) { int x, y; int neighY = 0; int center = radius - 1; int diameter = radius * 2 - 1; for (x = 0; x < diameter; x++) { for (y = 0; y < diameter; y++) { if (se[x * diameter + y]) { neighbors[neighY * 2] = (int) (y - center); neighbors[neighY * 2 + 1] = (int) (x - center); neighY++; } } } } /** * The synthetic video sequence we will work with here is composed of a * single moving object, circular in shape (fixed radius) * The motion here is a linear motion * the foreground intensity and the background intensity is known * the image is corrupted with zero mean Gaussian noise * @param I The video itself * @param IszX The x dimension of the video * @param IszY The y dimension of the video * @param Nfr The number of frames of the video * @param seed The seed array used for number generation */ void videoSequence(unsigned char * I, int IszX, int IszY, int Nfr, int * seed) { int k; int max_size = IszX * IszY * Nfr; /*get object centers*/ int x0 = (int) roundDouble(IszY / 2.0); int y0 = (int) roundDouble(IszX / 2.0); I[x0 * IszY * Nfr + y0 * Nfr + 0] = 1; /*move point*/ int xk, yk, pos; for (k = 1; k < Nfr; k++) { xk = abs(x0 + (k-1)); yk = abs(y0 - 2 * (k-1)); pos = yk * IszY * Nfr + xk * Nfr + k; if (pos >= max_size) pos = 0; I[pos] = 1; } /*dilate matrix*/ unsigned char * newMatrix = (unsigned char *) malloc(sizeof (unsigned char) * IszX * IszY * Nfr); imdilate_disk(I, IszX, IszY, Nfr, 5, newMatrix); int x, y; for (x = 0; x < IszX; x++) { for (y = 0; y < IszY; y++) { for (k = 0; k < Nfr; k++) { I[x * IszY * Nfr + y * Nfr + k] = newMatrix[x * IszY * Nfr + y * Nfr + k]; } } } free(newMatrix); /*define background, add noise*/ setIf(0, 100, I, &IszX, &IszY, &Nfr); setIf(1, 228, I, &IszX, &IszY, &Nfr); /*add noise*/ addNoise(I, &IszX, &IszY, &Nfr, seed); } /** * Finds the first element in the CDF that is greater than or equal to the provided value and returns that index * @note This function uses sequential search * @param CDF The CDF * @param lengthCDF The length of CDF * @param value The value to be found * @return The index of value in the CDF; if value is never found, returns the last index */ int findIndex(double * CDF, int lengthCDF, double value) { int index = -1; int x; for (x = 0; x < lengthCDF; x++) { if (CDF[x] >= value) { index = x; break; } } if (index == -1) { return lengthCDF - 1; } return index; } /** * The implementation of the particle filter using OpenMP for many frames * @see http://openmp.org/wp/ * @note This function is designed to work with a video of several frames. In addition, it references a provided MATLAB function which takes the video, the objxy matrix and the x and y arrays as arguments and returns the likelihoods * @param I The video to be run * @param IszX The x dimension of the video * @param IszY The y dimension of the video * @param Nfr The number of frames * @param seed The seed array used for random number generation * @param Nparticles The number of particles to be used */ void particleFilter(unsigned char *I, int IszX, int IszY, int Nfr, int *seed, int Nparticles) { dpct::device_ext &dev_ct1 = dpct::get_current_device(); sycl::queue &q_ct1 = dev_ct1.default_queue(); int max_size = IszX * IszY*Nfr; //original particle centroid double xe = roundDouble(IszY / 2.0); double ye = roundDouble(IszX / 2.0); //expected object locations, compared to center int radius = 5; int diameter = radius * 2 - 1; int * disk = (int*) malloc(diameter * diameter * sizeof (int)); strelDisk(disk, radius); int countOnes = 0; int x, y; for (x = 0; x < diameter; x++) { for (y = 0; y < diameter; y++) { if (disk[x * diameter + y] == 1) countOnes++; } } int * objxy = (int *) malloc(countOnes * 2 * sizeof (int)); getneighbors(disk, countOnes, objxy, radius); //initial weights are all equal (1/Nparticles) double * weights = (double *) malloc(sizeof (double) *Nparticles); for (x = 0; x < Nparticles; x++) { weights[x] = 1 / ((double) (Nparticles)); } //initial likelihood to 0.0 double * likelihood = (double *) malloc(sizeof (double) *Nparticles); double * arrayX = (double *) malloc(sizeof (double) *Nparticles); double * arrayY = (double *) malloc(sizeof (double) *Nparticles); double * xj = (double *) malloc(sizeof (double) *Nparticles); double * yj = (double *) malloc(sizeof (double) *Nparticles); double * CDF = (double *) malloc(sizeof (double) *Nparticles); //GPU copies of arrays double * arrayX_GPU; double * arrayY_GPU; double * xj_GPU; double * yj_GPU; double * CDF_GPU; double * likelihood_GPU; unsigned char * I_GPU; double * weights_GPU; int * objxy_GPU; int * ind = (int*) malloc(sizeof (int) *countOnes * Nparticles); int * ind_GPU; double * u = (double *) malloc(sizeof (double) *Nparticles); double * u_GPU; int * seed_GPU; double* partial_sums; //CUDA memory allocation /* DPCT1003:1: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (arrayX_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); /* DPCT1003:2: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ try{ check_error( (arrayY_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); } catch(const sycl::exception& e) { std::cerr << e.what() << '\n'; } /* DPCT1003:3: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((xj_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); /* DPCT1003:4: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((yj_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); /* DPCT1003:5: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((CDF_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); /* DPCT1003:6: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((u_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); /* DPCT1003:7: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (likelihood_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); //set likelihood to zero /* DPCT1003:8: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memset((void *)likelihood_GPU, 0, sizeof(double) * Nparticles) .wait(), 0)); /* DPCT1003:9: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (weights_GPU = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); /* DPCT1003:10: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((I_GPU = (unsigned char *)sycl::malloc_device( sizeof(unsigned char) * IszX * IszY * Nfr, q_ct1), 0)); /* DPCT1003:11: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((objxy_GPU = (int *)sycl::malloc_device( sizeof(int) * 2 * countOnes, q_ct1), 0)); /* DPCT1003:12: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((ind_GPU = (int *)sycl::malloc_device( sizeof(int) * countOnes * Nparticles, q_ct1), 0)); /* DPCT1003:13: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error((seed_GPU = sycl::malloc_device<int>(Nparticles, q_ct1), 0)); /* DPCT1003:14: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (partial_sums = sycl::malloc_device<double>(Nparticles, q_ct1), 0)); //Donnie - this loop is different because in this kernel, arrayX and arrayY // are set equal to xj before every iteration, so effectively, arrayX and // arrayY will be set to xe and ye before the first iteration. for (x = 0; x < Nparticles; x++) { xj[x] = xe; yj[x] = ye; } int k; int indX, indY; //start send long long send_start = get_time(); /* DPCT1003:15: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(I_GPU, I, sizeof(unsigned char) * IszX * IszY * Nfr) .wait(), 0)); /* DPCT1003:16: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error(( q_ct1.memcpy(objxy_GPU, objxy, sizeof(int) * 2 * countOnes).wait(), 0)); /* DPCT1003:17: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(weights_GPU, weights, sizeof(double) * Nparticles).wait(), 0)); /* DPCT1003:18: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(xj_GPU, xj, sizeof(double) * Nparticles).wait(), 0)); /* DPCT1003:19: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(yj_GPU, yj, sizeof(double) * Nparticles).wait(), 0)); /* DPCT1003:20: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(seed_GPU, seed, sizeof(int) * Nparticles).wait(), 0)); long long send_end = get_time(); printf("TIME TO SEND TO GPU: %f\n", elapsed_time(send_start, send_end)); int num_blocks = ceil((double) Nparticles / (double) threads_per_block); for (k = 1; k < Nfr; k++) { /* DPCT1049:21: The workgroup size passed to the SYCL kernel may * exceed the limit. To get the device limit, query * info::device::max_work_group_size. Adjust the workgroup size if * needed. */ q_ct1.submit([&](sycl::handler &cgh) { sycl::accessor<double, 1, sycl::access::mode::read_write, sycl::access::target::local> //buffer_acc_ct1(sycl::range<1>(512), cgh); buffer_acc_ct1(sycl::range<1>(threads_per_block), cgh); cgh.parallel_for( sycl::nd_range<3>(sycl::range<3>(1, 1, num_blocks) * sycl::range<3>(1, 1, threads_per_block), sycl::range<3>(1, 1, threads_per_block)), [=](sycl::nd_item<3> item_ct1) { likelihood_kernel(arrayX_GPU, arrayY_GPU, xj_GPU, yj_GPU, CDF_GPU, ind_GPU, objxy_GPU, likelihood_GPU, I_GPU, u_GPU, weights_GPU, Nparticles, countOnes, max_size, k, IszY, Nfr, seed_GPU, partial_sums, item_ct1, buffer_acc_ct1.get_pointer()); }); }); /* DPCT1049:22: The workgroup size passed to the SYCL kernel may * exceed the limit. To get the device limit, query * info::device::max_work_group_size. Adjust the workgroup size if * needed. */ q_ct1.submit([&](sycl::handler &cgh) { cgh.parallel_for( sycl::nd_range<3>(sycl::range<3>(1, 1, num_blocks) * sycl::range<3>(1, 1, threads_per_block), sycl::range<3>(1, 1, threads_per_block)), [=](sycl::nd_item<3> item_ct1) { sum_kernel(partial_sums, Nparticles, item_ct1); }); }); /* DPCT1049:23: The workgroup size passed to the SYCL kernel may * exceed the limit. To get the device limit, query * info::device::max_work_group_size. Adjust the workgroup size if * needed. */ q_ct1.submit([&](sycl::handler &cgh) { sycl::accessor<double, 0, sycl::access::mode::read_write, sycl::access::target::local> u1_acc_ct1(cgh); sycl::accessor<double, 0, sycl::access::mode::read_write, sycl::access::target::local> sumWeights_acc_ct1(cgh); cgh.parallel_for( sycl::nd_range<3>(sycl::range<3>(1, 1, num_blocks) * sycl::range<3>(1, 1, threads_per_block), sycl::range<3>(1, 1, threads_per_block)), [=](sycl::nd_item<3> item_ct1) { normalize_weights_kernel( weights_GPU, Nparticles, partial_sums, CDF_GPU, u_GPU, seed_GPU, item_ct1, u1_acc_ct1.get_pointer(), sumWeights_acc_ct1.get_pointer()); }); }); /* DPCT1049:24: The workgroup size passed to the SYCL kernel may * exceed the limit. To get the device limit, query * info::device::max_work_group_size. Adjust the workgroup size if * needed. */ q_ct1.submit([&](sycl::handler &cgh) { cgh.parallel_for( sycl::nd_range<3>(sycl::range<3>(1, 1, num_blocks) * sycl::range<3>(1, 1, threads_per_block), sycl::range<3>(1, 1, threads_per_block)), [=](sycl::nd_item<3> item_ct1) { find_index_kernel(arrayX_GPU, arrayY_GPU, CDF_GPU, u_GPU, xj_GPU, yj_GPU, weights_GPU, Nparticles, item_ct1); }); }); }//end loop //block till kernels are finished dev_ct1.queues_wait_and_throw(); long long back_time = get_time(); sycl::free(xj_GPU, q_ct1); sycl::free(yj_GPU, q_ct1); sycl::free(CDF_GPU, q_ct1); sycl::free(u_GPU, q_ct1); sycl::free(likelihood_GPU, q_ct1); sycl::free(I_GPU, q_ct1); sycl::free(objxy_GPU, q_ct1); sycl::free(ind_GPU, q_ct1); sycl::free(seed_GPU, q_ct1); sycl::free(partial_sums, q_ct1); long long free_time = get_time(); /* DPCT1003:25: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(arrayX, arrayX_GPU, sizeof(double) * Nparticles).wait(), 0)); long long arrayX_time = get_time(); /* DPCT1003:26: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(arrayY, arrayY_GPU, sizeof(double) * Nparticles).wait(), 0)); long long arrayY_time = get_time(); /* DPCT1003:27: Migrated API does not return error code. (*, 0) is * inserted. You may need to rewrite this code. */ check_error( (q_ct1.memcpy(weights, weights_GPU, sizeof(double) * Nparticles).wait(), 0)); long long back_end_time = get_time(); printf("GPU Execution: %lf\n", elapsed_time(send_end, back_time)); printf("FREE TIME: %lf\n", elapsed_time(back_time, free_time)); printf("TIME TO SEND BACK: %lf\n", elapsed_time(back_time, back_end_time)); printf("SEND ARRAY X BACK: %lf\n", elapsed_time(free_time, arrayX_time)); printf("SEND ARRAY Y BACK: %lf\n", elapsed_time(arrayX_time, arrayY_time)); printf("SEND WEIGHTS BACK: %lf\n", elapsed_time(arrayY_time, back_end_time)); xe = 0; ye = 0; // estimate the object location by expected values for (x = 0; x < Nparticles; x++) { xe += arrayX[x] * weights[x]; ye += arrayY[x] * weights[x]; } printf("XE: %lf\n", xe); printf("YE: %lf\n", ye); double distance = sqrt(pow((double)(xe - (int)roundDouble(IszY / 2.0)), 2) + pow((double)(ye - (int)roundDouble(IszX / 2.0)), 2)); printf("%lf\n", distance); //CUDA freeing of memory sycl::free(weights_GPU, q_ct1); sycl::free(arrayY_GPU, q_ct1); sycl::free(arrayX_GPU, q_ct1); //free regular memory free(likelihood); free(arrayX); free(arrayY); free(xj); free(yj); free(CDF); free(ind); free(u); } int main(int argc, char * argv[]) { char* usage = "double.out -x <dimX> -y <dimY> -z <Nfr> -np <Nparticles>"; //check number of arguments if (argc != 9) { printf("%s\n", usage); return 0; } //check args deliminators if (strcmp(argv[1], "-x") || strcmp(argv[3], "-y") || strcmp(argv[5], "-z") || strcmp(argv[7], "-np")) { printf("%s\n", usage); return 0; } int IszX, IszY, Nfr, Nparticles; //converting a string to a integer if (sscanf(argv[2], "%d", &IszX) == EOF) { printf("ERROR: dimX input is incorrect"); return 0; } if (IszX <= 0) { printf("dimX must be > 0\n"); return 0; } //converting a string to a integer if (sscanf(argv[4], "%d", &IszY) == EOF) { printf("ERROR: dimY input is incorrect"); return 0; } if (IszY <= 0) { printf("dimY must be > 0\n"); return 0; } //converting a string to a integer if (sscanf(argv[6], "%d", &Nfr) == EOF) { printf("ERROR: Number of frames input is incorrect"); return 0; } if (Nfr <= 0) { printf("number of frames must be > 0\n"); return 0; } //converting a string to a integer if (sscanf(argv[8], "%d", &Nparticles) == EOF) { printf("ERROR: Number of particles input is incorrect"); return 0; } if (Nparticles <= 0) { printf("Number of particles must be > 0\n"); return 0; } //establish seed select_custom_device(); int * seed = (int *) malloc(sizeof (int) *Nparticles); int i; for (i = 0; i < Nparticles; i++) seed[i] = time(0) * i; //malloc matrix unsigned char * I = (unsigned char *) malloc(sizeof (unsigned char) *IszX * IszY * Nfr); long long start = get_time(); //call video sequence videoSequence(I, IszX, IszY, Nfr, seed); long long endVideoSequence = get_time(); printf("VIDEO SEQUENCE TOOK %f\n", elapsed_time(start, endVideoSequence)); //call particle filter particleFilter(I, IszX, IszY, Nfr, seed, Nparticles); long long endParticleFilter = get_time(); printf("PARTICLE FILTER TOOK %f\n", elapsed_time(endVideoSequence, endParticleFilter)); printf("ENTIRE PROGRAM TOOK %f\n", elapsed_time(start, endParticleFilter)); free(seed); free(I); return 0; }
34.233755
295
0.553505
[ "object", "shape", "vector", "3d" ]
34be25c17eda7c157cd433fa9a8e106367c5087b
1,685
cpp
C++
Premium/Meeting Rooms II.cpp
JanaSabuj/Leetcode-solutions
78d10926b15252a969df598fbf1f9b69b2760b79
[ "MIT" ]
13
2019-10-12T14:36:32.000Z
2021-06-08T04:26:30.000Z
Premium/Meeting Rooms II.cpp
JanaSabuj/Leetcode-solutions
78d10926b15252a969df598fbf1f9b69b2760b79
[ "MIT" ]
1
2020-02-29T14:02:39.000Z
2020-02-29T14:02:39.000Z
Premium/Meeting Rooms II.cpp
JanaSabuj/Leetcode-solutions
78d10926b15252a969df598fbf1f9b69b2760b79
[ "MIT" ]
3
2020-02-08T12:04:28.000Z
2020-03-17T11:53:00.000Z
Description 中文 English Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. Have you met this question in a real interview? Example Example1 Input: intervals = [(0,30),(5,10),(15,20)] Output: 2 Explanation: We need two meeting rooms room1: (0,30) room2: (5,10),(15,20) Example2 Input: intervals = [(2,7)] Output: 1 Explanation: Only need one meeting room /** * Definition of Interval: * classs Interval { * int start, end; * Interval(int start, int end) { * this->start = start; * this->end = end; * } * } */ class Solution { public: /** * @param intervals: an array of meeting time intervals * @return: the minimum number of conference rooms required */ static bool comp(Interval& lhs, Interval& rhs){ return lhs.start < rhs.start; } int minMeetingRooms(vector<Interval> &intervals) { // Write your code here sort(intervals.begin(), intervals.end(), comp); int n = intervals.size(); if(n == 0) return 0; priority_queue<int, vector<int>, greater<int>> pq; int mx = 0; for(int i = 0; i < n; i++){ if(pq.empty()){ pq.push(intervals[i].end); }else if(intervals[i].start > pq.top()){ // re-use the room pq.pop(); pq.push(intervals[i].end); }else{ pq.push(intervals[i].end); } mx = max(mx, int(pq.size())); } return mx; } };
24.071429
161
0.539466
[ "vector" ]
34bed3fb8bf7c392085fd6c7a827e91facc2ee6e
538
cpp
C++
ProceduralGeneration/IndexBuffer.cpp
cristi191096/ProceduralGeneration
912b738ced73d676f9d0885d917a94c710857396
[ "Apache-2.0" ]
null
null
null
ProceduralGeneration/IndexBuffer.cpp
cristi191096/ProceduralGeneration
912b738ced73d676f9d0885d917a94c710857396
[ "Apache-2.0" ]
null
null
null
ProceduralGeneration/IndexBuffer.cpp
cristi191096/ProceduralGeneration
912b738ced73d676f9d0885d917a94c710857396
[ "Apache-2.0" ]
null
null
null
#include "IndexBuffer.h" IndexBuffer::IndexBuffer(const std::vector<unsigned int>& data, unsigned int count) : count(count) { glGenBuffers(1, &bufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(GLuint), data.data(), GL_STATIC_DRAW); } IndexBuffer::~IndexBuffer() { glDeleteBuffers(1, &bufferID); } void IndexBuffer::Bind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferID); } void IndexBuffer::Unbind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
19.214286
92
0.760223
[ "vector" ]
34c01d5748c84177c082e00cfbda63ef48fc134d
505
cpp
C++
External/inheritance.cpp
lymven-io/OOP
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
[ "MIT" ]
null
null
null
External/inheritance.cpp
lymven-io/OOP
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
[ "MIT" ]
null
null
null
External/inheritance.cpp
lymven-io/OOP
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
[ "MIT" ]
null
null
null
#include <iostream> // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derive Class class Rectangle : public Shape{ public: int getArea() { return (width * height); } }; int main() { Rectangle Rect; // Set value Rect.setHeight(10); Rect.setWidth(7); std::cout << "Area : " << Rect.getArea() << std::endl; return 0; }
14.428571
58
0.540594
[ "shape" ]
34ca8c6d9ad7fda15959ff4b4760cdf854eefe36
1,014
cpp
C++
USACO/1-5NumberTriangles.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
USACO/1-5NumberTriangles.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
USACO/1-5NumberTriangles.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
/* ID: zhanghu14 PROG: numtri LANG: C++11 */ #include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <unordered_set> #include <algorithm> #include <set> using namespace std; //#define STDIO #ifdef STDIO #define IN cin #define OUT cout #else #define IN fin #define OUT fout #endif int main() { const string path = "numtri"; ifstream fin(path+".in"); ofstream fout(path+".out"); int n; while (IN>>n) { vector<vector<int>> arr; for (int i=0;i<n;++i) { vector<int> vec(i+1); if (i>0) { for (int j=0;j<=i;++j) { IN>>vec[j]; if (j==0) { vec[j] += arr[i-1][j]; } else if (j==i) { vec[j] += arr[i-1][j-1]; } else { vec[j] += max(arr[i-1][j-1],arr[i-1][j]); } } arr.push_back(vec); } else { IN>>vec[0]; arr.push_back(vec); } } int result = 0; for (int i=0;i<n;++i) { result = max(arr[n-1][i],result); } OUT<<result<<endl; } }
13.890411
47
0.518738
[ "vector" ]
34cc62d7daa44c8036a8e95e16afd98ebac8be13
7,764
cpp
C++
load_balancer/enc/balancer.cpp
ucbrise/snoopy
da4c98e3876c10cf52aa51ece3b62c5e8b8e335a
[ "Apache-2.0" ]
9
2021-11-10T20:34:00.000Z
2022-03-23T02:30:29.000Z
load_balancer/enc/balancer.cpp
ucbrise/snoopy
da4c98e3876c10cf52aa51ece3b62c5e8b8e335a
[ "Apache-2.0" ]
null
null
null
load_balancer/enc/balancer.cpp
ucbrise/snoopy
da4c98e3876c10cf52aa51ece3b62c5e8b8e335a
[ "Apache-2.0" ]
4
2021-09-30T05:12:06.000Z
2022-03-18T03:05:21.000Z
#include "balancer.h" //#include <openenclave/enclave.h> #include <openssl/evp.h> #include <stdlib.h> #include <string.h> #include <vector> #include <map> #include "../../common/obl_primitives.h" #include "../../common/par_obl_primitives.h" #include "../../common/crypto.h" using namespace std; LoadBalancer::LoadBalancer(size_t n, size_t num_blocks, int num_threads) : num_threads(num_threads) { num_suborams = n; suboram_key = EVP_CIPHER_CTX_new(); unsigned char *key_bytes = (unsigned char *) "0123456789123456"; EVP_EncryptInit_ex(suboram_key, EVP_aes_128_ecb(), NULL, key_bytes, NULL); EVP_CIPHER_CTX_set_padding(suboram_key, 0); client_comm_key.push_back((unsigned char *)"01234567891234567891234567891234"); for (int i = 0; i < num_suborams; i++) { suboram_replay_ctr_in.push_back(0); suboram_replay_ctr_out.push_back(1); suboram_comm_key.push_back((unsigned char *)"01234567891234567891234567891234"); } for (uint32_t i = 1; i < num_blocks; i++) { SubOramID sid = get_suboram_for_req(suboram_key, i, num_suborams); suboram_key_map[sid % num_suborams].emplace(i); } } void Batch::add_incoming_request(KeyBlockPairBucketItem req) { incoming_reqs.push_back(req); } void Batch::add_suboram_response(KeyBlockPairBucketItem resp) { suboram_responses.push_back(resp); } void LoadBalancer::create_outgoing_batch(Batch &b) { /* Assign each request to a subORAM. */ for (int i = 0; i < b.incoming_reqs.size(); i++) { uint32_t tag = !ObliviousEqual(b.incoming_reqs[i].item.block, static_cast<uint8_t *>(nullptr)); AssignedRequestBucketItem assigned_req(i, b.incoming_reqs[i].item, get_suboram_for_req(suboram_key, b.incoming_reqs[i].item.key, num_suborams), tag); b.outgoing_reqs.push_back(assigned_req); } int index = b.incoming_reqs.size(); /* Add max number of dummy reqs for each subORAM. */ for (uint32_t i = 0; i < num_suborams; i++) { SubOramID SID = (SubOramID) i; set<uint32_t>::iterator it = suboram_key_map[SID].begin(); int j = 0; while (it != suboram_key_map[SID].end() && j < b.reqs_per_suboram) { AssignedRequestBucketItem req(index, SID, 0xff); req.item.req.key = *it; memset(req.item.req.block, 0, BLOCK_LEN); b.outgoing_reqs.push_back(req); j++; it++; index++; // need to prepopulate this thing } } /* Oblivious sort. */ //ObliviousSort(b.outgoing_reqs.begin(), b.outgoing_reqs.end(), AssignedRequestBucketItemSorter()); state.curr_batch = &b; notify_workers(WorkerFn::create_outgoing_batch); ObliviousSortParallel(b.outgoing_reqs.begin(), b.outgoing_reqs.end(), AssignedRequestBucketItemSorter(), num_threads, 0); wait_for_workers(); /* Tag first padded_reqs_per_suboram reqs for each subORAM. */ uint32_t prev_SID = -1; // no match uint32_t count = 0; uint8_t zero_u8 = 0; uint32_t zero_u32 = 0; uint8_t one_u8 = 1; uint32_t one_u32 = 1; uint32_t prev_key = 0xff; uint8_t *tags = (uint8_t *)malloc(b.outgoing_reqs.size()); for (uint32_t i = 0; i < b.outgoing_reqs.size(); i++) { bool match = ObliviousEqual(prev_SID, b.outgoing_reqs[i].item.SID); uint32_t next_count = count + 1; bool can_assign = ObliviousLess(count, b.reqs_per_suboram) && !ObliviousEqual(prev_key, b.outgoing_reqs[i].item.req.key); tags[i] = ObliviousChoose(can_assign, one_u8, zero_u8); prev_SID = b.outgoing_reqs[i].item.SID; count = ObliviousChoose(match, next_count, zero_u32); prev_key = b.outgoing_reqs[i].item.req.key; } /* Oblivious compaction and truncate. */ ObliviousCompact(b.outgoing_reqs.begin(), b.outgoing_reqs.end(), tags); b.outgoing_reqs.resize(b.reqs_per_suboram * num_suborams); free(tags); } void LoadBalancer::match_responses_to_clients(Batch &b) { /* Merge requests and responses. */ b.client_responses.reserve(b.suboram_responses.size() + b.incoming_reqs.size()); b.client_responses.insert(b.client_responses.end(), b.suboram_responses.begin(), b.suboram_responses.end()); b.client_responses.insert(b.client_responses.end(), b.incoming_reqs.begin(), b.incoming_reqs.end()); /* Sort by (key, isResp) */ //ObliviousSort(b.client_responses.begin(), b.client_responses.end(), KeyBlockPairBucketItemSorter()); notify_workers(WorkerFn::match_responses_to_clients); ObliviousSortParallel(b.client_responses.begin(), b.client_responses.end(), KeyBlockPairBucketItemSorter(), num_threads, 0); wait_for_workers(); /* Iterate through and propagate value of block from responses to subsequent requests in list. */ uint8_t *tags = (uint8_t *)malloc(b.client_responses.size()); uint8_t zero_u8 = 0; uint8_t one_u8 = 1; uint8_t curr_block[BLOCK_LEN]; for (int i = 0; i < b.client_responses.size(); i++) { /* Set tag to 0 if isResp so can compact away later. */ bool isResp = ObliviousEqual(b.client_responses[i].item.isResp, one_u8); tags[i] = ObliviousChoose(isResp, zero_u8, one_u8); /* If isResp, update current block. Otherwise, copy current block. */ for (int j = 0; j < BLOCK_LEN; j++) { curr_block[j] = ObliviousChoose(isResp, b.client_responses[i].item.block[j], curr_block[j]); b.client_responses[i].item.block[j] = ObliviousChoose(!isResp, curr_block[j], b.client_responses[i].item.block[j]); } } /* Compact out responses. */ ObliviousCompact(b.client_responses.begin(), b.client_responses.end(), tags); b.client_responses.resize(b.incoming_reqs.size()); free(tags); } void LoadBalancer::worker_loop(int thread_id) { int next_iter = 1; while (true) { std::unique_lock<std::mutex> lk(m); cv.wait(lk, [&, this, next_iter, thread_id] { bool ready = state.curr_iter == next_iter; /* if (ready) { printf("[t%d] got job\n", thread_id); } else { printf("[t%d] waiting for job\n", thread_id); } */ return ready; }); lk.unlock(); if (state.fn == WorkerFn::create_outgoing_batch) { ObliviousSortParallel(state.curr_batch->outgoing_reqs.begin(), state.curr_batch->outgoing_reqs.end(), AssignedRequestBucketItemSorter(), num_threads, thread_id); } else if (state.fn == WorkerFn::match_responses_to_clients) { ObliviousSortParallel(state.curr_batch->client_responses.begin(), state.curr_batch->client_responses.end(), KeyBlockPairBucketItemSorter(), num_threads, thread_id); } else if (state.fn == WorkerFn::stop) { return; } next_iter++; lk.lock(); if (++state.n_done == num_threads) { lk.unlock(); cv.notify_all(); } } } void LoadBalancer::notify_workers(WorkerFn fn) { { std::lock_guard<std::mutex> lk(m); state.fn = fn; state.curr_iter++; state.n_done = 1; } cv.notify_all(); } void LoadBalancer::wait_for_workers() { { std::unique_lock<std::mutex> lk(m); cv.wait(lk, [&, this] { bool done = state.n_done == num_threads; /* if (done) { printf("all threads done\n"); } else { printf("waiting for threads to finish, done: %d\n", state.n_done); } */ return done; }); } } void LoadBalancer::stop_workers() { notify_workers(WorkerFn::stop); } // TODO: cleanup and setup for next batch
38.246305
176
0.641808
[ "vector" ]
34ced89c3ef37eb25cab0dc77bd6e0415a74536f
22,942
cpp
C++
chest/windows/core/src/main/cpp/general/NTService.cpp
lgoldstein/communitychest
5d4f4b58324cd9dbd07223e2ea68ff738bd32459
[ "Apache-2.0" ]
1
2020-08-12T07:40:11.000Z
2020-08-12T07:40:11.000Z
chest/windows/core/src/main/cpp/general/NTService.cpp
lgoldstein/communitychest
5d4f4b58324cd9dbd07223e2ea68ff738bd32459
[ "Apache-2.0" ]
null
null
null
chest/windows/core/src/main/cpp/general/NTService.cpp
lgoldstein/communitychest
5d4f4b58324cd9dbd07223e2ea68ff738bd32459
[ "Apache-2.0" ]
null
null
null
/*---------------------------------------------------------------------------*/ #ifndef __cplusplus #error "This file requires a C++ compiler !!!" #endif // NTService.cpp // // Implementation of CNTService /*---------------------------------------------------------------------------*/ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <util/string.h> #include <win32/NTService.h> /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::Close () { if (NULL == m_hSCM) return S_OK; HRESULT hr=S_OK; if (!::CloseServiceHandle(m_hSCM)) { hr = ::GetLastError(); if (S_OK == hr) hr = ERROR_INVALID_HANDLE; } m_hSCM = NULL; return hr; } /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::Attach (SC_HANDLE hScm) { if (m_hSCM != NULL) return ERROR_ALREADY_EXISTS; if (NULL == (m_hSCM=hScm)) return ERROR_INVALID_HANDLE; return S_OK; } /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::Open (LPCTSTR lpMachineName, // pointer to machine name string LPCTSTR lpDatabaseName, // pointer to database name string const DWORD dwDesiredAccess) // type of access { if (m_hSCM != NULL) return ERROR_ALREADY_INITIALIZED; if (NULL == (m_hSCM=::OpenSCManager(lpMachineName, lpDatabaseName, dwDesiredAccess))) { HRESULT hr=::GetLastError(); return (S_OK == hr) ? ERROR_INVALID_HANDLE : hr; } return S_OK; } /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::OpenService (LPCTSTR lpServiceName, // pointer to name of service to start const DWORD dwDesiredAccess, // type of access to service SC_HANDLE& hSvc) const { hSvc = NULL; if (NULL == m_hSCM) return ERROR_INVALID_HANDLE; if (NULL == (hSvc=::OpenService(m_hSCM, lpServiceName, dwDesiredAccess))) { HRESULT hr=::GetLastError(); return (S_OK == hr) ? ERROR_INVALID_HANDLE : hr; } return S_OK; } /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::CreateService (LPCTSTR lpServiceName, // name of service to start LPCTSTR lpDisplayName, // display name const DWORD dwDesiredAccess, // type of access to service const DWORD dwServiceType, // type of service const DWORD dwStartType, // when to start service const DWORD dwErrorControl, // severity of service failure LPCTSTR lpBinaryPathName, // name of binary file LPCTSTR lpLoadOrderGroup, // name of load ordering group LPDWORD lpdwTagId, // receives tag identifier LPCTSTR lpDependencies, // array of dependency names LPCTSTR lpServiceStartName, // service account name LPCTSTR lpPassword, // account password SC_HANDLE& hSVC) const { hSVC = NULL; if (NULL == m_hSCM) return ERROR_INVALID_HANDLE; if (IsEmptyStr(lpServiceName)) return ERROR_SOURCE_ELEMENT_EMPTY; if (IsEmptyStr(lpBinaryPathName)) return ERROR_ILLEGAL_ELEMENT_ADDRESS; if (NULL == (hSVC=::CreateService(m_hSCM, lpServiceName, lpDisplayName, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, lpServiceStartName, lpPassword))) { HRESULT hr=::GetLastError(); return (S_OK == hr) ? ERROR_INVALID_HANDLE : hr; } return S_OK; } /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::HandleService (LPCTSTR lpszSrvcName, const BOOL fStart) { if (IsEmptyStr(lpszSrvcName)) return ERROR_BAD_ARGUMENTS; LPCTSTR lpszSrvcs[]={ lpszSrvcName, NULL }; DWORD dwSrvcsNum=0; HRESULT hr=HandleServices(lpszSrvcs, fStart, dwSrvcsNum); if (hr != S_OK) return hr; if (dwSrvcsNum != 1) return ERROR_ARENA_TRASHED; return S_OK; } /*---------------------------------------------------------------------------*/ HRESULT CServicesManager::DeleteService (LPCTSTR lpszSrvcName) const { if (IsEmptyStr(lpszSrvcName)) return ERROR_SOURCE_ELEMENT_EMPTY; if (NULL == m_hSCM) return ERROR_INVALID_HANDLE; SC_HANDLE hService=NULL; HRESULT hr=OpenService(lpszSrvcName, DELETE, hService); if (hr != S_OK) return hr; if (!::DeleteService(hService)) { hr = ::GetLastError(); if (S_OK == hr) hr =ERROR_INVALID_HANDLE; } ::CloseServiceHandle(hService); return hr; } /*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*/ class CSvcStatusArg { private: const LPCTSTR m_lpszSvcName; SERVICE_STATUS& m_svcStatus; HRESULT m_hr; HRESULT CheckStatus (const ENUM_SERVICE_STATUS& eSvcStatus); public: CSvcStatusArg (LPCTSTR lpszSvcName, SERVICE_STATUS& svcStatus) : m_lpszSvcName(GetSafeStrPtr(lpszSvcName)) , m_svcStatus(svcStatus) , m_hr(ERROR_SECTOR_NOT_FOUND) { } static BOOL svcsEcfn (SC_HANDLE hSCM, const LPENUM_SERVICE_STATUS pSvcEnumStatus, LPVOID pArg) { if ((pArg != NULL) && (pSvcEnumStatus != NULL)) return (((CSvcStatusArg *) pArg)->CheckStatus(*pSvcEnumStatus) != S_OK); return TRUE; } HRESULT VerifyStatus () const { return m_hr; } }; /*---------------------------------------------------------------------------*/ HRESULT CSvcStatusArg::CheckStatus (const ENUM_SERVICE_STATUS& eSvcStatus) { if (S_OK == m_hr) // make sure not called more than once m_hr = ERROR_ALREADY_EXISTS; if (m_hr != ERROR_SECTOR_NOT_FOUND) return m_hr; if ((eSvcStatus.lpServiceName != NULL) && (0 == ::_tcsicmp(eSvcStatus.lpServiceName, m_lpszSvcName))) { m_svcStatus = eSvcStatus.ServiceStatus; m_hr = S_OK; } return m_hr; } /*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*/ HRESULT CServicesManager::GetServiceStatus (LPCTSTR lpszSvcName, SERVICE_STATUS& svcStatus) const { ::memset(&svcStatus, 0, (sizeof svcStatus)); if (IsEmptyStr(lpszSvcName)) return ERROR_SOURCE_ELEMENT_EMPTY; CSvcStatusArg ssa(lpszSvcName, svcStatus); HRESULT hr=EnumServices(SERVICE_WIN32, SERVICE_ACTIVE, CSvcStatusArg::svcsEcfn, (LPVOID) &ssa); if (hr != S_OK) return hr; if ((hr=ssa.VerifyStatus()) != S_OK) return hr; return S_OK; } ////////////////////////////////////////////////////////////////////////////// CNTService *CNTService::m_pThis=NULL; CNTService::CNTService (const ULONG ulMajorVersion, const ULONG ulMinorVersion) : m_ulMajorVersion(ulMajorVersion), m_ulMinorVersion(ulMinorVersion), m_hServiceStatus(NULL), m_bIsRunning(FALSE) { memset(m_szServiceName, 0, (sizeof m_szServiceName)); memset(m_szServiceDisplayName, 0, (sizeof m_szServiceDisplayName)); memset(&m_Status, 0, (sizeof m_Status)); m_Status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; m_Status.dwCurrentState = SERVICE_STOPPED; m_Status.dwControlsAccepted = SERVICE_ACCEPT_STOP; } /*---------------------------------------------------------------------------*/ HRESULT CNTService::Init (LPCTSTR lpszSrvcName, LPCTSTR lpszSrvcDispName) { if (IsEmptyStr(lpszSrvcName)) return ERROR_SOURCE_ELEMENT_EMPTY; if ((m_szServiceName[0] != _T('\0')) || (m_pThis != NULL)) return ERROR_ALREADY_INITIALIZED; if (_tcslen(lpszSrvcName) > MAX_SERVICE_NAME_LEN) return ERROR_BUFFER_OVERFLOW; _tcscpy(m_szServiceName, lpszSrvcName); if (!IsEmptyStr(lpszSrvcDispName)) { if (_tcslen(lpszSrvcDispName) > MAX_SERVICE_DISPLY_NAME_LEN) return ERROR_BUFFER_OVERFLOW; _tcscpy(m_szServiceDisplayName, lpszSrvcDispName); } else // don't have a display name - use service name { if (_tcslen(lpszSrvcName) > MAX_SERVICE_DISPLY_NAME_LEN) return ERROR_BUFFER_OVERFLOW; _tcscpy(m_szServiceDisplayName, lpszSrvcName); } m_pThis = this; return S_OK; } /*---------------------------------------------------------------------------*/ CNTService::~CNTService() { m_pThis = NULL; } /*---------------------------------------------------------------------------*/ // Test if the service is currently installed BOOL CNTService::IsInstalled (void) const { CServicesManager scm; HRESULT hr=scm.Open(); if (hr != S_OK) return FALSE; // Try to open the service SC_HANDLE hService=NULL; if ((hr=scm.OpenService(m_szServiceName, SERVICE_QUERY_CONFIG, hService)) != S_OK) return FALSE; ::CloseServiceHandle(hService); return TRUE; } /*---------------------------------------------------------------------------*/ // Install the service HRESULT CNTService::Install (const BOOL fAutoStart) { CServicesManager scm; HRESULT hr=scm.Open(); if (hr != S_OK) return hr; // Get the executable file path TCHAR szFilePath[MAX_PATH+2]=_T(""); DWORD dwFLen=::GetModuleFileName(NULL, szFilePath, MAX_PATH); if ((0 == dwFLen) || (dwFLen >= MAX_PATH)) { hr = GetLastError(); return ((S_OK == hr) ? ERROR_MAGAZINE_NOT_PRESENT : hr); } // Create the service SC_HANDLE hService=NULL; if ((hr=scm.CreateSimpleService(m_szServiceName, m_szServiceDisplayName, szFilePath, fAutoStart, hService)) != S_OK) return hr; ::CloseServiceHandle(hService); return S_OK; } /*---------------------------------------------------------------------------*/ HRESULT CNTService::Uninstall (void) { CServicesManager scm; HRESULT hr=scm.Open(); if (hr != S_OK) return hr; if ((hr=scm.DeleteService(m_szServiceName)) != S_OK) return hr; return S_OK; } /*---------------------------------------------------------------------------*/ // Control request handlers // static member function (callback) to handle commands from the // service control manager void CNTService::Handler (DWORD dwOpcode) { // Get a pointer to the object CNTService *pService=m_pThis; if (NULL == pService) return; CNTService& svc=(*pService); switch (dwOpcode) { case SERVICE_CONTROL_STOP: // 1 svc.SetStatus(SERVICE_STOP_PENDING); svc.OnStop(); svc.SetRunningState(FALSE); break; case SERVICE_CONTROL_PAUSE: // 2 svc.OnPause(); break; case SERVICE_CONTROL_CONTINUE: // 3 svc.OnContinue(); break; case SERVICE_CONTROL_INTERROGATE: // 4 svc.OnInterrogate(); break; case SERVICE_CONTROL_SHUTDOWN: // 5 svc.OnShutdown(); break; default: if (dwOpcode >= SERVICE_CONTROL_USER) { HRESULT hr=svc.OnUserControl(dwOpcode); } } // Report current status SERVICE_STATUS& st=svc.GetStatus(); ::SetServiceStatus(svc.GetStatusHandle(), &st); } /*---------------------------------------------------------------------------*/ // static member function (callback) void WINAPI CNTService::ServiceMain (const DWORD dwArgc, LPTSTR *lpszArgv) { CNTService *pService=m_pThis; if (NULL == pService) return; CNTService& svc=(*pService); SERVICE_STATUS_HANDLE hStatus=RegisterServiceCtrlHandler(svc.GetName(), CNTService::Handler); if (NULL == hStatus) return; svc.SetStatusHandle(hStatus); SERVICE_STATUS& st=svc.GetStatus(); st.dwServiceType = SERVICE_WIN32_OWN_PROCESS; st.dwServiceSpecificExitCode = S_OK; // Start the initialization HRESULT hr=svc.Initialize(); if (S_OK == hr) { // Do the real work - when the Run function returns, the service has stopped. st.dwWin32ExitCode = S_OK; st.dwCheckPoint = 0; st.dwWaitHint = 0; svc.SetStatus(SERVICE_RUNNING); svc.SetRunningState(TRUE); hr = svc.Run(); } // Tell the service manager we are stopped svc.SetStatus(SERVICE_STOPPED); } /*---------------------------------------------------------------------------*/ // status functions HRESULT CNTService::SetStatus (const DWORD dwState, const DWORD dwErr, const DWORD dwHintWait) { if (NULL == m_hServiceStatus) return ERROR_INVALID_HANDLE; m_Status.dwCurrentState = dwState; m_Status.dwWaitHint = dwHintWait; ::SetServiceStatus(m_hServiceStatus, &m_Status); return S_OK; } /*---------------------------------------------------------------------------*/ // Service startup and registration HRESULT CNTService::StartService (void) { SERVICE_TABLE_ENTRY st[]={ { m_szServiceName, CNTService::ServiceMain }, { NULL, NULL } }; if (_T('\0') == m_szServiceName[0]) return ERROR_NO_TRACKING_SERVICE; if (m_pThis != this) return ERROR_NO_MATCH; if (!::StartServiceCtrlDispatcher(st)) { HRESULT hr=GetLastError(); return hr; } return S_OK; } /*---------------------------------------------------------------------------*/ // Service initialization HRESULT CNTService::Initialize (void) { SetStatus(SERVICE_START_PENDING); // Perform the actual initialization HRESULT hr=OnInit(); // Set final state m_Status.dwWin32ExitCode = hr; m_Status.dwCheckPoint = 0; m_Status.dwWaitHint = 0; if (hr != S_OK) { SetStatus(SERVICE_STOPPED); return hr; } return S_OK; } ////////////////////////////////////////////////////////////////////////////// /* Enumerates available services according to supplied options: * * eSvcType - type of services to enumerate * eSvcState - state of services to enumerate * * Note: see "EnumServicesStatus" for available values. */ HRESULT EnumSCMServices (SC_HANDLE hSCM, const DWORD eSvcType, const DWORD eSvcState, HSRVCS_ENUM_CFN lpfnEcfn, LPVOID pArg) { static const DWORD MIN_SRVC_STBUF_SIZE=(MAX_SERVICE_NAME_LEN+MAX_PATH+2+sizeof(ENUM_SERVICE_STATUS)+sizeof(ENUM_SERVICE_STATUS_PROCESS)); if ((NULL == hSCM) | (NULL == lpfnEcfn)) return ERROR_BAD_ARGUMENTS; for (DWORD dwSdx=0, dwRH=0; ; dwSdx++) { BYTE buf[MIN_SRVC_STBUF_SIZE]={ 0 }; DWORD cbNeeded=0, dwSrvcNum=0; LPENUM_SERVICE_STATUS pe=(LPENUM_SERVICE_STATUS) buf; BOOL fSuccess=EnumServicesStatus(hSCM, // handle to service control manager database eSvcType, // type of services to enumerate eSvcState, // state of services to enumerate pe, // status buffer (sizeof buf), // size of available buffer &cbNeeded, &dwSrvcNum, // num of returned status(es) &dwRH); // management handle HRESULT hr=GetLastError(); if ((ERROR_MORE_DATA == hr) || (ERROR_IO_PENDING == hr)) { hr = ERROR_SUCCESS; if (!fSuccess) fSuccess = TRUE; } if ((!fSuccess) || (hr != ERROR_SUCCESS)) return hr; for (DWORD i=0; i < dwSrvcNum; i++, pe++) if (!(*lpfnEcfn)(hSCM, pe, pArg)) return ERROR_SUCCESS; if (0 == dwRH) break; } return ERROR_SUCCESS; } /*---------------------------------------------------------------------------*/ /* Enumerate services on specified host - if NULL or empty then local host */ HRESULT EnumHostServices (LPCTSTR lpszHostName, const DWORD eSvcType, const DWORD eSvcState, HSRVCS_ENUM_CFN lpfnEcfn, LPVOID pArg) { HRESULT hr=ERROR_SUCCESS; SC_HANDLE hSCM=NULL; if (NULL == lpfnEcfn) return ERROR_BAD_ARGUMENTS; hSCM = OpenSCManager(lpszHostName, NULL, SC_MANAGER_ENUMERATE_SERVICE); if (NULL == hSCM) { hr = GetLastError(); return hr; } hr = EnumSCMServices(hSCM, eSvcType, eSvcState, lpfnEcfn, pArg); CloseServiceHandle(hSCM); return hr; } /*---------------------------------------------------------------------------*/ static HRESULT ControlSCMServices (SC_HANDLE hSCM, const DWORD dwCtrl, LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { DWORD dwDummy=0; DWORD& dwCount=((NULL == pdwSrvcsNum) ? dwDummy : *pdwSrvcsNum); if (NULL == hSCM) return ERROR_BAD_ARGUMENTS; dwCount = 0; if (NULL == lpszSrvcs) return ERROR_SUCCESS; for (DWORD idx=0; lpszSrvcs[idx] != NULL; idx++, dwCount++) { LPCTSTR lpszSrvcName=lpszSrvcs[idx]; if (IsEmptyStr(lpszSrvcName)) break; SC_HANDLE hSrvc=NULL; CServiceHandleGuard svg(hSrvc); switch(dwCtrl) { case SERVICE_CONTROL_START : hSrvc = OpenService(hSCM, lpszSrvcName, SERVICE_START); break; case SERVICE_CONTROL_STOP : hSrvc = OpenService(hSCM, lpszSrvcName, SERVICE_STOP); break; default : return ERROR_BAD_ARGUMENTS; } if (NULL == hSrvc) return GetLastError(); SERVICE_STATUS st={ 0 }; BOOL fSuccess=FALSE; switch(dwCtrl) { case SERVICE_CONTROL_START : fSuccess = StartService(hSrvc, 0, NULL); break; case SERVICE_CONTROL_STOP : fSuccess = ControlService(hSrvc, SERVICE_CONTROL_STOP, &st); break; default : return ERROR_BAD_ARGUMENTS; } if (!fSuccess) return GetLastError(); HRESULT hr=svg.Release(); if (hr != ERROR_SUCCESS) return hr; } return ERROR_SUCCESS; } /*---------------------------------------------------------------------------*/ /* Start/Stop the specified service(s) (without any arguments !!!). * * hSCM - handle to the services manager * * lpszSrvcs - a NULL terminated list of service names (!) to be started * * pdwSrvcsNum - if non-NULL contains upon return the number of started * services. Since the routine stops the at the 1st service which fails * to start, this parameter will hold the index of the failed service * in this case. */ HRESULT StartSCMServices (SC_HANDLE hSCM, LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { return ControlSCMServices(hSCM, SERVICE_CONTROL_START, lpszSrvcs, pdwSrvcsNum); } HRESULT StopSCMServices (SC_HANDLE hSCM, LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { return ControlSCMServices(hSCM, SERVICE_CONTROL_STOP, lpszSrvcs, pdwSrvcsNum); } /*---------------------------------------------------------------------------*/ static HRESULT ControlHostServices (LPCTSTR lpszHostName, /* NULL == local */ const DWORD dwCtrl, LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { HRESULT hr=ERROR_SUCCESS; SC_HANDLE hSCM=NULL; hSCM = OpenSCManager(lpszHostName, NULL, SC_MANAGER_ALL_ACCESS); if (NULL == hSCM) { hr = GetLastError(); return hr; } hr = ControlSCMServices(hSCM, dwCtrl, lpszSrvcs, pdwSrvcsNum); CloseServiceHandle(hSCM); return hr; } /*---------------------------------------------------------------------------*/ HRESULT StartHostServices (LPCTSTR lpszHostName, /* NULL == localhost */ LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { return ControlHostServices(lpszHostName, SERVICE_CONTROL_START, lpszSrvcs, pdwSrvcsNum); } HRESULT StopHostServices (LPCTSTR lpszHostName, /* NULL == localhost */ LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { return ControlHostServices(lpszHostName, SERVICE_CONTROL_STOP, lpszSrvcs, pdwSrvcsNum); } /*---------------------------------------------------------------------------*/ HRESULT RestartSCMServices (SC_HANDLE hSCM, const BOOL fReverseStart, LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { HRESULT hr=ERROR_SUCCESS; DWORD dwDummy=0, idx=0, dwNum=0; LPDWORD pdwCount=((NULL == pdwSrvcsNum) ? &dwDummy : pdwSrvcsNum); if ((hr=StopSCMServices(hSCM, lpszSrvcs, pdwCount)) != ERROR_SUCCESS) return hr; if (!fReverseStart) return StartSCMServices(hSCM, lpszSrvcs, pdwCount); /* at this point, since we were successful, "pdwCount" holds number of services */ for (idx=(*pdwCount), *pdwCount=0; idx > 0; idx--, (*pdwCount)++) { LPCTSTR lpszSrvcName=lpszSrvcs[idx-1], lpszDummy[2]={ lpszSrvcName, NULL }; DWORD dwStam=0; if ((hr=StartSCMServices(hSCM, lpszDummy, &dwStam)) != ERROR_SUCCESS) return hr; } return ERROR_SUCCESS; } /*---------------------------------------------------------------------------*/ HRESULT RestartHostServices (LPCTSTR lpszHostName, /* NULL == local */ const BOOL fReverseStart, LPCTSTR lpszSrvcs[], /* may be NULL */ LPDWORD pdwSrvcsNum) /* out - may be NULL */ { HRESULT hr=ERROR_SUCCESS; SC_HANDLE hSCM=NULL; hSCM = OpenSCManager(lpszHostName, NULL, SC_MANAGER_ALL_ACCESS); if (NULL == hSCM) { hr = GetLastError(); return hr; } hr = RestartSCMServices(hSCM, fReverseStart, lpszSrvcs, pdwSrvcsNum); CloseServiceHandle(hSCM); return hr; } /*---------------------------------------------------------------------------*/ typedef struct { HRESULT hr; HSRVCS_ENUM_CFN lpfnEcfn; LPVOID pArg; } XCGSRVCS; /* Callback used when enumerating services - if returns FALSE then * enumeration is aborted. */ static BOOL xcg_srvcs_cfn (SC_HANDLE hSCM, const LPENUM_SERVICE_STATUS pSvcEnumStatus, LPVOID pArg) { static LPCTSTR lpszMSExchangeSvcPrefix=_T("MSExchange"); HRESULT hr=ERROR_SUCCESS; XCGSRVCS *pSrvcs=(XCGSRVCS *) pArg; HSRVCS_ENUM_CFN lpfnEcfn=NULL; BOOL fRetVal=FALSE; if ((NULL == hSCM) || (NULL == pSvcEnumStatus) || (NULL == pArg)) { hr = ERROR_BAD_ENVIRONMENT; goto Quit; } if (NULL == (lpfnEcfn=pSrvcs->lpfnEcfn)) { hr = ERROR_INVALID_FUNCTION; goto Quit; } if (_tcsstr(pSvcEnumStatus->lpServiceName, lpszMSExchangeSvcPrefix) != NULL) fRetVal = (*lpfnEcfn)(hSCM, pSvcEnumStatus, pSrvcs->pArg); else fRetVal = TRUE; Quit: if ((hr != ERROR_SUCCESS) && (pSrvcs != NULL)) pSrvcs->hr = hr; return fRetVal; } /*---------------------------------------------------------------------------*/ HRESULT EnumXcgSCMServices (SC_HANDLE hSCM, const DWORD eSvcType, const DWORD eSvcState, HSRVCS_ENUM_CFN lpfnEcfn, LPVOID pArg) { HRESULT hr=ERROR_SUCCESS; XCGSRVCS xcgSrvcs={ ERROR_SUCCESS, lpfnEcfn, pArg }; if (NULL == lpfnEcfn) return ERROR_BAD_ARGUMENTS; hr = EnumSCMServices(hSCM, eSvcType, eSvcState, xcg_srvcs_cfn, (LPVOID) &xcgSrvcs); if (ERROR_SUCCESS == hr) hr = xcgSrvcs.hr; return hr; } /*---------------------------------------------------------------------------*/ HRESULT EnumXcgHostServices (LPCTSTR lpszHostName, const DWORD eSvcType, const DWORD eSvcState, HSRVCS_ENUM_CFN lpfnEcfn, LPVOID pArg) { HRESULT hr=ERROR_SUCCESS; SC_HANDLE hSCM=NULL; if (NULL == lpfnEcfn) return ERROR_BAD_ARGUMENTS; hSCM = OpenSCManager(lpszHostName, NULL, SC_MANAGER_ALL_ACCESS); if (NULL == hSCM) { hr = GetLastError(); return hr; } hr = EnumXcgSCMServices(hSCM, eSvcType, eSvcState, lpfnEcfn, pArg); CloseServiceHandle(hSCM); return hr; } /*---------------------------------------------------------------------------*/
26.040863
138
0.604481
[ "object" ]
34d16bc57ad2023565c6345bd14bdba6aebcf252
2,498
hpp
C++
board.hpp
miguelrodriguesdossantos/CellularAutomata
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
[ "MIT" ]
null
null
null
board.hpp
miguelrodriguesdossantos/CellularAutomata
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
[ "MIT" ]
null
null
null
board.hpp
miguelrodriguesdossantos/CellularAutomata
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
[ "MIT" ]
null
null
null
// board.hpp #ifndef BOARD_H #define BOARD_H #include <iostream> #include <vector> #include <string> #include <unordered_map> #include "global.hpp" #include "cell.hpp" class Board { public: /* These structs are here to increase the readability of the subsequent code calling this class. Example: - Constructor: Board B( Board::SizeV{10}, Board::SizeH{15} ) - isAlive: B.isAlive( Board::Row{10}, Board::Col{15} ) */ struct Row {size_t val;}; struct Col {size_t val;}; struct SizeV {size_t val;}; // Number of rows, size of the columns struct SizeH {size_t val;}; // Number of columns, size of the rows Board(SizeV, SizeH, std::string s = ConwaysLife_rulestring); Board(const Board&); ~Board(); bool isAlive(Row, Col) const; bool isStable() const; size_t stepsToStability(); size_t stabilityPeriod(); // Evaluates the number of steps in the stability period. void setRule(const std::string&); void setCellStatus(Row, Col, Cell::Status); void setAll(Cell::Status); void clearAll(); void setRandom(int); // Expects number of occupied cells. void insertShape(std::string file_name, Row row, Col col); void setBoundary(Cell::Status); void setNext(); void setStorage(bool on=true); //Assignment operator Board& operator=(Board); friend std::ostream& operator << (std::ostream&, const Board&); friend std::istream& operator >> (std::istream&, Board&); friend bool operator==(const Board&, const Board&); private: /* Two boards are created for optimization purposes. One of them is the "current" board, the other is the "next" board. This prevents having to copy the board at each iteration. std::vector<bool> is a specialization of std::vector that uses only one bit to represent each bool. */ std::vector<bool> board[2]; /* This unordered_map will store the hashes of each of the previous configurations of the board if _should_store == true */ std::unordered_map< std::size_t, size_t > hash_map; std::string rule; std::vector<int> survival; std::vector<int> birth; bool _isStable; bool _should_store; bool _index; // Used to determine which of the boards is currently active size_t sizeV; size_t sizeH; // Can only access the _next_ element from within // the implementation of the class. The public // implementation of setCellStatus only void setCellStatus(Row, Col, Cell::Status, bool next); void storeHash(); int countLivingNeighbours(Row, Col) const; }; #endif
24.98
85
0.705765
[ "vector" ]
34d3e271442d92dc6e4344b210de1f94878047c9
11,994
cpp
C++
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Device app for printers SDK sample (Windows 8)/C++/DeviceAppForPrinters/Preferences.xaml.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Device app for printers SDK sample (Windows 8)/C++/DeviceAppForPrinters/Preferences.xaml.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Device app for printers SDK sample (Windows 8)/C++/DeviceAppForPrinters/Preferences.xaml.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Preferences.xaml.cpp // Implementation of the Preferences class // #include "pch.h" #include "Preferences.xaml.h" using namespace DeviceAppForPrinters; using namespace Platform; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Devices::Printers::Extensions; Preferences::Preferences() { InitializeComponent(); // Get a copy of the dispatcher for later usage _dispatcher = Window::Current->Dispatcher; // Initialize feature list _features = ref new Platform::Collections::Vector<Platform::String^>; _features->Append("PageOrientation"); _features->Append("PageOutputColor"); _features->Append("PageMediaSize"); _features->Append("PageMediaType"); // Initialize _selection to unselected state (-1) _selections = ref new Platform::Collections::Vector<int>; _selections->Append(-1); _selections->Append(-1); _selections->Append(-1); _selections->Append(-1); _featureLabels = ref new Platform::Collections::Vector<TextBlock^>; _featureLabels->Append(PageOrientationLabel); _featureLabels->Append(PageOutputColorLabel); _featureLabels->Append(PageMediaSizeLabel); _featureLabels->Append(PageMediaTypeLabel); _featureBoxes = ref new Platform::Collections::Vector<ComboBox^>; _featureBoxes->Append(PageOrientationBox); _featureBoxes->Append(PageOutputColorBox); _featureBoxes->Append(PageMediaSizeBox); _featureBoxes->Append(PageMediaTypeBox); _featureConstraints = ref new Platform::Collections::Vector<TextBlock^>; _featureConstraints->Append(PageOrientationConstraint); _featureConstraints->Append(PageOutputColorConstraint); _featureConstraints->Append(PageMediaSizeConstraint); _featureConstraints->Append(PageMediaTypeConstraint); } void Preferences::Initialize() { rootPage->AddMessage("Initialize Preference"); Windows::Devices::Printers::Extensions::PrintTaskConfiguration^ configuration = rootPage->Configuration; DeviceAppForPrinters::PrintHelper^ printHelper = rootPage->PrintHelper; if ((configuration == nullptr) || (printHelper == nullptr)) { rootPage->AddMessage("PrintTaskConfiguration is nullptr"); return; } _saveRequestedToken = configuration->SaveRequested += ref new Windows::Foundation::TypedEventHandler<PrintTaskConfiguration^, PrintTaskConfigurationSaveRequestedEventArgs^>(this, &Preferences::OnSaveRequested); // Fill in the drop-down select controls for some common printing features. for (unsigned int i = 0; i < _features->Size; i++) { String^ feature = _features->GetAt(i); // Only show features that exists TextBlock^ featureName = _featureLabels->GetAt(i); ComboBox^ featureBox = _featureBoxes->GetAt(i); featureName->Visibility = Windows::UI::Xaml::Visibility::Collapsed; featureBox->Visibility = Windows::UI::Xaml::Visibility::Collapsed; // Check whether the currently selected printer's capabilities include this feature. if (!printHelper->FeatureExists(feature)) { rootPage->AddMessage(feature + ": feature does not exist"); continue; } // Fill in the labels so that they display the display name of each feature. featureName->Text = printHelper->GetFeatureDisplayName(feature); // Fill in the items for each feature featureBox->Items->Clear(); printHelper->GetOptionInfo(feature, featureBox); rootPage->AddMessage(feature + ": DisplayName is " + featureName->Text); // Everytime the selection for a feature changes, we update our local cached set of selections. featureBox->SelectionChanged += ref new Windows::UI::Xaml::Controls::SelectionChangedEventHandler(this, &Preferences::OnFeatureOptionsChanged); // Show existing features featureName->Visibility = Windows::UI::Xaml::Visibility::Visible; featureBox->Visibility = Windows::UI::Xaml::Visibility::Visible; // By default there is no constraint TextBlock^ block = _featureConstraints->GetAt(i); block->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } // Notify user on UI thread void Preferences::NotifyUser(Platform::String^ strMessage, NotifyType type) { _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, strMessage, type] () { rootPage->NotifyUser(strMessage, type); }, Window::Current->CallbackContext::Any)); } // Add debug message on UI thread void Preferences::AddMessage(Platform::String^ strMessage) { _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, strMessage] () { rootPage->AddMessage(strMessage); }, Window::Current->CallbackContext::Any)); } // Hide or show the settings void Preferences::AllowSettingsChange(bool bAllow) { _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, bAllow] () { if (bAllow) { Input->Visibility = Windows::UI::Xaml::Visibility::Visible; } else { Input->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } }, Window::Current->CallbackContext::Any)); } // Check if the selected option has constraint void Preferences::CheckConstraint(void) { _dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this] () { // Retrieve the existing print helper class PrintHelper^ printHelper = rootPage->PrintHelper; if (printHelper == nullptr) { rootPage->NotifyUser("CheckConstraint: printHelper cannot be null", NotifyType::ErrorMessage); } else { // Go through all the feature select elements and check their constraint for (unsigned int i = 0; i < _features->Size; i++) { ULONG index = _selections->GetAt(i); bool bResult = printHelper->IsOptionConstrained(_features->GetAt(i), index); AddMessage("Constraint: feature " + _features->GetAt(i) + " is " + bResult.ToString()); TextBlock^ block = _featureConstraints->GetAt(i); if (nullptr != block && bResult) { block->Visibility = Windows::UI::Xaml::Visibility::Visible; } } } }, Window::Current->CallbackContext::Any)); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Preferences::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; rootPage->AddMessage("Navigate to Preference"); Initialize(); } void Preferences::OnFeatureOptionsChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ args) { ComboBox^ featureBox = safe_cast<ComboBox^>(sender); for (unsigned int i = 0; i < _features->Size; i++) { // Find the feature associated with the selected combo box using name matching if (_features->GetAt(i) + "Box" == featureBox->Name) { ComboBoxItem^ item = safe_cast<ComboBoxItem^>(featureBox->SelectedItem); // Save the new setting // Validation is delayed to when user press BACK button to avoid multiple validations _selections->SetAt(i, featureBox->SelectedIndex); rootPage->AddMessage(featureBox->Name + " changed to " + featureBox->SelectedIndex); // Remove the constrint error TextBlock^ block = _featureConstraints->GetAt(i); block->Visibility = Windows::UI::Xaml::Visibility::Collapsed; break; } } } void Preferences::OnSaveRequested(Windows::Devices::Printers::Extensions::PrintTaskConfiguration^ sender, Windows::Devices::Printers::Extensions::PrintTaskConfigurationSaveRequestedEventArgs^ args) { NotifyUser("Saving print settings", NotifyType::WaitMessage); AllowSettingsChange(false); // Retrieve the existing print helper class PrintHelper^ printHelper = rootPage->PrintHelper; Object^ context = rootPage->PrinterExtensionContext; if (printHelper == nullptr || context == nullptr || args == nullptr) { NotifyUser("onSaveRequested: args, printHelper, and context cannot be null", NotifyType::ErrorMessage); return; } // Get the request object, which has the save method that allows saving updated print settings _request = args->Request; if (_request == nullptr) { NotifyUser("onSaveRequested: request cannot be null", NotifyType::ErrorMessage); return; } // Request for deferral to do asynchronous operation to save the ticket _deferral = _request->GetDeferral(); // Go through all the feature select elements, look up the selected option name, and update the context for (unsigned int i = 0; i < _features->Size; i++) { // Set the feature's selected option in the context's print ticket ULONG value = _selections->GetAt(i); if (value >= 0) { printHelper->SetFeatureOption(_features->GetAt(i), value); AddMessage("update feature " + _features->GetAt(i) + " to " + value.ToString()); } } try { // Save the print ticket through printer extension context AddMessage("Calling Save()..."); if (_request != nullptr) { // This save request will throw an exception if ticket validation fails. // When the exception is thrown, the app flyout will remain. // If you want the flyout to remain regardless of outcome, you can call // _request->Cancel(). This should be used sparingly, however, as it could // disrupt the entire the print flow and will force the user to // light dismiss to restart the entire experience. _request->Save(context); } AddMessage("Save() returned"); // Remove the SaveRequested event handler Windows::Devices::Printers::Extensions::PrintTaskConfiguration^ configuration = rootPage->Configuration; if (configuration != nullptr) { configuration->SaveRequested -= _saveRequestedToken; AddMessage("SaveRequested event removed"); } NotifyUser("Print settings saved", NotifyType::StatusMessage); } catch (Platform::Exception^ exception) { // Check the result to see if the exception is because of invalid print ticket if (exception->HResult == static_cast<int>(HRESULT_FROM_WIN32(ERROR_INVALID_DATA))) { NotifyUser("Failed to save the print ticket", NotifyType::ErrorMessage); CheckConstraint(); } else { NotifyUser(exception->Message, NotifyType::ErrorMessage); throw; } } // The operation is complete, we complete the deferral if (_deferral != nullptr) { _deferral->Complete(); } AllowSettingsChange(true); }
40.248322
197
0.664832
[ "object", "vector" ]
34d736baa5e33787b2198db6da374160d6de0c22
4,254
cpp
C++
app/src/main/cpp/player/FFMediaPlayer.cpp
qq326646683/wenshi_android
dc6fe95df39345766b13c67947b7b92d512c6269
[ "MIT" ]
19
2020-10-19T03:46:27.000Z
2021-08-17T12:59:32.000Z
app/src/main/cpp/player/FFMediaPlayer.cpp
qq326646683/wenshi_android
dc6fe95df39345766b13c67947b7b92d512c6269
[ "MIT" ]
1
2021-07-14T03:34:46.000Z
2021-07-14T03:34:46.000Z
app/src/main/cpp/player/FFMediaPlayer.cpp
qq326646683/wenshi_android
dc6fe95df39345766b13c67947b7b92d512c6269
[ "MIT" ]
2
2020-10-19T06:14:27.000Z
2021-07-15T07:55:05.000Z
#include <render/video/VideoGLRender.h> #include <render/audio/OpenSLRender.h> #include "FFMediaPlayer.h" void FFMediaPlayer::Init(JNIEnv *jniEnv, jobject obj, char *url, int videoRenderType, jobject surface) { jniEnv->GetJavaVM(&m_JavaVM); m_JavaObj = jniEnv->NewGlobalRef(obj); m_VideoDecoder = new VideoDecoder(url); m_AudioDecoder = new AudioDecoder(url); m_VideoDecoder->SetVideoRender(VideoGLRender::GetInstance()); m_AudioRender = new OpenSLRender(); m_AudioDecoder->SetAudioRender(m_AudioRender); m_VideoDecoder->SetMessageCallback(this, PostMessage); m_AudioDecoder->SetMessageCallback(this, PostMessage); //AVSync //m_VideoDecoder->SetAVSyncCallback(m_AudioDecoder, AudioDecoder::GetAudioDecoderTimestampForAVSync); } void FFMediaPlayer::UnInit() { LOGCATE("FFMediaPlayer::UnInit"); if(m_VideoDecoder) { delete m_VideoDecoder; m_VideoDecoder = nullptr; } if(m_VideoRender) { delete m_VideoRender; m_VideoRender = nullptr; } if(m_AudioDecoder) { delete m_AudioDecoder; m_AudioDecoder = nullptr; } if(m_AudioRender) { delete m_AudioRender; m_AudioRender = nullptr; } VideoGLRender::ReleaseInstance(); bool isAttach = false; GetJNIEnv(&isAttach)->DeleteGlobalRef(m_JavaObj); if(isAttach) GetJavaVM()->DetachCurrentThread(); } void FFMediaPlayer::Play() { LOGCATE("FFMediaPlayer::Play"); if(m_VideoDecoder) m_VideoDecoder->Start(); if(m_AudioDecoder) m_AudioDecoder->Start(); } void FFMediaPlayer::Pause() { LOGCATE("FFMediaPlayer::Pause"); if(m_VideoDecoder) m_VideoDecoder->Pause(); if(m_AudioDecoder) m_AudioDecoder->Pause(); } void FFMediaPlayer::Stop() { LOGCATE("FFMediaPlayer::Stop"); if(m_VideoDecoder) m_VideoDecoder->Stop(); if(m_AudioDecoder) m_AudioDecoder->Stop(); } void FFMediaPlayer::SeekToPosition(float position) { LOGCATE("FFMediaPlayer::SeekToPosition position=%f", position); if(m_VideoDecoder) m_VideoDecoder->SeekToPosition(position); if(m_AudioDecoder) m_AudioDecoder->SeekToPosition(position); } long FFMediaPlayer::GetMediaParams(int paramType) { LOGCATE("FFMediaPlayer::GetMediaParams paramType=%d", paramType); long value = 0; switch(paramType) { case MEDIA_PARAM_VIDEO_WIDTH: value = m_VideoDecoder != nullptr ? m_VideoDecoder->GetVideoWidth() : 0; break; case MEDIA_PARAM_VIDEO_HEIGHT: value = m_VideoDecoder != nullptr ? m_VideoDecoder->GetVideoHeight() : 0; break; case MEDIA_PARAM_VIDEO_DURATION: value = m_VideoDecoder != nullptr ? m_VideoDecoder->GetDuration() : 0; break; } return value; } JNIEnv *FFMediaPlayer::GetJNIEnv(bool *isAttach) { JNIEnv *env; int status; if (nullptr == m_JavaVM) { LOGCATE("FFMediaPlayer::GetJNIEnv m_JavaVM == nullptr"); return nullptr; } *isAttach = false; status = m_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_4); if (status != JNI_OK) { status = m_JavaVM->AttachCurrentThread(&env, nullptr); if (status != JNI_OK) { LOGCATE("FFMediaPlayer::GetJNIEnv failed to attach current thread"); return nullptr; } *isAttach = true; } return env; } jobject FFMediaPlayer::GetJavaObj() { return m_JavaObj; } JavaVM *FFMediaPlayer::GetJavaVM() { return m_JavaVM; } void FFMediaPlayer::PostMessage(void *context, int msgType, float msgCode) { if(context != nullptr) { FFMediaPlayer *player = static_cast<FFMediaPlayer *>(context); bool isAttach = false; JNIEnv *env = player->GetJNIEnv(&isAttach); LOGCATE("FFMediaPlayer::PostMessage env=%p", env); if(env == nullptr) return; jobject javaObj = player->GetJavaObj(); jmethodID mid = env->GetMethodID(env->GetObjectClass(javaObj), JAVA_PLAYER_EVENT_CALLBACK_API_NAME, "(IF)V"); env->CallVoidMethod(javaObj, mid, msgType, msgCode); if(isAttach) player->GetJavaVM()->DetachCurrentThread(); } }
27.095541
117
0.657264
[ "render" ]
34da8a66e182ee91d57a92c1857458dd67993b52
6,514
cpp
C++
dali-toolkit/internal/visuals/gradient/gradient.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
dali-toolkit/internal/visuals/gradient/gradient.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
dali-toolkit/internal/visuals/gradient/gradient.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "gradient.h" #include <dali/public-api/math/vector4.h> #include <algorithm> // std::sort namespace { // The maximum width of the lookup texture ( it is a 1-dimension texture with the height as 1 ) const unsigned int MAXIMUM_TEXTURE_RESOLUTION(128u); } // namespace namespace Dali { namespace Toolkit { namespace Internal { Gradient::Gradient() : mGradientUnits(Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX), mSpreadMethod(Toolkit::GradientVisual::SpreadMethod::PAD) { } Gradient::~Gradient() { } void Gradient::AddStop(float offset, const Vector4& color) { // the offset is clamped to the range [0.0, 1.0] mGradientStops.PushBack(GradientStop(Clamp(offset, 0.f, 1.f), color)); } const Vector<Gradient::GradientStop>& Gradient::GetStops() { return mGradientStops; } void Gradient::SetGradientUnits(Toolkit::GradientVisual::Units::Type gradientUnits) { mGradientUnits = gradientUnits; } Toolkit::GradientVisual::Units::Type Gradient::GetGradientUnits() const { return mGradientUnits; } void Gradient::SetSpreadMethod(Toolkit::GradientVisual::SpreadMethod::Type spread) { mSpreadMethod = spread; } Toolkit::GradientVisual::SpreadMethod::Type Gradient::GetSpreadMethod() const { return mSpreadMethod; } const Matrix3& Gradient::GetAlignmentTransform() const { return mAlignmentTransform; } /** * Following the SVG gradient. * * Not only the spread method decides the texture wrap mode: * PAD-->GL_CLAMP_TO_EDGE; REPEAT-->GL_REPEAT; REFLECT-->GL_MIRROR_REPEAT * * If the stops have not covered the whole zero to one range, * the REPEAT spread behaves different from the two others in the lookup texture generation. */ Dali::Texture Gradient::GenerateLookupTexture() { std::sort(mGradientStops.Begin(), mGradientStops.End()); unsigned int numStops = mGradientStops.Count(); /** * If the stops have not covered the whole zero to one range, * for PAD and REFLECT, use the color of the first stop to fill the range [0.0, first stop offset) * and use the color of the last stop to fill the range (last stop offset, 1.0] * for REPEAT, mix the two color of the first and last stop to fill the remainder */ bool tempFirstStop = false; if(mGradientStops[0].mOffset > 0.f) { tempFirstStop = true; Vector4 firstStopColor(mGradientStops[0].mStopColor); // If spread method is PAD or REFLECT if(mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT) { firstStopColor = (mGradientStops[0].mStopColor * (1.f - mGradientStops[numStops - 1].mOffset) + mGradientStops[numStops - 1].mStopColor * mGradientStops[0].mOffset) / (mGradientStops[0].mOffset + 1.f - mGradientStops[numStops - 1].mOffset); } mGradientStops.Insert(mGradientStops.Begin(), GradientStop(0.f, firstStopColor)); numStops++; } bool tempLastStop = false; if(mGradientStops[numStops - 1].mOffset < 1.f) { tempLastStop = true; Vector4 lastStopColor(mGradientStops[numStops - 1].mStopColor); // If spread method is PAD or REFLECT if(mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT) { lastStopColor = mGradientStops[0].mStopColor; } mGradientStops.PushBack(GradientStop(1.f, lastStopColor)); numStops++; } /** * Generate the pixels with the color transit from one stop to next. */ unsigned int resolution = EstimateTextureResolution(); unsigned int bufferSize = resolution * 4u; unsigned char* pixels = new unsigned char[bufferSize]; PixelData pixelData = PixelData::New(pixels, bufferSize, resolution, 1u, Pixel::RGBA8888, PixelData::DELETE_ARRAY); int segmentStart = 0; int segmentEnd = 0; int k = 0; float length = static_cast<float>(resolution); for(unsigned int i = 0; i < numStops - 1u; i++) { segmentEnd = floorf(mGradientStops[i + 1].mOffset * length + 0.5f); if(segmentEnd == segmentStart) { continue; } float segmentWidth = static_cast<float>(segmentEnd - segmentStart); for(int j = segmentStart; j < segmentEnd; j++) { float ratio = static_cast<float>(j - segmentStart) / (segmentWidth - 1); Vector4 currentColor = mGradientStops[i].mStopColor * (1.f - ratio) + mGradientStops[i + 1].mStopColor * ratio; pixels[k * 4] = static_cast<unsigned char>(255.f * Clamp(currentColor.r, 0.f, 1.f)); pixels[k * 4 + 1] = static_cast<unsigned char>(255.f * Clamp(currentColor.g, 0.f, 1.f)); pixels[k * 4 + 2] = static_cast<unsigned char>(255.f * Clamp(currentColor.b, 0.f, 1.f)); pixels[k * 4 + 3] = static_cast<unsigned char>(255.f * Clamp(currentColor.a, 0.f, 1.f)); k++; } segmentStart = segmentEnd; } Texture texture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, resolution, 1u); texture.Upload(pixelData); // remove the stops added temporarily for generating the pixels, as the spread method might get changed later if(tempLastStop) { mGradientStops.Erase(mGradientStops.Begin() + numStops - 1); } if(tempFirstStop) { mGradientStops.Erase(mGradientStops.Begin()); } return texture; } unsigned int Gradient::EstimateTextureResolution() { float minInterval = 1.0; for(unsigned int i = 0, numStops = mGradientStops.Count(); i < numStops - 1u; i++) { float interval = mGradientStops[i + 1].mOffset - mGradientStops[i].mOffset; minInterval = interval > minInterval ? minInterval : interval; } // Use at least three pixels for each segment between two stops unsigned int resolution = static_cast<int>(3.f / (minInterval + Math::MACHINE_EPSILON_100) + 0.5f); // Clamp the resolution to handle the overlapping stops if(resolution > MAXIMUM_TEXTURE_RESOLUTION) { return MAXIMUM_TEXTURE_RESOLUTION; } return resolution; } } // namespace Internal } // namespace Toolkit } // namespace Dali
31.931373
246
0.702333
[ "vector" ]
34db9b791a529bda20491efe9e7149f622ad3bf8
5,912
cpp
C++
admin/winning_teams/strongAccept/code/impl/libfuzzy/search_time.cpp
isj/sigmod
8ffd3c50ac288aa12c05218d52b1f05eeb23a085
[ "BSD-2-Clause" ]
1
2015-11-27T05:56:25.000Z
2015-11-27T05:56:25.000Z
admin/winning_teams/strongAccept/code/impl/libfuzzy/search_time.cpp
isj/sigmod
8ffd3c50ac288aa12c05218d52b1f05eeb23a085
[ "BSD-2-Clause" ]
null
null
null
admin/winning_teams/strongAccept/code/impl/libfuzzy/search_time.cpp
isj/sigmod
8ffd3c50ac288aa12c05218d52b1f05eeb23a085
[ "BSD-2-Clause" ]
null
null
null
#include "fuzzy.h" extern int queryRounds; using namespace std; void SharedInfoTime::init() { for (int dist = 0; dist < MAXED; dist++) { edIndexes[dist].init(dist); hmIndexes[dist].init(dist); } } void SharedInfoTime::clear() { for (int dist = 0; dist < MAXED; dist++) { edIndexes[dist].clear(); hmIndexes[dist].clear(); } } void SharedInfoTime::insertED(int ed, int id, const char *record, int time) { edIndexes[ed].insert(id, record, time); } void SharedInfoTime::insertHM(int hm, int id, const char *record, int time) { hmIndexes[hm].insert(id, record, time); } void SearchTime::init(SharedInfoTime *sharedInfo) { quickRefSize = 1e7; quickRef = new bool[quickRefSize]; memset(quickRef, 0, quickRefSize); this->sharedInfo = sharedInfo; for (int k = 0; k < SAFELEN; k++) { matrix[k][0] = _mm_set1_epi8(k); matrix[0][k] = _mm_set1_epi8(k); } } void SearchTime::searchHM(int time, const vector<string> &dict, int hm, const char *query, vector<pair<int, int>> &res) { D = hm; index = &(sharedInfo->hmIndexes[D]); if (D == 0) { auto iter = index->index0.find(query); if (iter != index->index0.end() && iter->second.time >= time) { res.emplace_back(iter->second.id, 0); } return; } checkQuickRefID(index); int id[16]; int result[16]; int count = 0; int qlen = strlen(query); hash.initQuery(query, qlen); for (int partId = 0; partId < index->PN; partId++) { int len = index->partLen[partId][qlen]; int pos = index->partPos[partId][qlen]; auto value = hash.getQueryValue(pos, pos + len); auto inv_it = index->invList[partId][qlen].find(value); if (inv_it == index->invList[partId][qlen].end()) continue; // enumerate all element in inverted list for (auto vit = inv_it->second.rbegin(); vit != inv_it->second.rend(); vit++) { if (vit->time < time) break; const char *candidate = dict[vit->id].c_str(); for (int k = 0; k < qlen; k++) buffer[k][count] = candidate[k]; id[count] = vit->id; if (++count == 16) { getHM((__m128i*)buffer, query, qlen, result, count, D); for (int k = 0; k < 16; k++) { if (result[k] <= D) { res.emplace_back(id[k], result[k]); } } count = 0; } } } if (count != 0) { getHM((__m128i*)buffer, query, qlen, result, count, D); for (int k = 0; k < count; k++) { if (result[k] <= D) { res.emplace_back(id[k], result[k]); } } } } void SearchTime::searchED(int time, const vector<string> &dict, int ed, const char *query, vector<pair<int, int>> &res) { D = ed; index = &(sharedInfo->edIndexes[D]); if (D == 0) { auto iter = index->index0.find(query); if (iter != index->index0.end() && iter->second.time >= time) { res.emplace_back(iter->second.id, 0); } return; } checkQuickRefID(index); int id[16]; int result[16]; int length[16]; int qlen = strlen(query); hash.initQuery(query, qlen); auto &partIndex = index->partIndex; int count = 0; for (int partId = 0; partId < index->PN; partId++) { for (unsigned lp = 0; lp < partIndex[partId][qlen].size(); lp++) { int stPos = partIndex[partId][qlen][lp].stPos; int plen = partIndex[partId][qlen][lp].partLen; int clen = partIndex[partId][qlen][lp].len; auto value = hash.getQueryValue(stPos, stPos + plen); auto inv_it = index->invList[partId][clen].find(value); if (inv_it == index->invList[partId][clen].end()) continue; // enumerate all element in inverted list for (auto vit = inv_it->second.rbegin(); vit != inv_it->second.rend(); vit++) { if (vit->time < time) break; if (!quickRef[vit->id]) { quickRef[vit->id] = true; testIDs.push_back(vit->id); } else { continue; } const char *candidate = dict[vit->id].c_str(); for (int k = 0; k < clen; k++) buffer[k][count] = candidate[k]; length[count] = clen; id[count] = vit->id; if (++count == 16) { getED((__m128i*)buffer, query, length, qlen, result, count, D); for (int k = 0; k < 16; k++) { if (result[k] <= D) { res.emplace_back(id[k], result[k]); } } count = 0; } } } } if (count != 0) { getED((__m128i*)buffer, query, length, qlen, result, count, D); for (int k = 0; k < count; k++) { if (result[k] <= D) { res.emplace_back(id[k], result[k]); } } } for (int id : testIDs) quickRef[id] = false; testIDs.clear(); } void SearchTime::getED(__m128i *a, const char *b, int *alen, int blen, int *eds, int count, int D) { __m128i one = _mm_set1_epi8(1); for (int i = 1; i <= blen; i++) { __m128i bcurrent = _mm_set1_epi8(b[i - 1]); for(int j = 1; j <= blen + D; j++) { matrix[i][j] = _mm_add_epi8(matrix[i - 1][j - 1], _mm_cmpeq_epi8(bcurrent, a[j - 1])); matrix[i][j] = _mm_min_epi8(matrix[i][j], _mm_min_epi8(matrix[i][j - 1], matrix[i - 1][j])); matrix[i][j] = _mm_add_epi8(matrix[i][j], one); // matrix[i][j] = _mm_add_epi8(matrix[i - 1][j - 1], _mm_cmpeq_epi8(bcurrent, a[j - 1])); // matrix[i][j] = _mm_add_epi8(matrix[i][j], one); // matrix[i][j] = _mm_min_epu8(matrix[i][j], // _mm_add_epi8(_mm_min_epu8(matrix[i][j - 1], matrix[i - 1][j]), one)); } } for (int k = 0; k < count; k++) { eds[k] = ((char*)&(matrix[blen][alen[k]]))[k]; } } void SearchTime::getHM(__m128i *a, const char *b, int len, int *hms, int count, int D) { __m128i result = _mm_set1_epi8(len); for (int k = 1; k <= len; k++) { __m128i bcurrent = _mm_set1_epi8(b[k - 1]); result = _mm_add_epi8(result, _mm_cmpeq_epi8(bcurrent, a[k - 1])); } char *c = (char*)&result; for (int k = 0; k < count; k++) { hms[k] = c[k]; } } void SearchTime::checkQuickRefID(IndexTime *index) { if (index->maxID >= quickRefSize) { while (index->maxID >= quickRefSize) quickRefSize *= 2; delete[] quickRef; quickRef = new bool[quickRefSize]; memset(quickRef, 0, quickRefSize); } }
23.09375
119
0.596076
[ "vector" ]
34ec1d2d031dfa7f500f70753fa6a1487e6dc6fe
1,491
cpp
C++
src/SeqUtils.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
src/SeqUtils.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
src/SeqUtils.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
#ifndef SEQUTILS_CPP #define SEQUTILS_CPP #include "SeqUtils.h" char BaseComplement(char c) { switch (c) { case 'A' : return 'T'; case 'C' : return 'G'; case 'G' : return 'C'; case 'T' : return 'A'; default : return 'N'; }; } /*int SeqDistance(string a, string b) { int n = a.size(), c1 = 0, c2 = 0; for (int i = 0; i < n; ++i) { c1 += a[i] != b[i]; c2 += a[i] != BaseComplement(b[n - i]); } return min(c1, c2); }*/ int SeqDistance(string a, string b) { int c = 0; int n = min(a.size(), b.size()); for (int i = 0; i < n; ++i) c += toupper(a[i]) != toupper(b[i]); return c; } string Hts2Seq(unsigned char* A, int n) { string s(n, ' '); for (int i = 0; i < n; ++i) switch (bam_seqi(A, i)) { case 1: s[i] = 'A'; break; case 2: s[i] = 'C'; break; case 4: s[i] = 'G'; break; case 8: s[i] = 'T'; break; default: s[i] = 'N'; } return s; } vector<string> SplitString(string s, char c) { vector<string> V({""}); for(unsigned int i = 0; i < s.size(); i++) if (s[i] != c) V.back() += s[i]; else if (i < s.size() - 1) V.push_back(""); return V; } template<typename T> vector<T> SetIntersection(set<T>& A, set<T>& B) { vector<T> R; set_intersection(A.begin(), A.end(), B.begin(), B.end(), back_inserter(R)); return R; } template<typename T> vector<T> SetUnion(set<T>& A, set<T>& B) { vector<T> R; set_union(A.begin(), A.end(), B.begin(), B.end(), back_inserter(R)); return R; } #endif
18.873418
79
0.530516
[ "vector" ]
34ef75f846eb4acfad392cbdfffdf4a2a6a82323
3,101
hxx
C++
src/utils/Singleton.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
34
2015-05-23T03:57:56.000Z
2022-03-27T03:48:48.000Z
src/utils/Singleton.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
214
2015-07-05T05:06:55.000Z
2022-02-06T14:53:14.000Z
src/utils/Singleton.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
38
2015-08-28T05:32:07.000Z
2021-07-06T16:47:23.000Z
/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * \file Singleton.hxx * * Utility class to ensure a particular class has only a single object, and * access it via a static reference. * * @author Balazs Racz * @date 19 July 2013 */ #ifndef _UTILS_SINGLETON_HXX_ #define _UTILS_SINGLETON_HXX_ #include "utils/macros.h" /** Singleton class. By inheriting from this class you declare that the descendants will have only a single instance in the running binary. This will allow accessing the running instance without passing around a pointer to it. Usage: class Foo; class Foo: public Singleton<Foo> { ...as usual... }; DEFINE_SINGLETON_INSTANCE(Foo); void appl_main() { Foo my_instance(constructor_args); } somewhere else: Foo::instance()->DoSomething(); */ template<class T> class Singleton { public: Singleton() { HASSERT(instance_ == nullptr); instance_ = static_cast<T*>(this); } ~Singleton() { instance_ = nullptr; } /// @return the singleton instance of this object. static T* instance() { HASSERT(instance_ != nullptr); return instance_; } /// @return true if there is a class of this singleton instantiated. static bool exists() { return (instance_ != nullptr); } private: /// The singleton instance pointer. static T* instance_; }; template<class T> T* Singleton<T>::instance_ = nullptr; /// Helper macro the the customer may (but is not required to) use for ensuring /// that the singleton instance is found by the linker. Must appear in a single /// .cxx file. /// @param T the class name that is a Singleton. #define DEFINE_SINGLETON_INSTANCE(T) template<> T* Singleton<T>::instance_ = nullptr #endif // _UTILS_SINGLETON_HXX_
30.401961
84
0.723638
[ "object" ]
34f9a36d47ad11cce90841f0fa78ea08956aec3e
1,094
cpp
C++
src/main.cpp
spjuanjoc/uri_parser_cpp
83c67bf29b12f3eee55c78661aad8495f08f73b3
[ "MIT" ]
null
null
null
src/main.cpp
spjuanjoc/uri_parser_cpp
83c67bf29b12f3eee55c78661aad8495f08f73b3
[ "MIT" ]
null
null
null
src/main.cpp
spjuanjoc/uri_parser_cpp
83c67bf29b12f3eee55c78661aad8495f08f73b3
[ "MIT" ]
null
null
null
#include "../include/URIHandler.h" #include <iostream> #include <string> #include <vector> using std::boolalpha; using std::cout; using std::endl; using std::string; using std::stringstream; using std::vector; int main() { cout << "Inicio" << endl; // for (string &it : sV) // { //// cout << "URI: " << it << endl; // URIHandler oUri{it}; /// @see https://en.wikipedia.org/wiki/File:URI_syntax_diagram.svg //// cout << "Scheme: \"" << oUri.GetScheme() << "\" \n"; //// cout << "Authority: \"" << oUri.GetAuthority() << "\" "; //// cout << "Host: \"" << oUri.GetHost() << "\" "; //// if (oUri.HasPort() == true) //// { //// cout << "Port: \"" << oUri.GetPort() << "\" \n"; //// } //// cout << "Path: \"" << oUri.GetPath() << "\" \n"; //// cout << "Query: \"" << oUri.GetQuery() << "\" \n"; //// cout << "Fragment: \"" << oUri.GetFragment() << "\" \n"; // cout << std::boolalpha << count << ": " << oUri.IsValidUri() << endl; // ++count; // } cout << endl; return 0; }
28.789474
97
0.463437
[ "vector" ]
5a5ff9805ced5644ee33062628f56cfe601fad4c
706
hpp
C++
Application/include/utils/MP3.hpp
einsteinx2/TriPlayer
cb9e12fb71b90241b9fa08c40b8ca73a209ca8c2
[ "MIT" ]
null
null
null
Application/include/utils/MP3.hpp
einsteinx2/TriPlayer
cb9e12fb71b90241b9fa08c40b8ca73a209ca8c2
[ "MIT" ]
null
null
null
Application/include/utils/MP3.hpp
einsteinx2/TriPlayer
cb9e12fb71b90241b9fa08c40b8ca73a209ca8c2
[ "MIT" ]
null
null
null
#ifndef UTILS_MP3_HPP #define UTILS_MP3_HPP #include "Types.hpp" #include <vector> namespace Utils::MP3 { // Initializes libraries used for helper functions // Returns false if an error occurred bool init(); // Cleans up any initialized libraries void exit(); // Reads image(s) from ID3 tags using mpg123 and returns SongArt // data pointer will be nullptr and size 0 if none found std::vector<unsigned char> getArtFromID3(std::string); // Reads ID3 tags of file using mpg123 and returns SongInfo // ID is -1 on success (filled), -2 on success (song has no tags), -3 on failure // Pass path of file Metadata::Song getInfoFromID3(std::string); }; #endif
28.24
84
0.695467
[ "vector" ]
5a60d53cf8707069d445396cd27d3695da9eda53
4,390
cpp
C++
XLib-v1.2.0/src/Graph/Host/GraphSTD_SCC.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
1
2019-12-28T09:30:24.000Z
2019-12-28T09:30:24.000Z
XLib-v1.2.0/src/Graph/Host/GraphSTD_SCC.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
1
2020-08-25T10:57:11.000Z
2020-08-25T10:57:11.000Z
XLib-v1.2.0/src/Graph/Host/GraphSTD_SCC.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------------ Copyright © 2016 by Nicola Bombieri XLib is provided under the terms of The MIT License (MIT): 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. ------------------------------------------------------------------------------*/ /** * @author Federico Busato * Univerity of Verona, Dept. of Computer Science * federico.busato@univr.it */ #include "Base/Host/fUtil.hpp" namespace graph { template<typename node_t, typename edge_t, typename dist_t> const node_t GraphSTD<node_t, edge_t, dist_t>::SCC_Class::INDEX_UNDEF = -1; template<typename node_t, typename edge_t, typename dist_t> GraphSTD<node_t, edge_t, dist_t>::SCC_Class ::SCC_Class(const GraphSTD<node_t, edge_t, dist_t>& _graph) : graph(_graph), LowLink(nullptr), Index(nullptr), SCC_set(nullptr), InStack(0), Queue(0), scc_init(false), extern_scc_init(false), curr_index(0), SCC_index(0) {} template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::SCC_Class::_init() { scc_init = true; LowLink = new node_t[graph.V]; Index = new node_t[graph.V]; SCC_set = new node_t[graph.V]; InStack.init(graph.V); Queue.init(graph.V); curr_index = 0; SCC_index = 0; std::fill(Index, Index + graph.V, SCC_Class::INDEX_UNDEF); } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::SCC_Class::init() { extern_scc_init = true; _init(); } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::SCC_Class::close() { scc_init = false; extern_scc_init = false; delete[] LowLink; delete[] Index; delete[] SCC_set; InStack.free(); Queue.free(); } template<typename node_t, typename edge_t, typename dist_t> std::vector<node_t> GraphSTD<node_t, edge_t, dist_t>::SCC_Class::exec() { xlib::stackManagement StackSTR; StackSTR.checkUnlimited(); if (!scc_init) _init(); std::vector<node_t> scc_distr; for (node_t i = 0; i < graph.V; i++) { if (Index[i] == -1) { singleSCC(i, &scc_distr); Queue.reset(); } } if (!extern_scc_init) close(); return scc_distr; } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::SCC_Class ::singleSCC(node_t source, std::vector<node_t>* scc_distr_v) { Queue.insert(source); Index[source] = LowLink[source] = curr_index++; InStack.set(source); for (edge_t i = graph.OutOffset[source]; i < graph.OutOffset[source + 1]; i++) { const node_t dest = graph.OutEdges[i]; if ( Index[dest] == INDEX_UNDEF ) { singleSCC(dest, scc_distr_v); LowLink[source] = std::min(LowLink[source], LowLink[dest]); } else if ( InStack[dest] ) LowLink[source] = std::min(LowLink[source], Index[dest]); } if (Index[source] == LowLink[source]) { node_t extracted; node_t SCC_size = 0; do { SCC_size++; extracted = Queue.template extract<xlib::QueuePolicy::LIFO>(); InStack.unset(extracted); SCC_set[extracted] = SCC_index; } while (extracted != source); scc_distr_v->push_back(SCC_size); SCC_index++; } } } //@graph
35.12
80
0.656264
[ "vector" ]
5a72536d43e70702969f4f3e84d2ad863e31d27e
17,259
cpp
C++
src/avx512sort.cpp
Tabasz/quick-AVX-512-sort
a614e76040640359b2c256c41367dbbad68c63ab
[ "MIT" ]
null
null
null
src/avx512sort.cpp
Tabasz/quick-AVX-512-sort
a614e76040640359b2c256c41367dbbad68c63ab
[ "MIT" ]
null
null
null
src/avx512sort.cpp
Tabasz/quick-AVX-512-sort
a614e76040640359b2c256c41367dbbad68c63ab
[ "MIT" ]
null
null
null
#include <immintrin.h> #include <cstdint> #include "vectorized_sort.hpp" #include "defines.hpp" inline int calc_min(__m512i vec2) { auto perm_mask2 = _mm512_setr_epi32(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); vec2 = _mm512_min_epi32(vec2, _mm512_permutexvar_epi32(perm_mask2, vec2)); __m256i vec = _mm512_extracti64x4_epi64(vec2, 0); auto perm_mask = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); vec = _mm256_min_epi32(vec, _mm256_permutevar8x32_epi32(vec, perm_mask)); vec = _mm256_min_epi32(vec, _mm256_shuffle_epi32(vec, 0b10110001)); vec = _mm256_min_epi32(vec, _mm256_shuffle_epi32(vec, 0b01001110)); return _mm256_extract_epi32(vec, 0); } inline int calc_max(__m512i vec2) { auto perm_mask2 = _mm512_setr_epi32(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); vec2 = _mm512_max_epi32(vec2, _mm512_permutexvar_epi32(perm_mask2, vec2)); __m256i vec = _mm512_extracti64x4_epi64(vec2, 0); auto perm_mask = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); vec = _mm256_max_epi32(vec, _mm256_permutevar8x32_epi32(vec, perm_mask)); vec = _mm256_max_epi32(vec, _mm256_shuffle_epi32(vec, 0b10110001)); vec = _mm256_max_epi32(vec, _mm256_shuffle_epi32(vec, 0b01001110)); return _mm256_extract_epi32(vec, 0); } void partition_vec(__m512i &curr_vec, const __m512i &pivot_vec, __m512i &smallest_vec, __m512i &biggest_vec, int *arr, int &l_store, int &r_store) { /* which elements are smaller or equal than the pivot */ int less_equal_mask = _mm512_cmple_epi32_mask(curr_vec, pivot_vec); /* update the smallest and largest values of the array */ smallest_vec = _mm512_min_epi32(curr_vec, smallest_vec); biggest_vec = _mm512_max_epi32(curr_vec, biggest_vec); int amount_le_pivot = _mm_popcnt_u32(less_equal_mask); /* store smaller/equal elements at the l_store and bigger at the r_store */ _mm512_mask_compressstoreu_epi32(arr + l_store, less_equal_mask, curr_vec); r_store -= 16 - amount_le_pivot; l_store += (amount_le_pivot); _mm512_mask_compressstoreu_epi32(arr + r_store, ~less_equal_mask, curr_vec); } void partition_vec_mask(__m512i &curr_vec, int cnt, const __m512i &pivot_vec, __m512i &smallest_vec, __m512i &biggest_vec, int *arr, int &l_store, int &r_store) { int mask = (1 << cnt) - 1; /* which elements are smaller or equal than the pivot */ int less_equal_mask = _mm512_cmple_epi32_mask(curr_vec, pivot_vec); /* update the smallest and largest values of the array */ smallest_vec = _mm512_min_epi32(curr_vec, smallest_vec); biggest_vec = _mm512_max_epi32(curr_vec, biggest_vec); int amount_le_pivot = _mm_popcnt_u32(less_equal_mask & mask); r_store -= cnt - amount_le_pivot; /* store smaller/equal elements at the l_store and bigger at the r_store */ _mm512_mask_compressstoreu_epi32(arr + l_store, less_equal_mask & mask, curr_vec); l_store += (amount_le_pivot); _mm512_mask_compressstoreu_epi32(arr + r_store, (~less_equal_mask) & mask, curr_vec); } inline int partition(int *arr, int left, int right, int pivot, int &smallest, int &biggest) { auto pivot_vec = _mm512_set1_epi32(pivot); /* fill vector with pivot */ auto sv = _mm512_set1_epi32(smallest); /* vector for smallest elements */ auto bv = _mm512_set1_epi32(biggest); /* vector for biggest elements */ int r_store = right; /* right store point */ int l_store = left; /* left store point */ /* buffer 8 vectors from both sides of the array */ auto vec_left = LOAD_VECTOR(arr + left), vec_left2 = LOAD_VECTOR(arr + left + 16); auto vec_left3 = LOAD_VECTOR(arr + left + 32), vec_left4 = LOAD_VECTOR(arr + left + 48); auto vec_left5 = LOAD_VECTOR(arr + left + 64), vec_left6 = LOAD_VECTOR(arr + left + 80); auto vec_left7 = LOAD_VECTOR(arr + left + 96), vec_left8 = LOAD_VECTOR(arr + left + 112); right -= 128; auto vec_right = LOAD_VECTOR(arr + right), vec_right2 = LOAD_VECTOR(arr + right + 16); auto vec_right3 = LOAD_VECTOR(arr + right + 32), vec_right4 = LOAD_VECTOR(arr + right + 48); auto vec_right5 = LOAD_VECTOR(arr + right + 64), vec_right6 = LOAD_VECTOR(arr + right + 80); auto vec_right7 = LOAD_VECTOR(arr + right + 96), vec_right8 = LOAD_VECTOR(arr + right + 112); left += 128; while (right - left >= 128) { /* partition 128 elements per iteration */ __m512i curr_vec, curr_vec2, curr_vec3, curr_vec4, curr_vec5, curr_vec6, curr_vec7, curr_vec8; /* load 8 vectors from the side where is less space for storing */ if (r_store - right < left - l_store) { right -= 128; curr_vec = LOAD_VECTOR(arr + right); curr_vec2 = LOAD_VECTOR(arr + right + 16); curr_vec3 = LOAD_VECTOR(arr + right + 32); curr_vec4 = LOAD_VECTOR(arr + right + 48); curr_vec5 = LOAD_VECTOR(arr + right + 64); curr_vec6 = LOAD_VECTOR(arr + right + 80); curr_vec7 = LOAD_VECTOR(arr + right + 96); curr_vec8 = LOAD_VECTOR(arr + right + 112); } else { curr_vec = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); curr_vec4 = LOAD_VECTOR(arr + left + 48); curr_vec5 = LOAD_VECTOR(arr + left + 64); curr_vec6 = LOAD_VECTOR(arr + left + 80); curr_vec7 = LOAD_VECTOR(arr + left + 96); curr_vec8 = LOAD_VECTOR(arr + left + 112); left += 128; } /* partition 8 vectors and store them on both sides of the array */ partition_vec(curr_vec, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec5, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec6, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec7, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec8, pivot_vec, sv, bv, arr, l_store, r_store); } int extra = (right - left); __m512i curr_vec1, curr_vec2, curr_vec3, curr_vec4, curr_vec5, curr_vec6, curr_vec7, curr_vec8; switch ((extra + 15) >> 4) // process rest of n % 128 elements { case 0: break; case 1: curr_vec1 = LOAD_VECTOR(arr + left); partition_vec_mask(curr_vec1, extra, pivot_vec, sv, bv, arr, l_store, r_store); break; case 2: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec2, extra - 16, pivot_vec, sv, bv, arr, l_store, r_store); break; case 3: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec3, extra - 32, pivot_vec, sv, bv, arr, l_store, r_store); break; case 4: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); curr_vec4 = LOAD_VECTOR(arr + left + 48); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec4, extra - 48, pivot_vec, sv, bv, arr, l_store, r_store); break; case 5: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); curr_vec4 = LOAD_VECTOR(arr + left + 48); curr_vec5 = LOAD_VECTOR(arr + left + 64); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec5, extra - 64, pivot_vec, sv, bv, arr, l_store, r_store); break; case 6: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); curr_vec4 = LOAD_VECTOR(arr + left + 48); curr_vec5 = LOAD_VECTOR(arr + left + 64); curr_vec6 = LOAD_VECTOR(arr + left + 80); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec5, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec6, extra - 80, pivot_vec, sv, bv, arr, l_store, r_store); break; case 7: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); curr_vec4 = LOAD_VECTOR(arr + left + 48); curr_vec5 = LOAD_VECTOR(arr + left + 64); curr_vec6 = LOAD_VECTOR(arr + left + 80); curr_vec7 = LOAD_VECTOR(arr + left + 96); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec5, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec6, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec7, extra - 96, pivot_vec, sv, bv, arr, l_store, r_store); break; case 8: curr_vec1 = LOAD_VECTOR(arr + left); curr_vec2 = LOAD_VECTOR(arr + left + 16); curr_vec3 = LOAD_VECTOR(arr + left + 32); curr_vec4 = LOAD_VECTOR(arr + left + 48); curr_vec5 = LOAD_VECTOR(arr + left + 64); curr_vec6 = LOAD_VECTOR(arr + left + 80); curr_vec7 = LOAD_VECTOR(arr + left + 96); curr_vec8 = LOAD_VECTOR(arr + left + 112); partition_vec(curr_vec1, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec5, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec6, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(curr_vec7, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec_mask(curr_vec8, extra - 112, pivot_vec, sv, bv, arr, l_store, r_store); break; } /* partition and store 8 vectors coming from the left side of the array */ partition_vec(vec_left, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left5, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left6, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left7, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_left8, pivot_vec, sv, bv, arr, l_store, r_store); /* partition and store 8 vectors coming from the right side of the array */ partition_vec(vec_right, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right2, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right3, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right4, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right5, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right6, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right7, pivot_vec, sv, bv, arr, l_store, r_store); partition_vec(vec_right8, pivot_vec, sv, bv, arr, l_store, r_store); smallest = calc_min(sv); biggest = calc_max(bv); return l_store; } /*** * vectorized pivot selection */ /* vectorized random number generator xoroshiro128+ */ inline __m256i vnext(__m256i &s0, __m256i &s1) { s1 = _mm256_xor_si256(s0, s1); /* modify vectors s1 and s0 */ s0 = _mm256_xor_si256(_mm256_xor_si256(VROTL(s0, 24), s1), _mm256_slli_epi64(s1, 16)); s1 = VROTL(s1, 37); return _mm256_add_epi64(s0, s1); } /* return random vector */ /* transform random numbers to the range between 0 and bound - 1 */ inline __m256i rnd_epu32(__m256i rnd_vec, __m256i bound) { __m256i even = _mm256_srli_epi64(_mm256_mul_epu32(rnd_vec, bound), 32); __m256i odd = _mm256_mul_epu32(_mm256_srli_epi64(rnd_vec, 32), bound); return _mm256_blend_epi32(odd, even, 0b01010101); } /* average of two integers without overflow * http://aggregate.org/MAGIC/#Average%20of%20Integers */ inline int average(int a, int b) { return (a & b) + ((a ^ b) >> 1); } inline int get_pivot(int *arr, const int left, const int right) { auto bound = _mm256_set1_epi32(right - left + 1); auto left_vec = _mm256_set1_epi32(left); /* seeds for vectorized random number generator */ auto s0 = _mm256_setr_epi64x(8265987198341093849, 3762817312854612374, 1324281658759788278, 6214952190349879213); auto s1 = _mm256_setr_epi64x(2874178529384792648, 1257248936691237653, 7874578921548791257, 1998265912745817298); s0 = _mm256_add_epi64(s0, _mm256_set1_epi64x(left)); s1 = _mm256_sub_epi64(s1, _mm256_set1_epi64x(right)); __m256i v[9]; for (int i = 0; i < 9; ++i) { /* fill 9 vectors with random numbers */ auto result = vnext(s0, s1); /* vector with 4 random uint64_t */ result = rnd_epu32(result, bound); /* random numbers between 0 and bound - 1 */ result = _mm256_add_epi32(result, left_vec); /* indices for arr */ v[i] = _mm256_i32gather_epi32(arr, result, sizeof(uint32_t)); } /* median network for 9 elements */ COEX(v[0], v[1]); COEX(v[2], v[3]); /* step 1 */ COEX(v[4], v[5]); COEX(v[6], v[7]); COEX(v[0], v[2]); COEX(v[1], v[3]); /* step 2 */ COEX(v[4], v[6]); COEX(v[5], v[7]); COEX(v[0], v[4]); COEX(v[1], v[2]); /* step 3 */ COEX(v[5], v[6]); COEX(v[3], v[7]); COEX(v[1], v[5]); COEX(v[2], v[6]); /* step 4 */ COEX(v[3], v[5]); COEX(v[2], v[4]); /* step 5 */ COEX(v[3], v[4]); /* step 6 */ COEX(v[3], v[8]); /* step 7 */ COEX(v[4], v[8]); /* step 8 */ SORT_8(v[4]); /* sort the eight medians in v[4] */ return average(_mm256_extract_epi32(v[4], 3), /* compute next pivot */ _mm256_extract_epi32(v[4], 4)); } /* recursion for quicksort */ inline void qs_core512(int *arr, int left, int right, bool choose_avg = false, const int avg = 0, const int upper_bound = INT32_MAX) { if (right - left < SORTING_NETWORK_THRESHOLD) { /* use sorting networks for small arrays up to SORTING_NETWORK_THRESHOLD */ sorting_network512(arr + left, right - left + 1); return; } /* avg is average of largest and smallest values in array */ int pivot = choose_avg ? avg : get_pivot(arr, left, right); // assumes that get pivot is in [smallest, biggest] if (pivot == upper_bound) pivot--; int smallest = INT32_MAX; /* smallest value after partitioning */ int biggest = INT32_MIN; /* largest value after partitioning */ int bound = partition(arr, left, right + 1, pivot, smallest, biggest); if (!choose_avg) { /* the ratio of the length of the smaller partition to the array length */ double ratio = (std::min(right - (bound - 1), bound - left) / double(right - left + 1)); /* if unbalanced sub-arrays, change pivot selection strategy */ if (ratio < 0.2) choose_avg = true; } if (smallest < pivot) /* if values in the left sub-array are not identical */ qs_core512(arr, left, bound - 1, choose_avg, average(smallest, pivot), pivot); if (pivot + 1 < biggest) /* if values in the right sub-array are not identical */ qs_core512(arr, bound, right, choose_avg, average(biggest, pivot + 1), biggest); } /* call this function for sorting */ void quicksort512(int *arr, int n) { qs_core512(arr, 0, n - 1); }
49.03125
115
0.644881
[ "vector", "transform" ]
5a757b635e6871804f6556fc43f4e6d3353abfe9
4,934
cpp
C++
turtlebot3_deliver_service/src/pose_initialization.cpp
ROBOTIS-GIT/turtlebot3_deliver
41b2a825fdc943989b13853d5c35b85b2328f1f9
[ "Apache-2.0" ]
21
2018-04-21T09:15:11.000Z
2021-02-12T16:11:04.000Z
turtlebot3_deliver_service/src/pose_initialization.cpp
ROBOTIS-GIT/turtlebot3_deliver
41b2a825fdc943989b13853d5c35b85b2328f1f9
[ "Apache-2.0" ]
null
null
null
turtlebot3_deliver_service/src/pose_initialization.cpp
ROBOTIS-GIT/turtlebot3_deliver
41b2a825fdc943989b13853d5c35b85b2328f1f9
[ "Apache-2.0" ]
11
2018-04-02T00:08:08.000Z
2021-09-05T04:52:49.000Z
#include "ros/ros.h" #include "turtlebot3_deliver_service/InitTurtlebotPose.h" #include "geometry_msgs/PoseWithCovarianceStamped.h" #include "geometry_msgs/PoseArray.h" #include "geometry_msgs/PoseStamped.h" #include "geometry_msgs/Twist.h" #include "tf2_msgs/TFMessage.h" #define MSE_IS_POSE_INITIALIZING_COMPLETED 15000.0 class PoseInitialization { public: PoseInitialization() { std::string machine_name; ros::param::get("~machine_name", machine_name); nh_.getParam("init_pose/position", init_pose_position); nh_.getParam("init_pose/orientation", init_pose_orientation); // nh_.getParam("table_pose/position", table_pose_position); // nh_.getParam("table_pose/orientation", table_pose_orientation); nh_.getParam("table_pose_" + machine_name + "/position", table_pose_position); nh_.getParam("table_pose_" + machine_name + "/orientation", table_pose_orientation); pub_initial_pose = nh_.advertise<geometry_msgs::PoseWithCovarianceStamped>("initialpose", 1); pub_table_pose = nh_.advertise<geometry_msgs::PoseStamped>("move_base_simple/goal", 1); pub_twist = nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1); sub_gather_particle = nh_.subscribe("particlecloud", 1, &PoseInitialization::cbGatherParticle, this); is_pose_initialized = fnSetInitialPose(); } void cbGatherParticle(const geometry_msgs::PoseArray& poseArray) { if (!is_pose_initialized) return; int size = poseArray.poses.size(); float score = 0.0; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) score += sqrt((poseArray.poses[i].position.x - poseArray.poses[j].position.x) * (poseArray.poses[i].position.x - poseArray.poses[j].position.x) + (poseArray.poses[i].position.y - poseArray.poses[j].position.y) * (poseArray.poses[i].position.y - poseArray.poses[j].position.y)); } if (score > MSE_IS_POSE_INITIALIZING_COMPLETED) { geometry_msgs::Twist twist; twist.angular.z = 0.8; ROS_INFO("on pose initializing | MSE : %lf > %lf", score, MSE_IS_POSE_INITIALIZING_COMPLETED); pub_twist.publish(twist); } else { geometry_msgs::Twist twist; twist.angular.z = 0.0; ROS_INFO("pose initializing completed"); pub_twist.publish(twist); fnTablePose(); exit(0); } } bool fnSetInitialPose() { geometry_msgs::PoseWithCovarianceStamped pubPoseWithCovarianceStamped; pubPoseWithCovarianceStamped.header.stamp = ros::Time::now(); pubPoseWithCovarianceStamped.pose.pose.position.x = init_pose_position[0]; pubPoseWithCovarianceStamped.pose.pose.position.y = init_pose_position[1]; pubPoseWithCovarianceStamped.pose.pose.position.z = init_pose_position[2]; pubPoseWithCovarianceStamped.pose.pose.orientation.x = init_pose_orientation[0]; pubPoseWithCovarianceStamped.pose.pose.orientation.y = init_pose_orientation[1]; pubPoseWithCovarianceStamped.pose.pose.orientation.z = init_pose_orientation[2]; pubPoseWithCovarianceStamped.pose.pose.orientation.w = init_pose_orientation[3]; pubPoseWithCovarianceStamped.pose.covariance = {0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.06853891945200942}; ros::Rate poll_rate(100); while(pub_initial_pose.getNumSubscribers() == 0) poll_rate.sleep(); pub_initial_pose.publish(pubPoseWithCovarianceStamped); return true; } void fnTablePose() { // start pubPoseStamped.header.frame_id = "map"; pubPoseStamped.header.stamp = ros::Time::now(); pubPoseStamped.pose.position.x = table_pose_position[0]; pubPoseStamped.pose.position.y = table_pose_position[1]; pubPoseStamped.pose.position.z = table_pose_position[2]; pubPoseStamped.pose.orientation.x = table_pose_orientation[0]; pubPoseStamped.pose.orientation.y = table_pose_orientation[1]; pubPoseStamped.pose.orientation.z = table_pose_orientation[2]; pubPoseStamped.pose.orientation.w = table_pose_orientation[3]; pub_table_pose.publish(pubPoseStamped); } private: ros::NodeHandle nh_; // Publisher ros::Publisher pub_initial_pose; ros::Publisher pub_twist; ros::Publisher pub_table_pose; // Subscriber ros::Subscriber sub_gather_particle; // msgs geometry_msgs::PoseStamped pubPoseStamped; std::vector<double> init_pose_position; std::vector<double> init_pose_orientation; std::vector<double> table_pose_position; std::vector<double> table_pose_orientation; bool is_pose_initialized = false; }; int main(int argc, char **argv) { //Initiate ROS ros::init(argc, argv, "pose_initialization"); //Create an object of class PoseInitialization that will take care of everything PoseInitialization poseInitialization; ros::spin(); return 0; }
31.628205
250
0.717065
[ "object", "vector" ]
5a7763138aba48d9a1f1556922c15588d794b911
3,985
cpp
C++
qrgui/mainWindow/modelExplorer.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
39
2015-01-26T16:18:43.000Z
2021-12-20T23:36:41.000Z
qrgui/mainWindow/modelExplorer.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
1,248
2019-02-21T19:32:09.000Z
2022-03-29T16:50:04.000Z
qrgui/mainWindow/modelExplorer.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
58
2015-03-03T12:57:28.000Z
2020-05-09T15:54:42.000Z
/* Copyright 2007-2016 QReal Research Group * * 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 "modelExplorer.h" #include <QtGui/QFocusEvent> #include <qrgui/controller/controller.h> #include <qrgui/models/clipboard.h> #include <qrgui/models/models.h> #include <qrgui/models/commands/renameCommand.h> #include <qrgui/models/details/modelsImplementation/abstractModel.h> using namespace qReal; using namespace gui; using namespace models::details::modelsImplementation; ModelExplorer::ModelExplorer(QWidget *parent) : QTreeView(parent) , mController(nullptr) , mModel(nullptr) , mExploser(nullptr) , mClipboard(nullptr) , mDeleteAction(tr("Delete"), this) { mDeleteAction.setShortcut(QKeySequence(Qt::Key_Delete)); connect(&mDeleteAction, &QAction::triggered, this, &ModelExplorer::elementRemoved); mDeleteAction.setEnabled(false); QAction * const deleteActionSeparator = new QAction(this); deleteActionSeparator->setSeparator(true); addAction(&mDeleteAction); addAction(deleteActionSeparator); } ModelExplorer::~ModelExplorer() { } void ModelExplorer::initialize(Controller &controller, const models::Models &models , details::ModelsAssistInterface &model) { mController = &controller; mModel = &model; mExploser = &models.exploser(); mClipboard.reset(new models::Clipboard(controller, models)); // This is bad, but for now we consider that registerEditor() was already invoked by system. // Later when model explorers will be pluginized this will be done manually in init(), so this // consideration will live for a while. addAction(mCopyAction); addAction(mPasteAction); addAction(mCutAction); } QString ModelExplorer::editorId() const { return "qReal." + objectName(); } bool ModelExplorer::supportsCopying() const { return true; } bool ModelExplorer::supportsPasting() const { return true; } bool ModelExplorer::supportsCutting() const { return true; } void ModelExplorer::copy() { const Id id = mModel->idByIndex(currentIndex()); mClipboard->copy({id}); } void ModelExplorer::paste() { const Id selectedId = mModel->idByIndex(currentIndex()); const Id rootId = selectedId.isNull() ? Id::rootId() : selectedId; mClipboard->paste(rootId, QPointF(), false); } void ModelExplorer::cut() { copy(); emit elementRemoved(); } void ModelExplorer::commitData(QWidget *editor) { const Id id = static_cast<AbstractModel *>(model())->idByIndex(currentIndex()); const QString oldName = model()->data(currentIndex()).toString(); QTreeView::commitData(editor); const QString newName = model()->data(currentIndex()).toString(); if (oldName != newName) { mController->execute(new commands::RenameCommand(*mModel, id, oldName, newName, mExploser)); } } void ModelExplorer::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { QTreeView::selectionChanged(selected, deselected); updateActions(); } void ModelExplorer::focusInEvent(QFocusEvent *event) { QTreeView::focusInEvent(event); onFocusIn(); updateActions(); mDeleteAction.setEnabled(true); } void ModelExplorer::focusOutEvent(QFocusEvent *event) { QTreeView::focusOutEvent(event); if (event->reason() != Qt::PopupFocusReason) { mDeleteAction.setEnabled(false); } } void ModelExplorer::updateActions() { const bool itemSelected = !selectedIndexes().isEmpty(); mCopyAction->setEnabled(itemSelected); mCutAction->setEnabled(itemSelected); mPasteAction->setEnabled(!mClipboard.isNull() && !mClipboard->isEmpty()); }
27.108844
102
0.75458
[ "model" ]
5a78471395b7fcb6bcc199ac7c4bf800723d36d1
19,297
cpp
C++
Src/base/BootupAnimation.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/base/BootupAnimation.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/base/BootupAnimation.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "Common.h" #include "BootupAnimation.h" #include <time.h> #include <errno.h> #include <QPainter> #include <PGFallbackFonts.h> #include <PGContext.h> #include <PGSurface.h> #include <PGFont.h> #include <sys/wait.h> //#include "GraphicsUtil.h" #include "HostBase.h" #include "Localization.h" #include "Logging.h" #include "Settings.h" const qreal kLowOpacity = -0.5; const qreal kHighOpacity = 1.0; const int kFirstGlowAnimDuration = 4000; // ms const int kGlowAnimDuration = 2080; // ms const int kFadeAnimDuration = 700; // ms static const int s_activityProgressTotal = 20; static const int s_activitySpinnerTotal = 10; static const int s_frameTimeSlow = 80; // 80ms, 12.5FPS static const int s_frameTimeFast = 33; // 33ms, 30FPS static int s_frameTime = 0; static const int s_fontHeight1 = 20; static const int s_fontHeight2 = 16; static const char* s_line1 = "Updating the system"; static const char* s_line2 = "Do not remove battery"; static void sleepMs(unsigned int ms) { struct timespec req = {0, 0}; req.tv_sec = 0; req.tv_nsec = ms * 1000000L; while (true) { if (nanosleep(&req, &req) == 0) break; if (errno != EINTR) break; } } BootupAnimation::BootupAnimation(int readPipeFd) : m_renderThread(0) , m_state(StateIdle) , m_ctxt(0) , m_font(0) , m_fallbackFonts(0) , m_logoSurf(0) , m_logoBrightSurf(0) , m_activityStaticSurf(0) , m_activityProgressSurf(0) , m_activitySpinnerSurf(0) , m_widthLine1(0) , m_widthLine2(0) , m_readPipeFd(readPipeFd) , m_readNotifier(readPipeFd, QSocketNotifier::Read, this) , m_rotation(0) { Settings::LunaSettings()->forceSoftwareRendering = true; m_readNotifier.setEnabled(true); connect(&m_readNotifier, SIGNAL(activated(int)), SLOT(pipeDataAvailable(int))); } BootupAnimation::~BootupAnimation() { if (m_renderThread) { g_thread_join(m_renderThread); m_renderThread = 0; } } void BootupAnimation::init() { s_frameTime = s_frameTimeSlow; HostBase* host = HostBase::instance(); const HostInfo& info = host->getInfo(); m_ctxt = PGContext::create(); m_ctxt->setDisplay(PPrimary, 0, PFORMAT_8888, 3); // Fill with black m_ctxt->push(); m_ctxt->setStrokeColor(PColor32(0x00, 0x00, 0x00, 0x00)); m_ctxt->setFillColor(PColor32(0x00, 0x00, 0x00, 0xFF)); m_ctxt->drawRect(0, 0, (int) info.displayWidth, (int) info.displayHeight); m_ctxt->pop(); std::string imageRootPath = Settings::LunaSettings()->lunaSystemResourcesPath + "/"; std::string imagePath; imagePath = imageRootPath + "hp-logo.png"; m_logoSurf = PGSurface::createFromPNGFile(imagePath.c_str()); if (!m_logoSurf) g_warning("Failed to load image: %s", imagePath.c_str()); imagePath = imageRootPath + "hp-logo-bright.png"; m_logoBrightSurf = PGSurface::createFromPNGFile(imagePath.c_str()); if (!m_logoBrightSurf) g_warning("Failed to load image: %s", imagePath.c_str()); imagePath = imageRootPath + "activity-static.png"; m_activityStaticSurf = PGSurface::createFromPNGFile(imagePath.c_str()); if (!m_activityStaticSurf) g_warning("Failed to load image: %s", imagePath.c_str()); imagePath = imageRootPath + "activity-spinner.png"; m_activitySpinnerSurf = PGSurface::createFromPNGFile(imagePath.c_str()); if (!m_activitySpinnerSurf) g_warning("Failed to load image: %s", imagePath.c_str()); imagePath = imageRootPath + "activity-progress.png"; m_activityProgressSurf = PGSurface::createFromPNGFile(imagePath.c_str()); if (!m_activityProgressSurf) g_warning("Failed to load image: %s", imagePath.c_str()); const char* fontName = Settings::LunaSettings()->fontBootupAnimation.c_str(); m_font = PGFont::createFromFile(fontName, s_fontHeight1); if (!m_font) { g_critical("%s: Failed to load font: %s", __PRETTY_FUNCTION__, fontName); } m_fallbackFonts = new PGFallbackFonts(); generateUtf16AndGlyphOffsets(); m_logoScale = 1.0f; m_logoAlpha = 0xFF; m_activityProgress = 0; m_activitySpinner = 0; switch (Settings::LunaSettings()->homeButtonOrientationAngle) { case 90: m_rotation = -90; break; case -90: case 270: m_rotation = 90; break; case 180: m_rotation = 180; break; default: m_rotation = 0; } } void BootupAnimation::deinit() { s_frameTime = s_frameTimeSlow; if (m_ctxt) m_ctxt->releaseRef(); if (m_logoSurf) m_logoSurf->releaseRef(); if (m_logoBrightSurf) m_logoBrightSurf->releaseRef(); if (m_activityStaticSurf) m_activityStaticSurf->releaseRef(); if (m_activitySpinnerSurf) m_activitySpinnerSurf->releaseRef(); if (m_activityProgressSurf) m_activityProgressSurf->releaseRef(); if (m_font) m_font->releaseRef(); delete m_fallbackFonts; m_ctxt = 0; m_logoSurf = 0; m_logoBrightSurf = 0; m_activityStaticSurf = 0; m_activityProgressSurf = 0; m_activitySpinnerSurf = 0; m_font = 0; m_fallbackFonts = 0; m_textLine1.clear(); m_textLine2.clear(); m_glyphOffsetsLine1.clear(); m_glyphOffsetsLine2.clear(); m_widthLine1 = 0; m_widthLine2 = 0; } gpointer BootupAnimation::renderThread(gpointer arg) { BootupAnimation* ptr = (BootupAnimation*) arg; ptr->init(); ptr->renderThread(); ptr->deinit(); return NULL; } void BootupAnimation::renderThread() { while (m_state != StateIdle) { switch (m_state) { case (StateLogo): renderInStateLogo(); break; case (StateActivity): renderInStateActivity(); break; default: break; } sleepMs(s_frameTime); } } void BootupAnimation::renderInStateLogo() { if (!m_logoSurf || !m_logoBrightSurf) return; const int kLowAlpha = 0x00 - 0x80; const int kHighAlpha = 0xFF; static int sCurrAlpha = kLowAlpha; static int sDelta = 0x08; HostBase* host = HostBase::instance(); const HostInfo& info = host->getInfo(); int w = (int) (m_logoSurf->width()); int h = (int) (m_logoSurf->height()); int dx = (info.displayWidth - w) / 2; int dy = (info.displayHeight - h) / 2; int dr = dx + w; int db = dy + h; m_ctxt->push(); m_ctxt->setStrokeColor(PColor32(0x00, 0x00, 0x00, 0x00)); m_ctxt->setFillColor(PColor32(0x00, 0x00, 0x00, 0xFF)); m_ctxt->drawRect(0, 0, (int) info.displayWidth, (int) info.displayHeight); if (m_rotation != 0) { m_ctxt->translate((int)info.displayWidth/2, (int) info.displayHeight/2); m_ctxt->rotate(m_rotation); m_ctxt->translate((int) -info.displayWidth/2, (int) -info.displayHeight/2); } if (m_logoSurf) { m_ctxt->bitblt(m_logoSurf, dx, dy, dr, db); } if (m_logoBrightSurf) { m_ctxt->setFillOpacity(MAX(MIN(sCurrAlpha, 0xFF), 0x00)); m_ctxt->bitblt(m_logoBrightSurf, dx, dy, dr, db); } m_ctxt->pop(); m_ctxt->flip(); sCurrAlpha += sDelta; if (sCurrAlpha <= kLowAlpha) { sDelta = 0x0F; sCurrAlpha = kLowAlpha; } else if (sCurrAlpha >= kHighAlpha) { sDelta = -0x0F; sCurrAlpha = kHighAlpha; } } void BootupAnimation::renderInStateActivity() { if (!m_activityStaticSurf || !m_activitySpinnerSurf || !m_activityProgressSurf) return; const HostInfo& info = HostBase::instance()->getInfo(); int wStatic = (int) (m_activityStaticSurf->width()); int hStatic = (int) (m_activityStaticSurf->height()); int dxStatic = (info.displayWidth - wStatic) / 2; int dyStatic = (info.displayHeight - hStatic) / 2; int wSpinner = (int) (m_activitySpinnerSurf->width()); int hSpinner = (int) (m_activitySpinnerSurf->height()) / s_activitySpinnerTotal; int dxSpinner = (info.displayWidth - wSpinner) / 2; int dySpinner = (info.displayHeight - hSpinner) / 2; m_ctxt->push(); // Fill with black m_ctxt->setStrokeColor(PColor32(0x00, 0x00, 0x00, 0x00)); m_ctxt->setFillColor(PColor32(0x00, 0x00, 0x00, 0xFF)); m_ctxt->drawRect(0, 0, (int) info.displayWidth, (int) info.displayHeight); if (m_rotation != 0) { m_ctxt->translate((int)info.displayWidth/2, (int) info.displayHeight/2); m_ctxt->rotate(m_rotation); m_ctxt->translate((int) -info.displayWidth/2, (int) -info.displayHeight/2); } int progress = m_activityProgress; if (progress == 0) { m_ctxt->bitblt(m_activityStaticSurf, dxStatic, dyStatic, dxStatic + wStatic, dyStatic + hStatic); } else { progress = progress - 1; m_ctxt->bitblt(m_activityProgressSurf, 0, progress * hStatic, wStatic, hStatic + progress * hStatic, dxStatic, dyStatic, dxStatic + wStatic, dyStatic + hStatic); } m_ctxt->bitblt(m_activitySpinnerSurf, 0, m_activitySpinner * hSpinner, wSpinner, hSpinner + m_activitySpinner * hSpinner, dxSpinner, dySpinner, dxSpinner + wSpinner, dySpinner + hSpinner); m_font->setPointSize(s_fontHeight1); m_ctxt->setFont(m_font); int xTextLine1 = (info.displayWidth - m_widthLine1) / 2; int xTextLine2 = (info.displayWidth - m_widthLine2) / 2; int yTextLine1 = (info.displayHeight - s_fontHeight1 * 2); int yTextLine2 = (info.displayHeight - s_fontHeight1); int xTextOffset = 0; int yTextOffset = 0; m_ctxt->setStrokeColor(PColor32(0xFF, 0xFF, 0xFF, 0xC0)); m_ctxt->setFillColor(PColor32(0xFF, 0xFF, 0xFF, 0xC0)); xTextOffset = xTextLine1; yTextOffset = yTextLine1; for (unsigned int i = 0; i < m_textLine1.size(); i++) { m_ctxt->drawCharacter(m_textLine1[i], xTextOffset, yTextOffset); xTextOffset += m_glyphOffsetsLine1[i]; } m_font->setPointSize(s_fontHeight2); m_ctxt->setFont(m_font); m_ctxt->setStrokeColor(PColor32(0xFF, 0xFF, 0xFF, 0x80)); m_ctxt->setFillColor(PColor32(0xFF, 0xFF, 0xFF, 0x80)); xTextOffset = xTextLine2; yTextOffset = yTextLine2; for (unsigned int i = 0; i < m_textLine2.size(); i++) { m_ctxt->drawCharacter(m_textLine2[i], xTextOffset, yTextOffset); xTextOffset += m_glyphOffsetsLine2[i]; } m_ctxt->pop(); m_activitySpinner = (m_activitySpinner + 1) % s_activitySpinnerTotal; if (m_activityProgress == s_activityProgressTotal) { // Fill with black m_ctxt->push(); m_ctxt->setStrokeColor(PColor32(0x00, 0x00, 0x00, 0x00)); m_ctxt->setFillColor(PColor32(0x00, 0x00, 0x00, 0xFF)); m_ctxt->drawRect(0, 0, (int) info.displayWidth, (int) info.displayHeight); m_ctxt->pop(); m_logoScale = 1.0f; m_logoAlpha = 0xFF; m_state = StateLogo; } m_ctxt->flip(); } // static function invoked by the main process to stop the animation void BootupAnimation::stopBootupAnimation() { if(bootAnimPipeFd < 0) return; char message[BOOT_ANIM_MESSAGE_LENGHT]; message[0] = BOOT_ANIM_MESSAGE_END_ANIMATION; ::write(bootAnimPipeFd, message, BOOT_ANIM_MESSAGE_LENGHT); // now wait until the boot animation process exits ::waitpid(bootAnimPid, 0, 0); } // static function invoked by the main process to start the progress part of the animation void BootupAnimation::startActivityAnimation() { if(bootAnimPipeFd < 0) return; char message[BOOT_ANIM_MESSAGE_LENGHT]; message[0] = BOOT_ANIM_MESSAGE_START_PROGRESS; ::write(bootAnimPipeFd, message, BOOT_ANIM_MESSAGE_LENGHT); } // static function invoked by the main process to stop the progress part of the animation void BootupAnimation::stopActivityAnimation() { if(bootAnimPipeFd < 0) return; char message[BOOT_ANIM_MESSAGE_LENGHT]; message[0] = BOOT_ANIM_MESSAGE_END_PROGRESS; ::write(bootAnimPipeFd, message, BOOT_ANIM_MESSAGE_LENGHT); } // static function invoked by the main process to update the progress meter during the animation void BootupAnimation::setActivityAnimationProgress(int val, int total) { if(bootAnimPipeFd < 0) return; char message[BOOT_ANIM_MESSAGE_LENGHT]; message[0] = BOOT_ANIM_MESSAGE_PROGRESS_UPDATE; int* p = (int*)&(message[1]); *p = val; p = (int*)&(message[1 + sizeof(int)]); *p = total; ::write(bootAnimPipeFd, message, BOOT_ANIM_MESSAGE_LENGHT); } void BootupAnimation::start() { init(); luna_assert(m_state == StateIdle); luna_assert(m_renderThread == 0); m_state = StateLogo; m_renderThread = g_thread_create(BootupAnimation::renderThread, this, true, NULL); } void BootupAnimation::stop() { luna_assert(m_state == StateLogo); luna_assert(m_renderThread); s_frameTime = s_frameTimeFast; m_logoAlpha = 0xFF; m_logoScale = 1.0f; m_state = StateIdle; g_thread_join(m_renderThread); m_renderThread = 0; //At this point, the render thread has terminated and we have //done a deinit of all resources. exit exit(0); } void BootupAnimation::startActivity() { luna_assert(m_state == StateLogo); luna_assert(m_renderThread); setActivityProgress(0, 1); m_state = StateActivity; } void BootupAnimation::stopActivity() { luna_assert(m_renderThread); setActivityProgress(1, 1); } void BootupAnimation::setActivityProgress(int val, int total) { val = CLAMP(val, 0, total); m_activityProgress = (int) ::roundf((val * s_activityProgressTotal) / (total * 1.0f)); m_activityProgress = CLAMP(m_activityProgress, 0, s_activityProgressTotal); } void BootupAnimation::pipeDataAvailable(int pipe) { char buffer[BOOT_ANIM_MESSAGE_LENGHT]; int index = 0; char data; while(index < BOOT_ANIM_MESSAGE_LENGHT && (::read(pipe, &(buffer[index]), 1) == 1)) { index++; } if(buffer[0] == BOOT_ANIM_MESSAGE_END_ANIMATION) { stop(); } else if(buffer[0] == BOOT_ANIM_MESSAGE_START_PROGRESS) { startActivity(); } else if(buffer[0] == BOOT_ANIM_MESSAGE_END_PROGRESS) { stopActivity(); } else if(buffer[0] == BOOT_ANIM_MESSAGE_PROGRESS_UPDATE) { int val, total; int* p = (int*)&(buffer[1]); val = *p; p = (int*)&(buffer[1 + sizeof(int)]); total = *p; setActivityProgress(val, total); } } // ==================================================================== BootupAnimationTransition::BootupAnimationTransition() : m_screenPixmap(0) { init(); } BootupAnimationTransition::~BootupAnimationTransition() { } void BootupAnimationTransition::init() { HostBase* host = HostBase::instance(); const HostInfo& info = host->getInfo(); m_bounds = QRect(-info.displayWidth/2, -info.displayHeight/2, info.displayWidth, info.displayHeight); std::string imageRootPath = Settings::LunaSettings()->lunaSystemResourcesPath + "/"; std::string imagePath; imagePath = imageRootPath + "hp-logo.png"; QPixmap logoPixmap(imagePath.c_str()); if (logoPixmap.isNull()) g_warning("Failed to load image: %s", imagePath.c_str()); m_screenPixmap = new QPixmap(info.displayWidth, info.displayHeight); m_rotation = Settings::LunaSettings()->homeButtonOrientationAngle; // prepare the full screen pixmap for the animation QPainter painter(m_screenPixmap); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); painter.fillRect(QRect(0, 0, info.displayWidth, info.displayHeight), QColor(0x00, 0x00, 0x00, 0xFF)); if (m_rotation != 0) { painter.translate(info.displayWidth/2, info.displayHeight/2); painter.rotate(m_rotation); painter.translate(-info.displayWidth/2, -info.displayHeight/2); } painter.drawPixmap(info.displayWidth/2 - logoPixmap.width()/ 2, info.displayHeight/2 - logoPixmap.height()/ 2, logoPixmap); painter.setRenderHint(QPainter::SmoothPixmapTransform, false); painter.end(); m_opacityAnimationPtr = new QPropertyAnimation(); m_opacityAnimationPtr->setPropertyName("opacity"); m_opacityAnimationPtr->setEasingCurve(QEasingCurve::Linear); m_opacityAnimationPtr->setTargetObject(this); m_opacityAnimationPtr->setDuration(kFadeAnimDuration); m_opacityAnimationPtr->setStartValue(1.0); m_opacityAnimationPtr->setEndValue(0.0); m_scaleAnimationPtr = new QPropertyAnimation(); m_scaleAnimationPtr->setPropertyName("scale"); m_scaleAnimationPtr->setEasingCurve(QEasingCurve::Linear); m_scaleAnimationPtr->setTargetObject(this); m_scaleAnimationPtr->setDuration(kFadeAnimDuration); m_scaleAnimationPtr->setStartValue(1.0); m_scaleAnimationPtr->setEndValue(2.0); m_fadeAnimationGroupPtr = new QParallelAnimationGroup(); m_fadeAnimationGroupPtr->addAnimation(m_opacityAnimationPtr); m_fadeAnimationGroupPtr->addAnimation(m_scaleAnimationPtr); connect(m_fadeAnimationGroupPtr, SIGNAL(finished()), SLOT(fadeAnimationFinished())); } void BootupAnimationTransition::deinit() { if(m_screenPixmap) { delete m_screenPixmap; m_screenPixmap = 0; } if(!m_fadeAnimationGroupPtr.isNull()) { m_fadeAnimationGroupPtr->stop(); delete m_fadeAnimationGroupPtr; } if(!m_opacityAnimationPtr.isNull()) { m_opacityAnimationPtr->stop(); delete m_opacityAnimationPtr; } if(!m_scaleAnimationPtr.isNull()) { m_scaleAnimationPtr->stop(); delete m_scaleAnimationPtr; } } void BootupAnimationTransition::start() { luna_assert(!m_fadeAnimationGroupPtr.isNull()); m_fadeAnimationGroupPtr->start(); } QRectF BootupAnimationTransition::boundingRect() const { return m_bounds; } void BootupAnimationTransition::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { if (!m_screenPixmap) return; painter->setRenderHint(QPainter::SmoothPixmapTransform, true); painter->setCompositionMode(QPainter::CompositionMode_SourceOver); painter->drawPixmap(-m_screenPixmap->width()/ 2, -m_screenPixmap->height()/ 2, *m_screenPixmap); painter->setRenderHint(QPainter::SmoothPixmapTransform, false); } void BootupAnimationTransition::fadeAnimationFinished() { deinit(); // self-destruct delete this; } void BootupAnimation::generateUtf16AndGlyphOffsets() { m_textLine1 = convertToUtf16(LOCALIZED(s_line1)); m_textLine2 = convertToUtf16(LOCALIZED(s_line2)); m_glyphOffsetsLine1 = getGlyphOffsets(m_textLine1, s_fontHeight1); m_glyphOffsetsLine2 = getGlyphOffsets(m_textLine2, s_fontHeight2); m_widthLine1 = 0; for (unsigned int i = 0; i < m_glyphOffsetsLine1.size(); i++) m_widthLine1 += m_glyphOffsetsLine1[i]; m_widthLine2 = 0; for (unsigned int i = 0; i < m_glyphOffsetsLine2.size(); i++) m_widthLine2 += m_glyphOffsetsLine2[i]; } std::vector<gunichar2> BootupAnimation::convertToUtf16(const std::string& s) const { glong charsWritten = 0; gunichar2* utf16Str = g_utf8_to_utf16(s.c_str(), -1, NULL, &charsWritten, NULL); std::vector<gunichar2> res; if (!utf16Str || charsWritten <= 0) { g_warning("%s: Failed to convert banner message to utf16: %s", __PRETTY_FUNCTION__, s.c_str()); res.resize(s.size()); for (unsigned int i = 0; i < s.size(); i++) { res[i] = s[i]; } } else { res.resize(charsWritten); for (int i = 0; i < charsWritten; i++) { res[i] = utf16Str[i]; } } g_free(utf16Str); return res; } std::vector<int> BootupAnimation::getGlyphOffsets(const std::vector<gunichar2>& s, int height) const { std::vector<int> res; res.resize(s.size()); m_font->setPointSize(height, true); for (unsigned int i = 0; i < s.size(); i++) res[i] = m_font->width(s[i], static_cast<PGContext*>(m_fallbackFonts->sharedFontMeasuringContext())); return res; } void BootupAnimation::paintEvent(QPaintEvent *event) { }
25.798128
124
0.724258
[ "render", "vector" ]
5a7cb0ca4c914238f9225f01263f6cbafdccddc6
5,926
cpp
C++
3rdparty/OculusSDKv1_8/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp
PlusToolkit/OvrvisionPro
ed64cade144ce47d17423369476fb43ea69b124d
[ "MIT" ]
1
2017-10-27T14:01:39.000Z
2017-10-27T14:01:39.000Z
OculusSDK/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp
Ybalrid/AnnwvynDeps
3309b126e6e501df5bd7f617cf3c47941b0754e5
[ "CECILL-B" ]
null
null
null
OculusSDK/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp
Ybalrid/AnnwvynDeps
3309b126e6e501df5bd7f617cf3c47941b0754e5
[ "CECILL-B" ]
null
null
null
/************************************************************************************ Filename : Render_GL_Win32 Device.cpp Content : Win32 OpenGL Device implementation Created : September 10, 2012 Authors : Andrew Reisse, Michael Antonov, David Borel Copyright : Copyright 2012 Oculus VR, LLC. 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 "Render_GL_Win32_Device.h" #include "OVR_CAPI_GL.h" #include <stdlib.h> #include <dwmapi.h> namespace OVR { namespace Render { namespace GL { namespace Win32 { #pragma warning(disable : 4995) // The compiler encountered a function that was marked with pragma deprecated. // ***** GL::Win32::RenderDevice RenderDevice::RenderDevice(ovrSession session, const Render::RendererParams& p, HWND win, HGLRC gl) : GL::RenderDevice(session, p) , Window(win) , WglContext(gl) { OVR_UNUSED(p); } // Implement static initializer function to create this class. Render::RenderDevice* RenderDevice::CreateDevice(ovrSession session, const RendererParams& rp, void* oswnd, ovrGraphicsLuid luid) { // FIXME: Figure out how to best match luid's in OpenGL OVR_UNUSED(luid); HWND hwnd = (HWND)oswnd; HDC dc = GetDC(hwnd); PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBFunc = NULL; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARBFunc = NULL; { // First create a context for the purpose of getting access to wglChoosePixelFormatARB / wglCreateContextAttribsARB. PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.iPixelType = PFD_TYPE_RGBA; pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; pfd.cColorBits = 32; pfd.cDepthBits = 16; int pf = ChoosePixelFormat(dc, &pfd); if (!pf) { ReleaseDC(hwnd, dc); return NULL; } if (!SetPixelFormat(dc, pf, &pfd)) { ReleaseDC(hwnd, dc); return NULL; } HGLRC context = wglCreateContext(dc); if (!wglMakeCurrent(dc, context)) { wglDeleteContext(context); ReleaseDC(hwnd, dc); return NULL; } wglChoosePixelFormatARBFunc = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); wglCreateContextAttribsARBFunc = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); OVR_ASSERT(wglChoosePixelFormatARBFunc && wglCreateContextAttribsARBFunc); wglDeleteContext(context); } // Now create the real context that we will be using. int iAttributes[] = { //WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 16, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, GL_TRUE, 0, 0}; float fAttributes[] = {0,0}; int pf = 0; UINT numFormats = 0; if (!wglChoosePixelFormatARBFunc(dc, iAttributes, fAttributes, 1, &pf, &numFormats)) { ReleaseDC(hwnd, dc); return NULL; } PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(pfd)); if (!SetPixelFormat(dc, pf, &pfd)) { ReleaseDC(hwnd, dc); return NULL; } GLint attribs[16]; int attribCount = 0; int flags = 0; int profileFlags = 0; // Version if(rp.GLMajorVersion) { attribs[attribCount++] = WGL_CONTEXT_MAJOR_VERSION_ARB; attribs[attribCount++] = rp.GLMajorVersion; attribs[attribCount++] = WGL_CONTEXT_MINOR_VERSION_ARB; attribs[attribCount++] = rp.GLMinorVersion; } // Flags if(rp.DebugEnabled) flags |= WGL_CONTEXT_DEBUG_BIT_ARB; if(rp.GLForwardCompatibleProfile) flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; if(flags) { attribs[attribCount++] = WGL_CONTEXT_FLAGS_ARB; attribs[attribCount++] = flags; } // Profile flags if(rp.GLCoreProfile) profileFlags |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB; else if(rp.GLCompatibilityProfile) profileFlags |= WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; if(profileFlags) { attribs[attribCount++] = WGL_CONTEXT_PROFILE_MASK_ARB; attribs[attribCount++] = profileFlags; } attribs[attribCount] = 0; HGLRC context = wglCreateContextAttribsARBFunc(dc, 0, attribs); if (!wglMakeCurrent(dc, context)) { wglDeleteContext(context); ReleaseDC(hwnd, dc); return NULL; } InitGLExtensions(); return new RenderDevice(session, rp, hwnd, context); } bool RenderDevice::Present(bool useVsync) { BOOL success; int swapInterval = (useVsync) ? 1 : 0; if (wglGetSwapIntervalEXT() != swapInterval) wglSwapIntervalEXT(swapInterval); HDC dc = GetDC(Window); success = SwapBuffers(dc); ReleaseDC(Window, dc); OVR_ASSERT(success == TRUE); return success == TRUE; } void RenderDevice::Shutdown() { //Release any remaining GL resources. GL::RenderDevice::Shutdown(); if (WglContext) { wglMakeCurrent(NULL,NULL); wglDeleteContext(WglContext); WglContext = NULL; Window = NULL; } } bool RenderDevice::SetParams(const RendererParams& newParams) { Params = newParams; //TODO: Apply changes now. return true; } }}}}
27.308756
129
0.664867
[ "render" ]
5a803791a0c9fdc9cfa12168c997679fece72718
2,320
cpp
C++
src/main.cpp
rogerthat52/snackman
7d0bf2fd1a8343f44b1a0ab61be16f6ace35af95
[ "MIT" ]
null
null
null
src/main.cpp
rogerthat52/snackman
7d0bf2fd1a8343f44b1a0ab61be16f6ace35af95
[ "MIT" ]
null
null
null
src/main.cpp
rogerthat52/snackman
7d0bf2fd1a8343f44b1a0ab61be16f6ace35af95
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> #include "tilemap.h" #include "sdlecs.h" #include "chara.h" // main file ayy // this is a lib / framework for learning c++ and making games // all code (except linked libraries) was all written by: // --------- ROGER HUNTLEY II --------- // // ----- roger.a.huntley@gmail.com ---- // // ----------- @rogerthat52 ----------- // // -------------- A.K.A. -------------- // // ----------- @YoungsDitch ----------- // int main(int argv, char** args) { // init SDL SDL_Window* window = SDL_CreateWindow("Snackman early dev", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 480, 272, 0); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_PRESENTVSYNC); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); // instantiate main scene Scene mainScene(renderer); // create new tilemap entity Entity& tileMap = mainScene.createEntity<TileMapEntity>("res/map1.tmx"); mainScene.setSpecialEntity("tilemap", tileMap); // create pacman entity Entity& pacman = mainScene.createEntity<PacmanEntity>(16, 64); // create ghost entities Entity& ghost1 = mainScene.createEntity<GhostEntity>(64, 32); Entity& ghost2 = mainScene.createEntity<GhostEntity>(32, 64); Entity& ghost3 = mainScene.createEntity<GhostEntity>(128, 128); Entity& ghost4 = mainScene.createEntity<GhostEntity>(128, 64); // register systems mainScene.registerSystem<TileMapDataSystem>(); mainScene.registerSystem<TileMapRenderSystem>(); // chararacter stuff mainScene.registerSystem<PlayerControllerSystem>(); mainScene.registerSystem<AIControllerSystem>(); mainScene.registerSystem<CharacterControlSystem>(); mainScene.registerSystem<CharacterRenderSystem>(); SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_PNG); SDLEventComponent& event = mainScene.getComponent<SDLEventComponent>(); while (!event.quit) { // INIT NEW COMPONENTS mainScene.init(); // UPDATE COMPONENTS mainScene.update(); // RENDER COMPONENTS mainScene.render(); } // quit SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
30.526316
143
0.671983
[ "render" ]
5a813cf6bd495bbe06518a3cc63bbd0fb8c9955f
6,437
cpp
C++
src/transformations/ssa_generator.cpp
Sokolmish/diploma
8441b17f430bbdce8fd1825329c9e53e755470b7
[ "MIT" ]
null
null
null
src/transformations/ssa_generator.cpp
Sokolmish/diploma
8441b17f430bbdce8fd1825329c9e53e755470b7
[ "MIT" ]
null
null
null
src/transformations/ssa_generator.cpp
Sokolmish/diploma
8441b17f430bbdce8fd1825329c9e53e755470b7
[ "MIT" ]
null
null
null
#include "ssa_generator.hpp" #include "cfg_cleaner.hpp" #include <vector> #include <stack> SSA_Generator::SSA_Generator(CFGraph in_cfg) : IRTransformer(std::move(in_cfg)) { gInfo = std::make_unique<GraphInfo>(cfg); placePhis(); versionize(); gInfo.reset(); CfgCleaner cleaner(std::move(cfg)); cleaner.removeUselessNodes(); cleaner.removeNops(); cfg = std::move(cleaner).moveCfg(); } // PHIs placing void SSA_Generator::placePhis() { int counter = 0; std::set<int> visited; makePostOrder(visited, counter, cfg.entryBlockId); makeVerticesDF(); // For each variable find, where a value assigned to it std::map<IRval, std::set<int>> varsDefSet; for (auto const &[bId, block] : cfg.getBlocks()) for (IRval const &def : block.getDefinitions()) varsDefSet[def].insert(bId); for (auto const &[var, varDefs] : varsDefSet) { std::set<int> JP = getSetDFP(varDefs); // JP == DFP (theorem) for (int blockId : JP) { cfg.block(blockId).addNewPhiNode(var); } } } void SSA_Generator::makePostOrder(std::set<int> &visited, int &counter, int cur) { visited.insert(cur); for (int nextId : cfg.block(cur).next) if (!visited.contains(nextId)) makePostOrder(visited, counter, nextId); postOrder.insert({ cur, counter++ }); } void SSA_Generator::makeVerticesDF() { // Sort blocks by post order std::vector<int> sortedIds; for (auto const &[bId, block] : cfg.getBlocks()) if (postOrder.contains(bId)) // TODO: get set from makePostOrder sortedIds.push_back(bId); std::sort(sortedIds.begin(), sortedIds.end(), [this](int a, int b) { return postOrder.at(a) < postOrder.at(b); }); for (int xId : sortedIds) { auto it = verticesDF.emplace(xId, std::set<int>()); auto &curSet = it.first->second; for (int yId : cfg.block(xId).next) { if (gInfo->getIdom(yId) != xId) { curSet.insert(yId); } } for (int z : gInfo->getChildren(xId)) { for (int y : verticesDF.at(z)) { if (gInfo->getIdom(y) != xId) { curSet.insert(y); } } } } } std::set<int> SSA_Generator::getSetDF(const std::set<int> &S) const { std::set<int> res; for (int x : S) res.insert(verticesDF.at(x).cbegin(), verticesDF.at(x).cend()); return res; } std::set<int> SSA_Generator::getSetDFP(const std::set<int> &S) const { std::set<int> res; std::set<int> DFP; bool changed = true; while (changed) { changed = false; std::set<int> tmp = S; tmp.insert(DFP.cbegin(), DFP.cend()); DFP = getSetDF(tmp); if (res != DFP) { res = DFP; changed = true; } } return res; } // Versioning void SSA_Generator::versionize() { // Collect variables from graph because its was not passed in CFG std::set<IRval> variables; for (auto const &[bId, block] : cfg.getBlocks()) { for (const IRval& def : block.getDefinitions()) variables.insert(def); for (const IRval& ref : block.getReferences()) variables.insert(ref); } for (const IRval& var : variables) { traverseForVar(cfg.entryBlockId, var); } } void SSA_Generator::traverseForVar(int startBlockId, const IRval &var) { std::stack<IRval> versions; // Maybe reuse this stack for different variables? versions.push(IRval::createUndef(var.getType())); // In case of uninitialized variable // A phis results std::set<IRval> phiRess; phiRess.insert(var); // Before versioning all phis retruns var enum { SSAV_REC_CALL = false, SSAV_ROLLBACK = true }; std::stack<std::pair<int, bool>> stack; stack.push(std::make_pair(startBlockId, SSAV_REC_CALL)); while (!stack.empty()) { if (stack.top().second == SSAV_ROLLBACK) { int rollback = stack.top().first; while (rollback--) { versions.pop(); } stack.pop(); continue; } int blockId = stack.top().first; stack.pop(); auto &curBlock = cfg.block(blockId); int rollbackCnt = 0; // Phis for (auto &phiNode : curBlock.phis) { if (phiNode.res == var) { IRval rg = cfg.getParentUnit()->createReg(var.getType()); phiNode.res = rg; versions.push(std::move(rg)); phiRess.insert(*phiNode.res); rollbackCnt++; break; } } // General nodes for (auto &node : curBlock.body) { for (IRval *arg : node.body->getArgs()) { if (*arg == var) { IRval v = versions.top(); // CLion warnings... *arg = std::move(v); } } if (node.res == var) { IRval rg = cfg.getParentUnit()->createReg(var.getType()); node.res = rg; versions.push(std::move(rg)); rollbackCnt++; } } // Terminator if (curBlock.termNode.has_value()) { auto &terminator = dynamic_cast<IR_ExprTerminator &>(*curBlock.termNode->body); if (terminator.arg == var) { terminator.arg = versions.top(); } } // Set phis args in next blocks for (int nextId : curBlock.next) { auto &nextBlock = cfg.block(nextId); int j = -1; for (size_t k = 0; k < nextBlock.prev.size(); k++) { if (nextBlock.prev.at(k) == blockId) { j = static_cast<int>(k); break; } } for (auto &phiNode : nextBlock.phis) { if (phiNode.res && phiRess.contains(*phiNode.res)) { IRval phiArg = versions.top(); auto &phiExpr = dynamic_cast<IR_ExprPhi &>(*phiNode.body); phiExpr.args.emplace(j, phiArg); break; } } } stack.push({ rollbackCnt, SSAV_ROLLBACK }); for (int domChild : gInfo->getChildren(blockId)) stack.push({ domChild, SSAV_REC_CALL }); } }
30.220657
91
0.53441
[ "vector" ]
5a85d642abb403efb3125c1a5a64f960135150e8
865
hpp
C++
application/include/camera_node.hpp
luigielbambino/CG_Lab_Titz120003Alvarez119446
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
[ "MIT" ]
null
null
null
application/include/camera_node.hpp
luigielbambino/CG_Lab_Titz120003Alvarez119446
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
[ "MIT" ]
null
null
null
application/include/camera_node.hpp
luigielbambino/CG_Lab_Titz120003Alvarez119446
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
[ "MIT" ]
null
null
null
// Camera Node Header, Functions declarations #ifndef CAMERA_NODE_HPP #define CAMERA_NODE_HPP #include <iostream> using namespace std; #include "application.hpp" #include "model.hpp" #include "structs.hpp" #include <list> #include "node.hpp" class CameraNode : public Node{ public: // Default constructor CameraNode(); // Destructor ~CameraNode(); // getters and setters functions bool getPerspective(); // Return state of perspective bool getEnabled(); // Return state of ableness void setEnabled(bool); // set state of enable glm::fmat4 getProjectionMatrix(); // Return projection matrix void setProjectionMatrix(glm::fmat4); // Set projection matrix private: // Member attributes bool isPerspective; bool isEnabled; glm::fmat4 projectionMatrix; }; #endif
19.222222
45
0.677457
[ "model" ]
5a8859364e2c5fd4526636feb5ee3ffe98e2252e
898
cpp
C++
test18_3.cpp
chenshiyang/C-Primer-5ed-solution
54ce8670e7ad6d82bf62c18523a5be175325276d
[ "Apache-2.0" ]
null
null
null
test18_3.cpp
chenshiyang/C-Primer-5ed-solution
54ce8670e7ad6d82bf62c18523a5be175325276d
[ "Apache-2.0" ]
null
null
null
test18_3.cpp
chenshiyang/C-Primer-5ed-solution
54ce8670e7ad6d82bf62c18523a5be175325276d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <memory> using namespace std; void exercise1(int *b, int *e) { try { vector<int> v(b, e); int *p = new int[v.size()]; ifstream in("ins"); throw p; } catch(int *p) { delete[] p; } } void exercise2(int *b, int *e) { try { vector<int> v(b, e); unique_ptr<int[]> p(new int[v.size()]); ifstream in("ins"); } catch(...) { } } void exercise3(int *b, int *e) { vector<int> v(b, e); int* p = new int[v.size()]; ifstream in("ins"); try { throw p; } catch(...) { delete[] p; } delete[] p; } int main() { int a[] = {1, 2, 3, 4}; int *b = std::begin(a), *e = std::end(a); exercise1(b, e); exercise2(b, e); exercise3(b, e); return 0; }
18.326531
48
0.447661
[ "vector" ]
5a8f7d57fb2bbad4eac0914d27f713f7d7bd8482
4,969
cpp
C++
modules/xfeatures2d/test/test_logos_matcher.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/xfeatures2d/test/test_logos_matcher.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/xfeatures2d/test/test_logos_matcher.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "test_precomp.hpp" namespace opencv_test { namespace { static void loadKeypoints(const std::string& vP_path, const std::string& oP_path, const std::string& sP_path, const std::string& w_path, std::vector<cv::KeyPoint>& keypoints, std::vector<int>& nn) { { std::ifstream file(vP_path.c_str()); if (file.is_open()) { float x = 0, y = 0; while (file >> x >> y) { keypoints.push_back(cv::KeyPoint(x, y, 0)); } } } { std::ifstream file(oP_path.c_str()); if (file.is_open()) { float orientation = 0; size_t idx = 0; while (file >> orientation) { keypoints[idx].angle = static_cast<float>(orientation * 180.0 / CV_PI); idx++; } } } { std::ifstream file(sP_path.c_str()); if (file.is_open()) { float scale = 0; size_t idx = 0; while (file >> scale) { keypoints[idx].size = scale; idx++; } } } { std::ifstream file(w_path.c_str()); if (file.is_open()) { int neighborIdx = 0; while (file >> neighborIdx) { nn.push_back(neighborIdx); } } } ASSERT_TRUE(!keypoints.empty()); } static void loadGroundTruth(const std::string& d1_path, const std::string& b1_path, std::vector<cv::DMatch>& groundTruth) { std::vector<int> d1_vec; { std::ifstream file(d1_path.c_str()); if (file.is_open()) { int idx = 0; while (file >> idx) { d1_vec.push_back(idx-1); } } } std::vector<int> b1_vec; { std::ifstream file(b1_path.c_str()); if (file.is_open()) { int idx = 0; while (file >> idx) { b1_vec.push_back(idx-1); } } } ASSERT_TRUE(!d1_vec.empty()); ASSERT_EQ(d1_vec.size(), b1_vec.size()); for (size_t i = 0; i < d1_vec.size(); i++) { groundTruth.push_back(cv::DMatch(d1_vec[i], b1_vec[i], 0)); } } TEST(XFeatures2d_LogosMatcher, logos_matcher_regression) { const std::string vP1_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/vP1.txt"); const std::string oP1_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/oP1.txt"); const std::string sP1_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/sP1.txt"); const std::string w1_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/w1.txt"); const std::string vP2_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/vP2.txt"); const std::string oP2_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/oP2.txt"); const std::string sP2_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/sP2.txt"); const std::string w2_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/w2.txt"); std::vector<cv::KeyPoint> keypoints1, keypoints2; std::vector<int> nn1, nn2; loadKeypoints(vP1_path, oP1_path, sP1_path, w1_path, keypoints1, nn1); loadKeypoints(vP2_path, oP2_path, sP2_path, w2_path, keypoints2, nn2); std::vector<cv::DMatch> matchesLogos; matchLOGOS(keypoints1, keypoints2, nn1, nn2, matchesLogos); std::vector<cv::DMatch> groundTruth; const std::string d1_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/d1.txt"); const std::string b1_path = cvtest::findDataFile("detectors_descriptors_evaluation/matching/LOGOS/b1.txt"); loadGroundTruth(d1_path, b1_path, groundTruth); int correctMatches = 0; for (size_t i = 0; i < matchesLogos.size(); i++) { for (size_t j = 0; j < groundTruth.size(); j++) { if (groundTruth[j].queryIdx == matchesLogos[i].queryIdx && groundTruth[j].trainIdx == matchesLogos[j].trainIdx) { correctMatches++; break; } } } ASSERT_EQ(static_cast<int>(groundTruth.size()), correctMatches) << "groundTruth: " << groundTruth.size() << " ; matchesLogos: " << matchesLogos.size() << " ; correctMatches: " << correctMatches; } }} // namespace
32.477124
113
0.562487
[ "vector" ]
5a9488407378cf119bb89f18fb9d8de81387d35c
104,737
cc
C++
02-dependency/lib/RPC/Input.pb.cc
ZHYfeng/2018_dependency
42a2226d905862669d3f704398a943d49c707cfb
[ "Apache-2.0" ]
5
2022-03-08T06:32:13.000Z
2022-03-28T02:02:44.000Z
02-dependency/lib/RPC/Input.pb.cc
ZHYfeng/2018_dependency
42a2226d905862669d3f704398a943d49c707cfb
[ "Apache-2.0" ]
null
null
null
02-dependency/lib/RPC/Input.pb.cc
ZHYfeng/2018_dependency
42a2226d905862669d3f704398a943d49c707cfb
[ "Apache-2.0" ]
2
2022-03-08T06:32:16.000Z
2022-03-27T17:54:03.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Input.proto #include "Input.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.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> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace dra { constexpr Call_AddressEntry_DoNotUse::Call_AddressEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct Call_AddressEntry_DoNotUseDefaultTypeInternal { constexpr Call_AddressEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~Call_AddressEntry_DoNotUseDefaultTypeInternal() {} union { Call_AddressEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT Call_AddressEntry_DoNotUseDefaultTypeInternal _Call_AddressEntry_DoNotUse_default_instance_; constexpr Call::Call( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : address_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) , idx_(0u){} struct CallDefaultTypeInternal { constexpr CallDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~CallDefaultTypeInternal() {} union { Call _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT CallDefaultTypeInternal _Call_default_instance_; constexpr Input_CallEntry_DoNotUse::Input_CallEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct Input_CallEntry_DoNotUseDefaultTypeInternal { constexpr Input_CallEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~Input_CallEntry_DoNotUseDefaultTypeInternal() {} union { Input_CallEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT Input_CallEntry_DoNotUseDefaultTypeInternal _Input_CallEntry_DoNotUse_default_instance_; constexpr Input_UncoveredAddressEntry_DoNotUse::Input_UncoveredAddressEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct Input_UncoveredAddressEntry_DoNotUseDefaultTypeInternal { constexpr Input_UncoveredAddressEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~Input_UncoveredAddressEntry_DoNotUseDefaultTypeInternal() {} union { Input_UncoveredAddressEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT Input_UncoveredAddressEntry_DoNotUseDefaultTypeInternal _Input_UncoveredAddressEntry_DoNotUse_default_instance_; constexpr Input_WriteAddressEntry_DoNotUse::Input_WriteAddressEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct Input_WriteAddressEntry_DoNotUseDefaultTypeInternal { constexpr Input_WriteAddressEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~Input_WriteAddressEntry_DoNotUseDefaultTypeInternal() {} union { Input_WriteAddressEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT Input_WriteAddressEntry_DoNotUseDefaultTypeInternal _Input_WriteAddressEntry_DoNotUse_default_instance_; constexpr Input::Input( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : call_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) , paths_() , uncovered_address_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) , write_address_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) , sig_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , program_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , program_before_mini_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , stable_(0u) , number_conditions_(0u) , number_conditions_dependency_(0u) , stat_(0) {} struct InputDefaultTypeInternal { constexpr InputDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~InputDefaultTypeInternal() {} union { Input _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT InputDefaultTypeInternal _Input_default_instance_; constexpr Inputs::Inputs( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : input_(){} struct InputsDefaultTypeInternal { constexpr InputsDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~InputsDefaultTypeInternal() {} union { Inputs _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT InputsDefaultTypeInternal _Inputs_default_instance_; constexpr Path::Path( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : address_() , _address_cached_byte_size_(0){} struct PathDefaultTypeInternal { constexpr PathDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~PathDefaultTypeInternal() {} union { Path _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PathDefaultTypeInternal _Path_default_instance_; constexpr Paths_PathEntry_DoNotUse::Paths_PathEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct Paths_PathEntry_DoNotUseDefaultTypeInternal { constexpr Paths_PathEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~Paths_PathEntry_DoNotUseDefaultTypeInternal() {} union { Paths_PathEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT Paths_PathEntry_DoNotUseDefaultTypeInternal _Paths_PathEntry_DoNotUse_default_instance_; constexpr Paths::Paths( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : path_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}){} struct PathsDefaultTypeInternal { constexpr PathsDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~PathsDefaultTypeInternal() {} union { Paths _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PathsDefaultTypeInternal _Paths_default_instance_; constexpr UnstableInput_AddressEntry_DoNotUse::UnstableInput_AddressEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct UnstableInput_AddressEntry_DoNotUseDefaultTypeInternal { constexpr UnstableInput_AddressEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~UnstableInput_AddressEntry_DoNotUseDefaultTypeInternal() {} union { UnstableInput_AddressEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT UnstableInput_AddressEntry_DoNotUseDefaultTypeInternal _UnstableInput_AddressEntry_DoNotUse_default_instance_; constexpr UnstableInput::UnstableInput( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : unstable_path_() , address_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) , sig_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , program_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){} struct UnstableInputDefaultTypeInternal { constexpr UnstableInputDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~UnstableInputDefaultTypeInternal() {} union { UnstableInput _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT UnstableInputDefaultTypeInternal _UnstableInput_default_instance_; constexpr UnstableInputs_UnstableInputEntry_DoNotUse::UnstableInputs_UnstableInputEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){} struct UnstableInputs_UnstableInputEntry_DoNotUseDefaultTypeInternal { constexpr UnstableInputs_UnstableInputEntry_DoNotUseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~UnstableInputs_UnstableInputEntry_DoNotUseDefaultTypeInternal() {} union { UnstableInputs_UnstableInputEntry_DoNotUse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT UnstableInputs_UnstableInputEntry_DoNotUseDefaultTypeInternal _UnstableInputs_UnstableInputEntry_DoNotUse_default_instance_; constexpr UnstableInputs::UnstableInputs( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : unstable_input_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}){} struct UnstableInputsDefaultTypeInternal { constexpr UnstableInputsDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~UnstableInputsDefaultTypeInternal() {} union { UnstableInputs _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT UnstableInputsDefaultTypeInternal _UnstableInputs_default_instance_; } // namespace dra static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_Input_2eproto[14]; static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_Input_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_Input_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_Input_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::dra::Call_AddressEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::Call_AddressEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Call_AddressEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::Call_AddressEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::Call, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Call, idx_), PROTOBUF_FIELD_OFFSET(::dra::Call, address_), PROTOBUF_FIELD_OFFSET(::dra::Input_CallEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::Input_CallEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Input_CallEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::Input_CallEntry_DoNotUse, value_), 0, 1, PROTOBUF_FIELD_OFFSET(::dra::Input_UncoveredAddressEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::Input_UncoveredAddressEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Input_UncoveredAddressEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::Input_UncoveredAddressEntry_DoNotUse, value_), 0, 1, PROTOBUF_FIELD_OFFSET(::dra::Input_WriteAddressEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::Input_WriteAddressEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Input_WriteAddressEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::Input_WriteAddressEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::Input, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Input, sig_), PROTOBUF_FIELD_OFFSET(::dra::Input, program_), PROTOBUF_FIELD_OFFSET(::dra::Input, call_), PROTOBUF_FIELD_OFFSET(::dra::Input, stable_), PROTOBUF_FIELD_OFFSET(::dra::Input, paths_), PROTOBUF_FIELD_OFFSET(::dra::Input, number_conditions_), PROTOBUF_FIELD_OFFSET(::dra::Input, number_conditions_dependency_), PROTOBUF_FIELD_OFFSET(::dra::Input, stat_), PROTOBUF_FIELD_OFFSET(::dra::Input, uncovered_address_), PROTOBUF_FIELD_OFFSET(::dra::Input, write_address_), PROTOBUF_FIELD_OFFSET(::dra::Input, program_before_mini_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::Inputs, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Inputs, input_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::Path, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Path, address_), PROTOBUF_FIELD_OFFSET(::dra::Paths_PathEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::Paths_PathEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Paths_PathEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::Paths_PathEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::Paths, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::Paths, path_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInput_AddressEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInput_AddressEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::UnstableInput_AddressEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInput_AddressEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::UnstableInput, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::UnstableInput, sig_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInput, program_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInput, unstable_path_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInput, address_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInputs_UnstableInputEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInputs_UnstableInputEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::UnstableInputs_UnstableInputEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::dra::UnstableInputs_UnstableInputEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::dra::UnstableInputs, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::dra::UnstableInputs, unstable_input_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 8, -1, sizeof(::dra::Call_AddressEntry_DoNotUse)}, { 10, -1, -1, sizeof(::dra::Call)}, { 18, 26, -1, sizeof(::dra::Input_CallEntry_DoNotUse)}, { 28, 36, -1, sizeof(::dra::Input_UncoveredAddressEntry_DoNotUse)}, { 38, 46, -1, sizeof(::dra::Input_WriteAddressEntry_DoNotUse)}, { 48, -1, -1, sizeof(::dra::Input)}, { 65, -1, -1, sizeof(::dra::Inputs)}, { 72, -1, -1, sizeof(::dra::Path)}, { 79, 87, -1, sizeof(::dra::Paths_PathEntry_DoNotUse)}, { 89, -1, -1, sizeof(::dra::Paths)}, { 96, 104, -1, sizeof(::dra::UnstableInput_AddressEntry_DoNotUse)}, { 106, -1, -1, sizeof(::dra::UnstableInput)}, { 116, 124, -1, sizeof(::dra::UnstableInputs_UnstableInputEntry_DoNotUse)}, { 126, -1, -1, sizeof(::dra::UnstableInputs)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Call_AddressEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Call_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Input_CallEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Input_UncoveredAddressEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Input_WriteAddressEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Input_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Inputs_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Path_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Paths_PathEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_Paths_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_UnstableInput_AddressEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_UnstableInput_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_UnstableInputs_UnstableInputEntry_DoNotUse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::dra::_UnstableInputs_default_instance_), }; const char descriptor_table_protodef_Input_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\013Input.proto\022\003dra\"l\n\004Call\022\013\n\003idx\030\001 \001(\r\022" "\'\n\007address\030\002 \003(\0132\026.dra.Call.AddressEntry" "\032.\n\014AddressEntry\022\013\n\003key\030\001 \001(\r\022\r\n\005value\030\002" " \001(\r:\0028\001\"\212\004\n\005Input\022\013\n\003sig\030\013 \001(\t\022\017\n\007progr" "am\030\014 \001(\014\022\"\n\004call\030\r \003(\0132\024.dra.Input.CallE" "ntry\022\016\n\006stable\030\016 \001(\r\022\031\n\005paths\030\020 \003(\0132\n.dr" "a.Paths\022\031\n\021number_conditions\030\021 \001(\r\022$\n\034nu" "mber_conditions_dependency\030\022 \001(\r\022\036\n\004stat" "\030\025 \001(\0162\020.dra.FuzzingStat\022;\n\021uncovered_ad" "dress\030\026 \003(\0132 .dra.Input.UncoveredAddress" "Entry\0223\n\rwrite_address\030\031 \003(\0132\034.dra.Input" ".WriteAddressEntry\022\033\n\023program_before_min" "i\030\036 \001(\014\0326\n\tCallEntry\022\013\n\003key\030\001 \001(\r\022\030\n\005val" "ue\030\002 \001(\0132\t.dra.Call:\0028\001\0327\n\025UncoveredAddr" "essEntry\022\013\n\003key\030\001 \001(\r\022\r\n\005value\030\002 \001(\r:\0028\001" "\0323\n\021WriteAddressEntry\022\013\n\003key\030\001 \001(\r\022\r\n\005va" "lue\030\002 \001(\r:\0028\001\"#\n\006Inputs\022\031\n\005input\030\001 \003(\0132\n" ".dra.Input\"\027\n\004Path\022\017\n\007address\030\001 \003(\r\"c\n\005P" "aths\022\"\n\004path\030\001 \003(\0132\024.dra.Paths.PathEntry" "\0326\n\tPathEntry\022\013\n\003key\030\001 \001(\r\022\030\n\005value\030\002 \001(" "\0132\t.dra.Path:\0028\001\"\262\001\n\rUnstableInput\022\013\n\003si" "g\030\001 \001(\t\022\017\n\007program\030\002 \001(\014\022!\n\runstable_pat" "h\030\014 \003(\0132\n.dra.Paths\0220\n\007address\030\r \003(\0132\037.d" "ra.UnstableInput.AddressEntry\032.\n\014Address" "Entry\022\013\n\003key\030\001 \001(\r\022\r\n\005value\030\002 \001(\r:\0028\001\"\232\001" "\n\016UnstableInputs\022>\n\016unstable_input\030\001 \003(\013" "2&.dra.UnstableInputs.UnstableInputEntry" "\032H\n\022UnstableInputEntry\022\013\n\003key\030\001 \001(\t\022!\n\005v" "alue\030\002 \001(\0132\022.dra.UnstableInput:\0028\001*\323\001\n\013F" "uzzingStat\022\020\n\014StatGenerate\020\000\022\014\n\010StatFuzz" "\020\001\022\021\n\rStatCandidate\020\002\022\016\n\nStatTriage\020\003\022\020\n" "\014StatMinimize\020\004\022\r\n\tStatSmash\020\005\022\014\n\010StatHi" "nt\020\006\022\014\n\010StatSeed\020\007\022\022\n\016StatDependency\020\010\022\026" "\n\022StatDependencyBoot\020\t\022\030\n\013StatDefault\020\377\377" "\377\377\377\377\377\377\377\001B\007Z\005.;drab\006proto3" ; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_Input_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_Input_2eproto = { false, false, 1385, descriptor_table_protodef_Input_2eproto, "Input.proto", &descriptor_table_Input_2eproto_once, nullptr, 0, 14, schemas, file_default_instances, TableStruct_Input_2eproto::offsets, file_level_metadata_Input_2eproto, file_level_enum_descriptors_Input_2eproto, file_level_service_descriptors_Input_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_Input_2eproto_getter() { return &descriptor_table_Input_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_Input_2eproto(&descriptor_table_Input_2eproto); namespace dra { const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FuzzingStat_descriptor() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Input_2eproto); return file_level_enum_descriptors_Input_2eproto[0]; } bool FuzzingStat_IsValid(int value) { switch (value) { case -1: case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: return true; default: return false; } } // =================================================================== Call_AddressEntry_DoNotUse::Call_AddressEntry_DoNotUse() {} Call_AddressEntry_DoNotUse::Call_AddressEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void Call_AddressEntry_DoNotUse::MergeFrom(const Call_AddressEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata Call_AddressEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[0]); } // =================================================================== class Call::_Internal { public: }; Call::Call(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), address_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.Call) } Call::Call(const Call& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); address_.MergeFrom(from.address_); idx_ = from.idx_; // @@protoc_insertion_point(copy_constructor:dra.Call) } void Call::SharedCtor() { idx_ = 0u; } Call::~Call() { // @@protoc_insertion_point(destructor:dra.Call) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void Call::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void Call::ArenaDtor(void* object) { Call* _this = reinterpret_cast< Call* >(object); (void)_this; _this->address_. ~MapField(); } inline void Call::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena) { if (arena != nullptr) { arena->OwnCustomDestructor(this, &Call::ArenaDtor); } } void Call::SetCachedSize(int size) const { _cached_size_.Set(size); } void Call::Clear() { // @@protoc_insertion_point(message_clear_start:dra.Call) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; address_.Clear(); idx_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* Call::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // uint32 idx = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { idx_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // map<uint32, uint32> address = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(&address_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* Call::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.Call) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 idx = 1; if (this->_internal_idx() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_idx(), target); } // map<uint32, uint32> address = 2; if (!this->_internal_address().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_pointer ConstPtr; typedef ::PROTOBUF_NAMESPACE_ID::internal::SortItem< ::PROTOBUF_NAMESPACE_ID::uint32, ConstPtr > SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByFirstField<SortItem> Less; if (stream->IsSerializationDeterministic() && this->_internal_address().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_address().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_address().begin(); it != this->_internal_address().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = Call_AddressEntry_DoNotUse::Funcs::InternalSerialize(2, items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second, target, stream); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_address().begin(); it != this->_internal_address().end(); ++it) { target = Call_AddressEntry_DoNotUse::Funcs::InternalSerialize(2, it->first, it->second, target, stream); } } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.Call) return target; } size_t Call::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.Call) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // map<uint32, uint32> address = 2; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_address_size()); for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_address().begin(); it != this->_internal_address().end(); ++it) { total_size += Call_AddressEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } // uint32 idx = 1; if (this->_internal_idx() != 0) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32SizePlusOne(this->_internal_idx()); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Call::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, Call::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Call::GetClassData() const { return &_class_data_; } void Call::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<Call *>(to)->MergeFrom( static_cast<const Call &>(from)); } void Call::MergeFrom(const Call& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.Call) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; address_.MergeFrom(from.address_); if (from._internal_idx() != 0) { _internal_set_idx(from._internal_idx()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void Call::CopyFrom(const Call& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.Call) if (&from == this) return; Clear(); MergeFrom(from); } bool Call::IsInitialized() const { return true; } void Call::InternalSwap(Call* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); address_.InternalSwap(&other->address_); swap(idx_, other->idx_); } ::PROTOBUF_NAMESPACE_ID::Metadata Call::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[1]); } // =================================================================== Input_CallEntry_DoNotUse::Input_CallEntry_DoNotUse() {} Input_CallEntry_DoNotUse::Input_CallEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void Input_CallEntry_DoNotUse::MergeFrom(const Input_CallEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata Input_CallEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[2]); } // =================================================================== Input_UncoveredAddressEntry_DoNotUse::Input_UncoveredAddressEntry_DoNotUse() {} Input_UncoveredAddressEntry_DoNotUse::Input_UncoveredAddressEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void Input_UncoveredAddressEntry_DoNotUse::MergeFrom(const Input_UncoveredAddressEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata Input_UncoveredAddressEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[3]); } // =================================================================== Input_WriteAddressEntry_DoNotUse::Input_WriteAddressEntry_DoNotUse() {} Input_WriteAddressEntry_DoNotUse::Input_WriteAddressEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void Input_WriteAddressEntry_DoNotUse::MergeFrom(const Input_WriteAddressEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata Input_WriteAddressEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[4]); } // =================================================================== class Input::_Internal { public: }; Input::Input(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), call_(arena), paths_(arena), uncovered_address_(arena), write_address_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.Input) } Input::Input(const Input& from) : ::PROTOBUF_NAMESPACE_ID::Message(), paths_(from.paths_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); call_.MergeFrom(from.call_); uncovered_address_.MergeFrom(from.uncovered_address_); write_address_.MergeFrom(from.write_address_); sig_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_sig().empty()) { sig_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_sig(), GetArenaForAllocation()); } program_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_program().empty()) { program_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_program(), GetArenaForAllocation()); } program_before_mini_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_program_before_mini().empty()) { program_before_mini_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_program_before_mini(), GetArenaForAllocation()); } ::memcpy(&stable_, &from.stable_, static_cast<size_t>(reinterpret_cast<char*>(&stat_) - reinterpret_cast<char*>(&stable_)) + sizeof(stat_)); // @@protoc_insertion_point(copy_constructor:dra.Input) } void Input::SharedCtor() { sig_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); program_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); program_before_mini_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&stable_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&stat_) - reinterpret_cast<char*>(&stable_)) + sizeof(stat_)); } Input::~Input() { // @@protoc_insertion_point(destructor:dra.Input) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void Input::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); sig_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); program_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); program_before_mini_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void Input::ArenaDtor(void* object) { Input* _this = reinterpret_cast< Input* >(object); (void)_this; _this->call_. ~MapField(); _this->uncovered_address_. ~MapField(); _this->write_address_. ~MapField(); } inline void Input::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena) { if (arena != nullptr) { arena->OwnCustomDestructor(this, &Input::ArenaDtor); } } void Input::SetCachedSize(int size) const { _cached_size_.Set(size); } void Input::Clear() { // @@protoc_insertion_point(message_clear_start:dra.Input) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; call_.Clear(); paths_.Clear(); uncovered_address_.Clear(); write_address_.Clear(); sig_.ClearToEmpty(); program_.ClearToEmpty(); program_before_mini_.ClearToEmpty(); ::memset(&stable_, 0, static_cast<size_t>( reinterpret_cast<char*>(&stat_) - reinterpret_cast<char*>(&stable_)) + sizeof(stat_)); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* Input::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string sig = 11; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90)) { auto str = _internal_mutable_sig(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "dra.Input.sig")); CHK_(ptr); } else goto handle_unusual; continue; // bytes program = 12; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) { auto str = _internal_mutable_program(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // map<uint32, .dra.Call> call = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 106)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(&call_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<106>(ptr)); } else goto handle_unusual; continue; // uint32 stable = 14; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112)) { stable_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .dra.Paths paths = 16; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) { ptr -= 2; do { ptr += 2; ptr = ctx->ParseMessage(_internal_add_paths(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<130>(ptr)); } else goto handle_unusual; continue; // uint32 number_conditions = 17; case 17: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 136)) { number_conditions_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // uint32 number_conditions_dependency = 18; case 18: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 144)) { number_conditions_dependency_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // .dra.FuzzingStat stat = 21; case 21: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 168)) { ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); _internal_set_stat(static_cast<::dra::FuzzingStat>(val)); } else goto handle_unusual; continue; // map<uint32, uint32> uncovered_address = 22; case 22: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 178)) { ptr -= 2; do { ptr += 2; ptr = ctx->ParseMessage(&uncovered_address_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<178>(ptr)); } else goto handle_unusual; continue; // map<uint32, uint32> write_address = 25; case 25: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 202)) { ptr -= 2; do { ptr += 2; ptr = ctx->ParseMessage(&write_address_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<202>(ptr)); } else goto handle_unusual; continue; // bytes program_before_mini = 30; case 30: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 242)) { auto str = _internal_mutable_program_before_mini(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* Input::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.Input) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string sig = 11; if (!this->_internal_sig().empty()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_sig().data(), static_cast<int>(this->_internal_sig().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "dra.Input.sig"); target = stream->WriteStringMaybeAliased( 11, this->_internal_sig(), target); } // bytes program = 12; if (!this->_internal_program().empty()) { target = stream->WriteBytesMaybeAliased( 12, this->_internal_program(), target); } // map<uint32, .dra.Call> call = 13; if (!this->_internal_call().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Call >::const_pointer ConstPtr; typedef ::PROTOBUF_NAMESPACE_ID::internal::SortItem< ::PROTOBUF_NAMESPACE_ID::uint32, ConstPtr > SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByFirstField<SortItem> Less; if (stream->IsSerializationDeterministic() && this->_internal_call().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_call().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Call >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Call >::const_iterator it = this->_internal_call().begin(); it != this->_internal_call().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = Input_CallEntry_DoNotUse::Funcs::InternalSerialize(13, items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second, target, stream); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Call >::const_iterator it = this->_internal_call().begin(); it != this->_internal_call().end(); ++it) { target = Input_CallEntry_DoNotUse::Funcs::InternalSerialize(13, it->first, it->second, target, stream); } } } // uint32 stable = 14; if (this->_internal_stable() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(14, this->_internal_stable(), target); } // repeated .dra.Paths paths = 16; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_paths_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(16, this->_internal_paths(i), target, stream); } // uint32 number_conditions = 17; if (this->_internal_number_conditions() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(17, this->_internal_number_conditions(), target); } // uint32 number_conditions_dependency = 18; if (this->_internal_number_conditions_dependency() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(18, this->_internal_number_conditions_dependency(), target); } // .dra.FuzzingStat stat = 21; if (this->_internal_stat() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 21, this->_internal_stat(), target); } // map<uint32, uint32> uncovered_address = 22; if (!this->_internal_uncovered_address().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_pointer ConstPtr; typedef ::PROTOBUF_NAMESPACE_ID::internal::SortItem< ::PROTOBUF_NAMESPACE_ID::uint32, ConstPtr > SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByFirstField<SortItem> Less; if (stream->IsSerializationDeterministic() && this->_internal_uncovered_address().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_uncovered_address().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_uncovered_address().begin(); it != this->_internal_uncovered_address().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = Input_UncoveredAddressEntry_DoNotUse::Funcs::InternalSerialize(22, items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second, target, stream); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_uncovered_address().begin(); it != this->_internal_uncovered_address().end(); ++it) { target = Input_UncoveredAddressEntry_DoNotUse::Funcs::InternalSerialize(22, it->first, it->second, target, stream); } } } // map<uint32, uint32> write_address = 25; if (!this->_internal_write_address().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_pointer ConstPtr; typedef ::PROTOBUF_NAMESPACE_ID::internal::SortItem< ::PROTOBUF_NAMESPACE_ID::uint32, ConstPtr > SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByFirstField<SortItem> Less; if (stream->IsSerializationDeterministic() && this->_internal_write_address().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_write_address().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_write_address().begin(); it != this->_internal_write_address().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = Input_WriteAddressEntry_DoNotUse::Funcs::InternalSerialize(25, items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second, target, stream); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_write_address().begin(); it != this->_internal_write_address().end(); ++it) { target = Input_WriteAddressEntry_DoNotUse::Funcs::InternalSerialize(25, it->first, it->second, target, stream); } } } // bytes program_before_mini = 30; if (!this->_internal_program_before_mini().empty()) { target = stream->WriteBytesMaybeAliased( 30, this->_internal_program_before_mini(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.Input) return target; } size_t Input::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.Input) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // map<uint32, .dra.Call> call = 13; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_call_size()); for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Call >::const_iterator it = this->_internal_call().begin(); it != this->_internal_call().end(); ++it) { total_size += Input_CallEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } // repeated .dra.Paths paths = 16; total_size += 2UL * this->_internal_paths_size(); for (const auto& msg : this->paths_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // map<uint32, uint32> uncovered_address = 22; total_size += 2 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_uncovered_address_size()); for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_uncovered_address().begin(); it != this->_internal_uncovered_address().end(); ++it) { total_size += Input_UncoveredAddressEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } // map<uint32, uint32> write_address = 25; total_size += 2 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_write_address_size()); for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_write_address().begin(); it != this->_internal_write_address().end(); ++it) { total_size += Input_WriteAddressEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } // string sig = 11; if (!this->_internal_sig().empty()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_sig()); } // bytes program = 12; if (!this->_internal_program().empty()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_program()); } // bytes program_before_mini = 30; if (!this->_internal_program_before_mini().empty()) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_program_before_mini()); } // uint32 stable = 14; if (this->_internal_stable() != 0) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32SizePlusOne(this->_internal_stable()); } // uint32 number_conditions = 17; if (this->_internal_number_conditions() != 0) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_number_conditions()); } // uint32 number_conditions_dependency = 18; if (this->_internal_number_conditions_dependency() != 0) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_number_conditions_dependency()); } // .dra.FuzzingStat stat = 21; if (this->_internal_stat() != 0) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_stat()); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Input::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, Input::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Input::GetClassData() const { return &_class_data_; } void Input::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<Input *>(to)->MergeFrom( static_cast<const Input &>(from)); } void Input::MergeFrom(const Input& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.Input) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; call_.MergeFrom(from.call_); paths_.MergeFrom(from.paths_); uncovered_address_.MergeFrom(from.uncovered_address_); write_address_.MergeFrom(from.write_address_); if (!from._internal_sig().empty()) { _internal_set_sig(from._internal_sig()); } if (!from._internal_program().empty()) { _internal_set_program(from._internal_program()); } if (!from._internal_program_before_mini().empty()) { _internal_set_program_before_mini(from._internal_program_before_mini()); } if (from._internal_stable() != 0) { _internal_set_stable(from._internal_stable()); } if (from._internal_number_conditions() != 0) { _internal_set_number_conditions(from._internal_number_conditions()); } if (from._internal_number_conditions_dependency() != 0) { _internal_set_number_conditions_dependency(from._internal_number_conditions_dependency()); } if (from._internal_stat() != 0) { _internal_set_stat(from._internal_stat()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void Input::CopyFrom(const Input& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.Input) if (&from == this) return; Clear(); MergeFrom(from); } bool Input::IsInitialized() const { return true; } void Input::InternalSwap(Input* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); call_.InternalSwap(&other->call_); paths_.InternalSwap(&other->paths_); uncovered_address_.InternalSwap(&other->uncovered_address_); write_address_.InternalSwap(&other->write_address_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &sig_, lhs_arena, &other->sig_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &program_, lhs_arena, &other->program_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &program_before_mini_, lhs_arena, &other->program_before_mini_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(Input, stat_) + sizeof(Input::stat_) - PROTOBUF_FIELD_OFFSET(Input, stable_)>( reinterpret_cast<char*>(&stable_), reinterpret_cast<char*>(&other->stable_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Input::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[5]); } // =================================================================== class Inputs::_Internal { public: }; Inputs::Inputs(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), input_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.Inputs) } Inputs::Inputs(const Inputs& from) : ::PROTOBUF_NAMESPACE_ID::Message(), input_(from.input_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:dra.Inputs) } void Inputs::SharedCtor() { } Inputs::~Inputs() { // @@protoc_insertion_point(destructor:dra.Inputs) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void Inputs::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void Inputs::ArenaDtor(void* object) { Inputs* _this = reinterpret_cast< Inputs* >(object); (void)_this; } void Inputs::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Inputs::SetCachedSize(int size) const { _cached_size_.Set(size); } void Inputs::Clear() { // @@protoc_insertion_point(message_clear_start:dra.Inputs) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; input_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* Inputs::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // repeated .dra.Input input = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_input(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* Inputs::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.Inputs) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .dra.Input input = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_input_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(1, this->_internal_input(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.Inputs) return target; } size_t Inputs::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.Inputs) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .dra.Input input = 1; total_size += 1UL * this->_internal_input_size(); for (const auto& msg : this->input_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Inputs::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, Inputs::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Inputs::GetClassData() const { return &_class_data_; } void Inputs::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<Inputs *>(to)->MergeFrom( static_cast<const Inputs &>(from)); } void Inputs::MergeFrom(const Inputs& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.Inputs) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; input_.MergeFrom(from.input_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void Inputs::CopyFrom(const Inputs& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.Inputs) if (&from == this) return; Clear(); MergeFrom(from); } bool Inputs::IsInitialized() const { return true; } void Inputs::InternalSwap(Inputs* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); input_.InternalSwap(&other->input_); } ::PROTOBUF_NAMESPACE_ID::Metadata Inputs::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[6]); } // =================================================================== class Path::_Internal { public: }; Path::Path(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), address_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.Path) } Path::Path(const Path& from) : ::PROTOBUF_NAMESPACE_ID::Message(), address_(from.address_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:dra.Path) } void Path::SharedCtor() { } Path::~Path() { // @@protoc_insertion_point(destructor:dra.Path) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void Path::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void Path::ArenaDtor(void* object) { Path* _this = reinterpret_cast< Path* >(object); (void)_this; } void Path::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void Path::SetCachedSize(int size) const { _cached_size_.Set(size); } void Path::Clear() { // @@protoc_insertion_point(message_clear_start:dra.Path) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; address_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* Path::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // repeated uint32 address = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_address(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8) { _internal_add_address(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* Path::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.Path) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated uint32 address = 1; { int byte_size = _address_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 1, _internal_address(), byte_size, target); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.Path) return target; } size_t Path::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.Path) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated uint32 address = 1; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->address_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _address_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Path::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, Path::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Path::GetClassData() const { return &_class_data_; } void Path::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<Path *>(to)->MergeFrom( static_cast<const Path &>(from)); } void Path::MergeFrom(const Path& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.Path) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; address_.MergeFrom(from.address_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void Path::CopyFrom(const Path& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.Path) if (&from == this) return; Clear(); MergeFrom(from); } bool Path::IsInitialized() const { return true; } void Path::InternalSwap(Path* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); address_.InternalSwap(&other->address_); } ::PROTOBUF_NAMESPACE_ID::Metadata Path::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[7]); } // =================================================================== Paths_PathEntry_DoNotUse::Paths_PathEntry_DoNotUse() {} Paths_PathEntry_DoNotUse::Paths_PathEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void Paths_PathEntry_DoNotUse::MergeFrom(const Paths_PathEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata Paths_PathEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[8]); } // =================================================================== class Paths::_Internal { public: }; Paths::Paths(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), path_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.Paths) } Paths::Paths(const Paths& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); path_.MergeFrom(from.path_); // @@protoc_insertion_point(copy_constructor:dra.Paths) } void Paths::SharedCtor() { } Paths::~Paths() { // @@protoc_insertion_point(destructor:dra.Paths) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void Paths::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void Paths::ArenaDtor(void* object) { Paths* _this = reinterpret_cast< Paths* >(object); (void)_this; _this->path_. ~MapField(); } inline void Paths::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena) { if (arena != nullptr) { arena->OwnCustomDestructor(this, &Paths::ArenaDtor); } } void Paths::SetCachedSize(int size) const { _cached_size_.Set(size); } void Paths::Clear() { // @@protoc_insertion_point(message_clear_start:dra.Paths) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; path_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* Paths::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // map<uint32, .dra.Path> path = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(&path_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* Paths::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.Paths) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<uint32, .dra.Path> path = 1; if (!this->_internal_path().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Path >::const_pointer ConstPtr; typedef ::PROTOBUF_NAMESPACE_ID::internal::SortItem< ::PROTOBUF_NAMESPACE_ID::uint32, ConstPtr > SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByFirstField<SortItem> Less; if (stream->IsSerializationDeterministic() && this->_internal_path().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_path().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Path >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Path >::const_iterator it = this->_internal_path().begin(); it != this->_internal_path().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = Paths_PathEntry_DoNotUse::Funcs::InternalSerialize(1, items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second, target, stream); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Path >::const_iterator it = this->_internal_path().begin(); it != this->_internal_path().end(); ++it) { target = Paths_PathEntry_DoNotUse::Funcs::InternalSerialize(1, it->first, it->second, target, stream); } } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.Paths) return target; } size_t Paths::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.Paths) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // map<uint32, .dra.Path> path = 1; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_path_size()); for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::dra::Path >::const_iterator it = this->_internal_path().begin(); it != this->_internal_path().end(); ++it) { total_size += Paths_PathEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Paths::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, Paths::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Paths::GetClassData() const { return &_class_data_; } void Paths::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<Paths *>(to)->MergeFrom( static_cast<const Paths &>(from)); } void Paths::MergeFrom(const Paths& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.Paths) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; path_.MergeFrom(from.path_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void Paths::CopyFrom(const Paths& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.Paths) if (&from == this) return; Clear(); MergeFrom(from); } bool Paths::IsInitialized() const { return true; } void Paths::InternalSwap(Paths* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); path_.InternalSwap(&other->path_); } ::PROTOBUF_NAMESPACE_ID::Metadata Paths::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[9]); } // =================================================================== UnstableInput_AddressEntry_DoNotUse::UnstableInput_AddressEntry_DoNotUse() {} UnstableInput_AddressEntry_DoNotUse::UnstableInput_AddressEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void UnstableInput_AddressEntry_DoNotUse::MergeFrom(const UnstableInput_AddressEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata UnstableInput_AddressEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[10]); } // =================================================================== class UnstableInput::_Internal { public: }; UnstableInput::UnstableInput(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), unstable_path_(arena), address_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.UnstableInput) } UnstableInput::UnstableInput(const UnstableInput& from) : ::PROTOBUF_NAMESPACE_ID::Message(), unstable_path_(from.unstable_path_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); address_.MergeFrom(from.address_); sig_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_sig().empty()) { sig_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_sig(), GetArenaForAllocation()); } program_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_program().empty()) { program_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_program(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:dra.UnstableInput) } void UnstableInput::SharedCtor() { sig_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); program_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } UnstableInput::~UnstableInput() { // @@protoc_insertion_point(destructor:dra.UnstableInput) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void UnstableInput::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); sig_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); program_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void UnstableInput::ArenaDtor(void* object) { UnstableInput* _this = reinterpret_cast< UnstableInput* >(object); (void)_this; _this->address_. ~MapField(); } inline void UnstableInput::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena) { if (arena != nullptr) { arena->OwnCustomDestructor(this, &UnstableInput::ArenaDtor); } } void UnstableInput::SetCachedSize(int size) const { _cached_size_.Set(size); } void UnstableInput::Clear() { // @@protoc_insertion_point(message_clear_start:dra.UnstableInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; unstable_path_.Clear(); address_.Clear(); sig_.ClearToEmpty(); program_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UnstableInput::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string sig = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_sig(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "dra.UnstableInput.sig")); CHK_(ptr); } else goto handle_unusual; continue; // bytes program = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_program(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // repeated .dra.Paths unstable_path = 12; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_unstable_path(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<98>(ptr)); } else goto handle_unusual; continue; // map<uint32, uint32> address = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 106)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(&address_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<106>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UnstableInput::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.UnstableInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string sig = 1; if (!this->_internal_sig().empty()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_sig().data(), static_cast<int>(this->_internal_sig().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "dra.UnstableInput.sig"); target = stream->WriteStringMaybeAliased( 1, this->_internal_sig(), target); } // bytes program = 2; if (!this->_internal_program().empty()) { target = stream->WriteBytesMaybeAliased( 2, this->_internal_program(), target); } // repeated .dra.Paths unstable_path = 12; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_unstable_path_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(12, this->_internal_unstable_path(i), target, stream); } // map<uint32, uint32> address = 13; if (!this->_internal_address().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_pointer ConstPtr; typedef ::PROTOBUF_NAMESPACE_ID::internal::SortItem< ::PROTOBUF_NAMESPACE_ID::uint32, ConstPtr > SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByFirstField<SortItem> Less; if (stream->IsSerializationDeterministic() && this->_internal_address().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_address().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_address().begin(); it != this->_internal_address().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = UnstableInput_AddressEntry_DoNotUse::Funcs::InternalSerialize(13, items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second, target, stream); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_address().begin(); it != this->_internal_address().end(); ++it) { target = UnstableInput_AddressEntry_DoNotUse::Funcs::InternalSerialize(13, it->first, it->second, target, stream); } } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.UnstableInput) return target; } size_t UnstableInput::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.UnstableInput) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .dra.Paths unstable_path = 12; total_size += 1UL * this->_internal_unstable_path_size(); for (const auto& msg : this->unstable_path_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // map<uint32, uint32> address = 13; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_address_size()); for (::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >::const_iterator it = this->_internal_address().begin(); it != this->_internal_address().end(); ++it) { total_size += UnstableInput_AddressEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } // string sig = 1; if (!this->_internal_sig().empty()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_sig()); } // bytes program = 2; if (!this->_internal_program().empty()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_program()); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData UnstableInput::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, UnstableInput::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*UnstableInput::GetClassData() const { return &_class_data_; } void UnstableInput::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<UnstableInput *>(to)->MergeFrom( static_cast<const UnstableInput &>(from)); } void UnstableInput::MergeFrom(const UnstableInput& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.UnstableInput) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; unstable_path_.MergeFrom(from.unstable_path_); address_.MergeFrom(from.address_); if (!from._internal_sig().empty()) { _internal_set_sig(from._internal_sig()); } if (!from._internal_program().empty()) { _internal_set_program(from._internal_program()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void UnstableInput::CopyFrom(const UnstableInput& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.UnstableInput) if (&from == this) return; Clear(); MergeFrom(from); } bool UnstableInput::IsInitialized() const { return true; } void UnstableInput::InternalSwap(UnstableInput* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); unstable_path_.InternalSwap(&other->unstable_path_); address_.InternalSwap(&other->address_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &sig_, lhs_arena, &other->sig_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &program_, lhs_arena, &other->program_, rhs_arena ); } ::PROTOBUF_NAMESPACE_ID::Metadata UnstableInput::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[11]); } // =================================================================== UnstableInputs_UnstableInputEntry_DoNotUse::UnstableInputs_UnstableInputEntry_DoNotUse() {} UnstableInputs_UnstableInputEntry_DoNotUse::UnstableInputs_UnstableInputEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : SuperType(arena) {} void UnstableInputs_UnstableInputEntry_DoNotUse::MergeFrom(const UnstableInputs_UnstableInputEntry_DoNotUse& other) { MergeFromInternal(other); } ::PROTOBUF_NAMESPACE_ID::Metadata UnstableInputs_UnstableInputEntry_DoNotUse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[12]); } // =================================================================== class UnstableInputs::_Internal { public: }; UnstableInputs::UnstableInputs(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), unstable_input_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:dra.UnstableInputs) } UnstableInputs::UnstableInputs(const UnstableInputs& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); unstable_input_.MergeFrom(from.unstable_input_); // @@protoc_insertion_point(copy_constructor:dra.UnstableInputs) } void UnstableInputs::SharedCtor() { } UnstableInputs::~UnstableInputs() { // @@protoc_insertion_point(destructor:dra.UnstableInputs) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void UnstableInputs::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void UnstableInputs::ArenaDtor(void* object) { UnstableInputs* _this = reinterpret_cast< UnstableInputs* >(object); (void)_this; _this->unstable_input_. ~MapField(); } inline void UnstableInputs::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena) { if (arena != nullptr) { arena->OwnCustomDestructor(this, &UnstableInputs::ArenaDtor); } } void UnstableInputs::SetCachedSize(int size) const { _cached_size_.Set(size); } void UnstableInputs::Clear() { // @@protoc_insertion_point(message_clear_start:dra.UnstableInputs) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; unstable_input_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UnstableInputs::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // map<string, .dra.UnstableInput> unstable_input = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(&unstable_input_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UnstableInputs::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:dra.UnstableInputs) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .dra.UnstableInput> unstable_input = 1; if (!this->_internal_unstable_input().empty()) { typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::dra::UnstableInput >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { (void)p; ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "dra.UnstableInputs.UnstableInputEntry.key"); } }; if (stream->IsSerializationDeterministic() && this->_internal_unstable_input().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->_internal_unstable_input().size()]); typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::dra::UnstableInput >::size_type size_type; size_type n = 0; for (::PROTOBUF_NAMESPACE_ID::Map< std::string, ::dra::UnstableInput >::const_iterator it = this->_internal_unstable_input().begin(); it != this->_internal_unstable_input().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); for (size_type i = 0; i < n; i++) { target = UnstableInputs_UnstableInputEntry_DoNotUse::Funcs::InternalSerialize(1, items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second, target, stream); Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)])); } } else { for (::PROTOBUF_NAMESPACE_ID::Map< std::string, ::dra::UnstableInput >::const_iterator it = this->_internal_unstable_input().begin(); it != this->_internal_unstable_input().end(); ++it) { target = UnstableInputs_UnstableInputEntry_DoNotUse::Funcs::InternalSerialize(1, it->first, it->second, target, stream); Utf8Check::Check(&(*it)); } } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:dra.UnstableInputs) return target; } size_t UnstableInputs::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dra.UnstableInputs) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // map<string, .dra.UnstableInput> unstable_input = 1; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_unstable_input_size()); for (::PROTOBUF_NAMESPACE_ID::Map< std::string, ::dra::UnstableInput >::const_iterator it = this->_internal_unstable_input().begin(); it != this->_internal_unstable_input().end(); ++it) { total_size += UnstableInputs_UnstableInputEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData UnstableInputs::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, UnstableInputs::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*UnstableInputs::GetClassData() const { return &_class_data_; } void UnstableInputs::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<UnstableInputs *>(to)->MergeFrom( static_cast<const UnstableInputs &>(from)); } void UnstableInputs::MergeFrom(const UnstableInputs& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dra.UnstableInputs) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; unstable_input_.MergeFrom(from.unstable_input_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void UnstableInputs::CopyFrom(const UnstableInputs& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dra.UnstableInputs) if (&from == this) return; Clear(); MergeFrom(from); } bool UnstableInputs::IsInitialized() const { return true; } void UnstableInputs::InternalSwap(UnstableInputs* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); unstable_input_.InternalSwap(&other->unstable_input_); } ::PROTOBUF_NAMESPACE_ID::Metadata UnstableInputs::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_Input_2eproto_getter, &descriptor_table_Input_2eproto_once, file_level_metadata_Input_2eproto[13]); } // @@protoc_insertion_point(namespace_scope) } // namespace dra PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::dra::Call_AddressEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::Call_AddressEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Call_AddressEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::Call* Arena::CreateMaybeMessage< ::dra::Call >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Call >(arena); } template<> PROTOBUF_NOINLINE ::dra::Input_CallEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::Input_CallEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Input_CallEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::Input_UncoveredAddressEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::Input_UncoveredAddressEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Input_UncoveredAddressEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::Input_WriteAddressEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::Input_WriteAddressEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Input_WriteAddressEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::Input* Arena::CreateMaybeMessage< ::dra::Input >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Input >(arena); } template<> PROTOBUF_NOINLINE ::dra::Inputs* Arena::CreateMaybeMessage< ::dra::Inputs >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Inputs >(arena); } template<> PROTOBUF_NOINLINE ::dra::Path* Arena::CreateMaybeMessage< ::dra::Path >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Path >(arena); } template<> PROTOBUF_NOINLINE ::dra::Paths_PathEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::Paths_PathEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Paths_PathEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::Paths* Arena::CreateMaybeMessage< ::dra::Paths >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::Paths >(arena); } template<> PROTOBUF_NOINLINE ::dra::UnstableInput_AddressEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::UnstableInput_AddressEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::UnstableInput_AddressEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::UnstableInput* Arena::CreateMaybeMessage< ::dra::UnstableInput >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::UnstableInput >(arena); } template<> PROTOBUF_NOINLINE ::dra::UnstableInputs_UnstableInputEntry_DoNotUse* Arena::CreateMaybeMessage< ::dra::UnstableInputs_UnstableInputEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::UnstableInputs_UnstableInputEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::dra::UnstableInputs* Arena::CreateMaybeMessage< ::dra::UnstableInputs >(Arena* arena) { return Arena::CreateMessageInternal< ::dra::UnstableInputs >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
40.658773
197
0.718676
[ "object" ]
5a9b2ef64f6b1e116e2fde2e74879ebf23db8521
918
cpp
C++
1786/1786.cpp11.cpp
isac322/BOJ
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
[ "MIT" ]
14
2017-05-02T02:00:42.000Z
2021-11-16T07:25:29.000Z
1786/1786.cpp11.cpp
isac322/BOJ
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
[ "MIT" ]
1
2017-12-25T14:18:14.000Z
2018-02-07T06:49:44.000Z
1786/1786.cpp11.cpp
isac322/BOJ
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
[ "MIT" ]
9
2016-03-03T22:06:52.000Z
2020-04-30T22:06:24.000Z
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; vector<int> failure; vector<size_t> mached; void buildTable(string &w) { failure.resize(w.size()); int i = 2, j = 0; failure[0] = -1; failure[1] = 0; while (i < w.length()) { if (w[i - 1] == w[j]) { failure[i] = j + 1; i++; j++; } else if (j > 0) j = failure[j]; else { failure[i] = 0; i++; } } } void KMP(string &s, string &w) { int m = 0, i = 0; buildTable(w); while (m + i < s.length()) { if (w[i] == s[m + i]) { i++; if (i == w.length()) { mached.emplace_back(m); i--; m += i - failure[i]; i = failure[i]; } } else { m += i - failure[i]; if (i > 0) i = failure[i]; } } } int main() { string t, p; getline(cin, t); getline(cin, p); KMP(t, p); cout << mached.size() << '\n'; for (auto d : mached) { cout << d + 1 << ' '; } }
14.123077
33
0.489107
[ "vector" ]
5ab11e81a74b926f69088620572fff7810c85fa5
2,352
hpp
C++
Geometry/NumPairHashTable.hpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
null
null
null
Geometry/NumPairHashTable.hpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
2
2020-10-19T02:03:11.000Z
2021-03-19T16:34:39.000Z
Geometry/NumPairHashTable.hpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
1
2020-04-28T00:33:14.000Z
2020-04-28T00:33:14.000Z
#ifndef __Num_Pair_Hash_Table_hpp__ #define __Num_Pair_Hash_Table_hpp__ #include "ItemBuffer.hpp" // assistent data structs for tetrahedron mesh template <typename Num> class NumPairHashTable { public: struct NumPair { Num key; Num val; NumPair *next; }; protected: size_t entry_num; NumPair **num_pair_list; MemoryUtils::ItemBuffer<NumPair> num_pair_buf; size_t pair_num; public: NumPairHashTable(size_t _entry_num) : entry_num(_entry_num), pair_num(0) { num_pair_list = new NumPair*[entry_num]; for (size_t en_id = 0; en_id < entry_num; ++en_id) num_pair_list[en_id] = nullptr; } ~NumPairHashTable() {} size_t get_pair_num() { return pair_num; } template <typename ResNum = Num> void output_pairs(ResNum *mem) { for (size_t e_id = 0; e_id < entry_num; ++e_id) for (NumPair *pair = num_pair_list[e_id]; pair; pair = pair->next) { mem[0] = ResNum(pair->key); mem[1] = ResNum(pair->val); mem += 2; } } // Assume key has single value bool find_key(Num _key, Num &_val) { for (NumPair *pair = num_pair_list[_key % entry_num]; pair; pair = pair->next) if (pair->key == _key) { _val = pair->val; return true; } return false; } bool add_key(Num _key, Num &_val) { NumPair *&top = num_pair_list[_key % entry_num]; for (NumPair *pair = top; pair; pair = pair->next) { if (pair->key == _key) return false; } NumPair *tmp = num_pair_buf.alloc(); tmp->key = _key; tmp->val = _val; tmp->next = top; top = tmp; ++pair_num; return true; } // Assume key has multiple value bool find_pair(Num _key, Num _val) { for (NumPair *pair = num_pair_list[_key % entry_num]; pair; pair = pair->next) if (pair->key == _key && pair->val == _val) return true; return false; } // return false if the pair already exists bool add_pair(Num _key, Num _val) { NumPair *&top = num_pair_list[_key % entry_num]; for (NumPair *pair = top; pair; pair = pair->next) { if (pair->key == _key && pair->val == _val) return false; } NumPair *tmp = num_pair_buf.alloc(); tmp->key = _key; tmp->val = _val; tmp->next = top; top = tmp; ++pair_num; return true; } void reset() { for (size_t en_id = 0; en_id < entry_num; ++en_id) num_pair_list[en_id] = nullptr; num_pair_buf.reset(); pair_num = 0; } }; #endif
20.452174
69
0.646259
[ "mesh" ]
62c36d0ffec8e12c105efd2df70e9bbebb661365
3,230
cpp
C++
adaptors/default/job/test/test_job_get_stdio.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
adaptors/default/job/test/test_job_get_stdio.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
adaptors/default/job/test/test_job_get_stdio.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
#include <saga/saga.hpp> int main (int argc, char** argv) { int err = 0; try { ///////////////////////////////////////////////////////////////////////// // get_stdin/get_stdou/get_stderr are best tested in combination, so that // we can see if what is entered on stdin arrives at stdout/stderr. ///////////////////////////////////////////////////////////////////////// namespace sja = saga::job::attributes; namespace sa = saga::attributes; ///////////////////////////////////////////////////////////////////////// // create cat job, write to i, and check output { saga::session s; saga::job::service js (s, "fork://localhost"); saga::job::description jd; jd.set_attribute (sja::description_executable, "/bin/sh"); jd.set_attribute (sja::description_interactive, sa::common_true); std::vector <std::string> args; args.push_back ("-c"); args.push_back ("/usr/bin/bc -ql"); jd.set_vector_attribute (sja::description_arguments, args); saga::job::job j = js.create_job (jd); saga::job::ostream my_in = j.get_stdin (); saga::job::istream my_out = j.get_stdout (); saga::job::istream my_err = j.get_stderr (); j.run (); my_in << "6*7\n" << std::flush; my_in << "quit\n" << std::flush; std::string output = ""; char buffer[1024*64]; while ( my_out.good () ) { my_out.read (buffer, sizeof (buffer)); if ( my_out.gcount () > 0 ) { output += buffer; } } if ( output != "42\n" ) { std::cerr << "Expected Output to be '42\\n', not " << output << std::endl; err++; } j.wait (); } ///////////////////////////////////////////////////////////////////////// // do just the same, but switch stdout and stderr in the shell, using // { saga::session s; saga::job::service js (s, "fork://localhost"); saga::job::description jd; jd.set_attribute (sja::description_executable, "/bin/sh"); jd.set_attribute (sja::description_interactive, sa::common_true); std::vector <std::string> args; args.push_back ("-c"); args.push_back ("/usr/bin/bc -ql 3>&1 1>&2 2>&3"); jd.set_vector_attribute (sja::description_arguments, args); saga::job::job j = js.create_job (jd); saga::job::ostream my_in = j.get_stdin (); saga::job::istream my_out = j.get_stdout (); saga::job::istream my_err = j.get_stderr (); j.run (); my_in << "6*7\n" << std::flush; my_in << "quit\n" << std::flush; std::string output = ""; char buffer[1024*64]; while ( my_err.good () ) { my_err.read (buffer, sizeof (buffer)); if ( my_err.gcount () > 0 ) { output += buffer; } } if ( output != "42\n" ) { std::cerr << "Expected Output to be '42\\n', not " << output << std::endl; err++; } j.wait (); } } catch ( const saga::exception & e ) { std::cerr << "Exception: " << e.what () << std::endl; err++; } return err; }
25.84
82
0.478947
[ "vector" ]
62ccdf63f5a8fd01ce8c182de18498c5ecdf8d00
2,052
cpp
C++
Codeforces/594D.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Codeforces/594D.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Codeforces/594D.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <bits/stdc++.h> #define MAXN 200005 #define MAXM 1000005 #define fi first #define se second using namespace std; const int M=1e9+7; int n,m,l,r,a[MAXN],ans[MAXN],c[MAXN],mul[MAXN],imul[MAXN]; int tot,prime[MAXM],inv[MAXM],las[MAXM]; bool not_prime[MAXM]; vector <pair<int,int> > q[MAXN]; vector <int> f[MAXM]; inline int fpow(int a,int b) { int r=1; for (;b;b>>=1,a=1LL*a*a%M) if (b&1) r=1LL*r*a%M; return r; } inline int lowbit(int x){return x&-x;} inline void modify(int x,int v){for (;x<=n;x+=lowbit(x)) c[x]=1LL*c[x]*v%M;return ;} inline int query(int x){int r=1;for (;x;x-=lowbit(x)) r=1LL*r*c[x]%M;return r;} inline int query(int l,int r){return 1LL*query(r)*fpow(query(l-1),M-2)%M;} inline int prod(int l,int r){return 1LL*mul[r]*imul[l-1]%M;} inline void LinearShaker(int n=1000000) { for (int i=2;i<=n;i++) { if (!not_prime[i]) prime[++tot]=i; for (int j=1;i*prime[j]<=n;j++) { not_prime[i*prime[j]]=true; if (!(i%prime[j])) break; } } inv[1]=1; for (int i=2;i<=n;i++) inv[i]=1LL*(M-M/i)*inv[M%i]%M; return ; } inline void fac(int x) { int p=x;if (f[x].size()) return ; for (int i=1;prime[i]*prime[i]<=x;i++) if (!(x%prime[i])) { f[p].push_back(prime[i]); while (!(x%prime[i])) x/=prime[i]; } if (x>1) f[p].push_back(x); return ; } inline void add(int x) { for (auto v:f[a[x]]) { if (las[v]) modify(las[v],1LL*v*inv[v-1]%M); modify(x,1LL*(v-1)*inv[v]%M); las[v]=x; } return ; } inline void read(int &x) { x=0;char ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return ; } int main() { LinearShaker();read(n);mul[0]=imul[0]=1; for (int i=1;i<=n;i++) { read(a[i]),fac(a[i]),c[i]=1; mul[i]=1LL*mul[i-1]*a[i]%M; imul[i]=1LL*imul[i-1]*inv[a[i]]%M; } read(m); for (int i=1;i<=m;i++) { read(l);read(r); q[r].push_back({l,i}); } for (int i=1;i<=n;i++) { add(i); for (auto v:q[i]) ans[v.se]=1LL*prod(v.fi,i)*query(v.fi,i)%M; } for (int i=1;i<=m;i++) printf("%d\n",ans[i]); return 0; }
20.316832
84
0.568713
[ "vector" ]
62d12bff1094bae8f720c96312d2febc5cc197f0
1,099
hpp
C++
Shell.hpp
iliaskap12/my-shell
62dac3d40496fc58c48a6753325848322a60ccc9
[ "Unlicense" ]
null
null
null
Shell.hpp
iliaskap12/my-shell
62dac3d40496fc58c48a6753325848322a60ccc9
[ "Unlicense" ]
null
null
null
Shell.hpp
iliaskap12/my-shell
62dac3d40496fc58c48a6753325848322a60ccc9
[ "Unlicense" ]
null
null
null
// // Created by ilias on 9/8/21. // #ifndef MY_SHELL_SHELL_HPP #define MY_SHELL_SHELL_HPP #include "Builtin.hpp" using builtinFunctionPointer_t = Status (Builtin::*)(const std::vector<std::string>&) const; using commandToFunctionMap_t = const std::unordered_map<std::string, builtinFunctionPointer_t>; class Shell { private: const std::string home_directory_{ secure_getenv("HOME") }; std::vector<std::string> tokens_{ std::vector<std::string>() }; std::vector<char*> c_string_tokens_{ std::vector<char*>() }; const Builtin builtin_{ Builtin(this) }; const commandToFunctionMap_t builtin_map_{ builtin_.getBuiltinCommands() }; public: Shell(); void launch(); [[nodiscard]] const std::string& getHomeDirectory() const; private: static std::string readInput(); void tokenizeInput(); Status interpretCommand() const; [[nodiscard]] Status launchBuiltin(const std::string& builtin) const; Status launchProgram() const; void launchChildProcess() const; void handleChildProcessExit(pid_t process_id) const; }; #endif //MY_SHELL_SHELL_HPP
28.921053
95
0.722475
[ "vector" ]
62dd920aff199a2ef2955dbbe9a50d6cea2e581b
2,865
hpp
C++
Client/src/Client/Game.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
Client/src/Client/Game.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
Client/src/Client/Game.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
#pragma once //SELF //LIBS #include <Core/Window/Window.hpp> #include <Core/Input/Input.hpp> #include <Core/IMGUI/IMGUI.hpp> #include <Core/Raytrace/Ray.hpp> #include <Core/Raytrace/Scene.hpp> #include <Core/Raytrace/Frame.hpp> #include <Core/Raytrace/Camera.hpp> #include <Core/Raytrace/Shape/Shape.hpp> #include <Core/Raytrace/Material/Material.hpp> #include <Core/Texture/TextureGL.hpp> #include <threadpool/threadpool.hpp> //STD #include <array> #include <chrono> namespace core { class WindowSDL; } namespace rico::client { class Game { public: static int add(int, int); Game(); ~Game(); int run(); void events(); void update(float dt); void render(); private: void raytrace_chunk(std::size_t start, std::size_t end); void raytrace(); std::chrono::high_resolution_clock::time_point previous; float delta; std::unique_ptr<core::Window> window; core::WindowSDL* window_sdl = nullptr; //todo: not needed when we have proper abstractions everywhere void* glc; //todo: hide in renderer? core::Input input; //todo: remove once we have some IMGUI windows we can use instead, or maybe hide behind a special key bool show_demo_window = true; //todo: lots of openGL specific stuff, that should live... somewhere else std::array<float, 6> vertices{ 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f }; const char* vertexSource = "attribute vec4 position; \n" "void main() \n" "{ \n" " gl_Position = vec4(position.xyz, 1.0); \n" "} \n"; const char* fragmentSource = "precision mediump float;\n" "void main() \n" "{ \n" " gl_FragColor = vec4 (1.0, 1.0, 1.0, 1.0 );\n" "} \n"; std::unique_ptr<core::IMGUI> imgui; // Raytracing core::Camera camera; core::Frame render_frame; core::Frame update_frame; core::Scene scene; std::unique_ptr<core::TextureGL> texture; zx::threadpool<> pool; std::mutex super_cool_mutex; std::mutex super_cool_mutex2; std::atomic<float> percentage = 0.0f; std::size_t max_samples = 1; std::atomic<int> current_samples = 0; std::thread raytracer_thread; std::atomic<bool> raytracing = true; core::Camera::Settings cam_settings; core::Sphere sphere1; core::Sphere sphere2; core::Sphere sphere3; core::Sphere sphere4; bool skip = false; bool dirty = false; }; } // namespace rico::client
28.65
105
0.558115
[ "render", "shape" ]
62fc58912c6e4e29a09d5265fa2ae03b19b354ce
2,226
cpp
C++
competitive programming/leetcode/733. Flood Fill.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/leetcode/733. Flood Fill.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/leetcode/733. Flood Fill.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. At the end, return the modified image. Example 1: Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. Note: The length of image and image[0] will be in the range [1, 50]. The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. class Solution { public: bool isSafe(vector<vector<int> > &image, int sr, int sc, int c, int nc){ return (sr>=0 && sr<image.size() && sc>=0 && sc<image[0].size() && image[sr][sc]==c); } void dfs(vector<vector<int> > &image, int sr, int sc, int c, int nc){ image[sr][sc]=nc; if(isSafe(image, sr-1, sc, c, nc)) dfs(image, sr-1, sc, c, nc); // top if(isSafe(image, sr, sc+1, c, nc)) dfs(image, sr, sc+1, c, nc); // right if(isSafe(image, sr+1, sc, c, nc)) dfs(image, sr+1, sc, c, nc); // bottom if(isSafe(image, sr, sc-1, c, nc)) dfs(image, sr, sc-1, c, nc); // left } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int nc) { int c=image[sr][sc]; if(c!=nc){ dfs(image, sr, sc, c, nc); // <image, row, column, color, new color } return image; } };
37.728814
108
0.647799
[ "vector" ]
62ffe13ca3d9e7dc671aa1433502791b9b928bfb
1,252
hh
C++
commands/tri-cmd.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
commands/tri-cmd.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
commands/tri-cmd.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 FAINT_TRI_CMD_HH #define FAINT_TRI_CMD_HH #include "commands/command.hh" #include "geo/tri.hh" #include "text/utf8-string.hh" #include "util/distinct.hh" namespace faint{ class Object; using NewTri = Order<Tri>::New; using OldTri = Order<Tri>::Old; enum class MergeMode { // Whether a TriCommand wants to merge with consecutive TriCommands // targetting the same object. SOCIABLE, SOLITARY}; CommandPtr tri_command(Object*, const NewTri&, const OldTri&, const utf8_string& name="Adjust", MergeMode=MergeMode::SOLITARY); std::unique_ptr<class MergeCondition> append_tri_commands(); } // namespace #endif
27.217391
70
0.744409
[ "object" ]
1a061e0c38efcbcac77818a301da1be3358383d8
2,255
cpp
C++
vox.render/lighting/sprite/sprite_debug.cpp
ArcheGraphics/Arche-cpp
da6770edd4556a920b3f7298f38176107caf7e3a
[ "MIT" ]
8
2022-02-15T12:54:57.000Z
2022-03-30T16:35:58.000Z
vox.render/lighting/sprite/sprite_debug.cpp
yangfengzzz/DigitalArche
da6770edd4556a920b3f7298f38176107caf7e3a
[ "MIT" ]
null
null
null
vox.render/lighting/sprite/sprite_debug.cpp
yangfengzzz/DigitalArche
da6770edd4556a920b3f7298f38176107caf7e3a
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Feng Yang // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include "sprite_debug.h" #include "sprite_debug_material.h" #include "mesh/mesh_renderer.h" #include "lighting/light_manager.h" #include "entity.h" namespace vox { std::string SpriteDebug::name() { return "SpriteDebug"; } SpriteDebug::SpriteDebug(Entity *entity) : Script(entity) { Shader::create("spotlight_sprite_debug", std::make_unique<WGSLSpriteDebugVertex>(true), std::make_unique<WGSLSpriteDebugFragment>()); Shader::create("pointlight_sprite_debug", std::make_unique<WGSLSpriteDebugVertex>(false), std::make_unique<WGSLSpriteDebugFragment>()); _spotLightMesh = std::make_shared<BufferMesh>(); _spotLightMesh->addSubMesh(0, 4, wgpu::PrimitiveTopology::TriangleStrip); _spotEntity = entity->createChild(); auto spotRenderer = _spotEntity->addComponent<MeshRenderer>(); spotRenderer->setMaterial(std::make_shared<SpriteDebugMaterial>(entity->scene()->device(), true)); spotRenderer->setMesh(_spotLightMesh); _pointLightMesh = std::make_shared<BufferMesh>(); _pointLightMesh->addSubMesh(0, 4, wgpu::PrimitiveTopology::TriangleStrip); _pointEntity = entity->createChild(); auto pointRenderer = _pointEntity->addComponent<MeshRenderer>(); pointRenderer->setMaterial(std::make_shared<SpriteDebugMaterial>(entity->scene()->device(), false)); pointRenderer->setMesh(_pointLightMesh); } void SpriteDebug::onUpdate(float deltaTime) { auto spotLightCount = LightManager::getSingleton().spotLights().size(); if (spotLightCount > 0) { _spotLightMesh->setInstanceCount(static_cast<uint32_t>(spotLightCount)); _spotEntity->setIsActive(true); } else { _spotEntity->setIsActive(false); } auto pointLightCount = LightManager::getSingleton().pointLights().size(); if (pointLightCount > 0) { _pointLightMesh->setInstanceCount(static_cast<uint32_t>(pointLightCount)); _pointEntity->setIsActive(true); } else { _pointEntity->setIsActive(false); } } }
37.583333
104
0.716186
[ "mesh" ]
1a0c48fbee83fcb607711d733dd24434a71218c3
64,004
hpp
C++
src/ScaFES_Parameters.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/ScaFES_Parameters.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/ScaFES_Parameters.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* ScaFES * Copyright (c) 2011-2018, ZIH, TU Dresden, Federal Republic of Germany. * For details, see the files COPYING and LICENSE in the base directory * of the package. */ /** * @file ScaFES_Parameters.hpp * @brief Contains the class Parameters. */ #ifndef SCAFES_PARAMETERS_HPP_ #define SCAFES_PARAMETERS_HPP_ #include "ScaFES_Config.hpp" #include "ScaFES_Communicator.hpp" #include "ScaFES_Environment.hpp" #include <cstdlib> #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <string> #ifdef SCAFES_HAVE_BOOST_SERIALIZATION #include <boost/serialization/serialization.hpp> #endif // #ifdef SCAFES_HAVE_BOOST_SERIALIZATION // namespace boost // { // namespace serialization // { // class access; // } // } // #include <boost/serialization/vector.hpp> // #include <boost/serialization/version.hpp> // #endif #ifdef SCAFES_HAVE_BOOST_PROGRAM_OPTIONS #include <boost/program_options.hpp> #endif #ifdef SCAFES_HAVE_BOOST #include <boost/lexical_cast.hpp> #include <boost/format.hpp> #endif #ifdef SCAFES_HAVE_BOOST_REGEX #include <boost/regex.hpp> #endif #include "ScaFES_Ntuple.hpp" namespace ScaFES { #ifdef SCAFES_HAVE_BOOST_PROGRAM_OPTIONS namespace po = boost::program_options; #endif /******************************************************************************* ******************************************************************************/ /** * \class Parameters * @brief The class \c Parameters contains all parameters related to ScaFES. * * Parameters can be given via the command line. * If a command line parameter is invalid, a help message will be displayed. * * The MPI environment lives as long as an instance of this class is living. * In particular, if the destructor of this class is called, * the MPI environment will be finalized. Thus, if the descructor is called * too early, the instance of the calls goes out of scope. So, please be careful * with calls to the destructor of this class. * * \remarks The master MPI process reads in the command line arguments * and distributed the parameters to all other MPI processes. */ class Parameters { public: /*---------------------------------------------------------------------- | FRIEND CLASSES. ----------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION friend class boost::serialization::access; #endif /*---------------------------------------------------------------------- | LIFE CYCLE METHODS. ----------------------------------------------------------------------*/ // // /** Creates own default constructor. */ // // Parameters(); /** Creates own constructor from command line parameters. * Parses the command line of a program call and provides a help * message. */ Parameters(int argc, char* argv[]); /** Creates own copy constructor. */ Parameters(const Parameters& rhs); /** Creates own destructor. */ ~Parameters(); /** Creates own assignment operator. */ Parameters& operator=(Parameters rhs); /*---------------------------------------------------------------------- | GETTER METHODS. ----------------------------------------------------------------------*/ /** Returns the space dimension. */ const int& dim() const; /** Returns the number of grid nodes in each dimension. */ const std::vector<int>& nNodes() const; /** Returns the coordinates of the first grid point. */ const std::vector<double>& coordNodeFirst() const; /** Returns the coordinates of the last grid point. */ const std::vector<double>& coordNodeLast() const; /** Returns the number of partitions in each direction. */ const std::vector<int>& nPartitions() const; /** Returns the directions in which the grid should be partitioned. */ const std::vector<bool>& divideGrid() const; /** Returns the decision if the kind field should be read in. */ const bool& readKindFile() const; /** Returns if the kind field should be written to file. */ const bool& writeKindFile() const; /** Returns the name of the kind file. */ const std::string& kindFile() const; /** Returns the name of the domain decomposition approach. */ const std::string& typeDomainDecomp() const; /** Returns the name of the partition file for writing. */ const std::string& nameWritePartitionFile() const; /** Returns the decision if a partition file should be written. */ const bool& writePartitionFile() const; /** Returns the name of the partition file for reading. */ const std::string& nameReadPartitionFile() const; /** Returns the decision if a partition file should be written. */ const bool& readPartitionFile() const; /** Returns the start of the time interval. */ const double& timeIntervalStart() const; /** Returns the end of the time interval. */ const double& timeIntervalEnd() const; /** Returns the number of time steps. */ const int& nTimesteps() const; /** Returns time step width. */ const double& tau() const; /** Returns threshold for convergence check. */ const double& threshold() const; /** Returns the number of iteration when convergence should be checked * for the first time. */ const int& checkConvFirstAtIter() const; /** Returns the number of iterations between two convergence checks. */ const int& checkConvAtEveryNIter() const; /** Returns the number of snapshots. */ const int& nSnapshots() const; /** Returns the number of layers at the border. */ const int& nLayersAtBorder() const; /** Returns the decision if an output file should be written. */ const bool& writeDataFile() const; /** Returns the name of the output file. */ const std::string& nameDataFile() const; /** Returns the name of the config file. */ const std::string& nameConfigFile() const; /** Returns the name of the config file. */ const std::string& nameInitFile() const; /** Returns the decision if an init file should be read. */ const bool& readInitFile() const; /** Returns the decision if known datafields should be initialized * from init file. */ const bool& initKnownDfs() const; /** Returns if ADOL-C is enabled. */ const bool& enabledAdolc() const; /** Returns if asynchronous MPI communication is enabled. */ const bool& asynchronMode() const; /** Returns if the Boost.MPI skeleton concept for the MPI communication * will be used. */ const bool& useBoostMpiSkeletonConcept() const; /** Returns if gradients should be computed. */ const bool& computeGradients() const; /** Returns if gradients should be checked. */ const bool& checkGradients() const; /** Returns the MPI rank for output. */ int rankOutput() const; /** Returns the MPI communicator. */ const ScaFES::Communicator& myWorld() const; /** Returns the environment. */ const ScaFES::Environment& myEnv() const; /** Returns the MPI rank. */ int rank() const; /** Returns the maximal output level at the console. */ int outputLevelMax() const; /** Returns the current output level at the console. */ int outputLevelCurr() const; /** Returns the maximum level of console output. */ const int& indentDepth() const; /*---------------------------------------------------------------------- | SETTER METHODS. ----------------------------------------------------------------------*/ /** Increase output level by one. */ void increaseLevel(); /** Decrease output level by one. */ void decreaseLevel(); /*---------------------------------------------------------------------- | COMPARISON METHODS. ----------------------------------------------------------------------*/ /** Tests if two grids are equal. */ bool operator==(const Parameters& rhs) const; /** Tests if two grids are not equal. */ bool operator!=(const Parameters& rhs) const; /*---------------------------------------------------------------------- | WORK METHODS. ----------------------------------------------------------------------*/ /** Sets a prefix to the output of process with MPI rank. */ std::string getPrefix(const std::string& nameFramework = std::string("ScaFES ")) const; /*---------------------------------------------------------------------- | FREE METHODS WHICH ARE FRIENDS OF THIS CLASS. ----------------------------------------------------------------------*/ /** Swaps to elements of this class. */ friend void swap(Parameters& first, Parameters& second); private: /*---------------------------------------------------------------------- | WORK METHODS. ----------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST /** Checks a parameter given by its name. */ template <typename TT> void checkParameter(const po::variables_map& vm, const std::string& nameParam, std::vector<TT>& param, bool isNecessary); /** Checks a parameter with floating point values given by its name. */ template <typename TT> void checkParameterDouble(const po::variables_map& vm, const std::string& nameParam, std::vector<TT>& param, bool isNecessary); #endif #ifdef SCAFES_HAVE_BOOST_SERIALIZATION /** Serializes class. */ template <class Archive> void serialize(Archive& ar, const unsigned int version); #endif /*---------------------------------------------------------------------- | MEMBER VARIABLES. ----------------------------------------------------------------------*/ /** Space dimension. */ int mDim; /** Number of grid nodes in each dimension. */ std::vector<int> mNnodes; /** Coordinate of first grid point (left lower point of grid). */ std::vector<double> mCoordNodeFirst; /** Coordinate of last grid point (right upper point of grid). */ std::vector<double> mCoordNodeLast; /** Number of partitions in each direction. */ std::vector<int> mNpartitions; /** Divide grid into partitions: Which directions are enabled? */ std::vector<bool> mDivideGrid; /** Read kind field from a given kind file? */ bool mReadKindFile; /** Write kind field? */ bool mWriteKindFile; /** Name of the kind file. */ std::string mKindFile; /** Type of domain decomposition. */ std::string mTypeDomainDecomp; /** Write partition table to a partition file? */ bool mWritePartitionFile; /** Name of partition file which should be written. */ std::string mNameWritePartitionFile; /** Read partition table from a partition file? */ bool mReadPartitionFile; /** Name of the partition file which should be read in. */ std::string mNameReadPartitionFile; /** Start of time interval [tstart;tend]. */ double mTimeIntervalStart; /** End of time interval [tstart;t_end]. */ double mTimeIntervalEnd; /** Number of timesteps. */ int mNtimesteps; /** Time step width. */ double mTau; /** Threshold for convergence check. */ double mThreshold; /** Number of iteration when convergence should be checked * for the first time. */ int mCheckConvFirstAtIter; /** Number of iterations between two convergence checks. */ int mCheckConvAtEveryNIter; /** Number of snapshots: Write data each m timesteps. */ int mNsnapshots; /** Number of layers at the border. */ int mNlayersAtBorder; /** Write output file? */ bool mWriteDataFile; /** Name of the output file. */ std::string mNameOfDataFile; /** Name of the configuration file. */ std::string mNameOfConfigFile; /** Name of the initialization file. */ std::string mNameOfInitFile; /** Read init file? */ bool mReadInitFile; /** Initialize known datafields from file? */ bool mInitKnownDfs; /** Is ADOL-C enabled? */ bool mEnabledAdolc; /** Is asynchronous MPI communication enabled? */ bool mAsynchronMode; /** Use Boost.MPI skeleton concept for the MPI communication? */ bool mUseBoostMpiSkeletonConcept; /** Should gradients be computed? */ bool mComputeGradients; /** Should gradients be checked? */ bool mCheckGradients; /** MPI rank for output. */ int mRankOutput; /** MPI environment. */ ScaFES::Environment mMyEnv; /** MPI communicator. */ ScaFES::Communicator mMyWorld; /** Maximal indentation depth level of console output. */ int gOutputLevelMax; /** Current indentation depth level of console output. */ int gOutputLevelCurr; }; // End of class. // /******************************************************************************* * LIFE CYCLE METHODS. ******************************************************************************/ inline Parameters::Parameters(int argc, char* argv[]) : mDim(3) , mNnodes(3) , mCoordNodeFirst(3) , mCoordNodeLast(3) , mNpartitions(3) , mDivideGrid(3) , mReadKindFile(false) , mWriteKindFile(false) , mKindFile("EMPTY") , mTypeDomainDecomp("RCB") , mWritePartitionFile(false) , mNameWritePartitionFile("EMPTY") , mReadPartitionFile(false) , mNameReadPartitionFile("EMPTY") , mTimeIntervalStart(0.0) , mTimeIntervalEnd(1.0) , mNtimesteps(1) , mTau((mTimeIntervalEnd-mTimeIntervalStart)/mNtimesteps) , mThreshold(0.00001) , mCheckConvFirstAtIter(1) , mCheckConvAtEveryNIter(1) , mNsnapshots(1) , mNlayersAtBorder(1) , mWriteDataFile(false) , mNameOfDataFile("EMPTYDATAFILE") , mNameOfConfigFile("EMPTYCONFIGFILE") , mNameOfInitFile("EMPTYINITFILE") , mReadInitFile(false) , mInitKnownDfs(false) , mEnabledAdolc(false) , mAsynchronMode(true) , mUseBoostMpiSkeletonConcept(true) , mComputeGradients(false) , mCheckGradients(false) , mRankOutput(0) , mMyEnv(argc, argv) , mMyWorld(argc, argv) , gOutputLevelMax(2) , gOutputLevelCurr(gOutputLevelMax) { // if (0 == this->myWorld().rank()) // { #ifdef SCAFES_HAVE_BOOST po::variables_map vm; /*---------------------------------------------------------------------- | Describe the options of the command line. ----------------------------------------------------------------------*/ po::options_description desc("Available ScaFES parameters"); desc.add_options()("help", "Displays this help message.")( "dim", po::value<int>(), "Sets the space dimension.")( "nPartitions", po::value<std::string>(), "Sets the number of partitions in each dimension (Np1x..xNpd).")( "typeDomainDecomposition", po::value<std::string>(), "Sets the type of domain decomposition: RCB (RCB algorithm), UNI " "(Uniform decomposition in each direction).")( "nNodes", po::value<std::string>(), "Sets the number of grid nodes in each dimension (N1x..xNd).")( "coordNodeFirst", po::value<std::string>(), "Sets the coordinates of the first grid node (c1x..xcd).")( "coordNodeLast", po::value<std::string>(), "Sets the coordinates of the last grid node (c1x..xcd).")( "divideGrid", po::value<std::string>(), "Divides the grid in which dimension? (g1x..xgd).")( "readKindFile", po::value<std::string>(), "Reads the kind field from a given kind file.")( "writeKindFile", po::value<int>(), "Sets if the kind field should be written to a NetCDF data file, yes=1, no=0 (default=0).")( "readPartitionfile", po::value<std::string>(), "Reads the partition table from a given partition file.")( "writePartitionfile", po::value<std::string>(), "Writes the partition table to a given partition file.")( "starttime", po::value<double>(), "Sets the start time.")( "endtime", po::value<double>(), "Sets the end time.")( "nTimesteps", po::value<int>(), "Sets the number of time steps (=#{time intervals} (default=0).")( "tau", po::value<double>(), "Sets the time step width.")( "threshold", po::value<double>(), "Sets the threshold for convergence check.")( "checkConvFirstAtIter", po::value<int>(), "Sets the number of iteration when convergence " "should be checked for the first time.")( "checkConvAtEveryNIter", po::value<int>(), "Sets the number of iterations between two convergence checks.")( "nSnapshots", po::value<int>(), "Sets how many times the data " "fields are written to output " "(default=1).")( "nLayersAtBorder", po::value<int>(), "Sets of how many layers the border should consist (default=1).")( "outputfile", po::value<std::string>(), "Sets the name of the output data file.")( "configfile", po::value<std::string>(), "Sets the name of the config file.")( "initfile", po::value<std::string>(), "Sets the name of the init file.")( "initKnownDfs", po::value<int>(), "Sets if known datafields should be init from file.")( "enabledAdolc", po::value<int>(), "Sets if ADOL-C should be enabled, 1=yes, 0=no (default=0).")( "asynchronMode", po::value<int>(), "Sets if asynchronous MPI " "communication should be used, 1=yes, 0=no " "(default=1).")( "useBoostMpiSkeletonConcept", po::value<int>(), "Sets if the Boost.MPI skeleton " "concept should be used for the MPI communication, " "1=yes, 0=no " "(default=1).")( "computeGradients", po::value<int>(), "Sets if gradients should be computed, 1=yes, 0=no (default=0).")( "checkGradients", po::value<int>(), "Sets if gradients of forward " "computation should be checked, " "1=yes, 0=no " "(default=0).")( "rankOutput", po::value<int>(), "Sets the rank of the MPI process whose output should be displayed " "(default=0).")("outputlevel", po::value<int>(), "Controls the amount of console output."); /*---------------------------------------------------------------------- | Try to parse the command line. ----------------------------------------------------------------------*/ try { po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(); po::store(parsed, vm); po::notify(vm); } catch (std::exception& e) { throw std::runtime_error("Wrong command line options."); } /*---------------------------------------------------------------------- | Actions of command line options. ----------------------------------------------------------------------*/ if (vm.count("help")) { std::cout << desc << "\n"; this->mMyEnv.abort(this->mMyWorld,0); } else { /*---------------------------------------------------------------------- | NECESSARY PARAMETERS. ----------------------------------------------------------------------*/ if (vm.count("dim")) { this->mDim = vm["dim"].as<int>(); if (0 >= this->dim()) { std::cerr << "\nERROR: Space dimension is less or equal" " to zero. Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nERROR: Use --dim=<integral value>.\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } /*--------------------------------------------------------------------*/ this->mNnodes.resize(this->dim()); this->checkParameter(vm, "nNodes", mNnodes, true); /*--------------------------------------------------------------------*/ if (vm.count("nTimesteps")) { this->mNtimesteps = vm["nTimesteps"].as<int>(); if (0 > this->nTimesteps()) { std::cerr << "\nERROR: Number of time steps is negative." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --nTimesteps=<integral value>.\n\n"; } /*--------------------------------------------------------------------*/ this->mCoordNodeLast.resize(this->dim()); this->checkParameterDouble(vm, "coordNodeLast", this->mCoordNodeLast, true); /*---------------------------------------------------------------------- | OPTIONAL PARAMETERS. ----------------------------------------------------------------------*/ this->mCoordNodeFirst.resize(this->dim()); this->checkParameterDouble(vm, "coordNodeFirst", this->mCoordNodeFirst, false); /*--------------------------------------------------------------------*/ if (vm.count("typeDomainDecomposition")) { this->mTypeDomainDecomp = vm["typeDomainDecomposition"].as<std::string>(); } else { std::cerr << "\nREMARK: Set default --typeDomainDecomposition=RCB.\n\n"; } /*--------------------------------------------------------------------*/ this->mNpartitions.resize(this->dim()); if (vm.count("nPartitions")) { this->checkParameter(vm, "nPartitions", this->mNpartitions, false); int nPartitionsTotal = 1; for (std::size_t ii = 0; ii < this->nPartitions().size(); ++ii) { nPartitionsTotal *= (this->mNpartitions.at(ii)); } if (nPartitionsTotal != this->mMyWorld.size()) { std::cerr << "\nERROR: #{Partitions} != #{MPI processes}." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Set nPartitions = [nMPIprocs 1,...,1].\n\n"; /* If the number of partitions is not given at the command line, * set the number from the number of generated MPI processes: * nPartitions = [MPI_size(), 1, ..., 1]. */ this->mNpartitions.at(0) = this->mMyWorld.size(); for (std::size_t ii = 1; ii < this->nPartitions().size(); ++ii) { this->mNpartitions.at(ii) = 1; } } /*--------------------------------------------------------------------*/ this->mDivideGrid.resize(this->dim()); this->checkParameter(vm, "divideGrid", this->mDivideGrid, false); /*--------------------------------------------------------------------*/ if (vm.count("readKindFile")) { this->mKindFile = vm["readKindFile"].as<std::string>(); this->mReadKindFile = true; } else { std::cerr << "\nREMARK: Use --readKindFile=<name>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("writeKindFile")) { int tmpWriteKindFile = vm["writeKindFile"].as<int>(); if (0 == tmpWriteKindFile) { this->mWriteKindFile = false; } else { this->mWriteKindFile = true; } } else { std::cerr << "\nREMARK: Use --writeKindFile=<0/1>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("useBoostMpiSkeletonConcept")) { int tmpUseBoostMpiSkeletonConcept = vm["useBoostMpiSkeletonConcept"].as<int>(); if (0 == tmpUseBoostMpiSkeletonConcept) { this->mUseBoostMpiSkeletonConcept = false; } else { this->mUseBoostMpiSkeletonConcept = true; } } else { std::cerr << "\nREMARK: Use --useBoostMpiSkeletonConcept=<0/1>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("readPartitionFile")) { this->mNameReadPartitionFile = vm["readPartitionfile"].as<std::string>(); this->mReadPartitionFile = true; } else { std::cerr << "\nREMARK: Use --readPartitionfile=<name>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("writePartitionfile")) { this->mNameWritePartitionFile = vm["writePartitionfile"].as<std::string>(); this->mWritePartitionFile = true; } else { std::cerr << "\nREMARK: Use --writePartitionfile=<name>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("starttime")) { this->mTimeIntervalStart = vm["starttime"].as<double>(); if (0.0 > this->timeIntervalStart()) { std::cerr << "\nERROR: Start time < 0.0." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --starttime=<real value>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("endtime")) { this->mTimeIntervalEnd = vm["endtime"].as<double>(); if (0.0 >= this->timeIntervalEnd()) { std::cerr << "\nERROR: End time <= 0.0." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --endtime=<real value>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("tau")) { this->mTau = vm["tau"].as<double>(); if (0.0 >= this->tau()) { std::cerr << "\nERROR: Time step width tau <= 0.0. " " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else if (vm.count("endtime") && vm.count("nTimesteps")) { if (0 == this->nTimesteps()) { this->mTau = 0.0; } else { this->mTau = (this->timeIntervalEnd() - this->timeIntervalStart()) / this->nTimesteps(); } } else { this->mTau = 1.0; std::cerr << "REMARK: No time step width tau was specified.\n" " Set tau=1.0 and proceeded. \n\n"; std::cerr << "\nREMARK: Use --tau=<real value>.\n\n"; } if (vm.count("tau") && vm.count("endTime") && vm.count("nTimesteps")) { if (this->mTau != (this->timeIntervalEnd() - this->timeIntervalStart()) / this->nTimesteps()) { std::cerr << "\nERROR: Inconsistency between time step width, " "number of time steps and time interval. Exit...\n\n"; exit(-1); } } /*--------------------------------------------------------------------*/ if (vm.count("threshold")) { this->mThreshold = vm["threshold"].as<double>(); if (0.0 > this->threshold()) { std::cerr << "\nWARNING: Threshold < 0.0." << std::endl; this->mThreshold = std::fabs(this->threshold()); std::cerr << "threshold = fabs(threshold)." << "\n" << std::endl; } } else { std::cerr << "\nREMARK: Use --threshold=<real value>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("checkConvFirstAtIter")) { this->mCheckConvFirstAtIter = vm["checkConvFirstAtIter"].as<int>(); if (1 > this->checkConvFirstAtIter()) { std::cerr << "\nWARNING: CheckConvFirstAtIter < 1." << std::endl; this->mCheckConvFirstAtIter = 1; std::cerr << "checkConvFirstAtIter = 1." << "\n" << std::endl; } } else { std::cerr << "\nREMARK: Use --checkConvFirstAtIter=<int>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("checkConvAtEveryNIter")) { this->mCheckConvAtEveryNIter = vm["checkConvAtEveryNIter"].as<int>(); if (1 > this->checkConvAtEveryNIter()) { std::cerr << "\nWARNING: CheckConvAtEveryNIter < 1." << std::endl; this->mCheckConvAtEveryNIter = 1; std::cerr << "checkConvAtEveryNIter = 1." << "\n" << std::endl; } } else { std::cerr << "\nREMARK: Use --checkConvAtEveryNIter=<int>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("nSnapshots")) { this->mNsnapshots = vm["nSnapshots"].as<int>(); if (0 >= nSnapshots()) { std::cerr << "\nERROR: Number of snap shots is less or equal" " to zero. It has to be greater or equal to one." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --nSnapshots=<integral value>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("nLayersAtBorder")) { this->mNlayersAtBorder = vm["nLayersAtBorder"].as<int>(); for (std::size_t ii = 0; ii < this->nNodes().size(); ++ii) { if (this->nLayersAtBorder() >= (this->nNodes()[ii] / 2)) { std::cerr << "\nERROR: Number of layers at global border" " is too large (nLayers >= nNodes(ii)/2)." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } if (0 >= this->nLayersAtBorder()) { std::cerr << "\nERROR: Number of layers is less or equal" " to zero. It has to be greater or equal to one." " Exit...\n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --nLayersAtBorder=<integral value>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("outputfile")) { this->mNameOfDataFile = vm["outputfile"].as<std::string>(); this->mWriteDataFile = true; } else { std::cerr << "\nREMARK: Use --outputfile=<name>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("configfile")) { this->mNameOfConfigFile = vm["configfile"].as<std::string>(); } else { std::cerr << "\nREMARK: Use --configfile=<name>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("initfile")) { this->mNameOfInitFile = vm["initfile"].as<std::string>(); this->mReadInitFile = true; } else { std::cerr << "\nREMARK: Use --initfile=<name>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("initKnownDfs")) { int tmpInitKnownDfs = vm["initKnownDfs"].as<int>(); if (1 == tmpInitKnownDfs) { this->mInitKnownDfs = true; } else { this->mInitKnownDfs = false; } } else { std::cerr << "\nREMARK: Use --initKnownDfs=<YES/NO>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("enabledAdolc")) { int tmpEnabledAdolc = vm["enabledAdolc"].as<int>(); if (0 == tmpEnabledAdolc) { this->mEnabledAdolc = false; } else { this->mEnabledAdolc = true; #ifndef SCAFES_HAVE_ADOLC // Enforce disabling of ADOL-C mode if software was not // built with ADOL-C. std::cerr << "\nWARNING: Framework was NOT built with ADOL-C " "support!\n"; std::cerr << " ===> Enforced enabledAdolc=0!\n\n"; this->mEnabledAdolc = false; #endif } } else { std::cerr << "\nREMARK: Use --enabledAdolc=<0/1>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("asynchronMode")) { int tmpAsynchronMode = vm["asynchronMode"].as<int>(); if (0 == tmpAsynchronMode) { this->mAsynchronMode = false; } else { this->mAsynchronMode = true; } } else { std::cerr << "\nREMARK: Use --asynchronMode=<0/1>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("computeGradients")) { int tmpComputeGradients = vm["computeGradients"].as<int>(); if (0 == tmpComputeGradients) { this->mComputeGradients = false; } else { this->mComputeGradients = true; } } else { std::cerr << "\nREMARK: Use --computeGradients=<0/1>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("checkGradients")) { int tmpCheckGradients = vm["checkGradients"].as<int>(); if (0 == tmpCheckGradients) { this->mCheckGradients = false; } else { this->mCheckGradients = true; } } else { std::cerr << "\nREMARK: Use --checkGradients=<0/1>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("rankOutput")) { this->mRankOutput = vm["rankOutput"].as<int>(); if (static_cast<int>(this->rankOutput()) > this->myWorld().size() - 1) { throw std::runtime_error("rankOutput > rankMax."); } } else { std::cerr << "\nREMARK: Use --rankOutput=<integral value>.\n\n"; } /*--------------------------------------------------------------------*/ if (vm.count("outputlevel")) { gOutputLevelMax = vm["outputlevel"].as<int>(); gOutputLevelCurr = gOutputLevelMax; } else { std::cerr << "\nREMARK: Use --outputlevel=<integral value>.\n\n"; } } // End of if block related to "help". #else for (int ii = 0; ii < this->dim(); ++ii) { this->mNnodes.at(ii) = 32; this->mCoordNodeFirst.at(ii) = 0.0; this->mCoordNodeLast.at(ii) = 1.0; this->mDivideGrid.at(ii) = false; this->mNpartitions.at(ii) = 1; } this->mDivideGrid.at(0) = true; this->mNpartitions.at(0) = this->mMyWorld.size(); #endif // } // // // Communicate result. // // REMARK: Broadcasting all members using one call to broadcast() does // // not work at Juqueen! // // [KF, 04/22/2015] // //ScaFES::broadcast(this->mMyWorld, *this, 0); // // ScaFES::broadcast(this->mMyWorld, this->mDim, 0); // ScaFES::broadcast(this->mMyWorld, this->mNnodes, 0); // ScaFES::broadcast(this->mMyWorld, this->mCoordNodeFirst, 0); // ScaFES::broadcast(this->mMyWorld, this->mCoordNodeLast, 0); // ScaFES::broadcast(this->mMyWorld, this->mNpartitions, 0); // ScaFES::broadcast(this->mMyWorld, this->mDivideGrid, 0); // ScaFES::broadcast(this->mMyWorld, this->mReadKindFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mWriteKindFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mTypeDomainDecomp, 0); // ScaFES::broadcast(this->mMyWorld, this->mWritePartitionFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mNameWritePartitionFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mReadPartitionFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mNameReadPartitionFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mTimeIntervalEnd, 0); // ScaFES::broadcast(this->mMyWorld, this->mNtimesteps, 0); // ScaFES::broadcast(this->mMyWorld, this->mTau, 0); // ScaFES::broadcast(this->mMyWorld, this->mNsnapshots, 0); // ScaFES::broadcast(this->mMyWorld, this->mNlayersAtBorder, 0); // ScaFES::broadcast(this->mMyWorld, this->mWriteDataFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mNameOfDataFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mNameOfConfigFile, 0); // ScaFES::broadcast(this->mMyWorld, this->mEnabledAdolc, 0); // ScaFES::broadcast(this->mMyWorld, this->mAsynchronMode, 0); // ScaFES::broadcast(this->mMyWorld, this->mUseBoostMpiSkeletonConcept, 0); // ScaFES::broadcast(this->mMyWorld, this->mComputeGradients, 0); // ScaFES::broadcast(this->mMyWorld, this->mCheckGradients, 0); // ScaFES::broadcast(this->mMyWorld, this->mRankOutput, 0); // ScaFES::broadcast(this->mMyWorld, this->mMyWorld, 0); // ScaFES::broadcast(this->mMyWorld, this->gOutputLevelMax, 0); // ScaFES::broadcast(this->mMyWorld, this->gOutputLevelCurr, 0); } /*----------------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_MPI /** REMARK: Adding mMyEnv(rhs.myEnv()) results in the following compile error: * /usr/include/boost/mpi/environment.hpp:85:22: note: 'boost::mpi::environment::environment(const boost::mpi::environment&)' is implicitly deleted because the default definition would be ill-formed: class BOOST_MPI_DECL environment : noncopyable { ^ /usr/include/boost/mpi/environment.hpp:85:22: error: use of deleted function 'boost::noncopyable_::noncopyable::noncopyable(const boost::noncopyable_::noncopyable&)' */ inline Parameters::Parameters(const Parameters& rhs) : mDim(rhs.dim()) , mNnodes(rhs.nNodes()) , mCoordNodeFirst(rhs.coordNodeFirst()) , mCoordNodeLast(rhs.coordNodeLast()) , mNpartitions(rhs.nPartitions()) , mDivideGrid(rhs.divideGrid()) , mReadKindFile(rhs.readKindFile()) , mWriteKindFile(rhs.writeKindFile()) , mKindFile(rhs.kindFile()) , mTypeDomainDecomp(rhs.typeDomainDecomp()) , mWritePartitionFile(rhs.writePartitionFile()) , mNameWritePartitionFile(rhs.nameWritePartitionFile()) , mReadPartitionFile(rhs.readPartitionFile()) , mNameReadPartitionFile(rhs.nameReadPartitionFile()) , mTimeIntervalStart(rhs.timeIntervalStart()) , mTimeIntervalEnd(rhs.timeIntervalEnd()) , mNtimesteps(rhs.nTimesteps()) , mTau(rhs.tau()) , mThreshold(rhs.threshold()) , mCheckConvFirstAtIter(rhs.checkConvFirstAtIter()) , mCheckConvAtEveryNIter(rhs.checkConvAtEveryNIter()) , mNsnapshots(rhs.nSnapshots()) , mNlayersAtBorder(rhs.nLayersAtBorder()) , mWriteDataFile(rhs.writeDataFile()) , mNameOfDataFile(rhs.nameDataFile()) , mNameOfConfigFile(rhs.nameConfigFile()) , mNameOfInitFile(rhs.nameInitFile()) , mReadInitFile(rhs.readInitFile()) , mInitKnownDfs(rhs.initKnownDfs()) , mEnabledAdolc(rhs.enabledAdolc()) , mAsynchronMode(rhs.asynchronMode()) , mUseBoostMpiSkeletonConcept(rhs.useBoostMpiSkeletonConcept()) , mComputeGradients(rhs.computeGradients()) , mCheckGradients(rhs.checkGradients()) , mRankOutput(rhs.rankOutput()) , mMyWorld(rhs.myWorld()) , gOutputLevelMax(rhs.outputLevelMax()) , gOutputLevelCurr(rhs.outputLevelCurr()) { } #else inline Parameters::Parameters(const Parameters& rhs) : mDim(rhs.dim()) , mNnodes(rhs.nNodes()) , mCoordNodeFirst(rhs.coordNodeFirst()) , mCoordNodeLast(rhs.coordNodeLast()) , mNpartitions(rhs.nPartitions()) , mDivideGrid(rhs.divideGrid()) , mReadKindFile(rhs.readKindFile()) , mWriteKindFile(rhs.writeKindFile()) , mKindFile(rhs.kindFile()) , mTypeDomainDecomp(rhs.typeDomainDecomp()) , mWritePartitionFile(rhs.writePartitionFile()) , mNameWritePartitionFile(rhs.nameWritePartitionFile()) , mReadPartitionFile(rhs.readPartitionFile()) , mNameReadPartitionFile(rhs.nameReadPartitionFile()) , mTimeIntervalStart(rhs.timeIntervalStart()) , mTimeIntervalEnd(rhs.timeIntervalEnd()) , mNtimesteps(rhs.nTimesteps()) , mTau(rhs.tau()) , mThreshold(rhs.threshold()) , mCheckConvFirstAtIter(rhs.checkConvFirstAtIter()) , mCheckConvAtEveryNIter(rhs.checkConvAtEveryNIter()) , mNsnapshots(rhs.nSnapshots()) , mNlayersAtBorder(rhs.nLayersAtBorder()) , mWriteDataFile(rhs.writeDataFile()) , mNameOfDataFile(rhs.nameDataFile()) , mNameOfConfigFile(rhs.nameConfigFile()) , mNameOfInitFile(rhs.nameInitFile()) , mReadInitFile(rhs.readInitFile()) , mInitKnownDfs(rhs.initKnownDfs()) , mEnabledAdolc(rhs.enabledAdolc()) , mAsynchronMode(rhs.asynchronMode()) , mUseBoostMpiSkeletonConcept(rhs.useBoostMpiSkeletonConcept()) , mComputeGradients(rhs.computeGradients()) , mCheckGradients(rhs.checkGradients()) , mRankOutput(rhs.rankOutput()) , mMyEnv(rhs.myEnv()) , mMyWorld(rhs.myWorld()) , gOutputLevelMax(rhs.outputLevelMax()) , gOutputLevelCurr(rhs.outputLevelCurr()) { } #endif /*----------------------------------------------------------------------------*/ inline Parameters& Parameters::operator=(Parameters rhs) { swap(*this, rhs); return *this; } /*----------------------------------------------------------------------------*/ inline Parameters::~Parameters() { } /******************************************************************************* * GETTER METHODS. ******************************************************************************/ inline const int& Parameters::dim() const { return this->mDim; } /*----------------------------------------------------------------------------*/ inline const std::vector<int>& Parameters::nNodes() const { return this->mNnodes; } /*----------------------------------------------------------------------------*/ inline const std::vector<double>& Parameters::coordNodeFirst() const { return this->mCoordNodeFirst; } /*----------------------------------------------------------------------------*/ inline const std::vector<double>& Parameters::coordNodeLast() const { return this->mCoordNodeLast; } /*----------------------------------------------------------------------------*/ inline const std::vector<int>& Parameters::nPartitions() const { return this->mNpartitions; } /*----------------------------------------------------------------------------*/ inline const std::vector<bool>& Parameters::divideGrid() const { return this->mDivideGrid; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::readKindFile() const { return this->mReadKindFile; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::writeKindFile() const { return this->mWriteKindFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::kindFile() const { return this->mKindFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::typeDomainDecomp() const { return this->mTypeDomainDecomp; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::writePartitionFile() const { return this->mWritePartitionFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::nameWritePartitionFile() const { return this->mNameWritePartitionFile; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::readPartitionFile() const { return this->mReadPartitionFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::nameReadPartitionFile() const { return this->mNameReadPartitionFile; } /*----------------------------------------------------------------------------*/ inline const double& Parameters::timeIntervalStart() const { return this->mTimeIntervalStart; } /*----------------------------------------------------------------------------*/ inline const double& Parameters::timeIntervalEnd() const { return this->mTimeIntervalEnd; } /*----------------------------------------------------------------------------*/ inline const int& Parameters::nTimesteps() const { return this->mNtimesteps; } /*----------------------------------------------------------------------------*/ inline const double& Parameters::tau() const { return this->mTau; } /*----------------------------------------------------------------------------*/ inline const double& Parameters::threshold() const { return this->mThreshold; } /*----------------------------------------------------------------------------*/ inline const int& Parameters::checkConvFirstAtIter() const { return this->mCheckConvFirstAtIter; } /*----------------------------------------------------------------------------*/ inline const int& Parameters::checkConvAtEveryNIter() const { return this->mCheckConvAtEveryNIter; } /*----------------------------------------------------------------------------*/ inline const int& Parameters::nSnapshots() const { return this->mNsnapshots; } /*----------------------------------------------------------------------------*/ inline const int& Parameters::nLayersAtBorder() const { return this->mNlayersAtBorder; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::writeDataFile() const { return this->mWriteDataFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::nameDataFile() const { return this->mNameOfDataFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::nameConfigFile() const { return this->mNameOfConfigFile; } /*----------------------------------------------------------------------------*/ inline const std::string& Parameters::nameInitFile() const { return this->mNameOfInitFile; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::readInitFile() const { return this->mReadInitFile; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::initKnownDfs() const { return this->mInitKnownDfs; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::enabledAdolc() const { return this->mEnabledAdolc; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::asynchronMode() const { return this->mAsynchronMode; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::useBoostMpiSkeletonConcept() const { return this->mUseBoostMpiSkeletonConcept; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::computeGradients() const { return this->mComputeGradients; } /*----------------------------------------------------------------------------*/ inline const bool& Parameters::checkGradients() const { return this->mCheckGradients; } /*----------------------------------------------------------------------------*/ inline int Parameters::rankOutput() const { return this->mRankOutput; } /*----------------------------------------------------------------------------*/ inline const ScaFES::Communicator& Parameters::myWorld() const { return this->mMyWorld; } /*----------------------------------------------------------------------------*/ inline const ScaFES::Environment& Parameters::myEnv() const { return this->mMyEnv; } /*----------------------------------------------------------------------------*/ inline int Parameters::rank() const { return this->myWorld().rank(); } /*----------------------------------------------------------------------------*/ inline int Parameters::outputLevelMax() const { return this->gOutputLevelMax; } /*----------------------------------------------------------------------------*/ inline int Parameters::outputLevelCurr() const { return this->gOutputLevelCurr; } /*----------------------------------------------------------------------------*/ inline const int& Parameters::indentDepth() const { return this->gOutputLevelCurr; } /******************************************************************************* * SETTER METHODS. ******************************************************************************/ inline void Parameters::increaseLevel() { ++(this->gOutputLevelCurr); } /*----------------------------------------------------------------------------*/ inline void Parameters::decreaseLevel() { --(this->gOutputLevelCurr); } /******************************************************************************* * COMPARISON METHODS. ******************************************************************************/ inline bool Parameters::operator==(const Parameters& rhs) const { bool isEqual = true; if (this->dim() != rhs.dim()) { isEqual = false; } if (this->nNodes() != rhs.nNodes()) { isEqual = false; } if (this->coordNodeFirst() != rhs.coordNodeFirst()) { isEqual = false; } if (this->coordNodeLast() != rhs.coordNodeLast()) { isEqual = false; } if (this->nPartitions() != rhs.nPartitions()) { isEqual = false; } if (this->divideGrid() != rhs.divideGrid()) { isEqual = false; } if (this->readKindFile() != rhs.readKindFile()) { isEqual = false; } if (this->kindFile() != rhs.kindFile()) { isEqual = false; } if (this->writePartitionFile() != rhs.writePartitionFile()) { isEqual = false; } if (this->nameWritePartitionFile() != rhs.nameWritePartitionFile()) { isEqual = false; } if (this->nameReadPartitionFile() != rhs.nameReadPartitionFile()) { isEqual = false; } if (this->timeIntervalStart() != rhs.timeIntervalStart()) { isEqual = false; } if (this->timeIntervalEnd() != rhs.timeIntervalEnd()) { isEqual = false; } if (this->nTimesteps() != rhs.nTimesteps()) { isEqual = false; } if (this->tau() != rhs.tau()) { isEqual = false; } if (this->threshold() != rhs.threshold()) { isEqual = false; } if (this->checkConvFirstAtIter() != rhs.checkConvFirstAtIter()) { isEqual = false; } if (this->checkConvAtEveryNIter() != rhs.checkConvAtEveryNIter()) { isEqual = false; } if (this->nSnapshots() != rhs.nSnapshots()) { isEqual = false; } if (this->writeDataFile() != rhs.writeDataFile()) { isEqual = false; } if (this->nameDataFile() != rhs.nameDataFile()) { isEqual = false; } if (this->nameConfigFile() != rhs.nameConfigFile()) { isEqual = false; } if (this->nameInitFile() != rhs.nameInitFile()) { isEqual = false; } if (this->readInitFile() != rhs.readInitFile()) { isEqual = false; } if (this->initKnownDfs() != rhs.initKnownDfs()) { isEqual = false; } if (this->enabledAdolc() != rhs.enabledAdolc()) { isEqual = false; } if (this->asynchronMode() != rhs.asynchronMode()) { isEqual = false; } if (this->useBoostMpiSkeletonConcept() != rhs.useBoostMpiSkeletonConcept()) { isEqual = false; } if (this->computeGradients() != rhs.computeGradients()) { isEqual = false; } if (this->checkGradients() != rhs.checkGradients()) { isEqual = false; } if (this->rankOutput() != rhs.rankOutput()) { isEqual = false; } // if (this->myWorld() != rhs.myWorld()) // { // isEqual = false; // } return isEqual; } /*----------------------------------------------------------------------------*/ inline bool Parameters::operator!=(const Parameters& rhs) const { return !(*this == rhs); } /******************************************************************************* * WORK METHODS. ******************************************************************************/ #ifdef SCAFES_HAVE_BOOST template <typename TT> inline void Parameters::checkParameter(const po::variables_map& vm, const std::string& nameParam, std::vector<TT>& param, bool isNecessary) { if (vm.count(nameParam)) { std::ostringstream ostrRegex; for (int ii = 0; ii < dim(); ++ii) { ostrRegex << "(-?\\d+)"; if ((dim() - 1) > ii) { ostrRegex << "x"; } } std::string strRegex = ostrRegex.str(); boost::regex re(strRegex); std::string strParam; boost::cmatch matches; strParam = vm[nameParam].as<std::string>(); if (boost::regex_match(strParam.c_str(), matches, re)) { for (std::size_t i = 1; i < matches.size(); ++i) { std::string match(matches[i].first, matches[i].second); param.at(i - 1) = atoi(match.c_str()); } } else { std::ostringstream ostrErr; for (int ii = 0; ii < dim(); ++ii) { ostrErr << "n" << ii; if ((dim() - 1) > ii) { ostrErr << "x"; } } std::string strErr = ostrErr.str(); std::cerr << "\nERROR: The parameter --" << nameParam << "=" << strParam << " is not of a format like" " --" << nameParam << "=" << strErr << ". Exit... \n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --" << nameParam << "=<a1xa2xa3>\n\n"; if (isNecessary) { this->mMyEnv.abort(this->mMyWorld,-1); } } } template <typename TT> inline void Parameters::checkParameterDouble(const po::variables_map& vm, const std::string& nameParam, std::vector<TT>& param, bool isNecessary) { if (vm.count(nameParam)) { std::ostringstream ostrRegex; for (int ii = 0; ii < dim(); ++ii) { ostrRegex << "([-+]?[0-9]*\\.?[0-9]+)"; if ((dim() - 1) > ii) { ostrRegex << "x"; } } std::string strRegex = ostrRegex.str(); boost::regex re(strRegex); std::string strParam; boost::cmatch matches; strParam = vm[nameParam].as<std::string>(); if (boost::regex_match(strParam.c_str(), matches, re)) { for (std::size_t i = 1; i < matches.size(); ++i) { std::string match(matches[i].first, matches[i].second); param.at(i - 1) = atof(match.c_str()); } } else { std::ostringstream ostrErr; for (int ii = 0; ii < dim(); ++ii) { ostrErr << "n" << ii; if ((dim() - 1) > ii) { ostrErr << "x"; } } std::string strErr = ostrErr.str(); std::cerr << "\nERROR: The parameter --" << nameParam << "=" << strParam << " is not of a format like" " --" << nameParam << "=" << strErr << ". Exit... \n\n"; this->mMyEnv.abort(this->mMyWorld,-1); } } else { std::cerr << "\nREMARK: Use --" << nameParam << "=<a1xa2xa3>\n\n"; if (isNecessary) { this->mMyEnv.abort(this->mMyWorld,-1); } } } #endif /*----------------------------------------------------------------------------*/ /** Free function which sets a prefix to the output of process with * identifier \c rank. */ inline std::string Parameters::getPrefix(const std::string& nameFramework) const { std::string blanks(" "); std::ostringstream blankStream; blankStream << nameFramework << ": Rank=" << this->rankOutput() << ": "; int nIndents = this->gOutputLevelMax - this->gOutputLevelCurr; for (int jj = 0; jj < nIndents; ++jj) { blankStream << blanks; } return blankStream.str(); } /*----------------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION template <class Archive> void Parameters::serialize(Archive& ar, const unsigned int version) { if (1 <= version) { ar&(this->mDim); ar&(this->mNnodes); ar&(this->mCoordNodeFirst); ar&(this->mCoordNodeLast); ar&(this->mNpartitions); ar&(this->mDivideGrid); ar&(this->mReadKindFile); ar&(this->mWriteKindFile); ar&(this->mKindFile); ar&(this->mTypeDomainDecomp); ar&(this->mWritePartitionFile); ar&(this->mNameWritePartitionFile); ar&(this->mReadPartitionFile); ar&(this->mNameReadPartitionFile); ar&(this->mTimeIntervalStart); ar&(this->mTimeIntervalEnd); ar&(this->mNtimesteps); ar&(this->mTau); ar&(this->mThreshold); ar&(this->mCheckConvFirstAtIter); ar&(this->mCheckConvAtEveryNIter); ar&(this->mNsnapshots); ar&(this->mNlayersAtBorder); ar&(this->mWriteDataFile); ar&(this->mNameOfDataFile); ar&(this->mNameOfConfigFile); ar&(this->mNameOfInitFile); ar&(this->mReadInitFile); ar&(this->mInitKnownDfs); ar&(this->mEnabledAdolc); ar&(this->mAsynchronMode); ar&(this->mUseBoostMpiSkeletonConcept); ar&(this->mComputeGradients); ar&(this->mCheckGradients); ar&(this->mRankOutput); ar&(this->gOutputLevelMax); ar&(this->gOutputLevelCurr); } } #endif /******************************************************************************* * FREE METHODS WHICH ARE FRIENDS OF THIS CLASS. ******************************************************************************/ inline void swap(Parameters& first, Parameters& second) { std::swap(first.mDim, second.mDim); std::swap(first.mNnodes, second.mNnodes); std::swap(first.mCoordNodeFirst, second.mCoordNodeFirst); std::swap(first.mCoordNodeLast, second.mCoordNodeLast); std::swap(first.mNpartitions, second.mNpartitions); std::swap(first.mDivideGrid, second.mDivideGrid); std::swap(first.mReadKindFile, second.mReadKindFile); std::swap(first.mWriteKindFile, second.mWriteKindFile); std::swap(first.mKindFile, second.mKindFile); std::swap(first.mTypeDomainDecomp, second.mTypeDomainDecomp); std::swap(first.mWritePartitionFile, second.mWritePartitionFile); std::swap(first.mNameWritePartitionFile, second.mNameWritePartitionFile); std::swap(first.mReadPartitionFile, second.mReadPartitionFile); std::swap(first.mNameReadPartitionFile, second.mNameReadPartitionFile); std::swap(first.mTimeIntervalStart, second.mTimeIntervalStart); std::swap(first.mTimeIntervalEnd, second.mTimeIntervalEnd); std::swap(first.mNtimesteps, second.mNtimesteps); std::swap(first.mTau, second.mTau); std::swap(first.mThreshold, second.mThreshold); std::swap(first.mCheckConvFirstAtIter, second.mCheckConvFirstAtIter); std::swap(first.mCheckConvAtEveryNIter, second.mCheckConvAtEveryNIter); std::swap(first.mNsnapshots, second.mNsnapshots); std::swap(first.mNlayersAtBorder, second.mNlayersAtBorder); std::swap(first.mWriteDataFile, second.mWriteDataFile); std::swap(first.mNameOfDataFile, second.mNameOfDataFile); std::swap(first.mNameOfConfigFile, second.mNameOfConfigFile); std::swap(first.mNameOfInitFile, second.mNameOfInitFile); std::swap(first.mReadInitFile, second.mReadInitFile); std::swap(first.mInitKnownDfs, second.mInitKnownDfs); std::swap(first.mEnabledAdolc, second.mEnabledAdolc); std::swap(first.mAsynchronMode, second.mAsynchronMode); std::swap(first.mUseBoostMpiSkeletonConcept, second.mUseBoostMpiSkeletonConcept); std::swap(first.mComputeGradients, second.mComputeGradients); std::swap(first.mCheckGradients, second.mCheckGradients); std::swap(first.mRankOutput, second.mRankOutput); std::swap(first.mMyWorld, second.mMyWorld); std::swap(first.gOutputLevelMax, second.gOutputLevelMax); std::swap(first.gOutputLevelCurr, second.gOutputLevelCurr); } } // End of namespace. // /******************************************************************************* ******************************************************************************/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION /** Boost serialization version of class \c Parameter. */ BOOST_CLASS_VERSION(ScaFES::Parameters, 2); #endif #endif
34.747014
199
0.490735
[ "vector" ]
1a0cc3f65ac1e0febf9a40a29dcdb6016ff9e005
1,657
cpp
C++
Hacker Rank/Datastructure/Array/Hacker Rank - Sparse Arrays.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
28
2017-11-08T11:52:11.000Z
2021-07-16T06:30:02.000Z
Hacker Rank/Datastructure/Array/Hacker Rank - Sparse Arrays.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
null
null
null
Hacker Rank/Datastructure/Array/Hacker Rank - Sparse Arrays.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
30
2017-09-01T09:14:27.000Z
2021-04-12T12:08:56.000Z
//#Name: Anonta Haque #Problm: hacker Rank Sparse Arrays //https://www.hackerrank.com/challenges/sparse-arrays/submissions/code/19307682 #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <cstring> #include <cstdlib> #include <cstdarg> #include <utility> #include <cctype> #include <cstdio> #include <vector> #include <string> #include <cmath> #include <ctime> #include <queue> #include <stack> #include <set> #include <map> using namespace std; typedef long long LL; //"%lld" typedef vector<int> vint; typedef pair<int,int> pint; typedef unsigned long long ULL; //"%llu" short COUNT_; #define sf scanf #define pf printf #define NL pf("\n"); #define put(x_) pf("%d", x_) #define read(x_) sf("%d", &x_) #define readf(x_) sf("%f", &x_) #define SS pf(">_<LOOOOOK@MEEEEEEEEEEEEEEE<<( %d )>>\n",++COUNT_); #define DD(x_) cout<<">>>>( "<<++COUNT_<<" ) "<<#x_<<": "<<x_<<endl; #define EXT(st_) cout<<"\n>>>Exicution Time: "<<(double)(clock()-st_)/CLOCKS_PER_SEC<<endl; //constants const int SZ= 1E4; const int INF= (1<<29); const double EPS= 1E-9; const double PI= 2*acos(0.0); char str[1000][23]; char query[1000][23]; void solve(void) { int n, q, occurance; read(n); for(int i= 0; i<n; i++){ sf("%s", str[i]); } read(q); for(int i= 0; i<q; i++){ sf("%s", query[i]); } for(int i= 0; i<q; i++) { occurance= 0; for(int j= 0; j<n; j++) { if(!strcmp(query[i], str[j]) ) occurance++; } pf("%d\n",occurance++); } } int main(void) { solve(); return 0; }
18.208791
91
0.575739
[ "vector" ]
1a0d89dcbab5fa09c49993c0f6b587f92cd5bce9
3,783
cpp
C++
sux.cpp
philippebourcier/sux
d3df021ce3cb973af7a00b8dd55dfd16f5e1e29d
[ "BSD-2-Clause" ]
null
null
null
sux.cpp
philippebourcier/sux
d3df021ce3cb973af7a00b8dd55dfd16f5e1e29d
[ "BSD-2-Clause" ]
null
null
null
sux.cpp
philippebourcier/sux
d3df021ce3cb973af7a00b8dd55dfd16f5e1e29d
[ "BSD-2-Clause" ]
null
null
null
/* ________ ______ ___ / ___/ || \ \/ / _\___ \| |/ /> < /______>______//__/\_ \ \/ v1.01 written by Philippe Bourcier with input from Serge Danzanvilliers with fixes by Pierre Ynard This code is published under the BSD License: http://www.opensource.org/licenses/bsd-license.php The main idea is to replace "... | sort | uniq -c [ | sort -(r)(n) ] [ | head -N ]" This program is (way) faster and less memory consuming than the above commands. Sample use: # cat file.txt | awk ... | sort | uniq -c | sort -rn | head -n 20 will be replaced by: # cat file.txt | awk ... | sux -rn 20 # cat file.txt | awk ... | sort | uniq -c | sort -n will be replaced by: # cat file.txt | awk ... | sux -s # cat file.txt | awk ... | sort | uniq -c will be replaced by: # cat file.txt | awk ... | sux # cat file.txt | awk ... | sort | uniq -c | head -n 20 will be replaced by: # cat file.txt | awk ... | sux -n 20 */ #include <algorithm> #include <string> #include <iostream> #include <fstream> #include <map> #include <vector> #include <stdlib.h> #include <unistd.h> using namespace std; typedef pair<std::string, int> mypair; struct intcmp { bool operator()(const mypair &lhs, const mypair &rhs) { return lhs.second < rhs.second; } }; struct rintcmp { bool operator()(const mypair &lhs, const mypair &rhs) { return lhs.second > rhs.second; } }; void usage(string p) { cout << "Usage: " << p << " [OPTION]... [FILE]..." << endl << "Write sorted concatenation of all FILE(s) to standard output." << endl << endl << "Ordering options:" << endl << "-s sort the result (sort -n)" << endl << "-r reverse sorting order (sort -rn)" << endl << "-nN limit output to the first N lines" << endl << endl << "Report bugs to <philippe@sysctl.org>." << endl; } int main(int argc, char *argv[]) { map<string,int> c; string line; bool s, r, l; s = r = l = false; char *n=NULL; int opt; int z=-1; // Getting arguments while ((opt=getopt(argc,argv,"hsrn:"))!=-1) { switch (opt) { case 's': s = true; break; case 'r': r = true; break; case 'n': l = true; n = optarg; z=atoi(n); break; case 'h': usage(argv[0]); return 0; case '?': cout << "Try '" << argv[0] << " -h' for more information." << endl; return 1; default: return 0; } } if(argv[optind]) { ifstream file(argv[optind]); if(!file.is_open()) { cout << "Unable to open file : " << argv[(argc-1)] << endl; return 1; } while(file.good()) { getline(file,line); if (!file.eof()) c[line]++; } file.close(); } else { if(!cin) return 1; while(cin) { getline(cin,line); if (!cin.eof()) c[line]++; } } // Sorting if(s || r) { vector<mypair> myvec(c.begin(),c.end()); if(r) partial_sort(myvec.begin(),myvec.begin()+c.size(),myvec.end(),rintcmp()); else partial_sort(myvec.begin(),myvec.begin()+c.size(),myvec.end(),intcmp()); for (int i=0;i<int(c.size());++i) { cout << myvec[i].second << " " << myvec[i].first << endl; if(l) { z--; if(z==0) break; } } } else { // No Sorting for (map<string,int>::iterator i=c.begin();i!=c.end();i++) { cout << i->second << " " << i->first << endl; if(l) { z--; if(z==0) break; } } } return 0; }
24.564935
92
0.49511
[ "vector" ]
1a13164b797658ef38d113982b7cb9485e1bd6b9
618
cpp
C++
LeetCode/Combinations/Solution.cpp
maochongxin/WorkForTheInternship
3587f0dd19579de0330b8c33fc7282ed7bba9f5c
[ "MIT" ]
null
null
null
LeetCode/Combinations/Solution.cpp
maochongxin/WorkForTheInternship
3587f0dd19579de0330b8c33fc7282ed7bba9f5c
[ "MIT" ]
null
null
null
LeetCode/Combinations/Solution.cpp
maochongxin/WorkForTheInternship
3587f0dd19579de0330b8c33fc7282ed7bba9f5c
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if (n < 1 || k > n) { return res; } vector<int> vec; solve(res, vec, n, k, 1); return res; } void solve(vector<vector<int>>& res, vector<int> vec, int n, int k, int step) { if (vec.size() == k) { res.push_back(vec); return; } for (int i = step; i <= n - (k - vec.size()) + 1; ++i) { vec.push_back(i); solve(res, vec, n, k, i + 1); vec.pop_back(); } } };
23.769231
83
0.427184
[ "vector" ]
1a227c01e32fb7dfff15d75c7844056442657ccf
8,055
hpp
C++
include/ivulk/core/command_buffer.hpp
zfzackfrost/incredible_vulk
b5a6eb7072d5dc1d6e7a24d31379c1c6986f225c
[ "MIT" ]
null
null
null
include/ivulk/core/command_buffer.hpp
zfzackfrost/incredible_vulk
b5a6eb7072d5dc1d6e7a24d31379c1c6986f225c
[ "MIT" ]
null
null
null
include/ivulk/core/command_buffer.hpp
zfzackfrost/incredible_vulk
b5a6eb7072d5dc1d6e7a24d31379c1c6986f225c
[ "MIT" ]
null
null
null
/** * @file command_buffer.hpp * @author Zachary Frost * @copyright MIT License (See LICENSE.md in repostory root) * @brief `CommandBuffer` class. */ #pragma once #include <ivulk/config.hpp> #include <ivulk/core/vulkan_resource.hpp> #include <ivulk/core/shader_stage.hpp> #include <ivulk/utils/keywords.hpp> #include <ivulk/utils/messages.hpp> #include <glm/glm.hpp> #include <ivulk/vk.hpp> #include <optional> #include <stdexcept> #include <vector> namespace ivulk { class Buffer; class GraphicsPipeline; /** * @brief Information for initializing a CommandBuffers resource */ struct CommandBuffersCreateInfo { vk::CommandBufferLevel level = vk::CommandBufferLevel::ePrimary; ///< Vulkan command buffer level. vk::CommandPool cmdPool; ///< The Vulkan command buffer pool to allocate from uint32_t count = 1; ///< The number of command buffers to allocate }; /** * @brief A memory-managed resource for a group of Vulkan command buffers */ class CommandBuffers : public VulkanResource<CommandBuffers, CommandBuffersCreateInfo, vk::CommandPool, std::vector<vk::CommandBuffer>> { public: CommandBuffers(VkDevice device, vk::CommandPool pool, std::vector<vk::CommandBuffer> buffers) : base_t(device, handles_t {pool, buffers}) { } /** * @brief Get the Vulkan command pool used to allocate the command buffers. */ vk::CommandPool getCmdPool() { return getHandleAt<0>(); } /** * @brief Get a command buffer from this group by index. * * @param i The index of the command buffer to get */ vk::CommandBuffer getCmdBuffer(std::size_t i) { return getHandleAt<1>()[i]; } /** * @brief Get an STL vector of all the command buffers in this group. */ std::vector<vk::CommandBuffer> getCmdBuffers() { return getHandleAt<1>(); } /** * @brief Optional arguments for the `start` method. */ struct StartCallInfo { std::size_t index; ///< The index of the command buffer to start recording to. vk::CommandBufferUsageFlags flags = vk::CommandBufferUsageFlagBits:: eSimultaneousUse; ///< The Vulkan command buffer usage flags. }; /** * @brief Set the current command buffer by index and start recording to it. * * @param callInfo The optional arguments structure. */ void start(const StartCallInfo&& callInfo) { startImpl(callInfo.index, callInfo.flags); } /** * @brief Finish recording to the current command buffer */ void finish(); /** * @brief Optional arguments for the `draw` method. */ struct DrawCallInfo { std::weak_ptr<Buffer> vertexBuffer; ///< The vertex buffer to use for drawing std::weak_ptr<Buffer> indexBuffer; ///< The index buffer to use for drawing uint32_t vertices = 0u; ///< Override the number of vertices to draw uint32_t instances = 1u; ///< The number of instances for instanced rendering uint32_t firstVertex = 0u; ///< The index of the first vertex to draw uint32_t firstInstance = 0u; ///< The index of the first instance to draw }; /** * @brief Bind vertex/index buffers and draw from them. * * @param callInfo The optional arguments structure. */ void draw(const DrawCallInfo&& callInfo) { drawImpl(callInfo.vertexBuffer, callInfo.indexBuffer, callInfo.vertices, callInfo.instances, callInfo.firstVertex, callInfo.firstInstance); } /** * @brief Optional arguments for the `clearAttachments` method. */ struct ClearAttachmentsCallInfo { glm::vec4 color = {0, 0, 0, 1}; ///< The clear color std::optional<float> depth = 0.0f; ///< The clear depth, if any }; /** * @brief Clear the attachments for a graphics pipeline * * @param pipeline The pipeline we are working with * @param callInfo The option arguments structure */ void clearAttachments(std::weak_ptr<GraphicsPipeline> pipeline, const ClearAttachmentsCallInfo&& callInfo) { clearAttachmentsImpl(pipeline, callInfo.color); } /** * @brief Bind a graphics pipeline * * @param pipeline The pipeline to bind */ void bindPipeline(std::weak_ptr<GraphicsPipeline> pipeline) { bindPipelineImpl(pipeline); } /** * @brief Optional arguments structure for `pushConstants` method. */ struct PushConstantsCallInfo { vk::DeviceSize offset = 0u; ///< the start offset of the push constant range to update, in units of bytes VkShaderStageFlags stageFlags = E_ShaderStage:: All; ///< the shader stages that will use the push constants in the updated range }; /** * @brief Update the values of push constants. * * @param data The data to update the push constants with * @param layout The pipeline layout used to program the push constant updates * @param size The size of the push constant range to update, in units of bytes */ void pushConstants(const void* data, vk::PipelineLayout layout, vk::DeviceSize size, const PushConstantsCallInfo&& callInfo) { pushConstantsImpl(data, layout, callInfo.stageFlags, callInfo.offset, size); } private: friend base_t; static CommandBuffers* createImpl(VkDevice device, CommandBuffersCreateInfo createInfo) { vk::CommandBufferAllocateInfo allocInfo {}; allocInfo.setCommandPool(createInfo.cmdPool); allocInfo.setLevel(createInfo.level); allocInfo.setCommandBufferCount(createInfo.count); std::vector<VkCommandBuffer> commandBuffers(createInfo.count); VkCommandBufferAllocateInfo ai = allocInfo; if (vkAllocateCommandBuffers(device, &ai, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error( utils::makeErrorMessage("VK::CREATE", "Failed to create Vulkan command buffer(s)")); } return new CommandBuffers( device, createInfo.cmdPool, std::vector<vk::CommandBuffer>(commandBuffers.begin(), commandBuffers.end())); } void destroyImpl() { } void startImpl(std::size_t index, vk::CommandBufferUsageFlags flags); void drawImpl(std::weak_ptr<Buffer> vertexBuffer, std::weak_ptr<Buffer> indexBuffer, uint32_t vertices, uint32_t instances, uint32_t firstVertex, uint32_t firstInstance); void clearAttachmentsImpl(std::weak_ptr<GraphicsPipeline> pipeline, glm::vec4 color); void bindPipelineImpl(std::weak_ptr<GraphicsPipeline> pipeline); void pushConstantsImpl(const void* data, VkPipelineLayout layout, VkShaderStageFlags stages, VkDeviceSize offset, VkDeviceSize size); std::optional<std::size_t> m_currentIdx = {}; }; } // namespace ivulk
37.119816
106
0.572936
[ "vector" ]
1a3303dcfa5b86a2d8774747892c06f4972d84f9
1,060
hpp
C++
src/thread_local.hpp
ktts16/mini-caffe
58a5007d7921c69c9c3105b20b92b2136af26a4e
[ "BSD-3-Clause" ]
413
2015-07-09T09:33:07.000Z
2022-03-10T02:26:27.000Z
src/thread_local.hpp
ktts16/mini-caffe
58a5007d7921c69c9c3105b20b92b2136af26a4e
[ "BSD-3-Clause" ]
65
2015-07-10T01:38:10.000Z
2020-08-06T07:27:42.000Z
src/thread_local.hpp
ktts16/mini-caffe
58a5007d7921c69c9c3105b20b92b2136af26a4e
[ "BSD-3-Clause" ]
196
2015-08-18T07:59:33.000Z
2021-07-27T02:44:21.000Z
// ThreadLocal Template #ifndef CAFFE_THREAD_LOCAL_HPP_ #define CAFFE_THREAD_LOCAL_HPP_ #include <vector> #include <mutex> #ifdef __GNUC__ #define THREAD_LOCAL __thread #elif __STDC_VERSION__ >= 201112L #define THREAD_LOCAL _Thread_local #elif defined(_MSC_VER) #define THREAD_LOCAL __declspec(thread) #endif #ifndef THREAD_LOCAL #message("Warning: Threadlocal is not enabled"); #endif template<typename T> class ThreadLocalStore { public: static T *Get() { static THREAD_LOCAL T *ptr = nullptr; if (ptr == nullptr) { ptr = new T(); Singleton()->RegisterDelete(ptr); } return ptr; } private: ThreadLocalStore() {} ~ThreadLocalStore() { for (auto obj : objs_) { delete obj; } } static ThreadLocalStore<T> *Singleton() { static ThreadLocalStore<T> inst; return &inst; } void RegisterDelete(T *obj) { std::unique_lock<std::mutex> lock(mutex_); objs_.push_back(obj); lock.unlock(); } private: std::mutex mutex_; std::vector<T*> objs_; }; #endif // CAFFE_THREAD_LOCAL_HPP_
19.272727
48
0.689623
[ "vector" ]
1a3620c61225affbba9095ee6d76cc11fc4b8aa3
4,922
hpp
C++
src/imageio/itkdetails/ImageIOInfo.hpp
halfmvsq/histolozee
c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5
[ "Apache-2.0" ]
null
null
null
src/imageio/itkdetails/ImageIOInfo.hpp
halfmvsq/histolozee
c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5
[ "Apache-2.0" ]
null
null
null
src/imageio/itkdetails/ImageIOInfo.hpp
halfmvsq/histolozee
c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5
[ "Apache-2.0" ]
null
null
null
#pragma once #include "itkdetails/IITKImageIOInfo.hpp" #include <itkImageBase.h> #include <boost/variant.hpp> #include <string> #include <unordered_map> namespace itkdetails { /// @brief Definitions in this namespace are for ITK image IO. /// With the exception of SPIRAL codes, nothing is specific to image type or dimension. namespace io { class FileInfo : public IItkImageIoInfo { public: FileInfo(); FileInfo( const ::itk::ImageIOBase::Pointer imageIO ); FileInfo( const FileInfo& ) = default; FileInfo& operator=( const FileInfo& ) = default; FileInfo( FileInfo&& ) = default; FileInfo& operator=( FileInfo&& ) = default; ~FileInfo() override = default; bool set( const ::itk::ImageIOBase::Pointer imageIO ) override; bool validate() override; std::string m_fileName; ::itk::ImageIOBase::ByteOrder m_byteOrder; std::string m_byteOrderString; bool m_useCompression; ::itk::ImageIOBase::IOFileEnum m_fileType; std::string m_fileTypeString; std::vector< std::string > m_supportedReadExtensions; std::vector< std::string > m_supportedWriteExtensions; }; class ComponentInfo : public IItkImageIoInfo { public: ComponentInfo(); ComponentInfo( const ::itk::ImageIOBase::Pointer imageIO ); ComponentInfo( const ComponentInfo& ) = default; ComponentInfo& operator=( const ComponentInfo& ) = default; ComponentInfo( ComponentInfo&& ) = default; ComponentInfo& operator=( ComponentInfo&& ) = default; ~ComponentInfo() override = default; bool set( const ::itk::ImageIOBase::Pointer imageIO ) override; bool validate() override; ::itk::ImageIOBase::IOComponentType m_componentType; std::string m_componentTypeString; uint32_t m_componentSizeInBytes; }; class PixelInfo : public IItkImageIoInfo { public: PixelInfo(); PixelInfo( const ::itk::ImageIOBase::Pointer imageIO ); PixelInfo( const PixelInfo& ) = default; PixelInfo& operator=( const PixelInfo& ) = default; PixelInfo( PixelInfo&& ) = default; PixelInfo& operator=( PixelInfo&& ) = default; ~PixelInfo() override = default; bool set( const ::itk::ImageIOBase::Pointer imageIO ) override; bool validate() override; ::itk::ImageIOBase::IOPixelType m_pixelType; std::string m_pixelTypeString; uint32_t m_numComponents; ::itk::ImageIOBase::SizeType m_pixelStrideInBytes; }; class SizeInfo : public IItkImageIoInfo { public: SizeInfo(); SizeInfo( const ::itk::ImageIOBase::Pointer imageIO ); SizeInfo( const SizeInfo& ) = default; SizeInfo& operator=( const SizeInfo& ) = default; SizeInfo( SizeInfo&& ) = default; SizeInfo& operator=( SizeInfo&& ) = default; ~SizeInfo() override = default; bool set( const ::itk::ImageIOBase::Pointer imageIO ) override; bool set( const typename ::itk::ImageBase< 3 >::Pointer imageBase, const uint32_t componentSizeInBytes ); bool validate() override; ::itk::ImageIOBase::SizeType m_imageSizeInComponents; ::itk::ImageIOBase::SizeType m_imageSizeInPixels; ::itk::ImageIOBase::SizeType m_imageSizeInBytes; }; class SpaceInfo : public IItkImageIoInfo { public: SpaceInfo(); SpaceInfo( const ::itk::ImageIOBase::Pointer imageIO ); SpaceInfo( const SpaceInfo& ) = default; SpaceInfo& operator=( const SpaceInfo& ) = default; SpaceInfo( SpaceInfo&& ) = default; SpaceInfo& operator=( SpaceInfo&& ) = default; ~SpaceInfo() override = default; bool set( const ::itk::ImageIOBase::Pointer imageIO ) override; bool set( const typename ::itk::ImageBase< 3 >::Pointer imageBase ); bool validate() override; uint32_t m_numDimensions; std::vector< uint64_t > m_dimensions; std::vector< double > m_origin; std::vector< double > m_spacing; std::vector< std::vector< double > > m_directions; }; using MetaDataMap = std::unordered_map< std::string, boost::variant< std::string, int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t, float, double > >; class ImageIoInfo : public IItkImageIoInfo { public: ImageIoInfo() = default; ImageIoInfo( const ::itk::ImageIOBase::Pointer imageIO ); ImageIoInfo( const ImageIoInfo& ) = default; ImageIoInfo& operator=( const ImageIoInfo& ) = default; ImageIoInfo( ImageIoInfo&& ) = default; ImageIoInfo& operator=( ImageIoInfo&& ) = default; ~ImageIoInfo() override = default; bool set( const ::itk::ImageIOBase::Pointer imageIO ) override; bool validate() override; FileInfo m_fileInfo; ComponentInfo m_componentInfo; PixelInfo m_pixelInfo; SizeInfo m_sizeInfo; SpaceInfo m_spaceInfo; MetaDataMap m_metaData; }; } // namespace io } // namespace itkdetails
25.502591
87
0.677367
[ "vector" ]
1a3bcf937109595b466695f4d400453607a8142c
2,740
cpp
C++
Workshops/salaries_completed.cpp
hoelzl/CleanCodeCppCatch
88861faf48967e840b1d66f7faf94c0e9bef26a4
[ "MIT" ]
null
null
null
Workshops/salaries_completed.cpp
hoelzl/CleanCodeCppCatch
88861faf48967e840b1d66f7faf94c0e9bef26a4
[ "MIT" ]
null
null
null
Workshops/salaries_completed.cpp
hoelzl/CleanCodeCppCatch
88861faf48967e840b1d66f7faf94c0e9bef26a4
[ "MIT" ]
null
null
null
#include "salaries_completed.h" #include <array> #include <iostream> #include <stdexcept> #include <string> #include <vector> void assert_valid_day_number(int day_number); double process_salary(int day_number, double salary_per_day, const char* employee_name, std::vector<double>& all_salaries) { assert_valid_day_number(day_number); auto salary_after_taxes = compute_salary_after_taxes(day_number, salary_per_day); store_salary(salary_after_taxes, all_salaries); print_salary(day_number, salary_per_day, employee_name); return compute_taxes(day_number, salary_per_day); } void assert_valid_day_number(int day_number) { if (day_number < 1 || day_number > 7) { throw std::domain_error( "The value of day_number must be between 1 and 7."); } } double compute_salary_after_taxes(int day_number, double salary_per_day) { auto salary_before_taxes = compute_salary_before_taxes(day_number, salary_per_day); auto taxes = compute_taxes(salary_before_taxes); return salary_before_taxes - taxes; } double compute_salary_before_taxes(int day_number, double salary_per_day) { assert_valid_day_number(day_number); return (day_number - 1) * salary_per_day; } double compute_taxes(double salary_before_taxes) { return salary_before_taxes * compute_tax_rate(salary_before_taxes); } double compute_taxes(int day_number, double salary_per_day) { auto salary_before_taxes = compute_salary_before_taxes(day_number, salary_per_day); return compute_taxes(salary_before_taxes); } double compute_tax_rate(double salary) { if (salary <= 500.0) { return 0.0; } else if (salary <= 1000.0) { return 0.05; } else if (salary <= 2000.0) { return 0.1; } else { return 0.15; } } void store_salary(double salary, std::vector<double>& all_salaries) { all_salaries.push_back(salary); } void print_salary(int day_number, double salary_per_day, const char* employee_name) { std::cout << employee_name << " worked till " << compute_day_of_week_name(day_number) << " and earned $" << compute_salary_after_taxes(day_number, salary_per_day) << " this week.\n"; std::cout << " " << "Their taxes were $" << compute_taxes(day_number, salary_per_day) << "."; std::cout << std::endl; } const std::string& compute_day_of_week_name(int day_number) { const static std::array<const std::string, 7> day_names{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; assert_valid_day_number(day_number); return day_names.at(day_number - 1); }
29.148936
73
0.677737
[ "vector" ]
1a48826d3e1d16519137d4fb3bcdf5782b7d5f71
1,272
cpp
C++
Chapter 8/CustomQmlElementsTest/quickitemtriangle.cpp
mrkkrj/Hands-On-High-performance-with-QT
baab230ff7cfefd58421f4cbb4ab48492fa9ae54
[ "MIT" ]
43
2018-10-20T15:32:42.000Z
2022-03-24T06:13:32.000Z
Chapter 8/CustomQmlElementsTest/quickitemtriangle.cpp
mrkkrj/Hands-On-High-performance-with-QT
baab230ff7cfefd58421f4cbb4ab48492fa9ae54
[ "MIT" ]
null
null
null
Chapter 8/CustomQmlElementsTest/quickitemtriangle.cpp
mrkkrj/Hands-On-High-performance-with-QT
baab230ff7cfefd58421f4cbb4ab48492fa9ae54
[ "MIT" ]
15
2018-11-03T14:03:51.000Z
2021-11-11T07:48:46.000Z
#include "quickitemtriangle.h" #include <QSGNode> #include<QSGFlatColorMaterial> QuickItemTriangle::QuickItemTriangle(QQuickItem* parent) : QQuickItem(parent) { setFlag(QQuickItem::ItemHasContents, true); } QSGNode* QuickItemTriangle::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData* data) { if (width() <= 0 || height() <= 0) { delete oldNode; return nullptr; } QSGGeometryNode* triangle = static_cast<QSGGeometryNode*>(oldNode); if (!triangle) { triangle = new QSGGeometryNode; triangle->setFlag(QSGNode::OwnsMaterial, true); triangle->setFlag(QSGNode::OwnsGeometry, true); } const QRectF rect = boundingRect(); QSGGeometry* geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 3); QSGGeometry::Point2D* points = geometry->vertexDataAsPoint2D(); points[0].x = rect.left(); points[0].y = rect.top(); points[1].x = rect.left() + rect.width() / 2.0; points[1].y = rect.bottom(); points[2].x = rect.right(); points[2].y = rect.top(); triangle->setGeometry(geometry); QSGFlatColorMaterial* material = new QSGFlatColorMaterial; material->setColor(Qt::blue); triangle->setMaterial(material); return triangle; }
25.44
89
0.668239
[ "geometry" ]
1a48a68d0bc3511c5b9d2aa7e03343711fc47f53
29,286
cpp
C++
src/bind/bt_CollisionWorld.cpp
lubyk/bt
479561766e8578d670d5e215ae5d301c7a4d92dd
[ "Zlib" ]
4
2015-01-02T01:06:01.000Z
2019-03-21T00:18:27.000Z
src/bind/bt_CollisionWorld.cpp
lubyk/bt
479561766e8578d670d5e215ae5d301c7a4d92dd
[ "Zlib" ]
1
2015-01-02T22:43:49.000Z
2015-04-09T16:13:36.000Z
src/bind/bt_CollisionWorld.cpp
lubyk/bt
479561766e8578d670d5e215ae5d301c7a4d92dd
[ "Zlib" ]
null
null
null
/** * * MACHINE GENERATED FILE. DO NOT EDIT. * * Bindings for class btCollisionWorld * * This file has been generated by dub 2.2.1. */ #include "dub/dub.h" #include "BulletCollision/CollisionDispatch/btCollisionWorld.h" /** btCollisionWorld::btCollisionWorld(btDispatcher *dispatcher, btBroadphaseInterface *broadphasePairCache, btCollisionConfiguration *collisionConfiguration) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:113 */ static int btCollisionWorld_btCollisionWorld(lua_State *L) { try { btDispatcher *dispatcher = *((btDispatcher **)dub::checksdata(L, 1, "bt.Dispatcher")); btBroadphaseInterface *broadphasePairCache = *((btBroadphaseInterface **)dub::checksdata(L, 2, "bt.BroadphaseInterface")); btCollisionConfiguration *collisionConfiguration = *((btCollisionConfiguration **)dub::checksdata(L, 3, "bt.CollisionConfiguration")); btCollisionWorld *retval__ = new btCollisionWorld(dispatcher, broadphasePairCache, collisionConfiguration); dub::pushudata(L, retval__, "bt.CollisionWorld", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "new: %s", e.what()); } catch (...) { lua_pushfstring(L, "new: Unknown exception"); } return dub::error(L); } /** virtual btCollisionWorld::~btCollisionWorld() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:115 */ static int btCollisionWorld__btCollisionWorld(lua_State *L) { try { DubUserdata *userdata = ((DubUserdata*)dub::checksdata_d(L, 1, "bt.CollisionWorld")); if (userdata->gc) { btCollisionWorld *self = (btCollisionWorld *)userdata->ptr; delete self; } userdata->gc = false; return 0; } catch (std::exception &e) { lua_pushfstring(L, "__gc: %s", e.what()); } catch (...) { lua_pushfstring(L, "__gc: Unknown exception"); } return dub::error(L); } /** void btCollisionWorld::setBroadphase(btBroadphaseInterface *pairCache) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:117 */ static int btCollisionWorld_setBroadphase(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btBroadphaseInterface *pairCache = *((btBroadphaseInterface **)dub::checksdata(L, 2, "bt.BroadphaseInterface")); self->setBroadphase(pairCache); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setBroadphase: %s", e.what()); } catch (...) { lua_pushfstring(L, "setBroadphase: Unknown exception"); } return dub::error(L); } /** const btBroadphaseInterface* btCollisionWorld::getBroadphase() const * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:122 */ static int btCollisionWorld_getBroadphase(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); const btBroadphaseInterface *retval__ = self->getBroadphase(); if (!retval__) return 0; dub::pushudata(L, const_cast<btBroadphaseInterface*>(retval__), "bt.BroadphaseInterface", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getBroadphase: %s", e.what()); } catch (...) { lua_pushfstring(L, "getBroadphase: Unknown exception"); } return dub::error(L); } /** btOverlappingPairCache* btCollisionWorld::getPairCache() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:132 */ static int btCollisionWorld_getPairCache(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btOverlappingPairCache *retval__ = self->getPairCache(); if (!retval__) return 0; dub::pushudata(L, retval__, "OverlappingPairCache", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getPairCache: %s", e.what()); } catch (...) { lua_pushfstring(L, "getPairCache: Unknown exception"); } return dub::error(L); } /** btDispatcher* btCollisionWorld::getDispatcher() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:138 */ static int btCollisionWorld_getDispatcher(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btDispatcher *retval__ = self->getDispatcher(); if (!retval__) return 0; dub::pushudata(L, retval__, "bt.Dispatcher", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getDispatcher: %s", e.what()); } catch (...) { lua_pushfstring(L, "getDispatcher: Unknown exception"); } return dub::error(L); } /** void btCollisionWorld::updateSingleAabb(btCollisionObject *colObj) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:148 */ static int btCollisionWorld_updateSingleAabb(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btCollisionObject *colObj = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); self->updateSingleAabb(colObj); return 0; } catch (std::exception &e) { lua_pushfstring(L, "updateSingleAabb: %s", e.what()); } catch (...) { lua_pushfstring(L, "updateSingleAabb: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::updateAabbs() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:150 */ static int btCollisionWorld_updateAabbs(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); self->updateAabbs(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "updateAabbs: %s", e.what()); } catch (...) { lua_pushfstring(L, "updateAabbs: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::computeOverlappingPairs() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:154 */ static int btCollisionWorld_computeOverlappingPairs(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); self->computeOverlappingPairs(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "computeOverlappingPairs: %s", e.what()); } catch (...) { lua_pushfstring(L, "computeOverlappingPairs: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::setDebugDrawer(btIDebugDraw *debugDrawer) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:157 */ static int btCollisionWorld_setDebugDrawer(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btIDebugDraw *debugDrawer = *((btIDebugDraw **)dub::checksdata(L, 2, "bt.IDebugDraw")); self->setDebugDrawer(debugDrawer); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setDebugDrawer: %s", e.what()); } catch (...) { lua_pushfstring(L, "setDebugDrawer: Unknown exception"); } return dub::error(L); } /** virtual btIDebugDraw* btCollisionWorld::getDebugDrawer() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:162 */ static int btCollisionWorld_getDebugDrawer(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btIDebugDraw *retval__ = self->getDebugDrawer(); if (!retval__) return 0; dub::pushudata(L, retval__, "bt.IDebugDraw", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getDebugDrawer: %s", e.what()); } catch (...) { lua_pushfstring(L, "getDebugDrawer: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::debugDrawWorld() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:167 */ static int btCollisionWorld_debugDrawWorld(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); self->debugDrawWorld(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "debugDrawWorld: %s", e.what()); } catch (...) { lua_pushfstring(L, "debugDrawWorld: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::debugDrawObject(const btTransform &worldTransform, const btCollisionShape *shape, const btVector3 &color) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:169 */ static int btCollisionWorld_debugDrawObject(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btTransform *worldTransform = *((btTransform **)dub::checksdata(L, 2, "bt.Transform")); btCollisionShape *shape = *((btCollisionShape **)dub::checksdata(L, 3, "bt.CollisionShape")); btVector3 *color = *((btVector3 **)dub::checksdata(L, 4, "bt.Vector3")); self->debugDrawObject(*worldTransform, shape, *color); return 0; } catch (std::exception &e) { lua_pushfstring(L, "debugDrawObject: %s", e.what()); } catch (...) { lua_pushfstring(L, "debugDrawObject: Unknown exception"); } return dub::error(L); } /** int btCollisionWorld::getNumCollisionObjects() const * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:438 */ static int btCollisionWorld_getNumCollisionObjects(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); lua_pushnumber(L, self->getNumCollisionObjects()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNumCollisionObjects: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNumCollisionObjects: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::rayTest(const btVector3 &rayFromWorld, const btVector3 &rayToWorld, RayResultCallback &resultCallback) const * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:445 */ static int btCollisionWorld_rayTest(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btVector3 *rayFromWorld = *((btVector3 **)dub::checksdata(L, 2, "bt.Vector3")); btVector3 *rayToWorld = *((btVector3 **)dub::checksdata(L, 3, "bt.Vector3")); btCollisionWorld::RayResultCallback *resultCallback = *((btCollisionWorld::RayResultCallback **)dub::checksdata(L, 4, "bt.CollisionWorld.RayResultCallback")); self->rayTest(*rayFromWorld, *rayToWorld, *resultCallback); return 0; } catch (std::exception &e) { lua_pushfstring(L, "rayTest: %s", e.what()); } catch (...) { lua_pushfstring(L, "rayTest: Unknown exception"); } return dub::error(L); } /** void btCollisionWorld::convexSweepTest(const btConvexShape *castShape, const btTransform &from, const btTransform &to, ConvexResultCallback &resultCallback, btScalar allowedCcdPenetration=btScalar(0.)) const * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:449 */ static int btCollisionWorld_convexSweepTest(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); int top__ = lua_gettop(L); if (top__ >= 6) { btConvexShape *castShape = *((btConvexShape **)dub::checksdata(L, 2, "bt.ConvexShape")); btTransform *from = *((btTransform **)dub::checksdata(L, 3, "bt.Transform")); btTransform *to = *((btTransform **)dub::checksdata(L, 4, "bt.Transform")); btCollisionWorld::ConvexResultCallback *resultCallback = *((btCollisionWorld::ConvexResultCallback **)dub::checksdata(L, 5, "bt.CollisionWorld.ConvexResultCallback")); btScalar allowedCcdPenetration = dub::checknumber(L, 6); self->convexSweepTest(castShape, *from, *to, *resultCallback, allowedCcdPenetration); return 0; } else { btConvexShape *castShape = *((btConvexShape **)dub::checksdata(L, 2, "bt.ConvexShape")); btTransform *from = *((btTransform **)dub::checksdata(L, 3, "bt.Transform")); btTransform *to = *((btTransform **)dub::checksdata(L, 4, "bt.Transform")); btCollisionWorld::ConvexResultCallback *resultCallback = *((btCollisionWorld::ConvexResultCallback **)dub::checksdata(L, 5, "bt.CollisionWorld.ConvexResultCallback")); self->convexSweepTest(castShape, *from, *to, *resultCallback); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "convexSweepTest: %s", e.what()); } catch (...) { lua_pushfstring(L, "convexSweepTest: Unknown exception"); } return dub::error(L); } /** void btCollisionWorld::contactTest(btCollisionObject *colObj, ContactResultCallback &resultCallback) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:453 */ static int btCollisionWorld_contactTest(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btCollisionObject *colObj = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); btCollisionWorld::ContactResultCallback *resultCallback = *((btCollisionWorld::ContactResultCallback **)dub::checksdata(L, 3, "bt.CollisionWorld.ContactResultCallback")); self->contactTest(colObj, *resultCallback); return 0; } catch (std::exception &e) { lua_pushfstring(L, "contactTest: %s", e.what()); } catch (...) { lua_pushfstring(L, "contactTest: Unknown exception"); } return dub::error(L); } /** void btCollisionWorld::contactPairTest(btCollisionObject *colObjA, btCollisionObject *colObjB, ContactResultCallback &resultCallback) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:457 */ static int btCollisionWorld_contactPairTest(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btCollisionObject *colObjA = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); btCollisionObject *colObjB = *((btCollisionObject **)dub::checksdata(L, 3, "bt.CollisionObject")); btCollisionWorld::ContactResultCallback *resultCallback = *((btCollisionWorld::ContactResultCallback **)dub::checksdata(L, 4, "bt.CollisionWorld.ContactResultCallback")); self->contactPairTest(colObjA, colObjB, *resultCallback); return 0; } catch (std::exception &e) { lua_pushfstring(L, "contactPairTest: %s", e.what()); } catch (...) { lua_pushfstring(L, "contactPairTest: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::addCollisionObject(btCollisionObject *collisionObject, short int collisionFilterGroup=btBroadphaseProxy::DefaultFilter, short int collisionFilterMask=btBroadphaseProxy::AllFilter) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:484 */ static int btCollisionWorld_addCollisionObject(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); int top__ = lua_gettop(L); if (top__ >= 4) { btCollisionObject *collisionObject = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); short int *collisionFilterGroup = *((short int **)dub::checksdata(L, 3, "short int")); short int *collisionFilterMask = *((short int **)dub::checksdata(L, 4, "short int")); self->addCollisionObject(collisionObject, *collisionFilterGroup, *collisionFilterMask); return 0; } else if (top__ >= 3) { btCollisionObject *collisionObject = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); short int *collisionFilterGroup = *((short int **)dub::checksdata(L, 3, "short int")); self->addCollisionObject(collisionObject, *collisionFilterGroup); return 0; } else { btCollisionObject *collisionObject = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); self->addCollisionObject(collisionObject); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "addCollisionObject: %s", e.what()); } catch (...) { lua_pushfstring(L, "addCollisionObject: Unknown exception"); } return dub::error(L); } /** btCollisionObjectArray& btCollisionWorld::getCollisionObjectArray() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:486 */ static int btCollisionWorld_getCollisionObjectArray(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); dub::pushudata(L, &self->getCollisionObjectArray(), "CollisionObjectArray", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getCollisionObjectArray: %s", e.what()); } catch (...) { lua_pushfstring(L, "getCollisionObjectArray: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::removeCollisionObject(btCollisionObject *collisionObject) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:497 */ static int btCollisionWorld_removeCollisionObject(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btCollisionObject *collisionObject = *((btCollisionObject **)dub::checksdata(L, 2, "bt.CollisionObject")); self->removeCollisionObject(collisionObject); return 0; } catch (std::exception &e) { lua_pushfstring(L, "removeCollisionObject: %s", e.what()); } catch (...) { lua_pushfstring(L, "removeCollisionObject: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::performDiscreteCollisionDetection() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:499 */ static int btCollisionWorld_performDiscreteCollisionDetection(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); self->performDiscreteCollisionDetection(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "performDiscreteCollisionDetection: %s", e.what()); } catch (...) { lua_pushfstring(L, "performDiscreteCollisionDetection: Unknown exception"); } return dub::error(L); } /** btDispatcherInfo& btCollisionWorld::getDispatchInfo() * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:501 */ static int btCollisionWorld_getDispatchInfo(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); dub::pushudata(L, &self->getDispatchInfo(), "bt.DispatcherInfo", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getDispatchInfo: %s", e.what()); } catch (...) { lua_pushfstring(L, "getDispatchInfo: Unknown exception"); } return dub::error(L); } /** bool btCollisionWorld::getForceUpdateAllAabbs() const * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:511 */ static int btCollisionWorld_getForceUpdateAllAabbs(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); lua_pushboolean(L, self->getForceUpdateAllAabbs()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getForceUpdateAllAabbs: %s", e.what()); } catch (...) { lua_pushfstring(L, "getForceUpdateAllAabbs: Unknown exception"); } return dub::error(L); } /** void btCollisionWorld::setForceUpdateAllAabbs(bool forceUpdateAllAabbs) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:515 */ static int btCollisionWorld_setForceUpdateAllAabbs(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); bool forceUpdateAllAabbs = dub::checkboolean(L, 2); self->setForceUpdateAllAabbs(forceUpdateAllAabbs); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setForceUpdateAllAabbs: %s", e.what()); } catch (...) { lua_pushfstring(L, "setForceUpdateAllAabbs: Unknown exception"); } return dub::error(L); } /** virtual void btCollisionWorld::serialize(btSerializer *serializer) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:521 */ static int btCollisionWorld_serialize(lua_State *L) { try { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata(L, 1, "bt.CollisionWorld")); btSerializer *serializer = *((btSerializer **)dub::checksdata(L, 2, "Serializer")); self->serialize(serializer); return 0; } catch (std::exception &e) { lua_pushfstring(L, "serialize: %s", e.what()); } catch (...) { lua_pushfstring(L, "serialize: Unknown exception"); } return dub::error(L); } /** static void btCollisionWorld::rayTestSingle(const btTransform &rayFromTrans, const btTransform &rayToTrans, btCollisionObject *collisionObject, const btCollisionShape *collisionShape, const btTransform &colObjWorldTransform, RayResultCallback &resultCallback) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:463 */ static int btCollisionWorld_rayTestSingle(lua_State *L) { try { btTransform *rayFromTrans = *((btTransform **)dub::checksdata(L, 1, "bt.Transform")); btTransform *rayToTrans = *((btTransform **)dub::checksdata(L, 2, "bt.Transform")); btCollisionObject *collisionObject = *((btCollisionObject **)dub::checksdata(L, 3, "bt.CollisionObject")); btCollisionShape *collisionShape = *((btCollisionShape **)dub::checksdata(L, 4, "bt.CollisionShape")); btTransform *colObjWorldTransform = *((btTransform **)dub::checksdata(L, 5, "bt.Transform")); btCollisionWorld::RayResultCallback *resultCallback = *((btCollisionWorld::RayResultCallback **)dub::checksdata(L, 6, "bt.CollisionWorld.RayResultCallback")); btCollisionWorld::rayTestSingle(*rayFromTrans, *rayToTrans, collisionObject, collisionShape, *colObjWorldTransform, *resultCallback); return 0; } catch (std::exception &e) { lua_pushfstring(L, "rayTestSingle: %s", e.what()); } catch (...) { lua_pushfstring(L, "rayTestSingle: Unknown exception"); } return dub::error(L); } /** static void btCollisionWorld::rayTestSingleInternal(const btTransform &rayFromTrans, const btTransform &rayToTrans, const btCollisionObjectWrapper *collisionObjectWrap, RayResultCallback &resultCallback) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:469 */ static int btCollisionWorld_rayTestSingleInternal(lua_State *L) { try { btTransform *rayFromTrans = *((btTransform **)dub::checksdata(L, 1, "bt.Transform")); btTransform *rayToTrans = *((btTransform **)dub::checksdata(L, 2, "bt.Transform")); btCollisionObjectWrapper *collisionObjectWrap = *((btCollisionObjectWrapper **)dub::checksdata(L, 3, "CollisionObjectWrapper")); btCollisionWorld::RayResultCallback *resultCallback = *((btCollisionWorld::RayResultCallback **)dub::checksdata(L, 4, "bt.CollisionWorld.RayResultCallback")); btCollisionWorld::rayTestSingleInternal(*rayFromTrans, *rayToTrans, collisionObjectWrap, *resultCallback); return 0; } catch (std::exception &e) { lua_pushfstring(L, "rayTestSingleInternal: %s", e.what()); } catch (...) { lua_pushfstring(L, "rayTestSingleInternal: Unknown exception"); } return dub::error(L); } /** static void btCollisionWorld::objectQuerySingle(const btConvexShape *castShape, const btTransform &rayFromTrans, const btTransform &rayToTrans, btCollisionObject *collisionObject, const btCollisionShape *collisionShape, const btTransform &colObjWorldTransform, ConvexResultCallback &resultCallback, btScalar allowedPenetration) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:474 */ static int btCollisionWorld_objectQuerySingle(lua_State *L) { try { btConvexShape *castShape = *((btConvexShape **)dub::checksdata(L, 1, "bt.ConvexShape")); btTransform *rayFromTrans = *((btTransform **)dub::checksdata(L, 2, "bt.Transform")); btTransform *rayToTrans = *((btTransform **)dub::checksdata(L, 3, "bt.Transform")); btCollisionObject *collisionObject = *((btCollisionObject **)dub::checksdata(L, 4, "bt.CollisionObject")); btCollisionShape *collisionShape = *((btCollisionShape **)dub::checksdata(L, 5, "bt.CollisionShape")); btTransform *colObjWorldTransform = *((btTransform **)dub::checksdata(L, 6, "bt.Transform")); btCollisionWorld::ConvexResultCallback *resultCallback = *((btCollisionWorld::ConvexResultCallback **)dub::checksdata(L, 7, "bt.CollisionWorld.ConvexResultCallback")); btScalar allowedPenetration = dub::checknumber(L, 8); btCollisionWorld::objectQuerySingle(castShape, *rayFromTrans, *rayToTrans, collisionObject, collisionShape, *colObjWorldTransform, *resultCallback, allowedPenetration); return 0; } catch (std::exception &e) { lua_pushfstring(L, "objectQuerySingle: %s", e.what()); } catch (...) { lua_pushfstring(L, "objectQuerySingle: Unknown exception"); } return dub::error(L); } /** static void btCollisionWorld::objectQuerySingleInternal(const btConvexShape *castShape, const btTransform &convexFromTrans, const btTransform &convexToTrans, const btCollisionObjectWrapper *colObjWrap, ConvexResultCallback &resultCallback, btScalar allowedPenetration) * src/vendor/bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h:480 */ static int btCollisionWorld_objectQuerySingleInternal(lua_State *L) { try { btConvexShape *castShape = *((btConvexShape **)dub::checksdata(L, 1, "bt.ConvexShape")); btTransform *convexFromTrans = *((btTransform **)dub::checksdata(L, 2, "bt.Transform")); btTransform *convexToTrans = *((btTransform **)dub::checksdata(L, 3, "bt.Transform")); btCollisionObjectWrapper *colObjWrap = *((btCollisionObjectWrapper **)dub::checksdata(L, 4, "CollisionObjectWrapper")); btCollisionWorld::ConvexResultCallback *resultCallback = *((btCollisionWorld::ConvexResultCallback **)dub::checksdata(L, 5, "bt.CollisionWorld.ConvexResultCallback")); btScalar allowedPenetration = dub::checknumber(L, 6); btCollisionWorld::objectQuerySingleInternal(castShape, *convexFromTrans, *convexToTrans, colObjWrap, *resultCallback, allowedPenetration); return 0; } catch (std::exception &e) { lua_pushfstring(L, "objectQuerySingleInternal: %s", e.what()); } catch (...) { lua_pushfstring(L, "objectQuerySingleInternal: Unknown exception"); } return dub::error(L); } // --=============================================== __tostring static int btCollisionWorld___tostring(lua_State *L) { btCollisionWorld *self = *((btCollisionWorld **)dub::checksdata_n(L, 1, "bt.CollisionWorld")); lua_pushfstring(L, "bt.CollisionWorld: %p", self); return 1; } // --=============================================== METHODS static const struct luaL_Reg btCollisionWorld_member_methods[] = { { "new" , btCollisionWorld_btCollisionWorld }, { "__gc" , btCollisionWorld__btCollisionWorld }, { "setBroadphase", btCollisionWorld_setBroadphase }, { "getBroadphase", btCollisionWorld_getBroadphase }, { "getPairCache" , btCollisionWorld_getPairCache }, { "getDispatcher", btCollisionWorld_getDispatcher }, { "updateSingleAabb", btCollisionWorld_updateSingleAabb }, { "updateAabbs" , btCollisionWorld_updateAabbs }, { "computeOverlappingPairs", btCollisionWorld_computeOverlappingPairs }, { "setDebugDrawer", btCollisionWorld_setDebugDrawer }, { "getDebugDrawer", btCollisionWorld_getDebugDrawer }, { "debugDrawWorld", btCollisionWorld_debugDrawWorld }, { "debugDrawObject", btCollisionWorld_debugDrawObject }, { "getNumCollisionObjects", btCollisionWorld_getNumCollisionObjects }, { "rayTest" , btCollisionWorld_rayTest }, { "convexSweepTest", btCollisionWorld_convexSweepTest }, { "contactTest" , btCollisionWorld_contactTest }, { "contactPairTest", btCollisionWorld_contactPairTest }, { "addCollisionObject", btCollisionWorld_addCollisionObject }, { "getCollisionObjectArray", btCollisionWorld_getCollisionObjectArray }, { "removeCollisionObject", btCollisionWorld_removeCollisionObject }, { "performDiscreteCollisionDetection", btCollisionWorld_performDiscreteCollisionDetection }, { "getDispatchInfo", btCollisionWorld_getDispatchInfo }, { "getForceUpdateAllAabbs", btCollisionWorld_getForceUpdateAllAabbs }, { "setForceUpdateAllAabbs", btCollisionWorld_setForceUpdateAllAabbs }, { "serialize" , btCollisionWorld_serialize }, { "rayTestSingle", btCollisionWorld_rayTestSingle }, { "rayTestSingleInternal", btCollisionWorld_rayTestSingleInternal }, { "objectQuerySingle", btCollisionWorld_objectQuerySingle }, { "objectQuerySingleInternal", btCollisionWorld_objectQuerySingleInternal }, { "__tostring" , btCollisionWorld___tostring }, { "deleted" , dub::isDeleted }, { NULL, NULL}, }; extern "C" int luaopen_bt_CollisionWorld(lua_State *L) { // Create the metatable which will contain all the member methods luaL_newmetatable(L, "bt.CollisionWorld"); // <mt> // register member methods dub::fregister(L, btCollisionWorld_member_methods); // setup meta-table dub::setup(L, "bt.CollisionWorld"); // <mt> return 1; }
45.974882
331
0.721573
[ "shape", "transform" ]
1a4f0d6ed29f1f42a6ea54a775dda57688853756
1,147
cpp
C++
A12/docMaker.cpp
SoniCoder/Parallel_Computing-2018
609a75c6e5849a67741b1287f61bfabd6cb3de1d
[ "MIT" ]
null
null
null
A12/docMaker.cpp
SoniCoder/Parallel_Computing-2018
609a75c6e5849a67741b1287f61bfabd6cb3de1d
[ "MIT" ]
1
2018-02-20T12:36:53.000Z
2018-02-20T12:37:27.000Z
A12/docMaker.cpp
SoniCoder/Parallel_Computing-2018
609a75c6e5849a67741b1287f61bfabd6cb3de1d
[ "MIT" ]
1
2018-02-11T15:31:07.000Z
2018-02-11T15:31:07.000Z
#include <cstdlib> #include <fstream> #include <iostream> #include <mpi.h> #include <string> #include <unordered_map> #include <vector> using namespace std; int main(int argc, char * argv[]){ MPI_Init(&argc,&argv); int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); srand(time(0)+rank);//Initialize Pseudo-Random Seed ios::sync_with_stdio(false);//For faster IO cout << "Starting Document Maker on Rank " << rank << endl; const int wlslen = 69903; //Known Wordlist Length const int docwlen = 100000; //Desired Document Word Length const int docn = 10; //Desired Number of Documents string wlist[wlslen];//Store WordList on RAM ifstream wfile("wordlist"); string s; int i = 0; while (wfile >> s){ wlist[i] = s; ++i; } ofstream out; for(int cur_doc=0; cur_doc < docn; ++cur_doc){ out.open("doc-"+to_string(cur_doc));//Create new document for(int w_i=0; w_i<docwlen; ++w_i){ int w_index = rand() % wlslen; out << wlist[w_index] << " ";//Add random word to the document } out << endl; out.close(); } cout << "Document Maker finished on Rank " << rank << endl; MPI_Finalize(); return 0; }
20.122807
65
0.660854
[ "vector" ]
1a553467f08dbafb4777c452b753415cd938366a
2,329
cpp
C++
cpp/opendnp3/src/opendnp3/master/MasterTaskBase.cpp
tarm/dnp3_orig
87c639b3462c980fba255e85793f6ec663abe981
[ "Apache-2.0" ]
null
null
null
cpp/opendnp3/src/opendnp3/master/MasterTaskBase.cpp
tarm/dnp3_orig
87c639b3462c980fba255e85793f6ec663abe981
[ "Apache-2.0" ]
null
null
null
cpp/opendnp3/src/opendnp3/master/MasterTaskBase.cpp
tarm/dnp3_orig
87c639b3462c980fba255e85793f6ec663abe981
[ "Apache-2.0" ]
3
2016-07-13T18:54:13.000Z
2021-04-12T13:30:39.000Z
/** * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you 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. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include "MasterTaskBase.h" #include "AsyncTaskInterfaces.h" #include <openpal/LogMacros.h> #include "opendnp3/LogLevels.h" using namespace openpal; namespace opendnp3 { MasterTaskBase::MasterTaskBase(const openpal::Logger& logger_) : logger(logger_) {} bool MasterTaskBase::OnPartialResponse(const APDUResponseRecord& record) { if(this->ValidateIIN(record.IIN)) return this->_OnPartialResponse(record); else return false; } TaskResult MasterTaskBase::OnFinalResponse(const APDUResponseRecord& record) { if(this->ValidateIIN(record.IIN)) return this->_OnFinalResponse(record); else return TR_FAIL; } bool MasterTaskBase::ValidateIIN(const IINField& GetIIN) const { return true; } SingleRspBase::SingleRspBase(openpal::Logger& arLogger) : MasterTaskBase(arLogger) {} bool SingleRspBase::_OnPartialResponse(const APDUResponseRecord& record) { FORMAT_LOG_BLOCK(logger, flags::WARN, "Ignoring non-FIN response to task: ", this->Name()); return false; } SimpleRspBase::SimpleRspBase(openpal::Logger& arLogger) : SingleRspBase(arLogger) {} TaskResult SimpleRspBase::_OnFinalResponse(const APDUResponseRecord& record) { if(record.objects.Size() > 0) { FORMAT_LOG_BLOCK(logger, flags::WARN, "Unexpected object data in response to task: %s", this->Name()); } return TR_SUCCESS; } } //ens ns
29.858974
104
0.766853
[ "object" ]
1a5957d0d5e201ed02f741261ebe310e2115e9e1
1,336
cpp
C++
Merge_k_Sorted_Lists_v2.cpp
xiekc/leetcode
56dc65850ac68752f7c6f50f8b35eb23bfafed93
[ "MIT" ]
null
null
null
Merge_k_Sorted_Lists_v2.cpp
xiekc/leetcode
56dc65850ac68752f7c6f50f8b35eb23bfafed93
[ "MIT" ]
null
null
null
Merge_k_Sorted_Lists_v2.cpp
xiekc/leetcode
56dc65850ac68752f7c6f50f8b35eb23bfafed93
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * time complexity: N*logk */ #include <queue> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { void addNode(ListNode *&head, ListNode *&tail, int &val) { if (NULL == head) { head = new ListNode(val); tail = head; } else { tail->next = new ListNode(val); tail = tail->next; } } public: ListNode *mergeKLists(vector<ListNode *> &lists) { ListNode *head = NULL, *tail = NULL; priority_queue<pair<int, ListNode *>> pq; int minimum = 0xfffff, index = -1; for (int i = 0; i < lists.size(); i++) { if (lists[i] != NULL) { pq.push(make_pair(-1 * lists[i]->val, lists[i]->next)); } } while (!pq.empty()) { pair p = pq.top(); pq.pop(); p.first = -1 * p.first; addNode(head, tail, p.first); if (p.second != NULL) { pq.push(make_pair(-1 * p.second->val, p.second->next)); } } return head; } };
24.740741
71
0.478293
[ "vector" ]
1a5aa2970ac8596ab0566f51523263cadba9c6ae
8,056
cpp
C++
src/mumble/PositionalSound.cpp
main--/mumble
e1bdd6564bb0445c535d3c711e5142d9bafa13d8
[ "BSD-3-Clause" ]
2
2017-03-20T22:18:53.000Z
2018-12-12T09:34:27.000Z
src/mumble/PositionalSound.cpp
Rantanen/mumble
762122319381bd9d5f23f497c68aad5186e30d91
[ "BSD-3-Clause" ]
null
null
null
src/mumble/PositionalSound.cpp
Rantanen/mumble
762122319381bd9d5f23f497c68aad5186e30d91
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com> Copyright (C) 2008, Andreas Messer <andi@bupfen.de> 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 Mumble Developers 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 FOUNDATION 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 "mumble_pch.hpp" #include "PositionalSound.h" #include "Global.h" PlotWidget::PlotWidget(QWidget *p, const QList<float> &xl,const QList<float> &yl) : QWidget(p), xdata(xl), ydata(yl) { setPalette(QPalette(QColor(255,255,255))); setAutoFillBackground(true); setMinimumSize(20,20); setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); } void PlotWidget::paintEvent(QPaintEvent *) { QPainter painter(this); if (xdata.size() < 2 || ydata.size() < 2) return; float minx = xdata.front(); float maxx = xdata.back(); float miny = ydata.front(); float maxy = ydata.back(); float f; foreach(f,ydata) { miny = qMin(miny,f); maxy = qMax(maxy,f); } if (miny == maxy) { miny -= 1; maxy += 1; } const int hght = this->height(); const int wdth = this->width(); painter.drawLine(15,hght - 20, wdth, hght -20); painter.drawLine(20,hght - 15, 20, 0); float ticstep = 1; while ((maxx - minx) / ticstep > 10.9) ticstep *= 2; for (f = (lround(minx / ticstep) + 1) * ticstep; f < maxx; f += ticstep) { const int ipos = lround(20 + (wdth-20) * (f-minx) / (maxx-minx)); painter.drawLine(ipos,hght - 20, ipos, hght -17); painter.drawText(QRect(ipos-20,hght-17,40,17),Qt::AlignCenter,QString::number(lroundf(f))); } ticstep = 1; while ((maxy - miny) / ticstep > 10.9) ticstep *= 2; for (f = (lround(miny / ticstep) + 1) * ticstep; f < maxy; f += ticstep) { const int ipos = lround((hght-20) *(1 - (f - miny) / (maxy-miny))); painter.drawLine(17 ,ipos , 20, ipos); painter.drawText(QRect(0,ipos-10,17,20),Qt::AlignCenter,QString::number(lroundf(f))); } QList<float>::const_iterator xit = xdata.begin(); QList<float>::const_iterator yit = ydata.begin(); float xold = *(xit++); float yold = *(yit++); painter.setPen(QColor(255,0,0)); while (xit != xdata.end() && yit != ydata.end()) { painter.drawLine( lround(20 + (wdth-20) * (xold-minx) / (maxx-minx)), lround((hght-20) *(1 - (yold - miny) / (maxy-miny))), lround(20 + (wdth-20) * (*xit-minx) / (maxx-minx)), lround((hght-20) * (1 - (*yit - miny) / (maxy-miny)))); xold = *(xit++); yold = *(yit++); } } int PlotWidget::heightForWidth(int w) const { return w * 3 / 4; } static ConfigWidget *PositionalSoundConfigDialogNew(Settings &st) { return new PositionalSoundConfig(st); } static ConfigRegistrar registrar(29, PositionalSoundConfigDialogNew); PositionalSoundConfig::PositionalSoundConfig(Settings &st) : ConfigWidget(st) { setupUi(this); plot = new PlotWidget(qgbVolume,xdata,ydata); plot->setObjectName(QString::fromUtf8("Plot")); gridLayout->addWidget(plot, 3, 1, 1, 3); qcbModel->addItem(tr("constant"),Settings::CONSTANT); qcbModel->addItem(tr("linear"),Settings::LINEAR); update(); } PositionalSoundConfig::~PositionalSoundConfig() { delete plot; } QString PositionalSoundConfig::title() const { return tr("Positional Sound"); } QIcon PositionalSoundConfig::icon() const { return QIcon(QLatin1String("skin:config_dsound.png")); } void PositionalSoundConfig::save() const { s.ePositionalSoundModel = static_cast<Settings::PositionalSoundModels>(qcbModel->itemData(qcbModel->currentIndex()).toInt()); s.fPositionalSoundDistance = qdsbDistance->value(); s.fPositionalSoundPreGain = qdsbPreGain->value(); s.fPositionalSoundMaxAtt = qdsbMaxAtt->value(); s.bPositionalSoundEnable = qcbEnable->checkState() == Qt::Checked; s.bPositionalSoundSwap = qcbSwap->checkState() == Qt::Checked; } void PositionalSoundConfig::load(const Settings &r) { for (int i=0;i<qcbModel->count();i++) { if (qcbModel->itemData(i).toInt() == r.ePositionalSoundModel) { loadComboBox(qcbModel, i); break; } } qdsbDistance->setValue(r.fPositionalSoundDistance); qdsbPreGain->setValue(r.fPositionalSoundPreGain); qdsbMaxAtt->setValue(r.fPositionalSoundMaxAtt); qcbEnable->setCheckState(r.bPositionalSoundEnable ? Qt::Checked : Qt::Unchecked); qcbSwap->setCheckState(r.bPositionalSoundSwap ? Qt::Checked : Qt::Unchecked); update(); } bool PositionalSoundConfig::expert(bool) { return false; } void PositionalSoundConfig::update() { const Settings::PositionalSoundModels model = static_cast<Settings::PositionalSoundModels>(qcbModel->itemData(qcbModel->currentIndex()).toInt()); const float distance = qdsbDistance->value(); const float pregain = qdsbPreGain->value(); const float maxatt = qdsbMaxAtt->value(); float yold = pregain; float xmax = 1000; xdata.clear(); ydata.clear(); for (float xv = 0; xv < xmax; xv+= 1) { xdata << xv; float yv = 0; switch (model) { case Settings::CONSTANT: yv = PositionalSound::ModelConstant(pregain); break; case Settings::LINEAR: yv = PositionalSound::ModelLinear(pregain,maxatt,distance,xv); break; } ydata << yv; if (yold - yv < 1e-10 && xmax >= 1000 && xv > 0) xmax = 1.1*xv+1; yold = yv; } plot->update(); } void PositionalSoundConfig::on_qcbEnable_stateChanged(int state) { if (state == Qt::Checked) { qcbSwap->setEnabled(true); qgbVolume->setEnabled(true); } else { qcbSwap->setEnabled(false); qgbVolume->setEnabled(false); } } void PositionalSoundConfig::on_qcbModel_currentIndexChanged(int i) { if (qcbModel->itemData(i).toInt() == Settings::CONSTANT) { qdsbDistance->setEnabled(false); qdsbMaxAtt->setEnabled(false); } else { qdsbDistance->setEnabled(true); qdsbMaxAtt->setEnabled(true); } update(); } void PositionalSoundConfig::on_qdsbDistance_valueChanged(double) { update(); } void PositionalSoundConfig::on_qdsbPreGain_valueChanged(double) { update(); } void PositionalSoundConfig::on_qdsbMaxAtt_valueChanged(double) { update(); } float PositionalSound::todB(float ratio) { return 20.0f * log10f(ratio); } float PositionalSound::toRatio(float dB) { return powf(10.0f, dB / 20.0f); } float PositionalSound::ModelConstant(float pregain) { return pregain; } float PositionalSound::ModelLinear(float pregain, float maxatt, float distance, float d) { float att = 10.0f * d/distance; return pregain - (att < maxatt ? att : maxatt); } float PositionalSound::calcdB(float d) { switch (g.s.ePositionalSoundModel) { case Settings::CONSTANT: return ModelConstant(g.s.fPositionalSoundPreGain); case Settings::LINEAR: return ModelLinear(g.s.fPositionalSoundPreGain, g.s.fPositionalSoundMaxAtt, g.s.fPositionalSoundDistance, d); default: break; } return 0.0f; }
27.972222
126
0.707795
[ "model" ]
1a6383bf1233296f8118b0ed2ef4a0ada9875a8b
1,064
hpp
C++
lumino/LuminoEngine/include/LuminoEngine/Scene/Common.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
113
2020-03-05T01:27:59.000Z
2022-03-28T13:20:51.000Z
lumino/LuminoEngine/include/LuminoEngine/Scene/Common.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/LuminoEngine/include/LuminoEngine/Scene/Common.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
12
2020-12-21T12:03:59.000Z
2021-12-15T02:07:49.000Z
 #pragma once #include <LuminoEngine/Base/Delegate.hpp> #include <LuminoEngine/Graphics/ColorStructs.hpp> namespace ln { class MeshModel; class MeshComponent; class ParticleEmitterComponent2; class WorldObject; class World; class WorldRenderView; class Level; class Camera; class Raycaster; class RaycastResult; class Material; class RenderingContext; class OffscreenWorldRenderView; class ReflectorComponent; class Collision; class CameraOrbitControlComponent; /** CollisionEventHandler */ LN_DELEGATE() using CollisionEventHandler = Delegate<void(Collision*)>; /** レベル遷移時の画面エフェクトの種類 */ LN_ENUM() enum class LevelTransitionEffectMode { /** エフェクト無し */ None, /** フェードイン・フェードアウト */ FadeInOut, /** クロスフェード */ CrossFade, }; class IWorldRenderingElement { protected: //virtual void onPrepareRender(RenderingContext* context) = 0; virtual void render(RenderingContext* context) = 0; friend class World; }; namespace detail { class IWorldObjectVisitor; } // namespace detail } // namespace ln
18.344828
64
0.736842
[ "render" ]
1a6db51b51be1764d6ebdf42f41d115a035c2a6f
1,703
cpp
C++
bytecode/generator/src/Generator/GeneratorOperatorUserDefinedObject.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
3
2019-04-08T17:34:19.000Z
2020-01-03T04:47:06.000Z
bytecode/generator/src/Generator/GeneratorOperatorUserDefinedObject.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
4
2020-04-19T22:09:06.000Z
2020-11-06T15:47:08.000Z
bytecode/generator/src/Generator/GeneratorOperatorUserDefinedObject.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
null
null
null
#include "Config/LoggerConfigLang.h" #include <string> #include "NodeValue/AST.h" #include "GeneratorOperatorUserDefinedObject.h" #include "BytecodeCommand.h" #include "Generator/Value/BytecodeScriptGenerationHelper.h" #include "Generator/Value/BytecodeSymbolInfo.h" SKA_LOGC_CONFIG(ska::LogLevel::Disabled, ska::bytecode::GeneratorOperator<ska::Operator::USER_DEFINED_OBJECT>); #define LOG_INFO SLOG_STATIC(ska::LogLevel::Info, ska::bytecode::GeneratorOperator<ska::Operator::USER_DEFINED_OBJECT>) #define LOG_DEBUG SLOG_STATIC(ska::LogLevel::Debug, ska::bytecode::GeneratorOperator<ska::Operator::USER_DEFINED_OBJECT>) ska::bytecode::InstructionOutput ska::bytecode::GeneratorOperator<ska::Operator::USER_DEFINED_OBJECT>::generate(OperateOn node, GenerationContext& context) { auto objectResult = InstructionOutput{ }; std::size_t childIndex = 0; for(auto& field: node) { auto valueGroup = generateNext({ context, *field, 1 }); auto* oldSymbolInfo = context.getSymbolInfo(*field); auto symbolInfo = SymbolInfo { context.scope() + 1, field->name(), context.scriptIndex() }; if (oldSymbolInfo != nullptr) { symbolInfo.binding = oldSymbolInfo->binding; symbolInfo.bindingPassThrough = oldSymbolInfo->bindingPassThrough; } symbolInfo.childIndex = childIndex; LOG_INFO << "%12cRegistering symbol info " << symbolInfo << " for field node " << *field << " (this symbol is not exported)"; context.setSymbolInfo(*field, std::move(symbolInfo)); valueGroup.push(Instruction { Command::PUSH, valueGroup.operand() }); objectResult.push(std::move(valueGroup)); childIndex++; } LOG_INFO << "Creating user defined object "; LOG_DEBUG << objectResult; return objectResult; }
41.536585
157
0.760423
[ "object" ]
2b3258e5d6c9a6dbaa61d050988a31d9397f2613
5,242
hpp
C++
test/test-constants.hpp
rpetrano/libndef-lite
6df1d55bd525bb00e7242979b8e7e3422375f643
[ "MIT" ]
null
null
null
test/test-constants.hpp
rpetrano/libndef-lite
6df1d55bd525bb00e7242979b8e7e3422375f643
[ "MIT" ]
null
null
null
test/test-constants.hpp
rpetrano/libndef-lite
6df1d55bd525bb00e7242979b8e7e3422375f643
[ "MIT" ]
1
2021-03-08T20:46:28.000Z
2021-03-08T20:46:28.000Z
#ifndef TEST_CONSTANTS_HPP #define TEST_CONSTANTS_HPP #include <string> #include <vector> // clang-format off static const std::vector<uint8_t> invalid_record_bytes{ 0xd3, 0x4d, 0xb3, 0x3f }; static const std::vector<uint8_t> valid_text_record_bytes_sr{ // Record Header // - Message Begin (1b), Message End (1b), Last chunk (0b), Short Record (1b) // - ID Length not present (0b), NFC Forum Well Known Type TNF (0b001) 0xd1, // Type length // - Payload type field is 1 octet long (single "T" char) // - No ID Length 0x01, // Payload length // - 19 octet (character) long payload // - SR flag set 0x13, // Well Known Type - Text (ASCII "T") 0x54, // Text encoding information // - UTF-8 (1b), RFU (always 0b), IANA language code "en-US" length = 5 (0b00101) 0x85, // ISO/IANA language code "en-US" encoded in US-ASCII 0x65, 0x6e, 0x2d, 0x55, 0x53, // UTF-8 encoded text payload ("Hello, World") 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, }; static const std::vector<uint8_t> valid_text_record_bytes_sr_id{ // Record Header // - Message Begin (1b), Message End (1b), Last chunk (0b), Short Record (1b) // - ID Length present (1b), NFC Forum Well Known Type TNF (0b001) 0xd9, // Type length // - Payload type field is 1 octet long (single "T" char) 0x01, // Payload length // - 19 octet (character) long payload // - SR flag set 0x13, // ID length field 0x04, // Well Known Type - Text (ASCII "T") 0x54, // ID Field - "test" 0x74, 0x65, 0x73, 0x74, // Text encoding information // - UTF-8 (1b), RFU (always 0b), IANA language code "en-US" length = 5 (0b00101) 0x85, // ISO/IANA language code "en-US" encoded in US-ASCII 0x65, 0x6e, 0x2d, 0x55, 0x53, // UTF-8 encoded text payload ("Hello, World") 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, }; static const std::vector<uint8_t> valid_text_record_bytes_nosr{ // Record Header // - Message Begin (1b), Message End (1b), Last chunk (0b), Short Record (0b) // - ID Length not present (0b), NFC Forum Well Known Type TNF (0b001) 0xc1, // Type length // - Payload type field is 1 octet long (single "T" char) // - No ID Length 0x01, // Payload length // - 257 octet (character) long payload 0x00, 0x00, 0x01, 0x07, // Well Known Type - Text (ASCII "T") 0x54, // Text encoding information // - UTF-8 (1b), RFU (always 0b), IANA language code "en-US" length = 5 (0b00101) 0x85, // ISO/IANA language code "en-US" encoded in US-ASCII 0x65, 0x6e, 0x2d, 0x55, 0x53, // UTF-8 encoded text payload 257 random ASCII/UTF-8 characters 0x64, 0x78, 0x6c, 0x66, 0x6e, 0x65, 0x72, 0x65, 0x78, 0x7a, 0x76, 0x79, 0x73, 0x69, 0x67, 0x77, 0x75, 0x67, 0x66, 0x73, 0x64, 0x74, 0x71, 0x69, 0x6d, 0x6d, 0x6e, 0x7a, 0x6b, 0x74, 0x72, 0x68, 0x65, 0x6c, 0x62, 0x6f, 0x6a, 0x69, 0x70, 0x6a, 0x71, 0x73, 0x64, 0x61, 0x6b, 0x76, 0x77, 0x7a, 0x74, 0x64, 0x68, 0x6e, 0x6d, 0x76, 0x71, 0x6c, 0x65, 0x79, 0x69, 0x79, 0x6c, 0x73, 0x66, 0x63, 0x70, 0x73, 0x64, 0x74, 0x6b, 0x64, 0x71, 0x61, 0x63, 0x65, 0x6e, 0x7a, 0x6a, 0x68, 0x71, 0x65, 0x71, 0x72, 0x75, 0x6e, 0x72, 0x6c, 0x77, 0x6e, 0x76, 0x64, 0x73, 0x61, 0x70, 0x62, 0x6f, 0x73, 0x69, 0x6a, 0x77, 0x75, 0x6e, 0x62, 0x70, 0x75, 0x78, 0x67, 0x65, 0x69, 0x69, 0x73, 0x61, 0x63, 0x74, 0x65, 0x73, 0x6b, 0x63, 0x76, 0x78, 0x63, 0x6c, 0x72, 0x63, 0x62, 0x6f, 0x73, 0x6e, 0x63, 0x73, 0x6e, 0x7a, 0x61, 0x69, 0x71, 0x6b, 0x65, 0x75, 0x6e, 0x68, 0x6b, 0x6c, 0x79, 0x6d, 0x63, 0x79, 0x70, 0x78, 0x6e, 0x75, 0x63, 0x61, 0x63, 0x75, 0x6d, 0x73, 0x68, 0x70, 0x79, 0x61, 0x70, 0x62, 0x62, 0x65, 0x74, 0x6c, 0x65, 0x68, 0x7a, 0x76, 0x63, 0x62, 0x68, 0x66, 0x75, 0x70, 0x72, 0x65, 0x6c, 0x70, 0x69, 0x74, 0x6a, 0x63, 0x6c, 0x78, 0x67, 0x76, 0x61, 0x67, 0x73, 0x6b, 0x61, 0x6f, 0x63, 0x78, 0x70, 0x67, 0x69, 0x72, 0x72, 0x75, 0x72, 0x71, 0x73, 0x68, 0x69, 0x6a, 0x6f, 0x69, 0x76, 0x6e, 0x69, 0x68, 0x67, 0x61, 0x75, 0x67, 0x72, 0x6c, 0x69, 0x69, 0x77, 0x64, 0x7a, 0x75, 0x73, 0x61, 0x6e, 0x63, 0x74, 0x71, 0x70, 0x75, 0x68, 0x77, 0x6b, 0x6b, 0x64, 0x6a, 0x79, 0x61, 0x64, 0x6e, 0x69, 0x66, 0x64, 0x6a, 0x68, 0x6c, 0x64, 0x68, 0x61, 0x67, 0x64, 0x61, 0x6c, 0x6d }; static const std::vector<uint8_t> valid_https_prefix_uri_payload{ // Prefix is https:// 0x02, // Contents are google.com, encoded in UTF-8 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, }; static const std::vector<uint8_t> valid_utf8_text_payload{ // Text encoding information // - UTF-8 (1b), RFU (always 0b), IANA language code "en-US" length = 5 (0b00101) 0x85, // ISO/IANA language code "en-US" encoded in US-ASCII 0x65, 0x6e, 0x2d, 0x55, 0x53, // UTF-8 encoded text payload ("Hello, World") 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, }; // clang-format on const std::string rand_string_257 = "dxlfnerexzvysigwugfsdtqimmnzktrhelbojipjqsdakvwztdhnmvqleyiylsfcpsdtkdqacenzjhqeqrunrlwnvdsa" "pbosijwunbpuxgeiisacteskcvxclrcbosncsnzaiqkeunhklymcypxnucacumshpyapbbetlehzvcbhfuprelpitjcl" "xgvagskaocxpgirrurqshijoivnihgaugrliiwdzusanctqpuhwkkdjyadnifdjhldhagdalm"; #endif // TEST_CONSTANTS_HPP
37.177305
115
0.67169
[ "vector" ]
2b32e44fc5ddded2fd317dcc408de09fc17259d2
1,065
cpp
C++
leetcode/medium/63. Unique Paths II.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
7
2019-08-05T14:49:41.000Z
2022-03-13T07:10:51.000Z
leetcode/medium/63. Unique Paths II.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
leetcode/medium/63. Unique Paths II.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
4
2021-01-04T03:45:22.000Z
2021-10-06T06:11:00.000Z
/** * problem : https://leetcode.com/problems/unique-paths-ii/ * algorithm : DP * time complexity : O(NM) */ class Solution { public: vector<vector<int>> d = vector<vector<int>>(); vector<vector<int>> obstacle = vector<vector<int>>(); int row = 0; int col = 0; int dx[2] = {0, 1}; int dy[2] = {1, 0}; int go(int x, int y){ int& ret = d[x][y]; if(ret != -1) return ret; ret = 0; if(obstacle[x][y] == 1) return ret = 0; if(x==row-1 && y==col-1) return ret = 1; for(int i=0; i<2; i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(nx < row && ny < col) ret += go(nx, ny); } return ret; } int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { obstacle = obstacleGrid; row = obstacleGrid.size(); col = obstacleGrid[0].size(); d.resize(row, vector<int>(col, -1)); return go(0, 0); } };
23.666667
69
0.451643
[ "vector" ]
2b36a881aab466056971657ae935b89d11aadfe0
6,606
cc
C++
plugins/textual/sql_csv_scope.cc
kstepanmpmg/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
665
2015-12-09T17:00:14.000Z
2022-03-25T07:46:46.000Z
plugins/textual/sql_csv_scope.cc
tomzhang/mldb
a09cf2d9ca454d1966b9e49ae69f2fe6bf571494
[ "Apache-2.0" ]
797
2015-12-09T19:48:19.000Z
2022-03-07T02:19:47.000Z
plugins/textual/sql_csv_scope.cc
matebestek/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
103
2015-12-25T04:39:29.000Z
2022-02-03T02:55:22.000Z
/** sql_csv_scope.h -*- C++ -*- Jeremy Barnes, 27 June 2017 Copyright (c) 2017 Element AI Inc. All rights reserved. */ #include "sql_csv_scope.h" #include "mldb/types/annotated_exception.h" #include "mldb/types/basic_value_descriptions.h" using namespace std; namespace MLDB { /*****************************************************************************/ /* SQL CSV SCOPE */ /*****************************************************************************/ /** This allows an SQL expression to be bound to a parsed CSV row, which allowing it to find the variables, etc. */ SqlCsvScope:: SqlCsvScope(MldbEngine * engine, const std::vector<ColumnPath> & columnNames, Date fileTimestamp, Utf8String dataFileUrl) : SqlExpressionMldbScope(engine), columnNames(columnNames), fileTimestamp(fileTimestamp), dataFileUrl(std::move(dataFileUrl)) { columnsUsed.resize(columnNames.size(), false); lineNumberUsed = false; } ColumnGetter SqlCsvScope:: doGetColumn(const Utf8String & tableName, const ColumnPath & columnName) { if (!tableName.empty()) { throw AnnotatedException(400, "Unknown table name in import.text procedure", "tableName", tableName); } int index = std::find(columnNames.begin(), columnNames.end(), columnName) - columnNames.begin(); if (index == columnNames.size()) throw AnnotatedException(400, "Unknown column name in import.text procedure", "columnName", columnName, "knownColumnNames", columnNames); columnsUsed[index] = true; return {[=] (const SqlRowScope & scope, ExpressionValue & storage, const VariableFilter & filter) -> const ExpressionValue & { auto & row = scope.as<RowScope>(); return storage = ExpressionValue(row.row[index], row.ts); }, std::make_shared<AtomValueInfo>()}; } GetAllColumnsOutput SqlCsvScope:: doGetAllColumns(const Utf8String & tableName, const ColumnFilter& keep) { vector<ColumnPath> toKeep; std::vector<KnownColumn> columnsWithInfo; size_t numToKeep = 0; for (unsigned i = 0; i < columnNames.size(); ++i) { const ColumnPath & columnName = columnNames[i]; ColumnPath outputName(keep(columnName)); bool keep = !outputName.empty(); toKeep.emplace_back(outputName); if (keep) { columnsUsed[i] = true; columnsWithInfo.emplace_back(outputName, std::make_shared<AtomValueInfo>(), COLUMN_IS_DENSE); ++numToKeep; } } // Fill out the offset so we know where it is in the input for (size_t i = 0; i < columnsWithInfo.size(); ++i) { columnsWithInfo[i].offset = i; } auto exec = [=] (const SqlRowScope & scope, const VariableFilter & filter) { /* The filter parameter here is not used since this context is only used when importing tabular data and there is no way to specify a timestamp for this data. */ auto & row = scope.as<RowScope>(); RowValue result; result.reserve(numToKeep); for (unsigned i = 0; i < columnNames.size(); ++i) { if (!toKeep[i].empty()) result.emplace_back(columnNames[i], row.row[i], row.ts); } ExcAssertEqual(result.size(), numToKeep); return result; }; GetAllColumnsOutput result; result.exec = exec; result.info = std::make_shared<RowValueInfo>(std::move(columnsWithInfo), SCHEMA_CLOSED); return result; } BoundFunction SqlCsvScope:: doGetFunction(const Utf8String & tableName, const Utf8String & functionName, const std::vector<BoundSqlExpression> & args, SqlBindingScope & argScope) { if (functionName == "lineNumber") { lineNumberUsed = true; return {[=] (const std::vector<ExpressionValue> & args, const SqlRowScope & scope) { auto & row = scope.as<RowScope>(); return ExpressionValue(row.lineNumber, fileTimestamp); }, std::make_shared<IntegerValueInfo>() }; } else if (functionName == "rowHash") { lineNumberUsed = true; return {[=] (const std::vector<ExpressionValue> & args, const SqlRowScope & scope) { auto & row = scope.as<RowScope>(); if(!row.rowName) { throw MLDB::Exception("rowHash() not available in this scope"); } return ExpressionValue(row.rowName->hash(), fileTimestamp); }, std::make_shared<IntegerValueInfo>() }; } else if (functionName == "fileTimestamp") { return {[=] (const std::vector<ExpressionValue> & args, const SqlRowScope & scope) { return ExpressionValue(fileTimestamp, fileTimestamp); }, std::make_shared<TimestampValueInfo>() }; } else if (functionName == "dataFileUrl") { return {[=] (const std::vector<ExpressionValue> & args, const SqlRowScope & scope) { return ExpressionValue(dataFileUrl, fileTimestamp); }, std::make_shared<Utf8StringValueInfo>() }; } else if (functionName == "lineOffset") { return {[=] (const std::vector<ExpressionValue> & args, const SqlRowScope & scope) { auto & row = scope.as<RowScope>(); return ExpressionValue(row.lineOffset, fileTimestamp); }, std::make_shared<IntegerValueInfo>() }; } return SqlBindingScope::doGetFunction(tableName, functionName, args, argScope); } } // namespace MLDB
34.768421
87
0.514078
[ "vector" ]
2b4ff47d5924c8f1a12a69158650e4a28903056e
2,845
cpp
C++
test/ArticleTests.cpp
dueringa/WikiWalker
24a83936efac1e217af949275b0677861c216957
[ "MIT" ]
null
null
null
test/ArticleTests.cpp
dueringa/WikiWalker
24a83936efac1e217af949275b0677861c216957
[ "MIT" ]
1
2018-03-17T15:42:18.000Z
2018-03-19T11:49:03.000Z
test/ArticleTests.cpp
dueringa/WikiWalker
24a83936efac1e217af949275b0677861c216957
[ "MIT" ]
null
null
null
#include <UnitTest++/UnitTest++.h> #include <algorithm> #include <iterator> #include <memory> #include <vector> #include "Article.h" #include "WalkerException.h" SUITE(ArticleTests) { using namespace WikiWalker; TEST(Article_GetCountLinks_Uninited_ThrowsException) { Article a("Foo"); CHECK_EQUAL(false, a.analyzed()); CHECK_THROW(a.countLinks(), WalkerException); } TEST(Article_GetCountLinks_Inited_ReturnsNull) { Article a("Foo"); a.analyzed(true); CHECK_EQUAL(true, a.analyzed()); CHECK_EQUAL(0, a.countLinks()); } TEST(Article_AddLinks_OneLinkAdded) { Article a("Foo"); auto link = std::make_shared<Article>("Barmiz"); a.addLink(link); CHECK_EQUAL(true, a.analyzed()); CHECK_EQUAL(1, a.countLinks()); } TEST(Article_AddLinks_DuplicateInstance) { Article a("Foo"); auto arl = std::make_shared<Article>("Barmiz"); CHECK(a.addLink(arl)); CHECK(!a.addLink(arl)); CHECK_EQUAL(true, a.analyzed()); CHECK_EQUAL(1, a.countLinks()); } TEST(Article_AddLinks_WhenLinkExpiredToNulltpr) { Article a("Foo"); { /* Checks for absence of bug with nullptr access when checking for * duplicates */ auto arl = std::make_shared<Article>("Barmiz"); CHECK(a.addLink(arl)); } auto arl2 = std::make_shared<Article>("Barmiz"); CHECK(a.addLink(arl2)); CHECK_EQUAL(a.analyzed(), true); /* this one's actually awkward and is counterintuitive. But since the * shared_ptr went out of scope, it expired. I chose to simply ignore * expired smart pointers / nullptrs inside the link collection for actual * processing purposes. They're still counted, however. */ CHECK_EQUAL(2, a.countLinks()); } TEST(Article_Iterator_Test) { Article a("Foo"); std::vector<std::string> titles{"Barmiz", "Kodopa", "Minting"}; // must keep them in scope std::vector<std::shared_ptr<Article>> articleLinks; std::transform(titles.begin(), titles.end(), std::back_inserter(articleLinks), [](std::string s) { return std::make_shared<Article>(s); }); for(const auto& s : articleLinks) { a.addLink(s); } CHECK_EQUAL(true, a.analyzed()); CHECK_EQUAL(3, a.countLinks()); int num = 0; for(auto x = a.linkBegin(); x != a.linkEnd(); x++) { num++; auto atitle = x->lock()->title(); auto findpos = std::find(titles.cbegin(), titles.cend(), atitle); bool isFound = (titles.end() != findpos); CHECK(isFound); } CHECK_EQUAL(num, titles.size()); } TEST(Article_Marked_State) { Article a("Todo"); CHECK_EQUAL(false, a.marked()); a.marked(true); CHECK_EQUAL(true, a.marked()); a.marked(false); CHECK_EQUAL(false, a.marked()); } }
24.316239
79
0.628822
[ "vector", "transform" ]
2b503af711d214f5b3700f3aa5a0ca484dd62b6c
12,330
hxx
C++
opencascade/gp_Quaternion.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/gp_Quaternion.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/gp_Quaternion.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Created on: 2010-05-11 // Created by: Kirill GAVRILOV // Copyright (c) 2010-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gp_Quaternion_HeaderFile #define _gp_Quaternion_HeaderFile #include <gp_EulerSequence.hxx> #include <gp_Mat.hxx> #include <gp_Vec.hxx> //! Represents operation of rotation in 3d space as quaternion //! and implements operations with rotations basing on //! quaternion mathematics. //! //! In addition, provides methods for conversion to and from other //! representations of rotation (3*3 matrix, vector and //! angle, Euler angles) class gp_Quaternion { public: DEFINE_STANDARD_ALLOC //! Creates an identity quaternion gp_Quaternion() : x (0.0), y (0.0), z (0.0), w (1.0) {} //! Creates quaternion directly from component values gp_Quaternion (const Standard_Real theX, const Standard_Real theY, const Standard_Real theZ, const Standard_Real theW) : x (theX), y (theY), z (theZ), w (theW) {} //! Creates quaternion representing shortest-arc rotation //! operator producing vector theVecTo from vector theVecFrom. gp_Quaternion (const gp_Vec& theVecFrom, const gp_Vec& theVecTo) { SetRotation (theVecFrom, theVecTo); } //! Creates quaternion representing shortest-arc rotation //! operator producing vector theVecTo from vector theVecFrom. //! Additional vector theHelpCrossVec defines preferred direction for //! rotation and is used when theVecTo and theVecFrom are directed //! oppositely. gp_Quaternion(const gp_Vec& theVecFrom, const gp_Vec& theVecTo, const gp_Vec& theHelpCrossVec) { SetRotation (theVecFrom, theVecTo, theHelpCrossVec); } //! Creates quaternion representing rotation on angle //! theAngle around vector theAxis gp_Quaternion(const gp_Vec& theAxis, const Standard_Real theAngle) { SetVectorAndAngle (theAxis, theAngle); } //! Creates quaternion from rotation matrix 3*3 //! (which should be orthonormal skew-symmetric matrix) gp_Quaternion(const gp_Mat& theMat) { SetMatrix (theMat); } //! Simple equal test without precision Standard_EXPORT Standard_Boolean IsEqual (const gp_Quaternion& theOther) const; //! Sets quaternion to shortest-arc rotation producing //! vector theVecTo from vector theVecFrom. //! If vectors theVecFrom and theVecTo are opposite then rotation //! axis is computed as theVecFrom ^ (1,0,0) or theVecFrom ^ (0,0,1). Standard_EXPORT void SetRotation (const gp_Vec& theVecFrom, const gp_Vec& theVecTo); //! Sets quaternion to shortest-arc rotation producing //! vector theVecTo from vector theVecFrom. //! If vectors theVecFrom and theVecTo are opposite then rotation //! axis is computed as theVecFrom ^ theHelpCrossVec. Standard_EXPORT void SetRotation (const gp_Vec& theVecFrom, const gp_Vec& theVecTo, const gp_Vec& theHelpCrossVec); //! Create a unit quaternion from Axis+Angle representation Standard_EXPORT void SetVectorAndAngle (const gp_Vec& theAxis, const Standard_Real theAngle); //! Convert a quaternion to Axis+Angle representation, //! preserve the axis direction and angle from -PI to +PI Standard_EXPORT void GetVectorAndAngle (gp_Vec& theAxis, Standard_Real& theAngle) const; //! Create a unit quaternion by rotation matrix //! matrix must contain only rotation (not scale or shear) //! //! For numerical stability we find first the greatest component of quaternion //! and than search others from this one Standard_EXPORT void SetMatrix (const gp_Mat& theMat); //! Returns rotation operation as 3*3 matrix Standard_EXPORT gp_Mat GetMatrix() const; //! Create a unit quaternion representing rotation defined //! by generalized Euler angles Standard_EXPORT void SetEulerAngles (const gp_EulerSequence theOrder, const Standard_Real theAlpha, const Standard_Real theBeta, const Standard_Real theGamma); //! Returns Euler angles describing current rotation Standard_EXPORT void GetEulerAngles (const gp_EulerSequence theOrder, Standard_Real& theAlpha, Standard_Real& theBeta, Standard_Real& theGamma) const; void Set (const Standard_Real theX, const Standard_Real theY, const Standard_Real theZ, const Standard_Real theW); void Set (const gp_Quaternion& theQuaternion); Standard_Real X() const { return x; } Standard_Real Y() const { return y; } Standard_Real Z() const { return z; } Standard_Real W() const { return w; } //! Make identity quaternion (zero-rotation) void SetIdent() { x = y = z = 0.0; w = 1.0; } //! Reverse direction of rotation (conjugate quaternion) void Reverse() { x = -x; y = -y; z = -z; } //! Return rotation with reversed direction (conjugated quaternion) Standard_NODISCARD gp_Quaternion Reversed() const { return gp_Quaternion (-x, -y, -z, w); } //! Inverts quaternion (both rotation direction and norm) void Invert() { Standard_Real anIn = 1.0 / SquareNorm(); Set (-x * anIn, -y * anIn, -z * anIn, w * anIn); } //! Return inversed quaternion q^-1 Standard_NODISCARD gp_Quaternion Inverted() const { Standard_Real anIn = 1.0 / SquareNorm(); return gp_Quaternion (-x * anIn, -y * anIn, -z * anIn, w * anIn); } //! Returns square norm of quaternion Standard_Real SquareNorm() const { return x * x + y * y + z * z + w * w; } //! Returns norm of quaternion Standard_Real Norm() const { return Sqrt (SquareNorm()); } //! Scale all components by quaternion by theScale; note that //! rotation is not changed by this operation (except 0-scaling) void Scale (const Standard_Real theScale); void operator *= (const Standard_Real theScale) { Scale (theScale); } //! Returns scaled quaternion Standard_NODISCARD gp_Quaternion Scaled (const Standard_Real theScale) const { return gp_Quaternion (x * theScale, y * theScale, z * theScale, w * theScale); } Standard_NODISCARD gp_Quaternion operator * (const Standard_Real theScale) const { return Scaled (theScale); } //! Stabilize quaternion length within 1 - 1/4. //! This operation is a lot faster than normalization //! and preserve length goes to 0 or infinity Standard_EXPORT void StabilizeLength(); //! Scale quaternion that its norm goes to 1. //! The appearing of 0 magnitude or near is a error, //! so we can be sure that can divide by magnitude Standard_EXPORT void Normalize(); //! Returns quaternion scaled so that its norm goes to 1. Standard_NODISCARD gp_Quaternion Normalized() const { gp_Quaternion aNormilizedQ (*this); aNormilizedQ.Normalize(); return aNormilizedQ; } //! Returns quaternion with all components negated. //! Note that this operation does not affect neither //! rotation operator defined by quaternion nor its norm. Standard_NODISCARD gp_Quaternion Negated() const { return gp_Quaternion (-x, -y, -z, -w); } Standard_NODISCARD gp_Quaternion operator -() const { return Negated(); } //! Makes sum of quaternion components; result is "rotations mix" Standard_NODISCARD gp_Quaternion Added (const gp_Quaternion& theOther) const { return gp_Quaternion (x + theOther.x, y + theOther.y, z + theOther.z, w + theOther.w); } Standard_NODISCARD gp_Quaternion operator + (const gp_Quaternion& theOther) const { return Added (theOther); } //! Makes difference of quaternion components; result is "rotations mix" Standard_NODISCARD gp_Quaternion Subtracted (const gp_Quaternion& theOther) const { return gp_Quaternion (x - theOther.x, y - theOther.y, z - theOther.z, w - theOther.w); } Standard_NODISCARD gp_Quaternion operator - (const gp_Quaternion& theOther) const { return Subtracted (theOther); } //! Multiply function - work the same as Matrices multiplying. //! @code //! qq' = (cross(v,v') + wv' + w'v, ww' - dot(v,v')) //! @endcode //! Result is rotation combination: q' than q (here q=this, q'=theQ). //! Notices that: //! @code //! qq' != q'q; //! qq^-1 = q; //! @endcode Standard_NODISCARD gp_Quaternion Multiplied (const gp_Quaternion& theOther) const; Standard_NODISCARD gp_Quaternion operator * (const gp_Quaternion& theOther) const { return Multiplied (theOther); } //! Adds components of other quaternion; result is "rotations mix" void Add (const gp_Quaternion& theOther); void operator += (const gp_Quaternion& theOther) { Add (theOther); } //! Subtracts components of other quaternion; result is "rotations mix" void Subtract (const gp_Quaternion& theOther); void operator -= (const gp_Quaternion& theOther) { Subtract (theOther); } //! Adds rotation by multiplication void Multiply (const gp_Quaternion& theOther) { (*this) = Multiplied (theOther); // have no optimization here } void operator *= (const gp_Quaternion& theOther) { Multiply (theOther); } //! Computes inner product / scalar product / Dot Standard_Real Dot (const gp_Quaternion& theOther) const { return x * theOther.x + y * theOther.y + z * theOther.z + w * theOther.w; } //! Return rotation angle from -PI to PI Standard_EXPORT Standard_Real GetRotationAngle() const; //! Rotates vector by quaternion as rotation operator Standard_EXPORT gp_Vec Multiply (const gp_Vec& theVec) const; gp_Vec operator * (const gp_Vec& theVec) const { return Multiply (theVec); } private: Standard_Real x; Standard_Real y; Standard_Real z; Standard_Real w; }; //======================================================================= //function : Set //purpose : //======================================================================= inline void gp_Quaternion::Set (Standard_Real theX, Standard_Real theY, Standard_Real theZ, Standard_Real theW) { this->x = theX; this->y = theY; this->z = theZ; this->w = theW; } //======================================================================= //function : Set //purpose : //======================================================================= inline void gp_Quaternion::Set (const gp_Quaternion& theQuaternion) { x = theQuaternion.x; y = theQuaternion.y; z = theQuaternion.z; w = theQuaternion.w; } //======================================================================= //function : Scale //purpose : //======================================================================= inline void gp_Quaternion::Scale (const Standard_Real theScale) { x *= theScale; y *= theScale; z *= theScale; w *= theScale; } //======================================================================= //function : Multiplied //purpose : //======================================================================= inline gp_Quaternion gp_Quaternion::Multiplied (const gp_Quaternion& theQ) const { return gp_Quaternion (w * theQ.x + x * theQ.w + y * theQ.z - z * theQ.y, w * theQ.y + y * theQ.w + z * theQ.x - x * theQ.z, w * theQ.z + z * theQ.w + x * theQ.y - y * theQ.x, w * theQ.w - x * theQ.x - y * theQ.y - z * theQ.z); // 16 multiplications 12 addidtions 0 variables } //======================================================================= //function : Add //purpose : //======================================================================= inline void gp_Quaternion::Add (const gp_Quaternion& theQ) { x += theQ.x; y += theQ.y; z += theQ.z; w += theQ.w; } //======================================================================= //function : Subtract //purpose : //======================================================================= inline void gp_Quaternion::Subtract (const gp_Quaternion& theQ) { x -= theQ.x; y -= theQ.y; z -= theQ.z; w -= theQ.w; } #endif // _gp_Quaternion_HeaderFile
34.25
161
0.65588
[ "vector", "3d" ]
2b5ee093557cb79e29222fd0960870a38ec9d56b
8,849
hpp
C++
src/csv.hpp
MattKang/std-csv
30af46538a156c723f1a4b9f905a7114c3024ffd
[ "MIT" ]
2
2019-05-14T04:04:42.000Z
2019-12-15T20:47:32.000Z
src/csv.hpp
MattKang/std-csv
30af46538a156c723f1a4b9f905a7114c3024ffd
[ "MIT" ]
null
null
null
src/csv.hpp
MattKang/std-csv
30af46538a156c723f1a4b9f905a7114c3024ffd
[ "MIT" ]
null
null
null
// // Created by Matthew Kang on 2019-04-25. // #ifndef CSV_HPP #define CSV_HPP #include <array> #include <fstream> #include <regex> #include <sstream> #include <tuple> #include <vector> namespace csv { using ignore = std::tuple<>; /// @brief Defines std::tuple<FilteredTs...> template<typename... Ts> using FilteredTuple = decltype(std::tuple_cat( std::declval<std::conditional_t<std::is_same<ignore, Ts>::value, std::tuple<>, std::tuple<Ts>>>()...)); namespace detail { /// @defgroup Helper types /// @{ template<typename> struct IndexSequence; template<typename ...IntegralConstants> struct IndexSequence<std::tuple<IntegralConstants...>> { using type = std::index_sequence<IntegralConstants::value...>; }; template<typename UnwantedT, typename Sequence, typename ...Ts> struct FilteredIndexSequenceImpl; template<typename UnwantedT, size_t... indices, typename... Ts> struct FilteredIndexSequenceImpl<UnwantedT, std::index_sequence<indices...>, Ts...> { using FilteredIntegralConstantTuple = decltype(std::tuple_cat( std::declval<std::conditional_t<std::is_same<UnwantedT, Ts>::value, std::tuple<>, std::tuple<std::integral_constant<size_t, indices>> > >()...)); using type = typename IndexSequence<FilteredIntegralConstantTuple>::type; }; template<typename UnwantedT, typename ...Ts> using FilteredIndexSequence = typename FilteredIndexSequenceImpl<UnwantedT, std::index_sequence_for<Ts...>, Ts...>::type; template<typename T> struct IsArray : std::false_type { }; template<typename T, size_t N> struct IsArray<std::array<T, N>> : std::true_type { }; template<typename T> struct IsTuple : std::false_type { }; template<typename... Ts> struct IsTuple<std::tuple<Ts...>> : std::true_type { }; template<typename T> struct FilteredTypes { using type = T; }; template<typename... Ts> struct FilteredTypes<std::tuple<Ts...>> { using type = FilteredTuple<Ts...>; }; /// @} template<typename CharT> char get_delimiter(std::basic_istream<CharT>& file) { std::string line; const auto position = file.tellg(); std::getline(file, line); file.seekg(position); // rewind our line get char delimiter = ' '; // space-separated if (std::regex_search(line.cbegin(), line.cend(), std::regex(","))) // comma-separated { delimiter = ','; } else if (std::regex_search(line.cbegin(), line.cend(), std::regex(";"))) // semicolon-separated { delimiter = ';'; } else if (std::regex_search(line.cbegin(), line.cend(), std::regex("\\t"))) // tab-separated { delimiter = '\t'; } return delimiter; } template<typename... Ts, size_t... indices> auto filter_tuple_by_sequence(std::tuple<Ts...> tup, std::index_sequence<indices...>) { return std::make_tuple(std::move(std::get<indices>(tup))...); } template<typename UnwantedT, typename... Ts> auto filter_tuple_by_type(std::tuple<Ts...> tup) { return filter_tuple_by_sequence(std::move(tup), FilteredIndexSequence<UnwantedT, Ts...>{}); } template<typename T, typename CharT> T parse_row(std::basic_istream<CharT>& row, char delimiter) { if constexpr (std::is_same_v<T, ignore>) { row.ignore(std::numeric_limits<std::streamsize>::max(), delimiter); return {}; } else if constexpr (std::is_same_v<T, std::string>) { std::string value; std::getline(row, value, delimiter); if (row.eof() && value.back() == '\r') { value.pop_back(); } return value; } else if constexpr (std::is_same_v<T, bool>) { std::string valueAsString; std::getline(row, valueAsString, delimiter); const auto first = valueAsString[valueAsString.find_first_of("tTfF01")]; return (!valueAsString.empty() && (first == 't' || first == 'T' || first == '1')); } else { T value = std::numeric_limits<T>::quiet_NaN(); std::string valueAsString; std::getline(row, valueAsString, delimiter); std::istringstream(valueAsString) >> value; return value; } } template<typename ...Ts, typename CharT> FilteredTuple<Ts...> parse_row(std::basic_istream<CharT>& row, char delimiter, std::tuple<Ts...>) { auto unfilteredTuple = std::tuple<Ts...>{detail::parse_row<Ts>(row, delimiter)...}; return filter_tuple_by_type<ignore>(std::move(unfilteredTuple)); } template<typename RowT, typename CharT> auto parse_csv(std::basic_istream<CharT>& file, char delimiter) { using RowOutT = std::conditional_t<IsTuple<RowT>::value, typename FilteredTypes<RowT>::type, RowT>; std::vector<RowOutT> data; std::string line; while (std::getline(file, line)) { std::istringstream stream(line); RowOutT values; if constexpr (IsArray<RowOutT>::value) { for (auto& v : values) { v = detail::parse_row<typename RowOutT::value_type>(stream, delimiter); } } else if constexpr (IsTuple<RowOutT>::value) { values = detail::parse_row(stream, delimiter, RowT{}); } else { while (!stream.eof()) { values.push_back(detail::parse_row<typename RowOutT::value_type>(stream, delimiter)); } } data.push_back(std::move(values)); } return data; } template<typename ContainerT> ContainerT get_header(std::ifstream& file, char delimiter) { std::string line; std::getline(file, line); std::istringstream stream(line); return detail::parse_csv<ContainerT>(stream, delimiter).front(); } template<typename ContainerT, typename HeaderT = ignore> auto to_containers(std::string_view& path, char delimiter, HeaderT&& header = {}) { // Open file auto file = std::ifstream(path.data()); if (file) { // Check delimiter if (delimiter == '\0') { delimiter = detail::get_delimiter(file); } // Read header if constexpr (!std::is_same_v<HeaderT, ignore>) { header = detail::get_header<std::decay_t<HeaderT>>(file, delimiter); } // Read CSV return detail::parse_csv<ContainerT>(file, delimiter); } return decltype(detail::parse_csv<ContainerT>(file, delimiter)){}; } } // namespace detail std::vector<std::string> get_header(std::string_view path, char delimiter = '\0') { // Open file if (auto file = std::ifstream(path.data())) { // Check delimiter if (delimiter == '\0') { delimiter = detail::get_delimiter(file); } // Read header return detail::get_header<std::vector<std::string>>(file, delimiter); } return {}; } template<typename ValueT, size_t nColumns> std::vector<std::array<ValueT, nColumns>> to_arrays(std::string_view path, char delimiter = '\0') { return detail::to_containers<std::array<ValueT, nColumns>>(path, delimiter); } template<typename ValueT, size_t nColumns> std::vector<std::array<ValueT, nColumns>> to_arrays(std::string_view path, std::array<std::string, nColumns>& header, char delimiter = '\0') { return detail::to_containers<std::array<ValueT, nColumns>>(path, delimiter, header); } template<typename... ColumnTs> std::vector<FilteredTuple<ColumnTs...>> to_tuples(std::string_view path, char delimiter = '\0') { return detail::to_containers<std::tuple<ColumnTs...>>(path, delimiter); } template<typename... ColumnTs, size_t nColumns = std::tuple_size_v<FilteredTuple<ColumnTs...>>> std::vector<FilteredTuple<ColumnTs...>> to_tuples(std::string_view path, std::array<std::string, nColumns>& header, char delimiter = '\0') { return detail::to_containers<std::tuple<ColumnTs...>>(path, delimiter, header); } template<typename ValueT> std::vector<std::vector<ValueT>> to_vectors(std::string_view path, char delimiter = '\0') { return detail::to_containers<std::vector<ValueT>>(path, delimiter); } template<typename ValueT> std::vector<std::vector<ValueT>> to_vectors(std::string_view path, std::vector<std::string>& header, char delimiter = '\0') { return detail::to_containers<std::vector<ValueT>>(path, delimiter, header); } } // namespace csv #endif //CSV_HPP
31.049123
111
0.606057
[ "vector" ]
2b60986549d643165038ea46a66c13804851f23e
2,664
hpp
C++
include/mandoline/vertex.hpp
mtao/mandoline
79438c5b210a2ca4b9f72cbfd2879a9ae6a665da
[ "MIT" ]
54
2019-11-12T11:07:03.000Z
2022-03-23T11:09:19.000Z
include/mandoline/vertex.hpp
mtao/mandoline
79438c5b210a2ca4b9f72cbfd2879a9ae6a665da
[ "MIT" ]
2
2019-12-17T01:49:44.000Z
2020-03-29T19:46:36.000Z
include/mandoline/vertex.hpp
mtao/mandoline
79438c5b210a2ca4b9f72cbfd2879a9ae6a665da
[ "MIT" ]
8
2019-11-29T02:30:49.000Z
2022-02-19T06:15:22.000Z
#pragma once #include <set> #include <mtao/types.hpp> #include <variant> #include "mandoline/coord_mask.hpp" #define __STATIC_TEST__ namespace mandoline { #if defined(_MSC_VER) || defined(__APPLE__) || defined(__STATIC_TEST__) extern const double threshold_epsilon; #else //TODO: sqrt isn't constepxr on mac constexpr static double threshold_epsilon = std::sqrt(std::numeric_limits<double>::epsilon()); #endif //Base vertex class, holds points in grid space. //Vertex is at p() = coord+quot and clamped_indices stores what type of grid entry the vertex belongs to template<int D> struct Vertex { //Definitions using Vec = mtao::Vector<double, D>; using coord_type = std::array<int, D>; using MaskType = coord_mask<D>; using OptInd = std::array<std::optional<int>, D>; //Members coord_type coord = {}; Vec quot = Vec::Zero(); std::bitset<D> clamped_indices = {}; //Constructors Vertex() = default; Vertex(const coord_type &); template<typename Derived> Vertex(const coord_type &c, const Eigen::MatrixBase<Derived> &q); template<typename Derived> Vertex(const coord_type &c, const Eigen::MatrixBase<Derived> &q, const std::bitset<D> &bs); Vertex(const Vertex &) = default; Vertex(Vertex &&) = default; Vertex &operator=(const Vertex &) = default; Vertex &operator=(Vertex &&) = default; //Construction helpers template<typename Derived> static std::bitset<D> bs_from_quot(const Eigen::MatrixBase<Derived> &q); template<typename Derived> static Vertex from_vertex(const Eigen::MatrixBase<Derived> &p); //Comparison bool operator==(const Vertex &o) const; bool operator!=(const Vertex &o) const; bool operator<(const Vertex &o) const; bool approx(const Vertex &o) const; //Transformations Vec p() const; OptInd optional_index() const; MaskType mask() const; operator std::string() const; //Bitmask convenience functions bool clamped(int index) const; size_t clamped_count() const; bool is_grid_vertex() const; bool is_in_cell(const coord_type &c) const;//closed cell concept std::set<coord_type> possible_cells() const; //std::set<coord_type> possible_faces() const; //Thresholding void repair(); void apply_thresholding(); void apply_thresholding(double thresh); //Vector field operations Vertex operator+(const Vertex &o) const; Vertex operator-(const Vertex &o) const; Vertex operator*(double val) const; Vertex lerp(const Vertex &other, double t) const; EIGEN_MAKE_ALIGNED_OPERATOR_NEW; }; }// namespace mandoline #include "vertex_impl.hpp"
30.272727
104
0.696697
[ "vector" ]
2b6bd22c790b159ab965f27003f3117ddfb02258
219
hxx
C++
include/ChebyshevWindow.hxx
kb1vc/SoDaSignals
f7ae9be3e8865e24e9b61643f099b59f5a5efd1a
[ "BSD-2-Clause" ]
null
null
null
include/ChebyshevWindow.hxx
kb1vc/SoDaSignals
f7ae9be3e8865e24e9b61643f099b59f5a5efd1a
[ "BSD-2-Clause" ]
null
null
null
include/ChebyshevWindow.hxx
kb1vc/SoDaSignals
f7ae9be3e8865e24e9b61643f099b59f5a5efd1a
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include <vector> #include <cstddef> namespace SoDa { void ChebyshevWindow(std::vector<float> & win, size_t N, float atten); void ChebyshevWindow(std::vector<double> & win, size_t N, float atten); }
27.375
76
0.716895
[ "vector" ]
2b6bdb5829318d8483428450090f3340346b5767
5,507
cpp
C++
Engine/ModuleInput.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
2
2019-11-22T23:34:36.000Z
2019-11-27T10:27:35.000Z
Engine/ModuleInput.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
null
null
null
Engine/ModuleInput.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleInput.h" #include "ModuleEditor.h" #include "W_Config.h" #include "W_Rendering.h" #include "Event.h" #include "ImGui/Impl/imgui_impl_sdl.h" #include "ImGui/imgui_internal.h" // TODO: DELETE FROM HERE #include "C_Material.h" #include "Component.h" #include "R_Material.h" // TODO: maybe temporal untill we get to fully work module filesystem // the most recommended approach to deal with paths/extensions/filenames in windows // before boost lib //#include <filesystem> // for search filename extension / file name | needed c++17 #define MAX_KEYS 300 ModuleInput::ModuleInput(bool start_enabled) : Module(start_enabled) { name.assign("Input"); keyboard = new KEY_STATE[MAX_KEYS]; memset(keyboard, KEY_IDLE, sizeof(KEY_STATE) * MAX_KEYS); memset(mouse_buttons, KEY_IDLE, sizeof(KEY_STATE) * MAX_MOUSE_BUTTONS); } // Destructor ModuleInput::~ModuleInput() { delete[] keyboard; } // Called before render is available bool ModuleInput::Init(Config& config) { LOG("[Init] SDL input event system"); bool ret = true; SDL_Init(0); if(SDL_InitSubSystem(SDL_INIT_EVENTS) < 0) { LOG("SDL_EVENTS could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } // SDL Enables ----------------------------- SDL_EventState(SDL_DROPFILE, SDL_ENABLE); return ret; } bool ModuleInput::CleanUp() { LOG("Quitting SDL input event subsystem"); SDL_QuitSubSystem(SDL_INIT_EVENTS); return true; } // Called every draw update update_status ModuleInput::PreUpdate() { SDL_PumpEvents(); const Uint8* keys = SDL_GetKeyboardState(NULL); for (int i = 0; i < MAX_KEYS; ++i) { if (keys[i] == 1) { // TODO: maybe we dont need to update every key repeat the input log if (keyboard[i] == KEY_IDLE) { keyboard[i] = KEY_DOWN; App->editor->w_config->AddInputLog(i, KEY_DOWN, 0); } else { keyboard[i] = KEY_REPEAT; } } else { if (keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN) { keyboard[i] = KEY_UP; App->editor->w_config->AddInputLog(i, KEY_UP, 0); } else { keyboard[i] = KEY_IDLE; } } } Uint32 buttons = SDL_GetMouseState(&mouse_x, &mouse_y); mouse_x /= SCREEN_SIZE; mouse_y /= SCREEN_SIZE; mouse_z = 0; for(int i = 0; i < MAX_MOUSE_BUTTONS; ++i) { if(buttons & SDL_BUTTON(i)) { if (mouse_buttons[i] == KEY_IDLE) { mouse_buttons[i] = KEY_DOWN; App->editor->w_config->AddInputLog(i, KEY_DOWN, 1 ); } else { mouse_buttons[i] = KEY_REPEAT; } } else { if (mouse_buttons[i] == KEY_REPEAT || mouse_buttons[i] == KEY_DOWN) { mouse_buttons[i] = KEY_UP; App->editor->w_config->AddInputLog(i, KEY_UP, 1); } else { mouse_buttons[i] = KEY_IDLE; } } } mouse_x_motion = mouse_y_motion = 0; bool quit = false; SDL_Event event; //char* dropped_filedir = nullptr; //SDL_DisplayMode DM; //SDL_GetCurrentDisplayMode(0, &DM); //auto width = DM.w; //auto height = DM.h; //int offset = 12; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); switch (event.type) { case SDL_MOUSEWHEEL: mouse_z = event.wheel.y; break; case SDL_MOUSEMOTION: mouse_x = event.motion.x / SCREEN_SIZE; mouse_y = event.motion.y / SCREEN_SIZE; mouse_x_motion = (event.motion.xrel / SCREEN_SIZE) ; mouse_y_motion = (event.motion.yrel / SCREEN_SIZE); break; case SDL_DROPFILE: { Event e(Event::file_dropped); e.string.ptr = event.drop.file; App->BroadcastEvent(e); SDL_free(event.drop.file); break; } case SDL_QUIT: quit = true; break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) { App->window->window_focused = true; } else if (event.window.event == SDL_WINDOWEVENT_TAKE_FOCUS) { App->window->window_focused = true; } else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) { App->window->window_focused = false; } if (event.window.event == SDL_WINDOWEVENT_MAXIMIZED) App->window->maximized = true; if (event.window.event == SDL_WINDOWEVENT_RESTORED) App->window->maximized = false; if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { App->window->current_w = event.window.data1; App->window->current_h= event.window.data2; } } } if(quit == true || keyboard[SDL_SCANCODE_ESCAPE] == KEY_UP) return UPDATE_STOP; return UPDATE_CONTINUE; } bool ModuleInput::Save(Config& config) { return true; } void ModuleInput::Load(Config& config) { } //if (mouse_x > width - offset) //{ // int last_x = mouse_x; // App->input->SetMouseX(offset); // mouse_offset_x = mouse_x - last_x; // ImGui::GetIO().MousePos.x = mouse_x; //} //else if (mouse_x < offset) //{ // int last_x = mouse_x; // App->input->SetMouseX(width - offset); // mouse_offset_x = mouse_x - last_x; // ImGui::GetIO().MousePos.x = mouse_x; //} //if (mouse_y > height - offset) //{ // int last_y = mouse_y; // App->input->SetMouseY(offset); // mouse_offset_y = mouse_y - last_y; // ImGui::GetIO().MousePos.y = mouse_y; //} //else if (mouse_y < offset) //{ // int last_y = mouse_y; // App->input->SetMouseY(height - offset); // mouse_offset_y = mouse_y - last_y; // ImGui::GetIO().MousePos.y = mouse_y; //} //ImGui::ResetMouseDragDelta(0); //ImGui::ResetMouseDragDelta(1); //ImGui::ResetMouseDragDelta(2); //ImGui::GetCurrentContext()->ActiveIdIsJustActivated = true; //LOG("mouse x: %i mouse y: %i", mouse_x, mouse_y);
20.859848
83
0.666243
[ "render" ]
2b7913e23292e9240f7cbac6a7b37c35a5c763a4
5,424
hh
C++
src/t123/internal/MORE_GTEST_MACROS.hh
wawiesel/Testing123
54ee29511736bf35a5340c73f1fdf49615fb82d8
[ "MIT" ]
2
2017-02-01T00:39:00.000Z
2017-03-20T02:56:19.000Z
src/t123/internal/MORE_GTEST_MACROS.hh
wawiesel/Testing123
54ee29511736bf35a5340c73f1fdf49615fb82d8
[ "MIT" ]
6
2017-07-15T01:26:56.000Z
2017-08-22T03:38:30.000Z
src/t123/internal/MORE_GTEST_MACROS.hh
wawiesel/Testing123
54ee29511736bf35a5340c73f1fdf49615fb82d8
[ "MIT" ]
null
null
null
#include <cmath> /*std::abs*/ #include <algorithm> /*std::min*/ //----------------------------------------------------------------------------- template <typename T1, typename T2> inline T1 MIN_SIZE_INTEGER( T1 n1, T2 n2 ) { return std::min(n1,static_cast<T1>(n2)); } //----------------------------------------------------------------------------- template <typename T1, typename T2> inline ::testing::AssertionResult FUNCTION_COMPARE_VEC_EQ(const std::string& ref_name, const T1& ref, const std::string& test_name, const T2& test) { std::stringstream msg; bool pass = true; //test sizes first if( ref.size() != test.size() ) { pass=false; msg << "vector sizes not equal:\n"<< " reference vector, "<<ref_name<<".size()="<<ref.size()<<"\n"<< " test vector, "<<test_name<<".size()="<<test.size()<<"\n"; } //test any elements we can for( size_t i=0; i<MIN_SIZE_INTEGER(ref.size(),test.size()); ++i) { //use equality operator == instead of != to catch more custom comparison //operators that may not have != implemented if( !( ref[i] == test[i] ) ) { pass=false; msg<<"vector element "<<i<<" not equal:\n"<< " reference, "<<ref_name<<"["<<i<<"]="<<ref[i]<<"\n"<< " test, "<<test_name<<"["<<i<<"]="<<test[i]<<"\n"; } } if( pass )return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "\n"<<msg.str(); } #define COMPARE_VEC_EQ(a,b) FUNCTION_COMPARE_VEC_EQ(#a,a,#b,b) #define EXPECTORASSERT_VEC_EQ(name,a,b) name##_TRUE( COMPARE_VEC_EQ(a,b) ) #define EXPECT_VEC_EQ(a,b) EXPECTORASSERT_VEC_EQ(EXPECT,a,b) #define ASSERT_VEC_EQ(a,b) EXPECTORASSERT_VEC_EQ(ASSERT,a,b) //----------------------------------------------------------------------------- template <typename T, typename U> inline ::testing::AssertionResult FUNCTION_COMPARE_VEC_NEAR(const std::string& ref_name, const T& ref, const std::string& test_name, const T& test, const std::string& tol_name, const U& tol) { std::stringstream msg; bool pass = true; //test sizes first if( ref.size() != test.size() ) { pass=false; msg << " vector sizes not equal:\n"<< " reference vector, "<<ref_name<<".size()="<<ref.size()<<"\n"<< " test vector, "<<test_name<<".size()="<<test.size()<<"\n"; } //test any elements we can for( size_t i=0; i<MIN_SIZE_INTEGER(ref.size(),test.size()); ++i) { //absolute tolerance if( std::abs(ref[i]-test[i]) > std::abs(tol) ) { pass=false; msg<<" vector element "<<i<<" not near:\n"<< " reference, "<<ref_name<<"["<<i<<"]="<<ref[i]<<"\n"<< " test, "<<test_name<<"["<<i<<"]="<<test[i]<<"\n"; } } if( pass )return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "\n"<< " with absolute tolerance, "<<tol_name<<" -> "<<tol<<"\n" << msg.str(); } #define COMPARE_VEC_NEAR(a,b,tol) FUNCTION_COMPARE_VEC_NEAR(#a,a,#b,b,#tol,tol) #define EXPECTORASSERT_VEC_NEAR(name,a,b,tol) name##_TRUE( COMPARE_VEC_NEAR(a,b,tol) ) #define EXPECT_VEC_NEAR(a,b,tol) EXPECTORASSERT_VEC_NEAR(EXPECT,a,b,tol) #define ASSERT_VEC_NEAR(a,b,tol) EXPECTORASSERT_VEC_NEAR(ASSERT,a,b,tol) //----------------------------------------------------------------------------- template <typename T, typename U> inline ::testing::AssertionResult FUNCTION_COMPARE_VEC_APPROX(const std::string& ref_name, const T& ref, const std::string& test_name, const T& test, const std::string& tol_name, const U& tol) { std::stringstream msg; bool pass = true; //test sizes first if( ref.size() != test.size() ) { pass=false; msg << " vector sizes not equal:\n"<< " reference vector, "<<ref_name<<".size()="<<ref.size()<<"\n"<< " test vector, "<<test_name<<".size()="<<test.size()<<"\n"; } //test any elements we can for( size_t i=0; i<MIN_SIZE_INTEGER(ref.size(),test.size()); ++i) { //relative tolerance if( std::abs(ref[i]-test[i]) > std::abs(tol*ref[i]) ) { pass=false; msg<<" vector element "<<i<<" not approximately equal:\n"<< " reference, "<<ref_name<<"["<<i<<"]="<<ref[i]<<"\n"<< " test, "<<test_name<<"["<<i<<"]="<<test[i]<<"\n"; } } if( pass )return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "\n"<< " with relative tolerance, "<<tol_name<<" -> "<<tol<<"\n" << msg.str(); } #define COMPARE_VEC_APPROX(a,b,tol) FUNCTION_COMPARE_VEC_APPROX(#a,a,#b,b,#tol,tol) #define EXPECTORASSERT_VEC_APPROX(name,a,b,tol) name##_TRUE( COMPARE_VEC_APPROX(a,b,tol) ) #define EXPECT_VEC_APPROX(a,b,tol) EXPECTORASSERT_VEC_APPROX(EXPECT,a,b,tol) #define ASSERT_VEC_APPROX(a,b,tol) EXPECTORASSERT_VEC_APPROX(ASSERT,a,b,tol) //----------------------------------------------------------------------------- #define EXPECTORASSERT_APPROX(name,a,b,tol) name##_NEAR(a,b,std::abs(tol*a)) #define EXPECT_APPROX(a,b,tol) EXPECTORASSERT_APPROX(EXPECT,a,b,tol) #define ASSERT_APPROX(a,b,tol) EXPECTORASSERT_APPROX(ASSERT,a,b,tol) //-----------------------------------------------------------------------------
38.197183
187
0.535214
[ "vector" ]
2b7e0f653922f62758c22181a2a4e297f0983041
1,252
hpp
C++
include/est/sparse.hpp
naruto2/CodeFEM
eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90
[ "MIT" ]
1
2020-09-27T07:28:04.000Z
2020-09-27T07:28:04.000Z
include/est/sparse.hpp
naruto2/CodeFEM
eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90
[ "MIT" ]
null
null
null
include/est/sparse.hpp
naruto2/CodeFEM
eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90
[ "MIT" ]
null
null
null
#ifndef _EST_SPARSE_HPP_ #define _EST_SPARSE_HPP_ #include <iostream> #include <vector> #include <map> #include <cstdio> #include <unistd.h> using namespace std; namespace sparse { template<typename T> class matrix : public vector< map<long, T> > { public: matrix(){} matrix(long n) : vector< map<long, T> >(n){}; }; template<typename T> void printmatrix(matrix<T>&A) { long i, j, n; n = A.size(); for(i=1;i<n;i++){ for(j=1;j<n;j++) cout<<A[i][j]<<" "; cout << endl; } }; template<typename T> void plotmatrix(matrix<T>&A) { FILE *pp; long i, j, n=A.size(); pp = fopen("xgraph.dat","w"); //fprintf(pp,"unset border\n"); //fprintf(pp,"unset xtics\n"); //fprintf(pp,"set xrange [0:%d]\n",n); //fprintf(pp,"set yrange [%d:0]\n",n); //fprintf(pp,"set size square\n"); for(i=1;i<n;i++){ for( auto it : A[i]){ j = it.first; if ( A[i][j] != 0 ) fprintf(pp,"%d %d\n",j,-i); //fprintf(pp,"set label \"%.4f\" at %d, %d;\n",A[i][j],j,i); } } //fprintf(pp,"plot '-' with lines title \"\"\n"); //fprintf(pp,"1 1\n"); //fprintf(pp,"%d %d\n",n-1,n-1); //fprintf(pp,"e\n\n"); fflush(pp); fclose(pp); }; } #endif
19.873016
63
0.525559
[ "vector" ]
2b83c307452294ccf2b38e7a38bdb3b9adb5e474
60,141
cpp
C++
platforms/build_android_x86/modules/java/photo.cpp
swinstonMirada/opencv
6bf40d535215b118fcd41d50eacfa41349bb86d2
[ "BSD-3-Clause" ]
null
null
null
platforms/build_android_x86/modules/java/photo.cpp
swinstonMirada/opencv
6bf40d535215b118fcd41d50eacfa41349bb86d2
[ "BSD-3-Clause" ]
null
null
null
platforms/build_android_x86/modules/java/photo.cpp
swinstonMirada/opencv
6bf40d535215b118fcd41d50eacfa41349bb86d2
[ "BSD-3-Clause" ]
null
null
null
// // This file is auto-generated, please don't edit! // #define LOG_TAG "org.opencv.photo" #include "common.h" #include "opencv2/opencv_modules.hpp" #ifdef HAVE_OPENCV_PHOTO #include <string> #include "opencv2/photo.hpp" using namespace cv; /// throw java exception static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method) { std::string what = "unknown exception"; jclass je = 0; if(e) { std::string exception_type = "std::exception"; if(dynamic_cast<const cv::Exception*>(e)) { exception_type = "cv::Exception"; je = env->FindClass("org/opencv/core/CvException"); } what = exception_type + ": " + e->what(); } if(!je) je = env->FindClass("java/lang/Exception"); env->ThrowNew(je, what.c_str()); LOGE("%s caught %s", method, what.c_str()); (void)method; // avoid "unused" warning } extern "C" { // // void CalibrateRobertson::setMaxIter(int max_iter) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateRobertson_setMaxIter_10 (JNIEnv*, jclass, jlong, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateRobertson_setMaxIter_10 (JNIEnv* env, jclass , jlong self, jint max_iter) { static const char method_name[] = "photo::setMaxIter_10()"; try { LOGD("%s", method_name); CalibrateRobertson* me = (CalibrateRobertson*) self; //TODO: check for NULL me->setMaxIter( (int)max_iter ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void CalibrateRobertson::setThreshold(float threshold) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateRobertson_setThreshold_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateRobertson_setThreshold_10 (JNIEnv* env, jclass , jlong self, jfloat threshold) { static const char method_name[] = "photo::setThreshold_10()"; try { LOGD("%s", method_name); CalibrateRobertson* me = (CalibrateRobertson*) self; //TODO: check for NULL me->setThreshold( (float)threshold ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void CalibrateRobertson::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateRobertson_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateRobertson_delete (JNIEnv*, jclass, jlong self) { delete (CalibrateRobertson*) self; } // // void TonemapMantiuk::setSaturation(float saturation) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapMantiuk_setSaturation_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapMantiuk_setSaturation_10 (JNIEnv* env, jclass , jlong self, jfloat saturation) { static const char method_name[] = "photo::setSaturation_10()"; try { LOGD("%s", method_name); TonemapMantiuk* me = (TonemapMantiuk*) self; //TODO: check for NULL me->setSaturation( (float)saturation ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapMantiuk::setScale(float scale) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapMantiuk_setScale_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapMantiuk_setScale_10 (JNIEnv* env, jclass , jlong self, jfloat scale) { static const char method_name[] = "photo::setScale_10()"; try { LOGD("%s", method_name); TonemapMantiuk* me = (TonemapMantiuk*) self; //TODO: check for NULL me->setScale( (float)scale ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void TonemapMantiuk::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapMantiuk_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapMantiuk_delete (JNIEnv*, jclass, jlong self) { delete (TonemapMantiuk*) self; } // // void TonemapDurand::setContrast(float contrast) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setContrast_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setContrast_10 (JNIEnv* env, jclass , jlong self, jfloat contrast) { static const char method_name[] = "photo::setContrast_10()"; try { LOGD("%s", method_name); TonemapDurand* me = (TonemapDurand*) self; //TODO: check for NULL me->setContrast( (float)contrast ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapDurand::setSaturation(float saturation) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setSaturation_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setSaturation_10 (JNIEnv* env, jclass , jlong self, jfloat saturation) { static const char method_name[] = "photo::setSaturation_10()"; try { LOGD("%s", method_name); TonemapDurand* me = (TonemapDurand*) self; //TODO: check for NULL me->setSaturation( (float)saturation ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapDurand::setSigmaColor(float sigma_color) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setSigmaColor_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setSigmaColor_10 (JNIEnv* env, jclass , jlong self, jfloat sigma_color) { static const char method_name[] = "photo::setSigmaColor_10()"; try { LOGD("%s", method_name); TonemapDurand* me = (TonemapDurand*) self; //TODO: check for NULL me->setSigmaColor( (float)sigma_color ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapDurand::setSigmaSpace(float sigma_space) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setSigmaSpace_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_setSigmaSpace_10 (JNIEnv* env, jclass , jlong self, jfloat sigma_space) { static const char method_name[] = "photo::setSigmaSpace_10()"; try { LOGD("%s", method_name); TonemapDurand* me = (TonemapDurand*) self; //TODO: check for NULL me->setSigmaSpace( (float)sigma_space ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void TonemapDurand::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDurand_delete (JNIEnv*, jclass, jlong self) { delete (TonemapDurand*) self; } // // void CalibrateDebevec::setLambda(float lambda) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_setLambda_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_setLambda_10 (JNIEnv* env, jclass , jlong self, jfloat lambda) { static const char method_name[] = "photo::setLambda_10()"; try { LOGD("%s", method_name); CalibrateDebevec* me = (CalibrateDebevec*) self; //TODO: check for NULL me->setLambda( (float)lambda ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void CalibrateDebevec::setRandom(bool random) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_setRandom_10 (JNIEnv*, jclass, jlong, jboolean); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_setRandom_10 (JNIEnv* env, jclass , jlong self, jboolean random) { static const char method_name[] = "photo::setRandom_10()"; try { LOGD("%s", method_name); CalibrateDebevec* me = (CalibrateDebevec*) self; //TODO: check for NULL me->setRandom( (bool)random ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void CalibrateDebevec::setSamples(int samples) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_setSamples_10 (JNIEnv*, jclass, jlong, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_setSamples_10 (JNIEnv* env, jclass , jlong self, jint samples) { static const char method_name[] = "photo::setSamples_10()"; try { LOGD("%s", method_name); CalibrateDebevec* me = (CalibrateDebevec*) self; //TODO: check for NULL me->setSamples( (int)samples ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void CalibrateDebevec::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateDebevec_delete (JNIEnv*, jclass, jlong self) { delete (CalibrateDebevec*) self; } // // void TonemapReinhard::setColorAdaptation(float color_adapt) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_setColorAdaptation_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_setColorAdaptation_10 (JNIEnv* env, jclass , jlong self, jfloat color_adapt) { static const char method_name[] = "photo::setColorAdaptation_10()"; try { LOGD("%s", method_name); TonemapReinhard* me = (TonemapReinhard*) self; //TODO: check for NULL me->setColorAdaptation( (float)color_adapt ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapReinhard::setIntensity(float intensity) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_setIntensity_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_setIntensity_10 (JNIEnv* env, jclass , jlong self, jfloat intensity) { static const char method_name[] = "photo::setIntensity_10()"; try { LOGD("%s", method_name); TonemapReinhard* me = (TonemapReinhard*) self; //TODO: check for NULL me->setIntensity( (float)intensity ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapReinhard::setLightAdaptation(float light_adapt) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_setLightAdaptation_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_setLightAdaptation_10 (JNIEnv* env, jclass , jlong self, jfloat light_adapt) { static const char method_name[] = "photo::setLightAdaptation_10()"; try { LOGD("%s", method_name); TonemapReinhard* me = (TonemapReinhard*) self; //TODO: check for NULL me->setLightAdaptation( (float)light_adapt ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void TonemapReinhard::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapReinhard_delete (JNIEnv*, jclass, jlong self) { delete (TonemapReinhard*) self; } // // void colorChange(Mat src, Mat mask, Mat& dst, float red_mul = 1.0f, float green_mul = 1.0f, float blue_mul = 1.0f) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_colorChange_10 (JNIEnv*, jclass, jlong, jlong, jlong, jfloat, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_colorChange_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong mask_nativeObj, jlong dst_nativeObj, jfloat red_mul, jfloat green_mul, jfloat blue_mul) { static const char method_name[] = "photo::colorChange_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::colorChange( src, mask, dst, (float)red_mul, (float)green_mul, (float)blue_mul ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_colorChange_11 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_colorChange_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong mask_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::colorChange_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::colorChange( src, mask, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void decolor(Mat src, Mat& grayscale, Mat& color_boost) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_decolor_10 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_decolor_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong grayscale_nativeObj, jlong color_boost_nativeObj) { static const char method_name[] = "photo::decolor_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& grayscale = *((Mat*)grayscale_nativeObj); Mat& color_boost = *((Mat*)color_boost_nativeObj); cv::decolor( src, grayscale, color_boost ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void detailEnhance(Mat src, Mat& dst, float sigma_s = 10, float sigma_r = 0.15f) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_detailEnhance_10 (JNIEnv*, jclass, jlong, jlong, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_detailEnhance_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj, jfloat sigma_s, jfloat sigma_r) { static const char method_name[] = "photo::detailEnhance_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::detailEnhance( src, dst, (float)sigma_s, (float)sigma_r ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_detailEnhance_11 (JNIEnv*, jclass, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_detailEnhance_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::detailEnhance_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::detailEnhance( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void edgePreservingFilter(Mat src, Mat& dst, int flags = 1, float sigma_s = 60, float sigma_r = 0.4f) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_edgePreservingFilter_10 (JNIEnv*, jclass, jlong, jlong, jint, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_edgePreservingFilter_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj, jint flags, jfloat sigma_s, jfloat sigma_r) { static const char method_name[] = "photo::edgePreservingFilter_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::edgePreservingFilter( src, dst, (int)flags, (float)sigma_s, (float)sigma_r ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_edgePreservingFilter_11 (JNIEnv*, jclass, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_edgePreservingFilter_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::edgePreservingFilter_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::edgePreservingFilter( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void fastNlMeansDenoising(Mat src, Mat& dst, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoising_10 (JNIEnv*, jclass, jlong, jlong, jfloat, jint, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoising_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj, jfloat h, jint templateWindowSize, jint searchWindowSize) { static const char method_name[] = "photo::fastNlMeansDenoising_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoising( src, dst, (float)h, (int)templateWindowSize, (int)searchWindowSize ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoising_11 (JNIEnv*, jclass, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoising_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::fastNlMeansDenoising_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoising( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void fastNlMeansDenoisingColored(Mat src, Mat& dst, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColored_10 (JNIEnv*, jclass, jlong, jlong, jfloat, jfloat, jint, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColored_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj, jfloat h, jfloat hColor, jint templateWindowSize, jint searchWindowSize) { static const char method_name[] = "photo::fastNlMeansDenoisingColored_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoisingColored( src, dst, (float)h, (float)hColor, (int)templateWindowSize, (int)searchWindowSize ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColored_11 (JNIEnv*, jclass, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColored_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::fastNlMeansDenoisingColored_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoisingColored( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void fastNlMeansDenoisingColoredMulti(vector_Mat srcImgs, Mat& dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColoredMulti_10 (JNIEnv*, jclass, jlong, jlong, jint, jint, jfloat, jfloat, jint, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColoredMulti_10 (JNIEnv* env, jclass , jlong srcImgs_mat_nativeObj, jlong dst_nativeObj, jint imgToDenoiseIndex, jint temporalWindowSize, jfloat h, jfloat hColor, jint templateWindowSize, jint searchWindowSize) { static const char method_name[] = "photo::fastNlMeansDenoisingColoredMulti_10()"; try { LOGD("%s", method_name); std::vector<Mat> srcImgs; Mat& srcImgs_mat = *((Mat*)srcImgs_mat_nativeObj); Mat_to_vector_Mat( srcImgs_mat, srcImgs ); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoisingColoredMulti( srcImgs, dst, (int)imgToDenoiseIndex, (int)temporalWindowSize, (float)h, (float)hColor, (int)templateWindowSize, (int)searchWindowSize ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColoredMulti_11 (JNIEnv*, jclass, jlong, jlong, jint, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingColoredMulti_11 (JNIEnv* env, jclass , jlong srcImgs_mat_nativeObj, jlong dst_nativeObj, jint imgToDenoiseIndex, jint temporalWindowSize) { static const char method_name[] = "photo::fastNlMeansDenoisingColoredMulti_11()"; try { LOGD("%s", method_name); std::vector<Mat> srcImgs; Mat& srcImgs_mat = *((Mat*)srcImgs_mat_nativeObj); Mat_to_vector_Mat( srcImgs_mat, srcImgs ); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoisingColoredMulti( srcImgs, dst, (int)imgToDenoiseIndex, (int)temporalWindowSize ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void fastNlMeansDenoisingMulti(vector_Mat srcImgs, Mat& dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingMulti_10 (JNIEnv*, jclass, jlong, jlong, jint, jint, jfloat, jint, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingMulti_10 (JNIEnv* env, jclass , jlong srcImgs_mat_nativeObj, jlong dst_nativeObj, jint imgToDenoiseIndex, jint temporalWindowSize, jfloat h, jint templateWindowSize, jint searchWindowSize) { static const char method_name[] = "photo::fastNlMeansDenoisingMulti_10()"; try { LOGD("%s", method_name); std::vector<Mat> srcImgs; Mat& srcImgs_mat = *((Mat*)srcImgs_mat_nativeObj); Mat_to_vector_Mat( srcImgs_mat, srcImgs ); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoisingMulti( srcImgs, dst, (int)imgToDenoiseIndex, (int)temporalWindowSize, (float)h, (int)templateWindowSize, (int)searchWindowSize ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingMulti_11 (JNIEnv*, jclass, jlong, jlong, jint, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_fastNlMeansDenoisingMulti_11 (JNIEnv* env, jclass , jlong srcImgs_mat_nativeObj, jlong dst_nativeObj, jint imgToDenoiseIndex, jint temporalWindowSize) { static const char method_name[] = "photo::fastNlMeansDenoisingMulti_11()"; try { LOGD("%s", method_name); std::vector<Mat> srcImgs; Mat& srcImgs_mat = *((Mat*)srcImgs_mat_nativeObj); Mat_to_vector_Mat( srcImgs_mat, srcImgs ); Mat& dst = *((Mat*)dst_nativeObj); cv::fastNlMeansDenoisingMulti( srcImgs, dst, (int)imgToDenoiseIndex, (int)temporalWindowSize ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void illuminationChange(Mat src, Mat mask, Mat& dst, float alpha = 0.2f, float beta = 0.4f) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_illuminationChange_10 (JNIEnv*, jclass, jlong, jlong, jlong, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_illuminationChange_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong mask_nativeObj, jlong dst_nativeObj, jfloat alpha, jfloat beta) { static const char method_name[] = "photo::illuminationChange_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::illuminationChange( src, mask, dst, (float)alpha, (float)beta ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_illuminationChange_11 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_illuminationChange_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong mask_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::illuminationChange_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::illuminationChange( src, mask, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void inpaint(Mat src, Mat inpaintMask, Mat& dst, double inpaintRadius, int flags) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_inpaint_10 (JNIEnv*, jclass, jlong, jlong, jlong, jdouble, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_inpaint_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong inpaintMask_nativeObj, jlong dst_nativeObj, jdouble inpaintRadius, jint flags) { static const char method_name[] = "photo::inpaint_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& inpaintMask = *((Mat*)inpaintMask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::inpaint( src, inpaintMask, dst, (double)inpaintRadius, (int)flags ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void pencilSketch(Mat src, Mat& dst1, Mat& dst2, float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_pencilSketch_10 (JNIEnv*, jclass, jlong, jlong, jlong, jfloat, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_pencilSketch_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst1_nativeObj, jlong dst2_nativeObj, jfloat sigma_s, jfloat sigma_r, jfloat shade_factor) { static const char method_name[] = "photo::pencilSketch_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst1 = *((Mat*)dst1_nativeObj); Mat& dst2 = *((Mat*)dst2_nativeObj); cv::pencilSketch( src, dst1, dst2, (float)sigma_s, (float)sigma_r, (float)shade_factor ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_pencilSketch_11 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_pencilSketch_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst1_nativeObj, jlong dst2_nativeObj) { static const char method_name[] = "photo::pencilSketch_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst1 = *((Mat*)dst1_nativeObj); Mat& dst2 = *((Mat*)dst2_nativeObj); cv::pencilSketch( src, dst1, dst2 ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void seamlessClone(Mat src, Mat dst, Mat mask, Point p, Mat& blend, int flags) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_seamlessClone_10 (JNIEnv*, jclass, jlong, jlong, jlong, jdouble, jdouble, jlong, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_seamlessClone_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj, jlong mask_nativeObj, jdouble p_x, jdouble p_y, jlong blend_nativeObj, jint flags) { static const char method_name[] = "photo::seamlessClone_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Point p((int)p_x, (int)p_y); Mat& blend = *((Mat*)blend_nativeObj); cv::seamlessClone( src, dst, mask, p, blend, (int)flags ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void stylization(Mat src, Mat& dst, float sigma_s = 60, float sigma_r = 0.45f) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_stylization_10 (JNIEnv*, jclass, jlong, jlong, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_stylization_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj, jfloat sigma_s, jfloat sigma_r) { static const char method_name[] = "photo::stylization_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::stylization( src, dst, (float)sigma_s, (float)sigma_r ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_stylization_11 (JNIEnv*, jclass, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_stylization_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::stylization_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::stylization( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void textureFlattening(Mat src, Mat mask, Mat& dst, double low_threshold = 30, double high_threshold = 45, int kernel_size = 3) // JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_textureFlattening_10 (JNIEnv*, jclass, jlong, jlong, jlong, jdouble, jdouble, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_textureFlattening_10 (JNIEnv* env, jclass , jlong src_nativeObj, jlong mask_nativeObj, jlong dst_nativeObj, jdouble low_threshold, jdouble high_threshold, jint kernel_size) { static const char method_name[] = "photo::textureFlattening_10()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::textureFlattening( src, mask, dst, (double)low_threshold, (double)high_threshold, (int)kernel_size ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_textureFlattening_11 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Photo_textureFlattening_11 (JNIEnv* env, jclass , jlong src_nativeObj, jlong mask_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::textureFlattening_11()"; try { LOGD("%s", method_name); Mat& src = *((Mat*)src_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); cv::textureFlattening( src, mask, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignExposures::process(vector_Mat src, vector_Mat dst, Mat times, Mat response) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignExposures_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignExposures_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_mat_nativeObj, jlong times_nativeObj, jlong response_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); std::vector<Mat> dst; Mat& dst_mat = *((Mat*)dst_mat_nativeObj); Mat_to_vector_Mat( dst_mat, dst ); AlignExposures* me = (AlignExposures*) self; //TODO: check for NULL Mat& times = *((Mat*)times_nativeObj); Mat& response = *((Mat*)response_nativeObj); me->process( src, dst, times, response ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void AlignExposures::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignExposures_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignExposures_delete (JNIEnv*, jclass, jlong self) { delete (AlignExposures*) self; } // // void CalibrateCRF::process(vector_Mat src, Mat& dst, Mat times) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateCRF_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateCRF_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); CalibrateCRF* me = (CalibrateCRF*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); me->process( src, dst, times ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void CalibrateCRF::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateCRF_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_CalibrateCRF_delete (JNIEnv*, jclass, jlong self) { delete (CalibrateCRF*) self; } // // void TonemapDrago::setBias(float bias) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDrago_setBias_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDrago_setBias_10 (JNIEnv* env, jclass , jlong self, jfloat bias) { static const char method_name[] = "photo::setBias_10()"; try { LOGD("%s", method_name); TonemapDrago* me = (TonemapDrago*) self; //TODO: check for NULL me->setBias( (float)bias ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void TonemapDrago::setSaturation(float saturation) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDrago_setSaturation_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDrago_setSaturation_10 (JNIEnv* env, jclass , jlong self, jfloat saturation) { static const char method_name[] = "photo::setSaturation_10()"; try { LOGD("%s", method_name); TonemapDrago* me = (TonemapDrago*) self; //TODO: check for NULL me->setSaturation( (float)saturation ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void TonemapDrago::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDrago_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_TonemapDrago_delete (JNIEnv*, jclass, jlong self) { delete (TonemapDrago*) self; } // // Point AlignMTB::calculateShift(Mat img0, Mat img1) // JNIEXPORT jdoubleArray JNICALL Java_org_opencv_photo_AlignMTB_calculateShift_10 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT jdoubleArray JNICALL Java_org_opencv_photo_AlignMTB_calculateShift_10 (JNIEnv* env, jclass , jlong self, jlong img0_nativeObj, jlong img1_nativeObj) { static const char method_name[] = "photo::calculateShift_10()"; try { LOGD("%s", method_name); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL Mat& img0 = *((Mat*)img0_nativeObj); Mat& img1 = *((Mat*)img1_nativeObj); Point _retval_ = me->calculateShift( img0, img1 ); jdoubleArray _da_retval_ = env->NewDoubleArray(2); jdouble _tmp_retval_[2] = {_retval_.x, _retval_.y}; env->SetDoubleArrayRegion(_da_retval_, 0, 2, _tmp_retval_); return _da_retval_; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return 0; } // // void AlignMTB::computeBitmaps(Mat img, Mat& tb, Mat& eb) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_computeBitmaps_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_computeBitmaps_10 (JNIEnv* env, jclass , jlong self, jlong img_nativeObj, jlong tb_nativeObj, jlong eb_nativeObj) { static const char method_name[] = "photo::computeBitmaps_10()"; try { LOGD("%s", method_name); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL Mat& img = *((Mat*)img_nativeObj); Mat& tb = *((Mat*)tb_nativeObj); Mat& eb = *((Mat*)eb_nativeObj); me->computeBitmaps( img, tb, eb ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignMTB::process(vector_Mat src, vector_Mat dst, Mat times, Mat response) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_mat_nativeObj, jlong times_nativeObj, jlong response_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); std::vector<Mat> dst; Mat& dst_mat = *((Mat*)dst_mat_nativeObj); Mat_to_vector_Mat( dst_mat, dst ); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL Mat& times = *((Mat*)times_nativeObj); Mat& response = *((Mat*)response_nativeObj); me->process( src, dst, times, response ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignMTB::process(vector_Mat src, vector_Mat dst) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_process_11 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_process_11 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_mat_nativeObj) { static const char method_name[] = "photo::process_11()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); std::vector<Mat> dst; Mat& dst_mat = *((Mat*)dst_mat_nativeObj); Mat_to_vector_Mat( dst_mat, dst ); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL me->process( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignMTB::setCut(bool value) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_setCut_10 (JNIEnv*, jclass, jlong, jboolean); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_setCut_10 (JNIEnv* env, jclass , jlong self, jboolean value) { static const char method_name[] = "photo::setCut_10()"; try { LOGD("%s", method_name); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL me->setCut( (bool)value ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignMTB::setExcludeRange(int exclude_range) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_setExcludeRange_10 (JNIEnv*, jclass, jlong, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_setExcludeRange_10 (JNIEnv* env, jclass , jlong self, jint exclude_range) { static const char method_name[] = "photo::setExcludeRange_10()"; try { LOGD("%s", method_name); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL me->setExcludeRange( (int)exclude_range ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignMTB::setMaxBits(int max_bits) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_setMaxBits_10 (JNIEnv*, jclass, jlong, jint); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_setMaxBits_10 (JNIEnv* env, jclass , jlong self, jint max_bits) { static const char method_name[] = "photo::setMaxBits_10()"; try { LOGD("%s", method_name); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL me->setMaxBits( (int)max_bits ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void AlignMTB::shiftMat(Mat src, Mat& dst, Point shift) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_shiftMat_10 (JNIEnv*, jclass, jlong, jlong, jlong, jdouble, jdouble); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_shiftMat_10 (JNIEnv* env, jclass , jlong self, jlong src_nativeObj, jlong dst_nativeObj, jdouble shift_x, jdouble shift_y) { static const char method_name[] = "photo::shiftMat_10()"; try { LOGD("%s", method_name); AlignMTB* me = (AlignMTB*) self; //TODO: check for NULL Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); Point shift((int)shift_x, (int)shift_y); me->shiftMat( src, dst, shift ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void AlignMTB::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_AlignMTB_delete (JNIEnv*, jclass, jlong self) { delete (AlignMTB*) self; } // // void MergeDebevec::process(vector_Mat src, Mat& dst, Mat times, Mat response) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeDebevec_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeDebevec_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj, jlong response_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeDebevec* me = (MergeDebevec*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); Mat& response = *((Mat*)response_nativeObj); me->process( src, dst, times, response ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void MergeDebevec::process(vector_Mat src, Mat& dst, Mat times) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeDebevec_process_11 (JNIEnv*, jclass, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeDebevec_process_11 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj) { static const char method_name[] = "photo::process_11()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeDebevec* me = (MergeDebevec*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); me->process( src, dst, times ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void MergeDebevec::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeDebevec_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeDebevec_delete (JNIEnv*, jclass, jlong self) { delete (MergeDebevec*) self; } // // void MergeMertens::process(vector_Mat src, Mat& dst, Mat times, Mat response) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj, jlong response_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeMertens* me = (MergeMertens*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); Mat& response = *((Mat*)response_nativeObj); me->process( src, dst, times, response ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void MergeMertens::process(vector_Mat src, Mat& dst) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_process_11 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_process_11 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::process_11()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeMertens* me = (MergeMertens*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); me->process( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void MergeMertens::setContrastWeight(float contrast_weiht) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_setContrastWeight_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_setContrastWeight_10 (JNIEnv* env, jclass , jlong self, jfloat contrast_weiht) { static const char method_name[] = "photo::setContrastWeight_10()"; try { LOGD("%s", method_name); MergeMertens* me = (MergeMertens*) self; //TODO: check for NULL me->setContrastWeight( (float)contrast_weiht ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void MergeMertens::setExposureWeight(float exposure_weight) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_setExposureWeight_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_setExposureWeight_10 (JNIEnv* env, jclass , jlong self, jfloat exposure_weight) { static const char method_name[] = "photo::setExposureWeight_10()"; try { LOGD("%s", method_name); MergeMertens* me = (MergeMertens*) self; //TODO: check for NULL me->setExposureWeight( (float)exposure_weight ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void MergeMertens::setSaturationWeight(float saturation_weight) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_setSaturationWeight_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_setSaturationWeight_10 (JNIEnv* env, jclass , jlong self, jfloat saturation_weight) { static const char method_name[] = "photo::setSaturationWeight_10()"; try { LOGD("%s", method_name); MergeMertens* me = (MergeMertens*) self; //TODO: check for NULL me->setSaturationWeight( (float)saturation_weight ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void MergeMertens::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeMertens_delete (JNIEnv*, jclass, jlong self) { delete (MergeMertens*) self; } // // void MergeExposures::process(vector_Mat src, Mat& dst, Mat times, Mat response) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeExposures_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeExposures_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj, jlong response_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeExposures* me = (MergeExposures*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); Mat& response = *((Mat*)response_nativeObj); me->process( src, dst, times, response ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void MergeExposures::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeExposures_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeExposures_delete (JNIEnv*, jclass, jlong self) { delete (MergeExposures*) self; } // // void MergeRobertson::process(vector_Mat src, Mat& dst, Mat times, Mat response) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeRobertson_process_10 (JNIEnv*, jclass, jlong, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeRobertson_process_10 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj, jlong response_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeRobertson* me = (MergeRobertson*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); Mat& response = *((Mat*)response_nativeObj); me->process( src, dst, times, response ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void MergeRobertson::process(vector_Mat src, Mat& dst, Mat times) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeRobertson_process_11 (JNIEnv*, jclass, jlong, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeRobertson_process_11 (JNIEnv* env, jclass , jlong self, jlong src_mat_nativeObj, jlong dst_nativeObj, jlong times_nativeObj) { static const char method_name[] = "photo::process_11()"; try { LOGD("%s", method_name); std::vector<Mat> src; Mat& src_mat = *((Mat*)src_mat_nativeObj); Mat_to_vector_Mat( src_mat, src ); MergeRobertson* me = (MergeRobertson*) self; //TODO: check for NULL Mat& dst = *((Mat*)dst_nativeObj); Mat& times = *((Mat*)times_nativeObj); me->process( src, dst, times ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void MergeRobertson::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_MergeRobertson_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_MergeRobertson_delete (JNIEnv*, jclass, jlong self) { delete (MergeRobertson*) self; } // // void Tonemap::process(Mat src, Mat& dst) // JNIEXPORT void JNICALL Java_org_opencv_photo_Tonemap_process_10 (JNIEnv*, jclass, jlong, jlong, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Tonemap_process_10 (JNIEnv* env, jclass , jlong self, jlong src_nativeObj, jlong dst_nativeObj) { static const char method_name[] = "photo::process_10()"; try { LOGD("%s", method_name); Tonemap* me = (Tonemap*) self; //TODO: check for NULL Mat& src = *((Mat*)src_nativeObj); Mat& dst = *((Mat*)dst_nativeObj); me->process( src, dst ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // void Tonemap::setGamma(float gamma) // JNIEXPORT void JNICALL Java_org_opencv_photo_Tonemap_setGamma_10 (JNIEnv*, jclass, jlong, jfloat); JNIEXPORT void JNICALL Java_org_opencv_photo_Tonemap_setGamma_10 (JNIEnv* env, jclass , jlong self, jfloat gamma) { static const char method_name[] = "photo::setGamma_10()"; try { LOGD("%s", method_name); Tonemap* me = (Tonemap*) self; //TODO: check for NULL me->setGamma( (float)gamma ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; } // // native support for java finalize() // static void Tonemap::delete( __int64 self ) // JNIEXPORT void JNICALL Java_org_opencv_photo_Tonemap_delete(JNIEnv*, jclass, jlong); JNIEXPORT void JNICALL Java_org_opencv_photo_Tonemap_delete (JNIEnv*, jclass, jlong self) { delete (Tonemap*) self; } } // extern "C" #endif // HAVE_OPENCV_PHOTO
31.921975
204
0.678489
[ "vector" ]
2b864fb43a3380163287f948ea7fbf1725a57921
1,927
cpp
C++
chapter02/problem_15/main.cpp
AhmedShaban94/the_modern_cpp_challenge_solutions
c5ea164ecc224389ee35db12126eeee2bc459564
[ "MIT" ]
1
2021-07-08T15:34:14.000Z
2021-07-08T15:34:14.000Z
chapter02/problem_15/main.cpp
AhmedShaban94/the_modern_cpp_challenge_solutions
c5ea164ecc224389ee35db12126eeee2bc459564
[ "MIT" ]
null
null
null
chapter02/problem_15/main.cpp
AhmedShaban94/the_modern_cpp_challenge_solutions
c5ea164ecc224389ee35db12126eeee2bc459564
[ "MIT" ]
null
null
null
#include "catch2/catch.hpp" #include "Ipv4.hpp" TEST_CASE("IPv4 Address class constructor validation", "[IPv4]") { const std::unordered_map<std::string, std::uint32_t> validIpAddresses{ {"255.255.255.255", 4294967295}, {"128.147.0.1", 2157117441}, {"123.70.50.1", 2068197889}, {"128.107.20.1", 2154501121}, {"128.107.30.1", 2154503681}, {"128.107.20.10", 2154501130}, {"128.107.10.15", 2154498575}}; const std::vector<std::string> invalidIpAddresses{"", "some string", "360.255.255.255", "255.360.255.255", "255.255.360.255", "255.255.255.360", "255,255,255,255", "255.-255.255.255", "255.255.255.255.255"}; SECTION("IPv4 Address class string constructor validation") { for (const auto &[str, dec] : validIpAddresses) { REQUIRE_NOTHROW(IPv4{str}); REQUIRE_NOTHROW(IPv4{dec}); REQUIRE(dec == static_cast<std::uint32_t>(IPv4{str})); } for (const auto &addr : invalidIpAddresses) REQUIRE_THROWS_AS(IPv4{addr}, IPv4::IpAddressException); } SECTION("testing input stream operator") { std::stringstream ss; IPv4 ip{}; for (const auto &addr : validIpAddresses) { ss << addr.first; CHECK_NOTHROW(ss >> ip); } ss.clear(); for (const auto &addr : invalidIpAddresses) { ss << addr; REQUIRE_THROWS_AS(ss >> ip, IPv4::IpAddressException); } } }
36.358491
100
0.451479
[ "vector" ]
2b8cc0a62c481a656c405384c22246df0761df19
8,000
cpp
C++
TaylorGreenVortex.cpp
zhaoweifeng1991/LBM-code-for-curved-boundaries
3acac478fdfef9ee9232b41cfdbbceb49656123d
[ "MIT" ]
2
2018-12-03T01:53:46.000Z
2021-12-01T20:32:06.000Z
TaylorGreenVortex.cpp
zhaoweifeng1991/LBM-code-for-curved-boundaries
3acac478fdfef9ee9232b41cfdbbceb49656123d
[ "MIT" ]
null
null
null
TaylorGreenVortex.cpp
zhaoweifeng1991/LBM-code-for-curved-boundaries
3acac478fdfef9ee9232b41cfdbbceb49656123d
[ "MIT" ]
1
2022-02-17T13:50:19.000Z
2022-02-17T13:50:19.000Z
///////////////// Taylor-Green vortex flow with curved boundaries, convex scheme #include<iostream> #include<cmath> #include<cstdlib> #include<iomanip> #include<fstream> #include<sstream> #include<string> #include<stdio.h> using namespace std; const int Q=9; const int NX=39; const int NY=39; const double U=0.05; const double pi=3.1415926; int e[Q][2]={{0,0},{1,0},{0,1},{-1,0},{0,-1},{1,1},{-1,1},{-1,-1},{1,-1}}; //9 directions int ne[Q]={0,3,4,1,2,7,8,5,6}; //back directions double w[Q]={4.0/9,1.0/9,1.0/9,1.0/9,1.0/9,1.0/36,1.0/36,1.0/36,1.0/36}; double rho[NX+1][NY+1],u[NX+1][NY+1][2],u0[NX+1][NY+1][2],f[NX+1][NY+1][Q],ff[NX+1][NY+1][Q],F[NX+1][NY+1][Q],xlabel[NX+1][NY+1],ylabel[NX+1][NY+1]; int i,j,k,ip,jp,n,q_flag; double c,Re,dx,dy,Lx,Ly,D,dt,rho0,p0,tau_f,niu,error,y,yy1,yy2,kk,b,cc,x1,x2,x,q; double iq,jq,AA,BB,CC,DD,EE,rr,uu,vv,Center_x,Center_y; double R; //radius of the circle double ell=1.0; // a parameter to control the shape of the boundary: ell*(x-x0)^2+(y-y0)^2=R^2, ell=1 for circle double s_nu,s_q,SS,cs_2; double abs( double i); void comput_q (int i, int j, int ip, int jp); void init(); double feq(int k,double rho,double u[2]); void evolution(); void output(int m); void Error(); int flag[NX+1][NY+1]; int main() { using namespace std; init(); //initiate for(n=0; ;n++) { evolution(); if(n%100==0) { Error(); } if(n%100==0) { cout<<"The"<<n<<"th computation result:"<<endl<<"The u,v of point (NX/2,NY/2)is : " <<setprecision(6)<<u[NX/2][NY/2][0]<<","<<u[NX/2][NY/2][1]<<endl; cout<<"The max relative error of uv is:" <<setiosflags(ios::scientific)<<error<<endl; } // if(n%1000==0) // output(n); if(n==int(1.0*Lx/U/dt)) { Error(); cout<<"The max relative error of uv is:" <<setiosflags(ios::scientific)<<error<<endl; output(n+1); break; } } return 0; } void init() { Lx=1.0; Ly=1.0; dx=Lx/(NX+1); dy=dx; niu=0.002; SS=1.0; //tau s_nu=-1.0/SS; s_q=-8.0*(2+s_nu)/(8+s_nu); dt=(SS -0.5)/3.0 *dx*dx /niu; c=dx/dt; cout<<"U/c = "<<U/c<<"\n"; R=Lx/4.0; // radius rho0=1.0; cs_2=c*c/3.0; for(i=0;i<=NX;i++) //corrdinates of the lattice nodes for(j=0;j<=NY;j++) { xlabel[i][j]=i*dx+0.5*dx; ylabel[i][j]=j*dy+0.5*dy; } Center_x=Lx/2.0; //the centre of the circle Center_y=Ly/2.0; for (i=0;i<=NX;i++) //tag different lattice nodes for (j=0;j<=NY;j++) { flag[i][j]=0; if( ( ell*(xlabel[i][j]-Center_x)*(xlabel[i][j]-Center_x) + (ylabel[i][j]-Center_y)*(ylabel[i][j]-Center_y) ) < R*R ) { flag[i][j]=1; //internal fluid lattice nodes } } for(i=0;i<=NX;i++) //initialization of DF for(j=0;j<=NY;j++) { u[i][j][0]=-U*cos(2.0*pi*xlabel[i][j])*sin(2.0*pi*ylabel[i][j]); u[i][j][1]=U*cos(2.0*pi*ylabel[i][j])*sin(2.0*pi*xlabel[i][j]); rho[i][j]= rho0 -3.0*U*U/4.0/c/c*( cos(4.0*pi*xlabel[i][j])+cos(4.0*pi*ylabel[i][j]) ); for(k=0;k<Q;k++) { f[i][j][k]=feq(k,rho[i][j],u[i][j]); } } } double feq(int k,double rho,double u[2]) // equilibrium distribution { double eu,uv,feq; eu=(e[k][0]*u[0]+e[k][1]*u[1]); uv=(u[0]*u[0]+u[1]*u[1]); feq=w[k]*(rho + rho0* (3.0*eu/c+4.5*eu*eu/c/c-1.5*uv/c/c) ); return feq; } void evolution() { for(i=(NX+1)/4-3;i<=(NX+1)/4*3+3;i++) for(j=(NY+1)/4-3;j<=(NY+1)/4*3+3;j++) { for(k=0;k<Q;k++) F[i][j][k]=f[i][j][k] + s_nu*( 0.5*(f[i][j][k]+f[i][j][ne[k]]) - 0.5*(feq(k,rho[i][j], u[i][j])+feq(ne[k],rho[i][j], u[i][j])) ) + s_q*( 0.5*(f[i][j][k]-f[i][j][ne[k]]) - 0.5*(feq(k,rho[i][j], u[i][j])-feq(ne[k],rho[i][j], u[i][j])) ); //collision } for(i=(NX+1)/4-3; i<=(NX+1)/4*3+3; i++) for(j=(NY+1)/4-3; j<=(NY+1)/4*3+3; j++) { if(flag[i][j]==1) { for(k=0;k<Q;k++) { ip=i-e[k][0]; jp=j-e[k][1]; if( flag[i][j]==1 && flag[ip][jp]==0 ) { comput_q(i,j,ip,jp); // compute the ratio $gamma$, the computed value is 'q', which is equal to gamma * dx iq=xlabel[i][j]-q*double(e[k][0]); jq=ylabel[i][j]-q*double(e[k][1]); rr= rho0 - 3.0*U*U/4.0/c/c*( cos(iq*4.0*pi)+cos(jq*4.0*pi) )*exp(-16.0*niu*pi*pi*(n)*dt) ; uu=-U*cos(iq*2.0*pi)*sin(jq*2.0*pi)*exp(-8.0*niu*pi*pi*(n)*dt) ; vv=U*sin(iq*2.0*pi)*cos(jq*2.0*pi)*exp(-8.0*niu*pi*pi*(n)*dt) ; q=q/dx; AA= 2.0*q/(1.0+2.0*q); BB = 1.0-AA; CC = 1.0-AA+BB; ff[i][j][k] = AA*F[i][j][k] +BB*f[i][j][ne[k]] + CC*w[k]*rho0*3.0/c*(e[k][0]*uu+e[k][1]*vv); } else ff[i][j][k]=F[ip][jp][k]; } } } for(i=(NX+1)/4-3;i<=(NX+1)/4*3+3;i++) for(j=(NY+1)/4-3;j<=(NY+1)/4*3+3;j++) if(flag[i][j]==1) { rho[i][j]=0; u[i][j][0]=0; u[i][j][1]=0; for(k=0;k<Q;k++) { f[i][j][k] = ff[i][j][k]; rho[i][j]+=f[i][j][k]; u[i][j][0]+=c*e[k][0]*f[i][j][k]; u[i][j][1]+=c*e[k][1]*f[i][j][k]; } u[i][j][0]/=rho0; u[i][j][1]/=rho0; } } double abs( double i) { if(i>=0.0) return i; else return -i; } void comput_q (int i, int j, int ip, int jp) // compute the ratio $gamma$, the computed value is 'q', which is equal to gamma * dx { if (ip==i) { yy1 = abs( Center_y+sqrt( (R*R-(xlabel[i][j]-Center_x)*(xlabel[i][j]-Center_x))/ell )-ylabel[i][j] ); yy2 = abs( Center_y-sqrt( (R*R-(xlabel[i][j]-Center_x)*(xlabel[i][j]-Center_x))/ell )-ylabel[i][j] ); if(yy1<=yy2) q=yy1; else q=yy2; } else { kk = (ylabel[ip][jp]-ylabel[i][j])/(xlabel[ip][jp]-xlabel[i][j]); b = ( 2.0*Center_x - 2.0*ell*kk*(ylabel[i][j]-kk*xlabel[i][j]-Center_y) ) / (ell*kk*kk+1.0); cc = ( ell*(ylabel[i][j]-kk*xlabel[i][j]-Center_y)*(ylabel[i][j]-kk*xlabel[i][j]-Center_y)+Center_x*Center_x-R*R ) / (ell*kk*kk+1.0); x1 = abs( (b+sqrt(b*b-4.0*cc))/2.0-xlabel[i][j] ); x2 = abs( (b-sqrt(b*b-4.0*cc))/2.0-xlabel[i][j] ); if(x1<=x2) q=x1; else q=x2; } } void output(int m) //output the data { ostringstream name; name<<"TaylorGreen"<<"Mesh"<<NX<<"_"<<NY<<"compute_"<<m<<"times"".dat"; ofstream out(name.str().c_str()); out<<"Title= \"TaylorGreen\"\n"<<"VARIABLES=\"X\",\"Y\",\"U\",\"V\",\"U0\",\"V0\",\"p\" \n"<<"ZONE T=\"BOX\",I=" <<NX+1<<",J="<<NY+1<<",F=POINT"<<endl; for(j=0;j<=NY;j++) for(i=0;i<=NX;i++) { out<<setprecision(15)<<xlabel[i][j]<<" "<<ylabel[i][j]<<" "<<u[i][j][0]<<" "<< u[i][j][1]<<" "<<u0[i][j][0]<<" "<< u0[i][j][1]<<" "<<rho[i][j]<<endl; // cout<<rho[i][j]<<endl; } } void Error() //compute error { double temp1,temp2; temp1=0; temp2=0; for(i=1;i<NX;i++) for(j=1;j<NY;j++) { if(flag[i][j]==1) { u0[i][j][0]=-U*cos(xlabel[i][j]*2.0*pi)*sin(ylabel[i][j]*2.0*pi)*exp(-8.0*niu*pi*pi*(n)*dt); u0[i][j][1]= U*cos(ylabel[i][j]*2.0*pi)*sin(xlabel[i][j]*2.0*pi)*exp(-8.0*niu*pi*pi*(n)*dt); temp1+=( (u[i][j][0]-u0[i][j][0])*(u[i][j][0]-u0[i][j][0])+(u[i][j][1]-u0[i][j][1])*(u[i][j][1]-u0[i][j][1])); temp2+=(u0[i][j][0]*u0[i][j][0]+u0[i][j][1]*u0[i][j][1]); } } temp1=sqrt(temp1); temp2=sqrt(temp2); error=temp1/(temp2+1e-30); }
21.917808
168
0.449
[ "mesh", "shape" ]
2b8ce630bb294e4228db926a0251c6a99b457242
3,051
cpp
C++
nw2fbx/export_info.cpp
Karbust/nwn2mdk
0ec3efa1f75aa5df481a95f4b9d8e921b7881613
[ "Apache-2.0" ]
23
2017-09-21T23:17:07.000Z
2022-02-20T19:34:35.000Z
nw2fbx/export_info.cpp
Karbust/nwn2mdk
0ec3efa1f75aa5df481a95f4b9d8e921b7881613
[ "Apache-2.0" ]
7
2017-05-18T13:07:51.000Z
2020-04-07T00:02:30.000Z
nw2fbx/export_info.cpp
Karbust/nwn2mdk
0ec3efa1f75aa5df481a95f4b9d8e921b7881613
[ "Apache-2.0" ]
4
2019-05-05T13:51:24.000Z
2021-01-19T04:00:39.000Z
#include <fstream> #include <filesystem> #include <iostream> #include "config.h" #include "export_info.h" using namespace std; namespace fs = std::filesystem; void process_fbx_bones(Dependency& dep) { FbxNode* ribcage = nullptr; for (auto it = dep.fbx_bones.begin(); it != dep.fbx_bones.end();) { if (strncmp((*it)->GetName(), "ap_", 3) == 0) { // "ap_..." (attachment point) bones are not used for skinning. } else if (strncmp((*it)->GetName(), "f_", 2) == 0) { // "f_..." (face) bones are only used for head skinning. dep.fbx_face_bones.push_back(*it); } else if (strcmp((*it)->GetName(), "Ribcage") == 0) { // Keep "Ribcage" bone to reinsert it later. ribcage = *it; } else { // The remaining bones are used for body skinning. dep.fbx_body_bones.push_back(*it); } ++it; } if (ribcage) { // Reinsert "Ribcage" bone. For some unknown reason, it seems // this bone must be always the last one. dep.fbx_body_bones.push_back(ribcage); } } static Archive_container load_model_archives(const Config& config) { const char* files[] = { "Data/NWN2_Models_X2_v121.zip", "Data/NWN2_Models_X2.zip", "Data/NWN2_Models_X1_v121.zip", "Data/NWN2_Models_X1.zip", "Data/NWN2_Models_v121.zip", "Data/NWN2_Models_v112.zip", "Data/NWN2_Models_v107.zip", "Data/NWN2_Models_v106.zip", "Data/NWN2_Models_v105.zip", "Data/NWN2_Models_v104.zip", "Data/NWN2_Models_v103x1.zip", "Data/NWN2_Models.zip", "Data/lod-merged_X2_v121.zip", "Data/lod-merged_X2.zip", "Data/lod-merged_X1_v121.zip", "Data/lod-merged_X1.zip", "Data/lod-merged_v121.zip", "Data/lod-merged_v107.zip", "Data/lod-merged_v101.zip", "Data/lod-merged.zip" }; Archive_container archives; for (unsigned i = 0; i < sizeof(files) / sizeof(char*); ++i) { cout << "Indexing: " << files[i]; fs::path p = fs::path(config.nwn2_home) / fs::path(files[i]); if (!archives.add_archive(p.string().c_str())) { cout << " : Cannot open zip"; } cout << endl; } return archives; } Archive_container& model_archives(const Config& config) { static auto a = load_model_archives(config); return a; } static std::vector<unsigned char> read_file(const char* filename) { vector<unsigned char> buffer; ifstream in(filename, ios::in | ios::binary); if (!in) return buffer; // Get file size in.seekg(0, ios::end); auto size = in.tellg(); in.seekg(0, ios::beg); buffer.resize(size); in.read((char *)buffer.data(), size); return buffer; } std::vector<unsigned char> load_resource(const Config& config, const char* filename) { if (fs::exists(filename)) return read_file(filename); static auto& archives = model_archives(config); auto r = archives.find_file(filename); if (r.matches == 0) return {}; cout << "Extracting: " << filename << endl; vector<unsigned char> buffer; if (!archives.extract_file_to_mem(r.archive_index, r.file_index, buffer)) { cout << " Cannot extract\n"; return {}; } return buffer; }
26.076923
68
0.656506
[ "vector" ]
2b90d7a0f1fd6c22a20d54e4a82562585b1f519c
2,505
cpp
C++
src/IO/Surface_Mesh_IO/ObjFileLoader.cpp
Oncle-Ha/peridyno
7952252923d637685bf3a982856aca8095b78c50
[ "Apache-2.0" ]
22
2021-05-26T09:19:07.000Z
2022-03-28T04:06:21.000Z
src/IO/Surface_Mesh_IO/ObjFileLoader.cpp
Oncle-Ha/peridyno
7952252923d637685bf3a982856aca8095b78c50
[ "Apache-2.0" ]
1
2021-07-27T09:43:42.000Z
2022-02-07T14:47:18.000Z
src/IO/Surface_Mesh_IO/ObjFileLoader.cpp
Oncle-Ha/peridyno
7952252923d637685bf3a982856aca8095b78c50
[ "Apache-2.0" ]
11
2021-04-24T03:43:33.000Z
2022-03-11T14:09:21.000Z
#include "ObjFileLoader.h" #include <fstream> #include <iostream> #include <sstream> namespace dyno{ ObjFileLoader::ObjFileLoader(std::string filename) { load(filename); } bool ObjFileLoader::load(const std::string &filename) { if (filename.size() < 5 || filename.substr(filename.size() - 4) != std::string(".obj")) { std::cerr << "Error: Expected OBJ file with filename of the form <name>.obj.\n"; exit(-1); } std::ifstream infile(filename); if (!infile) { std::cerr << "Failed to open. Terminating.\n"; exit(-1); } int ignored_lines = 0; std::string line; std::vector<std::string> facelets; while (!infile.eof()) { std::getline(infile, line); //.obj files sometimes contain vertex normals indicated by "vn" if (line.substr(0, 1) == std::string("v") && line.substr(0, 2) != std::string("vn") && line.substr(0, 2) != std::string("vt")) { std::stringstream data(line); char c; Vec3f point; data >> c >> point[0] >> point[1] >> point[2]; vertList.push_back(point); } else if (line.substr(0, 1) == std::string("f")) { facelets.push_back(line); } else if (line.substr(0, 2) == std::string("vn")) { std::cerr << "Obj-loader is not able to parse vertex normals, please strip them from the input file. \n"; exit(-2); } else if (line.substr(0, 2) == std::string("vt")) { std::stringstream data(line); char c; TexCoord tex; data >> c >> tex[0] >> tex[1]; texCoords.push_back(tex); } else { ++ignored_lines; } } for each (auto line in facelets) { std::stringstream data(line); std::string item; std::getline(data, item, ' '); Face faceIndex; TexIndex texIndex; for(int i = 0; i < 3; i++) { std::getline(data, item, ' '); std::stringstream vertexData(item); std::string triId; std::getline(vertexData, triId, '/'); faceIndex[i] = atoi(triId.c_str()) - 1; if (texCoords.size() > 0) { std::string texId; std::getline(vertexData, texId, '/'); texIndex[i] = atoi(texId.c_str()) - 1; } } faceList.push_back(faceIndex); if (texCoords.size() > 0) { texList.push_back(texIndex); } } infile.close(); facelets.clear(); } bool ObjFileLoader::save(const std::string &filename) { return true; } std::vector<Vec3f>& ObjFileLoader::getVertexList() { return vertList; } std::vector<Face>& ObjFileLoader::getFaceList() { return faceList; } } //end of namespace dyno
22.168142
131
0.601198
[ "vector" ]
2b91a4bff93e77c51cfafceaa38adf0ee032bc8f
341
cpp
C++
cpp/blockchainNativeApi.cpp
t348575/blockchain-api
9c5ab8046c9ac1e88591bbba7f81126da85f7724
[ "MIT" ]
null
null
null
cpp/blockchainNativeApi.cpp
t348575/blockchain-api
9c5ab8046c9ac1e88591bbba7f81126da85f7724
[ "MIT" ]
null
null
null
cpp/blockchainNativeApi.cpp
t348575/blockchain-api
9c5ab8046c9ac1e88591bbba7f81126da85f7724
[ "MIT" ]
null
null
null
#include <napi.h> #include "blockchainWrapper.h" #include "blockchain.h" // InitAll called when addon is included // BlockChainWrapper::Init wraps the C++ class around the JS class Napi::Object InitAll(Napi::Env env, Napi::Object exports) { return BlockChainWrapper::Init(env, exports); } NODE_API_MODULE(NODE_GYP_MODULE_NAME, InitAll);
34.1
66
0.765396
[ "object" ]
2b948af3b77bbe94b9b4a6ca86aded513d09a6ae
20,028
cpp
C++
Source/AllProjects/Drivers/CQSLRepo/MediaRepoMgr/MediaRepoMgr_EdTitleSetDlg.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/CQSLRepo/MediaRepoMgr/MediaRepoMgr_EdTitleSetDlg.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/CQSLRepo/MediaRepoMgr/MediaRepoMgr_EdTitleSetDlg.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: MediaRepoMgr_EditTitleSet.cpp // // AUTHOR: Dean Roddey // // CREATED: 09/13/2006 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the MediaRepoMgr_EditTitleSetDlg.cpp file, which // implements a dialog box for editing title set contents. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "MediaRepoMgr.hpp" #include "MediaRepoMgr_EdTitleSetDlg.hpp" // --------------------------------------------------------------------------- // Do our RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TEditTitleSetDlg,TDlgBox) // --------------------------------------------------------------------------- // CLASS: TEditTitleSetDlg // PREFIX: dlg // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TEditTitleSetDlg: Constructors and Destructor // --------------------------------------------------------------------------- TEditTitleSetDlg::TEditTitleSetDlg() : m_bNewImage(kCIDLib::False) , m_c2ArtId(0) , m_eRes(EEditRes::NoChange) , m_eMType(tCQCMedia::EMediaTypes::Count) , m_pmdbEdit(nullptr) , m_pwndArt(nullptr) , m_pwndArtist(nullptr) , m_pwndCancel(nullptr) , m_pwndColDel(nullptr) , m_pwndColDn(nullptr) , m_pwndColList(nullptr) , m_pwndColUp(nullptr) , m_pwndDelArt(nullptr) , m_pwndSave(nullptr) , m_pwndSetArt(nullptr) , m_pwndSortTitle(nullptr) , m_pwndTitle(nullptr) , m_pwndUserRating(nullptr) { // Set the JPEG image settings for our desired quality m_imgiNew.bOptimalEncoding(kCIDLib::True); m_imgiNew.c4CompQuality(80); m_imgiNew.eOutSample(tCIDJPEG::EOutSamples::F4_2_1); } TEditTitleSetDlg::~TEditTitleSetDlg() { } // --------------------------------------------------------------------------- // TEditTitleSetDlg: Public, non-virtual methods // --------------------------------------------------------------------------- TEditTitleSetDlg::EEditRes TEditTitleSetDlg::eRun( const TWindow& wndOwner , const TMediaTitleSet& mtsEdit , TMediaDB& mdbToEdit , const TString& strRepoMoniker) { // Store incoming stuff for later use m_c2ArtId = mtsEdit.c2ArtId(); m_eMType = mtsEdit.eType(); m_pmdbEdit = &mdbToEdit; m_strRepoMoniker = strRepoMoniker; // Copy the incoming for editing m_mtsEdit = mtsEdit; c4RunDlg(wndOwner, facMediaRepoMgr, kMediaRepoMgr::ridDlg_EdTitle); // Just return whatever result they left return m_eRes; } // --------------------------------------------------------------------------- // TEditTitleSetDlg: Protected, inherited methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TEditTitleSetDlg::bCreated() { // Call our parent first const tCIDLib::TBoolean bRet = TParent::bCreated(); // Get typed pointers to some of the widgets CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_Art, m_pwndArt); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_Artist, m_pwndArtist); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_Cancel, m_pwndCancel); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_ColDel, m_pwndColDel); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_ColDn, m_pwndColDn); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_ColList, m_pwndColList); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_ColUp, m_pwndColUp); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_DelArt, m_pwndDelArt); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_Save, m_pwndSave); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_SetArt, m_pwndSetArt); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_SortTitle, m_pwndSortTitle); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_Title, m_pwndTitle); CastChildWnd(*this, kMediaRepoMgr::ridDlg_EdTitle_UserRating, m_pwndUserRating); // Set an AR maintaining placement type on the art m_pwndArt->ePlacement(tCIDGraphDev::EPlacement::FitAR); // Load up incoming stuff m_pwndArtist->strWndText(m_mtsEdit.strArtist()); m_pwndSortTitle->strWndText(m_mtsEdit.strSortTitle()); m_pwndTitle->strWndText(m_mtsEdit.strName()); // If this guy has an art id set, then try to load it if (m_c2ArtId) LoadArt(m_c2ArtId); // Load up the user rating combo box m_pwndUserRating->LoadNumRange(1, 10); // Select the current value, which is just the rating minus one m_pwndUserRating->SelectByIndex(m_mtsEdit.c4UserRating() - 1); // // Load the names of the collections. Store the id of the collections in // an extra field of the list window items, so we can be sure we are associating // them with the right collections. // const tCIDLib::TCard4 c4ColCount = m_mtsEdit.c4ColCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4ColCount; c4Index++) { // Get the id of the collection at this index within the set const tCIDLib::TCard2 c2CurId = m_mtsEdit.c2ColIdAt(c4Index); // And use that to look up the collection const TMediaCollect* pmcolCur = m_pmdbEdit->pmcolById ( m_eMType, c2CurId, kCIDLib::True ); m_pwndColList->c4AddItem(pmcolCur->strName(), pmcolCur->c2Id()); } // Install handlers m_pwndCancel->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); m_pwndColDel->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); m_pwndColDn->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); m_pwndColUp->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); m_pwndDelArt->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); m_pwndSave->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); m_pwndSetArt->pnothRegisterHandler(this, &TEditTitleSetDlg::eClickHandler); return bRet; } // --------------------------------------------------------------------------- // TEditTitleSetDlg: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TEditTitleSetDlg::bValidate() { // Scale the image down if we got a new one, and if it's too big if (m_bNewImage) { try { if ((m_imgiNew.c4Width() > kMediaRepoMgr::c4MaxH) || (m_imgiNew.c4Height() > kMediaRepoMgr::c4MaxV)) { // We need to scale it TSize szNew(m_imgiNew.szImage()); if ((m_imgiNew.c4Width() > kMediaRepoMgr::c4MaxH) && (m_imgiNew.c4Height() > kMediaRepoMgr::c4MaxV)) { // It's bigger in both directions, so take the larger one if (m_imgiNew.c4Width() > m_imgiNew.c4Height()) szNew.ScaleToWidthAR(kMediaRepoMgr::c4MaxH); else szNew.ScaleToHeightAR(kMediaRepoMgr::c4MaxV); } else if (m_imgiNew.c4Width() > kMediaRepoMgr::c4MaxH) { szNew.ScaleToWidthAR(kMediaRepoMgr::c4MaxH); } else { szNew.ScaleToHeightAR(kMediaRepoMgr::c4MaxV); } m_imgiNew.Scale(szNew, 4); } } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); TErrBox msgbErr(facMediaRepoMgr.strMsg(kMRMgrMsgs::midStatus_BadImage)); msgbErr.ShowIt(*this); return kCIDLib::False; } } try { // The sort title and artist cannot be empty TString strSortTitle(m_pwndSortTitle->strWndText()); strSortTitle.StripWhitespace(); TString strArtist(m_pwndArtist->strWndText()); strArtist.StripWhitespace(); TWindow* pwndErr = 0; TString strErr; if (strSortTitle.bIsEmpty()) { pwndErr = m_pwndSortTitle; strErr.LoadFromMsg(kMRMgrMsgs::midStatus_NoSortTitle, facMediaRepoMgr); } else if (strArtist.bIsEmpty()) { pwndErr = m_pwndSortTitle; strErr.LoadFromMsg(kMRMgrMsgs::midStatus_MustHaveLastName, facMediaRepoMgr); } // If any errors, show the message, put the focus there, and fail if (pwndErr) { TErrBox msgbErr(strErr); msgbErr.ShowIt(*this); pwndErr->TakeFocus(); return kCIDLib::False; } // Set this basic stuff on our title set m_mtsEdit.strArtist(strArtist); m_mtsEdit.strSortTitle(strSortTitle); m_mtsEdit.c4UserRating(m_pwndUserRating->c4CurItem() + 1); // // If they loaded a new image, we need to store it for later upload. What // we do is just 'cache' it in the database on the image object, which is // normally just a server side thing, but it lets us store it such that we // know later it needs to be uploaded, and without having to have some other // data structure to store it in. // // If this guy was not already associated with a media image, we create a // new one and it to the database first. // if (m_bNewImage) { // Get the image flattened and generate a persistent id for it TString strPerId; TChunkedBinOutStream strmOut(16 * (1024 * 1024)); strmOut << m_imgiNew << kCIDLib::FlushIt; TChunkedBinInStream strmSrc(strmOut); facCQCMedia().CreatePersistentId ( strmSrc, strmOut.c4CurSize(), strPerId ); tCIDLib::TCard2 c2Id = m_mtsEdit.c2ArtId(); if (!c2Id) { // // Create a new one and add it to our database. We don't know any of // the paths at this point. // TMediaImg* pmimgStore = new TMediaImg ( m_eMType, TString::strEmpty(), TString::strEmpty() ); c2Id = m_pmdbEdit->c2AddImage(pmimgStore); // Update the title to reference this art id m_mtsEdit.c2ArtId(c2Id); } // // Store the art on the image object. Reset the source stream before // we do it, so that it's back to the beginning. // strmSrc.Reset(); m_pmdbEdit->SetArt ( c2Id , m_eMType , tCQCMedia::ERArtTypes::LrgCover , strmSrc , strmOut.c4CurSize() , strPerId ); } // // Deal with the collections. We first find any that were in the original // but aren't now in our edited set info. For those, we remove them from // the database. So get the original set so we can compare. // // If these are not playlists we are removing, then any items they reference // will be removed as well. // { const TMediaTitleSet* pmtsOrg = m_pmdbEdit->pmtsById ( m_eMType, m_mtsEdit.c2Id(), kCIDLib::True ); tCIDLib::TCard4 c4Count = pmtsOrg->c4ColCount(); tCIDLib::TCard4 c4Index = 0; while (c4Index < c4Count) { const tCIDLib::TCard2 c2CurCol = pmtsOrg->c2ColIdAt(c4Index); tCIDLib::TCard2 c2ColInd; if(m_mtsEdit.bContainsCol(c2CurCol, c2ColInd)) { c4Index++; } else { m_pmdbEdit->PruneHierarchy(m_eMType, kCIDLib::False, c2CurCol); c4Count--; } } } // // If the title set has ended up empty, we remove it as well. Else we // update the database with the new title set contents. // if (!m_mtsEdit.c4ColCount()) { m_pmdbEdit->PruneHierarchy(m_eMType, kCIDLib::True, m_mtsEdit.c2Id()); m_eRes = EEditRes::Deleted; } else { // Assume they changed soemthing so copy over the changes m_pmdbEdit->UpdateTitle(m_mtsEdit); m_eRes = EEditRes::Changed; } } catch(const TError& errToCatch) { TExceptDlg dlgErr ( *this , strWndText() , facMediaRepoMgr.strMsg(kMRMgrMsgs::midStatus_Exception) , errToCatch ); return kCIDLib::False; } return kCIDLib::True; } // // Delete the selected collection. // tCIDLib::TVoid TEditTitleSetDlg::DeleteCollect() { const tCIDLib::TCard4 c4CurInd = m_pwndColList->c4CurItem(); if (c4CurInd == kCIDLib::c4MaxCard) return; try { // // Get this collection id and remove it from our list and from the // title set. // m_mtsEdit.RemoveColAt(c4CurInd); m_pwndColList->RemoveAt(c4CurInd); } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); TExceptDlg dlgErr ( *this , strWndText() , facMediaRepoMgr.strMsg(kMRMgrMsgs::midStatus_Exception) , errToCatch ); } } // Handle button clicks tCIDCtrls::EEvResponses TEditTitleSetDlg::eClickHandler(TButtClickInfo& wnotEvent) { if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_Cancel) { m_eRes = EEditRes::NoChange; EndDlg(kMediaRepoMgr::ridDlg_EdTitle_Cancel); } else if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_ColDel) { const tCIDLib::TCard4 c4ColCount = m_pwndColList->c4ItemCount(); // // If this is the last collection, tell them that the title set is // going to be removed and the dialog closed if they do this. Else, // just confirm the removal. // TString strQuestion; if (c4ColCount == 1) strQuestion.LoadFromMsg(kMRMgrMsgs::midQ_DeleteLastCollect, facMediaRepoMgr); else strQuestion.LoadFromMsg(kMRMgrMsgs::midQ_DeleteCollect, facMediaRepoMgr); TYesNoBox msgbQ(strQuestion); if (msgbQ.bShowIt(*this)) DeleteCollect(); } else if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_ColDn) { // // If we have more than one collection, and it's not already at the // end, then swap it with the one after it. // const tCIDLib::TCard4 c4Index = m_pwndColList->c4CurItem(); const tCIDLib::TCard4 c4Count = m_pwndColList->c4ItemCount(); if ((c4Count > 1) && (c4Index < (c4Count - 1))) { m_pwndColList->bMoveDn(kCIDLib::True); m_mtsEdit.SwapCollects(c4Index, c4Index + 1); } } else if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_ColUp) { // // If we have more than one collection, and it's not already at the // top, then swap it with the one before it. // const tCIDLib::TCard4 c4Index = m_pwndColList->c4CurItem(); const tCIDLib::TCard4 c4Count = m_pwndColList->c4ItemCount(); if ((c4Count > 1) && c4Index) { m_pwndColList->bMoveUp(kCIDLib::True); m_mtsEdit.SwapCollects(c4Index, c4Index - 1); } } else if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_DelArt) { // Clear the image window and zero our art id m_pwndArt->Reset(); m_mtsEdit.c2ArtId(0); // In case we loaded a new one, forget that now m_bNewImage = kCIDLib::False; } else if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_Save) { // Validate the entered stuf and collect it up if (bValidate()) EndDlg(kMediaRepoMgr::ridDlg_EdTitle_Save); } else if (wnotEvent.widSource() == kMediaRepoMgr::ridDlg_EdTitle_SetArt) { SelectArt(); } return tCIDCtrls::EEvResponses::Handled; } // Called on entry to load the existing art if any tCIDLib::TVoid TEditTitleSetDlg::LoadArt(const tCIDLib::TCard2 c2ArtId) { // If the id is zero, then there isn't any if (!c2ArtId) return; try { TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait); tMediaRepoMgr::TRepoMgrProxyPtr orbcSrv ( facMediaRepoMgr.orbcMakeProxy(m_strRepoMoniker) ); THeapBuf mbufImg(1024 * 64); tCIDLib::TCard4 c4Size; const tCIDLib::TBoolean bRes = orbcSrv->bQueryArtById ( m_eMType , tCQCMedia::ERArtTypes::LrgCover , c2ArtId , c4Size , mbufImg , kCIDLib::False ); if (bRes) { TBinMBufInStream strmSrc(&mbufImg, c4Size); TJPEGImage imgArt; strmSrc >> imgArt; TGraphWndDev gdevCompat(*this); m_pwndArt->SetImage(gdevCompat, imgArt); } } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); TExceptDlg dlgErr ( *this , strWndText() , facMediaRepoMgr.strMsg ( kMRMgrMsgs::midStatus_CantLoadArt , tCQCMedia::strXlatEDataTypes(tCQCMedia::EDataTypes::TitleSet) ) , errToCatch ); } } tCIDLib::TVoid TEditTitleSetDlg::SelectArt() { // Let the user select a local image TPathStr pathSrcFile; { tCIDLib::TKVPList colFileTypes(1); colFileTypes.objAdd(TKeyValuePair(L"Image Files", L"*.bmp,*.png,*.jpeg,*.jpg")); tCIDLib::TStrList colSel; const tCIDLib::TBoolean bRes = facCIDCtrls().bOpenFileDlg ( *this , facMediaRepoMgr.strMsg(kMRMgrMsgs::midPrompt_SelectImg) , TString::strEmpty() , colSel , colFileTypes , tCIDCtrls::EFOpenOpts::FileMustExist ); if (!bRes) return; pathSrcFile = colSel[0]; } try { // Use the image factory to laod the file, converting to JPEG if needed facCIDImgFact().bLoadToJPEG(pathSrcFile, m_imgiNew, kCIDLib::True); // Remember we have a new image to upload m_bNewImage = kCIDLib::True; // Update our previe window with the new stuff TGraphWndDev gdevCompat(*this); m_pwndArt->SetImage(gdevCompat, m_imgiNew); } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); TExceptDlg dlgErr ( *this , strWndText() , facMediaRepoMgr.strMsg ( kMRMgrMsgs::midStatus_CantLoadArt , tCQCMedia::strXlatEDataTypes(tCQCMedia::EDataTypes::Collect) ) , errToCatch ); } }
32.618893
89
0.56451
[ "object" ]
2b9d32e350ccc7df869285fb0d5c958b3ce8d82f
4,949
cc
C++
bin/spectatord_main.cc
copperlight/spectatord
dfc0ec35bc027d090f1d71a3f067fe164ef84b56
[ "Apache-2.0" ]
null
null
null
bin/spectatord_main.cc
copperlight/spectatord
dfc0ec35bc027d090f1d71a3f067fe164ef84b56
[ "Apache-2.0" ]
null
null
null
bin/spectatord_main.cc
copperlight/spectatord
dfc0ec35bc027d090f1d71a3f067fe164ef84b56
[ "Apache-2.0" ]
null
null
null
#include "backward.hpp" #include "local.h" #include "util/logger.h" #include "spectatord.h" #include "spectator/registry.h" #include <cstdlib> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/time/time.h" #include <fmt/ranges.h> auto GetSpectatorConfig() -> std::unique_ptr<spectator::Config>; using spectatord::GetLogger; using spectatord::Logger; struct PortNumber { explicit PortNumber(int p = 0) : port(p) {} int port; // Valid range is [1..65535] }; // Returns a textual flag value corresponding to the PortNumber `p`. auto AbslUnparseFlag(PortNumber p) -> std::string { // Delegate to the usual unparsing for int. return absl::UnparseFlag(p.port); } // Parses a PortNumber from the command line flag value `text`. // Returns true and sets `*p` on success; returns false and sets `*error` // on failure. auto AbslParseFlag(absl::string_view text, PortNumber* p, std::string* error) -> bool { // Convert from text to int using the int-flag parser. if (!absl::ParseFlag(text, &p->port, error)) { return false; } if (p->port < 1 || p->port > 65535) { *error = "not in range [1,65535]"; return false; } return true; } ABSL_FLAG(PortNumber, port, PortNumber(1234), "Port number for the UDP socket."); ABSL_FLAG(bool, enable_statsd, false, "Enable statsd support."); ABSL_FLAG(PortNumber, statsd_port, PortNumber(8125), "Port number for the statsd socket."); ABSL_FLAG(bool, enable_socket, true, "Enable UNIX domain socket support."); ABSL_FLAG(std::string, socket_path, "/run/spectatord/spectatord.unix", "Path to the UNIX domain socket."); ABSL_FLAG(absl::Duration, meter_ttl, absl::Minutes(15), "Meter TTL: expire meters after this period of inactivity."); ABSL_FLAG(size_t, age_gauge_limit, 1000, "The maximum number of age gauges that may be reported by this process."); ABSL_FLAG(std::string, common_tags, "", "Common tags: nf.app=app,nf.cluster=cluster. Override the default common " "tags. If empty, then spectatord will use the default set. " "This flag should only be used by experts who understand the risks."); ABSL_FLAG(bool, verbose, false, "Use verbose logging."); ABSL_FLAG(bool, verbose_http, false, "Output debug info for HTTP requests."); ABSL_FLAG(bool, debug, false, "Debug spectatord. All values will be sent to a dev aggregator and " "dropped."); auto main(int argc, char** argv) -> int { auto logger = Logger(); auto signals = backward::SignalHandling::make_default_signals(); // default signals with the exception of SIGABRT signals.erase(std::remove(signals.begin(), signals.end(), SIGABRT), signals.end()); backward::SignalHandling sh{signals}; absl::SetProgramUsageMessage( "A daemon that listens for metrics and reports them to Atlas."); absl::ParseCommandLine(argc, argv); auto cfg = GetSpectatorConfig(); if (absl::GetFlag(FLAGS_debug)) { cfg->uri = "http://atlas-aggr-dev.us-east-1.ieptest.netflix.net/api/v4/update"; } if (absl::GetFlag(FLAGS_verbose_http)) { cfg->verbose_http = true; } cfg->meter_ttl = absl::GetFlag(FLAGS_meter_ttl); cfg->age_gauge_limit = absl::GetFlag(FLAGS_age_gauge_limit); auto spectator_logger = GetLogger("spectator"); if (absl::GetFlag(FLAGS_verbose)) { logger->set_level(spdlog::level::trace); spectator_logger->set_level(spdlog::level::trace); } else { logger->set_level(spdlog::level::info); spectator_logger->set_level(spdlog::level::info); } auto maybe_common_tags = absl::GetFlag(FLAGS_common_tags); if (!maybe_common_tags.empty()) { std::map<std::string, std::string> common_tags; for (std::string_view sp : absl::StrSplit(maybe_common_tags, ',')) { std::vector<std::string> kv = absl::StrSplit(sp, absl::MaxSplits('=', 1)); if (kv.size() != 2 || kv.at(0).empty() || kv.at(1).empty()) { logger->error("Invalid common tags specified: {}", maybe_common_tags); exit(EXIT_FAILURE); } common_tags[kv.at(0)] = kv.at(1); } logger->info("Using common tags: {}", common_tags); cfg->common_tags = std::move(common_tags); } if (!sh.loaded()) { logger->info("Unable to load signal handling for stacktraces"); } spectator::Registry registry{std::move(cfg), std::move(spectator_logger)}; registry.Start(); std::optional<std::string> socket_path; if (absl::GetFlag(FLAGS_enable_socket)) { socket_path = absl::GetFlag(FLAGS_socket_path); } std::optional<int> statsd_port; if (absl::GetFlag(FLAGS_enable_statsd)) { statsd_port = absl::GetFlag(FLAGS_statsd_port).port; } spectatord::Server server{absl::GetFlag(FLAGS_port).port, statsd_port, socket_path, &registry}; server.Start(); return 0; }
35.099291
84
0.680946
[ "vector" ]
2b9dcce1fbfad46f42dc9a2411df4799d1e55813
11,553
cpp
C++
NYP_Framework_Week08_SOLUTION/Common/Source/RenderHelper.cpp
KianMarvi/Assignment
8133acec4dd65bc49316aec8deb3961035bdef27
[ "MIT" ]
null
null
null
NYP_Framework_Week08_SOLUTION/Common/Source/RenderHelper.cpp
KianMarvi/Assignment
8133acec4dd65bc49316aec8deb3961035bdef27
[ "MIT" ]
8
2019-12-29T17:17:00.000Z
2020-02-07T08:08:01.000Z
NYP_Framework_Week08_SOLUTION/Common/Source/RenderHelper.cpp
KianMarvi/Assignment
8133acec4dd65bc49316aec8deb3961035bdef27
[ "MIT" ]
null
null
null
#include "RenderHelper.h" #include "Mesh.h" #include "GraphicsManager.h" #include "ShaderProgram.h" #include "MatrixStack.h" bool RenderHelper::bLightEnable = false; bool RenderHelper::bColorTextureEnabled = false; bool RenderHelper::bColorTexture = false; bool RenderHelper::bTextEnabled = false; /** * Pre Render Mesh to setup the shaders before rendering a mesh without light */ void RenderHelper::PreRenderMesh(const bool bLightEnable, const bool bColorTextureEnabled, const bool bColorTexture, const bool bTextEnabled) { // Get current shader program ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); // Enable / Disable lighting stuff RenderHelper::bLightEnable = bLightEnable; if (bLightEnable) currProg->UpdateInt("lightEnabled", 1); else currProg->UpdateInt("lightEnabled", 0); // Enable / Disable colour texture enabled RenderHelper::bColorTextureEnabled = bColorTextureEnabled; if (bColorTextureEnabled) currProg->UpdateInt("colorTextureEnabled", 1); else currProg->UpdateInt("colorTextureEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTexture = bColorTexture; if (bColorTexture) currProg->UpdateInt("colorTexture", 1); else currProg->UpdateInt("colorTexture", 0); // Enable / Disable text display RenderHelper::bTextEnabled = bTextEnabled; if (bColorTexture) currProg->UpdateInt("textEnabled", 1); else currProg->UpdateInt("textEnabled", 0); } /** * Render Mesh to render a mesh without light */ void RenderHelper::RenderMesh(Mesh* _mesh) { // Get all our transform matrices & update shader Mtx44 MVP; MVP = GraphicsManager::GetInstance()->GetProjectionMatrix() * GraphicsManager::GetInstance()->GetViewMatrix() * GraphicsManager::GetInstance()->GetModelStack().Top(); ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); currProg->UpdateMatrix44("MVP", &MVP.a[0]); // Update textures first if available if (_mesh->textureID > 0) { // if (RenderHelper::bColorTextureEnabled) // currProg->UpdateInt("colorTextureEnabled", 1); GraphicsManager::GetInstance()->UpdateTexture(0, _mesh->textureID); // if (RenderHelper::bColorTexture) // currProg->UpdateInt("colorTexture", 0); } else { if (bColorTextureEnabled) { currProg->UpdateInt("colorTextureEnabled", 0); } } // Do actual rendering _mesh->Render(); // Unbind texture for safety (in case next render call uses it by accident) if (_mesh->textureID > 0) { GraphicsManager::GetInstance()->UnbindTexture(0); } else { if (bColorTextureEnabled) { currProg->UpdateInt("colorTextureEnabled", 1); } } } /** * Post Render Mesh to setup the shaders after rendering a mesh without light */ void RenderHelper::PostRenderMesh(const bool bLightEnable, const bool bColorTextureEnabled, const bool bColorTexture, const bool bTextEnabled) { // Get current shader program ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); // Enable / Disable lighting stuff RenderHelper::bLightEnable = bLightEnable; if (bLightEnable) currProg->UpdateInt("lightEnabled", 1); else currProg->UpdateInt("lightEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTextureEnabled = bColorTextureEnabled; if (bColorTextureEnabled) currProg->UpdateInt("colorTextureEnabled", 1); else currProg->UpdateInt("colorTextureEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTexture = bColorTexture; if (bColorTexture) currProg->UpdateInt("colorTexture", 1); else currProg->UpdateInt("colorTexture", 0); // Enable / Disable text display RenderHelper::bTextEnabled = bTextEnabled; if (bColorTexture) currProg->UpdateInt("textEnabled", 1); else currProg->UpdateInt("textEnabled", 0); } /** * Pre Render Mesh to setup the shaders before rendering a mesh with light */ void RenderHelper::PreRenderMeshWithLight(const bool bLightEnable, const bool bColorTextureEnabled, const bool bColorTexture, const bool bTextEnabled) { // Get current shader program ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); // Enable / Disable lighting stuff if (bLightEnable) currProg->UpdateInt("lightEnabled", 1); else currProg->UpdateInt("lightEnabled", 0); // Enable / Disable colour texture if (bColorTextureEnabled) currProg->UpdateInt("colorTextureEnabled", 1); else currProg->UpdateInt("colorTextureEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTexture = bColorTexture; if (bColorTexture) currProg->UpdateInt("colorTexture", 1); else currProg->UpdateInt("colorTexture", 0); // Enable / Disable text display RenderHelper::bTextEnabled = bTextEnabled; if (bColorTexture) currProg->UpdateInt("textEnabled", 1); else currProg->UpdateInt("textEnabled", 0); } /** * Render Mesh to render a mesh with light */ void RenderHelper::RenderMeshWithLight(Mesh* _mesh) { // Get all our transform matrices & update shader Mtx44 MVP, modelView, modelView_inverse_transpose; MVP = GraphicsManager::GetInstance()->GetProjectionMatrix() * GraphicsManager::GetInstance()->GetViewMatrix() * GraphicsManager::GetInstance()->GetModelStack().Top(); ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); currProg->UpdateMatrix44("MVP", &MVP.a[0]); // Update light stuff //currProg->UpdateInt("lightEnabled", 1); modelView = GraphicsManager::GetInstance()->GetViewMatrix() * GraphicsManager::GetInstance()->GetModelStack().Top(); currProg->UpdateMatrix44("MV", &modelView.a[0]); modelView_inverse_transpose = modelView.GetInverse().GetTranspose(); currProg->UpdateMatrix44("MV_inverse_transpose", &modelView.a[0]); //load material currProg->UpdateVector3("material.kAmbient", &_mesh->material.kAmbient.r); currProg->UpdateVector3("material.kDiffuse", &_mesh->material.kDiffuse.r); currProg->UpdateVector3("material.kSpecular", &_mesh->material.kSpecular.r); currProg->UpdateFloat("material.kShininess", _mesh->material.kShininess); // Update textures first if available if (_mesh->textureID > 0) { // currProg->UpdateInt("colorTextureEnabled", 1); GraphicsManager::GetInstance()->UpdateTexture(0, _mesh->textureID); // currProg->UpdateInt("colorTexture", 0); } else { if (bColorTextureEnabled) { currProg->UpdateInt("colorTextureEnabled", 0); } } // Do actual rendering _mesh->Render(); // Unbind texture for safety (in case next render call uses it by accident) if (_mesh->textureID > 0) { GraphicsManager::GetInstance()->UnbindTexture(0); } else { if (bColorTextureEnabled) { currProg->UpdateInt("colorTextureEnabled", 1); } } } /** * Post Render Mesh to setup the shaders after rendering a mesh with light */ void RenderHelper::PostRenderMeshWithLight(const bool bLightEnable, const bool bColorTextureEnabled, const bool bColorTexture, const bool bTextEnabled) { // Get current shader program ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); // Enable / Disable lighting stuff if (bLightEnable) currProg->UpdateInt("lightEnabled", 1); else currProg->UpdateInt("lightEnabled", 0); // Enable / Disable colour texture if (bColorTextureEnabled) currProg->UpdateInt("colorTextureEnabled", 1); else currProg->UpdateInt("colorTextureEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTexture = bColorTexture; if (bColorTexture) currProg->UpdateInt("colorTexture", 1); else currProg->UpdateInt("colorTexture", 0); // Enable / Disable text display RenderHelper::bTextEnabled = bTextEnabled; if (bColorTexture) currProg->UpdateInt("textEnabled", 1); else currProg->UpdateInt("textEnabled", 0); } // Pre Render Text to setup the shaders before rendering text void RenderHelper::PreRenderText(const bool bLightEnable, const bool bColorTextureEnabled, const bool bColorTexture, const bool bTextEnabled) { // Get current shader program ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); // Enable / Disable lighting stuff RenderHelper::bLightEnable = bLightEnable; if (bLightEnable) currProg->UpdateInt("lightEnabled", 1); else currProg->UpdateInt("lightEnabled", 0); // Enable / Disable colour texture enabled RenderHelper::bColorTextureEnabled = bColorTextureEnabled; if (bColorTextureEnabled) currProg->UpdateInt("colorTextureEnabled", 1); else currProg->UpdateInt("colorTextureEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTexture = bColorTexture; if (bColorTexture) currProg->UpdateInt("colorTexture", 1); else currProg->UpdateInt("colorTexture", 0); // Enable / Disable text display RenderHelper::bTextEnabled = bTextEnabled; if (bColorTexture) currProg->UpdateInt("textEnabled", 1); else currProg->UpdateInt("textEnabled", 0); } /** * Setup the shaders before rendering a text */ void RenderHelper::RenderText(Mesh* _mesh, const std::string& _text, Color _color) { // Trivial Rejection : Unable to render without mesh or texture if (!_mesh || _mesh->textureID <= 0) return; ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); currProg->UpdateInt("textEnabled", 1); currProg->UpdateVector3("textColor", &_color.r); //currProg->UpdateInt("lightEnabled", 0); if (_mesh->textureID > 0) { //currProg->UpdateInt("colorTextureEnabled", 1); GraphicsManager::GetInstance()->UpdateTexture(0, _mesh->textureID); //currProg->UpdateInt("colorTexture", 0); } else { if (bColorTextureEnabled) { currProg->UpdateInt("colorTextureEnabled", 1); } } for (unsigned i = 0; i < _text.length(); ++i) { Mtx44 characterSpacing, MVP; //characterSpacing.SetToTranslation((i+0.5f) * 1.0f, 0, 0); // 1.0f is the spacing of each character, you may change this value characterSpacing.SetToTranslation((float)(1 + (int)i), 0.0f, 0.0f); // 1.0f is the spacing of each character, you may change this value MVP = GraphicsManager::GetInstance()->GetProjectionMatrix() * GraphicsManager::GetInstance()->GetViewMatrix() * GraphicsManager::GetInstance()->GetModelStack().Top() * characterSpacing; currProg->UpdateMatrix44("MVP", &MVP.a[0]); _mesh->Render((unsigned)_text[i] * 6, 6); } if (_mesh->textureID > 0) { GraphicsManager::GetInstance()->UnbindTexture(0); } else { if (bColorTextureEnabled) { currProg->UpdateInt("colorTextureEnabled", 0); } } currProg->UpdateInt("textEnabled", 0); } // Post Render Text to setup the shaders before rendering text void RenderHelper::PostRenderText(const bool bLightEnable, const bool bColorTextureEnabled, const bool bColorTexture, const bool bTextEnabled) { // Get current shader program ShaderProgram* currProg = GraphicsManager::GetInstance()->GetActiveShader(); // Enable / Disable lighting stuff RenderHelper::bLightEnable = bLightEnable; if (bLightEnable) currProg->UpdateInt("lightEnabled", 1); else currProg->UpdateInt("lightEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTextureEnabled = bColorTextureEnabled; if (bColorTextureEnabled) currProg->UpdateInt("colorTextureEnabled", 1); else currProg->UpdateInt("colorTextureEnabled", 0); // Enable / Disable colour texture RenderHelper::bColorTexture = bColorTexture; if (bColorTexture) currProg->UpdateInt("colorTexture", 1); else currProg->UpdateInt("colorTexture", 0); // Enable / Disable text display RenderHelper::bTextEnabled = bTextEnabled; if (bColorTexture) currProg->UpdateInt("textEnabled", 1); else currProg->UpdateInt("textEnabled", 0); }
30.164491
187
0.742578
[ "mesh", "render", "transform" ]