hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f845f3416589d1d48c63c61cae435a1759886430
1,983
cpp
C++
test/xsimd_hyperbolic_test.cpp
ukoethe/xsimd
c15e4da30d6777863d994750d4c3a61b32f2de95
[ "BSD-3-Clause" ]
null
null
null
test/xsimd_hyperbolic_test.cpp
ukoethe/xsimd
c15e4da30d6777863d994750d4c3a61b32f2de95
[ "BSD-3-Clause" ]
null
null
null
test/xsimd_hyperbolic_test.cpp
ukoethe/xsimd
c15e4da30d6777863d994750d4c3a61b32f2de95
[ "BSD-3-Clause" ]
1
2020-08-19T01:15:47.000Z
2020-08-19T01:15:47.000Z
/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include <fstream> #include <iostream> #include "gtest/gtest.h" #include "xsimd/math/xsimd_hyperbolic.hpp" #include "xsimd/memory/xsimd_aligned_allocator.hpp" #include "xsimd/types/xsimd_types_include.hpp" #include "xsimd_hyperbolic_test.hpp" namespace xsimd { template <class T, size_t N, size_t A> bool test_hyperbolic(std::ostream& out, const std::string& name) { simd_hyperbolic_tester<T, N, A> tester(name); return test_simd_hyperbolic(out, tester); } } #if XSIMD_X86_INSTR_SET >= XSIMD_X86_SSE2_VERSION TEST(xsimd, sse_float_hyperbolic) { std::ofstream out("log/sse_float_hyperbolic.log", std::ios_base::out); bool res = xsimd::test_hyperbolic<float, 4, 16>(out, "sse float"); EXPECT_TRUE(res); } TEST(xsimd, sse_double_hyperbolic) { std::ofstream out("log/sse_double_hyperbolic.log", std::ios_base::out); bool res = xsimd::test_hyperbolic<double, 2, 16>(out, "sse double"); EXPECT_TRUE(res); } #endif #if XSIMD_X86_INSTR_SET >= XSIMD_X86_AVX_VERSION TEST(xsimd, avx_float_hyperbolic) { std::ofstream out("log/avx_float_hyperbolic.log", std::ios_base::out); bool res = xsimd::test_hyperbolic<float, 8, 32>(out, "avx float"); EXPECT_TRUE(res); } TEST(xsimd, avx_double_hyperbolic) { std::ofstream out("log/avx_double_hyperbolic.log", std::ios_base::out); bool res = xsimd::test_hyperbolic<double, 4, 32>(out, "avx double"); EXPECT_TRUE(res); } #endif
33.610169
77
0.595058
ukoethe
f848bacda619b0fafbb669632a9720d64f2df744
1,677
cpp
C++
modelConvert/source/main.cpp
sormo/simpleSDL
79a830a013f911c4670c86ccf68bd068a887670d
[ "MIT" ]
null
null
null
modelConvert/source/main.cpp
sormo/simpleSDL
79a830a013f911c4670c86ccf68bd068a887670d
[ "MIT" ]
null
null
null
modelConvert/source/main.cpp
sormo/simpleSDL
79a830a013f911c4670c86ccf68bd068a887670d
[ "MIT" ]
null
null
null
#include "ModelLoader.h" #include "ModelChecker.h" #include <iostream> #include <filesystem> #include <fstream> #include <string> bool SaveModel(const ModelData::ModelT * model, const std::string & path) { flatbuffers::FlatBufferBuilder builder(1024); auto offset = ModelData::CreateModel(builder, model); builder.Finish(offset); std::ofstream result(path.c_str(), std::ios_base::binary); if (!result) { std::cout << "Error opening result file " << path.c_str() << "\n\n"; return false; } result.write((const char*)builder.GetBufferPointer(), builder.GetSize()); std::wcout << L"Success: " << path.c_str() << L"\n\n"; return true; } int main(int32_t argc, char * argv[]) { for (int32_t i = 1; i < argc; ++i) { std::cout << "Processing: " << argv[i] << std::endl; std::filesystem::path path(argv[i]); if (path.extension() == ".model") { std::ifstream file(argv[i], std::ios::binary | std::ios::ate); size_t fileSize = (size_t)file.tellg(); file.seekg(std::ios::beg); std::vector<char> fileData(fileSize); file.read(fileData.data(), fileSize); auto data = ModelData::UnPackModel(fileData.data()); if (CheckModel(*data)) SaveModel(&(*data), path.string()); } else { auto data = LoadModel(argv[i]); if (!data) { std::cout << "Error loading!\n\n"; continue; } path.replace_extension("model"); SaveModel(&(*data), path.string()); } } }
26.619048
77
0.539058
sormo
f849d5baf154313e3e0f62b8751f8f8cb711d0b5
6,841
cpp
C++
caffe/src/caffe/test/test_clustering_loss_layer.cpp
blitzingeagle/DeepEmbeddedClustering
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
[ "MIT" ]
408
2015-11-19T21:50:16.000Z
2022-03-22T08:17:26.000Z
caffe/src/caffe/test/test_clustering_loss_layer.cpp
blitzingeagle/DeepEmbeddedClustering
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
[ "MIT" ]
29
2016-05-18T10:24:00.000Z
2021-09-26T21:43:46.000Z
caffe/src/caffe/test/test_clustering_loss_layer.cpp
blitzingeagle/DeepEmbeddedClustering
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
[ "MIT" ]
152
2015-11-24T17:30:36.000Z
2021-11-11T07:17:03.000Z
#include <cmath> #include <cstdlib> #include <cstring> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { const int dim = 32; template <typename TypeParam> class ClusteringLossLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: ClusteringLossLayerTest() : blob_bottom_data_(new Blob<Dtype>(dim, 1, 1, dim)), blob_bottom_label_(new Blob<Dtype>(dim, 1, 1, 1)), blob_top_loss_(new Blob<Dtype>()), blob_top_std_(new Blob<Dtype>()), blob_top_ind_(new Blob<Dtype>()), blob_top_dist_(new Blob<Dtype>()) { // fill the values FillerParameter filler_param; filler_param.set_value(0.0005); ConstantFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_data_); Dtype *data = this->blob_bottom_data_->mutable_cpu_data(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { data[i*dim + j] *= j; } data[i*dim + i] += Dtype(1.0); } Dtype *cpu_data = this->blob_bottom_label_->mutable_cpu_data(); for (int i = 0; i < dim; i++) { if (i < dim/2) cpu_data[i] = Dtype(1); else cpu_data[i] = Dtype(0); } blob_bottom_vec_.push_back(blob_bottom_data_); blob_bottom_vec_.push_back(blob_bottom_label_); blob_top_vec_.push_back(blob_top_loss_); blob_top_vec_.push_back(blob_top_std_); blob_top_vec_.push_back(blob_top_ind_); blob_top_vec_.push_back(blob_top_dist_); } virtual ~ClusteringLossLayerTest() { delete blob_bottom_data_; delete blob_bottom_label_; delete blob_top_loss_; delete blob_top_ind_; delete blob_top_std_; delete blob_top_dist_; } void TestForward() { // Get the loss without a specified objective weight -- should be // equivalent to explicitly specifiying a weight of 1. LayerParameter layer_param; layer_param.mutable_clustering_loss_param()->set_margin(10); layer_param.mutable_clustering_loss_param()->set_num_center(dim); ClusteringLossLayer<Dtype> layer_weight_1(layer_param); layer_weight_1.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_); layer_weight_1.Forward(this->blob_bottom_vec_, &this->blob_top_vec_); FillerParameter filler_param; filler_param.set_value(-0.0005); ConstantFiller<Dtype> filler2(filler_param); filler2.Fill(layer_weight_1.blobs()[0].get()); Dtype *center = layer_weight_1.blobs()[0]->mutable_cpu_data(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { center[j*dim + i] *= j; } center[i*dim + i] += Dtype(1.0); } const Dtype loss_weight_1 = layer_weight_1.Forward(this->blob_bottom_vec_, &this->blob_top_vec_); // Get the loss again with a different objective weight; check that it is // scaled appropriately. const Dtype kLossWeight = 3.7; LayerParameter layer_param2; layer_param2.mutable_clustering_loss_param()->set_margin(10); layer_param2.mutable_clustering_loss_param()->set_num_center(dim); layer_param2.add_loss_weight(kLossWeight); ClusteringLossLayer<Dtype> layer_weight_2(layer_param2); layer_weight_2.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_); layer_weight_2.Forward(this->blob_bottom_vec_, &this->blob_top_vec_); filler2.Fill(layer_weight_2.blobs()[0].get()); center = layer_weight_2.blobs()[0]->mutable_cpu_data(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { center[j*dim + i] *= j; } center[i*dim + i] += Dtype(1.0); } const Dtype loss_weight_2 = layer_weight_2.Forward(this->blob_bottom_vec_, &this->blob_top_vec_); const Dtype kErrorMargin = 1e-5; EXPECT_NEAR(loss_weight_1 * kLossWeight, loss_weight_2, kErrorMargin); // Make sure the loss is non-trivial. const Dtype kNonTrivialAbsThresh = 1e-1; EXPECT_GE(fabs(loss_weight_1), kNonTrivialAbsThresh); int m = dim, n = layer_param.clustering_loss_param().num_center(), p = dim; Blob<Dtype> *distance = layer_weight_1.distance(); const Dtype *cpu_data = blob_bottom_data_->cpu_data(); const Dtype *cpu_dist = distance->cpu_data(); const Dtype *cpu_center = layer_weight_1.blobs()[0]->cpu_data(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { Dtype acc = Dtype(0); for (int k = 0; k < p; ++k) { acc += (cpu_data[i*p + k] - cpu_center[k*n + j])*(cpu_data[i*p + k] - cpu_center[k*n + j]); } EXPECT_NEAR(std::sqrt(acc/p), cpu_dist[i*n + j], kErrorMargin); } } /* const Dtype *cpu_ind = blob_top_ind_->cpu_data(); for (int i = 0; i < m; i++) EXPECT_EQ(cpu_ind[i], i); EXPECT_NEAR(blob_top_std_->cpu_data()[0], Dtype(0), kErrorMargin);*/ } Blob<Dtype>* const blob_bottom_data_; Blob<Dtype>* const blob_bottom_label_; Blob<Dtype>* const blob_top_loss_; Blob<Dtype>* const blob_top_std_; Blob<Dtype>* const blob_top_ind_; Blob<Dtype>* const blob_top_dist_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(ClusteringLossLayerTest, TestDtypesAndDevices); TYPED_TEST(ClusteringLossLayerTest, TestForward) { this->TestForward(); } TYPED_TEST(ClusteringLossLayerTest, TestGradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; const Dtype kLossWeight = 1.0; layer_param.add_loss_weight(kLossWeight); layer_param.mutable_clustering_loss_param()->set_margin(10); layer_param.mutable_clustering_loss_param()->set_num_center(dim); layer_param.mutable_clustering_loss_param()->set_lambda(0.5); ClusteringLossLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, &this->blob_top_vec_); FillerParameter filler_param; filler_param.set_value(0.0005); ConstantFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_data_); filler_param.set_value(-0.0005); ConstantFiller<Dtype> filler2(filler_param); filler2.Fill(layer.blobs()[0].get()); Dtype *center = layer.blobs()[0]->mutable_cpu_data(); Dtype *data = this->blob_bottom_data_->mutable_cpu_data(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { data[i*dim + j] *= j; center[j*dim + i] *= j; } center[i*dim + i] += Dtype(1.0); data[i*dim + i] += Dtype(1.0); } GradientChecker<Dtype> checker(1e-1, 1e-10, 1701); checker.CheckGradientSingle(&layer, &(this->blob_bottom_vec_), &(this->blob_top_vec_), 0, 0, 0); } } // namespace caffe
33.866337
101
0.679871
blitzingeagle
f84e69482e238d973f71a8aab1ed2faf5127deb6
9,654
cpp
C++
src/util/time.cpp
bridger-herman/OpenSpace
e3afd82c4700536a2221fc76f64fdc873c93e964
[ "MIT" ]
1
2019-10-27T12:42:40.000Z
2019-10-27T12:42:40.000Z
src/util/time.cpp
bridger-herman/OpenSpace
e3afd82c4700536a2221fc76f64fdc873c93e964
[ "MIT" ]
null
null
null
src/util/time.cpp
bridger-herman/OpenSpace
e3afd82c4700536a2221fc76f64fdc873c93e964
[ "MIT" ]
1
2020-04-29T01:34:22.000Z
2020-04-29T01:34:22.000Z
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2019 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <openspace/util/time.h> #include <openspace/scripting/scriptengine.h> #include <openspace/util/spicemanager.h> #include <openspace/util/syncbuffer.h> #include <openspace/util/timemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/misc/assert.h> #include <mutex> #include "time_lua.inl" namespace openspace { double Time::convertTime(const std::string& time) { ghoul_assert(!time.empty(), "timeString must not be empty"); return SpiceManager::ref().ephemerisTimeFromDate(time); } Time::Time(double secondsJ2000) : _time(secondsJ2000) {} Time Time::now() { Time now; time_t secondsSince1970; secondsSince1970 = time(nullptr); const time_t secondsInAYear = static_cast<time_t>(365.25 * 24 * 60 * 60); const double secondsSince2000 = static_cast<double>( secondsSince1970 - 30 * secondsInAYear ); now.setTime(secondsSince2000); return now; } void Time::setTime(double value) { _time = value; } double Time::j2000Seconds() const { return _time; } double Time::advanceTime(double delta) { _time += delta; return _time; } void Time::setTime(std::string time) { _time = SpiceManager::ref().ephemerisTimeFromDate(std::move(time)); } std::string Time::UTC() const { return SpiceManager::ref().dateFromEphemerisTime(_time); } std::string Time::ISO8601() const { std::string datetime = SpiceManager::ref().dateFromEphemerisTime(_time); const std::string& month = datetime.substr(5, 3); std::string MM; if (month == "JAN") { MM = "01"; } else if (month == "FEB") { MM = "02"; } else if (month == "MAR") { MM = "03"; } else if (month == "APR") { MM = "04"; } else if (month == "MAY") { MM = "05"; } else if (month == "JUN") { MM = "06"; } else if (month == "JUL") { MM = "07"; } else if (month == "AUG") { MM = "08"; } else if (month == "SEP") { MM = "09"; } else if (month == "OCT") { MM = "10"; } else if (month == "NOV") { MM = "11"; } else if (month == "DEC") { MM = "12"; } else { ghoul_assert(false, "Bad month"); } datetime.replace(4, 5, "-" + MM + "-"); return datetime; } scripting::LuaLibrary Time::luaLibrary() { return { "time", { { "setTime", &luascriptfunctions::time_setTime, {}, "{number, string}", "Sets the current simulation time to the " "specified value. If the parameter is a number, the value is the number " "of seconds past the J2000 epoch. If it is a string, it has to be a " "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS. " "Note: providing time zone using the Z format is not supported. UTC is " "assumed." }, { "setDeltaTime", &luascriptfunctions::time_setDeltaTime, {}, "number", "Sets the amount of simulation time that happens " "in one second of real time" }, { "deltaTime", &luascriptfunctions::time_deltaTime, {}, "", "Returns the amount of simulated time that passes in one " "second of real time" }, { "setPause", &luascriptfunctions::time_setPause, {}, "bool", "Pauses the simulation time or restores the delta time" }, { "togglePause", &luascriptfunctions::time_togglePause, {}, "", "Toggles the pause function, i.e. temporarily setting the delta time to 0" " and restoring it afterwards" }, { "interpolateTime", &luascriptfunctions::time_interpolateTime, {}, "{number, string} [, number]", "Sets the current simulation time to the " "specified value. If the parameter is a number, the value is the number " "of seconds past the J2000 epoch. If it is a string, it has to be a " "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS. " "Note: providing time zone using the Z format is not supported. UTC is " "assumed." }, { "interpolateTimeRelative", &luascriptfunctions::time_interpolateTimeRelative, {}, "number [, number]", "Increments the current simulation time " "by the specified number of seconds." }, { "interpolateDeltaTime", &luascriptfunctions::time_interpolateDeltaTime, {}, "number", "Sets the amount of simulation time that happens " "in one second of real time" }, { "interpolatePause", &luascriptfunctions::time_interpolatePause, {}, "bool", "Pauses the simulation time or restores the delta time" }, { "interpolateTogglePause", &luascriptfunctions::time_interpolateTogglePause, {}, "", "Toggles the pause function, i.e. temporarily setting the delta time to 0" " and restoring it afterwards" }, { "currentTime", &luascriptfunctions::time_currentTime, {}, "", "Returns the current time as the number of seconds since " "the J2000 epoch" }, { "UTC", &luascriptfunctions::time_currentTimeUTC, {}, "", "Returns the current time as an ISO 8601 date string " "(YYYY-MM-DDTHH:MN:SS)" }, { "currentWallTime", &luascriptfunctions::time_currentWallTime, {}, "", "Returns the current wall time as an ISO 8601 date string " "(YYYY-MM-DDTHH-MN-SS) in the UTC timezone" }, { "advancedTime", &luascriptfunctions::time_advancedTime, {}, "string or number, string or number", "Modifies the passed time (first argument) by the delta time (second " "argument). The first argument can either be an ISO 8601 date string or " "the number of seconds past the J2000 epoch. The second argument can " "either be a string of the form [-]XX(s,m,h,d,M,y] with (s)econds, " "(m)inutes, (h)ours, (d)ays, (M)onths, and (y)ears as units and an " "optional - sign to move backwards in time. If the second argument is a " "number, it is interpreted as a number of seconds. The return value is " "of the same type as the first argument." } } }; } } // namespace openspace
36.847328
90
0.480526
bridger-herman
f850ebcad2e04127a5937d7d506d9584d0348aed
15,526
hpp
C++
core/src/cogs/collections/avltree.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
5
2019-02-08T15:59:14.000Z
2022-01-22T19:12:33.000Z
core/src/cogs/collections/avltree.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
1
2019-12-03T03:11:34.000Z
2019-12-03T03:11:34.000Z
core/src/cogs/collections/avltree.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
null
null
null
// // Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC // // Status: Good #ifndef COGS_HEADER_COLLECTION_AVLTREE #define COGS_HEADER_COLLECTION_AVLTREE #include "cogs/collections/btree.hpp" #include "cogs/operators.hpp" #include "cogs/mem/ptr.hpp" namespace cogs { /// @defgroup BinaryTrees Binary Trees /// @{ /// @ingroup Collections /// @brief Binary Tree classes /// @} /// @ingroup BinaryTrees /// @brief Base classes for (intrusive) nodes of avltree. /// @tparam derived_t Derived type of this class. Allows links to be returned as references to the derived type without requiring a cast. /// If void is specified, links will point to avltree_node_t<void, ref_type, link_accessor>. Default: void /// @tparam ref_type Reference type to use for links. Default: ptr /// @tparam link_accessor Helper type providing functions to get and set links. Default: default_tlink_accessor<derived_t, ref_type> template <class derived_t = void, template <typename> class ref_type = ptr, class link_accessor = default_tlink_accessor<derived_t, ref_type> > class avltree_node_t : public tlink_t<derived_t, ref_type, link_accessor> { private: typedef avltree_node_t<derived_t, ref_type, link_accessor> this_t; typedef tlink_t<derived_t, ref_type, link_accessor> base_t; int m_factor; avltree_node_t(const this_t& t) = delete; this_t& operator=(const this_t& t) = delete; public: avltree_node_t() { } template <typename P, typename L, typename R> avltree_node_t(int f, P&& p, L&& l, R&& r) : base_t(std::forward<P>(p), std::forward<L>(l), std::forward<R>(r)), m_factor(f) { } avltree_node_t(this_t&& t) : base_t(std::move(t)), m_factor(t.m_factor) { } this_t& operator=(this_t&& t) { base_t::operator=(std::move(t)); m_factor = t.m_factor; return *this; } /// @brief Gets the AVL factor value of this node /// @return The AVL factor value of this node int get_factor() const { return m_factor; } /// @brief Sets the AVL factor value of this node /// @param f The value to set as the AVL factor of this node void set_factor(int f) { m_factor = f; } }; template <template <typename> class ref_type, class link_accessor> class avltree_node_t<void, ref_type, link_accessor> : public tlink_t<avltree_node_t<void, ref_type>, ref_type, link_accessor> { private: typedef avltree_node_t<void, ref_type, link_accessor> this_t; typedef tlink_t<avltree_node_t<void, ref_type>, ref_type, link_accessor> base_t; int m_factor; avltree_node_t(const this_t& t) = delete; this_t& operator=(const this_t& t) = delete; public: avltree_node_t() { } template <typename P, typename L, typename R> avltree_node_t(int f, P&& p, L&& l, R&& r) : base_t(std::forward<P>(p), std::forward<L>(l), std::forward<R>(r)), m_factor(f) { } avltree_node_t(this_t&& t) : base_t(std::move(t)), m_factor(t.m_factor) { } this_t& operator=(this_t&& t) { base_t::operator=(std::move(t)); m_factor = t.m_factor; return *this; } int get_factor() const { return m_factor; } void set_factor(int f) { m_factor = f; } }; /// @brief An alias to avltree_node_t<void,ptr> typedef avltree_node_t<void,ptr> avltree_node; /// @ingroup BinaryTrees /// @brief An intrusive AVL ("Adelson-Velsky-Landis") binary tree. /// /// derived_node_t must be derived from avltree_node_t, and include the equivalent of the following member function: /// @code{.cpp} /// const key_t& get_key() const; /// @endcode /// or: /// @code{.cpp} /// key_t get_key() const; /// @endcode /// @tparam key_t The key type to contain /// @tparam derived_node_t A class derived from the intrusive node base, avltree_node_t. /// @tparam comparator_t A static comparator class used to compare keys. Default: default_comparator /// @tparam ref_type Reference type to use for links. Default: ptr template <typename key_t, class derived_node_t, class comparator_t = default_comparator, template <typename> class ref_type = ptr> class avltree : public sorted_btree<key_t, derived_node_t, comparator_t, ref_type> { public: typedef key_t key_type; /// @brief Alias to this type. typedef avltree<key_t, derived_node_t, comparator_t, ref_type> this_t; /// @brief Alias to the node type. typedef derived_node_t node_t; /// @brief The node reference type typedef ref_type<node_t> ref_t; private: typedef sorted_btree<key_t, derived_node_t, comparator_t, ref_type> base_t; avltree(const this_t&) = delete; this_t& operator=(const this_t&) = delete; // rebalance balances and repaints the tree after an insert or remove. // // - When inserting, the inserted node is passed as n and will be at max depth (no children, // and factor should already be set to zero). parent and isRightChild are needed for // parity with removal (determined automatically by rebalance_after_insert()). // // - When removing a node, the node will always be at the bottom of the tree, and will have // 0 or 1 children. If there was a child moved into it's place, it is passed in n, otherwise // n is null. Since the tree was previously balanced, we know that n has no children and should // already have a zero factor. The parent of the removed node (and now of n, if present) is passed in parent. // isRightChild is passed in to indicate which side of the parent node the removed node had been on // (since it may be null now, and cannot be automatically determined). // template <bool isInsert> void rebalance(const ref_t& nIn, const ref_t& parentIn, bool isRightChildIn) { if (!parentIn) return; bool isRightChild = isRightChildIn; ref_t n = nIn; ref_t parent = parentIn; ref_t parentParent; ref_t child; typename ref_t::locked_t lockedRef; typename ref_t::locked_t lockedParent; typename ref_t::locked_t lockedChild; if (isInsert) // if (!!n) lockedRef = n; lockedParent = parent; parentParent = lockedParent->get_parent_link(); int childFactor = 0; int factor = 0; for (;;) { const int side_convert[2] = { -1, 1 }; const int parentFactor = lockedParent->get_factor(); const int side = side_convert[isRightChild ^ !isInsert]; const int nSide = -side; if (parentFactor == side) // If the parent has a factor that indicates it's lopsided to the other side. { int newFactor[2]; // index 0 is newFactor, index 1 is newParentFactor ref_t* localRoot; if (!isInsert) // figure out new n. When removing and rotating, we need to use the excess node on the other side as N. { n = lockedParent->get_child_link(!isRightChild); lockedRef = n; factor = lockedRef->get_factor(); } bool direction = (isInsert == isRightChild); if (factor == nSide) // If inverted factors, double rotate. { if (!isInsert) // Figure out new child, since we wont already know it when inserting. { child = lockedRef->get_child_link(isRightChild); lockedChild = child; childFactor = lockedChild->get_factor(); } //balancing_double_rotate(); // Fix up parents lockedChild->set_parent_link(parentParent); lockedRef->set_parent_link(child); lockedParent->set_parent_link(child); ref_t childChild1 = lockedChild->get_child_link(direction); if (!!childChild1) { typename ref_t::locked_t lockedChildChild1 = childChild1; lockedChildChild1->set_parent_link(n); } ref_t childChild2 = lockedChild->get_child_link(!direction); if (!!childChild2) { typename ref_t::locked_t lockedChildChild2 = childChild2; lockedChildChild2->set_parent_link(parent); } // fix up children lockedRef->set_child_link(!direction, childChild1); lockedParent->set_child_link(direction, childChild2); lockedChild->set_child_link(direction, n); lockedChild->set_child_link(!direction, parent); // fixup factors newFactor[0] = newFactor[1] = 0; if (!!childFactor) { lockedChild->set_factor(0); newFactor[(childFactor == side)] = -childFactor; } localRoot = &child; } else // single rotate { if (!isInsert) { child = lockedRef->get_child_link(direction); lockedChild = child; } //balancing_single_rotate(); // Fix up parents const ref_t& otherChild = lockedRef->get_child_link(!direction); lockedParent->set_parent_link(n); lockedRef->set_parent_link(parentParent); if (!!otherChild) { typename ref_t::locked_t lockedOtherChild = otherChild; lockedOtherChild->set_parent_link(parent); } // fix up children lockedParent->set_child_link(direction, otherChild); lockedRef->set_child_link(!direction, parent); // set n's child last, so as not to stomp on otherChild ref // fixup factors newFactor[0] = factor - side; newFactor[1] = -(newFactor[0]); localRoot = &n; } lockedRef->set_factor(newFactor[0]); lockedParent->set_factor(newFactor[1]); // tree parent fixup if (parent == get_root()) { set_root(*localRoot); break; } lockedParent = parentParent; // Moving lockedParentParent into lockedParent isRightChild = (lockedParent->get_right_link() == parent); lockedParent->set_child_link(isRightChild, *localRoot); if (isInsert) // If inserting, a single or double rotate means we won't need to pass anything up. break; if (parentFactor == newFactor[1]) break; // If removing, we only need to pass up valid values for parent (and lockedParent), and parentParent. N and child are computed parent = parentParent; parentParent = lockedParent->get_parent_link(); } else { int newParentFactor = parentFactor + side; lockedParent->set_factor(newParentFactor); if (parent == get_root()) break; if (isInsert) // If Inserting, and no need to rotate, we stop if just changed the factor TO 0. { if (newParentFactor == 0) //if (parentFactor == nSide) break; } else // If removing, we stop if we've change a factor FROM 0. { if (parentFactor == 0) // if (!parentFactor) break; } child = n; lockedChild = lockedRef; childFactor = factor; n = parent; lockedRef = lockedParent; factor = newParentFactor; parent = parentParent; lockedParent = parent; parentParent = lockedParent->get_parent_link(); isRightChild = (n == lockedParent->get_right_link()); } } } ref_t insert(const ref_t& n, sorted_btree_insert_mode insertMode, const ref_t& hint) { bool wasEmpty = is_empty(); typename ref_t::locked_t lockedRef = n; ref_t existing = base_t::insert(n, insertMode, hint); if (!!existing) { if (insertMode == sorted_btree_insert_mode::replace) { typename ref_t::locked_t lockedExisting = existing; lockedRef->set_factor(lockedExisting->get_factor()); } } else { lockedRef->set_factor(0); if (!wasEmpty) { ref_t parent = lockedRef->get_parent_link(); typename ref_t::locked_t lockedParent = parent; bool isRightChild = (n == lockedParent->get_right_link()); rebalance<true>(n, parent, isRightChild); } } return existing; } const ref_t& get_root() const { return base_t::get_root(); } void set_root(const ref_t& r) { base_t::set_root(r); } public: avltree() { } avltree(this_t&& t) : base_t(std::move(t)) { } this_t& operator=(this_t&& t) { base_t::operator=(std::move(t)); return *this; } /// @{ /// @brief Tests if the tree is empty /// @return True if the tree is empty bool is_empty() const { return base_t::is_empty(); } /// @} /// @{ /// @brief Clears the root, leftmost and rightmost values maintained by the tree. Does not delete any elements. void clear() { base_t::clear(); } /// @} /// @{ /// @brief Get the first in-order node /// @return The first in-order node const ref_t& get_first() const { return base_t::get_first(); } /// @} /// @{ /// @brief Get the last in-order node /// @return The last in-order node const ref_t& get_last() const { return base_t::get_last(); } /// @} /// @{ /// @brief Insert a node, allowing duplicates /// @param n Node to insert /// @param hint If set, must be the result of a prior call to one of the 'last_equal' or /// 'nearest_greater' find() functions passed the value being inserted. This is useful /// if additional work is needed before insert, only if an existing match is or is not found. /// @return A reference to an equal node in the case of collision, or an empty node if no collision. ref_t insert_multi(const ref_t& n, const ref_t& hint = ref_t()) { return insert(n, sorted_btree_insert_mode::multi, hint); } /// @} /// @{ /// @brief Insert a node, replacing a duplicate /// @param n Node to insert /// @param hint If set, must be the result of a prior call to one of the 'last_equal' or /// 'nearest_greater' find() functions passed the value being inserted. This is useful /// if additional work is needed before insert, only if an existing match is or is not found. /// @return A reference to the replaced node, or an empty node if no collision. ref_t insert_replace(const ref_t& n, const ref_t& hint = ref_t()) { return insert(n, sorted_btree_insert_mode::replace, hint); } /// @} /// @{ /// @brief Insert a node, if an equal node is not already present /// @param n Node to insert /// @param hint If set, must be the result of a prior call to one of the 'last_equal' or /// 'nearest_greater' find() functions passed the value being inserted. This is useful /// if additional work is needed before insert, only if an existing match is or is not found. /// @return A reference to an equal node in the case of collision, or an empty node if no collision. ref_t insert_unique(const ref_t& n, const ref_t& hint = ref_t()) { return insert(n, sorted_btree_insert_mode::unique, hint); } /// @} /// @{ /// @brief Remove a node void remove(const ref_t& n) { ref_t liftedChild; ref_t swappedWith; typename ref_t::locked_t lockedRef = n; const int factor = lockedRef->get_factor(); bool wasRightChild = base_t::balance_remove(n, swappedWith, liftedChild, (factor == 1)); if (!!get_root()) { for (;;) { ref_t parent = lockedRef->get_parent_link(); typename ref_t::locked_t lockedSwappedWith; if (!swappedWith) // If no swap occured, we know the removed node has 0 or 1 children. { // Go ahead and set its parent's factor accordingly, and enter rebalance one level up. if (!parent) // if the root is being removed, we know it's now empty, or has just 1 element. { if (!!liftedChild) // If just 1 element, set its factor to 0 and clear the parent { typename ref_t::locked_t lockedLiftedChild = liftedChild; lockedLiftedChild->set_factor(0); ref_t emptyRef; lockedLiftedChild->set_parent_link(emptyRef); } break; } } else { lockedSwappedWith = swappedWith; lockedSwappedWith->set_factor(factor); // If a swap occured, trade factors with it. } rebalance<false>(liftedChild, parent, wasRightChild); break; } } } /// @} /// @{ /// @brief Swaps the contents of this tree with another. /// @param wth The tree to swap with. void swap(this_t& wth) { base_t::swap(wth); } /// @} this_t exchange(this_t&& src) { this_t tmp(std::move(src)); swap(tmp); return tmp; } void exchange(this_t&& src, this_t& rtn) { rtn = std::move(src); swap(rtn); } }; } #endif
30.99002
143
0.682983
cogmine
f852a012513af28ca39177087d200ae341b4577a
4,204
cpp
C++
library/src/cpp/audio/audioengine.cpp
tommyettinger/libgdx-oboe
f74a166b8ac1e256e236035c485f15bbd048448e
[ "MIT" ]
36
2020-01-13T07:11:56.000Z
2022-01-04T16:55:18.000Z
library/src/cpp/audio/audioengine.cpp
tommyettinger/libgdx-oboe
f74a166b8ac1e256e236035c485f15bbd048448e
[ "MIT" ]
10
2020-04-01T05:57:31.000Z
2021-09-29T17:32:02.000Z
library/src/cpp/audio/audioengine.cpp
tommyettinger/libgdx-oboe
f74a166b8ac1e256e236035c485f15bbd048448e
[ "MIT" ]
8
2020-03-22T05:51:24.000Z
2021-12-30T01:26:01.000Z
#include "audioengine.hpp" #include "../utility/ptrptr.hpp" #include "../utility/log.hpp" #include "../utility/exception.hpp" #include <array> #include <algorithm> #include <iterator> #include <limits> #include <cassert> namespace { /// @note: message should contain {} inline bool check(oboe::Result result, std::string_view msg) { if (result != oboe::Result::OK) { throw_exception(msg, oboe::convertToText(result)); return false; } return true; } } audio_engine::audio_engine(mode mode, int8_t channels, int32_t sample_rate) : oboe::AudioStreamDataCallback() , oboe::AudioStreamErrorCallback() , m_mixer(std::make_unique<mixer>(1024, channels)) , m_channels(channels) , m_sample_rate(sample_rate) , m_payload_size(0) , m_volume(1) , m_rendering_flag(false) , m_is_playing(false) , m_mode(mode) { connect_to_device(); } audio_engine::~audio_engine() { stop(); check(m_stream->close(), "Error closing stream: {}"); } void audio_engine::connect_to_device() { // initialize Oboe audio stream oboe::AudioStreamBuilder builder; builder.setChannelCount(m_channels); builder.setSampleRate(m_sample_rate); if (m_mode == mode::async) { builder.setDataCallback(this); builder.setErrorCallback(this); } builder.setFormat(oboe::AudioFormat::I16); builder.setPerformanceMode(oboe::PerformanceMode::LowLatency); builder.setSharingMode(oboe::SharingMode::Exclusive); check(builder.openStream(ptrptr(m_stream)), "Error opening stream: {}"); m_payload_size = m_stream->getFramesPerBurst() * 2; m_stream->setBufferSizeInFrames(m_payload_size); m_mixer->resize_buffer(m_payload_size * m_channels); } void audio_engine::onErrorAfterClose(oboe::AudioStream *self, oboe::Result error) { if (error == oboe::Result::ErrorDisconnected) { info("Previous device disconnected. Trying to connect to a new one..."); connect_to_device(); if (m_is_playing) { resume(); } } } oboe::DataCallbackResult audio_engine::onAudioReady(oboe::AudioStream *self, void *audio_data, int32_t num_frames) { while (m_rendering_flag.test_and_set(std::memory_order_acquire)); auto stream = static_cast<int16_t *>(audio_data); m_mixer->render(stream, num_frames); m_rendering_flag.clear(std::memory_order_release); return oboe::DataCallbackResult::Continue; } void audio_engine::resume() { if (check(m_stream->requestStart(), "Error starting stream: {}")) { m_is_playing = true; } } void audio_engine::stop() { if (check(m_stream->requestStop(), "Error stopping stream: {}")) { m_is_playing = false; } } void audio_engine::play(const std::shared_ptr<renderable_audio> &audio) { android_assert(m_mode == mode::async, "playing sounds and music in blocking mode is not implemented."); m_mixer->play_audio(audio); } void audio_engine::play(const std::vector<int16_t> &pcm) { android_assert(m_mode == mode::blocking, "playing raw pcm in async mode is not implemented."); m_stream->write(pcm.data(), pcm.size() / m_channels, std::numeric_limits<int64_t>::max()); } void audio_engine::play(const std::vector<float> &pcm) { android_assert(m_mode == mode::blocking, "playing raw pcm in async mode is not implemented."); m_pcm_buffer.clear(); std::transform(pcm.cbegin(), pcm.cend(), std::back_inserter(m_pcm_buffer), [](const float &sample) { auto converted = sample * std::numeric_limits<int16_t>::max(); return static_cast<int16_t>(converted); }); m_stream->write(m_pcm_buffer.data(), m_pcm_buffer.size() / m_channels, std::numeric_limits<int64_t>::max()); } bool audio_engine::is_mono() const { return m_channels == 1; } void audio_engine::volume(float volume) { m_volume = std::max(std::min(volume, 1.0f), 0.0f); m_mixer->m_volume = m_volume; } int32_t audio_engine::payload_size() const { return m_payload_size * m_channels; }
33.102362
98
0.659372
tommyettinger
f8546e483ebebfcf996a663652145bea2317fb6d
14,533
cpp
C++
Python/esys/lsm/InteractionFieldSaverPrmsPy.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Python/esys/lsm/InteractionFieldSaverPrmsPy.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Python/esys/lsm/InteractionFieldSaverPrmsPy.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// #include <boost/version.hpp> #include <boost/python.hpp> #include "Python/esys/lsm/InteractionFieldSaverPrmsPy.h" namespace esys { namespace lsm { InteractionFieldSaverPrmsPy::InteractionFieldSaverPrmsPy( const std::string &interactionName, const std::string &fieldName, const std::string &fileName, const std::string &fileFormat, int beginTimeStep, int endTimeStep, int timeStepIncr ) : FieldSaverPrmsPy( fieldName, fileName, fileFormat, beginTimeStep, endTimeStep, timeStepIncr ), m_interactionName(interactionName) { } InteractionScalarFieldSaverPrmsPy::InteractionScalarFieldSaverPrmsPy( const std::string &interactionName, const std::string &fieldName, const std::string &fileName, const std::string &fileFormat, int beginTimeStep, int endTimeStep, int timeStepIncr ) : InteractionFieldSaverPrmsPy( interactionName, fieldName, fileName, fileFormat, beginTimeStep, endTimeStep, timeStepIncr ) { } CheckedInteractionScalarFieldSaverPrmsPy::CheckedInteractionScalarFieldSaverPrmsPy( const std::string &interactionName, const std::string &fieldName, const std::string &fileName, const std::string &fileFormat, int beginTimeStep, int endTimeStep, int timeStepIncr ) : InteractionFieldSaverPrmsPy( interactionName, fieldName, fileName, fileFormat, beginTimeStep, endTimeStep, timeStepIncr ) { } TaggedInteractionScalarFieldSaverPrmsPy::TaggedInteractionScalarFieldSaverPrmsPy( const std::string &interactionName, const std::string &fieldName, const std::string &fileName, const std::string &fileFormat, int beginTimeStep, int endTimeStep, int timeStepIncr, int tag, int mask ) : InteractionScalarFieldSaverPrmsPy( interactionName, fieldName, fileName, fileFormat, beginTimeStep, endTimeStep, timeStepIncr ) { m_tag=tag; m_mask=mask; } InteractionVectorFieldSaverPrmsPy::InteractionVectorFieldSaverPrmsPy( const std::string &interactionName, const std::string &fieldName, const std::string &fileName, const std::string &fileFormat, int beginTimeStep, int endTimeStep, int timeStepIncr ) : InteractionFieldSaverPrmsPy( interactionName, fieldName, fileName, fileFormat, beginTimeStep, endTimeStep, timeStepIncr ) { } CheckedInteractionVectorFieldSaverPrmsPy::CheckedInteractionVectorFieldSaverPrmsPy( const std::string &interactionName, const std::string &fieldName, const std::string &fileName, const std::string &fileFormat, int beginTimeStep, int endTimeStep, int timeStepIncr ) : InteractionFieldSaverPrmsPy( interactionName, fieldName, fileName, fileFormat, beginTimeStep, endTimeStep, timeStepIncr ) { } using boost::python::arg; void exportInteractionFieldSaverPrms() { // Disable autogeneration of C++ signatures (Boost 1.34.0 and higher) // for Epydoc which stumbles over indentation in the automatically generated strings. boost::python::docstring_options no_autogen(true,false); boost::python::class_< InteractionFieldSaverPrmsPy, boost::python::bases<FieldSaverPrmsPy> >( "InteractionFieldSaverPrms", "Base class describing parameters for saving interaction-data to" " file.", boost::python::init< const std::string &, const std::string &, const std::string &, const std::string &, int, int, int >( ( arg("interactionName"), arg("fieldName"), arg("fileName"), arg("fileFormat"), arg("beginTimeStep"), arg("endTimeStep"), arg("timeStepIncr") ), "Base class for interaction field savers\n" "@type interactionName: string\n" "@kwarg interactionName: Name of the interaction group for" " which data are saved\n" "@type fieldName: string\n" "@kwarg fieldName: Name of the data field\n" "@type fileName: string\n" "@kwarg fileName: Name of the file where data are saved\n" "@type fileFormat: string\n" "@kwarg fileFormat: Format of the data\n" "@type beginTimeStep: int\n" "@kwarg beginTimeStep: start saving data at this time step\n" "@type endTimeStep: int\n" "@kwarg endTimeStep: finish saving data at this time step\n" "@type timeStepIncr: int\n" "@kwarg timeStepIncr: save data every timeStepIncr time steps\n" ) ) .def( "getInteractionName", &InteractionFieldSaverPrmsPy::getInteractionName, boost::python::return_value_policy< boost::python::copy_const_reference >(), "Returns the name of the interaction associated with these saver parameters.\n" "@rtype: string\n" "@return: Interaction name." ) ; boost::python::class_< InteractionScalarFieldSaverPrmsPy, boost::python::bases<InteractionFieldSaverPrmsPy> >( "InteractionScalarFieldSaverPrms", "Parameters for saving scalar interaction-data to file.", boost::python::init< const std::string &, const std::string &, const std::string &, const std::string &, int, int, int >( ( arg("interactionName"), arg("fieldName"), arg("fileName"), arg("fileFormat"), arg("beginTimeStep"), arg("endTimeStep"), arg("timeStepIncr") ), "Defines interaction scalar field saver parameters\n" "@type interactionName: string\n" "@kwarg interactionName: Name of the interaction group for" " which data are saved\n" "@type fieldName: string\n" "@kwarg fieldName: Name of the data field, e.g. 'e_pot_normal'\n" "@type fileName: string\n" "@kwarg fileName: Name of the file where data are saved\n" "@type fileFormat: string\n" "@kwarg fileFormat: Format of the data, e.g. 'SUM' or 'RAW2'\n" "@type beginTimeStep: int\n" "@kwarg beginTimeStep: start saving data at this time step\n" "@type endTimeStep: int\n" "@kwarg endTimeStep: finish saving data at this time step\n" "@type timeStepIncr: int\n" "@kwarg timeStepIncr: save data every timeStepIncr time steps\n" ) ) ; boost::python::class_< CheckedInteractionScalarFieldSaverPrmsPy, boost::python::bases<InteractionFieldSaverPrmsPy> >( "CheckedInteractionScalarFieldSaverPrms", "Parameters for saving checked scalar interaction-data to file.", boost::python::init< const std::string &, const std::string &, const std::string &, const std::string &, int, int, int >( ( arg("interactionName"), arg("fieldName"), arg("fileName"), arg("fileFormat"), arg("beginTimeStep"), arg("endTimeStep"), arg("timeStepIncr") ), "Defines checked interaction scalar field saver parameters\n" "@type interactionName: string\n" "@kwarg interactionName: Name of the interaction group for" " which data are saved\n" "@type fieldName: string\n" "@kwarg fieldName: Name of the data field, e.g. 'e_pot_normal'\n" "@type fileName: string\n" "@kwarg fileName: Name of the file where data are saved\n" "@type fileFormat: string\n" "@kwarg fileFormat: Format of the data, e.g. 'SUM' or 'RAW2'\n" "@type beginTimeStep: int\n" "@kwarg beginTimeStep: start saving data at this time step\n" "@type endTimeStep: int\n" "@kwarg endTimeStep: finish saving data at this time step\n" "@type timeStepIncr: int\n" "@kwarg timeStepIncr: save data every timeStepIncr time steps\n" ) ); boost::python::class_< TaggedInteractionScalarFieldSaverPrmsPy, boost::python::bases<InteractionFieldSaverPrmsPy> >( "TaggedInteractionScalarFieldSaverPrms", "Parameters for saving scalar data on tagged interactions to file.", boost::python::init< const std::string &, const std::string &, const std::string &, const std::string &, int, int, int, int, int >( ( arg("interactionName"), arg("fieldName"), arg("fileName"), arg("fileFormat"), arg("beginTimeStep"), arg("endTimeStep"), arg("timeStepIncr"), arg("tag"), arg("mask") ), "Defines tagged interaction scalar field saver parameters\n" "@type interactionName: string\n" "@kwarg interactionName: Name of the interaction group for" " which data are saved\n" "@type fieldName: string\n" "@kwarg fieldName: Name of the data field, e.g. 'e_pot_normal'\n" "@type fileName: string\n" "@kwarg fileName: Name of the file where data are saved\n" "@type fileFormat: string\n" "@kwarg fileFormat: Format of the data, e.g. 'SUM' or 'RAW2'\n" "@type beginTimeStep: int\n" "@kwarg beginTimeStep: start saving data at this time step\n" "@type endTimeStep: int\n" "@kwarg endTimeStep: finish saving data at this time step\n" "@type timeStepIncr: int\n" "@kwarg timeStepIncr: save data every timeStepIncr time steps\n" "@type tag: int\n" "@kwarg tag: the tag of the particles\n" "@type mask: int\n" "@kwarg mask: the tag mask\n" ) ) ; boost::python::class_< InteractionVectorFieldSaverPrmsPy, boost::python::bases<InteractionFieldSaverPrmsPy> >( "InteractionVectorFieldSaverPrms", "Parameters for saving vector interaction-data to file.", boost::python::init< const std::string &, const std::string &, const std::string &, const std::string &, int, int, int >( ( arg("interactionName"), arg("fieldName"), arg("fileName"), arg("fileFormat"), arg("beginTimeStep"), arg("endTimeStep"), arg("timeStepIncr") ), "Defines interaction vector field saver parameters\n" "@type interactionName: string\n" "@kwarg interactionName: Name of the interaction group for" " which data are saved\n" "@type fieldName: string\n" "@kwarg fieldName: Name of the data field, e.g. 'normal_force'\n" "@type fileName: string\n" "@kwarg fileName: Name of the file where data are saved\n" "@type fileFormat: string\n" "@kwarg fileFormat: Format of the data, e.g. 'SUM' or 'RAW2'\n" "@type beginTimeStep: int\n" "@kwarg beginTimeStep: start saving data at this time step\n" "@type endTimeStep: int\n" "@kwarg endTimeStep: finish saving data at this time step\n" "@type timeStepIncr: int\n" "@kwarg timeStepIncr: save data every timeStepIncr time steps\n" ) ); boost::python::class_< CheckedInteractionVectorFieldSaverPrmsPy, boost::python::bases<InteractionFieldSaverPrmsPy> >( "CheckedInteractionVectorFieldSaverPrms", "Parameters for saving checked vector interaction-data to file.", boost::python::init< const std::string &, const std::string &, const std::string &, const std::string &, int, int, int >( ( arg("interactionName"), arg("fieldName"), arg("fileName"), arg("fileFormat"), arg("beginTimeStep"), arg("endTimeStep"), arg("timeStepIncr") ), "Defines checked interaction vector field saver parameters\n" "@type interactionName: string\n" "@kwarg interactionName: Name of the interaction group for" " which data are saved\n" "@type fieldName: string\n" "@kwarg fieldName: Name of the data field, e.g. 'normal_force'\n" "@type fileName: string\n" "@kwarg fileName: Name of the file where data are saved\n" "@type fileFormat: string\n" "@kwarg fileFormat: Format of the data, e.g. 'SUM' or 'RAW2'\n" "@type beginTimeStep: int\n" "@kwarg beginTimeStep: start saving data at this time step\n" "@type endTimeStep: int\n" "@kwarg endTimeStep: finish saving data at this time step\n" "@type timeStepIncr: int\n" "@kwarg timeStepIncr: save data every timeStepIncr time steps\n" ) ); } } }
32.658427
91
0.564096
danielfrascarelli
f855776911f2d7b2b129b13e2bb71c99377ad8f0
2,251
cpp
C++
AI/Src/MessageDispatcher.cpp
ArvydasSlekaitis/ReginaGameEngine
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
[ "MIT" ]
1
2020-09-02T06:00:14.000Z
2020-09-02T06:00:14.000Z
AI/Src/MessageDispatcher.cpp
ArvydasSlekaitis/ReginaGameEngine
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
[ "MIT" ]
null
null
null
AI/Src/MessageDispatcher.cpp
ArvydasSlekaitis/ReginaGameEngine
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////// // MessageDispatcher.cpp // Created on: 20-07-2008 // Last modified: 22-06-2009 // Original author: Arvydas Slekaitis (C) /////////////////////////////////////////////////////////// #include <MessageDispatcher.h> using namespace Regina; //***************************************************************************** CMessageDispatcher* CMessageDispatcher::Instance() { static CMessageDispatcher msgDisp; return &msgDisp; } //***************************************************************************** void CMessageDispatcher::DispatchMsg(CTelegram* iTelegram) { assert(globalTime!=NULL && L"Message dispatcher is not initialized"); if(globalTime!=NULL) { CBaseEntity* entity = AIManager->EntityFromID(iTelegram->Receiver()); if(entity!=NULL) { if(iTelegram->DispatchTime()<=0) Discharge(iTelegram, entity); else { telegramQ.insert(make_pair(iTelegram->DispatchTime()+(*globalTime), iTelegram)); } } } else preInitatedTelegrams.push_back(iTelegram); } //***************************************************************************** void CMessageDispatcher::UnregisterEntity(const unsigned& iID) { multimap<float, CTelegram*>::iterator it = telegramQ.begin(); while(it!=telegramQ.end()) { if(it->second->Receiver() == iID) { multimap<float, CTelegram*>::iterator ite = it; it++; telegramQ.erase(ite); } else it++; } } //***************************************************************************** void CMessageDispatcher::Update() { assert(globalTime!=NULL && L"Message dispatcher is not initialized"); if(preInitatedTelegrams.size()>0) { for(unsigned i=0; i<preInitatedTelegrams.size(); i++) DispatchMsg(preInitatedTelegrams[i]); preInitatedTelegrams.clear(); } multimap<float, CTelegram*>::iterator it = telegramQ.begin(); while(it!=telegramQ.end()) { if(it->first <= *globalTime) { CBaseEntity* entity = AIManager->EntityFromID(it->second->Receiver()); if(entity!=NULL) Discharge(it->second, entity); multimap<float, CTelegram*>::iterator ite = it; it++; telegramQ.erase(ite); } else break; } } //***************************************************************************** void CMessageDispatcher::Init(float* iGlobalTime) { globalTime = iGlobalTime; }
22.287129
80
0.564638
ArvydasSlekaitis
f859ac6a81e42cc97042b1bb9b81a3d8ba7bde8a
18,473
cpp
C++
plugins/core/qAnimation/src/qAnimationDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
plugins/core/qAnimation/src/qAnimationDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
plugins/core/qAnimation/src/qAnimationDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
//########################################################################## //# # //# CLOUDCOMPARE PLUGIN: qAnimation # //# # //# This program is free software; you can redistribute it and/or modify # //# it under the terms of the GNU General Public License as published by # //# the Free Software Foundation; version 2 or later of the License. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU General Public License for more details. # //# # //# COPYRIGHT: Ryan Wicks, 2G Robotics Inc., 2015 # //# # //########################################################################## #include "qAnimationDlg.h" //Local #include "ViewInterpolate.h" //qCC_db #include <cc2DViewportObject.h> //qCC_gl #include <ccGLWindow.h> //Qt #include <QtGui> #include <QApplication> #include <QFileDialog> #include <QFileInfo> #include <QSettings> #include <QElapsedTimer> #include <QProgressDialog> #include <QMessageBox> //standard includes #include <vector> #include <iomanip> #ifdef QFFMPEG_SUPPORT //QTFFmpeg #include <QVideoEncoder.h> #endif //System #include <algorithm> #if defined(CC_WINDOWS) #include "windows.h" #else #include <unistd.h> #endif static const QString s_stepDurationKey("StepDurationSec"); static const QString s_stepEnabledKey("StepEnabled"); qAnimationDlg::qAnimationDlg(ccGLWindow* view3d, QWidget* parent) : QDialog(parent, Qt::Tool) , Ui::AnimationDialog() , m_view3d(view3d) { setupUi(this); //restore previous settings { QSettings settings; settings.beginGroup("qAnimation"); //last filename { QString defaultDir; #ifdef _MSC_VER defaultDir = QApplication::applicationDirPath(); #else defaultDir = QDir::homePath(); #endif const QString defaultFileName( defaultDir + "/animation.mp4" ); QString lastFilename = settings.value("filename", defaultFileName ).toString(); #ifndef QFFMPEG_SUPPORT lastFilename = QFileInfo(lastFilename).absolutePath(); #endif outputFileLineEdit->setText( lastFilename ); } //other parameters { bool startPreviewFromSelectedStep = settings.value("previewFromSelected", previewFromSelectedCheckBox->isChecked()).toBool(); bool loop = settings.value("loop", loopCheckBox->isChecked()).toBool(); int frameRate = settings.value("frameRate", fpsSpinBox->value()).toInt(); int superRes = settings.value("superRes", superResolutionSpinBox->value()).toInt(); int renderingMode = settings.value("renderingMode", renderingModeComboBox->currentIndex()).toInt(); int bitRate = settings.value("bitRate", bitrateSpinBox->value()).toInt(); previewFromSelectedCheckBox->setChecked(startPreviewFromSelectedStep); loopCheckBox->setChecked(loop); fpsSpinBox->setValue(frameRate); superResolutionSpinBox->setValue(superRes); renderingModeComboBox->setCurrentIndex(renderingMode); bitrateSpinBox->setValue(bitRate); } settings.endGroup(); } connect ( fpsSpinBox, SIGNAL( valueChanged(int) ), this, SLOT( onFPSChanged(int) ) ); connect ( totalTimeDoubleSpinBox, SIGNAL( valueChanged(double) ), this, SLOT( onTotalTimeChanged(double) ) ); connect ( stepTimeDoubleSpinBox, SIGNAL( valueChanged(double) ), this, SLOT( onStepTimeChanged(double) ) ); connect ( loopCheckBox, SIGNAL( toggled(bool) ), this, SLOT( onLoopToggled(bool) ) ); connect ( browseButton, SIGNAL( clicked() ), this, SLOT( onBrowseButtonClicked() ) ); connect ( previewButton, SIGNAL( clicked() ), this, SLOT( preview() ) ); connect ( renderButton, SIGNAL( clicked() ), this, SLOT( renderAnimation() ) ); connect ( exportFramesPushButton, SIGNAL( clicked() ), this, SLOT( renderFrames() ) ); connect ( buttonBox, SIGNAL( accepted() ), this, SLOT( onAccept() ) ); } bool qAnimationDlg::init(const std::vector<cc2DViewportObject*>& viewports) { if (viewports.size() < 2) { assert(false); return false; } try { m_videoSteps.resize(viewports.size()); } catch (const std::bad_alloc&) { //not enough memory return false; } for (size_t i = 0; i < viewports.size(); ++i) { cc2DViewportObject* vp = viewports[i]; //check if the (1st) viewport has a duration in meta data (from a previous run) double duration_sec = 2.0; if (vp->hasMetaData(s_stepDurationKey)) { duration_sec = vp->getMetaData(s_stepDurationKey).toDouble(); } bool isChecked = true; if (vp->hasMetaData(s_stepEnabledKey)) { isChecked = vp->getMetaData(s_stepEnabledKey).toBool(); } QString itemName = QString("step %1 (%2)").arg(QString::number(i+1), vp->getName()); QListWidgetItem* item = new QListWidgetItem(itemName, stepSelectionList); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag item->setCheckState(isChecked ? Qt::Checked : Qt::Unchecked); // initialize check state stepSelectionList->addItem(item); m_videoSteps[i].viewport = vp; m_videoSteps[i].duration_sec = duration_sec; } connect ( stepSelectionList, SIGNAL( currentRowChanged(int) ), this, SLOT( onCurrentStepChanged(int) ) ); connect ( stepSelectionList, SIGNAL( itemChanged(QListWidgetItem*) ), this, SLOT( onItemChanged(QListWidgetItem*) ) ); stepSelectionList->setCurrentRow(0); //select the first one by default onCurrentStepChanged(getCurrentStepIndex()); updateTotalDuration(); return true; } void qAnimationDlg::onAccept() { assert(stepSelectionList->count() >= m_videoSteps.size()); for (size_t i = 0; i < m_videoSteps.size(); ++i) { cc2DViewportObject* vp = m_videoSteps[i].viewport; //save the step duration as meta data vp->setMetaData(s_stepDurationKey, m_videoSteps[i].duration_sec); vp->setMetaData(s_stepEnabledKey, (stepSelectionList->item(static_cast<int>(i))->checkState() == Qt::Checked)); } //store settings { QSettings settings; settings.beginGroup("qAnimation"); settings.setValue("previewFromSelected", previewFromSelectedCheckBox->isChecked()); settings.setValue("loop", loopCheckBox->isChecked()); settings.setValue("frameRate", fpsSpinBox->value()); settings.setValue("renderingMode", renderingModeComboBox->currentIndex()); settings.setValue("superRes", superResolutionSpinBox->value()); settings.setValue("bitRate", bitrateSpinBox->value()); settings.endGroup(); } } double qAnimationDlg::computeTotalTime() { double totalDuration_sec = 0; size_t vp1 = 0, vp2 = 0; while (getNextSegment(vp1, vp2)) { assert(vp1 < stepSelectionList->count()); totalDuration_sec += m_videoSteps[static_cast<int>(vp1)].duration_sec; if (vp2 == 0) { //loop case break; } vp1 = vp2; } return totalDuration_sec; } int qAnimationDlg::getCurrentStepIndex() { return stepSelectionList->currentRow(); } void qAnimationDlg::applyViewport( const cc2DViewportObject* viewport ) { if (m_view3d) { m_view3d->setViewportParameters( viewport->getParameters() ); m_view3d->redraw(); } //QApplication::processEvents(); } void qAnimationDlg::onFPSChanged(int fps) { //nothing to do } void qAnimationDlg::onTotalTimeChanged(double newTime_sec) { double previousTime_sec = computeTotalTime(); if (previousTime_sec != newTime_sec) { assert(previousTime_sec != 0); double scale = newTime_sec / previousTime_sec; size_t vp1 = 0, vp2 = 0; while (getNextSegment(vp1, vp2)) { assert(vp1 < stepSelectionList->count()); m_videoSteps[vp1].duration_sec *= scale; if (vp2 == 0) { //loop case break; } vp1 = vp2; } //update current step updateCurrentStepDuration(); } } void qAnimationDlg::onStepTimeChanged(double time_sec) { m_videoSteps[ getCurrentStepIndex() ].duration_sec = time_sec; //update total duration updateTotalDuration(); //update current step updateCurrentStepDuration(); } void qAnimationDlg::onBrowseButtonClicked() { #ifdef QFFMPEG_SUPPORT QString filename = QFileDialog::getSaveFileName( this, tr("Output animation file"), outputFileLineEdit->text() ); #else QString filename = QFileDialog::getExistingDirectory( this, tr("Open Directory"), outputFileLineEdit->text(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); #endif if (filename.isEmpty()) { //cancelled by user return; } outputFileLineEdit->setText(filename); } bool qAnimationDlg::getNextSegment(size_t& vp1, size_t& vp2) const { if( vp1 >= m_videoSteps.size()) { assert(false); return false; } size_t inputVP1 = vp1; while (stepSelectionList->item(static_cast<int>(vp1))->checkState() == Qt::Unchecked) { ++vp1; if (vp1 == m_videoSteps.size()) { if (loopCheckBox->isChecked()) { vp1 = 0; } else { //no more valid start (vp1) return false; } } if (vp1 == inputVP1) { return false; } } //look for the next enabled viewport for (vp2 = vp1+1; vp2 <= m_videoSteps.size(); ++vp2) { if (vp1 == vp2) { return false; } if (vp2 == m_videoSteps.size()) { if (loopCheckBox->isChecked()) { vp2 = 0; } else { //stop break; } } if (stepSelectionList->item(static_cast<int>(vp2))->checkState() == Qt::Checked) { //we have found a valid couple (vp1, vp2) return true; } } //no more valid stop (vp2) return false; } int qAnimationDlg::countFrames(size_t startIndex/*=0*/) { //reset the interpolators and count the total number of frames int totalFrameCount = 0; { double fps = fpsSpinBox->value(); size_t vp1 = startIndex; size_t vp2 = vp1+1; while (getNextSegment(vp1, vp2)) { const Step& currentStep = m_videoSteps[vp1]; int frameCount = static_cast<int>( fps * currentStep.duration_sec ); totalFrameCount += frameCount; //take care of the 'loop' case if (vp2 == 0) { assert(loopCheckBox->isChecked()); break; } vp1 = vp2; } } return totalFrameCount; } void qAnimationDlg::preview() { //we'll take the rendering time into account! QElapsedTimer timer; timer.start(); setEnabled(false); size_t vp1 = previewFromSelectedCheckBox->isChecked() ? static_cast<size_t>(getCurrentStepIndex()) : 0; //count the total number of frames int frameCount = countFrames(loopCheckBox->isChecked() ? 0 : vp1); int fps = fpsSpinBox->value(); //show progress dialog QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this); progressDialog.setWindowTitle("Preview"); progressDialog.show(); progressDialog.setModal(true); progressDialog.setAutoClose(false); QApplication::processEvents(); assert(stepSelectionList->count() >= m_videoSteps.size()); int frameIndex = 0; size_t vp2 = 0; while (getNextSegment(vp1, vp2)) { Step& step1 = m_videoSteps[vp1]; Step& step2 = m_videoSteps[vp2]; //theoretical waiting time per frame qint64 delay_ms = static_cast<int>(1000 * step1.duration_sec / fps); int frameCount = static_cast<int>( fps * step1.duration_sec ); ViewInterpolate interpolator(step1.viewport, step2.viewport); interpolator.setMaxStep(frameCount); cc2DViewportObject currentParams; while ( interpolator.nextView( currentParams ) ) { timer.restart(); applyViewport ( &currentParams ); qint64 dt_ms = timer.elapsed(); progressDialog.setValue(++frameIndex); QApplication::processEvents(); if (progressDialog.wasCanceled()) { break; } //remaining time if (dt_ms < delay_ms) { int wait_ms = static_cast<int>(delay_ms - dt_ms); #if defined(CC_WINDOWS) ::Sleep( wait_ms ); #else usleep( wait_ms * 1000 ); #endif } } if (progressDialog.wasCanceled()) { break; } if (vp2 == 0) { assert(loopCheckBox->isChecked()); frameIndex = 0; } vp1 = vp2; } //reset view onCurrentStepChanged(getCurrentStepIndex()); setEnabled(true); } void qAnimationDlg::render(bool asSeparateFrames) { if (!m_view3d) { assert(false); return; } QString outputFilename = outputFileLineEdit->text(); //save to persistent settings { QSettings settings; settings.beginGroup("qAnimation"); settings.setValue("filename", outputFilename); settings.endGroup(); } setEnabled(false); //count the total number of frames int frameCount = countFrames(0); int fps = fpsSpinBox->value(); //super resolution int superRes = superResolutionSpinBox->value(); const int SUPER_RESOLUTION = 0; const int ZOOM = 1; int renderingMode = renderingModeComboBox->currentIndex(); assert(renderingMode == SUPER_RESOLUTION || renderingMode == ZOOM); //show progress dialog QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this); progressDialog.setWindowTitle("Render"); progressDialog.show(); QApplication::processEvents(); #ifdef QFFMPEG_SUPPORT QScopedPointer<QVideoEncoder> encoder(0); QSize originalViewSize; if (!asSeparateFrames) { //get original viewport size originalViewSize = m_view3d->qtSize(); //hack: as the encoder requires that the video dimensions are multiples of 8, we resize the window a little bit... { //find the nearest multiples of 8 QSize customSize = originalViewSize; if (originalViewSize.width() % 8 || originalViewSize.height() % 8) { if (originalViewSize.width() % 8) customSize.setWidth((originalViewSize.width() / 8 + 1) * 8); if (originalViewSize.height() % 8) customSize.setHeight((originalViewSize.height() / 8 + 1) * 8); m_view3d->resize(customSize); QApplication::processEvents(); } } int bitrate = bitrateSpinBox->value() * 1024; int gop = fps; int animScale = 1; if (renderingMode == ZOOM) { animScale = superRes; } encoder.reset(new QVideoEncoder(outputFilename, m_view3d->glWidth() * animScale, m_view3d->glHeight() * animScale, bitrate, gop, static_cast<unsigned>(fpsSpinBox->value()))); QString errorString; if (!encoder->open(&errorString)) { QMessageBox::critical(this, "Error", QString("Failed to open file for output: %1").arg(errorString)); setEnabled(true); return; } } #else if (!asSeparateFrames) { QMessageBox::critical(this, "Error", QString("Animation mode is not supported (no FFMPEG support)")); return; } #endif bool lodWasEnabled = m_view3d->isLODEnabled(); m_view3d->setLODEnabled(false); QDir outputDir( QFileInfo(outputFilename).absolutePath() ); int frameIndex = 0; bool success = true; size_t vp1 = 0, vp2 = 0; while (getNextSegment(vp1, vp2)) { Step& step1 = m_videoSteps[vp1]; Step& step2 = m_videoSteps[vp2]; ViewInterpolate interpolator(step1.viewport, step2.viewport); int frameCount = static_cast<int>( fps * step1.duration_sec ); interpolator.setMaxStep(frameCount); cc2DViewportObject current_params; while ( interpolator.nextView( current_params ) ) { applyViewport ( &current_params ); //render to image QImage image = m_view3d->renderToImage(superRes, renderingMode == ZOOM, false, true ); if (image.isNull()) { QMessageBox::critical(this, "Error", "Failed to grab the screen!"); success = false; break; } if (renderingMode == SUPER_RESOLUTION && superRes > 1) { image = image.scaled(image.width() / superRes, image.height() / superRes, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } if (asSeparateFrames) { QString filename = QString("frame_%1.png").arg(frameIndex, 6, 10, QChar('0')); QString fullPath = outputDir.filePath(filename); if (!image.save(fullPath)) { QMessageBox::critical(this, "Error", QString("Failed to save frame #%1").arg(frameIndex + 1)); success = false; break; } } else { #ifdef QFFMPEG_SUPPORT QString errorString; if (!encoder->encodeImage(image, frameIndex, &errorString)) { QMessageBox::critical(this, "Error", QString("Failed to encode frame #%1: %2").arg(frameIndex + 1).arg(errorString)); success = false; break; } #endif } ++frameIndex; progressDialog.setValue(frameIndex); QApplication::processEvents(); if (progressDialog.wasCanceled()) { QMessageBox::warning(this, "Warning", QString("Process has been cancelled")); success = false; break; } } if (!success) { break; } if (vp2 == 0) { //stop loop here! break; } vp1 = vp2; } m_view3d->setLODEnabled(lodWasEnabled); #ifdef QFFMPEG_SUPPORT if (encoder) { encoder->close(); //hack: restore original size m_view3d->resize(originalViewSize); QApplication::processEvents(); } #endif progressDialog.hide(); QApplication::processEvents(); if (success) { QMessageBox::information(this, "Job done", "The animation has been saved successfully"); } setEnabled(true); } void qAnimationDlg::updateTotalDuration() { double totalDuration_sec = computeTotalTime(); totalTimeDoubleSpinBox->blockSignals(true); totalTimeDoubleSpinBox->setValue(totalDuration_sec); totalTimeDoubleSpinBox->blockSignals(false); } void qAnimationDlg::updateCurrentStepDuration() { int index = getCurrentStepIndex(); stepTimeDoubleSpinBox->blockSignals(true); stepTimeDoubleSpinBox->setValue(m_videoSteps[index].duration_sec); stepTimeDoubleSpinBox->blockSignals(false); } void qAnimationDlg::onItemChanged(QListWidgetItem*) { //update total duration updateTotalDuration(); onCurrentStepChanged(stepSelectionList->currentRow()); } void qAnimationDlg::onCurrentStepChanged(int index) { //update current step descriptor stepIndexLabel->setText(QString::number(index+1)); updateCurrentStepDuration(); applyViewport( m_videoSteps[index].viewport ); //check that the step is enabled bool isEnabled = (stepSelectionList->item(index)->checkState() == Qt::Checked); bool isLoop = loopCheckBox->isChecked(); currentStepGroupBox->setEnabled(isEnabled && (index+1 < m_videoSteps.size() || isLoop)); } void qAnimationDlg::onLoopToggled(bool) { updateTotalDuration(); onCurrentStepChanged(stepSelectionList->currentRow()); }
26.091808
176
0.678504
ohanlonl
f859cf8a8a0acff03cbfeacd1304e392edce10a4
1,255
cc
C++
utils/libcpp_utils/src/io/path.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
utils/libcpp_utils/src/io/path.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
utils/libcpp_utils/src/io/path.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
#include <utils/io/path.hh> #include <cstdlib> #include <limits.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <utils/cli/err.hh> #include <utils/str/format-string.hh> namespace utils { namespace path { std::string join(const std::string &p1, const std::string &p2) { if (p2.size() > 0 && p2[0] == '/') return p2; if (p1.size() > 0 && p1.back() == '/') return p1 + p2; else return p1 + "/" + p2; } std::pair<std::string, std::string> split_ext(const std::string &path) { auto spos = path.rfind('.'); if (spos == std::string::npos) return std::make_pair(path, std::string{}); else return std::make_pair(path.substr(0, spos), path.substr(spos)); } std::string abspath(const std::string &path) { char path_buf[PATH_MAX]; PANIC_IF(realpath(path.c_str(), path_buf) == NULL, FORMAT_STRING("abspath " << path << " failed.")); return path_buf; } bool is_file(const std::string &path) { struct stat st; if (stat(path.c_str(), &st) < 0) return false; return S_ISREG(st.st_mode); } bool is_dir(const std::string &path) { struct stat st; if (stat(path.c_str(), &st) < 0) return false; return S_ISDIR(st.st_mode); } } // namespace path } // namespace utils
21.637931
72
0.627888
obs145628
f85be4e3d41d9737b0d1bcbb90047c3c57eebb21
1,609
cc
C++
mojo/public/cpp/system/isolated_connection.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
mojo/public/cpp/system/isolated_connection.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
802
2017-04-21T14:18:36.000Z
2022-03-31T21:20:48.000Z
mojo/public/cpp/system/isolated_connection.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/public/cpp/system/isolated_connection.h" #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" namespace mojo { IsolatedConnection::IsolatedConnection() : token_(base::UnguessableToken::Create()) {} IsolatedConnection::~IsolatedConnection() { // We send a dummy invitation over a temporary channel, re-using |token_| as // the name. This ensures that the connection set up by Connect(), if any, // will be replaced with a short-lived, self-terminating connection. // // This is a bit of a hack since Mojo does not provide any API for explicitly // terminating isolated connections, but this is a decision made to minimize // the API surface dedicated to isolated connections in anticipation of the // concept being deprecated eventually. PlatformChannel channel; OutgoingInvitation::SendIsolated(channel.TakeLocalEndpoint(), token_.ToString()); } ScopedMessagePipeHandle IsolatedConnection::Connect( PlatformChannelEndpoint endpoint) { return OutgoingInvitation::SendIsolated(std::move(endpoint), token_.ToString()); } ScopedMessagePipeHandle IsolatedConnection::Connect( PlatformChannelServerEndpoint endpoint) { return OutgoingInvitation::SendIsolated(std::move(endpoint), token_.ToString()); } } // namespace mojo
38.309524
79
0.713487
zealoussnow
f85c7496c6de6833a5a0ebdc236bbacc783264f7
12,451
cpp
C++
gen/blink/bindings/modules/v8/V8Database.cpp
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
8
2019-05-05T16:38:05.000Z
2021-11-09T11:45:38.000Z
gen/blink/bindings/modules/v8/V8Database.cpp
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
null
null
null
gen/blink/bindings/modules/v8/V8Database.cpp
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
4
2018-12-14T07:52:46.000Z
2021-06-11T18:06:09.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8Database.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "bindings/core/v8/V8VoidCallback.h" #include "bindings/modules/v8/V8SQLTransactionCallback.h" #include "bindings/modules/v8/V8SQLTransactionErrorCallback.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8Database::wrapperTypeInfo = { gin::kEmbedderBlink, V8Database::domTemplate, V8Database::refObject, V8Database::derefObject, V8Database::trace, 0, 0, V8Database::preparePrototypeObject, V8Database::installConditionallyEnabledProperties, "Database", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::GarbageCollectedObject }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in Database.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // bindings/core/v8/ScriptWrappable.h. const WrapperTypeInfo& Database::s_wrapperTypeInfo = V8Database::wrapperTypeInfo; namespace DatabaseV8Internal { static void versionAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); Database* impl = V8Database::toImpl(holder); v8SetReturnValueString(info, impl->version(), info.GetIsolate()); } static void versionAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); DatabaseV8Internal::versionAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void changeVersionMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 2)) { V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "changeVersion", "Database", 2, info.Length()), info.GetIsolate()); return; } Database* impl = V8Database::toImpl(info.Holder()); V8StringResource<> oldVersion; V8StringResource<> newVersion; SQLTransactionCallback* callback; SQLTransactionErrorCallback* errorCallback; VoidCallback* successCallback; { oldVersion = info[0]; if (!oldVersion.prepare()) return; newVersion = info[1]; if (!newVersion.prepare()) return; if (!isUndefinedOrNull(info[2])) { if (!info[2]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("changeVersion", "Database", "The callback provided as parameter 3 is not a function.")); return; } callback = V8SQLTransactionCallback::create(v8::Local<v8::Function>::Cast(info[2]), ScriptState::current(info.GetIsolate())); } else { callback = nullptr; } if (!isUndefinedOrNull(info[3])) { if (!info[3]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("changeVersion", "Database", "The callback provided as parameter 4 is not a function.")); return; } errorCallback = V8SQLTransactionErrorCallback::create(v8::Local<v8::Function>::Cast(info[3]), ScriptState::current(info.GetIsolate())); } else { errorCallback = nullptr; } if (!isUndefinedOrNull(info[4])) { if (!info[4]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("changeVersion", "Database", "The callback provided as parameter 5 is not a function.")); return; } successCallback = V8VoidCallback::create(v8::Local<v8::Function>::Cast(info[4]), ScriptState::current(info.GetIsolate())); } else { successCallback = nullptr; } } impl->changeVersion(oldVersion, newVersion, callback, errorCallback, successCallback); } static void changeVersionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); DatabaseV8Internal::changeVersionMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void transactionMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "transaction", "Database", 1, info.Length()), info.GetIsolate()); return; } Database* impl = V8Database::toImpl(info.Holder()); SQLTransactionCallback* callback; SQLTransactionErrorCallback* errorCallback; VoidCallback* successCallback; { if (info.Length() <= 0 || !info[0]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("transaction", "Database", "The callback provided as parameter 1 is not a function.")); return; } callback = V8SQLTransactionCallback::create(v8::Local<v8::Function>::Cast(info[0]), ScriptState::current(info.GetIsolate())); if (!isUndefinedOrNull(info[1])) { if (!info[1]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("transaction", "Database", "The callback provided as parameter 2 is not a function.")); return; } errorCallback = V8SQLTransactionErrorCallback::create(v8::Local<v8::Function>::Cast(info[1]), ScriptState::current(info.GetIsolate())); } else { errorCallback = nullptr; } if (!isUndefinedOrNull(info[2])) { if (!info[2]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("transaction", "Database", "The callback provided as parameter 3 is not a function.")); return; } successCallback = V8VoidCallback::create(v8::Local<v8::Function>::Cast(info[2]), ScriptState::current(info.GetIsolate())); } else { successCallback = nullptr; } } impl->transaction(callback, errorCallback, successCallback); } static void transactionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); DatabaseV8Internal::transactionMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void readTransactionMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "readTransaction", "Database", 1, info.Length()), info.GetIsolate()); return; } Database* impl = V8Database::toImpl(info.Holder()); SQLTransactionCallback* callback; SQLTransactionErrorCallback* errorCallback; VoidCallback* successCallback; { if (info.Length() <= 0 || !info[0]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("readTransaction", "Database", "The callback provided as parameter 1 is not a function.")); return; } callback = V8SQLTransactionCallback::create(v8::Local<v8::Function>::Cast(info[0]), ScriptState::current(info.GetIsolate())); if (!isUndefinedOrNull(info[1])) { if (!info[1]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("readTransaction", "Database", "The callback provided as parameter 2 is not a function.")); return; } errorCallback = V8SQLTransactionErrorCallback::create(v8::Local<v8::Function>::Cast(info[1]), ScriptState::current(info.GetIsolate())); } else { errorCallback = nullptr; } if (!isUndefinedOrNull(info[2])) { if (!info[2]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("readTransaction", "Database", "The callback provided as parameter 3 is not a function.")); return; } successCallback = V8VoidCallback::create(v8::Local<v8::Function>::Cast(info[2]), ScriptState::current(info.GetIsolate())); } else { successCallback = nullptr; } } impl->readTransaction(callback, errorCallback, successCallback); } static void readTransactionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); DatabaseV8Internal::readTransactionMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } } // namespace DatabaseV8Internal static const V8DOMConfiguration::AccessorConfiguration V8DatabaseAccessors[] = { {"version", DatabaseV8Internal::versionAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; static const V8DOMConfiguration::MethodConfiguration V8DatabaseMethods[] = { {"changeVersion", DatabaseV8Internal::changeVersionMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts}, {"transaction", DatabaseV8Internal::transactionMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts}, {"readTransaction", DatabaseV8Internal::readTransactionMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts}, }; static void installV8DatabaseTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "Database", v8::Local<v8::FunctionTemplate>(), V8Database::internalFieldCount, 0, 0, V8DatabaseAccessors, WTF_ARRAY_LENGTH(V8DatabaseAccessors), V8DatabaseMethods, WTF_ARRAY_LENGTH(V8DatabaseMethods)); v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Local<v8::FunctionTemplate> V8Database::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8DatabaseTemplate); } bool V8Database::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8Database::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } Database* V8Database::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0; } void V8Database::refObject(ScriptWrappable* scriptWrappable) { } void V8Database::derefObject(ScriptWrappable* scriptWrappable) { } } // namespace blink
47.342205
468
0.709823
gergul
f8619af46e7182c45593d4b6bd1b18b6ad9e0fdf
1,076
cpp
C++
seletiva-grupro/C.cpp
gustavo-mendel/my-college-projects
ccc1285e1a6863312e275f973e728de231a9458a
[ "MIT" ]
3
2021-08-18T01:59:50.000Z
2021-08-28T00:19:07.000Z
seletiva-grupro/C.cpp
gustavo-mendel/my-college-projects
ccc1285e1a6863312e275f973e728de231a9458a
[ "MIT" ]
4
2021-03-09T18:39:47.000Z
2021-03-26T00:01:56.000Z
seletiva-grupro/C.cpp
gustavo-mendel/my-college-projects
ccc1285e1a6863312e275f973e728de231a9458a
[ "MIT" ]
1
2022-03-20T14:54:09.000Z
2022-03-20T14:54:09.000Z
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; // By: mende1 #define endl "\n" #define int ll #define cini(n) \ int n; \ cin >> n; #define fori(x, n) for (int i = x; i <= n; i++) #define forj(x, n) for (int j = x; j <= n; j++) #define fork(x, n) for (int k = x; k <= n; k++) void solve() { // ------------------------------------------- vector<int> arr(300000); int n; cin >> n; for (int i=1; i<=n; i++) { cin >> arr[i]; } int32_t ans[2] = { 0 }; int max = -9223372036854775807; int min = 9223372036854775807; for (int32_t i=1; i<=n; i++) { if (arr[i] > max) { max = arr[i]; ans[0] = i; } if (arr[i] < min) { min = arr[i]; ans[1] = i; } } if (ans[0] > ans[1]) { int32_t aux = ans[0]; ans[0] = ans[1]; ans[1] = aux; } cout << ans[0] << " " << ans[1] << endl; // ------------------------------------------- } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); // cini(t); int t = 1; while (t--) { solve(); } return 0; }
15.823529
48
0.462825
gustavo-mendel
f86338ac040f8d2195a6caae14f599f60cb40375
3,486
hpp
C++
src/Typing.hpp
aukdata/TorikaiType
8d4079c38510ee33bc2323231065b0d72f2ea3cc
[ "MIT" ]
null
null
null
src/Typing.hpp
aukdata/TorikaiType
8d4079c38510ee33bc2323231065b0d72f2ea3cc
[ "MIT" ]
null
null
null
src/Typing.hpp
aukdata/TorikaiType
8d4079c38510ee33bc2323231065b0d72f2ea3cc
[ "MIT" ]
null
null
null
// // Typing.hpp // TorikaiType // # ifndef Typing_hpp # define Typing_hpp # include <Siv3D.hpp> # include <functional> class Typing { static const Array<std::pair<String, String>> romanize_table; static const HashTable<char32, char32> hiraganaize_table; Array<String> m_parsed, m_hiraganized, m_romanized; int32 m_pos = -1; String m_buffer = U""; bool m_acceptSecondN = false; [[nodiscard]] bool isSmallChar(char32 c) const { constexpr std::array<char32, 16> smallChs = { U'ぁ', U'ぃ', U'ぅ', U'ぇ', U'ぉ', U'ゃ', U'ゅ', U'ょ', U'ァ', U'ィ', U'ゥ', U'ェ', U'ォ', U'ャ', U'ュ', U'ョ' }; return std::find(smallChs.begin(), smallChs.end(), c) != smallChs.end(); } [[nodiscard]] constexpr bool isAlphabet(char32 c) const { return U'A' <= c && c <= U'z'; } void parseText(String text) { String buf = U""; bool sokuon = false; m_parsed.clear(); for (auto c : text) { if (c == U'っ' || c == U'ッ') { if (!sokuon) { m_parsed.push_back(std::move(buf)); buf = U""; } buf += c; sokuon = true; } else { if (isSmallChar(c)) { m_parsed.push_back(buf + c); buf = U""; sokuon = true; } else { if (!sokuon) { m_parsed.push_back(std::move(buf)); buf = U""; } buf += c; sokuon = false; } } } if (buf != U"") { m_parsed.push_back(std::move(buf)); } m_parsed.pop_front(); } void setText(String text) { parseText(text); m_hiraganized = m_parsed.map([&] (const auto& s) { String hiragana = U""; s.each([&] (const auto c) { hiragana += hiraganaize_table.count(c) > 0 ? hiraganaize_table.at(c) : c; }); return std::move(hiragana); }); m_romanized = m_hiraganized.map([&] (const auto& kana) { for (const auto& pair : romanize_table) { if (pair.second == kana) { return pair.first; } else if (U"っ" + pair.second == kana) { return pair.first[0] + pair.first; } } return String(U" "); }); m_pos = 0; } std::function<void()> m_onCorrectWordHandler; std::function<String()> m_nextWordHandler; public: Typing() {}; std::pair<int32, int32> getNextCharPos() const; void setCorrectWordHandler(std::function<void()> handler) { m_onCorrectWordHandler = handler; } void setNextWordHandler(std::function<String()> handler) { m_nextWordHandler = handler; } bool onCharInput(const char32 s); [[nodiscard]] char32 getNextChar() const; void update(); void draw(const int32 x, const int32 y, const bool showHiragana = true, const bool showRomaji = true, const bool showTypedRomaji = true) const; }; # endif /* Typing_hpp */
26.815385
147
0.454676
aukdata
d379d514f9db4919fea39d1107d9432c41b660e2
7,292
cpp
C++
src/cpu/x64/zendnn_inner_product.cpp
amd/ZenDNN
2d8e025a05126b7c378d88a990a20e21a4182b20
[ "Apache-2.0" ]
28
2021-08-12T10:38:06.000Z
2022-03-25T08:37:31.000Z
src/cpu/x64/zendnn_inner_product.cpp
amd/ZenDNN
2d8e025a05126b7c378d88a990a20e21a4182b20
[ "Apache-2.0" ]
2
2021-08-17T03:20:10.000Z
2021-09-23T04:15:32.000Z
src/cpu/x64/zendnn_inner_product.cpp
amd/ZenDNN
2d8e025a05126b7c378d88a990a20e21a4182b20
[ "Apache-2.0" ]
5
2021-08-20T05:05:59.000Z
2022-02-25T19:13:07.000Z
/******************************************************************************* * Modifications Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved. * Notified per clause 4(b) of the license. *******************************************************************************/ /******************************************************************************* * Copyright 2017-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "c_types_map.hpp" #include "zendnn_thread.hpp" #include "type_helpers.hpp" #include "cpu/binary_injector_utils.hpp" #include "zendnn_logging.hpp" #include "zendnn_inner_product.hpp" #include "zendnn_private.hpp" namespace zendnn { namespace impl { namespace cpu { namespace x64 { using namespace zendnn::impl::status; using namespace zendnn::impl::prop_kind; using namespace zendnn::impl::data_type; using namespace zendnn::impl::format_tag; using namespace zendnn::impl::primitive_kind; template <impl::data_type_t data_type> status_t zendnn_inner_product_fwd_t<data_type>::execute_forward( const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const data_t *, ZENDNN_ARG_SRC); auto weights = CTX_IN_MEM(const data_t *, ZENDNN_ARG_WEIGHTS); auto bias = CTX_IN_MEM(const data_t *, ZENDNN_ARG_BIAS); auto dst = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DST); const auto post_ops_binary_rhs_arg_vec = binary_injector_utils::prepare_binary_args( this->pd()->attr()->post_ops_, ctx); const dim_t MB = pd()->MB(); const dim_t OC = pd()->OC(); const dim_t IC = pd()->IC_total_padded(); const auto &wmd = *pd()->weights_md(); // check if OC is NOT the leading dimension bool wei_tr = wmd.format_desc.blocking.strides[0] != 1; bool has_eltwise = pd()->attr()->post_ops_.find(primitive_kind::eltwise) >= 0; const float *scales = pd()->attr()->output_scales_.scales_; // The mask value of 0 implies a common output scaling factor for the // whole output tensor. float alpha = pd()->attr()->output_scales_.mask_ == 0 ? scales[0] : 1.0; //TODO(aakar): Handle case where (mask == 1 << 1) or (mask != 0) // Modify inner_product API to support Layout bool Layout = true; //CblasRowMajor zendnnInfo(ZENDNN_CORELOG, "ZENDNN implementation path in zendnn_inner_product_fwd_t::execute_forward [cpu/inner_product]"); if (bias == NULL) { zendnnInfo(ZENDNN_CORELOG, "zendnn_inner_product_fwd_t::execute_forward zenMatMul [cpu/inner_product]"); zenMatMul( Layout, false, wei_tr, 1, MB, IC, OC, alpha, (float *)src, IC, (float *)weights, wei_tr ? IC : OC, beta_, (float *)dst, OC); } else if (!has_eltwise) { zendnnInfo(ZENDNN_CORELOG, "zendnn_inner_product_fwd_t::execute_forward zenMatMulWithBias [cpu/inner_product]"); zenMatMulWithBias( Layout, false, wei_tr, 1, MB, IC, OC, alpha, (float *)src, IC, (float *)weights, wei_tr ? IC : OC, (float *)bias, beta_, (float *)dst, OC); } else { zendnnInfo(ZENDNN_CORELOG, "zendnn_inner_product_fwd_t::execute_forward zenMatMulWithBiasReLU [cpu/inner_product]"); zenMatMulWithBiasReLU( Layout, false, wei_tr, 1, MB, IC, OC, alpha, (float *)src, IC, (float *)weights, wei_tr ? IC : OC, (float *)bias, beta_, (float *)dst, OC); } return status::success; } template <impl::data_type_t data_type> status_t zendnn_inner_product_bwd_data_t<data_type>::execute_backward_data( const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const data_t *, ZENDNN_ARG_DIFF_DST); auto weights = CTX_IN_MEM(const data_t *, ZENDNN_ARG_WEIGHTS); auto diff_src = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DIFF_SRC); const dim_t MB = pd()->MB(); const dim_t OC = pd()->OC(); const dim_t IC = pd()->IC_total_padded(); const auto &wmd = *pd()->weights_md(); bool wei_tr = wmd.format_desc.blocking.strides[0] == 1; float alpha = 1.0, beta = 0.0; status_t st = extended_sgemm(wei_tr ? "T" : "N", "N", &IC, &MB, &OC, &alpha, weights, wei_tr ? &OC : &IC, diff_dst, &OC, &beta, diff_src, &IC); return st; } template <impl::data_type_t data_type> status_t zendnn_inner_product_bwd_weights_t<data_type>::execute_backward_weights( const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const data_t *, ZENDNN_ARG_DIFF_DST); auto src = CTX_IN_MEM(const data_t *, ZENDNN_ARG_SRC); auto diff_weights = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DIFF_WEIGHTS); auto diff_bias = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DIFF_BIAS); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const memory_desc_wrapper diff_bias_d(pd()->diff_weights_md(1)); diff_dst += diff_dst_d.offset0(); const dim_t MB = pd()->MB(); const dim_t OC = pd()->OC(); const dim_t IC = pd()->IC_total_padded(); const auto &wmd = *pd()->diff_weights_md(); bool wei_tr = wmd.format_desc.blocking.strides[0] == 1; float alpha = 1.0, beta = 0.0; status_t st; if (wei_tr) st = extended_sgemm("N", "T", &OC, &IC, &MB, &alpha, diff_dst, &OC, src, &IC, &beta, diff_weights, &OC); else st = extended_sgemm("N", "T", &IC, &OC, &MB, &alpha, src, &IC, diff_dst, &OC, &beta, diff_weights, &IC); if (st != status::success) { return st; } if (diff_bias) { diff_bias += diff_bias_d.offset0(); constexpr dim_t blksize = 8; const dim_t OC_blocks = utils::div_up(OC, blksize); parallel(0, [&](const int ithr, const int nthr) { dim_t oc_s {0}, oc_e {0}; balance211(OC_blocks, nthr, ithr, oc_s, oc_e); oc_s = std::min(oc_s * blksize, OC); oc_e = std::min(oc_e * blksize, OC); ZENDNN_PRAGMA_OMP_SIMD() for (dim_t oc = oc_s; oc < oc_e; ++oc) { diff_bias[oc] = diff_dst[oc]; } for (dim_t mb = 1; mb < MB; ++mb) { ZENDNN_PRAGMA_OMP_SIMD() for (dim_t oc = oc_s; oc < oc_e; ++oc) { diff_bias[oc] += diff_dst[mb * OC + oc]; } } }); } return status::success; } template struct zendnn_inner_product_fwd_t<data_type::f32>; template struct zendnn_inner_product_bwd_data_t<data_type::f32>; template struct zendnn_inner_product_bwd_weights_t<data_type::f32>; } // namespace x64 } // namespace cpu } // namespace impl } // namespace zendnn // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
37.782383
112
0.613961
amd
d37c8fc507a2f7e06c434ddc362d9e0c31db6323
3,366
hpp
C++
hydra/hydra.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
2
2016-09-15T22:29:46.000Z
2017-11-30T11:16:12.000Z
hydra/hydra.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
hydra/hydra.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
// // file : hydra.hpp // in : file:///home/tim/projects/hydra/hydra/hydra.hpp // // created by : Timothée Feuillet // date: Sat Apr 23 2016 15:19:07 GMT+0200 (CEST) // // // Copyright (c) 2016 Timothée Feuillet // // 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. // #ifndef __N_396519513304418946_3159317424_HYDRA_HPP__ #define __N_396519513304418946_3159317424_HYDRA_HPP__ // NOTE: There's *_ext.hpp file in the current folder. Those files aren't included // by this header as they are the main header of some extensions. If you plan using // that extension with hydra, you may want to include // a logger for hydra (define HYDRA_NO_MESSAGES to disable logs) #include "hydra_logger.hpp" // an optional reflective support for hydra (define HYDRA_NO_REFLECTIVE_SUPPORT to disable this) // you don't need to have reflective to build and use hydra, but if the reflective header is included // hydra will generate some meta/data for it #include "hydra_reflective.hpp" // some specific exception for hydra. Also, some checks. // The macro HYDRA_DISABLE_OPTIONAL_CHECKS will disable asserts and error checking // The macro HYDRA_ENABLE_DEBUG_CHECKS will enable some asserts and error checking that may slow down a bit the code // on non-critical sections of the code, // N_DISABLE_CHECKS will disable all the asserts and error checking // N_ALLOW_DEBUG will log a lot of information about checks and asserts // NOTE: hydra assert throws exceptions (neam::hydra::exception that inherits from std::exception) #include "hydra_exception.hpp" // include the bootstrap / init files #include "init/bootstrap.hpp" #include "init/feature_requesters/gen_feature_requester.hpp" // Make GLM compatible with vulkan #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> // glm is a core dependency of hydra // include the vulkan wrapper #include "vulkan/vulkan.hpp" // include main components #include "utilities/utilities.hpp" #include "geometry/geometry.hpp" #include "threading/threading.hpp" #include "geometry/geometry.hpp" // #ifndef HYDRA_NO_RENDERER // // include the renderer (can be disabled by defining HYDRA_NO_RENDERER) // #include "renderer/renderer.hpp" // #endif namespace neam { namespace hydra { } // namespace hydra } // namespace neam #endif // __N_396519513304418946_3159317424_HYDRA_HPP__
39.139535
116
0.773321
tim42
d37e367e65d79c1d15cfc978ad9e665229347063
1,796
cpp
C++
ZEngine/src/Engine.cpp
lamarrr/RendererEngine
0c3e2bd77859efc9c278ea8735dc3340803a75b2
[ "MIT" ]
null
null
null
ZEngine/src/Engine.cpp
lamarrr/RendererEngine
0c3e2bd77859efc9c278ea8735dc3340803a75b2
[ "MIT" ]
null
null
null
ZEngine/src/Engine.cpp
lamarrr/RendererEngine
0c3e2bd77859efc9c278ea8735dc3340803a75b2
[ "MIT" ]
null
null
null
#include <pch.h> #include <Engine.h> #include <Layers/ImguiLayer.h> #include <Logging/LoggerDefinition.h> namespace ZEngine { Core::TimeStep Engine::m_delta_time = {0.0f}; Engine::Engine() : m_request_terminate(false), m_last_frame_time(0.0f) { Logging::Logger::Initialize(); ZENGINE_CORE_INFO("Engine started"); m_window.reset(ZEngine::Window::Create()); m_window->SetAttachedEngine(this); } Engine::~Engine() { m_request_terminate = false; ZENGINE_CORE_INFO("Engine stopped"); } void Engine::Initialize() { if (!m_window->HasContext()) { m_window->CreateAndActiveContext(); m_window->Initialize(); } ZENGINE_CORE_INFO("Engine initialized"); } void Engine::ProcessEvent() { m_window->PollEvent(); } void Engine::Update(Core::TimeStep delta_time) { m_window->Update(delta_time); } void Engine::Render() { m_window->Render(); } bool Engine::OnEngineClosed(Event::EngineClosedEvent& event) { m_request_terminate = true; return true; } void Engine::Start() { m_request_terminate = false; Run(); } void Engine::Run() { while (true) { if (m_request_terminate) { break; } float time = m_window->GetTime() / 1000.0f; m_delta_time = time - m_last_frame_time; m_last_frame_time = (m_delta_time >= 1.0f) ? m_last_frame_time : time + 1.0f; // waiting 1s to update ProcessEvent(); if (!m_window->GetWindowProperty().IsMinimized) { Update(m_delta_time); Render(); } } } } // namespace ZEngine
24.60274
113
0.566815
lamarrr
d37fe7ba141af0de221e7f50b37bef2e12f003fd
1,268
cpp
C++
samples/v8test/v8test.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
24
2017-08-22T15:55:34.000Z
2022-03-06T11:41:31.000Z
samples/v8test/v8test.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
6
2018-07-21T12:17:55.000Z
2021-08-12T11:27:27.000Z
samples/v8test/v8test.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
9
2017-09-13T02:32:18.000Z
2022-03-06T11:41:32.000Z
#include <smooth.h> #include <smooth/main.h> using namespace smooth; using namespace smooth::GUI::Dialogs; #include <smooth-js/v8.h> using namespace v8; Int smooth::Main() { // Create a new isolate. Isolate *isolate = v8::Isolate::New(); // Enter the created isolate. { Isolate::Scope isolateScope(isolate); // Create a stack-allocated handle scope. HandleScope handleScope(isolate); // Create a new context. Local<Context> context = Context::New(isolate); // Enter the created context for compiling and // running the hello world script. Context::Scope contextScope(context); // Create a string containing the JavaScript source code. Handle<v8::String> source = v8::String::New("'Hello' + ', World!'"); Handle<v8::String> file = v8::String::New("unnamed"); // Compile the source code. Local<Script> script = Script::Compile(source, file); // Run the script to get the result. Handle<Value> result = script->Run(); // Convert the result to an ASCII string and print it. v8::String::AsciiValue ascii(result); QuickMessage((char *) *ascii, "V8 Engine Test", GUI::Dialogs::Message::Buttons::Ok, GUI::Dialogs::Message::Icon::Information); } // Dispose the isolate. isolate->Dispose(); return 0; }
24.862745
128
0.683754
Patriccollu
d3818e72dc11164afab7eb168a02d084246f7182
7,452
cpp
C++
CrossApp/view/CAWindow.cpp
AojiaoZero/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
[ "MIT" ]
794
2015-01-01T04:59:48.000Z
2022-03-09T03:31:13.000Z
CrossApp/view/CAWindow.cpp
AojiaoZero/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
[ "MIT" ]
83
2015-01-04T06:00:35.000Z
2021-05-20T08:48:38.000Z
CrossApp/view/CAWindow.cpp
AojiaoZero/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
[ "MIT" ]
598
2015-01-02T02:38:13.000Z
2022-03-09T03:31:37.000Z
#include "CAWindow.h" #include "basics/CAPointExtension.h" #include "basics/CAApplication.h" #include "animation/CAViewAnimation.h" #include "dispatcher/CATouchDispatcher.h" #include "basics/CACamera.h" #include "script_support/CAScriptSupport.h" NS_CC_BEGIN CAWindow::CAWindow() :m_pRootViewController(nullptr) ,m_pModalViewController(nullptr) ,m_bCameraOrderDirty(true) { this->setDisplayRange(false); CACamera::_visitingCamera = nullptr; m_pDefaultCamera = CACamera::create(); this->addSubview(m_pDefaultCamera); } CAWindow::~CAWindow() { CC_SAFE_RELEASE_NULL(m_pModalViewController); CC_SAFE_RELEASE_NULL(m_pRootViewController); #if CC_ENABLE_SCRIPT_BINDING if (CAScriptEngineManager::getScriptEngineManager()) { CAScriptEngineManager::getScriptEngineManager()->getScriptEngine()->releaseAllSubviewsRecursive(this); } #endif } bool CAWindow::init() { CAView::init(); bool bRet = false; if (CAApplication* application = CAApplication::getApplication()) { this->setFrame(DRect(DPointZero, application->getWinSize())); bRet = true; } return bRet; } CAWindow *CAWindow::create() { CAWindow *pRet = new CAWindow(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet); return NULL; } } void CAWindow::onEnterTransitionDidFinish() { CAView::onEnterTransitionDidFinish(); } void CAWindow::onExitTransitionDidStart() { CAView::onExitTransitionDidStart(); } void CAWindow::setRootViewController(CrossApp::CAViewController *var) { if (m_pRootViewController) { m_pRootViewController->removeViewFromSuperview(); CC_SAFE_RELEASE_NULL(m_pRootViewController); } if (var) { var->retain(); m_pRootViewController = var; m_pRootViewController->addViewFromSuperview(this); m_pRootViewController->getView()->setZOrder(CAWindowZOrderBottom); } } CAViewController* CAWindow::getRootViewController() { return m_pRootViewController; } void CAWindow::presentModalViewController(CAViewController* controller, bool animated) { CC_RETURN_IF(controller == nullptr); CC_RETURN_IF(m_pModalViewController); CC_SAFE_RETAIN(controller); m_pModalViewController = controller; m_pModalViewController->addViewFromSuperview(this); m_pModalViewController->getView()->setZOrder(CAWindowZOrderCenter); m_pModalViewController->setViewVisibleTrue(); CAApplication::getApplication()->getTouchDispatcher()->setDispatchEventsFalse(); if (animated) { CAView* view = m_pModalViewController->getView(); DLayout layout = view->getLayout(); float y = m_obContentSize.height; layout.vertical = DVerticalLayout_T_B(y, -y); view->setLayout(layout); CAViewAnimation::beginAnimations(""); CAViewAnimation::setAnimationDuration(0.3f); CAViewAnimation::setAnimationDelay(0.1f); CAViewAnimation::setAnimationCurve(CAViewAnimation::Curve::EaseOut); CAViewAnimation::setAnimationDidStopSelector([&]() { if (m_pRootViewController) { m_pRootViewController->setViewVisibleFalse(); } CAApplication::getApplication()->getTouchDispatcher()->setDispatchEventsTrue(); }); view->setLayout(DLayoutFill); CAViewAnimation::commitAnimations(); } else { if (m_pRootViewController) { m_pRootViewController->setViewVisibleFalse(); } CAApplication::getApplication()->getTouchDispatcher()->setDispatchEventsTrue(); } } void CAWindow::dismissModalViewController(bool animated) { CC_RETURN_IF(m_pModalViewController == NULL); if (m_pRootViewController) { m_pRootViewController->setViewVisibleTrue(); } CAApplication::getApplication()->getTouchDispatcher()->setDispatchEventsFalse(); if (animated) { CAView* view = m_pModalViewController->getView(); CAViewAnimation::beginAnimations(""); CAViewAnimation::setAnimationDuration(0.3f); CAViewAnimation::setAnimationDelay(0.1f); CAViewAnimation::setAnimationCurve(CAViewAnimation::Curve::EaseOut); CAViewAnimation::setAnimationDidStopSelector([&]() { m_pModalViewController->setViewVisibleFalse(); m_pModalViewController->removeViewFromSuperview(); CC_SAFE_RELEASE_NULL(m_pModalViewController); CAApplication::getApplication()->getTouchDispatcher()->setDispatchEventsTrue(); }); DLayout layout = view->getLayout(); float y = m_obContentSize.height; layout.vertical = DVerticalLayout_T_B(y, -y); view->setLayout(layout); CAViewAnimation::commitAnimations(); } else { m_pModalViewController->setViewVisibleFalse(); m_pModalViewController->removeViewFromSuperview(); CC_SAFE_RELEASE_NULL(m_pModalViewController); CAApplication::getApplication()->getTouchDispatcher()->setDispatchEventsTrue(); } } void CAWindow::render(Renderer* renderer, const Mat4& eyeTransform, const Mat4* eyeProjection) { auto application = CAApplication::getApplication(); CACamera* defaultCamera = nullptr; const auto& transform = getViewToSuperviewTransform(); for (const auto& camera : getCameras()) { if (!camera->isVisible()) continue; CACamera::_visitingCamera = camera; if (CACamera::_visitingCamera->getCameraFlag() == CACameraFlag::DEFAULT) { defaultCamera = CACamera::_visitingCamera; } if (eyeProjection) camera->setAdditionalProjection(*eyeProjection * camera->getProjectionMatrix().getInversed()); Mat4 eyeMat4 = eyeTransform.getInversed(); camera->setAdditionalTransform(&eyeMat4); application->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); application->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, CACamera::_visitingCamera->getViewProjectionMatrix()); camera->apply(); //clear background with max depth camera->clearBackground(); //visit the scene visit(renderer, transform, 0); renderer->render(); camera->restore(); application->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); // we shouldn't restore the transform matrix since it could be used // from "update" or other parts of the game to calculate culling or something else. // camera->setNodeToParentTransform(eyeCopy); } CACamera::_visitingCamera = nullptr; } void CAWindow::removeAllSubviews() { if (m_pDefaultCamera) { m_pDefaultCamera->retain(); } CAView::removeAllSubviews(); if (m_pDefaultCamera) { addSubview(m_pDefaultCamera); m_pDefaultCamera->release(); } } static bool camera_cmp(const CACamera* a, const CACamera* b) { return a->getRenderOrder() < b->getRenderOrder(); } const std::vector<CACamera*>& CAWindow::getCameras() { if (m_bCameraOrderDirty) { stable_sort(m_vCameras.begin(), m_vCameras.end(), camera_cmp); m_bCameraOrderDirty = false; } return m_vCameras; } NS_CC_END
28.772201
130
0.673913
AojiaoZero
d38223417136f27d5ab11015755a5fb407ea3359
876
hpp
C++
sources/Common/UseUnused.hpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Common/UseUnused.hpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Common/UseUnused.hpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * Created: 2011/05/02 17:48 * Author: Eugene V. Palchukovsky * E-mail: eugene@palchukovsky.com * ------------------------------------------------------------------- * Project: TunnelEx * URL: http://tunnelex.net **************************************************************************/ #ifndef INCLUDED_FILE__TUNNELEX__UseUnused_hpp__1105021748 #define INCLUDED_FILE__TUNNELEX__UseUnused_hpp__1105021748 template<typename T> inline void UseUnused(const T &) throw() { //...// } template<typename T1, typename T2> inline void UseUnused(const T1 &, const T2 &) throw() { //...// } template<typename T1, typename T2, typename T3> inline void UseUnused(const T1 &, const T2 &, const T3 &) throw() { //...// } #endif // INCLUDED_FILE__TUNNELEX__UseUnused_hpp__1105021748
29.2
76
0.531963
palchukovsky
d38275c6387cb1d5484bba50aa63d84525071056
5,412
cpp
C++
src/main.cpp
wx257osn2/symboli_carotene
710af9e913eae012cf02d2008b21127fb422b2b5
[ "MIT" ]
null
null
null
src/main.cpp
wx257osn2/symboli_carotene
710af9e913eae012cf02d2008b21127fb422b2b5
[ "MIT" ]
null
null
null
src/main.cpp
wx257osn2/symboli_carotene
710af9e913eae012cf02d2008b21127fb422b2b5
[ "MIT" ]
null
null
null
#include<symboli/prelude.hpp> #include<optional> #include<cstddef> #include<memory> #include<iostream> #include<mutex> #include<condition_variable> #include<thread> #include"symboli/carotene/core_version.hpp" static std::optional<symboli::prelude> prelude; extern "C"{ __declspec(dllexport) unsigned int major_version(){ return SYMBOLI_CAROTENE_CORE_EXPECTED_VERSION_MAJOR; } __declspec(dllexport) unsigned int minor_version(){ return SYMBOLI_CAROTENE_CORE_EXPECTED_VERSION_MINOR; } __declspec(dllexport) unsigned int patch_version(){ return SYMBOLI_CAROTENE_CORE_EXPECTED_VERSION_PATCH; } __declspec(dllexport) void* get_prelude(){ return static_cast<void*>(&*prelude); } } class task_t{ struct input{ const char* ptr; int size; enum class message_type{ request, response }type; }input_data = {nullptr, 0}; std::mutex mtx; std::condition_variable cv_ready_to_copy; std::condition_variable cv_finish_copy; bool met_demise = false; std::vector<std::function<void(const std::vector<std::byte>&)>> request_funcs; std::vector<std::function<void(const std::vector<std::byte>&)>> response_funcs; template<input::message_type Type> void copy(const char* ptr, int size){ std::unique_lock lock{mtx}; if constexpr(Type == input::message_type::request){ if(request_funcs.empty()) return; } else if constexpr(Type == input::message_type::response){ if(response_funcs.empty()) return; } input_data.ptr = ptr; input_data.size = size; input_data.type = Type; cv_ready_to_copy.notify_one(); cv_finish_copy.wait(lock, [&]{return input_data.ptr == nullptr || met_demise;}); } public: task_t() = default; void demise(){ std::scoped_lock lock{mtx}; met_demise = true; cv_ready_to_copy.notify_all(); cv_finish_copy.notify_all(); } void request(const char* ptr, int size){ this->copy<input::message_type::request>(ptr, size); } void response(const char* ptr, int size){ this->copy<input::message_type::response>(ptr, size); } void add_request_func(std::function<void(const std::vector<std::byte>&)> f){ std::scoped_lock lock{mtx}; request_funcs.emplace_back(std::move(f)); } void add_response_func(std::function<void(const std::vector<std::byte>&)> f){ std::scoped_lock lock{mtx}; response_funcs.emplace_back(std::move(f)); } void operator()(){ while(true){ std::vector<std::byte> data; input::message_type type; { std::unique_lock lock{mtx}; cv_ready_to_copy.wait(lock, [&]{return input_data.ptr != nullptr || met_demise;}); if(met_demise) break; data.assign(reinterpret_cast<const std::byte*>(input_data.ptr), reinterpret_cast<const std::byte*>(input_data.ptr+input_data.size)); type = input_data.type; input_data = {}; cv_finish_copy.notify_one(); } switch(type){ case input::message_type::request: for(auto&& f : request_funcs)try{ f(data); }catch(const std::exception& e){ prelude->diagnostic("Carotene Core :: request", e.what()); } break; case input::message_type::response: for(auto&& f : response_funcs)try{ f(data); }catch(const std::exception& e){ prelude->diagnostic("Carotene Core :: response", e.what()); } } } } }static task = {}; static std::thread task_thread; struct lz4_decompress_safe_ext : symboli::hook_func<int(char*, char*, int, int), lz4_decompress_safe_ext>{ static int func(char* src, char* dst, int compressed_size, int dst_capacity){ const auto ret = orig(src, dst, compressed_size, dst_capacity); task.response(dst, ret); return ret; } }; struct lz4_compress_default_ext : symboli::hook_func<int(char*, char*, int, int), lz4_compress_default_ext>{ static int func(char* src, char* dst, int src_size, int dst_capacity){ const auto ret = orig(src, dst, src_size, dst_capacity); task.request(src, src_size); return ret; } }; __declspec(dllexport) void add_request_func(std::function<void(const std::vector<std::byte>&)> f){ task.add_request_func(std::move(f)); } __declspec(dllexport) void add_response_func(std::function<void(const std::vector<std::byte>&)> f){ task.add_response_func(std::move(f)); } static inline BOOL process_attach(HINSTANCE hinst){ const std::filesystem::path plugin_path{will::get_module_file_name(hinst).value()}; prelude =+ symboli::prelude::create(plugin_path.parent_path()/"symboli_prelude.dll"); prelude->enqueue_task([]{ auto libnative =+ will::get_module_handle(_T("libnative.dll")); const auto LZ4_decompress_safe_ext =+ libnative.get_proc_address<int(char*, char*, int, int)>("LZ4_decompress_safe_ext"); prelude->hook<lz4_decompress_safe_ext>(LZ4_decompress_safe_ext); const auto LZ4_compress_default_ext =+ libnative.get_proc_address<int(char*, char*, int, int)>("LZ4_compress_default_ext"); prelude->hook<lz4_compress_default_ext>(LZ4_compress_default_ext); }); task_thread = std::thread{std::ref(task)}; return TRUE; } static inline BOOL process_detach(){ if(prelude) prelude.reset(); task.demise(); task_thread.join(); return TRUE; } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)try{ switch(fdwReason){ case DLL_PROCESS_ATTACH: return process_attach(hinstDLL); case DLL_PROCESS_DETACH: return process_detach(); default: return TRUE; } }catch(std::exception& e){ ::MessageBoxA(nullptr, e.what(), "Carotene Core exception", MB_OK|MB_ICONERROR|MB_SETFOREGROUND); return FALSE; }
29.736264
136
0.72561
wx257osn2
d384787e3e9cc8b1f58c96a00e36e9680cb3d2df
150
cpp
C++
FastWindows.UI.Composition/CompositionShadow.cpp
kennykerr/Minesweeper
6f28abab141d80725beb746073d994833075b862
[ "MIT" ]
2
2019-06-13T16:29:07.000Z
2019-12-17T18:06:59.000Z
FastWindows.UI.Composition/CompositionShadow.cpp
kennykerr/Minesweeper
6f28abab141d80725beb746073d994833075b862
[ "MIT" ]
null
null
null
FastWindows.UI.Composition/CompositionShadow.cpp
kennykerr/Minesweeper
6f28abab141d80725beb746073d994833075b862
[ "MIT" ]
2
2019-09-21T13:15:58.000Z
2020-08-30T06:48:59.000Z
#include "pch.h" #include "CompositionShadow.h" #include "CompositionShadow.g.cpp" namespace winrt::FastWindows::UI::Composition::implementation { }
18.75
61
0.773333
kennykerr
d386289cb8021520069839ae270b86c1c8022387
14,864
cxx
C++
main/svx/source/sidebar/text/TextCharacterSpacingControl.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svx/source/sidebar/text/TextCharacterSpacingControl.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svx/source/sidebar/text/TextCharacterSpacingControl.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.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 "precompiled_svx.hxx" #include "TextCharacterSpacingControl.hxx" #include "TextPropertyPanel.hrc" #include <sfx2/sidebar/ResourceDefinitions.hrc> #include <svx/dialogs.hrc> #include <svx/dialmgr.hxx> #include <unotools/viewoptions.hxx> #include <editeng/kernitem.hxx> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include <sfx2/sidebar/Theme.hxx> namespace svx { namespace sidebar { TextCharacterSpacingControl::TextCharacterSpacingControl ( Window* pParent, svx::sidebar::TextPropertyPanel& rPanel, SfxBindings* pBindings) : PopupControl( pParent,SVX_RES(RID_POPUPPANEL_TEXTPAGE_SPACING)) , mrTextPropertyPanel(rPanel) , mpBindings(pBindings) , maVSSpacing (ValueSetWithTextControl::IMAGE_TEXT,this, SVX_RES(VS_SPACING)) , maLastCus (this, SVX_RES(FT_LASTCUSTOM)) //, maBorder (this, SVX_RES(CT_BORDER)) , maFTSpacing (this, SVX_RES(FT_SPACING)) , maLBKerning (this, SVX_RES(LB_KERNING)) , maFTBy (this, SVX_RES(FT_BY)) , maEditKerning (this, SVX_RES(ED_KERNING)) , mpImg (NULL) , mpImgSel (NULL) , mpStr (NULL) , mpStrTip (NULL) , maImgCus (SVX_RES(IMG_CUSTOM)) , maImgCusGrey (SVX_RES(IMG_CUSTOM_GRAY)) , maStrCus (SVX_RES(STR_CUSTOM)) , maStrCusE (SVX_RES(STR_CUSTOM_E_TIP)) //add , maStrCusC (SVX_RES(STR_CUSTOM_C_TIP)) //add , maStrCusN (SVX_RES(STR_NORMAL_TIP)) //add , maStrUnit (SVX_RES(STR_PT)) //add , mnCustomKern(0) , mnLastCus ( SPACING_NOCUSTOM ) , mbCusEnable(false) , mbVS(true) { initial(); FreeResource(); Link aLink = LINK(this, TextCharacterSpacingControl, KerningSelectHdl); maLBKerning.SetSelectHdl(aLink); aLink =LINK(this, TextCharacterSpacingControl, KerningModifyHdl); maEditKerning.SetModifyHdl(aLink); } TextCharacterSpacingControl::~TextCharacterSpacingControl() { delete[] mpImg; delete[] mpImgSel; delete[] mpStr; delete[] mpStrTip; } void TextCharacterSpacingControl::initial() { maVSSpacing.SetStyle( maVSSpacing.GetStyle()| WB_3DLOOK | WB_NO_DIRECTSELECT ); { maVSSpacing.SetControlBackground(GetSettings().GetStyleSettings().GetHighContrastMode()? GetSettings().GetStyleSettings().GetMenuColor(): sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); maVSSpacing.SetColor(GetSettings().GetStyleSettings().GetHighContrastMode()? GetSettings().GetStyleSettings().GetMenuColor(): sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); maVSSpacing.SetBackground(GetSettings().GetStyleSettings().GetHighContrastMode()? GetSettings().GetStyleSettings().GetMenuColor(): sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); maFTSpacing.SetBackground(GetSettings().GetStyleSettings().GetHighContrastMode()? GetSettings().GetStyleSettings().GetMenuColor(): sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); maFTBy.SetBackground(GetSettings().GetStyleSettings().GetHighContrastMode()? GetSettings().GetStyleSettings().GetMenuColor(): sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); } mpImg = new Image[5]; mpImg[0] = Image(SVX_RES(IMG_VERY_TIGHT)); mpImg[1] = Image(SVX_RES(IMG_TIGHT)); mpImg[2] = Image(SVX_RES(IMG_NORMAL)); mpImg[3] = Image(SVX_RES(IMG_LOOSE)); mpImg[4] = Image(SVX_RES(IMG_VERY_LOOSE)); mpImgSel = new Image[5]; mpImgSel[0] = Image(SVX_RES(IMG_VERY_TIGHT_S)); mpImgSel[1] = Image(SVX_RES(IMG_TIGHT_S)); mpImgSel[2] = Image(SVX_RES(IMG_NORMAL_S)); mpImgSel[3] = Image(SVX_RES(IMG_LOOSE_S)); mpImgSel[4] = Image(SVX_RES(IMG_VERY_LOOSE_S)); mpStr = new XubString[5]; mpStr[0] = XubString(SVX_RES(STR_VERY_TIGHT)); mpStr[1] = XubString(SVX_RES(STR_TIGHT)); mpStr[2] = XubString(SVX_RES(STR_NORMAL)); mpStr[3] = XubString(SVX_RES(STR_LOOSE)); mpStr[4] = XubString(SVX_RES(STR_VERY_LOOSE)); mpStrTip = new XubString[5]; mpStrTip[0] = XubString(SVX_RES(STR_VERY_TIGHT_TIP)); mpStrTip[1] = XubString(SVX_RES(STR_TIGHT_TIP)); mpStrTip[2] = XubString(SVX_RES(STR_NORMAL_TIP)); mpStrTip[3] = XubString(SVX_RES(STR_LOOSE_TIP)); mpStrTip[4] = XubString(SVX_RES(STR_VERY_LOOSE_TIP)); for (int i=0;i<5;i++) maVSSpacing.AddItem(mpImg[i], &mpImgSel[i],mpStr[i],&mpStrTip[i]); maVSSpacing.AddItem( maImgCus, 0, maStrCus, 0 ); maVSSpacing.SetNoSelection(); Link aLink = LINK(this, TextCharacterSpacingControl,VSSelHdl ); maVSSpacing.SetSelectHdl(aLink); maVSSpacing.StartSelection(); maVSSpacing.Show(); } void TextCharacterSpacingControl::ToGetFocus() { if(!mbVS) maLBKerning.GrabFocus(); else maVSSpacing.GrabFocus(); } void TextCharacterSpacingControl::Rearrange(bool bLBAvailable,bool bAvailable, long nKerning) { mbVS = true; maVSSpacing.SetNoSelection(); SvtViewOptions aWinOpt( E_WINDOW, SIDEBAR_SPACING_GLOBAL_VALUE ); if ( aWinOpt.Exists() ) { ::com::sun::star::uno::Sequence < ::com::sun::star::beans::NamedValue > aSeq = aWinOpt.GetUserData(); ::rtl::OUString aTmp; if ( aSeq.getLength()) aSeq[0].Value >>= aTmp; String aWinData( aTmp ); mnCustomKern = aWinData.ToInt32(); mnLastCus = SPACING_CLOSE_BY_CUS_EDIT; mbCusEnable = true; } else { mnLastCus = SPACING_NOCUSTOM; mbCusEnable = false; } if( !mnLastCus ) { maVSSpacing.ReplaceItemImages(6, maImgCusGrey,0); } else { //set custom tips maVSSpacing.ReplaceItemImages(6, maImgCus,0); if(mnCustomKern > 0) { String aStrTip( maStrCusE); //LAST CUSTOM no tip defect //add aStrTip.Append( String::CreateFromDouble( (double)mnCustomKern / 10)); aStrTip.Append( xub_Unicode(' ') ); aStrTip.Append(maStrUnit); // modify maVSSpacing.SetItemText(6,aStrTip); } else if(mnCustomKern < 0) { String aStrTip(maStrCusC) ; //LAST CUSTOM no tip defect //add aStrTip.Append( String::CreateFromDouble( (double)-mnCustomKern / 10)); aStrTip.Append( xub_Unicode( ' ' ) ); aStrTip.Append(maStrUnit); // modify maVSSpacing.SetItemText( 6, aStrTip ); } else { String aStrTip(maStrCusN) ; //LAST CUSTOM no tip defect //add maVSSpacing.SetItemText( 6, aStrTip ); } } if(bLBAvailable && bAvailable) { maLBKerning.Enable(); maFTSpacing.Enable(); SfxMapUnit eUnit = mrTextPropertyPanel.GetSpaceController().GetCoreMetric(); MapUnit eOrgUnit = (MapUnit)eUnit; MapUnit ePntUnit( MAP_POINT ); long nBig = maEditKerning.Normalize(nKerning); nKerning = LogicToLogic( nBig, eOrgUnit, ePntUnit ); if ( nKerning > 0 ) { maFTBy.Enable(); maEditKerning.Enable(); maEditKerning.SetMax( 9999 ); maEditKerning.SetLast( 9999 ); maEditKerning.SetValue( nKerning ); maLBKerning.SelectEntryPos( SIDEBAR_SPACE_EXPAND ); if(nKerning == 30) { maVSSpacing.SelectItem(4); } else if(nKerning == 60) { maVSSpacing.SelectItem(5); } else { maVSSpacing.SetNoSelection(); maVSSpacing.SelectItem(0); mbVS = false; } } else if ( nKerning < 0 ) { maFTBy.Enable(); maEditKerning.Enable(); maEditKerning.SetValue( -nKerning ); maLBKerning.SelectEntryPos( SIDEBAR_SPACE_CONDENSED ); long nMax = mrTextPropertyPanel.GetSelFontSize()/6; maEditKerning.SetMax( maEditKerning.Normalize( nMax ), FUNIT_POINT ); maEditKerning.SetLast( maEditKerning.GetMax( maEditKerning.GetUnit() ) ); if( nKerning == -30 ) { maVSSpacing.SelectItem(1); } else if( nKerning == -15 ) { maVSSpacing.SelectItem(2); } else { maVSSpacing.SetNoSelection(); maVSSpacing.SelectItem(0); mbVS = false; } } else { maVSSpacing.SelectItem(3); maLBKerning.SelectEntryPos( SIDEBAR_SPACE_NORMAL ); maFTBy.Disable(); maEditKerning.Disable(); maEditKerning.SetValue( 0 ); maEditKerning.SetMax( 9999 ); maEditKerning.SetLast( 9999 ); } } else if(bLBAvailable && !bAvailable) { //modified maVSSpacing.SetNoSelection(); maVSSpacing.SelectItem(0); mbVS = false; maLBKerning.Enable(); maFTSpacing.Enable(); maLBKerning.SetNoSelection(); maEditKerning.SetText(String()); maEditKerning.Disable(); maFTBy.Disable(); } else { maVSSpacing.SetNoSelection(); maVSSpacing.SelectItem(0); mbVS = false; maEditKerning.SetText(String()); maLBKerning.SetNoSelection(); maLBKerning.Disable(); maFTSpacing.Disable(); maEditKerning.Disable(); maFTBy.Disable(); } GetFocus(); maVSSpacing.Format(); maVSSpacing.StartSelection(); } IMPL_LINK(TextCharacterSpacingControl, VSSelHdl, void *, pControl) { mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; if(pControl == &maVSSpacing) { sal_uInt16 iPos = maVSSpacing.GetSelectItemId(); short nKern = 0; SfxMapUnit eUnit = mrTextPropertyPanel.GetSpaceController().GetCoreMetric(); long nVal = 0; if(iPos == 1) { nVal = LogicToLogic(30, MAP_POINT, (MapUnit)eUnit); nKern = (short)maEditKerning.Denormalize(nVal); SvxKerningItem aKernItem(-nKern, SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(-nKern); mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; } else if(iPos == 2) { nVal = LogicToLogic(15, MAP_POINT, (MapUnit)eUnit); nKern = (short)maEditKerning.Denormalize(nVal); SvxKerningItem aKernItem(-nKern, SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(-nKern); mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; } else if(iPos == 3) { SvxKerningItem aKernItem(0, SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(0); mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; } else if(iPos == 4) { nVal = LogicToLogic(30, MAP_POINT, (MapUnit)eUnit); nKern = (short)maEditKerning.Denormalize(nVal); SvxKerningItem aKernItem(nKern, SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(nKern); mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; } else if(iPos == 5) { nVal = LogicToLogic(60, MAP_POINT, (MapUnit)eUnit); nKern = (short)maEditKerning.Denormalize(nVal); SvxKerningItem aKernItem(nKern, SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(nKern); mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; } else if(iPos == 6) { //modified if(mbCusEnable) { nVal = LogicToLogic(mnCustomKern, MAP_POINT, (MapUnit)eUnit); nKern = (short)maEditKerning.Denormalize(nVal); SvxKerningItem aKernItem(nKern , SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(nKern); mnLastCus = SPACING_CLOSE_BY_CLICK_ICON; } else { maVSSpacing.SetNoSelection(); //add , set no selection and keep the last select item maVSSpacing.Format(); Invalidate(); maVSSpacing.StartSelection(); } //modify end } if(iPos < 6 || (iPos == 6 && mbCusEnable)) //add mrTextPropertyPanel.EndSpacingPopupMode(); } return 0; } IMPL_LINK(TextCharacterSpacingControl, KerningSelectHdl, ListBox*, EMPTYARG) { if ( maLBKerning.GetSelectEntryPos() > 0 ) { maFTBy.Enable(); maEditKerning.Enable(); } else { maEditKerning.SetValue( 0 ); maFTBy.Disable(); maEditKerning.Disable(); } if ( maVSSpacing.GetSelectItemId() > 0 ) { maVSSpacing.SetNoSelection(); maVSSpacing.SelectItem(0); maVSSpacing.Format(); Invalidate(); maVSSpacing.StartSelection(); } KerningModifyHdl( NULL ); return 0; } IMPL_LINK(TextCharacterSpacingControl, KerningModifyHdl, MetricField*, EMPTYARG) { if ( maVSSpacing.GetSelectItemId() > 0 ) { maVSSpacing.SetNoSelection(); maVSSpacing.SelectItem(0); maVSSpacing.Format(); Invalidate(); maVSSpacing.StartSelection(); } sal_uInt16 nPos = maLBKerning.GetSelectEntryPos(); short nKern = 0; SfxMapUnit eUnit = mrTextPropertyPanel.GetSpaceController().GetCoreMetric(); mnLastCus = SPACING_CLOSE_BY_CUS_EDIT; if ( nPos == SIDEBAR_SPACE_EXPAND || nPos == SIDEBAR_SPACE_CONDENSED ) { long nTmp = static_cast<long>(maEditKerning.GetValue()); if ( nPos == SIDEBAR_SPACE_CONDENSED ) { long nMax = mrTextPropertyPanel.GetSelFontSize()/6; maEditKerning.SetMax( maEditKerning.Normalize( nMax ), FUNIT_TWIP ); maEditKerning.SetLast( maEditKerning.GetMax( maEditKerning.GetUnit() ) ); if(nTmp > maEditKerning.GetMax()) nTmp = maEditKerning.GetMax(); mnCustomKern = -nTmp; long nVal = LogicToLogic( nTmp, MAP_POINT, (MapUnit)eUnit ); nKern = (short)maEditKerning.Denormalize( nVal ); nKern *= - 1; } else { maEditKerning.SetMax( 9999 ); maEditKerning.SetLast( 9999 ); if(nTmp > maEditKerning.GetMax(FUNIT_TWIP)) nTmp = maEditKerning.GetMax(FUNIT_TWIP); mnCustomKern = nTmp; long nVal = LogicToLogic( nTmp, MAP_POINT, (MapUnit)eUnit ); nKern = (short)maEditKerning.Denormalize( nVal ); } } else { mnCustomKern = 0; } SvxKerningItem aKernItem(nKern, SID_ATTR_CHAR_KERNING); mpBindings->GetDispatcher()->Execute(SID_ATTR_CHAR_KERNING, SFX_CALLMODE_RECORD, &aKernItem, 0L); mrTextPropertyPanel.SetSpacing(nKern); return 0; } short TextCharacterSpacingControl::GetLastCustomState() { return mnLastCus; } long TextCharacterSpacingControl::GetLastCustomValue() { return mnCustomKern; } }} // end of namespace sidebar
31.35865
103
0.702301
Grosskopf
d3882f99f5ea555e5243b55d21491000e1af6b57
907
hpp
C++
android-31/android/widget/RemoteViews_RemoteResponse.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-30/android/widget/RemoteViews_RemoteResponse.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/widget/RemoteViews_RemoteResponse.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" namespace android::app { class PendingIntent; } namespace android::content { class Intent; } class JString; namespace android::widget { class RemoteViews_RemoteResponse : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit RemoteViews_RemoteResponse(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} RemoteViews_RemoteResponse(QJniObject obj); // Constructors RemoteViews_RemoteResponse(); // Methods static android::widget::RemoteViews_RemoteResponse fromFillInIntent(android::content::Intent arg0); static android::widget::RemoteViews_RemoteResponse fromPendingIntent(android::app::PendingIntent arg0); android::widget::RemoteViews_RemoteResponse addSharedElement(jint arg0, JString arg1) const; }; } // namespace android::widget
25.194444
167
0.755237
YJBeetle
d389d852a82d441ad303edaa0ff6fd33cf7150fc
1,236
cpp
C++
cpp/sowcpp/src/ch14/prog14-8.cpp
newnix/Forge
6d18105460fabc20592ed3c29813173cdb57d512
[ "BSD-3-Clause-Clear" ]
null
null
null
cpp/sowcpp/src/ch14/prog14-8.cpp
newnix/Forge
6d18105460fabc20592ed3c29813173cdb57d512
[ "BSD-3-Clause-Clear" ]
null
null
null
cpp/sowcpp/src/ch14/prog14-8.cpp
newnix/Forge
6d18105460fabc20592ed3c29813173cdb57d512
[ "BSD-3-Clause-Clear" ]
null
null
null
// Practice program 14-8 // Found on page 830 // This program demonstrates the overloaded '-' and '+' operators #include <iostream> #include "feetInches.h" using namespace std; int main() { int feet, inch; // Hold the input for feet and inch // Create three feetInches objects. // Default args for constructors will be used. feetInches first, second, third; // Get a distance from the user cout << "Enter a distance in feet and inches: "; cin >> feet >> inch; // Store the distance in the first object first.setFeet(feet); first.setInch(inch); // Get another distance cout << "Enter another distance in feet and inches: "; cin >> feet >> inch; // Store the distance in second second.setFeet(feet); second.setInch(inch); // Assign first + second to third third = first + second; // Display the results cout << "First + Second = "; cout << third.getF() << " feet, "; cout << third.getI() << " inches. \n"; // Assign first - second to third third = first - second; // Display the results again cout << "First - Second = "; cout << third.getF() << " feet, "; cout << third.getI() << " inches.\n"; return 0; }
23.320755
65
0.607605
newnix
d38c08a43bd10e184ae306b6061d067837ea318c
1,766
cpp
C++
async/examples/sockio/server/main.cpp
Rahul18728/cerl
8d90c03b2ffe397021bcb8c7198c713acf840bb4
[ "MIT" ]
443
2015-03-14T06:04:45.000Z
2022-01-10T01:30:56.000Z
async/examples/sockio/server/main.cpp
Rahul18728/cerl
8d90c03b2ffe397021bcb8c7198c713acf840bb4
[ "MIT" ]
null
null
null
async/examples/sockio/server/main.cpp
Rahul18728/cerl
8d90c03b2ffe397021bcb8c7198c713acf840bb4
[ "MIT" ]
125
2015-03-14T13:08:04.000Z
2021-12-08T13:03:29.000Z
//test socket io through epoll // //#define CERL_VERBOSE //#include <async/Io.h> //#include <netinet/in.h> //#include <arpa/inet.h> //#include <async/Socket.h> #include <async/Application.h> #include <sys/times.h> void cerl_callback run(LPVOID param) { cerl::FiberParam p(param); int socket1 = cerl::listenSocket(5039); if(socket1 == -1) { p.service->quit(); return; } cerl::ListenSocket s; if (s.open_handle((SOCKET)socket1) != S_OK) { CERL_VLOG("test", ("Listen Socket failed\n")); p.service->quit(); close(socket1); return; } SOCKET clisock = s.accept(); if(clisock == 0) { CERL_VLOG("test", ("Accept failed\n")); close((int)clisock); p.service->quit(); return; } cerl::SocketFileObject fileObj; fileObj.open_handle((SOCKET)clisock); cerl::SocketFile file(fileObj); printf("socket file opened.\n"); //char buf[64]; int data; tms tm; clock_t t = times(&tm); printf("start: %d\n", t); for(int i =0; i<10000; i++) { //printf("******************\nwait for client\n"); //printf("round # %d\n", i); ptrdiff_t n = file.read_some(&data, sizeof(data)); if(n == 0) { printf("connection failed.\n"); break; } //printf("message from client: %s\n******************\n", buf); //if(!strcmp(buf, "quit")) // break; //printf("******************\nresponse to client\n"); n = file.write_some(&data, sizeof(data)); if(n == 0) { printf("connection failed.\n"); break; } //printf("response over.\n******************\n"); } NS_STDEXT::print("10000 msg in %d ms\n", (int)((double)(times(&tm)-t)*1000)/sysconf(_SC_CLK_TCK)); fileObj.close(); p.service->quit(); } int main() { cerl::Application app; app.run(run, NULL, 16000); printf("leaving main fun\n"); return 0; }
17.485149
99
0.593431
Rahul18728
d393486ac84f477891c2be47dbe0212e403407dc
2,748
cpp
C++
str/apps/test/LifterTest.cpp
Tamiyas/etrobocon2018
c2c6921dae4ddd1ea98742bcf992777084e4e5dd
[ "MIT" ]
1
2018-07-29T13:31:03.000Z
2018-07-29T13:31:03.000Z
str/apps/test/LifterTest.cpp
Tamiyas/etrobocon2018
c2c6921dae4ddd1ea98742bcf992777084e4e5dd
[ "MIT" ]
60
2018-07-28T16:29:32.000Z
2019-01-08T06:04:05.000Z
str/apps/test/LifterTest.cpp
Tamiyas/etrobocon2018
c2c6921dae4ddd1ea98742bcf992777084e4e5dd
[ "MIT" ]
2
2018-08-07T08:02:07.000Z
2018-08-23T07:08:54.000Z
/** * LifterTest.cpp */ /* コンパイル(平木場) $ g++-7 LifterTest.cpp ../src/Lifter.cpp gtest_main.o gtest-all.o -I../include -I../../googletest/googletest/include */ #include "Lifter.h" // このヘッダファイルのcppファイルをテスト #include <gtest/gtest.h> #include <iostream> namespace etrobocon2018_test { class LifterTest : public ::testing::Test { protected: virtual void SetUp() { lifter.controller.liftMotor.count = 145000; lifter.reset(); } Controller controller; Lifter lifter{ controller }; std::int32_t getDefaultCount() { return lifter.default_count; } void addDefaultCount(int count) { lifter.default_count -= count; } std::int8_t limitPwm(std::int8_t pwm) { return lifter.limitPwm(pwm); } std::int32_t getCount() { return lifter.controller.liftMotor.getCount(); } }; TEST_F(LifterTest, setDefaultCountTest) { ASSERT_EQ(getDefaultCount(), getCount()); } TEST_F(LifterTest, getCurrentAngleTest1) { addDefaultCount(90); ASSERT_EQ(lifter.getCurrentAngle(), 90); } TEST_F(LifterTest, getCurrentAngleTest2) { ASSERT_EQ(lifter.getCurrentAngle(), 0); } TEST_F(LifterTest, limitPwmTest1) { ASSERT_EQ(limitPwm(99), 99); ASSERT_EQ(limitPwm(100), 100); ASSERT_EQ(limitPwm(101), 100); } TEST_F(LifterTest, limitPwmTest2) { ASSERT_EQ(limitPwm(2), 2); ASSERT_EQ(limitPwm(1), 1); ASSERT_EQ(limitPwm(0), 1); } TEST_F(LifterTest, limitPwmTest3) { ASSERT_EQ(limitPwm(-100), 1); ASSERT_EQ(limitPwm(-50), 1); ASSERT_EQ(limitPwm(-1), 1); } TEST_F(LifterTest, limitPwmTest4) { ASSERT_EQ(limitPwm(10), 10); ASSERT_EQ(limitPwm(50), 50); ASSERT_EQ(limitPwm(80), 80); } TEST_F(LifterTest, liftUpTest1) { lifter.liftUp(90); ASSERT_LE(lifter.getCurrentAngle(), 93); ASSERT_GE(lifter.getCurrentAngle(), 90); } TEST_F(LifterTest, liftUpTest2) { lifter.liftUp(45); ASSERT_LE(lifter.getCurrentAngle(), 48); ASSERT_GE(lifter.getCurrentAngle(), 45); } TEST_F(LifterTest, liftDownTest1) { lifter.liftDown(90); ASSERT_GE(lifter.getCurrentAngle(), -93); ASSERT_LE(lifter.getCurrentAngle(), -90); } TEST_F(LifterTest, liftDownTest2) { lifter.liftDown(45); ASSERT_GE(lifter.getCurrentAngle(), -48); ASSERT_LE(lifter.getCurrentAngle(), -45); } TEST_F(LifterTest, defaultSetTest1) { lifter.liftUp(90); ASSERT_GE(lifter.getCurrentAngle(), 90); lifter.defaultSet(); ASSERT_GE(lifter.getCurrentAngle(), -2); ASSERT_LE(lifter.getCurrentAngle(), 2); } TEST_F(LifterTest, defaultSetTest2) { lifter.defaultSet(); ASSERT_GE(lifter.getCurrentAngle(), -2); ASSERT_LE(lifter.getCurrentAngle(), 2); } } // namespace etrobocon2018_test
24.105263
87
0.6754
Tamiyas
d394cb153c37f5319d6618c9646ad971c0b739f1
12,604
cpp
C++
src/server/Xml/XslDoc.cpp
anewholm/generalserver
99321562921c317f1ef14a2b84abfe91f0f871b6
[ "X11" ]
null
null
null
src/server/Xml/XslDoc.cpp
anewholm/generalserver
99321562921c317f1ef14a2b84abfe91f0f871b6
[ "X11" ]
null
null
null
src/server/Xml/XslDoc.cpp
anewholm/generalserver
99321562921c317f1ef14a2b84abfe91f0f871b6
[ "X11" ]
null
null
null
//platform agnostic file #include "Xml/XslDoc.h" #include "IXml/IXmlBaseNode.h" #include "IXml/IXmlLibrary.h" #include "IXml/IXslNode.h" #include "Xml/XmlAdminQueryEnvironment.h" #include "Debug.h" #include "Xml/XmlNodeList.h" #include "Utilities/container.c" using namespace std; namespace general_server { //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- const char *XslDoc::name() const { const XmlAdminQueryEnvironment ibqe(mmParent(), this); //XslDoc::name() const char *sName; const IXmlBaseDoc *pDocType = queryInterface((const IXmlBaseDoc*) 0); const IXmlBaseNode *pRootNode = pDocType->rootNode(&ibqe); if (pRootNode) sName = pRootNode->attributeValue(&ibqe, "name", NAMESPACE_REPOSITORY); else sName = MM_STRDUP("stylesheet"); return sName; } //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- XslTransformContext::XslTransformContext(const IMemoryLifetimeOwner *pMemoryLifetimeOwner, const IXmlQueryEnvironment *pOwnerQE): MemoryLifetimeOwner(pMemoryLifetimeOwner), m_pOwnerQE(pOwnerQE) { assert(m_pOwnerQE); } XslTransformContext::~XslTransformContext() {} void XslTransformContext::setQueryEnvironment(const IXmlQueryEnvironment *pOwnerQE) {m_pOwnerQE = pOwnerQE;assert(m_pOwnerQE);} const IXmlQueryEnvironment *XslTransformContext::ownerQE() const {return m_pOwnerQE;} const char *XslTransformContext::currentSourceNodeXPath() const { const XmlAdminQueryEnvironment ibqe_error_reporting(this, sourceDoc()); const char *sXPath = 0; const IXmlBaseNode *pNode = 0; try { if (pNode = sourceNode(this)) sXPath = pNode->uniqueXPathToNode(&ibqe_error_reporting); } catch (ExceptionBase &eb) { sXPath = eb.toString(); } //free up if (pNode) delete pNode; return (sXPath ? sXPath : "<unknown>"); } const char *XslTransformContext::currentXSLTemplateXPath() const { const XmlAdminQueryEnvironment ibqe_error_reporting(this, commandDoc()); const char *sXPath = 0; const IXslCommandNode *pNode = 0; const IXmlBaseNode *pNodeType = 0; try { if (pNode = templateNode(this)) { if (pNodeType = pNode->queryInterface((const IXmlBaseNode*) 0)) sXPath = pNodeType->uniqueXPathToNode(&ibqe_error_reporting); } } catch (ExceptionBase &eb) { sXPath = eb.toString(); } //free up if (pNode) delete pNode; return (sXPath ? sXPath : "<unknown>"); } const char *XslTransformContext::currentXSLCommandXPath() const { const XmlAdminQueryEnvironment ibqe_error_reporting(this, commandDoc()); const char *sXPath = 0; const IXmlBaseNode *pNode = 0; try { if (pNode = instructionNode(this)) sXPath = pNode->uniqueXPathToNode(&ibqe_error_reporting); } catch (ExceptionBase &eb) { sXPath = eb.toString(); } //free up if (pNode) delete pNode; return (sXPath ? sXPath : "<unknown>"); } void XslTransformContext::handleError(const char *sErrorMessage) { //when the native XML library throws an XPATH error // we arrive here in the agnostic layer to deal with it // caught by our native library generic error handler // which will bubble up to the XSLTException catch layer if we throw here //XPathException() can also bubble up from our own custom xpath functions // directly to the XSLTException catch layer // without the native library generic error handler getting involved IXslTransformContext *pTC = 0; const IXmlBaseNode *pCommandNode = 0; iErrorPolicy er = throw_error; //error policies if (pTC = m_pOwnerQE->transformContext()) { if (pCommandNode = pTC->literalCommandNode(m_pOwnerQE)) er = pCommandNode->errorPolicy(); //pQE as MM } //free up if (pCommandNode) delete pCommandNode; //if (pTC) delete pTC; //server freed if (er == throw_error) throw XSLTException(this, MM_STRDUP(sErrorMessage)); else Debug::warn("error suppressed by xsl:error-policy"); } //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- XslXPathFunctionContext::XslXPathFunctionContext(const IMemoryLifetimeOwner *pMemoryLifetimeOwner, const IXmlQueryEnvironment *pOwnerQE): MemoryLifetimeOwner(pMemoryLifetimeOwner), //usually just a writeable pOwnerQE m_pOwnerQE(pOwnerQE) { assert(m_pOwnerQE); } XslXPathFunctionContext::~XslXPathFunctionContext() {} void XslXPathFunctionContext::setQueryEnvironment(const IXmlQueryEnvironment *pOwnerQE) {m_pOwnerQE = pOwnerQE;assert(m_pOwnerQE);} const IXmlQueryEnvironment *XslXPathFunctionContext::ownerQE() const {return m_pOwnerQE;} void XslXPathFunctionContext::handleError(const char *sErrorMessage) { //when the native XML library throws an XPATH error // we arrive here in the agnostic layer to deal with it // caught by our native library generic error handler // which will bubble up to the XSLTException catch layer if we throw here //XPathException() can also bubble up from our own custom xpath functions // directly to the XSLTException catch layer // without the native library generic error handler getting involved IXslTransformContext *pTC = 0; const IXmlBaseNode *pCommandNode = 0; iErrorPolicy er = throw_error; //error policies if (pTC = m_pOwnerQE->transformContext()) { if (pCommandNode = pTC->literalCommandNode(m_pOwnerQE)) er = pCommandNode->errorPolicy(); //pQE as MM } //free up if (pCommandNode) delete pCommandNode; //if (pTC) delete pTC; //server freed if (er == throw_error) throw XPathException(this, MM_STRDUP(sErrorMessage)); else Debug::warn("error suppressed by xsl:error-policy"); } const char *XslXPathFunctionContext::currentXSLCommandXPath() const { //caller frees result const char *ret = 0; IXslTransformContext *pTCtxt; if (pTCtxt = m_pOwnerQE->transformContext()) ret = pTCtxt->currentXSLCommandXPath(); //free up //if (pTCtxt) delete pTCtxt; //pointer in to pQE return ret; } const char *XslXPathFunctionContext::currentXSLTemplateXPath() const { //caller frees result const char *ret = 0; IXslTransformContext *pTCtxt; if (pTCtxt = m_pOwnerQE->transformContext()) ret = pTCtxt->currentXSLTemplateXPath(); //free up //if (pTCtxt) delete pTCtxt; //pointer in to pQE return ret; } const char *XslXPathFunctionContext::toString() const { return xpath(); } IXmlBaseNode *XslXPathFunctionContext::popInterpretNodeFromXPathFunctionCallStack(const bool bThrowOnNot1) { XmlNodeList<IXmlBaseNode>::iterator iNode; IXmlBaseNode *pNode = 0; XmlNodeList<IXmlBaseNode> *pNodes = 0; UNWIND_EXCEPTION_BEGIN { if (pNodes = popInterpretNodeListFromXPathFunctionCallStack()) { if (bThrowOnNot1 && pNodes->size() != 1) throw XPathNot1Nodes(this); else { for (iNode = pNodes->begin(); iNode != pNodes->end(); iNode++) { if (!pNode) pNode = *iNode; else delete *iNode; } } } } UNWIND_EXCEPTION_END; //free up if (pNodes) delete pNodes; UNWIND_EXCEPTION_THROW; return pNode; } //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- XslDoc::XslDoc(IXslTransformContext *pCtxt): m_pCtxt(pCtxt), m_pSourceNode(0) {} XslDoc::XslDoc(): m_pCtxt(0), m_pSourceNode(0) {} const IXmlBaseNode *XslDoc::sourceNode() const { return m_pSourceNode; } const IXmlBaseDoc *XslDoc::sourceDoc() const { //m_pSourceNode will also lock the source document return (m_pSourceNode ? m_pSourceNode->document() : NULL); } const IXmlBaseNode *XslDoc::sourceNode(const IXmlBaseNode *pSourceNode) { assert(pSourceNode); m_pSourceNode = pSourceNode; return m_pSourceNode; } XmlNodeList<IXmlBaseNode> *XslDoc::includes() { XmlAdminQueryEnvironment ibqe(this, this); //includes() return getMultipleNodes(&ibqe, "/xsl:stylesheet/xsl:include[@href and not(@xpath)]"); } size_t XslDoc::translateIncludes(XmlNodeList<IXmlBaseNode> *pvIncludes, IXmlQueryEnvironment *pMasterDocQE, const IXmlBaseNode *pIncludeDirectoryNode) { //this is enacted on a COPY of the XSL node in the transform() function //this is a live update of xsl:include @hrefs. Not a copy //USED mostly on client-side relative @hrefs that need translating to server-side @xpath //location of xsl:include same as: // C++ clearMyCachedStylesheetsRecursive() // C++ translateIncludes() @href => @xpath // LibXml2: xsl:include processing (of @xpath) during server side compilation // map_url_to_stylesheet_model.xsl REST based client xsl:include requests // AJAX client_stylesheet_transform.xsl xsl:include include directly in main xsl:stylesheet request size_t iUpdates = 0; const IXmlBaseNode *pIncludeNode = 0, *pIncludedNode = 0; const IXslStylesheetNode *pIncludedStylesheetNode = 0; typename XmlNodeList<IXmlBaseNode>::iterator iInclude; const char *sHREF = 0, *sXPath = 0; //get and alter @hrefs, if @xpath not there... //works only from the top level xsl:stylesheet node //xsl:includes have been altered in LibXml2 to accept @xpath instead of @href which is faster ensurePrefixedNamespaceDefinition(NAMESPACE_XSL_ALIAS, NAMESPACE_XSL); UNWIND_EXCEPTION_BEGIN { //NOTE: the disembodied stylesheet should have an xpath pointer to it's original parent in the world for (iInclude = pvIncludes->begin(); iInclude != pvIncludes->end(); iInclude++) { pIncludeNode = (*iInclude); sXPath = pIncludeNode->attributeValue(pMasterDocQE, "xpath"); if (sXPath) { if (pIncludedNode = pIncludeDirectoryNode->getSingleNode(pMasterDocQE, sXPath)) pIncludedStylesheetNode = pIncludedNode->queryInterface((const IXslStylesheetNode*) 0); } else { sHREF = pIncludeNode->attributeValue(pMasterDocQE, "href"); if (!sHREF) throw FailedToResolveXSLIncludePath(this, MM_STRDUP("no @xpath or @href")); if (xmlLibrary()->maybeAbsoluteXPath(pMasterDocQE, sHREF)) Debug::report("xsl:include @href=[%s] not verified because cannot resolve class references against non-ids-populated disembodied new doc yet", sXPath); pIncludedStylesheetNode = pIncludeDirectoryNode->relativeXSLIncludeFileSystemPathToXSLStylesheetNode(pMasterDocQE, sHREF); } //TODO: and recurse sub-includes //GDB: p *dynamic_cast<LibXmlBaseDoc*>(this)->m_oDoc if (!pIncludedStylesheetNode) throw FailedToResolveXSLIncludePath(this, MM_STRDUP("xpath result empty")); else { //register xpath parameter for later //TODO: should we TXml this register xpath parameter for later? better that it is dynamic? pIncludeNode->setAttribute(pMasterDocQE, "xpath", sXPath); pIncludeNode->removeAttribute(pMasterDocQE, "href"); iUpdates++; } //free up if (pIncludedStylesheetNode) {delete pIncludedStylesheetNode; pIncludedStylesheetNode = 0;} if (sHREF) {MM_FREE(sHREF); sHREF = 0;} if (sXPath) {MM_FREE(sXPath); sXPath = 0;} } //for loop } UNWIND_EXCEPTION_END; //free up if (pIncludedStylesheetNode) delete pIncludedStylesheetNode; if (sHREF) MM_FREE(sHREF); if (sXPath) MM_FREE(sXPath); UNWIND_EXCEPTION_THROW; return iUpdates; } }
38.901235
220
0.625754
anewholm
d3972eff3c04e9c7672abe7aca6751b1f400fb15
6,838
cpp
C++
source/GameApplicationLayer/Modules/ResourceCache/ResourceCache.cpp
Pedrexus/project-vendetta
ed0eb6df1d306f465eef52e1794ea1e0bc277fbe
[ "MIT" ]
null
null
null
source/GameApplicationLayer/Modules/ResourceCache/ResourceCache.cpp
Pedrexus/project-vendetta
ed0eb6df1d306f465eef52e1794ea1e0bc277fbe
[ "MIT" ]
null
null
null
source/GameApplicationLayer/Modules/ResourceCache/ResourceCache.cpp
Pedrexus/project-vendetta
ed0eb6df1d306f465eef52e1794ea1e0bc277fbe
[ "MIT" ]
null
null
null
#include "ResourceCache.h" #include "ResourceLoaders/DefaultResourceLoader.h" #include <macros.h> #include <Helpers/Functions.h> ResourceCache::ResourceCache(const unsigned int size, IResourceFile* file) : m_cacheSize(size), m_allocated(0), m_file(file) {} ResourceCache::~ResourceCache() { while (!m_lru.empty()) { FreeOneResource(); } SAFE_DELETE(m_file); }; bool ResourceCache::Init() { if (m_file->Open()) { // the most generic loaders come last in the list and the most specific loaders come first RegisterLoader(std::shared_ptr<IResourceLoader>{ NEW DefaultResourceLoader() }); LOG_INFO("Default Resource Loader registered"); return true; } LOG_ERROR("Failed to open resource file"); return false; } void ResourceCache::RegisterLoader(std::shared_ptr<IResourceLoader> loader) { m_resourceLoaders.push_front(loader); } std::shared_ptr<ResourceHandle> ResourceCache::GetHandle(Resource* r) { auto handle = Find(r); if (!handle) { handle = Load(r); if (!handle) { LOG_ERROR("Unable to load resource"); return nullptr; } } else { Update(handle); } return handle; } std::shared_ptr<ResourceHandle> ResourceCache::Find(Resource* r) { auto i = m_resources.find(r->GetName()); if (i == m_resources.end()) return nullptr; return i->second; } // Creates a new resource and add it to the lru list and map std::shared_ptr<ResourceHandle> ResourceCache::Load(Resource* r) { std::shared_ptr<ResourceHandle> handle; // traverse m_resourceLoaders looking for the right loader // m_resourceLoaders goes from specific loaders to generic ones std::shared_ptr<IResourceLoader> loader = *std::find_if( m_resourceLoaders.begin(), m_resourceLoaders.end(), [r] (std::shared_ptr<IResourceLoader> testLoader) { return WildcardMatch(testLoader->GetPattern().c_str(), r->GetName().c_str()); } ); if (!loader) { LOG_ERROR("Default resource loader not found!"); return nullptr; } size rawSize = m_file->GetRawResourceSize(*r); if (rawSize < 0) { LOG_ERROR("Resource size returned -1. Resource not found!"); return nullptr; } // allocates an empty string size allocSize = rawSize + loader->AddNullZero(); char* rawBuffer = loader->UseRawFile() ? Allocate(allocSize) : NEW char[allocSize]; memset(rawBuffer, 0, allocSize); // fills the first allocSize bytes in rawBuffer to 0 if (rawBuffer == nullptr || m_file->GetRawResource(*r, rawBuffer) == 0) { LOG_ERROR("Resource cache out of memory"); return nullptr; } char* buffer = nullptr; size size = 0; if (loader->UseRawFile()) { buffer = rawBuffer; handle = std::shared_ptr<ResourceHandle>{ NEW ResourceHandle(*r, buffer, rawSize, this) }; } else { size = loader->GetLoadedResourceSize(rawBuffer, rawSize); buffer = Allocate(size); if (rawBuffer == nullptr || buffer == nullptr) { LOG_ERROR("Resource cache out of memory"); return nullptr; } handle = std::shared_ptr<ResourceHandle>{ NEW ResourceHandle(*r, buffer, size, this) }; // set ResourceData auto pResourceData = std::shared_ptr<IResourceData>(loader->LoadResource(rawBuffer, rawSize, handle)); // TODO: make the loader unaware of the handle handle->SetData(pResourceData); // If the raw buffer from the resource file isn't needed, it shouldn't take up // any additional memory, so we release it. if (loader->DiscardRawBufferAfterLoad()) SAFE_DELETE_ARRAY(rawBuffer); } if (handle) { m_lru.push_front(handle); m_resources[r->GetName()] = handle; } return handle; } // moves handle to front or lru void ResourceCache::Update(std::shared_ptr<ResourceHandle> handle) { m_lru.remove(handle); m_lru.push_front(handle); } char* ResourceCache::Allocate(unsigned int size) { if (!MakeRoom(size)) return nullptr; char* mem = NEW char[size]; if (mem) m_allocated += size; return mem; } bool ResourceCache::MakeRoom(unsigned int size) { if (size > m_cacheSize) return false; // return null if there's no possible way to allocate the memory while (size > AvailableMemory()) { // The cache is empty, and there's still not enough room. if (m_lru.empty()) return false; FreeOneResource(); } return true; } void ResourceCache::FreeOneResource() { auto gonner = m_lru.end(); // last item is NULL gonner--; // true last item std::shared_ptr<ResourceHandle> handle = *gonner; m_lru.pop_back(); m_resources.erase(handle->m_resource.GetName()); // Note - you can't change the resource cache size yet - the resource bits could still actually be // used by some subsystem holding onto the ResourceHandle. Only when it goes out of scope can the memory // be actually free again. } int ResourceCache::Preload(const std::string pattern, std::function<void(int, bool&)> progressCallback) { if (m_file == NULL) return 0; int numFiles = m_file->GetNumResources(); int loaded = 0; bool cancel = false; for (int i = 0; i < numFiles; ++i) { Resource r{ m_file->GetResourceFilename(i) }; if (WildcardMatch(pattern.c_str(), r.GetName().c_str())) { auto handle = GetHandle(&r); ++loaded; } if (progressCallback) progressCallback(i * 100 / numFiles, cancel); } return loaded; } void ResourceCache::Free(std::shared_ptr<ResourceHandle> gonner) { m_lru.remove(gonner); m_resources.erase(gonner->m_resource.GetName()); // Note - the resource might still be in use by something, // so the cache can't actually count the memory freed until the // ResHandle pointing to it is destroyed. } void ResourceCache::MemoryHasBeenFreed(unsigned int size) { m_allocated -= size; } // Frees every handle in the cache - this would be good to call if you are loading a new // level, or if you wanted to force a refresh of all the data in the cache - which might be // good in a development environment. void ResourceCache::Flush() { while (!m_lru.empty()) { Free(m_lru.front()); m_lru.pop_front(); } } // Searches the resource cache assets for files matching the pattern. Useful for providing a // a list of levels for a main menu screen, for example. std::vector<std::string> ResourceCache::Match(const std::string pattern) { std::vector<std::string> matchingNames; if (m_file == NULL) return matchingNames; int numFiles = m_file->GetNumResources(); for (int i = 0; i < numFiles; ++i) { std::string name = m_file->GetResourceFilename(i); std::transform(name.begin(), name.end(), name.begin(), (int(*)(int)) std::tolower); if (WildcardMatch(pattern.c_str(), name.c_str())) { matchingNames.push_back(name); } } return matchingNames; } #include "ResourceCache.inl" template<class T> std::shared_ptr<T> ResourceCache::GetData(const std::string filename) { LOG_INFO("loading " + filename + " from the zip file"); Resource r{ filename }; auto handle = GetHandle(&r); return handle->GetData<T>(); }
23.992982
151
0.706493
Pedrexus
d39753420daa127b7f465efa38881a75a004d213
25,873
cpp
C++
src/test/test_convlayer.cpp
lsh123/yann
4a12b7c1ee2d89d34772d647586b3018df6997db
[ "MIT" ]
2
2019-08-22T18:14:44.000Z
2020-01-01T10:25:07.000Z
src/test/test_convlayer.cpp
lsh123/yann
4a12b7c1ee2d89d34772d647586b3018df6997db
[ "MIT" ]
null
null
null
src/test/test_convlayer.cpp
lsh123/yann
4a12b7c1ee2d89d34772d647586b3018df6997db
[ "MIT" ]
null
null
null
// // Add --log_level=message to see the messages! // #include <boost/test/unit_test.hpp> #include <sstream> #include "core/functions.h" #include "core/utils.h" #include "core/random.h" #include "core/training.h" #include "layers/convlayer.h" #include "test_utils.h" #include "timer.h" #include "test_layers.h" using namespace std; using namespace boost; using namespace boost::unit_test; using namespace yann; using namespace yann::test; struct ConvolutionalLayerTestFixture { ConvolutionalLayerTestFixture() { } ~ConvolutionalLayerTestFixture() { } inline MatrixSize find_max_pos(const RefConstVector & vv) { MatrixSize pos = 0; vv.maxCoeff(&pos); return pos; } void conv_perf_test(const MatrixSize & size, const MatrixSize & filter_size, const size_t & epochs) { BOOST_TEST_MESSAGE("*** ConvOp Performance test with" << " size=" << size << ", filter_size=" << filter_size << ", epochs=" << epochs ); Matrix input(size, size); Matrix filter(filter_size, filter_size); Matrix output(size + filter_size, size + filter_size); { Timer timer("Random generation"); unique_ptr<RandomGenerator> gen = RandomGenerator::normal_distribution(0, 1); gen->generate(input); gen->generate(filter); } output.resize(ConvolutionalLayer::get_conv_output_rows(size, filter_size), ConvolutionalLayer::get_conv_output_cols(size, filter_size)); { Timer timer("Test plus_conv"); for(auto ii = epochs; ii > 0; --ii) { ConvolutionalLayer::plus_conv(input, filter, output); } } output.resize(ConvolutionalLayer::get_full_conv_output_rows(size, filter_size), ConvolutionalLayer::get_full_conv_output_cols(size, filter_size)); { Timer timer("Test full_conv"); for(auto ii = epochs; ii > 0; --ii) { ConvolutionalLayer::full_conv(input, filter, output); } } } void conv_perf_batch_test(const MatrixSize & batch_size, const MatrixSize & size, const MatrixSize & filter_size, const size_t & epochs) { BOOST_TEST_MESSAGE("*** ConvOp Performance batch test with" << " batch_size=" << batch_size << ", size=" << size << ", filter_size=" << filter_size << ", epochs=" << epochs ); VectorBatch input, output; Matrix filter(filter_size, filter_size); resize_batch(input, batch_size, size * size); { Timer timer("Random generation"); unique_ptr<RandomGenerator> gen = RandomGenerator::normal_distribution(0, 1); gen->generate(input); gen->generate(filter); } resize_batch(output, batch_size, ConvolutionalLayer::get_conv_output_size(size, size, filter_size)); { Timer timer("Test plus_conv"); for(auto ii = epochs; ii > 0; --ii) { ConvolutionalLayer::plus_conv(input, size, size, filter, output); } } resize_batch(output, batch_size, ConvolutionalLayer::get_full_conv_output_size(size, size, filter_size)); { Timer timer("Test full_conv"); for(auto ii = epochs; ii > 0; --ii) { ConvolutionalLayer::full_conv(input, size, size, filter, output); } } } }; // struct ConvolutionalLayerTestFixture BOOST_FIXTURE_TEST_SUITE(ConvolutionalLayerTest, ConvolutionalLayerTestFixture); BOOST_AUTO_TEST_CASE(IO_Test) { BOOST_TEST_MESSAGE("*** ConvolutionalLayer IO test ..."); const MatrixSize input_cols = 5; const MatrixSize input_rows = 3; const MatrixSize filter_size = 2; auto one = make_unique<ConvolutionalLayer>(input_cols, input_rows, filter_size); one->init(Layer::InitMode_Random, boost::none); BOOST_TEST_MESSAGE("ConvolutionalLayer before writing to file: " << "\n" << *one); ostringstream oss; oss << *one; BOOST_CHECK(!oss.fail()); auto two = make_unique<ConvolutionalLayer>(input_cols, input_rows, filter_size); std::istringstream iss(oss.str()); iss >> *two; BOOST_CHECK(!iss.fail()); BOOST_TEST_MESSAGE("ConvolutionalLayer after loading from file: " << "\n" << *two); BOOST_CHECK(one->is_equal(*two, TEST_TOLERANCE)); } BOOST_AUTO_TEST_CASE(ConvOp_Test) { BOOST_TEST_MESSAGE("*** Convolutional operation test ..."); const size_t image_size = 4; const size_t max_filter_size = 4; Matrix filter(max_filter_size, max_filter_size); Matrix input(image_size, image_size); Matrix expected(image_size, image_size); Matrix output(image_size, image_size); ////////////////////////////////////////////////////////////////////// // // Test different filter sizes // input << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16; // 1x1 filter.resize(1, 1); filter << 3; expected.resize(4, 4); expected << 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x1 filter.resize(2, 1); filter << 2, 3; expected.resize(3, 4); expected << 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x2 filter.resize(2, 2); filter << 1, 2, 3, 4; expected.resize(3, 3); expected << 44, 54, 64, 84, 94, 104, 124, 134, 144; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x3 filter.resize(2, 3); filter << 1, 2, 3, 4, 5, 6; expected.resize(3, 2); expected << 106, 127, 190, 211, 274, 295; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 3x3 filter.resize(3, 3); filter << 1, 2, 3, 4, 5, 6, 7, 8, 9; expected.resize(2, 2); expected << 348, 393, 528, 573; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 4x4 filter.resize(4, 4); filter << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16; expected.resize(1, 1); expected << 1496; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); } BOOST_AUTO_TEST_CASE(ConvOp_Batch_Test) { BOOST_TEST_MESSAGE("*** Convolutional operation batch test ..."); const size_t max_filter_size = 4; const MatrixSize image_size = 4; const MatrixSize input_size = image_size * image_size; const MatrixSize batch_size = 2; Matrix filter(max_filter_size, max_filter_size); VectorBatch input, output, expected; ////////////////////////////////////////////////////////////////////// // // Test different filter sizes // resize_batch(input, batch_size, input_size); input << 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, /////////// 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0; // 1x1 filter.resize(1, 1); filter << 1; resize_batch(expected, batch_size, 4 * 4); expected << 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, /////////// 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x1 filter.resize(2, 1); filter << 1, 1; resize_batch(expected, batch_size, 3 * 4); expected << 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, /////////// 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x2 filter.resize(2, 2); filter << 1, 1, 1, 0; resize_batch(expected, batch_size, 3 * 3); expected << 1, 2, 1, 2, 1, 1, 1, 1, 1, //////// 0, 1, 0, 1, 1, 1, 0, 1, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 3x2 filter.resize(3, 2); filter << 1, 1, 1, 0, 1, 0; resize_batch(expected, batch_size, 2 * 3); expected << 2, 2, 2, 2, 1, 1, //////// 0, 1, 1, 1, 1, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 3x3 filter.resize(3, 3); filter << 1, 1, 1, 1, 0, 0, 1, 0, 1; resize_batch(expected, batch_size, 2 * 2); expected << 4, 2, 2, 1, ///// 1, 1, 1, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 4x4 filter.resize(4, 4); filter << 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1; resize_batch(expected, batch_size, 1 * 1); expected << 5, // 2; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); } BOOST_AUTO_TEST_CASE(FullConvOp_Test) { BOOST_TEST_MESSAGE("*** Full convolutional operation test ..."); const size_t image_size = 3; const size_t max_filter_size = 2; Matrix filter(max_filter_size, max_filter_size); Matrix input(image_size, image_size); Matrix expected(image_size + max_filter_size, image_size + max_filter_size); Matrix output(image_size + max_filter_size, image_size + max_filter_size); ////////////////////////////////////////////////////////////////////// // // Test different filter sizes // input.resize(image_size, image_size); input << 1, 2, 3, 4, 5, 6, 7, 8, 9; // 1x1 filter.resize(1, 1); filter << 3; expected.resize(3, 3); expected << 3, 6, 9, 12, 15, 18, 21, 24, 27; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x2 filter.resize(2, 2); filter << 1, 2, 3, 4; expected.resize(4, 4); expected << 4, 11, 18, 9, 18, 37, 47, 21, 36, 67, 77, 33, 14, 23, 26, 9; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x3 filter.resize(2, 3); filter << 1, 2, 3, 4, 5, 6; expected.resize(4, 5); expected << 6, 17, 32, 23, 12, 27, 58, 91, 58, 27, 54, 106, 154, 94, 42, 21, 38, 50, 26, 9; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 3x3 filter.resize(3, 3); filter << 1, 2, 3, 4, 5, 6, 7, 8, 9; expected.resize(5, 5); expected << 9, 26, 50, 38, 21, 42, 94, 154, 106, 54, 90, 186, 285, 186, 90, 54, 106, 154, 94, 42, 21, 38, 50, 26, 9; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); } BOOST_AUTO_TEST_CASE(FullConvOp_Batch_Test) { BOOST_TEST_MESSAGE("*** Full convolutional operation batch test ..."); const size_t max_filter_size = 4; const MatrixSize image_size = 3; const MatrixSize input_size = image_size * image_size; const MatrixSize batch_size = 3; Matrix filter(max_filter_size, max_filter_size); VectorBatch input, output, expected; ////////////////////////////////////////////////////////////////////// // // Test different filter sizes // resize_batch(input, batch_size, input_size); input << 1, 0, 1, 0, 1, 0, 1, 0, 0, /////// 0, 0, 0, 0, 0, 0, 0, 0, 0, /////// 1, 1, 1, 1, 1, 1, 1, 1, 1; // 1x1 filter.resize(1, 1); filter << 1; resize_batch(expected, batch_size, 3 * 3); expected << 1, 0, 1, 0, 1, 0, 1, 0, 0, /////// 0, 0, 0, 0, 0, 0, 0, 0, 0, /////// 1, 1, 1, 1, 1, 1, 1, 1, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x2 filter.resize(2, 2); filter << 1, 1, 1, 0; resize_batch(expected, batch_size, 4 * 4); expected << 0, 1, 0, 1, 1, 1, 2, 1, 0, 2, 1, 0, 1, 1, 0, 0, ////////// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ////////// 0, 1, 1, 1, 1, 3, 3, 2, 1, 3, 3, 2, 1, 2, 2, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 2x3 filter.resize(2, 3); filter << 1, 1, 1, 1, 0, 0; resize_batch(expected, batch_size, 4 * 5); expected << 0, 0, 1, 0, 1, 1, 1, 2, 2, 1, 0, 1, 2, 1, 0, 1, 1, 1, 0, 0, ///////////// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ///////////// 0, 0, 1, 1, 1, 1, 2, 4, 3, 2, 1, 2, 4, 3, 2, 1, 2, 3, 2, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); // 3x3 filter.resize(3, 3); filter << 1, 1, 1, 1, 0, 0, 1, 0, 1; resize_batch(expected, batch_size, 5 * 5); expected << 1, 0, 2, 0, 1, 0, 1, 1, 1, 1, 2, 1, 3, 2, 1, 0, 1, 2, 1, 0, 1, 1, 1, 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, ///////////// 1, 1, 2, 1, 1, 1, 1, 3, 2, 2, 2, 3, 6, 4, 3, 1, 2, 4, 3, 2, 1, 2, 3, 2, 1; output.resizeLike(expected); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output); } BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE)); } BOOST_AUTO_TEST_CASE(Rotate180_Test) { BOOST_TEST_MESSAGE("*** Rotate180 test ..."); const MatrixSize input0_size = 2; Matrix input0(input0_size, input0_size); input0 << 1, 2, 3, 4; Matrix expected0(input0_size, input0_size); expected0 << 4, 3, 2, 1; Matrix output0(input0_size, input0_size); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::rotate180(input0, output0); } BOOST_CHECK(expected0.isApprox(output0, TEST_TOLERANCE)); const MatrixSize input1_size = 3; Matrix input1(input1_size, input1_size); input1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix expected1(input1_size, input1_size); expected1 << 9, 8, 7, 6, 5, 4, 3, 2, 1; Matrix output1(input1_size, input1_size); { // ensure we don't do allocations in eigen BlockAllocations block; ConvolutionalLayer::rotate180(input1, output1); } BOOST_CHECK(expected1.isApprox(output1, TEST_TOLERANCE)); } BOOST_AUTO_TEST_CASE(FeedForward_Test) { BOOST_TEST_MESSAGE("*** ConvolutionalLayer FeedForward test ..."); const MatrixSize image_size = 5; const MatrixSize input_size = image_size * image_size; const MatrixSize filter_size = 3; const MatrixSize batch_size = 2; const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size( image_size, image_size, filter_size); Matrix ww(filter_size, filter_size); VectorBatch input, expected_output; resize_batch(input, batch_size, input_size); resize_batch(expected_output, batch_size, output_size); ww << 1, 0, 1, 0, 1, 0, 1, 0, 1; input << 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ///////////// 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0; expected_output << 5.5, 0.5, 2.5, 0.5, 2.5, 0.5, 2.5, 0.5, 2.5, ///////////// 4.5, 0.5, 5.5, 0.5, 5.5, 0.5, 5.5, 0.5, 4.5; auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size); BOOST_CHECK(layer); layer->set_activation_function(make_unique<IdentityFunction>()); layer->set_values(ww, 0.5); test_layer_feedforward(*layer, input, expected_output); } BOOST_AUTO_TEST_CASE(Backprop_Test) { BOOST_TEST_MESSAGE("*** ConvolutionalLayer backprop test ..."); const MatrixSize image_size = 3; const MatrixSize input_size = image_size * image_size; const MatrixSize filter_size = 2; const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size( image_size, image_size, filter_size); const double learning_rate = 0.1; const size_t epochs = 100; const MatrixSize batch_size = 2; Matrix ww(filter_size, filter_size); VectorBatch input, expected_output; resize_batch(input, batch_size, input_size); resize_batch(expected_output, batch_size, output_size); ww << 0, 0, 0, 1; input << 0, 0, 0, 0, 1, 1, 0, 1, 0, //////// 0, 0, 0, 1, 1, 0, 1, 0, 0; expected_output << 1, 0, 0, 0, //// 0, 0, 1, 0; auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size); BOOST_CHECK(layer); layer->set_activation_function(make_unique<IdentityFunction>()); layer->set_values(ww, 0.0); test_layer_backprop( *layer, input, boost::none, expected_output, make_unique<QuadraticCost>(), learning_rate, epochs ); } BOOST_AUTO_TEST_CASE(Backprop_OnVector_Test) { BOOST_TEST_MESSAGE("*** ConvolutionalLayer backprop on vector test ..."); const MatrixSize shift = 4; const MatrixSize image_size = 3; const MatrixSize input_size = image_size * image_size; const MatrixSize filter_size = 2; const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size( image_size, image_size, filter_size); const double learning_rate = 0.1; const size_t epochs = 100; const MatrixSize batch_size = 2; Matrix ww(filter_size, filter_size); Vector input_buffer(shift + batch_size * input_size); MapMatrix input(input_buffer.data() + shift, batch_size, input_size); // this assumes RowMajor layout VectorBatch expected_output; resize_batch(expected_output, batch_size, output_size); ww << 0, 0, 0, 1; input_buffer << 1, 2, 3, 4, // shift 0, 0, 0, 0, 1, 1, 0, 1, 0, //////// 0, 0, 0, 1, 1, 0, 1, 0, 0; expected_output << 1, 0, 0, 0, //// 0, 0, 1, 0; auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size); BOOST_CHECK(layer); layer->set_activation_function(make_unique<IdentityFunction>()); layer->set_values(ww, 0.0); test_layer_backprop( *layer, input, boost::none, expected_output, make_unique<QuadraticCost>(), learning_rate, epochs ); } BOOST_AUTO_TEST_CASE(Training_WithIdentity_Test) { BOOST_TEST_MESSAGE("*** ConvolutionalLayer with Identity activation training test ..."); const MatrixSize image_rows = 6; const MatrixSize image_cols = 3; const MatrixSize input_size = image_rows * image_cols; const MatrixSize filter_size = 2; const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(image_rows, image_cols, filter_size); const MatrixSize batch_size = 2; VectorBatch input, expected; resize_batch(input, batch_size, input_size); resize_batch(expected, batch_size, output_size); input << 0.01, 0.02, 0.11, 0.10, 0.13, 0.18, 0.03, 0.04, 0.12, 0.09, 0.14, 0.17, 0.05, 0.06, 0.07, 0.08, 0.15, 0.16, /////////////////////////////////// 0.02, 0.06, 0.08, 0.10, 0.13, 0.14, 0.03, 0.02, 0.07, 0.09, 0.16, 0.15, 0.04, 0.05, 0.13, 0.11, 0.16, 0.18; expected << 0.347, 0.478, 0.308, 0.462, 0.378, 0.492, 0.343, 0.415, 0.409, 0.480, ////////////////////////////////// 0.373, 0.446, 0.282, 0.368, 0.395, 0.442, 0.332, 0.492, 0.429, 0.530; // create layer auto layer = make_unique<ConvolutionalLayer>(image_rows, image_cols, filter_size); BOOST_CHECK(layer); layer->set_activation_function(make_unique<IdentityFunction>()); layer->init(Layer::InitMode_Zeros, boost::none); // test test_layer_training( *layer, input, expected, batch_size, // tests num make_unique<QuadraticCost>(), 0.09, // learning rate 8000 // epochs ); } BOOST_AUTO_TEST_CASE(Training_WithSigmoid_Test) { BOOST_TEST_MESSAGE("*** ConvolutionalLayer with Sigmoid activation training test ..."); const MatrixSize image_rows = 6; const MatrixSize image_cols = 3; const MatrixSize input_size = image_rows * image_cols; const MatrixSize filter_size = 2; const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(image_rows, image_cols, filter_size); const MatrixSize batch_size = 2; VectorBatch input, expected; resize_batch(input, batch_size, input_size); resize_batch(expected, batch_size, output_size); input << 0.01, 0.02, 0.11, 0.10, 0.13, 0.18, 0.03, 0.04, 0.12, 0.09, 0.14, 0.17, 0.05, 0.06, 0.07, 0.08, 0.15, 0.16, /////////////////////////////////// 0.02, 0.06, 0.08, 0.10, 0.13, 0.14, 0.03, 0.02, 0.07, 0.09, 0.16, 0.15, 0.04, 0.05, 0.13, 0.11, 0.16, 0.18; expected << 0.348, 0.478, 0.309, 0.462, 0.378, 0.492, 0.341, 0.412, 0.409, 0.480, ////////////////////////////////// 0.372, 0.445, 0.287, 0.366, 0.395, 0.440, 0.331, 0.494, 0.429, 0.532; // create layer auto layer = make_unique<ConvolutionalLayer>(image_rows, image_cols, filter_size); BOOST_CHECK(layer); layer->set_activation_function(make_unique<SigmoidFunction>()); layer->init(Layer::InitMode_Zeros, boost::none); // test test_layer_training( *layer, input, expected, batch_size, // tests num make_unique<CrossEntropyCost>(), 0.75, // learning rate 8000 // epochs ); } //////////////////////////////////////////////////////////////////////////////////////////////// // // perf conv tests // BOOST_AUTO_TEST_CASE(PerfConvTest, * disabled()) { conv_perf_test( 1000, // size 10, // filter 100 // epochs ); } BOOST_AUTO_TEST_CASE(PerfBatchConvTest, * disabled()) { conv_perf_batch_test( 10, // batch 1000, // size 10, // filter 10 // epochs ); } BOOST_AUTO_TEST_SUITE_END()
26.53641
138
0.576392
lsh123
d39781614f209bd37dac8fbe3673ed1fe9741deb
208
cpp
C++
4_loops/Code_Examples/output_tracing3.cpp
AhsanAyub/tntech_csc_1300_fall_2021
a96794e9800adccb71abaf83ecf5409ad4c25b3e
[ "MIT" ]
2
2022-02-02T05:25:46.000Z
2022-02-17T17:42:08.000Z
4_loops/Code_Examples/output_tracing3.cpp
AhsanAyub/tntech_csc_1300_fall_2021
a96794e9800adccb71abaf83ecf5409ad4c25b3e
[ "MIT" ]
null
null
null
4_loops/Code_Examples/output_tracing3.cpp
AhsanAyub/tntech_csc_1300_fall_2021
a96794e9800adccb71abaf83ecf5409ad4c25b3e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { for(int i = 0; i <= 10; i++) { if(i % 2 == 0) { continue; } cout << i << endl; } return 0; }
13
32
0.384615
AhsanAyub
d39a7d147f697051ffcfba0a5a50f415399fbe1c
230
cpp
C++
Week-1/Day-05-firstUniqChar.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
1
2020-05-02T04:21:54.000Z
2020-05-02T04:21:54.000Z
Week-1/Day-05-firstUniqChar.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
null
null
null
Week-1/Day-05-firstUniqChar.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
null
null
null
class Solution { public: int firstUniqChar(string s) { unordered_map<char, int> m; for(char c : s) m[c]++; for(int i=0; i<s.size(); i++) if(m[s[i]] == 1) return i; return -1; } };
23
66
0.473913
utkarshavardhana
d39c4c39557e3acd06192a317311199dee19ac85
2,464
cpp
C++
fbzmq/async/tests/ZmqTimeoutTest.cpp
eensy1207/fbzmq
9032d469ce9565756a0a160481a002c70e66f35c
[ "MIT" ]
null
null
null
fbzmq/async/tests/ZmqTimeoutTest.cpp
eensy1207/fbzmq
9032d469ce9565756a0a160481a002c70e66f35c
[ "MIT" ]
null
null
null
fbzmq/async/tests/ZmqTimeoutTest.cpp
eensy1207/fbzmq
9032d469ce9565756a0a160481a002c70e66f35c
[ "MIT" ]
null
null
null
/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gtest/gtest.h> #include <gflags/gflags.h> #include <fbzmq/async/ZmqEventLoop.h> #include <fbzmq/async/ZmqTimeout.h> namespace fbzmq { using namespace std::chrono_literals; namespace { class TestThread final : public ZmqEventLoop { public: TestThread() { prepare(); } int getCount() { return count_.load(std::memory_order_relaxed); } private: void prepare() { auto start = std::chrono::steady_clock::now(); // Schedule first timeout timeout_ = ZmqTimeout::make(this, [&, start]() noexcept { auto diff = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start); LOG(INFO) << "Executing callback after " << diff.count() << "ms."; // fetch_add returns previous value int oldCount = count_.fetch_add(1, std::memory_order_relaxed); EXPECT_EQ(1, getNumPendingTimeouts()); // Destruct the timeout on 4th time, this will cancel it. if (oldCount == 3) { timeout_.reset(); EXPECT_EQ(0, getNumPendingTimeouts()); } }); EXPECT_EQ(0, getNumPendingTimeouts()); EXPECT_NO_THROW(timeout_->cancelTimeout()); timeout_->scheduleTimeout(100ms, true /* periodic */); EXPECT_TRUE(timeout_->isScheduled()); // can schedule twice with no issue timeout_->scheduleTimeout(100ms, true /* periodic */); EXPECT_TRUE(timeout_->isScheduled()); EXPECT_TRUE(timeout_->isPeriodic()); EXPECT_EQ(1, getNumPendingTimeouts()); } std::atomic<int> count_{0}; std::unique_ptr<ZmqTimeout> timeout_; }; } // namespace TEST(ZmqTimeoutTest, TimeoutTest) { TestThread testThread; EXPECT_EQ(0, testThread.getCount()); std::thread thread([&]() { LOG(INFO) << "Starting zmq thread."; testThread.run(); LOG(INFO) << "Stopping zmq thread."; }); // Busy spin until callback has been executed 4 times while (testThread.getCount() != 4) { std::this_thread::yield(); } // Cleanup testThread.stop(); thread.join(); } } // namespace fbzmq int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); return RUN_ALL_TESTS(); }
23.92233
72
0.663555
eensy1207
d3a6e68ce13bd5b3512887ba3dabcdebc45d8483
374
hpp
C++
src/pspr_analyser.hpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
37
2015-10-30T21:56:26.000Z
2021-11-30T15:33:26.000Z
src/pspr_analyser.hpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
27
2015-01-06T05:45:55.000Z
2020-01-29T21:40:22.000Z
src/pspr_analyser.hpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
8
2016-02-07T23:31:03.000Z
2020-07-12T08:51:41.000Z
#ifndef PSPR_ANALYSER_HPP #define PSPR_ANALYSER_HPP /* pspr_analyser.hpp 2014/10/21 psycommmando@gmail.com Description: A little commandline utility that turns a sprite file into something human readable! And it also gather data about the file and writes a report! */ namespace pspr_analyser { //int RunPSPRAnalyser( int argc, const char * argv[] ); }; #endif
22
79
0.759358
SkyTemple
d3ab8adc2a1bb7fb4e3aee0521a5fd7e9a35a42d
2,295
cpp
C++
codeforces/F - Three Paths on a Tree/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/F - Three Paths on a Tree/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/F - Three Paths on a Tree/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: * kzvd4729 created: Jan/22/2020 21:35 * solution_verdict: Accepted language: GNU C++14 * run_time: 389 ms memory_used: 31600 KB * problem: https://codeforces.com/contest/1294/problem/F ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,inf=1e9; int sub[N+2],fav[N+2],on,tw,th,mx; vector<int>adj[N+2]; void dfs(int node,int par) { for(auto x:adj[node]) { if(x==par)continue;dfs(x,node); if(sub[x]+1>sub[node]) { sub[node]=sub[x]+1;fav[node]=fav[x]; } } if(!fav[node])fav[node]=node; } void dds(int node,int par,int sb,int fv) { multiset<pair<int,int> >st; st.insert({0,0});st.insert({0,0}); st.insert({sb,fv}); for(auto x:adj[node]) { if(x==par)continue; st.insert({sub[x]+1,fav[x]}); } pair<int,int>a=*st.rbegin();st.erase(st.find(a)); pair<int,int>b=*st.rbegin();st.erase(st.find(b)); pair<int,int>c=*st.rbegin();st.erase(st.find(c)); if(a.first+b.first+c.first>mx) { mx=a.first+b.first+c.first; on=a.second,tw=b.second,th=c.second; //cout<<mx<<" ** "<<node<<endl; } st.insert(a),st.insert(b),st.insert(c); for(auto x:adj[node]) { if(x==par)continue; st.erase(st.find({sub[x]+1,fav[x]})); pair<int,int>p=*st.rbegin(); dds(x,node,p.first+1,p.second); st.insert({sub[x]+1,fav[x]}); } } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=1;i<n;i++) { int u,v;cin>>u>>v; adj[u].push_back(v);adj[v].push_back(u); } dfs(1,-1);dds(1,-1,0,1); if(on==0) { if(tw!=1&&th!=1)on=1; else if(tw!=2&&th!=2)on=2; else if(tw!=3&&th!=3)on=3; } if(tw==0) { if(on!=1&&th!=1)tw=1; else if(on!=2&&th!=2)tw=2; else if(on!=3&&th!=3)tw=3; } if(th==0) { if(tw!=1&&on!=1)th=1; else if(tw!=2&&on!=2)th=2; else if(tw!=3&&on!=3)th=3; } cout<<mx<<endl<<on<<" "<<tw<<" "<<th<<endl; return 0; }
27.321429
111
0.471895
kzvd4729
d3ac14eb53a52717830d56b235d1409e02c8d426
3,370
cpp
C++
executor/operator/ref/ref_reverse.cpp
clovking/Tengine
655b93acd3ce02fd594b6173e996d0ea09833286
[ "Apache-2.0" ]
25
2018-12-09T09:31:56.000Z
2021-08-12T10:32:19.000Z
executor/operator/ref/ref_reverse.cpp
clovking/Tengine
655b93acd3ce02fd594b6173e996d0ea09833286
[ "Apache-2.0" ]
1
2022-03-31T03:33:42.000Z
2022-03-31T03:33:42.000Z
executor/operator/ref/ref_reverse.cpp
clovking/Tengine
655b93acd3ce02fd594b6173e996d0ea09833286
[ "Apache-2.0" ]
6
2018-12-16T01:18:42.000Z
2019-09-18T07:29:56.000Z
#include <iostream> #include <math.h> #include "logger.hpp" #include "node_ops.hpp" #include "tensor_mem.hpp" #include "kernel_registry.hpp" #include "tengine_errno.hpp" #include "graph.hpp" #include "operator/reverse.hpp" #include "kernel/reverse/ref_reverse_kernel.h" namespace TEngine { namespace RefReverseOps { // const int default_prio = 1500; struct ReverseOps : public MTNodeOps { bool Prerun(Node* node) override; bool Run(Node* node) override; // bool Postrun(Node* node) override; void InitRegistry(void); ReverseOps() { kernel_run = nullptr; InitRegistry(); } struct reverse_param op_param; ref_reverse_t kernel_run; KernelRegistry<ref_reverse_t> kernel_registry; }; bool ReverseOps::Prerun(Node* node) { int layout = exec_attr->graph_layout; // Reverse* reverse_op = dynamic_cast<Reverse*>(node->GetOp()); Tensor* input_tensor = node->GetInputTensor(0); int data_type = input_tensor->GetDataType(); if(!kernel_registry.GetKernel(kernel_run, layout, data_type)) { set_tengine_errno(ENOENT); return false; } return true; } bool ReverseOps::Run(Node* node) { Tensor* input_tensor = node->GetInputTensor(0); auto in_dim = input_tensor->GetShape().GetDim(); void* input = get_tensor_mem(input_tensor); Tensor* axis_tensor = node->GetInputTensor(1); void* axis_data = get_tensor_mem(axis_tensor); op_param.dim_size = (int)in_dim.size(); for(int i = 0; i < op_param.dim_size; i++) { op_param.in_shape[i] = in_dim[i]; } Tensor* output_tensor = node->GetOutputTensor(0); void* output = get_tensor_mem(output_tensor); // int* f_axis=(int*)axis_data; // printf("axis_data: %d\n",f_axis[0]); int ret = kernel_run(input, axis_data, output, &op_param); if (ret < 0) { return false; } else return true; } void ReverseOps::InitRegistry(void) { #ifdef CONFIG_KERNEL_FP32 kernel_registry.Register(( ref_reverse_t )ref_reverse_fp32, TENGINE_LAYOUT_NCHW, TENGINE_DT_FP32); kernel_registry.Register(( ref_reverse_t )ref_reverse_fp32, TENGINE_LAYOUT_NHWC, TENGINE_DT_FP32); #endif // #ifdef CONFIG_KERNEL_FP16 // kernel_registry.Register(( ref_reverse_t )ref_reverse_fp16, TENGINE_LAYOUT_NCHW, TENGINE_DT_FP16); // kernel_registry.Register(( ref_reverse_t )ref_reverse_fp16, TENGINE_LAYOUT_NHWC, TENGINE_DT_FP16); // #endif // #ifdef CONFIG_KERNEL_INT8 // kernel_registry.Register(( ref_reverse_t )ref_reverse_int8, TENGINE_LAYOUT_NCHW, TENGINE_DT_INT8); // kernel_registry.Register(( ref_reverse_t )ref_reverse_int8, TENGINE_LAYOUT_NHWC, TENGINE_DT_INT8); // #endif // #ifdef CONFIG_KERNEL_UINT8 // kernel_registry.Register(( ref_reverse_t )ref_reverse_uint8, TENGINE_LAYOUT_NCHW, TENGINE_DT_UINT8); // kernel_registry.Register(( ref_reverse_t )ref_reverse_uint8, TENGINE_LAYOUT_NHWC, TENGINE_DT_UINT8); // #endif } NodeOps* SelectFunc(const CPUInfo* info, Node* node) { ReverseOps* ops = new ReverseOps(); LOG_DEBUG() << "ReverseOps RefOp is selected\n"; return ops; } } //namespace RefReverseOps void RegisterRefReverseOps(void) { NodeOpsRegistryManager::RegisterOPImplementor(REF_REGISTRY_NAME, "Reverse", RefReverseOps::SelectFunc, 1000); } } // namespace TEngine
28.083333
113
0.708309
clovking
d3b5edaaedde73f5c62c091e9b655b319198d0fb
20,508
cpp
C++
src/windInit.cpp
MaddTheSane/executor
2a8baf83066ead802ae22e567af41d74a4e920ff
[ "MIT" ]
12
2016-02-01T06:26:19.000Z
2022-01-09T00:14:20.000Z
src/windInit.cpp
MaddTheSane/executor
2a8baf83066ead802ae22e567af41d74a4e920ff
[ "MIT" ]
2
2017-07-16T02:24:15.000Z
2018-02-14T04:15:37.000Z
src/windInit.cpp
MaddTheSane/executor
2a8baf83066ead802ae22e567af41d74a4e920ff
[ "MIT" ]
4
2017-04-07T13:55:46.000Z
2022-01-09T00:14:17.000Z
/* Copyright 1986-1995 by Abacus Research and * Development, Inc. All rights reserved. */ #if !defined (OMIT_RCSID_STRINGS) char ROMlib_rcsid_windInit[] = "$Id: windInit.c 88 2005-05-25 03:59:37Z ctm $"; #endif /* Forward declarations in WindowMgr.h (DO NOT DELETE THIS LINE) */ #include "rsys/common.h" #include "QuickDraw.h" #include "CQuickDraw.h" #include "WindowMgr.h" #include "ToolboxUtil.h" #include "ResourceMgr.h" #include "FontMgr.h" #include "MemoryMgr.h" #include "SegmentLdr.h" #include "OSUtil.h" #include "OSEvent.h" #include "ControlMgr.h" #include "MenuMgr.h" #include "SysErr.h" #include "DialogMgr.h" #include "rsys/cquick.h" #include "rsys/wind.h" #include "rsys/menu.h" #include "rsys/resource.h" #include "rsys/system_error.h" #include "rsys/prefs.h" #include "rsys/flags.h" #include "rsys/segment.h" #include "rsys/file.h" #include "rsys/executor.h" #include "rsys/custom.h" #include "rsys/options.h" #include "rsys/launch.h" using namespace Executor; PUBLIC BOOLEAN Executor::ROMlib_dirtyvariant = FALSE; boolean_t Executor::system_file_version_skew_p; static void exit_executor (void) { ROMlib_exit = TRUE; ExitToShell (); } #if !defined (MSDOS) PRIVATE std::string reinstall = "System and %System"; #else PRIVATE char *reinstall = "EXSYSTEM.HFV"; #endif P0 (PUBLIC pascal trap, void, InitWindows) { PatHandle ph; PixPatHandle new_ph; RgnHandle mrgn, corners; AuxWinHead = RM (default_aux_win); SaveVisRgn = NULL; THEPORT_SAVE_EXCURSION (thePort, { /* FIXME: is this a memory leak, to just call InitPort () again? */ InitPort (MR (WMgrPort)); InitCPort (MR (WMgrCPort)); ph = GetPattern(deskPatID); if (ph == NULL) { fprintf (stderr, "Can't open System file.\n" "This is very bad. You will have to reinstall %s" " before\n" "Executor will work again.\n", reinstall.c_str()); ROMlib_exit = TRUE; ExitToShell (); } new_ph = GetPixPat (deskPatID); if (new_ph) DeskCPat = RM(new_ph); else USE_DESKCPAT_VAR &= ~USE_DESKCPAT_BIT; InitPalettes (); InitMenus (); PATASSIGN (DeskPattern, STARH(ph)); GrayRgn = RM (NewRgn ()); OpenRgn (); if (ROMlib_creator && !(ROMlib_options & ROMLIB_RECT_SCREEN_BIT)) FrameRoundRect (&GD_BOUNDS (MR (TheGDevice)), 16, 16); else FrameRect (&GD_BOUNDS (MR (TheGDevice))); CloseRgn (MR (GrayRgn)); mrgn = NewRgn(); SetRectRgn(mrgn, 0, 0, CW (GD_BOUNDS (MR (TheGDevice)).right), CW(MBarHeight)); SectRgn(MR(GrayRgn), mrgn, mrgn); corners = NewRgn(); SetRectRgn(corners, 0, 0, CW (GD_BOUNDS (MR (TheGDevice)).right), CW (GD_BOUNDS (MR (TheGDevice)).bottom)); DiffRgn(corners, MR(GrayRgn), corners); PaintRgn(corners); CopyRgn (MR (GrayRgn), PORT_VIS_REGION (MR (wmgr_port))); DiffRgn(MR(GrayRgn), mrgn, MR(GrayRgn)); PenPat(white); PaintRgn(mrgn); PenPat(black); MoveTo(0, CW(MBarHeight) - 1); Line (CW (GD_BOUNDS (MR (TheGDevice)).right), 0); if ((USE_DESKCPAT_VAR & USE_DESKCPAT_BIT) && PIXMAP_PIXEL_SIZE (GD_PMAP (MR (MainDevice))) > 2) FillCRgn(MR(GrayRgn), MR(DeskCPat)); else FillRgn(MR(GrayRgn), DeskPattern); DisposeRgn(mrgn); DisposeRgn(corners); CopyRgn (MR (GrayRgn), PORT_CLIP_REGION (MR (wmgr_port))); WindowList = NULL; SaveUpdate = -1; PaintWhite = -1; DeskHook = NULL; GhostWindow = NULL; PATASSIGN (DragPattern, gray); }); /* since there is no `InitControls ()', we do this here */ ctl_color_init (); WWExist = EXIST_YES; if (ROMlib_creator && ROMlib_creatorsp) { int i; boolean_t found_p; int n_vals; n_vals = (ROMlib_creatorsp->head.length / sizeof ROMlib_creatorsp->vals[0]); for (found_p = FALSE, i = 0; !found_p && i < n_vals; ++i) if (ROMlib_creatorsp->vals[i] == (uint32) ROMlib_creator) found_p = TRUE; if (!found_p) { char msg_buf[1024]; sprintf (msg_buf, "You are trying to run a Macintosh Application " "for which this copy of Executor isn't licensed. This " "copy of Executor is licensed only to run specific " "applications. " "Please choose the \"About Executor...\" menu item and " "click on the \"License\" button for more information."); system_error (msg_buf, 0, "Exit", NULL, NULL, C_ExitToShell, NULL, NULL); } } { static boolean_t issued_system_file_version_skew_warning_p = FALSE; if (system_file_version_skew_p && ! issued_system_file_version_skew_warning_p) { system_error ("\ The system file you have installed appears to be too old. \ Executor may die without warning because of this mismatch", 0, "Continue", "Exit", NULL, NULL, exit_executor, NULL); } issued_system_file_version_skew_warning_p = TRUE; } #if defined (MSDOS) { static boolean_t issued_cd_warning_p = FALSE; if (cd_mounted_by_trickery_p && !issued_cd_warning_p) { char *warning_file; struct stat sbuf; warning_file = copystr ("+/cdinfo.txt"); if (warning_file) { if (stat (warning_file, &sbuf) == 0) { char buf[1024]; int i; for (i = strlen (warning_file) -1; i >=0; --i) if (warning_file[i] == '/') warning_file[i] = '\\'; sprintf (buf, "From DOS or Windows, please read the " "file \"%s\". " "If you don't, Executor won't be " "able to read Mac CD-ROMS (except " "the Executor CD-ROM, which is special).", warning_file); system_error (buf, 0, "Exit", "Continue", NULL, exit_executor, NULL, NULL); } free (warning_file); } issued_cd_warning_p = TRUE; } } #endif switch (ROMlib_launch_failure) { case launch_no_failure: break; case launch_cfm_requiring: system_error ("CFM-requiring applications are not currently supported.", 0, "OK", NULL, NULL, NULL, NULL, NULL); break; case launch_ppc_only: #if !defined (powerpc) && !defined (__ppc__) system_error ("That application is PowerPC-only. This version of " "Executor doesn't run PowerPC applications. " "You need to find an M68k version of that application.", 0, "OK", NULL, NULL, NULL, NULL, NULL); #else system_error ("That application is PowerPC-only. To attempt to run " "it, Executor must be started using the \"-ppc\" " "command-line switch.", 0, "OK", NULL, NULL, NULL, NULL, NULL); #endif break; case launch_damaged: system_error ("That application appears damaged (lacks CODE and cfrg).", 0, "OK", NULL, NULL, NULL, NULL, NULL); break; case launch_compressed_ge7: system_error ("That application has a compressed CODE 0. " "It is probably unusable under Executor but " "might work in System 6 mode", 0, "OK", NULL, NULL, NULL, NULL, NULL); break; case launch_compressed_lt7: system_error ("That application has a compressed CODE 0. " "It will not run under this version of Executor.", 0, "OK", NULL, NULL, NULL, NULL, NULL); break; default: warning_unexpected ("%d", ROMlib_launch_failure); break; } ROMlib_launch_failure = launch_no_failure; if (! size_info.application_p) return; /* only issue warnings once */ size_info.application_p = FALSE; if ((! size_info.size_resource_present_p || (size_info.size_flags & SZis32BitCompatible) != SZis32BitCompatible) && !ROMlib_nowarn32) { system_error ("This application doesn't claim to be \"32 bit clean\". " "It is quite possible that this program will not work " "under Executor.", 0, "Continue", "Restart", NULL, NULL, C_ExitToShell, NULL); } if (size_info.size_resource_present_p && ROMlib_applzone_size < size_info.preferred_size) { char msg_buf[1024]; int applzone_in_k, preferred_size_in_k; applzone_in_k = ROMlib_applzone_size / 1024; preferred_size_in_k = (size_info.preferred_size + 1023) / 1024; sprintf (msg_buf, "This application prefers `%dk' of memory, " "but only '%dk' of memory is available in the application " "zone. You should exit Executor and run it again " "with \"-applzone %dk\".", preferred_size_in_k, applzone_in_k, preferred_size_in_k); system_error (msg_buf, 0, "Continue", "Browser", "Exit", NULL, C_ExitToShell, exit_executor); } } P1 (PUBLIC pascal trap, void, GetWMgrPort, HIDDEN_GrafPtr *, wp) { wp->p = WMgrPort; } P1 (PUBLIC pascal trap, void, GetCWMgrPort, HIDDEN_CGrafPtr *, wp) { wp->p = WMgrCPort; } P1(PUBLIC pascal trap, void, SetDeskCPat, PixPatHandle, ph) { PatHandle bw_ph; if (ph) { DeskCPat = RM(ph); USE_DESKCPAT_VAR |= USE_DESKCPAT_BIT; } else { bw_ph = GetPattern(deskPatID); PATASSIGN(DeskPattern, STARH(bw_ph)); USE_DESKCPAT_VAR &= ~USE_DESKCPAT_BIT; } PaintOne((WindowPeek) 0, MR(GrayRgn)); } static void ROMlib_new_window_common (WindowPeek w, int allocated_p, int cwindow_p, Rect *bounds, StringPtr title, BOOLEAN visible_p, INTEGER proc_id, WindowPtr behind, BOOLEAN go_away_flag, LONGINT ref_con) { WindowPeek t_w; AuxWinHandle t_aux_w; GrafPtr save_port; save_port = thePort; if (!title) title = (StringPtr) ""; /* thank MS Word for pointing this out */ if (!behind) { WINDOW_NEXT_WINDOW_X (w) = (WindowPeek)CLC (0); if (WindowList) { for (t_w = MR (WindowList); WINDOW_NEXT_WINDOW_X (t_w); t_w = WINDOW_NEXT_WINDOW (t_w)) ; WINDOW_NEXT_WINDOW_X (t_w) = RM (w); } else { WindowList = RM (w); if (visible_p) { /* notify the palette manager that the `FrontWindow ()' may have changed */ pm_front_window_maybe_changed_hook (); } } } else if (behind == (WindowPtr) -1L) { WINDOW_NEXT_WINDOW_X (w) = WindowList; WindowList = (WindowPeek) RM (w); if (visible_p) { /* notify the palette manager that the `FrontWindow ()' may have changed */ pm_front_window_maybe_changed_hook (); } } else { WINDOW_NEXT_WINDOW_X (w) = WINDOW_NEXT_WINDOW_X (behind); WINDOW_NEXT_WINDOW_X (behind) = (WindowPeek) RM (w); } WINDOW_KIND_X (w) = CWC (userKind); WINDOW_VISIBLE_X (w) = visible_p; for (t_w = MR (WindowList); t_w && !WINDOW_VISIBLE (t_w); t_w = WINDOW_NEXT_WINDOW (t_w)) ; WINDOW_HILITED_X (w) = visible_p && (t_w == w); if (WINDOW_HILITED_X (w)) { CurActivate = (WindowPtr) RM (w); for (t_w = WINDOW_NEXT_WINDOW (t_w); t_w && !WINDOW_HILITED_X (t_w); t_w = WINDOW_NEXT_WINDOW (t_w)) ; } else t_w = 0; /* t_w will be used later */ WINDOW_GO_AWAY_FLAG_X (w) = go_away_flag; WINDOW_SPARE_FLAG_X (w) = 0; /* will be used zoombox (wNew) */ WINDOW_DATA_X (w) = 0; WINDOW_STRUCT_REGION_X (w) = RM (NewRgn ()); WINDOW_CONT_REGION_X (w) = RM (NewRgn ()); WINDOW_UPDATE_REGION_X (w) = RM (NewRgn ()); WINDOW_DEF_PROC_X (w) = RM (GetResource (TICK ("WDEF"), proc_id >> 4)); if (!WINDOW_DEF_PROC_X (w)) { WINDOW_DEF_PROC_X (w) = RM (GetResource (TICK ("WDEF"), 0)); if (!WINDOW_DEF_PROC_X (w)) { if (allocated_p) DisposPtr ((Ptr) w); /* fatal_error ("no window (?)"); */ gui_fatal ("Unable to find WDEF."); } } t_aux_w = (AuxWinHandle) NewHandle (sizeof (AuxWinRec)); HxX (t_aux_w, awNext) = AuxWinHead; HxX (t_aux_w, awOwner) = (WindowPtr) RM (w); HxX (t_aux_w, awCTable) = (CTabHandle) RM (GetResource (TICK("wctb"), 0)); HxX (t_aux_w, dialogCItem) = 0; HxX (t_aux_w, awFlags) = CL ((proc_id & 0xF) << 24); HxX (t_aux_w, awReserved) = 0; HxX (t_aux_w, awRefCon) = 0; AuxWinHead = RM (t_aux_w); { HIDDEN_Handle t; PtrToHand ((Ptr) title, &t, (LONGINT) title[0] + 1); WINDOW_TITLE_X (w) = (StringHandle) RM (t.p); } if (cwindow_p) OpenCPort ((CGrafPtr) w); else OpenPort ((GrafPtr) w); OffsetRect (&PORT_BOUNDS (w), -CW (bounds->left), -CW (bounds->top)); PORT_RECT (w) = *bounds; OffsetRect (&PORT_RECT (w), -CW (bounds->left), -CW (bounds->top)); LOCK_HANDLE_EXCURSION_1 (WINDOW_TITLE (w), { WINDOW_TITLE_WIDTH_X (w) = CW (StringWidth (STARH (WINDOW_TITLE (w)))); }); TextFont (applFont); WINDOW_CONTROL_LIST_X (w) = (ControlHandle)CWC (0); WINDOW_PIC_X (w) = (PicHandle)CWC (0); WINDOW_REF_CON_X (w) = CL (ref_con); WINDCALL ((WindowPtr) w, wNew, 0); if (WINDOW_VISIBLE_X (w)) { THEPORT_SAVE_EXCURSION (MR (wmgr_port), { WINDCALL ((WindowPtr) w, wCalcRgns, 0); SetClip (WINDOW_STRUCT_REGION (w)); ClipAbove (w); PenPat (black); WINDCALL ((WindowPtr) w, wDraw, 0); CalcVis (w); EraseRgn (WINDOW_CONT_REGION (w)); CopyRgn (WINDOW_CONT_REGION (w), WINDOW_UPDATE_REGION (w)); if (WINDOW_NEXT_WINDOW_X (w)) CalcVisBehind (WINDOW_NEXT_WINDOW (w), WINDOW_STRUCT_REGION (w)); }); } else SetEmptyRgn (PORT_VIS_REGION (w)); if (t_w) { HiliteWindow ((WindowPtr) t_w, FALSE); CurDeactive = (WindowPtr) RM (t_w); } SetPort (save_port); } P8 (PUBLIC pascal trap, WindowPtr, NewWindow, Ptr, window_storage, Rect *, bounds, StringPtr, title, BOOLEAN, visible_p, INTEGER, proc_id, WindowPtr, behind, BOOLEAN, go_away_flag, LONGINT, ref_con) { WindowPeek w; int allocated_p = 0; if (!window_storage) { allocated_p = 1; /* Hack for Dark Castle Demo. They call NewWindow and expect us to create the storage. Immediately after calling NewWindow they set the windowKind field to dialogKind. Later they call UpdateDialog on this window and we die a horrible death since we try to refer to a field that isn't present. I don't know how they get away with it on the Mac, but I doubt that this particular hack will hurt us elsewhere. At some point we should find out why it works on the Mac and then get rid of this evil hack. ctm 97/06/01 */ { int size; #define DARK_CASTLE_HACK #if defined(DARK_CASTLE_HACK) #warning DARK_CASTLE_HACK if (strncmp ((char *) title+1, "Modal", 5) == 0) size = sizeof (DialogRecord); else size = sizeof *w; w = (WindowPeek) _NewPtr_flags (size, FALSE, TRUE); #else w = (WindowPeek) NewPtr (sizeof *w); #endif } } else w = (WindowPeek) window_storage; ROMlib_new_window_common (w, allocated_p, 0, bounds, title, visible_p, proc_id, behind, go_away_flag, ref_con); return (WindowPtr) w; } P8 (PUBLIC pascal trap, CWindowPtr, NewCWindow, Ptr, window_storage, Rect *, bounds, StringPtr, title, BOOLEAN, visible_p, INTEGER, proc_id, CWindowPtr, behind, BOOLEAN, go_away_flag, LONGINT, ref_con) { WindowPeek w; int allocated_p = 0; if (!window_storage) { allocated_p = 1; w = (WindowPeek) NewPtr (sizeof *w); } else w = (WindowPeek) window_storage; ROMlib_new_window_common (w, allocated_p, 1, bounds, title, visible_p, proc_id, (WindowPtr) behind, go_away_flag, ref_con); return (CWindowPtr) w; } typedef windrestype *windrestypeptr; MAKE_HIDDEN(windrestypeptr); typedef HIDDEN_windrestypeptr *windrestypehand; P3 (PUBLIC pascal trap, CWindowPtr, GetNewCWindow, INTEGER, window_id, Ptr, window_storage, CWindowPtr, behind) { CWindowPtr new_cwin; windrestypehand win_res; Handle win_ctab_res; PaletteHandle palette; win_res = (windrestypehand) ROMlib_getrestid (TICK ("WIND"), window_id); if (win_res == NULL) return (CWindowPtr) NULL; new_cwin = NewCWindow (window_storage, &HxX (win_res, _wrect), (StringPtr) ((char *) &HxX (win_res, _wrect) + 18), Hx (win_res, _wvisible) != 0, Hx (win_res, _wprocid), behind, Hx (win_res, _wgoaway) != 0, CL (*(LONGINT *) ((char *) &HxX (win_res, _wrect) + 14))); win_ctab_res = ROMlib_getrestid (TICK ("wctb"), window_id); if (win_ctab_res != NULL) { THEPORT_SAVE_EXCURSION (thePort, { SetWinColor ((WindowPtr) new_cwin, (CTabHandle) win_ctab_res); }); } /* if this is a color window we must check if a palette corresponding to this window id exists */ palette = GetNewPalette (window_id); if (palette) NSetPalette ((WindowPtr) new_cwin, palette, pmAllUpdates); return new_cwin; } P3(PUBLIC pascal trap, WindowPtr, GetNewWindow, INTEGER, wid, Ptr, wst, WindowPtr, behind) { windrestypehand wh; WindowPtr tp; wh = (windrestypehand) GetResource(TICK("WIND"), wid); if (!wh) return(0); if (!(*wh).p) LoadResource((Handle) wh); tp = NewWindow(wst, &(HxX(wh, _wrect)), (StringPtr) ((char *) &HxX(wh, _wrect) + 18), Hx(wh, _wvisible) != 0, Hx(wh, _wprocid), (WindowPtr) behind, Hx(wh, _wgoaway) != 0, CL(*(LONGINT *)( (char *) &HxX(wh, _wrect) + 14))); return(tp); } /* * NOTE below: On the Mac+ if after you close a window, the top most * window is non-visible, it will shuffle things. */ P1(PUBLIC pascal trap, void, CloseWindow, WindowPtr, w) { WindowPeek wptmp; GrafPtr savgp; MAKE_HIDDEN(AuxWinHandle); AuxWinHandle saveauxh; HIDDEN_AuxWinHandle *auxhp; ControlHandle c, t; if (FrontWindow () == w) { wptmp = ROMlib_firstvisible ((WindowPtr) WINDOW_NEXT_WINDOW (w)); if (wptmp) { HiliteWindow ((WindowPtr) wptmp, TRUE); CurActivate = (WindowPtr) RM (wptmp); } } if (MR (WindowList) == (WindowPeek) w) { WindowList = WINDOW_NEXT_WINDOW_X (w); wptmp = MR(WindowList); } else { for (wptmp = MR (WindowList); wptmp && WINDOW_NEXT_WINDOW (wptmp) != (WindowPeek) w; wptmp = WINDOW_NEXT_WINDOW (wptmp)) ; if (wptmp) WINDOW_NEXT_WINDOW_X (wptmp) = WINDOW_NEXT_WINDOW_X (w); } /* notify the palette manager this window has been deleted */ pm_window_closed (w); /* notify the palette manager that the `FrontWindow ()' may have changed */ pm_front_window_maybe_changed_hook (); /* NOTE: tests have shown that the behaviour implemented below is indeed what a Mac+ does */ /* NOTE: we can't use THEPORT_SAVE_EXCURSION here, becuase of this odd behavior */ savgp = thePort == (GrafPtr) w ? (GrafPtr) MR (wmgr_port) : thePort; SetPort (MR (wmgr_port)); SetClip (MR (GrayRgn)); PaintBehind (WINDOW_NEXT_WINDOW (w), WINDOW_STRUCT_REGION (w)); if (WINDOW_NEXT_WINDOW_X (w)) CalcVisBehind (WINDOW_NEXT_WINDOW (w), WINDOW_STRUCT_REGION (w)); DisposeRgn (WINDOW_STRUCT_REGION (w)); DisposeRgn (WINDOW_CONT_REGION (w)); DisposeRgn (WINDOW_UPDATE_REGION (w)); DisposHandle ((Handle) WINDOW_TITLE (w)); for (auxhp = (HIDDEN_AuxWinHandle *) &AuxWinHead; (*auxhp).p && STARH(STARH(auxhp))->awOwner != RM(w); auxhp = (HIDDEN_AuxWinHandle *) &STARH(STARH(auxhp))->awNext) ; if ((*auxhp).p) { saveauxh = STARH(auxhp); (*auxhp).p = STARH(STARH(auxhp))->awNext; DisposHandle((Handle) saveauxh); } #if defined (NOTAGOODIDEA) #warning "what the hell does this mean?! DANGER WILL ROBINSON!" Cx(* (Ptr *) Cx)(((WindowPeek)w)->windowDefProc) = 0; DisposHandle(Cx(((WindowPeek)w)->windowDefProc)); #endif /* NOTAGOODIDEA */ /* * TODO: Fix this. Tests on the mac show that KillControls is called, * but just replacing the for loop causes many apps to die. It could * be because some window information that DisposeControl wants is * destroyed already, or it could be DisposeControl or KillControl * makes some FALSE assumptions. More tests need to be written. */ #if 1 for (c = WINDOW_CONTROL_LIST (w); c;) { t = c; c = HxP (c, nextControl); #if 0 DisposHandle(Hx(t, contrlDefProc)); #endif /* 0 */ DisposHandle((Handle) t); } #else /* 0 */ KillControls(w); #endif /* 0 */ if (WINDOW_PIC_X (w)) KillPicture (WINDOW_PIC (w)); ClosePort ((GrafPtr) w); SetPort (savgp); if (MR (CurActivate) == w) CurActivate = 0; if (MR (CurDeactive) == w) CurDeactive = 0; WINDCALL((WindowPtr) w, wDispose, 0); } P1 (PUBLIC pascal trap, void, DisposeWindow, WindowPtr, w) { CloseWindow(w); DisposPtr((Ptr) w); }
28.093151
78
0.639507
MaddTheSane
d3b7679b78b22c90df5d4779b1b558412e0926c3
8,894
cpp
C++
webkit/Source/WebKit/android/WebCoreSupport/PlatformBridge.cpp
mogoweb/webkit_for_android5.1
63728b4ae4c494011e8e43a466637c826f0f6b5f
[ "Apache-2.0" ]
2
2017-05-19T08:53:12.000Z
2017-08-28T11:59:26.000Z
webkit/Source/WebKit/android/WebCoreSupport/PlatformBridge.cpp
mogoweb/webkit_for_android5.1
63728b4ae4c494011e8e43a466637c826f0f6b5f
[ "Apache-2.0" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
webkit/Source/WebKit/android/WebCoreSupport/PlatformBridge.cpp
mogoweb/webkit_for_android5.1
63728b4ae4c494011e8e43a466637c826f0f6b5f
[ "Apache-2.0" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
/* * Copyright 2009, The Android Open Source Project * * 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <PlatformBridge.h> #include "CookieClient.h" #include "Document.h" #include "FileSystemClient.h" #include "FrameView.h" #include "JNIUtility.h" #include "JavaSharedClient.h" #include "KeyGeneratorClient.h" #include "MemoryUsage.h" #include "PluginView.h" #include "RenderLayer.h" #include "RenderView.h" #include "Settings.h" #include "WebCookieJar.h" #include "WebRequestContext.h" #include "WebViewCore.h" #include "npruntime.h" #include <gui/ISurfaceComposer.h> #include <gui/SurfaceComposerClient.h> #include <ui/DisplayInfo.h> #include <ui/PixelFormat.h> #include <wtf/android/AndroidThreading.h> #include <wtf/MainThread.h> #include <algorithm> using namespace android; namespace WebCore { WTF::Vector<String> PlatformBridge::getSupportedKeyStrengthList() { KeyGeneratorClient* client = JavaSharedClient::GetKeyGeneratorClient(); if (!client) return WTF::Vector<String>(); return client->getSupportedKeyStrengthList(); } String PlatformBridge::getSignedPublicKeyAndChallengeString(unsigned index, const String& challenge, const KURL& url) { KeyGeneratorClient* client = JavaSharedClient::GetKeyGeneratorClient(); if (!client) return String(); return client->getSignedPublicKeyAndChallengeString(index, challenge, url); } void PlatformBridge::setCookies(const Document* document, const KURL& url, const String& value) { std::string cookieValue(value.utf8().data()); GURL cookieGurl(url.string().utf8().data()); bool isPrivateBrowsing = document->settings() && document->settings()->privateBrowsingEnabled(); WebCookieJar* cookieJar = WebCookieJar::get(isPrivateBrowsing); if (cookieJar->allowCookies()) cookieJar->cookieStore()->SetCookie(cookieGurl, cookieValue); } String PlatformBridge::cookies(const Document* document, const KURL& url) { GURL cookieGurl(url.string().utf8().data()); bool isPrivateBrowsing = document->settings() && document->settings()->privateBrowsingEnabled(); WebCookieJar* cookieJar = WebCookieJar::get(isPrivateBrowsing); String cookieString; if (cookieJar->allowCookies()) { std::string cookies = cookieJar->cookieStore()->GetCookies(cookieGurl); cookieString = cookies.c_str(); } return cookieString; } bool PlatformBridge::cookiesEnabled(const Document* document) { bool isPrivateBrowsing = document->settings() && document->settings()->privateBrowsingEnabled(); return WebCookieJar::get(isPrivateBrowsing)->allowCookies(); } NPObject* PlatformBridge::pluginScriptableObject(Widget* widget) { if (!widget->isPluginView()) return 0; PluginView* pluginView = static_cast<PluginView*>(widget); return pluginView->getNPObject(); } bool PlatformBridge::popupsAllowed(NPP) { return false; } String PlatformBridge::resolveFilePathForContentUri(const String& contentUri) { FileSystemClient* client = JavaSharedClient::GetFileSystemClient(); return client->resolveFilePathForContentUri(contentUri); } int PlatformBridge::PlatformBridge::screenDepth() { android::sp<android::IBinder> display( android::SurfaceComposerClient::getBuiltInDisplay( android::ISurfaceComposer::eDisplayIdMain)); android::DisplayInfo info; android::SurfaceComposerClient::getDisplayInfo(display, &info); #if 0 //~: TODO(alex) return info.pixelFormatInfo.bitsPerPixel; #else //~: TODO(alex) ALOGW("PlatformBridge::screenDepth NOTIMPLEMENTED"); return 0; #endif } FloatRect PlatformBridge::screenRect() { android::sp<android::IBinder> display( android::SurfaceComposerClient::getBuiltInDisplay( android::ISurfaceComposer::eDisplayIdMain)); android::DisplayInfo info; android::SurfaceComposerClient::getDisplayInfo(display, &info); return FloatRect(0.0, 0.0, info.w, info.h); } // The visible size on screen in document coordinate int PlatformBridge::screenWidthInDocCoord(const WebCore::FrameView* frameView) { android::WebViewCore* webViewCore = android::WebViewCore::getWebViewCore(frameView); return webViewCore->screenWidth(); } int PlatformBridge::screenHeightInDocCoord(const WebCore::FrameView* frameView) { android::WebViewCore* webViewCore = android::WebViewCore::getWebViewCore(frameView); return webViewCore->screenHeight(); } String PlatformBridge::computeDefaultLanguage() { String acceptLanguages = WebRequestContext::acceptLanguage(); size_t length = acceptLanguages.find(','); if (length == std::string::npos) length = acceptLanguages.length(); return acceptLanguages.substring(0, length); } void PlatformBridge::updateViewport(FrameView* frameView) { android::WebViewCore* webViewCore = android::WebViewCore::getWebViewCore(frameView); webViewCore->updateViewport(); } void PlatformBridge::updateTextfield(FrameView* frameView, Node* nodePtr, const WTF::String& text) { android::WebViewCore* webViewCore = android::WebViewCore::getWebViewCore(frameView); webViewCore->updateTextfield(nodePtr, text); } void PlatformBridge::setScrollPosition(ScrollView* scrollView, int x, int y) { FrameView* frameView = scrollView->frameView(); if (!frameView) return; // Check to make sure the view is the main FrameView. android::WebViewCore *webViewCore = android::WebViewCore::getWebViewCore(scrollView); if (webViewCore->mainFrame()->view() == scrollView) { x = std::max(0, std::min(frameView->contentsWidth(), x)); y = std::max(0, std::min(frameView->contentsHeight(), y)); webViewCore->scrollTo(x, y); } } int PlatformBridge::lowMemoryUsageMB() { return MemoryUsage::lowMemoryUsageMb(); } int PlatformBridge::highMemoryUsageMB() { return MemoryUsage::highMemoryUsageMb(); } int PlatformBridge::highUsageDeltaMB() { return MemoryUsage::highUsageDeltaMb(); } int PlatformBridge::memoryUsageMB() { return MemoryUsage::memoryUsageMb(false); } int PlatformBridge::actualMemoryUsageMB() { return MemoryUsage::memoryUsageMb(true); } bool PlatformBridge::canSatisfyMemoryAllocation(long bytes) { JNIEnv* env = JSC::Bindings::getJNIEnv(); jclass bridgeClass = env->FindClass("android/webkit/JniUtil"); jmethodID method = env->GetStaticMethodID(bridgeClass, "canSatisfyMemoryAllocation", "(J)Z"); jboolean canAllocate = env->CallStaticBooleanMethod(bridgeClass, method, static_cast<jlong>(bytes)); env->DeleteLocalRef(bridgeClass); return canAllocate == JNI_TRUE; } } // namespace WebCore // This is the implementation of AndroidThreading, which is declared in // JavaScriptCore/wtf/android/AndroidThreading.h. It is provided here, rather // than in its own source file, to avoid linker problems. // // By default, when building a shared library, the linker strips from static // libraries any compilation units which do not contain any code referenced from // that static library. Since // AndroidThreading::scheduleDispatchFunctionsOnMainThread is not referenced // from libwebcore.a, implementing it in its own compilation unit results in it // being stripped. This stripping can be avoided by using the linker option // --whole-archive for libwebcore.a, but this adds considerably to the size of // libwebcore.so. namespace WTF { // Callback in the main thread. static void timeoutFired(void*) { dispatchFunctionsFromMainThread(); } void AndroidThreading::scheduleDispatchFunctionsOnMainThread() { JavaSharedClient::EnqueueFunctionPtr(timeoutFired, 0); } } // namespace WTF
33.689394
117
0.745446
mogoweb
d3bcf44a4de3cb66deaf832fc126e4ebff5918c5
887
cpp
C++
src/cpp/fdialog-win32.cpp
andraantariksa/fdialog
be2467aea34122854583f7769281adc9b2611ec7
[ "MIT" ]
null
null
null
src/cpp/fdialog-win32.cpp
andraantariksa/fdialog
be2467aea34122854583f7769281adc9b2611ec7
[ "MIT" ]
null
null
null
src/cpp/fdialog-win32.cpp
andraantariksa/fdialog
be2467aea34122854583f7769281adc9b2611ec7
[ "MIT" ]
null
null
null
#include <cstdio> #include <cwchar> #include <cstring> #include <locale> #include <codecvt> #include <windows.h> #include <commdlg.h> #pragma comment(lib, "comdlg32.lib") #ifndef _FDIALOG_WIN32 #define _FDIALOG_WIN32 extern "C" char* open_dialog() { const size_t MAX_STRING_LENGTH = 300; OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); char *szFile = (char*)malloc(MAX_STRING_LENGTH * sizeof(char)); szFile[0] = '\0'; ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = (LPSTR) szFile; ofn.nMaxFile = 300; ofn.lpstrFilter = "All\0*.*\0Text\0*.txt\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(!GetOpenFileNameA((LPOPENFILENAMEA) &ofn)) { printf("Can't open Windows open dialog\n"); } return szFile; } #endif
19.282609
67
0.694476
andraantariksa
d3c1b0b416e6a83a84e81982e70acab8311b8e84
1,798
cc
C++
tests/benchmark/chunk_replacement_bench.cc
Chippiewill/Phosphor
ef090fa5b331dd94301cd8562b24c78c0c2030f1
[ "Apache-2.0" ]
null
null
null
tests/benchmark/chunk_replacement_bench.cc
Chippiewill/Phosphor
ef090fa5b331dd94301cd8562b24c78c0c2030f1
[ "Apache-2.0" ]
null
null
null
tests/benchmark/chunk_replacement_bench.cc
Chippiewill/Phosphor
ef090fa5b331dd94301cd8562b24c78c0c2030f1
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <benchmark/benchmark.h> #include "bench_common.h" #include "phosphor/trace_log.h" #include "utils/memory.h" using phosphor::utils::make_unique; class MockTraceLog : public phosphor::TraceLog { public: using phosphor::TraceLog::TraceLog; void replaceChunk() { auto ctl = getChunkTenant(); if (!ctl) { return; } phosphor::TraceLog::replaceChunk(*ctl.mutex()); if (!ctl.mutex()->chunk) { ctl.unlock(); stop(); } } }; void RegisterTenants(benchmark::State& state) { static MockTraceLog log{phosphor::TraceLogConfig()}; log.registerThread(); if (state.thread_index == 0) { log.start(phosphor::TraceConfig( phosphor::BufferMode::ring, (sizeof(phosphor::TraceChunk) * (10 * state.threads)))); } while (state.KeepRunning()) { log.replaceChunk(); } if (state.thread_index == 0) { log.stop(); } log.deregisterThread(); } BENCHMARK(RegisterTenants)->ThreadRange(1, phosphor::benchNumThreads()); BENCHMARK_MAIN()
28.539683
79
0.6396
Chippiewill
d3c21fbb302729b47502c2d84cb61f98404cb09f
2,022
cpp
C++
Days 021 - 030/Day 24/LockableBinaryTree.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 021 - 030/Day 24/LockableBinaryTree.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 021 - 030/Day 24/LockableBinaryTree.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <iostream> struct Node { public: int value; Node* left; Node* right; Node* parent; bool isLocked; unsigned int descendantLockCount; Node(int value, Node* left = nullptr, Node* right = nullptr, Node* parent = nullptr) noexcept : value(value), left(left), right(right), parent(parent), isLocked(false), descendantLockCount(0) { if (left != nullptr) { left->parent = this; } if (right != nullptr) { right->parent = this; } } ~Node() noexcept { if (left != nullptr) { delete left; } if (right != nullptr) { delete right; } } inline bool IsLocked() const { return isLocked; } bool Lock() { if (CanBeLocked()) { isLocked = true; Node* currentNode = parent; while (currentNode != nullptr) { currentNode->descendantLockCount++; currentNode = currentNode->parent; } return true; } return false; } bool Unlock() { if (CanBeLocked()) { isLocked = false; Node* currentNode = parent; while (currentNode != nullptr) { currentNode->descendantLockCount--; currentNode = currentNode->parent; } return true; } return false; } private: bool CanBeLocked() const { if (descendantLockCount > 0) { return false; } Node* currentNode = parent; while (currentNode != nullptr) { if (currentNode->isLocked) { return false; } currentNode = currentNode->parent; } return true; } }; int main(int argc, const char* argv[]) { Node* leftleft = new Node(67); Node* leftright = new Node(49); Node* rightright = new Node(36); Node* left = new Node(82, leftleft, leftright); Node* right = new Node(49, nullptr, rightright); Node* root = new Node(19, left, right); std::cout << std::boolalpha; std::cout << left->Lock() << "\n"; std::cout << leftright->Lock() << "\n"; left->Unlock(); std::cout << leftright->Lock() << "\n"; if (leftright->IsLocked()) { std::cout << "Node leftright is locked." << "\n"; } std::cin.get(); return 0; }
14.652174
99
0.608309
LucidSigma
d3c2a72b9d24717384680c5b875076a20c977fde
2,322
cpp
C++
T__Floor.cpp
SJ-magic-work-GolemForBackStage/Kinobi_oF_main
836ef64ecf92a81230c051d308ee7e7d3a7ca1d4
[ "MIT" ]
null
null
null
T__Floor.cpp
SJ-magic-work-GolemForBackStage/Kinobi_oF_main
836ef64ecf92a81230c051d308ee7e7d3a7ca1d4
[ "MIT" ]
null
null
null
T__Floor.cpp
SJ-magic-work-GolemForBackStage/Kinobi_oF_main
836ef64ecf92a81230c051d308ee7e7d3a7ca1d4
[ "MIT" ]
null
null
null
/************************************************************ ************************************************************/ #include "T__Floor.h" /************************************************************ ************************************************************/ /****************************** ******************************/ T__FLOOR::T__FLOOR() : c_SkipProcessControl(0) { } /****************************** ******************************/ T__FLOOR::~T__FLOOR() { } /****************************** ******************************/ void T__FLOOR::exit() { } /****************************** ******************************/ void T__FLOOR::setup() { fbo.allocate(FBO_WIDTH, FBO_HEIGHT, GL_RGBA, 0); fbo_TextureSyphonServer.setName("oF Floor"); } /****************************** ******************************/ void T__FLOOR::update() { } /****************************** ******************************/ void T__FLOOR::drawToFbo_SendSyphon() { /******************** ********************/ c_SkipProcessControl++; if( b_SkipProcessControl && (c_SkipProcessControl % 10 != 0) ){ return; } c_SkipProcessControl = 0; /******************** ********************/ ofDisableAlphaBlending(); ofEnableSmoothing(); fbo.begin(); ofClear(0, 0, 0, 0); /* // 2m ofSetColor(255, 255, 255, 200); ofSetLineWidth(4); ofDrawLine(0, fbo.getHeight()/2, fbo.getWidth(), fbo.getHeight()/2); ofDrawLine(fbo.getWidth()/2, 0, fbo.getWidth()/2, fbo.getHeight()); /*/ // 1m ofSetColor(255, 255, 255, 170); ofSetLineWidth(2); /* ofSetColor(255, 255, 255, 120); ofSetLineWidth(600); */ ofDrawLine(0, fbo.getHeight()*1/4, fbo.getWidth(), fbo.getHeight()*1/4); ofDrawLine(0, fbo.getHeight()*3/4, fbo.getWidth(), fbo.getHeight()*3/4); ofDrawLine(fbo.getWidth()*1/4, 0, fbo.getWidth()*1/4, fbo.getHeight()); ofDrawLine(fbo.getWidth()*3/4, 0, fbo.getWidth()*3/4, fbo.getHeight()); //*/ fbo.end(); /******************** publish ********************/ ofTexture tex = fbo.getTextureReference(); fbo_TextureSyphonServer.publishTexture(&tex); } /****************************** ******************************/ void T__FLOOR::draw_FboToMonitor() { ofSetColor(255, 255, 255, 255); fbo.draw(0, 0, fbo.getWidth(), fbo.getHeight()); // fbo.draw(0, 0, ofGetWidth(), ofGetHeight()); }
22.990099
74
0.425065
SJ-magic-work-GolemForBackStage
d3c4b139c81875506b2ae0ca864141fc4b3ac7cb
6,048
cpp
C++
doc/Programs/LecturePrograms/programs/RandomWalks/cpp/main.cpp
kimrojas/ComputationalPhysicsMSU
a47cfc18b3ad6adb23045b3f49fab18c0333f556
[ "CC0-1.0" ]
220
2016-08-25T09:18:33.000Z
2022-03-31T14:09:16.000Z
doc/Programs/LecturePrograms/programs/RandomWalks/cpp/main.cpp
dnhdang94/ComputationalPhysicsMSU
16990c74cf06eb5b933982137f0536d669567259
[ "CC0-1.0" ]
1
2020-12-04T12:55:10.000Z
2020-12-04T12:55:10.000Z
doc/Programs/LecturePrograms/programs/RandomWalks/cpp/main.cpp
dnhdang94/ComputationalPhysicsMSU
16990c74cf06eb5b933982137f0536d669567259
[ "CC0-1.0" ]
136
2016-08-25T09:04:56.000Z
2022-03-12T09:54:21.000Z
#include <iostream> #include <fstream> #include <array> #include <random> #include <armadillo> using namespace std; using namespace arma; void MonteCarlo(vec &players, int MCSteps, int N, int transactions, double lambda, double alpha, double gamma, ofstream &outFile, vec &binCounts, double binSize, double m0, ofstream &outFileErr); void outPut(vec &players, int MCSteps, int N, int transactions, mat &expectVal); double findVariance(vec &players, int transaction, int N, double m0); void makeBins(vec &players, vec &binCount, double binSize); int main(int argc, char *argv[]) { if (argc < 8){ cout << "To few arguments given. Expected number of persons, Monte Carlo cycles, transactions, start money, lambda, alpha and gamma" << endl; } int N = stoi(argv[1]); int MCSteps = stoi(argv[2]); int transactions = stoi(argv[3]); double startMoney = stod(argv[4]); double lambda = stod(argv[5]); double alpha = stod(argv[6]); double gamma = stod(argv[7]); double binSize = 0.01*startMoney; ofstream outFileVar = ofstream("variance.txt"); ofstream outFileErr = ofstream("distError.txt"); //outFileVar.open("variance.txt"); ofstream outFileParameter; outFileParameter.open("parameters.txt"); ofstream binParameters = ofstream("binParameters.txt"); outFileParameter << "N " << N << "\n"; outFileParameter << "MCSteps " << MCSteps << "\n"; outFileParameter << "Trasactions " << transactions << "\n"; outFileParameter << "StartingMoney " << startMoney << "\n"; outFileParameter << "Lambda " << lambda << "\n"; outFileParameter << "Alpha " << alpha << "\n"; outFileParameter << "Gamma " << gamma; double binEnd; if (alpha > 0 || gamma > 0){ binEnd = 2*startMoney/(sqrt(lambda + 0.1)) + startMoney; } else{ binEnd = 2*startMoney/(sqrt(lambda + 0.1)) + startMoney; } int binNum = int(binEnd/double(binSize)); cout << binNum << endl; vec binCounts = zeros(binNum); vec players = ones(N)*startMoney; cout << alpha << " " << gamma << endl; binParameters << MCSteps << " " << N << " " << startMoney << " " << binSize << " " << binNum << " " << (binEnd) << " " << lambda << " " << alpha << " " << gamma << endl; binParameters.close(); MonteCarlo(players, MCSteps, N,transactions,lambda,alpha,gamma,outFileVar,binCounts,binSize,startMoney,outFileErr); //outPut(players, MCSteps, N, transactions, expectVal); binCounts.save("bins.bin",raw_binary); players.save("data.bin",raw_binary); outFileErr.close(); outFileVar.close(); //players.save("data.bin",raw_binary); cout << "Finished" << endl; } void MonteCarlo(vec &players, int MCSteps, int N, int transactions, double lambda,double alpha,double gamma, ofstream &outFile, vec &binCounts,double binSize,double m0,ofstream &outFileErr){ random_device rd; mt19937_64 gen(rd()); uniform_real_distribution<double> distribution(0.0,N); uniform_real_distribution<double> eps(0.0,1.0); int writingFreq = 100; double p = 0; mat c = zeros(N,N); double maxTransactions = 1; for (int i = 0; i < MCSteps; i++){ players.fill(m0); for (int j = 0; j < transactions; j++){ int index_i = distribution(gen); int index_j = distribution(gen); double epsFac = eps(gen); if (players(index_i) - players(index_j) == 0){ p = 1.; } else{ p = 2*pow(fabs((players(index_i) - players(index_j))/double(m0)),-alpha)*(pow((c(index_i,index_j)+1)/(maxTransactions+1),gamma)); } if (eps(gen) < p && (index_i != index_j)){ double m1 = lambda*players(index_i) + (1-lambda)*epsFac* (players(index_i) + players(index_j)); double m2 = lambda*players(index_j) + (1-lambda)*(1-epsFac)*(players(index_i) + players(index_j)); //cout << "hei" << endl; players(index_i) = m1; players(index_j) = m2; c(index_j,index_i) += 1; c(index_i,index_j) += 1; if (c(index_j,index_i) > maxTransactions){ maxTransactions = c(index_j,index_i); } else if (c(index_i,index_j) > maxTransactions){ maxTransactions = c(index_i,index_j); } } if (MCSteps == 1){ if (j%writingFreq == 0){ double mean = 0; for (int i = 0; i < N; i++){ mean += players(i)/m0; } mean /= (N); outFile << (j+1) << " " << findVariance(players,j+1,N,m0) << " " << mean << "\n"; } } } vec tempCounts = binCounts; makeBins(players,binCounts,binSize); if (i > 1){ outFileErr << i+1 << " " << norm(tempCounts/double(i-1) - binCounts/(double(i)) ) << endl; } } } //void outPut(vec &players, int MCSteps, int N, int transactions, mat &expectVal){ // vec means = zeros(N); // for (int k = 0; k < N;k++){ // means(k) = expectVal(0,k) / MCSteps; // } // means.save("data.bin",raw_binary); //} double findVariance(vec &players, int transaction, int N,double m0){ double mean = 0; double secondMoment = 0; for (int i = 0; i < N; i++){ mean += players(i)/m0; secondMoment += players(i)/m0*players(i)/m0; } mean /= (N); //cout << secondMoment << endl; secondMoment /= (N); return (secondMoment - mean*mean); } void makeBins(vec &players, vec &binCount, double binSize){ for (int i = 0; i < players.size();i++){ for (int j = 0; j < binCount.size();j++){ if(players(i)> (j-1)*binSize && players(i)< (j)*binSize){ binCount(j) += 1; } } } //binCount.print(); }
24
195
0.55506
kimrojas
d3ca00fb443a215ed3c8cde06d7e8f1b1a754c20
4,532
cpp
C++
cpp/altpebaddr.cpp
gregzakh/sketches
acbc573b9e67228dac21a94b597d89e2ea5cd755
[ "MIT" ]
1
2022-01-07T13:18:51.000Z
2022-01-07T13:18:51.000Z
cpp/altpebaddr.cpp
gregzakh/sketches
acbc573b9e67228dac21a94b597d89e2ea5cd755
[ "MIT" ]
null
null
null
cpp/altpebaddr.cpp
gregzakh/sketches
acbc573b9e67228dac21a94b597d89e2ea5cd755
[ "MIT" ]
4
2020-02-11T01:00:11.000Z
2022-01-07T14:24:38.000Z
/* * getting PEB address (against ASLR and NtQueryInformationProcess) */ #ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <tlhelp32.h> #include <iostream> #include <string> #include <vector> #include <memory> #include <locale> typedef LONG NTSTATUS; #ifdef _M_X64 #define PebImgBase 0x10 #else #define PebImgBase 0x08 #endif #define NT_SUCCESS(Status) ((static_cast<NTSTATUS>(Status)) >= 0L) #define AddrToFunc(T) (reinterpret_cast<T>(GetProcAddress(GetModuleHandle(L"ntdll.dll"), (&((#T)[1]))))) typedef enum _MEMORY_INFORMATION_CLASS { MemoryBasicInformation, MemoryWorkingSetInformation, MemoryMappedFilenameInformation, MemoryRegionInformation, MemoryWorkingSetExInformation, MemorySharedCommitInformation, MemoryImageInformation, MemoryRegionInformationEx, MemoryPrivilegedBasicInformation, MemoryEnclaveImageInformation, MemoryBasicInformationCapped } MEMORY_INFORMATION_CLASS; typedef NTSTATUS (__stdcall *pNtQueryVirtualMemory)(HANDLE, PVOID, MEMORY_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T); typedef NTSTATUS (__stdcall *pNtReadVirtualMemory)(HANDLE, PVOID, PVOID, SIZE_T, PSIZE_T); typedef ULONG (__stdcall *pRtlNtStatusToDosError)(NTSTATUS); pNtQueryVirtualMemory NtQueryVirtualMemory; pNtReadVirtualMemory NtReadVirtualMemory; pRtlNtStatusToDosError RtlNtStatusToDosError; BOOLEAN LocateSignatures(void) { NtQueryVirtualMemory = AddrToFunc(pNtQueryVirtualMemory); if (nullptr == NtQueryVirtualMemory) return FALSE; NtReadVirtualMemory = AddrToFunc(pNtReadVirtualMemory); if (nullptr == NtReadVirtualMemory) return FALSE; RtlNtStatusToDosError = AddrToFunc(pRtlNtStatusToDosError); if (nullptr == RtlNtStatusToDosError) return FALSE; return TRUE; } int wmain(int argc, WCHAR **argv) { using namespace std; locale::global(locale("")); auto getlasterror = [](NTSTATUS nts) { HLOCAL loc{}; DWORD size = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr, 0L != nts ? RtlNtStatusToDosError(nts) : GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&loc), 0, nullptr ); if (!size) wcout << L"[?] Unknown error has been occured." << endl; else { wstring msg(reinterpret_cast<LPWSTR>(loc)); wcout << L"[!] " << msg.substr(0, size - sizeof(WCHAR)) << endl; } if (nullptr != LocalFree(loc)) wcout << L"LocalFree (" << GetLastError() << L") fatal error." <<endl; }; auto getbaseaddress = [&getlasterror](DWORD pid) -> PBYTE { HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); if (INVALID_HANDLE_VALUE == snap) { getlasterror(0L); return nullptr; } MODULEENTRY32 mod = {0}; mod.dwSize = sizeof(mod); if (!Module32First(snap, &mod)) getlasterror(0L); if (!CloseHandle(snap)) getlasterror(0L); return !mod.modBaseAddr ? nullptr : mod.modBaseAddr; }; if (!LocateSignatures()) { getlasterror(0L); return 1; } wstring app(argv[0]); app = app.substr(app.find_last_of(L"\\") + 1, app.length()); if (2 != argc) { wcout << L"Usage: " << app << L" <PID>" <<endl; return 1; } auto ps = shared_ptr<HANDLE>(new HANDLE(OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, wcstoul(argv[1], 0, 0) )), [&getlasterror](HANDLE *instance) { if (*instance) { if (!CloseHandle(*instance)) getlasterror(0L); else wcout << L"[*] successfully released" << endl; } }); if (!*ps) { getlasterror(0L); return 1; } // image base address PBYTE img = getbaseaddress(wcstoul(argv[1], 0, 0)); if (nullptr == img) return 1; // locating PEB MEMORY_BASIC_INFORMATION mbi = {0}; PVOID ptr = reinterpret_cast<PVOID>(0x7FFE0000); // lower than KUSER_SHARED_DATA while (1) { NTSTATUS nts = NtQueryVirtualMemory( *ps, ptr, MemoryBasicInformation, &mbi, sizeof(mbi), nullptr ); if (!NT_SUCCESS(nts)) break; ptr = static_cast<PBYTE>(mbi.BaseAddress) + mbi.RegionSize; if (MEM_PRIVATE != mbi.Type && MEM_COMMIT != mbi.State && PAGE_READWRITE != mbi.Protect ) continue; PBYTE test{}; nts = NtReadVirtualMemory( *ps, static_cast<PBYTE>(mbi.BaseAddress) + PebImgBase, &test, sizeof(PBYTE), nullptr ); if (!NT_SUCCESS(nts)) { // getlasterror(nts); continue; } if (test == img) { wcout << L"[*] PEB address " << mbi.BaseAddress << endl; break; } } return 0; }
28.325
117
0.684687
gregzakh
d3cb37718b5d1232ca4a5ba6d54959243340e308
4,796
cpp
C++
src/PointwiseFunctions/MathFunctions/PowX.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
null
null
null
src/PointwiseFunctions/MathFunctions/PowX.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
1
2022-03-25T18:26:16.000Z
2022-03-25T19:30:39.000Z
src/PointwiseFunctions/MathFunctions/PowX.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
1
2019-01-03T21:47:04.000Z
2019-01-03T21:47:04.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "PointwiseFunctions/MathFunctions/PowX.hpp" #include "DataStructures/DataVector.hpp" #include "Utilities/GenerateInstantiations.hpp" #include "Utilities/MakeWithValue.hpp" namespace MathFunctions { template <typename Fr> PowX<1, Fr>::PowX(const int power) noexcept : power_(power) {} template <typename Fr> double PowX<1, Fr>::operator()(const double& x) const noexcept { return apply_call_operator(x); } template <typename Fr> DataVector PowX<1, Fr>::operator()(const DataVector& x) const noexcept { return apply_call_operator(x); } template <typename Fr> double PowX<1, Fr>::first_deriv(const double& x) const noexcept { return apply_first_deriv(x); } template <typename Fr> DataVector PowX<1, Fr>::first_deriv(const DataVector& x) const noexcept { return apply_first_deriv(x); } template <typename Fr> double PowX<1, Fr>::second_deriv(const double& x) const noexcept { return apply_second_deriv(x); } template <typename Fr> DataVector PowX<1, Fr>::second_deriv(const DataVector& x) const noexcept { return apply_second_deriv(x); } template <typename Fr> double PowX<1, Fr>::third_deriv(const double& x) const noexcept { return apply_third_deriv(x); } template <typename Fr> DataVector PowX<1, Fr>::third_deriv(const DataVector& x) const noexcept { return apply_third_deriv(x); } template <typename Fr> template <typename T> T PowX<1, Fr>::apply_call_operator(const T& x) const noexcept { return pow(x, power_); } template <typename Fr> template <typename T> T PowX<1, Fr>::apply_first_deriv(const T& x) const noexcept { return 0 == power_ ? make_with_value<T>(x, 0.0) : power_ * pow(x, power_ - 1); } template <typename Fr> template <typename T> T PowX<1, Fr>::apply_second_deriv(const T& x) const noexcept { return 0 == power_ or 1 == power_ ? make_with_value<T>(x, 0.0) : power_ * (power_ - 1) * pow(x, power_ - 2); } template <typename Fr> template <typename T> T PowX<1, Fr>::apply_third_deriv(const T& x) const noexcept { return 0 == power_ or 1 == power_ or 2 == power_ ? make_with_value<T>(x, 0.0) : power_ * (power_ - 1) * (power_ - 2) * pow(x, power_ - 3); } template <typename Fr> void PowX<1, Fr>::pup(PUP::er& p) { MathFunction<1, Fr>::pup(p); p | power_; } /// \cond template MathFunctions::PowX<1, Frame::Grid>::PowX(const int power) noexcept; template MathFunctions::PowX<1, Frame::Inertial>::PowX( const int power) noexcept; template void MathFunctions::PowX<1, Frame::Grid>::pup(PUP::er& p); template void MathFunctions::PowX<1, Frame::Inertial>::pup(PUP::er& p); #define FRAME(data) BOOST_PP_TUPLE_ELEM(0, data) #define DTYPE(data) BOOST_PP_TUPLE_ELEM(1, data) #define INSTANTIATE(_, data) \ template DTYPE(data) \ MathFunctions::PowX<1, FRAME(data)>::operator()(const DTYPE(data) & x) \ const noexcept; \ template DTYPE(data) \ MathFunctions::PowX<1, FRAME(data)>::first_deriv(const DTYPE(data) & x) \ const noexcept; \ template DTYPE(data) \ MathFunctions::PowX<1, FRAME(data)>::second_deriv(const DTYPE(data) & x) \ const noexcept; \ template DTYPE(data) \ MathFunctions::PowX<1, FRAME(data)>::third_deriv(const DTYPE(data) & x) \ const noexcept; \ template DTYPE(data) \ MathFunctions::PowX<1, FRAME(data)>::apply_call_operator( \ const DTYPE(data) & x) const noexcept; \ template DTYPE(data) MathFunctions::PowX<1, FRAME(data)>::apply_first_deriv( \ const DTYPE(data) & x) const noexcept; \ template DTYPE(data) \ MathFunctions::PowX<1, FRAME(data)>::apply_second_deriv( \ const DTYPE(data) & x) const noexcept; \ template DTYPE(data) MathFunctions::PowX<1, FRAME(data)>::apply_third_deriv( \ const DTYPE(data) & x) const noexcept; GENERATE_INSTANTIATIONS(INSTANTIATE, (Frame::Grid, Frame::Inertial), (double, DataVector)) #undef DTYPE #undef FRAME #undef INSTANTIATE /// \endcond } // namespace MathFunctions
36.892308
80
0.584028
tomwlodarczyk
d3cea590a7fc2df48824a7ed4cfda9c0d6d87666
582
hpp
C++
nodes/random_regex_node.hpp
do-m-en/random_regex_string
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
[ "BSL-1.0" ]
null
null
null
nodes/random_regex_node.hpp
do-m-en/random_regex_string
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
[ "BSL-1.0" ]
null
null
null
nodes/random_regex_node.hpp
do-m-en/random_regex_string
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
[ "BSL-1.0" ]
null
null
null
#ifndef RANDOM_REGEX_NODE_HPP_INCLUDED #define RANDOM_REGEX_NODE_HPP_INCLUDED #include "regex_node.hpp" namespace rand_regex { class random_regex_node_ : public regex_node_ // . TODO check if this could be derived from range_random_regex_node_ { public: void generate(std::ostream& os, random_generator_base& random_gen, std::vector<std::tuple<int, regex_node_*>>& groups) override; void regenerate(std::ostream& os, const std::vector<std::tuple<int, regex_node_*>>& groups) const override; private: char generated_value_; }; }; #endif // RANDOM_REGEX_NODE_HPP_INCLUDED
27.714286
130
0.785223
do-m-en
d3cfa2c85886b38d838c3caff1fb6629f0e765db
1,051
hpp
C++
Giga_v1/src/eeprom/KDEEPROMMap.hpp
azarashi2931/Giga-Project
2acbd937bec01e6042453fe777f4182b6d67d9b7
[ "MIT" ]
null
null
null
Giga_v1/src/eeprom/KDEEPROMMap.hpp
azarashi2931/Giga-Project
2acbd937bec01e6042453fe777f4182b6d67d9b7
[ "MIT" ]
null
null
null
Giga_v1/src/eeprom/KDEEPROMMap.hpp
azarashi2931/Giga-Project
2acbd937bec01e6042453fe777f4182b6d67d9b7
[ "MIT" ]
null
null
null
#ifndef KD_EEPROM_MAP_h #define KD_EEPROM_MAP_h typedef struct { int address; uint8_t size; } EEPROMData; class KDEEPROMMap { public: static constexpr int NumberOfAddresses = 1; static constexpr int LineThreshold = 0; static constexpr EEPROMData Addresses[NumberOfAddresses] = { {0, 2}, }; }; constexpr int KDEEPROMMap::NumberOfAddresses; constexpr int KDEEPROMMap::LineThreshold; constexpr EEPROMData KDEEPROMMap::Addresses[NumberOfAddresses]; //アドレスリストの整合性を確認します. 整合性が無い場合はコンパイルエラーになります. class KDEEPROMAddressCehecker { public: constexpr static bool checkCorrection(int i) { return i <= 0 ? true : (KDEEPROMMap::Addresses[i - 1].address + KDEEPROMMap::Addresses[i - 1].size == KDEEPROMMap::Addresses[i].address ? checkCorrection(i - 1) : false); }; }; static_assert(KDEEPROMAddressCehecker::checkCorrection(KDEEPROMMap::NumberOfAddresses - 1), "EEPROM address list is invaid."); #endif
25.634146
133
0.665081
azarashi2931
d3cfc6ae5338817f400e495160623ced2e329216
718
hh
C++
Watertank-System/1.0_SystemC/Solutions/Continous_Subsystem/include/watertank_lsf.hh
SimoGira/Embedded-Systems-Design
87829fb65aa64a24e062358671580716a1151572
[ "BSD-3-Clause" ]
null
null
null
Watertank-System/1.0_SystemC/Solutions/Continous_Subsystem/include/watertank_lsf.hh
SimoGira/Embedded-Systems-Design
87829fb65aa64a24e062358671580716a1151572
[ "BSD-3-Clause" ]
null
null
null
Watertank-System/1.0_SystemC/Solutions/Continous_Subsystem/include/watertank_lsf.hh
SimoGira/Embedded-Systems-Design
87829fb65aa64a24e062358671580716a1151572
[ "BSD-3-Clause" ]
null
null
null
#ifndef WATERTANK_LSF_HH #define WATERTANK_LSF_HH #include <systemc-ams> #include "global.hh" SC_MODULE(watertank_lsf){ public: //sc_in_clk clock; //sca_lsf::sca_signal sig_derivative_of_valve_aperture; sca_lsf::sca_signal sig_valve_aperture; sca_lsf::sca_signal sig_water_level; sca_lsf::sca_tdf::sca_source tdf2lsf; // get values from tdf sca_lsf::sca_tdf::sca_sink lsf2tdf; // get signal lsf and output value tdf // sca_lsf::sca_de::sca_source source; // sca_lsf::sca_de::sca_sink sink; sca_lsf::sca_integ int1; sca_lsf::sca_gain gain1, gain2; sca_lsf::sca_sub sub1; SC_CTOR( watertank_lsf ); private: sca_lsf::sca_signal sig1, sig2, sig3; }; #endif
21.117647
80
0.720056
SimoGira
d3d0eaf1b87ea2e66037622edba63a48ba31c13e
1,880
cxx
C++
xp_comm_misc/merl/src/hist.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
3
2020-08-03T08:52:20.000Z
2021-04-10T11:55:49.000Z
xp_comm_misc/merl/src/hist.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
null
null
null
xp_comm_misc/merl/src/hist.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
1
2021-06-08T18:16:45.000Z
2021-06-08T18:16:45.000Z
#include "express.h" #include "hist.hxx" int Volume_Histogram::ComputeHistogram(OMevent_mask , int ) { // volume (Mesh_Unif+Node_Data read notify) // data_component (OMXint read notify) // threshold (OMXint read notify) // histogram (OMXint_array write) int comp = (int)data_component; int thresh = (int)threshold; int dataSize; int dataType; void *data = volume.node_data[comp].values.ret_array_ptr(OM_GET_ARRAY_RD, &dataSize, &dataType); int histSize; int *hist = (int *)histogram.ret_array_ptr(OM_GET_ARRAY_WR, &histSize); if (data && hist) { int i; int value; for (i = 0; i < histSize; i++) hist[i] = 0; if ((dataType == OM_TYPE_CHAR) || (dataType == OM_TYPE_BYTE)) { unsigned char *bytes = (unsigned char *)data; for (i = 0; i < dataSize; i++, bytes++) { value = (int)(*bytes); if (value >= thresh) ++hist[value]; } } else if (dataType == OM_TYPE_SHORT) // actually 12 bits { unsigned short *shorts = (unsigned short *)data; unsigned short clamped; for (i = 0; i < dataSize; i++, shorts++) { clamped = *shorts; if (clamped > 0x0FFF) clamped = 0x0FFF; value = (int)clamped; if (value >= thresh) ++hist[value >> 4]; } } else ERRverror("Histogram", ERR_ERROR, "Histogram only supports char, byte, or short data\n"); } else ERRverror("Histogram", ERR_ERROR, "Unable to get volume data array\n"); if (data) ARRfree(data); if (hist) ARRfree(hist); return 1; }
24.102564
76
0.50266
avs
d3d4fe3b35745bf51381fcb22567416c9eeccc09
1,544
cpp
C++
src/pccts/notes/prependnl/nlDLG.cpp
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
2
2019-01-26T14:35:33.000Z
2020-03-31T10:39:39.000Z
src/pccts/notes/prependnl/nlDLG.cpp
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
1
2018-12-12T17:04:17.000Z
2018-12-12T17:04:17.000Z
src/pccts/notes/prependnl/nlDLG.cpp
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
1
2020-10-26T08:56:12.000Z
2020-10-26T08:56:12.000Z
// // nlDLG.cpp // 9-May-1995 // pccts 1.32b5 // /* This file should be accompanied by DISCLAIMER.TXT stating disclaimers */ #include "nlDLG.h" #include "prependnl.h" MyDLG::MyDLG(DLGInputStream *userStream,unsigned bufsize) : DLGLexer(userStream,bufsize), prependNLinputStream(userStream) { _line--; // compensate for extra newline // added by prependNL input=&prependNLinputStream; // replace users input stream // with the one which prepends // a newline and then call the // user specified version } MyDLG::~MyDLG() {} PrependNLinputStream::PrependNLinputStream(DLGInputStream * in) : usersInputStream(in), firstTime(1) {} PrependNLinputStream::~PrependNLinputStream() { /// delete usersInputStream; } // // this always adds a newline, even if the first call returns an EOF // after some thought I decided that eliminating the first newline // might prevent some lexical routines from working correctly // // it would be nice to replace the PrependNLinputStream with the user's // input stream pointer after the first character is fetched so as // to reduce overhead. However a DLGinputStream doesn't know which // DLGLexer called it. The MyDLG::getToken could do it, and this // would replace a per/character subroutine call with a per/token // subroutine call. int PrependNLinputStream::nextChar() { int result; if (firstTime) { firstTime=0; result='\n'; } else { result=usersInputStream->nextChar(); }; return result; }
27.087719
76
0.701425
clasqm
d3db75b63344d817e83451ef1cac9f8d28c654d5
3,690
cc
C++
test/hash_table_test.cc
yang-le/cpp-algorithms
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
[ "MIT" ]
null
null
null
test/hash_table_test.cc
yang-le/cpp-algorithms
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
[ "MIT" ]
null
null
null
test/hash_table_test.cc
yang-le/cpp-algorithms
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2018 Yang Le // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "hash_table.hpp" #include "gtest/gtest.h" TEST(HashTableTest, create) { HashTable<int> defaultHashTable; EXPECT_EQ(defaultHashTable.buckets_.size(), 32); HashTable<int, 64> biggerHashTable; EXPECT_EQ(biggerHashTable.buckets_.size(), 64); } TEST(HashTableTest, hash) { HashTable<int> hashTable; EXPECT_EQ(hashTable.hash("a"), 1); EXPECT_EQ(hashTable.hash("b"), 2); EXPECT_EQ(hashTable.hash("abc"), 6); } TEST(HashTableTest, collisions) { HashTable<std::string, 3> hashTable; EXPECT_EQ(hashTable.hash("a"), 1); EXPECT_EQ(hashTable.hash("b"), 2); EXPECT_EQ(hashTable.hash("c"), 0); EXPECT_EQ(hashTable.hash("d"), 1); hashTable.set("a", "sky-old"); hashTable.set("a", "sky"); hashTable.set("b", "sea"); hashTable.set("c", "earth"); hashTable.set("d", "ocean"); EXPECT_FALSE(hashTable.has("x")); EXPECT_TRUE(hashTable.has("b")); EXPECT_TRUE(hashTable.has("c")); auto stringifier = [](const std::pair<std::string, std::string>& pair) { return pair.first + ":" + pair.second; }; EXPECT_EQ(hashTable.buckets_[0].toString(stringifier), "c:earth"); EXPECT_EQ(hashTable.buckets_[1].toString(stringifier), "a:sky,d:ocean"); EXPECT_EQ(hashTable.buckets_[2].toString(stringifier), "b:sea"); EXPECT_EQ(*hashTable.get("a"), "sky"); EXPECT_EQ(*hashTable.get("d"), "ocean"); EXPECT_EQ(hashTable.get("x"), nullptr); hashTable.remove("a"); EXPECT_EQ(hashTable.remove("not-existing"), nullptr); EXPECT_EQ(hashTable.get("a"), nullptr); EXPECT_EQ(*hashTable.get("d"), "ocean"); hashTable.set("d", "ocean-new"); EXPECT_EQ(*hashTable.get("d"), "ocean-new"); } TEST(HashTableTest, add_objects) { HashTable<std::pair<std::string, std::string>> hashTable; hashTable.set("objectKey", std::make_pair("a", "b")); auto object = hashTable.get("objectKey"); EXPECT_NE(object, nullptr); EXPECT_EQ(object->first, "a"); EXPECT_EQ(object->second, "b"); } TEST(HashTableTest, keys) { HashTable<std::string, 3> hashTable; hashTable.set("a", "sky-old"); hashTable.set("a", "sky"); hashTable.set("b", "sea"); hashTable.set("c", "earth"); hashTable.set("d", "ocean"); EXPECT_EQ(hashTable.getKeys(), std::unordered_set<std::string>({"a", "b", "c", "d"})); EXPECT_TRUE(hashTable.has("a")); EXPECT_FALSE(hashTable.has("x")); hashTable.remove("a"); EXPECT_FALSE(hashTable.has("a")); EXPECT_TRUE(hashTable.has("b")); EXPECT_FALSE(hashTable.has("x")); }
32.368421
81
0.673984
yang-le
d3dbba38fb97db4bd7712fe5e03af497319d3387
927
cpp
C++
modules/imgproc/perf/perf_morph.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
144
2015-01-15T03:38:44.000Z
2022-02-17T09:07:52.000Z
modules/imgproc/perf/perf_morph.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
28
2016-10-16T19:42:37.000Z
2018-09-14T21:29:48.000Z
modules/imgproc/perf/perf_morph.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
58
2015-01-14T23:43:49.000Z
2021-11-15T05:19:08.000Z
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; #define TYPICAL_MAT_TYPES_MORPH CV_8UC1, CV_8UC4 #define TYPICAL_MATS_MORPH testing::Combine(SZ_ALL_GA, testing::Values(TYPICAL_MAT_TYPES_MORPH)) PERF_TEST_P(Size_MatType, erode, TYPICAL_MATS_MORPH) { Size sz = get<0>(GetParam()); int type = get<1>(GetParam()); Mat src(sz, type); Mat dst(sz, type); declare.in(src, WARMUP_RNG).out(dst); int runs = (sz.width <= 320) ? 15 : 1; TEST_CYCLE_MULTIRUN(runs) erode(src, dst, noArray()); SANITY_CHECK(dst); } PERF_TEST_P(Size_MatType, dilate, TYPICAL_MATS_MORPH) { Size sz = get<0>(GetParam()); int type = get<1>(GetParam()); Mat src(sz, type); Mat dst(sz, type); declare.in(src, WARMUP_RNG).out(dst); TEST_CYCLE() dilate(src, dst, noArray()); SANITY_CHECK(dst); }
22.071429
102
0.674218
snosov1
d3de4ff25af4de6bba411ea2b3b41813e7ef6d77
2,364
hpp
C++
src/perfnp/cmd_line.hpp
locksley-cz/perfnp
b55dc3401285042e1409ba930543627725a471c0
[ "MIT" ]
null
null
null
src/perfnp/cmd_line.hpp
locksley-cz/perfnp
b55dc3401285042e1409ba930543627725a471c0
[ "MIT" ]
10
2019-03-13T09:14:41.000Z
2020-02-19T18:01:14.000Z
src/perfnp/cmd_line.hpp
locksley-cz/perfnp
b55dc3401285042e1409ba930543627725a471c0
[ "MIT" ]
1
2019-03-08T09:32:31.000Z
2019-03-08T09:32:31.000Z
// Copyright (c) 2019 Locksley.CZ s.r.o. // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #ifndef PERFNP_CMD_LINE_H_ #define PERFNP_CMD_LINE_H_ #include <perfnp/tools.hpp> #include <string> #include <vector> namespace perfnp { /*! * Command to be executed with arguments */ class CmdWithArgs { //! Index of this run (see combin.hpp) unsigned m_run_index; //! Command to be executed std::string m_command; //! List of arguments for the command std::vector<std::string> m_arguments; public: CmdWithArgs( unsigned job_index, std::string command, std::vector<std::string> arguments) : m_run_index(job_index) , m_command(std::move(command)) , m_arguments(std::move(arguments)) {} //! Index of this run (see combin.hpp) unsigned job_index() const { return m_run_index; } //! Command to be executed const std::string& command() const { return m_command; } //! List of arguments for the command const std::vector<std::string>& arguments() const { return m_arguments; } /*! * Returns a native-shell-friendly string in UTF-8. * * Method is platform-dependent. On Windows, we create * a Command Prompt (cmd.exe) friendly string, on other * platforms, we assume Linux and prepare a Bash-friendly * string. */ std::string escape_for_native_shell() const; //! Escape command and arguments for Linux Bash. std::string escape_for_bash() const; //! Escape command and arguments for Windows Command Prompt std::wstring escape_for_cmd_exe() const; bool operator==(const CmdWithArgs& rhs) const { return m_run_index == rhs.m_run_index && m_command == rhs.m_command && m_arguments == rhs.m_arguments; } bool operator!=(const CmdWithArgs& rhs) const { return ! ((*this) == rhs); } }; // CmdWithArgs //! Serialize the command with arguments to a stream, escape for Bash std::ostream& operator<<(std::ostream& os, const perfnp::CmdWithArgs& cwa); //! Serialize the command with arguments to an UTF-16 stream, escape for Command Prompt (cmd.exe) std::wostream& operator<<(std::wostream& os, const perfnp::CmdWithArgs& cwa); } // perfnp #endif // PERFNP_CMD_LINE_H_
24.884211
97
0.654399
locksley-cz
d3e4f7cbd40981044a27bdf1bec005ded1d81537
632
hpp
C++
kernel/include/x86_64/pic.hpp
larrabyte/thepuck
dc9971bc0682354e74a1869b3cc6a5c80b85e821
[ "MIT" ]
5
2020-02-21T09:35:24.000Z
2021-03-28T08:26:20.000Z
kernel/include/x86_64/pic.hpp
larrabyte/thepuck
dc9971bc0682354e74a1869b3cc6a5c80b85e821
[ "MIT" ]
null
null
null
kernel/include/x86_64/pic.hpp
larrabyte/thepuck
dc9971bc0682354e74a1869b3cc6a5c80b85e821
[ "MIT" ]
1
2021-06-25T17:26:03.000Z
2021-06-25T17:26:03.000Z
#ifndef FREELSD_KERNEL_PIC_HEADER #define FREELSD_KERNEL_PIC_HEADER #include <stdint.h> #define MASTER_PIC_COMMAND 0x20 #define MASTER_PIC_DATA 0x21 #define SLAVE_PIC_COMMAND 0xA0 #define SLAVE_PIC_DATA 0xA1 #define PIC_READ_IRR 0x0A #define PIC_READ_ISR 0x0B namespace pic { // Check if the PIC is enabled or not. extern bool enabled; // Enable the Programmable Interrupt Controller. void enable(void); // Disable the Programmable Interrupt Controller. void disable(void); // Send an EOI command to the master and slave PICs. void sendeoi(uint64_t vector); } #endif
22.571429
56
0.726266
larrabyte
d3e5e90fd17a37c61f07cc59255962fa094ec09e
3,124
cc
C++
paddle/phi/kernels/cpu/log_softmax_grad_kernel.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/phi/kernels/cpu/log_softmax_grad_kernel.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
null
null
null
paddle/phi/kernels/cpu/log_softmax_grad_kernel.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
1
2021-09-24T11:23:36.000Z
2021-09-24T11:23:36.000Z
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/phi/kernels/log_softmax_grad_kernel.h" #include "paddle/phi/backends/cpu/cpu_context.h" #include "paddle/phi/core/kernel_registry.h" #include "paddle/phi/kernels/funcs/axis_utils.h" #include "paddle/phi/kernels/funcs/eigen/common.h" #include "paddle/phi/kernels/funcs/eigen/eigen_function.h" namespace phi { template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrixTemplate = EigenMatrix<T, MajorType, IndexType>; template <typename Context, typename T> struct LogSoftmaxGradFunctor { void operator()(const Context& context, const DenseTensor* Y, const DenseTensor* dY, DenseTensor* dX, const int axis) { constexpr int kBatchDim = 0; constexpr int kClassDim = 1; const int n = funcs::SizeToAxis(axis, Y->dims()); const int d = funcs::SizeFromAxis(axis, Y->dims()); phi::DDim dim_2d{n, d}; auto y = EigenMatrixTemplate<T>::From(*Y, dim_2d); auto dy = EigenMatrixTemplate<T>::From(*dY, dim_2d); auto dx = EigenMatrixTemplate<T>::From(*dX, dim_2d); const int axis_dim = Y->dims()[axis]; const int batch_size = y.dimension(kBatchDim); const int num_classes = y.dimension(kClassDim); const int num_remain = num_classes / axis_dim; Eigen::DSizes<int, 1> along_class(kClassDim); Eigen::DSizes<int, 3> batch_axis_remain(batch_size, axis_dim, num_remain); Eigen::DSizes<int, 2> one_axis(1, axis_dim); dx.device(*context.eigen_device()) = dy - (y.exp()) * (dy.reshape(batch_axis_remain) .sum(along_class) .broadcast(one_axis)); } }; template <typename T, typename Context> void LogSoftmaxGradKernel(const Context& dev_ctx, const DenseTensor& out, const DenseTensor& out_grad, int axis, DenseTensor* x_grad) { const int rank = out.dims().size(); const int canonical_axis = funcs::CanonicalAxis(axis, rank); dev_ctx.template Alloc<T>(x_grad); if (out.numel() != 0) { LogSoftmaxGradFunctor<Context, T>()( dev_ctx, &out, &out_grad, x_grad, canonical_axis); } } } // namespace phi PD_REGISTER_KERNEL(log_softmax_grad, CPU, ALL_LAYOUT, phi::LogSoftmaxGradKernel, float, double) {}
35.5
78
0.643086
L-Net-1992
d3e79a4e75f229efde8a3aae554600313686d193
1,771
cpp
C++
data-structure/Agenda.cpp
ejpcr/libs-c
e544e4338ea9f2fe8c57de83045944f38ae06a07
[ "MIT" ]
null
null
null
data-structure/Agenda.cpp
ejpcr/libs-c
e544e4338ea9f2fe8c57de83045944f38ae06a07
[ "MIT" ]
null
null
null
data-structure/Agenda.cpp
ejpcr/libs-c
e544e4338ea9f2fe8c57de83045944f38ae06a07
[ "MIT" ]
null
null
null
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- saved from url=(0224)http://65.54.187.250/cgi-bin/getmsg?curmbox=F000000001&a=2ec26e1f050efee654cc3bcc71597a74&msg=MSG1090110885.23&start=406335&len=45661&mimepart=3&disk=65.54.187.39_d298&login=nuverlomm&domain=hotmail%2ecom&_lang=ES&country=MX --> <HTML><HEAD> <META http-equiv=Content-Type content="text/html; charset=windows-1252"> <META content="MSHTML 6.00.2800.1106" name=GENERATOR></HEAD> <BODY><PRE>//LISTAS DOBLE LIGADURA #include AGENDA.h; #include CTYPE.H; void main() { clrscr(); LD agenda; char opc='N'; int op; char nombre[N]; char direccion[D]; char telefono[T]; do { cout&lt;&lt;"\n\t\tAGENDA VIRTUAL"; cout&lt;&lt;"\n\n\n\n\n\t1.INSERTAR"; cout&lt;&lt;"\n\t2.ELIMINAR"; cout&lt;&lt;"\n\t3.VISUALIZAR"; cout&lt;&lt;"\n\nselecciona una opcion: "; cin&gt;&gt;op; switch(op) { case 1: { clrscr(); cout&lt;&lt;"\n\t\tAGENDA VIRTUAL"; cout&lt;&lt;"\n\t1.INSERTAR AMIGUIS"; cout&lt;&lt;"\n\tNOMBRE: "; gets(nombre); cout&lt;&lt;"\n\tDIRECCION: "; gets(direccion); cout&lt;&lt;"\n\tTELEFONO: "; gets(telefono); agenda.insfinal(nombre,direccion,telefono); break; } case 2: { clrscr(); cout&lt;&lt;"\n\t\tAGENDA VIRTUAL"; cout&lt;&lt;"\n\t1.BORRAR AMIGUIS"; cout&lt;&lt;"\n\tNOMBRE: "; gets(nombre); agenda.del(nombre); break; } case 3: { clrscr(); cout&lt;&lt;"\n\t\tAGENDA VIRTUAL"; cout&lt;&lt;"\n\t1.VER TODOS MIS AMIGUIS"; agenda.visualiza(); cout&lt;&lt;"\npresione enter"; getchar(); break; } default: break; } cout&lt;&lt;"\n\tDesea salir (S/N) :"; cin&gt;&gt;opc; opc=toupper(opc); }while(opc=='N'); getchar(); } </PRE></BODY></HTML>
29.032787
254
0.627329
ejpcr
d3e83e27e776d08adf5f4e9c2c82d71898aaa415
1,949
cpp
C++
Queue/queue.cpp
hongwei7/CPP-data_structure
07b1d8571a1860bfd483bd0e4104806e3481b167
[ "MIT" ]
1
2021-12-16T13:04:31.000Z
2021-12-16T13:04:31.000Z
Queue/queue.cpp
hongwei7/CPP-data_structure
07b1d8571a1860bfd483bd0e4104806e3481b167
[ "MIT" ]
null
null
null
Queue/queue.cpp
hongwei7/CPP-data_structure
07b1d8571a1860bfd483bd0e4104806e3481b167
[ "MIT" ]
null
null
null
#include <iostream> #define maxsize 20 #define max_size 50 typedef int elem; using namespace std; /*后来定义的一些函数需要stack*/ #include "Stack.h" #include "queue.h" void Init_queue(queue* &q) { q = new queue; q->front = 0; q->rear = 0; } void Destroy_queue(queue *&q) { free(q); } bool queue_empty(queue *q) { return q->front == q->rear; } bool enQueue(queue *&q, elem e) { if (q->front == ((q->rear + 1) % maxsize))return false; q->rear = (q->rear + 1) % maxsize; q->data[q->rear] = e; return true; } bool deQueue(queue *&q, elem &e) { if (q->front == q->rear)return false; q->front = (q->front + 1) % maxsize; e = q->data[q->front]; q->data[q->front] = 0; return true; } void _display(queue *q) { for (int i = 0; i < maxsize; i++) { cout << q->data[i] << " "; } cout << endl; } void display(queue *q) { if (q->front == q->rear)return; for (int i = q->front + 1; i != (q->rear + 1) % maxsize; i = (i + 1) % maxsize) { cout << q->data[i] << ' '; } cout << endl; } void reverse_queue(queue *&q) { stack *p = new stack; Init_stack(p); elem t; while (deQueue(q, t))push(p, t); Init_queue(q); while (!Stack_empty(p)) { pop(p, t); enQueue(q, t); } } int main() { queue *q = new queue; elem e; Init_queue(q); for (int i = 1; i <= 20; i++) { if (enQueue(q, i))cout << "in: " << i << endl; } for (int i = 1; i <= 12; i++) { if (deQueue(q, i))cout << "out: " << i << endl; } for (int i = 1; i <= 6; i++) { if (enQueue(q, i))cout << "in: " << i << endl; } display(q); cout << "point:" << q->front << ' ' << q->rear << endl; reverse_queue(q); display(q); cout << "point:" << q->front << ' ' << q->rear << endl; reverse_queue(q); display(q); cout << "point:" << q->front << ' ' << q->rear << endl; return 0; }
20.302083
83
0.487429
hongwei7
d3e8f67b6a612ddf7e7589785f61cc3a51216bef
1,881
cpp
C++
tst/OpcUaStackServer/ServiceSet/MonitoredItem_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
tst/OpcUaStackServer/ServiceSet/MonitoredItem_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
tst/OpcUaStackServer/ServiceSet/MonitoredItem_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
#include "unittest.h" #include "OpcUaStackServer/ServiceSet/MonitorItem.h" #include "OpcUaStackServer/AddressSpaceModel/VariableNodeClass.h" #include "OpcUaStackServer/AddressSpaceModel/ObjectNodeClass.h" using namespace OpcUaStackServer; BOOST_AUTO_TEST_SUITE(MonitoredItem_) BOOST_AUTO_TEST_CASE(MonitoredItem_) { std::cout << "MonitoredItem_t" << std::endl; } BOOST_AUTO_TEST_CASE(MonitoredItem_minimalSamplingInterval) { MonitoredItemCreateRequest::SPtr monitoredItemCreateRequest = constructSPtr<MonitoredItemCreateRequest>(); monitoredItemCreateRequest->requestedParameters().samplingInterval(100); BaseNodeClass::SPtr valueNode = constructSPtr<VariableNodeClass>(); OpcUaDouble minValue = 200; valueNode->setMinimumSamplingInterval(minValue); MonitorItem item; item.receive(valueNode, monitoredItemCreateRequest); BOOST_REQUIRE_EQUAL(200, item.samplingInterval()); } BOOST_AUTO_TEST_CASE(MonitoredItem_minimalSamplingIntervalNull) { MonitoredItemCreateRequest::SPtr monitoredItemCreateRequest = constructSPtr<MonitoredItemCreateRequest>(); monitoredItemCreateRequest->requestedParameters().samplingInterval(100); BaseNodeClass::SPtr valueNode = constructSPtr<VariableNodeClass>(); MonitorItem item; item.receive(valueNode, monitoredItemCreateRequest); BOOST_REQUIRE_EQUAL(100, item.samplingInterval()); } BOOST_AUTO_TEST_CASE(MonitoredItem_minimalSamplingIntervalNotExist) { MonitoredItemCreateRequest::SPtr monitoredItemCreateRequest = constructSPtr<MonitoredItemCreateRequest>(); monitoredItemCreateRequest->requestedParameters().samplingInterval(100); BaseNodeClass::SPtr valueNode = constructSPtr<ObjectNodeClass>(); MonitorItem item; item.receive(valueNode, monitoredItemCreateRequest); BOOST_REQUIRE_EQUAL(100, item.samplingInterval()); } BOOST_AUTO_TEST_SUITE_END()
30.836066
110
0.812334
gianricardo
d3ed1bb0b43c1610d6b69c51f2236a798930bb9a
571
cpp
C++
4rth_Sem_c++_backup/PRACTICE/XAV/Jimut/part2/pointer.cpp
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
4rth_Sem_c++_backup/PRACTICE/XAV/Jimut/part2/pointer.cpp
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
4rth_Sem_c++_backup/PRACTICE/XAV/Jimut/part2/pointer.cpp
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
#include<iostream> using namespace std; class Array { int *a,s; public: Array(int); input(int s); ~Array(); }; inline Array::Array(int s) { cout<<"\n Constructed!!"; Array::s=s; a = new int[s]; } inline Array::~Array() { delete a; cout<<"\n Destroyed! "; } void input(int s) { int i; cout<<"\n Enter the elements one by one :"; for( i=0;i<s;i++) cin>>a[i]; for( i=0;i<s;i++) cout<<a[i]<<" "; } int main() { int n; cout<<"\n Enter the no. of elements in the array :"<<endl; cin>>n; Array obj(n); obj.input(n); return 0; }
10.773585
59
0.551664
SayanGhoshBDA
d3edad04732965f9dd3176e26bf8264facbe8743
420
cpp
C++
learncppdotcom/6.3_3/main.cpp
coal0/Challenges
528c2a32680b97ca36fed55caea5d545c18ba97a
[ "MIT" ]
null
null
null
learncppdotcom/6.3_3/main.cpp
coal0/Challenges
528c2a32680b97ca36fed55caea5d545c18ba97a
[ "MIT" ]
null
null
null
learncppdotcom/6.3_3/main.cpp
coal0/Challenges
528c2a32680b97ca36fed55caea5d545c18ba97a
[ "MIT" ]
null
null
null
#include <iostream> int main() { int scores[] = {84, 92, 76, 81, 56}; constexpr int numStudents = sizeof(scores) / sizeof(scores[0]); int maxScoreIndex = 0; for (int student = 1; student < numStudents; ++student) { if (scores[student] > scores[maxScoreIndex]) { maxScoreIndex = student; } } std::cout << "The best score was at index " << maxScoreIndex << ".\n"; }
24.705882
74
0.57619
coal0
d3ee176b0f44a3f9bcae8e1bed7c0691ebc2b0d6
11,131
cc
C++
Validation/HGCalValidation/test/HGCalWaferHitCheck.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
4
2020-06-27T23:27:21.000Z
2020-11-19T09:17:01.000Z
Validation/HGCalValidation/test/HGCalWaferHitCheck.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
524
2018-01-29T15:50:45.000Z
2021-08-04T14:03:21.000Z
Validation/HGCalValidation/test/HGCalWaferHitCheck.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
7
2018-02-19T11:17:13.000Z
2020-10-12T21:57:00.000Z
// system include files #include <cmath> #include <iostream> #include <fstream> #include <map> #include <mutex> #include <string> #include <vector> #include "DataFormats/ForwardDetId/interface/ForwardSubdetector.h" #include "DataFormats/ForwardDetId/interface/HFNoseDetId.h" #include "DataFormats/ForwardDetId/interface/HGCalDetId.h" #include "DataFormats/ForwardDetId/interface/HGCSiliconDetId.h" #include "DataFormats/ForwardDetId/interface/HGCScintillatorDetId.h" #include "DataFormats/HGCDigi/interface/HGCDigiCollections.h" #include "DataFormats/HGCRecHit/interface/HGCRecHitCollections.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Utilities/interface/ESGetToken.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/HGCalCommonData/interface/HGCalDDDConstants.h" #include "Geometry/HGCalCommonData/interface/HGCalWaferIndex.h" #include "SimDataFormats/CaloHit/interface/PCaloHitContainer.h" #include "SimDataFormats/CaloHit/interface/PCaloHit.h" namespace HGCalValidSimhitCheck { struct Counters { Counters() { badTypes_.clear(); occupancy_.clear(); goodChannels_.clear(); } CMS_THREAD_GUARD(mtx_) mutable std::map<int, int> badTypes_, occupancy_; CMS_THREAD_GUARD(mtx_) mutable std::vector<int> goodChannels_; mutable std::mutex mtx_; }; } // namespace HGCalValidSimhitCheck class HGCalWaferHitCheck : public edm::stream::EDAnalyzer<edm::GlobalCache<HGCalValidSimhitCheck::Counters> > { public: explicit HGCalWaferHitCheck(const edm::ParameterSet&, const HGCalValidSimhitCheck::Counters* count); static std::unique_ptr<HGCalValidSimhitCheck::Counters> initializeGlobalCache(edm::ParameterSet const& iConfig) { return std::make_unique<HGCalValidSimhitCheck::Counters>(); } void analyze(edm::Event const&, edm::EventSetup const&) override; void endStream() override; static void globalEndJob(const HGCalValidSimhitCheck::Counters* counters); static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); protected: void beginRun(edm::Run const&, edm::EventSetup const&) override; void endRun(edm::Run const&, edm::EventSetup const&) override {} private: template <class T> void analyzeHits(const std::string&, const T&); // ----------member data --------------------------- enum inputType { Sim = 1, Digi = 2, Reco = 3 }; const std::string nameDetector_, caloHitSource_; const edm::InputTag source_; const int inpType_; const int verbosity_; const bool ifNose_; edm::EDGetToken digiHitSource_; const HGCalDDDConstants* hgcons_; edm::ESGetToken<HGCalDDDConstants, IdealGeometryRecord> geomToken_; edm::EDGetTokenT<edm::PCaloHitContainer> tok_hit_; std::map<int, int> badTypes_, occupancy_; std::vector<int> goodChannels_; static const int waferMax = 12; static const int layerMax = 28; }; HGCalWaferHitCheck::HGCalWaferHitCheck(const edm::ParameterSet& iConfig, const HGCalValidSimhitCheck::Counters*) : nameDetector_(iConfig.getParameter<std::string>("detectorName")), caloHitSource_(iConfig.getParameter<std::string>("caloHitSource")), source_(iConfig.getParameter<edm::InputTag>("source")), inpType_(iConfig.getParameter<int>("inputType")), verbosity_(iConfig.getUntrackedParameter<int>("verbosity", 0)), ifNose_(iConfig.getUntrackedParameter<bool>("ifNose", false)), geomToken_(esConsumes<HGCalDDDConstants, IdealGeometryRecord, edm::Transition::BeginRun>( edm::ESInputTag{"", nameDetector_})), tok_hit_(consumes<edm::PCaloHitContainer>(edm::InputTag("g4SimHits", caloHitSource_))) { if (inpType_ == Digi) { digiHitSource_ = consumes<HGCalDigiCollection>(source_); } else if (inpType_ >= Reco) { digiHitSource_ = consumes<HGCRecHitCollection>(source_); } edm::LogVerbatim("HGCalValidation") << "Validation for input type " << inpType_ << " for " << nameDetector_; } void HGCalWaferHitCheck::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<std::string>("detectorName", "HGCalEESensitive"); desc.add<std::string>("caloHitSource", "HGCHitsEE"); desc.add<edm::InputTag>("source", edm::InputTag("simHGCalUnsuppressedDigis", "EE")); desc.add<int>("inputType", 1); desc.addUntracked<int>("verbosity", 0); desc.addUntracked<bool>("ifNose", false); descriptions.add("hgcalWaferHitCheckEE", desc); } void HGCalWaferHitCheck::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { //Get collection depending on inputType if (inpType_ <= Sim) { edm::Handle<edm::PCaloHitContainer> theCaloHitContainer; iEvent.getByToken(tok_hit_, theCaloHitContainer); if (theCaloHitContainer.isValid()) { if (verbosity_ > 0) edm::LogVerbatim("HGCalValidation") << nameDetector_ << " with " << theCaloHitContainer->size() << " SimHits"; analyzeHits(nameDetector_, *(theCaloHitContainer.product())); } else if (verbosity_ > 0) { edm::LogVerbatim("HGCalValidation") << "PCaloHitContainer does not exist for " << nameDetector_; } } else if (inpType_ == Digi) { edm::Handle<HGCalDigiCollection> theDigiContainer; iEvent.getByToken(digiHitSource_, theDigiContainer); if (theDigiContainer.isValid()) { if (verbosity_ > 0) edm::LogVerbatim("HGCalValidation") << nameDetector_ << " with " << theDigiContainer->size() << " Digis"; analyzeHits(nameDetector_, *(theDigiContainer.product())); } else if (verbosity_ > 0) { edm::LogVerbatim("HGCalValidation") << "DigiContainer does not exist for " << nameDetector_; } } else { edm::Handle<HGCRecHitCollection> theRecHitContainer; iEvent.getByToken(digiHitSource_, theRecHitContainer); if (theRecHitContainer.isValid()) { if (verbosity_ > 0) edm::LogVerbatim("HGCalValidation") << nameDetector_ << " with " << theRecHitContainer->size() << " hits"; analyzeHits(nameDetector_, *(theRecHitContainer.product())); } else if (verbosity_ > 0) { edm::LogVerbatim("HGCalValidation") << "RecHitContainer does not exist for " << nameDetector_; } } } template <class T> void HGCalWaferHitCheck::analyzeHits(std::string const& name, T const& hits) { for (auto const& hit : hits) { uint32_t id = hit.id(); int zside, type, layer, waferU, waferV; if (ifNose_) { HFNoseDetId detId = HFNoseDetId(id); waferU = detId.waferU(); waferV = detId.waferV(); type = detId.type(); layer = detId.layer(); zside = detId.zside(); } else { HGCSiliconDetId detId = HGCSiliconDetId(id); waferU = detId.waferU(); waferV = detId.waferV(); type = detId.type(); layer = detId.layer(); zside = detId.zside(); } int index = HGCalWaferIndex::waferIndex(layer, waferU, waferV, false); int typef = hgcons_->waferType(layer, waferU, waferV, true); if (zside < 0) index *= -1; auto itr = occupancy_.find(index); if (itr == occupancy_.end()) occupancy_[index] = 1; else ++occupancy_[index]; if (type != typef) { auto ktr = badTypes_.find(index); if (ktr == badTypes_.end()) badTypes_[index] = 1; else ++badTypes_[index]; if (verbosity_ == 1) edm::LogVerbatim("HGCalValidation") << "Detector " << name << " zside = " << zside << " layer = " << layer << " type = " << type << ":" << typef << " wafer = " << waferU << ":" << waferV << " index " << index; } if (verbosity_ > 1) edm::LogVerbatim("HGCalValidation") << "Detector " << name << " zside = " << zside << " layer = " << layer << " type = " << type << ":" << typef << " wafer = " << waferU << ":" << waferV; } } // ------------ method called when starting to processes a run ------------ void HGCalWaferHitCheck::beginRun(const edm::Run&, const edm::EventSetup& iSetup) { edm::ESHandle<HGCalDDDConstants> pHGDC = iSetup.getHandle(geomToken_); hgcons_ = &(*pHGDC); if (verbosity_ > 0) edm::LogVerbatim("HGCalValidation") << nameDetector_ << " defined with " << hgcons_->layers(false) << " Layers with " << (hgcons_->firstLayer() - 1) << " in front"; goodChannels_.clear(); for (int iz = 0; iz < 2; ++iz) { int zside = iz * 2 - 1; for (int layer = 1; layer <= layerMax; ++layer) { for (int waferU = -waferMax; waferU <= waferMax; ++waferU) { for (int waferV = -waferMax; waferV <= waferMax; ++waferV) { int index = zside * HGCalWaferIndex::waferIndex(layer, waferU, waferV, false); if (hgcons_->isValidHex8(layer, waferU, waferV, true)) goodChannels_.emplace_back(index); } } } } } void HGCalWaferHitCheck::endStream() { std::scoped_lock lock(globalCache()->mtx_); for (auto [id, count] : occupancy_) { if (globalCache()->occupancy_.find(id) == globalCache()->occupancy_.end()) globalCache()->occupancy_[id] = count; else globalCache()->occupancy_[id] += count; } for (auto [id, count] : badTypes_) { if (globalCache()->badTypes_.find(id) == globalCache()->badTypes_.end()) globalCache()->badTypes_[id] = count; else globalCache()->badTypes_[id] += count; } globalCache()->goodChannels_ = goodChannels_; globalCache()->mtx_.unlock(); } void HGCalWaferHitCheck::globalEndJob(const HGCalValidSimhitCheck::Counters* count) { int allbad(0), nocc(0); for (auto const& index : count->goodChannels_) { int zside = (index < 0) ? -1 : 1; int layer = HGCalWaferIndex::waferLayer(std::abs(index)); int waferU = HGCalWaferIndex::waferU(std::abs(index)); int waferV = HGCalWaferIndex::waferV(std::abs(index)); int occ = (count->occupancy_.find(index) == count->occupancy_.end()) ? 0 : count->occupancy_[index]; int bad = (count->badTypes_.find(index) == count->badTypes_.end()) ? 0 : count->badTypes_[index]; if (occ == 0) ++nocc; if (bad > 0) ++allbad; if (occ == 0 || bad > 0) { edm::LogVerbatim("HGCalValidation") << "ZS:Layer:u:v:index " << zside << ":" << layer << ":" << waferU << ":" << waferV << ":" << index << " Occ " << occ << " bad " << bad; } } edm::LogVerbatim("HGCalValidation") << "\n\n" << allbad << " channels with bad types among " << count->goodChannels_.size() << " channels and " << nocc << " channels with zero occupancy\n\n"; } #include "FWCore/Framework/interface/MakerMacros.h" //define this as a plug-in DEFINE_FWK_MODULE(HGCalWaferHitCheck);
41.845865
120
0.668224
ckamtsikis
d3eedfe1a27ba93a1eb98b9a036139041f15b0fb
3,376
cxx
C++
main/toolkit/workben/layout/recover.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/toolkit/workben/layout/recover.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/toolkit/workben/layout/recover.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.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. * *************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #if TEST_LAYOUT #include <cstdio> #endif /* TEST_LAYOUT */ #include <com/sun/star/awt/XDialog2.hpp> #include <tools/shl.hxx> #include <svtools/itemset.hxx> #include <svtools/itempool.hxx> #include <sfx2/objsh.hxx> #include <vcl/msgbox.hxx> #include <toolkit/awt/vclxwindow.hxx> #include <com/sun/star/awt/PosSize.hpp> //redrawAlready using namespace com::sun::star; #define _SVX_RECOVER_CXX #include "recover.hxx" #include <layout/layout-pre.hxx> #if ENABLE_LAYOUT #undef SVX_RES #define SVX_RES(x) #x #undef SfxModalDialog #define SfxModalDialog( parent, id ) Dialog( parent, "recover.xml", id ) #endif /* ENABLE_LAYOUT */ #if TEST_LAYOUT SvxRecoverDialog::SvxRecoverDialog( Window* pParent ) #else /* !TEST_LAYOUT */ SvxRecoverDialog::SvxRecoverDialog( Window* pParent, const SfxItemSet& rCoreSet ) #endif /* !TEST_LAYOUT */ : SfxModalDialog( pParent, SVX_RES( RID_SVXDLG_RECOVER ) ) , aHeaderImage( this, SVX_RES( FI_HEADER ) ) , aHeaderText( this, SVX_RES( FT_HEADER ) ) , aHeaderLine( this, SVX_RES( FL_HEADER ) ) , aRecoverText( this, SVX_RES( FT_RECOVER ) ) , aTextAdvanced( this, SVX_RES( FT_ADVANCED ) ) , aCheckBoxDoc( this, SVX_RES( CB_DOC ) ) , aImageDoc( this, SVX_RES( FI_DOC ) ) , aTextDoc( this, SVX_RES( FT_DOC ) ) , aCheckBoxSheet( this, SVX_RES( CB_SHEET ) ) , aImageSheet( this, SVX_RES( FI_SHEET ) ) , aTextSheet( this, SVX_RES( FT_SHEET ) ) , aCheckBoxDraw( this, SVX_RES( CB_DRAW ) ) , aImageDraw( this, SVX_RES( FI_DRAW ) ) , aTextDraw( this, SVX_RES( FT_DRAW ) ) , aCheckBoxPresent( this, SVX_RES( CB_PRESENT ) ) , aImagePresent( this, SVX_RES( FI_PRESENT ) ) , aTextPresent( this, SVX_RES( FT_PRESENT ) ) , aButtonAdvanced( this, SVX_RES( PB_ADVANCED ) ) , aProgressText( this, SVX_RES( FT_PROGRESS ) ) , aProgressBar( this, SVX_RES( PB_RECOVER ) ) , aCheckBoxLogFile( this, SVX_RES( CH_LOGFILE ) ) , aOKBtn( this, SVX_RES( BTN_OK ) ) , aCancelBtn( this, SVX_RES( BTN_CANCEL ) ) , aHelpBtn( this, SVX_RES( BTN_HELP ) ) { aButtonAdvanced.AddAdvanced( &aTextAdvanced ); aButtonAdvanced.AddAdvanced( &aCheckBoxDoc ); aButtonAdvanced.AddAdvanced( &aCheckBoxSheet ); aButtonAdvanced.AddAdvanced( &aCheckBoxDraw ); aButtonAdvanced.AddAdvanced( &aCheckBoxPresent ); aButtonAdvanced.AddAdvanced( &aCheckBoxLogFile ); } SvxRecoverDialog::~SvxRecoverDialog() { }
31.551402
81
0.697867
Grosskopf
d3ef8b38e01470bea7ce78e2543629d5a36c8a58
81,386
cpp
C++
src/gpu/cgpu/d3d12/cgpu_d3d12.cpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
29
2021-11-19T11:28:22.000Z
2022-03-29T00:26:51.000Z
src/gpu/cgpu/d3d12/cgpu_d3d12.cpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
null
null
null
src/gpu/cgpu/d3d12/cgpu_d3d12.cpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
1
2022-03-05T08:14:40.000Z
2022-03-05T08:14:40.000Z
#include "cgpu/backend/d3d12/cgpu_d3d12.h" #include "d3d12_utils.h" #include "../common/common_utils.h" #include <dxcapi.h> #include <EASTL/string_hash_map.h> #if !defined(XBOX) #pragma comment(lib, "d3d12.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "dxguid.lib") #pragma comment(lib, "dxcompiler.lib") #endif #include <comdef.h> // Call this only once. CGPUInstanceId cgpu_create_instance_d3d12(CGPUInstanceDescriptor const* descriptor) { CGPUInstance_D3D12* result = cgpu_new<CGPUInstance_D3D12>(); D3D12Util_Optionalenable_debug_layer(result, descriptor); UINT flags = 0; if (descriptor->enable_debug_layer) flags = DXGI_CREATE_FACTORY_DEBUG; #if defined(XBOX) #else if (SUCCEEDED(CreateDXGIFactory2(flags, IID_PPV_ARGS(&result->pDXGIFactory)))) { uint32_t gpuCount = 0; bool foundSoftwareAdapter = false; D3D12Util_QueryAllAdapters(result, &gpuCount, &foundSoftwareAdapter); // If the only adapter we found is a software adapter, log error message for QA if (!gpuCount && foundSoftwareAdapter) { cgpu_assert(0 && "The only available GPU has DXGI_ADAPTER_FLAG_SOFTWARE. Early exiting"); return CGPU_NULLPTR; } } else { cgpu_assert("[D3D12 Fatal]: Create DXGIFactory2 Failed!"); } #endif return &result->super; } void cgpu_query_instance_features_d3d12(CGPUInstanceId instance, struct CGPUInstanceFeatures* features) { CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)instance; (void)I; features->specialization_constant = false; } void cgpu_free_instance_d3d12(CGPUInstanceId instance) { CGPUInstance_D3D12* to_destroy = (CGPUInstance_D3D12*)instance; if (to_destroy->mAdaptersCount > 0) { for (uint32_t i = 0; i < to_destroy->mAdaptersCount; i++) { SAFE_RELEASE(to_destroy->pAdapters[i].pDxActiveGPU); } } cgpu_free(to_destroy->pAdapters); SAFE_RELEASE(to_destroy->pDXGIFactory); if (to_destroy->pDXDebug) { SAFE_RELEASE(to_destroy->pDXDebug); } cgpu_delete(to_destroy); #ifdef _DEBUG { IDXGIDebug1* dxgiDebug; if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&dxgiDebug)))) { dxgiDebug->ReportLiveObjects( DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_FLAGS(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_IGNORE_INTERNAL)); } SAFE_RELEASE(dxgiDebug); } #endif } void cgpu_enum_adapters_d3d12(CGPUInstanceId instance, CGPUAdapterId* const adapters, uint32_t* adapters_num) { cgpu_assert(instance != nullptr && "fatal: null instance!"); CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)instance; *adapters_num = I->mAdaptersCount; if (!adapters) { return; } else { for (auto i = 0u; i < *adapters_num; i++) adapters[i] = &(I->pAdapters[i].super); } } const CGPUAdapterDetail* cgpu_query_adapter_detail_d3d12(const CGPUAdapterId adapter) { const CGPUAdapter_D3D12* A = (CGPUAdapter_D3D12*)adapter; return &A->adapter_detail; } uint32_t cgpu_query_queue_count_d3d12(const CGPUAdapterId adapter, const ECGPUQueueType type) { // queues are virtual in d3d12. /* switch(type) { case CGPU_QUEUE_TYPE_GRAPHICS: return 1; case CGPU_QUEUE_TYPE_COMPUTE: return 2; case CGPU_QUEUE_TYPE_TRANSFER: return 2; default: return 0; } */ return UINT32_MAX; } CGPUDeviceId cgpu_create_device_d3d12(CGPUAdapterId adapter, const CGPUDeviceDescriptor* desc) { CGPUAdapter_D3D12* A = (CGPUAdapter_D3D12*)adapter; CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)A->super.instance; CGPUDevice_D3D12* D = cgpu_new<CGPUDevice_D3D12>(); *const_cast<CGPUAdapterId*>(&D->super.adapter) = adapter; if (!SUCCEEDED(D3D12CreateDevice(A->pDxActiveGPU, // default adapter A->mFeatureLevel, IID_PPV_ARGS(&D->pDxDevice)))) { cgpu_assert("[D3D12 Fatal]: Create D3D12Device Failed!"); } // Create Requested Queues. for (uint32_t i = 0u; i < desc->queueGroupCount; i++) { const auto& queueGroup = desc->queueGroups[i]; const auto type = queueGroup.queueType; *const_cast<uint32_t*>(&D->pCommandQueueCounts[type]) = queueGroup.queueCount; *const_cast<ID3D12CommandQueue***>(&D->ppCommandQueues[type]) = (ID3D12CommandQueue**)cgpu_malloc(sizeof(ID3D12CommandQueue*) * queueGroup.queueCount); for (uint32_t j = 0u; j < queueGroup.queueCount; j++) { DECLARE_ZERO(D3D12_COMMAND_QUEUE_DESC, queueDesc) switch (type) { case CGPU_QUEUE_TYPE_GRAPHICS: queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; break; case CGPU_QUEUE_TYPE_COMPUTE: queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; break; case CGPU_QUEUE_TYPE_TRANSFER: queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY; break; default: cgpu_assert(0 && "[D3D12 Fatal]: Unsupported ECGPUQueueType!"); return CGPU_NULLPTR; } queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; if (!SUCCEEDED(D->pDxDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&D->ppCommandQueues[type][j])))) { cgpu_assert("[D3D12 Fatal]: Create D3D12CommandQueue Failed!"); } } } // Create D3D12MA Allocator D3D12Util_CreateDMAAllocator(I, A, D); cgpu_assert(D->pResourceAllocator && "DMA Allocator Must be Created!"); // Create Descriptor Heaps D->pCPUDescriptorHeaps = (D3D12Util_DescriptorHeap**)cgpu_malloc(D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES * sizeof(D3D12Util_DescriptorHeap*)); D->pCbvSrvUavHeaps = (D3D12Util_DescriptorHeap**)cgpu_malloc(sizeof(D3D12Util_DescriptorHeap*)); D->pSamplerHeaps = (D3D12Util_DescriptorHeap**)cgpu_malloc(sizeof(D3D12Util_DescriptorHeap*)); for (uint32_t i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++i) { D3D12_DESCRIPTOR_HEAP_DESC desc = {}; desc.Flags = gCpuDescriptorHeapProperties[i].mFlags; desc.NodeMask = 0; // CPU Descriptor Heap - Node mask is irrelevant desc.NumDescriptors = gCpuDescriptorHeapProperties[i].mMaxDescriptors; desc.Type = (D3D12_DESCRIPTOR_HEAP_TYPE)i; D3D12Util_CreateDescriptorHeap(D->pDxDevice, &desc, &D->pCPUDescriptorHeaps[i]); } // One shader visible heap for each linked node for (uint32_t i = 0; i < SINGLE_GPU_NODE_COUNT; ++i) { D3D12_DESCRIPTOR_HEAP_DESC desc = {}; desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; desc.NodeMask = SINGLE_GPU_NODE_MASK; desc.NumDescriptors = 1 << 16; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; D3D12Util_CreateDescriptorHeap(D->pDxDevice, &desc, &D->pCbvSrvUavHeaps[i]); desc.NumDescriptors = 1 << 11; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; D3D12Util_CreateDescriptorHeap(D->pDxDevice, &desc, &D->pSamplerHeaps[i]); } // Pipeline cache D3D12_FEATURE_DATA_SHADER_CACHE feature = {}; HRESULT result = D->pDxDevice->CheckFeatureSupport( D3D12_FEATURE_SHADER_CACHE, &feature, sizeof(feature)); if (SUCCEEDED(result)) { result = E_NOTIMPL; if (feature.SupportFlags & D3D12_SHADER_CACHE_SUPPORT_LIBRARY) { ID3D12Device1* device1 = NULL; result = D->pDxDevice->QueryInterface(IID_ARGS(&device1)); if (SUCCEEDED(result)) { result = device1->CreatePipelineLibrary( D->pPSOCacheData, 0, IID_ARGS(&D->pPipelineLibrary)); } SAFE_RELEASE(device1); } } return &D->super; } void cgpu_free_device_d3d12(CGPUDeviceId device) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; for (uint32_t t = 0u; t < CGPU_QUEUE_TYPE_COUNT; t++) { for (uint32_t i = 0; i < D->pCommandQueueCounts[t]; i++) { SAFE_RELEASE(D->ppCommandQueues[t][i]); } cgpu_free((ID3D12CommandQueue**)D->ppCommandQueues[t]); } // Free D3D12MA Allocator SAFE_RELEASE(D->pResourceAllocator); // Free Descriptor Heaps for (uint32_t i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; i++) { D3D12Util_FreeDescriptorHeap(D->pCPUDescriptorHeaps[i]); } D3D12Util_FreeDescriptorHeap(D->pCbvSrvUavHeaps[0]); D3D12Util_FreeDescriptorHeap(D->pSamplerHeaps[0]); cgpu_free(D->pCPUDescriptorHeaps); cgpu_free(D->pCbvSrvUavHeaps); cgpu_free(D->pSamplerHeaps); // Release D3D12 Device SAFE_RELEASE(D->pDxDevice); SAFE_RELEASE(D->pPipelineLibrary); if (D->pPSOCacheData) cgpu_free(D->pPSOCacheData); cgpu_delete(D); } // API Objects APIs CGPUFenceId cgpu_create_fence_d3d12(CGPUDeviceId device) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; // create a Fence and cgpu_assert that it is valid CGPUFence_D3D12* F = cgpu_new<CGPUFence_D3D12>(); cgpu_assert(F); CHECK_HRESULT(D->pDxDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_ARGS(&F->pDxFence))); F->mFenceValue = 1; F->pDxWaitIdleFenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL); return &F->super; } void cgpu_wait_fences_d3d12(const CGPUFenceId* fences, uint32_t fence_count) { const CGPUFence_D3D12** Fences = (const CGPUFence_D3D12**)fences; for (uint32_t i = 0; i < fence_count; ++i) { ECGPUFenceStatus fenceStatus = cgpu_query_fence_status(fences[i]); uint64_t fenceValue = Fences[i]->mFenceValue - 1; if (fenceStatus == CGPU_FENCE_STATUS_INCOMPLETE) { Fences[i]->pDxFence->SetEventOnCompletion( fenceValue, Fences[i]->pDxWaitIdleFenceEvent); WaitForSingleObject(Fences[i]->pDxWaitIdleFenceEvent, INFINITE); } } } ECGPUFenceStatus cgpu_query_fence_status_d3d12(CGPUFenceId fence) { ECGPUFenceStatus status = CGPU_FENCE_STATUS_COMPLETE; CGPUFence_D3D12* F = (CGPUFence_D3D12*)fence; if (F->pDxFence->GetCompletedValue() < F->mFenceValue - 1) status = CGPU_FENCE_STATUS_INCOMPLETE; else status = CGPU_FENCE_STATUS_COMPLETE; return status; } void cgpu_free_fence_d3d12(CGPUFenceId fence) { CGPUFence_D3D12* F = (CGPUFence_D3D12*)fence; SAFE_RELEASE(F->pDxFence); CloseHandle(F->pDxWaitIdleFenceEvent); cgpu_delete(F); } CGPUSemaphoreId cgpu_create_semaphore_d3d12(CGPUDeviceId device) { return (CGPUSemaphoreId)cgpu_create_fence(device); } void cgpu_free_semaphore_d3d12(CGPUSemaphoreId semaphore) { return cgpu_free_fence((CGPUFenceId)semaphore); } CGPURootSignaturePoolId cgpu_create_root_signature_pool_d3d12(CGPUDeviceId device, const struct CGPURootSignaturePoolDescriptor* desc) { return CGPUUtil_CreateRootSignaturePool(desc); } void cgpu_free_root_signature_pool_d3d12(CGPURootSignaturePoolId pool) { CGPUUtil_FreeRootSignaturePool(pool); } // for example, shader register set: (s0t0) (s0b1) [s0b0[root]] (s1t0) (s1t1) {s2s0{static}} // rootParams: | s0 | s1 | [s0b0] | // rootRanges: | s0t0 | s0b1 | s1t0 | s1t1 | // staticSamplers: | s2s0 | ... | CGPURootSignatureId cgpu_create_root_signature_d3d12(CGPUDeviceId device, const struct CGPURootSignatureDescriptor* desc) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; CGPURootSignature_D3D12* RS = cgpu_new<CGPURootSignature_D3D12>(); // Pick root parameters from desc data CGPUShaderStages shaderStages = 0; for (uint32_t i = 0; i < desc->shader_count; i++) { CGPUPipelineShaderDescriptor* shader_desc = desc->shaders + i; shaderStages |= shader_desc->stage; } // Pick shader reflection data CGPUUtil_InitRSParamTables((CGPURootSignature*)RS, desc); // [RS POOL] ALLOCATION if (desc->pool) { CGPURootSignature_D3D12* poolSig = (CGPURootSignature_D3D12*)CGPUUtil_TryAllocateSignature(desc->pool, &RS->super, desc); if (poolSig != CGPU_NULLPTR) { RS->mRootConstantParam = poolSig->mRootConstantParam; RS->pDxRootSignature = poolSig->pDxRootSignature; RS->mRootParamIndex = poolSig->mRootParamIndex; RS->super.pool = desc->pool; RS->super.pool_sig = &poolSig->super; return &RS->super; } } // [RS POOL] END ALLOCATION // Fill resource slots // Only support descriptor tables now // TODO: Support root CBVs // Add backend sort for better performance const UINT tableCount = RS->super.table_count; UINT descRangeCount = 0; for (uint32_t i = 0; i < tableCount; i++) { descRangeCount += RS->super.tables[i].resources_count; } D3D12_ROOT_PARAMETER1* rootParams = (D3D12_ROOT_PARAMETER1*)cgpu_calloc( tableCount + RS->super.push_constant_count, sizeof(D3D12_ROOT_PARAMETER1)); D3D12_DESCRIPTOR_RANGE1* cbvSrvUavRanges = (D3D12_DESCRIPTOR_RANGE1*)cgpu_calloc(descRangeCount, sizeof(D3D12_DESCRIPTOR_RANGE1)); // Create descriptor tables UINT valid_root_tables = 0; for (uint32_t i_set = 0, i_range = 0; i_set < RS->super.table_count; i_set++) { CGPUParameterTable* paramTable = &RS->super.tables[i_set]; D3D12_ROOT_PARAMETER1* rootParam = &rootParams[valid_root_tables]; rootParam->ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; CGPUShaderStages visStages = CGPU_SHADER_STAGE_NONE; const D3D12_DESCRIPTOR_RANGE1* descRangeCursor = &cbvSrvUavRanges[i_range]; for (uint32_t i_register = 0; i_register < paramTable->resources_count; i_register++) { CGPUShaderResource* reflSlot = &paramTable->resources[i_register]; visStages |= reflSlot->stages; // Record RS::mRootConstantParam directly, it'll be copied to the end of rootParams list { D3D12_DESCRIPTOR_RANGE1* descRange = &cbvSrvUavRanges[i_range]; descRange->RegisterSpace = reflSlot->set; descRange->BaseShaderRegister = reflSlot->binding; descRange->Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE; descRange->NumDescriptors = (reflSlot->type != CGPU_RESOURCE_TYPE_UNIFORM_BUFFER) ? reflSlot->size : 1; descRange->OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; descRange->RangeType = D3D12Util_ResourceTypeToDescriptorRangeType(reflSlot->type); rootParam->DescriptorTable.NumDescriptorRanges++; i_range++; } } if (visStages != 0) { rootParam->ShaderVisibility = D3D12Util_TranslateShaderStages(visStages); rootParam->DescriptorTable.pDescriptorRanges = descRangeCursor; valid_root_tables++; } } // Root Const assert(RS->super.push_constant_count <= 1 && "Only support 1 push const now!"); if (RS->super.push_constant_count) { auto reflSlot = RS->super.push_constants; RS->mRootConstantParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; RS->mRootConstantParam.Constants.RegisterSpace = reflSlot->set; RS->mRootConstantParam.Constants.ShaderRegister = reflSlot->binding; RS->mRootConstantParam.Constants.Num32BitValues = reflSlot->size / sizeof(uint32_t); RS->mRootConstantParam.ShaderVisibility = D3D12Util_TranslateShaderStages(reflSlot->stages); } // Create static samplers UINT staticSamplerCount = desc->static_sampler_count; D3D12_STATIC_SAMPLER_DESC* staticSamplerDescs = CGPU_NULLPTR; if (staticSamplerCount > 0) { staticSamplerDescs = (D3D12_STATIC_SAMPLER_DESC*)alloca( staticSamplerCount * sizeof(D3D12_STATIC_SAMPLER_DESC)); for (uint32_t i = 0; i < RS->super.static_sampler_count; i++) { auto& RST_slot = RS->super.static_samplers[i]; for (uint32_t j = 0; j < desc->static_sampler_count; j++) { auto input_slot = (CGPUSampler_D3D12*)desc->static_samplers[j]; if (strcmp(RST_slot.name, desc->static_sampler_names[j]) == 0) { D3D12_SAMPLER_DESC& desc = input_slot->mDxDesc; staticSamplerDescs[i].Filter = desc.Filter; staticSamplerDescs[i].AddressU = desc.AddressU; staticSamplerDescs[i].AddressV = desc.AddressV; staticSamplerDescs[i].AddressW = desc.AddressW; staticSamplerDescs[i].MipLODBias = desc.MipLODBias; staticSamplerDescs[i].MaxAnisotropy = desc.MaxAnisotropy; staticSamplerDescs[i].ComparisonFunc = desc.ComparisonFunc; staticSamplerDescs[i].MinLOD = desc.MinLOD; staticSamplerDescs[i].MaxLOD = desc.MaxLOD; staticSamplerDescs[i].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; CGPUShaderResource* samplerResource = &RST_slot; staticSamplerDescs[i].RegisterSpace = samplerResource->set; staticSamplerDescs[i].ShaderRegister = samplerResource->binding; staticSamplerDescs[i].ShaderVisibility = D3D12Util_TranslateShaderStages(samplerResource->stages); } } } } bool useInputLayout = shaderStages & CGPU_SHADER_STAGE_VERT; // VertexStage uses input layout // Fill RS flags D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = D3D12_ROOT_SIGNATURE_FLAG_NONE; if (useInputLayout) rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; if (!(shaderStages & CGPU_SHADER_STAGE_VERT)) rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS; if (!(shaderStages & CGPU_SHADER_STAGE_HULL)) rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS; if (!(shaderStages & CGPU_SHADER_STAGE_DOMAIN)) rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS; if (!(shaderStages & CGPU_SHADER_STAGE_GEOM)) rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; if (!(shaderStages & CGPU_SHADER_STAGE_FRAG)) rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; // Serialize versioned RS const UINT paramCount = valid_root_tables + RS->super.push_constant_count /*must be 0 or 1 now*/; // Root Constant assert(RS->super.push_constant_count <= 1 && "Only support 1 push const now!"); for (uint32_t i = 0; i < RS->super.push_constant_count; i++) { rootParams[valid_root_tables + i] = RS->mRootConstantParam; RS->mRootParamIndex = valid_root_tables + i; } // Serialize PSO ID3DBlob* error = NULL; ID3DBlob* rootSignatureString = NULL; DECLARE_ZERO(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, sig_desc); sig_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; sig_desc.Desc_1_1.NumParameters = paramCount; sig_desc.Desc_1_1.pParameters = rootParams; sig_desc.Desc_1_1.NumStaticSamplers = staticSamplerCount; sig_desc.Desc_1_1.pStaticSamplers = staticSamplerDescs; sig_desc.Desc_1_1.Flags = rootSignatureFlags; HRESULT hres = D3D12SerializeVersionedRootSignature(&sig_desc, &rootSignatureString, &error); if (!SUCCEEDED(hres)) { cgpu_error("Failed to serialize root signature with error (%s)", (char*)error->GetBufferPointer()); } // If running Linked Mode (SLI) create root signature for all nodes // #NOTE : In non SLI mode, mNodeCount will be 0 which sets nodeMask to // default value CHECK_HRESULT(D->pDxDevice->CreateRootSignature( SINGLE_GPU_NODE_MASK, rootSignatureString->GetBufferPointer(), rootSignatureString->GetBufferSize(), IID_ARGS(&RS->pDxRootSignature))); cgpu_free(rootParams); cgpu_free(cbvSrvUavRanges); // [RS POOL] INSERTION if (desc->pool) { const bool result = CGPUUtil_AddSignature(desc->pool, &RS->super, desc); cgpu_assert(result && "Root signature pool insertion failed!"); } // [RS POOL] END INSERTION return &RS->super; } void cgpu_free_root_signature_d3d12(CGPURootSignatureId signature) { CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)signature; // [RS POOL] FREE if (signature->pool) { CGPUUtil_PoolFreeSignature(signature->pool, signature); if (signature->pool_sig) // not root { // Free Reflection Data CGPUUtil_FreeRSParamTables((CGPURootSignature*)signature); cgpu_delete(RS); } return; } // [RS POOL] END FREE CGPUUtil_FreeRSParamTables((CGPURootSignature*)signature); SAFE_RELEASE(RS->pDxRootSignature); cgpu_delete(RS); } CGPUDescriptorSetId cgpu_create_descriptor_set_d3d12(CGPUDeviceId device, const struct CGPUDescriptorSetDescriptor* desc) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; const CGPURootSignature_D3D12* RS = (const CGPURootSignature_D3D12*)desc->root_signature; CGPUDescriptorSet_D3D12* Set = cgpu_new<CGPUDescriptorSet_D3D12>(); const uint32_t nodeIndex = SINGLE_GPU_NODE_INDEX; struct D3D12Util_DescriptorHeap* pCbvSrvUavHeap = D->pCbvSrvUavHeaps[nodeIndex]; struct D3D12Util_DescriptorHeap* pSamplerHeap = D->pSamplerHeaps[nodeIndex]; (void)pSamplerHeap; CGPUParameterTable* param_table = &RS->super.tables[desc->set_index]; uint32_t CbvSrvUavCount = 0; uint32_t SamplerCount = 0; for (uint32_t i = 0; i < param_table->resources_count; i++) { if (param_table->resources[i].type == CGPU_RESOURCE_TYPE_SAMPLER) SamplerCount++; else if (param_table->resources[i].type == CGPU_RESOURCE_TYPE_TEXTURE || param_table->resources[i].type == CGPU_RESOURCE_TYPE_RW_TEXTURE || param_table->resources[i].type == CGPU_RESOURCE_TYPE_BUFFER || param_table->resources[i].type == CGPU_RESOURCE_TYPE_BUFFER_RAW || param_table->resources[i].type == CGPU_RESOURCE_TYPE_RW_BUFFER || param_table->resources[i].type == CGPU_RESOURCE_TYPE_RW_BUFFER_RAW || param_table->resources[i].type == CGPU_RESOURCE_TYPE_TEXTURE_CUBE || param_table->resources[i].type == CGPU_RESOURCE_TYPE_UNIFORM_BUFFER) { CbvSrvUavCount++; } } // CBV/SRV/UAV Set->mCbvSrvUavHandle = D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN; Set->mSamplerHandle = D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN; if (CbvSrvUavCount) { auto StartHandle = D3D12Util_ConsumeDescriptorHandles(pCbvSrvUavHeap, param_table->resources_count); Set->mCbvSrvUavHandle = StartHandle.mGpu.ptr - pCbvSrvUavHeap->mStartHandle.mGpu.ptr; Set->mCbvSrvUavStride = CbvSrvUavCount * pCbvSrvUavHeap->mDescriptorSize; } if (SamplerCount) { auto StartHandle = D3D12Util_ConsumeDescriptorHandles(pSamplerHeap, param_table->resources_count); Set->mSamplerHandle = StartHandle.mGpu.ptr - pSamplerHeap->mStartHandle.mGpu.ptr; Set->mSamplerStride = SamplerCount * pSamplerHeap->mDescriptorSize; } // TODO: Bind NULL handles on creation // TODO: Support root descriptors return &Set->super; } uint32_t descriptor_count_needed(CGPUShaderResource* resource) { if (resource->dim == CGPU_TEX_DIMENSION_1D_ARRAY || resource->dim == CGPU_TEX_DIMENSION_2D_ARRAY || resource->dim == CGPU_TEX_DIMENSION_2DMS_ARRAY || resource->dim == CGPU_TEX_DIMENSION_CUBE_ARRAY) return resource->size; else return 1; } void cgpu_update_descriptor_set_d3d12(CGPUDescriptorSetId set, const struct CGPUDescriptorData* datas, uint32_t count) { CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set; const CGPURootSignature_D3D12* RS = (const CGPURootSignature_D3D12*)set->root_signature; CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)set->root_signature->device; CGPUParameterTable* ParamTable = &RS->super.tables[set->index]; const uint32_t nodeIndex = SINGLE_GPU_NODE_INDEX; struct D3D12Util_DescriptorHeap* pCbvSrvUavHeap = D->pCbvSrvUavHeaps[nodeIndex]; struct D3D12Util_DescriptorHeap* pSamplerHeap = D->pSamplerHeaps[nodeIndex]; for (uint32_t i = 0; i < count; i++) { // Descriptor Info const CGPUDescriptorData* pParam = datas + i; CGPUShaderResource* ResData = CGPU_NULLPTR; uint32_t HeapOffset = 0; if (pParam->name != CGPU_NULLPTR) { size_t argNameHash = cgpu_hash(pParam->name, strlen(pParam->name), *(size_t*)&D); for (uint32_t j = 0; j < ParamTable->resources_count; j++) { if (ParamTable->resources[j].name_hash == argNameHash) { ResData = ParamTable->resources + j; break; } HeapOffset += descriptor_count_needed(&ParamTable->resources[j]); } } else { for (uint32_t j = 0; j < ParamTable->resources_count; j++) { if (ParamTable->resources[j].type == pParam->binding_type && ParamTable->resources[j].binding == pParam->binding) { ResData = &ParamTable->resources[j]; break; } HeapOffset += descriptor_count_needed(&ParamTable->resources[j]); } } // Update Info const uint32_t arrayCount = cgpu_max(1U, pParam->count); switch (ResData->type) { case CGPU_RESOURCE_TYPE_SAMPLER: { cgpu_assert(pParam->samplers && "cgpu_assert: Binding NULL Sampler(s)!"); CGPUSampler_D3D12** Samplers = (CGPUSampler_D3D12**)pParam->samplers; for (uint32_t arr = 0; arr < arrayCount; arr++) { cgpu_assert(pParam->samplers[arr] && "cgpu_assert: Binding NULL Sampler!"); D3D12Util_CopyDescriptorHandle(pSamplerHeap, { Samplers[arr]->mDxHandle.ptr }, Set->mSamplerHandle, arr + HeapOffset); } } break; case CGPU_RESOURCE_TYPE_TEXTURE: case CGPU_RESOURCE_TYPE_TEXTURE_CUBE: { cgpu_assert(pParam->textures && "cgpu_assert: Binding NULL Textures(s)!"); CGPUTextureView_D3D12** Textures = (CGPUTextureView_D3D12**)pParam->textures; for (uint32_t arr = 0; arr < arrayCount; arr++) { cgpu_assert(pParam->textures[arr] && "cgpu_assert: Binding NULL Textures!"); D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap, { Textures[arr]->mDxDescriptorHandles.ptr + Textures[arr]->mDxSrvOffset }, Set->mCbvSrvUavHandle, arr + HeapOffset); } } break; case CGPU_RESOURCE_TYPE_BUFFER: case CGPU_RESOURCE_TYPE_BUFFER_RAW: { cgpu_assert(pParam->buffers && "cgpu_assert: Binding NULL Buffer(s)!"); CGPUBuffer_D3D12** Buffers = (CGPUBuffer_D3D12**)pParam->buffers; for (uint32_t arr = 0; arr < arrayCount; arr++) { cgpu_assert(pParam->buffers[arr] && "cgpu_assert: Binding NULL Buffer!"); D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap, { Buffers[arr]->mDxDescriptorHandles.ptr + Buffers[arr]->mDxSrvOffset }, Set->mCbvSrvUavHandle, arr + HeapOffset); } } break; case CGPU_RESOURCE_TYPE_UNIFORM_BUFFER: { cgpu_assert(pParam->buffers && "cgpu_assert: Binding NULL Buffer(s)!"); CGPUBuffer_D3D12** Buffers = (CGPUBuffer_D3D12**)pParam->buffers; for (uint32_t arr = 0; arr < arrayCount; arr++) { cgpu_assert(pParam->buffers[arr] && "cgpu_assert: Binding NULL Buffer!"); D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap, { Buffers[arr]->mDxDescriptorHandles.ptr }, Set->mCbvSrvUavHandle, arr + HeapOffset); } } break; case CGPU_RESOURCE_TYPE_RW_TEXTURE: { cgpu_assert(pParam->textures && "cgpu_assert: Binding NULL Texture(s)!"); CGPUTextureView_D3D12** Textures = (CGPUTextureView_D3D12**)pParam->textures; for (uint32_t arr = 0; arr < arrayCount; arr++) { cgpu_assert(pParam->textures[arr] && "cgpu_assert: Binding NULL Texture!"); D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap, { Textures[arr]->mDxDescriptorHandles.ptr + Textures[arr]->mDxUavOffset }, Set->mCbvSrvUavHandle, arr + HeapOffset); } } break; case CGPU_RESOURCE_TYPE_RW_BUFFER: case CGPU_RESOURCE_TYPE_RW_BUFFER_RAW: { cgpu_assert(pParam->buffers && "cgpu_assert: Binding NULL Buffer(s)!"); CGPUBuffer_D3D12** Buffers = (CGPUBuffer_D3D12**)pParam->buffers; for (uint32_t arr = 0; arr < arrayCount; arr++) { cgpu_assert(pParam->buffers[arr] && "cgpu_assert: Binding NULL Buffer!"); D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap, { Buffers[arr]->mDxDescriptorHandles.ptr + Buffers[arr]->mDxUavOffset }, Set->mCbvSrvUavHandle, arr + HeapOffset); } } break; default: break; } } } void cgpu_free_descriptor_set_d3d12(CGPUDescriptorSetId set) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)set->root_signature->device; CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set; (void)D; // TODO: recycle of descriptor set heap handles cgpu_delete(Set); } CGPUComputePipelineId cgpu_create_compute_pipeline_d3d12(CGPUDeviceId device, const struct CGPUComputePipelineDescriptor* desc) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; CGPUComputePipeline_D3D12* PPL = cgpu_new<CGPUComputePipeline_D3D12>(); CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)desc->root_signature; CGPUShaderLibrary_D3D12* SL = (CGPUShaderLibrary_D3D12*)desc->compute_shader->library; PPL->pRootSignature = RS->pDxRootSignature; // Add pipeline specifying its for compute purposes DECLARE_ZERO(D3D12_SHADER_BYTECODE, CS); CS.BytecodeLength = SL->pShaderBlob->GetBufferSize(); CS.pShaderBytecode = SL->pShaderBlob->GetBufferPointer(); DECLARE_ZERO(D3D12_CACHED_PIPELINE_STATE, cached_pso_desc); cached_pso_desc.pCachedBlob = NULL; cached_pso_desc.CachedBlobSizeInBytes = 0; DECLARE_ZERO(D3D12_COMPUTE_PIPELINE_STATE_DESC, pipeline_state_desc); pipeline_state_desc.pRootSignature = RS->pDxRootSignature; pipeline_state_desc.CS = CS; pipeline_state_desc.CachedPSO = cached_pso_desc; pipeline_state_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; pipeline_state_desc.NodeMask = SINGLE_GPU_NODE_MASK; // Pipeline cache HRESULT result = E_FAIL; wchar_t pipelineName[PSO_NAME_LENGTH] = {}; size_t psoShaderHash = 0; size_t psoComputeHash = 0; if (D->pPipelineLibrary) { if (CS.BytecodeLength) psoShaderHash = cgpu_hash(CS.pShaderBytecode, CS.BytecodeLength, psoShaderHash); psoComputeHash = cgpu_hash(&pipeline_state_desc.Flags, sizeof(D3D12_PIPELINE_STATE_FLAGS), psoComputeHash); psoComputeHash = cgpu_hash(&pipeline_state_desc.NodeMask, sizeof(UINT), psoComputeHash); swprintf(pipelineName, PSO_NAME_LENGTH, L"%S_S%zuR%zu", "COMPUTEPSO", psoShaderHash, psoComputeHash); result = D->pPipelineLibrary->LoadComputePipeline(pipelineName, &pipeline_state_desc, IID_ARGS(&PPL->pDxPipelineState)); } if (!SUCCEEDED(result)) { // XBOX: Support PSO extensions CHECK_HRESULT(D->pDxDevice->CreateComputePipelineState( &pipeline_state_desc, IID_PPV_ARGS(&PPL->pDxPipelineState))); } return &PPL->super; } void cgpu_free_compute_pipeline_d3d12(CGPUComputePipelineId pipeline) { CGPUComputePipeline_D3D12* PPL = (CGPUComputePipeline_D3D12*)pipeline; SAFE_RELEASE(PPL->pDxPipelineState); cgpu_delete(PPL); } D3D12_DEPTH_STENCIL_DESC gDefaultDepthDesc = {}; D3D12_BLEND_DESC gDefaultBlendDesc = {}; D3D12_RASTERIZER_DESC gDefaultRasterizerDesc = {}; CGPURenderPipelineId cgpu_create_render_pipeline_d3d12(CGPUDeviceId device, const struct CGPURenderPipelineDescriptor* desc) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; CGPURenderPipeline_D3D12* PPL = cgpu_new<CGPURenderPipeline_D3D12>(); CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)desc->root_signature; // Vertex input state DECLARE_ZERO(D3D12_INPUT_ELEMENT_DESC, input_elements[CGPU_MAX_VERTEX_ATTRIBS]); uint32_t elem_count = 0; if (desc->vertex_layout != nullptr) { for (uint32_t attrib_index = 0; attrib_index < desc->vertex_layout->attribute_count; ++attrib_index) { const CGPUVertexAttribute* attrib = &(desc->vertex_layout->attributes[attrib_index]); for (uint32_t arr_index = 0; arr_index < attrib->array_size; arr_index++) { input_elements[elem_count].SemanticIndex = arr_index; input_elements[elem_count].SemanticName = attrib->semantic_name; input_elements[elem_count].Format = DXGIUtil_TranslatePixelFormat(attrib->format); input_elements[elem_count].InputSlot = attrib->binding; input_elements[elem_count].AlignedByteOffset = attrib->offset + arr_index * FormatUtil_BitSizeOfBlock(attrib->format) / 8; if (attrib->rate == CGPU_INPUT_RATE_INSTANCE) { input_elements[elem_count].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; input_elements[elem_count].InstanceDataStepRate = 1; } else { input_elements[elem_count].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; input_elements[elem_count].InstanceDataStepRate = 0; } elem_count++; } } } DECLARE_ZERO(D3D12_INPUT_LAYOUT_DESC, input_layout_desc); input_layout_desc.pInputElementDescs = elem_count ? input_elements : NULL; input_layout_desc.NumElements = elem_count; // Shader stages DECLARE_ZERO(D3D12_SHADER_BYTECODE, VS); DECLARE_ZERO(D3D12_SHADER_BYTECODE, PS); DECLARE_ZERO(D3D12_SHADER_BYTECODE, DS); DECLARE_ZERO(D3D12_SHADER_BYTECODE, HS); DECLARE_ZERO(D3D12_SHADER_BYTECODE, GS); for (uint32_t i = 0; i < 5; ++i) { ECGPUShaderStage stage_mask = (ECGPUShaderStage)(1 << i); switch (stage_mask) { case CGPU_SHADER_STAGE_VERT: { if (desc->vertex_shader) { CGPUShaderLibrary_D3D12* VertLib = (CGPUShaderLibrary_D3D12*)desc->vertex_shader->library; VS.BytecodeLength = VertLib->pShaderBlob->GetBufferSize(); VS.pShaderBytecode = VertLib->pShaderBlob->GetBufferPointer(); } } break; case CGPU_SHADER_STAGE_TESC: { if (desc->tesc_shader) { CGPUShaderLibrary_D3D12* TescLib = (CGPUShaderLibrary_D3D12*)desc->tesc_shader->library; HS.BytecodeLength = TescLib->pShaderBlob->GetBufferSize(); HS.pShaderBytecode = TescLib->pShaderBlob->GetBufferPointer(); } } break; case CGPU_SHADER_STAGE_TESE: { if (desc->tese_shader) { CGPUShaderLibrary_D3D12* TeseLib = (CGPUShaderLibrary_D3D12*)desc->tese_shader->library; DS.BytecodeLength = TeseLib->pShaderBlob->GetBufferSize(); DS.pShaderBytecode = TeseLib->pShaderBlob->GetBufferPointer(); } } break; case CGPU_SHADER_STAGE_GEOM: { if (desc->geom_shader) { CGPUShaderLibrary_D3D12* GeomLib = (CGPUShaderLibrary_D3D12*)desc->geom_shader->library; GS.BytecodeLength = GeomLib->pShaderBlob->GetBufferSize(); GS.pShaderBytecode = GeomLib->pShaderBlob->GetBufferPointer(); } } break; case CGPU_SHADER_STAGE_FRAG: { if (desc->fragment_shader) { CGPUShaderLibrary_D3D12* FragLib = (CGPUShaderLibrary_D3D12*)desc->fragment_shader->library; PS.BytecodeLength = FragLib->pShaderBlob->GetBufferSize(); PS.pShaderBytecode = FragLib->pShaderBlob->GetBufferPointer(); } } break; default: cgpu_assert(false && "Shader Stage not supported!"); break; } } // Stream out DECLARE_ZERO(D3D12_STREAM_OUTPUT_DESC, stream_output_desc); stream_output_desc.pSODeclaration = NULL; stream_output_desc.NumEntries = 0; stream_output_desc.pBufferStrides = NULL; stream_output_desc.NumStrides = 0; stream_output_desc.RasterizedStream = 0; // Sample DECLARE_ZERO(DXGI_SAMPLE_DESC, sample_desc); sample_desc.Count = (UINT)(desc->sample_count); sample_desc.Quality = (UINT)(desc->sample_quality); DECLARE_ZERO(D3D12_CACHED_PIPELINE_STATE, cached_pso_desc); cached_pso_desc.pCachedBlob = NULL; cached_pso_desc.CachedBlobSizeInBytes = 0; // Fill pipeline object desc DECLARE_ZERO(D3D12_GRAPHICS_PIPELINE_STATE_DESC, pipeline_state_desc); pipeline_state_desc.pRootSignature = RS->pDxRootSignature; // Single GPU pipeline_state_desc.NodeMask = SINGLE_GPU_NODE_MASK; pipeline_state_desc.VS = VS; pipeline_state_desc.PS = PS; pipeline_state_desc.DS = DS; pipeline_state_desc.HS = HS; pipeline_state_desc.GS = GS; pipeline_state_desc.StreamOutput = stream_output_desc; pipeline_state_desc.BlendState = desc->blend_state ? D3D12Util_TranslateBlendState(desc->blend_state) : gDefaultBlendDesc; pipeline_state_desc.SampleMask = UINT_MAX; pipeline_state_desc.RasterizerState = desc->rasterizer_state ? D3D12Util_TranslateRasterizerState(desc->rasterizer_state) : gDefaultRasterizerDesc; // Depth stencil pipeline_state_desc.DepthStencilState = desc->depth_state ? D3D12Util_TranslateDephStencilState(desc->depth_state) : gDefaultDepthDesc; pipeline_state_desc.InputLayout = input_layout_desc; pipeline_state_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; pipeline_state_desc.PrimitiveTopologyType = D3D12Util_TranslatePrimitiveTopology(desc->prim_topology); pipeline_state_desc.NumRenderTargets = desc->render_target_count; pipeline_state_desc.DSVFormat = DXGIUtil_TranslatePixelFormat(desc->depth_stencil_format); pipeline_state_desc.SampleDesc = sample_desc; pipeline_state_desc.CachedPSO = cached_pso_desc; pipeline_state_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; for (uint32_t i = 0; i < pipeline_state_desc.NumRenderTargets; ++i) { pipeline_state_desc.RTVFormats[i] = DXGIUtil_TranslatePixelFormat(desc->color_formats[i]); } // Create pipeline object HRESULT result = E_FAIL; wchar_t pipelineName[PSO_NAME_LENGTH] = {}; size_t psoShaderHash = 0; size_t psoRenderHash = 0; if (D->pPipelineLibrary) { // Calculate graphics pso shader hash if (VS.BytecodeLength) psoShaderHash = cgpu_hash(VS.pShaderBytecode, VS.BytecodeLength, psoShaderHash); if (PS.BytecodeLength) psoShaderHash = cgpu_hash(PS.pShaderBytecode, PS.BytecodeLength, psoShaderHash); if (DS.BytecodeLength) psoShaderHash = cgpu_hash(DS.pShaderBytecode, DS.BytecodeLength, psoShaderHash); if (HS.BytecodeLength) psoShaderHash = cgpu_hash(HS.pShaderBytecode, HS.BytecodeLength, psoShaderHash); if (GS.BytecodeLength) psoShaderHash = cgpu_hash(GS.pShaderBytecode, GS.BytecodeLength, psoShaderHash); // Calculate graphics pso desc hash psoRenderHash = cgpu_hash(&pipeline_state_desc.BlendState, sizeof(D3D12_BLEND_DESC), psoRenderHash); psoRenderHash = cgpu_hash(&pipeline_state_desc.RasterizerState, sizeof(D3D12_RASTERIZER_DESC), psoRenderHash); psoRenderHash = cgpu_hash(&pipeline_state_desc.DepthStencilState, sizeof(D3D12_DEPTH_STENCIL_DESC), psoRenderHash); psoRenderHash = cgpu_hash(&pipeline_state_desc.IBStripCutValue, sizeof(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE), psoRenderHash); psoRenderHash = cgpu_hash(pipeline_state_desc.RTVFormats, pipeline_state_desc.NumRenderTargets * sizeof(DXGI_FORMAT), psoRenderHash); psoRenderHash = cgpu_hash(&pipeline_state_desc.DSVFormat, sizeof(DXGI_FORMAT), psoRenderHash); psoRenderHash = cgpu_hash(&pipeline_state_desc.SampleDesc, sizeof(DXGI_SAMPLE_DESC), psoRenderHash); psoRenderHash = cgpu_hash(&pipeline_state_desc.Flags, sizeof(D3D12_PIPELINE_STATE_FLAGS), psoRenderHash); for (uint32_t i = 0; i < pipeline_state_desc.InputLayout.NumElements; i++) { psoRenderHash = cgpu_hash(&pipeline_state_desc.InputLayout.pInputElementDescs[i], sizeof(D3D12_INPUT_ELEMENT_DESC), psoRenderHash); } swprintf(pipelineName, PSO_NAME_LENGTH, L"%S_S%zuR%zu", "GRAPHICSPSO", psoShaderHash, psoRenderHash); result = D->pPipelineLibrary->LoadGraphicsPipeline(pipelineName, &pipeline_state_desc, IID_ARGS(&PPL->pDxPipelineState)); } if (!SUCCEEDED(result)) { CHECK_HRESULT(D->pDxDevice->CreateGraphicsPipelineState( &pipeline_state_desc, IID_PPV_ARGS(&PPL->pDxPipelineState))); // Pipeline cache if (D->pPipelineLibrary) { CHECK_HRESULT(D->pPipelineLibrary->StorePipeline(pipelineName, PPL->pDxPipelineState)); } } D3D_PRIMITIVE_TOPOLOGY topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; switch (desc->prim_topology) { case CGPU_PRIM_TOPO_POINT_LIST: topology = D3D_PRIMITIVE_TOPOLOGY_POINTLIST; break; case CGPU_PRIM_TOPO_LINE_LIST: topology = D3D_PRIMITIVE_TOPOLOGY_LINELIST; break; case CGPU_PRIM_TOPO_LINE_STRIP: topology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; break; case CGPU_PRIM_TOPO_TRI_LIST: topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; case CGPU_PRIM_TOPO_TRI_STRIP: topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; case CGPU_PRIM_TOPO_PATCH_LIST: { // TODO: Support D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST with Hull Shaders cgpu_assert(0 && "Unsupported primitive topology!"); } default: break; } PPL->mDxPrimitiveTopology = topology; PPL->pRootSignature = RS->pDxRootSignature; return &PPL->super; } void cgpu_free_render_pipeline_d3d12(CGPURenderPipelineId pipeline) { CGPURenderPipeline_D3D12* PPL = (CGPURenderPipeline_D3D12*)pipeline; SAFE_RELEASE(PPL->pDxPipelineState); cgpu_delete(PPL); } D3D12_QUERY_TYPE D3D12Util_ToD3D12QueryType(ECGPUQueryType type) { switch (type) { case CGPU_QUERY_TYPE_TIMESTAMP: return D3D12_QUERY_TYPE_TIMESTAMP; case CGPU_QUERY_TYPE_PIPELINE_STATISTICS: return D3D12_QUERY_TYPE_PIPELINE_STATISTICS; case CGPU_QUERY_TYPE_OCCLUSION: return D3D12_QUERY_TYPE_OCCLUSION; default: cgpu_assert(false && "Invalid query heap type"); return D3D12_QUERY_TYPE_OCCLUSION; } } D3D12_QUERY_HEAP_TYPE D3D12Util_ToD3D12QueryHeapType(ECGPUQueryType type) { switch (type) { case CGPU_QUERY_TYPE_TIMESTAMP: return D3D12_QUERY_HEAP_TYPE_TIMESTAMP; case CGPU_QUERY_TYPE_PIPELINE_STATISTICS: return D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS; case CGPU_QUERY_TYPE_OCCLUSION: return D3D12_QUERY_HEAP_TYPE_OCCLUSION; default: cgpu_assert(false && "Invalid query heap type"); return D3D12_QUERY_HEAP_TYPE_OCCLUSION; } } CGPUQueryPoolId cgpu_create_query_pool_d3d12(CGPUDeviceId device, const struct CGPUQueryPoolDescriptor* desc) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; CGPUQueryPool_D3D12* pQueryPool = cgpu_new<CGPUQueryPool_D3D12>(); pQueryPool->mType = D3D12Util_ToD3D12QueryType(desc->type); pQueryPool->super.count = desc->query_count; D3D12_QUERY_HEAP_DESC Desc = {}; Desc.Count = desc->query_count; Desc.NodeMask = SINGLE_GPU_NODE_MASK; Desc.Type = D3D12Util_ToD3D12QueryHeapType(desc->type); D->pDxDevice->CreateQueryHeap(&Desc, IID_ARGS(&pQueryPool->pDxQueryHeap)); return &pQueryPool->super; } void cgpu_free_query_pool_d3d12(CGPUQueryPoolId pool) { CGPUQueryPool_D3D12* QP = (CGPUQueryPool_D3D12*)pool; SAFE_RELEASE(QP->pDxQueryHeap); cgpu_delete(QP); } // Queue APIs CGPUQueueId cgpu_get_queue_d3d12(CGPUDeviceId device, ECGPUQueueType type, uint32_t index) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; CGPUQueue_D3D12* Q = cgpu_new<CGPUQueue_D3D12>(); Q->pCommandQueue = D->ppCommandQueues[type][index]; Q->pFence = (CGPUFence_D3D12*)cgpu_create_fence_d3d12(device); return &Q->super; } void cgpu_submit_queue_d3d12(CGPUQueueId queue, const struct CGPUQueueSubmitDescriptor* desc) { uint32_t CmdCount = desc->cmds_count; CGPUCommandBuffer_D3D12** Cmds = (CGPUCommandBuffer_D3D12**)desc->cmds; CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue; CGPUFence_D3D12* F = (CGPUFence_D3D12*)desc->signal_fence; // cgpu_assert that given cmd list and given params are valid cgpu_assert(CmdCount > 0); cgpu_assert(Cmds); // execute given command list cgpu_assert(Q->pCommandQueue); ID3D12CommandList** cmds = (ID3D12CommandList**)alloca(CmdCount * sizeof(ID3D12CommandList*)); for (uint32_t i = 0; i < CmdCount; ++i) { cmds[i] = Cmds[i]->pDxCmdList; } // Wait semaphores CGPUFence_D3D12** WaitSemaphores = (CGPUFence_D3D12**)desc->wait_semaphores; for (uint32_t i = 0; i < desc->wait_semaphore_count; ++i) Q->pCommandQueue->Wait(WaitSemaphores[i]->pDxFence, WaitSemaphores[i]->mFenceValue - 1); // Execute Q->pCommandQueue->ExecuteCommandLists(CmdCount, cmds); // Signal fences if (F) D3D12Util_SignalFence(Q, F->pDxFence, F->mFenceValue++); // Signal Semaphores CGPUFence_D3D12** SignalSemaphores = (CGPUFence_D3D12**)desc->signal_semaphores; for (uint32_t i = 0; i < desc->signal_semaphore_count; i++) D3D12Util_SignalFence(Q, SignalSemaphores[i]->pDxFence, SignalSemaphores[i]->mFenceValue++); } void cgpu_wait_queue_idle_d3d12(CGPUQueueId queue) { CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue; D3D12Util_SignalFence(Q, Q->pFence->pDxFence, Q->pFence->mFenceValue++); uint64_t fenceValue = Q->pFence->mFenceValue - 1; if (Q->pFence->pDxFence->GetCompletedValue() < Q->pFence->mFenceValue - 1) { Q->pFence->pDxFence->SetEventOnCompletion(fenceValue, Q->pFence->pDxWaitIdleFenceEvent); WaitForSingleObject(Q->pFence->pDxWaitIdleFenceEvent, INFINITE); } } void cgpu_queue_present_d3d12(CGPUQueueId queue, const struct CGPUQueuePresentDescriptor* desc) { CGPUSwapChain_D3D12* S = (CGPUSwapChain_D3D12*)desc->swapchain; HRESULT hr = S->pDxSwapChain->Present(S->mDxSyncInterval, S->mFlags /*desc->index*/); if (FAILED(hr)) { #if defined(_WIN32) ID3D12Device* device = NULL; S->pDxSwapChain->GetDevice(IID_ARGS(&device)); HRESULT removeHr = device->GetDeviceRemovedReason(); if (FAILED(removeHr)) { Sleep(5000); // Wait for a few seconds to allow the driver to come // back online before doing a reset. // onDeviceLost(); } #ifdef __ID3D12DeviceRemovedExtendedData_FWD_DEFINED__ ID3D12DeviceRemovedExtendedData* pDread; if (SUCCEEDED(device->QueryInterface(IID_ARGS(&pDread)))) { D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT breadcrumbs; if (SUCCEEDED(pDread->GetAutoBreadcrumbsOutput(&breadcrumbs))) { cgpu_info("Gathered auto-breadcrumbs output."); } D3D12_DRED_PAGE_FAULT_OUTPUT pageFault; if (SUCCEEDED(pDread->GetPageFaultAllocationOutput(&pageFault))) { cgpu_info("Gathered page fault allocation output."); } } pDread->Release(); #endif device->Release(); #endif cgpu_error("Failed to present swapchain render target!"); } } float cgpu_queue_get_timestamp_period_ns_d3d12(CGPUQueueId queue) { CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue; UINT64 freq = 0; // ticks per second Q->pCommandQueue->GetTimestampFrequency(&freq); // ns per tick const double ms_period = 1e9 / (double)freq; return (float)ms_period; } void cgpu_free_queue_d3d12(CGPUQueueId queue) { CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue; cgpu_assert(queue && "D3D12 ERROR: FREE NULL QUEUE!"); cgpu_free_fence_d3d12(&Q->pFence->super); cgpu_delete(Q); } // Command Objects // allocate_transient_command_allocator ID3D12CommandAllocator* allocate_transient_command_allocator(CGPUCommandPool_D3D12* E, CGPUQueueId queue) { CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)queue->device; D3D12_COMMAND_LIST_TYPE type = queue->type == CGPU_QUEUE_TYPE_TRANSFER ? D3D12_COMMAND_LIST_TYPE_COPY : queue->type == CGPU_QUEUE_TYPE_COMPUTE ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; bool res = SUCCEEDED(D->pDxDevice->CreateCommandAllocator(type, IID_PPV_ARGS(&E->pDxCmdAlloc))); if (res) { return E->pDxCmdAlloc; } return CGPU_NULLPTR; } void free_transient_command_allocator(ID3D12CommandAllocator* allocator) { SAFE_RELEASE(allocator); } CGPUCommandPoolId cgpu_create_command_pool_d3d12(CGPUQueueId queue, const CGPUCommandPoolDescriptor* desc) { CGPUCommandPool_D3D12* P = cgpu_new<CGPUCommandPool_D3D12>(); P->pDxCmdAlloc = allocate_transient_command_allocator(P, queue); return &P->super; } void cgpu_reset_command_pool_d3d12(CGPUCommandPoolId pool) { CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)pool; CHECK_HRESULT(P->pDxCmdAlloc->Reset()); } CGPUCommandBufferId cgpu_create_command_buffer_d3d12(CGPUCommandPoolId pool, const struct CGPUCommandBufferDescriptor* desc) { // initialize to zero CGPUCommandBuffer_D3D12* Cmd = cgpu_new<CGPUCommandBuffer_D3D12>(); CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)pool; CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)P->super.queue; CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)Q->super.device; cgpu_assert(Cmd); // set command pool of new command Cmd->mNodeIndex = SINGLE_GPU_NODE_INDEX; Cmd->mType = Q->super.type; Cmd->pBoundHeaps[0] = D->pCbvSrvUavHeaps[Cmd->mNodeIndex]; Cmd->pBoundHeaps[1] = D->pSamplerHeaps[Cmd->mNodeIndex]; Cmd->pCmdPool = P; uint32_t nodeMask = Cmd->mNodeIndex; ID3D12PipelineState* initialState = NULL; CHECK_HRESULT(D->pDxDevice->CreateCommandList( nodeMask, gDx12CmdTypeTranslator[Cmd->mType], P->pDxCmdAlloc, initialState, __uuidof(Cmd->pDxCmdList), (void**)&(Cmd->pDxCmdList))); // Command lists are addd in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. CHECK_HRESULT(Cmd->pDxCmdList->Close()); return &Cmd->super; } void cgpu_free_command_buffer_d3d12(CGPUCommandBufferId cmd) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd; SAFE_RELEASE(Cmd->pDxCmdList); cgpu_delete(Cmd); } void cgpu_free_command_pool_d3d12(CGPUCommandPoolId pool) { CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)pool; cgpu_assert(pool && "D3D12 ERROR: FREE NULL COMMAND POOL!"); cgpu_assert(P->pDxCmdAlloc && "D3D12 ERROR: FREE NULL pDxCmdAlloc!"); free_transient_command_allocator(P->pDxCmdAlloc); cgpu_delete(P); } // CMDs void cgpu_cmd_begin_d3d12(CGPUCommandBufferId cmd) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd; CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)Cmd->pCmdPool; CHECK_HRESULT(Cmd->pDxCmdList->Reset(P->pDxCmdAlloc, NULL)); if (Cmd->mType != CGPU_QUEUE_TYPE_TRANSFER) { ID3D12DescriptorHeap* heaps[] = { Cmd->pBoundHeaps[0]->pCurrentHeap, Cmd->pBoundHeaps[1]->pCurrentHeap, }; Cmd->pDxCmdList->SetDescriptorHeaps(2, heaps); Cmd->mBoundHeapStartHandles[0] = Cmd->pBoundHeaps[0]->pCurrentHeap->GetGPUDescriptorHandleForHeapStart(); Cmd->mBoundHeapStartHandles[1] = Cmd->pBoundHeaps[1]->pCurrentHeap->GetGPUDescriptorHandleForHeapStart(); } // Reset CPU side data Cmd->pBoundRootSignature = NULL; } // TODO: https://microsoft.github.io/DirectX-Specs/d3d/D3D12EnhancedBarriers.html#introduction // Enhanced Barriers is not currently a hardware or driver requirement void cgpu_cmd_resource_barrier_d3d12(CGPUCommandBufferId cmd, const struct CGPUResourceBarrierDescriptor* desc) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd; const uint32_t barriers_count = desc->buffer_barriers_count + desc->texture_barriers_count; D3D12_RESOURCE_BARRIER* barriers = (D3D12_RESOURCE_BARRIER*)alloca(barriers_count * sizeof(D3D12_RESOURCE_BARRIER)); uint32_t transitionCount = 0; for (uint32_t i = 0; i < desc->buffer_barriers_count; ++i) { const CGPUBufferBarrier* pTransBarrier = &desc->buffer_barriers[i]; D3D12_RESOURCE_BARRIER* pBarrier = &barriers[transitionCount]; CGPUBuffer_D3D12* pBuffer = (CGPUBuffer_D3D12*)pTransBarrier->buffer; if (pBuffer->super.memory_usage == CGPU_MEM_USAGE_GPU_ONLY || pBuffer->super.memory_usage == CGPU_MEM_USAGE_GPU_TO_CPU || (pBuffer->super.memory_usage == CGPU_MEM_USAGE_CPU_TO_GPU && (pBuffer->super.descriptors & CGPU_RESOURCE_TYPE_RW_BUFFER))) { if (CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->src_state && CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->dst_state) { pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; pBarrier->UAV.pResource = pBuffer->pDxResource; ++transitionCount; } else { pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; if (pTransBarrier->d3d12.begin_ony) { pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY; } else if (pTransBarrier->d3d12.end_only) { pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_END_ONLY; } pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; pBarrier->Transition.pResource = pBuffer->pDxResource; pBarrier->Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; if (pTransBarrier->queue_acquire) pBarrier->Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON; else pBarrier->Transition.StateBefore = D3D12Util_TranslateResourceState(pTransBarrier->src_state); if (pTransBarrier->queue_release) pBarrier->Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; else pBarrier->Transition.StateAfter = D3D12Util_TranslateResourceState(pTransBarrier->dst_state); ++transitionCount; } } } for (uint32_t i = 0; i < desc->texture_barriers_count; ++i) { const CGPUTextureBarrier* pTransBarrier = &desc->texture_barriers[i]; D3D12_RESOURCE_BARRIER* pBarrier = &barriers[transitionCount]; CGPUTexture_D3D12* pTexture = (CGPUTexture_D3D12*)pTransBarrier->texture; if (CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->src_state && CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->dst_state) { pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; pBarrier->UAV.pResource = pTexture->pDxResource; ++transitionCount; } else { pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; if (pTransBarrier->d3d12.begin_ony) { pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY; } else if (pTransBarrier->d3d12.end_only) { pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_END_ONLY; } pBarrier->Transition.pResource = pTexture->pDxResource; pBarrier->Transition.Subresource = pTransBarrier->subresource_barrier ? CALC_SUBRESOURCE_INDEX( pTransBarrier->mip_level, pTransBarrier->array_layer, 0, pTexture->super.mip_levels, pTexture->super.array_size_minus_one + 1) : D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; if (pTransBarrier->queue_acquire) pBarrier->Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON; else pBarrier->Transition.StateBefore = D3D12Util_TranslateResourceState(pTransBarrier->src_state); if (pTransBarrier->queue_release) pBarrier->Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; else pBarrier->Transition.StateAfter = D3D12Util_TranslateResourceState(pTransBarrier->dst_state); ++transitionCount; } } if (transitionCount) Cmd->pDxCmdList->ResourceBarrier(transitionCount, barriers); } void cgpu_cmd_begin_query_d3d12(CGPUCommandBufferId cmd, CGPUQueryPoolId pool, const struct CGPUQueryDescriptor* desc) { auto Cmd = (CGPUCommandBuffer_D3D12*)cmd; auto pQueryPool = (CGPUQueryPool_D3D12*)pool; D3D12_QUERY_TYPE type = pQueryPool->mType; switch (type) { case D3D12_QUERY_TYPE_OCCLUSION: case D3D12_QUERY_TYPE_PIPELINE_STATISTICS: case D3D12_QUERY_TYPE_BINARY_OCCLUSION: case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0: case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1: case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2: case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3: break; case D3D12_QUERY_TYPE_TIMESTAMP: Cmd->pDxCmdList->EndQuery(pQueryPool->pDxQueryHeap, type, desc->index); break; } } void cgpu_cmd_end_query_d3d12(CGPUCommandBufferId cmd, CGPUQueryPoolId pool, const struct CGPUQueryDescriptor* desc) { cgpu_cmd_begin_query(cmd, pool, desc); } void cgpu_cmd_reset_query_pool_d3d12(CGPUCommandBufferId, CGPUQueryPoolId, uint32_t, uint32_t) {} void cgpu_cmd_resolve_query_d3d12(CGPUCommandBufferId cmd, CGPUQueryPoolId pool, CGPUBufferId readback, uint32_t start_query, uint32_t query_count) { auto Cmd = (CGPUCommandBuffer_D3D12*)cmd; auto pQueryPool = (CGPUQueryPool_D3D12*)pool; auto pReadbackBuffer = (CGPUBuffer_D3D12*)readback; Cmd->pDxCmdList->ResolveQueryData( pQueryPool->pDxQueryHeap, pQueryPool->mType, start_query, query_count, pReadbackBuffer->pDxResource, start_query * 8); } void cgpu_cmd_end_d3d12(CGPUCommandBufferId cmd) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd; cgpu_assert(Cmd->pDxCmdList); CHECK_HRESULT(Cmd->pDxCmdList->Close()); } // Compute CMDs CGPUComputePassEncoderId cgpu_cmd_begin_compute_pass_d3d12(CGPUCommandBufferId cmd, const struct CGPUComputePassDescriptor* desc) { // DO NOTHING NOW return (CGPUComputePassEncoderId)cmd; } void cgpu_compute_encoder_bind_descriptor_set_d3d12(CGPUComputePassEncoderId encoder, CGPUDescriptorSetId set) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; const CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set; Cmd->pDxCmdList->SetComputeRootDescriptorTable(set->index, { Cmd->mBoundHeapStartHandles[0].ptr + Set->mCbvSrvUavHandle }); } bool reset_root_signature(CGPUCommandBuffer_D3D12* pCmd, ECGPUPipelineType type, ID3D12RootSignature* pRootSignature) { // Set root signature if the current one differs from pRootSignature if (pCmd->pBoundRootSignature != pRootSignature) { pCmd->pBoundRootSignature = pRootSignature; if (type == CGPU_PIPELINE_TYPE_GRAPHICS) pCmd->pDxCmdList->SetGraphicsRootSignature(pRootSignature); else pCmd->pDxCmdList->SetComputeRootSignature(pRootSignature); } return true; } void cgpu_compute_encoder_bind_pipeline_d3d12(CGPUComputePassEncoderId encoder, CGPUComputePipelineId pipeline) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; CGPUComputePipeline_D3D12* PPL = (CGPUComputePipeline_D3D12*)pipeline; reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_COMPUTE, PPL->pRootSignature); Cmd->pDxCmdList->SetPipelineState(PPL->pDxPipelineState); } void cgpu_compute_encoder_push_constants_d3d12(CGPUComputePassEncoderId encoder, CGPURootSignatureId rs, const char8_t* name, const void* data) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)rs; reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_GRAPHICS, RS->pDxRootSignature); if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_GRAPHICS) { Cmd->pDxCmdList->SetGraphicsRoot32BitConstants(RS->mRootParamIndex, RS->mRootConstantParam.Constants.Num32BitValues, data, 0); } else if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_COMPUTE) { Cmd->pDxCmdList->SetComputeRoot32BitConstants(RS->mRootParamIndex, RS->mRootConstantParam.Constants.Num32BitValues, data, 0); } } void cgpu_render_encoder_bind_vertex_buffers_d3d12(CGPURenderPassEncoderId encoder, uint32_t buffer_count, const CGPUBufferId* buffers, const uint32_t* strides, const uint32_t* offsets) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; const CGPUBuffer_D3D12** Buffers = (const CGPUBuffer_D3D12**)buffers; DECLARE_ZERO(D3D12_VERTEX_BUFFER_VIEW, views[CGPU_MAX_VERTEX_ATTRIBS]); for (uint32_t i = 0; i < buffer_count; ++i) { cgpu_assert(D3D12_GPU_VIRTUAL_ADDRESS_NULL != Buffers[i]->mDxGpuAddress); views[i].BufferLocation = (Buffers[i]->mDxGpuAddress + (offsets ? offsets[i] : 0)); views[i].SizeInBytes = (UINT)(Buffers[i]->super.size - (offsets ? offsets[i] : 0)); views[i].StrideInBytes = (UINT)strides[i]; } Cmd->pDxCmdList->IASetVertexBuffers(0, buffer_count, views); } void cgpu_render_encoder_bind_index_buffer_d3d12(CGPURenderPassEncoderId encoder, CGPUBufferId buffer, uint32_t index_stride, uint64_t offset) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; const CGPUBuffer_D3D12* Buffer = (const CGPUBuffer_D3D12*)buffer; cgpu_assert(Cmd); cgpu_assert(buffer); cgpu_assert(CGPU_NULLPTR != Cmd->pDxCmdList); cgpu_assert(CGPU_NULLPTR != Buffer->pDxResource); DECLARE_ZERO(D3D12_INDEX_BUFFER_VIEW, view); view.BufferLocation = Buffer->mDxGpuAddress + offset; view.Format = (sizeof(uint16_t) == index_stride) ? DXGI_FORMAT_R16_UINT : ((sizeof(uint8_t) == index_stride) ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_UINT); view.SizeInBytes = (UINT)(Buffer->super.size - offset); Cmd->pDxCmdList->IASetIndexBuffer(&view); } void cgpu_compute_encoder_dispatch_d3d12(CGPUComputePassEncoderId encoder, uint32_t X, uint32_t Y, uint32_t Z) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; Cmd->pDxCmdList->Dispatch(X, Y, Z); } void cgpu_cmd_end_compute_pass_d3d12(CGPUCommandBufferId cmd, CGPUComputePassEncoderId encoder) { // DO NOTHING NOW } // Render CMDs CGPURenderPassEncoderId cgpu_cmd_begin_render_pass_d3d12(CGPUCommandBufferId cmd, const struct CGPURenderPassDescriptor* desc) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd; #ifdef __ID3D12GraphicsCommandList4_FWD_DEFINED__ ID3D12GraphicsCommandList4* CmdList4 = (ID3D12GraphicsCommandList4*)Cmd->pDxCmdList; DECLARE_ZERO(D3D12_CLEAR_VALUE, clearValues[CGPU_MAX_MRT_COUNT]); DECLARE_ZERO(D3D12_CLEAR_VALUE, clearDepth); DECLARE_ZERO(D3D12_CLEAR_VALUE, clearStencil); DECLARE_ZERO(D3D12_RENDER_PASS_RENDER_TARGET_DESC, renderPassRenderTargetDescs[CGPU_MAX_MRT_COUNT]); DECLARE_ZERO(D3D12_RENDER_PASS_DEPTH_STENCIL_DESC, renderPassDepthStencilDesc); uint32_t colorTargetCount = 0; // color for (uint32_t i = 0; i < desc->render_target_count; i++) { CGPUTextureView_D3D12* TV = (CGPUTextureView_D3D12*)desc->color_attachments[i].view; clearValues[i].Format = DXGIUtil_TranslatePixelFormat(TV->super.info.format); clearValues[i].Color[0] = desc->color_attachments[i].clear_color.r; clearValues[i].Color[1] = desc->color_attachments[i].clear_color.g; clearValues[i].Color[2] = desc->color_attachments[i].clear_color.b; clearValues[i].Color[3] = desc->color_attachments[i].clear_color.a; D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE beginningAccess = gDx12PassBeginOpTranslator[desc->color_attachments[i].load_action]; CGPUTextureView_D3D12* TV_Resolve = (CGPUTextureView_D3D12*)desc->color_attachments[i].resolve_view; if (desc->sample_count != CGPU_SAMPLE_COUNT_1 && TV_Resolve) { CGPUTexture_D3D12* T = (CGPUTexture_D3D12*)TV->super.info.texture; CGPUTexture_D3D12* T_Resolve = (CGPUTexture_D3D12*)TV_Resolve->super.info.texture; D3D12_RENDER_PASS_ENDING_ACCESS_TYPE endingAccess = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE; renderPassRenderTargetDescs[colorTargetCount].cpuDescriptor = TV->mDxRtvDsvDescriptorHandle; renderPassRenderTargetDescs[colorTargetCount].BeginningAccess = { beginningAccess, { clearValues[i] } }; renderPassRenderTargetDescs[colorTargetCount].EndingAccess = { endingAccess, {} }; auto& Resolve = renderPassRenderTargetDescs[colorTargetCount].EndingAccess.Resolve; Resolve.ResolveMode = D3D12_RESOLVE_MODE_AVERAGE; // TODO: int->MODE_MAX Resolve.Format = clearValues[i].Format; Resolve.pSrcResource = T->pDxResource; Resolve.pDstResource = T_Resolve->pDxResource; Cmd->mSubResolveResource.SrcRect = { 0, 0, 0, 0 }; Cmd->mSubResolveResource.DstX = 0; Cmd->mSubResolveResource.DstY = 0; Cmd->mSubResolveResource.SrcSubresource = 0; Cmd->mSubResolveResource.DstSubresource = CALC_SUBRESOURCE_INDEX( 0, 0, 0, T->super.mip_levels, T->super.array_size_minus_one + 1); Resolve.PreserveResolveSource = false; Resolve.SubresourceCount = 1; Resolve.pSubresourceParameters = &Cmd->mSubResolveResource; } else { // Load & Store action D3D12_RENDER_PASS_ENDING_ACCESS_TYPE endingAccess = gDx12PassEndOpTranslator[desc->color_attachments[i].store_action]; renderPassRenderTargetDescs[colorTargetCount].cpuDescriptor = TV->mDxRtvDsvDescriptorHandle; renderPassRenderTargetDescs[colorTargetCount].BeginningAccess = { beginningAccess, { clearValues[i] } }; renderPassRenderTargetDescs[colorTargetCount].EndingAccess = { endingAccess, {} }; } colorTargetCount++; } // depth stencil D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* pRenderPassDepthStencilDesc = nullptr; if (desc->depth_stencil != nullptr && desc->depth_stencil->view != nullptr) { CGPUTextureView_D3D12* DTV = (CGPUTextureView_D3D12*)desc->depth_stencil->view; D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE dBeginingAccess = gDx12PassBeginOpTranslator[desc->depth_stencil->depth_load_action]; D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE sBeginingAccess = gDx12PassBeginOpTranslator[desc->depth_stencil->stencil_load_action]; D3D12_RENDER_PASS_ENDING_ACCESS_TYPE dEndingAccess = gDx12PassEndOpTranslator[desc->depth_stencil->depth_store_action]; D3D12_RENDER_PASS_ENDING_ACCESS_TYPE sEndingAccess = gDx12PassEndOpTranslator[desc->depth_stencil->stencil_store_action]; clearDepth.Format = DXGIUtil_TranslatePixelFormat(desc->depth_stencil->view->info.format); clearDepth.DepthStencil.Depth = desc->depth_stencil->clear_depth; clearStencil.Format = DXGIUtil_TranslatePixelFormat(desc->depth_stencil->view->info.format); clearStencil.DepthStencil.Stencil = desc->depth_stencil->clear_stencil; renderPassDepthStencilDesc.cpuDescriptor = DTV->mDxRtvDsvDescriptorHandle; renderPassDepthStencilDesc.DepthBeginningAccess = { dBeginingAccess, { clearDepth } }; renderPassDepthStencilDesc.DepthEndingAccess = { dEndingAccess }; renderPassDepthStencilDesc.StencilBeginningAccess = { sBeginingAccess, { clearStencil } }; renderPassDepthStencilDesc.StencilEndingAccess = { sEndingAccess }; pRenderPassDepthStencilDesc = &renderPassDepthStencilDesc; } D3D12_RENDER_PASS_RENDER_TARGET_DESC* pRenderPassRenderTargetDesc = renderPassRenderTargetDescs; CmdList4->BeginRenderPass(colorTargetCount, pRenderPassRenderTargetDesc, pRenderPassDepthStencilDesc, D3D12_RENDER_PASS_FLAG_NONE); return (CGPURenderPassEncoderId)&Cmd->super; #endif cgpu_info("ID3D12GraphicsCommandList4 is not defined!"); return (CGPURenderPassEncoderId)&Cmd->super; } void cgpu_render_encoder_bind_descriptor_set_d3d12(CGPURenderPassEncoderId encoder, CGPUDescriptorSetId set) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; const CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set; if (Set->mCbvSrvUavHandle != D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN) { Cmd->pDxCmdList->SetGraphicsRootDescriptorTable(set->index, { Cmd->mBoundHeapStartHandles[0].ptr + Set->mCbvSrvUavHandle }); } else if (Set->mSamplerHandle != D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN) { Cmd->pDxCmdList->SetGraphicsRootDescriptorTable(set->index, { Cmd->mBoundHeapStartHandles[1].ptr + Set->mSamplerHandle }); } } void cgpu_render_encoder_set_viewport_d3d12(CGPURenderPassEncoderId encoder, float x, float y, float width, float height, float min_depth, float max_depth) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; D3D12_VIEWPORT viewport; viewport.TopLeftX = x; viewport.TopLeftY = y; viewport.Width = width; viewport.Height = height; viewport.MinDepth = min_depth; viewport.MaxDepth = max_depth; Cmd->pDxCmdList->RSSetViewports(1, &viewport); } void cgpu_render_encoder_set_scissor_d3d12(CGPURenderPassEncoderId encoder, uint32_t x, uint32_t y, uint32_t width, uint32_t height) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; D3D12_RECT scissor; scissor.left = x; scissor.top = y; scissor.right = x + width; scissor.bottom = y + height; Cmd->pDxCmdList->RSSetScissorRects(1, &scissor); } void cgpu_render_encoder_bind_pipeline_d3d12(CGPURenderPassEncoderId encoder, CGPURenderPipelineId pipeline) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; CGPURenderPipeline_D3D12* PPL = (CGPURenderPipeline_D3D12*)pipeline; reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_GRAPHICS, PPL->pRootSignature); Cmd->pDxCmdList->IASetPrimitiveTopology(PPL->mDxPrimitiveTopology); Cmd->pDxCmdList->SetPipelineState(PPL->pDxPipelineState); } void cgpu_render_encoder_push_constants_d3d12(CGPURenderPassEncoderId encoder, CGPURootSignatureId rs, const char8_t* name, const void* data) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)rs; reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_GRAPHICS, RS->pDxRootSignature); if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_GRAPHICS) { Cmd->pDxCmdList->SetGraphicsRoot32BitConstants(RS->mRootParamIndex, RS->mRootConstantParam.Constants.Num32BitValues, data, 0); } else if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_COMPUTE) { Cmd->pDxCmdList->SetComputeRoot32BitConstants(RS->mRootParamIndex, RS->mRootConstantParam.Constants.Num32BitValues, data, 0); } } void cgpu_render_encoder_draw_d3d12(CGPURenderPassEncoderId encoder, uint32_t vertex_count, uint32_t first_vertex) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; Cmd->pDxCmdList->DrawInstanced((UINT)vertex_count, (UINT)1, (UINT)first_vertex, (UINT)0); } void cgpu_render_encoder_draw_instanced_d3d12(CGPURenderPassEncoderId encoder, uint32_t vertex_count, uint32_t first_vertex, uint32_t instance_count, uint32_t first_instance) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; Cmd->pDxCmdList->DrawInstanced((UINT)vertex_count, (UINT)instance_count, (UINT)first_vertex, (UINT)first_instance); } void cgpu_render_encoder_draw_indexed_d3d12(CGPURenderPassEncoderId encoder, uint32_t index_count, uint32_t first_index, uint32_t first_vertex) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; Cmd->pDxCmdList->DrawIndexedInstanced((UINT)index_count, (UINT)1, (UINT)first_index, (UINT)first_vertex, (UINT)0); } void cgpu_render_encoder_draw_indexed_instanced_d3d12(CGPURenderPassEncoderId encoder, uint32_t index_count, uint32_t first_index, uint32_t instance_count, uint32_t first_instance, uint32_t first_vertex) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder; Cmd->pDxCmdList->DrawIndexedInstanced((UINT)index_count, (UINT)instance_count, (UINT)first_index, (UINT)first_vertex, (UINT)first_instance); } void cgpu_cmd_end_render_pass_d3d12(CGPUCommandBufferId cmd, CGPURenderPassEncoderId encoder) { CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd; #ifdef __ID3D12GraphicsCommandList4_FWD_DEFINED__ ID3D12GraphicsCommandList4* CmdList4 = (ID3D12GraphicsCommandList4*)Cmd->pDxCmdList; CmdList4->EndRenderPass(); return; #endif cgpu_info("ID3D12GraphicsCommandList4 is not defined!"); } // SwapChain APIs CGPUSwapChainId cgpu_create_swapchain_d3d12(CGPUDeviceId device, const CGPUSwapChainDescriptor* desc) { CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)device->adapter->instance; CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device; const uint32_t buffer_count = desc->imageCount; void* Memory = cgpu_calloc(1, sizeof(CGPUSwapChain_D3D12) + sizeof(CGPUTexture_D3D12) * buffer_count + sizeof(CGPUTextureId) * buffer_count); CGPUSwapChain_D3D12* S = cgpu_new_placed<CGPUSwapChain_D3D12>(Memory); S->mDxSyncInterval = desc->enableVsync ? 1 : 0; DECLARE_ZERO(DXGI_SWAP_CHAIN_DESC1, chain_desc1) chain_desc1.Width = desc->width; chain_desc1.Height = desc->height; chain_desc1.Format = DXGIUtil_TranslatePixelFormat(desc->format); chain_desc1.Stereo = false; chain_desc1.SampleDesc.Count = 1; // If multisampling is needed, we'll resolve it later chain_desc1.SampleDesc.Quality = 0; chain_desc1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; chain_desc1.BufferCount = desc->imageCount; chain_desc1.Scaling = DXGI_SCALING_STRETCH; chain_desc1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // for better performance. chain_desc1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; chain_desc1.Flags = 0; BOOL allowTearing = FALSE; I->pDXGIFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing)); chain_desc1.Flags |= allowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0; S->mFlags |= (!desc->enableVsync && allowTearing) ? DXGI_PRESENT_ALLOW_TEARING : 0; IDXGISwapChain1* swapchain; HWND hwnd = (HWND)desc->surface; CGPUQueue_D3D12* Q = CGPU_NULLPTR; if (desc->presentQueues == CGPU_NULLPTR) { Q = (CGPUQueue_D3D12*)cgpu_get_queue_d3d12(device, CGPU_QUEUE_TYPE_GRAPHICS, 0); } else { Q = (CGPUQueue_D3D12*)desc->presentQueues[0]; } auto bCreated = SUCCEEDED(I->pDXGIFactory->CreateSwapChainForHwnd(Q->pCommandQueue, hwnd, &chain_desc1, NULL, NULL, &swapchain)); (void)bCreated; cgpu_assert(bCreated && "Failed to Try to Create SwapChain!"); auto bAssociation = SUCCEEDED(I->pDXGIFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER)); (void)bAssociation; cgpu_assert(bAssociation && "Failed to Try to Associate SwapChain With Window!"); auto bQueryChain3 = SUCCEEDED(swapchain->QueryInterface(IID_PPV_ARGS(&S->pDxSwapChain))); (void)bQueryChain3; cgpu_assert(bQueryChain3 && "Failed to Query IDXGISwapChain3 from Created SwapChain!"); SAFE_RELEASE(swapchain); // Get swapchain images ID3D12Resource** backbuffers = (ID3D12Resource**)alloca(desc->imageCount * sizeof(ID3D12Resource*)); for (uint32_t i = 0; i < desc->imageCount; ++i) { CHECK_HRESULT(S->pDxSwapChain->GetBuffer(i, IID_ARGS(&backbuffers[i]))); } CGPUTexture_D3D12* Ts = (CGPUTexture_D3D12*)(S + 1); for (uint32_t i = 0; i < buffer_count; i++) { Ts[i].pDxResource = backbuffers[i]; Ts[i].pDxAllocation = nullptr; Ts[i].super.is_cube = false; Ts[i].super.array_size_minus_one = 0; Ts[i].super.device = &D->super; Ts[i].super.format = desc->format; Ts[i].super.aspect_mask = 1; Ts[i].super.depth = 1; Ts[i].super.width = desc->width; Ts[i].super.height = desc->height; Ts[i].super.mip_levels = 1; Ts[i].super.node_index = SINGLE_GPU_NODE_INDEX; Ts[i].super.owns_image = false; } CGPUTextureId* Vs = (CGPUTextureId*)(Ts + buffer_count); for (uint32_t i = 0; i < buffer_count; i++) { Vs[i] = &Ts[i].super; } S->super.back_buffers = Vs; S->super.buffer_count = buffer_count; return &S->super; } uint32_t cgpu_acquire_next_image_d3d12(CGPUSwapChainId swapchain, const struct CGPUAcquireNextDescriptor* desc) { CGPUSwapChain_D3D12* S = (CGPUSwapChain_D3D12*)swapchain; // On PC AquireNext is always true HRESULT hr = S_OK; if (FAILED(hr)) { cgpu_error("Failed to acquire next image"); return UINT32_MAX; } return S->pDxSwapChain->GetCurrentBackBufferIndex(); } void cgpu_free_swapchain_d3d12(CGPUSwapChainId swapchain) { CGPUSwapChain_D3D12* S = (CGPUSwapChain_D3D12*)swapchain; for (uint32_t i = 0; i < S->super.buffer_count; i++) { CGPUTexture_D3D12* Texture = (CGPUTexture_D3D12*)S->super.back_buffers[i]; SAFE_RELEASE(Texture->pDxResource); } SAFE_RELEASE(S->pDxSwapChain); cgpu_delete_placed(S); cgpu_free(S); } #include "cgpu/extensions/cgpu_d3d12_exts.h" // extentions CGPUDREDSettingsId cgpu_d3d12_enable_DRED() { CGPUDREDSettingsId settings = cgpu_new<CGPUDREDSettings>(); SUCCEEDED(D3D12GetDebugInterface(__uuidof(settings->pDredSettings), (void**)&(settings->pDredSettings))); // Turn on auto-breadcrumbs and page fault reporting. settings->pDredSettings->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); settings->pDredSettings->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); return settings; } void cgpu_d3d12_disable_DRED(CGPUDREDSettingsId settings) { settings->pDredSettings->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_OFF); settings->pDredSettings->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_OFF); SAFE_RELEASE(settings->pDredSettings); cgpu_delete(settings); }
43.755914
203
0.691532
SakuraEngine
d3efec7cf6ef057849bb9a0cece6b50b8c920a04
8,896
cpp
C++
src/planner/ompl/CRRTConnect.cpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
src/planner/ompl/CRRTConnect.cpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
src/planner/ompl/CRRTConnect.cpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
#include "aikido/planner/ompl/CRRTConnect.hpp" #include <ompl/base/goals/GoalSampleableRegion.h> #include <ompl/tools/config/SelfConfig.h> #include "aikido/planner/ompl/BackwardCompatibility.hpp" #include "aikido/planner/ompl/GeometricStateSpace.hpp" namespace aikido { namespace planner { namespace ompl { //============================================================================== CRRTConnect::CRRTConnect(const ::ompl::base::SpaceInformationPtr& _si) : CRRT(_si, "CRRTConnect"), mConnectionRadius(1e-4) { specs_.recognizedGoal = ::ompl::base::GOAL_SAMPLEABLE_REGION; Planner::declareParam<double>( "connectionRadius", this, &CRRTConnect::setConnectionRadius, &CRRTConnect::getConnectionRadius, "0.:1.:10000."); mConnectionPoint = std::make_pair<::ompl::base::State*, ::ompl::base::State*>( nullptr, nullptr); } //============================================================================== CRRTConnect::~CRRTConnect() { clear(); } //============================================================================== void CRRTConnect::setup() { Planner::setup(); ::ompl::tools::SelfConfig sc(si_, getName()); sc.configurePlannerRange(mMaxDistance); if (!mStartTree) mStartTree.reset(new ::ompl::NearestNeighborsGNAT<Motion*>); if (!mGoalTree) mGoalTree.reset(new ::ompl::NearestNeighborsGNAT<Motion*>); mStartTree->setDistanceFunction(ompl_bind( &CRRTConnect::distanceFunction, this, OMPL_PLACEHOLDER(_1), OMPL_PLACEHOLDER(_2))); mGoalTree->setDistanceFunction(ompl_bind( &CRRTConnect::distanceFunction, this, OMPL_PLACEHOLDER(_1), OMPL_PLACEHOLDER(_2))); } //============================================================================== void CRRTConnect::freeMemory() { CRRT::freeMemory(); if (mGoalTree) { std::vector<Motion*> motions; mGoalTree->list(motions); for (std::size_t i = 0; i < motions.size(); ++i) { if (motions[i]->state) si_->freeState(motions[i]->state); delete motions[i]; } } } //============================================================================== void CRRTConnect::clear() { CRRT::clear(); if (mGoalTree) mGoalTree->clear(); mConnectionPoint = std::make_pair<::ompl::base::State*, ::ompl::base::State*>( nullptr, nullptr); } //============================================================================== void CRRTConnect::setConnectionRadius(double radius) { if (radius > si_->getStateValidityCheckingResolution()) { radius = si_->getStateValidityCheckingResolution(); ::ompl::msg::log( __FILE__, __LINE__, ::ompl::msg::LOG_WARN, "Passed connection radius was too large. Clamped to: %f \n", radius); } mConnectionRadius = radius; } //============================================================================== double CRRTConnect::getConnectionRadius() const { return mConnectionRadius; } //============================================================================== ::ompl::base::PlannerStatus CRRTConnect::solve( const ::ompl::base::PlannerTerminationCondition& _ptc) { checkValidity(); ::ompl::base::GoalSampleableRegion* goal = dynamic_cast<::ompl::base::GoalSampleableRegion*>( pdef_->getGoal().get()); if (!goal) { return ::ompl::base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE; } while (const ::ompl::base::State* st = pis_.nextStart()) { Motion* motion = new Motion(si_); si_->copyState(motion->state, st); mStartTree->add(motion); } if (mStartTree->size() == 0) { return ::ompl::base::PlannerStatus::INVALID_START; } if (!goal->couldSample()) { return ::ompl::base::PlannerStatus::INVALID_GOAL; } if (!mSampler) mSampler = si_->allocStateSampler(); // Extra state used during tree extensions ::ompl::base::State* xstate = si_->allocState(); auto rmotion = std::unique_ptr<Motion>(new Motion(si_)); ::ompl::base::State* rstate = rmotion->state; bool startTree = true; bool solved = false; bool foundgoal = false; while (_ptc == false) { TreeData& tree = startTree ? mStartTree : mGoalTree; TreeData& otherTree = startTree ? mGoalTree : mStartTree; startTree = !startTree; if (mGoalTree->size() == 0 || pis_.getSampledGoalsCount() < mGoalTree->size() / 2) { while (_ptc == false) { const ::ompl::base::State* st = pis_.nextGoal(_ptc); if (si_->isValid(st)) { Motion* motion = new Motion(si_); si_->copyState(motion->state, st); mGoalTree->add(motion); } if (mGoalTree->size() > 0) break; } } // Sample a random state mSampler->sampleUniform(rstate); if (!si_->isValid(rstate)) continue; // Find closest state in tree Motion* nmotion = tree->nearest(rmotion.get()); // Grow one tree toward the random sample double bestdist = std::numeric_limits<double>::infinity(); Motion* lastmotion = constrainedExtend( _ptc, tree, nmotion, rmotion->state, xstate, goal, true, bestdist, foundgoal); if (lastmotion == nmotion) { // trapped continue; } // Now grow the other tree nmotion = otherTree->nearest(lastmotion); Motion* newmotion = constrainedExtend( _ptc, otherTree, nmotion, lastmotion->state, xstate, goal, true, bestdist, foundgoal); Motion* startMotion = startTree ? newmotion : lastmotion; Motion* goalMotion = startTree ? lastmotion : newmotion; double treedist = si_->distance(newmotion->state, lastmotion->state); if (treedist <= mConnectionRadius) { if (treedist < 1e-6) { // The start and goal trees hit the same point, remove one of them // to avoid having a duplicate state on the path if (startMotion->parent) startMotion = startMotion->parent; else goalMotion = goalMotion->parent; } mConnectionPoint = std::make_pair(startMotion->state, goalMotion->state); /* construct the solution path */ Motion* solution = startMotion; std::vector<Motion*> mpath1; while (solution != nullptr) { mpath1.push_back(solution); solution = solution->parent; } solution = goalMotion; std::vector<Motion*> mpath2; while (solution != nullptr) { mpath2.push_back(solution); solution = solution->parent; } // Double check that the start and goal pair are valid if (mpath1.size() > 0 && mpath2.size() > 0) { if (!goal->isStartGoalPairValid( mpath1.front()->state, mpath2.back()->state)) continue; } auto path = ompl_make_shared<::ompl::geometric::PathGeometric>(si_); path->getStates().reserve(mpath1.size() + mpath2.size()); for (int i = mpath1.size() - 1; i >= 0; --i) path->append(mpath1[i]->state); for (std::size_t i = 0; i < mpath2.size(); ++i) path->append(mpath2[i]->state); pdef_->addSolutionPath(path, false, 0.0); solved = true; break; } } si_->freeState(xstate); si_->freeState(rstate); return solved ? ::ompl::base::PlannerStatus::EXACT_SOLUTION : ::ompl::base::PlannerStatus::TIMEOUT; } //============================================================================== void CRRTConnect::getPlannerData(::ompl::base::PlannerData& data) const { Planner::getPlannerData(data); std::vector<Motion*> motions; if (mStartTree) mStartTree->list(motions); for (std::size_t i = 0; i < motions.size(); ++i) { if (motions[i]->parent == nullptr) data.addStartVertex( ::ompl::base::PlannerDataVertex(motions[i]->state, 1)); else { data.addEdge( ::ompl::base::PlannerDataVertex(motions[i]->parent->state, 1), ::ompl::base::PlannerDataVertex(motions[i]->state, 1)); } } motions.clear(); if (mGoalTree) mGoalTree->list(motions); for (std::size_t i = 0; i < motions.size(); ++i) { if (motions[i]->parent == nullptr) { data.addGoalVertex(::ompl::base::PlannerDataVertex(motions[i]->state, 2)); } else { // The edges in the goal tree are reversed to be consistent with start // tree data.addEdge( ::ompl::base::PlannerDataVertex(motions[i]->state, 2), ::ompl::base::PlannerDataVertex(motions[i]->parent->state, 2)); } } // Add the edge connecting the two trees data.addEdge( data.vertexIndex(mConnectionPoint.first), data.vertexIndex(mConnectionPoint.second)); } } // namespace ompl } // namespace planner } // namespace aikido
26.714715
80
0.566996
personalrobotics
1092b1657a3218d559f31ac2e2192c429e0ef5fa
696
hpp
C++
products/PurePhone/services/desktop/endpoints/EndpointFactoryPure.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
products/PurePhone/services/desktop/endpoints/EndpointFactoryPure.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
products/PurePhone/services/desktop/endpoints/EndpointFactoryPure.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <endpoints/EndpointFactory.hpp> namespace sdesktop::endpoints { class EndpointFactoryPure : public EndpointFactory { public: explicit EndpointFactoryPure(EndpointSecurity security); virtual auto create(Context &context, sys::Service *ownerServicePtr) -> std::unique_ptr<Endpoint> override; private: auto constructEndpoint(Context &context, sys::Service *ownerServicePtr) -> std::unique_ptr<Endpoint>; EndpointSecurity endpointSecurity; }; } // namespace sdesktop::endpoints
27.84
115
0.719828
bitigchi
1093df5a6b141d24e5ad3ad314010410788a5e04
395
hpp
C++
tools/csv_command_line/command_line.hpp
dagronf/csvlib
790f48b7bc9d361508ea4b3fc3e9a2c962da0a47
[ "MIT" ]
1
2020-01-20T16:07:12.000Z
2020-01-20T16:07:12.000Z
tools/csv_command_line/command_line.hpp
dagronf/csvlib
790f48b7bc9d361508ea4b3fc3e9a2c962da0a47
[ "MIT" ]
null
null
null
tools/csv_command_line/command_line.hpp
dagronf/csvlib
790f48b7bc9d361508ea4b3fc3e9a2c962da0a47
[ "MIT" ]
null
null
null
// // command_line.hpp // csv_command_line // // Created by Darren Ford on 22/5/19. // Copyright © 2019 Darren Ford. All rights reserved. // #pragma once #include <string> struct Arguments { std::string type; char separator; bool verbose; std::string inputFile; std::string codepage; size_t limit; }; bool handle_command_args(int argc, const char * const * argv, Arguments& args);
17.173913
79
0.706329
dagronf
10956509edab8deef381ffa8a94e0a665183d631
1,452
hpp
C++
include/Entity.hpp
YuanSambo/Aircraft-Shooter
959114a34a25056fbffcfceb785b97a6834a9d97
[ "MIT" ]
null
null
null
include/Entity.hpp
YuanSambo/Aircraft-Shooter
959114a34a25056fbffcfceb785b97a6834a9d97
[ "MIT" ]
null
null
null
include/Entity.hpp
YuanSambo/Aircraft-Shooter
959114a34a25056fbffcfceb785b97a6834a9d97
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////// // Entity.hpp // Aircraft-Shooter // // Created by Yuan Sambo on 28/12/2020 // Based on SFML Game Development Book //////////////////////////////////////////////////////////////// #ifndef AIRCRAFT_SHOOTER_ENTITY_HPP #define AIRCRAFT_SHOOTER_ENTITY_HPP #include "SFML/Graphics.hpp" #include "SceneNode.hpp" ////////////////////////////////////////////// /// \brief Denotes a game element in the world /// ////////////////////////////////////////////// class Entity : public SceneNode{ public: ////////////////////////////////////// /// \brief Sets the Entity's velocity /// /// \param Vector2f velocity /// ////////////////////////////////////// void setVelocity(sf::Vector2f velocity); ////////////////////////////////////// /// \brief Sets the Entity's velocity /// /// \param float velocity x /// \param float velocity y /// ////////////////////////////////////// void setVelocity(float vx, float vy); ////////////////////////////////////// /// \brief Gets the Entity's velocity /// /// \return Vector2f velocity /// ////////////////////////////////////// sf::Vector2f getVelocity() const; void updateCurrent(sf:: Time deltaTime) override; private: sf::Vector2f m_velocity; }; #endif //AIRCRAFT_SHOOTER_ENTITY_HPP
26.888889
68
0.415978
YuanSambo
10959e88987120a76ebf19fef8b6f93f24c8090b
2,839
cpp
C++
plugins/csp-lod-bodies/src/TileId.cpp
FellegaraR/cosmoscout-vr
e04e1ac9c531106693a965bb03d3064f3a6179c6
[ "BSL-1.0", "Apache-2.0", "MIT" ]
302
2019-03-05T08:05:03.000Z
2022-03-16T22:35:21.000Z
plugins/csp-lod-bodies/src/TileId.cpp
Tubbz-alt/cosmoscout-vr
d9fe671857b1ca906febddb59175422fc083441a
[ "BSL-1.0", "Apache-2.0", "MIT" ]
230
2019-07-30T13:26:09.000Z
2022-03-11T11:21:06.000Z
plugins/csp-lod-bodies/src/TileId.cpp
Tubbz-alt/cosmoscout-vr
d9fe671857b1ca906febddb59175422fc083441a
[ "BSL-1.0", "Apache-2.0", "MIT" ]
24
2019-07-22T08:00:49.000Z
2022-01-25T10:55:17.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "TileId.hpp" // This is required for the << operator with const char[] with some MSVC versions. #include <sstream> namespace csp::lodbodies { //////////////////////////////////////////////////////////////////////////////////////////////////// TileId::TileId() = default; //////////////////////////////////////////////////////////////////////////////////////////////////// TileId::TileId(int level, glm::int64 patchIdx) : mPatchIdx(patchIdx) , mLevel(level) { } //////////////////////////////////////////////////////////////////////////////////////////////////// void TileId::reset() { mPatchIdx = -1; mLevel = -1; } //////////////////////////////////////////////////////////////////////////////////////////////////// int TileId::level() const { return mLevel; } //////////////////////////////////////////////////////////////////////////////////////////////////// void TileId::level(int level) { mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////// glm::int64 TileId::patchIdx() const { return mPatchIdx; } //////////////////////////////////////////////////////////////////////////////////////////////////// void TileId::patchIdx(glm::int64 pi) { mPatchIdx = pi; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool isValid(TileId const& tileId) { return (tileId.level() >= 0 && tileId.patchIdx() >= 0); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool isSameLevel(TileId const& lhs, TileId const& rhs) { return (lhs.level() == rhs.level()); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool operator==(TileId const& lhs, TileId const& rhs) { return (lhs.level() == rhs.level() && lhs.patchIdx() == rhs.patchIdx()); } //////////////////////////////////////////////////////////////////////////////////////////////////// // Print Method (not in class) std::ostream& operator<<(std::ostream& os, TileId const& tileId) { os << "(" << tileId.level() << " - " << tileId.patchIdx() << ")"; return os; } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace csp::lodbodies
33.011628
100
0.295879
FellegaraR
1096195661cfd6fa69943b06c55d6b28808debcd
9,036
cpp
C++
src/devices/openxrheadset/impl/OpenXrInterfaceImpl.cpp
ami-iit/yarp-device-openxrheadset
761a290c2c7be65ef142f8a5540f09bcb8d5749c
[ "BSD-2-Clause" ]
1
2022-02-17T08:39:22.000Z
2022-02-17T08:39:22.000Z
src/devices/openxrheadset/impl/OpenXrInterfaceImpl.cpp
ami-iit/yarp-device-openxrheadset
761a290c2c7be65ef142f8a5540f09bcb8d5749c
[ "BSD-2-Clause" ]
1
2022-02-16T17:23:02.000Z
2022-02-16T17:23:02.000Z
src/devices/openxrheadset/impl/OpenXrInterfaceImpl.cpp
ami-iit/yarp-device-openxrheadset
761a290c2c7be65ef142f8a5540f09bcb8d5749c
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * All rights reserved. * * This software may be modified and distributed under the terms of the * BSD-2-Clause license. See the accompanying LICENSE file for details. */ #include <impl/OpenXrInterfaceImpl.h> template<> XrActionType Action<bool>::type() const { return XR_ACTION_TYPE_BOOLEAN_INPUT; } template<> XrActionType Action<float>::type() const { return XR_ACTION_TYPE_FLOAT_INPUT; } template<> XrActionType Action<Eigen::Vector2f>::type() const { return XR_ACTION_TYPE_VECTOR2F_INPUT; } template<> XrResult Action<bool>::update(XrSession session) { XrActionStateBoolean action_state = {.type = XR_TYPE_ACTION_STATE_BOOLEAN, .next = NULL}; XrActionStateGetInfo get_info = {.type = XR_TYPE_ACTION_STATE_GET_INFO, .next = NULL, .action = xrAction, .subactionPath = XR_NULL_PATH}; XrResult output = xrGetActionStateBoolean(session, &get_info, &action_state); value = action_state.currentState; return output; } template<> XrResult Action<float>::update(XrSession session) { XrActionStateFloat action_state = {.type = XR_TYPE_ACTION_STATE_FLOAT, .next = NULL}; XrActionStateGetInfo get_info = {.type = XR_TYPE_ACTION_STATE_GET_INFO, .next = NULL, .action = xrAction, .subactionPath = XR_NULL_PATH}; XrResult output = xrGetActionStateFloat(session, &get_info, &action_state); value = action_state.currentState; return output; } template<> XrResult Action<Eigen::Vector2f>::update(XrSession session) { XrActionStateVector2f action_state = {.type = XR_TYPE_ACTION_STATE_VECTOR2F, .next = NULL}; XrActionStateGetInfo get_info = {.type = XR_TYPE_ACTION_STATE_GET_INFO, .next = NULL, .action = xrAction, .subactionPath = XR_NULL_PATH}; XrResult output = xrGetActionStateVector2f(session, &get_info, &action_state); value[0] = action_state.currentState.x; value[1] = action_state.currentState.y; return output; } void InputActions::clear() { buttons.clear(); axes.clear(); thumbsticks.clear(); } XrBool32 OpenXrInterface::Implementation::OpenXrDebugCallback(XrDebugUtilsMessageSeverityFlagsEXT severity, XrDebugUtilsMessageTypeFlagsEXT, const XrDebugUtilsMessengerCallbackDataEXT *data, void *) { yCTrace(OPENXRHEADSET); if (severity & XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { yCError(OPENXRHEADSET) << data->functionName + std::string(": ") + data->message; } else if (severity & XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { yCWarning(OPENXRHEADSET) << data->functionName + std::string(": ") + data->message; } else if (severity & XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) { yCInfo(OPENXRHEADSET) << data->functionName + std::string(": ") + data->message; } else if (severity & XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) { yCDebug(OPENXRHEADSET) << data->functionName + std::string(": ") + data->message; } return XR_TRUE; } void OpenXrInterface::Implementation::glfwErrorCallback(int error, const char *description) { yCError(OPENXRHEADSET) << "GLFW Error:" << error << description; } void OpenXrInterface::Implementation::GLMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, const GLchar *message, const void *) { yCError(OPENXRHEADSET, "GL CALLBACK: %s source = 0x%x, type = 0x%x, id = 0x%x, severity = 0x%x, message = %s", ( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ), source, type, id, severity, message ); } void OpenXrInterface::Implementation::submitLayer(const XrCompositionLayerBaseHeader *layer) { layer_count++; if (layer_count > submitted_layers.size()) { submitted_layers.resize(layer_count); } submitted_layers[layer_count-1] = layer; } OpenXrInterface::Pose OpenXrInterface::Implementation::getPose(const XrSpaceLocation &spaceLocation) { Pose output; output.positionValid = spaceLocation.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT; output.position = toEigen(spaceLocation.pose.position); output.rotationValid = spaceLocation.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT; output.rotation = toEigen(spaceLocation.pose.orientation); return output; } OpenXrInterface::Velocity OpenXrInterface::Implementation::getVelocity(const XrSpaceVelocity &spaceVelocity) { Velocity output; output.linearValid = spaceVelocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT; output.linear = toEigen(spaceVelocity.linearVelocity); output.angularValid = spaceVelocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT; output.angular = toEigen(spaceVelocity.angularVelocity); return output; } bool OpenXrInterface::Implementation::suggestInteractionProfileBindings(const std::string &interactionProfileName, const std::vector<XrActionSuggestedBinding> &poseBindings, std::initializer_list<std::pair<const char*, const char*>> buttonsList, std::initializer_list<std::pair<const char*, const char*>> axisList, std::initializer_list<std::pair<const char*, const char*>> thumbStickList) { std::vector<XrActionSuggestedBinding> bindings = poseBindings; InputActions& inputsEntry = inputActions[interactionProfileName]; inputsEntry.clear(); for (auto& input : buttonsList) { XrPath path; XrResult result = xrStringToPath(instance, input.first, &path); if (!checkXrOutput(result, "Failed to get path of %s for %s.", input.first, interactionProfileName.c_str())) { return false; } inputsEntry.buttons.emplace_back(); result = inputsEntry.buttons.back().create(actionset, input.second); if (!checkXrOutput(result, "Failed to create action %s for %s.", input.second, interactionProfileName.c_str())) { return false; } bindings.emplace_back(); bindings.back().action = inputsEntry.buttons.back().xrAction; bindings.back().binding = path; } for (auto& input : axisList) { XrPath path; XrResult result = xrStringToPath(instance, input.first, &path); if (!checkXrOutput(result, "Failed to get path of %s for %s.", input.first, interactionProfileName.c_str())) { return false; } inputsEntry.axes.emplace_back(); result = inputsEntry.axes.back().create(actionset, input.second); if (!checkXrOutput(result, "Failed to create action %s for %s.", input.second, interactionProfileName.c_str())) { return false; } bindings.emplace_back(); bindings.back().action = inputsEntry.axes.back().xrAction; bindings.back().binding = path; } for (auto& input : thumbStickList) { XrPath path; XrResult result = xrStringToPath(instance, input.first, &path); if (!checkXrOutput(result, "Failed to get path of %s for %s.", input.first, interactionProfileName.c_str())) { return false; } inputsEntry.thumbsticks.emplace_back(); result = inputsEntry.thumbsticks.back().create(actionset, input.second); if (!checkXrOutput(result, "Failed to create action %s for %s.", input.second, interactionProfileName.c_str())) { return false; } bindings.emplace_back(); bindings.back().action = inputsEntry.thumbsticks.back().xrAction; bindings.back().binding = path; } XrPath interaction_profile_path; XrResult result = xrStringToPath(instance, interactionProfileName.c_str(), &interaction_profile_path); if (!checkXrOutput(result, "Failed to get the path of the interaction profile %s.", interactionProfileName.c_str())) return false; const XrInteractionProfileSuggestedBinding suggested_bindings = { .type = XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, .next = NULL, .interactionProfile = interaction_profile_path, .countSuggestedBindings = static_cast<uint32_t>(bindings.size()), .suggestedBindings = bindings.data()}; result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings); if (!checkXrOutput(result, "Failed to suggest bindings for %s.", interactionProfileName.c_str())) return false; return true; }
37.338843
200
0.655046
ami-iit
10975d2fcaf9023f74f363c7ff3699d11c080ef7
732
hpp
C++
pythran/pythonic/numpy/isposinf.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/isposinf.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/isposinf.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_NUMPY_ISPOSINF_HPP #define PYTHONIC_NUMPY_ISPOSINF_HPP #include "pythonic/include/numpy/isposinf.hpp" #include "pythonic/utils/proxy.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/numexpr_to_ndarray.hpp" #include "pythonic/utils/numpy_traits.hpp" #include <nt2/include/functions/is_inf.hpp> #include <nt2/include/functions/is_positive.hpp> namespace pythonic { namespace numpy { namespace wrapper { template <class T> bool isposinf(T const &t) { return nt2::is_inf(t) and nt2::is_positive(t); } } #define NUMPY_NARY_FUNC_NAME isposinf #define NUMPY_NARY_FUNC_SYM wrapper::isposinf #include "pythonic/types/numpy_nary_expr.hpp" } } #endif
21.529412
54
0.743169
artas360
109b4686956a0e4baf7e56c896321f3ac93c5e8e
3,403
cpp
C++
cflib/net/net_test/http_test.cpp
fishbach/cflib
fa7a69c5962a73cf822435a67207ffc34badd0d4
[ "MIT" ]
null
null
null
cflib/net/net_test/http_test.cpp
fishbach/cflib
fa7a69c5962a73cf822435a67207ffc34badd0d4
[ "MIT" ]
null
null
null
cflib/net/net_test/http_test.cpp
fishbach/cflib
fa7a69c5962a73cf822435a67207ffc34badd0d4
[ "MIT" ]
null
null
null
/* Copyright (C) 2013-2022 Christian Fischbach <cf@cflib.de> * * This file is part of cflib. * * Licensed under the MIT License. */ #include <cflib/net/httpclient.h> #include <cflib/net/httpserver.h> #include <cflib/net/request.h> #include <cflib/net/requesthandler.h> #include <cflib/net/tcpmanager.h> #include <cflib/util/test.h> using namespace cflib::net; namespace { QSemaphore msgSem; QStringList msgs; QMutex mutex; void msg(const QString & msg) { QMutexLocker ml(&mutex); msgs << msg; msgSem.release(); } class TestHdl : public RequestHandler { public: TestHdl() : count_(0) {} protected: virtual void handleRequest(const Request & request) { msg("new request: " + request.getUri()); if (request.getUri() == "/abort") { request.abort(); } else { request.sendText(QString("reply %1").arg(++count_)); } } private: uint count_; }; class TestClient : public HttpClient { public: TestClient(TCPManager & mgr, bool keepAlive) : HttpClient(mgr, keepAlive) {} protected: virtual void reply(const QByteArray & raw) { QByteArray r = raw; r.replace("\r\n" , "|"); msg("http reply: " + r); } }; } class HTTP_Test: public QObject { Q_OBJECT private slots: void test_keepAlive() { TestHdl hdl; HttpServer server; server.registerHandler(hdl); server.start("127.0.0.1", 12301); TCPManager mgr; TestClient cli(mgr, true); cli.get("127.0.0.1", 12301, "/test1"); msgSem.acquire(2); QCOMPARE(msgs.size(), 2); QVERIFY(msgs.contains("new request: /test1")); QVERIFY(!msgs.filter(QRegularExpression( "http reply: HTTP/1.1 200 OK\\|" "Date: .*\\|" "Server: cflib/.*\\|" "Connection: keep-alive\\|" "Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 1" )).isEmpty()); msgs.clear(); cli.get("127.0.0.1", 12301, "/test2"); msgSem.acquire(2); QCOMPARE(msgs.size(), 2); QVERIFY(msgs.contains("new request: /test2")); QVERIFY(!msgs.filter(QRegularExpression( "http reply: HTTP/1.1 200 OK\\|" "Date: .*\\|" "Server: cflib/.*\\|" "Connection: keep-alive\\|" "Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 2" )).isEmpty()); msgs.clear(); cli.get("127.0.0.1", 12301, "/abort"); msgSem.acquire(2); QCOMPARE(msgs.size(), 2); QVERIFY(msgs.contains("new request: /abort")); QVERIFY(msgs.contains("http reply: ")); msgs.clear(); } void test_immediateClose() { TestHdl hdl; HttpServer server; server.registerHandler(hdl); server.start("127.0.0.1", 12301); TCPManager mgr; TestClient cli(mgr, false); cli.get("127.0.0.1", 12301, "/test1"); msgSem.acquire(2); QCOMPARE(msgs.size(), 2); QVERIFY(msgs.contains("new request: /test1")); QVERIFY(!msgs.filter(QRegularExpression( "http reply: HTTP/1.1 200 OK\\|" "Date: .*\\|" "Server: cflib/.*\\|" "Connection: keep-alive\\|" "Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 1" )).isEmpty()); msgs.clear(); cli.get("127.0.0.1", 12301, "/test2"); msgSem.acquire(2); QCOMPARE(msgs.size(), 2); QVERIFY(msgs.contains("new request: /test2")); QVERIFY(!msgs.filter(QRegularExpression( "http reply: HTTP/1.1 200 OK\\|" "Date: .*\\|" "Server: cflib/.*\\|" "Connection: keep-alive\\|" "Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 2" )).isEmpty()); msgs.clear(); } }; #include "http_test.moc" ADD_TEST(HTTP_Test)
21.675159
78
0.646488
fishbach
109babc10e55e7ddeaae9802bb8a6e3516100ea4
31
cpp
C++
SimulationCore/SimulationCore_pcp.cpp
MingAtUWA/SimpleMPM2
7a1d7c257c621123d85a0630e93d42ae25c70fb4
[ "MIT" ]
null
null
null
SimulationCore/SimulationCore_pcp.cpp
MingAtUWA/SimpleMPM2
7a1d7c257c621123d85a0630e93d42ae25c70fb4
[ "MIT" ]
null
null
null
SimulationCore/SimulationCore_pcp.cpp
MingAtUWA/SimpleMPM2
7a1d7c257c621123d85a0630e93d42ae25c70fb4
[ "MIT" ]
null
null
null
#include "SimulationCore_pcp.h"
31
31
0.83871
MingAtUWA
109dba915e4b8c33ae40cebc952c33cd696ec37d
1,310
cpp
C++
src/tools/tools_func/coredump.cpp
JaysonSirius/learning_platform_server
30dc08c54af5e6b04f8392d4d5da54b5497358e9
[ "MIT" ]
null
null
null
src/tools/tools_func/coredump.cpp
JaysonSirius/learning_platform_server
30dc08c54af5e6b04f8392d4d5da54b5497358e9
[ "MIT" ]
null
null
null
src/tools/tools_func/coredump.cpp
JaysonSirius/learning_platform_server
30dc08c54af5e6b04f8392d4d5da54b5497358e9
[ "MIT" ]
null
null
null
/** * @file coredump.cpp * @author 余王亮 (wotsen@outlook.com) * @brief * @version 0.1 * @date 2019-11-04 * * @copyright Copyright (c) 2019 * */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include <sys/resource.h> #include "coredump.h" static const char * const core_format = "core-%e-%p-%t"; /** * @brief Set the up coredump object * * @param path_dir : coredump生成路径 * @param core_size : 文件大小 * @return true : 设置成功 * @return false : 设置失败 */ bool setup_coredump(const char *path_dir, size_t core_size) { struct rlimit rlmt; char core_path[1024]; if (NULL == path_dir) return false; if (getrlimit(RLIMIT_CORE, &rlmt) < 0) { return false; } rlmt.rlim_cur = (rlim_t)core_size; rlmt.rlim_max = (rlim_t)core_size; if (setrlimit(RLIMIT_CORE, &rlmt) < 0) { return false; } if (path_dir[strlen(path_dir) - 1] != '/') { sprintf(core_path, "echo %s/%s > /proc/sys/kernel/core_pattern", path_dir, core_format); } else { sprintf(core_path, "echo %s%s > /proc/sys/kernel/core_pattern", path_dir, core_format); } sprintf(core_path, "echo %s/%s > /proc/sys/kernel/core_pattern", path_dir, core_format); system(core_path); system("echo 1 > /proc/sys/kernel/core_uses_pid"); return true; }
20.46875
90
0.654962
JaysonSirius
10a1d420e7c98dd3d88f4290387f4f6af15ac7ec
447
cpp
C++
Cpp_Workspace/C++ Primer Plus/Chapter05/Chapter5_17.textin2.cpp
agent1894/Quant-Practice-Workspace
f102e136389e2247bbbfb36ef78c16807a0ba7d2
[ "MIT" ]
1
2021-03-17T01:25:05.000Z
2021-03-17T01:25:05.000Z
Cpp_Workspace/C++ Primer Plus/Chapter05/Chapter5_17.textin2.cpp
agent1894/Quant-Practice-Workspace
f102e136389e2247bbbfb36ef78c16807a0ba7d2
[ "MIT" ]
null
null
null
Cpp_Workspace/C++ Primer Plus/Chapter05/Chapter5_17.textin2.cpp
agent1894/Quant-Practice-Workspace
f102e136389e2247bbbfb36ef78c16807a0ba7d2
[ "MIT" ]
2
2020-06-29T15:31:10.000Z
2021-03-24T14:20:15.000Z
// textin2.cpp -- using cin.get(char) #include <iostream> int main() { using namespace std; char ch; int count = 0; cout << "Enter characters: enter # to quit: " << endl; cin.get(ch); // use the cin.get(ch) function while (ch != '#') // test the character { cout << ch; ++count; cin.get(ch); // use it again } cout << endl << count << " characters read" << endl; return 0; }
20.318182
58
0.521253
agent1894
10a3edcc9eac67bd11a34b3db407bee33d9c789c
2,776
cpp
C++
src/public/dt_shared.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/public/dt_shared.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/public/dt_shared.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "dt_shared.h" #if !defined (CLIENT_DLL) #include "sendproxy.h" #else #include "recvproxy.h" #endif // ------------------------------------------------------------------------ // // Just wrappers to make shared code look easier... // ------------------------------------------------------------------------ // // Use these functions to setup your data tables. DataTableProp PropFloat( char *pVarName, // Variable name. int offset, // Offset into container structure. int sizeofVar, int nBits, // Number of bits to use when encoding. int flags, float fLowValue, // For floating point, low and high values. float fHighValue // High value. If HIGH_DEFAULT, it's (1<<nBits). ) { #if !defined (CLIENT_DLL) return SendPropFloat( pVarName, offset, sizeofVar, nBits, flags, fLowValue, fHighValue ); #else return RecvPropFloat( pVarName, offset, sizeofVar, flags ); #endif } DataTableProp PropVector( char *pVarName, int offset, int sizeofVar, int nBits, // Number of bits (for each floating-point component) to use when encoding. int flags, float fLowValue, // For floating point, low and high values. float fHighValue // High value. If HIGH_DEFAULT, it's (1<<nBits). ) { #if !defined (CLIENT_DLL) return SendPropVector( pVarName, offset, sizeofVar, nBits, flags, fLowValue, fHighValue ); #else return RecvPropVector( pVarName, offset, sizeofVar, flags ); #endif } DataTableProp PropAngle( char *pVarName, int offset, int sizeofVar, int nBits, int flags ) { #if !defined (CLIENT_DLL) return SendPropAngle( pVarName, offset, sizeofVar, nBits, flags ); #else return RecvPropFloat( pVarName, offset, sizeofVar, flags ); #endif } DataTableProp PropInt( char *pVarName, int offset, int sizeofVar, // Handled by SENDINFO macro. int nBits, // Set to -1 to automatically pick (max) number of bits based on size of element. int flags, int rightShift ) { #if !defined (CLIENT_DLL) return SendPropInt( pVarName, offset, sizeofVar, nBits, flags, rightShift ); #else return RecvPropInt( pVarName, offset, sizeofVar, flags ); #endif } DataTableProp PropString( char *pVarName, int offset, int bufferLen, int flags ) { #if !defined (CLIENT_DLL) return SendPropString( pVarName, offset, bufferLen, flags ); #else return RecvPropString( pVarName, offset, bufferLen, flags ); #endif } DataTableProp PropEHandle( char *pVarName, int offset, int sizeofVar ) { #if !defined (CLIENT_DLL) return SendPropEHandle( pVarName, offset, sizeofVar ); #else return RecvPropEHandle( pVarName, offset, sizeofVar ); #endif }
24.350877
97
0.65562
cstom4994
10a56f4118a157c8b6e4a2e692e1d9ca02ed8fa5
2,014
cpp
C++
vehicle/src/udp_trans/udp_client_main.cpp
Alvintang6/robot_formation
44017e939cede6bc3e964732511a53eba50544da
[ "MIT" ]
11
2018-10-28T17:51:58.000Z
2022-03-02T22:46:35.000Z
vehicle/src/udp_trans/udp_client_main.cpp
Alvintang6/robot_formation
44017e939cede6bc3e964732511a53eba50544da
[ "MIT" ]
null
null
null
vehicle/src/udp_trans/udp_client_main.cpp
Alvintang6/robot_formation
44017e939cede6bc3e964732511a53eba50544da
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////// // // This is a udp_client node for subscribe the loacl topics and than // send it to the internet. the ip address and the port num should be // configured. // Author: JieTang date: 29/08/2018 // //////////////////////////////////////////////////////// #include "udp_client.h" int main(int argc, char **argv) { ros::init(argc, argv, "multi_udpclt"); ros::NodeHandle nh; Udp_com obj; // import the ip configure from the launch file std::string bot1_ip,bot2_ip,bot3_ip,bot4_ip,laptop_ip; ros::param::get("/robot1_ip",bot1_ip); ros::param::get("/robot2_ip",bot2_ip); ros::param::get("/robot3_ip",bot3_ip); ros::param::get("/robot4_ip",bot4_ip); ros::param::get("/laptop_ip",laptop_ip); ip_list ip; // initial the ip struct for futher use strcpy(ip.robot1,bot1_ip.c_str()); strcpy(ip.robot2,bot2_ip.c_str()); strcpy(ip.robot3,bot3_ip.c_str()); strcpy(ip.robot4,bot4_ip.c_str()); strcpy(ip.laptop,laptop_ip.c_str()); int fd=socket(AF_INET,SOCK_DGRAM,0); if(fd==-1) { perror("socket create error!\n"); exit(-1); } printf("socket fd=%d\n",fd); struct sockaddr_in addr_from; addr_from.sin_family=AF_INET; addr_from.sin_port=htons(0); // get arbitrary port addr_from.sin_addr.s_addr=htons(INADDR_ANY); // get the host ip //const int opt=1; //int nb = 0; //nb=setsockopt(fd,SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt)); //if(nb==-1) //{ //printf("set socket error \n"); //exit(-1); //} int r; r=bind(fd,(struct sockaddr*)&addr_from,sizeof(addr_from)); if(r<0) { perror("bind error! \n"); exit(-1); } struct sockaddr_in addr_to;// addr_to.sin_family=AF_INET; addr_to.sin_port=htons(10278); addr_to.sin_addr.s_addr=inet_addr(ip.robot1); // unicast //addr_to.sin_addr.s_addr=htonl(INADDR_BROADCAST); //broadcast ros::Rate rate(20); while(ros::ok()) { obj.send_udp(fd,addr_to,ip); rate.sleep(); ros::spinOnce(); } } //need function send_udp , callback for imu
19.940594
71
0.64002
Alvintang6
10b12d131d101ddc6f75f76f326892a784392a48
1,550
cpp
C++
Dimik OJ/Array Jot.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Dimik OJ/Array Jot.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Dimik OJ/Array Jot.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
/** * Author: Sohel Rana * Date: 2020-10-23 09:55:34 * Link: link **/ #include <bits/stdc++.h> #define endl '\n' #define db double #define ld long double #define ll long long #define ull unsigned long long #define sqr(x) (x) * (x) #define gcd(a, b) __gcd(a, b) #define lcm(a, b) ((a / gcd(a, b)) * b) #define pf(x) push_front(x) #define pb(x) push_back(x) #define eb(x) emplace_back(x) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define sz(x) (int)x.size() #define debug(x) cerr << #x << " = " << (x) << endl #define debug2(x, y) cerr << #x << " = " << (x) << "," << #y << " = " << (y) << endl #define unsyncIO \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) const ld PI = acos((ld)-1); const int MOD = 1e9 + 7; const ll INF = 1e18; using namespace std; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); //unsyncIO; int t; cin >> t; while (t--) { vector<int> sorted; int n1, n2; cin >> n1; for (int i = 0; i < n1; i++) { int temp; cin >> temp; sorted.eb(temp); } cin >> n2; for (int i = 0; i < n2; i++) { int temp; cin >> temp; sorted.eb(temp); } sort(all(sorted)); cout << sorted[0]; for (int i = 1; i < sz(sorted); i++) { cout << " " << sorted[i]; } cout << endl; } return 0; }
23.134328
84
0.461935
Sohelr360
10b22b40b4b806576d1ba29f4e6f47e5100d9f43
931
hpp
C++
engine/src/ui/DirectionalLayout.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-01T20:22:41.000Z
2021-11-01T20:22:41.000Z
engine/src/ui/DirectionalLayout.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-02T12:45:20.000Z
2021-11-02T12:45:20.000Z
engine/src/ui/DirectionalLayout.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-02T12:28:58.000Z
2021-11-02T12:28:58.000Z
#pragma once #include "ui/Layout.hpp" namespace Birdy3d::ui { class DirectionalLayout : public Layout { public: enum class Direction { RIGHT, LEFT, DOWN, UP }; Direction dir; float gap; bool preserve_child_size; DirectionalLayout() = delete; DirectionalLayout(Direction dir, float gap = 0, bool preserve_child_size = false); void arrange(const std::list<std::shared_ptr<Widget>>& children, glm::vec2 pos, glm::vec2 size) const override; glm::vec2 minimal_size(const std::list<std::shared_ptr<Widget>>& children) const override; private: void arrange_full_size(const std::list<std::shared_ptr<Widget>>& children, glm::vec2 pos, glm::vec2 size) const; void arrange_preserve_size(const std::list<std::shared_ptr<Widget>>& children, glm::vec2 pos, glm::vec2 size) const; }; }
30.032258
124
0.632653
Birdy2014
10b49ca41a7e4de7d320afa83ee46808c8b3b6f0
284
cpp
C++
Source/BYGTextToSpeech/Private/BYGTextToSpeechSettings.cpp
BraceYourselfGames/UE-BYGTextToSpeech
a34abfb53c05c8b59706a8507bd49b6aabbd0f7c
[ "BSD-3-Clause" ]
1
2022-03-21T15:37:29.000Z
2022-03-21T15:37:29.000Z
Source/BYGTextToSpeech/Private/BYGTextToSpeechSettings.cpp
BraceYourselfGames/UE-BYGTextToSpeech
a34abfb53c05c8b59706a8507bd49b6aabbd0f7c
[ "BSD-3-Clause" ]
null
null
null
Source/BYGTextToSpeech/Private/BYGTextToSpeechSettings.cpp
BraceYourselfGames/UE-BYGTextToSpeech
a34abfb53c05c8b59706a8507bd49b6aabbd0f7c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017-2021 Brace Yourself Games. All Rights Reserved. #include "BYGTextToSpeechSettings.h" UBYGTextToSpeechSettings::UBYGTextToSpeechSettings( const FObjectInitializer& ObjectInitializer ) { TextSplitDelimiters = { TEXT( "." ), TEXT( "\r\n" ), TEXT( "\n" ) }; }
21.846154
97
0.721831
BraceYourselfGames
10b4b0917211f374c252f9a399545b0ccfb0c177
10,698
cc
C++
mysql-server/unittest/gunit/handler-t.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/unittest/gunit/handler-t.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/unittest/gunit/handler-t.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2012, 2020, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "unittest/gunit/handler-t.h" #include <stddef.h> #include <sys/types.h> #include "sql/sql_executor.h" #include "unittest/gunit/fake_table.h" #include "unittest/gunit/mock_field_datetime.h" #include "unittest/gunit/test_utils.h" namespace { using my_testing::Mock_error_handler; using my_testing::Server_initializer; using ::testing::StrictMock; class HandlerTest : public ::testing::Test { protected: void SetUp() override { initializer.SetUp(); } void TearDown() override { initializer.TearDown(); } THD *thd() { return initializer.thd(); } Server_initializer initializer; }; /** Some handler error returns are passed on to report_handler_error() which will: - ignore errors like END_OF_FILE - print most errors to the error log - pass the error code back to handler::print_error() */ TEST_F(HandlerTest, ReportErrorHandler) { Mock_field_datetime field_datetime; Fake_TABLE *table = static_cast<Fake_TABLE *>(field_datetime.table); handlerton *hton = nullptr; StrictMock<Mock_HANDLER> mock_handler(hton, table->get_share()); table->set_handler(&mock_handler); // This error should be ignored. EXPECT_EQ(-1, report_handler_error(table, HA_ERR_END_OF_FILE)); // This one should not be printed to stderr, but passed on to the handler. EXPECT_CALL(mock_handler, print_error(HA_ERR_TABLE_DEF_CHANGED, 0)).Times(1); EXPECT_EQ(1, report_handler_error(table, HA_ERR_TABLE_DEF_CHANGED)); } TEST_F(HandlerTest, TableInMemoryEstimate) { Mock_field_datetime field_datetime; Fake_TABLE *table = static_cast<Fake_TABLE *>(field_datetime.table); handlerton *hton = nullptr; StrictMock<Mock_HANDLER> mock_handler(hton, table->get_share()); table->set_handler(&mock_handler); // Verify that the handler does not know the buffer size EXPECT_EQ(mock_handler.get_memory_buffer_size(), -1); /* The implementation of table_in_memory_estimate() assumes that the memory buffer is 100 MB if the storage engine does not report the size of its memory buffer. */ const uint mem_buf_size = 100 * 1024 * 1024; /* Define representative table sizes to use in tests. */ // Table that is less than 20% of memory buffer const uint table_size_small = static_cast<uint>(mem_buf_size * 0.19); // Table that is larger than 20% but less than 100% of memory buffer const uint table_size_medium = mem_buf_size / 2; // Table that is larger than memory buffer const uint table_size_large = mem_buf_size * 2; /* Verify that the default table in memory estimate for a handler has been correctly initialized. */ EXPECT_EQ(mock_handler.stats.table_in_mem_estimate, IN_MEMORY_ESTIMATE_UNKNOWN); /* Test with a table that is less than 20% of memory buffer. This should be entirely in the memory buffer. */ mock_handler.stats.data_file_length = table_size_small; EXPECT_EQ(mock_handler.table_in_memory_estimate(), 1.0); /* Test with a medium sized table that is more than 20% but less than 100% of the memory buffer size. */ mock_handler.stats.data_file_length = table_size_medium; EXPECT_GT(mock_handler.table_in_memory_estimate(), 0.0); EXPECT_LT(mock_handler.table_in_memory_estimate(), 1.0); /* Test with a huge table. This should not be in memory at all. */ mock_handler.stats.data_file_length = table_size_large; EXPECT_EQ(mock_handler.table_in_memory_estimate(), 0.0); /* Simulate that the storage engine has reported that 50 percent of the table is in a memory buffer. */ mock_handler.stats.table_in_mem_estimate = 0.5; /* Set the table size to be less than 20 percent but larger than 10K. */ mock_handler.stats.data_file_length = table_size_small; EXPECT_DOUBLE_EQ(mock_handler.table_in_memory_estimate(), 0.5); /* Set the table size to be larger than 20 percent but less than 100 percent. */ mock_handler.stats.data_file_length = table_size_medium; EXPECT_DOUBLE_EQ(mock_handler.table_in_memory_estimate(), 0.5); /* Set the table size to be larger than the memory buffer. */ mock_handler.stats.data_file_length = table_size_large; EXPECT_DOUBLE_EQ(mock_handler.table_in_memory_estimate(), 0.5); } TEST_F(HandlerTest, IndexInMemoryEstimate) { Mock_field_datetime field_datetime; Fake_TABLE *table = static_cast<Fake_TABLE *>(field_datetime.table); handlerton *hton = nullptr; StrictMock<Mock_HANDLER> mock_handler(hton, table->get_share()); table->set_handler(&mock_handler); mock_handler.change_table_ptr(table, table->get_share()); const uint key_no = 0; // Verify that the handler does not know the buffer size EXPECT_EQ(mock_handler.get_memory_buffer_size(), -1); /* The implementation of index_in_memory_estimate() assumes that the memory buffer is 100 MB if the storage engine does not report the size of its memory buffer. */ const uint mem_buf_size = 100 * 1024 * 1024; /* Define representative table and index sizes to use in tests. */ // Index that is less than 20% of memory buffer const uint index_size_small = static_cast<uint>(mem_buf_size * 0.19); // Index that is larger than 20% but less than 100% of memory buffer const uint index_size_medium = mem_buf_size / 2; // Index that is larger than memory buffer const uint index_size_large = mem_buf_size * 2; // Initialize the estimate for how much of the index that is in memory table->key_info[key_no].set_in_memory_estimate(IN_MEMORY_ESTIMATE_UNKNOWN); /* Test with an index that is less than 20% of memory buffer. This should be entirely in the memory buffer. */ mock_handler.stats.index_file_length = index_size_small; EXPECT_EQ(mock_handler.index_in_memory_estimate(key_no), 1.0); /* Test with a medium sized index that is more than 20% but less than 100% of the memory buffer size. */ mock_handler.stats.index_file_length = index_size_medium; EXPECT_GT(mock_handler.index_in_memory_estimate(key_no), 0.0); EXPECT_LT(mock_handler.index_in_memory_estimate(key_no), 1.0); /* Test with a huge index. This should not be in memory at all. */ mock_handler.stats.index_file_length = index_size_large; EXPECT_EQ(mock_handler.index_in_memory_estimate(key_no), 0.0); /* Simulate that the storage engine has reported that 50 percent of the index is in a memory buffer. */ table->key_info[key_no].set_in_memory_estimate(0.5); /* Set the index size to be less than 20 percent but larger than 10K. */ mock_handler.stats.index_file_length = index_size_small; EXPECT_DOUBLE_EQ(mock_handler.index_in_memory_estimate(key_no), 0.5); /* Set the index size to be larger than 20 percent but less than 100 percent. */ mock_handler.stats.index_file_length = index_size_medium; EXPECT_DOUBLE_EQ(mock_handler.index_in_memory_estimate(key_no), 0.5); /* Set the index size to be larger than the memory buffer. */ mock_handler.stats.index_file_length = index_size_large; EXPECT_DOUBLE_EQ(mock_handler.index_in_memory_estimate(key_no), 0.5); } TEST_F(HandlerTest, SamplingInterfaceAllRows) { Mock_field_datetime field_datetime; Fake_TABLE *table = static_cast<Fake_TABLE *>(field_datetime.table); StrictMock<Mock_SAMPLING_HANDLER> mock_handler(nullptr, table, table->get_share()); table->set_handler(&mock_handler); uchar buffer[8]; void *scan_ctx = nullptr; // rnd_init should be called exactly one time by ha_sample_init. EXPECT_CALL(mock_handler, rnd_init(true)).Times(1); EXPECT_EQ(mock_handler.ha_sample_init(scan_ctx, 100.0, 0, enum_sampling_method::SYSTEM), 0); EXPECT_EQ(mock_handler.inited, handler::SAMPLING); /* Since we have set the sampling rate to 100%, all rows should be returned. Thus, rnd_next should be called exactly as many times as ha_sample_next(). */ const int num_iterations = 100; EXPECT_CALL(mock_handler, rnd_next(buffer)).Times(num_iterations); for (int i = 0; i < num_iterations; ++i) mock_handler.ha_sample_next(scan_ctx, buffer); // rnd_end should be called exactly one time by ha_sample_end. EXPECT_CALL(mock_handler, rnd_end()).Times(1); EXPECT_EQ(mock_handler.ha_sample_end(scan_ctx), 0); EXPECT_EQ(mock_handler.inited, handler::NONE); } TEST_F(HandlerTest, SamplingInterfaceNoRows) { Mock_field_datetime field_datetime; Fake_TABLE *table = reinterpret_cast<Fake_TABLE *>(field_datetime.table); StrictMock<Mock_SAMPLING_HANDLER> mock_handler(nullptr, table, table->get_share()); table->set_handler(&mock_handler); uchar buffer[8]; void *scan_ctx = nullptr; // rnd_init should be called exactly one time by ha_sample_init. EXPECT_CALL(mock_handler, rnd_init(true)).Times(1); EXPECT_EQ(mock_handler.ha_sample_init(scan_ctx, 0.0, 0, enum_sampling_method::SYSTEM), 0); EXPECT_EQ(mock_handler.inited, handler::SAMPLING); /* Since we have set the sampling rate to 0%, no rows should be returned. Thus, rnd_next should never be called. */ EXPECT_CALL(mock_handler, rnd_next(buffer)).Times(0); for (int i = 0; i < 100; ++i) mock_handler.ha_sample_next(scan_ctx, buffer); // rnd_end should be called exactly one time by ha_sample_end. EXPECT_CALL(mock_handler, rnd_end()).Times(1); EXPECT_EQ(mock_handler.ha_sample_end(scan_ctx), 0); EXPECT_EQ(mock_handler.inited, handler::NONE); } } // namespace
36.511945
80
0.736306
silenc3502
10b7c539479e5b49d5c36e86eb4a2c5f81a1ef78
333
cpp
C++
test/ecst/thread_pool/simple.cpp
SuperV1234/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
475
2016-05-03T13:34:30.000Z
2021-11-26T07:02:47.000Z
test/ecst/thread_pool/simple.cpp
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
28
2016-08-30T06:37:40.000Z
2017-11-24T11:14:07.000Z
test/ecst/thread_pool/simple.cpp
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
60
2016-05-11T22:16:15.000Z
2021-08-02T20:42:35.000Z
#include "../../utils/test_utils.hpp" using namespace vrm::core; TEST_MAIN() { std::atomic<int> x{0}; ecst::thread_pool pool; pool.post([&x] { x = 100; }); while(x != 100) { ecst::this_thread::sleep_for(std::chrono::milliseconds(1)); } TEST_ASSERT_NS(x == 100); }
15.136364
67
0.522523
SuperV1234
10b9d44ebf3ad51fc02fc70bd9fbebc6d9dd3cf4
27,874
cpp
C++
bridge/bridge.cpp
LaudateCorpus1/x64dbg_forwarder
de8f45d9434b227a9ce80431fb2190343263cda1
[ "MIT" ]
1
2016-03-25T16:19:55.000Z
2016-03-25T16:19:55.000Z
bridge/bridge.cpp
LaudateCorpus1/x64dbg_forwarder
de8f45d9434b227a9ce80431fb2190343263cda1
[ "MIT" ]
null
null
null
bridge/bridge.cpp
LaudateCorpus1/x64dbg_forwarder
de8f45d9434b227a9ce80431fb2190343263cda1
[ "MIT" ]
3
2016-03-25T16:19:57.000Z
2021-10-15T08:38:51.000Z
#ifdef _WIN64 #pragma comment(linker, "/export:BridgeAlloc=x64bridge.BridgeAlloc") #pragma comment(linker, "/export:BridgeFree=x64bridge.BridgeFree") #pragma comment(linker, "/export:BridgeGetDbgVersion=x64bridge.BridgeGetDbgVersion") #pragma comment(linker, "/export:BridgeInit=x64bridge.BridgeInit") #pragma comment(linker, "/export:BridgeSettingGet=x64bridge.BridgeSettingGet") #pragma comment(linker, "/export:BridgeSettingGetUint=x64bridge.BridgeSettingGetUint") #pragma comment(linker, "/export:BridgeSettingSet=x64bridge.BridgeSettingSet") #pragma comment(linker, "/export:BridgeSettingSetUint=x64bridge.BridgeSettingSetUint") #pragma comment(linker, "/export:BridgeStart=x64bridge.BridgeStart") #pragma comment(linker, "/export:DbgAssembleAt=x64bridge.DbgAssembleAt") #pragma comment(linker, "/export:DbgClearAutoBookmarkRange=x64bridge.DbgClearAutoBookmarkRange") #pragma comment(linker, "/export:DbgClearAutoCommentRange=x64bridge.DbgClearAutoCommentRange") #pragma comment(linker, "/export:DbgClearAutoFunctionRange=x64bridge.DbgClearAutoFunctionRange") #pragma comment(linker, "/export:DbgClearAutoLabelRange=x64bridge.DbgClearAutoLabelRange") #pragma comment(linker, "/export:DbgCmdExec=x64bridge.DbgCmdExec") #pragma comment(linker, "/export:DbgCmdExecDirect=x64bridge.DbgCmdExecDirect") #pragma comment(linker, "/export:DbgDisasmAt=x64bridge.DbgDisasmAt") #pragma comment(linker, "/export:DbgDisasmFastAt=x64bridge.DbgDisasmFastAt") #pragma comment(linker, "/export:DbgExit=x64bridge.DbgExit") #pragma comment(linker, "/export:DbgFunctionAdd=x64bridge.DbgFunctionAdd") #pragma comment(linker, "/export:DbgFunctionDel=x64bridge.DbgFunctionDel") #pragma comment(linker, "/export:DbgFunctionGet=x64bridge.DbgFunctionGet") #pragma comment(linker, "/export:DbgFunctionOverlaps=x64bridge.DbgFunctionOverlaps") #pragma comment(linker, "/export:DbgFunctions=x64bridge.DbgFunctions") #pragma comment(linker, "/export:DbgGetBookmarkAt=x64bridge.DbgGetBookmarkAt") #pragma comment(linker, "/export:DbgGetBpxTypeAt=x64bridge.DbgGetBpxTypeAt") #pragma comment(linker, "/export:DbgGetBranchDestination=x64bridge.DbgGetBranchDestination") #pragma comment(linker, "/export:DbgGetCommentAt=x64bridge.DbgGetCommentAt") #pragma comment(linker, "/export:DbgGetFunctionTypeAt=x64bridge.DbgGetFunctionTypeAt") #pragma comment(linker, "/export:DbgGetLabelAt=x64bridge.DbgGetLabelAt") #pragma comment(linker, "/export:DbgGetLoopTypeAt=x64bridge.DbgGetLoopTypeAt") #pragma comment(linker, "/export:DbgGetModuleAt=x64bridge.DbgGetModuleAt") #pragma comment(linker, "/export:DbgGetRegDump=x64bridge.DbgGetRegDump") #pragma comment(linker, "/export:DbgGetStringAt=x64bridge.DbgGetStringAt") #pragma comment(linker, "/export:DbgInit=x64bridge.DbgInit") #pragma comment(linker, "/export:DbgIsBpDisabled=x64bridge.DbgIsBpDisabled") #pragma comment(linker, "/export:DbgIsDebugging=x64bridge.DbgIsDebugging") #pragma comment(linker, "/export:DbgIsJumpGoingToExecute=x64bridge.DbgIsJumpGoingToExecute") #pragma comment(linker, "/export:DbgIsRunLocked=x64bridge.DbgIsRunLocked") #pragma comment(linker, "/export:DbgIsValidExpression=x64bridge.DbgIsValidExpression") #pragma comment(linker, "/export:DbgLoopAdd=x64bridge.DbgLoopAdd") #pragma comment(linker, "/export:DbgLoopDel=x64bridge.DbgLoopDel") #pragma comment(linker, "/export:DbgLoopGet=x64bridge.DbgLoopGet") #pragma comment(linker, "/export:DbgLoopOverlaps=x64bridge.DbgLoopOverlaps") #pragma comment(linker, "/export:DbgMemFindBaseAddr=x64bridge.DbgMemFindBaseAddr") #pragma comment(linker, "/export:DbgMemGetPageSize=x64bridge.DbgMemGetPageSize") #pragma comment(linker, "/export:DbgMemIsValidReadPtr=x64bridge.DbgMemIsValidReadPtr") #pragma comment(linker, "/export:DbgMemMap=x64bridge.DbgMemMap") #pragma comment(linker, "/export:DbgMemRead=x64bridge.DbgMemRead") #pragma comment(linker, "/export:DbgMemWrite=x64bridge.DbgMemWrite") #pragma comment(linker, "/export:DbgMenuEntryClicked=x64bridge.DbgMenuEntryClicked") #pragma comment(linker, "/export:DbgModBaseFromName=x64bridge.DbgModBaseFromName") #pragma comment(linker, "/export:DbgScriptAbort=x64bridge.DbgScriptAbort") #pragma comment(linker, "/export:DbgScriptBpGet=x64bridge.DbgScriptBpGet") #pragma comment(linker, "/export:DbgScriptBpToggle=x64bridge.DbgScriptBpToggle") #pragma comment(linker, "/export:DbgScriptCmdExec=x64bridge.DbgScriptCmdExec") #pragma comment(linker, "/export:DbgScriptGetBranchInfo=x64bridge.DbgScriptGetBranchInfo") #pragma comment(linker, "/export:DbgScriptGetLineType=x64bridge.DbgScriptGetLineType") #pragma comment(linker, "/export:DbgScriptLoad=x64bridge.DbgScriptLoad") #pragma comment(linker, "/export:DbgScriptRun=x64bridge.DbgScriptRun") #pragma comment(linker, "/export:DbgScriptSetIp=x64bridge.DbgScriptSetIp") #pragma comment(linker, "/export:DbgScriptStep=x64bridge.DbgScriptStep") #pragma comment(linker, "/export:DbgScriptUnload=x64bridge.DbgScriptUnload") #pragma comment(linker, "/export:DbgSetAutoBookmarkAt=x64bridge.DbgSetAutoBookmarkAt") #pragma comment(linker, "/export:DbgSetAutoCommentAt=x64bridge.DbgSetAutoCommentAt") #pragma comment(linker, "/export:DbgSetAutoFunctionAt=x64bridge.DbgSetAutoFunctionAt") #pragma comment(linker, "/export:DbgSetAutoLabelAt=x64bridge.DbgSetAutoLabelAt") #pragma comment(linker, "/export:DbgSetBookmarkAt=x64bridge.DbgSetBookmarkAt") #pragma comment(linker, "/export:DbgSetCommentAt=x64bridge.DbgSetCommentAt") #pragma comment(linker, "/export:DbgSetLabelAt=x64bridge.DbgSetLabelAt") #pragma comment(linker, "/export:DbgSettingsUpdated=x64bridge.DbgSettingsUpdated") #pragma comment(linker, "/export:DbgStackCommentGet=x64bridge.DbgStackCommentGet") #pragma comment(linker, "/export:DbgSymbolEnum=x64bridge.DbgSymbolEnum") #pragma comment(linker, "/export:DbgValFromString=x64bridge.DbgValFromString") #pragma comment(linker, "/export:DbgValToString=x64bridge.DbgValToString") #pragma comment(linker, "/export:DbgWinEvent=x64bridge.DbgWinEvent") #pragma comment(linker, "/export:DbgWinEventGlobal=x64bridge.DbgWinEventGlobal") #pragma comment(linker, "/export:GuiAddLogMessage=x64bridge.GuiAddLogMessage") #pragma comment(linker, "/export:GuiAddRecentFile=x64bridge.GuiAddRecentFile") #pragma comment(linker, "/export:GuiAddStatusBarMessage=x64bridge.GuiAddStatusBarMessage") #pragma comment(linker, "/export:GuiAutoCompleteAddCmd=x64bridge.GuiAutoCompleteAddCmd") #pragma comment(linker, "/export:GuiAutoCompleteClearAll=x64bridge.GuiAutoCompleteClearAll") #pragma comment(linker, "/export:GuiAutoCompleteDelCmd=x64bridge.GuiAutoCompleteDelCmd") #pragma comment(linker, "/export:GuiDisasmAt=x64bridge.GuiDisasmAt") #pragma comment(linker, "/export:GuiDumpAt=x64bridge.GuiDumpAt") #pragma comment(linker, "/export:GuiGetDisassembly=x64bridge.GuiGetDisassembly") #pragma comment(linker, "/export:GuiGetLineWindow=x64bridge.GuiGetLineWindow") #pragma comment(linker, "/export:GuiGetWindowHandle=x64bridge.GuiGetWindowHandle") #pragma comment(linker, "/export:GuiLoadSourceFile=x64bridge.GuiLoadSourceFile") #pragma comment(linker, "/export:GuiLogClear=x64bridge.GuiLogClear") #pragma comment(linker, "/export:GuiMenuAdd=x64bridge.GuiMenuAdd") #pragma comment(linker, "/export:GuiMenuAddEntry=x64bridge.GuiMenuAddEntry") #pragma comment(linker, "/export:GuiMenuAddSeparator=x64bridge.GuiMenuAddSeparator") #pragma comment(linker, "/export:GuiMenuClear=x64bridge.GuiMenuClear") #pragma comment(linker, "/export:GuiReferenceAddColumn=x64bridge.GuiReferenceAddColumn") #pragma comment(linker, "/export:GuiReferenceDeleteAllColumns=x64bridge.GuiReferenceDeleteAllColumns") #pragma comment(linker, "/export:GuiReferenceGetCellContent=x64bridge.GuiReferenceGetCellContent") #pragma comment(linker, "/export:GuiReferenceGetRowCount=x64bridge.GuiReferenceGetRowCount") #pragma comment(linker, "/export:GuiReferenceInitialize=x64bridge.GuiReferenceInitialize") #pragma comment(linker, "/export:GuiReferenceReloadData=x64bridge.GuiReferenceReloadData") #pragma comment(linker, "/export:GuiReferenceSetCellContent=x64bridge.GuiReferenceSetCellContent") #pragma comment(linker, "/export:GuiReferenceSetProgress=x64bridge.GuiReferenceSetProgress") #pragma comment(linker, "/export:GuiReferenceSetRowCount=x64bridge.GuiReferenceSetRowCount") #pragma comment(linker, "/export:GuiReferenceSetSearchStartCol=x64bridge.GuiReferenceSetSearchStartCol") #pragma comment(linker, "/export:GuiReferenceSetSingleSelection=x64bridge.GuiReferenceSetSingleSelection") #pragma comment(linker, "/export:GuiRepaintTableView=x64bridge.GuiRepaintTableView") #pragma comment(linker, "/export:GuiScriptAdd=x64bridge.GuiScriptAdd") #pragma comment(linker, "/export:GuiScriptClear=x64bridge.GuiScriptClear") #pragma comment(linker, "/export:GuiScriptEnableHighlighting=x64bridge.GuiScriptEnableHighlighting") #pragma comment(linker, "/export:GuiScriptError=x64bridge.GuiScriptError") #pragma comment(linker, "/export:GuiScriptMessage=x64bridge.GuiScriptMessage") #pragma comment(linker, "/export:GuiScriptMsgyn=x64bridge.GuiScriptMsgyn") #pragma comment(linker, "/export:GuiScriptSetInfoLine=x64bridge.GuiScriptSetInfoLine") #pragma comment(linker, "/export:GuiScriptSetIp=x64bridge.GuiScriptSetIp") #pragma comment(linker, "/export:GuiScriptSetTitle=x64bridge.GuiScriptSetTitle") #pragma comment(linker, "/export:GuiSelectionGet=x64bridge.GuiSelectionGet") #pragma comment(linker, "/export:GuiSelectionSet=x64bridge.GuiSelectionSet") #pragma comment(linker, "/export:GuiSetDebugState=x64bridge.GuiSetDebugState") #pragma comment(linker, "/export:GuiSetLastException=x64bridge.GuiSetLastException") #pragma comment(linker, "/export:GuiStackDumpAt=x64bridge.GuiStackDumpAt") #pragma comment(linker, "/export:GuiSymbolLogAdd=x64bridge.GuiSymbolLogAdd") #pragma comment(linker, "/export:GuiSymbolLogClear=x64bridge.GuiSymbolLogClear") #pragma comment(linker, "/export:GuiSymbolRefreshCurrent=x64bridge.GuiSymbolRefreshCurrent") #pragma comment(linker, "/export:GuiSymbolSetProgress=x64bridge.GuiSymbolSetProgress") #pragma comment(linker, "/export:GuiSymbolUpdateModuleList=x64bridge.GuiSymbolUpdateModuleList") #pragma comment(linker, "/export:GuiUpdateAllViews=x64bridge.GuiUpdateAllViews") #pragma comment(linker, "/export:GuiUpdateBreakpointsView=x64bridge.GuiUpdateBreakpointsView") #pragma comment(linker, "/export:GuiUpdateCallStack=x64bridge.GuiUpdateCallStack") #pragma comment(linker, "/export:GuiUpdateDisassemblyView=x64bridge.GuiUpdateDisassemblyView") #pragma comment(linker, "/export:GuiUpdateDumpView=x64bridge.GuiUpdateDumpView") #pragma comment(linker, "/export:GuiUpdateMemoryView=x64bridge.GuiUpdateMemoryView") #pragma comment(linker, "/export:GuiUpdatePatches=x64bridge.GuiUpdatePatches") #pragma comment(linker, "/export:GuiUpdateRegisterView=x64bridge.GuiUpdateRegisterView") #pragma comment(linker, "/export:GuiUpdateSideBar=x64bridge.GuiUpdateSideBar") #pragma comment(linker, "/export:GuiUpdateThreadView=x64bridge.GuiUpdateThreadView") #pragma comment(linker, "/export:GuiUpdateWindowTitle=x64bridge.GuiUpdateWindowTitle") #else //x86 #pragma comment(linker, "/export:BridgeAlloc=x32bridge.BridgeAlloc") #pragma comment(linker, "/export:BridgeFree=x32bridge.BridgeFree") #pragma comment(linker, "/export:BridgeGetDbgVersion=x32bridge.BridgeGetDbgVersion") #pragma comment(linker, "/export:BridgeInit=x32bridge.BridgeInit") #pragma comment(linker, "/export:BridgeSettingGet=x32bridge.BridgeSettingGet") #pragma comment(linker, "/export:BridgeSettingGetUint=x32bridge.BridgeSettingGetUint") #pragma comment(linker, "/export:BridgeSettingSet=x32bridge.BridgeSettingSet") #pragma comment(linker, "/export:BridgeSettingSetUint=x32bridge.BridgeSettingSetUint") #pragma comment(linker, "/export:BridgeStart=x32bridge.BridgeStart") #pragma comment(linker, "/export:DbgAssembleAt=x32bridge.DbgAssembleAt") #pragma comment(linker, "/export:DbgClearAutoBookmarkRange=x32bridge.DbgClearAutoBookmarkRange") #pragma comment(linker, "/export:DbgClearAutoCommentRange=x32bridge.DbgClearAutoCommentRange") #pragma comment(linker, "/export:DbgClearAutoFunctionRange=x32bridge.DbgClearAutoFunctionRange") #pragma comment(linker, "/export:DbgClearAutoLabelRange=x32bridge.DbgClearAutoLabelRange") #pragma comment(linker, "/export:DbgCmdExec=x32bridge.DbgCmdExec") #pragma comment(linker, "/export:DbgCmdExecDirect=x32bridge.DbgCmdExecDirect") #pragma comment(linker, "/export:DbgDisasmAt=x32bridge.DbgDisasmAt") #pragma comment(linker, "/export:DbgDisasmFastAt=x32bridge.DbgDisasmFastAt") #pragma comment(linker, "/export:DbgExit=x32bridge.DbgExit") #pragma comment(linker, "/export:DbgFunctionAdd=x32bridge.DbgFunctionAdd") #pragma comment(linker, "/export:DbgFunctionDel=x32bridge.DbgFunctionDel") #pragma comment(linker, "/export:DbgFunctionGet=x32bridge.DbgFunctionGet") #pragma comment(linker, "/export:DbgFunctionOverlaps=x32bridge.DbgFunctionOverlaps") #pragma comment(linker, "/export:DbgFunctions=x32bridge.DbgFunctions") #pragma comment(linker, "/export:DbgGetBookmarkAt=x32bridge.DbgGetBookmarkAt") #pragma comment(linker, "/export:DbgGetBpxTypeAt=x32bridge.DbgGetBpxTypeAt") #pragma comment(linker, "/export:DbgGetBranchDestination=x32bridge.DbgGetBranchDestination") #pragma comment(linker, "/export:DbgGetCommentAt=x32bridge.DbgGetCommentAt") #pragma comment(linker, "/export:DbgGetFunctionTypeAt=x32bridge.DbgGetFunctionTypeAt") #pragma comment(linker, "/export:DbgGetLabelAt=x32bridge.DbgGetLabelAt") #pragma comment(linker, "/export:DbgGetLoopTypeAt=x32bridge.DbgGetLoopTypeAt") #pragma comment(linker, "/export:DbgGetModuleAt=x32bridge.DbgGetModuleAt") #pragma comment(linker, "/export:DbgGetRegDump=x32bridge.DbgGetRegDump") #pragma comment(linker, "/export:DbgGetStringAt=x32bridge.DbgGetStringAt") #pragma comment(linker, "/export:DbgInit=x32bridge.DbgInit") #pragma comment(linker, "/export:DbgIsBpDisabled=x32bridge.DbgIsBpDisabled") #pragma comment(linker, "/export:DbgIsDebugging=x32bridge.DbgIsDebugging") #pragma comment(linker, "/export:DbgIsJumpGoingToExecute=x32bridge.DbgIsJumpGoingToExecute") #pragma comment(linker, "/export:DbgIsRunLocked=x32bridge.DbgIsRunLocked") #pragma comment(linker, "/export:DbgIsValidExpression=x32bridge.DbgIsValidExpression") #pragma comment(linker, "/export:DbgLoopAdd=x32bridge.DbgLoopAdd") #pragma comment(linker, "/export:DbgLoopDel=x32bridge.DbgLoopDel") #pragma comment(linker, "/export:DbgLoopGet=x32bridge.DbgLoopGet") #pragma comment(linker, "/export:DbgLoopOverlaps=x32bridge.DbgLoopOverlaps") #pragma comment(linker, "/export:DbgMemFindBaseAddr=x32bridge.DbgMemFindBaseAddr") #pragma comment(linker, "/export:DbgMemGetPageSize=x32bridge.DbgMemGetPageSize") #pragma comment(linker, "/export:DbgMemIsValidReadPtr=x32bridge.DbgMemIsValidReadPtr") #pragma comment(linker, "/export:DbgMemMap=x32bridge.DbgMemMap") #pragma comment(linker, "/export:DbgMemRead=x32bridge.DbgMemRead") #pragma comment(linker, "/export:DbgMemWrite=x32bridge.DbgMemWrite") #pragma comment(linker, "/export:DbgMenuEntryClicked=x32bridge.DbgMenuEntryClicked") #pragma comment(linker, "/export:DbgModBaseFromName=x32bridge.DbgModBaseFromName") #pragma comment(linker, "/export:DbgScriptAbort=x32bridge.DbgScriptAbort") #pragma comment(linker, "/export:DbgScriptBpGet=x32bridge.DbgScriptBpGet") #pragma comment(linker, "/export:DbgScriptBpToggle=x32bridge.DbgScriptBpToggle") #pragma comment(linker, "/export:DbgScriptCmdExec=x32bridge.DbgScriptCmdExec") #pragma comment(linker, "/export:DbgScriptGetBranchInfo=x32bridge.DbgScriptGetBranchInfo") #pragma comment(linker, "/export:DbgScriptGetLineType=x32bridge.DbgScriptGetLineType") #pragma comment(linker, "/export:DbgScriptLoad=x32bridge.DbgScriptLoad") #pragma comment(linker, "/export:DbgScriptRun=x32bridge.DbgScriptRun") #pragma comment(linker, "/export:DbgScriptSetIp=x32bridge.DbgScriptSetIp") #pragma comment(linker, "/export:DbgScriptStep=x32bridge.DbgScriptStep") #pragma comment(linker, "/export:DbgScriptUnload=x32bridge.DbgScriptUnload") #pragma comment(linker, "/export:DbgSetAutoBookmarkAt=x32bridge.DbgSetAutoBookmarkAt") #pragma comment(linker, "/export:DbgSetAutoCommentAt=x32bridge.DbgSetAutoCommentAt") #pragma comment(linker, "/export:DbgSetAutoFunctionAt=x32bridge.DbgSetAutoFunctionAt") #pragma comment(linker, "/export:DbgSetAutoLabelAt=x32bridge.DbgSetAutoLabelAt") #pragma comment(linker, "/export:DbgSetBookmarkAt=x32bridge.DbgSetBookmarkAt") #pragma comment(linker, "/export:DbgSetCommentAt=x32bridge.DbgSetCommentAt") #pragma comment(linker, "/export:DbgSetLabelAt=x32bridge.DbgSetLabelAt") #pragma comment(linker, "/export:DbgSettingsUpdated=x32bridge.DbgSettingsUpdated") #pragma comment(linker, "/export:DbgStackCommentGet=x32bridge.DbgStackCommentGet") #pragma comment(linker, "/export:DbgSymbolEnum=x32bridge.DbgSymbolEnum") #pragma comment(linker, "/export:DbgValFromString=x32bridge.DbgValFromString") #pragma comment(linker, "/export:DbgValToString=x32bridge.DbgValToString") #pragma comment(linker, "/export:DbgWinEvent=x32bridge.DbgWinEvent") #pragma comment(linker, "/export:DbgWinEventGlobal=x32bridge.DbgWinEventGlobal") #pragma comment(linker, "/export:GuiAddLogMessage=x32bridge.GuiAddLogMessage") #pragma comment(linker, "/export:GuiAddRecentFile=x32bridge.GuiAddRecentFile") #pragma comment(linker, "/export:GuiAddStatusBarMessage=x32bridge.GuiAddStatusBarMessage") #pragma comment(linker, "/export:GuiAutoCompleteAddCmd=x32bridge.GuiAutoCompleteAddCmd") #pragma comment(linker, "/export:GuiAutoCompleteClearAll=x32bridge.GuiAutoCompleteClearAll") #pragma comment(linker, "/export:GuiAutoCompleteDelCmd=x32bridge.GuiAutoCompleteDelCmd") #pragma comment(linker, "/export:GuiDisasmAt=x32bridge.GuiDisasmAt") #pragma comment(linker, "/export:GuiDumpAt=x32bridge.GuiDumpAt") #pragma comment(linker, "/export:GuiGetDisassembly=x32bridge.GuiGetDisassembly") #pragma comment(linker, "/export:GuiGetLineWindow=x32bridge.GuiGetLineWindow") #pragma comment(linker, "/export:GuiGetWindowHandle=x32bridge.GuiGetWindowHandle") #pragma comment(linker, "/export:GuiLoadSourceFile=x32bridge.GuiLoadSourceFile") #pragma comment(linker, "/export:GuiLogClear=x32bridge.GuiLogClear") #pragma comment(linker, "/export:GuiMenuAdd=x32bridge.GuiMenuAdd") #pragma comment(linker, "/export:GuiMenuAddEntry=x32bridge.GuiMenuAddEntry") #pragma comment(linker, "/export:GuiMenuAddSeparator=x32bridge.GuiMenuAddSeparator") #pragma comment(linker, "/export:GuiMenuClear=x32bridge.GuiMenuClear") #pragma comment(linker, "/export:GuiReferenceAddColumn=x32bridge.GuiReferenceAddColumn") #pragma comment(linker, "/export:GuiReferenceDeleteAllColumns=x32bridge.GuiReferenceDeleteAllColumns") #pragma comment(linker, "/export:GuiReferenceGetCellContent=x32bridge.GuiReferenceGetCellContent") #pragma comment(linker, "/export:GuiReferenceGetRowCount=x32bridge.GuiReferenceGetRowCount") #pragma comment(linker, "/export:GuiReferenceInitialize=x32bridge.GuiReferenceInitialize") #pragma comment(linker, "/export:GuiReferenceReloadData=x32bridge.GuiReferenceReloadData") #pragma comment(linker, "/export:GuiReferenceSetCellContent=x32bridge.GuiReferenceSetCellContent") #pragma comment(linker, "/export:GuiReferenceSetProgress=x32bridge.GuiReferenceSetProgress") #pragma comment(linker, "/export:GuiReferenceSetRowCount=x32bridge.GuiReferenceSetRowCount") #pragma comment(linker, "/export:GuiReferenceSetSearchStartCol=x32bridge.GuiReferenceSetSearchStartCol") #pragma comment(linker, "/export:GuiReferenceSetSingleSelection=x32bridge.GuiReferenceSetSingleSelection") #pragma comment(linker, "/export:GuiRepaintTableView=x32bridge.GuiRepaintTableView") #pragma comment(linker, "/export:GuiScriptAdd=x32bridge.GuiScriptAdd") #pragma comment(linker, "/export:GuiScriptClear=x32bridge.GuiScriptClear") #pragma comment(linker, "/export:GuiScriptEnableHighlighting=x32bridge.GuiScriptEnableHighlighting") #pragma comment(linker, "/export:GuiScriptError=x32bridge.GuiScriptError") #pragma comment(linker, "/export:GuiScriptMessage=x32bridge.GuiScriptMessage") #pragma comment(linker, "/export:GuiScriptMsgyn=x32bridge.GuiScriptMsgyn") #pragma comment(linker, "/export:GuiScriptSetInfoLine=x32bridge.GuiScriptSetInfoLine") #pragma comment(linker, "/export:GuiScriptSetIp=x32bridge.GuiScriptSetIp") #pragma comment(linker, "/export:GuiScriptSetTitle=x32bridge.GuiScriptSetTitle") #pragma comment(linker, "/export:GuiSelectionGet=x32bridge.GuiSelectionGet") #pragma comment(linker, "/export:GuiSelectionSet=x32bridge.GuiSelectionSet") #pragma comment(linker, "/export:GuiSetDebugState=x32bridge.GuiSetDebugState") #pragma comment(linker, "/export:GuiSetLastException=x32bridge.GuiSetLastException") #pragma comment(linker, "/export:GuiStackDumpAt=x32bridge.GuiStackDumpAt") #pragma comment(linker, "/export:GuiSymbolLogAdd=x32bridge.GuiSymbolLogAdd") #pragma comment(linker, "/export:GuiSymbolLogClear=x32bridge.GuiSymbolLogClear") #pragma comment(linker, "/export:GuiSymbolRefreshCurrent=x32bridge.GuiSymbolRefreshCurrent") #pragma comment(linker, "/export:GuiSymbolSetProgress=x32bridge.GuiSymbolSetProgress") #pragma comment(linker, "/export:GuiSymbolUpdateModuleList=x32bridge.GuiSymbolUpdateModuleList") #pragma comment(linker, "/export:GuiUpdateAllViews=x32bridge.GuiUpdateAllViews") #pragma comment(linker, "/export:GuiUpdateBreakpointsView=x32bridge.GuiUpdateBreakpointsView") #pragma comment(linker, "/export:GuiUpdateCallStack=x32bridge.GuiUpdateCallStack") #pragma comment(linker, "/export:GuiUpdateDisassemblyView=x32bridge.GuiUpdateDisassemblyView") #pragma comment(linker, "/export:GuiUpdateDumpView=x32bridge.GuiUpdateDumpView") #pragma comment(linker, "/export:GuiUpdateMemoryView=x32bridge.GuiUpdateMemoryView") #pragma comment(linker, "/export:GuiUpdatePatches=x32bridge.GuiUpdatePatches") #pragma comment(linker, "/export:GuiUpdateRegisterView=x32bridge.GuiUpdateRegisterView") #pragma comment(linker, "/export:GuiUpdateSideBar=x32bridge.GuiUpdateSideBar") #pragma comment(linker, "/export:GuiUpdateThreadView=x32bridge.GuiUpdateThreadView") #pragma comment(linker, "/export:GuiUpdateWindowTitle=x32bridge.GuiUpdateWindowTitle") #endif //_WIN64 //Fixes for https://github.com/x64dbg/x64dbg/issues/1202 #include <windows.h> #define MAX_THREAD_NAME_SIZE 256 #define MAX_BREAKPOINT_SIZE 256 #define MAX_MODULE_SIZE 256 #define MAX_CONDITIONAL_EXPR_SIZE 256 #define MAX_CONDITIONAL_TEXT_SIZE 256 typedef ULONG_PTR duint; typedef enum { _PriorityIdle = -15, _PriorityAboveNormal = 1, _PriorityBelowNormal = -1, _PriorityHighest = 2, _PriorityLowest = -2, _PriorityNormal = 0, _PriorityTimeCritical = 15, _PriorityUnknown = 0x7FFFFFFF } THREADPRIORITY; typedef enum { _Executive = 0, _FreePage = 1, _PageIn = 2, _PoolAllocation = 3, _DelayExecution = 4, _Suspended = 5, _UserRequest = 6, _WrExecutive = 7, _WrFreePage = 8, _WrPageIn = 9, _WrPoolAllocation = 10, _WrDelayExecution = 11, _WrSuspended = 12, _WrUserRequest = 13, _WrEventPair = 14, _WrQueue = 15, _WrLpcReceive = 16, _WrLpcReply = 17, _WrVirtualMemory = 18, _WrPageOut = 19, _WrRendezvous = 20, _Spare2 = 21, _Spare3 = 22, _Spare4 = 23, _Spare5 = 24, _WrCalloutStack = 25, _WrKernel = 26, _WrResource = 27, _WrPushLock = 28, _WrMutex = 29, _WrQuantumEnd = 30, _WrDispatchInt = 31, _WrPreempted = 32, _WrYieldExecution = 33, _WrFastMutex = 34, _WrGuardedMutex = 35, _WrRundown = 36, } THREADWAITREASON; typedef enum { bp_none = 0, bp_normal = 1, bp_hardware = 2, bp_memory = 4 } BPXTYPE; typedef struct { int ThreadNumber; HANDLE Handle; DWORD ThreadId; duint ThreadStartAddress; duint ThreadLocalBase; char threadName[MAX_THREAD_NAME_SIZE]; } THREADINFO; typedef struct { THREADINFO BasicInfo; duint ThreadCip; DWORD SuspendCount; THREADPRIORITY Priority; THREADWAITREASON WaitReason; DWORD LastError; } THREADALLINFO; typedef struct { int count; THREADALLINFO* list; int CurrentThread; } THREADLIST; typedef struct { THREADINFO BasicInfo; duint ThreadCip; DWORD SuspendCount; THREADPRIORITY Priority; THREADWAITREASON WaitReason; DWORD LastError; FILETIME UserTime; FILETIME KernelTime; FILETIME CreationTime; ULONG64 Cycles; // Windows Vista or greater } THREADALLINFOEX; typedef struct { int count; THREADALLINFOEX* list; int CurrentThread; } THREADLISTEX; typedef struct { BPXTYPE type; duint addr; bool enabled; bool singleshoot; bool active; char name[MAX_BREAKPOINT_SIZE]; char mod[MAX_MODULE_SIZE]; unsigned short slot; } BRIDGEBP; typedef struct { int count; BRIDGEBP* bp; } BPMAP; typedef struct { BPXTYPE type; duint addr; bool enabled; bool singleshoot; bool active; char name[MAX_BREAKPOINT_SIZE]; char mod[MAX_MODULE_SIZE]; unsigned short slot; unsigned int hitCount; bool fastResume; bool silent; char breakCondition[MAX_CONDITIONAL_EXPR_SIZE]; char logText[MAX_CONDITIONAL_TEXT_SIZE]; char logCondition[MAX_CONDITIONAL_EXPR_SIZE]; char commandText[MAX_CONDITIONAL_TEXT_SIZE]; char commandCondition[MAX_CONDITIONAL_EXPR_SIZE]; } BRIDGEBPEX; typedef struct { int count; BRIDGEBPEX* bp; } BPMAPEX; typedef void* (*BRIDGEALLOC)(duint); typedef void (*BRIDGEFREE)(void*); typedef void (*DBGGETTHREADLISTEX)(THREADLISTEX*); typedef int (*DBGGETBPLISTEX)(BPXTYPE, BPMAPEX*); extern "C" __declspec(dllexport) void DbgGetThreadList(THREADLIST* list) { #ifdef _WIN64 static HMODULE hBridge = LoadLibraryW(L"x64bridge.dll"); #else static HMODULE hBridge = LoadLibraryW(L"x32bridge.dll"); #endif //_WIN64 static DBGGETTHREADLISTEX DbgGetThreadListEx = (DBGGETTHREADLISTEX)GetProcAddress(hBridge, "DbgGetThreadList"); static BRIDGEALLOC BridgeAlloc = (BRIDGEALLOC)GetProcAddress(hBridge, "BridgeAlloc"); static BRIDGEFREE BridgeFree = (BRIDGEFREE)GetProcAddress(hBridge, "BridgeFree"); THREADLISTEX listEx; DbgGetThreadListEx(&listEx); list->count = listEx.count; if(list->count <= 0) return; list->list = (THREADALLINFO*)BridgeAlloc(list->count * sizeof(THREADALLINFO)); for(int i = 0; i < list->count; i++) for(size_t j = 0; j < sizeof(THREADALLINFO); j++) ((unsigned char*)&list->list[i])[j] = ((unsigned char*)&listEx.list[i])[j]; BridgeFree(listEx.list); list->CurrentThread = listEx.CurrentThread; } extern "C" __declspec(dllexport) int DbgGetBpList(BPXTYPE type, BPMAP* list) { #ifdef _WIN64 static HMODULE hBridge = LoadLibraryW(L"x64bridge.dll"); #else static HMODULE hBridge = LoadLibraryW(L"x32bridge.dll"); #endif //_WIN64 static DBGGETBPLISTEX DbgGetBpListEx = (DBGGETBPLISTEX)GetProcAddress(hBridge, "DbgGetBpList"); static BRIDGEALLOC BridgeAlloc = (BRIDGEALLOC)GetProcAddress(hBridge, "BridgeAlloc"); static BRIDGEFREE BridgeFree = (BRIDGEFREE)GetProcAddress(hBridge, "BridgeFree"); BPMAPEX listEx; DbgGetBpListEx(type, &listEx); list->count = listEx.count; if(!list->count) return 0; list->bp = (BRIDGEBP*)BridgeAlloc(list->count * sizeof(BRIDGEBP)); for(int i = 0; i < list->count; i++) for(size_t j = 0; j < sizeof(BRIDGEBP); j++) ((unsigned char*)&list->bp[i])[j] = ((unsigned char*)&listEx.bp[i])[j]; BridgeFree(listEx.bp); return list->count; }
56.654472
116
0.79515
LaudateCorpus1
10c01195375074ef2a0404288f0413d48492d8b0
1,387
cpp
C++
day17.cpp
anshd258/100days-of-code
512d3c30f64aad0621bc64a337e4fcffce567265
[ "MIT" ]
4
2020-11-13T12:27:52.000Z
2021-12-25T18:36:14.000Z
day17.cpp
anshd258/100days-of-code
512d3c30f64aad0621bc64a337e4fcffce567265
[ "MIT" ]
3
2020-11-27T11:15:08.000Z
2020-12-14T03:38:58.000Z
day17.cpp
anshd258/100days-of-code
512d3c30f64aad0621bc64a337e4fcffce567265
[ "MIT" ]
null
null
null
// day 16 solution of 100 -days - of -codding cpp //jamal erabaki //control git end #include <iostream> using namespace std; int ap(int a,int b) { if(a==0) //main recrussion function return b; return ap(b%a,a); } /*here it takes for ex 42%56,56 which will result in 42,56 then agin function is called this time a is 42 and b is56 which ressult in 0,42 so 42 will be returned*/ int main() { int result,n; int *arr = new(nothrow) int[n]; //allocated array in heap if(!arr) { cout<<"memory allocation failed"<<endl; system("pause"); exit(0); } //exit the program if program is unable to allocate memory else { cout<<"enter the nof of elements you want to enter \n"; cin>>n; cout<<"enter the elements\n"; for(int j=0;j<n;j++) { cin>>arr[j]; } //takin array elements result=arr[0]; for (int i = 1; i < n; i++) { result=ap(arr[i],result); //result called our recrussion function } } cout <<"result is" <<result<< endl; //result output delete[] arr; system("pause"); //deleting allocated memory return 0; }
21.671875
105
0.495314
anshd258
10c853d29d9dca04d538e48f3dbf2436ef17c469
7,096
cxx
C++
external/fltk-2.0.x-r5966/src/fillrect.cxx
jturner65/ParticleSim
0ad72630c6c417a924833c4d5955d6daa902fbe8
[ "Apache-2.0" ]
1
2018-06-10T11:35:32.000Z
2018-06-10T11:35:32.000Z
external/fltk-2.0.x-r5966/src/fillrect.cxx
jturner65/ParticleSim
0ad72630c6c417a924833c4d5955d6daa902fbe8
[ "Apache-2.0" ]
1
2020-04-03T12:46:17.000Z
2020-04-03T12:46:17.000Z
external/fltk-2.0.x-r5966/src/fillrect.cxx
jturner65/ParticleSim
0ad72630c6c417a924833c4d5955d6daa902fbe8
[ "Apache-2.0" ]
null
null
null
// // "$Id: fillrect.cxx 5887 2007-06-07 12:36:39Z spitzak $" // // Non-path routines from draw.h that are used by the standard boxtypes // and thus are always linked into an fltk program. // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". // #include <config.h> #include <fltk/draw.h> #include <fltk/x.h> #include <fltk/math.h> using namespace fltk; /*! Fill the rectangle with the current color. */ void fltk::fillrect(int x, int y, int w, int h) { if (w <= 0 || h <= 0) return; transform(x,y,w,h); #if USE_CAIRO cairo_rectangle(cc,x,y,w,h); cairo_fill(cc); #elif USE_X11 if (w && h) XFillRectangle(xdisplay, xwindow, gc, x, y, w, h); #elif defined(_WIN32) RECT rect; rect.left = x; rect.top = y; rect.right = x+w; rect.bottom = y+h; SetBkColor(dc, current_xpixel); ExtTextOut(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); #elif USE_QUARTZ if (!line_width_) CGContextSetShouldAntialias(quartz_gc, false); CGRect rect = CGRectMake(x, y, w-1, h-1); CGContextFillRect(quartz_gc, rect); if (!line_width_) CGContextSetShouldAntialias(quartz_gc, true); #else # error #endif } /*! Draw a line \e inside this bounding box (currently correct only for 0-thickness lines). */ void fltk::strokerect(int x, int y, int w, int h) { if (w <= 0 || h <= 0) return; transform(x,y,w,h); #if USE_CAIRO cairo_rectangle(cc,x+.5,y+.5,w-1,h-1); cairo_stroke(cc); #elif USE_X11 if (w && h) XDrawRectangle(xdisplay, xwindow, gc, x, y, w-1, h-1); else XDrawLine(xdisplay, xwindow, gc, x, y, x+w, y+h); #elif defined(_WIN32) setpen(); POINT pts[4]; pts[0].x = pts[3].x = x; pts[0].y = pts[1].y = y; pts[1].x = pts[2].x = x+w-1; pts[2].y = pts[3].y = y+h-1; static const BYTE i[4] = {PT_MOVETO, PT_LINETO, PT_LINETO, PT_LINETO|PT_CLOSEFIGURE}; PolyDraw(dc, pts, i, 4); #elif USE_QUARTZ if (!line_width_) CGContextSetShouldAntialias(quartz_gc, false); CGRect rect = CGRectMake(x, y, w-1, h-1); CGContextStrokeRect(quartz_gc, rect); if (!line_width_) CGContextSetShouldAntialias(quartz_gc, true); #else # error #endif } /*! Draw a straight line between the two points. If line_width() is zero, this tries to draw as though a 1x1 square pen is moved between the first centers of pixels to the lower-right of the start and end points. Thus if y==y1 this will fill a rectangle with the corners x,y and x1+1,y+1. This may be 1 wider than you expect, but is necessary for compatability with previous fltk versions (and is due to the original X11 behavior). If line_width() is not zero then the results depend on the back end. It also may not produce consistent results if the ctm is not an integer translation or if the line is not horizontal or vertical. */ void fltk::drawline(int x, int y, int x1, int y1) { transform(x,y); transform(x1,y1); #if USE_CAIRO // attempt to emulate the X11 drawing if line_width is zero. It also // works to set the end caps to square and add .5 in all cases... if (line_width_) { cairo_move_to(cc, x, y); cairo_line_to(cc, x1, y1); } else { cairo_move_to(cc, x+.5, y+.5); cairo_line_to(cc, x1+.5, y1+.5); } cairo_stroke(cc); #elif USE_QUARTZ // This appears to produce the same output as X11, though it is unclear // why, as the line caps are butt by default: if (( x==x1 || y==y1 ) && !line_width_ ) CGContextSetShouldAntialias(quartz_gc, false); CGContextMoveToPoint(quartz_gc, x, y); CGContextAddLineToPoint(quartz_gc, x1, y1); CGContextStrokePath(quartz_gc); if (!line_width_) CGContextSetShouldAntialias(quartz_gc, true); #elif USE_X11 XDrawLine(xdisplay, xwindow, gc, x, y, x1, y1); #elif defined(_WIN32) setpen(); MoveToEx(dc, x, y, 0L); LineTo(dc, x1, y1); // GDI does butt end caps (sort of, it just truncates the drawing // with horizontal or vertical lines depending on the slope). This // adds an extra pixel to emulate the X11 drawing. if (!line_width_) SetPixel(dc, x1, y1, current_xpixel); #else # error #endif } /*! Draw a straight line between the two points. */ void fltk::drawline(float x, float y, float x1, float y1) { transform(x,y); transform(x1,y1); #if USE_CAIRO if (line_width_) { cairo_move_to(cc, x, y); cairo_line_to(cc, x1, y1); } else { cairo_move_to(cc, x+.5, y+.5); cairo_line_to(cc, x1+.5, y1+.5); } cairo_stroke(cc); # elif USE_QUARTZ if (( x==x1 || y==y1 ) && !line_width_ ) CGContextSetShouldAntialias(quartz_gc, false); CGContextMoveToPoint(quartz_gc, x, y); CGContextAddLineToPoint(quartz_gc, x1, y1); CGContextStrokePath(quartz_gc); if (!line_width_) CGContextSetShouldAntialias(quartz_gc, true); #else int X = int(floorf(x)+.5); int Y = int(floorf(y)+.5); int X1 = int(floorf(x1)+.5); int Y1 = int(floorf(y1)+.5); # if USE_X11 XDrawLine(xdisplay, xwindow, gc, X, Y, X1, Y1); # elif defined(_WIN32) setpen(); MoveToEx(dc, X, Y, 0L); LineTo(dc, X1, Y1); if (!line_width_) SetPixel(dc, X1, Y1, current_xpixel); # else # error # endif #endif } /*! Draw a dot at the given point. If line_width() is zero this is a single pixel to the lower-right of x,y. If line_width() is non-zero this is a dot drawn with the current pen and line caps. */ void fltk::drawpoint(int x, int y) { if (!line_width_) { transform(x,y); #if USE_CAIRO fillrect(x,y,1,1); #elif USE_X11 XDrawPoint(xdisplay, xwindow, gc, x, y); #elif defined(_WIN32) SetPixel(dc, x, y, current_xpixel); #else fillrect(x,y,1,1); #endif } else { drawline(x,y,x,y); } } /*! Draw a dot at the given point. If line_width() is zero this is the single pixel containing X,Y, or the one to the lower-right if X and Y transform to integers. If line_width() is non-zero this is a dot drawn with the current pen and line caps (currently draws nothing in some api's unless the line_style has CAP_ROUND). */ void fltk::drawpoint(float X, float Y) { if (!line_width_) { transform(X,Y); int x = int(floorf(X)); int y = int(floorf(Y)); #if USE_CAIRO fillrect(x,y,1,1); #elif USE_X11 XDrawPoint(xdisplay, xwindow, gc, x, y); # elif defined(_WIN32) SetPixel(dc, x, y, current_xpixel); # else fillrect(x,y,1,1); #endif } else { drawline(X,Y,X,Y); } } // // End of "$Id: fillrect.cxx 5887 2007-06-07 12:36:39Z spitzak $". //
31.259912
73
0.683766
jturner65
10c8df646f1b6b9041b6dc95bb621d5c74212cb7
629
cpp
C++
SPOJ/ALCHE - Alchemy/alche.cpp
Zubieta/CPP
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
8
2017-03-02T07:56:45.000Z
2021-08-07T20:20:19.000Z
SPOJ/ALCHE - Alchemy/alche.cpp
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
null
null
null
SPOJ/ALCHE - Alchemy/alche.cpp
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
1
2021-08-07T20:20:20.000Z
2021-08-07T20:20:20.000Z
/*Santiago Zubieta*/ #include <iostream> #include <numeric> #include <fstream> #include <climits> #include <cstring> #include <cstdio> #include <cmath> #include <queue> #include <list> #include <map> #include <set> #include <stack> #include <deque> #include <vector> #include <string> #include <cstdlib> #include <cassert> #include <sstream> #include <iterator> #include <algorithm> using namespace std; int main(){ long double a,b; scanf("%Lf%Lf",&a,&b); while(a+b>=0){ if(a/b==(long double)1000.0/(long double)37.0){ printf("Y\n"); } else{ printf("N\n"); } scanf("%Lf%Lf",&a,&b); } }
17
49
0.627981
Zubieta
10ce4ff1216c79b166008cff80bad07e51574063
5,093
cpp
C++
PhysicsTools/Utilities/test/testIntegralTiming.cpp
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
PhysicsTools/Utilities/test/testIntegralTiming.cpp
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
PhysicsTools/Utilities/test/testIntegralTiming.cpp
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "PhysicsTools/Utilities/interface/Integral.h" #include <iostream> #include <cmath> #include <vector> #include <utility> #include <algorithm> #include <sys/time.h> #include "TCanvas.h" #include "TGraph.h" #include "TAxis.h" #include "TROOT.h" #include "TH2.h" using namespace funct; using namespace std; double getTime() { struct timeval t; if(gettimeofday(&t,0)<0) abort(); return (double)t.tv_sec + (double(t.tv_usec) * 1E-6); } struct gauss { static const double c; double operator()(double x) const { return c * exp(- x*x); } }; const double gauss::c = 2./sqrt(M_PI); struct gauss1 : public gauss { }; struct gauss2 : public gauss { }; struct gauss3 : public gauss { }; struct gauss4 : public gauss { }; struct gaussPrimitive { double operator()(double x) const { return erf(x); } }; NUMERICAL_FUNCT_INTEGRAL(gauss1, TrapezoidIntegrator); NUMERICAL_FUNCT_INTEGRAL(gauss2, GaussLegendreIntegrator); NUMERICAL_FUNCT_INTEGRAL(gauss3, GaussIntegrator); NUMERICAL_FUNCT_INTEGRAL(gauss4, RootIntegrator); template<typename G, typename I> pair<double, double> check(const G& g, const I& i) { gaussPrimitive pr; double xMax = 1; double i0 = pr(xMax); double t0, t1; t0 = getTime(); double i1 = integral_f(g, 0, xMax, i); t1 = getTime(); pair<double, double> p = make_pair(t1 - t0, fabs(i1 - i0)); cout << ">>> time: " << p.first << ", accuracy: " << p.second << endl; return p; } int main() { gauss1 g1; gauss2 g2; gauss3 g3; gauss4 g4; cout << ">>> Trapezoidal integration" << endl; vector<pair<double, double> > t; for(size_t i = 2; i < 20; i += 1) { TrapezoidIntegrator i1(i); t.push_back(check(g1, i1)); } for(size_t i = 20; i < 1000; i += 20) { TrapezoidIntegrator i1(i); t.push_back(check(g1, i1)); } cout << ">>> Gauss Legendre integration" << endl; vector<pair<double, double> > l; for(size_t i = 1; i < 20; i += 1) { GaussLegendreIntegrator i2(i, 1.e-5); l.push_back(check(g2, i2)); } for(size_t i = 20; i < 1000; i += 20) { GaussLegendreIntegrator i2(i, 1.e-5); l.push_back(check(g2, i2)); } cout << ">>> Gauss integration" << endl; vector<pair<double, double> > g; for(double e = 100; e > 1.e-5; e /= 2) { GaussIntegrator i3(e); g.push_back(check(g3, i3)); } cout << ">>> ROOT GSL integration" << endl; vector<pair<double, double> > r; for(double e = 100; e > 1.e-5; e /= 2) { RootIntegrator i4(ROOT::Math::IntegrationOneDim::kADAPTIVESINGULAR, e, e); r.push_back(check(g4, i4)); } gROOT->SetStyle("Plain"); TCanvas canvas; canvas.SetLogx(); canvas.SetLogy(); double xMin = 1e6, xMax = 0, yMin = 1e6, yMax = 0; size_t nt = t.size(); double * xt = new double[nt], * yt = new double[nt]; const double xAbsMin = 1e-10, yAbsMin = 1e-10; for(size_t i = 0; i < nt; ++i) { xt[i] = t[i].first; yt[i] = t[i].second; if(xt[i] < xAbsMin) xt[i] = xAbsMin; if(yt[i] < yAbsMin) yt[i] = yAbsMin; if(xMin > xt[i]) xMin = xt[i]; if(xMax < xt[i]) xMax = xt[i]; if(yMin > yt[i]) yMin = yt[i]; if(yMax < yt[i]) yMax = yt[i]; } size_t nl = l.size(); double * xl = new double[nl], * yl = new double[nl]; for(size_t i = 0; i < nl; ++i) { xl[i] = l[i].first; yl[i] = l[i].second; if(xl[i] < xAbsMin) xl[i] = xAbsMin; if(yl[i] < yAbsMin) yl[i] = yAbsMin; if(xMin > xl[i]) xMin = xl[i]; if(xMax < xl[i]) xMax = xl[i]; if(yMin > yl[i]) yMin = yl[i]; if(yMax < yl[i]) yMax = yl[i]; } size_t ng = g.size(); double * xg = new double[ng], * yg = new double[ng]; for(size_t i = 0; i < ng; ++i) { xg[i] = g[i].first; yg[i] = g[i].second; if(xg[i] < xAbsMin) xg[i] = xAbsMin; if(yg[i] < yAbsMin) yg[i] = yAbsMin; if(xMin > xg[i]) xMin = xg[i]; if(xMax < xg[i]) xMax = xg[i]; if(yMin > yg[i]) yMin = yg[i]; if(yMax < yg[i]) yMax = yg[i]; } size_t nr = r.size(); double * xr = new double[nr], * yr = new double[nr]; for(size_t i = 0; i < nr; ++i) { xr[i] = r[i].first; yr[i] = r[i].second; if(xr[i] < xAbsMin) xr[i] = xAbsMin; if(yr[i] < yAbsMin) yr[i] = yAbsMin; if(xMin > xr[i]) xMin = xr[i]; if(xMax < xr[i]) xMax = xr[i]; if(yMin > yr[i]) yMin = yr[i]; if(yMax < yr[i]) yMax = yr[i]; } TH2F frame("frame", "Red: T, Blue: G-L, Green: G, Black: GSL", 1, xMin, xMax, 1, yMin, yMax); frame.GetXaxis()->SetTitle("CPU time (sec)"); frame.GetYaxis()->SetTitle("Accuracy"); frame.Draw(); TGraph gt(nt, xt, yt), gl(nl, xl, yl), gg(ng, xg, yg), gr(nr, xr, yr); gt.SetMarkerStyle(21); gt.SetLineWidth(3); gt.SetLineColor(kRed); gl.SetMarkerStyle(21); gl.SetLineWidth(3); gl.SetLineColor(kBlue); gg.SetMarkerStyle(21); gg.SetLineWidth(3); gg.SetLineColor(kGreen); gr.SetMarkerStyle(21); gr.SetLineWidth(3); gr.SetLineColor(kBlack); gt.Draw("PC"); gl.Draw("PC"); gg.Draw("PC"); gr.Draw("PC"); canvas.SaveAs("integralTiming.eps"); delete [] xt; delete [] yt; delete [] xl; delete [] yl; delete [] xg; delete [] yg; delete [] xr; delete [] yr; return 0; }
27.52973
95
0.591007
nistefan
10ce5b4e4ea51817ffa4e14d9741233ecd67cd0d
8,681
cc
C++
cxx/hex.cc
ross-alexander/lizards
7329e754b3d8622fc202bc480fc5422dafd62a5d
[ "Apache-2.0" ]
null
null
null
cxx/hex.cc
ross-alexander/lizards
7329e754b3d8622fc202bc480fc5422dafd62a5d
[ "Apache-2.0" ]
null
null
null
cxx/hex.cc
ross-alexander/lizards
7329e754b3d8622fc202bc480fc5422dafd62a5d
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libxml/tree.h> #include <libxml/xpath.h> #include <libxml++/libxml++.h> #include "lizards.h" hex_t::hex_t(void) { owner = 0; terrain = WATER; // adjlist = new adjacent_t[DIRECTIONS]; #ifndef STL flistlen = 0; flist = 0; #endif title = 0; }; hex_t::~hex_t(void) { // debug.log("~hex_t(%p %s)", this, title); clear_features(); } void hex_t::set(int x_p, int y_p) { xy.x = x_p; xy.y = y_p; }; hex_t* hex_t::adjacent(const char *dir) { int d = (int)dir_t(dir); if (d < 0) return NULL; else return adjacent(d); } hex_t& hex_t::operator=(hex_t& h) { owner = h.owner; terrain = h.terrain; // undisturbed = h.undisturbed; xy = h.xy; title = strdup(h.title); // for (int i = 0; i < DIRECTIONS; i++) // { // adjlist[i].xy = h.adjlist[i].xy; // adjlist[i].hex = NULL; // } #ifdef STL for (unsigned i = 0; i < h.fv.size(); i++) fv.push_back(h.fv[i]->clone()); #else flistlen = h.flistlen; flist = new feature_t*[flistlen]; for (int i = 0; i < flistlen; i++) if (h.flist[i]) flist[i] = h.flist[i]->clone(); else flist[i] = 0; #endif return *this; } hex_t* hex_t::adjacent(dir_t d) { if (!d.okay()) return NULL; assert(map); return (*map)(map->move(xy, d)); // assert(adjlist[(int)d].hex != NULL); // return adjlist[(int)d].hex; } int hex_t::terrain_adjacent(Terrain t) { int j = 0; for (int i = 0; i < DIRECTIONS; i++) j += adjacent(i)->terrain == t ? 1 : 0; return j; } #ifdef KeepAdjacent void hex_t::set_adjacent(dir_t dir, hex_t *hex) { adjlist[dir].hex = hex; adjlist[dir].xy = hex->xy; } #endif int hex_t::num_features(void) { #ifdef STL return fv.size(); #else int i = 0; for (int j = 0; j < flistlen; j++) i += flist[j] ? 1 : 0; return i; #endif } feature_t* hex_t::feature(int i) { if (i < 0 || i >= num_features()) return 0; return fv[i]; } feature_t* hex_t::has_feature(feature_t* f) { #ifdef STL for (unsigned int i = 0; i < fv.size(); i++) if (fv[i] == f) return fv[i]; #else for (int i = 0; i < flistlen && flist[i]; i++) if (flist[i] == f) return flist[i]; #endif return 0; } feature_t* hex_t::has_feature(Feature f) { #ifdef STL for (unsigned int i = 0; i < fv.size(); i++) if (fv[i]->type == f) { misc_t::dbg.log("Hex(%s) found %s", title, fv[i]->describe()); return fv[i]; } #else for (int i = 0; i < flistlen && flist[i]; i++) if (flist[i]->type == f) return flist[i]; #endif return 0; } int hex_t::count_feature(Feature f) { int count = 0; #ifdef STL for (unsigned int i = 0; i < fv.size(); i++) if (fv[i]->type == f) count++; #else for (int i = 0; i < flistlen && flist[i]; i++) if (flist[i]->type == f) count++; #endif return count; } int hex_t::count_feature(Feature f, int owner) { int count = 0; #ifdef STL for (unsigned int i = 0; i < fv.size(); i++) if (fv[i]->type == f && fv[i]->owner == owner) count++; #else for (int i = 0; i < flistlen && flist[i]; i++) if (flist[i]->type == f && flist[i]->owner == owner) count++; #endif return count; } int hex_t::feature_adjacent(Feature f) { int j = 0; for (int i = NORTH; i <= NORTHWEST; i++) if (adjacent(i)->has_feature(f)) j++; return j; } feature_t* hex_t::add_feature(feature_t *f) { #ifdef STL if (has_feature(f)) return f; fv.push_back(f); misc_t::dbg.log("Hex(%s) added %s", title, f->describe()); #else int i; for (i = 0; i < flistlen && flist[i]; i++) { if (flist[i] == f) return f; } misc_t::dbg.log("add_feature(%d %s) i = %d, flistlen = %d", f->type, title, i, flistlen); if (i == flistlen) { feature_t **tmp = new feature_t*[flistlen + 10]; for (int j = 0; j < flistlen; j++) tmp[j] = flist[j]; for (int j = flistlen; j < flistlen + 10; j++) tmp[j] = 0; delete flist; flist = tmp; flistlen += 10; } flist[i] = f; #endif return f; } feature_t* hex_t::del_feature(feature_t *f) { if (f == 0) return f; #ifdef STL std::vector<feature_t*>::iterator i; for (i = fv.begin(); i != fv.end(); ++i) { if (*i == f) { fv.erase(i); break; } } #else int i, j; for (i = 0; i < flistlen && flist[i]; i++) if (flist[i] == f) break; if (flist[i] != f) return 0; /* Shuffle all other features down one */ for (j = i; j < flistlen && flist[j]; j++) flist[j] = flist[j+1]; flist[j+1] = NULL; #endif return f; } feature_t* hex_t::pop_feature() { #ifdef STL feature_t *f = 0; if (fv.size()) { f = fv.back(); fv.pop_back(); } return f; #else feature_t *f; f = (flistlen && flist[0]) ? del_feature(flist[0]) : NULL; return f; #endif } void hex_t::clear_features() { #ifdef STL misc_t::dbg.log("%s cleared", title); for (unsigned int i = 0; i < fv.size(); i++) delete fv[i]; fv.clear(); #else for (int i = 0; i < flistlen && flist[i]; i++) delete flist[i]; delete [] flist; flist = 0; flistlen = 0; #endif } int hex_t::size() { int size; band_t *band; den_t *den; size = ((den = (den_t*)has_feature(DEN))) ? den->pop : 0; return size + ((band = (band_t*)has_feature(BAND)) ? band->size() : 0); } void hex_t::save_xml(xmlpp::Element *p) { xmlpp::Element *xn_hex = p->add_child_element("hex"); xn_hex->set_attribute("x", Glib::ustring::compose("%1", xy.x)); xn_hex->set_attribute("y", Glib::ustring::compose("%1", xy.y)); xn_hex->set_attribute("title", Glib::ustring::compose("%1", title)); xn_hex->set_attribute("terrain", Glib::ustring::compose("%1", terrain)); xn_hex->set_attribute("owner", Glib::ustring::compose("%1", owner)); #ifdef KeepAdjacent for (int i = 0; i < DIRECTIONS; i++) { if (adjacent(i)) { xmlpp::Element *xn_adj = xn_hex->add_child_element("adj"); xn_adj->set_attribute("d", Glib::ustring::compose("%1", i)); xn_adj->set_attribute("x", Glib::ustring::compose("%1", adjlist[i].xy.x)); xn_adj->set_attribute("y", Glib::ustring::compose("%1", adjlist[i].xy.y)); } } #endif for (unsigned int i = 0; i < fv.size(); i++) #ifdef STL fv[i]->save_xml(xn_hex); #else for (int i = 0; i < flistlen && flist[i]; i++) flist[i]->save_xml(xn_hex); #endif } void hex_t::debug(FILE *stream) { fprintf(stream, "Hex(x=%d y=%d title=%s terrain=%d owner=%d)\n", xy.x, xy.y, title, terrain, owner); #ifdef STL for (unsigned int i = 0; i < fv.size(); i++) fv[i]->debug(stream); #else for (int i = 0; i < flistlen && flist[i]; i++) flist[i]->debug(stream); #endif } void hex_t::reload(xmlpp::Element *e, map_t *_map) { assert(e->get_attribute("title")); assert(e->get_attribute("owner")); assert(e->get_attribute("terrain")); owner = strtol(e->get_attribute("owner")->get_value().data(), NULL, 10); terrain = (Terrain)strtol(e->get_attribute("terrain")->get_value().data(), NULL, 10); title = strdup(e->get_attribute("title")->get_value().data()); map = _map; xmlpp::Node::NodeSet ns = e->find("./*"); for (unsigned int j = 0; j < ns.size(); j++) { xmlpp::Element *t = dynamic_cast<xmlpp::Element*>(ns[j]); #ifdef KeepAdjacent if (t->get_name() == "adj") { assert(t->get_attribute("d") != NULL); assert(t->get_attribute("x") != NULL); assert(t->get_attribute("y") != NULL); int dir = strtol(t->get_attribute("d")->get_value().data(), NULL, 10); int x = strtol(t->get_attribute("x")->get_value().data(), NULL, 10); int y = strtol(t->get_attribute("y")->get_value().data(), NULL, 10); adjlist[dir].hex = (*map)(x, y); adjlist[dir].xy = point_t(x, y); } #endif Glib::ustring name = t->get_name(); if (name == "den") add_feature(new den_t(t)); if (name == "band") add_feature(new band_t(t)); if (name == "fertile") add_feature(new fertile_t(t)); if (name == "ruin") add_feature(new ruin_t(t)); if (name == "temple") add_feature(new temple_t(t)); if (name == "cursed") add_feature(new cursed_t(t)); if (name == "whirlpool") add_feature(new whirlpool_t(t)); if (name == "volcano") add_feature(new volcano_t(t)); if (name == "peak") add_feature(new peak_t(t)); if (name == "swamp") add_feature(new swamp_t(t)); if (name == "scrub") add_feature(new scrub_t(t)); } } hex_t::operator char*() { return title; } void hex_t::remap(map_t* _map) { // for (int i = 0; i < DIRECTIONS; i++) // adjlist[i].hex = map(adjlist[i].xy); map = _map; } void hex_t::setmap(map_t *m) { map = m; }
21.648379
91
0.570326
ross-alexander
10ce90c53fb8693f21d6a80448007b9973d7a058
27,454
cpp
C++
src/browser-common-view.cpp
tizenorg/apps.web.browser
89ae3e2968d998e201f5e27f1036028c4b47e746
[ "Apache-2.0" ]
null
null
null
src/browser-common-view.cpp
tizenorg/apps.web.browser
89ae3e2968d998e201f5e27f1036028c4b47e746
[ "Apache-2.0" ]
null
null
null
src/browser-common-view.cpp
tizenorg/apps.web.browser
89ae3e2968d998e201f5e27f1036028c4b47e746
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012 Samsung Electronics Co., Ltd * * Licensed under the Flora License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.tizenopensource.org/license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "browser-class.h" #include "browser-common-view.h" #include "browser-view.h" #include "browser-window.h" Browser_Data_Manager *Browser_Common_View::m_data_manager; Evas_Object *Browser_Common_View::m_win; Evas_Object *Browser_Common_View::m_navi_bar; Evas_Object *Browser_Common_View::m_bg; Browser_Class *Browser_Common_View::m_browser; Browser_Common_View::Browser_Common_View(void) : m_selection_info(NULL) ,m_selection_info_layout(NULL) ,m_selinfo_layout(NULL) ,m_popup(NULL) ,m_ug(NULL) ,m_share_popup(NULL) ,m_share_list(NULL) ,m_call_confirm_popup(NULL) ,m_call_type(CALL_UNKNOWN) { BROWSER_LOGD("[%s]", __func__); } Browser_Common_View::~Browser_Common_View(void) { BROWSER_LOGD("[%s]", __func__); if (m_selection_info_layout) { evas_object_del(m_selection_info_layout); m_selection_info_layout = NULL; } if (m_selection_info) { evas_object_del(m_selection_info); m_selection_info = NULL; } if (m_popup) { evas_object_del(m_popup); m_popup = NULL; } if (m_share_popup) { evas_object_del(m_share_popup); m_share_popup = NULL; } if (m_share_list) { evas_object_del(m_share_list); m_share_list = NULL; } if (m_ug) { ug_destroy(m_ug); m_ug = NULL; } if (m_call_confirm_popup) { evas_object_del(m_call_confirm_popup); m_call_confirm_popup = NULL; } m_sns_path_list.clear(); m_sns_name_list.clear(); m_sns_icon_list.clear(); } void Browser_Common_View::show_msg_popup(const char *msg, int timeout) { BROWSER_LOGD("[%s]", __func__); if (m_popup) { evas_object_del(m_popup); m_popup = NULL; } m_popup = elm_popup_add(m_navi_bar); evas_object_size_hint_weight_set(m_popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); elm_object_text_set(m_popup, msg); elm_popup_timeout_set(m_popup, timeout); evas_object_show(m_popup); } void Browser_Common_View::show_msg_popup(const char *title, const char *msg, int timeout) { BROWSER_LOGD("[%s]", __func__); if (m_popup) { evas_object_del(m_popup); m_popup = NULL; } m_popup = elm_popup_add(m_navi_bar); evas_object_size_hint_weight_set(m_popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); elm_object_part_text_set(m_popup, "title,text", title); elm_object_text_set(m_popup, msg); elm_popup_timeout_set(m_popup, timeout); evas_object_show(m_popup); } void Browser_Common_View::hide_notify_popup(void) { if (m_selection_info_layout) { evas_object_del(m_selection_info_layout); m_selection_info_layout = NULL; } if (m_selection_info) { evas_object_del(m_selection_info); m_selection_info = NULL; } } void Browser_Common_View::show_notify_popup(const char *msg, int timeout, Eina_Bool has_control_bar) { if (m_selection_info_layout) { evas_object_del(m_selection_info_layout); m_selection_info_layout = NULL; } if (m_selection_info) { evas_object_del(m_selection_info); m_selection_info = NULL; } int angle = 0; angle = elm_win_rotation_get(m_win); m_selection_info = elm_notify_add(m_navi_bar); if (!m_selection_info) { BROWSER_LOGD("elm_notify_add failed"); return; } elm_notify_orient_set(m_selection_info, ELM_NOTIFY_ORIENT_BOTTOM); evas_object_size_hint_weight_set(m_selection_info, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(m_selection_info, EVAS_HINT_FILL, EVAS_HINT_FILL); m_selection_info_layout = elm_layout_add(m_selection_info); if (!m_selection_info_layout) { BROWSER_LOGD("elm_layout_add failed"); return; } evas_object_size_hint_weight_set(m_selection_info_layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(m_selection_info_layout, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_object_content_set(m_selection_info, m_selection_info_layout); if (has_control_bar) { if(angle == 0 || angle == 180) elm_layout_theme_set(m_selection_info_layout, "standard", "selectioninfo", "vertical/bottom_64"); else elm_layout_theme_set(m_selection_info_layout, "standard", "selectioninfo", "horizontal/bottom_64"); } else { if(angle == 0 || angle == 180) elm_layout_theme_set(m_selection_info_layout, "standard", "selectioninfo", "vertical/bottom_12"); else elm_layout_theme_set(m_selection_info_layout, "standard", "selectioninfo", "horizontal/bottom_12"); } edje_object_part_text_set(elm_layout_edje_get(m_selection_info_layout), "elm.text", msg); if (timeout) elm_notify_timeout_set(m_selection_info, timeout); evas_object_show(m_selection_info); } void Browser_Common_View::show_notify_popup_layout(const char *msg, int timeout, Evas_Object *parent) { if (m_selinfo_layout) { evas_object_del(m_selinfo_layout); m_selinfo_layout = NULL; } m_selinfo_layout = elm_layout_add(parent); if (!m_selinfo_layout) { BROWSER_LOGD("elm_layout_add failed"); return; } elm_object_part_content_set(parent, "selinfo.swallow.contents", m_selinfo_layout); evas_object_size_hint_weight_set(m_selinfo_layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(m_selinfo_layout, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_object_content_set(m_selection_info, m_selection_info_layout); /* Set the layout theme */ elm_layout_theme_set(m_selinfo_layout, "standard", "selectioninfo", "default"); /* Set the text */ elm_object_part_text_set(m_selinfo_layout, "elm.text", msg); elm_object_signal_emit(parent, "show,selection,info", "elm"); } void Browser_Common_View::hide_notify_popup_layout(Evas_Object *parent) { if (m_selinfo_layout) { evas_object_del(m_selinfo_layout); m_selinfo_layout = NULL; } elm_object_signal_emit(parent, "hide,selection,info", "elm"); } Eina_Bool Browser_Common_View::find_word_with_text(const char *text_to_find) { BROWSER_LOGD("[%s], text_to_find[%s]", __func__, text_to_find); if (!text_to_find) return EINA_FALSE; Browser_View *browser_view = m_data_manager->get_browser_view(); return browser_view->launch_find_word_with_text(text_to_find);; } /* Capture snapshot with current focused ewk view. */ Evas_Object *Browser_Common_View::_capture_snapshot(Browser_Window *window, float scale) { BROWSER_LOGD("[%s]", __func__); int focused_ewk_view_w = 0; int focused_ewk_view_h = 0; evas_object_geometry_get(window->m_ewk_view, NULL, NULL, &focused_ewk_view_w, &focused_ewk_view_h); Evas_Object *rectangle = evas_object_rectangle_add(evas_object_evas_get(m_navi_bar)); evas_object_size_hint_min_set(rectangle, focused_ewk_view_w * scale, focused_ewk_view_h * scale); evas_object_resize(rectangle, focused_ewk_view_w * scale, focused_ewk_view_h * scale); evas_object_color_set(rectangle, 255, 255, 255, 255); return rectangle; } void Browser_Common_View::__post_to_sns_cb(void *data, Evas_Object *obj, void *event_info) { if (!data) return; Browser_Common_View *common_view = (Browser_Common_View *)data; Elm_Object_Item *selected_item = elm_list_selected_item_get(common_view->m_share_list); const char *sns_name = elm_object_item_text_get(selected_item); BROWSER_LOGD("sns_name=[%s]", sns_name); if (!common_view->_post_to_sns(std::string(sns_name), common_view->m_share_url)) BROWSER_LOGE("_post_to_sns failed"); __popup_response_cb(common_view, NULL, NULL); } Eina_Bool Browser_Common_View::_post_to_sns(std::string sns_name, std::string url) { BROWSER_LOGD("sns_name=[%s], url=[%s]", sns_name.c_str(), url.c_str()); if (url.empty() || sns_name.empty()) { show_msg_popup(BR_STRING_EMPTY); return EINA_FALSE; } int index = 0; for (index = 0 ; index < m_sns_name_list.size() ; index++) { if (m_sns_name_list[index].find(sns_name) != string::npos) break; } if (m_sns_path_list[index].find("twitter") != string::npos || m_sns_path_list[index].find("facebook") != string::npos) { int ret = 0; service_h service_handle = NULL; if (service_create(&service_handle) < 0) { BROWSER_LOGE("Fail to create service handle"); return EINA_FALSE; } if (!service_handle) { BROWSER_LOGE("service handle is NULL"); return EINA_FALSE; } if (service_set_operation(service_handle, SERVICE_OPERATION_SEND_TEXT) < 0) { BROWSER_LOGE("Fail to set service operation"); service_destroy(service_handle); return EINA_FALSE; } if (service_add_extra_data(service_handle, SERVICE_DATA_TEXT, (char *)url.c_str()) < 0) { BROWSER_LOGE("Fail to set post data"); service_destroy(service_handle); return EINA_FALSE; } if (service_set_package(service_handle, m_sns_path_list[index].c_str()) < 0) { BROWSER_LOGE("Fail to set SNS"); service_destroy(service_handle); return EINA_FALSE; } if (service_send_launch_request(service_handle, NULL, NULL) < 0) { BROWSER_LOGE("Fail to launch service operation"); service_destroy(service_handle); return EINA_FALSE; } service_destroy(service_handle); } return EINA_TRUE; } void Browser_Common_View::__send_via_message_cb(void *data, Evas_Object *obj, void *event_info) { if (!data) return; Browser_Common_View *common_view = (Browser_Common_View *)data; if (!common_view->_send_via_message(common_view->m_share_url, std::string())) BROWSER_LOGE("_send_via_message failed"); __popup_response_cb(common_view, NULL, NULL); } Eina_Bool Browser_Common_View::_send_via_message(std::string url, std::string to, Eina_Bool attach_file) { BROWSER_LOGD("[%s], url[%s], to[%s]", __func__, url.c_str(), to.c_str()); if (url.empty() && to.empty()) { show_msg_popup(BR_STRING_EMPTY); return EINA_FALSE; } service_h service_handle = NULL; if (service_create(&service_handle) < 0) { BROWSER_LOGE("Fail to create service handle"); return EINA_FALSE; } if (!service_handle) { BROWSER_LOGE("Fail to create service handle"); return EINA_FALSE; } if (!url.empty()) { if (attach_file) { if (service_set_operation(service_handle, SERVICE_OPERATION_SEND) < 0) { BROWSER_LOGE("Fail to set service operation"); service_destroy(service_handle); return EINA_FALSE; } if (service_add_extra_data(service_handle, "ATTACHFILE", url.c_str())) { BROWSER_LOGE("Fail to set extra data"); service_destroy(service_handle); return EINA_FALSE; } } else { if (service_set_operation(service_handle, SERVICE_OPERATION_SEND_TEXT) < 0) { BROWSER_LOGE("Fail to set service operation"); service_destroy(service_handle); return EINA_FALSE; } if (service_add_extra_data(service_handle, SERVICE_DATA_TEXT, url.c_str()) < 0) { BROWSER_LOGE("Fail to set extra data"); service_destroy(service_handle); return EINA_FALSE; } } } if (!to.empty()) { if (url.empty()) { if (service_set_operation(service_handle, SERVICE_OPERATION_SEND_TEXT) < 0) { BROWSER_LOGE("Fail to set service operation"); service_destroy(service_handle); return EINA_FALSE; } } if (service_add_extra_data(service_handle, SERVICE_DATA_TO , to.c_str()) < 0) { BROWSER_LOGE("Fail to set extra data"); service_destroy(service_handle); return EINA_FALSE; } } if (service_set_package(service_handle, SEC_MESSAGE) < 0) {//SEC_EMAIL BROWSER_LOGE("Fail to launch service operation"); service_destroy(service_handle); return EINA_FALSE; } if (service_send_launch_request(service_handle, NULL, NULL) < 0) { BROWSER_LOGE("Fail to launch service operation"); service_destroy(service_handle); return EINA_FALSE; } service_destroy(service_handle); return EINA_TRUE; } void Browser_Common_View::__send_via_email_cb(void *data, Evas_Object *obj, void *event_info) { BROWSER_LOGD("%s", __func__); if (!data) return; Browser_Common_View *common_view = (Browser_Common_View *)data; if (!common_view->_send_via_email(common_view->m_share_url)) BROWSER_LOGE("_send_via_email failed"); __popup_response_cb(common_view, NULL, NULL); } void Browser_Common_View::__share_via_nfc_cb(void *data, Evas_Object *obj, void *event_info) { BROWSER_LOGD("%s", __func__); if (!data) return; Browser_Common_View *common_view = (Browser_Common_View *)data; if (!common_view->_share_via_nfc(common_view->m_share_url)) BROWSER_LOGE("_share_via_nfc failed"); __popup_response_cb(common_view, NULL, NULL); } Eina_Bool Browser_Common_View::_launch_streaming_player(const char *url, const char *cookie) { BROWSER_LOGD("%s", __func__); if (!url || strlen(url) == 0) { BROWSER_LOGE("url is empty"); return EINA_FALSE; } bool is_running = false; if (app_manager_is_running(SEC_VT_CALL, &is_running) < 0) { BROWSER_LOGE("Fail to get app running information\n"); return EINA_FALSE; } if (is_running) { BROWSER_LOGE("video-call is running......\n"); show_msg_popup(BR_STRING_WARNING_VIDEO_PLAYER); return EINA_FALSE; } service_h service_handle = NULL; if (service_create(&service_handle) < 0) { BROWSER_LOGE("Fail to create service handle"); return EINA_FALSE; } if (!service_handle) { BROWSER_LOGE("service handle is NULL"); return EINA_FALSE; } BROWSER_LOGD("url=[%s]", url); if (service_add_extra_data(service_handle, "path", url) < 0) { BROWSER_LOGE("Fail to set extra data"); service_destroy(service_handle); return EINA_FALSE; } if (cookie && strlen(cookie)) { if (service_add_extra_data(service_handle, "cookie", cookie) < 0) { BROWSER_LOGE("Fail to set extra data"); service_destroy(service_handle); return EINA_FALSE; } } if (service_set_package(service_handle,SEC_STREAMING_PLAYER) < 0) { BROWSER_LOGE("Fail to set package"); service_destroy(service_handle); return EINA_FALSE; } if (service_send_launch_request(service_handle, NULL, NULL) < 0) { BROWSER_LOGE("Fail to launch service operation"); service_destroy(service_handle); return EINA_FALSE; } service_destroy(service_handle); return EINA_TRUE; } Eina_Bool Browser_Common_View::_check_available_sns_account(void) { BROWSER_LOGD("%s", __func__); int error_code = account_connect(); bool result = EINA_FALSE; if(error_code != ACCOUNT_ERROR_NONE) { BROWSER_LOGD("account_connect failed with error_code[%d].\n", error_code); return EINA_FALSE; } if (account_query_account_by_package_name(__check_available_sns_account_cb, "org.tizen.facebook", NULL) == ACCOUNT_ERROR_NONE) { BROWSER_LOGD("Account for Facebook was set\n"); } else if (account_query_account_by_package_name(__check_available_sns_account_cb, "org.tizen.twitter", NULL) == ACCOUNT_ERROR_NONE) { BROWSER_LOGD("Account for Twitter was set\n"); } else { BROWSER_LOGD("Account Queried failed \n"); error_code = account_disconnect(); if(error_code != ACCOUNT_ERROR_NONE) { BROWSER_LOGD("(%d)-[Account] ret = %d, \n", __LINE__, error_code); return EINA_FALSE; } } error_code = account_disconnect(); if(error_code != ACCOUNT_ERROR_NONE) { BROWSER_LOGD("(%d)-[Account] ret = %d, \n", __LINE__, error_code); return EINA_FALSE; } return EINA_TRUE; } bool Browser_Common_View::__check_available_sns_account_cb(account_h handle, void *data) { BROWSER_LOGD("%s", __func__); char *pkg_name = NULL; account_get_package_name(handle, &pkg_name); BROWSER_LOGD("pkg_name [%s]", pkg_name); if (pkg_name) free(pkg_name); pkg_name = NULL; return true; } Eina_Bool Browser_Common_View::_get_available_sns_list(void) { BROWSER_LOGD("[%s]\n", __func__); int error_code = 0; error_code = account_connect(); if (error_code == ACCOUNT_ERROR_RECORD_NOT_FOUND) { show_msg_popup(BR_STRING_ERROR, BR_STRING_NOT_FOUND_URL, 2); return EINA_FALSE; } else if (error_code == ACCOUNT_ERROR_NONE) { error_code = account_foreach_account_from_db(__get_sns_list, this); error_code = account_disconnect(); if (error_code !=ACCOUNT_ERROR_NONE) { BROWSER_LOGD("account_svc_disconnect failed with error code [%d]\n", error_code); return EINA_FALSE; } } else { BROWSER_LOGD("account_connect failed with error code [%d]\n", error_code); return EINA_FALSE; } return EINA_TRUE; } bool Browser_Common_View::__get_sns_list(account_h account, void *data) { BROWSER_LOGD("[%s]\n", __func__); if (!data) return false; Browser_Common_View *common_view = (Browser_Common_View *)data; int account_id = 0; char *service_name = NULL; char *lib_path = NULL; char *icon_path = NULL; Eina_Bool can_post = EINA_FALSE; account_get_capability(account, __get_post_capability_cb, &can_post); account_get_account_id(account, &account_id); BROWSER_LOGD("account_id: %d\n", account_id); account_get_domain_name(account, &service_name); BROWSER_LOGD("service_name: %s\n", service_name); if (!can_post) { BROWSER_LOGD("cannot post to : [%s] in browser\n", service_name); if (service_name) free(service_name); service_name = NULL; return false; } else { account_get_package_name(account, &lib_path); BROWSER_LOGD("lib_path: %s\n", lib_path); account_get_icon_path(account, &icon_path); BROWSER_LOGD("icon_path: %s\n", icon_path); if (icon_path && strlen(icon_path) > 0) { BROWSER_LOGD("icon_path: %s\n", icon_path); Evas_Object *icon = elm_icon_add(common_view->m_share_popup); if (icon) { elm_icon_file_set(icon, icon_path, NULL); BROWSER_LOGD("icon_path: %s\n", icon_path); common_view->m_sns_icon_list.push_back(icon); } } if (service_name && strlen(service_name) && lib_path && strlen(lib_path)) { common_view->m_sns_path_list.push_back(std::string(lib_path)); common_view->m_sns_name_list.push_back(std::string(service_name)); } } if (service_name) free(service_name); service_name = NULL; if (icon_path) free(icon_path); icon_path = NULL; if (lib_path) free(lib_path); lib_path= NULL; return true; } bool Browser_Common_View::__get_post_capability_cb(account_capability_type_e type, account_capability_state_e state, void *data) { Eina_Bool *can_post = (Eina_Bool *)data; if (!can_post) { BROWSER_LOGD("unable to post"); return false; } if (ACCOUNT_CAPABILITY_STATUS_POST != type) return true; if (ACCOUNT_CAPABILITY_DISABLED == state) return true; *can_post = EINA_TRUE; return true; } Eina_Bool Browser_Common_View::_send_via_email(std::string url, Eina_Bool attach_file) { BROWSER_LOGD("[%s], url[%s]", __func__, url.c_str()); if (url.empty()) { show_msg_popup(BR_STRING_EMPTY); return EINA_FALSE; } service_h service_handle = NULL; if (service_create(&service_handle) < 0) { BROWSER_LOGE("Fail to create service handle"); return EINA_FALSE; } if (!service_handle) { BROWSER_LOGE("Fail to create service handle"); return EINA_FALSE; } if (attach_file) { if (service_set_operation(service_handle, SERVICE_OPERATION_SEND) < 0) { BROWSER_LOGE("Fail to set service operation"); service_destroy(service_handle); return EINA_FALSE; } if (service_set_uri(service_handle, url.c_str()) < 0) { BROWSER_LOGE("Fail to set uri"); service_destroy(service_handle); return EINA_FALSE; } } else { if (service_set_operation(service_handle, SERVICE_OPERATION_SEND_TEXT) < 0) { BROWSER_LOGE("Fail to set service operation"); service_destroy(service_handle); return EINA_FALSE; } if (strstr(url.c_str(), BROWSER_MAIL_TO_SCHEME)) { if (service_add_extra_data(service_handle, SERVICE_DATA_TO, url.c_str() + strlen(BROWSER_MAIL_TO_SCHEME)) < 0) { BROWSER_LOGE("Fail to set mailto data"); service_destroy(service_handle); return EINA_FALSE; } } else { if (service_add_extra_data(service_handle, SERVICE_DATA_TEXT, url.c_str()) < 0) { BROWSER_LOGE("Fail to set extra data"); service_destroy(service_handle); return EINA_FALSE; } } } if (service_set_package(service_handle, SEC_EMAIL) < 0) { BROWSER_LOGE("Fail to launch service operation"); service_destroy(service_handle); return EINA_FALSE; } if (service_send_launch_request(service_handle, NULL, NULL) < 0) { BROWSER_LOGE("Fail to launch service operation"); service_destroy(service_handle); return EINA_FALSE; } service_destroy(service_handle); return EINA_TRUE; } Eina_Bool Browser_Common_View::_add_to_contact(std::string number) { if (number.empty()) { BROWSER_LOGE("number is null"); return EINA_FALSE; } struct ug_cbs cbs = {0, }; cbs.layout_cb = __ug_layout_cb; cbs.result_cb = NULL;//__ug_result_cb; cbs.destroy_cb = __ug_destroy_cb; cbs.priv = (void *)this; char *phone_number = (char *)strdup(number.c_str()); if (!phone_number) { BROWSER_LOGE("strdup failed"); return EINA_FALSE; } service_h data = NULL; service_create(&data); if (data == NULL) { BROWSER_LOGE("fail to service_create."); return EINA_FALSE; } /* type. CT_UG_REQUEST_ADD = 21, CT_UG_REQUEST_ADD_WITH_NUM = 22, CT_UG_REQUEST_ADD_WITH_EMAIL = 23, CT_UG_REQUEST_ADD_WITH_WEB = 24, */ if (service_add_extra_data(data, "type", "22")) { BROWSER_LOGE("service_add_extra_data is failed."); service_destroy(data); return EINA_FALSE; } if (service_add_extra_data(data, "ct_num", number.c_str())) { BROWSER_LOGE("service_add_extra_data is failed."); service_destroy(data); return EINA_FALSE; } if (!ug_create(NULL, "contacts-details-efl", UG_MODE_FULLVIEW, data, &cbs)) BROWSER_LOGE("ug_create is failed."); if (service_destroy(data)) BROWSER_LOGE("service_destroy is failed."); free(phone_number); } Eina_Bool Browser_Common_View::_share_via_nfc(std::string url) { BROWSER_LOGD("[%s]", __func__); if (url.empty()) { show_msg_popup(BR_STRING_EMPTY); return EINA_FALSE; } struct ug_cbs cbs = {0, }; cbs.layout_cb = __ug_layout_cb; cbs.result_cb = NULL;//__ug_result_cb; cbs.destroy_cb = __ug_destroy_cb; cbs.priv = (void *)this; char *share_url = (char *)strdup(url.c_str()); if (!share_url) { BROWSER_LOGE("strdup failed"); return EINA_FALSE; } service_h data = NULL; service_create(&data); if (data == NULL) { BROWSER_LOGE("fail to service_create."); return EINA_FALSE; } if (service_add_extra_data(data, "count", "1")) { BROWSER_LOGE("service_add_extra_data is failed."); service_destroy(data); return EINA_FALSE; } if (service_add_extra_data(data, "request_type", "data_buffer")) { BROWSER_LOGE("service_add_extra_data is failed."); service_destroy(data); return EINA_FALSE; } if (service_add_extra_data(data, "request_data", share_url)) { BROWSER_LOGE("service_add_extra_data is failed."); service_destroy(data); free(share_url); return EINA_FALSE; } if(!ug_create(NULL, "share-nfc-efl", UG_MODE_FULLVIEW, data, &cbs)) BROWSER_LOGE("ug_create is failed."); if (service_destroy(data)) BROWSER_LOGE("service_destroy is failed."); free(share_url); return EINA_TRUE; } Eina_Bool Browser_Common_View::_show_share_popup(const char *url) { BROWSER_LOGE("url=[%s]", url); if (!url || strlen(url) == 0) { BROWSER_LOGE("url is empty"); return EINA_FALSE; } m_share_url = std::string(url); m_sns_path_list.clear(); m_sns_name_list.clear(); m_sns_icon_list.clear(); m_share_popup = elm_popup_add(m_navi_bar); if (!m_share_popup) { BROWSER_LOGE("elm_popup_add failed"); return EINA_FALSE; } elm_object_style_set(m_share_popup, "menustyle"); elm_object_part_text_set(m_share_popup, "title,text", BR_STRING_SHARE); evas_object_size_hint_weight_set(m_share_popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); m_share_list = elm_list_add(m_share_popup); if (!m_share_list) { BROWSER_LOGE("elm_list_add failed"); return EINA_FALSE; } evas_object_size_hint_weight_set(m_share_list, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(m_share_list, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_list_item_append(m_share_list, BR_STRING_MESSAGES, NULL, NULL, __send_via_message_cb, this); elm_list_item_append(m_share_list, BR_STRING_EMAIL, NULL, NULL, __send_via_email_cb, this); evas_object_show(m_share_list); Evas_Object *cancel_button = elm_button_add(m_share_popup); elm_object_text_set(cancel_button, BR_STRING_CANCEL); elm_object_part_content_set(m_share_popup, "button1", cancel_button); elm_object_style_set(cancel_button, "popup_button/default"); evas_object_smart_callback_add(cancel_button, "clicked", __popup_response_cb, this); elm_object_content_set(m_share_popup, m_share_list); evas_object_show(m_share_popup); return EINA_TRUE; } void Browser_Common_View::__popup_response_cb(void* data, Evas_Object* obj, void* event_info) { BROWSER_LOGD("%s, event_info=%d", __func__, (int)event_info); if (!data) return; Browser_Common_View *common_view = (Browser_Common_View *)data; if (common_view->m_share_popup) { evas_object_del(common_view->m_share_popup); common_view->m_share_popup = NULL; } if (common_view->m_share_list) { evas_object_del(common_view->m_share_list); common_view->m_share_list = NULL; } common_view->m_sns_name_list.clear(); common_view->m_sns_path_list.clear(); } char *Browser_Common_View::_trim(char *str) { char *pos_bos = str; while(*pos_bos == ' ') pos_bos++; char *pos_eos = pos_bos + strlen(pos_bos) - 1; while((pos_eos >= str) && (*pos_eos == ' ')) { *pos_eos = '\0'; pos_eos--; } return pos_bos; } #if defined(HORIZONTAL_UI) Eina_Bool Browser_Common_View::is_landscape(void) { app_device_orientation_e rotation_value = app_get_device_orientation(); if (rotation_value == APP_DEVICE_ORIENTATION_0 || rotation_value == APP_DEVICE_ORIENTATION_180) return EINA_FALSE; else return EINA_TRUE; } #endif /* set focus to edit field idler callback to show ime. */ Eina_Bool Browser_Common_View::__set_focus_editfield_idler_cb(void *edit_field) { BROWSER_LOGD("[%s]", __func__); if (!edit_field) return ECORE_CALLBACK_CANCEL; elm_object_focus_set((Evas_Object *)edit_field, EINA_TRUE); elm_object_signal_emit((Evas_Object *)edit_field, "clicked", "elm"); Evas_Object *entry = br_elm_editfield_entry_get((Evas_Object *)edit_field); elm_entry_cursor_end_set(entry); return ECORE_CALLBACK_CANCEL; } Eina_Bool Browser_Common_View::_has_url_sheme(const char *url) { if (url && strlen(url) && (strstr(url, BROWSER_URL_SCHEME_CHECK) || strstr(url, BROWSER_MAIL_TO_SCHEME))) return EINA_TRUE; else return EINA_FALSE; } void Browser_Common_View::__ug_layout_cb(ui_gadget_h ug, enum ug_mode mode, void *priv) { BROWSER_LOGD("[%s]", __func__); if (!priv || !ug) return; Browser_Common_View *common_view = (Browser_Common_View *)priv; Evas_Object *base = (Evas_Object*)ug_get_layout(ug); if (!base) return; common_view->m_ug = ug; Evas_Object *win = (Evas_Object *)ug_get_window(); switch (mode) { case UG_MODE_FULLVIEW: evas_object_size_hint_weight_set(base, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); elm_win_resize_object_add(win, base); evas_object_show(base); break; default: break; } } void Browser_Common_View::__ug_result_cb(ui_gadget_h ug, bundle *result, void *priv) { if (!priv || !ug) return; } void Browser_Common_View::__ug_destroy_cb(ui_gadget_h ug, void *priv) { if (!priv || !ug) return; if (ug_destroy(ug)) BROWSER_LOGD("ug_destroy is failed.\n"); }
27.371884
115
0.746849
tizenorg
10d07a0dcbb5aec4ac727656f1c8fda1dfbf79c7
1,312
cpp
C++
Arduino-master_2/Arduino-master/libraries/CountDown/CountDown.cpp
GHarduino/ArduinoOnlineTrainingClass
b039de3c79da0b8e87272aa911f03128798b7bf8
[ "MIT" ]
11
2017-05-02T09:50:07.000Z
2022-01-10T16:06:38.000Z
Arduino-master_2/Arduino-master/libraries/CountDown/CountDown.cpp
GHarduino/ArduinoOnlineTrainingClass
b039de3c79da0b8e87272aa911f03128798b7bf8
[ "MIT" ]
null
null
null
Arduino-master_2/Arduino-master/libraries/CountDown/CountDown.cpp
GHarduino/ArduinoOnlineTrainingClass
b039de3c79da0b8e87272aa911f03128798b7bf8
[ "MIT" ]
2
2017-05-15T05:32:07.000Z
2017-05-23T16:30:20.000Z
// // FILE: CountDown.cpp // AUTHOR: Rob Tillaart // VERSION: 0.1.00 // PURPOSE: CountDown library for Arduino // // The library is based upon millis() and therefore // has the same restrictions as millis() has wrt overflow. // // HISTORY: // 0.1.00 - 2015-10-27 initial version // // Released to the public domain // #include "CountDown.h" CountDown::CountDown(const enum Resolution res) { setResolution(res); stop(); } void CountDown::setResolution(const enum Resolution res) { _res = res; switch(_res) { case MICROS: _gettime = micros; break; case SECONDS: _gettime = seconds; break; case MILLIS: default: _gettime = millis; break; } } void CountDown::start(uint32_t ticks) { _state = CountDown::RUNNING; _starttime = _gettime(); _ticks = ticks; } unsigned long CountDown::remaining() { calcRemaining(); return _remaining; } void CountDown::stop() { calcRemaining(); _state = CountDown::STOPPED; } void CountDown::calcRemaining() { if (_state == CountDown::RUNNING) { uint32_t t = _gettime() - _starttime; _remaining = _ticks > t? _ticks - t: 0; if (_remaining == 0) { _state = CountDown::STOPPED; } } } // END OF FILE
17.972603
58
0.605945
GHarduino
10d0a391bd08b0c94fc20f244e985af9a74b3c44
238
cpp
C++
06 oop/virtual/final.cpp
thenlai/cpp-notes
9a8fbbc01a12abf874dfa4ffb10414236b8c24eb
[ "MIT" ]
null
null
null
06 oop/virtual/final.cpp
thenlai/cpp-notes
9a8fbbc01a12abf874dfa4ffb10414236b8c24eb
[ "MIT" ]
null
null
null
06 oop/virtual/final.cpp
thenlai/cpp-notes
9a8fbbc01a12abf874dfa4ffb10414236b8c24eb
[ "MIT" ]
null
null
null
/** * since c++11 * */ class A { virtual void fn() final; }; class B final : A { // error: void fn() override; // or, error: // void fn(); }; // error: B is `final` class C : B { }; int main() { return 0; }
10.347826
28
0.462185
thenlai
10d1708809afa14e46400923f7f39134de205a25
7,826
cpp
C++
head/contrib/groff/src/preproc/eqn/pile.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
head/contrib/groff/src/preproc/eqn/pile.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
head/contrib/groff/src/preproc/eqn/pile.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
1
2020-01-04T06:36:39.000Z
2020-01-04T06:36:39.000Z
// -*- C++ -*- /* Copyright (C) 1989, 1990, 1991, 1992, 2004 Free Software Foundation, Inc. Written by James Clark (jjc@jclark.com) This file is part of groff. groff is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. groff is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with groff; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin St - Fifth Floor, Boston, MA 02110-1301, USA. */ // piles and matrices #include "eqn.h" #include "pbox.h" // SUP_RAISE_FORMAT gives the first baseline // BASELINE_SEP_FORMAT gives the separation between baselines int pile_box::compute_metrics(int style) { int i; for (i = 0; i < col.len; i++) col.p[i]->compute_metrics(style); printf(".nr " WIDTH_FORMAT " 0", uid); for (i = 0; i < col.len; i++) printf(">?\\n[" WIDTH_FORMAT "]", col.p[i]->uid); printf("\n"); printf(".nr " BASELINE_SEP_FORMAT " %dM", uid, baseline_sep+col.space); for (i = 1; i < col.len; i++) printf(">?(\\n[" DEPTH_FORMAT "]+\\n[" HEIGHT_FORMAT "]+%dM)", col.p[i-1]->uid, col.p[i]->uid, default_rule_thickness*5); // round it so that it's a multiple of the vertical resolution printf("/\\n(.V+(\\n(.V/2)*\\n(.V\n"); printf(".nr " SUP_RAISE_FORMAT " \\n[" BASELINE_SEP_FORMAT "]*%d/2" "+%dM\n", uid, uid, col.len-1, axis_height - shift_down); printf(".nr " HEIGHT_FORMAT " \\n[" SUP_RAISE_FORMAT "]+\\n[" HEIGHT_FORMAT "]\n", uid, uid, col.p[0]->uid); printf(".nr " DEPTH_FORMAT " \\n[" BASELINE_SEP_FORMAT "]*%d+\\n[" DEPTH_FORMAT "]-\\n[" SUP_RAISE_FORMAT "]\n", uid, uid, col.len-1, col.p[col.len-1]->uid, uid); return FOUND_NOTHING; } void pile_box::output() { int i; printf("\\v'-\\n[" SUP_RAISE_FORMAT "]u'", uid); for (i = 0; i < col.len; i++) { switch (col.align) { case LEFT_ALIGN: break; case CENTER_ALIGN: printf("\\h'\\n[" WIDTH_FORMAT "]u-\\n[" WIDTH_FORMAT "]u/2u'", uid, col.p[i]->uid); break; case RIGHT_ALIGN: printf("\\h'\\n[" WIDTH_FORMAT "]u-\\n[" WIDTH_FORMAT "]u'", uid, col.p[i]->uid); break; default: assert(0); } col.p[i]->output(); printf("\\h'-\\n[" WIDTH_FORMAT "]u'", col.p[i]->uid); switch (col.align) { case LEFT_ALIGN: break; case CENTER_ALIGN: printf("\\h'\\n[" WIDTH_FORMAT "]u-\\n[" WIDTH_FORMAT "]u/2u'", col.p[i]->uid, uid); break; case RIGHT_ALIGN: printf("\\h'\\n[" WIDTH_FORMAT "]u-\\n[" WIDTH_FORMAT "]u'", col.p[i]->uid, uid); break; default: assert(0); } if (i != col.len - 1) printf("\\v'\\n[" BASELINE_SEP_FORMAT "]u'", uid); } printf("\\v'\\n[" SUP_RAISE_FORMAT "]u'", uid); printf("\\v'-(%du*\\n[" BASELINE_SEP_FORMAT "]u)'", col.len - 1, uid); printf("\\h'\\n[" WIDTH_FORMAT "]u'", uid); } pile_box::pile_box(box *pp) : col(pp) { } void pile_box::check_tabs(int level) { col.list_check_tabs(level); } void pile_box::debug_print() { col.debug_print("pile"); } int matrix_box::compute_metrics(int style) { int i, j; int max_len = 0; int space = 0; for (i = 0; i < len; i++) { for (j = 0; j < p[i]->len; j++) p[i]->p[j]->compute_metrics(style); if (p[i]->len > max_len) max_len = p[i]->len; if (p[i]->space > space) space = p[i]->space; } for (i = 0; i < len; i++) { printf(".nr " COLUMN_WIDTH_FORMAT " 0", uid, i); for (j = 0; j < p[i]->len; j++) printf(">?\\n[" WIDTH_FORMAT "]", p[i]->p[j]->uid); printf("\n"); } printf(".nr " WIDTH_FORMAT " %dM", uid, column_sep*(len-1)+2*matrix_side_sep); for (i = 0; i < len; i++) printf("+\\n[" COLUMN_WIDTH_FORMAT "]", uid, i); printf("\n"); printf(".nr " BASELINE_SEP_FORMAT " %dM", uid, baseline_sep+space); for (i = 0; i < len; i++) for (j = 1; j < p[i]->len; j++) printf(">?(\\n[" DEPTH_FORMAT "]+\\n[" HEIGHT_FORMAT "]+%dM)", p[i]->p[j-1]->uid, p[i]->p[j]->uid, default_rule_thickness*5); // round it so that it's a multiple of the vertical resolution printf("/\\n(.V+(\\n(.V/2)*\\n(.V\n"); printf(".nr " SUP_RAISE_FORMAT " \\n[" BASELINE_SEP_FORMAT "]*%d/2" "+%dM\n", uid, uid, max_len-1, axis_height - shift_down); printf(".nr " HEIGHT_FORMAT " 0\\n[" SUP_RAISE_FORMAT "]+(0", uid, uid); for (i = 0; i < len; i++) printf(">?\\n[" HEIGHT_FORMAT "]", p[i]->p[0]->uid); printf(")>?0\n"); printf(".nr " DEPTH_FORMAT " \\n[" BASELINE_SEP_FORMAT "]*%d-\\n[" SUP_RAISE_FORMAT "]+(0", uid, uid, max_len-1, uid); for (i = 0; i < len; i++) if (p[i]->len == max_len) printf(">?\\n[" DEPTH_FORMAT "]", p[i]->p[max_len-1]->uid); printf(")>?0\n"); return FOUND_NOTHING; } void matrix_box::output() { printf("\\h'%dM'", matrix_side_sep); for (int i = 0; i < len; i++) { int j; printf("\\v'-\\n[" SUP_RAISE_FORMAT "]u'", uid); for (j = 0; j < p[i]->len; j++) { switch (p[i]->align) { case LEFT_ALIGN: break; case CENTER_ALIGN: printf("\\h'\\n[" COLUMN_WIDTH_FORMAT "]u-\\n[" WIDTH_FORMAT "]u/2u'", uid, i, p[i]->p[j]->uid); break; case RIGHT_ALIGN: printf("\\h'\\n[" COLUMN_WIDTH_FORMAT "]u-\\n[" WIDTH_FORMAT "]u'", uid, i, p[i]->p[j]->uid); break; default: assert(0); } p[i]->p[j]->output(); printf("\\h'-\\n[" WIDTH_FORMAT "]u'", p[i]->p[j]->uid); switch (p[i]->align) { case LEFT_ALIGN: break; case CENTER_ALIGN: printf("\\h'\\n[" WIDTH_FORMAT "]u-\\n[" COLUMN_WIDTH_FORMAT "]u/2u'", p[i]->p[j]->uid, uid, i); break; case RIGHT_ALIGN: printf("\\h'\\n[" WIDTH_FORMAT "]u-\\n[" COLUMN_WIDTH_FORMAT "]u'", p[i]->p[j]->uid, uid, i); break; default: assert(0); } if (j != p[i]->len - 1) printf("\\v'\\n[" BASELINE_SEP_FORMAT "]u'", uid); } printf("\\v'\\n[" SUP_RAISE_FORMAT "]u'", uid); printf("\\v'-(%du*\\n[" BASELINE_SEP_FORMAT "]u)'", p[i]->len - 1, uid); printf("\\h'\\n[" COLUMN_WIDTH_FORMAT "]u'", uid, i); if (i != len - 1) printf("\\h'%dM'", column_sep); } printf("\\h'%dM'", matrix_side_sep); } matrix_box::matrix_box(column *pp) { p = new column*[10]; for (int i = 0; i < 10; i++) p[i] = 0; maxlen = 10; len = 1; p[0] = pp; } matrix_box::~matrix_box() { for (int i = 0; i < len; i++) delete p[i]; a_delete p; } void matrix_box::append(column *pp) { if (len + 1 > maxlen) { column **oldp = p; maxlen *= 2; p = new column*[maxlen]; memcpy(p, oldp, sizeof(column*)*len); a_delete oldp; } p[len++] = pp; } void matrix_box::check_tabs(int level) { for (int i = 0; i < len; i++) p[i]->list_check_tabs(level); } void matrix_box::debug_print() { fprintf(stderr, "matrix { "); p[0]->debug_print("col"); for (int i = 1; i < len; i++) { fprintf(stderr, " "); p[i]->debug_print("col"); } fprintf(stderr, " }"); } column::column(box *pp) : box_list(pp), align(CENTER_ALIGN), space(0) { } void column::set_alignment(alignment a) { align = a; } void column::set_space(int n) { space = n; } void column::debug_print(const char *s) { char c = '\0'; // shut up -Wall switch (align) { case LEFT_ALIGN: c = 'l'; break; case RIGHT_ALIGN: c = 'r'; break; case CENTER_ALIGN: c = 'c'; break; default: assert(0); } fprintf(stderr, "%c%s %d { ", c, s, space); list_debug_print(" above "); fprintf(stderr, " }"); }
26.619048
76
0.567467
dplbsd
10d3415f0bf6dfb9b91bc9f696525bab635f0bac
1,366
cpp
C++
tblock/source/GameLogic/Render.cpp
maximbilan/T-Block
b2eb3701a2567590090947a3c3dfb4afe282695a
[ "MIT" ]
1
2016-03-09T13:03:48.000Z
2016-03-09T13:03:48.000Z
tblock/source/GameLogic/Render.cpp
maximbilan/T-Block
b2eb3701a2567590090947a3c3dfb4afe282695a
[ "MIT" ]
null
null
null
tblock/source/GameLogic/Render.cpp
maximbilan/T-Block
b2eb3701a2567590090947a3c3dfb4afe282695a
[ "MIT" ]
null
null
null
#include "PlatformPrecomp.h" #include "Render.h" #include "Board.h" #include "GUI/GUI_MainMenu.h" #include "Defines/GameConstants.h" Render::Render() { if( !m_surface.IsLoaded() ) { char path[256]; sprintf( path, "%s%s", GetApp()->getResourceInstance()->getItem( GetApp()->getResolutionType(), RES_TYPE_ATLAS, RES_ID_NONE ).c_str(), s_textureUImenus ); m_surface.LoadFile( path ); } } Render::~Render() { } void Render::DrawRectangle( const float pX1, const float pY1, const E_TYPE_COLOR color, const float scaleX, const float scaleY ) { //m_surf[ color ].Blit( pX1, pY1 ); TextureImage* img = GetBaseApp()->getAtlasManager()->findImage( RES_TYPE_COLOR_ARRAY[ color ] ); float imgX = static_cast<float>( img->getX() ); float imgY = static_cast<float>( img->getY() ); float imgWidth = static_cast<float>( img->getWidth() ); float imgHeight = static_cast<float>( img->getHeight() ); rtRectf r( pX1, pY1, pX1 + imgWidth, pY1 + imgHeight ); r.Scale( ALIGNMENT_CENTER, CL_Vec2f( scaleX, scaleY ) ); rtRectf s( imgX, imgY, imgX + imgWidth , imgY + imgHeight ); s.Scale( ALIGNMENT_CENTER, CL_Vec2f( scaleX, scaleY ) ); m_surface.BlitEx( r, s ); } void Render::RDrawLine( const float pX1, const float pY1, const float pX2, const float pY2 ) { DrawLine( MAKE_RGBA( 0,255,0,100 ), pX1, pY1, pX2, pY2 ); }
31.767442
157
0.674231
maximbilan
10d5cb4f7e599120dc0499c44167d82f3b9cfbc5
1,486
hpp
C++
include/x2boost/flows/single_threaded_flow.hpp
jaykang920/x2boost
2a1160b7f840b7ceea6b18e61603ab4e0ce7a94c
[ "MIT" ]
null
null
null
include/x2boost/flows/single_threaded_flow.hpp
jaykang920/x2boost
2a1160b7f840b7ceea6b18e61603ab4e0ce7a94c
[ "MIT" ]
null
null
null
include/x2boost/flows/single_threaded_flow.hpp
jaykang920/x2boost
2a1160b7f840b7ceea6b18e61603ab4e0ce7a94c
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2017 Jae-jun Kang // See the file LICENSE for details. #ifndef X2BOOST_SINGLE_THREADED_FLOW_HPP_ #define X2BOOST_SINGLE_THREADED_FLOW_HPP_ #ifndef X2BOOST_PRE_HPP_ #include "x2boost/pre.hpp" #endif #include <boost/bind.hpp> #include <boost/thread.hpp> #include "x2boost/flows/event_based_flow.hpp" namespace x2boost { template<class Q = synchronized_event_queue> class X2BOOST_API single_threaded_flow : public event_based_flow<Q> { public: single_threaded_flow() : thread_(NULL) {} virtual ~single_threaded_flow() {} virtual void startup() { boost::mutex::scoped_lock lock(flow::mutex_); if (thread_) { return; } this->setup(); flow::case_stack_.setup(boost::enable_shared_from_this<flow>::shared_from_this()); thread_ = new boost::thread(boost::bind(&event_based_flow<Q>::run, this)); } virtual void shutdown() { boost::mutex::scoped_lock lock(flow::mutex_); if (!thread_) { return; } // enqueue flow_stop event_based_flow<Q>::queue_.close(); thread_->join(); delete thread_; thread_ = NULL; flow::case_stack_.teardown(boost::enable_shared_from_this<flow>::shared_from_this()); this->teardown(); } protected: boost::thread* thread_; }; } #endif // X2BOOST_SINGLE_THREADED_FLOW_HPP_
25.186441
97
0.625841
jaykang920
10d9b0b871e2fb9e55ea17a6f14df7e05784e5da
906
cpp
C++
Codechef/Div2/Long_Challenge/APRIL21B/BOLT.cpp
Pankajcoder1/Competitive_programming
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
[ "MIT" ]
null
null
null
Codechef/Div2/Long_Challenge/APRIL21B/BOLT.cpp
Pankajcoder1/Competitive_programming
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
[ "MIT" ]
null
null
null
Codechef/Div2/Long_Challenge/APRIL21B/BOLT.cpp
Pankajcoder1/Competitive_programming
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
[ "MIT" ]
1
2020-10-02T04:51:22.000Z
2020-10-02T04:51:22.000Z
/* written by Pankaj Kumar. country:-INDIA Institute: National Institute of Technology, Uttarakhand */ #include<bits/stdc++.h> using namespace std; long long solve() { double k1,k2,k3,v; cin>>k1>>k2>>k3>>v; cout<<setprecision(10)<<fixed; cout.precision(2); v=v*k1*k2*k3; double req_time=100.0/v; // cout<<"req_time is "<<req_time<<endl; if(req_time>=double(9.575)) cout<<"NO"<<endl; else cout<<"YES"<<endl; return 0; } int main() { // #ifndef ONLINEJUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); // #endif long long test=1; cin>>test; // scanf("%lld",&test); while(test--) { solve(); } return 0; } /* stuff you should look before submission * int overflow * special test case (n=0||n=1||n=2) * don't get stuck on one approach if you get wrong answer */
20.590909
60
0.582781
Pankajcoder1
10de4211acb431f392544838bd777d84390f3f0b
878
cpp
C++
poo/POO21/matrix.cpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
poo/POO21/matrix.cpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
poo/POO21/matrix.cpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
#include "matrix.h" Matrix::Matrix(){ nCols = 0; nRows = 0; m = 0; } Matrix::Matrix(int rows, int cols, double elem){ nCols = cols; nRows = rows; m = new double *[rows]; for (int i = 0; i < nRows; i++){ m[i]= new double [nCols]; for (int j = 0; j < nCols; j++) m[i][j]=elem; } } Matrix::~Matrix() { for(int i = 0; i < nRows; ++i) { delete [] m[i]; } delete []m; } int Matrix::getRows() const { return nRows; } int Matrix::getCols() const { return nCols; } Matrix Matrix::transpose() { double elem = m[0][0]; Matrix nova_matriz = Matrix(nCols, nRows, elem); return nova_matriz; } void Matrix::print() const { for (int i = 0; i < nRows; i++){ for (int j = 0; j < nCols; j++){ std::cout << m[i][j] << " "; } std::cout << std::endl; } }
18.291667
52
0.48861
pganaclara
10e02f0f4d2b518187620dad4681f4ebae9c6bcb
2,409
cpp
C++
src/egl-client-wayland.cpp
ceyusa/WPEBackend-fdo
e4c578f23359dba4d5abbd14b108f59e1b0701c1
[ "BSD-2-Clause" ]
16
2018-06-26T13:37:04.000Z
2022-03-11T14:08:22.000Z
src/egl-client-wayland.cpp
ceyusa/WPEBackend-fdo
e4c578f23359dba4d5abbd14b108f59e1b0701c1
[ "BSD-2-Clause" ]
118
2018-03-07T11:01:45.000Z
2022-02-01T19:44:14.000Z
src/egl-client-wayland.cpp
ceyusa/WPEBackend-fdo
e4c578f23359dba4d5abbd14b108f59e1b0701c1
[ "BSD-2-Clause" ]
16
2018-02-20T19:31:13.000Z
2021-02-23T21:10:57.000Z
/* * Copyright (C) 2020 Igalia S.L. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <wayland-egl.h> #include "egl-client-wayland.h" #include "ws-client.h" namespace WS { namespace EGLClient { BackendWayland::BackendWayland(BaseBackend& base) : m_base(base) { } BackendWayland::~BackendWayland() = default; EGLNativeDisplayType BackendWayland::nativeDisplay() const { return m_base.display(); } uint32_t BackendWayland::platform() const { return 0; } TargetWayland::TargetWayland(BaseTarget& base, uint32_t width, uint32_t height) : m_base(base) { m_egl.window = wl_egl_window_create(base.surface(), width, height); } TargetWayland::~TargetWayland() { g_clear_pointer(&m_egl.window, wl_egl_window_destroy); } EGLNativeWindowType TargetWayland::nativeWindow() const { return m_egl.window; } void TargetWayland::resize(uint32_t width, uint32_t height) { wl_egl_window_resize(m_egl.window, width, height, 0, 0); } void TargetWayland::frameWillRender() { m_base.requestFrame(); } void TargetWayland::frameRendered() { } void TargetWayland::deinitialize() { } } } // namespace WS::EGLClient
27.375
79
0.75301
ceyusa
10e174a1891644c6e05acfb6904f4e33c0edbbb0
1,961
hpp
C++
include/rasm2/control/trajectory_structures.hpp
ASM-Advised-Projects/rasm-software
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
[ "MIT" ]
3
2019-10-31T15:04:35.000Z
2021-06-24T16:35:18.000Z
include/rasm2/control/trajectory_structures.hpp
ASM-Advised-Projects/rasm-software
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
[ "MIT" ]
null
null
null
include/rasm2/control/trajectory_structures.hpp
ASM-Advised-Projects/rasm-software
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
[ "MIT" ]
2
2019-02-26T20:41:15.000Z
2019-05-14T01:40:40.000Z
/** * */ #ifndef RASM2_CONTROL_TRAJECTORY_STRUCTURES_HPP #define RASM2_CONTROL_TRAJECTORY_STRUCTURES_HPP #include <vector> #include <map> #include <functional> /** * */ class TrajectorySegment { private: std::vector<double> times; std::vector<double> positions; std::function<double (int)> position_function; public: TrajectorySegment(const std::vector<double> &times, const std::vector<double> &positions) { this->times = times; this->positions = positions; } TrajectorySegment(int start_time, int end_time, const std::function<double (int)> &time_to_pos) { times = std::vector<double>(2); positions = std::vector<double>(2); times[0] = (double)start_time; times[1] = (double)end_time; positions[0] = time_to_pos(start_time); positions[1] = time_to_pos(end_time); position_function = time_to_pos; } double position(int time_millis) { } void set_time_scale(double factor) { } int start_time() { return times[0]; } int end_time() { return times.back(); } }; /** * */ class Trajectory1D { private: std::vector<TrajectorySegment> segments; public: Trajectory1D() { } void add_segment(TrajectorySegment segment) { segments.push_back(segment); } double position(int time_ms) { } void set_time_scale(double factor) { } int start_time() { return segments[0].start_time(); } int end_time() { return segments.back().end_time(); } }; /** * */ class Trajectory6D { private: std::map<Joint, Trajectory1D> trajectories; public: Trajectory6D() { } void set_trajectory(Joint joint, Trajectory1D trajectory) { trajectories[joint] = trajectory; } double position(Joint joint, int time_millis) { } void autoscale() { } int start_time() { return trajectories[BASE].start_time(); } int end_time() { return trajectories[BASE].start_time(); } }; #endif
13.431507
97
0.653238
ASM-Advised-Projects
10e1db10fb60276c8e5926e7a6bf5316a14ea427
5,655
cpp
C++
src/ShaderCompiler.cpp
alandtse/SSEShaderTools
f73f4dcb334ff811bf634caa31ba4073c149e293
[ "MIT" ]
1
2021-11-11T19:35:42.000Z
2021-11-11T19:35:42.000Z
src/ShaderCompiler.cpp
alandtse/SSEShaderTools
f73f4dcb334ff811bf634caa31ba4073c149e293
[ "MIT" ]
1
2021-08-20T02:34:59.000Z
2022-01-17T04:01:35.000Z
src/ShaderCompiler.cpp
alandtse/SSEShaderTools
f73f4dcb334ff811bf634caa31ba4073c149e293
[ "MIT" ]
1
2021-11-11T19:35:48.000Z
2021-11-11T19:35:48.000Z
#include <functional> #include "d3dcompiler.h" #include "REL/Relocation.h" #include "BSShader/BSShaderTypes.h" #include "offsets.h" namespace ShaderCompiler { REL::Offset<ID3D11Device**> g_ID3D11Device_ptr(Offsets::BSShader::g_ID3D11Device); BSShader::VertexShader* CompileVertexShader(const std::wstring a_filePath, const std::vector<std::pair<const char*, const char*>>& Defines) { D3D_SHADER_MACRO macros[20+3+1]; memset(macros, 0, sizeof macros); for (size_t i = 0; i < Defines.size(); i++) { macros[i].Name = Defines[i].first; macros[i].Definition = Defines[i].second; } macros[Defines.size() + 0].Name = "WINPC"; macros[Defines.size() + 0].Definition = ""; macros[Defines.size() + 1].Name = "DX11"; macros[Defines.size() + 1].Definition = ""; macros[Defines.size() + 2].Name = "VERTEXSHADER"; macros[Defines.size() + 2].Definition = ""; UINT compilerFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3; ID3DBlob* shaderBlob = nullptr; ID3DBlob* shaderErrors = nullptr; if (FAILED(D3DCompileFromFile(a_filePath.c_str(), macros, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VSMain", "vs_5_0", compilerFlags, 0, &shaderBlob, &shaderErrors))) { _ERROR("Vertex shader compilation failed:\n%s", shaderErrors ? (const char*)shaderErrors->GetBufferPointer() : "Unknown error"); if (shaderBlob) shaderBlob->Release(); if (shaderErrors) shaderErrors->Release(); return nullptr; } if (shaderErrors) shaderErrors->Release(); _DMESSAGE("shader compilation succeeded"); _DMESSAGE("registering shader"); ID3D11VertexShader* regShader; if (FAILED((*g_ID3D11Device_ptr)->CreateVertexShader(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), nullptr, &regShader))) { _ERROR("vertex shader registration failed"); if (shaderBlob) shaderBlob->Release(); return nullptr; } _DMESSAGE("shader registration succeeded"); void* rawPtr = malloc(sizeof(BSShader::VertexShader) + shaderBlob->GetBufferSize()); BSShader::VertexShader* vs = new (rawPtr) BSShader::VertexShader; vs->m_Shader = regShader; memcpy(vs->m_RawBytecode, shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize()); vs->m_ShaderLength = (uint32_t)shaderBlob->GetBufferSize(); return vs; } BSShader::PixelShader* CompilePixelShader(const std::wstring a_filePath, const std::vector<std::pair<const char*, const char*>>& Defines) { D3D_SHADER_MACRO macros[20 + 4 + 1]; memset(macros, 0, sizeof macros); for (size_t i = 0; i < Defines.size(); i++) { macros[i].Name = Defines[i].first; macros[i].Definition = Defines[i].second; } macros[Defines.size() + 0].Name = "WINPC"; macros[Defines.size() + 0].Definition = ""; macros[Defines.size() + 1].Name = "DX11"; macros[Defines.size() + 1].Definition = ""; macros[Defines.size() + 2].Name = "FIX_VANILLA_BUGS"; macros[Defines.size() + 2].Definition = ""; macros[Defines.size() + 3].Name = "PIXELSHADER"; macros[Defines.size() + 3].Definition = ""; UINT compilerFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3; ID3DBlob* shaderBlob = nullptr; ID3DBlob* shaderErrors = nullptr; if (FAILED(D3DCompileFromFile(a_filePath.c_str(), macros, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PSMain", "ps_5_0", compilerFlags, 0, &shaderBlob, &shaderErrors))) { _ERROR("pixel shader compilation failed:\n%s", shaderErrors ? (const char*)shaderErrors->GetBufferPointer() : "Unknown error"); if (shaderBlob) shaderBlob->Release(); if (shaderErrors) shaderErrors->Release(); return nullptr; } if (shaderErrors) shaderErrors->Release(); _DMESSAGE("shader compilation succeeded"); _DMESSAGE("registering shader"); ID3D11PixelShader* regShader; if (FAILED((*g_ID3D11Device_ptr)->CreatePixelShader(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), nullptr, &regShader))) { _ERROR("pixel shader registration failed"); if (shaderBlob) shaderBlob->Release(); return nullptr; } _DMESSAGE("shader registration succeeded"); void* rawPtr = malloc(sizeof(BSShader::PixelShader)); BSShader::PixelShader* ps = new (rawPtr) BSShader::PixelShader; ps->m_Shader = regShader; return ps; } ID3D11PixelShader* CompileAndRegisterPixelShader(const std::wstring a_filePath) { D3D_SHADER_MACRO macros[3]; memset(macros, 0, sizeof macros); macros[0].Name = "WINPC"; macros[0].Definition = ""; macros[1].Name = "DX11"; macros[1].Definition = ""; UINT compilerFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3; ID3DBlob* shaderBlob = nullptr; ID3DBlob* shaderErrors = nullptr; if (FAILED(D3DCompileFromFile(a_filePath.c_str(), macros, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "ps_5_0", compilerFlags, 0, &shaderBlob, &shaderErrors))) { _ERROR( "Pixel shader compilation failed:\n%s", shaderErrors ? (const char*)shaderErrors->GetBufferPointer() : "Unknown error"); if (shaderBlob) shaderBlob->Release(); if (shaderErrors) shaderErrors->Release(); return nullptr; } if (shaderErrors) shaderErrors->Release(); _DMESSAGE("shader compilation succeeded"); _DMESSAGE("registering shader"); ID3D11PixelShader* regShader; if (FAILED((*g_ID3D11Device_ptr)->CreatePixelShader(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), nullptr, &regShader))) { _ERROR("pixel shader registration failed"); if (shaderBlob) shaderBlob->Release(); return nullptr; } _DMESSAGE("shader registration succeeded"); return regShader; } }
28.275
162
0.708576
alandtse
10e4bb8f7ad5828bb8879c0ba703233171741d8c
13,588
cpp
C++
src/compute.cpp
boberfly/bakec
4563441ab26b857de6b2e9e6f24b6a965aebccfc
[ "MIT" ]
3
2018-09-07T03:44:08.000Z
2019-02-19T15:20:26.000Z
src/compute.cpp
boberfly/bakec
4563441ab26b857de6b2e9e6f24b6a965aebccfc
[ "MIT" ]
null
null
null
src/compute.cpp
boberfly/bakec
4563441ab26b857de6b2e9e6f24b6a965aebccfc
[ "MIT" ]
null
null
null
/* Copyright 2018 Oscar Sebio Cajaraville 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. */ #define DEBUG_EXPORT_DIRECTIONS_MAP 1 #include "compute.h" #include "logging.h" #include "math.h" #include "mesh.h" #include <fstream> #if DEBUG_EXPORT_DIRECTIONS_MAP #include "image.h" #endif bgfx::ProgramHandle CreateComputeProgram(const char *path) { std::ifstream ifs(path); std::string src((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); const char *src_str = src.c_str(); return CreateComputeProgramFromMemory(src_str); } inline bgfx::ProgramHandle CreateComputeProgramFromMemory(const char *src) { GLuint shader = glCreateShader(GL_COMPUTE_SHADER); glShaderSource(shader, 1, &src, nullptr); glCompileShader(shader); #if 1 { GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (compiled != GL_TRUE) { const size_t buffSize = 2048; char *buff = new char[buffSize]; GLsizei length; glGetShaderInfoLog(shader, (GLsizei)buffSize, &length, buff); logError("Compute", buff); //assert(false); } } #endif GLuint program = glCreateProgram(); glAttachShader(program, shader); glLinkProgram(program); return program; } namespace { bool rasterTriangle ( const Mesh *mesh, const Mesh *meshForMapping, const Mesh::Triangle &tri, const Vector2 &pixsize, const Vector2 &halfpix, const Vector2 &scale, MapUV *map ) { const auto &v0 = mesh->vertices[tri.vertexIndex0]; const auto &v1 = mesh->vertices[tri.vertexIndex1]; const auto &v2 = mesh->vertices[tri.vertexIndex2]; if (v0.texcoordIndex == UINT32_MAX || v1.texcoordIndex == UINT32_MAX || v2.texcoordIndex == UINT32_MAX || v0.normalIndex == UINT32_MAX || v1.normalIndex == UINT32_MAX || v2.normalIndex == UINT32_MAX) { return false; } const Vector3 p0 = mesh->positions[v0.positionIndex]; const Vector3 p1 = mesh->positions[v1.positionIndex]; const Vector3 p2 = mesh->positions[v2.positionIndex]; const Vector2 u0 = mesh->texcoords[v0.texcoordIndex]; const Vector2 u1 = mesh->texcoords[v1.texcoordIndex]; const Vector2 u2 = mesh->texcoords[v2.texcoordIndex]; const Vector3 n0 = mesh->normals[v0.normalIndex]; const Vector3 n1 = mesh->normals[v1.normalIndex]; const Vector3 n2 = mesh->normals[v2.normalIndex]; Vector3 d0 = n0; Vector3 d1 = n1; Vector3 d2 = n2; if (meshForMapping) { const auto &mv0 = meshForMapping->vertices[tri.vertexIndex0]; const auto &mv1 = meshForMapping->vertices[tri.vertexIndex1]; const auto &mv2 = meshForMapping->vertices[tri.vertexIndex2]; d0 = meshForMapping->normals[mv0.normalIndex]; d1 = meshForMapping->normals[mv1.normalIndex]; d2 = meshForMapping->normals[mv2.normalIndex]; } const Vector3 t0 = mesh->tangents.empty() ? Vector3(0) : mesh->tangents[tri.vertexIndex0]; const Vector3 t1 = mesh->tangents.empty() ? Vector3(0) : mesh->tangents[tri.vertexIndex1]; const Vector3 t2 = mesh->tangents.empty() ? Vector3(0) : mesh->tangents[tri.vertexIndex2]; const Vector3 b0 = mesh->tangents.empty() ? Vector3(0) : mesh->bitangents[tri.vertexIndex0]; const Vector3 b1 = mesh->tangents.empty() ? Vector3(0) : mesh->bitangents[tri.vertexIndex1]; const Vector3 b2 = mesh->tangents.empty() ? Vector3(0) : mesh->bitangents[tri.vertexIndex2]; // Note: Surely not the fastest algorithm const Vector2 u01 = (u0 - halfpix) * scale; const Vector2 u11 = (u1 - halfpix) * scale; const Vector2 u21 = (u2 - halfpix) * scale; const uint32_t xMin = std::min(uint32_t(std::roundf(std::fminf(u01.x, std::fminf(u11.x, u21.x)))), map->width); const uint32_t yMin = std::min(uint32_t(std::roundf(std::fminf(u01.y, std::fminf(u11.y, u21.y)))), map->height); const uint32_t xMax = std::min(uint32_t(std::roundf(std::fmaxf(u01.x, std::fmaxf(u11.x, u21.x)))), map->width); const uint32_t yMax = std::min(uint32_t(std::roundf(std::fmaxf(u01.y, std::fmaxf(u11.y, u21.y)))), map->height); for (uint32_t y = yMin; y <= yMax; ++y) { for (uint32_t x = xMin; x <= xMax; ++x) { const Vector2 xy((float)x, (float)y); const Vector2 uv = xy * pixsize + halfpix; const Vector3 b = Barycentric(uv, u0, u1, u2); if (b.x >= -0.001f && b.x <= 1 && b.y >= -0.001f && b.y <= 1 && b.z >= -0.001f && b.z <= 1) { int i = y * map->width + x; map->positions[i] = p0 * b.x + p1 * b.y + p2 * b.z; map->directions[i] = normalize(d0 * b.x + d1 * b.y + d2 * b.z); map->normals[i] = normalize(n0 * b.x + n1 * b.y + n2 * b.z); map->tangents[i] = normalize(t0 * b.x + t1 * b.y + t2 * b.z); map->bitangents[i] = normalize(b0 * b.x + b1 * b.y + b2 * b.z); } } } return true; } MapUV* createMapUV(const Mesh *mesh, const Mesh *meshDirs, uint32_t width, uint32_t height) { assert(mesh); MapUV *map = new MapUV(width, height); const Vector2 scale((float)width, (float)height); const Vector2 pixsize = Vector2(1.0f) / scale; const Vector2 halfpix = pixsize * 0.5f; //if (computeTangentSpace) { const size_t size = map->normals.size(); map->tangents.resize(size); map->bitangents.resize(size); } //for (int vindex = 0; vindex < mesh->positions.size(); vindex += 3) for (const auto &tri : mesh->triangles) { if (!rasterTriangle(mesh, meshDirs, tri, pixsize, halfpix, scale, map)) { delete map; return nullptr; } } return map; } float edgeDistance(const Vector3 &e0, const Vector3 &e1, const Vector3 &p) { const Vector3 v = p - e0; const Vector3 e = e1 - e0; const float t = dot(v, e) / dot(e, e); const Vector3 p1 = e0 + e * t; return length(p1 - p); } float triangleDistance(const Vector3 &p0, const Vector3 &p1, const Vector3 &p2, const Vector3 &p) { const float d0 = edgeDistance(p0, p1, p); const float d1 = edgeDistance(p0, p2, p); const float d2 = edgeDistance(p1, p2, p); return std::fminf(d0, std::fminf(d1, d2)); } #pragma optimize( "", off ) bool rasterTriangleEdge ( const Mesh *mesh, const Mesh *meshForMapping, const Mesh::Triangle &tri, const Vector2 &pixsize, const Vector2 &halfpix, const Vector2 &scale, const float edge, MapUV *map ) { const auto &v0 = mesh->vertices[tri.vertexIndex0]; const auto &v1 = mesh->vertices[tri.vertexIndex1]; const auto &v2 = mesh->vertices[tri.vertexIndex2]; if (v0.texcoordIndex == UINT32_MAX || v1.texcoordIndex == UINT32_MAX || v2.texcoordIndex == UINT32_MAX || v0.normalIndex == UINT32_MAX || v1.normalIndex == UINT32_MAX || v2.normalIndex == UINT32_MAX) { return false; } const Vector3 p0 = mesh->positions[v0.positionIndex]; const Vector3 p1 = mesh->positions[v1.positionIndex]; const Vector3 p2 = mesh->positions[v2.positionIndex]; const Vector2 u0 = mesh->texcoords[v0.texcoordIndex]; const Vector2 u1 = mesh->texcoords[v1.texcoordIndex]; const Vector2 u2 = mesh->texcoords[v2.texcoordIndex]; const Vector3 n0 = mesh->normals[v0.normalIndex]; const Vector3 n1 = mesh->normals[v1.normalIndex]; const Vector3 n2 = mesh->normals[v2.normalIndex]; Vector3 d0 = n0; Vector3 d1 = n1; Vector3 d2 = n2; if (meshForMapping) { const auto &mv0 = meshForMapping->vertices[tri.vertexIndex0]; const auto &mv1 = meshForMapping->vertices[tri.vertexIndex1]; const auto &mv2 = meshForMapping->vertices[tri.vertexIndex2]; d0 = meshForMapping->normals[mv0.normalIndex]; d1 = meshForMapping->normals[mv1.normalIndex]; d2 = meshForMapping->normals[mv2.normalIndex]; } const Vector3 t0 = mesh->tangents.empty() ? Vector3(0) : mesh->tangents[tri.vertexIndex0]; const Vector3 t1 = mesh->tangents.empty() ? Vector3(0) : mesh->tangents[tri.vertexIndex1]; const Vector3 t2 = mesh->tangents.empty() ? Vector3(0) : mesh->tangents[tri.vertexIndex2]; const Vector3 b0 = mesh->tangents.empty() ? Vector3(0) : mesh->bitangents[tri.vertexIndex0]; const Vector3 b1 = mesh->tangents.empty() ? Vector3(0) : mesh->bitangents[tri.vertexIndex1]; const Vector3 b2 = mesh->tangents.empty() ? Vector3(0) : mesh->bitangents[tri.vertexIndex2]; // Note: Surely not the fastest algorithm const Vector2 u01 = (u0 - halfpix) * scale; const Vector2 u11 = (u1 - halfpix) * scale; const Vector2 u21 = (u2 - halfpix) * scale; const uint32_t xMin = (uint32_t)std::fmaxf(std::roundf(std::fminf(u01.x, std::fminf(u11.x, u21.x))), 0.0f); const uint32_t yMin = (uint32_t)std::fmaxf(std::roundf(std::fminf(u01.y, std::fminf(u11.y, u21.y))), 0.0f); const uint32_t xMax = (uint32_t)std::fmaxf(std::roundf(std::fmaxf(u01.x, std::fmaxf(u11.x, u21.x))), 0.0f); const uint32_t yMax = (uint32_t)std::fmaxf(std::roundf(std::fmaxf(u01.y, std::fmaxf(u11.y, u21.y))), 0.0f); for (uint32_t y = yMin; y <= yMax; ++y) { for (uint32_t x = xMin; x <= xMax; ++x) { const Vector2 xy((float)x, (float)y); const Vector2 uv = xy * pixsize + halfpix; const Vector3 b = Barycentric(uv, u0, u1, u2); if (b.x >= -0.001f && b.x <= 1 && b.y >= -0.001f && b.y <= 1 && b.z >= -0.001f && b.z <= 1) { const int i = y * map->width + x; const Vector3 p = p0 * b.x + p1 * b.y + p2 * b.z; const Vector3 n = normalize(n0 * b.x + n1 * b.y + n2 * b.z); /*const float e0 = std::fminf(edgeDistance(p0, p1, p) / edge, 1.0f); const float e1 = std::fminf(edgeDistance(p1, p2, p) / edge, 1.0f); const float e2 = std::fminf(edgeDistance(p2, p0, p) / edge, 1.0f); const float ev0 = std::fminf(e0, e2); const float ev1 = std::fminf(e0, e1); const float ev2 = std::fminf(e1, e2); const Vector3 d0h = normalize(d0 * ev0 + n0 * (1.0f - ev0)); const Vector3 d1h = normalize(d1 * ev1 + n1 * (1.0f - ev1)); const Vector3 d2h = normalize(d2 * ev2 + n2 * (1.0f - ev2)); const Vector3 d = normalize(d0h * b.x + d1h * b.y + d2h * b.z);*/ const float t = std::fminf(triangleDistance(p0, p1, p2, p) / edge, 1.0f); const Vector3 dsmooth = normalize(d0 * b.x + d1 * b.y + d2 * b.z); const Vector3 d = normalize(dsmooth * (1.0f - t) + n * t); map->positions[i] = p; map->directions[i] = d; map->normals[i] = n; map->tangents[i] = normalize(t0 * b.x + t1 * b.y + t2 * b.z); map->bitangents[i] = normalize(b0 * b.x + b1 * b.y + b2 * b.z); } } } return true; } #pragma optimize( "", on ) MapUV* createMapUVEdge(const Mesh *mesh, const Mesh *meshDirs, uint32_t width, uint32_t height, float edge) { assert(mesh); MapUV *map = new MapUV(width, height); const Vector2 scale((float)width, (float)height); const Vector2 pixsize = Vector2(1.0f) / scale; const Vector2 halfpix = pixsize * 0.5f; //if (computeTangentSpace) { const size_t size = map->normals.size(); map->tangents.resize(size); map->bitangents.resize(size); } for (const auto &tri : mesh->triangles) { if (!rasterTriangleEdge(mesh, meshDirs, tri, pixsize, halfpix, scale, edge, map)) { delete map; return nullptr; } } return map; } } MapUV* MapUV::fromMesh(const Mesh *mesh, uint32_t width, uint32_t height) { assert(mesh); return createMapUV(mesh, nullptr, width, height); } MapUV* MapUV::fromMeshes(const Mesh *mesh, const Mesh *meshDirs, uint32_t width, uint32_t height) { assert(mesh); assert(meshDirs); return createMapUV(mesh, meshDirs, width, height); } MapUV* MapUV::fromMeshes_Hybrid(const Mesh *mesh, const Mesh *meshDirs, uint32_t width, uint32_t height, float edge) { assert(mesh); assert(meshDirs); return createMapUVEdge(mesh, meshDirs, width, height, edge); } CompressedMapUV::CompressedMapUV(const MapUV *map) : width(map->width) , height(map->height) { assert(map); assert(map->normals.size() > 0); for (size_t i = 0; i < map->directions.size(); ++i) { const Vector3 n = map->directions[i]; if (dot(n, n) > 0.5f) // With normal data { indices.emplace_back((uint32_t)i); } } positions.resize(indices.size()); directions.resize(indices.size()); for (size_t i = 0; i < indices.size(); ++i) { const size_t idx = indices[i]; positions[i] = map->positions[idx]; directions[i] = map->directions[idx]; } if (map->tangents.size() > 0) { assert(map->bitangents.size() == map->tangents.size()); normals.resize(indices.size()); tangents.resize(indices.size()); bitangents.resize(indices.size()); for (size_t i = 0; i < indices.size(); ++i) { const size_t idx = indices[i]; normals[i] = map->normals[idx]; tangents[i] = map->tangents[idx]; bitangents[i] = map->bitangents[idx]; } } #if DEBUG_EXPORT_DIRECTIONS_MAP exportNormalImage(&directions[0], this, "D:\\asdf.png"); #endif }
32.585132
116
0.666765
boberfly
10e5012f586e23ad32ff55566f1793980129389b
2,662
cpp
C++
tests/test_conv1d.cpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
3
2018-10-23T18:46:39.000Z
2019-06-24T00:46:10.000Z
tests/test_conv1d.cpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
27
2018-11-10T14:19:16.000Z
2020-03-08T23:33:01.000Z
tests/test_conv1d.cpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
1
2018-11-05T06:17:12.000Z
2018-11-05T06:17:12.000Z
#include <ttl/nn/bits/ops/impl/col2im1d.hpp> #include <ttl/nn/bits/ops/impl/conv1d.hpp> #include <ttl/nn/bits/ops/impl/im2col1d.hpp> #include <ttl/nn/testing> #include <ttl/experimental/show> template <typename R> void test_col2im1d(const int n, const int ksize = 1, const int stride = 1, const int rate = 1) { ttl::nn::traits::linear_padding_trait<int> padding(1); ttl::nn::ops::im2col1d upper(ksize, stride, rate, padding); ttl::nn::ops::col2im1d lower(ksize, stride, rate, padding); ttl::tensor<R, 1> x(n); ttl::tensor<R, 1> x1(n); ttl::tensor<R, 1> c(n); const auto [m, _k] = upper(x.shape()).dims(); static_assert(sizeof(_k) > 0, ""); // unused ttl::tensor<R, 2> x_upper(m, ksize); const auto x_shape = lower(x_upper.shape()); ASSERT_EQ(x_shape, x.shape()); std::iota(x.data(), x.data_end(), 1); upper(ref(x_upper), view(x)); // x -> x_upper lower(ref(x1), view(x_upper)); // x_upper -> x1 std::map<R, int> counts; for (auto i : ttl::range(x_upper.shape().size())) { ++counts[x_upper.data()[i]]; } for (auto i : ttl::range(x.shape().size())) { const R xi = x.data()[i]; ASSERT_EQ(xi * counts[xi], x1.data()[i]); } // std::cout << ttl::show(view(x)); // std::cout << ttl::show(view(x1)); // std::cout << ttl::show(view(x_upper)); } TEST(conv1d_test, test_col2im1d) { test_col2im1d<int>(9, 3); // test_col2im1d<int>(9, 3); } template <typename R> void test_conv1d(const int n, const int ksize, const int stride = 1, const int rate = 1) { ttl::nn::traits::linear_padding_trait<int> padding(1); ttl::nn::ops::conv1d f(stride, rate, padding); ttl::nn::ops::im2col1d upper(ksize, stride, rate, padding); ttl::tensor<R, 1> x(n); ttl::tensor<R, 1> y(ksize); ttl::tensor<R, 2> x_upper(upper(x.shape())); ttl::tensor<R, 1> z(f(x.shape(), y.shape())); ttl::tensor<R, 1> z1(z.shape()); std::iota(x.data(), x.data_end(), 1); std::iota(y.data(), y.data_end(), 1); std::iota(z.data(), z.data_end(), 1); f(ref(z), view(x), view(y)); upper(ref(x_upper), view(x)); using la = ttl::nn::engines::linag<ttl::nn::engines::builtin>; la::mv(view(x_upper), view(y), ref(z1)); assert_bytes_eq(view(z), view(z1)); // std::cout << ttl::show(view(x)); // std::cout << ttl::show(view(y)); // std::cout << ttl::show(view(z)); // std::cout << ttl::show(view(x_upper)); // std::cout << std::endl; } TEST(conv1d_test, test_conv1d) { test_conv1d<int>(9, 3); test_conv1d<int>(9, 3, 1, 2); test_conv1d<int>(9, 3, 1, 3); }
29.910112
74
0.579639
stdml