hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
6dc042ed072decdca6a96ad518c9b67e1c491e5a
275
cpp
C++
static function in c++/main.cpp
Adarsh1999/learn.cpp
bd9b5238d62d6e9f8ebd7b7b8efe745a30e56f92
[ "MIT" ]
null
null
null
static function in c++/main.cpp
Adarsh1999/learn.cpp
bd9b5238d62d6e9f8ebd7b7b8efe745a30e56f92
[ "MIT" ]
null
null
null
static function in c++/main.cpp
Adarsh1999/learn.cpp
bd9b5238d62d6e9f8ebd7b7b8efe745a30e56f92
[ "MIT" ]
1
2019-10-24T11:15:51.000Z
2019-10-24T11:15:51.000Z
#include<iostream> using namespace std; class sample { static int c; public: sample(){ c++; } static int display(){ return c; } }; int sample :: c; int main(){ sample s1,s2,s3,s4; cout<<"total Object = "<<sample :: display(); }
15.277778
49
0.538182
[ "object" ]
6dc07732de817873b68ab66f86f52a7e115615d0
45,536
cc
C++
tensorflow/core/ops/math_grad_test.cc
imdone/tensorflow
bb4d1ef3861c83627ee9586b85ac3070a7d38335
[ "Apache-2.0" ]
1
2021-04-16T14:53:22.000Z
2021-04-16T14:53:22.000Z
tensorflow/core/ops/math_grad_test.cc
imdone/tensorflow
bb4d1ef3861c83627ee9586b85ac3070a7d38335
[ "Apache-2.0" ]
10
2018-02-04T18:41:52.000Z
2018-05-02T09:00:46.000Z
tensorflow/core/ops/math_grad_test.cc
imdone/tensorflow
bb4d1ef3861c83627ee9586b85ac3070a7d38335
[ "Apache-2.0" ]
4
2018-01-17T14:22:49.000Z
2018-02-27T15:06:41.000Z
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <vector> #include "tensorflow/core/framework/function_testlib.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/session.h" namespace tensorflow { namespace { namespace f = test::function; using FDH = FunctionDefHelper; std::unique_ptr<Session> NewSession() { SessionOptions opts; (*opts.config.mutable_device_count())["CPU"] = 1; return std::unique_ptr<Session>(NewSession(opts)); } class MathGradTest : public ::testing::Test { protected: // Unary Status Unary(const string& op, const Tensor& x, Tensor* y) { const DataType T = x.dtype(); auto adef = [T](const string& name) { // E.g., x:float, dy:double return strings::StrCat(name, ":", DataTypeString(T)); }; // Sum(op(x)), sum all output of op(x). auto test = FDH::Define("Test", {adef("x")}, {adef("l")}, {}, { {{"y"}, op, {"x"}, {{"T", T}}}, FDH::Const("zero", 0), FDH::Const("one", 1), {{"r"}, "Rank", {"x"}, {{"T", T}}}, {{"indices"}, "Range", {"zero", "r", "one"}}, {{"l"}, "Sum", {"y", "indices"}, {{"T", T}}}, }); // TestGrad = Test'(x) auto grad = FDH::Define( "TestGrad", {adef("x")}, {adef("dx")}, {}, { FDH::Const("one", 1), {{"dy"}, "Cast", {"one"}, {{"DstT", T}, {"SrcT", DT_INT32}}}, {{"grad"}, "SymbolicGradient", {"x", "dy"}, { {"f", FDH::FunctionRef("Test")}, {"Tin", DataTypeSlice{T, T}}, {"Tout", DataTypeSlice{T}}, }}, {{"dx"}, "Identity", {"grad"}, {{"T", T}}}, }); // Each test case will feed in "x:0" and expects to get "dx:0". auto gdef = test::function::GDef( { f::NDef("x", "Placeholder", {}, {{"dtype", T}}), f::NDef("dx", "TestGrad", {"x"}, {}), }, {test, grad}); auto sess = NewSession(); TF_CHECK_OK(sess->Create(gdef)); std::vector<Tensor> outputs; auto s = sess->Run({{"x:0", x}}, {"dx:0"}, {}, &outputs); if (s.ok()) { CHECK_EQ(outputs.size(), 1); *y = outputs[0]; } TF_CHECK_OK(sess->Close()); return s; } // Unary op expecting OK. Tensor SymGrad(const string& op, const Tensor& x) { Tensor ret; TF_CHECK_OK(Unary(op, x, &ret)); return ret; } // Binary void SymGrad(const string& op, const Tensor& x, const Tensor& y, Tensor* dx, Tensor* dy) { const DataType T = x.dtype(); auto adef = [T](const string& name) { // E.g., x:float, dy:double return strings::StrCat(name, ":", DataTypeString(T)); }; // Sum(op(x)), sum all output of op(x). auto test = FDH::Define("Test", {adef("x"), adef("y")}, {adef("l")}, {}, { {{"z"}, op, {"x", "y"}, {{"T", T}}}, FDH::Const("zero", 0), FDH::Const("one", 1), {{"r"}, "Rank", {"z"}, {{"T", T}}}, {{"indices"}, "Range", {"zero", "r", "one"}}, {{"l"}, "Sum", {"z", "indices"}, {{"T", T}}}, }); // TestGrad = Test'(x, y) auto grad = FDH::Define( "TestGrad", {adef("x"), adef("y")}, {adef("dx"), adef("dy")}, {}, { FDH::Const("one", 1), {{"dz"}, "Cast", {"one"}, {{"DstT", T}, {"SrcT", DT_INT32}}}, {{"grad0", "grad1"}, "SymbolicGradient", {"x", "y", "dz"}, { {"f", FDH::FunctionRef("Test")}, {"Tin", DataTypeSlice{T, T, T}}, {"Tout", DataTypeSlice{T, T}}, }}, {{"dx"}, "Identity", {"grad0"}, {{"T", T}}}, {{"dy"}, "Identity", {"grad1"}, {{"T", T}}}, }); // Each test case will feed in "x:0" and "y:0" and expects to get "d0" and // "d:0". auto gdef = test::function::GDef( { f::NDef("x", "Placeholder", {}, {{"dtype", T}}), f::NDef("y", "Placeholder", {}, {{"dtype", T}}), f::NDef("d", "TestGrad", {"x", "y"}, {}), }, {test, grad}); auto sess = NewSession(); TF_CHECK_OK(sess->Create(gdef)); std::vector<Tensor> outputs; TF_CHECK_OK( sess->Run({{"x:0", x}, {"y:0", y}}, {"d:0", "d:1"}, {}, &outputs)); CHECK_EQ(outputs.size(), 2); TF_CHECK_OK(sess->Close()); *dx = outputs[0]; *dy = outputs[1]; } // Reduction grad void ReductionGrad(const string& op, const Tensor& x, const Tensor& idx, Tensor* dx, Tensor* di) { const DataType T = x.dtype(); auto adef = [T](const string& name) { // E.g., x:float, dy:double return strings::StrCat(name, ":", DataTypeString(T)); }; // Sum(op(x, idx)), sum all output of op(x, idx). auto test = FDH::Define("Test", {adef("x"), "i:int32"}, {adef("l")}, {}, { {{"y"}, op, {"x", "i"}, {{"T", T}}}, FDH::Const("zero", 0), FDH::Const("one", 1), {{"r"}, "Rank", {"y"}, {{"T", T}}}, {{"indices"}, "Range", {"zero", "r", "one"}}, {{"l"}, "Sum", {"y", "indices"}, {{"T", T}}}, }); // TestGrad = Test'(x) auto grad = FDH::Define( "TestGrad", {adef("x"), "i:int32"}, {adef("dx"), "di:int32"}, {}, { FDH::Const("one", 1), {{"dy"}, "Cast", {"one"}, {{"DstT", T}, {"SrcT", DT_INT32}}}, {{"grad0", "grad1"}, "SymbolicGradient", {"x", "i", "dy"}, { {"f", FDH::FunctionRef("Test")}, {"Tin", DataTypeSlice{T, DT_INT32, T}}, {"Tout", DataTypeSlice{T, DT_INT32}}, }}, {{"dx"}, "Identity", {"grad0"}, {{"T", T}}}, {{"di"}, "Identity", {"grad1"}, {{"T", DT_INT32}}}, }); // Each test case will feed in "x:0" and expects to get "dx:0". auto gdef = test::function::GDef( { f::NDef("x", "Placeholder", {}, {{"dtype", T}}), f::NDef("i", "Placeholder", {}, {{"dtype", DT_INT32}}), f::NDef("d", "TestGrad", {"x", "i"}, {}), }, {test, grad}); auto sess = NewSession(); TF_CHECK_OK(sess->Create(gdef)); std::vector<Tensor> outputs; TF_CHECK_OK( sess->Run({{"x:0", x}, {"i:0", idx}}, {"d:0", "d:1"}, {}, &outputs)); CHECK_EQ(outputs.size(), 2); TF_CHECK_OK(sess->Close()); *dx = outputs[0]; *di = outputs[1]; } Tensor MatMulCommon(const string& opname, const string& attr_adj_x, const string& attr_adj_y, const Tensor& x, bool ax, const Tensor& y, bool ay) { auto T = x.dtype(); auto gdef = test::function::GDef( { f::NDef("x", "Placeholder", {}, {{"dtype", T}}), f::NDef("y", "Placeholder", {}, {{"dtype", T}}), f::NDef("z", opname, {"x", "y"}, {{"T", T}, {attr_adj_x, ax}, {attr_adj_y, ay}}), }, {}); auto sess = NewSession(); TF_CHECK_OK(sess->Create(gdef)); std::vector<Tensor> outputs; TF_CHECK_OK(sess->Run({{"x:0", x}, {"y:0", y}}, {"z:0"}, {}, &outputs)); CHECK_EQ(outputs.size(), 1); TF_CHECK_OK(sess->Close()); return outputs[0]; } Tensor MatMul(const Tensor& x, bool ax, const Tensor& y, bool ay) { return MatMulCommon("MatMul", "transpose_a", "transpose_b", x, ax, y, ay); } Tensor BatchMatMul(const Tensor& x, bool ax, const Tensor& y, bool ay) { return MatMulCommon("BatchMatMul", "adj_x", "adj_y", x, ax, y, ay); } void MatMulGradCommon(const string& opname, const string& attr_adj_x, const string& attr_adj_y, const Tensor& x, bool ax, const Tensor& y, bool ay, Tensor* dx, Tensor* dy) { const DataType T = x.dtype(); auto adef = [T](const string& name) { // E.g., x:float, dy:double return strings::StrCat(name, ":", DataTypeString(T)); }; // Sum(op(x)), sum all output of op(x). auto test = FDH::Define("Test", {adef("x"), adef("y")}, {adef("l")}, {}, { {{"z"}, opname, {"x", "y"}, {{"T", T}, {attr_adj_x, ax}, {attr_adj_y, ay}}}, FDH::Const("zero", 0), FDH::Const("one", 1), {{"r"}, "Rank", {"z"}, {{"T", T}}}, {{"indices"}, "Range", {"zero", "r", "one"}}, {{"l"}, "Sum", {"z", "indices"}, {{"T", T}}}, }); // TestGrad = Test'(x, y) auto grad = FDH::Define( "TestGrad", {adef("x"), adef("y")}, {adef("dx"), adef("dy")}, {}, { FDH::Const("one", 1), {{"dz"}, "Cast", {"one"}, {{"DstT", T}, {"SrcT", DT_INT32}}}, {{"grad0", "grad1"}, "SymbolicGradient", {"x", "y", "dz"}, { {"f", FDH::FunctionRef("Test")}, {"Tin", DataTypeSlice{T, T, T}}, {"Tout", DataTypeSlice{T, T}}, }}, {{"dx"}, "Identity", {"grad0"}, {{"T", T}}}, {{"dy"}, "Identity", {"grad1"}, {{"T", T}}}, }); // Each test case will feed in "x:0" and "y:0" and expects to get "d0" and // "d:0". auto gdef = test::function::GDef( { f::NDef("x", "Placeholder", {}, {{"dtype", T}}), f::NDef("y", "Placeholder", {}, {{"dtype", T}}), f::NDef("d", "TestGrad", {"x", "y"}, {}), }, {test, grad}); auto sess = NewSession(); TF_CHECK_OK(sess->Create(gdef)); std::vector<Tensor> outputs; TF_CHECK_OK( sess->Run({{"x:0", x}, {"y:0", y}}, {"d:0", "d:1"}, {}, &outputs)); CHECK_EQ(outputs.size(), 2); TF_CHECK_OK(sess->Close()); *dx = outputs[0]; *dy = outputs[1]; } void MatMulGrad(const Tensor& x, bool ax, const Tensor& y, bool ay, Tensor* dx, Tensor* dy) { return MatMulGradCommon("MatMul", "transpose_a", "transpose_b", x, ax, y, ay, dx, dy); } void BatchMatMulGrad(const Tensor& x, bool ax, const Tensor& y, bool ay, Tensor* dx, Tensor* dy) { return MatMulGradCommon("BatchMatMul", "adj_x", "adj_y", x, ax, y, ay, dx, dy); } void SelectGrad(const Tensor& c, const Tensor& x, const Tensor& y, Tensor* dc, Tensor* dx, Tensor* dy) { auto T = DT_FLOAT; // Sum(Select(c, x, y)) auto test = FDH::Define("Test", {"c:bool", "x:float", "y:float"}, {"l:float"}, {}, { {{"z"}, "Select", {"c", "x", "y"}, {{"T", T}}}, FDH::Const("zero", 0), FDH::Const("one", 1), {{"r"}, "Rank", {"z"}, {{"T", T}}}, {{"indices"}, "Range", {"zero", "r", "one"}}, {{"l"}, "Sum", {"z", "indices"}, {{"T", T}}}, }); // TestGrad(x, y) = Test'(c, x, y) auto grad = FDH::Define("TestGrad", {"c:bool", "x:float", "y:float"}, {"dc:bool", "dx:float", "dy:float"}, {}, {FDH::Const("dz", 1.f), {{"grad0", "grad1", "grad2"}, "SymbolicGradient", {"c", "x", "y", "dz"}, { {"f", FDH::FunctionRef("Test")}, {"Tin", DataTypeSlice{DT_BOOL, T, T, T}}, {"Tout", DataTypeSlice{DT_BOOL, T, T}}, }}, {{"dc"}, "Identity", {"grad0"}, {{"T", DT_BOOL}}}, {{"dx"}, "Identity", {"grad1"}, {{"T", T}}}, {{"dy"}, "Identity", {"grad2"}, {{"T", T}}}}); // Each test case will feed in "x:0" and expects to get "dx:0". auto gdef = test::function::GDef( { f::NDef("c", "Placeholder", {}, {{"dtype", DT_BOOL}}), f::NDef("x", "Placeholder", {}, {{"dtype", T}}), f::NDef("y", "Placeholder", {}, {{"dtype", T}}), f::NDef("d", "TestGrad", {"c", "x", "y"}, {}), }, {test, grad}); auto sess = NewSession(); TF_CHECK_OK(sess->Create(gdef)); std::vector<Tensor> outputs; TF_CHECK_OK(sess->Run({{"c:0", c}, {"x:0", x}, {"y:0", y}}, {"d:0", "d:1", "d:2"}, {}, &outputs)); CHECK_EQ(outputs.size(), 3); TF_CHECK_OK(sess->Close()); *dc = outputs[0]; *dx = outputs[1]; *dy = outputs[2]; } }; void HasError(const Status& s, const string& substr) { EXPECT_TRUE(str_util::StrContains(s.ToString(), substr)) << s << ", expected substring " << substr; } REGISTER_OP("TestOpWithNoGrad") .Input("x: T") .Output("y: T") .Attr("T: {float, double}") .Doc(R"doc( Test op with no grad registered. x: input y: output )doc"); class TestOp : public OpKernel { public: explicit TestOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { ctx->set_output(0, Tensor()); } }; REGISTER_KERNEL_BUILDER(Name("TestOpWithNoGrad").Device(DEVICE_CPU), TestOp); #ifdef TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("TestOpWithNoGrad").Device(DEVICE_SYCL), TestOp); #endif // TENSORFLOW_USE_SYCL TEST_F(MathGradTest, Error_Reporting) { auto x = test::AsTensor<float>({-3.f}); auto dx = test::AsTensor<float>({3.f}); Tensor donotcare; HasError(Unary("TestOpWithNoGrad", x, &donotcare), "No gradient defined for op: TestOpWithNoGrad"); } TEST_F(MathGradTest, Abs) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return x < 0 ? -1.f : 1.f; }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Abs", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Neg) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return -1.f; }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Neg", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Reciprocal) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return -1.f / (x * x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Reciprocal", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Square) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return 2 * x; }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Square", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Sqrt) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({2, 3})); auto g = [](float x) { return 0.5f / std::sqrt(x); }; auto dx = test::AsTensor<float>( {g(1.f), g(2.f), g(3.f), g(4.f), g(5.f), g(6.f)}, TensorShape({2, 3})); auto ans = SymGrad("Sqrt", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Rsqrt) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({2, 3})); auto g = [](float x) { return -0.5f / (x * std::sqrt(x)); }; auto dx = test::AsTensor<float>( {g(1.f), g(2.f), g(3.f), g(4.f), g(5.f), g(6.f)}, TensorShape({2, 3})); auto ans = SymGrad("Rsqrt", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Exp) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return std::exp(x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Exp", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Expm1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return std::exp(x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Expm1", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Log) { auto x = test::AsTensor<float>({0.1f, 1.f, 2.f, 3.f, 4.f, 10.f}, TensorShape({2, 3})); auto g = [](float x) { return 1 / x; }; auto dx = test::AsTensor<float>( {g(.1f), g(1.f), g(2.f), g(3.f), g(4.f), g(10.f)}, TensorShape({2, 3})); auto ans = SymGrad("Log", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Log1p) { auto x = test::AsTensor<float>({0.1f, 1.f, 2.f, 3.f, 4.f, 10.f}, TensorShape({2, 3})); auto g = [](float x) { return 1 / (1 + x); }; auto dx = test::AsTensor<float>( {g(.1f), g(1.f), g(2.f), g(3.f), g(4.f), g(10.f)}, TensorShape({2, 3})); auto ans = SymGrad("Log1p", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Sinh) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return std::cosh(x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Sinh", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Cosh) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return std::sinh(x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Cosh", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Tanh) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { auto y = std::tanh(x); return 1 - y * y; }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Tanh", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Asinh) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { auto y = std::asinh(x); return std::cosh(y); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Asinh", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Acosh) { auto x = test::AsTensor<float>({6.f, 5.f, 4.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { auto y = std::acosh(x); return std::sinh(y); }; auto dx = test::AsTensor<float>( {g(6.f), g(5.f), g(4.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Acosh", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Atanh) { auto x = test::AsTensor<float>({-0.3f, -0.2f, -0.1f, 0.1f, 0.2f, 0.3f}, TensorShape({2, 3})); auto g = [](float x) { return 1.f / (1.f - x * x); }; auto dx = test::AsTensor<float>( {g(-0.3f), g(-0.2f), g(-0.1f), g(0.1f), g(0.2f), g(0.3f)}, TensorShape({2, 3})); auto ans = SymGrad("Atanh", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Sigmoid) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { auto y = 1.f / (1.f + std::exp(-x)); return y * (1 - y); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Sigmoid", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Sign) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return 0.f; }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Sign", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Sin) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return std::cos(x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Sin", x); test::ExpectClose(ans, dx); } TEST_F(MathGradTest, Cos) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto g = [](float x) { return -std::sin(x); }; auto dx = test::AsTensor<float>( {g(-3.f), g(-2.f), g(-1.f), g(1.f), g(2.f), g(3.f)}, TensorShape({2, 3})); auto ans = SymGrad("Cos", x); test::ExpectClose(ans, dx); } // TODO (zhifengc) id:2959 // https://github.com/imdone/tensorflow/issues/2958 // TEST_F(MathGradSComplexTest, Real) {} // TEST_F(MathGradSComplexTest, Imag) {} // TEST_F(MathGradSComplexTest, Angle) {} // TEST_F(MathGradSComplexTest, Conj) {} // TEST_F(MathGradTernary, Select) {} TEST_F(MathGradTest, Add) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-10.f, 10.f}, TensorShape({2, 1})); auto ans_dx = test::AsTensor<float>({1.f, 1.f, 1.f, 1.f, 1.f, 1.f}, TensorShape({2, 3})); auto ans_dy = test::AsTensor<float>({3.f, 3.f}, TensorShape({2, 1})); Tensor dx; Tensor dy; { SymGrad("Add", x, y, &dx, &dy); test::ExpectClose(ans_dx, dx); test::ExpectClose(ans_dy, dy); } { // Swap x and y SymGrad("Add", y, x, &dy, &dx); test::ExpectClose(ans_dx, dx); test::ExpectClose(ans_dy, dy); } } TEST_F(MathGradTest, Sub) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-10.f, 10.f}, TensorShape({2, 1})); Tensor dx; Tensor dy; { SymGrad("Sub", x, y, &dx, &dy); auto ans_dx = test::AsTensor<float>({1.f, 1.f, 1.f, 1.f, 1.f, 1.f}, TensorShape({2, 3})); auto ans_dy = test::AsTensor<float>({-3.f, -3.f}, TensorShape({2, 1})); test::ExpectClose(ans_dx, dx); test::ExpectClose(ans_dy, dy); } { // Swap x and y SymGrad("Sub", y, x, &dy, &dx); auto ans_dx = test::AsTensor<float>({-1.f, -1.f, -1.f, -1.f, -1.f, -1.f}, TensorShape({2, 3})); auto ans_dy = test::AsTensor<float>({3.f, 3.f}, TensorShape({2, 1})); test::ExpectClose(ans_dx, dx); test::ExpectClose(ans_dy, dy); } } TEST_F(MathGradTest, Mul) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-10.f, 10.f}, TensorShape({2, 1})); auto ans_dx = test::AsTensor<float>({-10.f, -10.f, -10.f, 10.f, 10.f, 10.f}, TensorShape({2, 3})); auto ans_dy = test::AsTensor<float>({-3.f + (-2.f) + (-1.f), 1.f + 2.f + 3.f}, TensorShape({2, 1})); Tensor dx; Tensor dy; { SymGrad("Mul", x, y, &dx, &dy); test::ExpectClose(ans_dx, dx); test::ExpectClose(ans_dy, dy); } { // Swap x and y SymGrad("Mul", y, x, &dy, &dx); test::ExpectClose(ans_dx, dx); test::ExpectClose(ans_dy, dy); } } TEST_F(MathGradTest, Div) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-10.f, 10.f}, TensorShape({2, 1})); Tensor dx; Tensor dy; { SymGrad("Div", x, y, &dx, &dy); { auto g = [](float x, float y) { return 1.f / y; }; test::ExpectClose(dx, test::AsTensor<float>( {g(-3.f, -10.f), g(-2.f, -10.f), g(-1.f, -10.f), g(1.f, 10.f), g(2.f, 10.f), g(3.f, 10.f)}, TensorShape({2, 3}))); } { auto g = [](float x, float y) { return -x / (y * y); }; test::ExpectClose(dy, test::AsTensor<float>( {g(-3.f, -10.f) + g(-2.f, -10.f) + g(-1.f, -10.f), g(1.f, 10.f) + g(2.f, 10.f) + g(3.f, 10.f)}, TensorShape({2, 1}))); } } { // Swap x and y SymGrad("Div", y, x, &dy, &dx); { auto g = [](float x, float y) { return 1.f / y; }; test::ExpectClose(dy, test::AsTensor<float>( {g(-10.f, -3.f) + g(-10.f, -2.f) + g(-10.f, -1.f), g(10.f, 1.f) + g(10.f, 2.f) + g(10.f, 3.f)}, TensorShape({2, 1}))); } { auto g = [](float x, float y) { return -x / (y * y); }; test::ExpectClose(dx, test::AsTensor<float>( {g(-10.f, -3.f), g(-10.f, -2.f), g(-10.f, -1.f), g(10.f, 1.f), g(10.f, 2.f), g(10.f, 3.f)}, TensorShape({2, 3}))); } } } TEST_F(MathGradTest, Pow) { auto x = test::AsTensor<float>({0.f, 1.f, 2.f, 3.f, 4.f, 5.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({.5f, 2.f}, TensorShape({2, 1})); Tensor dx; Tensor dy; auto g = [](float x, float y) { return y * std::pow(x, y - 1); }; auto h = [](float x, float y) { return std::pow(x, y) * (x ? std::log(x) : 0); }; { SymGrad("Pow", x, y, &dx, &dy); test::ExpectClose( dx, test::AsTensor<float>({g(0.f, .5f), g(1.f, .5f), g(2.f, .5f), g(3.f, 2.f), g(4.f, 2.f), g(5.f, 2.f)}, TensorShape({2, 3}))); test::ExpectClose( dy, test::AsTensor<float>({h(0.f, .5f) + h(1.f, .5f) + h(2.f, .5f), h(3.f, 2.f) + h(4.f, 2.f) + h(5.f, 2.f)}, TensorShape({2, 1}))); } { // Swap x and y SymGrad("Pow", y, x, &dy, &dx); test::ExpectClose( dy, test::AsTensor<float>({g(.5f, 0.f) + g(.5f, 1.f) + g(.5f, 2.f), g(2.f, 3.f) + g(2.f, 4.f) + g(2.f, 5.f)}, TensorShape({2, 1}))); test::ExpectClose( dx, test::AsTensor<float>({h(.5f, 0.f), h(.5f, 1.f), h(.5f, 2.f), h(2.f, 3.f), h(2.f, 4.f), h(2.f, 5.f)}, TensorShape({2, 3}))); } } // TODO {lukeiwanski}: Implement Complex Pow for SYCL id:3414 // https://github.com/imdone/tensorflow/issues/3413 #ifndef TENSORFLOW_USE_SYCL TEST_F(MathGradTest, ComplexPow) { auto x = test::AsTensor<complex64>({0.f, 2.f, -2.f}, TensorShape({3})); auto y = test::AsTensor<complex64>({2.f, 2.f, 2.f}, TensorShape({3})); Tensor dx; Tensor dy; auto g = [](complex64 x, complex64 y) { return y * std::pow(x, y - 1.f); }; auto h = [](complex64 x, complex64 y) { return std::pow(x, y) * (x != complex64(0) ? std::log(x) : 0); }; SymGrad("Pow", x, y, &dx, &dy); test::ExpectClose( dx, test::AsTensor<complex64>({g(0.f, 2.f), g(2.f, 2.f), g(-2.f, 2.f)}, TensorShape({3}))); test::ExpectClose( dy, test::AsTensor<complex64>({h(0.f, 2.f), h(2.f, 2.f), h(-2.f, 2.f)}, TensorShape({3}))); } #endif // TENSORFLOW_USE_SYCL TEST_F(MathGradTest, Maximum) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-1.5f, 1.5f}, TensorShape({2, 1})); Tensor dx; Tensor dy; { SymGrad("Maximum", x, y, &dx, &dy); { auto g = [](float x, float y) { return x >= y ? 1.f : 0.f; }; test::ExpectClose(dx, test::AsTensor<float>( {g(-3.f, -1.5f), g(-2.f, -1.5f), g(-1.f, -1.5f), g(1.f, 1.5f), g(2.f, 1.5f), g(3.f, 1.5f)}, TensorShape({2, 3}))); } { auto g = [](float x, float y) { return x < y ? 1.f : 0.f; }; test::ExpectClose(dy, test::AsTensor<float>( {g(-3.f, -1.5f) + g(-2.f, -1.5f) + g(-1.f, -1.5f), g(1.f, 1.5f) + g(2.f, 1.5f) + g(3.f, 1.5f)}, TensorShape({2, 1}))); } } { // Swap x and y SymGrad("Maximum", y, x, &dy, &dx); { auto g = [](float x, float y) { return x >= y ? 1.f : 0.f; }; test::ExpectClose(dy, test::AsTensor<float>( {g(-1.5f, -3.f) + g(-1.5f, -2.f) + g(-1.5f, -1.f), g(1.5f, 1.f) + g(1.5f, 2.f) + g(1.5f, 3.f)}, TensorShape({2, 1}))); } { auto g = [](float x, float y) { return x < y ? 1.f : 0.f; }; test::ExpectClose(dx, test::AsTensor<float>( {g(-1.5f, -3.f), g(-1.5f, -2.f), g(-1.5f, -1.f), g(1.5f, 1.f), g(1.5f, 2.f), g(1.5f, 3.f)}, TensorShape({2, 3}))); } } } TEST_F(MathGradTest, Minimum) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-1.5f, 1.5f}, TensorShape({2, 1})); Tensor dx; Tensor dy; { SymGrad("Minimum", x, y, &dx, &dy); { auto g = [](float x, float y) { return x <= y ? 1.f : 0.f; }; test::ExpectClose(dx, test::AsTensor<float>( {g(-3.f, -1.5f), g(-2.f, -1.5f), g(-1.f, -1.5f), g(1.f, 1.5f), g(2.f, 1.5f), g(3.f, 1.5f)}, TensorShape({2, 3}))); } { auto g = [](float x, float y) { return x > y ? 1.f : 0.f; }; test::ExpectClose(dy, test::AsTensor<float>( {g(-3.f, -1.5f) + g(-2.f, -1.5f) + g(-1.f, -1.5f), g(1.f, 1.5f) + g(2.f, 1.5f) + g(3.f, 1.5f)}, TensorShape({2, 1}))); } } { // Swap x and y SymGrad("Minimum", y, x, &dy, &dx); { auto g = [](float x, float y) { return x <= y ? 1.f : 0.f; }; test::ExpectClose(dy, test::AsTensor<float>( {g(-1.5f, -3.f) + g(-1.5f, -2.f) + g(-1.5f, -1.f), g(1.5f, 1.f) + g(1.5f, 2.f) + g(1.5f, 3.f)}, TensorShape({2, 1}))); } { auto g = [](float x, float y) { return x > y ? 1.f : 0.f; }; test::ExpectClose(dx, test::AsTensor<float>( {g(-1.5f, -3.f), g(-1.5f, -2.f), g(-1.5f, -1.f), g(1.5f, 1.f), g(1.5f, 2.f), g(1.5f, 3.f)}, TensorShape({2, 3}))); } } } TEST_F(MathGradTest, Select) { auto c = test::AsTensor<bool>({true, false, false, true, true, false}, TensorShape({2, 3})); auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({3.f, 2.f, 1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); Tensor dc; Tensor dx; Tensor dy; { SelectGrad(c, x, y, &dc, &dx, &dy); test::ExpectTensorEqual<bool>( dc, test::AsTensor<bool>({false, false, false, false, false, false}, TensorShape({2, 3}))); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({1.f, 0.f, 0.f, 1.f, 1.f, 0.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<float>( dy, test::AsTensor<float>({0.f, 1.f, 1.f, 0.f, 0.f, 1.f}, TensorShape({2, 3}))); } } TEST_F(MathGradTest, MatMul_00) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({3, 1})); Tensor dx; Tensor dy; MatMulGrad(x, false, y, false, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({2, 1})); test::ExpectClose(dx, MatMul(dz, false, y, true)); test::ExpectClose(dy, MatMul(x, true, dz, false)); } TEST_F(MathGradTest, MatMul_01) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({2, 3})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({1, 3})); Tensor dx; Tensor dy; MatMulGrad(x, false, y, true, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({2, 1})); test::ExpectClose(dx, MatMul(dz, false, y, false)); test::ExpectClose(dy, MatMul(dz, true, x, false)); } TEST_F(MathGradTest, MatMul_10) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({3, 2})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({3, 1})); Tensor dx; Tensor dy; MatMulGrad(x, true, y, false, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({2, 1})); test::ExpectClose(dx, MatMul(y, false, dz, true)); test::ExpectClose(dy, MatMul(x, false, dz, false)); } TEST_F(MathGradTest, MatMul_11) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({3, 2})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({1, 3})); Tensor dx; Tensor dy; MatMulGrad(x, true, y, true, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({2, 1})); test::ExpectClose(dx, MatMul(y, true, dz, true)); test::ExpectClose(dy, MatMul(dz, true, x, true)); } // TODO {lukeiwanski}: Implement BatchMatMul for SYCL id:4104 // https://github.com/imdone/tensorflow/issues/4102 #ifndef TENSORFLOW_USE_SYCL TEST_F(MathGradTest, BatchMatMul_00) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({1, 2, 3})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({1, 3, 1})); Tensor dx; Tensor dy; BatchMatMulGrad(x, false, y, false, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({1, 2, 1})); test::ExpectClose(dx, BatchMatMul(dz, false, y, true)); test::ExpectClose(dy, BatchMatMul(x, true, dz, false)); } TEST_F(MathGradTest, BatchMatMul_01) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({1, 2, 3})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({1, 1, 3})); Tensor dx; Tensor dy; BatchMatMulGrad(x, false, y, true, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({1, 2, 1})); test::ExpectClose(dx, BatchMatMul(dz, false, y, false)); test::ExpectClose(dy, BatchMatMul(dz, true, x, false)); } TEST_F(MathGradTest, BatchMatMul_10) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({1, 3, 2})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({1, 3, 1})); Tensor dx; Tensor dy; BatchMatMulGrad(x, true, y, false, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({1, 2, 1})); test::ExpectClose(dx, BatchMatMul(y, false, dz, true)); test::ExpectClose(dy, BatchMatMul(x, false, dz, false)); } TEST_F(MathGradTest, BatchMatMul_11) { auto x = test::AsTensor<float>({1.f, 2.f, 3.f, 4.f, 5.f, 6.f}, TensorShape({1, 3, 2})); auto y = test::AsTensor<float>({-1.f, .5f, 2.f}, TensorShape({1, 1, 3})); Tensor dx; Tensor dy; BatchMatMulGrad(x, true, y, true, &dx, &dy); auto dz = test::AsTensor<float>({1.f, 1.f}, TensorShape({1, 2, 1})); test::ExpectClose(dx, BatchMatMul(y, true, dz, true)); test::ExpectClose(dy, BatchMatMul(dz, true, x, true)); } #endif // TENSORFLOW_USE_SYCL TEST_F(MathGradTest, Sum_dim0) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Sum", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({1.f, 1.f, 1.f, 1.f, 1.f, 1.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Sum_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({1}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Sum", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({1.f, 1.f, 1.f, 1.f, 1.f, 1.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Mean_dim0) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Mean", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>( {1.f / 2, 1.f / 2, 1.f / 2, 1.f / 2, 1.f / 2, 1.f / 2}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Mean_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({1}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Mean", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>( {1.f / 3, 1.f / 3, 1.f / 3, 1.f / 3, 1.f / 3, 1.f / 3}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Mean_dim0_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0, 1}, TensorShape({2})); Tensor dx; Tensor di; ReductionGrad("Mean", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>( {1.f / 6, 1.f / 6, 1.f / 6, 1.f / 6, 1.f / 6, 1.f / 6}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>( di, test::AsTensor<int32>({0, 0}, TensorShape({2}))); } TEST_F(MathGradTest, Min_dim0) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Min", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({1.f, 1.f, 1.f, 0.f, 0.f, 0.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Min_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({1}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Min", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({1.f, 0.f, 0.f, 1.f, 0.f, 0.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Min_dim0_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0, 1}, TensorShape({2})); Tensor dx; Tensor di; ReductionGrad("Min", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({1.f, 0.f, 0.f, 0.f, 0.f, 0.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>( di, test::AsTensor<int32>({0, 0}, TensorShape({2}))); } TEST_F(MathGradTest, Min_dim0_dim1_Dups) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, -3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0, 1}, TensorShape({2})); Tensor dx; Tensor di; ReductionGrad("Min", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({.5f, 0.f, 0.f, 0.f, 0.f, .5f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>( di, test::AsTensor<int32>({0, 0}, TensorShape({2}))); } TEST_F(MathGradTest, Max_dim0) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Max", x, i, &dx, &di); LOG(INFO) << dx.SummarizeValue(6); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({0.f, 0.f, 0.f, 1.f, 1.f, 1.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Max_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({1}, TensorShape({})); Tensor dx; Tensor di; ReductionGrad("Max", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({0.f, 0.f, 1.f, 0.f, 0.f, 1.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>(di, test::AsTensor<int32>({0}, TensorShape({}))); } TEST_F(MathGradTest, Max_dim0_dim1) { auto x = test::AsTensor<float>({-3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0, 1}, TensorShape({2})); Tensor dx; Tensor di; ReductionGrad("Max", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({0.f, 0.f, 0.f, 0.f, 0.f, 1.f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>( di, test::AsTensor<int32>({0, 0}, TensorShape({2}))); } TEST_F(MathGradTest, Max_dim0_dim1_Dups) { auto x = test::AsTensor<float>({3.f, -2.f, -1.f, 1.f, 2.f, 3.f}, TensorShape({2, 3})); auto i = test::AsTensor<int32>({0, 1}, TensorShape({2})); Tensor dx; Tensor di; ReductionGrad("Max", x, i, &dx, &di); test::ExpectTensorEqual<float>( dx, test::AsTensor<float>({.5f, 0.f, 0.f, 0.f, 0.f, .5f}, TensorShape({2, 3}))); test::ExpectTensorEqual<int32>( di, test::AsTensor<int32>({0, 0}, TensorShape({2}))); } } // namespace } // namespace tensorflow
38.329966
80
0.468047
[ "vector" ]
6dc227a38fc5e29a6c2eaf95b5d1efc77bbe37a5
8,766
hpp
C++
include/GlobalNamespace/MenuShockwave.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MenuShockwave.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MenuShockwave.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: UnityEngine.ParticleSystem/UnityEngine.EmitParams #include "UnityEngine/ParticleSystem_EmitParams.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: ParticleSystem because it is already included! // Skipping declaration: Vector3 because it is already included! } // Forward declaring namespace: VRUIControls namespace VRUIControls { // Forward declaring type: VRPointer class VRPointer; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: Signal class Signal; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0xBF #pragma pack(push, 1) // Autogenerated type: MenuShockwave // [TokenAttribute] Offset: FFFFFFFF class MenuShockwave : public UnityEngine::MonoBehaviour { public: // private UnityEngine.ParticleSystem _shockwavePS // Size: 0x8 // Offset: 0x18 UnityEngine::ParticleSystem* shockwavePS; // Field size check static_assert(sizeof(UnityEngine::ParticleSystem*) == 0x8); // private VRUIControls.VRPointer _vrPointer // Size: 0x8 // Offset: 0x20 VRUIControls::VRPointer* vrPointer; // Field size check static_assert(sizeof(VRUIControls::VRPointer*) == 0x8); // private Signal[] _buttonClickEvents // Size: 0x8 // Offset: 0x28 ::Array<GlobalNamespace::Signal*>* buttonClickEvents; // Field size check static_assert(sizeof(::Array<GlobalNamespace::Signal*>*) == 0x8); // private UnityEngine.ParticleSystem/UnityEngine.EmitParams _shockwavePSEmitParams // Size: 0x8F // Offset: 0x30 UnityEngine::ParticleSystem::EmitParams shockwavePSEmitParams; // Field size check static_assert(sizeof(UnityEngine::ParticleSystem::EmitParams) == 0x8F); // Creating value type constructor for type: MenuShockwave MenuShockwave(UnityEngine::ParticleSystem* shockwavePS_ = {}, VRUIControls::VRPointer* vrPointer_ = {}, ::Array<GlobalNamespace::Signal*>* buttonClickEvents_ = {}, UnityEngine::ParticleSystem::EmitParams shockwavePSEmitParams_ = {}) noexcept : shockwavePS{shockwavePS_}, vrPointer{vrPointer_}, buttonClickEvents{buttonClickEvents_}, shockwavePSEmitParams{shockwavePSEmitParams_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // Get instance field: private UnityEngine.ParticleSystem _shockwavePS UnityEngine::ParticleSystem* _get__shockwavePS(); // Set instance field: private UnityEngine.ParticleSystem _shockwavePS void _set__shockwavePS(UnityEngine::ParticleSystem* value); // Get instance field: private VRUIControls.VRPointer _vrPointer VRUIControls::VRPointer* _get__vrPointer(); // Set instance field: private VRUIControls.VRPointer _vrPointer void _set__vrPointer(VRUIControls::VRPointer* value); // Get instance field: private Signal[] _buttonClickEvents ::Array<GlobalNamespace::Signal*>* _get__buttonClickEvents(); // Set instance field: private Signal[] _buttonClickEvents void _set__buttonClickEvents(::Array<GlobalNamespace::Signal*>* value); // Get instance field: private UnityEngine.ParticleSystem/UnityEngine.EmitParams _shockwavePSEmitParams UnityEngine::ParticleSystem::EmitParams _get__shockwavePSEmitParams(); // Set instance field: private UnityEngine.ParticleSystem/UnityEngine.EmitParams _shockwavePSEmitParams void _set__shockwavePSEmitParams(UnityEngine::ParticleSystem::EmitParams value); // protected System.Void Awake() // Offset: 0x1FB02DC void Awake(); // protected System.Void OnEnable() // Offset: 0x1FB02EC void OnEnable(); // protected System.Void OnDisable() // Offset: 0x1FB03C0 void OnDisable(); // private System.Void HandleButtonClickEvent() // Offset: 0x1FB0494 void HandleButtonClickEvent(); // public System.Void SpawnShockwave(UnityEngine.Vector3 pos) // Offset: 0x1FB04C8 void SpawnShockwave(UnityEngine::Vector3 pos); // public System.Void .ctor() // Offset: 0x1FB0578 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MenuShockwave* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MenuShockwave::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MenuShockwave*, creationType>())); } }; // MenuShockwave #pragma pack(pop) static check_size<sizeof(MenuShockwave), 48 + sizeof(UnityEngine::ParticleSystem::EmitParams)> __GlobalNamespace_MenuShockwaveSizeCheck; static_assert(sizeof(MenuShockwave) == 0xBF); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MenuShockwave*, "", "MenuShockwave"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::MenuShockwave::Awake // Il2CppName: Awake template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MenuShockwave::*)()>(&GlobalNamespace::MenuShockwave::Awake)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MenuShockwave*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MenuShockwave::OnEnable // Il2CppName: OnEnable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MenuShockwave::*)()>(&GlobalNamespace::MenuShockwave::OnEnable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MenuShockwave*), "OnEnable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MenuShockwave::OnDisable // Il2CppName: OnDisable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MenuShockwave::*)()>(&GlobalNamespace::MenuShockwave::OnDisable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MenuShockwave*), "OnDisable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MenuShockwave::HandleButtonClickEvent // Il2CppName: HandleButtonClickEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MenuShockwave::*)()>(&GlobalNamespace::MenuShockwave::HandleButtonClickEvent)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MenuShockwave*), "HandleButtonClickEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MenuShockwave::SpawnShockwave // Il2CppName: SpawnShockwave template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MenuShockwave::*)(UnityEngine::Vector3)>(&GlobalNamespace::MenuShockwave::SpawnShockwave)> { static const MethodInfo* get() { static auto* pos = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MenuShockwave*), "SpawnShockwave", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pos}); } }; // Writing MetadataGetter for method: GlobalNamespace::MenuShockwave::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
52.807229
386
0.737052
[ "object", "vector" ]
6dc24dc0cc9f176fc2094384d7c43419d03035da
1,437
cpp
C++
acmp.ru/0540/540.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
acmp.ru/0540/540.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
acmp.ru/0540/540.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> using namespace std; struct elem { long long leftDiag, rightDiag, val; elem(long long lD = 0, long long rD = 0, long long val = 0, long long mod = 1):leftDiag(lD%mod), rightDiag(rD%mod), val(val%mod){} void divide(long long mod) { leftDiag%=mod; rightDiag%=mod; val%=mod; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, mod; cin >> m >> n >> mod; vector<elem> curLevel(n+2), nextLevel(n+2); for(int i = 1; i<=n; i++) { cin >> curLevel[i].val; curLevel[i].leftDiag = curLevel[i].rightDiag = curLevel[i].val; } for(int i = 1; i<m; i++) { for(int j = 1; j<=n; j++) { nextLevel[j].val = curLevel[j].val + curLevel[j-1].leftDiag + curLevel[j+1].rightDiag; nextLevel[j].leftDiag = curLevel[j-1].leftDiag + nextLevel[j].val; nextLevel[j].rightDiag = curLevel[j+1].rightDiag + nextLevel[j].val; nextLevel[j].divide(mod); nextLevel[j].val*=2; } nextLevel.swap(curLevel); } for(int i = 1; i<=n; i++) cout << curLevel[i].val/2 << ' '; return 0; }
25.210526
101
0.455811
[ "vector" ]
6dc979e7984dacc31411d7ab6e5536c16449c257
11,009
cpp
C++
src/base/FrameRenderer.cpp
kostrykin/Carna
099783bb7f8a6f52fcc8ccd4666e491cf0aa864c
[ "BSD-3-Clause" ]
null
null
null
src/base/FrameRenderer.cpp
kostrykin/Carna
099783bb7f8a6f52fcc8ccd4666e491cf0aa864c
[ "BSD-3-Clause" ]
null
null
null
src/base/FrameRenderer.cpp
kostrykin/Carna
099783bb7f8a6f52fcc8ccd4666e491cf0aa864c
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2010 - 2015 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/base/glew.h> #include <Carna/base/glError.h> #include <Carna/base/FrameRenderer.h> #include <Carna/base/Camera.h> #include <Carna/base/RenderTask.h> #include <Carna/base/RenderStage.h> #include <Carna/base/Node.h> #include <Carna/base/Viewport.h> #include <Carna/base/ShaderManager.h> #include <Carna/base/ShaderUniform.h> #include <Carna/base/Vertex.h> #include <Carna/base/Mesh.h> #include <Carna/base/VertexBuffer.h> #include <Carna/base/IndexBuffer.h> #include <Carna/base/Sampler.h> #include <Carna/base/Stopwatch.h> #include <Carna/base/Composition.h> #include <vector> namespace Carna { namespace base { // ---------------------------------------------------------------------------------- // createFullFrameQuadSampler // ---------------------------------------------------------------------------------- static Sampler* createFullFrameQuadSampler() { return new Sampler ( Sampler::WRAP_MODE_CLAMP, Sampler::WRAP_MODE_CLAMP, Sampler::WRAP_MODE_CLAMP , Sampler::FILTER_LINEAR, Sampler::FILTER_LINEAR ); } // ---------------------------------------------------------------------------------- // glContextMadeCurrent // ---------------------------------------------------------------------------------- static GLContext& glContextMadeCurrent( GLContext& glc ) { glc.makeCurrent(); return glc; } // ---------------------------------------------------------------------------------- // createFullFrameQuadMesh // ---------------------------------------------------------------------------------- static MeshBase* createFullFrameQuadMesh() { typedef PVertex VertexType; typedef uint8_t IndexType; /* Lets create clipping coordinates directly, * s.t. we won't need to pass any matrices to the shader. */ VertexType vertices[ 4 ]; IndexType indices[ 4 ]; vertices[ 0 ].x = -1; vertices[ 0 ].y = -1; indices [ 0 ] = 0; vertices[ 1 ].x = +1; vertices[ 1 ].y = -1; indices [ 1 ] = 1; vertices[ 2 ].x = +1; vertices[ 2 ].y = +1; indices [ 2 ] = 2; vertices[ 3 ].x = -1; vertices[ 3 ].y = +1; indices [ 3 ] = 3; /* Create vertex buffer. */ VertexBuffer< VertexType >* const vertexBuffer = new VertexBuffer< VertexType >(); vertexBuffer->copy( vertices, 4 ); /* Create index buffer. */ IndexBuffer< IndexType >* const indexBuffer = new IndexBuffer< IndexType >( IndexBufferBase::PRIMITIVE_TYPE_TRIANGLE_FAN ); indexBuffer->copy( indices, 4 ); /* Compose the mesh. */ return new Mesh< VertexType, IndexType > ( new Composition< VertexBufferBase >( vertexBuffer ) , new Composition< IndexBufferBase >( indexBuffer ) ); } // ---------------------------------------------------------------------------------- // circular_buffer // ---------------------------------------------------------------------------------- template< typename T > class circular_buffer { std::vector< T > buffer; unsigned int nextIdx; bool saturated; public: explicit circular_buffer( std::size_t size ); void push( const T& ); std::size_t size() const; const T& operator[]( std::size_t idx ) const; }; // circular_buffer template< typename T > circular_buffer< T >::circular_buffer( std::size_t size ) : buffer( size ) , nextIdx( 0 ) , saturated( false ) { } template< typename T > void circular_buffer< T >::push( const T& val ) { buffer[ nextIdx ] = val; nextIdx = ( ++nextIdx ) % buffer.size(); saturated = saturated || nextIdx == 0; } template< typename T > std::size_t circular_buffer< T >::size() const { return saturated ? buffer.size() : nextIdx; } template< typename T > const T& circular_buffer< T >::operator[]( std::size_t idx ) const { CARNA_ASSERT( idx < size() ); if( saturated ) { return buffer[ ( nextIdx + idx ) % buffer.size() ]; } else { return buffer[ idx ]; } } // ---------------------------------------------------------------------------------- // FrameRenderer :: Details // ---------------------------------------------------------------------------------- struct FrameRenderer::Details { Details( GLContext& glContext, unsigned int width, unsigned int height ); unsigned int width, height; bool fitSquare; mutable bool reshaped; std::unique_ptr< Viewport > viewport; GLContext* const glContext; const std::unique_ptr< Sampler > fullFrameQuadSampler; const std::unique_ptr< MeshBase > fullFrameQuadMesh; const ShaderProgram& fullFrameQuadShader; float backgroundColor[ 4 ]; bool backgroundColorChanged; math::Statistics< double > fpsStatistics; circular_buffer< double > fpsData; void updateFpsStatistics(); }; FrameRenderer::Details::Details( GLContext& glContext, unsigned int width, unsigned int height ) : width( width ) , height( height ) , reshaped( true ) , glContext( &glContextMadeCurrent( glContext ) ) // makes 'glContext' current , fullFrameQuadSampler( createFullFrameQuadSampler() ) , fullFrameQuadMesh( createFullFrameQuadMesh() ) , fullFrameQuadShader( ShaderManager::instance().acquireShader( "full_frame_quad" ) ) , backgroundColorChanged( true ) , fpsStatistics( 0, 0 ) , fpsData( 10 ) { backgroundColor[ 0 ] = 0; backgroundColor[ 1 ] = 0; backgroundColor[ 2 ] = 0; backgroundColor[ 3 ] = 0; } // ---------------------------------------------------------------------------------- // FrameRenderer :: RenderTextureParams // ---------------------------------------------------------------------------------- FrameRenderer::RenderTextureParams::RenderTextureParams( unsigned int unit ) : unit( unit ) , useDefaultSampler( true ) , useDefaultShader( true ) , textureUniformName( "colorMap" ) , alphaFactor( 1 ) { } // ---------------------------------------------------------------------------------- // FrameRenderer // ---------------------------------------------------------------------------------- FrameRenderer::FrameRenderer( GLContext& glContext, unsigned int width, unsigned int height, bool fitSquare ) : pimpl( new Details( glContext, width, height ) ) { pimpl->viewport.reset( new Viewport( width, height, fitSquare ) ); pimpl->fitSquare = fitSquare; } FrameRenderer::~FrameRenderer() { /* Context is activated by 'clearStages'. The context must be activated s.t. the * quad mesh and shader can be cleaned up properly. */ clearStages(); ShaderManager::instance().releaseShader( pimpl->fullFrameQuadShader ); } void FrameRenderer::setBackgroundColor( const math::Vector4f& bc ) { pimpl->backgroundColor[ 0 ] = bc.x(); pimpl->backgroundColor[ 1 ] = bc.y(); pimpl->backgroundColor[ 2 ] = bc.z(); pimpl->backgroundColor[ 3 ] = bc.w(); pimpl->backgroundColorChanged = true; } GLContext& FrameRenderer::glContext() const { return *pimpl->glContext; } void FrameRenderer::clearStages() { pimpl->glContext->makeCurrent(); RenderStageSequence::clearStages(); } unsigned int FrameRenderer::width() const { return pimpl->width; } unsigned int FrameRenderer::height() const { return pimpl->height; } void FrameRenderer::reshape( unsigned int width, unsigned int height, bool fitSquare ) { pimpl->width = width; pimpl->height = height; pimpl->fitSquare = fitSquare; pimpl->viewport.reset( new Viewport( width, height, fitSquare ) ); pimpl->reshaped = true; } void FrameRenderer::reshape( unsigned int width, unsigned int height ) { reshape( width, height, pimpl->fitSquare ); } void FrameRenderer::render( Camera& cam ) const { Node& root = cam.findRoot(); CARNA_ASSERT( static_cast< Spatial* >( &root ) != static_cast< Spatial* >( &cam ) ); render( cam, root ); } void FrameRenderer::render( Camera& cam, Node& root ) const { /* Update world transforms. */ root.updateWorldTransform(); glContext().makeCurrent(); render( cam, root, *pimpl->viewport ); } const Viewport& FrameRenderer::viewport() const { return *pimpl->viewport; } void FrameRenderer::render( Camera& cam, Node& root, const Viewport& vp ) const { /* Start time measurement. */ Stopwatch stopwatch; /* Check for errors. */ REPORT_GL_ERROR; /* Reshape render stages' buffers. */ for( std::size_t rsIdx = 0; rsIdx < stages(); ++rsIdx ) { RenderStage& rs = stageAt( rsIdx ); /* Ensure buffers are properly sized. */ if( pimpl->reshaped || !rs.isInitialized() ) { /* This 'const_cast' is okay, because 'RenderStage' objects are clearly * stated to be components of a 'FrameRenderer', thus "it runs in the * family" as long as an immutable 'RenderStage' reference not induces a * mutable 'FrameRenderer' reference. */ FrameRenderer& fr = const_cast< FrameRenderer& >( *this ); rs.reshape( fr, pimpl->viewport->width(), pimpl->viewport->height() ); } /* Notify stages of beginning frame. */ rs.prepareFrame( root ); } /* Mark that all buffer sizes have been established. */ pimpl->reshaped = false; /* Clear buffers. */ glClearColor ( pimpl->backgroundColor[ 0 ] , pimpl->backgroundColor[ 1 ] , pimpl->backgroundColor[ 2 ] , pimpl->backgroundColor[ 3 ] ); /* Render frame. */ RenderTask task( *this, cam.projection(), cam.viewTransform() ); task.render( vp, GLContext::COLOR_BUFFER_BIT | GLContext::DEPTH_BUFFER_BIT ); /* Check for errors. */ REPORT_GL_ERROR; /* Stop and evaluate time measurement. */ const double time = stopwatch.result(); const double fps = 1 / time; pimpl->fpsData.push( fps ); pimpl->fpsStatistics = math::Statistics< double >( pimpl->fpsData.size(), [&]( std::size_t idx )->double { return pimpl->fpsData[ idx ]; } ); } void FrameRenderer::renderTexture( const RenderTextureParams& params ) const { if( params.useDefaultSampler ) { pimpl->fullFrameQuadSampler->bind( params.unit ); } if( params.useDefaultShader ) { pimpl->glContext->setShader( pimpl->fullFrameQuadShader ); ShaderUniform< float >( "alphaFactor", params.alphaFactor ).upload(); } ShaderUniform< int >( params.textureUniformName, params.unit ).upload(); pimpl->fullFrameQuadMesh->render(); } const math::Statistics< double >& FrameRenderer::framesPerSecond() const { return pimpl->fpsStatistics; } } // namespace Carna :: base } // namespace Carna
25.308046
127
0.574076
[ "mesh", "render", "vector" ]
6dcaa0ee8c2862f7ab82097bbb5e20ffaa629e3e
5,203
cc
C++
src/lib/hooks/tests/parking_lots_unittest.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
2
2021-06-29T09:56:34.000Z
2021-06-29T09:56:39.000Z
src/lib/hooks/tests/parking_lots_unittest.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
null
null
null
src/lib/hooks/tests/parking_lots_unittest.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <exceptions/exceptions.h> #include <hooks/parking_lots.h> #include <gtest/gtest.h> #include <string> using namespace isc; using namespace isc::hooks; namespace { // Test that it is possible to create and retrieve parking lots for // specified hook points. TEST(ParkingLotsTest, createGetParkingLot) { ParkingLots parking_lots; ParkingLotPtr parking_lot0 = parking_lots.getParkingLotPtr(1); ParkingLotPtr parking_lot1 = parking_lots.getParkingLotPtr(2); ParkingLotPtr parking_lot2 = parking_lots.getParkingLotPtr(1); ASSERT_TRUE(parking_lot0); ASSERT_TRUE(parking_lot1); ASSERT_TRUE(parking_lot2); EXPECT_FALSE(parking_lot0 == parking_lot1); EXPECT_TRUE(parking_lot0 == parking_lot2); ASSERT_NO_THROW(parking_lots.clear()); ParkingLotPtr parking_lot3 = parking_lots.getParkingLotPtr(1); ASSERT_TRUE(parking_lot3); EXPECT_FALSE(parking_lot3 == parking_lot0); } // Test that object can't be parked if it hasn't been referenced on the // parking lot. TEST(ParkingLotTest, parkWithoutReferencing) { ParkingLot parking_lot; std::string parked_object = "foo"; EXPECT_THROW(parking_lot.park(parked_object, [] { }), InvalidOperation); } // Test that object can be parked and then unparked. TEST(ParkingLotTest, unpark) { ParkingLotPtr parking_lot = std::make_shared<ParkingLot>(); ParkingLotHandlePtr parking_lot_handle = std::make_shared<ParkingLotHandle>(parking_lot); std::string parked_object = "foo"; // Reference the parked object twice because we're going to test that // reference counting works fine. ASSERT_NO_THROW(parking_lot_handle->reference(parked_object)); ASSERT_NO_THROW(parking_lot_handle->reference(parked_object)); // This flag will indicate if the callback has been called. bool unparked = false; ASSERT_NO_THROW(parking_lot->park(parked_object, [&unparked] { unparked = true; })); // Try to unpark the object. It should decrease the reference count, but not // unpark the packet yet. EXPECT_TRUE(parking_lot_handle->unpark(parked_object)); EXPECT_FALSE(unparked); // Try to unpark the object. This time it should be successful, because the // reference count goes to 0. EXPECT_TRUE(parking_lot_handle->unpark(parked_object)); EXPECT_TRUE(unparked); // Calling unpark again should return false to indicate that the object is // not parked. EXPECT_FALSE(parking_lot_handle->unpark(parked_object)); } // Test that parked object can be dropped. TEST(ParkingLotTest, drop) { ParkingLotPtr parking_lot = std::make_shared<ParkingLot>(); ParkingLotHandlePtr parking_lot_handle = std::make_shared<ParkingLotHandle>(parking_lot); std::string parked_object = "foo"; // Reference object twice to test that dropping the packet ignores // reference counting. ASSERT_NO_THROW(parking_lot_handle->reference(parked_object)); ASSERT_NO_THROW(parking_lot_handle->reference(parked_object)); // This flag will indicate if the callback has been called. bool unparked = false; ASSERT_NO_THROW(parking_lot->park(parked_object, [&unparked] { unparked = true; })); // Drop parked object. The callback should not be invoked. EXPECT_TRUE(parking_lot_handle->drop(parked_object)); EXPECT_FALSE(unparked); // Expect that an attempt to unpark return false, as the object // has been dropped. EXPECT_FALSE(parking_lot_handle->unpark(parked_object)); } // Test that parked lots can be cleared. TEST(ParkingLotTest, clear) { ParkingLotsPtr parking_lots = std::make_shared<ParkingLots>(); ParkingLotPtr parking_lot = parking_lots->getParkingLotPtr(1234); ASSERT_TRUE(parking_lot); ParkingLotHandlePtr parking_lot_handle = std::make_shared<ParkingLotHandle>(parking_lot); std::shared_ptr<std::string> parked_object = std::make_shared<std::string>("foo"); std::weak_ptr<std::string> weak_parked_object(parked_object); // Reference object twice to test that clearing the parking lots // ignores reference counting. ASSERT_NO_THROW(parking_lot_handle->reference(parked_object)); ASSERT_NO_THROW(parking_lot_handle->reference(parked_object)); // This flag will indicate if the callback has been called. bool unparked = false; ASSERT_NO_THROW(parking_lot->park(parked_object, [&unparked] { unparked = true; })); // Drop reference on objects. parking_lot.reset(); parking_lot_handle.reset(); parked_object.reset(); // The parked object is still alive. EXPECT_FALSE(weak_parked_object.expired()); // Clear the parking lots. ASSERT_NO_THROW(parking_lots->clear()); // The callback should not be invoked. EXPECT_FALSE(unparked); // The parked object was destroyed. EXPECT_TRUE(weak_parked_object.expired()); } }
33.352564
80
0.72881
[ "object" ]
6dceb958414ac9b01d14e058b88cd3f76439e00f
3,194
cpp
C++
Language/Problem16.cpp
YuBis/ModernCppChallengeStudy
32d9de5fc2aedb8a1df0fb1ee820fb9697939226
[ "MIT" ]
null
null
null
Language/Problem16.cpp
YuBis/ModernCppChallengeStudy
32d9de5fc2aedb8a1df0fb1ee820fb9697939226
[ "MIT" ]
null
null
null
Language/Problem16.cpp
YuBis/ModernCppChallengeStudy
32d9de5fc2aedb8a1df0fb1ee820fb9697939226
[ "MIT" ]
null
null
null
// Project.cpp: 콘솔 응용 프로그램의 진입점을 정의합니다. // #include "stdafx.h" #include <conio.h> #include <iostream> #include <sstream> #include <algorithm> #include <vector> #include <array> #include <cassert> #define OCTET_MAX 0b11111111 static const std::array<int, 4> ERROR_VALUE{ -1, -1, -1, -1 }; class IPv4 { public: static IPv4* create(std::array<int, 4> oct_arr); void PrintThis(); void add_one(); bool isBiggerThan(IPv4* other); private: explicit IPv4(); virtual ~IPv4(); std::array<int, 4> octet_arr_; }; std::vector<IPv4*> item_vec_; std::array<int, 4> CheckValidate(std::string addr); void InsertAddress(const std::string& addr); void PrintAllAddress(); void PrintRange(IPv4* a, IPv4* b); IPv4* IPv4::create(std::array<int, 4> oct_arr) { auto instance = new(std::nothrow) IPv4(); assert(instance != nullptr, "IPv4 memory alloc failed."); instance->octet_arr_ = oct_arr; return instance; } IPv4::IPv4() { std::fill(octet_arr_.begin(), octet_arr_.end(), -1); } IPv4::~IPv4() { } void IPv4::PrintThis() { int point_left = 3; std::for_each(octet_arr_.cbegin(), octet_arr_.cend(), [&point_left](int item) { std::cout << item << (point_left-- > 0 ? "." : ""); }); std::cout << std::endl; } void IPv4::add_one() { octet_arr_[3]++; for (int i = 3; i > 0; --i) { if (octet_arr_[i] > OCTET_MAX) { octet_arr_[i] = 0; octet_arr_[i - 1]++; } } } bool IPv4::isBiggerThan(IPv4* other) { return std::tie(octet_arr_.at(0), octet_arr_.at(1), octet_arr_.at(2), octet_arr_.at(3)) > std::tie(other->octet_arr_.at(0), other->octet_arr_.at(1), other->octet_arr_.at(2), other->octet_arr_.at(3)); } void InsertAddress(const std::string& addr) { auto validate_var = CheckValidate(addr); if (validate_var != ERROR_VALUE) { auto maked_addr = IPv4::create(validate_var); item_vec_.push_back(maked_addr); } else std::cout << "it is not ipv4 address form" << std::endl; } void PrintAllAddress() { std::for_each(item_vec_.cbegin(), item_vec_.cend(), [=](IPv4* item) { item->PrintThis(); }); } std::array<int, 4> CheckValidate(std::string addr) { int oct_idx = 0; std::array<int, 4> ret_val{ -1, -1, -1, -1 }; char* context = nullptr; char* tok_addr = const_cast<char*>(addr.c_str()); char* ptr = strtok_s(tok_addr, ".", &context); while (ptr != nullptr) { if (oct_idx > 3) return ERROR_VALUE; std::stringstream n(ptr); int convert_value; if (n >> convert_value) { if (convert_value >= 0 && convert_value <= 255) ret_val[oct_idx++] = convert_value; } else return ERROR_VALUE; ptr = strtok_s(nullptr, ".", &context); } if (oct_idx != 4) return ERROR_VALUE; return ret_val; } void PrintRange(IPv4* begin_addr, IPv4* end_addr) { if (begin_addr->isBiggerThan(end_addr)) std::swap(begin_addr, end_addr); IPv4* print_addr = begin_addr; print_addr->add_one(); while (end_addr->isBiggerThan(print_addr)) { print_addr->PrintThis(); print_addr->add_one(); } } int main() { std::string input[2]; std::cout << "insert IPv4 class" << std::endl; std::cin >> input[0] >> input[1]; InsertAddress(input[0]); InsertAddress(input[1]); PrintRange(item_vec_.at(0), item_vec_.at(1)); _getch(); return 0; }
19.47561
136
0.656544
[ "vector" ]
6dd1c61490e142a46a32e29236db3e04c9f5ba6a
1,978
cpp
C++
android-31/android/os/SharedMemory.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/os/SharedMemory.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/os/SharedMemory.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./Parcel.hpp" #include "../../JString.hpp" #include "../../java/nio/ByteBuffer.hpp" #include "./SharedMemory.hpp" namespace android::os { // Fields JObject SharedMemory::CREATOR() { return getStaticObjectField( "android.os.SharedMemory", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } // QJniObject forward SharedMemory::SharedMemory(QJniObject obj) : JObject(obj) {} // Constructors // Methods android::os::SharedMemory SharedMemory::create(JString arg0, jint arg1) { return callStaticObjectMethod( "android.os.SharedMemory", "create", "(Ljava/lang/String;I)Landroid/os/SharedMemory;", arg0.object<jstring>(), arg1 ); } void SharedMemory::unmap(java::nio::ByteBuffer arg0) { callStaticMethod<void>( "android.os.SharedMemory", "unmap", "(Ljava/nio/ByteBuffer;)V", arg0.object() ); } void SharedMemory::close() const { callMethod<void>( "close", "()V" ); } jint SharedMemory::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } jint SharedMemory::getSize() const { return callMethod<jint>( "getSize", "()I" ); } java::nio::ByteBuffer SharedMemory::map(jint arg0, jint arg1, jint arg2) const { return callObjectMethod( "map", "(III)Ljava/nio/ByteBuffer;", arg0, arg1, arg2 ); } java::nio::ByteBuffer SharedMemory::mapReadOnly() const { return callObjectMethod( "mapReadOnly", "()Ljava/nio/ByteBuffer;" ); } java::nio::ByteBuffer SharedMemory::mapReadWrite() const { return callObjectMethod( "mapReadWrite", "()Ljava/nio/ByteBuffer;" ); } jboolean SharedMemory::setProtect(jint arg0) const { return callMethod<jboolean>( "setProtect", "(I)Z", arg0 ); } void SharedMemory::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::os
18.485981
79
0.654702
[ "object" ]
6dd2c0ec1743a6a50173f89a64256bcaffe280a6
17,281
cpp
C++
rclcpp_lifecycle/test/test_lifecycle_service_client.cpp
jlack1987/rclcpp
d107a844eae6f4d6a86515f0b3e469802ab1e785
[ "Apache-2.0" ]
271
2015-04-07T15:26:53.000Z
2022-03-31T17:42:58.000Z
rclcpp_lifecycle/test/test_lifecycle_service_client.cpp
jlack1987/rclcpp
d107a844eae6f4d6a86515f0b3e469802ab1e785
[ "Apache-2.0" ]
1,676
2015-01-15T23:46:56.000Z
2022-03-31T21:32:06.000Z
rclcpp_lifecycle/test/test_lifecycle_service_client.cpp
jlack1987/rclcpp
d107a844eae6f4d6a86515f0b3e469802ab1e785
[ "Apache-2.0" ]
299
2015-10-05T16:51:32.000Z
2022-03-30T11:23:18.000Z
// Copyright 2020 Open Source Robotics Foundation, 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. /** * Service client test was adopted from: * https://github.com/ros2/demos/blob/master/lifecycle/src/lifecycle_service_client.cpp */ #include <gtest/gtest.h> #include <chrono> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "lifecycle_msgs/msg/state.hpp" #include "lifecycle_msgs/msg/transition.hpp" #include "lifecycle_msgs/msg/transition_description.hpp" #include "lifecycle_msgs/srv/change_state.hpp" #include "lifecycle_msgs/srv/get_available_states.hpp" #include "lifecycle_msgs/srv/get_available_transitions.hpp" #include "lifecycle_msgs/srv/get_state.hpp" #include "rclcpp/node_interfaces/node_graph.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" #include "rcpputils/scope_exit.hpp" #include "./mocking_utils/patch.hpp" using namespace std::chrono_literals; constexpr char const * lifecycle_node_name = "lc_talker"; constexpr char const * node_get_state_topic = "/lc_talker/get_state"; constexpr char const * node_change_state_topic = "/lc_talker/change_state"; constexpr char const * node_get_available_states_topic = "/lc_talker/get_available_states"; constexpr char const * node_get_available_transitions_topic = "/lc_talker/get_available_transitions"; constexpr char const * node_get_transition_graph_topic = "/lc_talker/get_transition_graph"; const lifecycle_msgs::msg::State unknown_state = lifecycle_msgs::msg::State(); class EmptyLifecycleNode : public rclcpp_lifecycle::LifecycleNode { public: EmptyLifecycleNode() : rclcpp_lifecycle::LifecycleNode(lifecycle_node_name) {} }; class LifecycleServiceClient : public rclcpp::Node { public: explicit LifecycleServiceClient(std::string node_name) : Node(node_name) { client_get_available_states_ = this->create_client<lifecycle_msgs::srv::GetAvailableStates>( node_get_available_states_topic); client_get_available_transitions_ = this->create_client<lifecycle_msgs::srv::GetAvailableTransitions>( node_get_available_transitions_topic); client_get_transition_graph_ = this->create_client<lifecycle_msgs::srv::GetAvailableTransitions>( node_get_transition_graph_topic); client_get_state_ = this->create_client<lifecycle_msgs::srv::GetState>( node_get_state_topic); client_change_state_ = this->create_client<lifecycle_msgs::srv::ChangeState>( node_change_state_topic); } lifecycle_msgs::msg::State get_state(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetState::Request>(); if (!client_get_state_->wait_for_service(time_out)) { return unknown_state; } auto future_result = client_get_state_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { return unknown_state; } auto result = future_result.get(); if (result) { return result->current_state; } else { return unknown_state; } } bool change_state(std::uint8_t transition, std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::ChangeState::Request>(); request->transition.id = transition; if (!client_change_state_->wait_for_service(time_out)) { return false; } auto future_result = client_change_state_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { return false; } return future_result.get()->success; } std::vector<lifecycle_msgs::msg::State> get_available_states(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableStates::Request>(); if (!client_get_available_states_->wait_for_service(time_out)) { return std::vector<lifecycle_msgs::msg::State>(); } auto future_result = client_get_available_states_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { return std::vector<lifecycle_msgs::msg::State>(); } auto result = future_result.get(); if (result) { return result->available_states; } return std::vector<lifecycle_msgs::msg::State>(); } std::vector<lifecycle_msgs::msg::TransitionDescription> get_available_transitions(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableTransitions::Request>(); if (!client_get_available_transitions_->wait_for_service(time_out)) { return std::vector<lifecycle_msgs::msg::TransitionDescription>(); } auto future_result = client_get_available_transitions_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { return std::vector<lifecycle_msgs::msg::TransitionDescription>(); } auto result = future_result.get(); if (result) { return result->available_transitions; } return std::vector<lifecycle_msgs::msg::TransitionDescription>(); } std::vector<lifecycle_msgs::msg::TransitionDescription> get_transition_graph(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableTransitions::Request>(); if (!client_get_transition_graph_->wait_for_service(time_out)) { return std::vector<lifecycle_msgs::msg::TransitionDescription>(); } auto future_result = client_get_transition_graph_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { return std::vector<lifecycle_msgs::msg::TransitionDescription>(); } auto result = future_result.get(); if (result) { return result->available_transitions; } return std::vector<lifecycle_msgs::msg::TransitionDescription>(); } private: std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableStates>> client_get_available_states_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableTransitions>> client_get_available_transitions_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableTransitions>> client_get_transition_graph_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetState>> client_get_state_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::ChangeState>> client_change_state_; }; class TestLifecycleServiceClient : public ::testing::Test { protected: EmptyLifecycleNode * lifecycle_node() {return lifecycle_node_.get();} LifecycleServiceClient * lifecycle_client() {return lifecycle_client_.get();} private: void SetUp() override { rclcpp::init(0, nullptr); lifecycle_node_ = std::make_shared<EmptyLifecycleNode>(); lifecycle_client_ = std::make_shared<LifecycleServiceClient>("client"); spinner_ = std::thread(&TestLifecycleServiceClient::spin, this); } void TearDown() override { { std::lock_guard<std::mutex> guard(shutdown_mutex_); rclcpp::shutdown(); } spinner_.join(); } void spin() { while (true) { { std::lock_guard<std::mutex> guard(shutdown_mutex_); if (!rclcpp::ok()) { break; } rclcpp::spin_some(lifecycle_node_->get_node_base_interface()); rclcpp::spin_some(lifecycle_client_); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } std::shared_ptr<EmptyLifecycleNode> lifecycle_node_; std::shared_ptr<LifecycleServiceClient> lifecycle_client_; std::mutex shutdown_mutex_; std::thread spinner_; }; TEST_F(TestLifecycleServiceClient, construct_destruct) { EXPECT_NE(nullptr, lifecycle_client()); EXPECT_NE(nullptr, lifecycle_node()); } TEST_F(TestLifecycleServiceClient, available_states) { auto states = lifecycle_client()->get_available_states(); EXPECT_EQ(states.size(), 11u); EXPECT_EQ(states[0].id, lifecycle_msgs::msg::State::PRIMARY_STATE_UNKNOWN); EXPECT_EQ(states[1].id, lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED); EXPECT_EQ(states[2].id, lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE); EXPECT_EQ(states[3].id, lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE); EXPECT_EQ(states[4].id, lifecycle_msgs::msg::State::PRIMARY_STATE_FINALIZED); EXPECT_EQ(states[5].id, lifecycle_msgs::msg::State::TRANSITION_STATE_CONFIGURING); EXPECT_EQ(states[6].id, lifecycle_msgs::msg::State::TRANSITION_STATE_CLEANINGUP); EXPECT_EQ(states[7].id, lifecycle_msgs::msg::State::TRANSITION_STATE_SHUTTINGDOWN); EXPECT_EQ(states[8].id, lifecycle_msgs::msg::State::TRANSITION_STATE_ACTIVATING); EXPECT_EQ(states[9].id, lifecycle_msgs::msg::State::TRANSITION_STATE_DEACTIVATING); EXPECT_EQ(states[10].id, lifecycle_msgs::msg::State::TRANSITION_STATE_ERRORPROCESSING); } TEST_F(TestLifecycleServiceClient, transition_graph) { auto transitions = lifecycle_client()->get_transition_graph(); EXPECT_EQ(transitions.size(), 25u); } TEST_F(TestLifecycleServiceClient, available_transitions) { auto transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 2u); EXPECT_EQ(transitions[0].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); EXPECT_EQ( transitions[1].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_UNCONFIGURED_SHUTDOWN); } TEST_F(TestLifecycleServiceClient, lifecycle_transitions) { EXPECT_EQ( lifecycle_client()->get_state().id, lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED); auto transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 2u); EXPECT_EQ(transitions[0].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); EXPECT_EQ( transitions[1].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_UNCONFIGURED_SHUTDOWN); EXPECT_TRUE( lifecycle_client()->change_state( lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE)); EXPECT_EQ( lifecycle_client()->get_state().id, lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE); transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 3u); EXPECT_EQ(transitions[0].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP); EXPECT_EQ(transitions[1].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE); EXPECT_EQ( transitions[2].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_INACTIVE_SHUTDOWN); EXPECT_TRUE( lifecycle_client()->change_state( lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE)); EXPECT_EQ(lifecycle_client()->get_state().id, lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE); transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 2u); EXPECT_EQ(transitions[0].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE); EXPECT_EQ( transitions[1].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_ACTIVE_SHUTDOWN); EXPECT_TRUE( lifecycle_client()->change_state( lifecycle_msgs::msg::Transition:: TRANSITION_DEACTIVATE)); EXPECT_EQ( lifecycle_client()->get_state().id, lifecycle_msgs::msg::State::PRIMARY_STATE_INACTIVE); transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 3u); EXPECT_EQ(transitions[0].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP); EXPECT_EQ(transitions[1].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE); EXPECT_EQ( transitions[2].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_INACTIVE_SHUTDOWN); EXPECT_TRUE( lifecycle_client()->change_state( lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP)); EXPECT_EQ( lifecycle_client()->get_state().id, lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED); transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 2u); EXPECT_EQ(transitions[0].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); EXPECT_EQ( transitions[1].transition.id, lifecycle_msgs::msg::Transition::TRANSITION_UNCONFIGURED_SHUTDOWN); EXPECT_TRUE( lifecycle_client()->change_state( lifecycle_msgs::msg::Transition:: TRANSITION_UNCONFIGURED_SHUTDOWN)); EXPECT_EQ( lifecycle_client()->get_state().id, lifecycle_msgs::msg::State::PRIMARY_STATE_FINALIZED); transitions = lifecycle_client()->get_available_transitions(); EXPECT_EQ(transitions.size(), 0u); } TEST_F(TestLifecycleServiceClient, get_service_names_and_types_by_node) { auto node1 = std::make_shared<LifecycleServiceClient>("client1"); auto node2 = std::make_shared<LifecycleServiceClient>("client2"); auto node_graph = node1->get_node_graph_interface(); ASSERT_NE(nullptr, node_graph); EXPECT_THROW( node_graph->get_service_names_and_types_by_node("not_a_node", "not_absolute_namespace"), std::runtime_error); auto service_names_and_types1 = node_graph->get_service_names_and_types_by_node("client1", "/"); auto service_names_and_types2 = node_graph->get_service_names_and_types_by_node("client2", "/"); auto start = std::chrono::steady_clock::now(); while (0 == service_names_and_types1.size() || service_names_and_types1.size() != service_names_and_types2.size() || (std::chrono::steady_clock::now() - start) < std::chrono::seconds(1)) { service_names_and_types1 = node_graph->get_service_names_and_types_by_node("client1", "/"); service_names_and_types2 = node_graph->get_service_names_and_types_by_node("client2", "/"); } EXPECT_EQ(service_names_and_types1.size(), service_names_and_types2.size()); } TEST_F(TestLifecycleServiceClient, declare_parameter_with_no_initial_values) { auto node1 = std::make_shared<LifecycleServiceClient>("client1"); auto on_set_parameters = [](const std::vector<rclcpp::Parameter> &) { rcl_interfaces::msg::SetParametersResult result; result.successful = true; return result; }; auto handler = node1->add_on_set_parameters_callback(on_set_parameters); RCPPUTILS_SCOPE_EXIT( {node1->remove_on_set_parameters_callback(handler.get());}); // always reset } TEST_F(TestLifecycleServiceClient, wait_for_graph_change) { auto node = std::make_shared<LifecycleServiceClient>("client_wait_for_graph_change"); auto node_graph = node->get_node_graph_interface(); ASSERT_NE(nullptr, node_graph); EXPECT_NO_THROW(node_graph->notify_graph_change()); EXPECT_THROW( node_graph->wait_for_graph_change(nullptr, std::chrono::milliseconds(1)), rclcpp::exceptions::InvalidEventError); auto event = std::make_shared<rclcpp::Event>(); EXPECT_THROW( node_graph->wait_for_graph_change(event, std::chrono::milliseconds(0)), rclcpp::exceptions::EventNotRegisteredError); } class TestLifecycleServiceClientRCLErrors : public ::testing::Test { protected: void SetUp() override { rclcpp::init(0, nullptr); } void TearDown() override { rclcpp::shutdown(); } }; TEST_F(TestLifecycleServiceClientRCLErrors, call_services_rcl_errors) { auto lifecycle_node = std::make_shared<EmptyLifecycleNode>(); auto lifecycle_client = std::make_shared<LifecycleServiceClient>("client_with_errors"); auto mock = mocking_utils::patch_and_return( "lib:rclcpp_lifecycle", rcl_lifecycle_state_machine_is_initialized, RCL_RET_ERROR); // on_change_state lifecycle_client->change_state( lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); rclcpp::spin_some(lifecycle_client); EXPECT_THROW( rclcpp::spin_some(lifecycle_node->get_node_base_interface()), std::runtime_error); // on_get_state lifecycle_client->get_state(); rclcpp::spin_some(lifecycle_client); EXPECT_THROW( rclcpp::spin_some(lifecycle_node->get_node_base_interface()), std::runtime_error); // on_get_avilable_states lifecycle_client->get_available_states(); rclcpp::spin_some(lifecycle_client); EXPECT_THROW( rclcpp::spin_some(lifecycle_node->get_node_base_interface()), std::runtime_error); // on_get_available_transitions lifecycle_client->get_available_transitions(); rclcpp::spin_some(lifecycle_client); EXPECT_THROW( rclcpp::spin_some(lifecycle_node->get_node_base_interface()), std::runtime_error); // on_get_transition_graph lifecycle_client->get_transition_graph(); rclcpp::spin_some(lifecycle_client); EXPECT_THROW( rclcpp::spin_some(lifecycle_node->get_node_base_interface()), std::runtime_error); }
36.304622
98
0.755338
[ "vector" ]
6de53f5c267cd9cb26c68b601fc1d7cc1f9f4125
258,647
cpp
C++
Bld1/Il2CppOutputProject/Source/il2cppOutput/Microsoft.MixedReality.OpenXR_Attr.cpp
Reality-Hack-2022/TEAM-30
f3346ea1d7aa307f518730f12ec42cd18f5543e6
[ "MIT" ]
1
2022-03-28T07:59:17.000Z
2022-03-28T07:59:17.000Z
Bld1/Il2CppOutputProject/Source/il2cppOutput/Microsoft.MixedReality.OpenXR_Attr.cpp
Reality-Hack-2022/TEAM-30
f3346ea1d7aa307f518730f12ec42cd18f5543e6
[ "MIT" ]
null
null
null
Bld1/Il2CppOutputProject/Source/il2cppOutput/Microsoft.MixedReality.OpenXR_Attr.cpp
Reality-Hack-2022/TEAM-30
f3346ea1d7aa307f518730f12ec42cd18f5543e6
[ "MIT" ]
1
2022-03-26T18:23:31.000Z
2022-03-26T18:23:31.000Z
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <limits> #include <stdint.h> // System.Char[] struct CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34; // System.String[] struct StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A; // System.Type[] struct TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755; // System.Runtime.CompilerServices.AsyncStateMachineAttribute struct AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6; // System.AttributeUsageAttribute struct AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C; // System.Reflection.Binder struct Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30; // System.Runtime.CompilerServices.CompilationRelaxationsAttribute struct CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF; // System.Runtime.CompilerServices.CompilerGeneratedAttribute struct CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C; // System.Diagnostics.DebuggableAttribute struct DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B; // System.Diagnostics.DebuggerHiddenAttribute struct DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88; // System.Runtime.CompilerServices.ExtensionAttribute struct ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC; // System.FlagsAttribute struct FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36; // UnityEngine.InputSystem.Layouts.InputControlAttribute struct InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8; // UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute struct InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984; // System.Runtime.CompilerServices.InternalsVisibleToAttribute struct InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C; // System.Runtime.CompilerServices.IsReadOnlyAttribute struct IsReadOnlyAttribute_tB6E31A0106212818B0AB6DC627AA320291BD7566; // System.Runtime.CompilerServices.IteratorStateMachineAttribute struct IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830; // System.Reflection.MemberFilter struct MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81; // Microsoft.MixedReality.OpenXR.NativeLibTokenAttribute struct NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008; // System.ObsoleteAttribute struct ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671; // UnityEngine.Scripting.PreserveAttribute struct PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948; // System.Runtime.CompilerServices.RuntimeCompatibilityAttribute struct RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80; // UnityEngine.RuntimeInitializeOnLoadMethodAttribute struct RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D; // UnityEngine.SerializeField struct SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25; // System.String struct String_t; // UnityEngine.TooltipAttribute struct TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B; // System.Type struct Type_t; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5; IL2CPP_EXTERN_C RuntimeClass* StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C const RuntimeType* U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_0_0_0_var; IL2CPP_EXTERN_C const RuntimeType* U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_0_0_0_var; struct StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object // System.Attribute struct Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 : public RuntimeObject { public: public: }; // System.Reflection.MemberInfo struct MemberInfo_t : public RuntimeObject { public: public: }; // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::m_stringLength int32_t ___m_stringLength_0; // System.Char System.String::m_firstChar Il2CppChar ___m_firstChar_1; public: inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); } inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; } inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; } inline void set_m_stringLength_0(int32_t value) { ___m_stringLength_0 = value; } inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); } inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; } inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; } inline void set_m_firstChar_1(Il2CppChar value) { ___m_firstChar_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_5; public: inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); } inline String_t* get_Empty_5() const { return ___Empty_5; } inline String_t** get_address_of_Empty_5() { return &___Empty_5; } inline void set_Empty_5(String_t* value) { ___Empty_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value); } }; // System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com { }; // System.Nullable`1<System.Boolean> struct Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3 { public: // T System.Nullable`1::value bool ___value_0; // System.Boolean System.Nullable`1::has_value bool ___has_value_1; public: inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3, ___value_0)); } inline bool get_value_0() const { return ___value_0; } inline bool* get_address_of_value_0() { return &___value_0; } inline void set_value_0(bool value) { ___value_0 = value; } inline static int32_t get_offset_of_has_value_1() { return static_cast<int32_t>(offsetof(Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3, ___has_value_1)); } inline bool get_has_value_1() const { return ___has_value_1; } inline bool* get_address_of_has_value_1() { return &___has_value_1; } inline void set_has_value_1(bool value) { ___has_value_1 = value; } }; // System.Boolean struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37 { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value); } }; // System.Runtime.CompilerServices.CompilationRelaxationsAttribute struct CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.Int32 System.Runtime.CompilerServices.CompilationRelaxationsAttribute::m_relaxations int32_t ___m_relaxations_0; public: inline static int32_t get_offset_of_m_relaxations_0() { return static_cast<int32_t>(offsetof(CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF, ___m_relaxations_0)); } inline int32_t get_m_relaxations_0() const { return ___m_relaxations_0; } inline int32_t* get_address_of_m_relaxations_0() { return &___m_relaxations_0; } inline void set_m_relaxations_0(int32_t value) { ___m_relaxations_0 = value; } }; // System.Runtime.CompilerServices.CompilerGeneratedAttribute struct CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.Diagnostics.DebuggerHiddenAttribute struct DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA : public ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 { public: public: }; struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_com { }; // System.Runtime.CompilerServices.ExtensionAttribute struct ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.FlagsAttribute struct FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // System.Runtime.CompilerServices.InternalsVisibleToAttribute struct InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.String System.Runtime.CompilerServices.InternalsVisibleToAttribute::_assemblyName String_t* ____assemblyName_0; // System.Boolean System.Runtime.CompilerServices.InternalsVisibleToAttribute::_allInternalsVisible bool ____allInternalsVisible_1; public: inline static int32_t get_offset_of__assemblyName_0() { return static_cast<int32_t>(offsetof(InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C, ____assemblyName_0)); } inline String_t* get__assemblyName_0() const { return ____assemblyName_0; } inline String_t** get_address_of__assemblyName_0() { return &____assemblyName_0; } inline void set__assemblyName_0(String_t* value) { ____assemblyName_0 = value; Il2CppCodeGenWriteBarrier((void**)(&____assemblyName_0), (void*)value); } inline static int32_t get_offset_of__allInternalsVisible_1() { return static_cast<int32_t>(offsetof(InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C, ____allInternalsVisible_1)); } inline bool get__allInternalsVisible_1() const { return ____allInternalsVisible_1; } inline bool* get_address_of__allInternalsVisible_1() { return &____allInternalsVisible_1; } inline void set__allInternalsVisible_1(bool value) { ____allInternalsVisible_1 = value; } }; // System.Runtime.CompilerServices.IsReadOnlyAttribute struct IsReadOnlyAttribute_tB6E31A0106212818B0AB6DC627AA320291BD7566 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.ObsoleteAttribute struct ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.String System.ObsoleteAttribute::_message String_t* ____message_0; // System.Boolean System.ObsoleteAttribute::_error bool ____error_1; public: inline static int32_t get_offset_of__message_0() { return static_cast<int32_t>(offsetof(ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671, ____message_0)); } inline String_t* get__message_0() const { return ____message_0; } inline String_t** get_address_of__message_0() { return &____message_0; } inline void set__message_0(String_t* value) { ____message_0 = value; Il2CppCodeGenWriteBarrier((void**)(&____message_0), (void*)value); } inline static int32_t get_offset_of__error_1() { return static_cast<int32_t>(offsetof(ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671, ____error_1)); } inline bool get__error_1() const { return ____error_1; } inline bool* get_address_of__error_1() { return &____error_1; } inline void set__error_1(bool value) { ____error_1 = value; } }; // UnityEngine.Scripting.PreserveAttribute struct PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // UnityEngine.PropertyAttribute struct PropertyAttribute_t4A352471DF625C56C811E27AC86B7E1CE6444052 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.Runtime.CompilerServices.RuntimeCompatibilityAttribute struct RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::m_wrapNonExceptionThrows bool ___m_wrapNonExceptionThrows_0; public: inline static int32_t get_offset_of_m_wrapNonExceptionThrows_0() { return static_cast<int32_t>(offsetof(RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80, ___m_wrapNonExceptionThrows_0)); } inline bool get_m_wrapNonExceptionThrows_0() const { return ___m_wrapNonExceptionThrows_0; } inline bool* get_address_of_m_wrapNonExceptionThrows_0() { return &___m_wrapNonExceptionThrows_0; } inline void set_m_wrapNonExceptionThrows_0(bool value) { ___m_wrapNonExceptionThrows_0 = value; } }; // UnityEngine.SerializeField struct SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: public: }; // System.Runtime.CompilerServices.StateMachineAttribute struct StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.Type System.Runtime.CompilerServices.StateMachineAttribute::<StateMachineType>k__BackingField Type_t * ___U3CStateMachineTypeU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CStateMachineTypeU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3, ___U3CStateMachineTypeU3Ek__BackingField_0)); } inline Type_t * get_U3CStateMachineTypeU3Ek__BackingField_0() const { return ___U3CStateMachineTypeU3Ek__BackingField_0; } inline Type_t ** get_address_of_U3CStateMachineTypeU3Ek__BackingField_0() { return &___U3CStateMachineTypeU3Ek__BackingField_0; } inline void set_U3CStateMachineTypeU3Ek__BackingField_0(Type_t * value) { ___U3CStateMachineTypeU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CStateMachineTypeU3Ek__BackingField_0), (void*)value); } }; // System.UInt32 struct UInt32_tE60352A06233E4E69DD198BCC67142159F686B15 { public: // System.UInt32 System.UInt32::m_value uint32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_tE60352A06233E4E69DD198BCC67142159F686B15, ___m_value_0)); } inline uint32_t get_m_value_0() const { return ___m_value_0; } inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(uint32_t value) { ___m_value_0 = value; } }; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5 { public: union { struct { }; uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1]; }; public: }; // System.Runtime.CompilerServices.AsyncStateMachineAttribute struct AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 : public StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3 { public: public: }; // System.AttributeTargets struct AttributeTargets_t5F71273DFE1D0CA9B8109F02A023A7DBA9BFC923 { public: // System.Int32 System.AttributeTargets::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AttributeTargets_t5F71273DFE1D0CA9B8109F02A023A7DBA9BFC923, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // System.Reflection.BindingFlags struct BindingFlags_tAAAB07D9AC588F0D55D844E51D7035E96DF94733 { public: // System.Int32 System.Reflection.BindingFlags::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(BindingFlags_tAAAB07D9AC588F0D55D844E51D7035E96DF94733, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.InputSystem.Layouts.InputControlAttribute struct InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 : public PropertyAttribute_t4A352471DF625C56C811E27AC86B7E1CE6444052 { public: // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<layout>k__BackingField String_t* ___U3ClayoutU3Ek__BackingField_0; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<variants>k__BackingField String_t* ___U3CvariantsU3Ek__BackingField_1; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<name>k__BackingField String_t* ___U3CnameU3Ek__BackingField_2; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<format>k__BackingField String_t* ___U3CformatU3Ek__BackingField_3; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<usage>k__BackingField String_t* ___U3CusageU3Ek__BackingField_4; // System.String[] UnityEngine.InputSystem.Layouts.InputControlAttribute::<usages>k__BackingField StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___U3CusagesU3Ek__BackingField_5; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<parameters>k__BackingField String_t* ___U3CparametersU3Ek__BackingField_6; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<processors>k__BackingField String_t* ___U3CprocessorsU3Ek__BackingField_7; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<alias>k__BackingField String_t* ___U3CaliasU3Ek__BackingField_8; // System.String[] UnityEngine.InputSystem.Layouts.InputControlAttribute::<aliases>k__BackingField StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___U3CaliasesU3Ek__BackingField_9; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<useStateFrom>k__BackingField String_t* ___U3CuseStateFromU3Ek__BackingField_10; // System.UInt32 UnityEngine.InputSystem.Layouts.InputControlAttribute::<bit>k__BackingField uint32_t ___U3CbitU3Ek__BackingField_11; // System.UInt32 UnityEngine.InputSystem.Layouts.InputControlAttribute::<offset>k__BackingField uint32_t ___U3CoffsetU3Ek__BackingField_12; // System.UInt32 UnityEngine.InputSystem.Layouts.InputControlAttribute::<sizeInBits>k__BackingField uint32_t ___U3CsizeInBitsU3Ek__BackingField_13; // System.Int32 UnityEngine.InputSystem.Layouts.InputControlAttribute::<arraySize>k__BackingField int32_t ___U3CarraySizeU3Ek__BackingField_14; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<displayName>k__BackingField String_t* ___U3CdisplayNameU3Ek__BackingField_15; // System.String UnityEngine.InputSystem.Layouts.InputControlAttribute::<shortDisplayName>k__BackingField String_t* ___U3CshortDisplayNameU3Ek__BackingField_16; // System.Boolean UnityEngine.InputSystem.Layouts.InputControlAttribute::<noisy>k__BackingField bool ___U3CnoisyU3Ek__BackingField_17; // System.Boolean UnityEngine.InputSystem.Layouts.InputControlAttribute::<synthetic>k__BackingField bool ___U3CsyntheticU3Ek__BackingField_18; // System.Object UnityEngine.InputSystem.Layouts.InputControlAttribute::<defaultState>k__BackingField RuntimeObject * ___U3CdefaultStateU3Ek__BackingField_19; // System.Object UnityEngine.InputSystem.Layouts.InputControlAttribute::<minValue>k__BackingField RuntimeObject * ___U3CminValueU3Ek__BackingField_20; // System.Object UnityEngine.InputSystem.Layouts.InputControlAttribute::<maxValue>k__BackingField RuntimeObject * ___U3CmaxValueU3Ek__BackingField_21; public: inline static int32_t get_offset_of_U3ClayoutU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3ClayoutU3Ek__BackingField_0)); } inline String_t* get_U3ClayoutU3Ek__BackingField_0() const { return ___U3ClayoutU3Ek__BackingField_0; } inline String_t** get_address_of_U3ClayoutU3Ek__BackingField_0() { return &___U3ClayoutU3Ek__BackingField_0; } inline void set_U3ClayoutU3Ek__BackingField_0(String_t* value) { ___U3ClayoutU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3ClayoutU3Ek__BackingField_0), (void*)value); } inline static int32_t get_offset_of_U3CvariantsU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CvariantsU3Ek__BackingField_1)); } inline String_t* get_U3CvariantsU3Ek__BackingField_1() const { return ___U3CvariantsU3Ek__BackingField_1; } inline String_t** get_address_of_U3CvariantsU3Ek__BackingField_1() { return &___U3CvariantsU3Ek__BackingField_1; } inline void set_U3CvariantsU3Ek__BackingField_1(String_t* value) { ___U3CvariantsU3Ek__BackingField_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CvariantsU3Ek__BackingField_1), (void*)value); } inline static int32_t get_offset_of_U3CnameU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CnameU3Ek__BackingField_2)); } inline String_t* get_U3CnameU3Ek__BackingField_2() const { return ___U3CnameU3Ek__BackingField_2; } inline String_t** get_address_of_U3CnameU3Ek__BackingField_2() { return &___U3CnameU3Ek__BackingField_2; } inline void set_U3CnameU3Ek__BackingField_2(String_t* value) { ___U3CnameU3Ek__BackingField_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CnameU3Ek__BackingField_2), (void*)value); } inline static int32_t get_offset_of_U3CformatU3Ek__BackingField_3() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CformatU3Ek__BackingField_3)); } inline String_t* get_U3CformatU3Ek__BackingField_3() const { return ___U3CformatU3Ek__BackingField_3; } inline String_t** get_address_of_U3CformatU3Ek__BackingField_3() { return &___U3CformatU3Ek__BackingField_3; } inline void set_U3CformatU3Ek__BackingField_3(String_t* value) { ___U3CformatU3Ek__BackingField_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CformatU3Ek__BackingField_3), (void*)value); } inline static int32_t get_offset_of_U3CusageU3Ek__BackingField_4() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CusageU3Ek__BackingField_4)); } inline String_t* get_U3CusageU3Ek__BackingField_4() const { return ___U3CusageU3Ek__BackingField_4; } inline String_t** get_address_of_U3CusageU3Ek__BackingField_4() { return &___U3CusageU3Ek__BackingField_4; } inline void set_U3CusageU3Ek__BackingField_4(String_t* value) { ___U3CusageU3Ek__BackingField_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CusageU3Ek__BackingField_4), (void*)value); } inline static int32_t get_offset_of_U3CusagesU3Ek__BackingField_5() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CusagesU3Ek__BackingField_5)); } inline StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* get_U3CusagesU3Ek__BackingField_5() const { return ___U3CusagesU3Ek__BackingField_5; } inline StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A** get_address_of_U3CusagesU3Ek__BackingField_5() { return &___U3CusagesU3Ek__BackingField_5; } inline void set_U3CusagesU3Ek__BackingField_5(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* value) { ___U3CusagesU3Ek__BackingField_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CusagesU3Ek__BackingField_5), (void*)value); } inline static int32_t get_offset_of_U3CparametersU3Ek__BackingField_6() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CparametersU3Ek__BackingField_6)); } inline String_t* get_U3CparametersU3Ek__BackingField_6() const { return ___U3CparametersU3Ek__BackingField_6; } inline String_t** get_address_of_U3CparametersU3Ek__BackingField_6() { return &___U3CparametersU3Ek__BackingField_6; } inline void set_U3CparametersU3Ek__BackingField_6(String_t* value) { ___U3CparametersU3Ek__BackingField_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CparametersU3Ek__BackingField_6), (void*)value); } inline static int32_t get_offset_of_U3CprocessorsU3Ek__BackingField_7() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CprocessorsU3Ek__BackingField_7)); } inline String_t* get_U3CprocessorsU3Ek__BackingField_7() const { return ___U3CprocessorsU3Ek__BackingField_7; } inline String_t** get_address_of_U3CprocessorsU3Ek__BackingField_7() { return &___U3CprocessorsU3Ek__BackingField_7; } inline void set_U3CprocessorsU3Ek__BackingField_7(String_t* value) { ___U3CprocessorsU3Ek__BackingField_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CprocessorsU3Ek__BackingField_7), (void*)value); } inline static int32_t get_offset_of_U3CaliasU3Ek__BackingField_8() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CaliasU3Ek__BackingField_8)); } inline String_t* get_U3CaliasU3Ek__BackingField_8() const { return ___U3CaliasU3Ek__BackingField_8; } inline String_t** get_address_of_U3CaliasU3Ek__BackingField_8() { return &___U3CaliasU3Ek__BackingField_8; } inline void set_U3CaliasU3Ek__BackingField_8(String_t* value) { ___U3CaliasU3Ek__BackingField_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CaliasU3Ek__BackingField_8), (void*)value); } inline static int32_t get_offset_of_U3CaliasesU3Ek__BackingField_9() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CaliasesU3Ek__BackingField_9)); } inline StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* get_U3CaliasesU3Ek__BackingField_9() const { return ___U3CaliasesU3Ek__BackingField_9; } inline StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A** get_address_of_U3CaliasesU3Ek__BackingField_9() { return &___U3CaliasesU3Ek__BackingField_9; } inline void set_U3CaliasesU3Ek__BackingField_9(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* value) { ___U3CaliasesU3Ek__BackingField_9 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CaliasesU3Ek__BackingField_9), (void*)value); } inline static int32_t get_offset_of_U3CuseStateFromU3Ek__BackingField_10() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CuseStateFromU3Ek__BackingField_10)); } inline String_t* get_U3CuseStateFromU3Ek__BackingField_10() const { return ___U3CuseStateFromU3Ek__BackingField_10; } inline String_t** get_address_of_U3CuseStateFromU3Ek__BackingField_10() { return &___U3CuseStateFromU3Ek__BackingField_10; } inline void set_U3CuseStateFromU3Ek__BackingField_10(String_t* value) { ___U3CuseStateFromU3Ek__BackingField_10 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CuseStateFromU3Ek__BackingField_10), (void*)value); } inline static int32_t get_offset_of_U3CbitU3Ek__BackingField_11() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CbitU3Ek__BackingField_11)); } inline uint32_t get_U3CbitU3Ek__BackingField_11() const { return ___U3CbitU3Ek__BackingField_11; } inline uint32_t* get_address_of_U3CbitU3Ek__BackingField_11() { return &___U3CbitU3Ek__BackingField_11; } inline void set_U3CbitU3Ek__BackingField_11(uint32_t value) { ___U3CbitU3Ek__BackingField_11 = value; } inline static int32_t get_offset_of_U3CoffsetU3Ek__BackingField_12() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CoffsetU3Ek__BackingField_12)); } inline uint32_t get_U3CoffsetU3Ek__BackingField_12() const { return ___U3CoffsetU3Ek__BackingField_12; } inline uint32_t* get_address_of_U3CoffsetU3Ek__BackingField_12() { return &___U3CoffsetU3Ek__BackingField_12; } inline void set_U3CoffsetU3Ek__BackingField_12(uint32_t value) { ___U3CoffsetU3Ek__BackingField_12 = value; } inline static int32_t get_offset_of_U3CsizeInBitsU3Ek__BackingField_13() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CsizeInBitsU3Ek__BackingField_13)); } inline uint32_t get_U3CsizeInBitsU3Ek__BackingField_13() const { return ___U3CsizeInBitsU3Ek__BackingField_13; } inline uint32_t* get_address_of_U3CsizeInBitsU3Ek__BackingField_13() { return &___U3CsizeInBitsU3Ek__BackingField_13; } inline void set_U3CsizeInBitsU3Ek__BackingField_13(uint32_t value) { ___U3CsizeInBitsU3Ek__BackingField_13 = value; } inline static int32_t get_offset_of_U3CarraySizeU3Ek__BackingField_14() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CarraySizeU3Ek__BackingField_14)); } inline int32_t get_U3CarraySizeU3Ek__BackingField_14() const { return ___U3CarraySizeU3Ek__BackingField_14; } inline int32_t* get_address_of_U3CarraySizeU3Ek__BackingField_14() { return &___U3CarraySizeU3Ek__BackingField_14; } inline void set_U3CarraySizeU3Ek__BackingField_14(int32_t value) { ___U3CarraySizeU3Ek__BackingField_14 = value; } inline static int32_t get_offset_of_U3CdisplayNameU3Ek__BackingField_15() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CdisplayNameU3Ek__BackingField_15)); } inline String_t* get_U3CdisplayNameU3Ek__BackingField_15() const { return ___U3CdisplayNameU3Ek__BackingField_15; } inline String_t** get_address_of_U3CdisplayNameU3Ek__BackingField_15() { return &___U3CdisplayNameU3Ek__BackingField_15; } inline void set_U3CdisplayNameU3Ek__BackingField_15(String_t* value) { ___U3CdisplayNameU3Ek__BackingField_15 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CdisplayNameU3Ek__BackingField_15), (void*)value); } inline static int32_t get_offset_of_U3CshortDisplayNameU3Ek__BackingField_16() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CshortDisplayNameU3Ek__BackingField_16)); } inline String_t* get_U3CshortDisplayNameU3Ek__BackingField_16() const { return ___U3CshortDisplayNameU3Ek__BackingField_16; } inline String_t** get_address_of_U3CshortDisplayNameU3Ek__BackingField_16() { return &___U3CshortDisplayNameU3Ek__BackingField_16; } inline void set_U3CshortDisplayNameU3Ek__BackingField_16(String_t* value) { ___U3CshortDisplayNameU3Ek__BackingField_16 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CshortDisplayNameU3Ek__BackingField_16), (void*)value); } inline static int32_t get_offset_of_U3CnoisyU3Ek__BackingField_17() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CnoisyU3Ek__BackingField_17)); } inline bool get_U3CnoisyU3Ek__BackingField_17() const { return ___U3CnoisyU3Ek__BackingField_17; } inline bool* get_address_of_U3CnoisyU3Ek__BackingField_17() { return &___U3CnoisyU3Ek__BackingField_17; } inline void set_U3CnoisyU3Ek__BackingField_17(bool value) { ___U3CnoisyU3Ek__BackingField_17 = value; } inline static int32_t get_offset_of_U3CsyntheticU3Ek__BackingField_18() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CsyntheticU3Ek__BackingField_18)); } inline bool get_U3CsyntheticU3Ek__BackingField_18() const { return ___U3CsyntheticU3Ek__BackingField_18; } inline bool* get_address_of_U3CsyntheticU3Ek__BackingField_18() { return &___U3CsyntheticU3Ek__BackingField_18; } inline void set_U3CsyntheticU3Ek__BackingField_18(bool value) { ___U3CsyntheticU3Ek__BackingField_18 = value; } inline static int32_t get_offset_of_U3CdefaultStateU3Ek__BackingField_19() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CdefaultStateU3Ek__BackingField_19)); } inline RuntimeObject * get_U3CdefaultStateU3Ek__BackingField_19() const { return ___U3CdefaultStateU3Ek__BackingField_19; } inline RuntimeObject ** get_address_of_U3CdefaultStateU3Ek__BackingField_19() { return &___U3CdefaultStateU3Ek__BackingField_19; } inline void set_U3CdefaultStateU3Ek__BackingField_19(RuntimeObject * value) { ___U3CdefaultStateU3Ek__BackingField_19 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CdefaultStateU3Ek__BackingField_19), (void*)value); } inline static int32_t get_offset_of_U3CminValueU3Ek__BackingField_20() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CminValueU3Ek__BackingField_20)); } inline RuntimeObject * get_U3CminValueU3Ek__BackingField_20() const { return ___U3CminValueU3Ek__BackingField_20; } inline RuntimeObject ** get_address_of_U3CminValueU3Ek__BackingField_20() { return &___U3CminValueU3Ek__BackingField_20; } inline void set_U3CminValueU3Ek__BackingField_20(RuntimeObject * value) { ___U3CminValueU3Ek__BackingField_20 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CminValueU3Ek__BackingField_20), (void*)value); } inline static int32_t get_offset_of_U3CmaxValueU3Ek__BackingField_21() { return static_cast<int32_t>(offsetof(InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8, ___U3CmaxValueU3Ek__BackingField_21)); } inline RuntimeObject * get_U3CmaxValueU3Ek__BackingField_21() const { return ___U3CmaxValueU3Ek__BackingField_21; } inline RuntimeObject ** get_address_of_U3CmaxValueU3Ek__BackingField_21() { return &___U3CmaxValueU3Ek__BackingField_21; } inline void set_U3CmaxValueU3Ek__BackingField_21(RuntimeObject * value) { ___U3CmaxValueU3Ek__BackingField_21 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CmaxValueU3Ek__BackingField_21), (void*)value); } }; // UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute struct InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.Type UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<stateType>k__BackingField Type_t * ___U3CstateTypeU3Ek__BackingField_0; // System.String UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<stateFormat>k__BackingField String_t* ___U3CstateFormatU3Ek__BackingField_1; // System.String[] UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<commonUsages>k__BackingField StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___U3CcommonUsagesU3Ek__BackingField_2; // System.String UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<variants>k__BackingField String_t* ___U3CvariantsU3Ek__BackingField_3; // System.Nullable`1<System.Boolean> UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::updateBeforeRenderInternal Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3 ___updateBeforeRenderInternal_4; // System.Boolean UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<isGenericTypeOfDevice>k__BackingField bool ___U3CisGenericTypeOfDeviceU3Ek__BackingField_5; // System.String UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<displayName>k__BackingField String_t* ___U3CdisplayNameU3Ek__BackingField_6; // System.String UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<description>k__BackingField String_t* ___U3CdescriptionU3Ek__BackingField_7; // System.Boolean UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::<hideInUI>k__BackingField bool ___U3ChideInUIU3Ek__BackingField_8; public: inline static int32_t get_offset_of_U3CstateTypeU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CstateTypeU3Ek__BackingField_0)); } inline Type_t * get_U3CstateTypeU3Ek__BackingField_0() const { return ___U3CstateTypeU3Ek__BackingField_0; } inline Type_t ** get_address_of_U3CstateTypeU3Ek__BackingField_0() { return &___U3CstateTypeU3Ek__BackingField_0; } inline void set_U3CstateTypeU3Ek__BackingField_0(Type_t * value) { ___U3CstateTypeU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CstateTypeU3Ek__BackingField_0), (void*)value); } inline static int32_t get_offset_of_U3CstateFormatU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CstateFormatU3Ek__BackingField_1)); } inline String_t* get_U3CstateFormatU3Ek__BackingField_1() const { return ___U3CstateFormatU3Ek__BackingField_1; } inline String_t** get_address_of_U3CstateFormatU3Ek__BackingField_1() { return &___U3CstateFormatU3Ek__BackingField_1; } inline void set_U3CstateFormatU3Ek__BackingField_1(String_t* value) { ___U3CstateFormatU3Ek__BackingField_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CstateFormatU3Ek__BackingField_1), (void*)value); } inline static int32_t get_offset_of_U3CcommonUsagesU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CcommonUsagesU3Ek__BackingField_2)); } inline StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* get_U3CcommonUsagesU3Ek__BackingField_2() const { return ___U3CcommonUsagesU3Ek__BackingField_2; } inline StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A** get_address_of_U3CcommonUsagesU3Ek__BackingField_2() { return &___U3CcommonUsagesU3Ek__BackingField_2; } inline void set_U3CcommonUsagesU3Ek__BackingField_2(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* value) { ___U3CcommonUsagesU3Ek__BackingField_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CcommonUsagesU3Ek__BackingField_2), (void*)value); } inline static int32_t get_offset_of_U3CvariantsU3Ek__BackingField_3() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CvariantsU3Ek__BackingField_3)); } inline String_t* get_U3CvariantsU3Ek__BackingField_3() const { return ___U3CvariantsU3Ek__BackingField_3; } inline String_t** get_address_of_U3CvariantsU3Ek__BackingField_3() { return &___U3CvariantsU3Ek__BackingField_3; } inline void set_U3CvariantsU3Ek__BackingField_3(String_t* value) { ___U3CvariantsU3Ek__BackingField_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CvariantsU3Ek__BackingField_3), (void*)value); } inline static int32_t get_offset_of_updateBeforeRenderInternal_4() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___updateBeforeRenderInternal_4)); } inline Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3 get_updateBeforeRenderInternal_4() const { return ___updateBeforeRenderInternal_4; } inline Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3 * get_address_of_updateBeforeRenderInternal_4() { return &___updateBeforeRenderInternal_4; } inline void set_updateBeforeRenderInternal_4(Nullable_1_t1D1CD146BFCBDC2E53E1F700889F8C5C21063EF3 value) { ___updateBeforeRenderInternal_4 = value; } inline static int32_t get_offset_of_U3CisGenericTypeOfDeviceU3Ek__BackingField_5() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CisGenericTypeOfDeviceU3Ek__BackingField_5)); } inline bool get_U3CisGenericTypeOfDeviceU3Ek__BackingField_5() const { return ___U3CisGenericTypeOfDeviceU3Ek__BackingField_5; } inline bool* get_address_of_U3CisGenericTypeOfDeviceU3Ek__BackingField_5() { return &___U3CisGenericTypeOfDeviceU3Ek__BackingField_5; } inline void set_U3CisGenericTypeOfDeviceU3Ek__BackingField_5(bool value) { ___U3CisGenericTypeOfDeviceU3Ek__BackingField_5 = value; } inline static int32_t get_offset_of_U3CdisplayNameU3Ek__BackingField_6() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CdisplayNameU3Ek__BackingField_6)); } inline String_t* get_U3CdisplayNameU3Ek__BackingField_6() const { return ___U3CdisplayNameU3Ek__BackingField_6; } inline String_t** get_address_of_U3CdisplayNameU3Ek__BackingField_6() { return &___U3CdisplayNameU3Ek__BackingField_6; } inline void set_U3CdisplayNameU3Ek__BackingField_6(String_t* value) { ___U3CdisplayNameU3Ek__BackingField_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CdisplayNameU3Ek__BackingField_6), (void*)value); } inline static int32_t get_offset_of_U3CdescriptionU3Ek__BackingField_7() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3CdescriptionU3Ek__BackingField_7)); } inline String_t* get_U3CdescriptionU3Ek__BackingField_7() const { return ___U3CdescriptionU3Ek__BackingField_7; } inline String_t** get_address_of_U3CdescriptionU3Ek__BackingField_7() { return &___U3CdescriptionU3Ek__BackingField_7; } inline void set_U3CdescriptionU3Ek__BackingField_7(String_t* value) { ___U3CdescriptionU3Ek__BackingField_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CdescriptionU3Ek__BackingField_7), (void*)value); } inline static int32_t get_offset_of_U3ChideInUIU3Ek__BackingField_8() { return static_cast<int32_t>(offsetof(InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984, ___U3ChideInUIU3Ek__BackingField_8)); } inline bool get_U3ChideInUIU3Ek__BackingField_8() const { return ___U3ChideInUIU3Ek__BackingField_8; } inline bool* get_address_of_U3ChideInUIU3Ek__BackingField_8() { return &___U3ChideInUIU3Ek__BackingField_8; } inline void set_U3ChideInUIU3Ek__BackingField_8(bool value) { ___U3ChideInUIU3Ek__BackingField_8 = value; } }; // System.Runtime.CompilerServices.IteratorStateMachineAttribute struct IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 : public StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3 { public: public: }; // Microsoft.MixedReality.OpenXR.NativeLibToken struct NativeLibToken_t7870D55716369C2C8515F30B34C7E67CA5E63EA8 { public: // System.UInt64 Microsoft.MixedReality.OpenXR.NativeLibToken::value__ uint64_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(NativeLibToken_t7870D55716369C2C8515F30B34C7E67CA5E63EA8, ___value___2)); } inline uint64_t get_value___2() const { return ___value___2; } inline uint64_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(uint64_t value) { ___value___2 = value; } }; // UnityEngine.RuntimeInitializeLoadType struct RuntimeInitializeLoadType_t78BE0E3079AE8955C97DF6A9814A6E6BFA146EA5 { public: // System.Int32 UnityEngine.RuntimeInitializeLoadType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(RuntimeInitializeLoadType_t78BE0E3079AE8955C97DF6A9814A6E6BFA146EA5, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // System.RuntimeTypeHandle struct RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 { public: // System.IntPtr System.RuntimeTypeHandle::value intptr_t ___value_0; public: inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9, ___value_0)); } inline intptr_t get_value_0() const { return ___value_0; } inline intptr_t* get_address_of_value_0() { return &___value_0; } inline void set_value_0(intptr_t value) { ___value_0 = value; } }; // UnityEngine.TooltipAttribute struct TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B : public PropertyAttribute_t4A352471DF625C56C811E27AC86B7E1CE6444052 { public: // System.String UnityEngine.TooltipAttribute::tooltip String_t* ___tooltip_0; public: inline static int32_t get_offset_of_tooltip_0() { return static_cast<int32_t>(offsetof(TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B, ___tooltip_0)); } inline String_t* get_tooltip_0() const { return ___tooltip_0; } inline String_t** get_address_of_tooltip_0() { return &___tooltip_0; } inline void set_tooltip_0(String_t* value) { ___tooltip_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___tooltip_0), (void*)value); } }; // System.Diagnostics.DebuggableAttribute/DebuggingModes struct DebuggingModes_t279D5B9C012ABA935887CB73C5A63A1F46AF08A8 { public: // System.Int32 System.Diagnostics.DebuggableAttribute/DebuggingModes::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(DebuggingModes_t279D5B9C012ABA935887CB73C5A63A1F46AF08A8, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // System.AttributeUsageAttribute struct AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.AttributeTargets System.AttributeUsageAttribute::m_attributeTarget int32_t ___m_attributeTarget_0; // System.Boolean System.AttributeUsageAttribute::m_allowMultiple bool ___m_allowMultiple_1; // System.Boolean System.AttributeUsageAttribute::m_inherited bool ___m_inherited_2; public: inline static int32_t get_offset_of_m_attributeTarget_0() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C, ___m_attributeTarget_0)); } inline int32_t get_m_attributeTarget_0() const { return ___m_attributeTarget_0; } inline int32_t* get_address_of_m_attributeTarget_0() { return &___m_attributeTarget_0; } inline void set_m_attributeTarget_0(int32_t value) { ___m_attributeTarget_0 = value; } inline static int32_t get_offset_of_m_allowMultiple_1() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C, ___m_allowMultiple_1)); } inline bool get_m_allowMultiple_1() const { return ___m_allowMultiple_1; } inline bool* get_address_of_m_allowMultiple_1() { return &___m_allowMultiple_1; } inline void set_m_allowMultiple_1(bool value) { ___m_allowMultiple_1 = value; } inline static int32_t get_offset_of_m_inherited_2() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C, ___m_inherited_2)); } inline bool get_m_inherited_2() const { return ___m_inherited_2; } inline bool* get_address_of_m_inherited_2() { return &___m_inherited_2; } inline void set_m_inherited_2(bool value) { ___m_inherited_2 = value; } }; struct AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C_StaticFields { public: // System.AttributeUsageAttribute System.AttributeUsageAttribute::Default AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C * ___Default_3; public: inline static int32_t get_offset_of_Default_3() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C_StaticFields, ___Default_3)); } inline AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C * get_Default_3() const { return ___Default_3; } inline AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C ** get_address_of_Default_3() { return &___Default_3; } inline void set_Default_3(AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C * value) { ___Default_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___Default_3), (void*)value); } }; // System.Diagnostics.DebuggableAttribute struct DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // System.Diagnostics.DebuggableAttribute/DebuggingModes System.Diagnostics.DebuggableAttribute::m_debuggingModes int32_t ___m_debuggingModes_0; public: inline static int32_t get_offset_of_m_debuggingModes_0() { return static_cast<int32_t>(offsetof(DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B, ___m_debuggingModes_0)); } inline int32_t get_m_debuggingModes_0() const { return ___m_debuggingModes_0; } inline int32_t* get_address_of_m_debuggingModes_0() { return &___m_debuggingModes_0; } inline void set_m_debuggingModes_0(int32_t value) { ___m_debuggingModes_0 = value; } }; // Microsoft.MixedReality.OpenXR.NativeLibTokenAttribute struct NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 { public: // Microsoft.MixedReality.OpenXR.NativeLibToken Microsoft.MixedReality.OpenXR.NativeLibTokenAttribute::<NativeLibToken>k__BackingField uint64_t ___U3CNativeLibTokenU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CNativeLibTokenU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008, ___U3CNativeLibTokenU3Ek__BackingField_0)); } inline uint64_t get_U3CNativeLibTokenU3Ek__BackingField_0() const { return ___U3CNativeLibTokenU3Ek__BackingField_0; } inline uint64_t* get_address_of_U3CNativeLibTokenU3Ek__BackingField_0() { return &___U3CNativeLibTokenU3Ek__BackingField_0; } inline void set_U3CNativeLibTokenU3Ek__BackingField_0(uint64_t value) { ___U3CNativeLibTokenU3Ek__BackingField_0 = value; } }; // UnityEngine.RuntimeInitializeOnLoadMethodAttribute struct RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D : public PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 { public: // UnityEngine.RuntimeInitializeLoadType UnityEngine.RuntimeInitializeOnLoadMethodAttribute::m_LoadType int32_t ___m_LoadType_0; public: inline static int32_t get_offset_of_m_LoadType_0() { return static_cast<int32_t>(offsetof(RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D, ___m_LoadType_0)); } inline int32_t get_m_LoadType_0() const { return ___m_LoadType_0; } inline int32_t* get_address_of_m_LoadType_0() { return &___m_LoadType_0; } inline void set_m_LoadType_0(int32_t value) { ___m_LoadType_0 = value; } }; // System.Type struct Type_t : public MemberInfo_t { public: // System.RuntimeTypeHandle System.Type::_impl RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 ____impl_9; public: inline static int32_t get_offset_of__impl_9() { return static_cast<int32_t>(offsetof(Type_t, ____impl_9)); } inline RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 get__impl_9() const { return ____impl_9; } inline RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 * get_address_of__impl_9() { return &____impl_9; } inline void set__impl_9(RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 value) { ____impl_9 = value; } }; struct Type_t_StaticFields { public: // System.Reflection.MemberFilter System.Type::FilterAttribute MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterAttribute_0; // System.Reflection.MemberFilter System.Type::FilterName MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterName_1; // System.Reflection.MemberFilter System.Type::FilterNameIgnoreCase MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterNameIgnoreCase_2; // System.Object System.Type::Missing RuntimeObject * ___Missing_3; // System.Char System.Type::Delimiter Il2CppChar ___Delimiter_4; // System.Type[] System.Type::EmptyTypes TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* ___EmptyTypes_5; // System.Reflection.Binder System.Type::defaultBinder Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * ___defaultBinder_6; public: inline static int32_t get_offset_of_FilterAttribute_0() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterAttribute_0)); } inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterAttribute_0() const { return ___FilterAttribute_0; } inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterAttribute_0() { return &___FilterAttribute_0; } inline void set_FilterAttribute_0(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value) { ___FilterAttribute_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___FilterAttribute_0), (void*)value); } inline static int32_t get_offset_of_FilterName_1() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterName_1)); } inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterName_1() const { return ___FilterName_1; } inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterName_1() { return &___FilterName_1; } inline void set_FilterName_1(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value) { ___FilterName_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___FilterName_1), (void*)value); } inline static int32_t get_offset_of_FilterNameIgnoreCase_2() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterNameIgnoreCase_2)); } inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterNameIgnoreCase_2() const { return ___FilterNameIgnoreCase_2; } inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterNameIgnoreCase_2() { return &___FilterNameIgnoreCase_2; } inline void set_FilterNameIgnoreCase_2(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value) { ___FilterNameIgnoreCase_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___FilterNameIgnoreCase_2), (void*)value); } inline static int32_t get_offset_of_Missing_3() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Missing_3)); } inline RuntimeObject * get_Missing_3() const { return ___Missing_3; } inline RuntimeObject ** get_address_of_Missing_3() { return &___Missing_3; } inline void set_Missing_3(RuntimeObject * value) { ___Missing_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___Missing_3), (void*)value); } inline static int32_t get_offset_of_Delimiter_4() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Delimiter_4)); } inline Il2CppChar get_Delimiter_4() const { return ___Delimiter_4; } inline Il2CppChar* get_address_of_Delimiter_4() { return &___Delimiter_4; } inline void set_Delimiter_4(Il2CppChar value) { ___Delimiter_4 = value; } inline static int32_t get_offset_of_EmptyTypes_5() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___EmptyTypes_5)); } inline TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* get_EmptyTypes_5() const { return ___EmptyTypes_5; } inline TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755** get_address_of_EmptyTypes_5() { return &___EmptyTypes_5; } inline void set_EmptyTypes_5(TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* value) { ___EmptyTypes_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___EmptyTypes_5), (void*)value); } inline static int32_t get_offset_of_defaultBinder_6() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___defaultBinder_6)); } inline Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * get_defaultBinder_6() const { return ___defaultBinder_6; } inline Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 ** get_address_of_defaultBinder_6() { return &___defaultBinder_6; } inline void set_defaultBinder_6(Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * value) { ___defaultBinder_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___defaultBinder_6), (void*)value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // System.String[] struct StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A : public RuntimeArray { public: ALIGN_FIELD (8) String_t* m_Items[1]; public: inline String_t* GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline String_t** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, String_t* value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline String_t* GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline String_t** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, String_t* value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // System.Void System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InternalsVisibleToAttribute__ctor_m420071A75DCEEC72356490C64B4B0B9270DA32B9 (InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C * __this, String_t* ___assemblyName0, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CompilationRelaxationsAttribute__ctor_mAC3079EBC4EEAB474EED8208EF95DB39C922333B (CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF * __this, int32_t ___relaxations0, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.ExtensionAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * __this, const RuntimeMethod* method); // System.Void System.Diagnostics.DebuggableAttribute::.ctor(System.Diagnostics.DebuggableAttribute/DebuggingModes) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DebuggableAttribute__ctor_m7FF445C8435494A4847123A668D889E692E55550 (DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B * __this, int32_t ___modes0, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute__ctor_m551DDF1438CE97A984571949723F30F44CF7317C (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::set_WrapNonExceptionThrows(System.Boolean) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, bool ___value0, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35 (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * __this, const RuntimeMethod* method); // System.Void System.FlagsAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void FlagsAttribute__ctor_mE8DCBA1BE0E6B0424FEF5E5F249733CF6A0E1229 (FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 * __this, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IsReadOnlyAttribute__ctor_m02F9F7CD56DE227F7ABDD1E2593D82E6FFA57E9A (IsReadOnlyAttribute_tB6E31A0106212818B0AB6DC627AA320291BD7566 * __this, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(System.Type) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * __this, Type_t * ___stateMachineType0, const RuntimeMethod* method); // System.Void System.Diagnostics.DebuggerHiddenAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3 (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * __this, const RuntimeMethod* method); // System.Void UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputControlLayoutAttribute__ctor_m2C35D9C0A7CDEB6A840A215F33FF0FA9DDFD80BF (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * __this, const RuntimeMethod* method); // System.Void UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::set_displayName(System.String) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlLayoutAttribute_set_displayName_m51759C33760B60FB12DD2D2EDC8C431EA0FD1E20_inline (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * __this, String_t* ___value0, const RuntimeMethod* method); // System.Void UnityEngine.InputSystem.Layouts.InputControlLayoutAttribute::set_commonUsages(System.String[]) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlLayoutAttribute_set_commonUsages_mE744432198FBB37B38B16119433EB748EED7CCF3_inline (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * __this, StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Scripting.PreserveAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2 (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * __this, const RuntimeMethod* method); // System.Void UnityEngine.InputSystem.Layouts.InputControlAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * __this, const RuntimeMethod* method); // System.Void UnityEngine.InputSystem.Layouts.InputControlAttribute::set_aliases(System.String[]) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * __this, StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___value0, const RuntimeMethod* method); // System.Void UnityEngine.InputSystem.Layouts.InputControlAttribute::set_offset(System.UInt32) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * __this, uint32_t ___value0, const RuntimeMethod* method); // System.Void Microsoft.MixedReality.OpenXR.NativeLibTokenAttribute::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeLibTokenAttribute__ctor_m37D11C77F5A2D0487E11CC54852EAA3A5726C989 (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * __this, const RuntimeMethod* method); // System.Void Microsoft.MixedReality.OpenXR.NativeLibTokenAttribute::set_NativeLibToken(Microsoft.MixedReality.OpenXR.NativeLibToken) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * __this, uint64_t ___value0, const RuntimeMethod* method); // System.Void System.AttributeUsageAttribute::.ctor(System.AttributeTargets) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AttributeUsageAttribute__ctor_m5114E18826A49A025D48DC71904C430BD590656D (AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C * __this, int32_t ___validOn0, const RuntimeMethod* method); // System.Void UnityEngine.RuntimeInitializeOnLoadMethodAttribute::.ctor(UnityEngine.RuntimeInitializeLoadType) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RuntimeInitializeOnLoadMethodAttribute__ctor_mE79C8FD7B18EC53391334A6E6A66CAF09CDA8516 (RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D * __this, int32_t ___loadType0, const RuntimeMethod* method); // System.Void System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(System.Type) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481 (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * __this, Type_t * ___stateMachineType0, const RuntimeMethod* method); // System.Void System.ObsoleteAttribute::.ctor(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ObsoleteAttribute__ctor_mAC32A5CCD287DA84CDA9F08282C1C8B0DB7B9868 (ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 * __this, String_t* ___message0, const RuntimeMethod* method); // System.Void UnityEngine.TooltipAttribute::.ctor(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042 (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * __this, String_t* ___tooltip0, const RuntimeMethod* method); // System.Void UnityEngine.SerializeField::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3 (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * __this, const RuntimeMethod* method); static void Microsoft_MixedReality_OpenXR_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C * tmp = (InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C *)cache->attributes[0]; InternalsVisibleToAttribute__ctor_m420071A75DCEEC72356490C64B4B0B9270DA32B9(tmp, il2cpp_codegen_string_new_wrapper("\x4D\x69\x63\x72\x6F\x73\x6F\x66\x74\x2E\x4D\x69\x78\x65\x64\x52\x65\x61\x6C\x69\x74\x79\x2E\x4F\x70\x65\x6E\x58\x52\x2E\x49\x6E\x74\x65\x72\x6E\x61\x6C\x2E\x45\x64\x69\x74\x6F\x72"), NULL); } { CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF * tmp = (CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF *)cache->attributes[1]; CompilationRelaxationsAttribute__ctor_mAC3079EBC4EEAB474EED8208EF95DB39C922333B(tmp, 8LL, NULL); } { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[2]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } { DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B * tmp = (DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B *)cache->attributes[3]; DebuggableAttribute__ctor_m7FF445C8435494A4847123A668D889E692E55550(tmp, 2LL, NULL); } { RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * tmp = (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 *)cache->attributes[4]; RuntimeCompatibilityAttribute__ctor_m551DDF1438CE97A984571949723F30F44CF7317C(tmp, NULL); RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline(tmp, true, NULL); } { InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C * tmp = (InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C *)cache->attributes[5]; InternalsVisibleToAttribute__ctor_m420071A75DCEEC72356490C64B4B0B9270DA32B9(tmp, il2cpp_codegen_string_new_wrapper("\x4D\x69\x63\x72\x6F\x73\x6F\x66\x74\x2E\x4D\x69\x78\x65\x64\x52\x65\x61\x6C\x69\x74\x79\x2E\x4F\x70\x65\x6E\x58\x52\x2E\x49\x6E\x74\x65\x72\x6E\x61\x6C"), NULL); } { InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C * tmp = (InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C *)cache->attributes[6]; InternalsVisibleToAttribute__ctor_m420071A75DCEEC72356490C64B4B0B9270DA32B9(tmp, il2cpp_codegen_string_new_wrapper("\x4D\x69\x63\x72\x6F\x73\x6F\x66\x74\x2E\x4D\x69\x78\x65\x64\x52\x65\x61\x6C\x69\x74\x79\x2E\x4F\x70\x65\x6E\x58\x52\x2E\x45\x64\x69\x74\x6F\x72"), NULL); } } static void ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_U3CLeftU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_U3CRightU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_ControllerModel_get_Left_m1FB3666828A227C030BB6A287F49683B4699760A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_ControllerModel_get_Right_mAC84CF05866E20E95A66F526DF1E822984158DFB(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CU3Ec__DisplayClass13_0_t764C1CDC7007BE5D3C7CCDF91E4237DEE79BC906_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void GestureSettings_tA2E40AF567F0C444054F990A2C78E43A36CEDC3D_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 * tmp = (FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 *)cache->attributes[0]; FlagsAttribute__ctor_mE8DCBA1BE0E6B0424FEF5E5F249733CF6A0E1229(tmp, NULL); } } static void HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_U3CLeftU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_U3CRightU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_HandMeshTracker_get_Left_m1EAE07CE764BC96D38A547E0F215CE1C7F40C015(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_HandMeshTracker_get_Right_mEACD31EF886EDC5FDC9A8E134FCC963FC98F615D(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_U3CLeftU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_U3CRightU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_HandTracker_get_Left_m0BEF53EC2DD03579CF44792F49031853BE7E2D68(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_HandTracker_get_Right_mCDA43BD30EE1255DD9C81BD0224E5267A9E34725(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { IsReadOnlyAttribute_tB6E31A0106212818B0AB6DC627AA320291BD7566 * tmp = (IsReadOnlyAttribute_tB6E31A0106212818B0AB6DC627AA320291BD7566 *)cache->attributes[0]; IsReadOnlyAttribute__ctor_m02F9F7CD56DE227F7ABDD1E2593D82E6FFA57E9A(tmp, NULL); } } static void HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_U3CPoseU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_U3CRadiusU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_HandJointLocation_get_Pose_m685441722D6208F7628AF1D8B5E4CD0BB2AE8FBF(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_HandJointLocation_get_Radius_mA439BA1600FC5427C421428E9E726F34FEFBC745(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void SpatialGraphNode_tB6E047DE426AF84739C0A1A6410A0BB3DACEBEAD_CustomAttributesCacheGenerator_U3CIdU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void SpatialGraphNode_tB6E047DE426AF84739C0A1A6410A0BB3DACEBEAD_CustomAttributesCacheGenerator_SpatialGraphNode_get_Id_m0384E353CD73097BFE1698D2FE1DCE575D0C0EDB(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void SpatialGraphNode_tB6E047DE426AF84739C0A1A6410A0BB3DACEBEAD_CustomAttributesCacheGenerator_SpatialGraphNode_set_Id_mB11309DED7B65F6D9533BF464CA31222313B1371(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void XRAnchorStore_tEE5D563E126480718CF7A57DB2A03482C2DF1158_CustomAttributesCacheGenerator_XRAnchorStore_LoadAsync_m2BFF91FCC6FE8F810EF91774A1487B1183F44577(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_0_0_0_var); s_Il2CppMethodInitialized = true; } { AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0]; AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_0_0_0_var), NULL); } } static void U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_CustomAttributesCacheGenerator_U3CLoadAsyncU3Ed__6_SetStateMachine_mA58BEAB6BF7249223D1DBBA329714BF93CDB3ADF(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void XRAnchorTransferBatch_t7CE88BCD328FDF2F2C4561E039D10CDC0F8A1084_CustomAttributesCacheGenerator_XRAnchorTransferBatch_ExportAsync_m981CE1F5036DC4A64FC182195B078AE03755EDCB(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_0_0_0_var); s_Il2CppMethodInitialized = true; } { AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0]; AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_0_0_0_var), NULL); } } static void XRAnchorTransferBatch_t7CE88BCD328FDF2F2C4561E039D10CDC0F8A1084_CustomAttributesCacheGenerator_XRAnchorTransferBatch_ImportAsync_m9DAF64AD14776A3C7ABF63B84B1F947BCB40CD97(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_0_0_0_var); s_Il2CppMethodInitialized = true; } { AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0]; AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_0_0_0_var), NULL); } } static void U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_CustomAttributesCacheGenerator_U3CExportAsyncU3Ed__10_SetStateMachine_m6B8D1028583B5FD839CAE8A694E62860FE624F38(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_CustomAttributesCacheGenerator_U3CImportAsyncU3Ed__11_SetStateMachine_m672AE566F25C50EFB2B7C5F567ED206986ABA659(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_commonUsages = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 2); (_tmp_commonUsages)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x4C\x65\x66\x74\x48\x61\x6E\x64")); (_tmp_commonUsages)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x52\x69\x67\x68\x74\x48\x61\x6E\x64")); InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * tmp = (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 *)cache->attributes[0]; InputControlLayoutAttribute__ctor_m2C35D9C0A7CDEB6A840A215F33FF0FA9DDFD80BF(tmp, NULL); InputControlLayoutAttribute_set_displayName_m51759C33760B60FB12DD2D2EDC8C431EA0FD1E20_inline(tmp, il2cpp_codegen_string_new_wrapper("\x48\x50\x20\x52\x65\x76\x65\x72\x62\x20\x47\x32\x20\x43\x6F\x6E\x74\x72\x6F\x6C\x6C\x65\x72\x20\x28\x4F\x70\x65\x6E\x58\x52\x29"), NULL); InputControlLayoutAttribute_set_commonUsages_mE744432198FBB37B38B16119433EB748EED7CCF3_inline(tmp, _tmp_commonUsages, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CthumbstickU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CgripU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CgripPressedU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CmenuU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CprimaryButtonU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CsecondaryButtonU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CtriggerU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CtriggerPressedU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CthumbstickClickedU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CdevicePoseU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CpointerU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CisTrackedU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CtrackingStateU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CdevicePositionU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CdeviceRotationU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CpointerPositionU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CpointerRotationU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_thumbstick_mF1F80F83754D054E1A61481DDA4F7AD4487B80A3(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_thumbstick_m2A61B6E99F36CE1FEF36A53886EF7CCEF0BC92D4(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_grip_m774D15FE7471094CF99CE64F30BAADE9C49BF491(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_grip_mA9CF4613DC64DB7C69917E95AFA7984D73D77BC9(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_gripPressed_mFB6C14E271B06980E2F5557E61860ECB2609A97C(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_gripPressed_m2EDB5A204008B34EEB33D3D9994B78E44A72BB9D(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_menu_m8F1A3A101567E60020200DB6ADB0559DA5640ADB(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_menu_m4CA5B35B7C44A0309FFB8A04C50A7B92AAFF3AB2(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_primaryButton_m601E87B369B5F7D6E7C967A7B3DCD1DDB5014DA1(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_primaryButton_m18514B5ED6370CBA09554D9F0BF2E0C65D7A2813(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_secondaryButton_mD8EA3A151D83A49C2ED8AC31A3806E23EA02FCC9(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_secondaryButton_m829E3B763A1B7A62D2C0DE0F0F741B4FBA42D598(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_trigger_m4022967A651E51E93B17BE69514D34550938AB60(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_trigger_mDA2B294FCAFEEC9FDE5623D91AD4D817AAB2906A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_triggerPressed_mFF7961E88DE1EBB1A0D49DA5D9CDD38BE2DBE7CD(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_triggerPressed_mE6BA02C937BA01FDD3AC7F588C0D593795A4A1D3(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_thumbstickClicked_m379767F42B74AD8C0B15A806280E94B46B9D4BF6(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_thumbstickClicked_mC548083E740FC1B1FEDA7D8CDA52C25C3D05C3CA(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_devicePose_m705800BA6A7CFB5E1D19CC0529CC396557FBD80B(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_devicePose_m65620240064EEC8339888259A7CE05E105B18242(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_pointer_m86BAB94BBBE39A1C05AF0E362A850DC0DA765E78(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_pointer_mFE354A4FC6318457FDF89B0F49E86AD64B8CFA65(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_isTracked_m8B1594F9B2E418BB03E07A2CAE45F3C3F4D5F91A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_isTracked_m7DF699C2B94AF753610BF0A4D74E1F4F71D68B28(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_trackingState_m01C9864829A51F9B4B23BA14AAF9AEA768B9F8EC(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_trackingState_mCA7884F27836D9B2A6C98C452D74B7C07C1EF142(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_devicePosition_mC561964387CBA38CA3F19FDA2E5827F8020669EF(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_devicePosition_m55183A35411D152CDA83240DAE6C59E64D2FC74A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_deviceRotation_m7D2023CC3FFA04CE7CF39C8931A7355F7F94914E(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_deviceRotation_mE42529C48B3E7F80C7F0626284259BF96019DBEC(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_pointerPosition_m9741034F190CC314AC5DC2955035F9DCD4CB151E(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_pointerPosition_mD115A147A937DAD858BFEA8517FD5D24DD4CFD94(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_pointerRotation_mBA200BC275EE7A50C400924F5DA8C70F650FD569(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_pointerRotation_mAC28DEABE1570AAE9B7FEAF150677D70E6B95426(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____thumbstick_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 2); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x50\x72\x69\x6D\x61\x72\x79\x32\x44\x41\x78\x69\x73")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x4A\x6F\x79\x73\x74\x69\x63\x6B")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____grip_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 2); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x47\x72\x69\x70\x41\x78\x69\x73")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x73\x71\x75\x65\x65\x7A\x65")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____gripPressed_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 2); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x47\x72\x69\x70\x42\x75\x74\x74\x6F\x6E")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x73\x71\x75\x65\x65\x7A\x65\x43\x6C\x69\x63\x6B\x65\x64")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____menu_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 1); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x6D\x65\x6E\x75\x42\x75\x74\x74\x6F\x6E")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____primaryButton_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 4); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x41")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x58")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(2), il2cpp_codegen_string_new_wrapper("\x62\x75\x74\x74\x6F\x6E\x41")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(3), il2cpp_codegen_string_new_wrapper("\x62\x75\x74\x74\x6F\x6E\x58")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____secondaryButton_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 4); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x42")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x59")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(2), il2cpp_codegen_string_new_wrapper("\x62\x75\x74\x74\x6F\x6E\x42")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(3), il2cpp_codegen_string_new_wrapper("\x62\x75\x74\x74\x6F\x6E\x59")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____trigger_PropertyInfo(CustomAttributesCache* cache) { { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____triggerPressed_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 3); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x69\x6E\x64\x65\x78\x42\x75\x74\x74\x6F\x6E")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x69\x6E\x64\x65\x78\x54\x6F\x75\x63\x68\x65\x64")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(2), il2cpp_codegen_string_new_wrapper("\x74\x72\x69\x67\x67\x65\x72\x62\x75\x74\x74\x6F\x6E")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____thumbstickClicked_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 1); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x6A\x6F\x79\x73\x74\x69\x63\x6B\x4F\x72\x50\x61\x64\x50\x72\x65\x73\x73\x65\x64")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____devicePose_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 2); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x64\x65\x76\x69\x63\x65")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x67\x72\x69\x70\x50\x6F\x73\x65")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 0LL, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____pointer_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 1); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x61\x69\x6D\x50\x6F\x73\x65")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 0LL, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____isTracked_PropertyInfo(CustomAttributesCache* cache) { { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 26LL, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____trackingState_PropertyInfo(CustomAttributesCache* cache) { { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 28LL, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____devicePosition_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 1); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x67\x72\x69\x70\x50\x6F\x73\x69\x74\x69\x6F\x6E")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[1]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 32LL, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____deviceRotation_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 3); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x64\x65\x76\x69\x63\x65\x4F\x72\x69\x65\x6E\x74\x61\x74\x69\x6F\x6E")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x67\x72\x69\x70\x52\x6F\x74\x61\x74\x69\x6F\x6E")); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(2), il2cpp_codegen_string_new_wrapper("\x67\x72\x69\x70\x4F\x72\x69\x65\x6E\x74\x61\x74\x69\x6F\x6E")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 44LL, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____pointerPosition_PropertyInfo(CustomAttributesCache* cache) { { InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 92LL, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____pointerRotation_PropertyInfo(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_aliases = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 1); (_tmp_aliases)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x70\x6F\x69\x6E\x74\x65\x72\x4F\x72\x69\x65\x6E\x74\x61\x74\x69\x6F\x6E")); InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * tmp = (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 *)cache->attributes[0]; InputControlAttribute__ctor_mD95991F783A7335D8C33A2F159B878F49310D4DD(tmp, NULL); InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline(tmp, 104LL, NULL); InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline(tmp, _tmp_aliases, NULL); } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[1]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void HandTrackingFeaturePlugin_t3197364EF372511514EA338492C72AA361241243_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * tmp = (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 *)cache->attributes[0]; NativeLibTokenAttribute__ctor_m37D11C77F5A2D0487E11CC54852EAA3A5726C989(tmp, NULL); NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline(tmp, 2LL, NULL); } } static void OpenXRHandTracking_t048FCE7DC773A7DAACB199AD11E67AE818FDC23F_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } { StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* _tmp_commonUsages = (StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A*)SZArrayNew(StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A_il2cpp_TypeInfo_var, 2); (_tmp_commonUsages)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(0), il2cpp_codegen_string_new_wrapper("\x4C\x65\x66\x74\x48\x61\x6E\x64")); (_tmp_commonUsages)->SetAtUnchecked(static_cast<il2cpp_array_size_t>(1), il2cpp_codegen_string_new_wrapper("\x52\x69\x67\x68\x74\x48\x61\x6E\x64")); InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * tmp = (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 *)cache->attributes[1]; InputControlLayoutAttribute__ctor_m2C35D9C0A7CDEB6A840A215F33FF0FA9DDFD80BF(tmp, NULL); InputControlLayoutAttribute_set_displayName_m51759C33760B60FB12DD2D2EDC8C431EA0FD1E20_inline(tmp, il2cpp_codegen_string_new_wrapper("\x48\x61\x6E\x64\x20\x54\x72\x61\x63\x6B\x69\x6E\x67\x20\x28\x4F\x70\x65\x6E\x58\x52\x29"), NULL); InputControlLayoutAttribute_set_commonUsages_mE744432198FBB37B38B16119433EB748EED7CCF3_inline(tmp, _tmp_commonUsages, NULL); } } static void MixedRealityFeaturePlugin_tD965F3DEAA4D5DB36BB773DD5C7BC4CD082B2230_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * tmp = (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 *)cache->attributes[0]; NativeLibTokenAttribute__ctor_m37D11C77F5A2D0487E11CC54852EAA3A5726C989(tmp, NULL); NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline(tmp, 1LL, NULL); } } static void MotionControllerFeaturePlugin_tF8557DD9CE6F9251DF6371F3E82240C543116365_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * tmp = (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 *)cache->attributes[0]; NativeLibTokenAttribute__ctor_m37D11C77F5A2D0487E11CC54852EAA3A5726C989(tmp, NULL); NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline(tmp, 4LL, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CInstanceU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSystemIdU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSessionU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CIsSessionRunningU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSessionStateU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSceneOriginSpaceU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_InstanceCreated(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_InstanceDestroying(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionCreated(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionDestroying(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionBegun(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionEnding(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CIsAnchorExtensionSupportedU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_Instance_m478F662248FA2640B8B019281E1947AA49E028AA(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_Instance_m1A8A7D067D4D887F63B1954FA38A9C13CA3B1D39(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_SystemId_m8978EF8CF100778E018310C369BA458719CFFFB0(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_SystemId_mA1403EFC64E2F3B3628AC17F6E3CF92DA702B40A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_Session_m7B00AAE1745FD68A98D2C412930ADB79B4117A51(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_Session_mBE0367000ACA1A2B645C0F16F6AA46CAA6AFE018(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_IsSessionRunning_mF13018834DEDFB20BE07F4906AB918B9EBC0853F(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_IsSessionRunning_mC8A4E8C236E467426E95EEA1E76BB11CD109B5DF(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_SessionState_mFA99BBBBECA8E5005840FC58EAAD3ADEEDB56850(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_SessionState_m999248A365D17DD15937F8D596551B26173A1558(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_SceneOriginSpace_mAF3E111243FF25ED01FD16CAD629D5B1A7E155B9(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_SceneOriginSpace_m846468502F2EC1E402B34B2EBB7FB380F8ED35F4(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_InstanceCreated_m39FF573AF3380E87E2BFB08D51B038F045DE2CAA(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_InstanceCreated_mDEF28D8CA212D31ADCDC5FFD745B9A77DFE034A0(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_InstanceDestroying_m634DA3CAC64794817A38320C9FA09F5B557C2A71(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_InstanceDestroying_m6B7ECBB1B70D72A3FE82D64BBA3CFF81D34697F4(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionCreated_m1DFBDF0AEBCEC2070C75CB91D70B1AD64A96E321(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionCreated_mBA5DBF0A9907042CA57C7B6A6A297702E9DF8D66(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionDestroying_mAF460F6394B3892B3061D897CD5D09ADA7612F55(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionDestroying_m8E3EBFE093A7823E930BBB75E485BB5ABD2515C3(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionBegun_mB7CFC08009F82027CA71A36902B8E5D9C0BF6560(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionBegun_m612609030A04D44CE19BFE2263434260A56D09A2(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionEnding_m6B0FA0B326B91C3CB05BEEBF8A16C9692FF8FA33(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionEnding_m6146FE65744521D62C9F846740931C241106DCD6(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_IsAnchorExtensionSupported_m3BF05CC9CB155E70AFAEE5399EA57B9ADB8AFF8E(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_IsAnchorExtensionSupported_m56EB03D88B8809C7259DFF151D9BF1F4A279402A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemCreateU3Eb__54_0_m17964E04C6C6F38D64199EBBBC915F14D4DAE552(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemStartU3Eb__55_0_mD0B98D2FBD785222A202D7889B6188F25B289F95(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemStopU3Eb__56_0_m044341DC4B56D0211F8E6D7CBCFD6FFA438D989D(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemDestroyU3Eb__57_0_m5980F002A617E4A5908E2D3079CB15F4348F9AD6(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C * tmp = (AttributeUsageAttribute_tBB0BAAA82036E6FCDD80A688BBD039F6FFD8EA1C *)cache->attributes[0]; AttributeUsageAttribute__ctor_m5114E18826A49A025D48DC71904C430BD590656D(tmp, 4LL, NULL); } } static void NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator_U3CNativeLibTokenU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator_NativeLibTokenAttribute_get_NativeLibToken_mB51737DB1A16C9774DF12E4B276AD1ED9F2745E2(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator_NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void NativeSpaceLocationFlags_t1A07D31C5ABBDB8B9FBCF7605ED74474B80E7FEB_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 * tmp = (FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 *)cache->attributes[0]; FlagsAttribute__ctor_mE8DCBA1BE0E6B0424FEF5E5F249733CF6A0E1229(tmp, NULL); } } static void U3CU3Ec_t6A39FA001C51B2F50C678BDD58FD2BE7EA4E6D68_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void AnchorSubsystem_t6474543FC60DE8D8EF18ADF6B32AD11D4C1DF97D_CustomAttributesCacheGenerator_AnchorSubsystem_RegisterDescriptor_m8D4E902CF6B6E4BB0116C54C537F00843F74CFB8(CustomAttributesCache* cache) { { RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D * tmp = (RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D *)cache->attributes[0]; RuntimeInitializeOnLoadMethodAttribute__ctor_mE79C8FD7B18EC53391334A6E6A66CAF09CDA8516(tmp, 4LL, NULL); } } static void AnchorTransferBatch_tFB3416835CDE65C17E60391B3B8E73C9E46D418F_CustomAttributesCacheGenerator_AnchorTransferBatch_ExportAsync_mA030B6D7B1309E5E417CBB4BAB70BEA6B54B9E6B(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_0_0_0_var); s_Il2CppMethodInitialized = true; } { AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0]; AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_0_0_0_var), NULL); } } static void AnchorTransferBatch_tFB3416835CDE65C17E60391B3B8E73C9E46D418F_CustomAttributesCacheGenerator_AnchorTransferBatch_ImportAsync_m5113F7902EFB9F3FD4A3B687E93BEE57A02FFBA2(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_0_0_0_var); s_Il2CppMethodInitialized = true; } { AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0]; AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_0_0_0_var), NULL); } } static void U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_CustomAttributesCacheGenerator_U3CExportAsyncU3Ed__9_SetStateMachine_m6B48893D02142F8106ACBF477E5601B9BB0CCEC9(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_CustomAttributesCacheGenerator_U3CImportAsyncU3Ed__10_SetStateMachine_mC062886B72D424548DB7F96719FD345EA81DD4D7(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void NativeDirectionFlags_tB5EC1520C6B7B7E0522FAC709D2C307490BD648B_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 * tmp = (FlagsAttribute_t511C558FACEF1CC64702A8FAB67CAF3CBA65DF36 *)cache->attributes[0]; FlagsAttribute__ctor_mE8DCBA1BE0E6B0424FEF5E5F249733CF6A0E1229(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsValid_m7EB30A0AC32E787B8D90D1EE32BF57735C501EB3(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsTracked_m4EA5E6BB9CF2092F506A60193D41F90107153F93(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsTappedEvent_m21E961DFA85F45CCC168AB8761B65CBBA9D6FD3E(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsManipulationEvent_m69DAFCEFC7BF929E7752883BAF761A76C9EC94C1(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsNavigationEvent_m392FAEF10316578BD93EFD86407A2E0F217FCE53(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_Get_mD876387E34E0099740CC35BA2F7BCA8D307C081D(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void OpenXRSceneUnderstandingObserver_tB06F00BDCD4CF90133D1D88AB8FDDD6BB1EE7FE7_CustomAttributesCacheGenerator_OpenXRSceneUnderstandingObserver_StartDeserializingSceneFromStreamingAsset_mD05B81B40D454E662CFF5053CF3084CF57AD2080(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_0_0_0_var); s_Il2CppMethodInitialized = true; } { IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * tmp = (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 *)cache->attributes[0]; IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481(tmp, il2cpp_codegen_type_get_object(U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_0_0_0_var), NULL); } } static void U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7__ctor_mA619BF85BE952DB76CCD20585B5146BC7862C480(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_IDisposable_Dispose_m584732B6253E6A842F128B811F47FEA73D443B02(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m74CA9972B2F7E27F4A5A5C9E5D16045DB7AA422C(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_Collections_IEnumerator_Reset_m09FC79B19DC496C5F430CCDE11AF66587BC58EC2(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_Collections_IEnumerator_get_Current_mB5FC0CD369F6CB56E2839942AACA07DBF26C8E6F(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void PlaneSubsystem_t710F028EAB13682525886E666039FEA56059D388_CustomAttributesCacheGenerator_PlaneSubsystem_RegisterDescriptor_m51BA88B6AC36954A9128D083DDEA9D170A95DE8B(CustomAttributesCache* cache) { { RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D * tmp = (RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D *)cache->attributes[0]; RuntimeInitializeOnLoadMethodAttribute__ctor_mE79C8FD7B18EC53391334A6E6A66CAF09CDA8516(tmp, 4LL, NULL); } } static void RaycastSubsystem_t7BB1C6F9AD88936A76CEC05B01BCA9A0187A4BFA_CustomAttributesCacheGenerator_RaycastSubsystem_RegisterDescriptor_mBDEDD1FC03C4C610FAFF7218A1D8089A47F9C851(CustomAttributesCache* cache) { { RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D * tmp = (RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D *)cache->attributes[0]; RuntimeInitializeOnLoadMethodAttribute__ctor_mE79C8FD7B18EC53391334A6E6A66CAF09CDA8516(tmp, 4LL, NULL); } } static void SessionSubsystem_t0E2BDBAA19F6C316B072D8B1C1F30A0494B8CBA4_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 * tmp = (PreserveAttribute_tD3CDF1454F8E64CEF59CF7094B45BBACE2C69948 *)cache->attributes[0]; PreserveAttribute__ctor_mBD1EEF1095DBD581365C77729CF4ACB914859CD2(tmp, NULL); } } static void SessionSubsystem_t0E2BDBAA19F6C316B072D8B1C1F30A0494B8CBA4_CustomAttributesCacheGenerator_SessionSubsystem_RegisterDescriptor_m6AF63039F34CD8307B4DEEC9A6D1AF0FA8F615A6(CustomAttributesCache* cache) { { RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D * tmp = (RuntimeInitializeOnLoadMethodAttribute_tDE87D2AA72896514411AC9F8F48A4084536BDC2D *)cache->attributes[0]; RuntimeInitializeOnLoadMethodAttribute__ctor_mE79C8FD7B18EC53391334A6E6A66CAF09CDA8516(tmp, 4LL, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_InstanceCreated_mA6E44D474B83A96AEC1B8380C08FA3CAF25DD085(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_InstanceCreated_mA0C0CDAFC417D925395350DEA012CDBB2130661A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_InstanceDestroying_m2FD8BD5B36C45661EDF6C2519912D83A3896217E(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_InstanceDestroying_m6CD941B575DA748DC5E100C03E8D3A0C060BF19D(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionCreated_mE54BAA56D190850C39EFAA7D76B304051C0CCDAE(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionCreated_m786A59C33FA49E6CDB9906A8B85D7952F24304BE(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionDestroying_m002D16220B6F7AF5AAF850728FCCD9B37607CCE5(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionDestroying_m6DF5C40B5873FD4489698B4778F12997593FA1FB(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionBegun_m91093ED7712338B63834DD03508B71566C820C60(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionBegun_m2FDC29DD00FB5A75DAFE680D1564D78ACE25633E(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionEnding_mEEB13BF100379BD2C412B1DF482190D857C0B7C1(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionEnding_m8C1B783558B83D8D4887307453BA1D2E69A16CDE(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void Disposable_t243398450F985D7BCB211BCCCE2FB8C2FB5ED3A9_CustomAttributesCacheGenerator_U3CdisposedValueU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void Disposable_t243398450F985D7BCB211BCCCE2FB8C2FB5ED3A9_CustomAttributesCacheGenerator_Disposable_get_disposedValue_m72F0740380BC4CE33B321A4AB2F9139D18E02FC7(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void Disposable_t243398450F985D7BCB211BCCCE2FB8C2FB5ED3A9_CustomAttributesCacheGenerator_Disposable_set_disposedValue_m28A58FE88321CE69D15E42688BF650B323130022(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void AppRemotingPlugin_t74447E3077FEC2BB9DED16BCEF4D8D34BC2A2392_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * tmp = (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 *)cache->attributes[0]; NativeLibTokenAttribute__ctor_m37D11C77F5A2D0487E11CC54852EAA3A5726C989(tmp, NULL); NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline(tmp, 3LL, NULL); } } static void AppRemotingPlugin_t74447E3077FEC2BB9DED16BCEF4D8D34BC2A2392_CustomAttributesCacheGenerator_AppRemotingPlugin_Connect_m9CCE710F3E146BA711EEFB856E5DFE0C3BC65267(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_0_0_0_var); s_Il2CppMethodInitialized = true; } { IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * tmp = (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 *)cache->attributes[0]; IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481(tmp, il2cpp_codegen_type_get_object(U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_0_0_0_var), NULL); } } static void AppRemotingPlugin_t74447E3077FEC2BB9DED16BCEF4D8D34BC2A2392_CustomAttributesCacheGenerator_AppRemotingPlugin_Listen_m0A7815FE9DD9B3D20D529F18F67782401F0C5AB2(CustomAttributesCache* cache) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_0_0_0_var); s_Il2CppMethodInitialized = true; } { IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * tmp = (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 *)cache->attributes[0]; IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481(tmp, il2cpp_codegen_type_get_object(U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_0_0_0_var), NULL); } } static void U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15__ctor_m830FE491017257F8F41E8B09DB4398B736F616FE(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_IDisposable_Dispose_mFABCF3188965F688B71E1BC0182903BB215358D8(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m6B036DD7827A38F5503881A444A22A3AB20179E1(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_Collections_IEnumerator_Reset_m778F479BFBD4C9F8926C10F4FA560FCFAB38640F(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_Collections_IEnumerator_get_Current_m049D132C16DF931B2A4807616E5B7FA20B8C4628(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16__ctor_m3E19CC87C5261A566AFCAF02EC5A76DE3F5BE86C(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_IDisposable_Dispose_mA92B28943674D0063779E43AE02C719730BFDB02(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m3A86D78EF14077C3906F102E1E2AAA14D08B052B(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_Collections_IEnumerator_Reset_mC867807CE4311F92B2E91D8A695C62784EAD3722(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_Collections_IEnumerator_get_Current_mBDC14C5B54FCBEA3A79911B191A5F732503913F5(CustomAttributesCache* cache) { { DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0]; DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * tmp = (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 *)cache->attributes[0]; NativeLibTokenAttribute__ctor_m37D11C77F5A2D0487E11CC54852EAA3A5726C989(tmp, NULL); NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline(tmp, 3LL, NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_remoteHostName(CustomAttributesCache* cache) { { ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 * tmp = (ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 *)cache->attributes[0]; ObsoleteAttribute__ctor_mAC32A5CCD287DA84CDA9F08282C1C8B0DB7B9868(tmp, il2cpp_codegen_string_new_wrapper("\x55\x73\x65\x20\x74\x68\x65\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x53\x65\x74\x74\x69\x6E\x67\x73\x20\x76\x61\x6C\x75\x65\x73\x20\x69\x6E\x73\x74\x65\x61\x64"), NULL); } { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[1]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x68\x6F\x73\x74\x20\x6E\x61\x6D\x65\x20\x6F\x72\x20\x49\x50\x20\x61\x64\x64\x72\x65\x73\x73\x20\x6F\x66\x20\x74\x68\x65\x20\x70\x6C\x61\x79\x65\x72\x20\x72\x75\x6E\x6E\x69\x6E\x67\x20\x69\x6E\x20\x6E\x65\x74\x77\x6F\x72\x6B\x20\x73\x65\x72\x76\x65\x72\x20\x6D\x6F\x64\x65\x20\x74\x6F\x20\x63\x6F\x6E\x6E\x65\x63\x74\x20\x74\x6F\x2E"), NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[2]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_remoteHostPort(CustomAttributesCache* cache) { { ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 * tmp = (ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 *)cache->attributes[0]; ObsoleteAttribute__ctor_mAC32A5CCD287DA84CDA9F08282C1C8B0DB7B9868(tmp, il2cpp_codegen_string_new_wrapper("\x55\x73\x65\x20\x74\x68\x65\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x53\x65\x74\x74\x69\x6E\x67\x73\x20\x76\x61\x6C\x75\x65\x73\x20\x69\x6E\x73\x74\x65\x61\x64"), NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[1]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[2]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x70\x6F\x72\x74\x20\x6E\x75\x6D\x62\x65\x72\x20\x6F\x66\x20\x74\x68\x65\x20\x73\x65\x72\x76\x65\x72\x27\x73\x20\x68\x61\x6E\x64\x73\x68\x61\x6B\x65\x20\x70\x6F\x72\x74\x2E"), NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_maxBitrate(CustomAttributesCache* cache) { { ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 * tmp = (ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 *)cache->attributes[0]; ObsoleteAttribute__ctor_mAC32A5CCD287DA84CDA9F08282C1C8B0DB7B9868(tmp, il2cpp_codegen_string_new_wrapper("\x55\x73\x65\x20\x74\x68\x65\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x53\x65\x74\x74\x69\x6E\x67\x73\x20\x76\x61\x6C\x75\x65\x73\x20\x69\x6E\x73\x74\x65\x61\x64"), NULL); } { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[1]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x6D\x61\x78\x20\x62\x69\x74\x72\x61\x74\x65\x20\x69\x6E\x20\x4B\x62\x70\x73\x20\x74\x6F\x20\x75\x73\x65\x20\x66\x6F\x72\x20\x74\x68\x65\x20\x63\x6F\x6E\x6E\x65\x63\x74\x69\x6F\x6E\x2E"), NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[2]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_videoCodec(CustomAttributesCache* cache) { { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[0]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } { ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 * tmp = (ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 *)cache->attributes[1]; ObsoleteAttribute__ctor_mAC32A5CCD287DA84CDA9F08282C1C8B0DB7B9868(tmp, il2cpp_codegen_string_new_wrapper("\x55\x73\x65\x20\x74\x68\x65\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x53\x65\x74\x74\x69\x6E\x67\x73\x20\x76\x61\x6C\x75\x65\x73\x20\x69\x6E\x73\x74\x65\x61\x64"), NULL); } { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[2]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x76\x69\x64\x65\x6F\x20\x63\x6F\x64\x65\x63\x20\x74\x6F\x20\x75\x73\x65\x20\x66\x6F\x72\x20\x74\x68\x65\x20\x63\x6F\x6E\x6E\x65\x63\x74\x69\x6F\x6E\x2E"), NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_enableAudio(CustomAttributesCache* cache) { { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[0]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x45\x6E\x61\x62\x6C\x65\x2F\x64\x69\x73\x61\x62\x6C\x65\x20\x61\x75\x64\x69\x6F\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x2E"), NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[1]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } { ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 * tmp = (ObsoleteAttribute_t14BAC1669C0409EB9F28D72D664FFA6764ACD671 *)cache->attributes[2]; ObsoleteAttribute__ctor_mAC32A5CCD287DA84CDA9F08282C1C8B0DB7B9868(tmp, il2cpp_codegen_string_new_wrapper("\x55\x73\x65\x20\x74\x68\x65\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x53\x65\x74\x74\x69\x6E\x67\x73\x20\x76\x61\x6C\x75\x65\x73\x20\x69\x6E\x73\x74\x65\x61\x64"), NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_U3CRemotingSettingsU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_PlayModeRemotingPlugin_get_RemotingSettings_m7B06519240B8FA486580FFEDC44CC42B8CE608D6(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_PlayModeRemotingPlugin_set_RemotingSettings_m6893272120900DCE807BAB18AEFC36D7FBCF681B(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CRemoteHostNameU3Ek__BackingField(CustomAttributesCache* cache) { { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[0]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[1]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[2]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x68\x6F\x73\x74\x20\x6E\x61\x6D\x65\x20\x6F\x72\x20\x49\x50\x20\x61\x64\x64\x72\x65\x73\x73\x20\x6F\x66\x20\x74\x68\x65\x20\x70\x6C\x61\x79\x65\x72\x20\x72\x75\x6E\x6E\x69\x6E\x67\x20\x69\x6E\x20\x6E\x65\x74\x77\x6F\x72\x6B\x20\x73\x65\x72\x76\x65\x72\x20\x6D\x6F\x64\x65\x20\x74\x6F\x20\x63\x6F\x6E\x6E\x65\x63\x74\x20\x74\x6F\x2E"), NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CRemoteHostPortU3Ek__BackingField(CustomAttributesCache* cache) { { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[0]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x70\x6F\x72\x74\x20\x6E\x75\x6D\x62\x65\x72\x20\x6F\x66\x20\x74\x68\x65\x20\x73\x65\x72\x76\x65\x72\x27\x73\x20\x68\x61\x6E\x64\x73\x68\x61\x6B\x65\x20\x70\x6F\x72\x74\x2E"), NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[1]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[2]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CMaxBitrateU3Ek__BackingField(CustomAttributesCache* cache) { { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[0]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x6D\x61\x78\x20\x62\x69\x74\x72\x61\x74\x65\x20\x69\x6E\x20\x4B\x62\x70\x73\x20\x74\x6F\x20\x75\x73\x65\x20\x66\x6F\x72\x20\x74\x68\x65\x20\x63\x6F\x6E\x6E\x65\x63\x74\x69\x6F\x6E\x2E"), NULL); } { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[1]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[2]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CVideoCodecU3Ek__BackingField(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[1]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[2]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x54\x68\x65\x20\x76\x69\x64\x65\x6F\x20\x63\x6F\x64\x65\x63\x20\x74\x6F\x20\x75\x73\x65\x20\x66\x6F\x72\x20\x74\x68\x65\x20\x63\x6F\x6E\x6E\x65\x63\x74\x69\x6F\x6E\x2E"), NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CEnableAudioU3Ek__BackingField(CustomAttributesCache* cache) { { TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B * tmp = (TooltipAttribute_t503A1598A4E68E91673758F50447D0EDFB95149B *)cache->attributes[0]; TooltipAttribute__ctor_m1839ACEC1560968A6D0EA55D7EB4535546588042(tmp, il2cpp_codegen_string_new_wrapper("\x45\x6E\x61\x62\x6C\x65\x2F\x64\x69\x73\x61\x62\x6C\x65\x20\x61\x75\x64\x69\x6F\x20\x72\x65\x6D\x6F\x74\x69\x6E\x67\x2E"), NULL); } { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[1]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } { SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[2]; SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_RemoteHostName_mF7E2F022E7B3817D9579929EBAC65AA1BD722090(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_RemoteHostName_mD0817358EE624945DDDD440A951C8B5F7B189CC1(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_RemoteHostPort_m18FEDFAAAAD0D68853D7BCFD82CD6172D18E30FD(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_RemoteHostPort_m69145DC1D9C7DFB8837691A14482B696A933D24B(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_MaxBitrate_m23848E1F57157ADF0AB2F3B0D55462FAACFAA1B7(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_MaxBitrate_mD87B2F77955A0EE09F7313F0483D94C5D65C389F(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_VideoCodec_m7DCFF126E5EF3AF295CD04C2EDD9B8222A9B162A(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_VideoCodec_m7F9D59A946FECDFD66A75864E2244312F13D1184(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_EnableAudio_m233ED19A72BF0D3435DA130103087E88D2AD530D(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_EnableAudio_mA6B52F05FFF4229074859A62AE63FF213CDFBDD7(CustomAttributesCache* cache) { { CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0]; CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL); } } static void ARAnchorExtensions_t8792B73E0A6E37EEA746928608327B699AF36FD9_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void ARAnchorExtensions_t8792B73E0A6E37EEA746928608327B699AF36FD9_CustomAttributesCacheGenerator_ARAnchorExtensions_GetOpenXRHandle_m5F6791F083FC0EC8693082EF83B4EA62772A87B9(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void AnchorManagerExtensions_t54C6EAE326354508E091AD4C54BBEA676C195347_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void AnchorManagerExtensions_t54C6EAE326354508E091AD4C54BBEA676C195347_CustomAttributesCacheGenerator_AnchorManagerExtensions_LoadAnchorStoreAsync_mA79EEA73F39EBC8C34BFE59AA68E3E848AC3774C(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void XRAnchorExtensions_t5A745CCCA3EF008EAC116C285C4C143AA111DECE_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void XRAnchorExtensions_t5A745CCCA3EF008EAC116C285C4C143AA111DECE_CustomAttributesCacheGenerator_XRAnchorExtensions_GetOpenXRHandle_m1FDA9CFAC3FD2E506AEB822251E8DA0E759A525F(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void MeshSubsystemExtensions_t2E73175E6D66D07952D99AC289AF20DEE269F5A3_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void MeshSubsystemExtensions_t2E73175E6D66D07952D99AC289AF20DEE269F5A3_CustomAttributesCacheGenerator_MeshSubsystemExtensions_TrySetMeshComputeSettings_mBD9D788AB70A6EA3E5476FB36BACF54E5762164E(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void AnchorSubsystemExtensions_t597F2D3456B86E02D74E4B28C4BAC90851A9B076_CustomAttributesCacheGenerator(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } static void AnchorSubsystemExtensions_t597F2D3456B86E02D74E4B28C4BAC90851A9B076_CustomAttributesCacheGenerator_AnchorSubsystemExtensions_LoadAnchorStoreAsync_m6421EE79C71C759B05640A228ADA8A67BAF19915(CustomAttributesCache* cache) { { ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0]; ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL); } } IL2CPP_EXTERN_C const CustomAttributesCacheGenerator g_Microsoft_MixedReality_OpenXR_AttributeGenerators[]; const CustomAttributesCacheGenerator g_Microsoft_MixedReality_OpenXR_AttributeGenerators[244] = { U3CU3Ec__DisplayClass13_0_t764C1CDC7007BE5D3C7CCDF91E4237DEE79BC906_CustomAttributesCacheGenerator, GestureSettings_tA2E40AF567F0C444054F990A2C78E43A36CEDC3D_CustomAttributesCacheGenerator, HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator, U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_CustomAttributesCacheGenerator, U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_CustomAttributesCacheGenerator, U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_CustomAttributesCacheGenerator, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator, HandTrackingFeaturePlugin_t3197364EF372511514EA338492C72AA361241243_CustomAttributesCacheGenerator, OpenXRHandTracking_t048FCE7DC773A7DAACB199AD11E67AE818FDC23F_CustomAttributesCacheGenerator, MixedRealityFeaturePlugin_tD965F3DEAA4D5DB36BB773DD5C7BC4CD082B2230_CustomAttributesCacheGenerator, MotionControllerFeaturePlugin_tF8557DD9CE6F9251DF6371F3E82240C543116365_CustomAttributesCacheGenerator, NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator, NativeSpaceLocationFlags_t1A07D31C5ABBDB8B9FBCF7605ED74474B80E7FEB_CustomAttributesCacheGenerator, U3CU3Ec_t6A39FA001C51B2F50C678BDD58FD2BE7EA4E6D68_CustomAttributesCacheGenerator, U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_CustomAttributesCacheGenerator, U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_CustomAttributesCacheGenerator, NativeDirectionFlags_tB5EC1520C6B7B7E0522FAC709D2C307490BD648B_CustomAttributesCacheGenerator, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator, U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator, SessionSubsystem_t0E2BDBAA19F6C316B072D8B1C1F30A0494B8CBA4_CustomAttributesCacheGenerator, AppRemotingPlugin_t74447E3077FEC2BB9DED16BCEF4D8D34BC2A2392_CustomAttributesCacheGenerator, U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator, U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator, ARAnchorExtensions_t8792B73E0A6E37EEA746928608327B699AF36FD9_CustomAttributesCacheGenerator, AnchorManagerExtensions_t54C6EAE326354508E091AD4C54BBEA676C195347_CustomAttributesCacheGenerator, XRAnchorExtensions_t5A745CCCA3EF008EAC116C285C4C143AA111DECE_CustomAttributesCacheGenerator, MeshSubsystemExtensions_t2E73175E6D66D07952D99AC289AF20DEE269F5A3_CustomAttributesCacheGenerator, AnchorSubsystemExtensions_t597F2D3456B86E02D74E4B28C4BAC90851A9B076_CustomAttributesCacheGenerator, ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_U3CLeftU3Ek__BackingField, ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_U3CRightU3Ek__BackingField, HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_U3CLeftU3Ek__BackingField, HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_U3CRightU3Ek__BackingField, HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_U3CLeftU3Ek__BackingField, HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_U3CRightU3Ek__BackingField, HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_U3CPoseU3Ek__BackingField, HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_U3CRadiusU3Ek__BackingField, SpatialGraphNode_tB6E047DE426AF84739C0A1A6410A0BB3DACEBEAD_CustomAttributesCacheGenerator_U3CIdU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CthumbstickU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CgripU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CgripPressedU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CmenuU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CprimaryButtonU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CsecondaryButtonU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CtriggerU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CtriggerPressedU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CthumbstickClickedU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CdevicePoseU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CpointerU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CisTrackedU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CtrackingStateU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CdevicePositionU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CdeviceRotationU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CpointerPositionU3Ek__BackingField, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_U3CpointerRotationU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CInstanceU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSystemIdU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSessionU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CIsSessionRunningU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSessionStateU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CSceneOriginSpaceU3Ek__BackingField, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_InstanceCreated, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_InstanceDestroying, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionCreated, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionDestroying, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionBegun, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_SessionEnding, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_U3CIsAnchorExtensionSupportedU3Ek__BackingField, NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator_U3CNativeLibTokenU3Ek__BackingField, Disposable_t243398450F985D7BCB211BCCCE2FB8C2FB5ED3A9_CustomAttributesCacheGenerator_U3CdisposedValueU3Ek__BackingField, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_remoteHostName, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_remoteHostPort, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_maxBitrate, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_videoCodec, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_m_enableAudio, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_U3CRemotingSettingsU3Ek__BackingField, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CRemoteHostNameU3Ek__BackingField, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CRemoteHostPortU3Ek__BackingField, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CMaxBitrateU3Ek__BackingField, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CVideoCodecU3Ek__BackingField, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_U3CEnableAudioU3Ek__BackingField, ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_ControllerModel_get_Left_m1FB3666828A227C030BB6A287F49683B4699760A, ControllerModel_t2CDD023B4956C4FE0F1EEC74ABF7A9956C3238D0_CustomAttributesCacheGenerator_ControllerModel_get_Right_mAC84CF05866E20E95A66F526DF1E822984158DFB, HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_HandMeshTracker_get_Left_m1EAE07CE764BC96D38A547E0F215CE1C7F40C015, HandMeshTracker_t3FBBD968607CC22AC755C702DE687EE48416C078_CustomAttributesCacheGenerator_HandMeshTracker_get_Right_mEACD31EF886EDC5FDC9A8E134FCC963FC98F615D, HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_HandTracker_get_Left_m0BEF53EC2DD03579CF44792F49031853BE7E2D68, HandTracker_t5FF0B49317862EA953B9F8A3E6A182926DCEDB2B_CustomAttributesCacheGenerator_HandTracker_get_Right_mCDA43BD30EE1255DD9C81BD0224E5267A9E34725, HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_HandJointLocation_get_Pose_m685441722D6208F7628AF1D8B5E4CD0BB2AE8FBF, HandJointLocation_t6E513795AC3CD452C7F52DD3BB9F644944D968D5_CustomAttributesCacheGenerator_HandJointLocation_get_Radius_mA439BA1600FC5427C421428E9E726F34FEFBC745, SpatialGraphNode_tB6E047DE426AF84739C0A1A6410A0BB3DACEBEAD_CustomAttributesCacheGenerator_SpatialGraphNode_get_Id_m0384E353CD73097BFE1698D2FE1DCE575D0C0EDB, SpatialGraphNode_tB6E047DE426AF84739C0A1A6410A0BB3DACEBEAD_CustomAttributesCacheGenerator_SpatialGraphNode_set_Id_mB11309DED7B65F6D9533BF464CA31222313B1371, XRAnchorStore_tEE5D563E126480718CF7A57DB2A03482C2DF1158_CustomAttributesCacheGenerator_XRAnchorStore_LoadAsync_m2BFF91FCC6FE8F810EF91774A1487B1183F44577, U3CLoadAsyncU3Ed__6_tC74F75174A3CD812F485CE0E2EA90F3B6B7CBA12_CustomAttributesCacheGenerator_U3CLoadAsyncU3Ed__6_SetStateMachine_mA58BEAB6BF7249223D1DBBA329714BF93CDB3ADF, XRAnchorTransferBatch_t7CE88BCD328FDF2F2C4561E039D10CDC0F8A1084_CustomAttributesCacheGenerator_XRAnchorTransferBatch_ExportAsync_m981CE1F5036DC4A64FC182195B078AE03755EDCB, XRAnchorTransferBatch_t7CE88BCD328FDF2F2C4561E039D10CDC0F8A1084_CustomAttributesCacheGenerator_XRAnchorTransferBatch_ImportAsync_m9DAF64AD14776A3C7ABF63B84B1F947BCB40CD97, U3CExportAsyncU3Ed__10_t3DEA700D88871DEC10E34F80E90E45AD0EEB2A03_CustomAttributesCacheGenerator_U3CExportAsyncU3Ed__10_SetStateMachine_m6B8D1028583B5FD839CAE8A694E62860FE624F38, U3CImportAsyncU3Ed__11_tC6561F4498926E48DEF55DD1D43944889FA94F91_CustomAttributesCacheGenerator_U3CImportAsyncU3Ed__11_SetStateMachine_m672AE566F25C50EFB2B7C5F567ED206986ABA659, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_thumbstick_mF1F80F83754D054E1A61481DDA4F7AD4487B80A3, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_thumbstick_m2A61B6E99F36CE1FEF36A53886EF7CCEF0BC92D4, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_grip_m774D15FE7471094CF99CE64F30BAADE9C49BF491, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_grip_mA9CF4613DC64DB7C69917E95AFA7984D73D77BC9, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_gripPressed_mFB6C14E271B06980E2F5557E61860ECB2609A97C, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_gripPressed_m2EDB5A204008B34EEB33D3D9994B78E44A72BB9D, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_menu_m8F1A3A101567E60020200DB6ADB0559DA5640ADB, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_menu_m4CA5B35B7C44A0309FFB8A04C50A7B92AAFF3AB2, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_primaryButton_m601E87B369B5F7D6E7C967A7B3DCD1DDB5014DA1, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_primaryButton_m18514B5ED6370CBA09554D9F0BF2E0C65D7A2813, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_secondaryButton_mD8EA3A151D83A49C2ED8AC31A3806E23EA02FCC9, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_secondaryButton_m829E3B763A1B7A62D2C0DE0F0F741B4FBA42D598, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_trigger_m4022967A651E51E93B17BE69514D34550938AB60, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_trigger_mDA2B294FCAFEEC9FDE5623D91AD4D817AAB2906A, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_triggerPressed_mFF7961E88DE1EBB1A0D49DA5D9CDD38BE2DBE7CD, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_triggerPressed_mE6BA02C937BA01FDD3AC7F588C0D593795A4A1D3, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_thumbstickClicked_m379767F42B74AD8C0B15A806280E94B46B9D4BF6, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_thumbstickClicked_mC548083E740FC1B1FEDA7D8CDA52C25C3D05C3CA, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_devicePose_m705800BA6A7CFB5E1D19CC0529CC396557FBD80B, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_devicePose_m65620240064EEC8339888259A7CE05E105B18242, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_pointer_m86BAB94BBBE39A1C05AF0E362A850DC0DA765E78, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_pointer_mFE354A4FC6318457FDF89B0F49E86AD64B8CFA65, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_isTracked_m8B1594F9B2E418BB03E07A2CAE45F3C3F4D5F91A, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_isTracked_m7DF699C2B94AF753610BF0A4D74E1F4F71D68B28, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_trackingState_m01C9864829A51F9B4B23BA14AAF9AEA768B9F8EC, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_trackingState_mCA7884F27836D9B2A6C98C452D74B7C07C1EF142, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_devicePosition_mC561964387CBA38CA3F19FDA2E5827F8020669EF, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_devicePosition_m55183A35411D152CDA83240DAE6C59E64D2FC74A, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_deviceRotation_m7D2023CC3FFA04CE7CF39C8931A7355F7F94914E, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_deviceRotation_mE42529C48B3E7F80C7F0626284259BF96019DBEC, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_pointerPosition_m9741034F190CC314AC5DC2955035F9DCD4CB151E, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_pointerPosition_mD115A147A937DAD858BFEA8517FD5D24DD4CFD94, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_get_pointerRotation_mBA200BC275EE7A50C400924F5DA8C70F650FD569, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_set_pointerRotation_mAC28DEABE1570AAE9B7FEAF150677D70E6B95426, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_Instance_m478F662248FA2640B8B019281E1947AA49E028AA, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_Instance_m1A8A7D067D4D887F63B1954FA38A9C13CA3B1D39, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_SystemId_m8978EF8CF100778E018310C369BA458719CFFFB0, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_SystemId_mA1403EFC64E2F3B3628AC17F6E3CF92DA702B40A, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_Session_m7B00AAE1745FD68A98D2C412930ADB79B4117A51, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_Session_mBE0367000ACA1A2B645C0F16F6AA46CAA6AFE018, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_IsSessionRunning_mF13018834DEDFB20BE07F4906AB918B9EBC0853F, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_IsSessionRunning_mC8A4E8C236E467426E95EEA1E76BB11CD109B5DF, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_SessionState_mFA99BBBBECA8E5005840FC58EAAD3ADEEDB56850, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_SessionState_m999248A365D17DD15937F8D596551B26173A1558, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_SceneOriginSpace_mAF3E111243FF25ED01FD16CAD629D5B1A7E155B9, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_SceneOriginSpace_m846468502F2EC1E402B34B2EBB7FB380F8ED35F4, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_InstanceCreated_m39FF573AF3380E87E2BFB08D51B038F045DE2CAA, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_InstanceCreated_mDEF28D8CA212D31ADCDC5FFD745B9A77DFE034A0, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_InstanceDestroying_m634DA3CAC64794817A38320C9FA09F5B557C2A71, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_InstanceDestroying_m6B7ECBB1B70D72A3FE82D64BBA3CFF81D34697F4, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionCreated_m1DFBDF0AEBCEC2070C75CB91D70B1AD64A96E321, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionCreated_mBA5DBF0A9907042CA57C7B6A6A297702E9DF8D66, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionDestroying_mAF460F6394B3892B3061D897CD5D09ADA7612F55, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionDestroying_m8E3EBFE093A7823E930BBB75E485BB5ABD2515C3, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionBegun_mB7CFC08009F82027CA71A36902B8E5D9C0BF6560, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionBegun_m612609030A04D44CE19BFE2263434260A56D09A2, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_add_SessionEnding_m6B0FA0B326B91C3CB05BEEBF8A16C9692FF8FA33, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_remove_SessionEnding_m6146FE65744521D62C9F846740931C241106DCD6, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_get_IsAnchorExtensionSupported_m3BF05CC9CB155E70AFAEE5399EA57B9ADB8AFF8E, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_set_IsAnchorExtensionSupported_m56EB03D88B8809C7259DFF151D9BF1F4A279402A, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemCreateU3Eb__54_0_m17964E04C6C6F38D64199EBBBC915F14D4DAE552, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemStartU3Eb__55_0_mD0B98D2FBD785222A202D7889B6188F25B289F95, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemStopU3Eb__56_0_m044341DC4B56D0211F8E6D7CBCFD6FFA438D989D, OpenXRFeaturePlugin_1_tFB78AC62BFCFFEB44462810D79EB479D4B4CE12C_CustomAttributesCacheGenerator_OpenXRFeaturePlugin_1_U3COnSubsystemDestroyU3Eb__57_0_m5980F002A617E4A5908E2D3079CB15F4348F9AD6, NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator_NativeLibTokenAttribute_get_NativeLibToken_mB51737DB1A16C9774DF12E4B276AD1ED9F2745E2, NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008_CustomAttributesCacheGenerator_NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45, AnchorSubsystem_t6474543FC60DE8D8EF18ADF6B32AD11D4C1DF97D_CustomAttributesCacheGenerator_AnchorSubsystem_RegisterDescriptor_m8D4E902CF6B6E4BB0116C54C537F00843F74CFB8, AnchorTransferBatch_tFB3416835CDE65C17E60391B3B8E73C9E46D418F_CustomAttributesCacheGenerator_AnchorTransferBatch_ExportAsync_mA030B6D7B1309E5E417CBB4BAB70BEA6B54B9E6B, AnchorTransferBatch_tFB3416835CDE65C17E60391B3B8E73C9E46D418F_CustomAttributesCacheGenerator_AnchorTransferBatch_ImportAsync_m5113F7902EFB9F3FD4A3B687E93BEE57A02FFBA2, U3CExportAsyncU3Ed__9_t8EC884068A76850A80DF5BA0B72CB5D150EB3795_CustomAttributesCacheGenerator_U3CExportAsyncU3Ed__9_SetStateMachine_m6B48893D02142F8106ACBF477E5601B9BB0CCEC9, U3CImportAsyncU3Ed__10_tD21B1D5A13F170FAD8202D7E0B0D967D2EED99D6_CustomAttributesCacheGenerator_U3CImportAsyncU3Ed__10_SetStateMachine_mC062886B72D424548DB7F96719FD345EA81DD4D7, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsValid_m7EB30A0AC32E787B8D90D1EE32BF57735C501EB3, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsTracked_m4EA5E6BB9CF2092F506A60193D41F90107153F93, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsTappedEvent_m21E961DFA85F45CCC168AB8761B65CBBA9D6FD3E, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsManipulationEvent_m69DAFCEFC7BF929E7752883BAF761A76C9EC94C1, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_IsNavigationEvent_m392FAEF10316578BD93EFD86407A2E0F217FCE53, GestureSubsystemExtensions_t9088CF59A14C654749B7CBD44B647E79905CF6AC_CustomAttributesCacheGenerator_GestureSubsystemExtensions_Get_mD876387E34E0099740CC35BA2F7BCA8D307C081D, OpenXRSceneUnderstandingObserver_tB06F00BDCD4CF90133D1D88AB8FDDD6BB1EE7FE7_CustomAttributesCacheGenerator_OpenXRSceneUnderstandingObserver_StartDeserializingSceneFromStreamingAsset_mD05B81B40D454E662CFF5053CF3084CF57AD2080, U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7__ctor_mA619BF85BE952DB76CCD20585B5146BC7862C480, U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_IDisposable_Dispose_m584732B6253E6A842F128B811F47FEA73D443B02, U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m74CA9972B2F7E27F4A5A5C9E5D16045DB7AA422C, U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_Collections_IEnumerator_Reset_m09FC79B19DC496C5F430CCDE11AF66587BC58EC2, U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_t8A93A714AA28C609B5F89A2F9FE75FEEAD6BF1CA_CustomAttributesCacheGenerator_U3CStartDeserializingSceneFromStreamingAssetU3Ed__7_System_Collections_IEnumerator_get_Current_mB5FC0CD369F6CB56E2839942AACA07DBF26C8E6F, PlaneSubsystem_t710F028EAB13682525886E666039FEA56059D388_CustomAttributesCacheGenerator_PlaneSubsystem_RegisterDescriptor_m51BA88B6AC36954A9128D083DDEA9D170A95DE8B, RaycastSubsystem_t7BB1C6F9AD88936A76CEC05B01BCA9A0187A4BFA_CustomAttributesCacheGenerator_RaycastSubsystem_RegisterDescriptor_mBDEDD1FC03C4C610FAFF7218A1D8089A47F9C851, SessionSubsystem_t0E2BDBAA19F6C316B072D8B1C1F30A0494B8CBA4_CustomAttributesCacheGenerator_SessionSubsystem_RegisterDescriptor_m6AF63039F34CD8307B4DEEC9A6D1AF0FA8F615A6, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_InstanceCreated_mA6E44D474B83A96AEC1B8380C08FA3CAF25DD085, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_InstanceCreated_mA0C0CDAFC417D925395350DEA012CDBB2130661A, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_InstanceDestroying_m2FD8BD5B36C45661EDF6C2519912D83A3896217E, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_InstanceDestroying_m6CD941B575DA748DC5E100C03E8D3A0C060BF19D, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionCreated_mE54BAA56D190850C39EFAA7D76B304051C0CCDAE, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionCreated_m786A59C33FA49E6CDB9906A8B85D7952F24304BE, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionDestroying_m002D16220B6F7AF5AAF850728FCCD9B37607CCE5, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionDestroying_m6DF5C40B5873FD4489698B4778F12997593FA1FB, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionBegun_m91093ED7712338B63834DD03508B71566C820C60, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionBegun_m2FDC29DD00FB5A75DAFE680D1564D78ACE25633E, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_add_SessionEnding_mEEB13BF100379BD2C412B1DF482190D857C0B7C1, IOpenXRContext_t05229D735846297A83BCA68147489BA36505580B_CustomAttributesCacheGenerator_IOpenXRContext_remove_SessionEnding_m8C1B783558B83D8D4887307453BA1D2E69A16CDE, Disposable_t243398450F985D7BCB211BCCCE2FB8C2FB5ED3A9_CustomAttributesCacheGenerator_Disposable_get_disposedValue_m72F0740380BC4CE33B321A4AB2F9139D18E02FC7, Disposable_t243398450F985D7BCB211BCCCE2FB8C2FB5ED3A9_CustomAttributesCacheGenerator_Disposable_set_disposedValue_m28A58FE88321CE69D15E42688BF650B323130022, AppRemotingPlugin_t74447E3077FEC2BB9DED16BCEF4D8D34BC2A2392_CustomAttributesCacheGenerator_AppRemotingPlugin_Connect_m9CCE710F3E146BA711EEFB856E5DFE0C3BC65267, AppRemotingPlugin_t74447E3077FEC2BB9DED16BCEF4D8D34BC2A2392_CustomAttributesCacheGenerator_AppRemotingPlugin_Listen_m0A7815FE9DD9B3D20D529F18F67782401F0C5AB2, U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15__ctor_m830FE491017257F8F41E8B09DB4398B736F616FE, U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_IDisposable_Dispose_mFABCF3188965F688B71E1BC0182903BB215358D8, U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m6B036DD7827A38F5503881A444A22A3AB20179E1, U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_Collections_IEnumerator_Reset_m778F479BFBD4C9F8926C10F4FA560FCFAB38640F, U3CConnectU3Ed__15_tF38186C8D595CDCA5996F9F3706119D8F6C4B24E_CustomAttributesCacheGenerator_U3CConnectU3Ed__15_System_Collections_IEnumerator_get_Current_m049D132C16DF931B2A4807616E5B7FA20B8C4628, U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16__ctor_m3E19CC87C5261A566AFCAF02EC5A76DE3F5BE86C, U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_IDisposable_Dispose_mA92B28943674D0063779E43AE02C719730BFDB02, U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m3A86D78EF14077C3906F102E1E2AAA14D08B052B, U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_Collections_IEnumerator_Reset_mC867807CE4311F92B2E91D8A695C62784EAD3722, U3CListenU3Ed__16_tFFB763ABA458867F9D1B0ADC0AD6B24AB17F6207_CustomAttributesCacheGenerator_U3CListenU3Ed__16_System_Collections_IEnumerator_get_Current_mBDC14C5B54FCBEA3A79911B191A5F732503913F5, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_PlayModeRemotingPlugin_get_RemotingSettings_m7B06519240B8FA486580FFEDC44CC42B8CE608D6, PlayModeRemotingPlugin_tA189185C6B9994147DD4EECB20E544DAFECCC98E_CustomAttributesCacheGenerator_PlayModeRemotingPlugin_set_RemotingSettings_m6893272120900DCE807BAB18AEFC36D7FBCF681B, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_RemoteHostName_mF7E2F022E7B3817D9579929EBAC65AA1BD722090, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_RemoteHostName_mD0817358EE624945DDDD440A951C8B5F7B189CC1, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_RemoteHostPort_m18FEDFAAAAD0D68853D7BCFD82CD6172D18E30FD, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_RemoteHostPort_m69145DC1D9C7DFB8837691A14482B696A933D24B, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_MaxBitrate_m23848E1F57157ADF0AB2F3B0D55462FAACFAA1B7, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_MaxBitrate_mD87B2F77955A0EE09F7313F0483D94C5D65C389F, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_VideoCodec_m7DCFF126E5EF3AF295CD04C2EDD9B8222A9B162A, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_VideoCodec_m7F9D59A946FECDFD66A75864E2244312F13D1184, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_get_EnableAudio_m233ED19A72BF0D3435DA130103087E88D2AD530D, RemotingSettings_t64A0B31CA875FC1EB9D9964FDCA16CE988B796A2_CustomAttributesCacheGenerator_RemotingSettings_set_EnableAudio_mA6B52F05FFF4229074859A62AE63FF213CDFBDD7, ARAnchorExtensions_t8792B73E0A6E37EEA746928608327B699AF36FD9_CustomAttributesCacheGenerator_ARAnchorExtensions_GetOpenXRHandle_m5F6791F083FC0EC8693082EF83B4EA62772A87B9, AnchorManagerExtensions_t54C6EAE326354508E091AD4C54BBEA676C195347_CustomAttributesCacheGenerator_AnchorManagerExtensions_LoadAnchorStoreAsync_mA79EEA73F39EBC8C34BFE59AA68E3E848AC3774C, XRAnchorExtensions_t5A745CCCA3EF008EAC116C285C4C143AA111DECE_CustomAttributesCacheGenerator_XRAnchorExtensions_GetOpenXRHandle_m1FDA9CFAC3FD2E506AEB822251E8DA0E759A525F, MeshSubsystemExtensions_t2E73175E6D66D07952D99AC289AF20DEE269F5A3_CustomAttributesCacheGenerator_MeshSubsystemExtensions_TrySetMeshComputeSettings_mBD9D788AB70A6EA3E5476FB36BACF54E5762164E, AnchorSubsystemExtensions_t597F2D3456B86E02D74E4B28C4BAC90851A9B076_CustomAttributesCacheGenerator_AnchorSubsystemExtensions_LoadAnchorStoreAsync_m6421EE79C71C759B05640A228ADA8A67BAF19915, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____thumbstick_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____grip_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____gripPressed_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____menu_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____primaryButton_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____secondaryButton_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____trigger_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____triggerPressed_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____thumbstickClicked_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____devicePose_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____pointer_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____isTracked_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____trackingState_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____devicePosition_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____deviceRotation_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____pointerPosition_PropertyInfo, HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E_CustomAttributesCacheGenerator_HPMixedRealityController_t5260B1D8A45C24C72060207C9325C08848EFEF3E____pointerRotation_PropertyInfo, Microsoft_MixedReality_OpenXR_CustomAttributesCacheGenerator, }; IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, bool ___value0, const RuntimeMethod* method) { { bool L_0 = ___value0; __this->set_m_wrapNonExceptionThrows_0(L_0); return; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlLayoutAttribute_set_displayName_m51759C33760B60FB12DD2D2EDC8C431EA0FD1E20_inline (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * __this, String_t* ___value0, const RuntimeMethod* method) { { // public string displayName { get; set; } String_t* L_0 = ___value0; __this->set_U3CdisplayNameU3Ek__BackingField_6(L_0); return; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlLayoutAttribute_set_commonUsages_mE744432198FBB37B38B16119433EB748EED7CCF3_inline (InputControlLayoutAttribute_tD4D1C69B76A853B381AF67C608C42CAA19FEB984 * __this, StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___value0, const RuntimeMethod* method) { { // public string[] commonUsages { get; set; } StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* L_0 = ___value0; __this->set_U3CcommonUsagesU3Ek__BackingField_2(L_0); return; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlAttribute_set_aliases_mA2A0291BD4112A24F62155E0B58726AD28D5D1C5_inline (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * __this, StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* ___value0, const RuntimeMethod* method) { { // public string[] aliases { get; set; } StringU5BU5D_tACEBFEDE350025B554CD507C9AE8FFE49359549A* L_0 = ___value0; __this->set_U3CaliasesU3Ek__BackingField_9(L_0); return; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void InputControlAttribute_set_offset_mD1C8106D674D63F7FB7F0A28FE066191DC9F3671_inline (InputControlAttribute_tCFC1C1312D7E91421F9D1B43C1B7A8E99B7B1CB8 * __this, uint32_t ___value0, const RuntimeMethod* method) { { // public uint offset { get; set; } = InputStateBlock.InvalidOffset; uint32_t L_0 = ___value0; __this->set_U3CoffsetU3Ek__BackingField_12(L_0); return; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void NativeLibTokenAttribute_set_NativeLibToken_mF09ED419191B976853D26408E76B37DB50C18B45_inline (NativeLibTokenAttribute_t4DBFB5BF0535AE8CE73E9D79853C830B87DE0008 * __this, uint64_t ___value0, const RuntimeMethod* method) { { // public NativeLibToken NativeLibToken { get; set; } uint64_t L_0 = ___value0; __this->set_U3CNativeLibTokenU3Ek__BackingField_0(L_0); return; } }
69.21247
465
0.898843
[ "object" ]
6de724291cbc3b92f876398e4cba088dbb8509f4
5,005
cpp
C++
osquery/tables/applications/darwin/browser_plugins.cpp
saydulk/osquery
5789d889f421f6761ba7c600d7eaf8a3ba18ee82
[ "BSD-3-Clause" ]
null
null
null
osquery/tables/applications/darwin/browser_plugins.cpp
saydulk/osquery
5789d889f421f6761ba7c600d7eaf8a3ba18ee82
[ "BSD-3-Clause" ]
null
null
null
osquery/tables/applications/darwin/browser_plugins.cpp
saydulk/osquery
5789d889f421f6761ba7c600d7eaf8a3ba18ee82
[ "BSD-3-Clause" ]
16
2017-01-12T10:37:09.000Z
2019-04-19T08:23:19.000Z
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <osquery/filesystem.h> #include <osquery/tables.h> /// Include the "external" (not OS X provided) libarchive header. #include <archive.h> #include <archive_entry.h> #include "osquery/tables/applications/browser_utils.h" namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace osquery { namespace tables { /// Each home directory will include custom extensions. #define kSafariExtensionsPath "/Library/Safari/Extensions/" /// Safari extensions will not load unless they have the expected pattern. #define kSafariExtensionsPattern "%.safariextz" #define kBrowserPluginsPath "/Library/Internet Plug-Ins/" const std::map<std::string, std::string> kBrowserPluginKeys = { {"WebPluginName", "name"}, {"CFBundleIdentifier", "identifier"}, {"CFBundleShortVersionString", "version"}, {"DTPlatformBuild", "sdk"}, {"WebPluginDescription", "description"}, {"CFBundleDevelopmentRegion", "development_region"}, {"LSRequiresNativeExecution", "native"}, }; const std::map<std::string, std::string> kSafariExtensionKeys = { {"CFBundleDisplayName", "name"}, {"CFBundleIdentifier", "identifier"}, {"CFBundleShortVersionString", "version"}, {"Author", "author"}, {"CFBundleInfoDictionaryVersion", "sdk"}, {"Description", "description"}, {"Update Manifest URL", "update_url"}, }; void genBrowserPlugin(const std::string& path, QueryData& results) { Row r; pt::ptree tree; if (osquery::parsePlist(path + "/Contents/Info.plist", tree).ok()) { // Plugin did not include an Info.plist, or it was invalid for (const auto& it : kBrowserPluginKeys) { r[it.second] = tree.get(it.first, ""); // Convert bool-types to an integer. jsonBoolAsInt(r[it.second]); } } if (r.count("native") == 0 || r.at("native").size() == 0) { // The default case for native execution is false. r["native"] = "0"; } r["path"] = path; results.push_back(std::move(r)); } QueryData genBrowserPlugins(QueryContext& context) { QueryData results; std::vector<std::string> bundles; if (listDirectoriesInDirectory(kBrowserPluginsPath, bundles).ok()) { for (const auto& dir : bundles) { genBrowserPlugin(dir, results); } } auto homes = osquery::getHomeDirectories(); for (const auto& home : homes) { bundles.clear(); if (listDirectoriesInDirectory(home / kBrowserPluginsPath, bundles).ok()) { for (const auto& dir : bundles) { genBrowserPlugin(dir, results); } } } return results; } inline void genSafariExtension(const std::string& path, QueryData& results) { Row r; r["path"] = path; // Loop through (Plist key -> table column name) in kSafariExtensionKeys. struct archive* ext = archive_read_new(); if (ext == nullptr) { return; } // Use open_file, instead of the preferred open_filename for OS X 10.9. archive_read_support_format_xar(ext); if (archive_read_open_file(ext, path.c_str(), 10240) != ARCHIVE_OK) { archive_read_finish(ext); return; } struct archive_entry* entry = nullptr; while (archive_read_next_header(ext, &entry) == ARCHIVE_OK) { auto item_path = archive_entry_pathname(entry); // Documentation for libarchive mentions these APIs may return NULL. if (item_path == nullptr) { archive_read_data_skip(ext); continue; } // Assume there is no non-root Info. if (std::string(item_path).find("Info.plist") == std::string::npos) { archive_read_data_skip(ext); continue; } // Read the decompressed Info.plist content. auto content = std::string(archive_entry_size(entry), '\0'); archive_read_data_into_buffer(ext, &content[0], content.size()); // If the Plist can be parsed, extract important keys into columns. pt::ptree tree; if (parsePlistContent(content, tree).ok()) { for (const auto& it : kSafariExtensionKeys) { r[it.second] = tree.get(it.first, ""); } } break; } archive_read_close(ext); archive_read_finish(ext); results.push_back(std::move(r)); } QueryData genSafariExtensions(QueryContext& context) { QueryData results; auto homes = osquery::getHomeDirectories(); for (const auto& home : homes) { auto dir = home / kSafariExtensionsPath; // Check that an extensions directory exists. if (!pathExists(dir).ok()) { continue; } // Glob the extension files. std::vector<std::string> paths; if (!resolveFilePattern(dir / kSafariExtensionsPattern, paths).ok()) { continue; } for (const auto& extension_path : paths) { genSafariExtension(extension_path, results); } } return results; } } }
28.4375
79
0.674925
[ "vector" ]
6df0a55b1bbc1d037dc99603c17d1beffb21ecb6
16,213
hh
C++
harfbuzz-sys/harfbuzz/src/hb.hh
raphlinus/rust-harfbuzz
54c9be42cd23677df87b26938b0d6617df66e7e1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
56
2019-01-06T21:58:29.000Z
2022-02-10T06:22:47.000Z
harfbuzz-sys/harfbuzz/src/hb.hh
raphlinus/rust-harfbuzz
54c9be42cd23677df87b26938b0d6617df66e7e1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
harfbuzz-sys/harfbuzz/src/hb.hh
raphlinus/rust-harfbuzz
54c9be42cd23677df87b26938b0d6617df66e7e1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
4
2020-04-07T00:53:31.000Z
2021-03-21T08:18:21.000Z
/* * Copyright © 2007,2008,2009 Red Hat, Inc. * Copyright © 2011,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Red Hat Author(s): Behdad Esfahbod * Google Author(s): Behdad Esfahbod */ #ifndef HB_HH #define HB_HH #define _GNU_SOURCE 1 #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 200809L #endif #if defined (_MSC_VER) && defined (HB_DLL_EXPORT) #define HB_EXTERN __declspec (dllexport) extern #endif #include "hb.h" #define HB_H_IN #include "hb-ot.h" #define HB_OT_H_IN #include "hb-aat.h" #define HB_AAT_H_IN #include "hb-aat.h" #include <math.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdarg.h> #if (defined(_MSC_VER) && _MSC_VER >= 1500) || defined(__MINGW32__) #include <intrin.h> #endif #define HB_PASTE1(a,b) a##b #define HB_PASTE(a,b) HB_PASTE1(a,b) /* Compile-time custom allocator support. */ #if defined(hb_malloc_impl) \ && defined(hb_calloc_impl) \ && defined(hb_realloc_impl) \ && defined(hb_free_impl) extern "C" void* hb_malloc_impl(size_t size); extern "C" void* hb_calloc_impl(size_t nmemb, size_t size); extern "C" void* hb_realloc_impl(void *ptr, size_t size); extern "C" void hb_free_impl(void *ptr); #define malloc hb_malloc_impl #define calloc hb_calloc_impl #define realloc hb_realloc_impl #define free hb_free_impl #if defined(hb_memalign_impl) extern "C" int hb_memalign_impl(void **memptr, size_t alignment, size_t size); #define posix_memalign hb_memalign_impl #else #undef HAVE_POSIX_MEMALIGN #endif #endif /* * Compiler attributes */ #if __cplusplus < 201103L #ifndef nullptr #define nullptr NULL #endif #ifndef constexpr #define constexpr const #endif #ifndef static_assert #define static_assert(e, msg) \ HB_UNUSED typedef int HB_PASTE(static_assertion_failed_at_line_, __LINE__) [(e) ? 1 : -1] #endif // static_assert #ifdef __GNUC__ #if (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) #define thread_local __thread #endif #else #define thread_local #endif template <typename T> struct _hb_alignof { struct s { char c; T t; }; static constexpr size_t value = offsetof (s, t); }; #ifndef alignof #define alignof(x) (_hb_alignof<x>::value) #endif /* https://github.com/harfbuzz/harfbuzz/issues/1127 */ #ifndef explicit_operator #define explicit_operator #endif #else /* __cplusplus >= 201103L */ /* https://github.com/harfbuzz/harfbuzz/issues/1127 */ #ifndef explicit_operator #define explicit_operator explicit #endif #endif /* __cplusplus < 201103L */ #if (defined(__GNUC__) || defined(__clang__)) && defined(__OPTIMIZE__) #define likely(expr) (__builtin_expect (!!(expr), 1)) #define unlikely(expr) (__builtin_expect (!!(expr), 0)) #else #define likely(expr) (expr) #define unlikely(expr) (expr) #endif #if !defined(__GNUC__) && !defined(__clang__) #undef __attribute__ #define __attribute__(x) #endif #if __GNUC__ >= 3 #define HB_PURE_FUNC __attribute__((pure)) #define HB_CONST_FUNC __attribute__((const)) #define HB_PRINTF_FUNC(format_idx, arg_idx) __attribute__((__format__ (__printf__, format_idx, arg_idx))) #else #define HB_PURE_FUNC #define HB_CONST_FUNC #define HB_PRINTF_FUNC(format_idx, arg_idx) #endif #if __GNUC__ >= 4 #define HB_UNUSED __attribute__((unused)) #elif defined(_MSC_VER) /* https://github.com/harfbuzz/harfbuzz/issues/635 */ #define HB_UNUSED __pragma(warning(suppress: 4100 4101)) #else #define HB_UNUSED #endif #ifndef HB_INTERNAL # if !defined(HB_NO_VISIBILITY) && !defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(_MSC_VER) && !defined(__SUNPRO_CC) # define HB_INTERNAL __attribute__((__visibility__("hidden"))) # elif defined(__MINGW32__) /* We use -export-symbols on mingw32, since it does not support visibility attributes. */ # define HB_INTERNAL # elif defined (_MSC_VER) && defined (HB_DLL_EXPORT) /* We do not try to export internal symbols on Visual Studio */ # define HB_INTERNAL #else # define HB_INTERNAL # define HB_NO_VISIBILITY 1 # endif #endif #if __GNUC__ >= 3 #define HB_FUNC __PRETTY_FUNCTION__ #elif defined(_MSC_VER) #define HB_FUNC __FUNCSIG__ #else #define HB_FUNC __func__ #endif #if defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x5140) /* https://github.com/harfbuzz/harfbuzz/issues/630 */ #define __restrict #endif /* * Borrowed from https://bugzilla.mozilla.org/show_bug.cgi?id=1215411 * HB_FALLTHROUGH is an annotation to suppress compiler warnings about switch * cases that fall through without a break or return statement. HB_FALLTHROUGH * is only needed on cases that have code: * * switch (foo) { * case 1: // These cases have no code. No fallthrough annotations are needed. * case 2: * case 3: * foo = 4; // This case has code, so a fallthrough annotation is needed: * HB_FALLTHROUGH; * default: * return foo; * } */ #if defined(__clang__) && __cplusplus >= 201103L /* clang's fallthrough annotations are only available starting in C++11. */ # define HB_FALLTHROUGH [[clang::fallthrough]] #elif __GNUC__ >= 7 /* GNU fallthrough attribute is available from GCC7 */ # define HB_FALLTHROUGH __attribute__((fallthrough)) #elif defined(_MSC_VER) /* * MSVC's __fallthrough annotations are checked by /analyze (Code Analysis): * https://msdn.microsoft.com/en-us/library/ms235402%28VS.80%29.aspx */ # include <sal.h> # define HB_FALLTHROUGH __fallthrough #else # define HB_FALLTHROUGH /* FALLTHROUGH */ #endif #if defined(__clang__) /* Disable certain sanitizer errors. */ /* https://github.com/harfbuzz/harfbuzz/issues/1247 */ #define HB_NO_SANITIZE_SIGNED_INTEGER_OVERFLOW __attribute__((no_sanitize("signed-integer-overflow"))) #else #define HB_NO_SANITIZE_SIGNED_INTEGER_OVERFLOW #endif #ifdef _WIN32 /* We need Windows Vista for both Uniscribe backend and for * MemoryBarrier. We don't support compiling on Windows XP, * though we run on it fine. */ # if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600 # undef _WIN32_WINNT # endif # ifndef _WIN32_WINNT # if !defined(WINAPI_FAMILY) || !(WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) # define _WIN32_WINNT 0x0600 # endif # endif # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif # ifndef STRICT # define STRICT 1 # endif # if defined(_WIN32_WCE) /* Some things not defined on Windows CE. */ # define vsnprintf _vsnprintf # define getenv(Name) nullptr # if _WIN32_WCE < 0x800 # define setlocale(Category, Locale) "C" static int errno = 0; /* Use something better? */ # endif # elif defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) # define getenv(Name) nullptr # endif # if defined(_MSC_VER) && _MSC_VER < 1900 # define snprintf _snprintf # endif #endif #if defined(HAVE_ATEXIT) && !defined(HB_USE_ATEXIT) /* atexit() is only safe to be called from shared libraries on certain * platforms. Whitelist. * https://bugs.freedesktop.org/show_bug.cgi?id=82246 */ # if defined(__linux) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2,3) /* From atexit() manpage, it's safe with glibc 2.2.3 on Linux. */ # define HB_USE_ATEXIT 1 # endif # elif defined(_MSC_VER) || defined(__MINGW32__) /* For MSVC: * https://msdn.microsoft.com/en-us/library/tze57ck3.aspx * https://msdn.microsoft.com/en-us/library/zk17ww08.aspx * mingw32 headers say atexit is safe to use in shared libraries. */ # define HB_USE_ATEXIT 1 # elif defined(__ANDROID__) /* This is available since Android NKD r8 or r8b: * https://issuetracker.google.com/code/p/android/issues/detail?id=6455 */ # define HB_USE_ATEXIT 1 # elif defined(__APPLE__) /* For macOS and related platforms, the atexit man page indicates * that it will be invoked when the library is unloaded, not only * at application exit. */ # define HB_USE_ATEXIT 1 # endif #endif #ifdef HB_NO_ATEXIT # undef HB_USE_ATEXIT #endif #ifndef HB_USE_ATEXIT # define HB_USE_ATEXIT 0 #endif #define HB_STMT_START do #define HB_STMT_END while (0) /* Static-assert as expression. */ template <unsigned int cond> class hb_assert_constant_t; template <> class hb_assert_constant_t<1> {}; #define ASSERT_STATIC_EXPR_ZERO(_cond) (0 * (unsigned int) sizeof (hb_assert_constant_t<_cond>)) /* Lets assert int types. Saves trouble down the road. */ static_assert ((sizeof (int8_t) == 1), ""); static_assert ((sizeof (uint8_t) == 1), ""); static_assert ((sizeof (int16_t) == 2), ""); static_assert ((sizeof (uint16_t) == 2), ""); static_assert ((sizeof (int32_t) == 4), ""); static_assert ((sizeof (uint32_t) == 4), ""); static_assert ((sizeof (int64_t) == 8), ""); static_assert ((sizeof (uint64_t) == 8), ""); static_assert ((sizeof (hb_codepoint_t) == 4), ""); static_assert ((sizeof (hb_position_t) == 4), ""); static_assert ((sizeof (hb_mask_t) == 4), ""); static_assert ((sizeof (hb_var_int_t) == 4), ""); #if __cplusplus >= 201103L /* We only enable these with C++11 or later, since earlier language * does not allow structs with constructors in unions, and we need * those. */ #define HB_NO_COPY_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #define HB_NO_COPY_ASSIGN_TEMPLATE2(TypeName, T1, T2) \ TypeName(const TypeName<T1, T2>&); \ void operator=(const TypeName<T1, T2>&) #define HB_NO_CREATE_COPY_ASSIGN(TypeName) \ TypeName(void); \ TypeName(const TypeName&); \ void operator=(const TypeName&) #define HB_NO_CREATE_COPY_ASSIGN_TEMPLATE(TypeName, T) \ TypeName(void); \ TypeName(const TypeName<T>&); \ void operator=(const TypeName<T>&) #define HB_NO_CREATE_COPY_ASSIGN_TEMPLATE2(TypeName, T1, T2) \ TypeName(void); \ TypeName(const TypeName<T1, T2>&); \ void operator=(const TypeName<T1, T2>&) #else /* __cpluspplus >= 201103L */ #define HB_NO_COPY_ASSIGN(TypeName) #define HB_NO_COPY_ASSIGN_TEMPLATE2(TypeName, T1, T2) static_assert (true, "") #define HB_NO_CREATE_COPY_ASSIGN(TypeName) static_assert (true, "") #define HB_NO_CREATE_COPY_ASSIGN_TEMPLATE(TypeName, T) static_assert (true, "") #define HB_NO_CREATE_COPY_ASSIGN_TEMPLATE2(TypeName, T1, T2) static_assert (true, "") #endif /* __cpluspplus >= 201103L */ /* * Compiler-assisted vectorization parameters. */ /* * Disable vectorization for now. To correctly use them, we should * use posix_memalign() to allocate in hb_vector_t. Otherwise, can * cause misaligned access. * * https://bugs.chromium.org/p/chromium/issues/detail?id=860184 */ #if !defined(HB_VECTOR_SIZE) # define HB_VECTOR_SIZE 0 #endif /* The `vector_size' attribute was introduced in gcc 3.1. */ #if !defined(HB_VECTOR_SIZE) # if defined( __GNUC__ ) && ( __GNUC__ >= 4 ) # define HB_VECTOR_SIZE 128 # else # define HB_VECTOR_SIZE 0 # endif #endif static_assert (0 == (HB_VECTOR_SIZE & (HB_VECTOR_SIZE - 1)), "HB_VECTOR_SIZE is not power of 2."); static_assert (0 == (HB_VECTOR_SIZE % 64), "HB_VECTOR_SIZE is not multiple of 64."); #if HB_VECTOR_SIZE typedef uint64_t hb_vector_size_impl_t __attribute__((vector_size (HB_VECTOR_SIZE / 8))); #else typedef uint64_t hb_vector_size_impl_t; #endif /* HB_NDEBUG disables some sanity checks that are very safe to disable and * should be disabled in production systems. If NDEBUG is defined, enable * HB_NDEBUG; but if it's desirable that normal assert()s (which are very * light-weight) to be enabled, then HB_DEBUG can be defined to disable * the costlier checks. */ #ifdef NDEBUG #define HB_NDEBUG 1 #endif /* Flags */ /* Enable bitwise ops on enums marked as flags_t */ /* To my surprise, looks like the function resolver is happy to silently cast * one enum to another... So this doesn't provide the type-checking that I * originally had in mind... :(. * * For MSVC warnings, see: https://github.com/harfbuzz/harfbuzz/pull/163 */ #ifdef _MSC_VER # pragma warning(disable:4200) # pragma warning(disable:4800) #endif #define HB_MARK_AS_FLAG_T(T) \ extern "C++" { \ static inline T operator | (T l, T r) { return T ((unsigned) l | (unsigned) r); } \ static inline T operator & (T l, T r) { return T ((unsigned) l & (unsigned) r); } \ static inline T operator ^ (T l, T r) { return T ((unsigned) l ^ (unsigned) r); } \ static inline T operator ~ (T r) { return T (~(unsigned int) r); } \ static inline T& operator |= (T &l, T r) { l = l | r; return l; } \ static inline T& operator &= (T& l, T r) { l = l & r; return l; } \ static inline T& operator ^= (T& l, T r) { l = l ^ r; return l; } \ } /* Useful for set-operations on small enums. * For example, for testing "x ∈ {x1, x2, x3}" use: * (FLAG_UNSAFE(x) & (FLAG(x1) | FLAG(x2) | FLAG(x3))) */ #define FLAG(x) (ASSERT_STATIC_EXPR_ZERO ((unsigned)(x) < 32) + (((uint32_t) 1U) << (unsigned)(x))) #define FLAG_UNSAFE(x) ((unsigned)(x) < 32 ? (((uint32_t) 1U) << (unsigned)(x)) : 0) #define FLAG_RANGE(x,y) (ASSERT_STATIC_EXPR_ZERO ((x) < (y)) + FLAG(y+1) - FLAG(x)) #define FLAG64(x) (ASSERT_STATIC_EXPR_ZERO ((unsigned)(x) < 64) + (((uint64_t) 1ULL) << (unsigned)(x))) #define FLAG64_UNSAFE(x) ((unsigned)(x) < 64 ? (((uint64_t) 1ULL) << (unsigned)(x)) : 0) /* Size signifying variable-sized array */ #define VAR 1 /* fallback for round() */ static inline double _hb_round (double x) { if (x >= 0) return floor (x + 0.5); else return ceil (x - 0.5); } #if !defined (HAVE_ROUND) && !defined (HAVE_DECL_ROUND) #define round(x) _hb_round(x) #endif /* fallback for posix_memalign() */ static inline int _hb_memalign(void **memptr, size_t alignment, size_t size) { if (unlikely (0 != (alignment & (alignment - 1)) || !alignment || 0 != (alignment & (sizeof (void *) - 1)))) return EINVAL; char *p = (char *) malloc (size + alignment - 1); if (unlikely (!p)) return ENOMEM; size_t off = (size_t) p & (alignment - 1); if (off) p += alignment - off; *memptr = (void *) p; return 0; } #if !defined(posix_memalign) && !defined(HAVE_POSIX_MEMALIGN) #define posix_memalign _hb_memalign #endif /* * For lack of a better place, put Zawgyi script hack here. * https://github.com/harfbuzz/harfbuzz/issues/1162 */ #define HB_SCRIPT_MYANMAR_ZAWGYI ((hb_script_t) HB_TAG ('Q','a','a','g')) /* Some really basic things everyone wants. */ template <typename T> struct hb_remove_const { typedef T value; }; template <typename T> struct hb_remove_const<const T> { typedef T value; }; #define hb_remove_const(T) hb_remove_const<T>::value template <typename T> struct hb_remove_reference { typedef T value; }; template <typename T> struct hb_remove_reference<T &> { typedef T value; }; #define hb_remove_reference(T) hb_remove_reference<T>::value template <typename T> struct hb_remove_pointer { typedef T value; }; template <typename T> struct hb_remove_pointer<T *> { typedef T value; }; #define hb_remove_pointer(T) hb_remove_pointer<T>::value /* Headers we include for everyone. Keep sorted. They express dependency amongst * themselves, but no other file should include them.*/ #include "hb-atomic.hh" #include "hb-debug.hh" #include "hb-dsalgs.hh" #include "hb-mutex.hh" #include "hb-null.hh" #include "hb-object.hh" #endif /* HB_HH */
30.361423
127
0.717017
[ "object" ]
6df2bafda6952db4d17e696263055e7ac6d72010
16,352
hpp
C++
include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/error_bound.hpp
BoostGSoC20/geometry
5b63bdc9086829c4c00bf9f5e23c664430acdd48
[ "BSL-1.0" ]
5
2020-05-15T20:30:38.000Z
2022-01-31T08:14:05.000Z
include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/error_bound.hpp
Srutip04/geometry
5b63bdc9086829c4c00bf9f5e23c664430acdd48
[ "BSL-1.0" ]
null
null
null
include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/error_bound.hpp
Srutip04/geometry
5b63bdc9086829c4c00bf9f5e23c664430acdd48
[ "BSL-1.0" ]
4
2020-12-03T13:22:49.000Z
2022-03-31T10:43:59.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2020 Tinko Bartels, Berlin, Germany. // Contributed and/or modified by Tinko Bartels, // as part of Google Summer of Code 2020 program. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_ERROR_BOUND_HPP #define BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_ERROR_BOUND_HPP #include <limits> #include <boost/mp11/integral.hpp> #include <boost/mp11/list.hpp> #include <boost/mp11/map.hpp> #include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/coefficient_list.hpp> namespace boost { namespace geometry { namespace detail { namespace generic_robust_predicates { template <typename KV> using second_is_coeff_list = is_coeff_list< boost::mp11::mp_second<KV> >; template <typename EM> using is_error_map = boost::mp11::mp_and < boost::mp11::mp_is_map<EM>, boost::mp11::mp_all_of<EM, second_is_coeff_list>, boost::mp11::mp_similar<EM, boost::mp11::mp_list<> > //TODO: It would be desirable to also validate that the keys are good >; template <typename KV, typename M> struct error_map_insert_impl { private: using key = boost::mp11::mp_front<KV>; using value = boost::mp11::mp_second<KV>; using other_value = typename mp_map_at_second_or_void<M, key>::type; using merged_value = coeff_merge<value, other_value>; using nkv = boost::mp11::mp_list<key, merged_value>; public: using type = boost::mp11::mp_map_replace<M, nkv>; }; template <typename KV, typename M> using error_map_insert = typename error_map_insert_impl<KV, M>::type; template <typename M1, typename M2> struct add_fold_operator { public: template <typename M, typename K> using fn = boost::mp11::mp_map_insert < M, boost::mp11::mp_list < K, coeff_merge < typename mp_map_at_second_or_void<M1, K>::type, typename mp_map_at_second_or_void<M2, K>::type > > >; }; template <typename M1, typename M2> using add_children = boost::mp11::mp_fold < boost::mp11::mp_set_union < boost::mp11::mp_map_keys<M1>, boost::mp11::mp_map_keys<M2> >, boost::mp11::mp_list<>, add_fold_operator<M1, M2>::template fn >; template < typename Exp, typename EM, typename Out, typename LErr = typename val_or_empty_list<EM, typename Exp::left>::type, typename RErr = typename val_or_empty_list<EM, typename Exp::right>::type, typename skip_decompose = boost::mp11::mp_or < boost::mp11::mp_not < boost::mp11::mp_same < typename Exp::error_type, sum_error_type > >, boost::mp11::mp_same < boost::mp11::mp_list<>, LErr, RErr > > > struct decompose_add_impl { private: using decomp_left = typename decompose_add_impl < typename Exp::left, EM, Out >::type; using decomp_right = typename decompose_add_impl < typename Exp::right, EM, decomp_left >::type; public: using type = decomp_right; }; template < typename Exp, typename EM, typename Out, typename LErr, typename RErr > struct decompose_add_impl < Exp, EM, Out, LErr, RErr, boost::mp11::mp_true > { using type = error_map_insert < boost::mp11::mp_list < Exp, boost::mp11::mp_list<boost::mp11::mp_int<1>> >, Out >; }; template < typename Exp, typename EM, typename Out > using decompose_add = typename decompose_add_impl<Exp, EM, Out>::type; template < typename Exp, typename EM, typename LErr = typename val_or_empty_list<EM, typename Exp::left>::type, typename RErr = typename val_or_empty_list<EM, typename Exp::right>::type, typename Children_Empty = boost::mp11::mp_and < typename empty_or_void<LErr>::type, typename empty_or_void<RErr>::type > > struct sum_err_impl { private: static_assert(is_error_map<LErr>::value, "LErr needs to be a valid error map."); static_assert(is_error_map<RErr>::value, "RErr needs to be a valid error map."); using children = add_children<LErr, RErr>; static_assert( is_error_map<children>::value, "children needs to be a valid error map."); public: /* using type = boost::mp11::mp_map_insert< children, boost::mp11::mp_list<Exp, boost::mp11::mp_list<boost::mp11::mp_int<1>>> >;*/ using type = decompose_add<Exp, EM, children>; static_assert(is_error_map<type>::value, "type needs to be a valid error map."); }; template < typename Exp, typename EM, typename LErr, typename RErr > struct sum_err_impl < Exp, EM, LErr, RErr, boost::mp11::mp_true > { static_assert(is_error_map<LErr>::value, "LErr needs to be a valid error map."); static_assert(is_error_map<RErr>::value, "RErr needs to be a valid error map."); using type = boost::mp11::mp_list < boost::mp11::mp_list < Exp, boost::mp11::mp_list<boost::mp11::mp_int<1>> > >; static_assert(is_error_map<type>::value, "type needs to be a valid error map."); }; template <typename Exp, typename EM> using sum_err = typename sum_err_impl<Exp, EM>::type; template <typename L> using pad_second = boost::mp11::mp_list < boost::mp11::mp_front<L>, boost::mp11::mp_push_front < boost::mp11::mp_second<L>, boost::mp11::mp_int<0> > >; template <typename L> using pop_front_second = boost::mp11::mp_list < boost::mp11::mp_front<L>, boost::mp11::mp_pop_front<boost::mp11::mp_second<L>> >; template <typename K, typename V> using increment_first_of_second = boost::mp11::mp_transform_front<V, inc>; template <typename KV1, typename KV2> using prod_entry_merge = boost::mp11::mp_list < boost::mp11::mp_flatten < boost::mp11::mp_list < boost::mp11::mp_first<KV1>, boost::mp11::mp_first<KV2> > >, list_product < boost::mp11::mp_second<KV1>, boost::mp11::mp_second<KV2> > >; template < typename Exp, typename EM, typename LErr = typename val_or_empty_list<EM, typename Exp::left>::type, typename RErr = typename val_or_empty_list<EM, typename Exp::right>::type > struct prod_children_impl { private: static_assert(is_error_map<LErr>::value, "LErr needs to be a valid error map."); static_assert(is_error_map<RErr>::value, "RErr needs to be a valid error map."); using left = typename Exp::left; using right = typename Exp::right; using padded_lerr = boost::mp11::mp_transform<pad_second, LErr>; using added_left_lerr = decompose_add<left, EM, padded_lerr>; using padded_rerr = boost::mp11::mp_transform<pad_second, RErr>; using added_right_rerr = decompose_add<right, EM, padded_rerr>; using prod = boost::mp11::mp_product < prod_entry_merge, added_left_lerr, added_right_rerr >; using stripped_prod = boost::mp11::mp_transform<pop_front_second, prod>; public: using type = stripped_prod; static_assert(is_error_map<type>::value, "type needs to be a valid error map."); }; template <typename Exp, typename EM> using prod_children = typename prod_children_impl<Exp, EM>::type; template < typename Exp, typename EM, typename LErr = typename val_or_empty_list<EM, typename Exp::left>::type, typename RErr = typename val_or_empty_list<EM, typename Exp::right>::type > struct product_err_impl { private: static_assert(is_error_map<LErr>::value, "LErr needs to be a valid error map."); static_assert(is_error_map<RErr>::value, "RErr needs to be a valid error map."); using children = prod_children<Exp, EM>; static_assert(is_error_map<children>::value, "children needs to be a valid error map."); public: using type = boost::mp11::mp_map_insert < children, boost::mp11::mp_list < Exp, boost::mp11::mp_list< boost::mp11::mp_int<1> > > >; static_assert(is_error_map<type>::value, "type needs to be a valid error map."); }; template <typename Exp, typename EM> using product_err = typename product_err_impl<Exp, EM>::type; template < typename Errors, typename Exp, typename IsSum = boost::mp11::mp_same < typename Exp::error_type, sum_error_type > > struct sum_or_product_err_impl { using type = sum_err<Exp, Errors>; }; template < typename Errors, typename Exp > struct sum_or_product_err_impl<Errors, Exp, boost::mp11::mp_false> { using type = product_err<Exp, Errors>; }; template <typename Errors, typename Exp> using sum_or_product_err = typename sum_or_product_err_impl<Errors, Exp>::type; template < typename Errors, typename Exp > struct error_fold_impl { private: using lerr = typename val_or_empty_list<Errors, typename Exp::left>::type; using rerr = typename val_or_empty_list<Errors, typename Exp::right>::type; using err = sum_or_product_err<Errors, Exp>; public: using type = boost::mp11::mp_map_insert < Errors, boost::mp11::mp_list<Exp, err> >; }; template <typename Errors, typename Exp> using error_fold = typename error_fold_impl<Errors, Exp>::type; template <typename Evals> using evals_error = boost::mp11::mp_fold < Evals, boost::mp11::mp_list<>, error_fold >; template <typename T> using is_mp_list = boost::mp11::mp_similar < boost::mp11::mp_list<>, T >; template <typename KV> struct list_to_product_impl { private: using key = boost::mp11::mp_front<KV>; using value = boost::mp11::mp_second<KV>; using multiplications = boost::mp11::mp_int<boost::mp11::mp_size<key>::value - 1>; using nvalue = mult_by_1_p_eps_pow<value, multiplications>; using nkey = boost::mp11::mp_reverse_fold< boost::mp11::mp_pop_back<key>, boost::mp11::mp_back<key>, product >; public: using type = boost::mp11::mp_list<nkey, nvalue>; }; template <typename KV> using list_to_product = typename list_to_product_impl<KV>::type; template < typename M, typename KV, typename KeyMPList = is_mp_list< boost::mp11::mp_front<KV> > > struct error_map_list_to_product_fold_impl { using type = error_map_insert<list_to_product<KV>, M>; }; template <typename M, typename KV> struct error_map_list_to_product_fold_impl < M, KV, boost::mp11::mp_false > { using type = error_map_insert<KV, M>; }; template <typename M, typename KV> using error_map_list_to_product_fold = typename error_map_list_to_product_fold_impl<M, KV>::type; template <typename M> struct error_map_list_to_product_impl { using type = boost::mp11::mp_fold < M, boost::mp11::mp_list<>, error_map_list_to_product_fold >; }; template <typename M> using error_map_list_to_product = typename error_map_list_to_product_impl<M>::type; template <typename Expression> struct abs_unless_non_negative { using type = boost::mp11::mp_if_c < Expression::non_negative, Expression, abs<Expression> >; }; template <typename EM, typename KV> using abs_fold = boost::mp11::mp_push_back < EM, boost::mp11::mp_list < typename abs_unless_non_negative<boost::mp11::mp_front<KV>> ::type, boost::mp11::mp_second<KV> > >; template<typename EM> using abs_all = boost::mp11::mp_fold < EM, boost::mp11::mp_list<>, abs_fold >; template < typename KV1, typename KV2 > struct abs_sum_error_term_impl { private: using key1 = boost::mp11::mp_front<KV1>; using key2 = boost::mp11::mp_front<KV2>; using nkey = sum<key1, key2>; using val1 = boost::mp11::mp_second<KV1>; using val2 = boost::mp11::mp_second<KV2>; using mval = coeff_max<val1, val2>; static_assert(is_coeff_list<mval>::value, "merged coefficient list fails coefficient list check"); using nval = mult_by_1_p_eps<mval>; public: using type = boost::mp11::mp_list<nkey, nval>; }; template<typename KV1, typename KV2> using abs_sum_error_term = typename abs_sum_error_term_impl<KV1, KV2>::type; //TODO: The following could be probably optimized for potentially produce better error bounds in some cases // if the error map is treated as a minheap by ordering of epsilon-polynomial. template<typename M> using error_map_sum_up = boost::mp11::mp_fold < boost::mp11::mp_pop_front<M>, boost::mp11::mp_first<M>, abs_sum_error_term >; template<typename M, std::size_t MS = boost::mp11::mp_size<M>::value> struct error_map_balanced_sum_up_impl { private: static constexpr std::size_t mid = MS/2; using left = typename error_map_balanced_sum_up_impl < boost::mp11::mp_erase_c<M, 0, mid> >::type; using right = typename error_map_balanced_sum_up_impl < boost::mp11::mp_erase_c<M, mid, MS> >::type; public: using type = abs_sum_error_term<left, right>; }; template<typename M> struct error_map_balanced_sum_up_impl<M, 1> { using type = boost::mp11::mp_front<M>; }; template<typename M> using error_map_balanced_sum_up = typename error_map_balanced_sum_up_impl<M>::type; template < typename Real, typename Exp > struct eps_pow { static constexpr Real value = std::numeric_limits<Real>::epsilon()/2.0 * eps_pow<Real, boost::mp11::mp_size_t< Exp::value - 1 >>::value; }; template <typename Real> struct eps_pow<Real, boost::mp11::mp_size_t<0>> { static constexpr Real value = 1.0; }; template < typename Real, typename L, typename S = boost::mp11::mp_size<L> > struct eval_eps_polynomial { private: using last = boost::mp11::mp_back<L>; using s2last = boost::mp11::mp_back< boost::mp11::mp_pop_back<L> >; public: static constexpr Real value = s2last::value * eps_pow<Real, boost::mp11::mp_size_t<S::value - 1>>::value + last::value * eps_pow<Real, S>::value; }; template < typename Real, typename L > struct eval_eps_polynomial<Real, L, boost::mp11::mp_size_t<1>> { static constexpr Real value = boost::mp11::mp_front<L>::value * std::numeric_limits<Real>::epsilon() / 2.0; }; template < typename Real, typename L > struct eval_eps_polynomial<Real, L, boost::mp11::mp_size_t<0>> { static constexpr Real value = 0; }; }} // namespace detail::generic_robust_predicates }} // namespace boost::geometry #endif // BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_ERROR_BOUND_HPP
26.983498
113
0.618395
[ "geometry" ]
6dfb9808bb337e8f85076fdb5ac83a432f41a3d9
8,202
hxx
C++
src/Module/Decoder/RSC/BCJR/Inter_intra/Decoder_RSC_BCJR_inter_intra.hxx
bonben/aff3ct
8e78123bfc0a377947ecb690ce1e0d70c0dc0a68
[ "MIT" ]
null
null
null
src/Module/Decoder/RSC/BCJR/Inter_intra/Decoder_RSC_BCJR_inter_intra.hxx
bonben/aff3ct
8e78123bfc0a377947ecb690ce1e0d70c0dc0a68
[ "MIT" ]
4
2018-09-27T16:46:31.000Z
2018-11-22T11:10:41.000Z
src/Module/Decoder/RSC/BCJR/Inter_intra/Decoder_RSC_BCJR_inter_intra.hxx
bonben/aff3ct
8e78123bfc0a377947ecb690ce1e0d70c0dc0a68
[ "MIT" ]
null
null
null
#include <limits> #include <sstream> #include "Tools/Exception/exception.hpp" #include "Tools/Math/utils.h" #include "Decoder_RSC_BCJR_inter_intra.hpp" namespace aff3ct { namespace module { template <typename B, typename R> Decoder_RSC_BCJR_inter_intra<B,R> ::Decoder_RSC_BCJR_inter_intra(const int &K, const std::vector<std::vector<int>> &trellis, const bool buffered_encoding, const int n_frames) : Decoder(K, 2*(K + (int)std::log2(trellis[0].size())), n_frames, mipp::N<R>()/8), Decoder_RSC_BCJR<B,R>(K, trellis, buffered_encoding, n_frames, mipp::nElReg<R>() / 8), alpha(8 * (K +4) * (mipp::nElReg<R>()/8) + 1 * mipp::nElReg<R>()), gamma(2 * (K +3) * (mipp::nElReg<R>()/8) + 2 * mipp::nElReg<R>()) { const std::string name = "Decoder_RSC_BCJR_inter_intra"; this->set_name(name); std::vector<std::vector<int>> req_trellis(10, std::vector<int>(8)); req_trellis[0] = { 0, 2, 4, 6, 0, 2, 4, 6}; req_trellis[1] = { 1, -1, 1, -1, -1, 1, -1, 1}; req_trellis[2] = { 0, 1, 1, 0, 0, 1, 1, 0}; req_trellis[3] = { 1, 3, 5, 7, 1, 3, 5, 7}; req_trellis[4] = {-1, 1, -1, 1, 1, -1, 1, -1}; req_trellis[5] = { 0, 1, 1, 0, 0, 1, 1, 0}; req_trellis[6] = { 0, 4, 5, 1, 2, 6, 7, 3}; req_trellis[7] = { 0, 0, 1, 1, 1, 1, 0, 0}; req_trellis[8] = { 4, 0, 1, 5, 6, 2, 3, 7}; req_trellis[9] = { 0, 0, 1, 1, 1, 1, 0, 0}; for (unsigned i = 0; i < req_trellis.size(); i++) if (trellis[i] != req_trellis[i]) throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Unsupported trellis."); } template <typename B, typename R> void Decoder_RSC_BCJR_inter_intra<B,R> ::_load(const R *Y_N) { if (this->buffered_encoding && this->get_simd_inter_frame_level() > 1) { const auto tail = this->tail_length(); constexpr auto n_frames = mipp::nElReg<R>() / 8; const auto frame_size = 2*this->K + tail; std::vector<const R*> frames(n_frames); for (auto f = 0; f < n_frames; f++) frames[f] = Y_N + f*frame_size; tools::Reorderer_static<R,n_frames>::apply(frames, this->sys.data(), this->K + tail/2); for (auto f = 0; f < n_frames; f++) frames[f] = Y_N + f*frame_size + this->K + tail/2; tools::Reorderer_static<R,n_frames>::apply(frames, this->par.data(), this->K + tail/2); } else Decoder_RSC_BCJR<B,R>::_load(Y_N); } template <typename B, typename R> void Decoder_RSC_BCJR_inter_intra<B,R> ::decode_siso(const mipp::vector<R> &sys, const mipp::vector<R> &par, mipp::vector<R> &ext, const int n_frames) { if (n_frames != -1 && n_frames <= 0) { std::stringstream message; message << "'n_frames' has to be greater than 0 or equal to -1 ('n_frames' = " << n_frames << ")."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } const int real_n_frames = (n_frames != -1) ? n_frames : this->get_n_frames(); if (real_n_frames != this->simd_inter_frame_level_siso) { std::stringstream message; message << "'real_n_frames' has to be equal to 'simd_inter_frame_level_siso' ('real_n_frames' = " << real_n_frames << ", 'simd_inter_frame_level_siso' = " << this->simd_inter_frame_level_siso << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } const auto limit_size1 = (this->K + this->n_ff) * this->simd_inter_frame_level + mipp::nElReg<R>(); if ((int)sys.size() < limit_size1) { std::stringstream message; message << "'sys.size()' has to be equal or greater than 'limit_size1' ('sys.size()' = " << sys.size() << ", 'limit_size1' = " << limit_size1 << ")."; throw tools::length_error(__FILE__, __LINE__, __func__, message.str()); } if ((int)par.size() < limit_size1) { std::stringstream message; message << "'par.size()' has to be equal or greater than 'limit_size1' ('par.size()' = " << par.size() << ", 'limit_size1' = " << limit_size1 << ")."; throw tools::length_error(__FILE__, __LINE__, __func__, message.str()); } const auto limit_size2 = this->K * this->simd_inter_frame_level + mipp::nElReg<R>(); if ((int)ext.size() < limit_size2) { std::stringstream message; message << "'ext.size()' has to be equal or greater than 'limit_size2' * 'real_n_frames' ('ext.size()' = " << ext.size() << ", 'limit_size2' = " << limit_size2 << ", 'real_n_frames' = " << real_n_frames << ")."; throw tools::length_error(__FILE__, __LINE__, __func__, message.str()); } Decoder_SISO<R>::decode_siso(sys.data(), par.data(), ext.data(), real_n_frames); } template <typename B, typename R> void Decoder_RSC_BCJR_inter_intra<B,R> ::_decode_siso(const R *sys, const R *par, R *ext, const int frame_id) { if (!mipp::isAligned(sys)) throw tools::runtime_error(__FILE__, __LINE__, __func__, "'sys' is misaligned memory."); if (!mipp::isAligned(par)) throw tools::runtime_error(__FILE__, __LINE__, __func__, "'par' is misaligned memory."); if (!mipp::isAligned(ext)) throw tools::runtime_error(__FILE__, __LINE__, __func__, "'ext' is misaligned memory."); this->compute_gamma (sys, par); this->compute_alpha ( ); this->compute_beta_ext(sys, ext); } template <typename B, typename R> void Decoder_RSC_BCJR_inter_intra<B,R> ::_store(B *V_K) const { if (this->get_simd_inter_frame_level() > 1) { constexpr auto n_frames = mipp::nElReg<B>() / 8; std::vector<B*> frames(n_frames); for (auto f = 0; f < n_frames; f++) frames[f] = V_K + f*this->K; tools::Reorderer_static<B,n_frames>::apply_rev(this->s.data(), frames, this->K); } else Decoder_RSC_BCJR<B,R>::_store(V_K); } // =================================================================================================== sys/par division template <typename R> struct RSC_BCJR_inter_intra_div_or_not { static mipp::Reg<R> apply(mipp::Reg<R> r) { return mipp::div2(r); } }; template <> struct RSC_BCJR_inter_intra_div_or_not <short> { static mipp::Reg<short> apply(mipp::Reg<short> r) { // (WW) work only for max-log-MAP !!! return r; } }; // ====================================================================================================== post division template <typename R> struct RSC_BCJR_inter_intra_post { static mipp::Reg<R> compute(const mipp::Reg<R> &r_post) { return r_post; } }; template <> struct RSC_BCJR_inter_intra_post <short> { static mipp::Reg<short> compute(const mipp::Reg<short> &r_post) { // (WW) work only for max-log-MAP !!! return mipp::div2(r_post); } }; template <> struct RSC_BCJR_inter_intra_post <signed char> { static mipp::Reg<signed char> compute(const mipp::Reg<signed char> &r_post) { return r_post.sat(-63, 63); } }; // ====================================================================================================== normalization template <typename R> struct RSC_BCJR_inter_intra_normalize_core { static mipp::Reg<R> apply(const mipp::Reg<R> &r_metrics, const mipp::Reg<R> &r_cmask_norm) { const auto r_norm = r_metrics.shuff2(r_cmask_norm); return r_metrics - r_norm; } }; template <typename R, int I = -1> struct RSC_BCJR_inter_intra_normalize { static mipp::Reg<R> apply(const mipp::Reg<R> &r_metrics, const mipp::Reg<R> &r_cmask_norm, const int &i = 0) { return r_metrics; } }; template <> struct RSC_BCJR_inter_intra_normalize <short, -1> { static mipp::Reg<short> apply(const mipp::Reg<short> &r_metrics, const mipp::Reg<short> &r_cmask_norm, const int &i = 0) { if (i % 4 == 0) return RSC_BCJR_inter_intra_normalize_core<short>::apply(r_metrics, r_cmask_norm); else return r_metrics; } }; template <> struct RSC_BCJR_inter_intra_normalize <short, 3> { static mipp::Reg<short> apply(const mipp::Reg<short> &r_metrics, const mipp::Reg<short> &r_cmask_norm, const int &i = 0) { return RSC_BCJR_inter_intra_normalize_core<short>::apply(r_metrics, r_cmask_norm); } }; template <int I> struct RSC_BCJR_inter_intra_normalize <signed char, I> { static mipp::Reg<signed char> apply(const mipp::Reg<signed char> &r_metrics, const mipp::Reg<signed char> &r_cmask_norm, const int &i = 0) { return RSC_BCJR_inter_intra_normalize_core<signed char>::apply(r_metrics, r_cmask_norm); } }; } }
32.164706
139
0.631675
[ "vector" ]
a301ad06152be7e8fdbaa6f03698d61908d4f128
1,327
cpp
C++
DetectorDescription/RegressionTest/test/reg_rot.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DetectorDescription/RegressionTest/test/reg_rot.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DetectorDescription/RegressionTest/test/reg_rot.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <iostream> #include <vector> #include <cmath> #include "CLHEP/Vector/ThreeVector.h" #include "CLHEP/Vector/Rotation.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" using namespace std; /* print a rotationmatrix in phiX, thetaX, phiY, ... representation when given in an (rotation-axis, rotation-angle)-representation */ int main() { double phi,theta,alpha; cout << " axis: phi[deg]="; cin >> phi; phi = phi*deg; cout << " axis: theta[deg]="; cin >> theta; theta = theta*deg; cout << " angle: alpha[deg]="; cin >> alpha; alpha = alpha*deg; cout << endl; CLHEP::Hep3Vector axis; axis[0] = cos(phi)*sin(theta); axis[1] = sin(phi)*sin(theta); axis[2] = cos(theta); cout << " axis: (" << axis[0] << ',' << axis[1] << ',' << axis[2] << ')' << endl; CLHEP::HepRotation rot(axis,alpha); cout << endl; cout << "<Rotation name=\"YourNameHere\"" << endl; cout << " phiX=\"" << rot.phiX()/deg << "*deg\"" << endl; cout << " thetaX=\"" << rot.thetaX()/deg << "*deg\"" << endl; cout << " phiY=\"" << rot.phiY()/deg << "*deg\"" << endl; cout << " thetaY=\"" << rot.thetaY()/deg << "*deg\"" << endl; cout << " phiZ=\"" << rot.phiZ()/deg << "*deg\"" << endl; cout << " thetaZ=\"" << rot.thetaZ()/deg << "*deg\"/>" << endl; return 0; }
32.365854
66
0.546345
[ "vector" ]
a302d0424fe27243f7e0c3c97a0ab5776f23a325
8,671
hpp
C++
src/core/reference/include/ngraph/runtime/reference/deformable_psroi_pooling.hpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
ngraph/core/reference/include/ngraph/runtime/reference/deformable_psroi_pooling.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
ngraph/core/reference/include/ngraph/runtime/reference/deformable_psroi_pooling.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // DeformablePSROIPooling implementation was inspired by // https://github.com/msracver/Deformable-ConvNets // Copyright (c) 2017 Microsoft // SPDX-License-Identifier: MIT #pragma once #include <cfenv> #include <cmath> #include <string> #include <vector> #include "clamp.hpp" #include "ngraph/shape.hpp" namespace ngraph { namespace runtime { namespace reference { template <typename T> void deformable_psroi_pooling(const T* data_input, const Shape& data_input_shape, const T* rois_input, const Shape& rois_input_shape, const T* offsets_input, const Shape& offsets_input_shape, T* output, const Shape& output_shape, const std::string& mode_str, const float spatial_scale, const int64_t spatial_bins_x, const int64_t spatial_bins_y, const float trans_std, const int64_t part_size) { const size_t channels_in = data_input_shape[1]; const size_t height_in = data_input_shape[2]; const size_t width_in = data_input_shape[3]; const size_t rois_count = output_shape[0]; const size_t channels_out = output_shape[1]; const size_t height_out = output_shape[2]; const size_t width_out = output_shape[3]; std::fill(output, output + shape_size(output_shape), T{0}); // Single ROI is described by (batch_id, x1, y1, x2, y2) const size_t roi_attrs_count = 5; for (size_t roi_idx = 0; roi_idx < rois_count; ++roi_idx) { // Pointer to the beginning of the ROI coords tuple const T* roi = rois_input + roi_idx * roi_attrs_count; // Index of the corresponding input batch int64_t roi_batch_id = roi[0]; if (roi_batch_id < 0) continue; // Left top ROI corner const float roi_x1 = static_cast<float>(std::round(roi[1])) * spatial_scale - 0.5f; const float roi_y1 = static_cast<float>(std::round(roi[2])) * spatial_scale - 0.5f; // Right down ROI corner const float roi_x2 = static_cast<float>(std::round(roi[3]) + 1.0f) * spatial_scale - 0.5f; const float roi_y2 = static_cast<float>(std::round(roi[4]) + 1.0f) * spatial_scale - 0.5f; const float roi_width = std::max<float>(roi_x2 - roi_x1, 0.1f); const float roi_height = std::max<float>(roi_y2 - roi_y1, 0.1f); const float bin_width = roi_width / static_cast<float>(width_out); const float bin_height = roi_height / static_cast<float>(height_out); size_t c_idx_in = 0; for (size_t c_idx_out = 0; c_idx_out < channels_out; ++c_idx_out) { for (size_t h_idx_out = 0; h_idx_out < height_out; ++h_idx_out) { // Next bin is taken from the next input channel for (size_t w_idx_out = 0; w_idx_out < width_out; ++w_idx_out, ++c_idx_in) { const size_t out_value_idx = ((roi_idx * channels_out + c_idx_out) * height_out + h_idx_out) * width_out + w_idx_out; // Left top corner of bin float bin_x1_idx = roi_x1 + w_idx_out * bin_width; float bin_y1_idx = roi_y1 + h_idx_out * bin_height; // Take offsets from optional input if (offsets_input != nullptr && offsets_input_shape.size() == 4) { const auto num_coords = 2; // (x, y) const size_t coords_sub_channels = offsets_input_shape[1] / num_coords; const size_t class_sub_channels = channels_out / coords_sub_channels; const size_t roi_channel_idx = c_idx_out / class_sub_channels; const size_t off_bin_w_idx = w_idx_out * part_size / width_out; const size_t off_bin_h_idx = h_idx_out * part_size / height_out; const size_t offsets_channel_idx = (roi_idx * coords_sub_channels + roi_channel_idx) * num_coords; const size_t x_offset_idx = (offsets_channel_idx * part_size + off_bin_h_idx) * part_size + off_bin_w_idx; const size_t y_offset_idx = ((offsets_channel_idx + 1) * part_size + off_bin_h_idx) * part_size + off_bin_w_idx; T x_offset_value = offsets_input[x_offset_idx]; T y_offset_value = offsets_input[y_offset_idx]; x_offset_value *= trans_std; y_offset_value *= trans_std; // Move bin position by normalized offset values bin_x1_idx += (x_offset_value * roi_width); bin_y1_idx += (y_offset_value * roi_height); } // Each bin is divided into sub-bins // Values of sub-bins are calculated by bilinear interpolation // Value of single bin is average of its sub-bins const float sub_bin_width = bin_width / static_cast<float>(spatial_bins_x); const float sub_bin_height = bin_height / static_cast<float>(spatial_bins_y); T sub_bins_val_sum = 0; size_t legit_sub_bin_count = 0; for (int sub_bin_h_idx = 0; sub_bin_h_idx < spatial_bins_y; ++sub_bin_h_idx) { float sub_bin_y1_idx = bin_y1_idx + sub_bin_h_idx * sub_bin_height; if (sub_bin_y1_idx < -0.5 || sub_bin_y1_idx > height_in - 0.5) continue; for (int sub_bin_w_idx = 0; sub_bin_w_idx < spatial_bins_x; ++sub_bin_w_idx) { float sub_bin_x1_idx = bin_x1_idx + sub_bin_w_idx * sub_bin_width; if (sub_bin_x1_idx < -0.5 || sub_bin_x1_idx > width_in - 0.5) continue; clamp(&sub_bin_x1_idx, &sub_bin_x1_idx, 0.f, width_in - 1.f, 1); clamp(&sub_bin_y1_idx, &sub_bin_y1_idx, 0.f, height_in - 1.f, 1); // Calculate value for sub-bin by bilinear interpolation const int64_t left_x = static_cast<int64_t>(std::floor(sub_bin_x1_idx)); const int64_t right_x = static_cast<int64_t>(std::ceil(sub_bin_x1_idx)); const int64_t top_y = static_cast<int64_t>(std::floor(sub_bin_y1_idx)); const int64_t bottom_y = static_cast<int64_t>(std::ceil(sub_bin_y1_idx)); const T* data_channel_ptr = data_input + (roi_batch_id * channels_in + c_idx_in) * height_in * width_in; const T top_left_sample = data_channel_ptr[top_y * width_in + left_x]; const T top_right_sample = data_channel_ptr[top_y * width_in + right_x]; const T bottom_left_sample = data_channel_ptr[bottom_y * width_in + left_x]; const T bottom_right_sample = data_channel_ptr[bottom_y * width_in + right_x]; const float delta_left_x = std::fabs(sub_bin_x1_idx - left_x); const float delta_top_y = std::fabs(sub_bin_y1_idx - top_y); const T top_interp = top_left_sample + (top_right_sample - top_left_sample) * delta_left_x; const T bottom_interp = bottom_left_sample + (bottom_right_sample - bottom_left_sample) * delta_left_x; const T sub_bin_value = top_interp + (bottom_interp - top_interp) * delta_top_y; legit_sub_bin_count++; sub_bins_val_sum += sub_bin_value; } } // Calculate average of sub_bin values for single ROI bin if (legit_sub_bin_count != 0) { output[out_value_idx] = sub_bins_val_sum / legit_sub_bin_count; } } } } } } } // namespace reference } // namespace runtime } // namespace ngraph
49.548571
119
0.55553
[ "shape", "vector" ]
a30336ba2c6f924d578ae5ed51e4b8ace16cb607
101,879
cpp
C++
Plugins/org.mitk.gui.qt.diffusionimaging.fiberfox/src/internal/QmitkFiberfoxView.cpp
HRS-Navigation/MITK-Diffusion
b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87
[ "BSD-3-Clause" ]
37
2019-07-05T10:55:06.000Z
2022-03-21T12:09:35.000Z
Plugins/org.mitk.gui.qt.diffusionimaging.fiberfox/src/internal/QmitkFiberfoxView.cpp
HRS-Navigation/MITK-Diffusion
b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87
[ "BSD-3-Clause" ]
6
2019-11-04T16:05:47.000Z
2022-03-22T15:53:31.000Z
Plugins/org.mitk.gui.qt.diffusionimaging.fiberfox/src/internal/QmitkFiberfoxView.cpp
HRS-Navigation/MITK-Diffusion
b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87
[ "BSD-3-Clause" ]
10
2019-10-15T14:37:26.000Z
2022-02-18T03:22:01.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "QmitkFiberfoxView.h" // MITK #include <mitkImage.h> #include <mitkImageToItk.h> #include <mitkImageCast.h> #include <mitkProperties.h> #include <mitkPlanarFigureInteractor.h> #include <mitkDataStorage.h> #include <itkTractsToDWIImageFilter.h> #include <mitkTensorImage.h> #include <mitkILinkedRenderWindowPart.h> #include <mitkImageToItk.h> #include <mitkImageCast.h> #include <mitkImageGenerator.h> #include <mitkNodePredicateDataType.h> #include <itkScalableAffineTransform.h> #include <mitkLevelWindowProperty.h> #include <mitkNodePredicateOr.h> #include <mitkNodePredicateAnd.h> #include <mitkNodePredicateNot.h> #include <mitkNodePredicateProperty.h> #include <mitkNodePredicateIsDWI.h> #include <boost/property_tree/ptree.hpp> #define RAPIDXML_NO_EXCEPTIONS #include <boost/property_tree/xml_parser.hpp> #include <boost/foreach.hpp> #include <QFileDialog> #include <QMessageBox> #include "usModuleRegistry.h" #include <mitkChiSquareNoiseModel.h> #include <itksys/SystemTools.hxx> #include <mitkIOUtil.h> #include <QScrollBar> #include <itkInvertIntensityImageFilter.h> #include <QDialogButtonBox> #include <itkAdcImageFilter.h> #include <itkShiftScaleImageFilter.h> #include <mitkITKImageImport.h> #include "mitkNodePredicateDataType.h" #include <mitkNodePredicateProperty.h> #include <mitkNodePredicateAnd.h> #include <mitkNodePredicateNot.h> #include <mitkNodePredicateOr.h> QmitkFiberfoxWorker::QmitkFiberfoxWorker(QmitkFiberfoxView* view) : m_View(view) { } void QmitkFiberfoxWorker::run() { try{ m_View->m_TractsToDwiFilter->Update(); } catch( ... ) { } m_View->m_Thread.quit(); } const std::string QmitkFiberfoxView::VIEW_ID = "org.mitk.views.fiberfoxview"; QmitkFiberfoxView::QmitkFiberfoxView() : QmitkAbstractView() , m_Controls( 0 ) , m_SelectedImageNode( nullptr ) , m_Worker(this) , m_ThreadIsRunning(false) { m_Worker.moveToThread(&m_Thread); connect(&m_Thread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_Thread, SIGNAL(started()), &m_Worker, SLOT(run())); connect(&m_Thread, SIGNAL(finished()), this, SLOT(AfterThread())); // connect(&m_Thread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_SimulationTimer = new QTimer(this); } void QmitkFiberfoxView::KillThread() { MITK_INFO << "Aborting DWI simulation."; m_TractsToDwiFilter->SetAbortGenerateData(true); m_Controls->m_AbortSimulationButton->setEnabled(false); m_Controls->m_AbortSimulationButton->setText("Aborting simulation ..."); } void QmitkFiberfoxView::BeforeThread() { m_SimulationTime = QTime::currentTime(); m_SimulationTimer->start(100); m_Controls->m_AbortSimulationButton->setVisible(true); m_Controls->m_GenerateImageButton->setVisible(false); m_Controls->m_SimulationStatusText->setVisible(true); m_ThreadIsRunning = true; } void QmitkFiberfoxView::AfterThread() { UpdateSimulationStatus(); m_SimulationTimer->stop(); m_Controls->m_AbortSimulationButton->setVisible(false); m_Controls->m_AbortSimulationButton->setEnabled(true); m_Controls->m_AbortSimulationButton->setText("Abort simulation"); m_Controls->m_GenerateImageButton->setVisible(true); m_ThreadIsRunning = false; QString statusText; FiberfoxParameters parameters; mitk::Image::Pointer mitkImage = mitk::Image::New(); statusText = QString(m_TractsToDwiFilter->GetStatusText().c_str()); if (m_TractsToDwiFilter->GetAbortGenerateData()) { MITK_INFO << "Simulation aborted."; return; } parameters = m_TractsToDwiFilter->GetParameters(); mitkImage = mitk::GrabItkImageMemory( m_TractsToDwiFilter->GetOutput() ); if (parameters.m_SignalGen.GetNumWeightedVolumes() > 0) { mitk::DiffusionPropertyHelper::SetGradientContainer(mitkImage, parameters.m_SignalGen.GetItkGradientContainer()); mitk::DiffusionPropertyHelper::SetReferenceBValue(mitkImage, parameters.m_SignalGen.GetBvalue()); mitk::DiffusionPropertyHelper::InitializeImage( mitkImage ); } parameters.m_Misc.m_ResultNode->SetData( mitkImage ); GetDataStorage()->Add(parameters.m_Misc.m_ResultNode, parameters.m_Misc.m_ParentNode); if (m_Controls->m_VolumeFractionsBox->isChecked()) { if (m_TractsToDwiFilter->GetTickImage().IsNotNull()) { mitk::Image::Pointer mitkImage = mitk::Image::New(); itk::TractsToDWIImageFilter< short >::Float2DImageType::Pointer itkImage = m_TractsToDwiFilter->GetTickImage(); mitkImage = mitk::GrabItkImageMemory( itkImage.GetPointer() ); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( mitkImage ); node->SetName("Tick Image"); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); } if (m_TractsToDwiFilter->GetRfImage().IsNotNull()) { mitk::Image::Pointer mitkImage = mitk::Image::New(); itk::TractsToDWIImageFilter< short >::Float2DImageType::Pointer itkImage = m_TractsToDwiFilter->GetRfImage(); mitkImage = mitk::GrabItkImageMemory( itkImage.GetPointer() ); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( mitkImage ); node->SetName("RF Image"); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); } if (m_TractsToDwiFilter->GetPhaseImage().IsNotNull()) { mitk::Image::Pointer phaseImage = mitk::Image::New(); itk::TractsToDWIImageFilter< short >::DoubleDwiType::Pointer itkPhase = m_TractsToDwiFilter->GetPhaseImage(); phaseImage = mitk::GrabItkImageMemory( itkPhase.GetPointer() ); mitk::DataNode::Pointer phaseNode = mitk::DataNode::New(); phaseNode->SetData( phaseImage ); phaseNode->SetName("Phase Image"); GetDataStorage()->Add(phaseNode, parameters.m_Misc.m_ResultNode); } if (m_TractsToDwiFilter->GetKspaceImage().IsNotNull()) { mitk::Image::Pointer image = mitk::Image::New(); itk::TractsToDWIImageFilter< short >::DoubleDwiType::Pointer itkImage = m_TractsToDwiFilter->GetKspaceImage(); image = mitk::GrabItkImageMemory( itkImage.GetPointer() ); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("k-Space"); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); } { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(m_TractsToDwiFilter->GetCoilPointset()); node->SetName("Coil Positions"); node->SetProperty("pointsize", mitk::FloatProperty::New(parameters.m_SignalGen.m_ImageSpacing[0]/4)); node->SetProperty("color", mitk::ColorProperty::New(0, 1, 0)); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); } int c = 1; std::vector< itk::TractsToDWIImageFilter< short >::DoubleDwiType::Pointer > output_real = m_TractsToDwiFilter->GetOutputImagesReal(); for (auto real : output_real) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(real.GetPointer()); image->SetVolume(real->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Coil-"+QString::number(c).toStdString()+"-real"); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); ++c; } c = 1; std::vector< itk::TractsToDWIImageFilter< short >::DoubleDwiType::Pointer > output_imag = m_TractsToDwiFilter->GetOutputImagesImag(); for (auto imag : output_imag) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(imag.GetPointer()); image->SetVolume(imag->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Coil-"+QString::number(c).toStdString()+"-imag"); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); ++c; } std::vector< itk::TractsToDWIImageFilter< short >::ItkDoubleImgType::Pointer > volumeFractions = m_TractsToDwiFilter->GetVolumeFractions(); for (unsigned int k=0; k<volumeFractions.size(); k++) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(volumeFractions.at(k).GetPointer()); image->SetVolume(volumeFractions.at(k)->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("CompartmentVolume-"+QString::number(k).toStdString()); GetDataStorage()->Add(node, parameters.m_Misc.m_ResultNode); } } m_TractsToDwiFilter = nullptr; if (parameters.m_Misc.m_AfterSimulationMessage.size()>0) QMessageBox::information( nullptr, "Warning", parameters.m_Misc.m_AfterSimulationMessage.c_str()); mitk::BaseData::Pointer basedata = parameters.m_Misc.m_ResultNode->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if (!parameters.m_Misc.m_OutputPath.empty()) { try{ QString outputFileName(parameters.m_Misc.m_OutputPath.c_str()); outputFileName += parameters.m_Misc.m_ResultNode->GetName().c_str(); outputFileName.replace(QString("."), QString("_")); SaveParameters(outputFileName+".ffp"); outputFileName += ".dwi"; QString status("Saving output image to "); status += outputFileName; m_Controls->m_SimulationStatusText->append(status); mitk::IOUtil::Save(mitkImage, outputFileName.toStdString()); m_Controls->m_SimulationStatusText->append("File saved successfully."); } catch (itk::ExceptionObject &e) { QString status("Exception during DWI writing: "); status += e.GetDescription(); m_Controls->m_SimulationStatusText->append(status); } catch (...) { m_Controls->m_SimulationStatusText->append("Unknown exception during DWI writing!"); } } parameters.m_SignalGen.m_FrequencyMap = nullptr; } void QmitkFiberfoxView::UpdateSimulationStatus() { QString statusText = QString(m_TractsToDwiFilter->GetStatusText().c_str()); if (QString::compare(m_SimulationStatusText,statusText)!=0) { m_Controls->m_SimulationStatusText->clear(); m_Controls->m_SimulationStatusText->setText(statusText); QScrollBar *vScrollBar = m_Controls->m_SimulationStatusText->verticalScrollBar(); vScrollBar->triggerAction(QScrollBar::SliderToMaximum); } } // Destructor QmitkFiberfoxView::~QmitkFiberfoxView() { delete m_SimulationTimer; } void QmitkFiberfoxView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkFiberfoxViewControls; m_Controls->setupUi( parent ); m_Controls->m_StickWidget1->setVisible(true); m_Controls->m_StickWidget2->setVisible(false); m_Controls->m_ZeppelinWidget1->setVisible(false); m_Controls->m_ZeppelinWidget2->setVisible(false); m_Controls->m_TensorWidget1->setVisible(false); m_Controls->m_TensorWidget2->setVisible(false); m_Controls->m_BallWidget1->setVisible(true); m_Controls->m_BallWidget2->setVisible(false); m_Controls->m_BallWidget2->SetT1(4658); m_Controls->m_BallWidget2->SetT2(2200); m_Controls->m_AstrosticksWidget1->setVisible(false); m_Controls->m_AstrosticksWidget2->setVisible(false); m_Controls->m_AstrosticksWidget2->SetT1(4658); m_Controls->m_AstrosticksWidget2->SetT2(2200); m_Controls->m_DotWidget1->setVisible(false); m_Controls->m_DotWidget2->setVisible(false); m_Controls->m_DotWidget2->SetT1(4658); m_Controls->m_DotWidget2->SetT2(2200); m_Controls->m_PrototypeWidget1->setVisible(false); m_Controls->m_PrototypeWidget2->setVisible(false); m_Controls->m_PrototypeWidget3->setVisible(false); m_Controls->m_PrototypeWidget4->setVisible(false); m_Controls->m_PrototypeWidget3->SetMinFa(0.0); m_Controls->m_PrototypeWidget3->SetMaxFa(0.15); m_Controls->m_PrototypeWidget4->SetMinFa(0.0); m_Controls->m_PrototypeWidget4->SetMaxFa(0.15); m_Controls->m_PrototypeWidget3->SetMinAdc(0.0); m_Controls->m_PrototypeWidget3->SetMaxAdc(0.001); m_Controls->m_PrototypeWidget4->SetMinAdc(0.003); m_Controls->m_PrototypeWidget4->SetMaxAdc(0.004); m_Controls->m_Comp2FractionFrame->setVisible(false); m_Controls->m_Comp4FractionFrame->setVisible(false); m_Controls->m_DiffusionPropsMessage->setVisible(false); m_Controls->m_GeometryMessage->setVisible(false); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(false); m_Controls->m_NoiseFrame->setVisible(false); m_Controls->m_ZeroRinging->setVisible(false); m_Controls->m_GhostFrame->setVisible(false); m_Controls->m_DistortionsFrame->setVisible(false); m_Controls->m_EddyFrame->setVisible(false); m_Controls->m_SpikeFrame->setVisible(false); m_Controls->m_AliasingFrame->setVisible(false); m_Controls->m_MotionArtifactFrame->setVisible(false); m_Controls->m_DriftFrame->setVisible(false); m_ParameterFile = QDir::currentPath()+"/param.ffp"; m_Controls->m_AbortSimulationButton->setVisible(false); m_Controls->m_SimulationStatusText->setVisible(false); m_Controls->m_FrequencyMapBox->SetDataStorage(this->GetDataStorage()); m_Controls->m_Comp1VolumeFraction->SetDataStorage(this->GetDataStorage()); m_Controls->m_Comp2VolumeFraction->SetDataStorage(this->GetDataStorage()); m_Controls->m_Comp3VolumeFraction->SetDataStorage(this->GetDataStorage()); m_Controls->m_Comp4VolumeFraction->SetDataStorage(this->GetDataStorage()); m_Controls->m_MaskComboBox->SetDataStorage(this->GetDataStorage()); m_Controls->m_TemplateComboBox->SetDataStorage(this->GetDataStorage()); m_Controls->m_FiberBundleComboBox->SetDataStorage(this->GetDataStorage()); mitk::TNodePredicateDataType<mitk::FiberBundle>::Pointer isFiberBundle = mitk::TNodePredicateDataType<mitk::FiberBundle>::New(); mitk::TNodePredicateDataType<mitk::Image>::Pointer isMitkImage = mitk::TNodePredicateDataType<mitk::Image>::New(); mitk::NodePredicateIsDWI::Pointer isDwi = mitk::NodePredicateIsDWI::New( ); mitk::NodePredicateDataType::Pointer isDti = mitk::NodePredicateDataType::New("TensorImage"); mitk::NodePredicateDataType::Pointer isOdf = mitk::NodePredicateDataType::New("Odfmage"); mitk::NodePredicateOr::Pointer isDiffusionImage = mitk::NodePredicateOr::New(isDwi, isDti); isDiffusionImage = mitk::NodePredicateOr::New(isDiffusionImage, isOdf); mitk::NodePredicateNot::Pointer noDiffusionImage = mitk::NodePredicateNot::New(isDiffusionImage); mitk::NodePredicateAnd::Pointer isNonDiffMitkImage = mitk::NodePredicateAnd::New(isMitkImage, noDiffusionImage); mitk::NodePredicateProperty::Pointer isBinaryPredicate = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); mitk::NodePredicateAnd::Pointer isBinaryMitkImage = mitk::NodePredicateAnd::New( isNonDiffMitkImage, isBinaryPredicate ); m_Controls->m_FrequencyMapBox->SetPredicate(isNonDiffMitkImage); m_Controls->m_Comp1VolumeFraction->SetPredicate(isNonDiffMitkImage); m_Controls->m_Comp1VolumeFraction->SetZeroEntryText("--"); m_Controls->m_Comp2VolumeFraction->SetPredicate(isNonDiffMitkImage); m_Controls->m_Comp2VolumeFraction->SetZeroEntryText("--"); m_Controls->m_Comp3VolumeFraction->SetPredicate(isNonDiffMitkImage); m_Controls->m_Comp3VolumeFraction->SetZeroEntryText("--"); m_Controls->m_Comp4VolumeFraction->SetPredicate(isNonDiffMitkImage); m_Controls->m_Comp4VolumeFraction->SetZeroEntryText("--"); m_Controls->m_MaskComboBox->SetPredicate(isBinaryMitkImage); m_Controls->m_MaskComboBox->SetZeroEntryText("--"); m_Controls->m_TemplateComboBox->SetPredicate(isMitkImage); m_Controls->m_TemplateComboBox->SetZeroEntryText("--"); m_Controls->m_FiberBundleComboBox->SetPredicate(isFiberBundle); m_Controls->m_FiberBundleComboBox->SetZeroEntryText("--"); QFont font; font.setFamily("Courier"); font.setStyleHint(QFont::Monospace); font.setFixedPitch(true); font.setPointSize(7); m_Controls->m_SimulationStatusText->setFont(font); connect( m_SimulationTimer, SIGNAL(timeout()), this, SLOT(UpdateSimulationStatus()) ); connect((QObject*) m_Controls->m_AbortSimulationButton, SIGNAL(clicked()), (QObject*) this, SLOT(KillThread())); connect((QObject*) m_Controls->m_GenerateImageButton, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateImage())); connect((QObject*) m_Controls->m_AddNoise, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddNoise(int))); connect((QObject*) m_Controls->m_AddGhosts, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddGhosts(int))); connect((QObject*) m_Controls->m_AddDistortions, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddDistortions(int))); connect((QObject*) m_Controls->m_AddEddy, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddEddy(int))); connect((QObject*) m_Controls->m_AddSpikes, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddSpikes(int))); connect((QObject*) m_Controls->m_AddAliasing, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddAliasing(int))); connect((QObject*) m_Controls->m_AddMotion, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddMotion(int))); connect((QObject*) m_Controls->m_AddDrift, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddDrift(int))); connect((QObject*) m_Controls->m_AddGibbsRinging, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddRinging(int))); connect((QObject*) m_Controls->m_Compartment1Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp1ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment2Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp2ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment3Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp3ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment4Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp4ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_AdvancedOptionsBox_2, SIGNAL( stateChanged(int)), (QObject*) this, SLOT(ShowAdvancedOptions(int))); connect((QObject*) m_Controls->m_UseBvalsBvecsBox, SIGNAL( stateChanged(int)), (QObject*) this, SLOT(OnBvalsBvecsCheck(int))); connect((QObject*) m_Controls->m_SaveParametersButton, SIGNAL(clicked()), (QObject*) this, SLOT(SaveParameters())); connect((QObject*) m_Controls->m_LoadParametersButton, SIGNAL(clicked()), (QObject*) this, SLOT(LoadParameters())); connect((QObject*) m_Controls->m_OutputPathButton, SIGNAL(clicked()), (QObject*) this, SLOT(SetOutputPath())); connect((QObject*) m_Controls->m_LoadBvalsButton, SIGNAL(clicked()), (QObject*) this, SLOT(SetBvalsEdit())); connect((QObject*) m_Controls->m_LoadBvecsButton, SIGNAL(clicked()), (QObject*) this, SLOT(SetBvecsEdit())); connect((QObject*) m_Controls->m_MaskComboBox, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(OnMaskSelected(int))); connect((QObject*) m_Controls->m_TemplateComboBox, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(OnTemplateSelected(int))); connect((QObject*) m_Controls->m_FiberBundleComboBox, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(OnFibSelected(int))); connect((QObject*) m_Controls->m_LineReadoutTimeBox, SIGNAL( valueChanged(double)), (QObject*) this, SLOT(OnTlineChanged())); connect((QObject*) m_Controls->m_SizeX, SIGNAL( valueChanged(int)), (QObject*) this, SLOT(OnTlineChanged())); } OnTlineChanged(); UpdateGui(); } void QmitkFiberfoxView::OnTlineChanged() { double num_pix_line = 0; if (m_Controls->m_TemplateComboBox->GetSelectedNode().IsNotNull()) // use geometry of selected image { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()); num_pix_line = img->GetDimension(0); } else if (m_Controls->m_MaskComboBox->GetSelectedNode().IsNotNull()) // use geometry of mask image { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(m_Controls->m_MaskComboBox->GetSelectedNode()->GetData()); num_pix_line = img->GetDimension(0); } else { num_pix_line = m_Controls->m_SizeX->value(); } double value = static_cast<double>(m_Controls->m_LineReadoutTimeBox->value())/1000.0; // line readout time in seconds double dweel_pp = value/num_pix_line; // pixel readout time in seconds double bw = 1/dweel_pp; double bw_pp = bw/num_pix_line; std::string tt = "Bandwidth:\n" + boost::lexical_cast<std::string>(itk::Math::Round<int, double>(bw)) + "Hz\n" + boost::lexical_cast<std::string>(itk::Math::Round<int, double>(bw_pp)) + "Hz/Px"; m_Controls->m_LineReadoutTimeBox->setToolTip(tt.c_str()); } void QmitkFiberfoxView::OnMaskSelected(int ) { UpdateGui(); } void QmitkFiberfoxView::OnTemplateSelected(int ) { UpdateGui(); } void QmitkFiberfoxView::OnFibSelected(int ) { UpdateGui(); } void QmitkFiberfoxView::OnBvalsBvecsCheck(int ) { UpdateGui(); } void QmitkFiberfoxView::UpdateParametersFromGui() { m_Parameters.ClearSignalParameters(); m_Parameters.m_Misc.m_CheckAdvancedSignalOptionsBox = m_Controls->m_AdvancedOptionsBox_2->isChecked(); m_Parameters.m_Misc.m_OutputAdditionalImages = m_Controls->m_VolumeFractionsBox->isChecked(); std::string outputPath = m_Controls->m_SavePathEdit->text().toStdString(); if (outputPath.compare("-")!=0) { m_Parameters.m_Misc.m_OutputPath = outputPath; m_Parameters.m_Misc.m_OutputPath += "/"; } else { m_Parameters.m_Misc.m_OutputPath = ""; } if (m_Controls->m_MaskComboBox->GetSelectedNode().IsNotNull()) { mitk::Image::Pointer mitkMaskImage = dynamic_cast<mitk::Image*>(m_Controls->m_MaskComboBox->GetSelectedNode()->GetData()); mitk::CastToItkImage<ItkUcharImgType>(mitkMaskImage, m_Parameters.m_SignalGen.m_MaskImage); itk::ImageDuplicator<ItkUcharImgType>::Pointer duplicator = itk::ImageDuplicator<ItkUcharImgType>::New(); duplicator->SetInputImage(m_Parameters.m_SignalGen.m_MaskImage); duplicator->Update(); m_Parameters.m_SignalGen.m_MaskImage = duplicator->GetOutput(); } if (m_Controls->m_TemplateComboBox->GetSelectedNode().IsNotNull() && mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( m_Controls->m_TemplateComboBox->GetSelectedNode())) // use parameters of selected DWI { mitk::Image::Pointer dwi = dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()); ItkDwiType::Pointer itkVectorImagePointer = ItkDwiType::New(); mitk::CastToItkImage(dwi, itkVectorImagePointer); m_Parameters.m_SignalGen.m_ImageRegion = itkVectorImagePointer->GetLargestPossibleRegion(); m_Parameters.m_SignalGen.m_ImageSpacing = itkVectorImagePointer->GetSpacing(); m_Parameters.m_SignalGen.m_ImageOrigin = itkVectorImagePointer->GetOrigin(); m_Parameters.m_SignalGen.m_ImageDirection = itkVectorImagePointer->GetDirection(); m_Parameters.SetBvalue(mitk::DiffusionPropertyHelper::GetReferenceBValue(dwi)); m_Parameters.SetGradienDirections(mitk::DiffusionPropertyHelper::GetOriginalGradientContainer(dwi)); } else if (m_Controls->m_TemplateComboBox->GetSelectedNode().IsNotNull()) // use geometry of selected image { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()); itk::Image< float, 3 >::Pointer itkImg = itk::Image< float, 3 >::New(); CastToItkImage< itk::Image< float, 3 > >(img, itkImg); m_Parameters.m_SignalGen.m_ImageRegion = itkImg->GetLargestPossibleRegion(); m_Parameters.m_SignalGen.m_ImageSpacing = itkImg->GetSpacing(); m_Parameters.m_SignalGen.m_ImageOrigin = itkImg->GetOrigin(); m_Parameters.m_SignalGen.m_ImageDirection = itkImg->GetDirection(); if (m_Controls->m_UseBvalsBvecsBox->isChecked()) { double bval; m_Parameters.SetGradienDirections( mitk::gradients::ReadBvalsBvecs(m_Controls->m_LoadBvalsEdit->text().toStdString(), m_Controls->m_LoadBvecsEdit->text().toStdString(), bval) ); m_Parameters.SetBvalue(bval); } else { m_Parameters.SetNumWeightedVolumes(m_Controls->m_NumGradientsBox->value()); m_Parameters.SetBvalue(m_Controls->m_BvalueBox->value()); m_Parameters.GenerateGradientHalfShell(); } } else if (m_Parameters.m_SignalGen.m_MaskImage.IsNotNull()) // use geometry of mask image { ItkUcharImgType::Pointer itkImg = m_Parameters.m_SignalGen.m_MaskImage; m_Parameters.m_SignalGen.m_ImageRegion = itkImg->GetLargestPossibleRegion(); m_Parameters.m_SignalGen.m_ImageSpacing = itkImg->GetSpacing(); m_Parameters.m_SignalGen.m_ImageOrigin = itkImg->GetOrigin(); m_Parameters.m_SignalGen.m_ImageDirection = itkImg->GetDirection(); if (m_Controls->m_UseBvalsBvecsBox->isChecked()) { double bval; m_Parameters.SetGradienDirections( mitk::gradients::ReadBvalsBvecs(m_Controls->m_LoadBvalsEdit->text().toStdString(), m_Controls->m_LoadBvecsEdit->text().toStdString(), bval) ); m_Parameters.SetBvalue(bval); } else { m_Parameters.SetNumWeightedVolumes(m_Controls->m_NumGradientsBox->value()); m_Parameters.SetBvalue(m_Controls->m_BvalueBox->value()); m_Parameters.GenerateGradientHalfShell(); } } else // use GUI parameters { m_Parameters.m_SignalGen.m_ImageRegion.SetSize(0, m_Controls->m_SizeX->value()); m_Parameters.m_SignalGen.m_ImageRegion.SetSize(1, m_Controls->m_SizeY->value()); m_Parameters.m_SignalGen.m_ImageRegion.SetSize(2, m_Controls->m_SizeZ->value()); m_Parameters.m_SignalGen.m_ImageSpacing[0] = m_Controls->m_SpacingX->value(); m_Parameters.m_SignalGen.m_ImageSpacing[1] = m_Controls->m_SpacingY->value(); m_Parameters.m_SignalGen.m_ImageSpacing[2] = m_Controls->m_SpacingZ->value(); m_Parameters.m_SignalGen.m_ImageOrigin[0] = m_Parameters.m_SignalGen.m_ImageSpacing[0]/2; m_Parameters.m_SignalGen.m_ImageOrigin[1] = m_Parameters.m_SignalGen.m_ImageSpacing[1]/2; m_Parameters.m_SignalGen.m_ImageOrigin[2] = m_Parameters.m_SignalGen.m_ImageSpacing[2]/2; m_Parameters.m_SignalGen.m_ImageDirection.SetIdentity(); if (m_Controls->m_UseBvalsBvecsBox->isChecked()) { double bval; m_Parameters.SetGradienDirections( mitk::gradients::ReadBvalsBvecs(m_Controls->m_LoadBvalsEdit->text().toStdString(), m_Controls->m_LoadBvecsEdit->text().toStdString(), bval) ); m_Parameters.SetBvalue(bval); } else { m_Parameters.SetNumWeightedVolumes(m_Controls->m_NumGradientsBox->value()); m_Parameters.SetBvalue(m_Controls->m_BvalueBox->value()); m_Parameters.GenerateGradientHalfShell(); } } // signal relaxation m_Parameters.m_SignalGen.m_DoSimulateRelaxation = false; if (m_Controls->m_RelaxationBox->isChecked()) { m_Parameters.m_SignalGen.m_DoSimulateRelaxation = true; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Relaxation", BoolProperty::New(true)); m_Parameters.m_Misc.m_ArtifactModelString += "_RELAX"; } m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = m_Parameters.m_SignalGen.m_DoSimulateRelaxation; // N/2 ghosts m_Parameters.m_Misc.m_DoAddGhosts = m_Controls->m_AddGhosts->isChecked(); m_Parameters.m_SignalGen.m_KspaceLineOffset = m_Controls->m_kOffsetBox->value(); if (m_Controls->m_AddGhosts->isChecked()) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ArtifactModelString += "_GHOST"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Ghost", DoubleProperty::New(m_Parameters.m_SignalGen.m_KspaceLineOffset)); } // Aliasing m_Parameters.m_Misc.m_DoAddAliasing = m_Controls->m_AddAliasing->isChecked(); m_Parameters.m_SignalGen.m_CroppingFactor = (100-m_Controls->m_WrapBox->value())/100; if (m_Controls->m_AddAliasing->isChecked()) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ArtifactModelString += "_ALIASING"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Aliasing", DoubleProperty::New(m_Controls->m_WrapBox->value())); } // Spikes m_Parameters.m_Misc.m_DoAddSpikes = m_Controls->m_AddSpikes->isChecked(); m_Parameters.m_SignalGen.m_Spikes = m_Controls->m_SpikeNumBox->value(); m_Parameters.m_SignalGen.m_SpikeAmplitude = m_Controls->m_SpikeScaleBox->value(); if (m_Controls->m_AddSpikes->isChecked()) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ArtifactModelString += "_SPIKES"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Spikes.Number", IntProperty::New(m_Parameters.m_SignalGen.m_Spikes)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Spikes.Amplitude", DoubleProperty::New(m_Parameters.m_SignalGen.m_SpikeAmplitude)); } // Drift m_Parameters.m_SignalGen.m_DoAddDrift = m_Controls->m_AddDrift->isChecked(); m_Parameters.m_SignalGen.m_Drift = static_cast<float>(m_Controls->m_DriftFactor->value())/100; if (m_Controls->m_AddDrift->isChecked()) { m_Parameters.m_Misc.m_ArtifactModelString += "_DRIFT"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Drift", FloatProperty::New(m_Parameters.m_SignalGen.m_Drift)); } // gibbs ringing m_Parameters.m_SignalGen.m_DoAddGibbsRinging = m_Controls->m_AddGibbsRinging->isChecked(); m_Parameters.m_SignalGen.m_ZeroRinging = m_Controls->m_ZeroRinging->value(); if (m_Controls->m_AddGibbsRinging->isChecked()) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Ringing", BoolProperty::New(true)); m_Parameters.m_Misc.m_ArtifactModelString += "_RINGING"; } // add distortions m_Parameters.m_Misc.m_DoAddDistortions = m_Controls->m_AddDistortions->isChecked(); if (m_Controls->m_AddDistortions->isChecked() && m_Controls->m_FrequencyMapBox->GetSelectedNode().IsNotNull()) { mitk::DataNode::Pointer fMapNode = m_Controls->m_FrequencyMapBox->GetSelectedNode(); mitk::Image* img = dynamic_cast<mitk::Image*>(fMapNode->GetData()); ItkFloatImgType::Pointer itkImg = ItkFloatImgType::New(); CastToItkImage< ItkFloatImgType >(img, itkImg); if (m_Controls->m_TemplateComboBox->GetSelectedNode().IsNull()) // use geometry of frequency map { m_Parameters.m_SignalGen.m_ImageRegion = itkImg->GetLargestPossibleRegion(); m_Parameters.m_SignalGen.m_ImageSpacing = itkImg->GetSpacing(); m_Parameters.m_SignalGen.m_ImageOrigin = itkImg->GetOrigin(); m_Parameters.m_SignalGen.m_ImageDirection = itkImg->GetDirection(); } m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; itk::ImageDuplicator<ItkFloatImgType>::Pointer duplicator = itk::ImageDuplicator<ItkFloatImgType>::New(); duplicator->SetInputImage(itkImg); duplicator->Update(); m_Parameters.m_SignalGen.m_FrequencyMap = duplicator->GetOutput(); m_Parameters.m_Misc.m_ArtifactModelString += "_DISTORTED"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Distortions", BoolProperty::New(true)); } m_Parameters.m_SignalGen.m_EddyStrength = m_Controls->m_EddyGradientStrength->value(); m_Parameters.m_Misc.m_DoAddEddyCurrents = m_Controls->m_AddEddy->isChecked(); if (m_Controls->m_AddEddy->isChecked()) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ArtifactModelString += "_EDDY"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Eddy-strength", DoubleProperty::New(m_Parameters.m_SignalGen.m_EddyStrength)); } // Motion m_Parameters.m_SignalGen.m_DoAddMotion = false; m_Parameters.m_SignalGen.m_DoRandomizeMotion = m_Controls->m_RandomMotion->isChecked(); m_Parameters.m_SignalGen.m_Translation[0] = m_Controls->m_MaxTranslationBoxX->value(); m_Parameters.m_SignalGen.m_Translation[1] = m_Controls->m_MaxTranslationBoxY->value(); m_Parameters.m_SignalGen.m_Translation[2] = m_Controls->m_MaxTranslationBoxZ->value(); m_Parameters.m_SignalGen.m_Rotation[0] = m_Controls->m_MaxRotationBoxX->value(); m_Parameters.m_SignalGen.m_Rotation[1] = m_Controls->m_MaxRotationBoxY->value(); m_Parameters.m_SignalGen.m_Rotation[2] = m_Controls->m_MaxRotationBoxZ->value(); m_Parameters.m_SignalGen.m_MotionVolumes.clear(); m_Parameters.m_Misc.m_MotionVolumesBox = m_Controls->m_MotionVolumesBox->text().toStdString(); if ( m_Controls->m_AddMotion->isChecked()) { m_Parameters.m_SignalGen.m_DoAddMotion = true; m_Parameters.m_Misc.m_ArtifactModelString += "_MOTION"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Random", BoolProperty::New(m_Parameters.m_SignalGen.m_DoRandomizeMotion)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Translation-x", DoubleProperty::New(m_Parameters.m_SignalGen.m_Translation[0])); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Translation-y", DoubleProperty::New(m_Parameters.m_SignalGen.m_Translation[1])); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Translation-z", DoubleProperty::New(m_Parameters.m_SignalGen.m_Translation[2])); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Rotation-x", DoubleProperty::New(m_Parameters.m_SignalGen.m_Rotation[0])); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Rotation-y", DoubleProperty::New(m_Parameters.m_SignalGen.m_Rotation[1])); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Motion.Rotation-z", DoubleProperty::New(m_Parameters.m_SignalGen.m_Rotation[2])); if ( m_Parameters.m_Misc.m_MotionVolumesBox == "random" ) { for ( size_t i=0; i < m_Parameters.m_SignalGen.GetNumVolumes(); ++i ) { m_Parameters.m_SignalGen.m_MotionVolumes.push_back( bool( rand()%2 ) ); } MITK_DEBUG << "QmitkFiberfoxView.cpp: Case m_Misc.m_MotionVolumesBox == \"random\"."; } else if ( ! m_Parameters.m_Misc.m_MotionVolumesBox.empty() ) { std::stringstream stream( m_Parameters.m_Misc.m_MotionVolumesBox ); std::vector<int> numbers; int number = std::numeric_limits<int>::max(); while( stream >> number ) { if( number < std::numeric_limits<int>::max() ) { numbers.push_back( number ); } } // If a list of negative numbers is given: if( *(std::min_element( numbers.begin(), numbers.end() )) < 0 && *(std::max_element( numbers.begin(), numbers.end() )) <= 0 ) // cave: -0 == +0 { for ( size_t i=0; i < m_Parameters.m_SignalGen.GetNumVolumes(); ++i ) { m_Parameters.m_SignalGen.m_MotionVolumes.push_back( true ); } // set all true except those given. for( auto iter = std::begin( numbers ); iter != std::end( numbers ); ++iter ) { if ( -(*iter) < (int)m_Parameters.m_SignalGen.GetNumVolumes() && -(*iter) >= 0 ) { m_Parameters.m_SignalGen.m_MotionVolumes.at( -(*iter) ) = false; } } MITK_DEBUG << "QmitkFiberfoxView.cpp: Case list of negative numbers."; } // If a list of positive numbers is given: else if( *(std::min_element( numbers.begin(), numbers.end() )) >= 0 && *(std::max_element( numbers.begin(), numbers.end() )) >= 0 ) { for ( size_t i=0; i < m_Parameters.m_SignalGen.GetNumVolumes(); ++i ) { m_Parameters.m_SignalGen.m_MotionVolumes.push_back( false ); } // set all false except those given. for( auto iter = std::begin( numbers ); iter != std::end( numbers ); ++iter ) { if ( *iter < (int)m_Parameters.m_SignalGen.GetNumVolumes() && *iter >= 0 ) { m_Parameters.m_SignalGen.m_MotionVolumes.at( *iter ) = true; } } MITK_DEBUG << "QmitkFiberfoxView.cpp: Case list of positive numbers."; } else { MITK_ERROR << "QmitkFiberfoxView.cpp: Inconsistent list of numbers in m_MotionVolumesBox."; } } else { m_Parameters.m_Misc.m_MotionVolumesBox = ""; // set empty. m_Controls->m_MotionVolumesBox->setText(""); for (unsigned int i=0; i<m_Parameters.m_SignalGen.GetNumVolumes(); i++) { m_Parameters.m_SignalGen.m_MotionVolumes.push_back(i); } } } // other imaging parameters m_Parameters.m_SignalGen.m_AcquisitionType = (SignalGenerationParameters::AcquisitionType)m_Controls->m_AcquisitionTypeBox->currentIndex(); m_Parameters.m_SignalGen.m_CoilSensitivityProfile = (SignalGenerationParameters::CoilSensitivityProfile)m_Controls->m_CoilSensBox->currentIndex(); m_Parameters.m_SignalGen.m_NumberOfCoils = m_Controls->m_NumCoilsBox->value(); m_Parameters.m_SignalGen.m_PartialFourier = m_Controls->m_PartialFourier->value(); m_Parameters.m_SignalGen.m_ReversePhase = m_Controls->m_ReversePhaseBox->isChecked(); m_Parameters.m_SignalGen.m_tLine = m_Controls->m_LineReadoutTimeBox->value(); m_Parameters.m_SignalGen.m_tInhom = m_Controls->m_T2starBox->value(); m_Parameters.m_SignalGen.m_EchoTrainLength = m_Controls->m_EtlBox->value(); m_Parameters.m_SignalGen.m_tEcho = m_Controls->m_TEbox->value(); m_Parameters.m_SignalGen.m_tRep = m_Controls->m_TRbox->value(); m_Parameters.m_SignalGen.m_tInv = m_Controls->m_TIbox->value(); m_Parameters.m_SignalGen.m_DoDisablePartialVolume = m_Controls->m_EnforcePureFiberVoxelsBox->isChecked(); m_Parameters.m_SignalGen.m_AxonRadius = m_Controls->m_FiberRadius->value(); m_Parameters.m_SignalGen.m_SignalScale = m_Controls->m_SignalScaleBox->value(); // double voxelVolume = m_Parameters.m_SignalGen.m_ImageSpacing[0] // * m_Parameters.m_SignalGen.m_ImageSpacing[1] // * m_Parameters.m_SignalGen.m_ImageSpacing[2]; // if ( m_Parameters.m_SignalGen.m_SignalScale*voxelVolume > itk::NumericTraits<short>::max()*0.75 ) // { // m_Parameters.m_SignalGen.m_SignalScale = itk::NumericTraits<short>::max()*0.75/voxelVolume; // m_Controls->m_SignalScaleBox->setValue(m_Parameters.m_SignalGen.m_SignalScale); // QMessageBox::information( nullptr, "Warning", // "Maximum signal exceeding data type limits. Automatically adjusted to " // + QString::number(m_Parameters.m_SignalGen.m_SignalScale) // + " to obtain a maximum signal of 75% of the data type maximum." // " Relaxation and other effects that affect the signal intensities are not accounted for."); // } // Noise m_Parameters.m_Misc.m_DoAddNoise = m_Controls->m_AddNoise->isChecked(); m_Parameters.m_SignalGen.m_NoiseVariance = m_Controls->m_NoiseLevel->value(); if (m_Controls->m_AddNoise->isChecked()) { switch (m_Controls->m_NoiseDistributionBox->currentIndex()) { case 0: { if (m_Parameters.m_SignalGen.m_NoiseVariance>0) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ArtifactModelString += "_COMPLEX-GAUSSIAN-"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Complex Gaussian")); } break; } case 1: { if (m_Parameters.m_SignalGen.m_NoiseVariance>0) { m_Parameters.m_NoiseModel = std::make_shared< mitk::RicianNoiseModel<ScalarType> >(); m_Parameters.m_Misc.m_ArtifactModelString += "_RICIAN-"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Rician")); m_Parameters.m_NoiseModel->SetNoiseVariance(m_Parameters.m_SignalGen.m_NoiseVariance); } break; } case 2: { if (m_Parameters.m_SignalGen.m_NoiseVariance>0) { m_Parameters.m_NoiseModel = std::make_shared< mitk::ChiSquareNoiseModel<ScalarType> >(); m_Parameters.m_Misc.m_ArtifactModelString += "_CHISQUARED-"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Chi-squared")); m_Parameters.m_NoiseModel->SetNoiseVariance(m_Parameters.m_SignalGen.m_NoiseVariance); } break; } default: { if (m_Parameters.m_SignalGen.m_NoiseVariance>0) { m_Parameters.m_SignalGen.m_SimulateKspaceAcquisition = true; m_Parameters.m_Misc.m_ArtifactModelString += "_COMPLEX-GAUSSIAN-"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Complex Gaussian")); } break; } } if (m_Parameters.m_SignalGen.m_NoiseVariance>0) { m_Parameters.m_Misc.m_ArtifactModelString += QString::number(m_Parameters.m_SignalGen.m_NoiseVariance).toStdString(); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Noise-Variance", DoubleProperty::New(m_Parameters.m_SignalGen.m_NoiseVariance)); } } // signal models { // compartment 1 switch (m_Controls->m_Compartment1Box->currentIndex()) { case 0: { mitk::StickModel<ScalarType>* model = new mitk::StickModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity(m_Controls->m_StickWidget1->GetD()); model->SetT2(m_Controls->m_StickWidget1->GetT2()); model->SetT1(m_Controls->m_StickWidget1->GetT1()); model->m_CompartmentId = 1; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Stick"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Stick") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.D", DoubleProperty::New(m_Controls->m_StickWidget1->GetD()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(model->GetT2()) ); break; } case 1: { mitk::TensorModel<ScalarType>* model = new mitk::TensorModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity1(m_Controls->m_ZeppelinWidget1->GetD1()); model->SetDiffusivity2(m_Controls->m_ZeppelinWidget1->GetD2()); model->SetDiffusivity3(m_Controls->m_ZeppelinWidget1->GetD2()); model->SetT2(m_Controls->m_ZeppelinWidget1->GetT2()); model->SetT1(m_Controls->m_ZeppelinWidget1->GetT1()); model->m_CompartmentId = 1; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Zeppelin"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Zeppelin") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.D1", DoubleProperty::New(m_Controls->m_ZeppelinWidget1->GetD1()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.D2", DoubleProperty::New(m_Controls->m_ZeppelinWidget1->GetD2()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(model->GetT2()) ); break; } case 2: { mitk::TensorModel<ScalarType>* model = new mitk::TensorModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity1(m_Controls->m_TensorWidget1->GetD1()); model->SetDiffusivity2(m_Controls->m_TensorWidget1->GetD2()); model->SetDiffusivity3(m_Controls->m_TensorWidget1->GetD3()); model->SetT2(m_Controls->m_TensorWidget1->GetT2()); model->SetT1(m_Controls->m_TensorWidget1->GetT1()); model->m_CompartmentId = 1; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Tensor"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Tensor") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.D1", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD1()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.D2", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD2()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.D3", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD3()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(model->GetT2()) ); break; } case 3: { mitk::RawShModel<ScalarType>* model = new mitk::RawShModel<ScalarType>(); m_Parameters.m_SignalGen.m_DoSimulateRelaxation = false; model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetMaxNumKernels(m_Controls->m_PrototypeWidget1->GetNumberOfSamples()); model->SetFaRange(m_Controls->m_PrototypeWidget1->GetMinFa(), m_Controls->m_PrototypeWidget1->GetMaxFa()); model->SetAdcRange(m_Controls->m_PrototypeWidget1->GetMinAdc(), m_Controls->m_PrototypeWidget1->GetMaxAdc()); model->m_CompartmentId = 1; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Prototype"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Prototype") ); break; } } if (m_Controls->m_Comp1VolumeFraction->GetSelectedNode().IsNotNull()) { mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp1VolumeFraction->GetSelectedNode(); ItkDoubleImgType::Pointer comp1VolumeImage = ItkDoubleImgType::New(); mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); CastToItkImage< ItkDoubleImgType >(img, comp1VolumeImage); m_Parameters.m_FiberModelList.back()->SetVolumeFractionImage(comp1VolumeImage); } // compartment 2 switch (m_Controls->m_Compartment2Box->currentIndex()) { case 0: break; case 1: { mitk::StickModel<ScalarType>* model = new mitk::StickModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity(m_Controls->m_StickWidget2->GetD()); model->SetT2(m_Controls->m_StickWidget2->GetT2()); model->SetT1(m_Controls->m_StickWidget2->GetT1()); model->m_CompartmentId = 2; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Stick"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Stick") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.D", DoubleProperty::New(m_Controls->m_StickWidget2->GetD()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(model->GetT2()) ); break; } case 2: { mitk::TensorModel<ScalarType>* model = new mitk::TensorModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity1(m_Controls->m_ZeppelinWidget2->GetD1()); model->SetDiffusivity2(m_Controls->m_ZeppelinWidget2->GetD2()); model->SetDiffusivity3(m_Controls->m_ZeppelinWidget2->GetD2()); model->SetT2(m_Controls->m_ZeppelinWidget2->GetT2()); model->SetT1(m_Controls->m_ZeppelinWidget2->GetT1()); model->m_CompartmentId = 2; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Zeppelin"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Zeppelin") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.D1", DoubleProperty::New(m_Controls->m_ZeppelinWidget2->GetD1()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.D2", DoubleProperty::New(m_Controls->m_ZeppelinWidget2->GetD2()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(model->GetT2()) ); break; } case 3: { mitk::TensorModel<ScalarType>* model = new mitk::TensorModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity1(m_Controls->m_TensorWidget2->GetD1()); model->SetDiffusivity2(m_Controls->m_TensorWidget2->GetD2()); model->SetDiffusivity3(m_Controls->m_TensorWidget2->GetD3()); model->SetT2(m_Controls->m_TensorWidget2->GetT2()); model->SetT1(m_Controls->m_TensorWidget2->GetT1()); model->m_CompartmentId = 2; m_Parameters.m_FiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Tensor"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Tensor") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.D1", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD1()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.D2", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD2()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.D3", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD3()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(model->GetT2()) ); break; } } if (m_Controls->m_Comp2VolumeFraction->GetSelectedNode().IsNotNull() && m_Parameters.m_FiberModelList.size()==2) { mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp2VolumeFraction->GetSelectedNode(); ItkDoubleImgType::Pointer comp1VolumeImage = ItkDoubleImgType::New(); mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); CastToItkImage< ItkDoubleImgType >(img, comp1VolumeImage); m_Parameters.m_FiberModelList.back()->SetVolumeFractionImage(comp1VolumeImage); } // compartment 3 switch (m_Controls->m_Compartment3Box->currentIndex()) { case 0: { mitk::BallModel<ScalarType>* model = new mitk::BallModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity(m_Controls->m_BallWidget1->GetD()); model->SetT2(m_Controls->m_BallWidget1->GetT2()); model->SetT1(m_Controls->m_BallWidget1->GetT1()); model->m_CompartmentId = 3; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Ball"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Ball") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.D", DoubleProperty::New(m_Controls->m_BallWidget1->GetD()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(model->GetT2()) ); break; } case 1: { mitk::AstroStickModel<ScalarType>* model = new mitk::AstroStickModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity(m_Controls->m_AstrosticksWidget1->GetD()); model->SetT2(m_Controls->m_AstrosticksWidget1->GetT2()); model->SetT1(m_Controls->m_AstrosticksWidget1->GetT1()); model->SetRandomizeSticks(m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()); model->m_CompartmentId = 3; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Astrosticks"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Astrosticks") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.D", DoubleProperty::New(m_Controls->m_AstrosticksWidget1->GetD()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(model->GetT2()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.RandomSticks", BoolProperty::New(m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()) ); break; } case 2: { mitk::DotModel<ScalarType>* model = new mitk::DotModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetT2(m_Controls->m_DotWidget1->GetT2()); model->SetT1(m_Controls->m_DotWidget1->GetT1()); model->m_CompartmentId = 3; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Dot"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Dot") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(model->GetT2()) ); break; } case 3: { mitk::RawShModel<ScalarType>* model = new mitk::RawShModel<ScalarType>(); m_Parameters.m_SignalGen.m_DoSimulateRelaxation = false; model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetMaxNumKernels(m_Controls->m_PrototypeWidget3->GetNumberOfSamples()); model->SetFaRange(m_Controls->m_PrototypeWidget3->GetMinFa(), m_Controls->m_PrototypeWidget3->GetMaxFa()); model->SetAdcRange(m_Controls->m_PrototypeWidget3->GetMinAdc(), m_Controls->m_PrototypeWidget3->GetMaxAdc()); model->m_CompartmentId = 3; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Prototype"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Prototype") ); break; } } if (m_Controls->m_Comp3VolumeFraction->GetSelectedNode().IsNotNull()) { mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp3VolumeFraction->GetSelectedNode(); ItkDoubleImgType::Pointer comp1VolumeImage = ItkDoubleImgType::New(); mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); CastToItkImage< ItkDoubleImgType >(img, comp1VolumeImage); m_Parameters.m_NonFiberModelList.back()->SetVolumeFractionImage(comp1VolumeImage); } switch (m_Controls->m_Compartment4Box->currentIndex()) { case 0: break; case 1: { mitk::BallModel<ScalarType>* model = new mitk::BallModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity(m_Controls->m_BallWidget2->GetD()); model->SetT2(m_Controls->m_BallWidget2->GetT2()); model->SetT1(m_Controls->m_BallWidget2->GetT1()); model->m_CompartmentId = 4; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Ball"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Ball") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.D", DoubleProperty::New(m_Controls->m_BallWidget2->GetD()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(model->GetT2()) ); break; } case 2: { mitk::AstroStickModel<ScalarType>* model = new mitk::AstroStickModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetBvalue(m_Parameters.m_SignalGen.GetBvalue()); model->SetDiffusivity(m_Controls->m_AstrosticksWidget2->GetD()); model->SetT2(m_Controls->m_AstrosticksWidget2->GetT2()); model->SetT1(m_Controls->m_AstrosticksWidget2->GetT1()); model->SetRandomizeSticks(m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()); model->m_CompartmentId = 4; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Astrosticks"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Astrosticks") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.D", DoubleProperty::New(m_Controls->m_AstrosticksWidget2->GetD()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(model->GetT2()) ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.RandomSticks", BoolProperty::New(m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()) ); break; } case 3: { mitk::DotModel<ScalarType>* model = new mitk::DotModel<ScalarType>(); model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetT2(m_Controls->m_DotWidget2->GetT2()); model->SetT1(m_Controls->m_DotWidget2->GetT1()); model->m_CompartmentId = 4; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Dot"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Dot") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(model->GetT2()) ); break; } case 4: { mitk::RawShModel<ScalarType>* model = new mitk::RawShModel<ScalarType>(); m_Parameters.m_SignalGen.m_DoSimulateRelaxation = false; model->SetGradientList(m_Parameters.m_SignalGen.GetGradientDirections()); model->SetMaxNumKernels(m_Controls->m_PrototypeWidget4->GetNumberOfSamples()); model->SetFaRange(m_Controls->m_PrototypeWidget4->GetMinFa(), m_Controls->m_PrototypeWidget4->GetMaxFa()); model->SetAdcRange(m_Controls->m_PrototypeWidget4->GetMinAdc(), m_Controls->m_PrototypeWidget4->GetMaxAdc()); model->m_CompartmentId = 4; m_Parameters.m_NonFiberModelList.push_back(model); m_Parameters.m_Misc.m_SignalModelString += "Prototype"; m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Prototype") ); break; } } if (m_Controls->m_Comp4VolumeFraction->GetSelectedNode().IsNotNull() && m_Parameters.m_NonFiberModelList.size()==2) { mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp4VolumeFraction->GetSelectedNode(); ItkDoubleImgType::Pointer compVolumeImage = ItkDoubleImgType::New(); mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); CastToItkImage< ItkDoubleImgType >(img, compVolumeImage); m_Parameters.m_NonFiberModelList.back()->SetVolumeFractionImage(compVolumeImage); } } m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.SignalScale", IntProperty::New(m_Parameters.m_SignalGen.m_SignalScale)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.FiberRadius", IntProperty::New(m_Parameters.m_SignalGen.m_AxonRadius)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Tinhom", DoubleProperty::New(m_Parameters.m_SignalGen.m_tInhom)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.echoTrainLength", IntProperty::New(m_Parameters.m_SignalGen.m_EchoTrainLength)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Tline", DoubleProperty::New(m_Parameters.m_SignalGen.m_tLine)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.TE", DoubleProperty::New(m_Parameters.m_SignalGen.m_tEcho)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.b-value", DoubleProperty::New(m_Parameters.m_SignalGen.GetBvalue())); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.NoPartialVolume", BoolProperty::New(m_Parameters.m_SignalGen.m_DoDisablePartialVolume)); m_Parameters.m_Misc.m_ResultNode->AddProperty("Fiberfox.Relaxation", BoolProperty::New(m_Parameters.m_SignalGen.m_DoSimulateRelaxation)); m_Parameters.m_Misc.m_ResultNode->AddProperty("binary", BoolProperty::New(false)); } void QmitkFiberfoxView::SaveParameters(QString filename) { UpdateParametersFromGui(); std::vector< int > bVals = m_Parameters.m_SignalGen.GetBvalues(); std::cout << "b-values: "; for (auto v : bVals) std::cout << v << " "; std::cout << std::endl; bool ok = true; bool first = true; bool dosampling = false; mitk::Image::Pointer diffImg = nullptr; itk::Image< itk::DiffusionTensor3D< double >, 3 >::Pointer tensorImage = nullptr; const int shOrder = 2; typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,shOrder,ODF_SAMPLING_SIZE> QballFilterType; QballFilterType::CoefficientImageType::Pointer itkFeatureImage = nullptr; ItkDoubleImgType::Pointer adcImage = nullptr; for (unsigned int i=0; i<m_Parameters.m_FiberModelList.size()+m_Parameters.m_NonFiberModelList.size(); i++) { mitk::RawShModel<>* model = nullptr; if (i<m_Parameters.m_FiberModelList.size()) { model = dynamic_cast< mitk::RawShModel<>* >(m_Parameters.m_FiberModelList.at(i)); } else { model = dynamic_cast< mitk::RawShModel<>* >(m_Parameters.m_NonFiberModelList.at(i-m_Parameters.m_FiberModelList.size())); } if ( model!=nullptr && model->GetNumberOfKernels() <= 0 ) { if (first==true) { if ( QMessageBox::question(nullptr, "Prototype signal sampling", "Do you want to sample prototype signals from the selected diffusion-weighted imag and save them?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes ) dosampling = true; first = false; if ( dosampling && (m_Controls->m_TemplateComboBox->GetSelectedNode().IsNull() || !mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()) ) ) ) { QMessageBox::information(nullptr, "Parameter file not saved", "No diffusion-weighted image selected to sample signal from."); return; } else if (dosampling) { diffImg = dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()); typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, double > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); ItkDwiType::Pointer itkVectorImagePointer = ItkDwiType::New(); mitk::CastToItkImage(diffImg, itkVectorImagePointer); filter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); filter->SetGradientImage(dynamic_cast<mitk::GradientDirectionsProperty *>(diffImg->GetProperty(mitk::DiffusionPropertyHelper::GetGradientContainerPropertyName().c_str()).GetPointer())->GetGradientDirectionsContainerCopy(), itkVectorImagePointer ); filter->Update(); tensorImage = filter->GetOutput(); QballFilterType::Pointer qballfilter = QballFilterType::New(); qballfilter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); qballfilter->SetGradientImage(mitk::DiffusionPropertyHelper::GetGradientContainer(diffImg), itkVectorImagePointer ); qballfilter->SetLambda(0.006); qballfilter->SetNormalizationMethod(QballFilterType::QBAR_RAW_SIGNAL); qballfilter->Update(); itkFeatureImage = qballfilter->GetCoefficientImage(); itk::AdcImageFilter< short, double >::Pointer adcFilter = itk::AdcImageFilter< short, double >::New(); adcFilter->SetInput( itkVectorImagePointer ); adcFilter->SetGradientDirections(mitk::DiffusionPropertyHelper::GetGradientContainer(diffImg)); adcFilter->SetB_value(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); adcFilter->Update(); adcImage = adcFilter->GetOutput(); } } typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, double > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); ItkDwiType::Pointer itkVectorImagePointer = ItkDwiType::New(); mitk::CastToItkImage(diffImg, itkVectorImagePointer); filter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); filter->SetGradientImage(dynamic_cast<mitk::GradientDirectionsProperty *>(diffImg->GetProperty(mitk::DiffusionPropertyHelper::GetGradientContainerPropertyName().c_str()).GetPointer())->GetGradientDirectionsContainerCopy(), itkVectorImagePointer ); filter->Update(); tensorImage = filter->GetOutput(); QballFilterType::Pointer qballfilter = QballFilterType::New(); qballfilter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); qballfilter->SetGradientImage(mitk::DiffusionPropertyHelper::GetGradientContainer(diffImg), itkVectorImagePointer ); qballfilter->SetLambda(0.006); qballfilter->SetNormalizationMethod(QballFilterType::QBAR_RAW_SIGNAL); qballfilter->Update(); itkFeatureImage = qballfilter->GetCoefficientImage(); itk::AdcImageFilter< short, double >::Pointer adcFilter = itk::AdcImageFilter< short, double >::New(); adcFilter->SetInput( itkVectorImagePointer ); adcFilter->SetGradientDirections(mitk::DiffusionPropertyHelper::GetGradientContainer(diffImg)); adcFilter->SetB_value(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); adcFilter->Update(); adcImage = adcFilter->GetOutput(); if (dosampling && diffImg.IsNotNull()) { ok = model->SampleKernels(diffImg, m_Parameters.m_SignalGen.m_MaskImage, tensorImage, itkFeatureImage, adcImage); if (!ok) { QMessageBox::information( nullptr, "Parameter file not saved", "No valid prototype signals could be sampled."); return; } } } } m_Parameters.SaveParameters(filename.toStdString()); m_ParameterFile = filename; } void QmitkFiberfoxView::SaveParameters() { QString filename = QFileDialog::getSaveFileName( 0, tr("Save Parameters"), m_ParameterFile, tr("Fiberfox Parameters (*.ffp)") ); SaveParameters(filename); } void QmitkFiberfoxView::LoadParameters() { QString filename = QFileDialog::getOpenFileName(0, tr("Load Parameters"), QString(itksys::SystemTools::GetFilenamePath(m_ParameterFile.toStdString()).c_str()), tr("Fiberfox Parameters (*.ffp)") ); if(filename.isEmpty() || filename.isNull()) return; m_ParameterFile = filename; m_Parameters.LoadParameters(filename.toStdString()); if (m_Parameters.m_MissingTags.size()>0) { QString missing("Parameter file might be corrupted. The following parameters could not be read: "); missing += QString(m_Parameters.m_MissingTags.c_str()); missing += "\nDefault values have been assigned to the missing parameters."; QMessageBox::information( nullptr, "Warning!", missing); } // image generation parameters m_Controls->m_SizeX->setValue(m_Parameters.m_SignalGen.m_ImageRegion.GetSize(0)); m_Controls->m_SizeY->setValue(m_Parameters.m_SignalGen.m_ImageRegion.GetSize(1)); m_Controls->m_SizeZ->setValue(m_Parameters.m_SignalGen.m_ImageRegion.GetSize(2)); m_Controls->m_SpacingX->setValue(m_Parameters.m_SignalGen.m_ImageSpacing[0]); m_Controls->m_SpacingY->setValue(m_Parameters.m_SignalGen.m_ImageSpacing[1]); m_Controls->m_SpacingZ->setValue(m_Parameters.m_SignalGen.m_ImageSpacing[2]); m_Controls->m_NumGradientsBox->setValue(m_Parameters.m_SignalGen.GetNumWeightedVolumes()); m_Controls->m_BvalueBox->setValue(m_Parameters.m_SignalGen.GetBvalue()); m_Controls->m_SignalScaleBox->setValue(m_Parameters.m_SignalGen.m_SignalScale); m_Controls->m_TEbox->setValue(m_Parameters.m_SignalGen.m_tEcho); m_Controls->m_LineReadoutTimeBox->setValue(m_Parameters.m_SignalGen.m_tLine); m_Controls->m_T2starBox->setValue(m_Parameters.m_SignalGen.m_tInhom); m_Controls->m_EtlBox->setValue(m_Parameters.m_SignalGen.m_EchoTrainLength); m_Controls->m_FiberRadius->setValue(m_Parameters.m_SignalGen.m_AxonRadius); m_Controls->m_RelaxationBox->setChecked(m_Parameters.m_SignalGen.m_DoSimulateRelaxation); m_Controls->m_EnforcePureFiberVoxelsBox->setChecked(m_Parameters.m_SignalGen.m_DoDisablePartialVolume); m_Controls->m_ReversePhaseBox->setChecked(m_Parameters.m_SignalGen.m_ReversePhase); m_Controls->m_PartialFourier->setValue(m_Parameters.m_SignalGen.m_PartialFourier); m_Controls->m_TRbox->setValue(m_Parameters.m_SignalGen.m_tRep); m_Controls->m_TIbox->setValue(m_Parameters.m_SignalGen.m_tInv); m_Controls->m_NumCoilsBox->setValue(m_Parameters.m_SignalGen.m_NumberOfCoils); m_Controls->m_CoilSensBox->setCurrentIndex(m_Parameters.m_SignalGen.m_CoilSensitivityProfile); m_Controls->m_AcquisitionTypeBox->setCurrentIndex(m_Parameters.m_SignalGen.m_AcquisitionType); if (!m_Parameters.m_Misc.m_BvalsFile.empty()) { m_Controls->m_UseBvalsBvecsBox->setChecked(true); m_Controls->m_LoadBvalsEdit->setText(QString(m_Parameters.m_Misc.m_BvalsFile.c_str())); } else m_Controls->m_LoadBvalsEdit->setText("-"); if (!m_Parameters.m_Misc.m_BvecsFile.empty()) { m_Controls->m_UseBvalsBvecsBox->setChecked(true); m_Controls->m_LoadBvecsEdit->setText(QString(m_Parameters.m_Misc.m_BvecsFile.c_str())); } else m_Controls->m_LoadBvecsEdit->setText("-"); if (m_Parameters.m_NoiseModel!=nullptr) { m_Controls->m_AddNoise->setChecked(m_Parameters.m_Misc.m_DoAddNoise); if (dynamic_cast<mitk::RicianNoiseModel<double>*>(m_Parameters.m_NoiseModel.get())) { m_Controls->m_NoiseDistributionBox->setCurrentIndex(0); } else if (dynamic_cast<mitk::ChiSquareNoiseModel<double>*>(m_Parameters.m_NoiseModel.get())) { m_Controls->m_NoiseDistributionBox->setCurrentIndex(1); } m_Controls->m_NoiseLevel->setValue(m_Parameters.m_NoiseModel->GetNoiseVariance()); } else { m_Controls->m_AddNoise->setChecked(m_Parameters.m_Misc.m_DoAddNoise); m_Controls->m_NoiseLevel->setValue(m_Parameters.m_SignalGen.m_NoiseVariance); } m_Controls->m_VolumeFractionsBox->setChecked(m_Parameters.m_Misc.m_OutputAdditionalImages); m_Controls->m_AdvancedOptionsBox_2->setChecked(m_Parameters.m_Misc.m_CheckAdvancedSignalOptionsBox); m_Controls->m_AddGhosts->setChecked(m_Parameters.m_Misc.m_DoAddGhosts); m_Controls->m_AddAliasing->setChecked(m_Parameters.m_Misc.m_DoAddAliasing); m_Controls->m_AddDistortions->setChecked(m_Parameters.m_Misc.m_DoAddDistortions); m_Controls->m_AddSpikes->setChecked(m_Parameters.m_Misc.m_DoAddSpikes); m_Controls->m_AddEddy->setChecked(m_Parameters.m_Misc.m_DoAddEddyCurrents); m_Controls->m_AddDrift->setChecked(m_Parameters.m_SignalGen.m_DoAddDrift); m_Controls->m_kOffsetBox->setValue(m_Parameters.m_SignalGen.m_KspaceLineOffset); m_Controls->m_WrapBox->setValue(100*(1-m_Parameters.m_SignalGen.m_CroppingFactor)); m_Controls->m_DriftFactor->setValue(100*m_Parameters.m_SignalGen.m_Drift); m_Controls->m_SpikeNumBox->setValue(m_Parameters.m_SignalGen.m_Spikes); m_Controls->m_SpikeScaleBox->setValue(m_Parameters.m_SignalGen.m_SpikeAmplitude); m_Controls->m_EddyGradientStrength->setValue(m_Parameters.m_SignalGen.m_EddyStrength); m_Controls->m_AddGibbsRinging->setChecked(m_Parameters.m_SignalGen.m_DoAddGibbsRinging); m_Controls->m_ZeroRinging->setValue(m_Parameters.m_SignalGen.m_ZeroRinging); m_Controls->m_AddMotion->setChecked(m_Parameters.m_SignalGen.m_DoAddMotion); m_Controls->m_RandomMotion->setChecked(m_Parameters.m_SignalGen.m_DoRandomizeMotion); m_Controls->m_MotionVolumesBox->setText(QString(m_Parameters.m_Misc.m_MotionVolumesBox.c_str())); m_Controls->m_MaxTranslationBoxX->setValue(m_Parameters.m_SignalGen.m_Translation[0]); m_Controls->m_MaxTranslationBoxY->setValue(m_Parameters.m_SignalGen.m_Translation[1]); m_Controls->m_MaxTranslationBoxZ->setValue(m_Parameters.m_SignalGen.m_Translation[2]); m_Controls->m_MaxRotationBoxX->setValue(m_Parameters.m_SignalGen.m_Rotation[0]); m_Controls->m_MaxRotationBoxY->setValue(m_Parameters.m_SignalGen.m_Rotation[1]); m_Controls->m_MaxRotationBoxZ->setValue(m_Parameters.m_SignalGen.m_Rotation[2]); m_Controls->m_Compartment1Box->setCurrentIndex(0); m_Controls->m_Compartment2Box->setCurrentIndex(0); m_Controls->m_Compartment3Box->setCurrentIndex(0); m_Controls->m_Compartment4Box->setCurrentIndex(0); for (unsigned int i=0; i<m_Parameters.m_FiberModelList.size()+m_Parameters.m_NonFiberModelList.size(); i++) { mitk::DiffusionSignalModel<ScalarType>* signalModel = nullptr; if (i<m_Parameters.m_FiberModelList.size()) signalModel = m_Parameters.m_FiberModelList.at(i); else signalModel = m_Parameters.m_NonFiberModelList.at(i-m_Parameters.m_FiberModelList.size()); mitk::DataNode::Pointer compVolNode; if ( signalModel->GetVolumeFractionImage().IsNotNull() ) { compVolNode = mitk::DataNode::New(); mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(signalModel->GetVolumeFractionImage().GetPointer()); image->SetVolume(signalModel->GetVolumeFractionImage()->GetBufferPointer()); compVolNode->SetData( image ); compVolNode->SetName("Compartment volume "+QString::number(signalModel->m_CompartmentId).toStdString()); GetDataStorage()->Add(compVolNode); } switch (signalModel->m_CompartmentId) { case 1: { if (compVolNode.IsNotNull()) m_Controls->m_Comp1VolumeFraction->SetSelectedNode(compVolNode); if (dynamic_cast<mitk::StickModel<>*>(signalModel)) { mitk::StickModel<>* model = dynamic_cast<mitk::StickModel<>*>(signalModel); m_Controls->m_StickWidget1->SetT2(model->GetT2()); m_Controls->m_StickWidget1->SetT1(model->GetT1()); m_Controls->m_StickWidget1->SetD(model->GetDiffusivity()); m_Controls->m_Compartment1Box->setCurrentIndex(0); break; } else if (dynamic_cast<mitk::TensorModel<>*>(signalModel)) { mitk::TensorModel<>* model = dynamic_cast<mitk::TensorModel<>*>(signalModel); m_Controls->m_TensorWidget1->SetT2(model->GetT2()); m_Controls->m_TensorWidget1->SetT1(model->GetT1()); m_Controls->m_TensorWidget1->SetD1(model->GetDiffusivity1()); m_Controls->m_TensorWidget1->SetD2(model->GetDiffusivity2()); m_Controls->m_TensorWidget1->SetD3(model->GetDiffusivity3()); m_Controls->m_Compartment1Box->setCurrentIndex(2); break; } else if (dynamic_cast<mitk::RawShModel<>*>(signalModel)) { mitk::RawShModel<>* model = dynamic_cast<mitk::RawShModel<>*>(signalModel); m_Controls->m_PrototypeWidget1->SetNumberOfSamples(model->GetMaxNumKernels()); m_Controls->m_PrototypeWidget1->SetMinFa(model->GetFaRange().first); m_Controls->m_PrototypeWidget1->SetMaxFa(model->GetFaRange().second); m_Controls->m_PrototypeWidget1->SetMinAdc(model->GetAdcRange().first); m_Controls->m_PrototypeWidget1->SetMaxAdc(model->GetAdcRange().second); m_Controls->m_Compartment1Box->setCurrentIndex(3); break; } break; } case 2: { if (compVolNode.IsNotNull()) m_Controls->m_Comp2VolumeFraction->SetSelectedNode(compVolNode); if (dynamic_cast<mitk::StickModel<>*>(signalModel)) { mitk::StickModel<>* model = dynamic_cast<mitk::StickModel<>*>(signalModel); m_Controls->m_StickWidget2->SetT2(model->GetT2()); m_Controls->m_StickWidget2->SetT1(model->GetT1()); m_Controls->m_StickWidget2->SetD(model->GetDiffusivity()); m_Controls->m_Compartment2Box->setCurrentIndex(1); break; } else if (dynamic_cast<mitk::TensorModel<>*>(signalModel)) { mitk::TensorModel<>* model = dynamic_cast<mitk::TensorModel<>*>(signalModel); m_Controls->m_TensorWidget2->SetT2(model->GetT2()); m_Controls->m_TensorWidget2->SetT1(model->GetT1()); m_Controls->m_TensorWidget2->SetD1(model->GetDiffusivity1()); m_Controls->m_TensorWidget2->SetD2(model->GetDiffusivity2()); m_Controls->m_TensorWidget2->SetD3(model->GetDiffusivity3()); m_Controls->m_Compartment2Box->setCurrentIndex(3); break; } break; } case 3: { if (compVolNode.IsNotNull()) m_Controls->m_Comp3VolumeFraction->SetSelectedNode(compVolNode); if (dynamic_cast<mitk::BallModel<>*>(signalModel)) { mitk::BallModel<>* model = dynamic_cast<mitk::BallModel<>*>(signalModel); m_Controls->m_BallWidget1->SetT2(model->GetT2()); m_Controls->m_BallWidget1->SetT1(model->GetT1()); m_Controls->m_BallWidget1->SetD(model->GetDiffusivity()); m_Controls->m_Compartment3Box->setCurrentIndex(0); break; } else if (dynamic_cast<mitk::AstroStickModel<>*>(signalModel)) { mitk::AstroStickModel<>* model = dynamic_cast<mitk::AstroStickModel<>*>(signalModel); m_Controls->m_AstrosticksWidget1->SetT2(model->GetT2()); m_Controls->m_AstrosticksWidget1->SetT1(model->GetT1()); m_Controls->m_AstrosticksWidget1->SetD(model->GetDiffusivity()); m_Controls->m_AstrosticksWidget1->SetRandomizeSticks(model->GetRandomizeSticks()); m_Controls->m_Compartment3Box->setCurrentIndex(1); break; } else if (dynamic_cast<mitk::DotModel<>*>(signalModel)) { mitk::DotModel<>* model = dynamic_cast<mitk::DotModel<>*>(signalModel); m_Controls->m_DotWidget1->SetT2(model->GetT2()); m_Controls->m_DotWidget1->SetT1(model->GetT1()); m_Controls->m_Compartment3Box->setCurrentIndex(2); break; } else if (dynamic_cast<mitk::RawShModel<>*>(signalModel)) { mitk::RawShModel<>* model = dynamic_cast<mitk::RawShModel<>*>(signalModel); m_Controls->m_PrototypeWidget3->SetNumberOfSamples(model->GetMaxNumKernels()); m_Controls->m_PrototypeWidget3->SetMinFa(model->GetFaRange().first); m_Controls->m_PrototypeWidget3->SetMaxFa(model->GetFaRange().second); m_Controls->m_PrototypeWidget3->SetMinAdc(model->GetAdcRange().first); m_Controls->m_PrototypeWidget3->SetMaxAdc(model->GetAdcRange().second); m_Controls->m_Compartment3Box->setCurrentIndex(3); break; } break; } case 4: { if (compVolNode.IsNotNull()) m_Controls->m_Comp4VolumeFraction->SetSelectedNode(compVolNode); if (dynamic_cast<mitk::BallModel<>*>(signalModel)) { mitk::BallModel<>* model = dynamic_cast<mitk::BallModel<>*>(signalModel); m_Controls->m_BallWidget2->SetT2(model->GetT2()); m_Controls->m_BallWidget2->SetT1(model->GetT1()); m_Controls->m_BallWidget2->SetD(model->GetDiffusivity()); m_Controls->m_Compartment4Box->setCurrentIndex(1); break; } else if (dynamic_cast<mitk::AstroStickModel<>*>(signalModel)) { mitk::AstroStickModel<>* model = dynamic_cast<mitk::AstroStickModel<>*>(signalModel); m_Controls->m_AstrosticksWidget2->SetT2(model->GetT2()); m_Controls->m_AstrosticksWidget2->SetT1(model->GetT1()); m_Controls->m_AstrosticksWidget2->SetD(model->GetDiffusivity()); m_Controls->m_AstrosticksWidget2->SetRandomizeSticks(model->GetRandomizeSticks()); m_Controls->m_Compartment4Box->setCurrentIndex(2); break; } else if (dynamic_cast<mitk::DotModel<>*>(signalModel)) { mitk::DotModel<>* model = dynamic_cast<mitk::DotModel<>*>(signalModel); m_Controls->m_DotWidget2->SetT2(model->GetT2()); m_Controls->m_DotWidget2->SetT1(model->GetT1()); m_Controls->m_Compartment4Box->setCurrentIndex(3); break; } else if (dynamic_cast<mitk::RawShModel<>*>(signalModel)) { mitk::RawShModel<>* model = dynamic_cast<mitk::RawShModel<>*>(signalModel); m_Controls->m_PrototypeWidget4->SetNumberOfSamples(model->GetMaxNumKernels()); m_Controls->m_PrototypeWidget4->SetMinFa(model->GetFaRange().first); m_Controls->m_PrototypeWidget4->SetMaxFa(model->GetFaRange().second); m_Controls->m_PrototypeWidget4->SetMinAdc(model->GetAdcRange().first); m_Controls->m_PrototypeWidget4->SetMaxAdc(model->GetAdcRange().second); m_Controls->m_Compartment4Box->setCurrentIndex(4); break; } break; } } } if ( m_Parameters.m_SignalGen.m_MaskImage ) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(m_Parameters.m_SignalGen.m_MaskImage.GetPointer()); image->SetVolume(m_Parameters.m_SignalGen.m_MaskImage->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Tissue mask"); GetDataStorage()->Add(node); m_Controls->m_MaskComboBox->SetSelectedNode(node); } if ( m_Parameters.m_SignalGen.m_FrequencyMap ) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(m_Parameters.m_SignalGen.m_FrequencyMap.GetPointer()); image->SetVolume(m_Parameters.m_SignalGen.m_FrequencyMap->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Frequency map"); GetDataStorage()->Add(node); m_Controls->m_FrequencyMapBox->SetSelectedNode(node); } } void QmitkFiberfoxView::ShowAdvancedOptions(int state) { if (state) { m_Controls->m_AdvancedSignalOptionsFrame->setVisible(true); m_Controls->m_AdvancedOptionsBox_2->setChecked(true); } else { m_Controls->m_AdvancedSignalOptionsFrame->setVisible(false); m_Controls->m_AdvancedOptionsBox_2->setChecked(false); } } void QmitkFiberfoxView::Comp1ModelFrameVisibility(int index) { m_Controls->m_StickWidget1->setVisible(false); m_Controls->m_ZeppelinWidget1->setVisible(false); m_Controls->m_TensorWidget1->setVisible(false); m_Controls->m_PrototypeWidget1->setVisible(false); switch (index) { case 0: m_Controls->m_StickWidget1->setVisible(true); break; case 1: m_Controls->m_ZeppelinWidget1->setVisible(true); break; case 2: m_Controls->m_TensorWidget1->setVisible(true); break; case 3: m_Controls->m_PrototypeWidget1->setVisible(true); break; } } void QmitkFiberfoxView::Comp2ModelFrameVisibility(int index) { m_Controls->m_StickWidget2->setVisible(false); m_Controls->m_ZeppelinWidget2->setVisible(false); m_Controls->m_TensorWidget2->setVisible(false); m_Controls->m_Comp2FractionFrame->setVisible(false); switch (index) { case 0: break; case 1: m_Controls->m_StickWidget2->setVisible(true); m_Controls->m_Comp2FractionFrame->setVisible(true); break; case 2: m_Controls->m_ZeppelinWidget2->setVisible(true); m_Controls->m_Comp2FractionFrame->setVisible(true); break; case 3: m_Controls->m_TensorWidget2->setVisible(true); m_Controls->m_Comp2FractionFrame->setVisible(true); break; } } void QmitkFiberfoxView::Comp3ModelFrameVisibility(int index) { m_Controls->m_BallWidget1->setVisible(false); m_Controls->m_AstrosticksWidget1->setVisible(false); m_Controls->m_DotWidget1->setVisible(false); m_Controls->m_PrototypeWidget3->setVisible(false); switch (index) { case 0: m_Controls->m_BallWidget1->setVisible(true); break; case 1: m_Controls->m_AstrosticksWidget1->setVisible(true); break; case 2: m_Controls->m_DotWidget1->setVisible(true); break; case 3: m_Controls->m_PrototypeWidget3->setVisible(true); break; } } void QmitkFiberfoxView::Comp4ModelFrameVisibility(int index) { m_Controls->m_BallWidget2->setVisible(false); m_Controls->m_AstrosticksWidget2->setVisible(false); m_Controls->m_DotWidget2->setVisible(false); m_Controls->m_PrototypeWidget4->setVisible(false); m_Controls->m_Comp4FractionFrame->setVisible(false); switch (index) { case 0: break; case 1: m_Controls->m_BallWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 2: m_Controls->m_AstrosticksWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 3: m_Controls->m_DotWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 4: m_Controls->m_PrototypeWidget4->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; } } void QmitkFiberfoxView::OnAddMotion(int value) { if (value>0) m_Controls->m_MotionArtifactFrame->setVisible(true); else m_Controls->m_MotionArtifactFrame->setVisible(false); } void QmitkFiberfoxView::OnAddDrift(int value) { if (value>0) m_Controls->m_DriftFrame->setVisible(true); else m_Controls->m_DriftFrame->setVisible(false); } void QmitkFiberfoxView::OnAddAliasing(int value) { if (value>0) m_Controls->m_AliasingFrame->setVisible(true); else m_Controls->m_AliasingFrame->setVisible(false); } void QmitkFiberfoxView::OnAddSpikes(int value) { if (value>0) m_Controls->m_SpikeFrame->setVisible(true); else m_Controls->m_SpikeFrame->setVisible(false); } void QmitkFiberfoxView::OnAddEddy(int value) { if (value>0) m_Controls->m_EddyFrame->setVisible(true); else m_Controls->m_EddyFrame->setVisible(false); } void QmitkFiberfoxView::OnAddDistortions(int value) { if (value>0) m_Controls->m_DistortionsFrame->setVisible(true); else m_Controls->m_DistortionsFrame->setVisible(false); } void QmitkFiberfoxView::OnAddGhosts(int value) { if (value>0) m_Controls->m_GhostFrame->setVisible(true); else m_Controls->m_GhostFrame->setVisible(false); } void QmitkFiberfoxView::OnAddNoise(int value) { if (value>0) m_Controls->m_NoiseFrame->setVisible(true); else m_Controls->m_NoiseFrame->setVisible(false); } void QmitkFiberfoxView::OnAddRinging(int value) { if (value>0) m_Controls->m_ZeroRinging->setVisible(true); else m_Controls->m_ZeroRinging->setVisible(false); } QmitkFiberfoxView::GradientListType QmitkFiberfoxView::GenerateHalfShell(int NPoints) { NPoints *= 2; GradientListType pointshell; int numB0 = NPoints/20; if (numB0==0) numB0=1; GradientType g; g.Fill(0.0); for (int i=0; i<numB0; i++) pointshell.push_back(g); if (NPoints==0) return pointshell; vnl_vector<double> theta; theta.set_size(NPoints); vnl_vector<double> phi; phi.set_size(NPoints); double C = sqrt(4*itk::Math::pi); phi(0) = 0.0; phi(NPoints-1) = 0.0; for(int i=0; i<NPoints; i++) { theta(i) = acos(-1.0+2.0*i/(NPoints-1.0)) - itk::Math::pi / 2.0; if( i>0 && i<NPoints-1) { phi(i) = (phi(i-1) + C / sqrt(NPoints*(1-(-1.0+2.0*i/(NPoints-1.0))*(-1.0+2.0*i/(NPoints-1.0))))); // % (2*DIST_POINTSHELL_PI); } } for(int i=0; i<NPoints; i++) { g[2] = sin(theta(i)); if (g[2]<0) continue; g[0] = cos(theta(i)) * cos(phi(i)); g[1] = cos(theta(i)) * sin(phi(i)); pointshell.push_back(g); } return pointshell; } template<int ndirs> std::vector<itk::Vector<double,3> > QmitkFiberfoxView::MakeGradientList() { std::vector<itk::Vector<double,3> > retval; vnl_matrix_fixed<double, 3, ndirs>* U = itk::PointShell<ndirs, vnl_matrix_fixed<double, 3, ndirs> >::DistributePointShell(); // Add 0 vector for B0 int numB0 = ndirs/10; if (numB0==0) numB0=1; itk::Vector<double,3> v; v.Fill(0.0); for (int i=0; i<numB0; i++) { retval.push_back(v); } for(int i=0; i<ndirs;i++) { itk::Vector<double,3> v; v[0] = U->get(0,i); v[1] = U->get(1,i); v[2] = U->get(2,i); retval.push_back(v); } return retval; } void QmitkFiberfoxView::GenerateImage() { if (m_Controls->m_FiberBundleComboBox->GetSelectedNode().IsNull() && !mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( m_Controls->m_TemplateComboBox->GetSelectedNode())) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateGradientImage<unsigned int>( m_Controls->m_SizeX->value(), m_Controls->m_SizeY->value(), m_Controls->m_SizeZ->value(), m_Controls->m_SpacingX->value(), m_Controls->m_SpacingY->value(), m_Controls->m_SpacingZ->value()); mitk::Point3D origin; origin[0] = m_Controls->m_SpacingX->value()/2; origin[1] = m_Controls->m_SpacingY->value()/2; origin[2] = m_Controls->m_SpacingZ->value()/2; image->SetOrigin(origin); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Dummy"); GetDataStorage()->Add(node); m_SelectedImageNode = node; mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } UpdateGui(); QMessageBox::information(nullptr, "Template image generated", "You have selected no fiber bundle or diffusion-weighted image, which can be used to simulate a new diffusion-weighted image. A template image with the specified geometry has been generated that can be used to draw artificial fibers (see view 'Fiber Generator')."); } else if (m_Controls->m_FiberBundleComboBox->GetSelectedNode().IsNotNull()) SimulateImageFromFibers(m_Controls->m_FiberBundleComboBox->GetSelectedNode()); else if ( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( m_Controls->m_TemplateComboBox->GetSelectedNode()) ) SimulateForExistingDwi(m_Controls->m_TemplateComboBox->GetSelectedNode()); else QMessageBox::information(nullptr, "No image generated", "You have selected no fiber bundle or diffusion-weighted image, which can be used to simulate a new diffusion-weighted image."); } void QmitkFiberfoxView::SetFocus() { } void QmitkFiberfoxView::SimulateForExistingDwi(mitk::DataNode* imageNode) { bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image *>(imageNode->GetData())) ); if ( !isDiffusionImage ) { return; } UpdateParametersFromGui(); mitk::Image::Pointer diffImg = dynamic_cast<mitk::Image*>(imageNode->GetData()); ItkDwiType::Pointer itkVectorImagePointer = ItkDwiType::New(); mitk::CastToItkImage(diffImg, itkVectorImagePointer); m_TractsToDwiFilter = itk::TractsToDWIImageFilter< short >::New(); m_Parameters.m_Misc.m_ParentNode = imageNode; m_Parameters.m_SignalGen.m_SignalScale = 1; m_Parameters.m_Misc.m_ResultNode->SetName("b"+QString::number(m_Parameters.m_SignalGen.GetBvalue()).toStdString() +"_"+m_Parameters.m_Misc.m_SignalModelString +m_Parameters.m_Misc.m_ArtifactModelString); m_Parameters.ApplyDirectionMatrix(); m_TractsToDwiFilter->SetParameters(m_Parameters); m_TractsToDwiFilter->SetInputImage(itkVectorImagePointer); m_Thread.start(QThread::LowestPriority); } void QmitkFiberfoxView::SimulateImageFromFibers(mitk::DataNode* fiberNode) { mitk::FiberBundle::Pointer fiberBundle = dynamic_cast<mitk::FiberBundle*>(fiberNode->GetData()); if (fiberBundle->GetNumFibers()<=0) { return; } UpdateParametersFromGui(); m_TractsToDwiFilter = itk::TractsToDWIImageFilter< short >::New(); m_Parameters.m_Misc.m_ParentNode = fiberNode; m_Parameters.m_Misc.m_ResultNode->SetName("b"+QString::number(m_Parameters.m_SignalGen.GetBvalue()).toStdString() +"_"+m_Parameters.m_Misc.m_SignalModelString +m_Parameters.m_Misc.m_ArtifactModelString); if ( m_Controls->m_TemplateComboBox->GetSelectedNode().IsNotNull() && mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image*> (m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()) ) ) { bool first = true; bool ok = true; mitk::Image::Pointer diffImg = dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()); itk::Image< itk::DiffusionTensor3D< double >, 3 >::Pointer tensorImage = nullptr; const int shOrder = 2; typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,shOrder,ODF_SAMPLING_SIZE> QballFilterType; QballFilterType::CoefficientImageType::Pointer itkFeatureImage = nullptr; ItkDoubleImgType::Pointer adcImage = nullptr; for (unsigned int i=0; i<m_Parameters.m_FiberModelList.size()+m_Parameters.m_NonFiberModelList.size(); i++) { mitk::RawShModel<>* model = nullptr; if (i<m_Parameters.m_FiberModelList.size()) model = dynamic_cast< mitk::RawShModel<>* >(m_Parameters.m_FiberModelList.at(i)); else model = dynamic_cast< mitk::RawShModel<>* >(m_Parameters.m_NonFiberModelList.at(i-m_Parameters.m_FiberModelList.size())); if (model!=0 && model->GetNumberOfKernels()<=0) { if (first==true) { ItkDwiType::Pointer itkVectorImagePointer = ItkDwiType::New(); mitk::CastToItkImage(diffImg, itkVectorImagePointer); typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, double > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); filter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); filter->SetGradientImage(dynamic_cast<mitk::GradientDirectionsProperty *>(diffImg->GetProperty(mitk::DiffusionPropertyHelper::GetGradientContainerPropertyName().c_str()).GetPointer())->GetGradientDirectionsContainerCopy(), itkVectorImagePointer ); filter->Update(); tensorImage = filter->GetOutput(); QballFilterType::Pointer qballfilter = QballFilterType::New(); qballfilter->SetGradientImage(mitk::DiffusionPropertyHelper::GetGradientContainer(diffImg), itkVectorImagePointer ); qballfilter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); qballfilter->SetLambda(0.006); qballfilter->SetNormalizationMethod(QballFilterType::QBAR_RAW_SIGNAL); qballfilter->Update(); itkFeatureImage = qballfilter->GetCoefficientImage(); itk::AdcImageFilter< short, double >::Pointer adcFilter = itk::AdcImageFilter< short, double >::New(); adcFilter->SetInput( itkVectorImagePointer ); adcFilter->SetGradientDirections(mitk::DiffusionPropertyHelper::GetGradientContainer(diffImg)); adcFilter->SetB_value(mitk::DiffusionPropertyHelper::GetReferenceBValue(diffImg)); adcFilter->Update(); adcImage = adcFilter->GetOutput(); } ok = model->SampleKernels(diffImg, m_Parameters.m_SignalGen.m_MaskImage, tensorImage, itkFeatureImage, adcImage); if (!ok) break; } } if (!ok) { QMessageBox::information( nullptr, "Simulation cancelled", "No valid prototype signals could be sampled."); return; } } else if ( m_Controls->m_Compartment1Box->currentIndex()==3 || m_Controls->m_Compartment3Box->currentIndex()==3 || m_Controls->m_Compartment4Box->currentIndex()==4 ) { QMessageBox::information( nullptr, "Simulation cancelled", "Prototype signal but no diffusion-weighted image selected to sample signal from."); return; } m_Parameters.ApplyDirectionMatrix(); m_TractsToDwiFilter->SetParameters(m_Parameters); m_TractsToDwiFilter->SetFiberBundle(fiberBundle); m_Thread.start(QThread::LowestPriority); } void QmitkFiberfoxView::SetBvalsEdit() { // SELECT FOLDER DIALOG std::string filename; filename = QFileDialog::getOpenFileName(nullptr, "Select bvals file", QString(filename.c_str())).toStdString(); if (filename.empty()) m_Controls->m_LoadBvalsEdit->setText("-"); else m_Controls->m_LoadBvalsEdit->setText(QString(filename.c_str())); } void QmitkFiberfoxView::SetBvecsEdit() { // SELECT FOLDER DIALOG std::string filename; filename = QFileDialog::getOpenFileName(nullptr, "Select bvecs file", QString(filename.c_str())).toStdString(); if (filename.empty()) m_Controls->m_LoadBvecsEdit->setText("-"); else m_Controls->m_LoadBvecsEdit->setText(QString(filename.c_str())); } void QmitkFiberfoxView::SetOutputPath() { // SELECT FOLDER DIALOG std::string outputPath; outputPath = QFileDialog::getExistingDirectory(nullptr, "Save images to...", QString(outputPath.c_str())).toStdString(); if (outputPath.empty()) m_Controls->m_SavePathEdit->setText("-"); else { outputPath += "/"; m_Controls->m_SavePathEdit->setText(QString(outputPath.c_str())); } } void QmitkFiberfoxView::UpdateGui() { OnTlineChanged(); m_Controls->m_GeometryFrame->setEnabled(true); m_Controls->m_GeometryMessage->setVisible(false); m_Controls->m_DiffusionPropsMessage->setVisible(false); m_Controls->m_LoadGradientsFrame->setVisible(false); m_Controls->m_GenerateGradientsFrame->setVisible(false); if (m_Controls->m_UseBvalsBvecsBox->isChecked()) m_Controls->m_LoadGradientsFrame->setVisible(true); else m_Controls->m_GenerateGradientsFrame->setVisible(true); // Signal generation gui if (m_Controls->m_MaskComboBox->GetSelectedNode().IsNotNull() || m_Controls->m_TemplateComboBox->GetSelectedNode().IsNotNull()) { m_Controls->m_GeometryMessage->setVisible(true); m_Controls->m_GeometryFrame->setEnabled(false); } if ( m_Controls->m_TemplateComboBox->GetSelectedNode().IsNotNull() && mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image*>(m_Controls->m_TemplateComboBox->GetSelectedNode()->GetData()) ) ) { m_Controls->m_DiffusionPropsMessage->setVisible(true); m_Controls->m_GeometryMessage->setVisible(true); m_Controls->m_GeometryFrame->setEnabled(false); m_Controls->m_LoadGradientsFrame->setVisible(false); m_Controls->m_GenerateGradientsFrame->setVisible(false); } }
46.690651
331
0.726568
[ "geometry", "vector", "model" ]
a3088a77a7b221da65e0653bf4034594bab39d53
4,784
cpp
C++
core/LunaClient.cpp
webosose/com.webos.service.unifiedsearch
9e1c606dc6084476b711e64110b894a3f9bff019
[ "Apache-2.0" ]
null
null
null
core/LunaClient.cpp
webosose/com.webos.service.unifiedsearch
9e1c606dc6084476b711e64110b894a3f9bff019
[ "Apache-2.0" ]
null
null
null
core/LunaClient.cpp
webosose/com.webos.service.unifiedsearch
9e1c606dc6084476b711e64110b894a3f9bff019
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2020 LG Electronics, 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. // // SPDX-License-Identifier: Apache-2.0 #include "LunaClient.h" #include "Logger.h" LS::Handle *LunaClient::s_mainHandle = nullptr; vector<LunaClient*> LunaClient::s_deferred; JValue& LunaClient::getEmptyPayload() { static JValue empty; if (empty.isNull()) { empty = pbnjson::Object(); } return empty; } JValue& LunaClient::getSubscriptionPayload() { static JValue subscription; if (subscription.isNull()) { subscription = pbnjson::Object(); subscription.put("subscribe", true); } return subscription; } bool LunaClient::_onServerStatus(LSHandle* sh, LSMessage* message, void* context) { LunaClient* client = static_cast<LunaClient*>(context); Message response(message); JValue payload = JDomParser::fromString(response.getPayload()); bool connected = false; if (payload.isNull() || !payload.hasKey("connected") || (payload["connected"].asBool(connected) != CONV_OK)) return true; ; if (connected) Logger::info("LunaClient", __FUNCTION__, Logger::format("Service is up: %s", client->getName().c_str())); else Logger::info("LunaClient", __FUNCTION__, Logger::format("Service is down: %s", client->getName().c_str())); client->m_isConnected = connected; client->m_callMap.clear(); client->m_taskMap.clear(); client->m_callId = 0; client->onServerStatusChanged(connected); return true; } LunaClient::LunaClient(const string& name) : m_name(name) , m_isConnected(false) , m_callId(0) { } LunaClient::~LunaClient() { } void LunaClient::initialize() { if (!s_mainHandle) { Logger::info("LunaClient", __FUNCTION__, Logger::format("Main handle isn't ready, defer initialization: %s", getName().c_str())); s_deferred.push_back(this); return; } JValue requestPayload = pbnjson::Object(); requestPayload.put("serviceName", getName()); m_statusCall = s_mainHandle->callMultiReply( "luna://com.webos.service.bus/signal/registerServerStatus", requestPayload.stringify().c_str(), _onServerStatus, this ); onInitialzed(); } void LunaClient::finalize() { m_statusCall.cancel(); onFinalized(); } LunaClient::LunaReqTaskID LunaClient::call(string method, string payload, LunaReqCB callback, bool subscribe) { if (!isConnected()) { Logger::warning("LunaClient", __FUNCTION__, Logger::format("[LunaClient::call] '%s' called before connecting.", method.c_str())); return 0; } LunaReqTaskID id = ++m_callId; auto task = make_shared<LunaReqTask>(this, id, callback, subscribe); if (subscribe) { m_callMap.insert({id, getMainHandle()->callMultiReply(method.c_str(), payload.c_str(), _onResponse, task.get())}); m_taskMap.insert({id, task}); } else { m_callMap.insert({id, getMainHandle()->callOneReply(method.c_str(), payload.c_str(), _onResponse, task.get())}); m_taskMap.insert({id, task}); } return id; } bool LunaClient::cancel(LunaReqTaskID id) { auto it = m_callMap.find(id); if (it == m_callMap.end()) { return false; } it->second.cancel(); m_callMap.erase(id); m_taskMap.erase(id); return true; } bool LunaClient::_onResponse(LSHandle* sh, LSMessage* message, void* context) { LunaReqTask *task = static_cast<LunaReqTask*>(context); LunaClient *client = task->client; bool ret = true; if (task->callback) { ret = task->callback(message); } if (!task->isSubscribe) { client->m_callMap.erase(task->id); client->m_taskMap.erase(task->id); } return ret; } void LunaClient::setMainHandle(LS::Handle *handle) { if (s_mainHandle) { Logger::warning("LunaClient", __FUNCTION__, "[Warning] main handle already exist. Ignored!"); return; } s_mainHandle = handle; while (s_deferred.size()) { auto client = s_deferred.back(); Logger::info("LunaClient", __FUNCTION__, Logger::format("Main handle is ready now, re-initialization: %s", client->getName().c_str())); client->initialize(); s_deferred.pop_back(); } }
28.47619
143
0.660326
[ "object", "vector" ]
a30d95a54568b3b2bfdf24ebfa7d5b352c67f8bc
9,177
cpp
C++
cpid/redisclient.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
629
2018-11-19T21:03:01.000Z
2022-02-25T03:31:40.000Z
cpid/redisclient.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
27
2018-11-23T22:49:28.000Z
2020-05-15T21:09:30.000Z
cpid/redisclient.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
129
2018-11-22T01:16:56.000Z
2022-03-29T15:24:16.000Z
/* * Copyright (c) 2017-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 "redisclient.h" #include <unordered_map> #include <fmt/format.h> namespace cpid { namespace { template <typename ForwardIt> std::string formatT(ForwardIt begin, ForwardIt end) { int argc = int(std::distance(begin, end)); std::vector<char const*> argv; std::vector<size_t> argvlen; for (auto it = begin; it != end; ++it) { argv.push_back(it->data()); argvlen.push_back(it->size()); } char* target; int len = redisFormatCommandArgv(&target, argc, argv.data(), argvlen.data()); if (len == -1) { throw std::runtime_error("Out of memory"); } else if (len == -2) { throw std::runtime_error("Invalid format string"); } else { auto str = std::string(target, len); redisFreeCommand(target); return str; } throw std::runtime_error("Unknown error code: " + std::to_string(len)); } } // namespace RedisClient::RedisClient( std::string_view host, int port, std::string_view name) { struct timeval timeout = {.tv_sec = 10}; redis_ = redisConnectWithTimeout(host.data(), port, timeout); if (redis_ == nullptr) { throw std::runtime_error("Cannot initialize redis client"); } if (redis_->err != 0) { throw std::runtime_error( "Error connecting to redis: " + std::string(redis_->errstr)); } if (name.size() > 0) { auto reply = command({"CLIENT", "SETNAME", name}); if (reply.isError()) { throw std::runtime_error(fmt::format( "Failed to set requested name '{}';: {}", name, reply.error())); } } } RedisClient::~RedisClient() { if (redis_ != nullptr) { redisFree(redis_); } } std::string_view RedisClient::host() const { return std::string_view(redis_->tcp.host); } int RedisClient::port() const { return redis_->tcp.port; } bool RedisClient::isConnected() const { // This is not completely bullet-proof. We'll get I/O errors on timeouts, for // example, and EOF errors if the connction was dropped. if (redis_->err == REDIS_ERR_IO || redis_->err == REDIS_ERR_EOF) { return false; } return true; } void RedisClient::reconnect() const { if (redisReconnect(redis_) != REDIS_OK) { throw std::runtime_error( "Error connecting to redis: " + std::string(redis_->errstr)); } } std::string RedisClient::format(char const* fmt, ...) { va_list args; va_start(args, fmt); char* target; int len = redisvFormatCommand(&target, fmt, args); va_end(args); if (len == -1) { throw std::runtime_error("Out of memory"); } else if (len == -2) { throw std::runtime_error("Invalid format string"); } else { auto str = std::string(target, len); redisFreeCommand(target); return str; } throw std::runtime_error("Unknown error code: " + std::to_string(len)); } std::string RedisClient::format(std::initializer_list<std::string_view> args) { return formatT(args.begin(), args.end()); } std::string RedisClient::format(std::vector<std::string_view> const& args) { return formatT(args.begin(), args.end()); } RedisReply RedisClient::command(char const* fmt, ...) { va_list args; va_start(args, fmt); void* reply = redisvCommand(redis_, fmt, args); va_end(args); if (reply == nullptr) { throw std::runtime_error(redis_->errstr); } return RedisReply(reply); } RedisReply RedisClient::command(std::initializer_list<std::string_view> args) { return command(format(args)); } RedisReply RedisClient::command(std::vector<std::string_view> const& args) { return command(format(args)); } /// Sends a formatted command RedisReply RedisClient::command(std::string_view cmd) { int ret = redisAppendFormattedCommand(redis_, cmd.data(), cmd.size()); if (ret != REDIS_OK) { throw std::runtime_error(redis_->errstr); } return getReply(); } /** * Sends a list of formatted commands in a single request. * * This function peforms pipelining, assuming all elements in `cmds` are * formatted Redis commands. The function will wait for all replies (i.e. * `cmds.size()` replies) and then return all of them. */ std::vector<RedisReply> RedisClient::commands( std::vector<std::string> const& cmds) { for (auto const& cmd : cmds) { int ret = redisAppendFormattedCommand(redis_, cmd.c_str(), cmd.size()); if (ret != REDIS_OK) { throw std::runtime_error(redis_->errstr); } } std::vector<RedisReply> replies; for (auto i = 0U; i < cmds.size(); i++) { replies.emplace_back(getReply()); } return replies; } RedisReply RedisClient::getReply() { void* reply; int ret = redisGetReply(redis_, &reply); if (ret != REDIS_OK || reply == nullptr) { throw std::runtime_error(redis_->errstr); } return RedisReply(reply); } bool RedisClient::ping() { auto reply = command("PING"); auto v = reply.statusv(); return v == "PONG" || v == "pong"; } RedisReply RedisClient::set(std::string_view key, std::string_view value) { return command({"SET", key, value}); } RedisReply RedisClient::get(std::string_view key) { return command({"GET", key}); } redisContext* RedisClient::ctx() { return redis_; } RedisReply::RedisReply(void* reply, bool own) : reply_(static_cast<redisReply*>(reply)), owns_(own) { if (reply_->type == REDIS_REPLY_ARRAY) { elements_.reserve(reply_->elements); for (size_t i = 0; i < reply_->elements; i++) { elements_.push_back(RedisReply(reply_->element[i], false)); } } } RedisReply::RedisReply(RedisReply&& other) : reply_(other.reply_), owns_(other.owns_), elements_(std::move(other.elements_)) { other.reply_ = nullptr; } RedisReply::~RedisReply() { if (reply_ != nullptr && owns_) { freeReplyObject(reply_); } } RedisReply& RedisReply::operator=(RedisReply&& other) { if (reply_ != nullptr) { freeReplyObject(reply_); } reply_ = other.reply_; owns_ = other.owns_; elements_ = std::move(other.elements_); other.reply_ = nullptr; return *this; } bool RedisReply::isString() const { return reply_ != nullptr && reply_->type == REDIS_REPLY_STRING; } bool RedisReply::isArray() const { return reply_ != nullptr && reply_->type == REDIS_REPLY_ARRAY; } bool RedisReply::isInteger() const { return reply_ != nullptr && reply_->type == REDIS_REPLY_INTEGER; } bool RedisReply::isNil() const { return reply_ != nullptr && reply_->type == REDIS_REPLY_NIL; } bool RedisReply::isStatus() const { return reply_ != nullptr && reply_->type == REDIS_REPLY_STATUS; } bool RedisReply::isError() const { return reply_ != nullptr && reply_->type == REDIS_REPLY_ERROR; } std::string RedisReply::string() const { ensureType(REDIS_REPLY_STRING); return std::string(reply_->str, reply_->len); } std::string_view RedisReply::stringv() const { ensureType(REDIS_REPLY_STRING); return std::string_view(reply_->str, reply_->len); } /// Convenience method for array replies consisting of strings. std::vector<std::string_view> RedisReply::stringvs() const { ensureType(REDIS_REPLY_ARRAY); std::vector<std::string_view> res(elements_.size()); for (auto i = 0U; i < elements_.size(); i++) { res[i] = elements_[i].stringv(); } return res; } int64_t RedisReply::integer() const { ensureType(REDIS_REPLY_INTEGER); return reply_->integer; } std::string RedisReply::status() const { ensureType(REDIS_REPLY_STATUS); return std::string(reply_->str, reply_->len); } std::string_view RedisReply::statusv() const { ensureType(REDIS_REPLY_STATUS); return std::string_view(reply_->str, reply_->len); } std::string RedisReply::error() const { ensureType(REDIS_REPLY_ERROR); return std::string(reply_->str, reply_->len); } bool RedisReply::ok() const { ensureType(REDIS_REPLY_STATUS); return strcasecmp(reply_->str, "ok") == 0; } size_t RedisReply::size() const { ensureType(REDIS_REPLY_ARRAY); return elements_.size(); } RedisReply& RedisReply::at(size_t index) { ensureType(REDIS_REPLY_ARRAY); return elements_.at(index); } RedisReply::Iterator RedisReply::begin() { ensureType(REDIS_REPLY_ARRAY); return elements_.begin(); } RedisReply::Iterator RedisReply::end() { ensureType(REDIS_REPLY_ARRAY); return elements_.end(); } void RedisReply::ensureType(int type) const { if (reply_ == nullptr) { throw std::runtime_error("No reply set"); } if (type != REDIS_REPLY_ERROR && reply_->type == REDIS_REPLY_ERROR) { throw std::runtime_error("Error: " + std::string(reply_->str)); } if (reply_->type != type) { static std::unordered_map<decltype(REDIS_REPLY_ARRAY), std::string> typeToStr = {{REDIS_REPLY_ARRAY, "ARRAY"}, {REDIS_REPLY_ERROR, "ERROR"}, {REDIS_REPLY_INTEGER, "INTEGER"}, {REDIS_REPLY_NIL, "NIL"}, {REDIS_REPLY_STATUS, "STATUS"}, {REDIS_REPLY_STRING, "STRING"}}; throw std::runtime_error(fmt::format( "Expected reply of type {}, got {}", typeToStr[type], typeToStr[reply_->type])); } // ok! } } // namespace cpid
25.923729
79
0.665577
[ "vector" ]
a31003f281ba795e258b33f3a35cfa6f19150405
15,137
cpp
C++
src/core/tests/coordinate_range.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
ngraph/test/coordinate_range.cpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
ngraph/test/coordinate_range.cpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <algorithm> #include <ngraph/coordinate_range.hpp> #include <numeric> #include <utility> #include "gtest/gtest.h" using namespace ngraph; using namespace ngraph::coordinates; using Index = size_t; using ExpectedOutput = std::vector<std::pair<Index, Coordinate>>; /// /// /// SliceRange /// /// TEST(coordinate_range, slice_range_shape0d) { const Shape s; const Coordinate start_corner(s.size()); auto slice_range = slice(s, start_corner, s); auto it = slice_range.begin(); EXPECT_EQ(it, begin(slice_range)); EXPECT_FALSE(it == slice_range.end()); auto v = *it; // if it is not end it has to be dereferencable; (void)v; EXPECT_TRUE(++it == slice_range.end()); } TEST(coordinate_range, slice_range_shape1d) { const Shape s{3}; const Coordinate start_corner(s.size()); const ExpectedOutput expected{{0, {0}}, {1, {1}}, {2, {2}}}; ASSERT_EQ(expected.size(), shape_size(s)) << "check epxected data"; auto expected_val = begin(expected); for (auto slice_range : slice(s, start_corner, s)) { auto index = slice_range.begin_index; for (size_t i = 0; i < slice_range.element_number; index += slice_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, slice_range_shape2d) { const Shape s{2, 3}; const Coordinate start_corner(s.size()); // clang-format off const ExpectedOutput expected{ {0, {0, 0}}, {1, {0, 1}}, {2, {0, 2}}, {3, {1, 0}}, {4, {1, 1}}, {5, {1, 2}}}; // clang-format on ASSERT_EQ(expected.size(), shape_size(s)) << "check epxected data"; auto expected_val = begin(expected); for (auto slice_range : slice(s, start_corner, s)) { auto index = slice_range.begin_index; for (size_t i = 0; i < slice_range.element_number; index += slice_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, slice_range_shape3d) { const Shape s{2, 3, 4}; const Coordinate start_corner(s.size()); // clang-format off const ExpectedOutput expected{ {0, {0, 0, 0}}, {1, {0, 0, 1}}, {2, {0, 0, 2}}, {3, {0, 0, 3}}, {4, {0, 1, 0}}, {5, {0, 1, 1}}, {6, {0, 1, 2}}, {7, {0, 1, 3}}, {8, {0, 2, 0}}, {9, {0, 2, 1}}, {10, {0, 2, 2}}, {11, {0, 2, 3}}, {12, {1, 0, 0}}, {13, {1, 0, 1}}, {14, {1, 0, 2}}, {15, {1, 0, 3}}, {16, {1, 1, 0}}, {17, {1, 1, 1}}, {18, {1, 1, 2}}, {19, {1, 1, 3}}, {20, {1, 2, 0}}, {21, {1, 2, 1}}, {22, {1, 2, 2}}, {23, {1, 2, 3}}}; // clang-format on ASSERT_EQ(expected.size(), shape_size(s)) << "check epxected data"; auto expected_val = begin(expected); for (auto slice_range : slice(s, start_corner, s)) { auto index = slice_range.begin_index; for (size_t i = 0; i < slice_range.element_number; index += slice_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)); } TEST(coordinate_range, slice_range_zero_sized_axis) { const Shape s{2, 0, 4}; const Coordinate start_corner(s.size()); auto slice_range = slice(s, start_corner, s); auto it = slice_range.begin(); EXPECT_TRUE(it == slice_range.end()) << "Expect empyt range"; } /// /// slice specyfic test /// TEST(coordinate_range, slice_range_input_validataion) { const Shape s{10, 10, 10}; EXPECT_THROW(slice(s, {1}, {1}), std::domain_error); EXPECT_THROW(slice(s, s, {1}), std::domain_error); EXPECT_THROW(slice(s, {1}, s), std::domain_error); EXPECT_THROW(slice(s, s, s, {}), std::domain_error); } namespace { Shape sliced_shape(const std::vector<size_t>& start_corner, const std::vector<size_t>& end_corner) { Shape s; std::transform(end_corner.begin(), end_corner.end(), start_corner.begin(), std::back_inserter(s), [](size_t e, size_t b) { return e - b; }); return s; } Shape sliced_shape(const std::vector<size_t>& start_corner, const std::vector<size_t>& end_corner, const std::vector<size_t>& strides) { Shape s = sliced_shape(start_corner, end_corner); std::transform(s.begin(), s.end(), strides.begin(), s.begin(), [](size_t e, size_t s) { return (e + s - 1) / s; }); return s; } } // namespace TEST(coordinate_range, slice_range_corner) { const Shape s{10, 10}; const Coordinate source_start_corner{3, 3}; const Coordinate source_end_corner{6, 6}; const ExpectedOutput expected{{33, {3, 3}}, {34, {3, 4}}, {35, {3, 5}}, {43, {4, 3}}, {44, {4, 4}}, {45, {4, 5}}, {53, {5, 3}}, {54, {5, 4}}, {55, {5, 5}}}; ASSERT_EQ(expected.size(), shape_size(sliced_shape(source_start_corner, source_end_corner))) << "check epxected data"; auto expected_val = begin(expected); for (auto slice_range : slice(s, source_start_corner, source_end_corner)) { auto index = slice_range.begin_index; for (size_t i = 0; i < slice_range.element_number; index += slice_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, slice_range_strides) { const Shape s{10, 10}; const Coordinate source_start_corner{0, 0}; const Coordinate source_end_corner{s}; const Strides source_strides = Strides({2, 3}); // clang-format off const ExpectedOutput expected{ {0, {0, 0}}, {3, {0, 3}}, {6, {0, 6}}, {9, {0, 9}}, {20, {2, 0}}, {23, {2, 3}}, {26, {2, 6}}, {29, {2, 9}}, {40, {4, 0}}, {43, {4, 3}}, {46, {4, 6}}, {49, {4, 9}}, {60, {6, 0}}, {63, {6, 3}}, {66, {6, 6}}, {69, {6, 9}}, {80, {8, 0}}, {83, {8, 3}}, {86, {8, 6}}, {89, {8, 9}}}; // clang-format on ASSERT_EQ(expected.size(), shape_size(sliced_shape(source_start_corner, source_end_corner, source_strides))) << "check epxected data"; auto expected_val = begin(expected); for (auto slice_range : slice(s, source_start_corner, source_end_corner, source_strides)) { auto index = slice_range.begin_index; for (size_t i = 0; i < slice_range.element_number; index += slice_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } /// /// /// ReverseRange /// /// TEST(coordinate_range, reverse_range_shape0d) { const Shape s; const AxisSet reverset_axis{}; auto reverse_range = reverse(s, reverset_axis); auto it = reverse_range.begin(); EXPECT_EQ(it, begin(reverse_range)); auto v = *it; // if it is not end it has to be dereferencable; (void)v; EXPECT_TRUE(++it == reverse_range.end()); } TEST(coordinate_range, reverse_range_shape1d) { const Shape s{3}; const AxisSet reverset_axis{}; const ExpectedOutput expected{{0, {0}}, {1, {1}}, {2, {2}}}; EXPECT_EQ(expected.size(), shape_size(s)) << "check epxected data"; auto expected_val = begin(expected); for (auto reverse_range : reverse(s, reverset_axis)) { auto index = reverse_range.begin_index; ASSERT_EQ(reverse_range.direction, Direction::forward); for (size_t i = 0; i < reverse_range.element_number; index += reverse_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, reverse_range_shape2d) { const Shape s{2, 3}; const AxisSet reverset_axis{}; // clang-format off const ExpectedOutput expected{ {0, {0, 0}}, {1, {0, 1}}, {2, {0, 2}}, {3, {1, 0}}, {4, {1, 1}}, {5, {1, 2}}}; // clang-format on EXPECT_EQ(expected.size(), shape_size(s)) << "check epxected data"; auto expected_val = begin(expected); for (auto reverse_range : reverse(s, reverset_axis)) { auto index = reverse_range.begin_index; ASSERT_EQ(reverse_range.direction, Direction::forward); for (size_t i = 0; i < reverse_range.element_number; index += reverse_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, reverse_range_shape3d) { const Shape s{2, 3, 4}; const AxisSet reverset_axis{}; // clang-format off const ExpectedOutput expected{ {0, {0, 0, 0}}, {1, {0, 0, 1}}, {2, {0, 0, 2}}, {3, {0, 0, 3}}, {4, {0, 1, 0}}, {5, {0, 1, 1}}, {6, {0, 1, 2}}, {7, {0, 1, 3}}, {8, {0, 2, 0}}, {9, {0, 2, 1}}, {10, {0, 2, 2}}, {11, {0, 2, 3}}, {12, {1, 0, 0}}, {13, {1, 0, 1}}, {14, {1, 0, 2}}, {15, {1, 0, 3}}, {16, {1, 1, 0}}, {17, {1, 1, 1}}, {18, {1, 1, 2}}, {19, {1, 1, 3}}, {20, {1, 2, 0}}, {21, {1, 2, 1}}, {22, {1, 2, 2}}, {23, {1, 2, 3}}}; // clang-format on EXPECT_EQ(expected.size(), shape_size(s)) << "check epxected data"; auto expected_val = begin(expected); for (auto reverse_range : reverse(s, reverset_axis)) { auto index = reverse_range.begin_index; ASSERT_EQ(reverse_range.direction, Direction::forward); for (size_t i = 0; i < reverse_range.element_number; index += reverse_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, reverse_range_zero_sized_axis) { const Shape s{2, 0, 4}; auto reverse_range = reverse(s, {}); auto it = reverse_range.begin(); EXPECT_TRUE(it == reverse_range.end()) << "Expect empyt range"; } /// /// reverse specyfic test /// TEST(coordinate_range, reverse_range_input_validataion) { const Shape s{10, 10, 10}; EXPECT_THROW(reverse(s, {10}), std::domain_error); } TEST(coordinate_range, reverse_range_2d) { const Shape s{3, 10}; const AxisSet reverset_axis{1}; // clang-format off const ExpectedOutput expected{ {9, {0, 9}}, {8, {0, 8}}, {7, {0, 7}}, {6, {0, 6}}, {5, {0, 5}}, {4, {0, 4}}, {3, {0, 3}}, {2, {0, 2}}, {1, {0, 1}}, {0, {0, 0}}, {19, {1, 9}}, {18, {1, 8}}, {17, {1, 7}}, {16, {1, 6}}, {15, {1, 5}}, {14, {1, 4}}, {13, {1, 3}}, {12, {1, 2}}, {11, {1, 1}}, {10, {1, 0}}, {29, {2, 9}}, {28, {2, 8}}, {27, {2, 7}}, {26, {2, 6}}, {25, {2, 5}}, {24, {2, 4}}, {23, {2, 3}}, {22, {2, 2}}, {21, {2, 1}}, {20, {2, 0}}}; // clang-format on auto expected_val = begin(expected); for (auto reverse_range : reverse(s, reverset_axis)) { auto index = reverse_range.begin_index; ASSERT_EQ(reverse_range.direction, Direction::reverse); for (size_t i = 0; i < reverse_range.element_number; index -= reverse_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, reverse_1_range_3d) { const Shape s{3, 3, 3}; const AxisSet reverset_axis{1}; // clang-format off const ExpectedOutput expected{ {6, {0, 2, 0}}, {7, {0, 2, 1}}, {8, {0, 2, 2}}, {3, {0, 1, 0}}, {4, {0, 1, 1}}, {5, {0, 1, 2}}, {0, {0, 0, 0}}, {1, {0, 0, 1}}, {2, {0, 0, 2}}, {15, {1, 2, 0}}, {16, {1, 2, 1}}, {17, {1, 2, 2}}, {12, {1, 1, 0}}, {13, {1, 1, 1}}, {14, {1, 1, 2}}, {9, {1, 0, 0}}, {10, {1, 0, 1}}, {11, {1, 0, 2}}, {24, {2, 2, 0}}, {25, {2, 2, 1}}, {26, {2, 2, 2}}, {21, {2, 1, 0}}, {22, {2, 1, 1}}, {23, {2, 1, 2}}, {18, {2, 0, 0}}, {19, {2, 0, 1}}, {20, {2, 0, 2}}}; // clang-format on auto expected_val = begin(expected); for (auto reverse_range : reverse(s, reverset_axis)) { auto index = reverse_range.begin_index; ASSERT_EQ(reverse_range.direction, Direction::forward); for (size_t i = 0; i < reverse_range.element_number; index += reverse_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; } TEST(coordinate_range, reverse_2_range_3d) { const Shape s{3, 3, 3}; const AxisSet reverset_axis{1, 2}; // clang-format off const ExpectedOutput expected{ {8, {0, 2, 2}}, {7, {0, 2, 1}}, {6, {0, 2, 0}}, {5, {0, 1, 2}}, {4, {0, 1, 1}}, {3, {0, 1, 0}}, {2, {0, 0, 2}}, {1, {0, 0, 1}}, {0, {0, 0, 0}}, {17, {1, 2, 2}}, {16, {1, 2, 1}}, {15, {1, 2, 0}}, {14, {1, 1, 2}}, {13, {1, 1, 1}}, {12, {1, 1, 0}}, {11, {1, 0, 2}}, {10, {1, 0, 1}}, {9, {1, 0, 0}}, {26, {2, 2, 2}}, {25, {2, 2, 1}}, {24, {2, 2, 0}}, {23, {2, 1, 2}}, {22, {2, 1, 1}}, {21, {2, 1, 0}}, {20, {2, 0, 2}}, {19, {2, 0, 1}}, {18, {2, 0, 0}}}; // clang-format on auto expected_val = begin(expected); for (auto reverse_range : reverse(s, reverset_axis)) { auto index = reverse_range.begin_index; ASSERT_EQ(reverse_range.direction, Direction::reverse); for (size_t i = 0; i < reverse_range.element_number; index -= reverse_range.step, ++i) { EXPECT_EQ(index, expected_val->first); ++expected_val; } } EXPECT_TRUE(expected_val == end(expected)) << "not all expected values return, (" << std::distance(expected_val, end(expected)) << " is missing)"; }
37.283251
148
0.550043
[ "shape", "vector", "transform" ]
a31106d191fed529e8fd658ff8181a631f1634f3
112
cpp
C++
Window.cpp
lopesivan/delegation
c999f32145db3a43d92e01a40947306028c08de5
[ "MIT" ]
null
null
null
Window.cpp
lopesivan/delegation
c999f32145db3a43d92e01a40947306028c08de5
[ "MIT" ]
null
null
null
Window.cpp
lopesivan/delegation
c999f32145db3a43d92e01a40947306028c08de5
[ "MIT" ]
null
null
null
// // Created by ivan on 11/29/15. // #include "Window.h" double Window::area() { return shape->area(); }
11.2
31
0.589286
[ "shape" ]
a313b556cfe82056f84c1dd891c184520ba04f7f
27,644
cc
C++
talk/p2p/client/basicportallocator.cc
udit043/libjingle-0.6.14
acc37d0b3c29e984d6ba986b1edd8b1527e0451b
[ "BSD-3-Clause" ]
2
2017-09-05T03:49:39.000Z
2017-09-09T03:53:10.000Z
talk/p2p/client/basicportallocator.cc
udit043/libjingle-0.6.14
acc37d0b3c29e984d6ba986b1edd8b1527e0451b
[ "BSD-3-Clause" ]
null
null
null
talk/p2p/client/basicportallocator.cc
udit043/libjingle-0.6.14
acc37d0b3c29e984d6ba986b1edd8b1527e0451b
[ "BSD-3-Clause" ]
2
2016-08-17T07:21:08.000Z
2020-03-04T06:21:25.000Z
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <string> #include <vector> #include "talk/base/basicpacketsocketfactory.h" #include "talk/base/common.h" #include "talk/base/helpers.h" #include "talk/base/host.h" #include "talk/base/logging.h" #include "talk/p2p/client/basicportallocator.h" #include "talk/p2p/base/common.h" #include "talk/p2p/base/port.h" #include "talk/p2p/base/relayport.h" #include "talk/p2p/base/stunport.h" #include "talk/p2p/base/tcpport.h" #include "talk/p2p/base/udpport.h" using talk_base::CreateRandomId; using talk_base::CreateRandomString; namespace { const uint32 MSG_CONFIG_START = 1; const uint32 MSG_CONFIG_READY = 2; const uint32 MSG_ALLOCATE = 3; const uint32 MSG_ALLOCATION_PHASE = 4; const uint32 MSG_SHAKE = 5; const uint32 ALLOCATE_DELAY = 250; const uint32 ALLOCATION_STEP_DELAY = 1 * 1000; const int PHASE_UDP = 0; const int PHASE_RELAY = 1; const int PHASE_TCP = 2; const int PHASE_SSLTCP = 3; const int kNumPhases = 4; const float PREF_LOCAL_UDP = 1.0f; const float PREF_LOCAL_STUN = 0.9f; const float PREF_LOCAL_TCP = 0.8f; const float PREF_RELAY = 0.5f; // Modifiers of the above constants const float RELAY_PRIMARY_PREF_MODIFIER = 0.0f; const float RELAY_BACKUP_PREF_MODIFIER = -0.2f; // Returns the phase in which a given local candidate (or rather, the port that // gave rise to that local candidate) would have been created. int LocalCandidateToPhase(const cricket::Candidate& candidate) { cricket::ProtocolType proto; bool result = cricket::StringToProto(candidate.protocol().c_str(), &proto); if (result) { if (candidate.type() == cricket::LOCAL_PORT_TYPE) { switch (proto) { case cricket::PROTO_UDP: return PHASE_UDP; case cricket::PROTO_TCP: return PHASE_TCP; default: ASSERT(false); } } else if (candidate.type() == cricket::STUN_PORT_TYPE) { return PHASE_UDP; } else if (candidate.type() == cricket::RELAY_PORT_TYPE) { switch (proto) { case cricket::PROTO_UDP: return PHASE_RELAY; case cricket::PROTO_TCP: return PHASE_TCP; case cricket::PROTO_SSLTCP: return PHASE_SSLTCP; default: ASSERT(false); } } else { ASSERT(false); } } else { ASSERT(false); } return PHASE_UDP; // reached only with assert failure } const int SHAKE_MIN_DELAY = 45 * 1000; // 45 seconds const int SHAKE_MAX_DELAY = 90 * 1000; // 90 seconds int ShakeDelay() { int range = SHAKE_MAX_DELAY - SHAKE_MIN_DELAY + 1; return SHAKE_MIN_DELAY + CreateRandomId() % range; } } // namespace namespace cricket { const uint32 DISABLE_ALL_PHASES = PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP | PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY; // Performs the allocation of ports, in a sequenced (timed) manner, for a given // network and IP address. class AllocationSequence : public talk_base::MessageHandler { public: AllocationSequence(BasicPortAllocatorSession* session, talk_base::Network* network, PortConfiguration* config, uint32 flags); ~AllocationSequence(); // Disables the phases for a new sequence that this one already covers for an // equivalent network setup. void DisableEquivalentPhases(talk_base::Network* network, PortConfiguration* config, uint32* flags); // Starts and stops the sequence. When started, it will continue allocating // new ports on its own timed schedule. void Start(); void Stop(); // MessageHandler void OnMessage(talk_base::Message* msg); void EnableProtocol(ProtocolType proto); bool ProtocolEnabled(ProtocolType proto) const; private: typedef std::vector<ProtocolType> ProtocolList; void CreateUDPPorts(); void CreateTCPPorts(); void CreateStunPorts(); void CreateRelayPorts(); BasicPortAllocatorSession* session_; talk_base::Network* network_; talk_base::IPAddress ip_; PortConfiguration* config_; bool running_; int step_; int step_of_phase_[kNumPhases]; uint32 flags_; ProtocolList protocols_; }; // BasicPortAllocator BasicPortAllocator::BasicPortAllocator( talk_base::NetworkManager* network_manager, talk_base::PacketSocketFactory* socket_factory) : network_manager_(network_manager), socket_factory_(socket_factory) { ASSERT(socket_factory_ != NULL); Construct(); } BasicPortAllocator::BasicPortAllocator( talk_base::NetworkManager* network_manager) : network_manager_(network_manager), socket_factory_(NULL) { Construct(); } BasicPortAllocator::BasicPortAllocator( talk_base::NetworkManager* network_manager, const talk_base::SocketAddress& stun_address, const talk_base::SocketAddress& relay_address_udp, const talk_base::SocketAddress& relay_address_tcp, const talk_base::SocketAddress& relay_address_ssl) : network_manager_(network_manager), socket_factory_(NULL), stun_address_(stun_address), relay_address_udp_(relay_address_udp), relay_address_tcp_(relay_address_tcp), relay_address_ssl_(relay_address_ssl) { Construct(); } void BasicPortAllocator::Construct() { best_writable_phase_ = -1; allow_tcp_listen_ = true; } BasicPortAllocator::~BasicPortAllocator() { } int BasicPortAllocator::best_writable_phase() const { // If we are configured with an HTTP proxy, the best bet is to use the relay if ((best_writable_phase_ == -1) && ((proxy().type == talk_base::PROXY_HTTPS) || (proxy().type == talk_base::PROXY_UNKNOWN))) { return PHASE_RELAY; } return best_writable_phase_; } PortAllocatorSession *BasicPortAllocator::CreateSession( const std::string &name, const std::string &session_type) { return new BasicPortAllocatorSession(this, name, session_type); } void BasicPortAllocator::AddWritablePhase(int phase) { if ((best_writable_phase_ == -1) || (phase < best_writable_phase_)) best_writable_phase_ = phase; } // BasicPortAllocatorSession BasicPortAllocatorSession::BasicPortAllocatorSession( BasicPortAllocator *allocator, const std::string &name, const std::string &session_type) : PortAllocatorSession(name, session_type, allocator->flags()), allocator_(allocator), network_thread_(NULL), socket_factory_(allocator->socket_factory()), allocation_started_(false), network_manager_started_(false), running_(false) { allocator_->network_manager()->SignalNetworksChanged.connect( this, &BasicPortAllocatorSession::OnNetworksChanged); allocator_->network_manager()->StartUpdating(); } BasicPortAllocatorSession::~BasicPortAllocatorSession() { allocator_->network_manager()->StopUpdating(); if (network_thread_ != NULL) network_thread_->Clear(this); std::vector<PortData>::iterator it; for (it = ports_.begin(); it != ports_.end(); it++) delete it->port; for (uint32 i = 0; i < configs_.size(); ++i) delete configs_[i]; for (uint32 i = 0; i < sequences_.size(); ++i) delete sequences_[i]; } void BasicPortAllocatorSession::GetInitialPorts() { network_thread_ = talk_base::Thread::Current(); if (!socket_factory_) { owned_socket_factory_.reset( new talk_base::BasicPacketSocketFactory(network_thread_)); socket_factory_ = owned_socket_factory_.get(); } network_thread_->Post(this, MSG_CONFIG_START); if (flags() & PORTALLOCATOR_ENABLE_SHAKER) network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE); } void BasicPortAllocatorSession::StartGetAllPorts() { ASSERT(talk_base::Thread::Current() == network_thread_); running_ = true; if (allocation_started_) network_thread_->PostDelayed(ALLOCATE_DELAY, this, MSG_ALLOCATE); for (uint32 i = 0; i < sequences_.size(); ++i) sequences_[i]->Start(); for (size_t i = 0; i < ports_.size(); ++i) ports_[i].port->Start(); } void BasicPortAllocatorSession::StopGetAllPorts() { ASSERT(talk_base::Thread::Current() == network_thread_); running_ = false; network_thread_->Clear(this, MSG_ALLOCATE); for (uint32 i = 0; i < sequences_.size(); ++i) sequences_[i]->Stop(); } void BasicPortAllocatorSession::OnMessage(talk_base::Message *message) { switch (message->message_id) { case MSG_CONFIG_START: ASSERT(talk_base::Thread::Current() == network_thread_); GetPortConfigurations(); break; case MSG_CONFIG_READY: ASSERT(talk_base::Thread::Current() == network_thread_); OnConfigReady(static_cast<PortConfiguration*>(message->pdata)); break; case MSG_ALLOCATE: ASSERT(talk_base::Thread::Current() == network_thread_); OnAllocate(); break; case MSG_SHAKE: ASSERT(talk_base::Thread::Current() == network_thread_); OnShake(); break; default: ASSERT(false); } } void BasicPortAllocatorSession::GetPortConfigurations() { PortConfiguration* config = new PortConfiguration(allocator_->stun_address(), CreateRandomString(16), CreateRandomString(16), ""); PortConfiguration::PortList ports; if (!allocator_->relay_address_udp().IsAny()) ports.push_back(ProtocolAddress( allocator_->relay_address_udp(), PROTO_UDP)); if (!allocator_->relay_address_tcp().IsAny()) ports.push_back(ProtocolAddress( allocator_->relay_address_tcp(), PROTO_TCP)); if (!allocator_->relay_address_ssl().IsAny()) ports.push_back(ProtocolAddress( allocator_->relay_address_ssl(), PROTO_SSLTCP)); config->AddRelay(ports, RELAY_PRIMARY_PREF_MODIFIER); ConfigReady(config); } void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) { network_thread_->Post(this, MSG_CONFIG_READY, config); } // Adds a configuration to the list. void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) { if (config) configs_.push_back(config); AllocatePorts(); } void BasicPortAllocatorSession::AllocatePorts() { ASSERT(talk_base::Thread::Current() == network_thread_); network_thread_->Post(this, MSG_ALLOCATE); } void BasicPortAllocatorSession::OnAllocate() { if (network_manager_started_) DoAllocate(); allocation_started_ = true; if (running_) network_thread_->PostDelayed(ALLOCATE_DELAY, this, MSG_ALLOCATE); } // For each network, see if we have a sequence that covers it already. If not, // create a new sequence to create the appropriate ports. void BasicPortAllocatorSession::DoAllocate() { std::vector<talk_base::Network*> networks; allocator_->network_manager()->GetNetworks(&networks); if (networks.empty()) { LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated"; } else { for (uint32 i = 0; i < networks.size(); ++i) { PortConfiguration* config = NULL; if (configs_.size() > 0) config = configs_.back(); uint32 sequence_flags = flags(); // Disables phases that are not specified in this config. if (!config || config->stun_address.IsNil()) { // No STUN ports specified in this config. sequence_flags |= PORTALLOCATOR_DISABLE_STUN; } if (!config || config->relays.empty()) { // No relay ports specified in this config. sequence_flags |= PORTALLOCATOR_DISABLE_RELAY; } // Disable phases that would only create ports equivalent to // ones that we have already made. DisableEquivalentPhases(networks[i], config, &sequence_flags); if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) { // New AllocationSequence would have nothing to do, so don't make it. continue; } AllocationSequence* sequence = new AllocationSequence(this, networks[i], config, sequence_flags); if (running_) sequence->Start(); sequences_.push_back(sequence); } } } void BasicPortAllocatorSession::OnNetworksChanged() { network_manager_started_ = true; if (allocation_started_) DoAllocate(); } void BasicPortAllocatorSession::DisableEquivalentPhases( talk_base::Network* network, PortConfiguration* config, uint32* flags) { for (uint32 i = 0; i < sequences_.size() && (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES; ++i) { sequences_[i]->DisableEquivalentPhases(network, config, flags); } } void BasicPortAllocatorSession::AddAllocatedPort(Port* port, AllocationSequence * seq, float pref, bool prepare_address) { if (!port) return; port->set_name(name_); port->set_preference(pref); port->set_generation(generation()); if (allocator_->proxy().type != talk_base::PROXY_NONE) port->set_proxy(allocator_->user_agent(), allocator_->proxy()); PortData data; data.port = port; data.sequence = seq; data.ready = false; ports_.push_back(data); port->SignalAddressReady.connect(this, &BasicPortAllocatorSession::OnAddressReady); port->SignalConnectionCreated.connect(this, &BasicPortAllocatorSession::OnConnectionCreated); port->SignalDestroyed.connect(this, &BasicPortAllocatorSession::OnPortDestroyed); LOG_J(LS_INFO, port) << "Added port to allocator"; if (prepare_address) port->PrepareAddress(); if (running_) port->Start(); } void BasicPortAllocatorSession::OnAddressReady(Port *port) { ASSERT(talk_base::Thread::Current() == network_thread_); std::vector<PortData>::iterator it = std::find(ports_.begin(), ports_.end(), port); ASSERT(it != ports_.end()); if (it->ready) return; it->ready = true; SignalPortReady(this, port); // Only accumulate the candidates whose protocol has been enabled std::vector<Candidate> candidates; const std::vector<Candidate>& potentials = port->candidates(); for (size_t i = 0; i < potentials.size(); ++i) { ProtocolType pvalue; if (!StringToProto(potentials[i].protocol().c_str(), &pvalue)) continue; if (it->sequence->ProtocolEnabled(pvalue)) { candidates.push_back(potentials[i]); } } if (!candidates.empty()) { SignalCandidatesReady(this, candidates); } } void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence * seq, ProtocolType proto) { std::vector<Candidate> candidates; for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end(); ++it) { if (!it->ready || (it->sequence != seq)) continue; const std::vector<Candidate>& potentials = it->port->candidates(); for (size_t i = 0; i < potentials.size(); ++i) { ProtocolType pvalue; if (!StringToProto(potentials[i].protocol().c_str(), &pvalue)) continue; if (pvalue == proto) { candidates.push_back(potentials[i]); } } } if (!candidates.empty()) { SignalCandidatesReady(this, candidates); } } void BasicPortAllocatorSession::OnPortDestroyed(Port* port) { ASSERT(talk_base::Thread::Current() == network_thread_); std::vector<PortData>::iterator iter = std::find(ports_.begin(), ports_.end(), port); ASSERT(iter != ports_.end()); ports_.erase(iter); LOG_J(LS_INFO, port) << "Removed port from allocator (" << static_cast<int>(ports_.size()) << " remaining)"; } void BasicPortAllocatorSession::OnConnectionCreated(Port* port, Connection* conn) { conn->SignalStateChange.connect(this, &BasicPortAllocatorSession::OnConnectionStateChange); } void BasicPortAllocatorSession::OnConnectionStateChange(Connection* conn) { if (conn->write_state() == Connection::STATE_WRITABLE) allocator_->AddWritablePhase( LocalCandidateToPhase(conn->local_candidate())); } void BasicPortAllocatorSession::OnShake() { LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<"; std::vector<Port*> ports; std::vector<Connection*> connections; for (size_t i = 0; i < ports_.size(); ++i) { if (ports_[i].ready) ports.push_back(ports_[i].port); } for (size_t i = 0; i < ports.size(); ++i) { Port::AddressMap::const_iterator iter; for (iter = ports[i]->connections().begin(); iter != ports[i]->connections().end(); ++iter) { connections.push_back(iter->second); } } LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and " << connections.size() << " connections"; for (size_t i = 0; i < connections.size(); ++i) connections[i]->Destroy(); if (running_ || (ports.size() > 0) || (connections.size() > 0)) network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE); } // AllocationSequence AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session, talk_base::Network* network, PortConfiguration* config, uint32 flags) : session_(session), network_(network), ip_(network->ip()), config_(config), running_(false), step_(0), flags_(flags) { // All of the phases up until the best-writable phase so far run in step 0. // The other phases follow sequentially in the steps after that. If there is // no best-writable so far, then only phase 0 occurs in step 0. int last_phase_in_step_zero = talk_base::_max(0, session->allocator()->best_writable_phase()); for (int phase = 0; phase < kNumPhases; ++phase) step_of_phase_[phase] = talk_base::_max(0, phase - last_phase_in_step_zero); // Immediately perform phase 0. OnMessage(NULL); } AllocationSequence::~AllocationSequence() { session_->network_thread()->Clear(this); } void AllocationSequence::DisableEquivalentPhases(talk_base::Network* network, PortConfiguration* config, uint32* flags) { if (!((network == network_) && (ip_ == network->ip()))) { // Different network setup; nothing is equivalent. return; } // Else turn off the stuff that we've already got covered. // Every config implicitly specifies local, so turn that off right away. *flags |= PORTALLOCATOR_DISABLE_UDP; *flags |= PORTALLOCATOR_DISABLE_TCP; if (config_ && config) { if (config_->stun_address == config->stun_address) { // Already got this STUN server covered. *flags |= PORTALLOCATOR_DISABLE_STUN; } if (!config_->relays.empty()) { // Already got relays covered. // NOTE: This will even skip a _different_ set of relay servers if we // were to be given one, but that never happens in our codebase. Should // probably get rid of the list in PortConfiguration and just keep a // single relay server in each one. *flags |= PORTALLOCATOR_DISABLE_RELAY; } } } void AllocationSequence::Start() { running_ = true; session_->network_thread()->PostDelayed(ALLOCATION_STEP_DELAY, this, MSG_ALLOCATION_PHASE); } void AllocationSequence::Stop() { running_ = false; session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE); } void AllocationSequence::OnMessage(talk_base::Message* msg) { ASSERT(talk_base::Thread::Current() == session_->network_thread()); if (msg) ASSERT(msg->message_id == MSG_ALLOCATION_PHASE); const char* const PHASE_NAMES[kNumPhases] = { "Udp", "Relay", "Tcp", "SslTcp" }; // Perform all of the phases in the current step. for (int phase = 0; phase < kNumPhases; phase++) { if (step_of_phase_[phase] != step_) continue; LOG_J(LS_INFO, network_) << "Allocation Phase=" << PHASE_NAMES[phase] << " (Step=" << step_ << ")"; switch (phase) { case PHASE_UDP: CreateUDPPorts(); CreateStunPorts(); EnableProtocol(PROTO_UDP); break; case PHASE_RELAY: CreateRelayPorts(); break; case PHASE_TCP: CreateTCPPorts(); EnableProtocol(PROTO_TCP); break; case PHASE_SSLTCP: EnableProtocol(PROTO_SSLTCP); break; default: ASSERT(false); } } // TODO: use different delays for each stage step_ += 1; if (running_) { session_->network_thread()->PostDelayed(ALLOCATION_STEP_DELAY, this, MSG_ALLOCATION_PHASE); } } void AllocationSequence::EnableProtocol(ProtocolType proto) { if (!ProtocolEnabled(proto)) { protocols_.push_back(proto); session_->OnProtocolEnabled(this, proto); } } bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const { for (ProtocolList::const_iterator it = protocols_.begin(); it != protocols_.end(); ++it) { if (*it == proto) return true; } return false; } void AllocationSequence::CreateUDPPorts() { if (flags_ & PORTALLOCATOR_DISABLE_UDP) { LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping."; return; } Port* port = UDPPort::Create(session_->network_thread(), session_->socket_factory(), network_, ip_, session_->allocator()->min_port(), session_->allocator()->max_port()); if (port) session_->AddAllocatedPort(port, this, PREF_LOCAL_UDP); } void AllocationSequence::CreateTCPPorts() { if (flags_ & PORTALLOCATOR_DISABLE_TCP) { LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping."; return; } Port* port = TCPPort::Create(session_->network_thread(), session_->socket_factory(), network_, ip_, session_->allocator()->min_port(), session_->allocator()->max_port(), session_->allocator()->allow_tcp_listen()); if (port) session_->AddAllocatedPort(port, this, PREF_LOCAL_TCP); } void AllocationSequence::CreateStunPorts() { if (flags_ & PORTALLOCATOR_DISABLE_STUN) { LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping."; return; } // If BasicPortAllocatorSession::OnAllocate left STUN ports enabled then we // ought to have an address for them here. ASSERT(config_ && !config_->stun_address.IsNil()); if (!(config_ && !config_->stun_address.IsNil())) { LOG(LS_WARNING) << "AllocationSequence: No STUN server configured, skipping."; return; } Port* port = StunPort::Create(session_->network_thread(), session_->socket_factory(), network_, ip_, session_->allocator()->min_port(), session_->allocator()->max_port(), config_->stun_address); if (port) session_->AddAllocatedPort(port, this, PREF_LOCAL_STUN); } void AllocationSequence::CreateRelayPorts() { if (flags_ & PORTALLOCATOR_DISABLE_RELAY) { LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping."; return; } // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we // ought to have a relay list for them here. ASSERT(config_ && !config_->relays.empty()); if (!(config_ && !config_->relays.empty())) { LOG(LS_WARNING) << "AllocationSequence: No relay server configured, skipping."; return; } PortConfiguration::RelayList::const_iterator relay; for (relay = config_->relays.begin(); relay != config_->relays.end(); ++relay) { RelayPort* port = RelayPort::Create(session_->network_thread(), session_->socket_factory(), network_, ip_, session_->allocator()->min_port(), session_->allocator()->max_port(), config_->username, config_->password, config_->magic_cookie); if (port) { // Note: We must add the allocated port before we add addresses because // the latter will create candidates that need name and preference // settings. However, we also can't prepare the address (normally // done by AddAllocatedPort) until we have these addresses. So we // wait to do that until below. session_->AddAllocatedPort(port, this, PREF_RELAY + relay->pref_modifier, false); // Add the addresses of this protocol. PortConfiguration::PortList::const_iterator relay_port; for (relay_port = relay->ports.begin(); relay_port != relay->ports.end(); ++relay_port) { port->AddServerAddress(*relay_port); port->AddExternalAddress(*relay_port); } // Start fetching an address for this port. port->PrepareAddress(); } } } // PortConfiguration PortConfiguration::PortConfiguration(const talk_base::SocketAddress& sa, const std::string& un, const std::string& pw, const std::string& mc) : stun_address(sa), username(un), password(pw), magic_cookie(mc) { } void PortConfiguration::AddRelay(const PortList& ports, float pref_modifier) { RelayServer relay; relay.ports = ports; relay.pref_modifier = pref_modifier; relays.push_back(relay); } bool PortConfiguration::ResolveStunAddress() { int err = 0; if (!stun_address.ResolveIP(true, &err)) { LOG(LS_ERROR) << "Unable to resolve STUN host " << stun_address.hostname() << ". Error " << err; return false; } return true; } bool PortConfiguration::SupportsProtocol( const PortConfiguration::RelayServer& relay, ProtocolType type) { PortConfiguration::PortList::const_iterator relay_port; for (relay_port = relay.ports.begin(); relay_port != relay.ports.end(); ++relay_port) { if (relay_port->proto == type) return true; } return false; } } // namespace cricket
33.225962
80
0.662675
[ "vector" ]
a3162c6728b065226b5d75d3406da514a91501a4
2,399
cpp
C++
src/xray/core/sources/math_frustum.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/core/sources/math_frustum.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/core/sources/math_frustum.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 23.10.2008 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" using xray::math::frustum; using xray::math::intersection; using xray::math::aabb; using xray::math::float4x4; using xray::math::sphere; using xray::math::plane; frustum::frustum ( float4x4 const& transform ) { m_planes[ 0 ].plane.vector.x = -( transform.e03 + transform.e00 ); m_planes[ 0 ].plane.vector.y = -( transform.e13 + transform.e10 ); m_planes[ 0 ].plane.vector.z = -( transform.e23 + transform.e20 ); m_planes[ 0 ].plane.vector.w = -( transform.e33 + transform.e30 ); m_planes[ 1 ].plane.vector.x = -( transform.e03 - transform.e00 ); m_planes[ 1 ].plane.vector.y = -( transform.e13 - transform.e10 ); m_planes[ 1 ].plane.vector.z = -( transform.e23 - transform.e20 ); m_planes[ 1 ].plane.vector.w = -( transform.e33 - transform.e30 ); m_planes[ 2 ].plane.vector.x = -( transform.e03 - transform.e01 ); m_planes[ 2 ].plane.vector.y = -( transform.e13 - transform.e11 ); m_planes[ 2 ].plane.vector.z = -( transform.e23 - transform.e21 ); m_planes[ 2 ].plane.vector.w = -( transform.e33 - transform.e31 ); m_planes[ 3 ].plane.vector.x = -( transform.e03 + transform.e01 ); m_planes[ 3 ].plane.vector.y = -( transform.e13 + transform.e11 ); m_planes[ 3 ].plane.vector.z = -( transform.e23 + transform.e21 ); m_planes[ 3 ].plane.vector.w = -( transform.e33 + transform.e31 ); m_planes[ 4 ].plane.vector.x = -( transform.e03 - transform.e02 ); m_planes[ 4 ].plane.vector.y = -( transform.e13 - transform.e12 ); m_planes[ 4 ].plane.vector.z = -( transform.e23 - transform.e22 ); m_planes[ 4 ].plane.vector.w = -( transform.e33 - transform.e32 ); m_planes[ 5 ].plane.vector.x = -( transform.e03 + transform.e02 ); m_planes[ 5 ].plane.vector.y = -( transform.e13 + transform.e12 ); m_planes[ 5 ].plane.vector.z = -( transform.e23 + transform.e22 ); m_planes[ 5 ].plane.vector.w = -( transform.e33 + transform.e32 ); aabb_plane* i = m_planes; aabb_plane const* const e = m_planes + plane_count; for ( ; i != e; ++i) ( *i ).normalize ( ); }
45.264151
77
0.576907
[ "vector", "transform" ]
a31637ceffbac7113a27c0185fe70d1568c46ee0
3,869
cpp
C++
erpc-sys/src/client.cpp
frankrap/erpc-rs
2de6224732db91e766b848e7f3c01cee7252496b
[ "Apache-2.0" ]
8
2020-01-23T22:29:29.000Z
2022-02-01T00:52:31.000Z
erpc-sys/src/client.cpp
frankrap/erpc-rs
2de6224732db91e766b848e7f3c01cee7252496b
[ "Apache-2.0" ]
null
null
null
erpc-sys/src/client.cpp
frankrap/erpc-rs
2de6224732db91e766b848e7f3c01cee7252496b
[ "Apache-2.0" ]
null
null
null
#include "common.h" #include "rpc.h" #include "rpc_types.h" #include "transport_impl/eth_common.h" #include "util/latency.h" #include "util/numautils.h" #include <cstring> #include <signal.h> extern "C" { void client_cont_func(void *_c, void *_tag) { printf("client_cont_func start\n"); auto tag = reinterpret_cast<size_t>(_tag); auto *c = static_cast<AppContext *>(_c); std::string s((const char *)c->resp.buf, c->resp.get_data_size()); printf("tag: %zu %s\n", tag, s.c_str()); printf("client_cont_func end\n"); } // A basic session management handler that expects successful responses void client_sm_handler(int session_num, erpc::SmEventType sm_event_type, erpc::SmErrType sm_err_type, void *_context) { auto *c = static_cast<AppContext *>(_context); printf("client_sm_handler session_num: %d sm_event_type: %d sm_err_type: %d\n", session_num, (int)sm_event_type, (int)sm_err_type); } int connect_session(AppContext &c) { std::string server_uri = kServerHostname + ":" + std::to_string(kServerUDPPort); printf("connect session server_url: %s\n", server_uri.c_str()); int session_num = c.rpc->create_session(server_uri, 0 /* tid */); erpc::rt_assert(session_num >= 0, "Failed to create session"); while (!c.rpc->is_connected(session_num)) { c.rpc->run_event_loop_once(); } return session_num; } void send_q(AppContext *c) { auto kReqMsgSize = strlen("hello"); c->req = c->rpc->alloc_msg_buffer_or_die(kReqMsgSize); c->resp = c->rpc->alloc_msg_buffer_or_die(kMsgSize); sprintf(reinterpret_cast<char *>(c->req.buf), "%s", "hello"); c->rpc->enqueue_request(c->session_num, kReqType, &c->req, &c->resp, client_cont_func, nullptr); } void client_func(erpc::Nexus *nexus, size_t thread_id) { AppContext c; erpc::Rpc<erpc::CTransport> rpc(nexus, static_cast<void *>(&c), thread_id, client_sm_handler, 0); // phy_port rpc.retry_connect_on_invalid_rpc_id = true; c.rpc = &rpc; c.thread_id = thread_id; auto session_num = connect_session(c); printf("session_num %d\n", session_num); c.session_num = session_num; while (true) { rpc.run_event_loop(1000); send_q(&c); } } int client_test() { int num_threads = 2; std::string client_uri = kClientHostname + ":" + std::to_string(kClientUDPPort); erpc::Nexus nexus(client_uri, 0, 0); std::vector<std::thread> threads(num_threads); for (size_t i = 0; i < num_threads; i++) { threads[i] = std::thread(client_func, &nexus, i); erpc::bind_to_core(threads[i], 0, i); } for (size_t i = 0; i < num_threads; i++) threads[i].join(); return 0; } // int client_test_sample() { // std::string client_uri = kClientHostname + ":" + // std::to_string(kClientUDPPort); erpc::Nexus nexus(client_uri, // //erpc::get_uri_for_process(FLAGS_process_id), // FLAGS_process_id // 0, 0); // FLAGS_numa_node, 0 // AppContext c; // erpc::Rpc<erpc::CTransport> rpc(&nexus, static_cast<void *>(&c), 0, // client_sm_handler, 0); // phy_port // rpc.retry_connect_on_invalid_rpc_id = true; // c.rpc = &rpc; // auto session_num = connect_session(c); // auto kMsgSize = strlen("hello"); // auto req = rpc.alloc_msg_buffer_or_die(kMsgSize); // auto resp = rpc.alloc_msg_buffer_or_die(kMsgSize); // sprintf(reinterpret_cast<char *>(req.buf), "%s", "hello"); // c.rpc->enqueue_request(session_num, kReqType, &req, // &resp, client_cont_func, nullptr); // rpc.run_event_loop(10000); // return 0; // } }
30.706349
83
0.614629
[ "vector" ]
a316e790afa4994a35839a35a9575530df4c7791
2,316
cpp
C++
quantitative_finance/L2/demos/Quadrature/src/kernel/quad_integrate_pi1.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-06-14T17:02:06.000Z
2021-06-14T17:02:06.000Z
quantitative_finance/L2/demos/Quadrature/src/kernel/quad_integrate_pi1.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L2/demos/Quadrature/src/kernel/quad_integrate_pi1.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-04-28T05:58:38.000Z
2021-04-28T05:58:38.000Z
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xf_fintech/L2_utils.hpp" #include "quad_hcf_engine_def.hpp" namespace xf { namespace fintech { namespace internal { TEST_DT pi1Integrand(TEST_DT w, struct hcfEngineInputDataType* in); } // namespace internal } // namespace fintech } // namespace xf #define MAX_ITERATIONS 10000 #define MAX_DEPTH 20 #define XF_INTEGRAND_FN internal::pi1Integrand #define XF_USER_DATA_TYPE struct hcfEngineInputDataType #include "xf_fintech/quadrature.hpp" namespace xf { namespace fintech { namespace internal { extern struct complex_num<TEST_DT> charFunc(struct hcfEngineInputDataType* in, struct complex_num<TEST_DT> w); /// @brief function to calculate the integrand for pi 1 /// @param[in] in A structure containing the kerenl model parameters /// @param[in] w the variable of integration /// @return the calculated integrand value TEST_DT pi1Integrand(TEST_DT w, struct hcfEngineInputDataType* in) { struct complex_num<TEST_DT> ww = cn_init(w, (TEST_DT)-1); struct complex_num<TEST_DT> cf1 = charFunc(in, ww); ww = cn_init((TEST_DT)0, (TEST_DT)-1); struct complex_num<TEST_DT> cf2 = charFunc(in, ww); struct complex_num<TEST_DT> tmp = cn_scalar_mul(cn_init((TEST_DT)0, (TEST_DT)1), w); return cn_real(cn_mul(cn_exp(cn_scalar_mul(tmp, -LOG(in->k))), cn_div(cf1, cn_mul(tmp, cf2)))); } /// @brief integration function pi 1 /// @param[in] in A structure containing the kerenl model parameters /// @return the calculated value TEST_DT integrateForPi1(struct hcfEngineInputDataType* in) { TEST_DT res = 0; (void)xf::fintech::romberg_integrate((TEST_DT)1e-10, (TEST_DT)200, in->tol, (TEST_DT*)&res, in); return res; } } // namespace internal } // namespace fintech } // namespace xf
35.090909
110
0.743955
[ "model" ]
a318377a781f47c929b967e306d00dcd4e0f5786
1,393
cpp
C++
p480_Sliding_Window_Median/p480.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p480_Sliding_Window_Median/p480.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p480_Sliding_Window_Median/p480.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <string> #include <cassert> #include <stdlib.h> #include <fstream> #include <algorithm> #include <cmath> using namespace std; class Solution { public: vector<double> medianSlidingWindow(vector<int>& nums, int k) { //for(auto p:nums) printf("%d ",p); printf("\n"); vector<double> ans; multiset<int> s(nums.begin(),nums.begin()+k); auto mid = next(begin(s),k/2); //for(auto p = begin(s); p != end(s); p++) printf("%d ",*p); printf(": %d\n",*mid); ans.push_back(k%2?*mid:(*mid/2.0+*prev(mid)/2.0)); for(int i = k; i < nums.size(); i++) { s.insert(nums[i]); if(nums[i]<*mid) mid--; if(nums[i-k]<=*mid) mid++; s.erase(s.lower_bound(nums[i-k])); //for(auto p = begin(s); p != end(s); p++) printf("%d ",*p); printf(": %d\n",*mid); ans.push_back(k%2?*mid:(*mid/2.0+*prev(mid)/2.0)); } return ans; } }; int main() { //int x[] = {5,5,8,1,4,7,1,3,8,4}; //vector<int> v(x,x+10); int x[] = {1,3,-1,-3,5,3,6,7}; vector<int> v(x,x+sizeof(x)/sizeof(int)); Solution s; vector<double> y = s.medianSlidingWindow(v,3); for(int i = 0; i < y.size(); i++) printf("%f ",y[i]); printf("\n"); return 0; }
30.282609
95
0.524767
[ "vector" ]
a31ba9fbdb5f25245976993086160179b256f919
11,165
cpp
C++
src/unit_array_algs.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
44
2019-01-23T03:37:18.000Z
2021-08-24T02:20:29.000Z
src/unit_array_algs.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
67
2019-01-29T15:35:42.000Z
2021-08-17T20:42:40.000Z
src/unit_array_algs.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
29
2019-01-14T21:33:32.000Z
2021-08-10T11:35:24.000Z
#include "Omega_h_adj.hpp" #include "Omega_h_align.hpp" #include "Omega_h_array_ops.hpp" #include "Omega_h_expr.hpp" #include "Omega_h_for.hpp" #include "Omega_h_int_scan.hpp" #include "Omega_h_library.hpp" #include "Omega_h_linpart.hpp" #include "Omega_h_map.hpp" #include "Omega_h_mark.hpp" #include "Omega_h_sort.hpp" using namespace Omega_h; static void test_write() { auto w = Write<Real>(100, "foo"); OMEGA_H_CHECK(w.size() == 100); OMEGA_H_CHECK(w.name() == "foo"); } static void test_int128() { Int128 a(INT64_MAX); auto b = a + a; b = b + b; b = b + b; b = b >> 3; OMEGA_H_CHECK(b == a); } static void test_repro_sum() { Reals a({std::exp2(int(20)), std::exp2(int(-20))}); Real sum = repro_sum(a); OMEGA_H_CHECK(sum == std::exp2(20) + std::exp2(int(-20))); } static void test_sort() { { LOs a({0, 1}); LOs perm = sort_by_keys(a); OMEGA_H_CHECK(perm == LOs({0, 1})); } { LOs a({0, 2, 0, 1}); LOs perm = sort_by_keys(a, 2); OMEGA_H_CHECK(perm == LOs({1, 0})); } { LOs a({0, 2, 1, 1}); LOs perm = sort_by_keys(a, 2); OMEGA_H_CHECK(perm == LOs({0, 1})); } { LOs a({1, 2, 3, 1, 2, 2, 3, 0, 0}); LOs perm = sort_by_keys(a, 3); OMEGA_H_CHECK(perm == LOs({1, 0, 2})); } } static void test_sort_small_range() { Read<I32> in({10, 100, 1000, 10, 100, 1000, 10, 100, 1000}); LOs perm; LOs fan; Read<I32> uniq; sort_small_range(in, &perm, &fan, &uniq); OMEGA_H_CHECK(perm == LOs({0, 3, 6, 1, 4, 7, 2, 5, 8})); OMEGA_H_CHECK(fan == LOs({0, 3, 6, 9})); OMEGA_H_CHECK(uniq == Read<I32>({10, 100, 1000})); in = Read<I32>({}); sort_small_range(in, &perm, &fan, &uniq); OMEGA_H_CHECK(perm == LOs({})); OMEGA_H_CHECK(fan == LOs({0})); OMEGA_H_CHECK(uniq == Read<I32>({})); } static void test_scan() { { LOs scanned = offset_scan(LOs(3, 1)); OMEGA_H_CHECK(scanned == Read<LO>(4, 0, 1)); } { LOs scanned = offset_scan(Read<I8>(3, 1)); OMEGA_H_CHECK(scanned == Read<LO>(4, 0, 1)); } } static void test_fan_and_funnel() { OMEGA_H_CHECK(invert_funnel(LOs({0, 0, 1, 1, 2, 2}), 3) == LOs({0, 2, 4, 6})); OMEGA_H_CHECK(invert_fan(LOs({0, 2, 4, 6})) == LOs({0, 0, 1, 1, 2, 2})); OMEGA_H_CHECK(invert_funnel(LOs({0, 0, 0, 2, 2, 2}), 3) == LOs({0, 3, 3, 6})); OMEGA_H_CHECK(invert_fan(LOs({0, 3, 3, 6})) == LOs({0, 0, 0, 2, 2, 2})); OMEGA_H_CHECK(invert_funnel(LOs({0, 0, 0, 0, 0, 0}), 3) == LOs({0, 6, 6, 6})); OMEGA_H_CHECK(invert_fan(LOs({0, 6, 6, 6})) == LOs({0, 0, 0, 0, 0, 0})); OMEGA_H_CHECK(invert_funnel(LOs({2, 2, 2, 2, 2, 2}), 3) == LOs({0, 0, 0, 6})); OMEGA_H_CHECK(invert_fan(LOs({0, 0, 0, 6})) == LOs({2, 2, 2, 2, 2, 2})); } static void test_permute() { Reals data({0.1, 0.2, 0.3, 0.4}); LOs perm({3, 2, 1, 0}); Reals permuted = unmap(perm, data, 1); OMEGA_H_CHECK(permuted == Reals({0.4, 0.3, 0.2, 0.1})); Reals back = permute(permuted, perm, 1); OMEGA_H_CHECK(back == data); } static void test_invert_map() { { LOs hl2l({}, "hl2l"); auto l2hl = invert_map_by_atomics(hl2l, 4); OMEGA_H_CHECK(l2hl.a2ab == LOs(5, 0)); OMEGA_H_CHECK(l2hl.ab2b == LOs({})); } { LOs hl2l({0, 1, 2, 3}, "hl2l"); auto l2hl = invert_map_by_atomics(hl2l, 4); OMEGA_H_CHECK(l2hl.a2ab == LOs(5, 0, 1)); OMEGA_H_CHECK(l2hl.ab2b == LOs(4, 0, 1)); } { LOs hl2l({}, "hl2l"); auto l2hl = invert_map_by_sorting(hl2l, 4); OMEGA_H_CHECK(l2hl.a2ab == LOs(5, 0)); OMEGA_H_CHECK(l2hl.ab2b == LOs({})); } { LOs hl2l({0, 1, 2, 3}, "hl2l"); auto l2hl = invert_map_by_sorting(hl2l, 4); OMEGA_H_CHECK(l2hl.a2ab == LOs(5, 0, 1)); OMEGA_H_CHECK(l2hl.ab2b == LOs(4, 0, 1)); } { LOs hl2l({1, 0, 1, 0}, "hl2l"); auto l2hl = invert_map_by_sorting(hl2l, 2); OMEGA_H_CHECK(l2hl.a2ab == LOs({0, 2, 4})); OMEGA_H_CHECK(l2hl.ab2b == LOs({1, 3, 0, 2})); } } static void test_invert_adj() { Adj tris2verts(LOs({0, 1, 2, 2, 3, 0})); Adj verts2tris = invert_adj(tris2verts, 3, 4, 2, 0); OMEGA_H_CHECK(verts2tris.a2ab == offset_scan(LOs({2, 1, 2, 1}))); OMEGA_H_CHECK(verts2tris.ab2b == LOs({0, 1, 0, 0, 1, 1})); OMEGA_H_CHECK( verts2tris.codes == Read<I8>({make_code(0, 0, 0), make_code(0, 0, 2), make_code(0, 0, 1), make_code(0, 0, 2), make_code(0, 0, 0), make_code(0, 0, 1)})); } static void test_injective_map() { LOs primes2ints({2, 3, 5, 7}); LOs ints2primes = invert_injective_map(primes2ints, 8); OMEGA_H_CHECK(ints2primes == LOs({-1, -1, 0, 1, -1, 2, -1, 3})); } void test_binary_search(LOs a, LO val, LO expect) { auto size = a.size(); auto f = OMEGA_H_LAMBDA(LO) { auto res = binary_search(a, val, size); OMEGA_H_CHECK(res == expect); }; parallel_for(1, f); } static void test_binary_search() { auto a = LOs({20, 30, 40, 50, 90, 100}); for (LO i = 0; i < a.size(); ++i) test_binary_search(a, a.get(i), i); test_binary_search(a, 44, -1); test_binary_search(a, 15, -1); test_binary_search(a, 10000, -1); } static void test_is_sorted() { OMEGA_H_CHECK(is_sorted(LOs({}))); OMEGA_H_CHECK(is_sorted(Reals({42.0}))); OMEGA_H_CHECK(is_sorted(LOs({0, 1, 2}))); OMEGA_H_CHECK(!is_sorted(Reals({0.2, 0.1, 0.3, 0.4}))); OMEGA_H_CHECK(is_sorted(Reals({0.1, 0.1, 0.1, 0.1}))); } static void test_linpart() { GO total = 7; I32 comm_size = 2; OMEGA_H_CHECK(linear_partition_size(total, comm_size, 0) == 4); OMEGA_H_CHECK(linear_partition_size(total, comm_size, 1) == 3); Read<GO> globals({6, 5, 4, 3, 2, 1, 0}); auto remotes = globals_to_linear_owners(globals, total, comm_size); OMEGA_H_CHECK(remotes.ranks == Read<I32>({1, 1, 1, 0, 0, 0, 0})); OMEGA_H_CHECK(remotes.idxs == Read<I32>({2, 1, 0, 3, 2, 1, 0})); } static void test_expand() { auto fan = offset_scan(LOs({2, 1, 3})); Reals data({2.2, 3.14, 42.0}); OMEGA_H_CHECK( expand(data, fan, 1) == Reals({2.2, 2.2, 3.14, 42.0, 42.0, 42.0})); } static void test_find_last() { auto a = LOs({0, 3, 55, 12}); OMEGA_H_CHECK(find_last(a, 98) < 0); OMEGA_H_CHECK(find_last(a, 12) == 3); OMEGA_H_CHECK(find_last(a, 55) == 2); OMEGA_H_CHECK(find_last(a, 3) == 1); OMEGA_H_CHECK(find_last(a, 0) == 0); } static void test_scalar_ptr() { Vector<2> v; OMEGA_H_CHECK(scalar_ptr(v) == &v[0]); auto const& v2 = v; OMEGA_H_CHECK(scalar_ptr(v2) == &v2[0]); OMEGA_H_CHECK(scalar_ptr(v2) == &v2(0)); Matrix<5, 4> m; OMEGA_H_CHECK(scalar_ptr(m) == &m[0][0]); auto const& m2 = m; OMEGA_H_CHECK(scalar_ptr(m2) == &m2[0][0]); OMEGA_H_CHECK(scalar_ptr(m2) == &m2(0, 0)); } static void test_expr() { using Omega_h::any; using Omega_h::any_cast; ExprReader reader(4, 3); OMEGA_H_CHECK(any_cast<Real>(reader.read_string("1.0", "test0")) == 1.0); OMEGA_H_CHECK(any_cast<Real>(reader.read_string("1 + 1", "test1")) == 2.0); reader.register_variable("pi", any(Real(3.14159))); OMEGA_H_CHECK(any_cast<Real>(reader.read_string("pi", "test2")) == 3.14159); reader.register_variable("j", any(vector_3(0, 1, 0))); OMEGA_H_CHECK( are_close(any_cast<Vector<3>>(reader.read_string("pi * j", "test3")), vector_3(0, 3.14159, 0))); reader.register_variable("x", any(Reals({0, 1, 2, 3}))); OMEGA_H_CHECK(are_close(any_cast<Reals>(reader.read_string("x^2", "test4")), Reals({0, 1, 4, 9}))); reader.register_variable( "v", any(Reals({0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0}))); OMEGA_H_CHECK(are_close(any_cast<Reals>(reader.read_string("v(1)", "test5")), Reals({0, 1, 2, 3}))); OMEGA_H_CHECK( are_close(any_cast<Reals>(reader.read_string("v - 1.5 * j", "test6")), Reals({0, -1.5, 0, 0, -0.5, 0, 0, 0.5, 0, 0, 1.5, 0}))); OMEGA_H_CHECK(are_close( any_cast<Vector<3>>(reader.read_string("vector(0, 1, 2)", "test7")), vector_3(0, 1, 2))); OMEGA_H_CHECK( are_close(any_cast<Reals>(reader.read_string("vector(x, 0, 0)", "test8")), Reals({0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0}))); OMEGA_H_CHECK( are_close(any_cast<Real>(reader.read_string("exp(0)", "test9")), 1.0)); OMEGA_H_CHECK( are_close(any_cast<Reals>(reader.read_string("exp(x)", "test10")), Reals({1.0, std::exp(1.0), std::exp(2.0), std::exp(3.0)}))); } static Omega_h::any test_expr2( ExprEnv& env, std::string const& expr, std::string const& test_name) { ExprOpsReader reader; auto op = any_cast<OpPtr>(reader.read_string(expr, test_name)); return op->eval(env); } static void test_expr2() { using Omega_h::any; using Omega_h::any_cast; ExprEnv env(4, 3); OMEGA_H_CHECK(any_cast<Real>(test_expr2(env, "1.0", "test0")) == 1.0); OMEGA_H_CHECK(any_cast<Real>(test_expr2(env, "1 + 1", "test1")) == 2.0); env.register_variable("pi", any(Real(3.14159))); OMEGA_H_CHECK(any_cast<Real>(test_expr2(env, "pi", "test2")) == 3.14159); env.register_variable("j", any(vector_3(0, 1, 0))); OMEGA_H_CHECK( are_close(any_cast<Vector<3>>(test_expr2(env, "pi * j", "test3")), vector_3(0, 3.14159, 0))); env.register_variable("x", any(Reals({0, 1, 2, 3}))); OMEGA_H_CHECK(are_close( any_cast<Reals>(test_expr2(env, "x^2", "test4")), Reals({0, 1, 4, 9}))); env.register_variable("v", any(Reals({0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0}))); OMEGA_H_CHECK(are_close( any_cast<Reals>(test_expr2(env, "v(1)", "test5")), Reals({0, 1, 2, 3}))); OMEGA_H_CHECK( are_close(any_cast<Reals>(test_expr2(env, "v - 1.5 * j", "test6")), Reals({0, -1.5, 0, 0, -0.5, 0, 0, 0.5, 0, 0, 1.5, 0}))); OMEGA_H_CHECK(are_close( any_cast<Vector<3>>(test_expr2(env, "vector(0, 1, 2)", "test7")), vector_3(0, 1, 2))); OMEGA_H_CHECK( are_close(any_cast<Reals>(test_expr2(env, "vector(x, 0, 0)", "test8")), Reals({0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0}))); OMEGA_H_CHECK( are_close(any_cast<Real>(test_expr2(env, "exp(0)", "test9")), 1.0)); OMEGA_H_CHECK(are_close(any_cast<Reals>(test_expr2(env, "exp(x)", "test10")), Reals({1.0, std::exp(1.0), std::exp(2.0), std::exp(3.0)}))); } static void test_array_from_kokkos() { #ifdef OMEGA_H_USE_KOKKOS Kokkos::View<double**> managed( Kokkos::ViewAllocateWithoutInitializing("view"), 10, 10); Kokkos::View<double*> unmanaged(managed.data(), managed.span()); Omega_h::Write<double> unmanaged_array(unmanaged); OMEGA_H_CHECK(unmanaged_array.exists()); Kokkos::View<double*> zero_span("zero_span", 0); Omega_h::Write<double> zero_span_array(zero_span); OMEGA_H_CHECK(zero_span_array.exists()); Kokkos::View<double*> uninitialized; Omega_h::Write<double> uninitialized_array(uninitialized); OMEGA_H_CHECK(!uninitialized_array.exists()); #endif } int main(int argc, char** argv) { auto lib = Library(&argc, &argv); OMEGA_H_CHECK(std::string(lib.version()) == OMEGA_H_SEMVER); test_write(); test_int128(); test_repro_sum(); test_sort(); test_sort_small_range(); test_scan(); test_fan_and_funnel(); test_permute(); test_invert_map(); test_invert_adj(); test_injective_map(); test_binary_search(); test_is_sorted(); test_linpart(); test_expand(); test_find_last(); test_scalar_ptr(); test_expr(); test_expr2(); test_array_from_kokkos(); }
33.229167
80
0.614241
[ "vector" ]
a322771ed1c86537caeffd1be0e159d256921d51
3,089
cpp
C++
code/components/citizen-server-impl/src/GetConfigurationMethod.cpp
coverxit/wl-fivem
9ad4559106c0ef17c5a53c198ceae662eb264455
[ "MIT" ]
2
2021-01-26T01:56:40.000Z
2021-10-10T15:30:39.000Z
code/components/citizen-server-impl/src/GetConfigurationMethod.cpp
coverxit/wl-fivem
9ad4559106c0ef17c5a53c198ceae662eb264455
[ "MIT" ]
1
2021-09-10T21:44:58.000Z
2021-09-10T21:44:58.000Z
code/components/citizen-server-impl/src/GetConfigurationMethod.cpp
coverxit/wl-fivem
9ad4559106c0ef17c5a53c198ceae662eb264455
[ "MIT" ]
22
2018-11-17T17:19:01.000Z
2021-05-22T09:51:07.000Z
#include "StdInc.h" #include <ClientHttpHandler.h> #include <ResourceManager.h> #include <ResourceFilesComponent.h> #include <ResourceStreamComponent.h> #include <ResourceMetaDataComponent.h> #include <ServerInstanceBase.h> static InitFunction initFunction([]() { fx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase* instance) { fx::ResourceManager* resman = instance->GetComponent<fx::ResourceManager>().GetRef(); instance->GetComponent<fx::ClientMethodRegistry>()->AddHandler("getConfiguration", [=](const std::map<std::string, std::string>& postMap, const fwRefContainer<net::HttpRequest>& request, const std::function<void(const json&)>& cb) { json resources = json::array(); auto resourceIt = postMap.find("resources"); std::set<std::string_view> filters; if (resourceIt != postMap.end()) { std::string_view filterValues = resourceIt->second; int lastPos = 0; int pos = -1; do { lastPos = pos + 1; pos = filterValues.find_first_of(';', pos + 1); auto thisValue = filterValues.substr(lastPos, (pos - lastPos)); filters.insert(thisValue); } while (pos != std::string::npos); } resman->ForAllResources([&](fwRefContainer<fx::Resource> resource) { if (resource->GetName() == "_cfx_internal") { return; } if (!filters.empty() && filters.find(resource->GetName()) == filters.end()) { return; } if (resource->GetState() != fx::ResourceState::Started && resource->GetState() != fx::ResourceState::Starting) { return; } auto metaData = resource->GetComponent<fx::ResourceMetaDataComponent>(); auto iv = metaData->GetEntries("server_only"); if (iv.begin() != iv.end()) { return; } json resourceFiles = json::object(); fwRefContainer<fx::ResourceFilesComponent> files = resource->GetComponent<fx::ResourceFilesComponent>(); for (const auto& entry : files->GetFileHashPairs()) { resourceFiles[entry.first] = entry.second; } json resourceStreamFiles = json::object(); fwRefContainer<fx::ResourceStreamComponent> streamFiles = resource->GetComponent<fx::ResourceStreamComponent>(); for (const auto& entry : streamFiles->GetStreamingList()) { if (!entry.second.isAutoScan) { continue; } json obj = json::object({ { "hash", entry.second.hashString }, { "rscFlags", entry.second.rscFlags }, { "rscVersion", entry.second.rscVersion }, { "size", entry.second.size }, }); if (entry.second.isResource) { obj["rscPagesVirtual"] = entry.second.rscPagesVirtual; obj["rscPagesPhysical"] = entry.second.rscPagesPhysical; } resourceStreamFiles[entry.first] = obj; } resources.push_back(json::object({ { "name", resource->GetName() }, { "files", resourceFiles }, { "streamFiles", resourceStreamFiles } })); }); cb(json::object({ { "fileServer", "https://%s/files" }, { "resources", resources } })); cb(json(nullptr)); }); }, 5000); });
26.62931
232
0.641955
[ "object" ]
a324f9cc35122b85fa1369faa13a9845deddc672
53,205
cpp
C++
source/detail/number_format/number_formatter.cpp
yschungmr/xlnt
f30260153fcee7e1f775f25ff0cb2750e7826296
[ "Unlicense" ]
null
null
null
source/detail/number_format/number_formatter.cpp
yschungmr/xlnt
f30260153fcee7e1f775f25ff0cb2750e7826296
[ "Unlicense" ]
null
null
null
source/detail/number_format/number_formatter.cpp
yschungmr/xlnt
f30260153fcee7e1f775f25ff0cb2750e7826296
[ "Unlicense" ]
1
2020-10-29T06:17:32.000Z
2020-10-29T06:17:32.000Z
// Copyright (c) 2014-2018 Thomas Fussell // // 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, WRISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE // // @license: http://www.opensource.org/licenses/mit-license.php // @author: see AUTHORS file #include <algorithm> #include <cctype> #include <cmath> #include <detail/default_case.hpp> #include <detail/number_format/number_formatter.hpp> #include <xlnt/utils/exceptions.hpp> namespace { const std::unordered_map<int, std::string> known_locales() { static const std::unordered_map<int, std::string> *all = new std::unordered_map<int, std::string>( {{0x401, "Arabic - Saudi Arabia"}, {0x402, "Bulgarian"}, {0x403, "Catalan"}, {0x404, "Chinese - Taiwan"}, {0x405, "Czech"}, {0x406, "Danish"}, {0x407, "German - Germany"}, {0x408, "Greek"}, {0x409, "English - United States"}, {0x410, "Italian - Italy"}, {0x411, "Japanese"}, {0x412, "Korean"}, {0x413, "Dutch - Netherlands"}, {0x414, "Norwegian - Bokml"}, {0x415, "Polish"}, {0x416, "Portuguese - Brazil"}, {0x417, "Raeto-Romance"}, {0x418, "Romanian - Romania"}, {0x419, "Russian"}, {0x420, "Urdu"}, {0x421, "Indonesian"}, {0x422, "Ukrainian"}, {0x423, "Belarusian"}, {0x424, "Slovenian"}, {0x425, "Estonian"}, {0x426, "Latvian"}, {0x427, "Lithuanian"}, {0x428, "Tajik"}, {0x429, "Farsi - Persian"}, {0x430, "Sesotho (Sutu)"}, {0x431, "Tsonga"}, {0x432, "Setsuana"}, {0x433, "Venda"}, {0x434, "Xhosa"}, {0x435, "Zulu"}, {0x436, "Afrikaans"}, {0x437, "Georgian"}, {0x438, "Faroese"}, {0x439, "Hindi"}, {0x440, "Kyrgyz - Cyrillic"}, {0x441, "Swahili"}, {0x442, "Turkmen"}, {0x443, "Uzbek - Latin"}, {0x444, "Tatar"}, {0x445, "Bengali - India"}, {0x446, "Punjabi"}, {0x447, "Gujarati"}, {0x448, "Oriya"}, {0x449, "Tamil"}, {0x450, "Mongolian"}, {0x451, "Tibetan"}, {0x452, "Welsh"}, {0x453, "Khmer"}, {0x454, "Lao"}, {0x455, "Burmese"}, {0x456, "Galician"}, {0x457, "Konkani"}, {0x458, "Manipuri"}, {0x459, "Sindhi"}, {0x460, "Kashmiri"}, {0x461, "Nepali"}, {0x462, "Frisian - Netherlands"}, {0x464, "Filipino"}, {0x465, "Divehi; Dhivehi; Maldivian"}, {0x466, "Edo"}, {0x470, "Igbo - Nigeria"}, {0x474, "Guarani - Paraguay"}, {0x476, "Latin"}, {0x477, "Somali"}, {0x481, "Maori"}, {0x485, "sah-RU"}, {0x801, "Arabic - Iraq"}, {0x804, "Chinese - China"}, {0x807, "German - Switzerland"}, {0x809, "English - Great Britain"}, {0x810, "Italian - Switzerland"}, {0x813, "Dutch - Belgium"}, {0x814, "Norwegian - Nynorsk"}, {0x816, "Portuguese - Portugal"}, {0x818, "Romanian - Moldova"}, {0x819, "Russian - Moldova"}, {0x843, "Uzbek - Cyrillic"}, {0x845, "Bengali - Bangladesh"}, {0x850, "Mongolian"}, {0x1001, "Arabic - Libya"}, {0x1004, "Chinese - Singapore"}, {0x1007, "German - Luxembourg"}, {0x1009, "English - Canada"}, {0x1401, "Arabic - Algeria"}, {0x1404, "Chinese - Macau SAR"}, {0x1407, "German - Liechtenstein"}, {0x1409, "English - New Zealand"}, {0x1801, "Arabic - Morocco"}, {0x1809, "English - Ireland"}, {0x2001, "Arabic - Oman"}, {0x2009, "English - Jamaica"}, {0x2401, "Arabic - Yemen"}, {0x2409, "English - Caribbean"}, {0x2801, "Arabic - Syria"}, {0x2809, "English - Belize"}, {0x3001, "Arabic - Lebanon"}, {0x3009, "English - Zimbabwe"}, {0x3401, "Arabic - Kuwait"}, {0x3409, "English - Phillippines"}, {0x3801, "Arabic - United Arab Emirates"}, {0x4001, "Arabic - Qatar"}}); return *all; } [[noreturn]] void unhandled_case_error() { throw xlnt::exception("unhandled"); } void unhandled_case(bool error) { if (error) { unhandled_case_error(); } } } // namespace namespace xlnt { namespace detail { bool format_condition::satisfied_by(double number) const { switch (type) { case condition_type::greater_or_equal: return number >= value; case condition_type::greater_than: return number > value; case condition_type::less_or_equal: return number <= value; case condition_type::less_than: return number < value; case condition_type::not_equal: return std::fabs(number - value) != 0.0; case condition_type::equal: return std::fabs(number - value) == 0.0; } default_case(false); } number_format_parser::number_format_parser(const std::string &format_string) { reset(format_string); } const std::vector<format_code> &number_format_parser::result() const { return codes_; } void number_format_parser::reset(const std::string &format_string) { format_string_ = format_string; position_ = 0; codes_.clear(); } void number_format_parser::parse() { auto token = parse_next_token(); format_code section; template_part part; for (;;) { switch (token.type) { case number_format_token::token_type::end_section: { codes_.push_back(section); section = format_code(); break; } case number_format_token::token_type::color: { if (section.has_color || section.has_condition || section.has_locale || !section.parts.empty()) { throw xlnt::exception("color should be the first part of a format"); } section.has_color = true; section.color = color_from_string(token.string); break; } case number_format_token::token_type::locale: { if (section.has_locale) { throw xlnt::exception("multiple locales"); } section.has_locale = true; auto parsed_locale = locale_from_string(token.string); section.locale = parsed_locale.first; if (!parsed_locale.second.empty()) { part.type = template_part::template_type::text; part.string = parsed_locale.second; section.parts.push_back(part); part = template_part(); } break; } case number_format_token::token_type::condition: { if (section.has_condition) { throw xlnt::exception("multiple conditions"); } section.has_condition = true; std::string value; if (token.string.front() == '<') { if (token.string[1] == '=') { section.condition.type = format_condition::condition_type::less_or_equal; value = token.string.substr(2); } else if (token.string[1] == '>') { section.condition.type = format_condition::condition_type::not_equal; value = token.string.substr(2); } else { section.condition.type = format_condition::condition_type::less_than; value = token.string.substr(1); } } else if (token.string.front() == '>') { if (token.string[1] == '=') { section.condition.type = format_condition::condition_type::greater_or_equal; value = token.string.substr(2); } else { section.condition.type = format_condition::condition_type::greater_than; value = token.string.substr(1); } } else if (token.string.front() == '=') { section.condition.type = format_condition::condition_type::equal; value = token.string.substr(1); } section.condition.value = std::stod(value); break; } case number_format_token::token_type::text: { part.type = template_part::template_type::text; part.string = token.string; section.parts.push_back(part); part = template_part(); break; } case number_format_token::token_type::fill: { part.type = template_part::template_type::fill; part.string = token.string; section.parts.push_back(part); part = template_part(); break; } case number_format_token::token_type::space: { part.type = template_part::template_type::space; part.string = token.string; section.parts.push_back(part); part = template_part(); break; } case number_format_token::token_type::number: { part.type = template_part::template_type::general; part.placeholders = parse_placeholders(token.string); section.parts.push_back(part); part = template_part(); break; } case number_format_token::token_type::datetime: { section.is_datetime = true; switch (token.string.front()) { case '[': section.is_timedelta = true; if (token.string == "[h]" || token.string == "[hh]") { part.type = template_part::template_type::elapsed_hours; break; } else if (token.string == "[m]" || token.string == "[mm]") { part.type = template_part::template_type::elapsed_minutes; break; } else if (token.string == "[s]" || token.string == "[ss]") { part.type = template_part::template_type::elapsed_seconds; break; } unhandled_case(true); break; case 'm': if (token.string == "m") { part.type = template_part::template_type::month_number; break; } else if (token.string == "mm") { part.type = template_part::template_type::month_number_leading_zero; break; } else if (token.string == "mmm") { part.type = template_part::template_type::month_abbreviation; break; } else if (token.string == "mmmm") { part.type = template_part::template_type::month_name; break; } else if (token.string == "mmmmm") { part.type = template_part::template_type::month_letter; break; } unhandled_case(true); break; case 'd': if (token.string == "d") { part.type = template_part::template_type::day_number; break; } else if (token.string == "dd") { part.type = template_part::template_type::day_number_leading_zero; break; } else if (token.string == "ddd") { part.type = template_part::template_type::day_abbreviation; break; } else if (token.string == "dddd") { part.type = template_part::template_type::day_name; break; } unhandled_case(true); break; case 'y': if (token.string == "yy") { part.type = template_part::template_type::year_short; break; } else if (token.string == "yyyy") { part.type = template_part::template_type::year_long; break; } unhandled_case(true); break; case 'h': if (token.string == "h") { part.type = template_part::template_type::hour; break; } else if (token.string == "hh") { part.type = template_part::template_type::hour_leading_zero; break; } unhandled_case(true); break; case 's': if (token.string == "s") { part.type = template_part::template_type::second; break; } else if (token.string == "ss") { part.type = template_part::template_type::second_leading_zero; break; } unhandled_case(true); break; case 'A': section.twelve_hour = true; if (token.string == "AM/PM") { part.type = template_part::template_type::am_pm; break; } else if (token.string == "A/P") { part.type = template_part::template_type::a_p; break; } unhandled_case(true); break; default: unhandled_case(true); break; } section.parts.push_back(part); part = template_part(); break; } case number_format_token::token_type::end: { codes_.push_back(section); finalize(); return; } } token = parse_next_token(); } } void number_format_parser::finalize() { for (auto &code : codes_) { bool fix = false; bool leading_zero = false; std::size_t minutes_index = 0; bool integer_part = false; bool fractional_part = false; std::size_t integer_part_index = 0; bool percentage = false; bool exponent = false; std::size_t exponent_index = 0; bool fraction = false; std::size_t fraction_denominator_index = 0; std::size_t fraction_numerator_index = 0; bool seconds = false; bool fractional_seconds = false; std::size_t seconds_index = 0; for (std::size_t i = 0; i < code.parts.size(); ++i) { const auto &part = code.parts[i]; if (i > 0 && i + 1 < code.parts.size() && part.type == template_part::template_type::text && part.string == "/" && code.parts[i - 1].placeholders.type == format_placeholders::placeholders_type::integer_part && code.parts[i + 1].placeholders.type == format_placeholders::placeholders_type::integer_part) { fraction = true; fraction_numerator_index = i - 1; fraction_denominator_index = i + 1; } if (part.placeholders.type == format_placeholders::placeholders_type::integer_part) { integer_part = true; integer_part_index = i; } else if (part.placeholders.type == format_placeholders::placeholders_type::fractional_part) { fractional_part = true; } else if (part.placeholders.type == format_placeholders::placeholders_type::scientific_exponent_plus || part.placeholders.type == format_placeholders::placeholders_type::scientific_exponent_minus) { exponent = true; exponent_index = i; } if (part.placeholders.percentage) { percentage = true; } if (part.type == template_part::template_type::second || part.type == template_part::template_type::second_leading_zero) { seconds = true; seconds_index = i; } if (seconds && part.placeholders.type == format_placeholders::placeholders_type::fractional_part) { fractional_seconds = true; } // TODO this block needs improvement if (part.type == template_part::template_type::month_number || part.type == template_part::template_type::month_number_leading_zero) { if (code.parts.size() > 1 && i < code.parts.size() - 2) { const auto &next = code.parts[i + 1]; const auto &after_next = code.parts[i + 2]; if ((next.type == template_part::template_type::second || next.type == template_part::template_type::second_leading_zero) || (next.type == template_part::template_type::text && next.string == ":" && (after_next.type == template_part::template_type::second || after_next.type == template_part::template_type::second_leading_zero))) { fix = true; leading_zero = part.type == template_part::template_type::month_number_leading_zero; minutes_index = i; } } if (!fix && i > 1) { const auto &previous = code.parts[i - 1]; const auto &before_previous = code.parts[i - 2]; if (previous.type == template_part::template_type::text && previous.string == ":" && (before_previous.type == template_part::template_type::hour_leading_zero || before_previous.type == template_part::template_type::hour)) { fix = true; leading_zero = part.type == template_part::template_type::month_number_leading_zero; minutes_index = i; } } } } if (fix) { code.parts[minutes_index].type = leading_zero ? template_part::template_type::minute_leading_zero : template_part::template_type::minute; } if (integer_part && !fractional_part) { code.parts[integer_part_index].placeholders.type = format_placeholders::placeholders_type::integer_only; } if (integer_part && fractional_part && percentage) { code.parts[integer_part_index].placeholders.percentage = true; } if (exponent) { const auto &next = code.parts[exponent_index + 1]; auto temp = code.parts[exponent_index].placeholders.type; code.parts[exponent_index].placeholders = next.placeholders; code.parts[exponent_index].placeholders.type = temp; code.parts.erase(code.parts.begin() + static_cast<std::ptrdiff_t>(exponent_index + 1)); for (std::size_t i = 0; i < code.parts.size(); ++i) { code.parts[i].placeholders.scientific = true; } } if (fraction) { code.parts[fraction_numerator_index].placeholders.type = format_placeholders::placeholders_type::fraction_numerator; code.parts[fraction_denominator_index].placeholders.type = format_placeholders::placeholders_type::fraction_denominator; for (std::size_t i = 0; i < code.parts.size(); ++i) { if (code.parts[i].placeholders.type == format_placeholders::placeholders_type::integer_part) { code.parts[i].placeholders.type = format_placeholders::placeholders_type::fraction_integer; } } } if (fractional_seconds) { if (code.parts[seconds_index].type == template_part::template_type::second) { code.parts[seconds_index].type = template_part::template_type::second_fractional; } else { code.parts[seconds_index].type = template_part::template_type::second_leading_zero_fractional; } } } validate(); } number_format_token number_format_parser::parse_next_token() { number_format_token token; auto to_lower = [](char c) { return static_cast<char>(std::tolower(static_cast<std::uint8_t>(c))); }; if (format_string_.size() <= position_) { token.type = number_format_token::token_type::end; return token; } auto current_char = format_string_[position_++]; switch (current_char) { case '[': if (position_ == format_string_.size()) { throw xlnt::exception("missing ]"); } if (format_string_[position_] == ']') { throw xlnt::exception("empty []"); } do { token.string.push_back(format_string_[position_++]); } while (position_ < format_string_.size() && format_string_[position_] != ']'); if (token.string[0] == '<' || token.string[0] == '>' || token.string[0] == '=') { token.type = number_format_token::token_type::condition; } else if (token.string[0] == '$') { token.type = number_format_token::token_type::locale; } else if (token.string.size() <= 2 && ((token.string == "h" || token.string == "hh") || (token.string == "m" || token.string == "mm") || (token.string == "s" || token.string == "ss"))) { token.type = number_format_token::token_type::datetime; token.string = "[" + token.string + "]"; } else { token.type = number_format_token::token_type::color; color_from_string(token.string); } ++position_; break; case '\\': token.type = number_format_token::token_type::text; token.string.push_back(format_string_[position_++]); break; case 'G': if (format_string_.substr(position_ - 1, 7) != "General") { throw xlnt::exception("expected General"); } token.type = number_format_token::token_type::number; token.string = "General"; position_ += 6; break; case '_': token.type = number_format_token::token_type::space; token.string.push_back(format_string_[position_++]); break; case '*': token.type = number_format_token::token_type::fill; token.string.push_back(format_string_[position_++]); break; case '0': case '#': case '?': case '.': token.type = number_format_token::token_type::number; do { token.string.push_back(current_char); current_char = format_string_[position_++]; } while (current_char == '0' || current_char == '#' || current_char == '?' || current_char == ','); --position_; if (current_char == '%') { token.string.push_back('%'); ++position_; } break; case 'y': case 'Y': case 'm': case 'M': case 'd': case 'D': case 'h': case 'H': case 's': case 'S': token.type = number_format_token::token_type::datetime; token.string.push_back(to_lower(current_char)); while (format_string_[position_] == current_char) { token.string.push_back(to_lower(current_char)); ++position_; } break; case 'A': token.type = number_format_token::token_type::datetime; if (format_string_.substr(position_ - 1, 5) == "AM/PM") { position_ += 4; token.string = "AM/PM"; } else if (format_string_.substr(position_ - 1, 3) == "A/P") { position_ += 2; token.string = "A/P"; } else { throw xlnt::exception("expected AM/PM or A/P"); } break; case '"': { token.type = number_format_token::token_type::text; auto start = position_; auto end = format_string_.find('"', position_); while (end != std::string::npos && format_string_[end - 1] == '\\') { token.string.append(format_string_.substr(start, end - start - 1)); token.string.push_back('"'); position_ = end + 1; start = position_; end = format_string_.find('"', position_); } if (end != start) { token.string.append(format_string_.substr(start, end - start)); } position_ = end + 1; break; } case ';': token.type = number_format_token::token_type::end_section; break; case '(': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case ')': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case '-': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case '+': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case ':': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case ' ': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case '/': token.type = number_format_token::token_type::text; token.string.push_back(current_char); break; case '@': token.type = number_format_token::token_type::number; token.string.push_back(current_char); break; case 'E': token.type = number_format_token::token_type::number; token.string.push_back(current_char); current_char = format_string_[position_++]; if (current_char == '+' || current_char == '-') { token.string.push_back(current_char); break; } break; default: throw xlnt::exception("unexpected character"); } return token; } void number_format_parser::validate() { if (codes_.size() > 4) { throw xlnt::exception("too many format codes"); } if (codes_.size() > 2) { if (codes_[0].has_condition && codes_[1].has_condition && codes_[2].has_condition) { throw xlnt::exception("format should have a maximum of two codes with conditions"); } } } format_placeholders number_format_parser::parse_placeholders(const std::string &placeholders_string) { format_placeholders p; if (placeholders_string == "General") { p.type = format_placeholders::placeholders_type::general; return p; } else if (placeholders_string == "@") { p.type = format_placeholders::placeholders_type::text; return p; } else if (placeholders_string.front() == '.') { p.type = format_placeholders::placeholders_type::fractional_part; } else if (placeholders_string.front() == 'E') { p.type = placeholders_string[1] == '+' ? format_placeholders::placeholders_type::scientific_exponent_plus : format_placeholders::placeholders_type::scientific_exponent_minus; return p; } else { p.type = format_placeholders::placeholders_type::integer_part; } if (placeholders_string.back() == '%') { p.percentage = true; } std::vector<std::size_t> comma_indices; for (std::size_t i = 0; i < placeholders_string.size(); ++i) { auto c = placeholders_string[i]; if (c == '0') { ++p.num_zeros; } else if (c == '#') { ++p.num_optionals; } else if (c == '?') { ++p.num_spaces; } else if (c == ',') { comma_indices.push_back(i); } } if (!comma_indices.empty()) { std::size_t i = placeholders_string.size() - 1; while (!comma_indices.empty() && i == comma_indices.back()) { ++p.thousands_scale; --i; comma_indices.pop_back(); } p.use_comma_separator = !comma_indices.empty(); } return p; } format_color number_format_parser::color_from_string(const std::string &color) { switch (color[0]) { case 'C': if (color == "Cyan") { return format_color::cyan; } else if (color.substr(0, 5) == "Color") { auto color_number = std::stoull(color.substr(5)); if (color_number >= 1 && color_number <= 56) { return static_cast<format_color>(color_number); } } unhandled_case(true); break; case 'B': if (color == "Black") { return format_color::black; } else if (color == "Blue") { return format_color::blue; } unhandled_case(true); break; case 'G': if (color == "Green") { return format_color::green; } unhandled_case(true); break; case 'W': if (color == "White") { return format_color::white; } unhandled_case(true); break; case 'M': if (color == "Magenta") { return format_color::magenta; } unhandled_case(true); break; case 'Y': if (color == "Yellow") { return format_color::yellow; } unhandled_case(true); break; case 'R': if (color == "Red") { return format_color::red; } unhandled_case(true); break; default: unhandled_case(true); } unhandled_case_error(); } std::pair<format_locale, std::string> number_format_parser::locale_from_string(const std::string &locale_string) { auto hyphen_index = locale_string.find('-'); if (locale_string.empty() || locale_string.front() != '$' || hyphen_index == std::string::npos) { throw xlnt::exception("bad locale: " + locale_string); } std::pair<format_locale, std::string> result; if (hyphen_index > 1) { result.second = locale_string.substr(1, hyphen_index - 1); } auto country_code_string = locale_string.substr(hyphen_index + 1); if (country_code_string.empty()) { throw xlnt::exception("bad locale: " + locale_string); } for (auto c : country_code_string) { if (!((c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'))) { throw xlnt::exception("bad locale: " + locale_string); } } auto country_code = std::stoi(country_code_string, nullptr, 16); country_code &= 0xFFFF; for (const auto &known_locale : known_locales()) { if (known_locale.first == country_code) { result.first = static_cast<format_locale>(country_code); return result; } } throw xlnt::exception("unknown country code: " + country_code_string); } number_formatter::number_formatter(const std::string &format_string, xlnt::calendar calendar) : parser_(format_string), calendar_(calendar) { parser_.parse(); format_ = parser_.result(); } std::string number_formatter::format_number(double number) { if (format_[0].has_condition) { if (format_[0].condition.satisfied_by(number)) { return format_number(format_[0], number); } if (format_.size() == 1) { return std::string(11, '#'); } if (!format_[1].has_condition || format_[1].condition.satisfied_by(number)) { return format_number(format_[1], number); } if (format_.size() == 2) { return std::string(11, '#'); } return format_number(format_[2], number); } // no conditions, format based on sign: // 1 section, use for all if (format_.size() == 1) { return format_number(format_[0], number); } // 2 sections, first for positive and zero, second for negative else if (format_.size() == 2) { if (number >= 0) { return format_number(format_[0], number); } else { return format_number(format_[1], std::fabs(number)); } } // 3+ sections, first for positive, second for negative, third for zero else { if (number > 0) { return format_number(format_[0], number); } else if (number < 0) { return format_number(format_[1], std::fabs(number)); } else { return format_number(format_[2], number); } } } std::string number_formatter::format_text(const std::string &text) { if (format_.size() < 4) { format_code temp; template_part temp_part; temp_part.type = template_part::template_type::general; temp_part.placeholders.type = format_placeholders::placeholders_type::general; temp.parts.push_back(temp_part); return format_text(temp, text); } return format_text(format_[3], text); } std::string number_formatter::fill_placeholders(const format_placeholders &p, double number) { std::string result; if (p.type == format_placeholders::placeholders_type::general || p.type == format_placeholders::placeholders_type::text) { result = std::to_string(number); while (result.back() == '0') { result.pop_back(); } if (result.back() == '.') { result.pop_back(); } return result; } if (p.percentage) { number *= 100; } if (p.thousands_scale > 0) { number /= std::pow(1000.0, p.thousands_scale); } auto integer_part = static_cast<int>(number); if (p.type == format_placeholders::placeholders_type::integer_only || p.type == format_placeholders::placeholders_type::integer_part || p.type == format_placeholders::placeholders_type::fraction_integer) { result = std::to_string(integer_part); while (result.size() < p.num_zeros) { result = "0" + result; } while (result.size() < p.num_zeros + p.num_spaces) { result = " " + result; } if (p.use_comma_separator) { std::vector<char> digits(result.rbegin(), result.rend()); std::string temp; for (std::size_t i = 0; i < digits.size(); i++) { temp.push_back(digits[i]); if (i % 3 == 2) { temp.push_back(','); } } result = std::string(temp.rbegin(), temp.rend()); } if (p.percentage && p.type == format_placeholders::placeholders_type::integer_only) { result.push_back('%'); } } else if (p.type == format_placeholders::placeholders_type::fractional_part) { auto fractional_part = number - integer_part; result = std::fabs(fractional_part) < std::numeric_limits<double>::min() ? std::string(".") : std::to_string(fractional_part).substr(1); while (result.back() == '0' || result.size() > (p.num_zeros + p.num_optionals + p.num_spaces + 1)) { result.pop_back(); } while (result.size() < p.num_zeros + 1) { result.push_back('0'); } while (result.size() < p.num_zeros + p.num_optionals + p.num_spaces + 1) { result.push_back(' '); } if (p.percentage) { result.push_back('%'); } } return result; } std::string number_formatter::fill_scientific_placeholders(const format_placeholders &integer_part, const format_placeholders &fractional_part, const format_placeholders &exponent_part, double number) { std::size_t logarithm = 0; if (number != 0.0) { logarithm = static_cast<std::size_t>(std::log10(number)); if (integer_part.num_zeros + integer_part.num_optionals > 1) { logarithm = integer_part.num_zeros + integer_part.num_optionals; } } number /= std::pow(10.0, logarithm); auto integer = static_cast<int>(number); auto fraction = number - integer; std::string integer_string = std::to_string(integer); if (number == 0.0) { integer_string = std::string(integer_part.num_zeros + integer_part.num_optionals, '0'); } std::string fractional_string = std::to_string(fraction).substr(1); while (fractional_string.size() > fractional_part.num_zeros + fractional_part.num_optionals + 1) { fractional_string.pop_back(); } std::string exponent_string = std::to_string(logarithm); while (exponent_string.size() < fractional_part.num_zeros) { exponent_string.insert(0, "0"); } if (exponent_part.type == format_placeholders::placeholders_type::scientific_exponent_plus) { exponent_string.insert(0, "E+"); } else { exponent_string.insert(0, "E"); } return integer_string + fractional_string + exponent_string; } std::string number_formatter::fill_fraction_placeholders(const format_placeholders & /*numerator*/, const format_placeholders &denominator, double number, bool /*improper*/) { auto fractional_part = number - static_cast<int>(number); auto original_fractional_part = fractional_part; fractional_part *= 10; while (std::abs(fractional_part - static_cast<int>(fractional_part)) > 0.000001 && std::abs(fractional_part - static_cast<int>(fractional_part)) < 0.999999) { fractional_part *= 10; } fractional_part = static_cast<int>(fractional_part); auto denominator_digits = denominator.num_zeros + denominator.num_optionals + denominator.num_spaces; // auto denominator_digits = static_cast<std::size_t>(std::ceil(std::log10(fractional_part))); auto lower = static_cast<int>(std::pow(10, denominator_digits - 1)); auto upper = static_cast<int>(std::pow(10, denominator_digits)); auto best_denominator = lower; auto best_difference = 1000.0; for (int i = lower; i < upper; ++i) { auto numerator_full = original_fractional_part * i; auto numerator_rounded = static_cast<int>(std::round(numerator_full)); auto difference = std::fabs(original_fractional_part - (numerator_rounded / static_cast<double>(i))); if (difference < best_difference) { best_difference = difference; best_denominator = i; } } auto numerator_rounded = static_cast<int>(std::round(original_fractional_part * best_denominator)); return std::to_string(numerator_rounded) + "/" + std::to_string(best_denominator); } std::string number_formatter::format_number(const format_code &format, double number) { static const std::vector<std::string> *month_names = new std::vector<std::string>{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; static const std::vector<std::string> *day_names = new std::vector<std::string>{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; std::string result; if (number < 0) { result.push_back('-'); if (format.is_datetime) { return std::string(11, '#'); } } number = std::fabs(number); xlnt::datetime dt(0, 1, 0); std::size_t hour = 0; if (format.is_datetime) { if (number != 0.0) { dt = xlnt::datetime::from_number(number, calendar_); } hour = static_cast<std::size_t>(dt.hour); if (format.twelve_hour) { hour %= 12; if (hour == 0) { hour = 12; } } } bool improper_fraction = true; std::size_t fill_index = 0; bool fill = false; std::string fill_character; for (std::size_t i = 0; i < format.parts.size(); ++i) { const auto &part = format.parts[i]; switch (part.type) { case template_part::template_type::space: { result.push_back(' '); break; } case template_part::template_type::text: { result.append(part.string); break; } case template_part::template_type::fill: { fill = true; fill_index = result.size(); fill_character = part.string; break; } case template_part::template_type::general: { if (part.placeholders.type == format_placeholders::placeholders_type::fractional_part && (format.is_datetime || format.is_timedelta)) { auto digits = std::min( static_cast<std::size_t>(6), part.placeholders.num_zeros + part.placeholders.num_optionals); auto denominator = static_cast<int>(std::pow(10.0, digits)); auto fractional_seconds = dt.microsecond / 1.0E6 * denominator; fractional_seconds = std::round(fractional_seconds) / denominator; result.append(fill_placeholders(part.placeholders, fractional_seconds)); break; } if (part.placeholders.type == format_placeholders::placeholders_type::fraction_integer) { improper_fraction = false; } if (part.placeholders.type == format_placeholders::placeholders_type::fraction_numerator) { i += 2; if (number == 0.0) { result.pop_back(); break; } result.append(fill_fraction_placeholders( part.placeholders, format.parts[i].placeholders, number, improper_fraction)); } else if (part.placeholders.scientific && part.placeholders.type == format_placeholders::placeholders_type::integer_part) { auto integer_part = part.placeholders; ++i; auto fractional_part = format.parts[i++].placeholders; auto exponent_part = format.parts[i++].placeholders; result.append(fill_scientific_placeholders(integer_part, fractional_part, exponent_part, number)); } else { result.append(fill_placeholders(part.placeholders, number)); } break; } case template_part::template_type::day_number: { result.append(std::to_string(dt.day)); break; } case template_part::template_type::day_number_leading_zero: { if (dt.day < 10) { result.push_back('0'); } result.append(std::to_string(dt.day)); break; } case template_part::template_type::month_abbreviation: { result.append(month_names->at(static_cast<std::size_t>(dt.month) - 1).substr(0, 3)); break; } case template_part::template_type::month_name: { result.append(month_names->at(static_cast<std::size_t>(dt.month) - 1)); break; } case template_part::template_type::month_number: { result.append(std::to_string(dt.month)); break; } case template_part::template_type::month_number_leading_zero: { if (dt.month < 10) { result.push_back('0'); } result.append(std::to_string(dt.month)); break; } case template_part::template_type::year_short: { if (dt.year % 1000 < 10) { result.push_back('0'); } result.append(std::to_string(dt.year % 1000)); break; } case template_part::template_type::year_long: { result.append(std::to_string(dt.year)); break; } case template_part::template_type::hour: { result.append(std::to_string(hour)); break; } case template_part::template_type::hour_leading_zero: { if (hour < 10) { result.push_back('0'); } result.append(std::to_string(hour)); break; } case template_part::template_type::minute: { result.append(std::to_string(dt.minute)); break; } case template_part::template_type::minute_leading_zero: { if (dt.minute < 10) { result.push_back('0'); } result.append(std::to_string(dt.minute)); break; } case template_part::template_type::second: { result.append(std::to_string(dt.second + (dt.microsecond > 500000 ? 1 : 0))); break; } case template_part::template_type::second_fractional: { result.append(std::to_string(dt.second)); break; } case template_part::template_type::second_leading_zero: { if ((dt.second + (dt.microsecond > 500000 ? 1 : 0)) < 10) { result.push_back('0'); } result.append(std::to_string(dt.second + (dt.microsecond > 500000 ? 1 : 0))); break; } case template_part::template_type::second_leading_zero_fractional: { if (dt.second < 10) { result.push_back('0'); } result.append(std::to_string(dt.second)); break; } case template_part::template_type::am_pm: { if (dt.hour < 12) { result.append("AM"); } else { result.append("PM"); } break; } case template_part::template_type::a_p: { if (dt.hour < 12) { result.append("A"); } else { result.append("P"); } break; } case template_part::template_type::elapsed_hours: { result.append(std::to_string(24 * static_cast<int>(number) + dt.hour)); break; } case template_part::template_type::elapsed_minutes: { result.append(std::to_string(24 * 60 * static_cast<int>(number) + (60 * dt.hour) + dt.minute)); break; } case template_part::template_type::elapsed_seconds: { result.append(std::to_string(24 * 60 * 60 * static_cast<int>(number) + (60 * 60 * dt.hour) + (60 * dt.minute) + dt.second)); break; } case template_part::template_type::month_letter: { result.append(month_names->at(static_cast<std::size_t>(dt.month) - 1).substr(0, 1)); break; } case template_part::template_type::day_abbreviation: { result.append(day_names->at(static_cast<std::size_t>(dt.weekday()) - 1).substr(0, 3)); break; } case template_part::template_type::day_name: { result.append(day_names->at(static_cast<std::size_t>(dt.weekday()) - 1)); break; } } } const std::size_t width = 11; if (fill && result.size() < width) { auto remaining = width - result.size(); std::string fill_string(remaining, fill_character.front()); // TODO: A UTF-8 character could be multiple bytes result = result.substr(0, fill_index) + fill_string + result.substr(fill_index); } return result; } std::string number_formatter::format_text(const format_code &format, const std::string &text) { std::string result; bool any_text_part = false; for (const auto &part : format.parts) { if (part.type == template_part::template_type::text) { result.append(part.string); any_text_part = true; } else if (part.type == template_part::template_type::general) { if (part.placeholders.type == format_placeholders::placeholders_type::general || part.placeholders.type == format_placeholders::placeholders_type::text) { result.append(text); any_text_part = true; } } } if (!format.parts.empty() && !any_text_part) { return text; } return result; } } // namespace detail } // namespace xlnt
30.630397
121
0.512602
[ "vector" ]
a32995137e9c6a86a29d6d4e5e12d3ea4f4d4abe
1,411
cpp
C++
src/xray/xrLC/xrMU_Model_export_cform_game_s.cpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/xray/xrLC/xrMU_Model_export_cform_game_s.cpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/xray/xrLC/xrMU_Model_export_cform_game_s.cpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
#include "stdafx.h" #include "xrMU_model.h" void xrMU_Reference::export_cform_game (_mesh& mesh, xr_vector<cform_FailFace>& failedfaces) { Log ("model:",*(model->m_name)); // verts for (u32 V=0; V<model->m_vertices.size(); V++) model->m_vertices[V]->handle = _mesh::InvalidVertexHandle.idx(); // faces std::vector <_mesh::VertexHandle> fhandles; cform_mergeprops fmergeprops; for (xrMU_Model::v_faces_it I=model->m_faces.begin(); I!=model->m_faces.end(); I++) { xrMU_Model::_face* F = *I; if (F->Shader().flags.bCollision) { // add vertices fhandles.clear (); for (u32 v=0; v<3; v++) { _mesh::VertexHandle h = _mesh::VertexHandle(F->v[v]->handle); if (_mesh::InvalidVertexHandle == h) { Fvector p; xform.transform_tiny(p,F->v[0]->P); h = mesh.add_vertex (_mesh::Point(p.x,p.y,p.z)); F->v[v]->handle = h.idx(); } fhandles.push_back (h); } // add face fmergeprops.material = F->dwMaterialGame; fmergeprops.sector = sector; _mesh::FaceHandle hface = mesh.add_face (fhandles); if (hface == _mesh::InvalidFaceHandle) { failedfaces.push_back (cform_FailFace()); failedfaces.back().P[0] = F->v[0]->P; failedfaces.back().P[1] = F->v[1]->P; failedfaces.back().P[2] = F->v[2]->P; failedfaces.back().props = fmergeprops.props; } else mesh.face(hface).set_props (fmergeprops.props); } } }
30.021277
112
0.627215
[ "mesh", "vector", "model" ]
a32bb6600444d08f028031267f30d13f9a6c742b
31,149
cpp
C++
IGC/VectorCompiler/lib/GenXOpts/CMTrans/GenXImportOCLBiF.cpp
liushuyu/intel-graphics-compiler
093655fe61e74cc9851436ed5233c61e181d6f60
[ "Intel", "MIT" ]
null
null
null
IGC/VectorCompiler/lib/GenXOpts/CMTrans/GenXImportOCLBiF.cpp
liushuyu/intel-graphics-compiler
093655fe61e74cc9851436ed5233c61e181d6f60
[ "Intel", "MIT" ]
null
null
null
IGC/VectorCompiler/lib/GenXOpts/CMTrans/GenXImportOCLBiF.cpp
liushuyu/intel-graphics-compiler
093655fe61e74cc9851436ed5233c61e181d6f60
[ "Intel", "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (C) 2019-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ // /// GenXImportOCLBiF /// ----------- /// /// This pass import Builtin Function library compiled into bitcode /// /// - analysis functions called by the main module /// /// - import used function, and remove unused functions /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "cmimportbif" #include "vc/GenXOpts/GenXOpts.h" #include "vc/Support/BackendConfig.h" #include "vc/Utils/General/BiF.h" #include <llvm/ADT/STLExtras.h> #include <llvm/ADT/SmallPtrSet.h> #include <llvm/ADT/StringRef.h> #include <llvm/ADT/Twine.h> #include <llvm/Bitcode/BitcodeReader.h> #include <llvm/IR/Attributes.h> #include <llvm/IR/Constants.h> #include <llvm/IR/InstIterator.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/Module.h> #include <llvm/Linker/Linker.h> #include <llvm/Support/Error.h> #include <llvm/Support/ErrorHandling.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/Transforms/Utils/ValueMapper.h> #include <llvmWrapper/IR/Instructions.h> #include <algorithm> #include <iterator> #include <sstream> #include <unordered_set> #include <vector> #include "Probe/Assertion.h" #include "llvm/GenXIntrinsics/GenXIntrinsicInst.h" using namespace llvm; class BIConvert { // builtins that maps to one intrinsic std::map<StringRef, unsigned> OneMap; // builtins that maps to two intrinsics std::map<StringRef, std::pair<unsigned, unsigned>> TwoMap; public: BIConvert(); void runOnModule(Module &M); }; BIConvert::BIConvert() { // float-to-float OneMap["__builtin_IB_frnd_ne"] = GenXIntrinsic::genx_rnde; OneMap["__builtin_IB_ftoh_rtn"] = GenXIntrinsic::genx_rndd; OneMap["__builtin_IB_ftoh_rtp"] = GenXIntrinsic::genx_rndu; OneMap["__builtin_IB_ftoh_rtz"] = GenXIntrinsic::genx_rndz; OneMap["__builtin_IB_dtoh_rtn"] = GenXIntrinsic::genx_rnde; OneMap["__builtin_IB_dtoh_rtp"] = GenXIntrinsic::genx_rndu; OneMap["__builtin_IB_dtoh_rtz"] = GenXIntrinsic::genx_rndz; OneMap["__builtin_IB_dtof_rtn"] = GenXIntrinsic::genx_rnde; OneMap["__builtin_IB_dtof_rtp"] = GenXIntrinsic::genx_rndu; OneMap["__builtin_IB_dtof_rtz"] = GenXIntrinsic::genx_rndz; // math OneMap["__builtin_IB_frnd_pi"] = GenXIntrinsic::genx_rndu; OneMap["__builtin_IB_frnd_ni"] = GenXIntrinsic::genx_rndd; OneMap["__builtin_IB_frnd_zi"] = GenXIntrinsic::genx_rndz; OneMap["__builtin_IB_native_cosf"] = GenXIntrinsic::genx_cos; OneMap["__builtin_IB_native_cosh"] = GenXIntrinsic::genx_cos; OneMap["__builtin_IB_native_sinf"] = GenXIntrinsic::genx_sin; OneMap["__builtin_IB_native_sinh"] = GenXIntrinsic::genx_sin; OneMap["__builtin_IB_native_exp2f"] = GenXIntrinsic::genx_exp; OneMap["__builtin_IB_native_exp2h"] = GenXIntrinsic::genx_exp; OneMap["__builtin_IB_native_log2f"] = GenXIntrinsic::genx_log; OneMap["__builtin_IB_native_log2h"] = GenXIntrinsic::genx_log; OneMap["__builtin_IB_native_sqrtf"] = GenXIntrinsic::genx_sqrt; OneMap["__builtin_IB_native_sqrth"] = GenXIntrinsic::genx_sqrt; OneMap["__builtin_IB_native_sqrtd"] = GenXIntrinsic::genx_sqrt; OneMap["__builtin_IB_popcount_1u32"] = GenXIntrinsic::genx_cbit; OneMap["__builtin_IB_popcount_1u16"] = GenXIntrinsic::genx_cbit; OneMap["__builtin_IB_popcount_1u8"] = GenXIntrinsic::genx_cbit; OneMap["__builtin_IB_native_powrf"] = GenXIntrinsic::genx_pow; OneMap["__builtin_IB_fma"] = Intrinsic::fma; OneMap["__builtin_IB_fmah"] = Intrinsic::fma; OneMap["__builtin_IB_bfrev"] = GenXIntrinsic::genx_bfrev; OneMap["__builtin_IB_fmax"] = GenXIntrinsic::genx_fmax; OneMap["__builtin_IB_fmin"] = GenXIntrinsic::genx_fmin; OneMap["__builtin_IB_HMAX"] = GenXIntrinsic::genx_fmax; OneMap["__builtin_IB_HMIN"] = GenXIntrinsic::genx_fmin; OneMap["__builtin_IB_dmin"] = GenXIntrinsic::genx_fmin; OneMap["__builtin_IB_dmax"] = GenXIntrinsic::genx_fmax; // ieee OneMap["__builtin_IB_ieee_sqrt"] = GenXIntrinsic::genx_ieee_sqrt; OneMap["__builtin_IB_ieee_divide"] = GenXIntrinsic::genx_ieee_div; OneMap["__builtin_IB_ieee_divide_f64"] = GenXIntrinsic::genx_ieee_div; TwoMap["__builtin_IB_dtoi8_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi8_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi8_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi16_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi16_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi16_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi32_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi32_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi32_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi64_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi64_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoi64_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptosi_sat); TwoMap["__builtin_IB_dtoui8_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui8_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui8_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui16_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui16_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui16_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui32_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui32_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui32_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui64_rtn"] = std::make_pair(GenXIntrinsic::genx_rndd, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui64_rtp"] = std::make_pair(GenXIntrinsic::genx_rndu, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_dtoui64_rte"] = std::make_pair(GenXIntrinsic::genx_rnde, GenXIntrinsic::genx_fptoui_sat); TwoMap["__builtin_IB_fma_rtz_f64"] = std::make_pair(Intrinsic::fma, GenXIntrinsic::genx_rndz); TwoMap["__builtin_IB_fma_rtz_f32"] = std::make_pair(Intrinsic::fma, GenXIntrinsic::genx_rndz); } void BIConvert::runOnModule(Module &M) { std::vector<Instruction *> ListDelete; for (Function &func : M) { for (auto &BB : func) { for (auto I = BB.begin(), E = BB.end(); I != E; I++) { CallInst *InstCall = dyn_cast<CallInst>(I); if (!InstCall) continue; Function *callee = InstCall->getCalledFunction(); if (!callee) continue; // get rid of lifetime marker, avoid dealing with it in packetizer Intrinsic::ID id = (Intrinsic::ID)callee->getIntrinsicID(); if (id == Intrinsic::lifetime_start || id == Intrinsic::lifetime_end) { ListDelete.push_back(InstCall); continue; } else if (id == Intrinsic::ctlz) { // convert this to genx_ldz, but genx_lzd only support 32-bit input auto Src = InstCall->getOperand(0); auto SrcTy = Src->getType(); IGC_ASSERT(SrcTy->isIntegerTy()); IGC_ASSERT(SrcTy->getPrimitiveSizeInBits() == 32); Type *tys[1]; SmallVector<llvm::Value *, 1> args; // build type-list for the 1st intrinsic tys[0] = SrcTy; // build argument list for the 1st intrinsic args.push_back(Src); Function *IntrinFunc = GenXIntrinsic::getAnyDeclaration( &M, GenXIntrinsic::genx_lzd, tys); Instruction *IntrinCall = CallInst::Create(IntrinFunc, args, InstCall->getName(), InstCall); IntrinCall->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(IntrinCall); ListDelete.push_back(InstCall); continue; } StringRef CalleeName = callee->getName(); // Check if it exists in the one-intrinsic map. if (OneMap.count(CalleeName)) { // Some of OneMap intrinsics require only ret type, but others require // arg types (currently only arg0) as well. std::vector<Type *> tys; tys.reserve(InstCall->getNumArgOperands() + 1 /* RetTy */); SmallVector<llvm::Value *, 3> args; unsigned IID = OneMap[CalleeName]; // build type-list if (GenXIntrinsic::isGenXIntrinsic(IID)) { if (GenXIntrinsic::isOverloadedRet(IID)) tys.push_back(callee->getReturnType()); for (unsigned i = 0; i < InstCall->getNumArgOperands(); ++i) if (GenXIntrinsic::isOverloadedArg(IID, i)) tys.push_back(InstCall->getArgOperand(i)->getType()); } else tys.push_back(callee->getReturnType()); // build argument list args.append(InstCall->op_begin(), InstCall->op_begin() + InstCall->getNumArgOperands()); Function *IntrinFunc = GenXIntrinsic::getAnyDeclaration(&M, IID, tys); Instruction *IntrinCall = CallInst::Create(IntrinFunc, args, InstCall->getName(), InstCall); IntrinCall->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(IntrinCall); ListDelete.push_back(InstCall); } // check if the builtin maps to two intrinsics else if (TwoMap.count(CalleeName)) { auto pair = TwoMap[CalleeName]; // create the 1st intrinsic Type *tys0[1]; SmallVector<llvm::Value *, 3> args0; // build type-list for the 1st intrinsic tys0[0] = InstCall->getArgOperand(0)->getType(); // build argument list for the 1st intrinsic args0.append(InstCall->op_begin(), InstCall->op_begin() + InstCall->getNumArgOperands()); Function *IntrinFunc0 = GenXIntrinsic::getAnyDeclaration(&M, pair.first, tys0); Instruction *IntrinCall0 = CallInst::Create( IntrinFunc0, args0, InstCall->getName(), InstCall); IntrinCall0->setDebugLoc(InstCall->getDebugLoc()); // create the 2nd intrinsic Type *tys1[2]; SmallVector<llvm::Value *, 3> args1; // build type-list for the 1st intrinsic tys1[0] = callee->getReturnType(); tys1[1] = IntrinCall0->getType(); // build argument list for the 1st intrinsic args1.push_back(IntrinCall0); Function *IntrinFunc1 = GenXIntrinsic::getAnyDeclaration(&M, pair.second, tys1); Instruction *IntrinCall1 = CallInst::Create( IntrinFunc1, args1, InstCall->getName(), InstCall); IntrinCall1->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(IntrinCall1); ListDelete.push_back(InstCall); } // other cases else if (CalleeName.startswith("__builtin_IB_itof")) { Instruction *Replace = SIToFPInst::Create( Instruction::SIToFP, InstCall->getArgOperand(0), callee->getReturnType(), InstCall->getName(), InstCall); Replace->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(Replace); ListDelete.push_back(InstCall); } else if (CalleeName.startswith("__builtin_IB_uitof")) { Instruction *Replace = UIToFPInst::Create( Instruction::UIToFP, InstCall->getArgOperand(0), callee->getReturnType(), InstCall->getName(), InstCall); Replace->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(Replace); ListDelete.push_back(InstCall); } else if (CalleeName.startswith("__builtin_IB_mul_rtz")) { Instruction *Mul = BinaryOperator::Create( Instruction::FMul, InstCall->getArgOperand(0), InstCall->getArgOperand(1), InstCall->getName(), InstCall); Mul->setDebugLoc(InstCall->getDebugLoc()); Type *tys[1]; SmallVector<llvm::Value *, 3> args; // build type-list for the 1st intrinsic tys[0] = InstCall->getArgOperand(0)->getType(); // build argument list for the 1st intrinsic args.push_back(Mul); Function *IntrinFunc = GenXIntrinsic::getAnyDeclaration( &M, GenXIntrinsic::genx_rndz, tys); Instruction *IntrinCall = CallInst::Create(IntrinFunc, args, InstCall->getName(), InstCall); IntrinCall->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(IntrinCall); ListDelete.push_back(InstCall); } else if (CalleeName.startswith("__builtin_IB_add_rtz")) { Instruction *Add = BinaryOperator::Create( Instruction::FAdd, InstCall->getArgOperand(0), InstCall->getArgOperand(1), InstCall->getName(), InstCall); Add->setDebugLoc(InstCall->getDebugLoc()); Type *tys[1]; SmallVector<llvm::Value *, 3> args; // build type-list for the 1st intrinsic tys[0] = InstCall->getArgOperand(0)->getType(); // build argument list for the 1st intrinsic args.push_back(Add); Function *IntrinFunc = GenXIntrinsic::getAnyDeclaration( &M, GenXIntrinsic::genx_rndz, tys); Instruction *IntrinCall = CallInst::Create(IntrinFunc, args, InstCall->getName(), InstCall); IntrinCall->setDebugLoc(InstCall->getDebugLoc()); InstCall->replaceAllUsesWith(IntrinCall); ListDelete.push_back(InstCall); } } } } // clean up the dead calls for (auto I : ListDelete) { I->eraseFromParent(); } for (auto &Global : M.getGlobalList()) { if (!Global.isDeclaration()) Global.setLinkage(GlobalValue::InternalLinkage); } for (auto &F : M.getFunctionList()) { // TODO: revise the code once CM-based BIFs are implemented if (F.getName().contains("__cm_intrinsic_impl_")) { IGC_ASSERT_MESSAGE( F.getLinkage() == GlobalValue::ExternalLinkage, "CM library functions are expected to have an external linkage"); continue; } if (F.getIntrinsicID() == Intrinsic::not_intrinsic && !F.isDeclaration() && !F.hasDLLExportStorageClass()) F.setLinkage(GlobalValue::InternalLinkage); } } typedef std::vector<llvm::Function *> TFunctionsVec; static Function *GetBuiltinFunction(llvm::StringRef funcName, llvm::Module &BiFModule) { Function *pFunc = BiFModule.getFunction(funcName); if (pFunc && !pFunc->isDeclaration()) return pFunc; return nullptr; } static bool materialized_use_empty(const Value *v) { return v->materialized_use_begin() == v->use_end(); } static void removeFunctionBitcasts(llvm::Module &M) { std::vector<Instruction *> list_delete; DenseMap<Function *, std::vector<Function *>> bitcastFunctionMap; for (Function &func : M) { for (auto &BB : func) { for (auto I = BB.begin(), E = BB.end(); I != E; I++) { CallInst *pInstCall = dyn_cast<CallInst>(I); if (!pInstCall || pInstCall->getCalledFunction()) continue; if (auto constExpr = dyn_cast<llvm::ConstantExpr>( IGCLLVM::getCalledValue(pInstCall))) { if (auto funcTobeChanged = dyn_cast<llvm::Function>(constExpr->stripPointerCasts())) { if (funcTobeChanged->isDeclaration()) continue; // Map between values (functions) in source of bitcast // to their counterpart values in destination llvm::ValueToValueMapTy operandMap; Function *pDstFunc = nullptr; auto BCFMI = bitcastFunctionMap.find(funcTobeChanged); bool notExists = BCFMI == bitcastFunctionMap.end(); if (!notExists) { auto funcVec = bitcastFunctionMap[funcTobeChanged]; notExists = true; for (Function *F : funcVec) { if (pInstCall->getFunctionType() == F->getFunctionType()) { notExists = false; pDstFunc = F; break; } } } if (notExists) { pDstFunc = Function::Create(pInstCall->getFunctionType(), funcTobeChanged->getLinkage(), funcTobeChanged->getName(), &M); if (pDstFunc->arg_size() != funcTobeChanged->arg_size()) continue; // Need to copy the attributes over too. auto FuncAttrs = funcTobeChanged->getAttributes(); pDstFunc->setAttributes(FuncAttrs); // Go through and convert function arguments over, remembering the // mapping. Function::arg_iterator itSrcFunc = funcTobeChanged->arg_begin(); Function::arg_iterator eSrcFunc = funcTobeChanged->arg_end(); llvm::Function::arg_iterator itDest = pDstFunc->arg_begin(); for (; itSrcFunc != eSrcFunc; ++itSrcFunc, ++itDest) { itDest->setName(itSrcFunc->getName()); operandMap[&(*itSrcFunc)] = &(*itDest); } // Clone the body of the function into the dest function. SmallVector<ReturnInst *, 8> Returns; // Ignore returns. CloneFunctionInto(pDstFunc, funcTobeChanged, operandMap, false, Returns, ""); pDstFunc->setCallingConv(funcTobeChanged->getCallingConv()); bitcastFunctionMap[funcTobeChanged].push_back(pDstFunc); } std::vector<Value *> Args; for (unsigned I = 0, E = pInstCall->getNumArgOperands(); I != E; ++I) { Args.push_back(pInstCall->getArgOperand(I)); } auto newCI = CallInst::Create(pDstFunc, Args, "", pInstCall); newCI->takeName(pInstCall); newCI->setCallingConv(pInstCall->getCallingConv()); pInstCall->replaceAllUsesWith(newCI); pInstCall->dropAllReferences(); if (constExpr->use_empty()) constExpr->dropAllReferences(); if (funcTobeChanged->use_empty()) funcTobeChanged->eraseFromParent(); list_delete.push_back(pInstCall); } } } } } for (auto i : list_delete) { i->eraseFromParent(); } } static void InitializeBIFlags(llvm::Module &M) { /// @brief Adds initialization to a global-var according to given value. /// If the given global-var does not exist, does nothing. auto initializeVarWithValue = [&M](StringRef varName, uint32_t value) { GlobalVariable *gv = M.getGlobalVariable(varName); if (gv == nullptr) return; gv->setInitializer( ConstantInt::get(Type::getInt32Ty(M.getContext()), value)); }; initializeVarWithValue("__FlushDenormals", 1); initializeVarWithValue("__DashGSpecified", 0); initializeVarWithValue("__FastRelaxedMath", 0); initializeVarWithValue("__UseNative64BitIntSubgroupBuiltin", 1); initializeVarWithValue("__UseNative64BitFloatSubgroupBuiltin", 1); initializeVarWithValue("__CRMacros", 1); initializeVarWithValue("__IsSPIRV", 0); initializeVarWithValue("__EnableSWSrgbWrites", 0); float profilingTimerResolution = 0.0; initializeVarWithValue("__ProfilingTimerResolution", *reinterpret_cast<int *>(&profilingTimerResolution)); initializeVarWithValue("__UseMathWithLUT", 0); } namespace { // Note: FuncDecl is a declaration of a function in the main module. // FuncImpl is a definition of this function in the BiF module. struct FuncAndItsImpl { Function *FuncDecl; Function *FuncImpl; }; } // namespace static constexpr const char SPIRVOCLBuiltinPrefix[] = "__spirv_ocl_"; static bool isOCLBuiltinDecl(const Function &F) { if (!F.isDeclaration()) return false; if (F.isIntrinsic() || GenXIntrinsic::isGenXIntrinsic(&F)) return false; // presuming that the only declarations left are from OCL header return true; } static bool isSPIRVOCLBuiltinDecl(const Function &F) { return isOCLBuiltinDecl(F) && F.getName().contains(SPIRVOCLBuiltinPrefix); } static void fixCallingConv(Function &FuncDecl, CallingConv::ID Conv) { FuncDecl.setCallingConv(Conv); for (User *U : FuncDecl.users()) cast<CallInst>(U)->setCallingConv(Conv); } static void fixCallingConv(const std::vector<FuncAndItsImpl> &UsedBiFFuncs) { for (const auto &FuncLinkInfo : UsedBiFFuncs) { if (FuncLinkInfo.FuncDecl->getCallingConv() != FuncLinkInfo.FuncImpl->getCallingConv()) fixCallingConv(*FuncLinkInfo.FuncDecl, FuncLinkInfo.FuncImpl->getCallingConv()); } } static std::vector<FuncAndItsImpl> collectBiFFuncUses(Module &MainModule, Module &BiFModule) { std::vector<FuncAndItsImpl> FuncsFromBiF; for (auto &Func : MainModule) if (isOCLBuiltinDecl(Func)) { StringRef FuncName = Func.getName(); Function *FuncBiFImpl = GetBuiltinFunction(FuncName, BiFModule); if (FuncBiFImpl) FuncsFromBiF.push_back({&Func, FuncBiFImpl}); } return std::move(FuncsFromBiF); } static void materializeFuncIfRequired(Function &Func) { if (Func.isMaterializable()) { if (Error Err = Func.materialize()) { handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { errs() << "===> Materialize Failure: " << EIB.message().c_str() << '\n'; }); IGC_ASSERT_MESSAGE(0, "Failed to materialize Global Variables"); } } } // Collects functions that are directly called from \p Parent function // (goes only one step in depth in the call graph). static std::vector<Function *> collectDirectSubroutines(Function &Parent) { std::vector<Function *> Subroutines; llvm::transform( make_filter_range( instructions(Parent), [](Instruction &Inst) { if (!isa<CallInst>(Inst)) return false; auto *Subroutine = cast<CallInst>(Inst).getCalledFunction(); IGC_ASSERT_MESSAGE(Subroutine, "indirect calls are unexpected in BiF module"); IGC_ASSERT_MESSAGE(!GenXIntrinsic::isGenXIntrinsic(Subroutine), "genx intrinsics are unexpected in BiF module"); return !Subroutine->isIntrinsic(); }), std::back_inserter(Subroutines), [](Instruction &Inst) { auto *Subroutine = cast<CallInst>(Inst).getCalledFunction(); IGC_ASSERT_MESSAGE(Subroutine, "indirect calls are unexpected in BiF module"); IGC_ASSERT_MESSAGE(!Subroutine->isIntrinsic() && !GenXIntrinsic::isGenXIntrinsic(Subroutine), "it should've been already checked"); return Subroutine; }); std::sort(Subroutines.begin(), Subroutines.end()); Subroutines.erase(std::unique(Subroutines.begin(), Subroutines.end()), Subroutines.end()); return std::move(Subroutines); } class BiFImporter { Module &MainModule; std::unique_ptr<Module> BiFModule; std::unordered_set<Function *> ImportedFuncs; public: BiFImporter(Module &MainModuleIn, std::unique_ptr<llvm::Module> BiFModuleIn) : MainModule{MainModuleIn}, BiFModule{std::move(BiFModuleIn)} {} void run(); private: void materializeSubroutines(Function &Parent); void materializeUsedBiFFuncs(const std::vector<FuncAndItsImpl> &FuncsFromBiF); void forceInlining(); }; // Recursively materialize \p Parent's subroutines and its subroutines too. void BiFImporter::materializeSubroutines(Function &Parent) { std::vector<Function *> DirectSubroutines = collectDirectSubroutines(Parent); for (Function *Subroutine : DirectSubroutines) { if (ImportedFuncs.count(Subroutine) == 0) { ImportedFuncs.insert(Subroutine); materializeFuncIfRequired(*Subroutine); materializeSubroutines(*Subroutine); } } } void BiFImporter::materializeUsedBiFFuncs( const std::vector<FuncAndItsImpl> &FuncsFromBiF) { std::vector<Function *> BiFFuncs; for (auto &&[FuncDecl, FuncImpl] : FuncsFromBiF) { (void)FuncDecl; ImportedFuncs.insert(FuncImpl); materializeFuncIfRequired(*FuncImpl); materializeSubroutines(*FuncImpl); } } void BiFImporter::forceInlining() { for (auto *Func : ImportedFuncs) if (!Func->hasFnAttribute(Attribute::AlwaysInline)) Func->addFnAttr(Attribute::AlwaysInline); } void BiFImporter::run() { std::vector<FuncAndItsImpl> FuncsFromBiF = collectBiFFuncUses(MainModule, *BiFModule); materializeUsedBiFFuncs(FuncsFromBiF); fixCallingConv(FuncsFromBiF); // FIXME: workaround to solve several issues in the backend, remove it forceInlining(); // nuke the unused functions so we can materializeAll() quickly auto CleanUnused = [](llvm::Module *Module) { for (auto I = Module->begin(), E = Module->end(); I != E;) { auto *F = &(*I++); if (F->isDeclaration() || F->isMaterializable()) { if (materialized_use_empty(F)) { F->eraseFromParent(); } } } }; CleanUnused(BiFModule.get()); Linker ld(MainModule); if (Error Err = BiFModule->materializeAll()) { handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { errs() << "===> Materialize All Failure: " << EIB.message().c_str() << '\n'; }); IGC_ASSERT_MESSAGE(0, "materializeAll failed for generic builtin module"); } if (ld.linkInModule(std::move(BiFModule))) { IGC_ASSERT_MESSAGE(0, "Error linking generic builtin module"); } InitializeBIFlags(MainModule); removeFunctionBitcasts(MainModule); std::vector<Instruction *> InstToRemove; for (auto I : InstToRemove) { I->eraseFromParent(); } } class GenXImportOCLBiF final : public ModulePass { public: static char ID; GenXImportOCLBiF() : ModulePass(ID) {} StringRef getPassName() const override { return "GenX import OCL BiF"; } void getAnalysisUsage(AnalysisUsage &AU) const override; bool runOnModule(Module &M) override; private: std::unique_ptr<Module> getBiFModule(BiFKind Kind, LLVMContext &Ctx); }; char GenXImportOCLBiF::ID = 0; INITIALIZE_PASS_BEGIN(GenXImportOCLBiF, "GenXImportOCLBiF", "GenXImportOCLBiF", false, false) INITIALIZE_PASS_DEPENDENCY(GenXBackendConfig) INITIALIZE_PASS_END(GenXImportOCLBiF, "GenXImportOCLBiF", "GenXImportOCLBiF", false, false) ModulePass *llvm::createGenXImportOCLBiFPass() { initializeGenXImportOCLBiFPass(*PassRegistry::getPassRegistry()); return new GenXImportOCLBiF; } void GenXImportOCLBiF::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<GenXBackendConfig>(); } // Whether module has uresolved calls to OpenCL builtins. static bool OCLBuiltinsRequired(const Module &M) { return std::any_of(M.begin(), M.end(), [](const Function &F) { return isOCLBuiltinDecl(F); }); } // Translates SPIR-V OCL builtin name into OCL library function name. // FIXME: delete it. Hand demangling was provided as a quick'n'dirty solution. static std::string translateSPIRVOCLBuiltinName(StringRef OrigName) { StringRef SPIRVOCLBuiltinPrefixRef{SPIRVOCLBuiltinPrefix}; auto DemangledNameBegin = OrigName.find(SPIRVOCLBuiltinPrefix); IGC_ASSERT_MESSAGE(DemangledNameBegin != StringRef::npos, "should've found spirv ocl prefix in the name"); StringRef NameLengthWithPrefix = OrigName.take_front(DemangledNameBegin); const StringRef GlobalNSPrefix = "_Z"; IGC_ASSERT_MESSAGE(NameLengthWithPrefix.startswith(GlobalNSPrefix), "the name is expected to start with _Z"); StringRef NameLengthStr = NameLengthWithPrefix.drop_front(GlobalNSPrefix.size()); int NameLength; bool Error = NameLengthStr.getAsInteger(10, NameLength); IGC_ASSERT_MESSAGE(!Error, "error occured during name length decoding"); StringRef OrigDemangledName = OrigName.substr(DemangledNameBegin, NameLength); StringRef NewDemangledName = OrigDemangledName.drop_front(SPIRVOCLBuiltinPrefixRef.size()); StringRef OrigNameSuffix = OrigName.take_back( OrigName.size() - NameLengthWithPrefix.size() - NameLength); std::stringstream NewNameBuilder; NewNameBuilder << GlobalNSPrefix.str() << NewDemangledName.size() << NewDemangledName.str() << OrigNameSuffix.str(); return NewNameBuilder.str(); } static void translateSPIRVOCLBuiltin(Function &F) { StringRef OrigName = F.getName(); auto NewName = translateSPIRVOCLBuiltinName(OrigName); F.setName(NewName); } // SPIR-V OCL builtins are functions that start with __spirv_ocl_. // OCL library functions have no prefix. So e.g. __spirv_ocl_exp(double) // should be translated into exp(double). static void translateSPIRVOCLBuiltins(Module &M) { auto Worklist = make_filter_range( M, [](Function &F) { return isSPIRVOCLBuiltinDecl(F); }); llvm::for_each(Worklist, [](Function &F) { translateSPIRVOCLBuiltin(F); }); } bool GenXImportOCLBiF::runOnModule(Module &M) { if (!OCLBuiltinsRequired(M)) return false; translateSPIRVOCLBuiltins(M); std::unique_ptr<Module> GenericBiFModule = getBiFModule(BiFKind::OCLGeneric, M.getContext()); GenericBiFModule->setDataLayout(M.getDataLayout()); GenericBiFModule->setTargetTriple(M.getTargetTriple()); BiFImporter{M, std::move(GenericBiFModule)}.run(); BIConvert{}.runOnModule(M); return true; } std::unique_ptr<Module> GenXImportOCLBiF::getBiFModule(BiFKind Kind, LLVMContext &Ctx) { MemoryBufferRef BiFModuleBuffer = getAnalysis<GenXBackendConfig>().getBiFModule(Kind); return vc::getLazyBiFModuleOrReportError(BiFModuleBuffer, Ctx); }
40.877953
80
0.666763
[ "vector", "transform" ]
cd113cb74f436cf495fc4434f9757f53c9e08297
7,523
cpp
C++
app/tenncor/src/tensor/tensorshape.cpp
mingkaic/rocnnet
b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab
[ "MIT" ]
3
2017-01-18T20:42:56.000Z
2018-11-07T12:56:15.000Z
app/tenncor/src/tensor/tensorshape.cpp
mingkaic/rocnnet
b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab
[ "MIT" ]
10
2016-12-01T08:15:28.000Z
2018-09-28T17:16:32.000Z
app/tenncor/src/tensor/tensorshape.cpp
mingkaic/rocnnet
b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab
[ "MIT" ]
null
null
null
// // tensorshape.cpp // cnnet // // Created by Mingkai Chen on 2016-08-29. // Copyright © 2016 Mingkai Chen. All rights reserved. // #include "tensor/tensorshape.hpp" #ifdef TENNCOR_TENSORSHAPE_HPP namespace nnet { tensorshape::tensorshape (const std::vector<size_t>& dims) : dimensions_(dims) {} tensorshape& tensorshape::operator = (const std::vector<size_t>& dims) { dimensions_ = dims; return *this; } std::vector<size_t> tensorshape::as_list (void) const { return dimensions_; } size_t tensorshape::n_elems (void) const { if (dimensions_.empty()) { return 0; } size_t elems = std::accumulate(dimensions_.begin(), dimensions_.end(), (size_t) 1, std::multiplies<size_t>()); return elems; } size_t tensorshape::n_known (void) const { if (dimensions_.empty()) { return 0; } size_t elems = std::accumulate(dimensions_.begin(), dimensions_.end(), (size_t) 1, [](size_t a, size_t b) { if (b != 0) { return a * b; } return a; }); return elems; } size_t tensorshape::rank (void) const { return dimensions_.size(); } bool tensorshape::is_compatible_with (const tensorshape& other) const { bool incomp = true; if (!dimensions_.empty() && !other.dimensions_.empty()) { size_t thisn = dimensions_.size(); size_t othern = other.dimensions_.size(); size_t beginthis = 0; size_t beginother = 0; // invariant thisn and othern >= 1 (since dimensions are not empty) size_t endthis = thisn-1; size_t endother = othern-1; if (thisn != othern) { while (beginthis < thisn-1 && 1 == dimensions_[beginthis]) { beginthis++; } while (endthis > beginthis && 1 == dimensions_[endthis]) { endthis--; } while (beginother < othern-1 && 1 == other.dimensions_[beginother]) { beginother++; } while (endother > beginother && 1 == other.dimensions_[endother]) { endother--; } size_t lenthis = endthis - beginthis; size_t lenother = endother - beginother; if (lenthis > lenother) { // todo: improve this matching algorithm to account for cases where // decrementing endthis before incrementing beginthis matches while the opposite order doesn't // try to match this to other by searching for padding zeros to convert to 1 padding in this while (endthis - beginthis > lenother && beginthis < endthis && 0 == dimensions_[beginthis]) { beginthis++; } while (endthis - beginthis > lenother && endthis > beginthis && 0 == dimensions_[endthis]) { endthis--; } if (endthis - beginthis > lenother) // match unsuccessful, they are incompatible return false; } else if (lenother > lenthis) { // try to match other to this by searching for padding zeros to convert to 1 padding in other while (endother - beginother > lenthis && beginother < endother && 0 == other.dimensions_[beginother]) { beginother++; } while (endother - beginother > lenthis && endother > beginother && 0 == other.dimensions_[endother]) { endother--; } if (endother - beginother > lenthis) // match unsuccessful, they are incompatible return false; } } // invariant: endthis - beginthis == endother - beginother while (beginthis <= endthis && beginother <= endother) { incomp = incomp && (dimensions_[beginthis] == other.dimensions_[beginother] || 0 == (dimensions_[beginthis] && other.dimensions_[beginother])); beginthis++; beginother++; } } return incomp; } bool tensorshape::is_part_defined (void) const { return !dimensions_.empty(); } bool tensorshape::is_fully_defined (void) const { if (dimensions_.empty()) { return false; } bool known = true; for (size_t d : dimensions_) { known = known && (0 < d); } return known; } void tensorshape::assert_has_rank (size_t rank) const { assert(dimensions_.empty() || rank == dimensions_.size()); } void tensorshape::assert_same_rank (const tensorshape& other) const { assert(dimensions_.empty() || other.dimensions_.empty() || other.dimensions_.size() == dimensions_.size()); } void tensorshape::assert_is_fully_defined (void) const { assert(is_fully_defined()); } void tensorshape::undefine (void) { dimensions_.clear(); } tensorshape tensorshape::merge_with (const tensorshape& other) const { if (dimensions_.empty()) { return other; } if (other.dimensions_.empty()) { return *this; } if (dimensions_.size() != other.dimensions_.size()) { throw std::logic_error(nnutils::formatter() << "shape of rank " << dimensions_.size() << " is not compatible with shape of rank " << other.dimensions_.size()); } std::vector<size_t> ds; for (size_t i = 0; i < dimensions_.size(); i++) { size_t value = dimensions_[i]; size_t ovalue = other.dimensions_[i]; if (value == ovalue || (value && ovalue)) { ds.push_back(value); } else { // one of the values is zero, return the non-zero value ds.push_back(value + ovalue); } } return ds; } tensorshape tensorshape::trim (void) const { std::vector<size_t> res; if (false == dimensions_.empty()) { size_t start = 0; size_t end = dimensions_.size() - 1; while (start < end && 1 == dimensions_.at(start)) { start++; } while (start < end && 1 == dimensions_.at(end)) { end--; } if (start < end || 1 != dimensions_.at(end)) { res.insert(res.end(), dimensions_.begin()+start, dimensions_.begin()+end+1); } } return res; } tensorshape tensorshape::concatenate (const tensorshape& other) const { if (dimensions_.empty()) { return other; } if (other.dimensions_.empty()) { return *this; } std::vector<size_t> ds = dimensions_; ds.insert(ds.end(), other.dimensions_.begin(), other.dimensions_.end()); return tensorshape(ds); } tensorshape tensorshape::with_rank (size_t rank) const { size_t ndim = dimensions_.size(); std::vector<size_t> ds; if (rank < ndim) { // clip to rank auto it = dimensions_.begin(); ds.insert(ds.end(), it, it+rank); } else if (rank > ndim) { // pad to fit rank ds = dimensions_; size_t diff = rank - ndim; ds.insert(ds.end(), diff, 1); } else { ds = dimensions_; } return ds; } tensorshape tensorshape::with_rank_at_least (size_t rank) const { size_t ndim = dimensions_.size(); std::vector<size_t> ds = dimensions_; if (rank > ndim) { // pad to fit rank size_t diff = rank - ndim; ds.insert(ds.end(), diff, 1); } return ds; } tensorshape tensorshape::with_rank_at_most (size_t rank) const { std::vector<size_t> ds; if (rank < dimensions_.size()) { // clip to fit rank auto it = dimensions_.begin(); ds.insert(ds.end(), it, it+rank); } else { ds = dimensions_; } return ds; } size_t tensorshape::flat_idx (std::vector<size_t> coord) const { size_t n = std::min(dimensions_.size(), coord.size()); size_t index = 0; for (size_t i = 1; i < n; i++) { index += coord[n-i]; index *= dimensions_[n-i-1]; } return index + coord[0]; } std::vector<size_t> tensorshape::coordinate_from_idx (size_t idx) const { std::vector<size_t> coord; size_t i = idx; for (size_t d : dimensions_) { size_t xd = i % d; coord.push_back(xd); i = (i - xd) / d; } return coord; } void tensorshape::iterate (std::function<void(std::vector<size_t>, size_t)> coord_call) const { size_t n_elems = this->n_elems(); for (size_t i = 0; i < n_elems; i++) { coord_call(coordinate_from_idx(i), i); } } void print_shape (tensorshape ts, std::ostream& os) { std::vector<size_t> shape = ts.as_list(); if (shape.empty()) { os << "undefined "; } else { for (size_t dim : shape) { os << dim << " "; } } } } #endif
22.523952
124
0.660774
[ "shape", "vector" ]
cd12836554b56c9b59fcdf6160ff2cd5309a5c0b
4,842
cpp
C++
Examples/model_viewer.cpp
yushroom/FishEngine-ECS
99e96f96d30a1cc624a7ffb410a34e418449dd81
[ "MIT" ]
10
2018-08-28T17:07:06.000Z
2021-06-19T09:51:27.000Z
Examples/model_viewer.cpp
yushroom/FishEngine-ECS
99e96f96d30a1cc624a7ffb410a34e418449dd81
[ "MIT" ]
1
2018-10-25T19:42:10.000Z
2018-10-30T09:34:05.000Z
Examples/model_viewer.cpp
yushroom/FishEngine-ECS
99e96f96d30a1cc624a7ffb410a34e418449dd81
[ "MIT" ]
5
2018-10-25T19:39:26.000Z
2020-08-09T05:47:57.000Z
#include <FishEngine.hpp> #include <FishEditor.hpp> #include <GLFW/glfw3.h> using namespace FishEngine; using namespace FishEditor; class DrawSkeletonSystem : public System { SYSTEM(DrawSkeletonSystem); public: void Update() override { m_Scene->ForEach<Renderable>([](GameObject* go, Renderable* rend) { if (rend->m_Skin == nullptr) return; Gizmos::matrix = Matrix4x4::identity; Gizmos::color = Vector4(1, 0, 0, 1); for (auto* bone : rend->m_Skin->joints) { auto t = bone->GetTransform(); //Gizmos::matrix = t->GetLocalToWorldMatrix(); //Gizmos::DrawCube(Vector3::zero, Vector3::one * 0.05f); Gizmos::DrawCube(t->GetPosition(), Vector3::one * 0.1f); //auto p = t->GetParent(); //if (p != nullptr) //{ // Gizmos::matrix = p->GetLocalToWorldMatrix(); // Gizmos::DrawLine(t->GetLocalPosition(), Vector3::zero); //} } Gizmos::matrix = Matrix4x4::identity; Gizmos::color = Vector4(0, 1, 0, 1); for (auto* bone : rend->m_Skin->joints) { auto t = bone->GetTransform(); auto p = t->GetParent(); if (p != nullptr) { Gizmos::DrawLine(t->GetPosition(), p->GetPosition()); } } }); } }; inline std::string GetglTFSample(const std::string& name) { #ifdef __APPLE__ return "/Users/yushroom/program/github/glTF-Sample-Models/2.0/" #else return R"(D:\program\glTF-Sample-Models\2.0\)" #endif + name + "/glTF-Binary/" + name + ".glb"; } GameObject* CreateGO(Scene* scene, Mesh* mesh) { auto go = scene->CreateGameObject(); go->name = "GameObject"; auto r = scene->GameObjectAddComponent<Renderable>(go); r->m_Mesh = mesh; auto mat = Material::Clone(Material::pbrMetallicRoughness); mat->SetTexture("baseColorTexture", Texture::s_WhiteTexture); r->m_Materials.push_back(mat); return go; } class ModelViewer : public FishEditor::GameApp { public: void Start() override { // const char* path = FISHENGINE_ROOT "Assets/Models/T-Rex.glb"; auto path = GetglTFSample("CesiumMan"); //path = GetglTFSample("RiggedSimple"); //path = GetglTFSample("TextureCoordinateTest"); // path = GetglTFSample("Triangle"); //path = "/Users/yushroom/program/github/glTF-Sample-Models/2.0/BoomBoxWithAxes/glTF/BoomBoxWithAxes.gltf"; // path = "/Users/yushroom/program/github/glTF-Sample-Models/2.0/Triangle/glTF/Triangle.gltf"; path = R"(D:\program\glTF-Sample-Models\2.0\Sponza\glTF\Sponza.gltf)"; // path = "/Users/yushroom/program/github/glTF-Sample-Models/2.0/Sponza/glTF/Sponza.gltf"; // path = GetglTFSample("Buggy"); //path = GetglTFSample("BrainStem"); { auto go = m_Scene->CreateGameObject(); m_Scene->GameObjectAddComponent<Camera>(go); go->GetTransform()->SetLocalPosition(0, 0, -10); //m_Scene->GameObjectAddComponent<FreeCamera>(go); go->name = "Main Camera"; } { auto go = m_Scene->CreateGameObject(); auto t = go->GetTransform(); auto light = m_Scene->GameObjectAddComponent<Light>(go); t->SetLocalEulerAngles(50, -30, 0); t->SetLocalPosition(0, 3, 0); go->name = "Directional Light"; } auto plane = CreateGO(m_Scene, Mesh::Plane); plane->name = "Plane"; auto cube = CreateGO(m_Scene, Mesh::Cube); cube->name = "Cube"; auto sphere = CreateGO(m_Scene, Mesh::Sphere); sphere->name = "Sphere"; // auto quad = CreateGO(m_Scene, Mesh::Quad); // quad->name = "Quad"; auto cone = CreateGO(m_Scene, Mesh::Cone); cone->name = "Cone"; auto cylinder = CreateGO(m_Scene, Mesh::Cylinder); cylinder->name = "Cylinder"; // auto capsule = CreateGO(m_Scene, Mesh::Capsule); // capsule->name = "Capsule"; GLTFLoadFlags flags; flags.loadMateirals = false; flags.loadPrimitiveAsSubMesh = true; auto rootGO = ModelUtil::FromGLTF(path, flags, m_Scene); // auto rootGO = m_Scene->CreateGameObject(); // auto r = m_Scene->GameObjectAddComponent<Renderable>(rootGO); // r->mesh = Mesh::Cube; // rootGO->GetTransform()->SetLocalEulerAngles(-90, -90, 0); //rootGO->GetTransform()->SetLocalScale(100); { auto s = m_Scene->AddSystem<AnimationSystem>(); s->m_Priority = 999; s->m_Enabled = false; } m_Scene->AddSystem<DrawSkeletonSystem>(); auto selection = m_EditorScene->GetSingletonComponent<SingletonSelection>(); // selection->selected = Camera::GetMainCamera()->m_GameObject; selection->selected = rootGO; { auto cam = Camera::GetEditorCamera(); assert(cam != nullptr); cam->GetTransform()->SetLocalPosition(5, 6, -0.5); cam->GetTransform()->SetLocalEulerAngles(30, -90, 0); } // { // auto cam = Camera::GetMainCamera(); // cam->SetFarClipPlane(40); // cam->SetNearClipPlane(5); // auto t = Camera::GetMainCamera()->GetTransform(); // t->SetPosition(-12, 0, -12); // } // bgfx::setViewMode(0, bgfx::ViewMode::Sequential); } }; int main(void) { ModelViewer demo; demo.Run(); return 0; }
28.650888
109
0.666047
[ "mesh" ]
cd1648a7fd1298432f835720d9c018ddb954fe1c
16,983
cpp
C++
logdevice/admin/maintenance/test/APIUtilsTest.cpp
dmitris/LogDevice
18336bb95262c51d9b1e8f2f9ae9ad0874b023cd
[ "BSD-3-Clause" ]
null
null
null
logdevice/admin/maintenance/test/APIUtilsTest.cpp
dmitris/LogDevice
18336bb95262c51d9b1e8f2f9ae9ad0874b023cd
[ "BSD-3-Clause" ]
null
null
null
logdevice/admin/maintenance/test/APIUtilsTest.cpp
dmitris/LogDevice
18336bb95262c51d9b1e8f2f9ae9ad0874b023cd
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/admin/maintenance/APIUtils.h" #include <folly/container/F14Set.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "logdevice/admin/AdminAPIUtils.h" #include "logdevice/admin/maintenance/test/MaintenanceTestUtil.h" using namespace ::testing; using namespace facebook::logdevice; using namespace facebook::logdevice::maintenance; TEST(APIUtilsTest, Validate) { // empty definition is invalid. { MaintenanceDefinition def1; auto failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("At least one of shards or sequencer_nodes must be set", failed->get_message()); } MaintenanceDefinition def1; thrift::ShardSet shards; thrift::NodeID node1 = mkNodeID(1); shards.push_back(mkShardID(1, -1)); def1.set_shards(shards); def1.set_shard_target_state(ShardOperationalState::DRAINED); // user must be set auto failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("user must be set for the definition to non-empty string", failed->get_message()); def1.set_user(INTERNAL_USER); failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("This is a reserved user, cannot be used through the API", failed->get_message()); def1.set_user("bunny"); failed = APIUtils::validateDefinition(def1); ASSERT_EQ(folly::none, failed); def1.set_user("bun ny"); failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("user cannot contain whitespaces", failed->get_message()); def1.set_user("bunny"); def1.set_sequencer_nodes({node1}); failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("sequencer_target_state must be DISABLED if sequencer_nodes is set", failed->get_message()); def1.set_sequencer_target_state(SequencingState::BOYCOTTED); failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("sequencer_target_state must be DISABLED if sequencer_nodes is set", failed->get_message()); def1.set_sequencer_target_state(SequencingState::DISABLED); ASSERT_EQ(folly::none, APIUtils::validateDefinition(def1)); shards.push_back(mkShardID(2, -10)); def1.set_shards(shards); failed = APIUtils::validateDefinition(def1); ASSERT_TRUE(failed.hasValue()); ASSERT_EQ("Cannot accept shard_index smaller than -1", failed->get_message()); shards.pop_back(); def1.set_shards(shards); ASSERT_EQ(folly::none, APIUtils::validateDefinition(def1)); { MaintenanceDefinition def2 = def1; def2.set_ttl_seconds(-1); auto failed2 = APIUtils::validateDefinition(def2); ASSERT_EQ( "ttl_seconds must be a non-negative number", failed2->get_message()); } { MaintenanceDefinition def2 = def1; def2.set_group_id("hola"); auto failed2 = APIUtils::validateDefinition(def2); ASSERT_EQ("group_id cannot be set by the user", failed2->get_message()); } { MaintenanceDefinition def2 = def1; def2.set_last_check_impact_result(thrift::CheckImpactResponse()); auto failed2 = APIUtils::validateDefinition(def2); ASSERT_EQ("last_check_impact_result cannot be set by the user", failed2->get_message()); } { MaintenanceDefinition def2 = def1; def2.set_expires_on(200); auto failed2 = APIUtils::validateDefinition(def2); ASSERT_EQ("expires_on cannot be set by the user", failed2->get_message()); } { MaintenanceDefinition def2 = def1; def2.set_created_on(100); auto failed2 = APIUtils::validateDefinition(def2); ASSERT_EQ("created_on cannot be set by the user", failed2->get_message()); } } TEST(APIUtilsTest, RandomGroupID) { folly::F14FastSet<std::string> generated; std::string id = APIUtils::generateGroupID(8); ASSERT_EQ(8, id.size()); generated.insert(std::move(id)); for (int i = 0; i < 100000; ++i) { // We should be happy without collisions in 100k id space. id = APIUtils::generateGroupID(8); ASSERT_TRUE(generated.count(id) == 0); generated.insert(std::move(id)); } ASSERT_EQ(100001, generated.size()); } TEST(APIUtilsTest, ExpandMaintenances1) { /** * generate a single maintenance because all shards are in the same node, * whether we pass group with true or false. */ std::shared_ptr<const NodesConfiguration> nodes_config = genNodesConfiguration(); MaintenanceDefinition request; request.set_user("bunny"); request.set_shard_target_state(ShardOperationalState::DRAINED); // expands to all shards of node 1 request.set_shards({mkShardID(1, -1)}); request.set_sequencer_nodes({mkNodeID(1)}); request.set_sequencer_target_state(SequencingState::DISABLED); // to validate we correctly respect the attributes request.set_skip_safety_checks(true); request.set_group(false); { auto output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(1, output.value().size()); const MaintenanceDefinition& result = (*output)[0]; ASSERT_EQ("bunny", result.get_user()); ASSERT_TRUE(result.group_id_ref().has_value()); ASSERT_EQ(8, result.group_id_ref().value().size()); ASSERT_THAT(result.get_shards(), UnorderedElementsAre(mkShardID(1, 0))); ASSERT_EQ(ShardOperationalState::DRAINED, result.get_shard_target_state()); ASSERT_EQ(SequencingState::DISABLED, result.get_sequencer_target_state()); ASSERT_THAT( result.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(1))); ASSERT_TRUE(result.get_skip_safety_checks()); ASSERT_TRUE(result.created_on_ref().has_value()); ASSERT_TRUE(result.created_on_ref().value() > 0); } { // Let's try while group = true; Our expecations should be identical since // all maintenances in this request are on the same node. request.set_group(true); auto output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(1, output.value().size()); const MaintenanceDefinition& result = (*output)[0]; ASSERT_EQ("bunny", result.get_user()); ASSERT_TRUE(result.group_id_ref().has_value()); ASSERT_EQ(8, result.group_id_ref().value().size()); ASSERT_THAT(result.get_shards(), UnorderedElementsAre(mkShardID(1, 0))); ASSERT_EQ(ShardOperationalState::DRAINED, result.get_shard_target_state()); ASSERT_EQ(SequencingState::DISABLED, result.get_sequencer_target_state()); ASSERT_THAT( result.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(1))); ASSERT_TRUE(result.get_skip_safety_checks()); ASSERT_TRUE(result.created_on_ref().has_value()); ASSERT_TRUE(result.created_on_ref().value() > 0); } { // Let's add another sequenecer node and we should get two maintenances in // return if group=false, and 1 of group=true // request.set_sequencer_nodes({mkNodeID(1), mkNodeID(7)}); request.set_group(true); auto output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(1, output.value().size()); const MaintenanceDefinition& result = (*output)[0]; ASSERT_THAT(result.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(1), mkNodeID(7))); request.set_group(false); output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(2, output.value().size()); for (const auto& def : *output) { ASSERT_EQ(SequencingState::DISABLED, def.get_sequencer_target_state()); if (def.get_shards().empty()) { // This has to be the sequencer only maintenance ASSERT_THAT( def.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(7))); } else { ASSERT_THAT( def.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(1))); } } } { // Let's add another shard in a different node and we should get three // maintenances in return if group=false // request.set_shards({mkShardID(1, -1), mkShardID(13, -1)}); request.set_sequencer_nodes({mkNodeID(1), mkNodeID(7)}); request.set_group(false); auto output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(3, output.value().size()); std::unordered_set<std::string> found_ids; for (const auto& def : *output) { ASSERT_EQ(SequencingState::DISABLED, def.get_sequencer_target_state()); if (def.get_shards().empty()) { // This has to be the sequencer only maintenance ASSERT_THAT( def.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(7))); ASSERT_EQ(0, def.get_shards().size()); } else if (def.get_shards()[0].get_node().node_index_ref().value() == 1) { ASSERT_THAT( def.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(1))); ASSERT_THAT(def.get_shards(), UnorderedElementsAre(mkShardID(1, 0))); } else { ASSERT_EQ(0, def.get_sequencer_nodes().size()); ASSERT_THAT(def.get_shards(), UnorderedElementsAre(mkShardID(13, 0))); } // For each of these maintenances, we should have a set of attributs set. // the maintnances must have unique ids ASSERT_EQ(0, found_ids.count(*def.group_id_ref())); ASSERT_TRUE(def.group_id_ref().value().size() > 0); ASSERT_EQ(0, found_ids.count(def.group_id_ref().value())); found_ids.insert(def.group_id_ref().value()); ASSERT_TRUE(def.get_skip_safety_checks()); ASSERT_TRUE(def.created_on_ref().has_value()); ASSERT_TRUE(def.created_on_ref().value() > 0); } } } TEST(APIUtilsTest, ExpandMaintenances2) { // We can't reference shards in non-storage nodes, or sequencer nodes that do // not have this role in maintenances. std::shared_ptr<const NodesConfiguration> nodes_config = genNodesConfiguration(); MaintenanceDefinition request; request.set_user("bunny"); request.set_shard_target_state(ShardOperationalState::DRAINED); // expands to all shards of node 1 request.set_shards({mkShardID(1, -1)}); // node 9 is storage node only. request.set_sequencer_nodes({mkNodeID(9)}); request.set_sequencer_target_state(SequencingState::DISABLED); // to validate we correctly respect the attributes request.set_skip_safety_checks(true); request.set_group(false); { // make sure we ignore a node with a wrong role (1) auto output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(output.value().size(), 1); ASSERT_TRUE(output.value().front().sequencer_nodes.empty()); } { // make sure we ignore a node with a wrong role (2) request.set_sequencer_nodes({mkNodeID(1)}); request.set_shards({mkShardID(7, -1)}); auto output = APIUtils::expandMaintenances(request, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(output.value().size(), 1); ASSERT_TRUE(output.value().front().shards.empty()); } } TEST(APIUtilsTest, MaintenanceEquivalence) { std::shared_ptr<const NodesConfiguration> nodes_config = genNodesConfiguration(); MaintenanceDefinition def1; def1.set_user("bunny"); def1.set_shard_target_state(ShardOperationalState::DRAINED); // expands to all shards of node 1 def1.set_shards({mkShardID(1, -1), mkShardID(13, -1)}); def1.set_sequencer_nodes({mkNodeID(1)}); def1.set_sequencer_target_state(SequencingState::DISABLED); // to validate we correctly respect the attributes def1.set_skip_safety_checks(true); def1.set_group(true); auto output = APIUtils::expandMaintenances(def1, nodes_config); ASSERT_TRUE(output.hasValue()); ASSERT_EQ(1, output.value().size()); MaintenanceDefinition def2; def2.set_user("bunny"); def2.set_shard_target_state(ShardOperationalState::MAY_DISAPPEAR); // expands to all shards of node 1. Verify order in vector does not // matter def2.set_shards({mkShardID(13, -1), mkShardID(1, -1)}); def2.set_sequencer_nodes({mkNodeID(1)}); def2.set_sequencer_target_state(SequencingState::DISABLED); // to validate we correctly respect the attributes def2.set_skip_safety_checks(true); def2.set_group(true); auto def2_output = APIUtils::expandMaintenances(def2, nodes_config); ASSERT_TRUE(def2_output.hasValue()); ASSERT_EQ(1, def2_output.value().size()); ASSERT_FALSE( APIUtils::areMaintenancesEquivalent((*output)[0], (*def2_output)[0])); def2.set_shard_target_state(ShardOperationalState::DRAINED); def2_output = APIUtils::expandMaintenances(def2, nodes_config); ASSERT_TRUE( APIUtils::areMaintenancesEquivalent((*output)[0], (*def2_output)[0])); ASSERT_EQ((*def2_output)[0], APIUtils::findEquivalentMaintenance(*def2_output, (*output)[0])); def2.set_user("what"); def2_output = APIUtils::expandMaintenances(def2, nodes_config); ASSERT_FALSE( APIUtils::areMaintenancesEquivalent((*output)[0], (*def2_output)[0])); def2.set_user("bunny"); def2.set_sequencer_nodes({mkNodeID(7)}); def2_output = APIUtils::expandMaintenances(def2, nodes_config); ASSERT_FALSE( APIUtils::areMaintenancesEquivalent((*output)[0], (*def2_output)[0])); ASSERT_EQ(folly::none, APIUtils::findEquivalentMaintenance(*def2_output, (*output)[0])); MaintenanceDefinition def3; def3.set_user("bunny"); def3.set_shard_target_state(ShardOperationalState::DRAINED); // expands to all shards of node 1 def3.set_shards({mkShardID(1, -1), mkShardID(13, -1)}); def3.set_sequencer_nodes({mkNodeID(1), mkNodeID(7)}); def3.set_sequencer_target_state(SequencingState::DISABLED); // to validate we correctly respect the attributes def3.set_skip_safety_checks(true); def3.set_group(true); auto def3_output = APIUtils::expandMaintenances(def3, nodes_config); ASSERT_TRUE(def3_output.hasValue()); ASSERT_EQ(1, def3_output.value().size()); // def1 and def3 are not equivalent because def3 has an extra // sequencer maintenance ASSERT_FALSE( APIUtils::areMaintenancesEquivalent((*output)[0], (*def3_output)[0])); } TEST(APIUtilsTest, MaintenanceFilter) { std::vector<MaintenanceDefinition> defs; MaintenanceDefinition def1; def1.set_user("bunny"); def1.set_group_id("group1"); defs.push_back(def1); MaintenanceDefinition def2; def2.set_user("bunny"); def2.set_group_id("group2"); defs.push_back(def2); MaintenanceDefinition def3; def3.set_user("funny"); def3.set_group_id("group3"); defs.push_back(def3); thrift::MaintenancesFilter filter1; ASSERT_EQ(defs, APIUtils::filterMaintenances(filter1, defs)); filter1.set_user("bunny"); auto res1 = APIUtils::filterMaintenances(filter1, defs); ASSERT_EQ(2, res1.size()); ASSERT_THAT(res1, UnorderedElementsAre(def1, def2)); filter1.set_group_ids({"group1"}); res1 = APIUtils::filterMaintenances(filter1, defs); ASSERT_EQ(1, res1.size()); ASSERT_THAT(res1, UnorderedElementsAre(def1)); } TEST(APIUtilsTest, TestIsEmptyMaintenance) { MaintenanceDefinition def; def.set_user("bunny"); def.set_shard_target_state(ShardOperationalState::DRAINED); def.set_shards({mkShardID(1, -1), mkShardID(13, -1)}); def.set_sequencer_nodes({mkNodeID(1)}); def.set_sequencer_target_state(SequencingState::DISABLED); EXPECT_FALSE(APIUtils::isEmptyMaintenance(def)); def.set_shards({}); def.set_sequencer_nodes({mkNodeID(1)}); EXPECT_FALSE(APIUtils::isEmptyMaintenance(def)); def.set_shards({mkShardID(1, -1), mkShardID(13, -1)}); def.set_sequencer_nodes({}); EXPECT_FALSE(APIUtils::isEmptyMaintenance(def)); def.set_shards({}); def.set_sequencer_nodes({}); EXPECT_TRUE(APIUtils::isEmptyMaintenance(def)); } TEST(APIUtilsTest, TestRemoveNonExistentNodesFromMaintenance) { MaintenanceDefinition def; def.set_user("bunny"); def.set_shard_target_state(ShardOperationalState::DRAINED); def.set_shards( {mkShardID(1, -1), mkShardID(130, 0), mkShardID(0, 1), mkShardID(7, 1)}); def.set_sequencer_nodes( {mkNodeID(1), mkNodeID(100), mkNodeID(0), mkNodeID(101)}); def.set_sequencer_target_state(SequencingState::DISABLED); APIUtils::removeNonExistentNodesFromMaintenance( def, *genNodesConfiguration()); for (auto seq : def.get_sequencer_nodes()) { LOG(INFO) << *seq.get_node_index(); } EXPECT_THAT(def.get_shards(), UnorderedElementsAre(mkShardID(1, -1), mkShardID(7, 1))); EXPECT_THAT(def.get_sequencer_nodes(), UnorderedElementsAre(mkNodeID(1))); // Trying to remove the nodes again, wouldn't change anything auto def_copy = def; APIUtils::removeNonExistentNodesFromMaintenance( def_copy, *genNodesConfiguration()); EXPECT_EQ(def, def_copy); }
38.597727
80
0.718954
[ "vector" ]
cd182180ef4494c7464ea3bfe45bc8bbf3370269
4,220
cpp
C++
Funambol/source/common/syncml/core/ComplexData.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
[ "MIT" ]
null
null
null
Funambol/source/common/syncml/core/ComplexData.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
[ "MIT" ]
null
null
null
Funambol/source/common/syncml/core/ComplexData.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
[ "MIT" ]
null
null
null
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include <Funambol/syncml/core/ComplexData.h> #include <Funambol/base/globalsdef.h> USE_NAMESPACE ComplexData::ComplexData() { initialize(); } ComplexData::~ComplexData() { if (anchor) { delete anchor; anchor = NULL; } if (devInf) { delete devInf; devInf = NULL; } if (properties) { delete properties; properties = NULL; } } void ComplexData::initialize() { anchor = NULL; devInf = NULL; properties = NULL; } /** * Creates a Data object from the given anchors string. * * @param data the data * */ ComplexData::ComplexData(const char* data) : Data(data) { initialize(); } // ---------------------------------------------------------- Public methods /** * Gets the Anchor object property * * @return anchor the Anchor object */ Anchor* ComplexData::getAnchor() { return anchor; } /** * Sets the Anchor object property * * @param anchor the Anchor object */ void ComplexData::setAnchor(Anchor* anchor) { if (anchor == NULL) { // TBD } else { if (this->anchor) { delete this->anchor; this->anchor = NULL; } this->anchor = anchor->clone(); } } /** * Gets the DevInf object property * * @return devInf the DevInf object property */ DevInf* ComplexData::getDevInf() { return devInf; } /** * Sets the DevInf object property * * @param devInf the DevInf object property * */ void ComplexData::setDevInf(DevInf* devInf) { if (devInf == NULL) { // TBD } else { if (this->devInf) { delete this->devInf; this->devInf = NULL; } this->devInf = devInf->clone(); } } /* * Gets properties * * @return the current properties's value * */ ArrayList* ComplexData::getProperties() { return properties; } /* * Sets properties * * @param properties the new value * */ void ComplexData::setProperties(ArrayList* properties) { if (this->properties) { delete this->properties; this->properties = NULL; } if (properties) { this->properties = properties->clone(); } } ComplexData* ComplexData::clone() { ComplexData* ret = new ComplexData(data); if (getAnchor()) { ret->setAnchor(getAnchor()); } if (getDevInf()) { ret->setDevInf(getDevInf()); } if (properties) { ret->setProperties(properties); } return ret; }
24.678363
80
0.658531
[ "object" ]
cd19ae0a5abdad553e75f59e415a050569794426
1,550
cc
C++
chrome/browser/ui/autofill/payments/offer_notification_helper.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/ui/autofill/payments/offer_notification_helper.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/ui/autofill/payments/offer_notification_helper.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2021 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 "chrome/browser/ui/autofill/payments/offer_notification_helper.h" #include "content/public/browser/navigation_handle.h" namespace autofill { OfferNotificationHelper::OfferNotificationHelper(content::WebContents* contents) : content::WebContentsObserver(contents) {} OfferNotificationHelper::~OfferNotificationHelper() = default; bool OfferNotificationHelper::OfferNotificationHasAlreadyBeenShown() { return !origins_to_display_notification_.empty(); } void OfferNotificationHelper::OnDisplayOfferNotification( const std::vector<GURL>& origins) { origins_to_display_notification_ = origins; } void OfferNotificationHelper::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame() || !navigation_handle->HasCommitted()) { return; } // Don't react to same-document (fragment) navigations. if (navigation_handle->IsSameDocument()) return; // Don't do anything if user is still on an eligible origin for this offer. if (base::ranges::count(origins_to_display_notification_, navigation_handle->GetURL().GetOrigin())) { return; } // TODO(crbug.com/1093057): Introduce a callback and hide the offer // notification. origins_to_display_notification_.clear(); } WEB_CONTENTS_USER_DATA_KEY_IMPL(OfferNotificationHelper) } // namespace autofill
32.978723
80
0.763226
[ "vector" ]
cd1a7ec6c5f61201b3c138f99bcce06e0fbb0197
2,475
cpp
C++
src/link.cpp
mvukov/gazebo_server
e1a30fee043e14a31ca5a70d441f375d155f9a65
[ "Apache-2.0" ]
null
null
null
src/link.cpp
mvukov/gazebo_server
e1a30fee043e14a31ca5a70d441f375d155f9a65
[ "Apache-2.0" ]
null
null
null
src/link.cpp
mvukov/gazebo_server
e1a30fee043e14a31ca5a70d441f375d155f9a65
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Milan Vukov. 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 "gazebo_server/link.h" #include <Eigen/Geometry> #include <gazebo/physics/Link.hh> namespace gazebo_server { using Eigen::Matrix3d; using Eigen::Quaterniond; using Eigen::Vector3d; void Link::GetWorldPose(Vector3d* world_p_link, Matrix3d* world_r_link) const { assert(world_p_link != nullptr); assert(world_r_link != nullptr); const auto world_t_link = link_->WorldPose(); *world_p_link = {world_t_link.Pos().X(), world_t_link.Pos().Y(), world_t_link.Pos().Z()}; *world_r_link = Quaterniond(world_t_link.Rot().W(), world_t_link.Rot().X(), world_t_link.Rot().Y(), world_t_link.Rot().Z()) .toRotationMatrix(); } Vector3d Link::GetWorldLinearVel() const { const auto ret = link_->WorldLinearVel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetWorldAngularVel() const { const auto ret = link_->WorldAngularVel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetWorldLinearAccel() const { const auto ret = link_->WorldLinearAccel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetWorldAngularAccel() const { const auto ret = link_->WorldAngularAccel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetRelativeLinearVel() const { const auto ret = link_->RelativeLinearVel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetRelativeLinearAccel() const { const auto ret = link_->RelativeLinearAccel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetRelativeAngularVel() const { const auto ret = link_->RelativeAngularVel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } Vector3d Link::GetRelativeAngularAccel() const { const auto ret = link_->RelativeAngularAccel(); return Vector3d(ret.X(), ret.Y(), ret.Z()); } } // namespace gazebo_server
34.859155
79
0.693737
[ "geometry" ]
cd201354e8d8751bd9f5ee3dc4d2bc60b8f39f4c
259
hpp
C++
src/Cpp/1-getting-started/1-1-1-HelloWindow/HelloWindowApplication.hpp
spnda/learnd3d11
83fea43afffca48776521d8f1ae60e9d0bc6dc84
[ "MIT" ]
29
2022-02-19T00:54:51.000Z
2022-03-24T11:05:47.000Z
src/Cpp/1-getting-started/1-1-1-HelloWindow/HelloWindowApplication.hpp
spnda/learnd3d11
83fea43afffca48776521d8f1ae60e9d0bc6dc84
[ "MIT" ]
67
2022-02-19T16:47:40.000Z
2022-03-30T15:09:38.000Z
src/Cpp/1-getting-started/1-1-1-HelloWindow/HelloWindowApplication.hpp
spnda/learnd3d11
83fea43afffca48776521d8f1ae60e9d0bc6dc84
[ "MIT" ]
8
2022-02-15T11:06:31.000Z
2022-03-16T22:34:22.000Z
#pragma once #include "Application.hpp" class HelloWindowApplication final : public Application { public: HelloWindowApplication(const std::string& title); protected: bool Load() override; void Update() override; void Render() override; };
17.266667
55
0.725869
[ "render" ]
cd21a3d41157b5ea534d030e125a3847d5296d14
832
cpp
C++
tests/main.cpp
sliedes/mayo
26e5366d5658b70613789a5f1c2d7cc7263c52a4
[ "BSD-2-Clause" ]
null
null
null
tests/main.cpp
sliedes/mayo
26e5366d5658b70613789a5f1c2d7cc7263c52a4
[ "BSD-2-Clause" ]
null
null
null
tests/main.cpp
sliedes/mayo
26e5366d5658b70613789a5f1c2d7cc7263c52a4
[ "BSD-2-Clause" ]
null
null
null
/**************************************************************************** ** Copyright (c) 2021, Fougue Ltd. <http://www.fougue.pro> ** All rights reserved. ** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt ****************************************************************************/ #include "test_base.h" #include "test_app.h" #include <QtGui/QGuiApplication> #include <memory> #include <vector> int main(int argc, char** argv) { // Required by TestApp QGuiApplication guiApp(argc, argv); int retcode = 0; std::vector<std::unique_ptr<QObject>> vecTest; vecTest.emplace_back(new Mayo::TestBase); vecTest.emplace_back(new Mayo::TestApp); for (const std::unique_ptr<QObject>& test : vecTest) retcode += QTest::qExec(test.get(), argc, argv); return retcode; }
28.689655
77
0.557692
[ "vector" ]
cd2403c009fef315766a689da86adad2279c6e90
12,430
cpp
C++
branches/g3d-8.0-64ffmpeg-win/G3D.lib/source/CoordinateFrame.cpp
brown-ccv/VRG3D
0854348453ac150b27a8ae89024ef57360f15d45
[ "BSD-3-Clause" ]
null
null
null
branches/g3d-8.0-64ffmpeg-win/G3D.lib/source/CoordinateFrame.cpp
brown-ccv/VRG3D
0854348453ac150b27a8ae89024ef57360f15d45
[ "BSD-3-Clause" ]
null
null
null
branches/g3d-8.0-64ffmpeg-win/G3D.lib/source/CoordinateFrame.cpp
brown-ccv/VRG3D
0854348453ac150b27a8ae89024ef57360f15d45
[ "BSD-3-Clause" ]
null
null
null
/** @file CoordinateFrame.cpp Coordinate frame class @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2001-06-02 @edited 2010-03-13 Copyright 2000-2010, Morgan McGuire. All rights reserved. */ #include "G3D/platform.h" #include "G3D/CoordinateFrame.h" #include "G3D/Quat.h" #include "G3D/Matrix4.h" #include "G3D/Box.h" #include "G3D/AABox.h" #include "G3D/Sphere.h" #include "G3D/Triangle.h" #include "G3D/Ray.h" #include "G3D/Capsule.h" #include "G3D/Cylinder.h" #include "G3D/UprightFrame.h" #include "G3D/Any.h" #include "G3D/stringutils.h" #include "G3D/PhysicsFrame.h" #include "G3D/UprightFrame.h" namespace G3D { std::string CoordinateFrame::toXYZYPRDegreesString() const { UprightFrame uframe(*this); return format("CFrame::fromXYZYPRDegrees(% 5.1ff, % 5.1ff, % 5.1ff, % 5.1ff, % 5.1ff, % 5.1ff)", uframe.translation.x, uframe.translation.y, uframe.translation.z, toDegrees(uframe.yaw), toDegrees(uframe.pitch), 0.0f); } CoordinateFrame::CoordinateFrame(const Any& any) { *this = CFrame(); const std::string& n = toUpper(any.name()); if (beginsWith(n, "VECTOR3")) { translation = any; } else if (beginsWith(n, "MATRIX3")) { rotation = any; } else if ((n == "CFRAME") || (n == "COORDINATEFRAME")) { any.verifyType(Any::TABLE, Any::ARRAY); if (any.type() == Any::ARRAY) { any.verifySize(2); rotation = any[0]; translation = any[1]; } else { for (Any::AnyTable::Iterator it = any.table().begin(); it.hasMore(); ++it) { const std::string& n = toLower(it->key); if (n == "translation") { translation = Vector3(it->value); } else if (n == "rotation") { rotation = Matrix3(it->value); } else { any.verify(false, "Illegal table key: " + it->key); } } } } else if (beginsWith(n, "PHYSICSFRAME") || beginsWith(n, "PFRAME")) { *this = PhysicsFrame(any); } else { any.verifyName("CFrame::fromXYZYPRDegrees", "CoordinateFrame::fromXYZYPRDegrees"); any.verifyType(Any::ARRAY); any.verifySize(3, 6); int s = any.size(); *this = fromXYZYPRDegrees(any[0], any[1], any[2], (s > 3) ? any[3].number() : 0.0f, (s > 4) ? any[4].number() : 0.0f, (s > 5) ? any[5].number() : 0.0f); } } CoordinateFrame::operator Any() const { Any a(Any::ARRAY, "CFrame"); a.append(rotation); a.append(translation); return a; /* Dane Mod below code doesn't work, repeats yaw twice and the fromXYZYPRDegrees method isn't even fully implemented float x, y, z, yaw, pitch, roll; getXYZYPRDegrees(x, y, z, yaw, pitch, roll); Any a(Any::ARRAY, "CFrame::fromXYZYPRDegrees"); a.append(x, y, z, yaw); if ( ! G3D::fuzzyEq(yaw, 0.0f) || ! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { a.append(yaw); if (! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { a.append(pitch); if (! G3D::fuzzyEq(roll, 0.0f)) { a.append(roll); } } } return a; */ } CoordinateFrame::CoordinateFrame(const class UprightFrame& f) { *this = f.toCoordinateFrame(); } CoordinateFrame::CoordinateFrame() : rotation(Matrix3::identity()), translation(Vector3::zero()) { } CoordinateFrame CoordinateFrame::fromXYZYPRRadians(float x, float y, float z, float yaw, float pitch, float roll) { Matrix3 rotation = Matrix3::fromAxisAngle(Vector3::unitY(), yaw); rotation = Matrix3::fromAxisAngle(rotation.column(0), pitch) * rotation; rotation = Matrix3::fromAxisAngle(rotation.column(2), roll) * rotation; const Vector3 translation(x, y, z); return CoordinateFrame(rotation, translation); } void CoordinateFrame::getXYZYPRRadians(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const { x = translation.x; y = translation.y; z = translation.z; const Vector3& look = lookVector(); if (abs(look.y) > 0.99f) { // Looking nearly straight up or down yaw = G3D::pi() + atan2(look.x, look.z); pitch = asin(look.y); roll = 0.0f; } else { // Yaw cannot be affected by others, so pull it first yaw = G3D::pi() + atan2(look.x, look.z); // Pitch is the elevation of the yaw vector pitch = asin(look.y); Vector3 actualRight = rightVector(); Vector3 expectedRight = look.cross(Vector3::unitY()); roll = 0;//acos(actualRight.dot(expectedRight)); TODO } } void CoordinateFrame::getXYZYPRDegrees(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const { getXYZYPRRadians(x, y, z, yaw, pitch, roll); yaw = toDegrees(yaw); pitch = toDegrees(pitch); roll = toDegrees(roll); } CoordinateFrame CoordinateFrame::fromXYZYPRDegrees(float x, float y, float z, float yaw, float pitch, float roll) { return fromXYZYPRRadians(x, y, z, toRadians(yaw), toRadians(pitch), toRadians(roll)); } Ray CoordinateFrame::lookRay() const { return Ray::fromOriginAndDirection(translation, lookVector()); } bool CoordinateFrame::fuzzyEq(const CoordinateFrame& other) const { for (int c = 0; c < 3; ++c) { for (int r = 0; r < 3; ++r) { if (! G3D::fuzzyEq(other.rotation[r][c], rotation[r][c])) { return false; } } if (! G3D::fuzzyEq(translation[c], other.translation[c])) { return false; } } return true; } bool CoordinateFrame::fuzzyIsIdentity() const { const Matrix3& I = Matrix3::identity(); for (int c = 0; c < 3; ++c) { for (int r = 0; r < 3; ++r) { if (fuzzyNe(I[r][c], rotation[r][c])) { return false; } } if (fuzzyNe(translation[c], 0)) { return false; } } return true; } bool CoordinateFrame::isIdentity() const { return (translation == Vector3::zero()) && (rotation == Matrix3::identity()); } Matrix4 CoordinateFrame::toMatrix4() const { return Matrix4(*this); } std::string CoordinateFrame::toXML() const { return G3D::format( "<COORDINATEFRAME>\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf\n</COORDINATEFRAME>\n", rotation[0][0], rotation[0][1], rotation[0][2], translation.x, rotation[1][0], rotation[1][1], rotation[1][2], translation.y, rotation[2][0], rotation[2][1], rotation[2][2], translation.z, 0.0, 0.0, 0.0, 1.0); } Plane CoordinateFrame::toObjectSpace(const Plane& p) const { Vector3 N, P; double d; p.getEquation(N, d); P = N * (float)d; P = pointToObjectSpace(P); N = normalToObjectSpace(N); return Plane(N, P); } Plane CoordinateFrame::toWorldSpace(const Plane& p) const { Vector3 N, P; double d; p.getEquation(N, d); P = N * (float)d; P = pointToWorldSpace(P); N = normalToWorldSpace(N); return Plane(N, P); } Triangle CoordinateFrame::toObjectSpace(const Triangle& t) const { return Triangle(pointToObjectSpace(t.vertex(0)), pointToObjectSpace(t.vertex(1)), pointToObjectSpace(t.vertex(2))); } Triangle CoordinateFrame::toWorldSpace(const Triangle& t) const { return Triangle(pointToWorldSpace(t.vertex(0)), pointToWorldSpace(t.vertex(1)), pointToWorldSpace(t.vertex(2))); } Cylinder CoordinateFrame::toWorldSpace(const Cylinder& c) const { return Cylinder( pointToWorldSpace(c.point(0)), pointToWorldSpace(c.point(1)), c.radius()); } Capsule CoordinateFrame::toWorldSpace(const Capsule& c) const { return Capsule( pointToWorldSpace(c.point(0)), pointToWorldSpace(c.point(1)), c.radius()); } Box CoordinateFrame::toWorldSpace(const AABox& b) const { Box b2(b); return toWorldSpace(b2); } Box CoordinateFrame::toWorldSpace(const Box& b) const { Box out(b); for (int i = 0; i < 8; ++i) { out._corner[i] = pointToWorldSpace(b._corner[i]); debugAssert(! isNaN(out._corner[i].x)); } for (int i = 0; i < 3; ++i) { out._axis[i] = vectorToWorldSpace(b._axis[i]); } out._center = pointToWorldSpace(b._center); return out; } Box CoordinateFrame::toObjectSpace(const Box &b) const { return inverse().toWorldSpace(b); } Box CoordinateFrame::toObjectSpace(const AABox& b) const { return toObjectSpace(Box(b)); } CoordinateFrame::CoordinateFrame(class BinaryInput& b) : rotation(Matrix3::zero()) { deserialize(b); } void CoordinateFrame::deserialize(class BinaryInput& b) { rotation.deserialize(b); translation.deserialize(b); } void CoordinateFrame::serialize(class BinaryOutput& b) const { rotation.serialize(b); translation.serialize(b); } Sphere CoordinateFrame::toWorldSpace(const Sphere &b) const { return Sphere(pointToWorldSpace(b.center), b.radius); } Sphere CoordinateFrame::toObjectSpace(const Sphere &b) const { return Sphere(pointToObjectSpace(b.center), b.radius); } Ray CoordinateFrame::toWorldSpace(const Ray& r) const { return Ray::fromOriginAndDirection(pointToWorldSpace(r.origin()), vectorToWorldSpace(r.direction())); } Ray CoordinateFrame::toObjectSpace(const Ray& r) const { return Ray::fromOriginAndDirection(pointToObjectSpace(r.origin()), vectorToObjectSpace(r.direction())); } void CoordinateFrame::lookAt(const Vector3 &target) { lookAt(target, Vector3::unitY()); } void CoordinateFrame::lookAt( const Vector3& target, Vector3 up) { up = up.direction(); Vector3 look = (target - translation).direction(); if (fabs(look.dot(up)) > .99f) { up = Vector3::unitX(); if (fabs(look.dot(up)) > .99f) { up = Vector3::unitY(); } } up -= look * look.dot(up); up.unitize(); Vector3 z = -look; Vector3 x = -z.cross(up); x.unitize(); Vector3 y = z.cross(x); rotation.setColumn(0, x); rotation.setColumn(1, y); rotation.setColumn(2, z); } CoordinateFrame CoordinateFrame::lerp( const CoordinateFrame& other, float alpha) const { if (alpha == 1.0f) { return other; } else if (alpha == 0.0f) { return *this; } else { const Quat q1(this->rotation); const Quat q2(other.rotation); return CoordinateFrame( q1.slerp(q2, alpha).toRotationMatrix(), translation * (1 - alpha) + other.translation * alpha); } } void CoordinateFrame::pointToWorldSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = 0; i < v.size(); ++i) { vout[i] = pointToWorldSpace(v[i]); } } void CoordinateFrame::normalToWorldSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = 0; i < v.size(); ++i) { vout[i] = normalToWorldSpace(v[i]); } } void CoordinateFrame::vectorToWorldSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = vectorToWorldSpace(v[i]); } } void CoordinateFrame::pointToObjectSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = pointToObjectSpace(v[i]); } } void CoordinateFrame::normalToObjectSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = normalToObjectSpace(v[i]); } } void CoordinateFrame::vectorToObjectSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = vectorToObjectSpace(v[i]); } } } // namespace
26.334746
129
0.58745
[ "vector" ]
cd26838753b564a2a89f0e17afba550b2701bc9e
5,668
cpp
C++
src/core/film_repository.cpp
amirhossein-1378/AP_CA7
dee6bda34741f6a8a311904c32c33cf5cc48449d
[ "MIT" ]
null
null
null
src/core/film_repository.cpp
amirhossein-1378/AP_CA7
dee6bda34741f6a8a311904c32c33cf5cc48449d
[ "MIT" ]
null
null
null
src/core/film_repository.cpp
amirhossein-1378/AP_CA7
dee6bda34741f6a8a311904c32c33cf5cc48449d
[ "MIT" ]
null
null
null
#include "film_repository.h" #include "customer.h" #include <algorithm> using namespace std; FilmRepository::~FilmRepository() { for (int i = 0; i < films.size(); i++) delete films[i]; } void FilmRepository::add(Film* new_film) { films.push_back(new_film); films_adjacency_matrix.resize(get_films_count()); for (int i = 0; i < films_adjacency_matrix.size(); i++) films_adjacency_matrix[i].resize(get_films_count()); id_location[new_film->get_id()] = films_adjacency_matrix.size() - 1; } Film* FilmRepository::find(int film_id) { for (int i = 0; i < films.size(); i++) { if (films[i]->get_id() == film_id) return films[i]; } return NULL; } vector<Film*> FilmRepository::find(map<string, string> filters) { vector<Film*> result; for (map<string, string>::iterator it = filters.begin(); it != filters.end(); it++) { if (it->first == "name") { for (int i = 0; i < films.size(); i++) if (films[i]->is_published() && films[i]->get_name() == it->second) result.push_back(films[i]); } else if (it->first == "min_rate") { for (int i = 0; i < films.size(); i++) if (films[i]->is_published() && films[i]->get_score() >= stoi(it->second)) result.push_back(films[i]); } else if (it->first == "min_year") { for (int i = 0; i < films.size(); i++) if (films[i]->is_published() && films[i]->get_year() >= stoi(it->second)) result.push_back(films[i]); } else if (it->first == "max_year") { for (int i = 0; i < films.size(); i++) if (films[i]->is_published() && films[i]->get_year() <= stoi(it->second)) { vector<Film*>::iterator it = std::find(result.begin(), result.end(), films[i]); if (it == result.end()) result.push_back(films[i]); } for (int i = 0; i < result.size(); i++) if (result[i]->get_year() > stoi(it->second)) result.erase(result.begin() + i); } else if (it->first == "price") { for (int i = 0; i < films.size(); i++) if (films[i]->is_published() && films[i]->get_price() <= stoi(it->second)) result.push_back(films[i]); } else if (it->first == "director") { for (int i = 0; i < films.size(); i++) if (films[i]->is_published() && films[i]->get_director() == it->second) result.push_back(films[i]); } else throw Bad_Request_Ex(); } if (filters.size() == 0) { for (int i = 0; i < films.size(); i++) if (films[i]->is_published()) result.push_back(films[i]); } return result; } void FilmRepository::remove(int film_id) { Film* film = find(film_id); film->unpublish(); int location = id_location[film_id]; for (int i = 0; i < films_adjacency_matrix[location].size(); i++) { films_adjacency_matrix[location][i] = -1; films_adjacency_matrix[i][location] = -1; } } int FilmRepository::get_films_count() { return films.size(); } void FilmRepository::update_adjacency_matrix(Customer* user, Film* film) { map<string, string> all; int new_film_location = id_location[film->get_id()]; vector<Film*> purchased = user->get_purchased_films(all); for (int i = 0; i < purchased.size(); i++) { if (purchased[i]->is_published() && purchased[i] != film) { int location = id_location[purchased[i]->get_id()]; if (films_adjacency_matrix[location][new_film_location] != -1) films_adjacency_matrix[location][new_film_location]++; if (films_adjacency_matrix[new_film_location][location] != -1) films_adjacency_matrix[new_film_location][location]++; } } } int FilmRepository::find_largest_index(vector<int> input, vector<int> skips) { bool skip = false; int largest_value = -1; int largest_index = -1; for (int i = 0; i < input.size(); i++) { if (input[i] > largest_value) { for (int j = 0; j < skips.size(); j++) { if (i == skips[j]) { skip = true; break; } } if (!skip) { largest_value = input[i]; largest_index = i; } } skip = false; } return largest_index; } vector<Film*> FilmRepository::get_recommendations(Film* film, Customer* user) { vector<Film*> result; int location = id_location[film->get_id()]; vector<int> recommended_films_index(RECOMMENDED_COUNT); vector<int> skips; skips.push_back(location); for (int i = 0; i < RECOMMENDED_COUNT; i++) { recommended_films_index[i] = find_largest_index(films_adjacency_matrix[location], skips); skips.push_back(recommended_films_index[i]); } for (int i = 0; i < RECOMMENDED_COUNT; i++) { for (map<int, int>::iterator it = id_location.begin(); it != id_location.end(); it++) { if (recommended_films_index[i] == it->second) { Film* recommended = find(it->first); result.push_back(recommended); break; } } } return result; }
31.314917
99
0.518878
[ "vector" ]
cd2a38dc4d8ae4aaa5355a51d53a4fe36971d44f
1,182
cc
C++
src/xenia/base/console_app_main_win.cc
andruuuuush/xenia
f2150a31256761b6a250150ffffbe1b529906387
[ "BSD-3-Clause" ]
3,100
2018-05-03T10:04:39.000Z
2022-03-31T04:51:53.000Z
src/xenia/base/console_app_main_win.cc
MerkeX/xenia
701300e8e9be446e04afb4731b18100783032ff9
[ "BSD-3-Clause" ]
671
2018-05-04T00:51:22.000Z
2022-03-31T15:20:22.000Z
src/xenia/base/console_app_main_win.cc
MerkeX/xenia
701300e8e9be446e04afb4731b18100783032ff9
[ "BSD-3-Clause" ]
877
2018-05-03T21:01:17.000Z
2022-03-31T19:43:14.000Z
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2021 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <cstdlib> #include <vector> #include "xenia/base/console_app_main.h" #include "xenia/base/main_win.h" int main(int argc_ignored, char** argv_ignored) { xe::ConsoleAppEntryInfo entry_info = xe::GetConsoleAppEntryInfo(); std::vector<std::string> args; if (!xe::ParseWin32LaunchArguments(entry_info.transparent_options, entry_info.positional_usage, entry_info.positional_options, &args)) { return EXIT_FAILURE; } int result = xe::InitializeWin32App(entry_info.name); if (result) { return result; } result = entry_info.entry_point(args); xe::ShutdownWin32App(); return result; }
31.945946
79
0.499154
[ "vector" ]
cd34e74ced5cef7f31f096573c89c9038bcf1ab7
43,467
cpp
C++
vpr/src/ripple/db/db_bookshelf.cpp
honeychen718/vtrwithap
c5073f89dad7e02a6f898d795be8d624591ff39e
[ "MIT" ]
null
null
null
vpr/src/ripple/db/db_bookshelf.cpp
honeychen718/vtrwithap
c5073f89dad7e02a6f898d795be8d624591ff39e
[ "MIT" ]
null
null
null
vpr/src/ripple/db/db_bookshelf.cpp
honeychen718/vtrwithap
c5073f89dad7e02a6f898d795be8d624591ff39e
[ "MIT" ]
null
null
null
#include "db.h" #include "SetupGrid.h" #include "gp_setting.h" using namespace db; void bilf_models_in_pb_type(const t_pb_type* pb_type, map<string, int>& blif_models_and_num); bool pb_type_contains_blif_model(const t_pb_type* pb_type, const std::string& blif_model_name, int& capacity); bool read_line_as_tokens(istream& is, vector<string>& tokens) { tokens.clear(); string line; getline(is, line); while (is && tokens.empty()) { string token = ""; for (unsigned i = 0; i < line.size(); ++i) { char currChar = line[i]; if (isspace(currChar)) { if (!token.empty()) { // Add the current token to the list of tokens tokens.push_back(token); token.clear(); } } else { // Add the char to the current token token.push_back(currChar); } } if (!token.empty()) { tokens.push_back(token); } if (tokens.empty()) { // Previous line read was empty. Read the next one. getline(is, line); } } return !tokens.empty(); } bool Database::readAux(string file) { string directory; size_t found = file.find_last_of("/\\"); if (found == file.npos) { directory = "./"; } else { directory = file.substr(0, found); directory += "/"; } ifstream fs(file); if (!fs.good()) { printlog(LOG_ERROR, "Cannot open %s to read", file.c_str()); return false; } string buffer; while (fs >> buffer) { if (buffer == "#") { //ignore comments fs.ignore(std::numeric_limits<streamsize>::max(), '\n'); continue; } size_t dot_pos = buffer.find_last_of("."); if (dot_pos == string::npos) { //ignore words without "dot" continue; } string ext = buffer.substr(dot_pos); if (ext == ".nodes") { setting.io_nodes = directory + buffer; } else if (ext == ".nets") { setting.io_nets = directory + buffer; } else if (ext == ".pl") { setting.io_pl = directory + buffer; } else if (ext == ".wts") { setting.io_wts = directory + buffer; } else if (ext == ".scl") { setting.io_scl = directory + buffer; } else if (ext == ".lib") { setting.io_lib = directory + buffer; } else { continue; } } printlog(LOG_VERBOSE, "nodes = %s", setting.io_nodes.c_str()); printlog(LOG_VERBOSE, "nets = %s", setting.io_nets.c_str()); printlog(LOG_VERBOSE, "pl = %s", setting.io_pl.c_str()); printlog(LOG_VERBOSE, "wts = %s", setting.io_wts.c_str()); printlog(LOG_VERBOSE, "scl = %s", setting.io_scl.c_str()); printlog(LOG_VERBOSE, "lib = %s", setting.io_lib.c_str()); fs.close(); return true; } bool Database::alloc_and_load_Instances(){ auto& atom_ctx = g_vpr_ctx.atom(); auto blocks = atom_ctx.nlist.blocks(); for (auto blk_iter = blocks.begin(); blk_iter != blocks.end(); ++blk_iter) { auto blk_id = *blk_iter; auto model = atom_ctx.nlist.block_model(blk_id); string block_name = atom_ctx.nlist.block_name(blk_id); Instance* instance = database.getInstance(block_name); if (instance != NULL) { printlog(LOG_ERROR, "Instance duplicated: %s", block_name.c_str()); } else { Master* master = NULL; if((string)model->name == ".names"){ int num_input_pins = atom_ctx.nlist.block_input_pins(blk_id).size(); master = database.getMaster(model , num_input_pins); }else{ master = database.getMaster(model); } if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", model->name); } else { Instance newinstance(block_name, master ,blk_id); instance = database.addInstance(newinstance); } } } } bool Database::readNodes(string file) { ifstream fs(file); if (!fs.good()) { cerr << "Read nodes file: " << file << " fail" << endl; return false; } vector<string> tokens; while (read_line_as_tokens(fs, tokens)) { Instance* instance = database.getInstance(tokens[0]); if (instance != NULL) { printlog(LOG_ERROR, "Instance duplicated: %s", tokens[0].c_str()); } else { Master* master = database.getMaster(Master::NameString2Enum(tokens[1])); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", tokens[1].c_str()); } else { Instance newinstance(tokens[0], master); instance = database.addInstance(newinstance); } } } fs.close(); return true; } bool Database::alloc_and_load_Nets(){ auto& atom_ctx = g_vpr_ctx.atom(); auto nets = atom_ctx.nlist.nets(); Net* net = NULL; for (auto net_iter = nets.begin(); net_iter != nets.end(); ++net_iter) { string net_name = atom_ctx.nlist.net_name(*net_iter); //cout<<"net:\t"<<net_name<<endl; net = database.getNet(net_name); if (net != NULL) { printlog(LOG_ERROR, "Net duplicated: %s", net_name.c_str()); } else { Net newnet(net_name); net = database.addNet(newnet); } auto net_pins = atom_ctx.nlist.net_pins(*net_iter); for (auto pin_iter = net_pins.begin(); pin_iter != net_pins.end(); ++pin_iter) { auto pin_block = atom_ctx.nlist.pin_block(*pin_iter); auto model = atom_ctx.nlist.block_model(pin_block); string block_name = atom_ctx.nlist.block_name(pin_block); string pin_full_name = atom_ctx.nlist.pin_name(*pin_iter); size_t dot_pos = pin_full_name.find_last_of("."); string pin_name = pin_full_name.substr(dot_pos + 1); Instance* instance = database.getInstance(block_name.c_str()); Pin* pin = NULL; if (instance != NULL) { pin = instance->getPin(pin_name); } else { printlog(LOG_ERROR, "Instance not found: %s", pin_name.c_str()); } if (pin == NULL) { printlog(LOG_ERROR, "Pin not found: %s", pin_name.c_str()); } else { net->addPin(pin); if (pin->type->type == 'o' && pin->instance->master->name == Master::BUFGCE) { net->isClk = true; } } //cout<<block_name<<"\t"<<atom_ctx.nlist.pin_name(*pin_iter)<<endl; } //cout<<"\n"<<endl; } } bool Database::readNets(string file) { ifstream fs(file); if (!fs.good()) { cerr << "Read net file: " << file << " fail" << endl; return false; } vector<string> tokens; Net* net = NULL; while (read_line_as_tokens(fs, tokens)) { if (tokens[0][0] == '#') { continue; } if (tokens[0] == "net") { net = database.getNet(tokens[1]); if (net != NULL) { printlog(LOG_ERROR, "Net duplicated: %s", tokens[1].c_str()); } else { Net newnet(tokens[1]); net = database.addNet(newnet); } } else if (tokens[0] == "endnet") { net = NULL; } else { Instance* instance = database.getInstance(tokens[0].c_str()); Pin* pin = NULL; if (instance != NULL) { pin = instance->getPin(tokens[1]); } else { printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str()); } if (pin == NULL) { printlog(LOG_ERROR, "Pin not found: %s", tokens[1].c_str()); } else { net->addPin(pin); if (pin->type->type == 'o' && pin->instance->master->name == Master::BUFGCE) { net->isClk = true; } } } } fs.close(); return false; } bool Database::alloc_and_load_Sites(){ auto& device_ctx = g_vpr_ctx.mutable_device(); device_ctx.grid = create_device_grid("ripple", database.arch->grid_layouts); //auto &grid=device_ctx.grid; //cout<<device_ctx.grid.width()<<"\t"<<device_ctx.grid.height()<<"\t"<<endl; int nx = device_ctx.grid.width(); int ny = device_ctx.grid.height(); database.setSiteMap(nx, ny); database.setSwitchBoxes(nx - 1, ny - 1); for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { //cout<<i<<"\t"<<j<<"\t"<<device_ctx.grid[i][j].type->name<<endl; string site_name = device_ctx.grid[x][y].type->name; SiteType* sitetype = database.getSiteType(SiteType::NameString2Enum(site_name)); if (sitetype == NULL) { printlog(LOG_ERROR, "Site type not found: %s", site_name.c_str()); } else { database.addSite(x, y, sitetype); } } } } bool Database::readPl(string file) { ifstream fs(file); if (!fs.good()) { cerr << "Read pl file: " << file << " fail" << endl; return false; } vector<string> tokens; while (read_line_as_tokens(fs, tokens)) { Instance* instance = database.getInstance(tokens[0]); if (instance == NULL) { printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str()); continue; } int x = atoi(tokens[1].c_str()); int y = atoi(tokens[2].c_str()); int slot = atoi(tokens[3].c_str()); instance->inputFixed = (tokens.size() >= 5 && tokens[4] == "FIXED"); instance->fixed = instance->inputFixed; if (instance->IsFF()) slot += 16; else if (instance->IsCARRY()) slot += 32; place(instance, x, y); } fs.close(); return true; } bool Database::alloc_and_load_Resources(){ primitive_candidate_block_types = identify_primitive_candidate_block_types(); auto& device_ctx = g_vpr_ctx.mutable_device(); for (auto const& tile : device_ctx.physical_tile_types) { const t_physical_tile_type* physical_tile = &tile; SiteType* sitetype = database.getSiteType(physical_tile); if (sitetype == NULL) { SiteType* newsitetype = new SiteType(physical_tile); sitetypes.push_back(newsitetype); } else { printlog(LOG_WARN, "Duplicated site type: %s", sitetype->name); } //write dsp&ram area in GPsetting if (sitetype->name == SiteType::DSP) { gpSetting.dspArea = tile.height * tile.width; } if (sitetype->name == SiteType::BRAM) { gpSetting.ramArea = tile.height * tile.width; } // assert(tile.sub_tiles.size()<=1); for (auto const& sub_tile : tile.sub_tiles) { int const sub_tile_capacity = sub_tile.capacity.total(); database.subtile_capacity[sitetype]=sub_tile_capacity; for (auto const& pb_type : sub_tile.equivalent_sites) { //cout<<equivalent_site->name<<endl; t_model* cur_model = vpr_setup->user_models; while (cur_model) { int capacity = 1; //string model_name=cur_model->name; if (pb_type_contains_blif_model(pb_type->pb_type, cur_model->name, capacity)) { capacity *= sub_tile_capacity; string resource_name = cur_model->name; Resource* resource = database.getResource(Resource::NameString2Enum(resource_name)); if (resource == NULL) { Resource newresource(Resource::NameString2Enum(resource_name)); resource = database.addResource(newresource); } sitetype->addResource(resource, capacity); Master* master = database.getMaster(cur_model); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } } cur_model = cur_model->next; } cur_model = vpr_setup->library_models; bool has_io_resource_added = false; while (cur_model) { int capacity = 1; //string model_name=cur_model->name; string model_name = cur_model->name; if (pb_type_contains_blif_model(pb_type->pb_type, cur_model->name, capacity)) { capacity *= sub_tile_capacity; if (model_name == ".input" || model_name == ".output") { Resource* resource = database.getResource(Resource::NameString2Enum("IO")); if (resource == NULL) { Resource newresource(Resource::NameString2Enum("IO")); resource = database.addResource(newresource); } if (!has_io_resource_added) { sitetype->addResource(resource, capacity); has_io_resource_added = true; } Master* master = database.getMaster(cur_model); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } } else if (model_name == ".names") { Resource* resource = database.getResource(Resource::NameString2Enum("LUT")); if (resource == NULL) { Resource newresource(Resource::NameString2Enum("LUT")); resource = database.addResource(newresource); } sitetype->addResource(resource, capacity); for (int i = 6; i > 0; i--) { string lut_name = "LUT" + to_string(i); Master* master = database.getMaster(Master::NameString2Enum(lut_name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } } //write lutPerSlice in gpsettings lutPerSlice = capacity * 0.75; } else if (model_name == ".latch") { Resource* resource = database.getResource(Resource::NameString2Enum("FF")); if (resource == NULL) { Resource newresource(Resource::NameString2Enum("FF")); resource = database.addResource(newresource); } sitetype->addResource(resource, capacity); Master* master = database.getMaster(Master::NameString2Enum(cur_model->name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } ffPerSlice = capacity * 0.75; } } cur_model = cur_model->next; } } } } } bool Database::readScl(string file) { ifstream fs(file); if (!fs.good()) { printlog(LOG_ERROR, "Cannot open %s to read", file.c_str()); return false; } vector<string> tokens; while (read_line_as_tokens(fs, tokens)) { if (tokens[0] == "SITE") { SiteType* sitetype = database.getSiteType(SiteType::NameString2Enum(tokens[1])); if (sitetype == NULL) { SiteType newsitetype(SiteType::NameString2Enum(tokens[1])); sitetype = database.addSiteType(newsitetype); } else { printlog(LOG_WARN, "Duplicated site type: %s", sitetype->name); } while (read_line_as_tokens(fs, tokens)) { if (tokens[0] == "END" && tokens[1] == "SITE") { break; } Resource* resource = database.getResource(Resource::NameString2Enum(tokens[0])); if (resource == NULL) { Resource newresource(Resource::NameString2Enum(tokens[0])); resource = database.addResource(newresource); } sitetype->addResource(resource, atoi(tokens[1].c_str())); } } if (tokens[0] == "RESOURCES") { while (read_line_as_tokens(fs, tokens)) { if (tokens[0] == "END" && tokens[1] == "RESOURCES") { break; } Resource* resource = database.getResource(Resource::NameString2Enum(tokens[0])); if (resource == NULL) { Resource newresource(Resource::NameString2Enum(tokens[0])); resource = database.addResource(newresource); } for (int i = 1; i < (int)tokens.size(); i++) { Master* master = database.getMaster(Master::NameString2Enum(tokens[i])); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", tokens[i].c_str()); } else { resource->addMaster(master); } } } } if (tokens[0] == "SITEMAP") { int nx = atoi(tokens[1].c_str()); int ny = atoi(tokens[2].c_str()); database.setSiteMap(nx, ny); database.setSwitchBoxes(nx / 2 - 1, ny); while (read_line_as_tokens(fs, tokens)) { if (tokens[0] == "END" && tokens[1] == "SITEMAP") { break; } int x = atoi(tokens[0].c_str()); int y = atoi(tokens[1].c_str()); SiteType* sitetype = database.getSiteType(SiteType::NameString2Enum(tokens[2])); if (sitetype == NULL) { printlog(LOG_ERROR, "Site type not found: %s", tokens[2].c_str()); } else { database.addSite(x, y, sitetype); } } } if (tokens[0] == "CLOCKREGIONS") { int nx = atoi(tokens[1].c_str()); int ny = atoi(tokens[2].c_str()); crmap_nx = nx; crmap_ny = ny; clkrgns.assign(nx, vector<ClkRgn*>(ny, NULL)); hfcols.assign(sitemap_nx, vector<HfCol*>(2 * ny, NULL)); for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { read_line_as_tokens(fs, tokens); string name = tokens[0] + tokens[1]; int lx = atoi(tokens[3].c_str()); int ly = atoi(tokens[4].c_str()); int hx = atoi(tokens[5].c_str()); int hy = atoi(tokens[6].c_str()); clkrgns[x][y] = new ClkRgn(name, lx, ly, hx, hy, x, y); } } } } fs.close(); return true; } bool Database::alloc_and_load_Masters(){ Master* master = NULL; const t_model* cur_model; cur_model = vpr_setup->user_models; while (cur_model) { master = database.getMaster(cur_model); if (master == NULL) { Master* master= new Master(cur_model); masters.push_back(master); } else { printlog(LOG_WARN, "Duplicated master: %s",cur_model->name); } cur_model = cur_model->next; } cur_model = vpr_setup->library_models; while (cur_model) { string cur_model_name = cur_model->name; if (cur_model_name == ".names") { //////alloc_and_add_lut_Masters(); for (int i = 6; i > 0; i--) { master = database.getMaster(cur_model , i); if (master == NULL) { Master* newmaster = new Master(cur_model , i); masters.push_back(newmaster); } else { printlog(LOG_WARN, "Duplicated master: %s", cur_model_name.c_str()); } } cur_model = cur_model->next; continue; } master = database.getMaster(cur_model); if (master == NULL) { Master* master= new Master(cur_model); masters.push_back(master); } else { printlog(LOG_WARN, "Duplicated master: %s", cur_model_name.c_str()); } cur_model = cur_model->next; } } bool Database::readLib(string file) { ifstream fs(file); if (!fs.good()) { printlog(LOG_ERROR, "Cannot open %s to read", file.c_str()); return false; } vector<string> tokens; Master* master = NULL; while (read_line_as_tokens(fs, tokens)) { if (tokens[0] == "CELL") { master = database.getMaster(Master::NameString2Enum(tokens[1])); if (master == NULL) { Master newmaster(Master::NameString2Enum(tokens[1])); master = database.addMaster(newmaster); } else { printlog(LOG_WARN, "Duplicated master: %s", tokens[1].c_str()); } } else if (tokens[0] == "PIN") { char type = 'x'; if (tokens.size() >= 4) { if (tokens[3] == "CLOCK") { type = 'c'; } else if (tokens[3] == "CTRL") { type = 'e'; } } else if (tokens.size() >= 3) { if (tokens[2] == "OUTPUT") { type = 'o'; } else if (tokens[2] == "INPUT") { type = 'i'; } } RipplePinType pintype(tokens[1], type); if (master != NULL) { master->addPin(pintype); } } else if (tokens[0] == "END") { } } fs.close(); return true; } bool Database::readWts(string file) { return false; } bool Database::writePl(string file) { // ofstream fs(file); // if (!fs.good()) { // printlog(LOG_ERROR, "Cannot open %s to write", file.c_str()); // return false; // } // vector<Instance*>::iterator ii = database.instances.begin(); // vector<Instance*>::iterator ie = database.instances.end(); // int nErrorLimit = 10; // for (; ii != ie; ++ii) { // Instance* instance = *ii; // if (instance->pack == NULL || instance->pack->site == NULL) { // if (nErrorLimit > 0) { // printlog(LOG_ERROR, "Instance not placed: %s", instance->name.c_str()); // nErrorLimit--; // } else if (nErrorLimit == 0) { // printlog(LOG_ERROR, "(Remaining same errors are not shown)"); // nErrorLimit--; // } // continue; // } // Site* site = instance->pack->site; // int slot = instance->slot; // if (instance->IsFF()) // slot -= 16; // else if (instance->IsCARRY()) // slot -= 32; // fs << instance->name << " " << site->x << " " << site->y << " " << slot; // if (instance->inputFixed) fs << " FIXED"; // fs << endl; // } return true; } bool Database::read_from_vpr_database(){ alloc_and_load_Masters(); alloc_and_load_Instances(); alloc_and_load_Resources(); alloc_and_load_Sites(); alloc_and_load_Nets(); } // vector<string> modelname_to_mastername(string modelname){ // if (modelname=="" // } bool pb_type_contains_blif_model(const t_pb_type* pb_type, const std::string& blif_model_name, int& capacity) { if (!pb_type) { return false; } if (pb_type->blif_model != nullptr) { //Leaf pb_type VTR_ASSERT(pb_type->num_modes == 0); if (blif_model_name == pb_type->blif_model || ".subckt " + blif_model_name == pb_type->blif_model) { return true; } else { return false; } } else { for (int imode = 0; imode < pb_type->num_modes; ++imode) { const t_mode* mode = &pb_type->modes[imode]; for (int ichild = 0; ichild < mode->num_pb_type_children; ++ichild) { const t_pb_type* pb_type_child = &mode->pb_type_children[ichild]; if (pb_type_contains_blif_model(pb_type_child, blif_model_name, capacity)) { capacity *= pb_type_child->num_pb; return true; } } } } return false; } void bilf_models_in_pb_type(const t_pb_type* pb_type, map<string, int>& blif_models_and_num) { if (!pb_type) { return; } if (pb_type->blif_model != nullptr) { //Leaf pb_type VTR_ASSERT(pb_type->num_modes == 0); string blif_model_name = pb_type->blif_model; string::size_type idx; idx = blif_model_name.find(".subckt "); if (idx == string::npos) { blif_model_name.replace(idx, sizeof(".subckt "), ""); } blif_models_and_num[blif_model_name] = 1; } for (int imode = 0; imode < pb_type->num_modes; ++imode) { const t_mode* mode = &pb_type->modes[imode]; for (int ichild = 0; ichild < mode->num_pb_type_children; ++ichild) { const t_pb_type* pb_type_child = &mode->pb_type_children[ichild]; bilf_models_in_pb_type(pb_type_child, blif_models_and_num); map<string, int>::iterator iter; for (iter = blif_models_and_num.begin(); iter != blif_models_and_num.end(); iter++) { iter->second *= pb_type_child->num_pb; } } } } bool Database::readArch() { /* readlib */ Master* master = NULL; const t_model* cur_model; cur_model = vpr_setup->user_models; while (cur_model) { string cur_model_name; cur_model_name = cur_model->name; master = database.getMaster(Master::NameString2Enum(cur_model_name)); if (master == NULL) { Master newmaster(Master::NameString2Enum(cur_model_name)); master = database.addMaster(newmaster); } else { printlog(LOG_WARN, "Duplicated master: %s", cur_model_name.c_str()); } const t_model_ports* cur_port; cur_port = cur_model->outputs; while (cur_port) { string cur_port_name = cur_port->name; for (int pini = 0; pini < cur_port->size; pini++) { RipplePinType pintype(cur_port_name + "[" + to_string(pini) + "]", 'o'); if (master != NULL) { master->addPin(pintype); } } cur_port = cur_port->next; } cur_port = cur_model->inputs; while (cur_port) { string cur_port_name = cur_port->name; char type = (cur_port->is_clock) ? 'c' : 'i'; for (int pini = 0; pini < cur_port->size; pini++) { RipplePinType pintype(cur_port_name + "[" + to_string(pini) + "]", type); if (master != NULL) { master->addPin(pintype); } } cur_port = cur_port->next; } cur_model = cur_model->next; num_models++; } cur_model = vpr_setup->library_models; while (cur_model) { string cur_model_name; cur_model_name = cur_model->name; if (cur_model_name == ".names") { for (int i = 6; i > 0; i--) { cur_model_name = "LUT" + to_string(i); master = database.getMaster(Master::NameString2Enum(cur_model_name)); if (master == NULL) { Master newmaster(Master::NameString2Enum(cur_model_name)); master = database.addMaster(newmaster); } else { printlog(LOG_WARN, "Duplicated master: %s", cur_model_name.c_str()); } string lut_out_pin_name = "out[0]"; RipplePinType pintype(lut_out_pin_name, 'o'); if (master != NULL) { master->addPin(pintype); } string lut_in_port_name = "in"; for (int j = 0; j < i; j++) { RipplePinType pintype(lut_in_port_name + "[" + to_string(j) + "]", 'i'); if (master != NULL) { master->addPin(pintype); } } } cur_model = cur_model->next; continue; } master = database.getMaster(Master::NameString2Enum(cur_model_name)); if (master == NULL) { Master newmaster(Master::NameString2Enum(cur_model_name)); master = database.addMaster(newmaster); } else { printlog(LOG_WARN, "Duplicated master: %s", cur_model_name.c_str()); } const t_model_ports* cur_port; cur_port = cur_model->outputs; while (cur_port) { string cur_port_name = cur_port->name; for (int pini = 0; pini < cur_port->size; pini++) { RipplePinType pintype(cur_port_name + "[" + to_string(pini) + "]", 'o'); if (master != NULL) { master->addPin(pintype); } } cur_port = cur_port->next; } cur_port = cur_model->inputs; while (cur_port) { string cur_port_name = cur_port->name; char type = (cur_port->is_clock) ? 'c' : 'i'; for (int pini = 0; pini < cur_port->size; pini++) { RipplePinType pintype(cur_port_name + "[" + to_string(pini) + "]", type); if (master != NULL) { master->addPin(pintype); } } cur_port = cur_port->next; } cur_model = cur_model->next; num_models++; } /* readlib */ /* readnodes */ //std::set<const t_model*> unique_models;// the set of models , for readscl!! auto& atom_ctx = g_vpr_ctx.atom(); auto blocks = atom_ctx.nlist.blocks(); for (auto blk_iter = blocks.begin(); blk_iter != blocks.end(); ++blk_iter) { auto blk_id = *blk_iter; auto model = atom_ctx.nlist.block_model(blk_id); //unique_models.insert(model);// the set of models , for readscl!! //size_t blk_int_id = size_t(blk_id); //string inst_name="inst_" + to_string(blk_int_id); //cout<<inst_name<<endl; string block_name = atom_ctx.nlist.block_name(blk_id); string model_name = model->name; if (model_name == ".names") { int lut_input_num = atom_ctx.nlist.block_input_pins(blk_id).size(); model_name = "LUT" + to_string(lut_input_num); if (lut_input_num == 0) { model_name = "LUT1"; } } //Instance *instance = database.getInstance(inst_name); Instance* instance = database.getInstance(block_name); //cout<<block_name<<endl; if (instance != NULL) { //printlog(LOG_ERROR, "Instance duplicated: %s", inst_name.c_str()); printlog(LOG_ERROR, "Instance duplicated: %s", block_name.c_str()); } else { Master* master = database.getMaster(Master::NameString2Enum(model_name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", model_name.c_str()); } else { //Instance newinstance(inst_name, master); Instance newinstance(block_name, master ,blk_id); instance = database.addInstance(newinstance); } } } /* readnodes */ /* readscl */ auto& device_ctx = g_vpr_ctx.mutable_device(); for (auto const& tile : device_ctx.physical_tile_types) { string tile_name = tile.name; SiteType* sitetype = database.getSiteType(SiteType::NameString2Enum(tile_name)); if (sitetype == NULL) { SiteType newsitetype(SiteType::NameString2Enum(tile_name)); sitetype = database.addSiteType(newsitetype); } else { printlog(LOG_WARN, "Duplicated site type: %s", sitetype->name); } //write dsp&ram area in GPsetting if (sitetype->name == SiteType::DSP) { gpSetting.dspArea = tile.height * tile.width; } if (sitetype->name == SiteType::BRAM) { gpSetting.ramArea = tile.height * tile.width; } // assert(tile.sub_tiles.size()<=1); for (auto const& sub_tile : tile.sub_tiles) { int const sub_tile_capacity = sub_tile.capacity.total(); database.subtile_capacity[sitetype]=sub_tile_capacity; for (auto const& pb_type : sub_tile.equivalent_sites) { //cout<<equivalent_site->name<<endl; t_model* cur_model = vpr_setup->user_models; while (cur_model) { int capacity = 1; //string model_name=cur_model->name; if (pb_type_contains_blif_model(pb_type->pb_type, cur_model->name, capacity)) { capacity *= sub_tile_capacity; string resource_name = cur_model->name; Resource* resource = database.getResource(Resource::NameString2Enum(resource_name)); if (resource == NULL) { Resource newresource(Resource::NameString2Enum(resource_name)); resource = database.addResource(newresource); } sitetype->addResource(resource, capacity); Master* master = database.getMaster(Master::NameString2Enum(cur_model->name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } } cur_model = cur_model->next; } cur_model = vpr_setup->library_models; bool has_io_resource_added = false; while (cur_model) { int capacity = 1; //string model_name=cur_model->name; string model_name = cur_model->name; if (pb_type_contains_blif_model(pb_type->pb_type, cur_model->name, capacity)) { capacity *= sub_tile_capacity; if (model_name == ".input" || model_name == ".output") { Resource* resource = database.getResource(Resource::NameString2Enum("IO")); if (resource == NULL) { Resource newresource(Resource::NameString2Enum("IO")); resource = database.addResource(newresource); } if (!has_io_resource_added) { sitetype->addResource(resource, capacity); has_io_resource_added = true; } Master* master = database.getMaster(Master::NameString2Enum(cur_model->name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } } else if (model_name == ".names") { Resource* resource = database.getResource(Resource::NameString2Enum("LUT")); if (resource == NULL) { Resource newresource(Resource::NameString2Enum("LUT")); resource = database.addResource(newresource); } sitetype->addResource(resource, capacity); for (int i = 6; i > 0; i--) { string lut_name = "LUT" + to_string(i); Master* master = database.getMaster(Master::NameString2Enum(lut_name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } } //write lutPerSlice in gpsettings lutPerSlice = capacity * 0.75; } else if (model_name == ".latch") { Resource* resource = database.getResource(Resource::NameString2Enum("FF")); if (resource == NULL) { Resource newresource(Resource::NameString2Enum("FF")); resource = database.addResource(newresource); } sitetype->addResource(resource, capacity); Master* master = database.getMaster(Master::NameString2Enum(cur_model->name)); if (master == NULL) { printlog(LOG_ERROR, "Master not found: %s", cur_model->name); } else { resource->addMaster(master); } ffPerSlice = capacity * 0.75; } } cur_model = cur_model->next; } } } } device_ctx.grid = create_device_grid("ripple", database.arch->grid_layouts); //auto &grid=device_ctx.grid; //cout<<device_ctx.grid.width()<<"\t"<<device_ctx.grid.height()<<"\t"<<endl; int nx = device_ctx.grid.width(); int ny = device_ctx.grid.height(); database.setSiteMap(nx, ny); database.setSwitchBoxes(nx - 1, ny - 1); for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { //cout<<i<<"\t"<<j<<"\t"<<device_ctx.grid[i][j].type->name<<endl; string site_name = device_ctx.grid[x][y].type->name; SiteType* sitetype = database.getSiteType(SiteType::NameString2Enum(site_name)); if (sitetype == NULL) { printlog(LOG_ERROR, "Site type not found: %s", site_name.c_str()); } else { database.addSite(x, y, sitetype); } } } /* readscl */ /* readNets */ auto nets = atom_ctx.nlist.nets(); Net* net = NULL; for (auto net_iter = nets.begin(); net_iter != nets.end(); ++net_iter) { string net_name = atom_ctx.nlist.net_name(*net_iter); //cout<<"net:\t"<<net_name<<endl; net = database.getNet(net_name); if (net != NULL) { printlog(LOG_ERROR, "Net duplicated: %s", net_name.c_str()); } else { Net newnet(net_name); net = database.addNet(newnet); } auto net_pins = atom_ctx.nlist.net_pins(*net_iter); for (auto pin_iter = net_pins.begin(); pin_iter != net_pins.end(); ++pin_iter) { auto pin_block = atom_ctx.nlist.pin_block(*pin_iter); auto model = atom_ctx.nlist.block_model(pin_block); string block_name = atom_ctx.nlist.block_name(pin_block); string pin_full_name = atom_ctx.nlist.pin_name(*pin_iter); size_t dot_pos = pin_full_name.find_last_of("."); string pin_name = pin_full_name.substr(dot_pos + 1); Instance* instance = database.getInstance(block_name.c_str()); Pin* pin = NULL; if (instance != NULL) { pin = instance->getPin(pin_name); } else { printlog(LOG_ERROR, "Instance not found: %s", pin_name.c_str()); } if (pin == NULL) { printlog(LOG_ERROR, "Pin not found: %s", pin_name.c_str()); } else { net->addPin(pin); if (pin->type->type == 'o' && pin->instance->master->name == Master::BUFGCE) { net->isClk = true; } } //cout<<block_name<<"\t"<<atom_ctx.nlist.pin_name(*pin_iter)<<endl; } //cout<<"\n"<<endl; } cout << "finish" << endl; } // bool Database::readNets(string file){ // ifstream fs(file); // if (!fs.good()) { // cerr<<"Read net file: "<<file<<" fail"<<endl; // return false; // } // vector<string> tokens; // Net *net = NULL; // while(read_line_as_tokens(fs, tokens)){ // if(tokens[0][0] == '#'){ // continue; // } // if(tokens[0] == "net"){ // net = database.getNet(tokens[1]); // if(net != NULL){ // printlog(LOG_ERROR, "Net duplicated: %s", tokens[1].c_str()); // }else{ // Net newnet(tokens[1]); // net = database.addNet(newnet); // } // }else if(tokens[0] == "endnet"){ // net = NULL; // }else{ // Instance *instance = database.getInstance(tokens[0].c_str()); // Pin *pin = NULL; // if(instance != NULL){ // pin = instance->getPin(tokens[1]); // }else{ // printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str()); // } // if(pin == NULL){ // printlog(LOG_ERROR, "Pin not found: %s", tokens[1].c_str()); // }else{ // net->addPin(pin); // if (pin->type->type=='o' && pin->instance->master->name==Master::BUFGCE){ // net->isClk=true; // } // } // } // } // fs.close(); // return false; // }
39.69589
111
0.494122
[ "vector", "model" ]
cd3cd15d6d4e45109663cb22a6272ea2f15210ef
6,270
cc
C++
src/vm/VirtualMachineTemplate.cc
rdiaz-on/one
4b7f47c7e218dd9aea1b4eb79db5725450bc5644
[ "Apache-2.0" ]
null
null
null
src/vm/VirtualMachineTemplate.cc
rdiaz-on/one
4b7f47c7e218dd9aea1b4eb79db5725450bc5644
[ "Apache-2.0" ]
null
null
null
src/vm/VirtualMachineTemplate.cc
rdiaz-on/one
4b7f47c7e218dd9aea1b4eb79db5725450bc5644
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */ /* */ /* 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 "VirtualMachineTemplate.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ std::map<std::string, std::set<std::string> > VirtualMachineTemplate::restricted; std::map<std::string, std::set<std::string> > VirtualMachineTemplate::encrypted; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachineTemplate::replace_disk_image(int target_id, const string& target_name, const string& target_uname, const string& new_name, const string& new_uname) { int num_disks; int tmp_id; string tmp_name; string tmp_uname; vector<VectorAttribute *> disks; VectorAttribute * disk = 0; num_disks = get("DISK", disks); for(int i=0; i<num_disks; i++) { disk = disks[i]; if (disk->vector_value("IMAGE_ID", tmp_id) == 0) //DISK has IMAGE_ID { if (tmp_id == target_id) { break; } } else //IMAGE and IMAGE_UNAME { tmp_name = disk->vector_value("IMAGE"); tmp_uname = disk->vector_value("IMAGE_UNAME"); bool uname = tmp_uname.empty() || tmp_uname == target_uname; if ( tmp_name == target_name && uname ) { break; } } disk = 0; } if ( disk == 0 ) { return -1; } disk->remove("IMAGE_ID"); disk->replace("IMAGE", new_name); disk->replace("IMAGE_UNAME", new_uname); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string& VirtualMachineTemplate::to_xml_short(string& xml) const { ostringstream oss; string labels; string schd_rank, schd_ds_rank; string schd_req, schd_ds_req; string user_prio; vector<const VectorAttribute*> attrs; if (attributes.empty()) { oss << "<USER_TEMPLATE/>"; } else { oss << "<USER_TEMPLATE>"; /* ------------------------------------------------------------------ */ /* Attributes required by Sunstone */ /* - LABELS */ /* ------------------------------------------------------------------ */ if (get("LABELS", labels)) { oss << "<LABELS>" << one_util::escape_xml(labels) << "</LABELS>"; } /* ------------------------------------------------------------------ */ /* Attributes required by Scheduler */ /* - SCHED_RANK (RANK - deprecated) */ /* - SCHED_DS_RANK */ /* - SCHED_REQUIREMENTS */ /* - SCHED_DS_REQUIREMENTS */ /* */ /* - SCHED_ACTION */ /* - PUBLIC_CLOUD */ /* ------------------------------------------------------------------ */ if (get("SCHED_RANK", schd_rank)) { oss << "<SCHED_RANK>" << one_util::escape_xml(schd_rank) << "</SCHED_RANK>"; } if (get("SCHED_DS_RANK", schd_ds_rank)) { oss << "<SCHED_DS_RANK>" << one_util::escape_xml(schd_ds_rank) << "</SCHED_DS_RANK>"; } if (get("SCHED_REQUIREMENTS", schd_req)) { oss << "<SCHED_REQUIREMENTS>" << one_util::escape_xml(schd_req) << "</SCHED_REQUIREMENTS>"; } if (get("SCHED_DS_REQUIREMENTS", schd_ds_req)) { oss << "<SCHED_DS_REQUIREMENTS>" << one_util::escape_xml(schd_ds_req) << "</SCHED_DS_REQUIREMENTS>"; } if (get("USER_PRIORITY", user_prio)) { oss << "<USER_PRIORITY>" << one_util::escape_xml(user_prio) << "</USER_PRIORITY>"; } if ( get("PUBLIC_CLOUD", attrs) > 0 ) { vector<const VectorAttribute *>::const_iterator it; for (it = attrs.begin(); it != attrs.end(); it++) { (*it)->to_xml(oss); } } attrs.clear(); if ( get("SCHED_ACTION", attrs) > 0 ) { vector<const VectorAttribute *>::const_iterator it; for (it = attrs.begin(); it != attrs.end(); it++) { (*it)->to_xml(oss); } } oss << "</USER_TEMPLATE>"; } xml = oss.str(); return xml; }
33.709677
81
0.381499
[ "vector" ]
cd3e26bdf715f81f6e05566c9f2ae858fc967e32
61,731
cpp
C++
game/ui/tileview/battletileview.cpp
trevortomesh/OpenApoc
53cd163889fbfd21a9c128183427dad4255ac1a3
[ "MIT" ]
1
2020-11-10T18:31:44.000Z
2020-11-10T18:31:44.000Z
game/ui/tileview/battletileview.cpp
FilmBoy84/OpenApoc_FB84
a6b69cafba01744998ced6c67b93fbd937d32d26
[ "MIT" ]
null
null
null
game/ui/tileview/battletileview.cpp
FilmBoy84/OpenApoc_FB84
a6b69cafba01744998ced6c67b93fbd937d32d26
[ "MIT" ]
null
null
null
#include "game/ui/tileview/battletileview.h" #include "forms/form.h" #include "forms/graphic.h" #include "forms/ui.h" #include "framework/configfile.h" #include "framework/data.h" #include "framework/event.h" #include "framework/font.h" #include "framework/framework.h" #include "framework/keycodes.h" #include "framework/palette.h" #include "framework/renderer.h" #include "framework/sound.h" #include "framework/trace.h" #include "game/state/battle/battle.h" #include "game/state/battle/battlehazard.h" #include "game/state/battle/battleitem.h" #include "game/state/battle/battlemappart.h" #include "game/state/battle/battleunitmission.h" #include "game/state/gamestate.h" #include "game/state/rules/battle/battlecommonimagelist.h" #include "game/state/rules/battle/battlecommonsamplelist.h" #include "game/state/shared/organisation.h" #include "game/state/tilemap/tileobject_battlehazard.h" #include "game/state/tilemap/tileobject_battleitem.h" #include "game/state/tilemap/tileobject_battlemappart.h" #include "game/state/tilemap/tileobject_battleunit.h" #include "game/state/tilemap/tileobject_shadow.h" #include "library/strings_format.h" #include <glm/glm.hpp> namespace OpenApoc { void BattleTileView::updateHiddenBar() { hiddenBarTicksAccumulated = 0; int width = 321; int height = 33; Colour bar = {142, 142, 142, 255}; Colour black = {0, 0, 0, 0}; int totalTU = 0; int remainingTU = 0; for (auto &u : battle.units) { if (u.second->owner != battle.currentActiveOrganisation || !u.second->isConscious() || u.second->getAIType() == AIType::None || !u.second->canMove()) { continue; } int reserve = u.second->reserveShotCost + u.second->getBodyStateChangeCost(BodyState::Standing, BodyState::Kneeling); totalTU += u.second->initialTU - reserve; remainingTU += std::max(0, u.second->agent->modified_stats.time_units - reserve); } int maxWidth = totalTU ? clamp(width - remainingTU * width / totalTU, 0, width) : 0; auto progressBar = mksp<RGBImage>(Vec2<int>{width, height}); { RGBImageLock l(progressBar); // Content for (int x = 1; x < maxWidth; x++) { for (int y = 1; y < height - 1; y++) { l.set({x, y}, bar); } } // Borders for (int y = 1; y < height - 1; y++) { l.set({0, y}, bar); l.set({width - 1, y}, bar); } for (int x = 0; x < width; x++) { l.set({x, 0}, bar); l.set({x, height - 1}, bar); } // Remainder for (int x = maxWidth + 1; x < width - 1; x++) { for (int y = 1; y < height - 1; y++) { l.set({x, y}, black); } } } hiddenForm->findControlTyped<Graphic>("GRAPHIC_HIDDEN")->setImage(progressBar); } BattleTileView::BattleTileView(TileMap &map, Vec3<int> isoTileSize, Vec2<int> stratTileSize, TileViewMode initialMode, Vec3<float> screenCenterTile, GameState &gameState) : TileView(map, isoTileSize, stratTileSize, initialMode), hiddenForm(ui().getForm("battle/hidden")), state(gameState), battle(*gameState.current_battle), palette(fw().data->loadPalette("xcom3/tacdata/tactical.pal")) { pal = palette; for (int j = 0; j <= 15; j++) { colorCurrent = j; auto newPal = mksp<Palette>(); for (int i = 0; i < 255 - 4; i++) { newPal->setColour(i, palette->getColour(i)); } // Lift color, pulsates from (0r 3/8g 5/8b) to (0r 8/8g 4/8b) newPal->setColour(255 - 4, Colour(0, (colorCurrent * 16 * 5 + 255 * 3) / 8, (colorCurrent * 16 * -1 + 255 * 5) / 8)); // Yellow color, for owned indicators, pulsates from (3/8r 3/8g 0b) to (8/8r 8/8g 0b) newPal->setColour(255 - 3, Colour((colorCurrent * 16 * 5 + 255 * 3) / 8, (colorCurrent * 16 * 5 + 255 * 3) / 8, 0)); // Red color, for enemy indicators, pulsates from (3/8r 0g 0b) to (8/8r 0g 0b) newPal->setColour(255 - 2, Colour((colorCurrent * 16 * 5 + 255 * 3) / 8, 0, 0)); // Pink color, for neutral indicators, pulsates from (3/8r 0g 3/8b) to (8/8r 0g 8/8b) newPal->setColour(255 - 1, Colour((colorCurrent * 16 * 5 + 255 * 3) / 8, 0, (colorCurrent * 16 * 5 + 255 * 3) / 8)); // Blue color, for misc. indicators, pulsates from (0r 3/8g 3/8b) to (0r 8/8g 8/8b) newPal->setColour(255 - 0, Colour(0, (colorCurrent * 16 * 5 + 255 * 3) / 8, (colorCurrent * 16 * 5 + 255 * 3) / 8)); modPalette.push_back(newPal); } layerDrawingMode = LayerDrawingMode::UpToCurrentLevel; targetTacticalThisLevel = fw().data->loadImage(format("PCKSTRAT:xcom3/tacdata/stratico.pck:xcom3/tacdata/" "stratico.tab:%d", 482)); targetTacticalOtherLevel = fw().data->loadImage(format("PCKSTRAT:xcom3/tacdata/stratico.pck:xcom3/tacdata/" "stratico.tab:%d", 483)); selectedTileEmptyImageBack = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 182)); selectedTileEmptyImageFront = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 183)); selectedTileFilledImageBack = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 184)); selectedTileFilledImageFront = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 185)); selectedTileFireImageBack = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 186)); selectedTileFireImageFront = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 187)); selectedTileBackgroundImageBack = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 188)); selectedTileBackgroundImageFront = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 189)); selectedTileImageOffset = {23, 42}; pal = fw().data->loadPalette("xcom3/tacdata/tactical.pal"); selectionImageFriendlySmall = fw().data->loadImage("battle/map-selection-small.png"); selectionImageFriendlyLarge = fw().data->loadImage("battle/map-selection-large.png"); activeUnitSelectionArrow.push_back(fw().data->loadImage("battle/battle-active-squadless.png")); inactiveUnitSelectionArrow.push_back( fw().data->loadImage("battle/battle-inactive-squadless.png")); for (int i = 0; i < 6; i++) { activeUnitSelectionArrow.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 167 + i))); inactiveUnitSelectionArrow.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 173 + i))); } // Alexey Andronov (Istrebitel) // FIXME: For some reason, when drawing unit selection images, a wild pixel appears // in the bottom left (visible above soldier's shoulder) when moving // Using PNG instead solves the problem, but we should rather find a way to properly use // vanilla game resources? // activeUnitSelectionArrow.front() = fw().data->loadImage("battle/167.png"); behaviorUnitSelectionUnderlay[BattleUnit::BehaviorMode::Evasive] = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 190)); behaviorUnitSelectionUnderlay[BattleUnit::BehaviorMode::Normal] = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 191)); behaviorUnitSelectionUnderlay[BattleUnit::BehaviorMode::Aggressive] = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 192)); runningIcon = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 193)); bleedingIcon = fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 194)); healingIcons.push_back(fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 195))); healingIcons.push_back(fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 196))); lowMoraleIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 197))); lowMoraleIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 198))); psiIcons[PsiStatus::Probe].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 199))); psiIcons[PsiStatus::Probe].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 200))); psiIcons[PsiStatus::Panic].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 201))); psiIcons[PsiStatus::Panic].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 202))); psiIcons[PsiStatus::Stun].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 203))); psiIcons[PsiStatus::Stun].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 204))); psiIcons[PsiStatus::Control].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 205))); psiIcons[PsiStatus::Control].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 206))); psiIcons[PsiStatus::NotEngaged].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 207))); psiIcons[PsiStatus::NotEngaged].push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 208))); targetLocationIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 68))); targetLocationIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 69))); targetLocationIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 70))); targetLocationIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 69))); targetLocationIcons.push_back( fw().data->loadImage(format("PCK:xcom3/tacdata/icons.pck:xcom3/tacdata/" "icons.tab:%d:xcom3/tacdata/tactical.pal", 68))); targetLocationOffset = {23, 42}; waypointIcons.push_back(fw().data->loadImage("battle/battle-waypoint-1.png")); waypointIcons.push_back(fw().data->loadImage("battle/battle-waypoint-2.png")); waypointIcons.push_back(fw().data->loadImage("battle/battle-waypoint-3.png")); waypointIcons.push_back(fw().data->loadImage("battle/battle-waypoint-2.png")); waypointIcons.push_back(fw().data->loadImage("battle/battle-waypoint-1.png")); waypointDarkIcons.push_back(fw().data->loadImage("battle/battle-waypoint-1-dark.png")); waypointDarkIcons.push_back(fw().data->loadImage("battle/battle-waypoint-2-dark.png")); waypointDarkIcons.push_back(fw().data->loadImage("battle/battle-waypoint-3-dark.png")); waypointDarkIcons.push_back(fw().data->loadImage("battle/battle-waypoint-2-dark.png")); waypointDarkIcons.push_back(fw().data->loadImage("battle/battle-waypoint-1-dark.png")); auto font = ui().getFont("smallset"); for (int i = 0; i <= 255; i++) { tuIndicators.push_back(font->getString(format("%d", i))); } tuSeparator = font->getString("/"); pathPreviewTooFar = font->getString(tr("Too Far")); pathPreviewUnreachable = font->getString(tr("Blocked")); attackCostOutOfRange = font->getString(tr("Out of range")); attackCostNoArc = font->getString(tr("No arc of throw")); for (int i = 0; i < 16; i++) { auto healthBar = mksp<RGBImage>(Vec2<int>{15, 2}); { RGBImageLock l(healthBar); for (int y = 0; y < 2; y++) { for (int x = 0; x < (int)healthBar->size.x; x++) { if (x >= i) l.set({x, y}, {0, 0, 0, 255}); else l.set({x, y}, {0, 0, 0, 0}); } } } arrowHealthBars.push_back(healthBar); } // FIXME: Load from save last screen location? setScreenCenterTile(screenCenterTile); }; BattleTileView::~BattleTileView() = default; void BattleTileView::eventOccurred(Event *e) { if (e->type() == EVENT_KEY_DOWN) { if (debugHotkeyMode) { switch (e->keyboard().KeyCode) { case SDLK_F6: { LogWarning("Writing voxel view to tileviewvoxels.png"); auto imageOffset = -this->getScreenOffset(); auto img = std::dynamic_pointer_cast<RGBImage>(this->map.dumpVoxelView( {imageOffset, imageOffset + dpySize}, *this, battle.battleViewZLevel)); fw().data->writeImage("tileviewvoxels.png", img); return; } case SDLK_F7: { LogWarning("Writing voxel view (fast) to tileviewvoxels.png"); auto imageOffset = -this->getScreenOffset(); auto img = std::dynamic_pointer_cast<RGBImage>( this->map.dumpVoxelView({imageOffset, imageOffset + dpySize}, *this, battle.battleViewZLevel, true)); fw().data->writeImage("tileviewvoxels.png", img); return; } case SDLK_F8: { LogWarning("Writing voxel view to tileviewvoxels.png"); auto imageOffset = -this->getScreenOffset(); auto img = std::dynamic_pointer_cast<RGBImage>( this->map.dumpVoxelView({imageOffset, imageOffset + dpySize}, *this, battle.battleViewZLevel, false, true)); fw().data->writeImage("tileviewvoxels.png", img); return; } case SDLK_F9: { LogWarning("Writing voxel view (fast) to tileviewvoxels.png"); auto imageOffset = -this->getScreenOffset(); auto img = std::dynamic_pointer_cast<RGBImage>( this->map.dumpVoxelView({imageOffset, imageOffset + dpySize}, *this, battle.battleViewZLevel, true, true)); fw().data->writeImage("tileviewvoxels.png", img); return; } default: break; } } else { switch (e->keyboard().KeyCode) { default: break; } } } TileView::eventOccurred(e); } void BattleTileView::render() { TRACE_FN; Renderer &r = *fw().renderer; r.clear(); r.setPalette(this->pal); if (hideDisplay) { hiddenBarTicksAccumulated++; if (hiddenBarTicksAccumulated > 10) { updateHiddenBar(); } hiddenForm->render(); return; } // Rotate Icons { healingIconTicksAccumulated++; healingIconTicksAccumulated %= 2 * HEALING_ICON_ANIMATION_DELAY; lowMoraleIconTicksAccumulated++; lowMoraleIconTicksAccumulated %= 2 * LOWMORALE_ICON_ANIMATION_DELAY; psiIconTicksAccumulated++; psiIconTicksAccumulated %= 2 * PSI_ICON_ANIMATION_DELAY; selectionFrameTicksAccumulated++; selectionFrameTicksAccumulated %= 2 * SELECTION_FRAME_ANIMATION_DELAY; iconAnimationTicksAccumulated++; iconAnimationTicksAccumulated %= targetLocationIcons.size() * TARGET_ICONS_ANIMATION_DELAY; focusAnimationTicksAccumulated++; focusAnimationTicksAccumulated %= (2 * FOCUS_ICONS_ANIMATION_FRAMES - 2) * FOCUS_ICONS_ANIMATION_DELAY; } // screenOffset.x/screenOffset.y is the 'amount added to the tile coords' - so we want // the inverse to tell which tiles are at the screen bounds auto topLeft = offsetScreenToTileCoords(Vec2<int>{-isoTileSize.x, -isoTileSize.y}, 0); auto topRight = offsetScreenToTileCoords(Vec2<int>{dpySize.x, -isoTileSize.y}, 0); auto bottomLeft = offsetScreenToTileCoords(Vec2<int>{-isoTileSize.x, dpySize.y}, map.size.z); auto bottomRight = offsetScreenToTileCoords(Vec2<int>{dpySize.x, dpySize.y}, map.size.z); int minX = std::max(0, topLeft.x); int maxX = std::min(map.size.x, bottomRight.x); int minY = std::max(0, topRight.y); int maxY = std::min(map.size.y, bottomLeft.y); int zFrom = 0; int zTo = maxZDraw; switch (layerDrawingMode) { case LayerDrawingMode::UpToCurrentLevel: zFrom = 0; zTo = battle.battleViewZLevel; break; case LayerDrawingMode::AllLevels: zFrom = 0; zTo = maxZDraw; break; case LayerDrawingMode::OnlyCurrentLevel: zFrom = battle.battleViewZLevel - 1; zTo = battle.battleViewZLevel; break; } // This is also the place where we emit a burning sound, because we find out which fire is in // the viewport and is closest to the screen center bool fireEncountered = false; float closestFireDistance = FLT_MAX; Vec3<float> closestFirePosition; // FIXME: A different algorithm is required in order to properly display everything // --- Read the note at the bottom of this file --- // FIXME: Draw double selection bracket for big units? switch (this->viewMode) { case TileViewMode::Isometric: { // List of units that require drawing of an overhead icon (bool = is first) std::list<std::pair<sp<BattleUnit>, bool>> unitsToDrawSelectionArrows; // List of units that require drawing of focus arrows (bool = islarge) std::list<std::pair<sp<TileObject>, bool>> unitsToDrawFocusArrows; // List of target icons to draw // std::map<Vec3<int>, std::list<Vec3<float>>> targetIconLocations; std::set<Vec3<int>> targetIconLocations; // List of waypointLocations to draw // std::map<Vec3<int>, std::list<Vec3<float>>> waypointLocations; std::set<Vec3<int>> waypointLocations; bool drawWaypoints = config().getBool("OpenApoc.NewFeature.DisplayUnitPaths"); bool darkenWaypoints = false; std::list<StateRef<BattleUnit>> allUnits; if (revealWholeMap) { for (auto &entry : battle.units) { if (entry.second->isDead() || entry.second->retreated) { continue; } auto &u = entry.second; for (auto &m : u->missions) { if (m->type == BattleUnitMission::Type::ReachGoal) { targetIconLocations.insert(m->targetLocation); break; } if (m->type == BattleUnitMission::Type::GotoLocation && !m->currentPlannedPath.empty()) { targetIconLocations.insert(m->targetLocation); if (drawWaypoints) { for (auto &w : m->currentPlannedPath) { if (w != m->targetLocation) { waypointLocations.insert(w); } } } break; } } } } else { for (auto &u : battle.battleViewSelectedUnits) { for (auto &m : u->missions) { if (m->type == BattleUnitMission::Type::ReachGoal) { targetIconLocations.insert(m->targetLocation); break; } if (m->type == BattleUnitMission::Type::GotoLocation && !m->currentPlannedPath.empty()) { targetIconLocations.insert(m->targetLocation); if (drawWaypoints) { for (auto &w : m->currentPlannedPath) { if (w != m->targetLocation) { waypointLocations.insert(w); } } } break; } } } } if (previewedPathCost != PreviewedPathCostSpecial::NONE && drawWaypoints && waypointLocations.empty()) { darkenWaypoints = true; for (auto &w : pathPreview) { waypointLocations.insert(w); } } auto &waypointImageSource = darkenWaypoints ? waypointDarkIcons : waypointIcons; static const Vec2<float> offsetFaceIcon = {-7.0f, -1.0f}; for (int z = zFrom; z < zTo; z++) { int currentLevel = z - battle.battleViewZLevel + 1; // Find out when to draw selection bracket parts (if ever) Tile *selTileOnCurLevel = nullptr; Vec3<int> selTilePosOnCurLevel; sp<Image> selectionImageBack; sp<Image> selectionImageFront; bool drawPathPreview = false; bool drawAttackCost = false; if (selectedTilePosition.z >= z && selectedTilePosition.x >= minX && selectedTilePosition.x < maxX && selectedTilePosition.y >= minY && selectedTilePosition.y < maxY) { selTilePosOnCurLevel = {selectedTilePosition.x, selectedTilePosition.y, z}; selTileOnCurLevel = map.getTile(selTilePosOnCurLevel.x, selTilePosOnCurLevel.y, selTilePosOnCurLevel.z); // Find what kind of selection bracket to draw (yellow or green) // Yellow if this tile intersects with a unit if (selectedTilePosition.z == z) { drawPathPreview = previewedPathCost != PreviewedPathCostSpecial::NONE; drawAttackCost = calculatedAttackCost != CalculatedAttackCostSpecial::NONE; auto u = selTileOnCurLevel->getUnitIfPresent(true); auto unit = u ? u->getUnit() : nullptr; if (unit && (unit->owner == battle.currentPlayer || battle.visibleUnits[battle.currentPlayer].find({&state, unit->id}) != battle.visibleUnits[battle.currentPlayer].end())) { if (battle.currentPlayer->isRelatedTo(unit->owner) == Organisation::Relation::Hostile) { selectionImageBack = selectedTileFireImageBack; selectionImageFront = selectedTileFireImageFront; } else { selectionImageBack = selectedTileFilledImageBack; selectionImageFront = selectedTileFilledImageFront; } } else { selectionImageBack = selectedTileEmptyImageBack; selectionImageFront = selectedTileEmptyImageFront; } } else { selectionImageBack = selectedTileBackgroundImageBack; selectionImageFront = selectedTileBackgroundImageFront; } } // Actually draw stuff for (unsigned int layer = 0; layer < map.getLayerCount(); layer++) { for (int y = minY; y < maxY; y++) { for (int x = minX; x < maxX; x++) { auto tile = map.getTile(x, y, z); bool visible = battle.getVisible(battle.currentPlayer, x, y, z); auto object_count = tile->drawnObjects[layer].size(); size_t obj_id = 0; do { if (tile == selTileOnCurLevel && layer == 0 && selTileOnCurLevel->drawBattlescapeSelectionBackAt == obj_id) { r.draw(selectionImageBack, tileToOffsetScreenCoords(selTilePosOnCurLevel) - selectedTileImageOffset); } if (tile->drawTargetLocationIconAt == obj_id) { if (targetIconLocations.find({x, y, z}) != targetIconLocations.end()) { r.draw(targetLocationIcons[iconAnimationTicksAccumulated / TARGET_ICONS_ANIMATION_DELAY], tileToOffsetScreenCoords(Vec3<float>{ x, y, tile->getRestingPosition().z}) - targetLocationOffset); } if (waypointLocations.find({x, y, z}) != waypointLocations.end()) { r.draw(waypointImageSource[iconAnimationTicksAccumulated / TARGET_ICONS_ANIMATION_DELAY], tileToOffsetScreenCoords(Vec3<float>{ x, y, tile->getRestingPosition().z}) - targetLocationOffset); } } if (obj_id >= object_count) { break; } auto &obj = tile->drawnObjects[layer][obj_id]; bool friendly = false; bool hostile = false; bool unitLowMorale = false; bool unitPsiAttacker = false; PsiStatus unitPsiAttackedStatus = PsiStatus::NotEngaged; Vec2<float> unitFaceIconPos; bool objectVisible = visible; switch (obj->getType()) { case TileObject::Type::Shadow: { auto s = std::static_pointer_cast<TileObjectShadow>(obj); auto u = s->ownerBattleUnit.lock(); if (u) { objectVisible = !u->isConscious() || u->owner == battle.currentPlayer || battle.visibleUnits.at(battle.currentPlayer) .find({&state, u->id}) != battle.visibleUnits.at(battle.currentPlayer) .end(); } break; } case TileObject::Type::Unit: { auto u = std::static_pointer_cast<TileObjectBattleUnit>(obj) ->getUnit(); objectVisible = !u->isConscious() || u->owner == battle.currentPlayer || battle.visibleUnits.at(battle.currentPlayer) .find({&state, u->id}) != battle.visibleUnits.at(battle.currentPlayer).end(); friendly = u->owner == battle.currentPlayer; hostile = battle.currentPlayer->isRelatedTo(u->owner) == Organisation::Relation::Hostile; if (objectVisible) { if (u->moraleState != MoraleState::Normal) { unitLowMorale = true; } else if (u->psiStatus != PsiStatus::NotEngaged) { unitPsiAttacker = true; } if (!u->psiAttackers.empty()) { unitPsiAttackedStatus = u->psiAttackers.begin()->second; } if (unitLowMorale || unitPsiAttacker || unitPsiAttackedStatus != PsiStatus::NotEngaged) { unitFaceIconPos = tileToOffsetScreenCoords( u->getPosition() + Vec3<float>{0.0f, 0.0f, (u->getCurrentHeight() - 4.0f) * 1.5f / 40.0f}) + offsetFaceIcon; } } if (!battle.battleViewSelectedUnits.empty()) { auto selectedPos = std::find(battle.battleViewSelectedUnits.begin(), battle.battleViewSelectedUnits.end(), u); if (selectedPos == battle.battleViewSelectedUnits.begin()) { unitsToDrawSelectionArrows.push_back({u, true}); } else if (selectedPos != battle.battleViewSelectedUnits.end()) { unitsToDrawSelectionArrows.push_back({u, false}); } // If visible and focused by selected - draw focus // arrows if (objectVisible) { bool focusedBySelectedUnits = false; for (auto &su : battle.battleViewSelectedUnits) { if (std::find(u->focusedByUnits.begin(), u->focusedByUnits.end(), su) != u->focusedByUnits.end()) { focusedBySelectedUnits = true; break; } } if (focusedBySelectedUnits) { unitsToDrawFocusArrows.push_back( {obj, u->isLarge()}); } } } break; } case TileObject::Type::Hazard: { if (visible && ticksUntilFireSound == 0) { auto h = std::static_pointer_cast<TileObjectBattleHazard>( obj) ->getHazard(); if (h->hazardType->fire) { auto distance = glm::length(centerPos - h->position); if (distance < closestFireDistance) { fireEncountered = true; closestFireDistance = distance; closestFirePosition = h->position; } } } } default: break; } Vec2<float> pos = tileToOffsetScreenCoords(obj->getCenter()); obj->draw(r, *this, pos, this->viewMode, revealWholeMap || objectVisible, currentLevel, friendly, hostile); int faceShift = 0; if (unitPsiAttacker) { r.draw( psiIcons[PsiStatus::NotEngaged][psiIconTicksAccumulated / PSI_ICON_ANIMATION_DELAY], unitFaceIconPos); faceShift = 1; } if (unitPsiAttackedStatus != PsiStatus::NotEngaged) { r.draw( psiIcons[unitPsiAttackedStatus][psiIconTicksAccumulated / PSI_ICON_ANIMATION_DELAY], unitFaceIconPos + Vec2<float>{0, faceShift * 16.0f}); faceShift = -1; } if (unitLowMorale) { r.draw(lowMoraleIcons[lowMoraleIconTicksAccumulated / LOWMORALE_ICON_ANIMATION_DELAY], unitFaceIconPos + Vec2<float>{0, faceShift * 16.0f}); } // Loop ends when "break" is reached above obj_id++; } while (true); // When done with all objects, draw the front selection image if (tile == selTileOnCurLevel && layer == 0) { static const Vec2<int> offset{2, -53}; const Vec2<int> tileScreenCoords = tileToOffsetScreenCoords(selTilePosOnCurLevel); r.draw(selectionImageFront, tileScreenCoords - selectedTileImageOffset); // drawing attack cost takes precedence over path cost if (drawAttackCost) { sp<Image> img; switch (static_cast<CalculatedAttackCostSpecial>( calculatedAttackCost)) { case CalculatedAttackCostSpecial::NO_WEAPON: img = nullptr; break; case CalculatedAttackCostSpecial::NO_ARC: img = attackCostNoArc; break; case CalculatedAttackCostSpecial::OUT_OF_RANGE: img = attackCostOutOfRange; break; default: { img = nullptr; // don't draw using img if (!lastSelectedUnit) // shouldn't happen LogError("Displaying attack cost without selected " "unit?!"); auto imgCost = tuIndicators[calculatedAttackCost]; auto imgStock = tuIndicators[lastSelectedUnit->agent->modified_stats .time_units]; Vec2<int> offset2{(imgCost->size.x + imgStock->size.x + tuSeparator->size.x) / 2, tuSeparator->size.y / 2}; r.draw(imgCost, tileScreenCoords + offset - offset2); offset2.x -= imgCost->size.x; r.draw(tuSeparator, tileScreenCoords + offset - offset2); offset2.x -= tuSeparator->size.x; r.draw(imgStock, tileScreenCoords + offset - offset2); break; } } if (img) { r.draw(img, tileScreenCoords + offset - Vec2<int>{img->size.x / 2, img->size.y / 2}); } } else if (drawPathPreview) { sp<Image> img; switch ( static_cast<PreviewedPathCostSpecial>(previewedPathCost)) { case PreviewedPathCostSpecial::UNREACHABLE: img = pathPreviewUnreachable; break; case PreviewedPathCostSpecial::TOO_FAR: img = pathPreviewTooFar; break; default: img = tuIndicators[previewedPathCost]; break; } if (img) { r.draw(img, tileScreenCoords + offset - Vec2<int>{img->size.x / 2, img->size.y / 2}); } } } if (tile->pathfindingDebugFlag) r.draw(waypointIcons[0], tileToOffsetScreenCoords(Vec3<int>{x, y, z}) - selectedTileImageOffset); } } } } // Draw next level, units whose "legs" are below "zTo", projectiles and items moving for (int z = zTo; z < maxZDraw && z < zTo + 1; z++) { int currentLevel = z - battle.battleViewZLevel + 1; unsigned int layer1 = map.getLayer(TileObject::Type::Unit); unsigned int layer2 = map.getLayer(TileObject::Type::Shadow); unsigned int minLayer = std::min(layer1, layer2); unsigned int maxLayer = std::max(layer1, layer2); for (unsigned int layer = minLayer; layer <= maxLayer; layer++) { for (int y = minY; y < maxY; y++) { for (int x = minX; x < maxX; x++) { auto tile = map.getTile(x, y, z); bool visible = battle.getVisible(battle.currentPlayer, x, y, z); auto object_count = tile->drawnObjects[layer].size(); size_t obj_id = 0; do { if (obj_id >= object_count) { break; } auto &obj = tile->drawnObjects[layer][obj_id]; bool objectVisible = visible; bool friendly = false; bool hostile = false; bool draw = false; bool unitLowMorale = false; bool unitPsiAttacker = false; PsiStatus unitPsiAttackedStatus = PsiStatus::NotEngaged; Vec2<float> unitFaceIconPos; switch (obj->getType()) { case TileObject::Type::Unit: { auto u = std::static_pointer_cast<TileObjectBattleUnit>(obj) ->getUnit(); if (u->position.z < zTo) { objectVisible = !u->isConscious() || u->owner == battle.currentPlayer || battle.visibleUnits.at(battle.currentPlayer) .find({&state, u->id}) != battle.visibleUnits.at(battle.currentPlayer) .end(); friendly = u->owner == battle.currentPlayer; hostile = battle.currentPlayer->isRelatedTo(u->owner) == Organisation::Relation::Hostile; draw = true; if (objectVisible) { if (u->moraleState != MoraleState::Normal) { unitLowMorale = true; } else if (u->psiStatus != PsiStatus::NotEngaged) { unitPsiAttacker = true; } if (!u->psiAttackers.empty()) { unitPsiAttackedStatus = u->psiAttackers.begin()->second; } if (unitLowMorale || unitPsiAttacker || unitPsiAttackedStatus != PsiStatus::NotEngaged) { unitFaceIconPos = tileToOffsetScreenCoords( u->getPosition() + Vec3<float>{ 0.0f, 0.0f, (u->getCurrentHeight() - 4.0f) * 1.5f / 40.0f}) + offsetFaceIcon; } } if (!battle.battleViewSelectedUnits.empty()) { auto selectedPos = std::find( battle.battleViewSelectedUnits.begin(), battle.battleViewSelectedUnits.end(), u); if (selectedPos == battle.battleViewSelectedUnits.begin()) { unitsToDrawSelectionArrows.push_back({u, true}); } else if (selectedPos != battle.battleViewSelectedUnits.end()) { unitsToDrawSelectionArrows.push_back( {u, false}); } // If visible and focused - draw focus arrows if (objectVisible) { bool focusedBySelectedUnits = false; for (auto &su : battle.battleViewSelectedUnits) { if (std::find(u->focusedByUnits.begin(), u->focusedByUnits.end(), su) != u->focusedByUnits.end()) { focusedBySelectedUnits = true; break; } } if (focusedBySelectedUnits) { unitsToDrawFocusArrows.push_back( {obj, u->isLarge()}); } } } } break; } case TileObject::Type::Item: { draw = std::static_pointer_cast<TileObjectBattleItem>(obj) ->getItem() ->falling; break; } case TileObject::Type::Projectile: { draw = true; break; } case TileObject::Type::Ground: case TileObject::Type::LeftWall: case TileObject::Type::RightWall: case TileObject::Type::Feature: { draw = std::static_pointer_cast<TileObjectBattleMapPart>(obj) ->getOwner() ->falling; break; } default: break; } if (draw) { Vec2<float> pos = tileToOffsetScreenCoords(obj->getCenter()); obj->draw(r, *this, pos, this->viewMode, revealWholeMap || objectVisible, currentLevel, friendly, hostile); int faceShift = 0; if (unitPsiAttacker) { r.draw(psiIcons[PsiStatus::NotEngaged] [psiIconTicksAccumulated / PSI_ICON_ANIMATION_DELAY], unitFaceIconPos); faceShift = 1; } if (unitPsiAttackedStatus != PsiStatus::NotEngaged) { r.draw(psiIcons[unitPsiAttackedStatus] [psiIconTicksAccumulated / PSI_ICON_ANIMATION_DELAY], unitFaceIconPos + Vec2<float>{0, faceShift * 16.0f}); faceShift = -1; } if (unitLowMorale) { r.draw(lowMoraleIcons[lowMoraleIconTicksAccumulated / LOWMORALE_ICON_ANIMATION_DELAY], unitFaceIconPos + Vec2<float>{0, faceShift * 16.0f}); } } // Loop ends when "break" is reached above obj_id++; } while (true); } } } } // Draw selected unit arrows for (auto &obj : unitsToDrawSelectionArrows) { static const Vec2<float> offset = {-13.0f, -14.0f}; static const Vec2<float> offsetRunning = {0.0f, 0.0f}; static const Vec2<float> offsetBehavior = {0.0f, 0.0f}; static const Vec2<float> offsetBleed = {0.0f, 0.0f}; static const Vec2<float> offsetHealing = {6.0f, 14.0f}; static const Vec2<float> offsetTU = {13.0f, -5.0f}; static const Vec2<float> offsetHealth = {6.0f, 2.0f}; // Health from 0 to 15, where 15 = 100%, 14 = less than 99.9% and 0 = 0%+ int health = obj.first->agent->modified_stats.health * 15 / obj.first->agent->current_stats.health; if (health < 0) continue; Vec2<float> pos = tileToOffsetScreenCoords( obj.first->getPosition() + Vec3<float>{0.0f, 0.0f, (obj.first->getCurrentHeight() - 4.0f) * 1.5f / 40.0f}) + offset; // Selection arrow r.draw(obj.second ? activeUnitSelectionArrow[obj.first->squadNumber + 1] : inactiveUnitSelectionArrow[obj.first->squadNumber + 1], pos); r.draw(arrowHealthBars[health], pos + offsetHealth); // Behavior r.draw(behaviorUnitSelectionUnderlay[obj.first->behavior_mode], pos + offsetBehavior); if (battle.mode == Battle::Mode::TurnBased) { auto &img = tuIndicators[obj.first->agent->modified_stats.time_units]; r.draw(img, pos + offsetTU - Vec2<float>{img->size.x / 2, img->size.y / 2}); } if (obj.first->movement_mode == MovementMode::Running) { r.draw(runningIcon, pos + offsetRunning); } if (obj.first->isFatallyWounded()) { if (obj.first->isHealing) { r.draw(healingIcons[healingIconTicksAccumulated / HEALING_ICON_ANIMATION_DELAY], pos + offsetHealing); } else { r.draw(bleedingIcon, pos + offsetBleed); } } } if (revealWholeMap) { static const Vec2<float> offset = {-13.0f, -19.0f}; static const Vec2<float> offsetTU = {13.0f, -5.0f}; for (auto &u : battle.units) { if (!u.second->isConscious()) { continue; } Vec2<float> pos = tileToOffsetScreenCoords( u.second->getPosition() + Vec3<float>{0.0f, 0.0f, (u.second->getCurrentHeight() - 4.0f) * 1.5f / 40.0f}); if (battle.mode == Battle::Mode::TurnBased) { auto &img = tuIndicators[u.second->agent->modified_stats.time_units]; r.draw(img, pos + offset + offsetTU - Vec2<float>{img->size.x / 2, img->size.y / 2}); } for (auto &t : u.second->visibleEnemies) { auto tarPos = tileToOffsetScreenCoords(t->getPosition()); auto tarVec = tarPos - pos; tarVec *= 0.75f; r.drawLine(pos, pos + tarVec, this->strategyViewBoxColour, this->strategyViewBoxThickness); } } } // Draw unit focus arrows if (!unitsToDrawFocusArrows.empty()) { static const Vec2<float> offset1 = {-20.0f, -29.0f}; static const Vec2<float> offset2 = {22.0f, -29.0f}; static const Vec2<float> offset3 = {-20.0f, 27.0f}; static const Vec2<float> offset4 = {22.0f, 27.0f}; static const Vec2<float> offsetd14 = {-1.0f, -1.0f}; static const Vec2<float> offsetd23 = {1.0f, -1.0f}; float offset = (float)focusAnimationTicksAccumulated / FOCUS_ICONS_ANIMATION_DELAY; // Offset goes like this: 0 1 2 3 4 3 2 1 (example for 5 frames) // Therefore, if value is >=frames, we do 2*frames -2 -offset // For example, 2*5 - 2 - 5 = 3, that's how we get 3 that's after 4 Vec2<float> imgOffset = { (float)battle.common_image_list->focusArrows[0]->size.x / 2.0f, (float)battle.common_image_list->focusArrows[0]->size.y / 2.0f}; if (offset >= FOCUS_ICONS_ANIMATION_FRAMES) offset = 2 * FOCUS_ICONS_ANIMATION_FRAMES - 2 - offset; for (auto &obj : unitsToDrawFocusArrows) { float largeOffset = obj.second ? 2.0f : 1.0f; Vec2<float> pos = tileToOffsetScreenCoords(obj.first->getCenter()); r.draw(battle.common_image_list->focusArrows[0], pos - imgOffset + largeOffset * offset1 + offset * offsetd14); r.draw(battle.common_image_list->focusArrows[1], pos - imgOffset + largeOffset * offset2 + offset * offsetd23); r.draw(battle.common_image_list->focusArrows[2], pos - imgOffset + largeOffset * offset3 - offset * offsetd23); r.draw(battle.common_image_list->focusArrows[3], pos - imgOffset + largeOffset * offset4 - offset * offsetd14); } } } break; case TileViewMode::Strategy: { // Params are: visible, level, friendly, hostile, selected (0 = not, 1 = small, 2 = // large) std::list<std::tuple<sp<TileObject>, bool, int, bool, bool, int>> unitsToDraw; // Lines to draw between unit and destination, as well as what kind of target to draw std::list<std::tuple<Vec3<int>, Vec3<int>, bool>> targetLocationsToDraw; // Params are: visible, level std::list<std::tuple<sp<TileObject>, bool, int>> itemsToDraw; // Gather units below current level for (int z = 0; z < zFrom; z++) { for (unsigned int layer = 0; layer < map.getLayerCount(); layer++) { for (int y = minY; y < maxY; y++) { for (int x = minX; x < maxX; x++) { auto tile = map.getTile(x, y, z); auto object_count = tile->drawnObjects[layer].size(); for (size_t obj_id = 0; obj_id < object_count; obj_id++) { auto &obj = tile->drawnObjects[layer][obj_id]; switch (obj->getType()) { case TileObject::Type::Unit: { auto u = std::static_pointer_cast<TileObjectBattleUnit>(obj) ->getUnit(); bool objectVisible = !u->isConscious() || u->owner == battle.currentPlayer || battle.visibleUnits.at(battle.currentPlayer) .find({&state, u->id}) != battle.visibleUnits.at(battle.currentPlayer).end(); bool friendly = u->owner == battle.currentPlayer; bool hostile = battle.currentPlayer->isRelatedTo(u->owner) == Organisation::Relation::Hostile; bool selected = false; if (friendly) { if (std::find(battle.battleViewSelectedUnits.begin(), battle.battleViewSelectedUnits.end(), u) != battle.battleViewSelectedUnits.end()) { selected = true; } for (auto &m : u->missions) { if ((m->type == BattleUnitMission::Type::ReachGoal) || (m->type == BattleUnitMission::Type::GotoLocation && !m->currentPlannedPath.empty())) { targetLocationsToDraw.emplace_back( m->targetLocation, (Vec3<int>)u->position, (obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1)) == 0); break; } } } unitsToDraw.emplace_back( obj, revealWholeMap || objectVisible, obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1), friendly, hostile, selected ? (u->isLarge() ? 2 : 1) : 0); break; } default: break; } } } } } } // Draw everything but units and items // Gather units and items on current level for (int z = zFrom; z < zTo; z++) { // currentZLevel is an upper exclusive boundary, that's why we need to sub 1 here int currentLevel = z - (battle.battleViewZLevel - 1); for (unsigned int layer = 0; layer < map.getLayerCount(); layer++) { for (int y = minY; y < maxY; y++) { for (int x = minX; x < maxX; x++) { auto tile = map.getTile(x, y, z); bool visible = battle.getVisible(battle.currentPlayer, x, y, z); auto object_count = tile->drawnObjects[layer].size(); for (size_t obj_id = 0; obj_id < object_count; obj_id++) { auto &obj = tile->drawnObjects[layer][obj_id]; bool objectVisible = visible; switch (obj->getType()) { case TileObject::Type::Unit: { auto u = std::static_pointer_cast<TileObjectBattleUnit>(obj) ->getUnit(); objectVisible = !u->isConscious() || u->owner == battle.currentPlayer || battle.visibleUnits.at(battle.currentPlayer) .find({&state, u->id}) != battle.visibleUnits.at(battle.currentPlayer).end(); bool friendly = u->owner == battle.currentPlayer; bool hostile = battle.currentPlayer->isRelatedTo(u->owner) == Organisation::Relation::Hostile; bool selected = false; if (friendly) { if (std::find(battle.battleViewSelectedUnits.begin(), battle.battleViewSelectedUnits.end(), u) != battle.battleViewSelectedUnits.end()) { selected = true; } for (auto &m : u->missions) { if ((m->type == BattleUnitMission::Type::ReachGoal) || (m->type == BattleUnitMission::Type::GotoLocation && !m->currentPlannedPath.empty())) { targetLocationsToDraw.emplace_back( m->targetLocation, (Vec3<int>)u->position, (obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1)) == 0); break; } } } unitsToDraw.emplace_back( obj, revealWholeMap || objectVisible, obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1), friendly, hostile, selected ? (u->isLarge() ? 2 : 1) : 0); continue; } case TileObject::Type::Item: { if (currentLevel == 0) { itemsToDraw.emplace_back( obj, revealWholeMap || visible, obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1)); } continue; } case TileObject::Type::Hazard: { if (visible && ticksUntilFireSound == 0) { auto h = std::static_pointer_cast<TileObjectBattleHazard>( obj) ->getHazard(); if (h->hazardType->fire) { auto distance = glm::length(centerPos - h->position); if (distance < closestFireDistance) { fireEncountered = true; closestFireDistance = distance; closestFirePosition = h->position; } } } } default: break; } Vec2<float> pos = tileToOffsetScreenCoords(obj->getCenter()); obj->draw(r, *this, pos, this->viewMode, revealWholeMap || objectVisible, currentLevel); } } } } } // Gather units above current level for (int z = zTo; z < maxZDraw; z++) { for (unsigned int layer = 0; layer < map.getLayerCount(); layer++) { for (int y = minY; y < maxY; y++) { for (int x = minX; x < maxX; x++) { auto tile = map.getTile(x, y, z); auto object_count = tile->drawnObjects[layer].size(); for (size_t obj_id = 0; obj_id < object_count; obj_id++) { auto &obj = tile->drawnObjects[layer][obj_id]; switch (obj->getType()) { case TileObject::Type::Unit: { auto u = std::static_pointer_cast<TileObjectBattleUnit>(obj) ->getUnit(); bool objectVisible = !u->isConscious() || u->owner == battle.currentPlayer || battle.visibleUnits.at(battle.currentPlayer) .find({&state, u->id}) != battle.visibleUnits.at(battle.currentPlayer).end(); bool friendly = u->owner == battle.currentPlayer; bool hostile = battle.currentPlayer->isRelatedTo(u->owner) == Organisation::Relation::Hostile; bool selected = false; if (friendly) { if (std::find(battle.battleViewSelectedUnits.begin(), battle.battleViewSelectedUnits.end(), u) != battle.battleViewSelectedUnits.end()) { selected = true; } for (auto &m : u->missions) { if ((m->type == BattleUnitMission::Type::ReachGoal) || (m->type == BattleUnitMission::Type::GotoLocation && !m->currentPlannedPath.empty())) { targetLocationsToDraw.emplace_back( m->targetLocation, (Vec3<int>)u->position, (obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1)) == 0); break; } } } unitsToDraw.emplace_back( obj, revealWholeMap || objectVisible, obj->getOwningTile()->position.z - (battle.battleViewZLevel - 1), friendly, hostile, selected ? (u->isLarge() ? 2 : 1) : 0); break; } default: break; } } } } } } // Draw stuff for (auto &obj : targetLocationsToDraw) { static const auto offsetLine = Vec2<int>{3, 3}; static const auto offsetStrat = Vec2<int>{-1, -1}; static const auto lineColor = Colour(255, 255, 0, 255); // Draw line from unit to target tile r.drawLine(tileToOffsetScreenCoords(std::get<0>(obj)) + offsetLine, tileToOffsetScreenCoords(std::get<1>(obj)) + offsetLine, lineColor); // Draw location image at target tile r.draw(std::get<2>(obj) ? targetTacticalThisLevel : targetTacticalOtherLevel, tileToOffsetScreenCoords(std::get<0>(obj)) + offsetStrat); } for (auto &obj : unitsToDraw) { auto unit = std::get<0>(obj); Vec2<float> pos = tileToOffsetScreenCoords(unit->getCenter()); unit->draw(r, *this, pos, this->viewMode, std::get<1>(obj), std::get<2>(obj), std::get<3>(obj), std::get<4>(obj)); // Draw unit selection brackets auto selected = std::get<5>(obj); if (selected && (selectionFrameTicksAccumulated / SELECTION_FRAME_ANIMATION_DELAY)) { auto drawn = selected == 1 ? selectionImageFriendlySmall : selectionImageFriendlyLarge; r.draw(drawn, pos - Vec2<float>(drawn->size / (unsigned)2)); } } for (auto &obj : itemsToDraw) { Vec2<float> pos = tileToOffsetScreenCoords(std::get<0>(obj)->getCenter()); std::get<0>(obj)->draw(r, *this, pos, this->viewMode, std::get<1>(obj), std::get<2>(obj)); } renderStrategyOverlay(r); } break; default: LogError("Unexpected tile view mode \"%d\"", (int)this->viewMode); break; } if (fireEncountered) { ticksUntilFireSound = 60 * state.battle_common_sample_list->burn->sampleCount / state.battle_common_sample_list->burn->format.frequency / state.battle_common_sample_list->burn->format.channels; fw().soundBackend->playSample(state.battle_common_sample_list->burn, closestFirePosition); } if (this->debugHotkeyMode) { auto font = ui().getFont("smallset"); auto cursorPositionString = font->getString(format("Cursor at %s", selectedTilePosition)); r.draw(cursorPositionString, {0, 0}); } } void BattleTileView::update() { TileView::update(); // Pulsate palette colors colorCurrent += (colorForward ? 1 : -1); if (colorCurrent <= 0 || colorCurrent >= 15) { colorCurrent = clamp(colorCurrent, 0, 15); colorForward = !colorForward; } pal = modPalette[colorCurrent]; } void BattleTileView::resetAttackCost() { if (attackCostTicksAccumulated > 0) { attackCostTicksAccumulated = 0; calculatedAttackCost = static_cast<int>(CalculatedAttackCostSpecial::NONE); } } void BattleTileView::setZLevel(int zLevel) { battle.battleViewZLevel = clamp(zLevel, 1, maxZDraw); setScreenCenterTile(Vec3<float>{centerPos.x, centerPos.y, battle.battleViewZLevel - 1}); } int BattleTileView::getZLevel() { return battle.battleViewZLevel; } void BattleTileView::setLayerDrawingMode(LayerDrawingMode mode) { layerDrawingMode = mode; } void BattleTileView::setScreenCenterTile(Vec3<float> center) { TileView::setScreenCenterTile(center); fw().soundBackend->setListenerPosition({center.x, center.y, center.z}); } void BattleTileView::setScreenCenterTile(Vec2<float> center) { this->setScreenCenterTile(Vec3<float>{center.x, center.y, battle.battleViewZLevel - 1}); } void BattleTileView::setSelectedTilePosition(Vec3<int> newPosition) { auto oldPosition = selectedTilePosition; TileView::setSelectedTilePosition(newPosition); if (oldPosition != selectedTilePosition) { resetPathPreview(); resetAttackCost(); } } void BattleTileView::resetPathPreview() { if (pathPreviewTicksAccumulated > 0) { pathPreviewTicksAccumulated = 0; previewedPathCost = static_cast<int>(PreviewedPathCostSpecial::NONE); pathPreview.clear(); } } } // namespace OpenApoc // Alexey Andronov (Istrebitel) // A different algorithm is required in order to properly display big units. /* 1) Rendering must go in diagonal lines. Illustration (on XY plane): CURRENT TARGET 147 136 258 258 369 479 2) Objects must be located in the bottom-most, right-most tile they intersect (already implemented) 3) Object can either occupy 1, 2 or 3 tiles on the X axis (only X matters) - Tiny objects (items, projectiles) occupy 1 tile always - Small typical objects (walls, sceneries, small units) occupy 1 tile when static, 2 when moving on X axis - Large objects (large units) occupy 2 tiles when static, 3 when moving on x axis How to determine this value is TBD. 4) When rendering we must check 1 tile ahead for 2-tile object and 1 tile ahead and further on x axis for 3-tile object. If present we must draw 1 tile ahead for 2-tile object or 2 tiles ahead and one tile further on x-axis for 3 tile object then resume normal draw order without drawing already drawn tiles Illustration: SMALL MOVING LARGE STATIC LARGE MOVING LEGEND xxxxx > xxxxx6. x = tile w/o object drawn xxxx > xxxx48 xxxx > xxxx48 x+++ > x+++59 + = tile with object drawn xxx > xxx37 x++ > x++37 x++O > x++28. digit = draw order x+O > x+16 x+O > x+16 x+OO > x+13. o = object yet to draw x? > x25 x? > x25 x? > x47. ? = current position So, if we encounter a 2-tile (on x axis) object in the next position (x-1, y+1) then we must first draw tile (x-1,y+1), and then draw our tile, and then skip drawing next tile (as we have already drawn it!) If we encounter a 3-tile (on x axis) object in the position (x-1,y+2) then we must first draw (x-1,y+1), then (x-2,y+2), then (x-1,y+2), then draw our tile, and then skip drawing next two tiles (as we have already drawn it) and skip drawing the tile (x-1, y+2) on the next row This is done best by having a set of Vec3<int>'s, and "skip next X tiles" variable. When encountering a 2-tile object, we increment "skip next X tiles" by 1. When encountering a 3-tile object, we increment "skip next X tiles" by 2, and we add (x-1, y+2) to the set. When trying to draw a tile we first check the "skip next X tiles" variable, if > 0 we decrement and continue. Second, we check if our tile is in the set. If so, we remove from set and continue. Third, we draw normally */ // FIXME: A different drawing algorithm is required for battle's strategic view /* First, draw everything except units and items Then, draw items only on current z-level Then, draw agents, bottom to top, drawing hollow sprites for non-current levels */
35.890116
96
0.567219
[ "render", "object" ]
cd43002c1d4cd4682524fc088a6afea728dced69
1,076
cpp
C++
1. OOP/04. Inheritance/fig_12_17_final/main.cpp
oneonlee/Computer-Science
4a3e2bf92986b5db3967d788832bca353fe71e61
[ "MIT" ]
1
2021-10-19T20:06:55.000Z
2021-10-19T20:06:55.000Z
1. OOP/04. Inheritance/fig_12_17_final/main.cpp
oneonlee/Computer-Science
4a3e2bf92986b5db3967d788832bca353fe71e61
[ "MIT" ]
null
null
null
1. OOP/04. Inheritance/fig_12_17_final/main.cpp
oneonlee/Computer-Science
4a3e2bf92986b5db3967d788832bca353fe71e61
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> using namespace std; #include "BasePlusCommissionEmployee.h" int main() { // instantiate BasePlusCommissionEmployee object BasePlusCommissionEmployee employee("Bob", "Lewis", "333-33-3333", 5000, .04, 300); cout << fixed << setprecision(2); cout << "Employee information obtained by get function: \n" << "\nFirst name is " << employee.getFirstName() << "\nLast name is " << employee.getLastName() << "\nsocial security number is " << employee.getSocialSecurityNumber() << "\nGross sales is " << employee.getGrossSales() << "\ncommission rate is " << employee.getCommissionRate() << "\nBase salary is " << employee.getBaseSalary() << endl; employee.setGrossSales(1000); // employee.setGrossSales(8000); // employee.setCommissionRate(.1); cout << "\nUpdated employee information ouput bt print function: \n" << endl; employee.print(); cout << "\n\nEmployee's earning: $" << employee.earnings() << endl; return 0; }
29.888889
80
0.6329
[ "object" ]
cd4d68d08af12de8fe8841d058210f238e280408
117,276
cpp
C++
B2G/gecko/dom/workers/WorkerPrivate.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/dom/workers/WorkerPrivate.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/dom/workers/WorkerPrivate.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "WorkerPrivate.h" #include "mozIThirdPartyUtil.h" #include "nsIClassInfo.h" #include "nsIContentSecurityPolicy.h" #include "nsIConsoleService.h" #include "nsIDOMFile.h" #include "nsIDocument.h" #include "nsIDocShell.h" #include "nsIJSContextStack.h" #include "nsIMemoryReporter.h" #include "nsIPermissionManager.h" #include "nsIScriptError.h" #include "nsIScriptGlobalObject.h" #include "nsIScriptSecurityManager.h" #include "nsPIDOMWindow.h" #include "nsITextToSubURI.h" #include "nsITimer.h" #include "nsIURI.h" #include "nsIURL.h" #include "nsIXPConnect.h" #include "nsIXPCScriptNotify.h" #include "jsfriendapi.h" #include "jsdbgapi.h" #include "jsfriendapi.h" #include "jsprf.h" #include "js/MemoryMetrics.h" #include "nsAlgorithm.h" #include "nsContentUtils.h" #include "nsError.h" #include "nsDOMJSUtils.h" #include "nsGUIEvent.h" #include "nsJSEnvironment.h" #include "nsJSUtils.h" #include "nsNetUtil.h" #include "nsSandboxFlags.h" #include "nsThreadUtils.h" #include "xpcpublic.h" #include "mozilla/Attributes.h" #ifdef ANDROID #include <android/log.h> #endif #include "Events.h" #include "Exceptions.h" #include "File.h" #include "ImageData.h" #include "Principal.h" #include "RuntimeService.h" #include "ScriptLoader.h" #include "Worker.h" #include "WorkerFeature.h" #include "WorkerScope.h" #if 0 // Define to run GC more often. #define EXTRA_GC #endif // GC will run once every thirty seconds during normal execution. #define NORMAL_GC_TIMER_DELAY_MS 5000 // GC will run five seconds after the last event is processed. #define IDLE_GC_TIMER_DELAY_MS 2000 using mozilla::MutexAutoLock; using mozilla::TimeDuration; using mozilla::TimeStamp; using mozilla::dom::workers::exceptions::ThrowDOMExceptionForNSResult; USING_WORKERS_NAMESPACE using namespace mozilla::dom::workers::events; using namespace mozilla::dom; NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(JsWorkerMallocSizeOf, "js-worker") namespace { const char gErrorChars[] = "error"; const char gMessageChars[] = "message"; template <class T> class AutoPtrComparator { typedef nsAutoPtr<T> A; typedef T* B; public: bool Equals(const A& a, const B& b) const { return a && b ? *a == *b : !a && !b ? true : false; } bool LessThan(const A& a, const B& b) const { return a && b ? *a < *b : b ? true : false; } }; template <class T> inline AutoPtrComparator<T> GetAutoPtrComparator(const nsTArray<nsAutoPtr<T> >&) { return AutoPtrComparator<T>(); } // Specialize this if there's some class that has multiple nsISupports bases. template <class T> struct ISupportsBaseInfo { typedef T ISupportsBase; }; template <template <class> class SmartPtr, class T> inline void SwapToISupportsArray(SmartPtr<T>& aSrc, nsTArray<nsCOMPtr<nsISupports> >& aDest) { nsCOMPtr<nsISupports>* dest = aDest.AppendElement(); T* raw = nullptr; aSrc.swap(raw); nsISupports* rawSupports = static_cast<typename ISupportsBaseInfo<T>::ISupportsBase*>(raw); dest->swap(rawSupports); } struct WorkerStructuredCloneCallbacks { static JSObject* Read(JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag, uint32_t aData, void* aClosure) { // See if object is a nsIDOMFile pointer. if (aTag == DOMWORKER_SCTAG_FILE) { JS_ASSERT(!aData); nsIDOMFile* file; if (JS_ReadBytes(aReader, &file, sizeof(file))) { JS_ASSERT(file); #ifdef DEBUG { // File should not be mutable. nsCOMPtr<nsIMutable> mutableFile = do_QueryInterface(file); bool isMutable; NS_ASSERTION(NS_SUCCEEDED(mutableFile->GetMutable(&isMutable)) && !isMutable, "Only immutable file should be passed to worker"); } #endif // nsIDOMFiles should be threadsafe, thus we will use the same instance // in the worker. JSObject* jsFile = file::CreateFile(aCx, file); return jsFile; } } // See if object is a nsIDOMBlob pointer. else if (aTag == DOMWORKER_SCTAG_BLOB) { JS_ASSERT(!aData); nsIDOMBlob* blob; if (JS_ReadBytes(aReader, &blob, sizeof(blob))) { JS_ASSERT(blob); #ifdef DEBUG { // Blob should not be mutable. nsCOMPtr<nsIMutable> mutableBlob = do_QueryInterface(blob); bool isMutable; NS_ASSERTION(NS_SUCCEEDED(mutableBlob->GetMutable(&isMutable)) && !isMutable, "Only immutable blob should be passed to worker"); } #endif // nsIDOMBlob should be threadsafe, thus we will use the same instance // in the worker. JSObject* jsBlob = file::CreateBlob(aCx, blob); return jsBlob; } } // See if the object is an ImageData. else if (aTag == SCTAG_DOM_IMAGEDATA) { JS_ASSERT(!aData); // Read the information out of the stream. uint32_t width, height; jsval dataArray; if (!JS_ReadUint32Pair(aReader, &width, &height) || !JS_ReadTypedArray(aReader, &dataArray)) { return nullptr; } MOZ_ASSERT(dataArray.isObject()); // Construct the ImageData. JSObject* obj = imagedata::Create(aCx, width, height, JSVAL_TO_OBJECT(dataArray)); return obj; } Error(aCx, 0); return nullptr; } static JSBool Write(JSContext* aCx, JSStructuredCloneWriter* aWriter, JSObject* aObj, void* aClosure) { NS_ASSERTION(aClosure, "Null pointer!"); // We'll stash any nsISupports pointers that need to be AddRef'd here. nsTArray<nsCOMPtr<nsISupports> >* clonedObjects = static_cast<nsTArray<nsCOMPtr<nsISupports> >*>(aClosure); // See if this is a File object. { nsIDOMFile* file = file::GetDOMFileFromJSObject(aObj); if (file) { if (JS_WriteUint32Pair(aWriter, DOMWORKER_SCTAG_FILE, 0) && JS_WriteBytes(aWriter, &file, sizeof(file))) { clonedObjects->AppendElement(file); return true; } } } // See if this is a Blob object. { nsIDOMBlob* blob = file::GetDOMBlobFromJSObject(aObj); if (blob) { nsCOMPtr<nsIMutable> mutableBlob = do_QueryInterface(blob); if (mutableBlob && NS_SUCCEEDED(mutableBlob->SetMutable(false)) && JS_WriteUint32Pair(aWriter, DOMWORKER_SCTAG_BLOB, 0) && JS_WriteBytes(aWriter, &blob, sizeof(blob))) { clonedObjects->AppendElement(blob); return true; } } } // See if this is an ImageData object. if (imagedata::IsImageData(aObj)) { // Pull the properties off the object. uint32_t width = imagedata::GetWidth(aObj); uint32_t height = imagedata::GetHeight(aObj); JSObject* data = imagedata::GetData(aObj); // Write the structured clone. return JS_WriteUint32Pair(aWriter, SCTAG_DOM_IMAGEDATA, 0) && JS_WriteUint32Pair(aWriter, width, height) && JS_WriteTypedArray(aWriter, OBJECT_TO_JSVAL(data)); } Error(aCx, 0); return false; } static void Error(JSContext* aCx, uint32_t /* aErrorId */) { ThrowDOMExceptionForNSResult(aCx, NS_ERROR_DOM_DATA_CLONE_ERR); } }; JSStructuredCloneCallbacks gWorkerStructuredCloneCallbacks = { WorkerStructuredCloneCallbacks::Read, WorkerStructuredCloneCallbacks::Write, WorkerStructuredCloneCallbacks::Error }; struct MainThreadWorkerStructuredCloneCallbacks { static JSObject* Read(JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag, uint32_t aData, void* aClosure) { AssertIsOnMainThread(); // See if object is a nsIDOMFile pointer. if (aTag == DOMWORKER_SCTAG_FILE) { JS_ASSERT(!aData); nsIDOMFile* file; if (JS_ReadBytes(aReader, &file, sizeof(file))) { JS_ASSERT(file); #ifdef DEBUG { // File should not be mutable. nsCOMPtr<nsIMutable> mutableFile = do_QueryInterface(file); bool isMutable; NS_ASSERTION(NS_SUCCEEDED(mutableFile->GetMutable(&isMutable)) && !isMutable, "Only immutable file should be passed to worker"); } #endif // nsIDOMFiles should be threadsafe, thus we will use the same instance // on the main thread. jsval wrappedFile; nsresult rv = nsContentUtils::WrapNative(aCx, JS_GetGlobalForScopeChain(aCx), file, &NS_GET_IID(nsIDOMFile), &wrappedFile); if (NS_FAILED(rv)) { Error(aCx, DATA_CLONE_ERR); return nullptr; } return JSVAL_TO_OBJECT(wrappedFile); } } // See if object is a nsIDOMBlob pointer. else if (aTag == DOMWORKER_SCTAG_BLOB) { JS_ASSERT(!aData); nsIDOMBlob* blob; if (JS_ReadBytes(aReader, &blob, sizeof(blob))) { JS_ASSERT(blob); #ifdef DEBUG { // Blob should not be mutable. nsCOMPtr<nsIMutable> mutableBlob = do_QueryInterface(blob); bool isMutable; NS_ASSERTION(NS_SUCCEEDED(mutableBlob->GetMutable(&isMutable)) && !isMutable, "Only immutable blob should be passed to worker"); } #endif // nsIDOMBlobs should be threadsafe, thus we will use the same instance // on the main thread. jsval wrappedBlob; nsresult rv = nsContentUtils::WrapNative(aCx, JS_GetGlobalForScopeChain(aCx), blob, &NS_GET_IID(nsIDOMBlob), &wrappedBlob); if (NS_FAILED(rv)) { Error(aCx, DATA_CLONE_ERR); return nullptr; } return JSVAL_TO_OBJECT(wrappedBlob); } } JS_ClearPendingException(aCx); return NS_DOMReadStructuredClone(aCx, aReader, aTag, aData, nullptr); } static JSBool Write(JSContext* aCx, JSStructuredCloneWriter* aWriter, JSObject* aObj, void* aClosure) { AssertIsOnMainThread(); NS_ASSERTION(aClosure, "Null pointer!"); // We'll stash any nsISupports pointers that need to be AddRef'd here. nsTArray<nsCOMPtr<nsISupports> >* clonedObjects = static_cast<nsTArray<nsCOMPtr<nsISupports> >*>(aClosure); // See if this is a wrapped native. nsCOMPtr<nsIXPConnectWrappedNative> wrappedNative; nsContentUtils::XPConnect()-> GetWrappedNativeOfJSObject(aCx, aObj, getter_AddRefs(wrappedNative)); if (wrappedNative) { // Get the raw nsISupports out of it. nsISupports* wrappedObject = wrappedNative->Native(); NS_ASSERTION(wrappedObject, "Null pointer?!"); nsISupports* ccISupports = nullptr; wrappedObject->QueryInterface(NS_GET_IID(nsCycleCollectionISupports), reinterpret_cast<void**>(&ccISupports)); if (ccISupports) { NS_WARNING("Cycle collected objects are not supported!"); } else { // See if the wrapped native is a nsIDOMFile. nsCOMPtr<nsIDOMFile> file = do_QueryInterface(wrappedObject); if (file) { nsCOMPtr<nsIMutable> mutableFile = do_QueryInterface(file); if (mutableFile && NS_SUCCEEDED(mutableFile->SetMutable(false))) { nsIDOMFile* filePtr = file; if (JS_WriteUint32Pair(aWriter, DOMWORKER_SCTAG_FILE, 0) && JS_WriteBytes(aWriter, &filePtr, sizeof(filePtr))) { clonedObjects->AppendElement(file); return true; } } } // See if the wrapped native is a nsIDOMBlob. nsCOMPtr<nsIDOMBlob> blob = do_QueryInterface(wrappedObject); if (blob) { nsCOMPtr<nsIMutable> mutableBlob = do_QueryInterface(blob); if (mutableBlob && NS_SUCCEEDED(mutableBlob->SetMutable(false))) { nsIDOMBlob* blobPtr = blob; if (JS_WriteUint32Pair(aWriter, DOMWORKER_SCTAG_BLOB, 0) && JS_WriteBytes(aWriter, &blobPtr, sizeof(blobPtr))) { clonedObjects->AppendElement(blob); return true; } } } } } JS_ClearPendingException(aCx); return NS_DOMWriteStructuredClone(aCx, aWriter, aObj, nullptr); } static void Error(JSContext* aCx, uint32_t aErrorId) { AssertIsOnMainThread(); NS_DOMStructuredCloneError(aCx, aErrorId); } }; JSStructuredCloneCallbacks gMainThreadWorkerStructuredCloneCallbacks = { MainThreadWorkerStructuredCloneCallbacks::Read, MainThreadWorkerStructuredCloneCallbacks::Write, MainThreadWorkerStructuredCloneCallbacks::Error }; struct ChromeWorkerStructuredCloneCallbacks { static JSObject* Read(JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag, uint32_t aData, void* aClosure) { return WorkerStructuredCloneCallbacks::Read(aCx, aReader, aTag, aData, aClosure); } static JSBool Write(JSContext* aCx, JSStructuredCloneWriter* aWriter, JSObject* aObj, void* aClosure) { return WorkerStructuredCloneCallbacks::Write(aCx, aWriter, aObj, aClosure); } static void Error(JSContext* aCx, uint32_t aErrorId) { return WorkerStructuredCloneCallbacks::Error(aCx, aErrorId); } }; JSStructuredCloneCallbacks gChromeWorkerStructuredCloneCallbacks = { ChromeWorkerStructuredCloneCallbacks::Read, ChromeWorkerStructuredCloneCallbacks::Write, ChromeWorkerStructuredCloneCallbacks::Error }; struct MainThreadChromeWorkerStructuredCloneCallbacks { static JSObject* Read(JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag, uint32_t aData, void* aClosure) { AssertIsOnMainThread(); JSObject* clone = MainThreadWorkerStructuredCloneCallbacks::Read(aCx, aReader, aTag, aData, aClosure); if (clone) { return clone; } clone = ChromeWorkerStructuredCloneCallbacks::Read(aCx, aReader, aTag, aData, aClosure); if (clone) { return clone; } JS_ClearPendingException(aCx); return NS_DOMReadStructuredClone(aCx, aReader, aTag, aData, nullptr); } static JSBool Write(JSContext* aCx, JSStructuredCloneWriter* aWriter, JSObject* aObj, void* aClosure) { AssertIsOnMainThread(); if (MainThreadWorkerStructuredCloneCallbacks::Write(aCx, aWriter, aObj, aClosure) || ChromeWorkerStructuredCloneCallbacks::Write(aCx, aWriter, aObj, aClosure) || NS_DOMWriteStructuredClone(aCx, aWriter, aObj, nullptr)) { return true; } return false; } static void Error(JSContext* aCx, uint32_t aErrorId) { AssertIsOnMainThread(); NS_DOMStructuredCloneError(aCx, aErrorId); } }; JSStructuredCloneCallbacks gMainThreadChromeWorkerStructuredCloneCallbacks = { MainThreadChromeWorkerStructuredCloneCallbacks::Read, MainThreadChromeWorkerStructuredCloneCallbacks::Write, MainThreadChromeWorkerStructuredCloneCallbacks::Error }; class MainThreadReleaseRunnable : public nsRunnable { nsCOMPtr<nsIThread> mThread; nsTArray<nsCOMPtr<nsISupports> > mDoomed; public: MainThreadReleaseRunnable(nsCOMPtr<nsIThread>& aThread, nsTArray<nsCOMPtr<nsISupports> >& aDoomed) { mThread.swap(aThread); mDoomed.SwapElements(aDoomed); } MainThreadReleaseRunnable(nsTArray<nsCOMPtr<nsISupports> >& aDoomed) { mDoomed.SwapElements(aDoomed); } NS_IMETHOD Run() { mDoomed.Clear(); if (mThread) { RuntimeService* runtime = RuntimeService::GetService(); NS_ASSERTION(runtime, "This should never be null!"); runtime->NoteIdleThread(mThread); } return NS_OK; } }; class WorkerFinishedRunnable : public WorkerControlRunnable { WorkerPrivate* mFinishedWorker; nsCOMPtr<nsIThread> mThread; public: WorkerFinishedRunnable(WorkerPrivate* aWorkerPrivate, WorkerPrivate* aFinishedWorker, nsIThread* aFinishedThread) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount), mFinishedWorker(aFinishedWorker), mThread(aFinishedThread) { } bool PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // Silence bad assertions. return true; } void PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aDispatchResult) { // Silence bad assertions. } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { nsTArray<nsCOMPtr<nsISupports> > doomed; mFinishedWorker->ForgetMainThreadObjects(doomed); nsRefPtr<MainThreadReleaseRunnable> runnable = new MainThreadReleaseRunnable(mThread, doomed); if (NS_FAILED(NS_DispatchToMainThread(runnable, NS_DISPATCH_NORMAL))) { NS_WARNING("Failed to dispatch, going to leak!"); } mFinishedWorker->Finish(aCx); RuntimeService* runtime = RuntimeService::GetService(); NS_ASSERTION(runtime, "This should never be null!"); runtime->UnregisterWorker(aCx, mFinishedWorker); mFinishedWorker->Release(); return true; } }; class TopLevelWorkerFinishedRunnable : public nsRunnable { WorkerPrivate* mFinishedWorker; nsCOMPtr<nsIThread> mThread; public: TopLevelWorkerFinishedRunnable(WorkerPrivate* aFinishedWorker, nsIThread* aFinishedThread) : mFinishedWorker(aFinishedWorker), mThread(aFinishedThread) { aFinishedWorker->AssertIsOnWorkerThread(); } NS_IMETHOD Run() { AssertIsOnMainThread(); RuntimeService::AutoSafeJSContext cx; mFinishedWorker->Finish(cx); RuntimeService* runtime = RuntimeService::GetService(); NS_ASSERTION(runtime, "This should never be null!"); runtime->UnregisterWorker(cx, mFinishedWorker); nsTArray<nsCOMPtr<nsISupports> > doomed; mFinishedWorker->ForgetMainThreadObjects(doomed); nsRefPtr<MainThreadReleaseRunnable> runnable = new MainThreadReleaseRunnable(doomed); if (NS_FAILED(NS_DispatchToCurrentThread(runnable))) { NS_WARNING("Failed to dispatch, going to leak!"); } if (mThread) { runtime->NoteIdleThread(mThread); } mFinishedWorker->Release(); return NS_OK; } }; class ModifyBusyCountRunnable : public WorkerControlRunnable { bool mIncrease; public: ModifyBusyCountRunnable(WorkerPrivate* aWorkerPrivate, bool aIncrease) : WorkerControlRunnable(aWorkerPrivate, ParentThread, UnchangedBusyCount), mIncrease(aIncrease) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { return aWorkerPrivate->ModifyBusyCount(aCx, mIncrease); } void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult) { if (mIncrease) { WorkerControlRunnable::PostRun(aCx, aWorkerPrivate, aRunResult); return; } // Don't do anything here as it's possible that aWorkerPrivate has been // deleted. } }; class CompileScriptRunnable : public WorkerRunnable { public: CompileScriptRunnable(WorkerPrivate* aWorkerPrivate) : WorkerRunnable(aWorkerPrivate, WorkerThread, ModifyBusyCount, SkipWhenClearing) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { JSObject* global = CreateDedicatedWorkerGlobalScope(aCx); if (!global) { NS_WARNING("Failed to make global!"); return false; } JSAutoCompartment ac(aCx, global); JS_SetGlobalObject(aCx, global); return scriptloader::LoadWorkerScript(aCx); } }; class CloseEventRunnable : public WorkerRunnable { public: CloseEventRunnable(WorkerPrivate* aWorkerPrivate) : WorkerRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount, SkipWhenClearing) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { JSObject* target = JS_GetGlobalObject(aCx); NS_ASSERTION(target, "This must never be null!"); aWorkerPrivate->CloseHandlerStarted(); JSString* type = JS_InternString(aCx, "close"); if (!type) { return false; } JSObject* event = CreateGenericEvent(aCx, type, false, false, false); if (!event) { return false; } bool ignored; return DispatchEventToTarget(aCx, target, event, &ignored); } void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult) { // Report errors. WorkerRunnable::PostRun(aCx, aWorkerPrivate, aRunResult); // Match the busy count increase from NotifyRunnable. if (!aWorkerPrivate->ModifyBusyCountFromWorker(aCx, false)) { JS_ReportPendingException(aCx); } aWorkerPrivate->CloseHandlerFinished(); } }; class MessageEventRunnable : public WorkerRunnable { uint64_t* mData; size_t mDataByteCount; nsTArray<nsCOMPtr<nsISupports> > mClonedObjects; public: MessageEventRunnable(WorkerPrivate* aWorkerPrivate, Target aTarget, JSAutoStructuredCloneBuffer& aData, nsTArray<nsCOMPtr<nsISupports> >& aClonedObjects) : WorkerRunnable(aWorkerPrivate, aTarget, aTarget == WorkerThread ? ModifyBusyCount : UnchangedBusyCount, SkipWhenClearing) { aData.steal(&mData, &mDataByteCount); if (!mClonedObjects.SwapElements(aClonedObjects)) { NS_ERROR("This should never fail!"); } } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { JSAutoStructuredCloneBuffer buffer; buffer.adopt(mData, mDataByteCount); mData = nullptr; mDataByteCount = 0; bool mainRuntime; JSObject* target; if (mTarget == ParentThread) { // Don't fire this event if the JS object has been disconnected from the // private object. if (!aWorkerPrivate->IsAcceptingEvents()) { return true; } mainRuntime = !aWorkerPrivate->GetParent(); target = aWorkerPrivate->GetJSObject(); NS_ASSERTION(target, "Must have a target!"); if (aWorkerPrivate->IsSuspended()) { aWorkerPrivate->QueueRunnable(this); buffer.steal(&mData, &mDataByteCount); return true; } aWorkerPrivate->AssertInnerWindowIsCorrect(); } else { NS_ASSERTION(aWorkerPrivate == GetWorkerPrivateFromContext(aCx), "Badness!"); mainRuntime = false; target = JS_GetGlobalObject(aCx); } NS_ASSERTION(target, "This should never be null!"); JSObject* event = CreateMessageEvent(aCx, buffer, mClonedObjects, mainRuntime); if (!event) { return false; } bool dummy; return DispatchEventToTarget(aCx, target, event, &dummy); } void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult) { // Notify before WorkerRunnable::PostRun, since that can kill aWorkerPrivate NotifyScriptExecutedIfNeeded(); WorkerRunnable::PostRun(aCx, aWorkerPrivate, aRunResult); } }; class NotifyRunnable : public WorkerControlRunnable { Status mStatus; public: NotifyRunnable(WorkerPrivate* aWorkerPrivate, Status aStatus) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount), mStatus(aStatus) { NS_ASSERTION(aStatus == Terminating || aStatus == Canceling || aStatus == Killing, "Bad status!"); } bool PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // Modify here, but not in PostRun! This busy count addition will be matched // by the CloseEventRunnable. return aWorkerPrivate->ModifyBusyCount(aCx, true); } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { return aWorkerPrivate->NotifyInternal(aCx, mStatus); } }; class CloseRunnable MOZ_FINAL : public WorkerControlRunnable { public: CloseRunnable(WorkerPrivate* aWorkerPrivate) : WorkerControlRunnable(aWorkerPrivate, ParentThread, UnchangedBusyCount) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // This busy count will be matched by the CloseEventRunnable. return aWorkerPrivate->ModifyBusyCount(aCx, true) && aWorkerPrivate->Close(aCx); } }; class SuspendRunnable : public WorkerControlRunnable { public: SuspendRunnable(WorkerPrivate* aWorkerPrivate) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { return aWorkerPrivate->SuspendInternal(aCx); } }; class ResumeRunnable : public WorkerControlRunnable { public: ResumeRunnable(WorkerPrivate* aWorkerPrivate) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { return aWorkerPrivate->ResumeInternal(aCx); } }; class ReportErrorRunnable : public WorkerRunnable { nsString mMessage; nsString mFilename; nsString mLine; uint32_t mLineNumber; uint32_t mColumnNumber; uint32_t mFlags; uint32_t mErrorNumber; public: ReportErrorRunnable(WorkerPrivate* aWorkerPrivate, const nsString& aMessage, const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber, uint32_t aColumnNumber, uint32_t aFlags, uint32_t aErrorNumber) : WorkerRunnable(aWorkerPrivate, ParentThread, UnchangedBusyCount, SkipWhenClearing), mMessage(aMessage), mFilename(aFilename), mLine(aLine), mLineNumber(aLineNumber), mColumnNumber(aColumnNumber), mFlags(aFlags), mErrorNumber(aErrorNumber) { } void PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aDispatchResult) { aWorkerPrivate->AssertIsOnWorkerThread(); // Dispatch may fail if the worker was canceled, no need to report that as // an error, so don't call base class PostDispatch. } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { JSObject* target = aWorkerPrivate->IsAcceptingEvents() ? aWorkerPrivate->GetJSObject() : nullptr; uint64_t innerWindowId; WorkerPrivate* parent = aWorkerPrivate->GetParent(); if (parent) { innerWindowId = 0; } else { AssertIsOnMainThread(); if (aWorkerPrivate->IsSuspended()) { aWorkerPrivate->QueueRunnable(this); return true; } aWorkerPrivate->AssertInnerWindowIsCorrect(); innerWindowId = aWorkerPrivate->GetInnerWindowId(); } return ReportErrorRunnable::ReportError(aCx, parent, true, target, mMessage, mFilename, mLine, mLineNumber, mColumnNumber, mFlags, mErrorNumber, innerWindowId); } void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult) { // Notify before WorkerRunnable::PostRun, since that can kill aWorkerPrivate NotifyScriptExecutedIfNeeded(); WorkerRunnable::PostRun(aCx, aWorkerPrivate, aRunResult); } static bool ReportError(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aFireAtScope, JSObject* aTarget, const nsString& aMessage, const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber, uint32_t aColumnNumber, uint32_t aFlags, uint32_t aErrorNumber, uint64_t aInnerWindowId) { if (aWorkerPrivate) { aWorkerPrivate->AssertIsOnWorkerThread(); } else { AssertIsOnMainThread(); } JSString* message = JS_NewUCStringCopyN(aCx, aMessage.get(), aMessage.Length()); if (!message) { return false; } JSString* filename = JS_NewUCStringCopyN(aCx, aFilename.get(), aFilename.Length()); if (!filename) { return false; } // First fire an ErrorEvent at the worker. if (aTarget) { JSObject* event = CreateErrorEvent(aCx, message, filename, aLineNumber, !aWorkerPrivate); if (!event) { return false; } bool preventDefaultCalled; if (!DispatchEventToTarget(aCx, aTarget, event, &preventDefaultCalled)) { return false; } if (preventDefaultCalled) { return true; } } // Now fire an event at the global object, but don't do that if the error // code is too much recursion and this is the same script threw the error. if (aFireAtScope && (aTarget || aErrorNumber != JSMSG_OVER_RECURSED)) { aTarget = JS_GetGlobalForScopeChain(aCx); NS_ASSERTION(aTarget, "This should never be null!"); bool preventDefaultCalled; nsIScriptGlobalObject* sgo; if (aWorkerPrivate || !(sgo = nsJSUtils::GetStaticScriptGlobal(aCx, aTarget))) { // Fire a normal ErrorEvent if we're running on a worker thread. JSObject* event = CreateErrorEvent(aCx, message, filename, aLineNumber, false); if (!event) { return false; } if (!DispatchEventToTarget(aCx, aTarget, event, &preventDefaultCalled)) { return false; } } else { // Icky, we have to fire an nsScriptErrorEvent... nsScriptErrorEvent event(true, NS_LOAD_ERROR); event.lineNr = aLineNumber; event.errorMsg = aMessage.get(); event.fileName = aFilename.get(); nsEventStatus status = nsEventStatus_eIgnore; if (NS_FAILED(sgo->HandleScriptError(&event, &status))) { NS_WARNING("Failed to dispatch main thread error event!"); status = nsEventStatus_eIgnore; } preventDefaultCalled = status == nsEventStatus_eConsumeNoDefault; } if (preventDefaultCalled) { return true; } } // Now fire a runnable to do the same on the parent's thread if we can. if (aWorkerPrivate) { nsRefPtr<ReportErrorRunnable> runnable = new ReportErrorRunnable(aWorkerPrivate, aMessage, aFilename, aLine, aLineNumber, aColumnNumber, aFlags, aErrorNumber); return runnable->Dispatch(aCx); } // Otherwise log an error to the error console. nsCOMPtr<nsIScriptError> scriptError = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID); NS_WARN_IF_FALSE(scriptError, "Failed to create script error!"); if (scriptError) { if (NS_FAILED(scriptError->InitWithWindowID(aMessage, aFilename, aLine, aLineNumber, aColumnNumber, aFlags, "Web Worker", aInnerWindowId))) { NS_WARNING("Failed to init script error!"); scriptError = nullptr; } } nsCOMPtr<nsIConsoleService> consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID); NS_WARN_IF_FALSE(consoleService, "Failed to get console service!"); bool logged = false; if (consoleService) { if (scriptError) { if (NS_SUCCEEDED(consoleService->LogMessage(scriptError))) { logged = true; } else { NS_WARNING("Failed to log script error!"); } } else if (NS_SUCCEEDED(consoleService->LogStringMessage(aMessage.get()))) { logged = true; } else { NS_WARNING("Failed to log script error!"); } } if (!logged) { NS_ConvertUTF16toUTF8 msg(aMessage); #ifdef ANDROID __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", msg.get()); #endif fputs(msg.get(), stderr); fflush(stderr); } return true; } }; class TimerRunnable : public WorkerRunnable { public: TimerRunnable(WorkerPrivate* aWorkerPrivate) : WorkerRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount, SkipWhenClearing) { } bool PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // Silence bad assertions. return true; } void PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aDispatchResult) { // Silence bad assertions. } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { return aWorkerPrivate->RunExpiredTimeouts(aCx); } }; void DummyCallback(nsITimer* aTimer, void* aClosure) { // Nothing! } class WorkerRunnableEventTarget MOZ_FINAL : public nsIEventTarget { protected: nsRefPtr<WorkerRunnable> mWorkerRunnable; public: WorkerRunnableEventTarget(WorkerRunnable* aWorkerRunnable) : mWorkerRunnable(aWorkerRunnable) { } NS_DECL_ISUPPORTS NS_IMETHOD Dispatch(nsIRunnable* aRunnable, uint32_t aFlags) { NS_ASSERTION(aFlags == nsIEventTarget::DISPATCH_NORMAL, "Don't call me!"); nsRefPtr<WorkerRunnableEventTarget> kungFuDeathGrip = this; // Run the runnable we're given now (should just call DummyCallback()), // otherwise the timer thread will leak it... If we run this after // dispatch running the event can race against resetting the timer. aRunnable->Run(); // This can fail if we're racing to terminate or cancel, should be handled // by the terminate or cancel code. mWorkerRunnable->Dispatch(nullptr); return NS_OK; } NS_IMETHOD IsOnCurrentThread(bool* aIsOnCurrentThread) { *aIsOnCurrentThread = false; return NS_OK; } }; NS_IMPL_THREADSAFE_ISUPPORTS1(WorkerRunnableEventTarget, nsIEventTarget) class KillCloseEventRunnable : public WorkerRunnable { nsCOMPtr<nsITimer> mTimer; class KillScriptRunnable : public WorkerControlRunnable { public: KillScriptRunnable(WorkerPrivate* aWorkerPrivate) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount) { } bool PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // Silence bad assertions. return true; } void PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aDispatchResult) { // Silence bad assertions. } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // Kill running script. return false; } }; public: KillCloseEventRunnable(WorkerPrivate* aWorkerPrivate) : WorkerRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount, SkipWhenClearing) { } ~KillCloseEventRunnable() { if (mTimer) { mTimer->Cancel(); } } bool PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { NS_NOTREACHED("Not meant to be dispatched!"); return false; } bool SetTimeout(JSContext* aCx, uint32_t aDelayMS) { nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID); if (!timer) { JS_ReportError(aCx, "Failed to create timer!"); return false; } nsRefPtr<KillScriptRunnable> runnable = new KillScriptRunnable(mWorkerPrivate); nsRefPtr<WorkerRunnableEventTarget> target = new WorkerRunnableEventTarget(runnable); if (NS_FAILED(timer->SetTarget(target))) { JS_ReportError(aCx, "Failed to set timer's target!"); return false; } if (NS_FAILED(timer->InitWithFuncCallback(DummyCallback, nullptr, aDelayMS, nsITimer::TYPE_ONE_SHOT))) { JS_ReportError(aCx, "Failed to start timer!"); return false; } mTimer.swap(timer); return true; } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { if (mTimer) { mTimer->Cancel(); mTimer = nullptr; } return true; } }; class UpdateJSContextOptionsRunnable : public WorkerControlRunnable { uint32_t mOptions; public: UpdateJSContextOptionsRunnable(WorkerPrivate* aWorkerPrivate, uint32_t aOptions) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount), mOptions(aOptions) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { aWorkerPrivate->UpdateJSContextOptionsInternal(aCx, mOptions); return true; } }; class UpdateJSWorkerMemoryParameterRunnable : public WorkerControlRunnable { uint32_t mValue; JSGCParamKey mKey; public: UpdateJSWorkerMemoryParameterRunnable(WorkerPrivate* aWorkerPrivate, JSGCParamKey aKey, uint32_t aValue) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount), mValue(aValue), mKey(aKey) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { aWorkerPrivate->UpdateJSWorkerMemoryParameterInternal(aCx, mKey, mValue); return true; } }; #ifdef JS_GC_ZEAL class UpdateGCZealRunnable : public WorkerControlRunnable { uint8_t mGCZeal; public: UpdateGCZealRunnable(WorkerPrivate* aWorkerPrivate, uint8_t aGCZeal) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount), mGCZeal(aGCZeal) { } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { aWorkerPrivate->UpdateGCZealInternal(aCx, mGCZeal); return true; } }; #endif class GarbageCollectRunnable : public WorkerControlRunnable { protected: bool mShrinking; bool mCollectChildren; public: GarbageCollectRunnable(WorkerPrivate* aWorkerPrivate, bool aShrinking, bool aCollectChildren) : WorkerControlRunnable(aWorkerPrivate, WorkerThread, UnchangedBusyCount), mShrinking(aShrinking), mCollectChildren(aCollectChildren) { } bool PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { // Silence bad assertions, this can be dispatched from either the main // thread or the timer thread.. return true; } void PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aDispatchResult) { // Silence bad assertions, this can be dispatched from either the main // thread or the timer thread.. } bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { aWorkerPrivate->GarbageCollectInternal(aCx, mShrinking, mCollectChildren); return true; } }; class WorkerJSRuntimeStats : public JS::RuntimeStats { const nsACString& mRtPath; public: WorkerJSRuntimeStats(const nsACString& aRtPath) : JS::RuntimeStats(JsWorkerMallocSizeOf), mRtPath(aRtPath) { } ~WorkerJSRuntimeStats() { for (size_t i = 0; i != compartmentStatsVector.length(); i++) { free(compartmentStatsVector[i].extra1); // No need to free |extra2| because it's a static string. } } virtual void initExtraCompartmentStats(JSCompartment* aCompartment, JS::CompartmentStats* aCompartmentStats) MOZ_OVERRIDE { MOZ_ASSERT(!aCompartmentStats->extra1); MOZ_ASSERT(!aCompartmentStats->extra2); // ReportJSRuntimeExplicitTreeStats expects that // aCompartmentStats->{extra1,extra2} are char pointers. // This is the |cJSPathPrefix|. Each worker has exactly two compartments: // one for atoms, and one for everything else. nsAutoCString cJSPathPrefix(mRtPath); cJSPathPrefix += js::IsAtomsCompartment(aCompartment) ? NS_LITERAL_CSTRING("compartment(web-worker-atoms)/") : NS_LITERAL_CSTRING("compartment(web-worker)/"); aCompartmentStats->extra1 = strdup(cJSPathPrefix.get()); // This should never be used when reporting with workers (hence the "?!"). static const char bogusMemoryReporterPath[] = "explicit/workers/?!/"; aCompartmentStats->extra2 = const_cast<char*>(bogusMemoryReporterPath); } }; } /* anonymous namespace */ #ifdef DEBUG void mozilla::dom::workers::AssertIsOnMainThread() { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); } WorkerRunnable::WorkerRunnable(WorkerPrivate* aWorkerPrivate, Target aTarget, BusyBehavior aBusyBehavior, ClearingBehavior aClearingBehavior) : mWorkerPrivate(aWorkerPrivate), mTarget(aTarget), mBusyBehavior(aBusyBehavior), mClearingBehavior(aClearingBehavior) { NS_ASSERTION(aWorkerPrivate, "Null worker private!"); } #endif NS_IMPL_THREADSAFE_ISUPPORTS1(WorkerRunnable, nsIRunnable) bool WorkerRunnable::PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) { #ifdef DEBUG if (mBusyBehavior == ModifyBusyCount) { NS_ASSERTION(mTarget == WorkerThread, "Don't set this option unless targeting the worker thread!"); } if (mTarget == ParentThread) { aWorkerPrivate->AssertIsOnWorkerThread(); } else { aWorkerPrivate->AssertIsOnParentThread(); } #endif if (mBusyBehavior == ModifyBusyCount && aCx) { return aWorkerPrivate->ModifyBusyCount(aCx, true); } return true; } bool WorkerRunnable::Dispatch(JSContext* aCx) { bool ok; if (!aCx) { ok = PreDispatch(nullptr, mWorkerPrivate); if (ok) { ok = DispatchInternal(); } PostDispatch(nullptr, mWorkerPrivate, ok); return ok; } JSAutoRequest ar(aCx); JSObject* global = JS_GetGlobalObject(aCx); Maybe<JSAutoCompartment> ac; if (global) { ac.construct(aCx, global); } ok = PreDispatch(aCx, mWorkerPrivate); if (ok && !DispatchInternal()) { ok = false; } PostDispatch(aCx, mWorkerPrivate, ok); return ok; } // static bool WorkerRunnable::DispatchToMainThread(nsIRunnable* aRunnable) { nsCOMPtr<nsIThread> mainThread = do_GetMainThread(); NS_ASSERTION(mainThread, "This should never fail!"); return NS_SUCCEEDED(mainThread->Dispatch(aRunnable, NS_DISPATCH_NORMAL)); } // These DispatchInternal functions look identical but carry important type // informaton so they can't be consolidated... #define IMPL_DISPATCH_INTERNAL(_class) \ bool \ _class ::DispatchInternal() \ { \ if (mTarget == WorkerThread) { \ return mWorkerPrivate->Dispatch(this); \ } \ \ if (mWorkerPrivate->GetParent()) { \ return mWorkerPrivate->GetParent()->Dispatch(this); \ } \ \ return DispatchToMainThread(this); \ } IMPL_DISPATCH_INTERNAL(WorkerRunnable) IMPL_DISPATCH_INTERNAL(WorkerSyncRunnable) IMPL_DISPATCH_INTERNAL(WorkerControlRunnable) #undef IMPL_DISPATCH_INTERNAL void WorkerRunnable::PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aDispatchResult) { #ifdef DEBUG if (mTarget == ParentThread) { aWorkerPrivate->AssertIsOnWorkerThread(); } else { aWorkerPrivate->AssertIsOnParentThread(); } #endif if (!aDispatchResult && aCx) { if (mBusyBehavior == ModifyBusyCount) { aWorkerPrivate->ModifyBusyCount(aCx, false); } JS_ReportPendingException(aCx); } } NS_IMETHODIMP WorkerRunnable::Run() { JSContext* cx; JSObject* targetCompartmentObject; nsIThreadJSContextStack* contextStack = nullptr; nsRefPtr<WorkerPrivate> kungFuDeathGrip; if (mTarget == WorkerThread) { mWorkerPrivate->AssertIsOnWorkerThread(); cx = mWorkerPrivate->GetJSContext(); targetCompartmentObject = JS_GetGlobalObject(cx); } else { kungFuDeathGrip = mWorkerPrivate; mWorkerPrivate->AssertIsOnParentThread(); cx = mWorkerPrivate->ParentJSContext(); targetCompartmentObject = mWorkerPrivate->GetJSObject(); if (!mWorkerPrivate->GetParent()) { AssertIsOnMainThread(); contextStack = nsContentUtils::ThreadJSContextStack(); NS_ASSERTION(contextStack, "This should never be null!"); if (NS_FAILED(contextStack->Push(cx))) { NS_WARNING("Failed to push context!"); contextStack = nullptr; } } } NS_ASSERTION(cx, "Must have a context!"); JSAutoRequest ar(cx); Maybe<JSAutoCompartment> ac; if (targetCompartmentObject) { ac.construct(cx, targetCompartmentObject); } bool result = WorkerRun(cx, mWorkerPrivate); PostRun(cx, mWorkerPrivate, result); if (contextStack) { JSContext* otherCx; if (NS_FAILED(contextStack->Pop(&otherCx))) { NS_WARNING("Failed to pop context!"); } else if (otherCx != cx) { NS_WARNING("Popped a different context!"); } } return result ? NS_OK : NS_ERROR_FAILURE; } void WorkerRunnable::PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult) { #ifdef DEBUG if (mTarget == ParentThread) { mWorkerPrivate->AssertIsOnParentThread(); } else { mWorkerPrivate->AssertIsOnWorkerThread(); } #endif if (mBusyBehavior == ModifyBusyCount) { if (!aWorkerPrivate->ModifyBusyCountFromWorker(aCx, false)) { aRunResult = false; } } if (!aRunResult) { JS_ReportPendingException(aCx); } } void WorkerRunnable::NotifyScriptExecutedIfNeeded() const { // if we're on the main thread notify about the end of our script execution. if (mTarget == ParentThread && !mWorkerPrivate->GetParent()) { AssertIsOnMainThread(); if (mWorkerPrivate->GetScriptNotify()) { mWorkerPrivate->GetScriptNotify()->ScriptExecuted(); } } } struct WorkerPrivate::TimeoutInfo { TimeoutInfo() : mTimeoutVal(JS::UndefinedValue()), mLineNumber(0), mId(0), mIsInterval(false), mCanceled(false) { MOZ_COUNT_CTOR(mozilla::dom::workers::WorkerPrivate::TimeoutInfo); } ~TimeoutInfo() { MOZ_COUNT_DTOR(mozilla::dom::workers::WorkerPrivate::TimeoutInfo); } bool operator==(const TimeoutInfo& aOther) { return mTargetTime == aOther.mTargetTime; } bool operator<(const TimeoutInfo& aOther) { return mTargetTime < aOther.mTargetTime; } JS::Value mTimeoutVal; nsTArray<jsval> mExtraArgVals; mozilla::TimeStamp mTargetTime; mozilla::TimeDuration mInterval; nsCString mFilename; uint32_t mLineNumber; uint32_t mId; bool mIsInterval; bool mCanceled; }; class WorkerPrivate::MemoryReporter MOZ_FINAL : public nsIMemoryMultiReporter { friend class WorkerPrivate; SharedMutex mMutex; WorkerPrivate* mWorkerPrivate; nsCString mRtPath; public: NS_DECL_ISUPPORTS MemoryReporter(WorkerPrivate* aWorkerPrivate) : mMutex(aWorkerPrivate->mMutex), mWorkerPrivate(aWorkerPrivate) { aWorkerPrivate->AssertIsOnWorkerThread(); nsCString escapedDomain(aWorkerPrivate->Domain()); escapedDomain.ReplaceChar('/', '\\'); NS_ConvertUTF16toUTF8 escapedURL(aWorkerPrivate->ScriptURL()); escapedURL.ReplaceChar('/', '\\'); nsAutoCString addressString; addressString.AppendPrintf("0x%p", static_cast<void*>(aWorkerPrivate)); mRtPath = NS_LITERAL_CSTRING("explicit/workers/workers(") + escapedDomain + NS_LITERAL_CSTRING(")/worker(") + escapedURL + NS_LITERAL_CSTRING(", ") + addressString + NS_LITERAL_CSTRING(")/"); } NS_IMETHOD GetName(nsACString& aName) { aName.AssignLiteral("workers"); return NS_OK; } NS_IMETHOD CollectReports(nsIMemoryMultiReporterCallback* aCallback, nsISupports* aClosure) { AssertIsOnMainThread(); WorkerJSRuntimeStats rtStats(mRtPath); { MutexAutoLock lock(mMutex); if (!mWorkerPrivate || !mWorkerPrivate->BlockAndCollectRuntimeStats(/* aIsQuick = */ false, &rtStats)) { // Returning NS_OK here will effectively report 0 memory. return NS_OK; } } return xpc::ReportJSRuntimeExplicitTreeStats(rtStats, mRtPath, aCallback, aClosure); } NS_IMETHOD GetExplicitNonHeap(int64_t* aAmount) { AssertIsOnMainThread(); { MutexAutoLock lock(mMutex); if (!mWorkerPrivate || !mWorkerPrivate->BlockAndCollectRuntimeStats(/* aIsQuick = */ true, aAmount)) { *aAmount = 0; } } return NS_OK; } private: ~MemoryReporter() { } void Disable() { // Called from WorkerPrivate::DisableMemoryReporter. mMutex.AssertCurrentThreadOwns(); NS_ASSERTION(mWorkerPrivate, "Disabled more than once!"); mWorkerPrivate = nullptr; } }; NS_IMPL_THREADSAFE_ISUPPORTS1(WorkerPrivate::MemoryReporter, nsIMemoryMultiReporter) template <class Derived> WorkerPrivateParent<Derived>::WorkerPrivateParent( JSContext* aCx, JSObject* aObject, WorkerPrivate* aParent, JSContext* aParentJSContext, const nsAString& aScriptURL, bool aIsChromeWorker, const nsACString& aDomain, nsCOMPtr<nsPIDOMWindow>& aWindow, nsCOMPtr<nsIScriptContext>& aScriptContext, nsCOMPtr<nsIURI>& aBaseURI, nsCOMPtr<nsIPrincipal>& aPrincipal, nsCOMPtr<nsIContentSecurityPolicy>& aCSP, bool aEvalAllowed) : EventTarget(aParent ? aCx : NULL), mMutex("WorkerPrivateParent Mutex"), mCondVar(mMutex, "WorkerPrivateParent CondVar"), mMemoryReportCondVar(mMutex, "WorkerPrivateParent Memory Report CondVar"), mJSObject(aObject), mParent(aParent), mParentJSContext(aParentJSContext), mScriptURL(aScriptURL), mDomain(aDomain), mBusyCount(0), mParentStatus(Pending), mJSContextOptions(0), mGCZeal(0), mJSObjectRooted(false), mParentSuspended(false), mIsChromeWorker(aIsChromeWorker), mPrincipalIsSystem(false), mMainThreadObjectsForgotten(false), mEvalAllowed(aEvalAllowed) { MOZ_COUNT_CTOR(mozilla::dom::workers::WorkerPrivateParent); if (aWindow) { NS_ASSERTION(aWindow->IsInnerWindow(), "Should have inner window here!"); } mWindow.swap(aWindow); mScriptContext.swap(aScriptContext); mScriptNotify = do_QueryInterface(mScriptContext); mBaseURI.swap(aBaseURI); mPrincipal.swap(aPrincipal); mCSP.swap(aCSP); if (aParent) { aParent->AssertIsOnWorkerThread(); NS_ASSERTION(JS_GetOptions(aCx) == aParent->GetJSContextOptions(), "Options mismatch!"); mJSContextOptions = aParent->GetJSContextOptions(); aParent->GetMemoryParameters(mMemoryParams); #ifdef JS_GC_ZEAL mGCZeal = aParent->GetGCZeal(); #endif } else { AssertIsOnMainThread(); mJSContextOptions = RuntimeService::GetDefaultJSContextOptions(); RuntimeService::GetDefaultMemoryParameters(mMemoryParams); #ifdef JS_GC_ZEAL mGCZeal = RuntimeService::GetDefaultGCZeal(); #endif } } template <class Derived> WorkerPrivateParent<Derived>::~WorkerPrivateParent() { MOZ_COUNT_DTOR(mozilla::dom::workers::WorkerPrivateParent); } template <class Derived> bool WorkerPrivateParent<Derived>::Start() { // May be called on any thread! { MutexAutoLock lock(mMutex); NS_ASSERTION(mParentStatus != Running, "How can this be?!"); if (mParentStatus == Pending) { mParentStatus = Running; return true; } } return false; } // aCx is null when called from the finalizer template <class Derived> bool WorkerPrivateParent<Derived>::NotifyPrivate(JSContext* aCx, Status aStatus) { AssertIsOnParentThread(); bool pending; { MutexAutoLock lock(mMutex); if (mParentStatus >= aStatus) { return true; } pending = mParentStatus == Pending; mParentStatus = aStatus; } if (pending) { WorkerPrivate* self = ParentAsWorkerPrivate(); #ifdef DEBUG { // Silence useless assertions in debug builds. nsIThread* currentThread = NS_GetCurrentThread(); NS_ASSERTION(currentThread, "This should never be null!"); self->SetThread(currentThread); } #endif // Worker never got a chance to run, go ahead and delete it. self->ScheduleDeletion(true); return true; } NS_ASSERTION(aStatus != Terminating || mQueuedRunnables.IsEmpty(), "Shouldn't have anything queued!"); // Anything queued will be discarded. mQueuedRunnables.Clear(); nsRefPtr<NotifyRunnable> runnable = new NotifyRunnable(ParentAsWorkerPrivate(), aStatus); return runnable->Dispatch(aCx); } template <class Derived> bool WorkerPrivateParent<Derived>::Suspend(JSContext* aCx) { AssertIsOnParentThread(); NS_ASSERTION(!mParentSuspended, "Suspended more than once!"); mParentSuspended = true; { MutexAutoLock lock(mMutex); if (mParentStatus >= Terminating) { return true; } } nsRefPtr<SuspendRunnable> runnable = new SuspendRunnable(ParentAsWorkerPrivate()); return runnable->Dispatch(aCx); } template <class Derived> bool WorkerPrivateParent<Derived>::Resume(JSContext* aCx) { AssertIsOnParentThread(); NS_ASSERTION(mParentSuspended, "Not yet suspended!"); mParentSuspended = false; { MutexAutoLock lock(mMutex); if (mParentStatus >= Terminating) { return true; } } // Dispatch queued runnables before waking up the worker, otherwise the worker // could post new messages before we run those that have been queued. if (!mQueuedRunnables.IsEmpty()) { AssertIsOnMainThread(); nsTArray<nsRefPtr<WorkerRunnable> > runnables; mQueuedRunnables.SwapElements(runnables); for (uint32_t index = 0; index < runnables.Length(); index++) { nsRefPtr<WorkerRunnable>& runnable = runnables[index]; if (NS_FAILED(NS_DispatchToCurrentThread(runnable))) { NS_WARNING("Failed to dispatch queued runnable!"); } } } nsRefPtr<ResumeRunnable> runnable = new ResumeRunnable(ParentAsWorkerPrivate()); if (!runnable->Dispatch(aCx)) { return false; } return true; } template <class Derived> void WorkerPrivateParent<Derived>::_trace(JSTracer* aTrc) { // This should only happen on the parent thread but we can't assert that // because it can also happen on the cycle collector thread when this is a // top-level worker. EventTarget::_trace(aTrc); } template <class Derived> void WorkerPrivateParent<Derived>::_finalize(JSFreeOp* aFop) { AssertIsOnParentThread(); MOZ_ASSERT(mJSObject); MOZ_ASSERT(!mJSObjectRooted); // Clear the JS object. mJSObject = nullptr; if (!TerminatePrivate(nullptr)) { NS_WARNING("Failed to terminate!"); } // Before calling through to the base class we need to grab another reference // if we're on the main thread. Otherwise the base class' _Finalize method // will call Release, and some of our members cannot be released during // finalization. Of course, if those members are already gone then we can skip // this mess... WorkerPrivateParent<Derived>* extraSelfRef = NULL; if (!mParent && !mMainThreadObjectsForgotten) { AssertIsOnMainThread(); NS_ADDREF(extraSelfRef = this); } EventTarget::_finalize(aFop); if (extraSelfRef) { nsCOMPtr<nsIRunnable> runnable = NS_NewNonOwningRunnableMethod(extraSelfRef, &WorkerPrivateParent<Derived>::Release); if (NS_FAILED(NS_DispatchToCurrentThread(runnable))) { NS_WARNING("Failed to proxy release, this will leak!"); } } } template <class Derived> bool WorkerPrivateParent<Derived>::Close(JSContext* aCx) { AssertIsOnParentThread(); { MutexAutoLock lock(mMutex); if (mParentStatus < Closing) { mParentStatus = Closing; } } return true; } template <class Derived> bool WorkerPrivateParent<Derived>::ModifyBusyCount(JSContext* aCx, bool aIncrease) { AssertIsOnParentThread(); NS_ASSERTION(aIncrease || mBusyCount, "Mismatched busy count mods!"); if (aIncrease) { if (mBusyCount++ == 0 && mJSObject) { if (!RootJSObject(aCx, true)) { return false; } } return true; } if (--mBusyCount == 0 && mJSObject) { if (!RootJSObject(aCx, false)) { return false; } bool shouldCancel; { MutexAutoLock lock(mMutex); shouldCancel = mParentStatus == Terminating; } if (shouldCancel && !Cancel(aCx)) { return false; } } return true; } template <class Derived> bool WorkerPrivateParent<Derived>::RootJSObject(JSContext* aCx, bool aRoot) { AssertIsOnParentThread(); if (aRoot != mJSObjectRooted) { if (aRoot) { NS_ASSERTION(mJSObject, "Nothing to root?"); if (!JS_AddNamedObjectRoot(aCx, &mJSObject, "Worker root")) { NS_WARNING("JS_AddNamedObjectRoot failed!"); return false; } } else { JS_RemoveObjectRoot(aCx, &mJSObject); } mJSObjectRooted = aRoot; } return true; } template <class Derived> void WorkerPrivateParent<Derived>::ForgetMainThreadObjects( nsTArray<nsCOMPtr<nsISupports> >& aDoomed) { AssertIsOnParentThread(); MOZ_ASSERT(!mMainThreadObjectsForgotten); aDoomed.SetCapacity(7); SwapToISupportsArray(mWindow, aDoomed); SwapToISupportsArray(mScriptContext, aDoomed); SwapToISupportsArray(mScriptNotify, aDoomed); SwapToISupportsArray(mBaseURI, aDoomed); SwapToISupportsArray(mScriptURI, aDoomed); SwapToISupportsArray(mPrincipal, aDoomed); SwapToISupportsArray(mCSP, aDoomed); mMainThreadObjectsForgotten = true; } template <class Derived> bool WorkerPrivateParent<Derived>::PostMessage(JSContext* aCx, jsval aMessage, jsval aTransferable) { AssertIsOnParentThread(); { MutexAutoLock lock(mMutex); if (mParentStatus != Running) { return true; } } JSStructuredCloneCallbacks* callbacks; if (GetParent()) { if (IsChromeWorker()) { callbacks = &gChromeWorkerStructuredCloneCallbacks; } else { callbacks = &gWorkerStructuredCloneCallbacks; } } else { AssertIsOnMainThread(); if (IsChromeWorker()) { callbacks = &gMainThreadChromeWorkerStructuredCloneCallbacks; } else { callbacks = &gMainThreadWorkerStructuredCloneCallbacks; } } nsTArray<nsCOMPtr<nsISupports> > clonedObjects; JSAutoStructuredCloneBuffer buffer; if (!buffer.write(aCx, aMessage, aTransferable, callbacks, &clonedObjects)) { return false; } nsRefPtr<MessageEventRunnable> runnable = new MessageEventRunnable(ParentAsWorkerPrivate(), WorkerRunnable::WorkerThread, buffer, clonedObjects); return runnable->Dispatch(aCx); } template <class Derived> uint64_t WorkerPrivateParent<Derived>::GetInnerWindowId() { AssertIsOnMainThread(); NS_ASSERTION(!mWindow || mWindow->IsInnerWindow(), "Outer window?"); return mWindow ? mWindow->WindowID() : 0; } template <class Derived> void WorkerPrivateParent<Derived>::UpdateJSContextOptions(JSContext* aCx, uint32_t aOptions) { AssertIsOnParentThread(); mJSContextOptions = aOptions; nsRefPtr<UpdateJSContextOptionsRunnable> runnable = new UpdateJSContextOptionsRunnable(ParentAsWorkerPrivate(), aOptions); if (!runnable->Dispatch(aCx)) { NS_WARNING("Failed to update worker context options!"); JS_ClearPendingException(aCx); } } template <class Derived> void WorkerPrivateParent<Derived>::UpdateJSWorkerMemoryParameter(JSContext* aCx, JSGCParamKey aKey, uint32_t aValue) { AssertIsOnParentThread(); NS_ASSERTION(aValue, "Can't handle 0 for these values!"); bool found = false; { MutexAutoLock lock(mMutex); for (uint32_t index = 0; index < mMemoryParams.Length(); index++) { MemoryParameter& param = mMemoryParams[index]; if (param.key == aKey) { param.value = aValue; found = true; break; } } } if (!found) { NS_ERROR("Unknown key!"); return; } nsRefPtr<UpdateJSWorkerMemoryParameterRunnable> runnable = new UpdateJSWorkerMemoryParameterRunnable(ParentAsWorkerPrivate(), aKey, aValue); if (!runnable->Dispatch(aCx)) { NS_WARNING("Failed to update memory parameter!"); JS_ClearPendingException(aCx); } } #ifdef JS_GC_ZEAL template <class Derived> void WorkerPrivateParent<Derived>::UpdateGCZeal(JSContext* aCx, uint8_t aGCZeal) { AssertIsOnParentThread(); mGCZeal = aGCZeal; nsRefPtr<UpdateGCZealRunnable> runnable = new UpdateGCZealRunnable(ParentAsWorkerPrivate(), aGCZeal); if (!runnable->Dispatch(aCx)) { NS_WARNING("Failed to update worker gczeal!"); JS_ClearPendingException(aCx); } } #endif template <class Derived> void WorkerPrivateParent<Derived>::GarbageCollect(JSContext* aCx, bool aShrinking) { nsRefPtr<GarbageCollectRunnable> runnable = new GarbageCollectRunnable(ParentAsWorkerPrivate(), aShrinking, true); if (!runnable->Dispatch(aCx)) { NS_WARNING("Failed to update worker heap size!"); JS_ClearPendingException(aCx); } } template <class Derived> void WorkerPrivateParent<Derived>::SetBaseURI(nsIURI* aBaseURI) { AssertIsOnMainThread(); mBaseURI = aBaseURI; if (NS_FAILED(aBaseURI->GetSpec(mLocationInfo.mHref))) { mLocationInfo.mHref.Truncate(); } if (NS_FAILED(aBaseURI->GetHost(mLocationInfo.mHostname))) { mLocationInfo.mHostname.Truncate(); } if (NS_FAILED(aBaseURI->GetPath(mLocationInfo.mPathname))) { mLocationInfo.mPathname.Truncate(); } nsCString temp; nsCOMPtr<nsIURL> url(do_QueryInterface(aBaseURI)); if (url && NS_SUCCEEDED(url->GetQuery(temp)) && !temp.IsEmpty()) { mLocationInfo.mSearch.AssignLiteral("?"); mLocationInfo.mSearch.Append(temp); } if (NS_SUCCEEDED(aBaseURI->GetRef(temp)) && !temp.IsEmpty()) { nsCOMPtr<nsITextToSubURI> converter = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID); if (converter) { nsCString charset; nsAutoString unicodeRef; if (NS_SUCCEEDED(aBaseURI->GetOriginCharset(charset)) && NS_SUCCEEDED(converter->UnEscapeURIForUI(charset, temp, unicodeRef))) { mLocationInfo.mHash.AssignLiteral("#"); mLocationInfo.mHash.Append(NS_ConvertUTF16toUTF8(unicodeRef)); } } if (mLocationInfo.mHash.IsEmpty()) { mLocationInfo.mHash.AssignLiteral("#"); mLocationInfo.mHash.Append(temp); } } if (NS_SUCCEEDED(aBaseURI->GetScheme(mLocationInfo.mProtocol))) { mLocationInfo.mProtocol.AppendLiteral(":"); } else { mLocationInfo.mProtocol.Truncate(); } int32_t port; if (NS_SUCCEEDED(aBaseURI->GetPort(&port)) && port != -1) { mLocationInfo.mPort.AppendInt(port); nsAutoCString host(mLocationInfo.mHostname); host.AppendLiteral(":"); host.Append(mLocationInfo.mPort); mLocationInfo.mHost.Assign(host); } else { mLocationInfo.mHost.Assign(mLocationInfo.mHostname); } } template <class Derived> void WorkerPrivateParent<Derived>::SetPrincipal(nsIPrincipal* aPrincipal) { AssertIsOnMainThread(); mPrincipal = aPrincipal; mPrincipalIsSystem = nsContentUtils::IsSystemPrincipal(aPrincipal); } template <class Derived> JSContext* WorkerPrivateParent<Derived>::ParentJSContext() const { AssertIsOnParentThread(); if (!mParent) { AssertIsOnMainThread(); if (!mScriptContext) { NS_ASSERTION(!mParentJSContext, "Shouldn't have a parent context!"); return RuntimeService::AutoSafeJSContext::GetSafeContext(); } NS_ASSERTION(mParentJSContext == mScriptContext->GetNativeContext(), "Native context has changed!"); } return mParentJSContext; } WorkerPrivate::WorkerPrivate(JSContext* aCx, JSObject* aObject, WorkerPrivate* aParent, JSContext* aParentJSContext, const nsAString& aScriptURL, bool aIsChromeWorker, const nsACString& aDomain, nsCOMPtr<nsPIDOMWindow>& aWindow, nsCOMPtr<nsIScriptContext>& aParentScriptContext, nsCOMPtr<nsIURI>& aBaseURI, nsCOMPtr<nsIPrincipal>& aPrincipal, nsCOMPtr<nsIContentSecurityPolicy>& aCSP, bool aEvalAllowed, bool aXHRParamsAllowed) : WorkerPrivateParent<WorkerPrivate>(aCx, aObject, aParent, aParentJSContext, aScriptURL, aIsChromeWorker, aDomain, aWindow, aParentScriptContext, aBaseURI, aPrincipal, aCSP, aEvalAllowed), mJSContext(nullptr), mErrorHandlerRecursionCount(0), mNextTimeoutId(1), mStatus(Pending), mSuspended(false), mTimerRunning(false), mRunningExpiredTimeouts(false), mCloseHandlerStarted(false), mCloseHandlerFinished(false), mMemoryReporterRunning(false), mBlockedForMemoryReporter(false), mXHRParamsAllowed(aXHRParamsAllowed) { MOZ_COUNT_CTOR(mozilla::dom::workers::WorkerPrivate); } WorkerPrivate::~WorkerPrivate() { MOZ_COUNT_DTOR(mozilla::dom::workers::WorkerPrivate); } // static already_AddRefed<WorkerPrivate> WorkerPrivate::Create(JSContext* aCx, JSObject* aObj, WorkerPrivate* aParent, JSString* aScriptURL, bool aIsChromeWorker) { nsCString domain; nsCOMPtr<nsIURI> baseURI; nsCOMPtr<nsIPrincipal> principal; nsCOMPtr<nsIScriptContext> scriptContext; nsCOMPtr<nsIDocument> document; nsCOMPtr<nsPIDOMWindow> window; nsCOMPtr<nsIContentSecurityPolicy> csp; bool evalAllowed = true; JSContext* parentContext; bool xhrParamsAllowed = false; if (aParent) { aParent->AssertIsOnWorkerThread(); parentContext = aCx; // Domain is the only thing we can touch here. The rest will be handled by // the ScriptLoader. domain = aParent->Domain(); } else { AssertIsOnMainThread(); nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager(); NS_ASSERTION(ssm, "This should never be null!"); bool isChrome = nsContentUtils::IsCallerChrome(); // First check to make sure the caller has permission to make a // ChromeWorker if they called the ChromeWorker constructor. if (aIsChromeWorker && !isChrome) { xpc::Throw(aCx, NS_ERROR_DOM_SECURITY_ERR); return nullptr; } // Chrome callers (whether ChromeWorker of Worker) always get the system // principal here as they're allowed to load anything. The script loader may // change the principal later depending on the script uri. if (isChrome && NS_FAILED(ssm->GetSystemPrincipal(getter_AddRefs(principal)))) { JS_ReportError(aCx, "Could not get system principal!"); return nullptr; } // See if we're being called from a window or from somewhere else. nsCOMPtr<nsIScriptGlobalObject> scriptGlobal = nsJSUtils::GetStaticScriptGlobal(aCx, JS_GetGlobalForScopeChain(aCx)); if (scriptGlobal) { // Window! nsCOMPtr<nsPIDOMWindow> globalWindow = do_QueryInterface(scriptGlobal); // Only use the current inner window, and only use it if the caller can // access it. nsPIDOMWindow* outerWindow = globalWindow ? globalWindow->GetOuterWindow() : nullptr; window = outerWindow ? outerWindow->GetCurrentInnerWindow() : nullptr; if (!window || (globalWindow != window && !nsContentUtils::CanCallerAccess(window))) { xpc::Throw(aCx, NS_ERROR_DOM_SECURITY_ERR); return nullptr; } scriptContext = scriptGlobal->GetContext(); if (!scriptContext) { JS_ReportError(aCx, "Couldn't get script context for this worker!"); return nullptr; } parentContext = scriptContext->GetNativeContext(); // If we're called from a window then we can dig out the principal and URI // from the document. document = do_QueryInterface(window->GetExtantDocument()); if (!document) { JS_ReportError(aCx, "No document in this window!"); return nullptr; } baseURI = document->GetDocBaseURI(); // Use the document's NodePrincipal as our principal if we're not being // called from chrome. if (!principal) { if (!(principal = document->NodePrincipal())) { JS_ReportError(aCx, "Could not get document principal!"); return nullptr; } nsCOMPtr<nsIURI> codebase; if (NS_FAILED(principal->GetURI(getter_AddRefs(codebase)))) { JS_ReportError(aCx, "Could not determine codebase!"); return nullptr; } NS_NAMED_LITERAL_CSTRING(file, "file"); bool isFile; if (NS_FAILED(codebase->SchemeIs(file.get(), &isFile))) { JS_ReportError(aCx, "Could not determine if codebase is file!"); return nullptr; } if (isFile) { // XXX Fix this, need a real domain here. domain = file; } // Workaround for workers needing a string domain - will be fixed // in a followup after this lands. else if (document->GetSandboxFlags() & SANDBOXED_ORIGIN) { if (NS_FAILED(codebase->GetAsciiSpec(domain))) { JS_ReportError(aCx, "Could not get URI's spec for sandboxed document!"); return nullptr; } } else { nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID); if (!thirdPartyUtil) { JS_ReportError(aCx, "Could not get third party helper service!"); return nullptr; } if (NS_FAILED(thirdPartyUtil->GetBaseDomain(codebase, domain))) { JS_ReportError(aCx, "Could not get domain!"); return nullptr; } } } xhrParamsAllowed = CheckXHRParamsAllowed(window); } else { // Not a window NS_ASSERTION(isChrome, "Should be chrome only!"); parentContext = nullptr; // We're being created outside of a window. Need to figure out the script // that is creating us in order for us to use relative URIs later on. JSScript *script; if (JS_DescribeScriptedCaller(aCx, &script, nullptr)) { if (NS_FAILED(NS_NewURI(getter_AddRefs(baseURI), JS_GetScriptFilename(aCx, script)))) { JS_ReportError(aCx, "Failed to construct base URI!"); return nullptr; } } xhrParamsAllowed = true; } NS_ASSERTION(principal, "Must have a principal now!"); if (!isChrome && domain.IsEmpty()) { NS_ERROR("Must be chrome or have an domain!"); return nullptr; } if (!GetContentSecurityPolicy(aCx, getter_AddRefs(csp))) { return nullptr; } if (csp && NS_FAILED(csp->GetAllowsEval(&evalAllowed))) { NS_ERROR("CSP: failed to get allowsEval"); return nullptr; } } size_t urlLength; const jschar* urlChars = JS_GetStringCharsZAndLength(aCx, aScriptURL, &urlLength); if (!urlChars) { return nullptr; } nsDependentString scriptURL(urlChars, urlLength); nsRefPtr<WorkerPrivate> worker = new WorkerPrivate(aCx, aObj, aParent, parentContext, scriptURL, aIsChromeWorker, domain, window, scriptContext, baseURI, principal, csp, evalAllowed, xhrParamsAllowed); worker->SetIsDOMBinding(); worker->SetWrapper(aObj); nsRefPtr<CompileScriptRunnable> compiler = new CompileScriptRunnable(worker); if (!compiler->Dispatch(aCx)) { return nullptr; } return worker.forget(); } void WorkerPrivate::DoRunLoop(JSContext* aCx) { AssertIsOnWorkerThread(); { MutexAutoLock lock(mMutex); mJSContext = aCx; NS_ASSERTION(mStatus == Pending, "Huh?!"); mStatus = Running; } // We need a timer for GC. The basic plan is to run a normal (non-shrinking) // GC periodically (NORMAL_GC_TIMER_DELAY_MS) while the worker is running. // Once the worker goes idle we set a short (IDLE_GC_TIMER_DELAY_MS) timer to // run a shrinking GC. If the worker receives more messages then the short // timer is canceled and the periodic timer resumes. nsCOMPtr<nsITimer> gcTimer = do_CreateInstance(NS_TIMER_CONTRACTID); if (!gcTimer) { JS_ReportError(aCx, "Failed to create GC timer!"); return; } bool normalGCTimerRunning = false; // We need to swap event targets below to get different types of GC behavior. nsCOMPtr<nsIEventTarget> normalGCEventTarget; nsCOMPtr<nsIEventTarget> idleGCEventTarget; // We also need to track the idle GC event so that we don't confuse it with a // generic event that should re-trigger the idle GC timer. nsCOMPtr<nsIRunnable> idleGCEvent; { nsRefPtr<GarbageCollectRunnable> runnable = new GarbageCollectRunnable(this, false, false); normalGCEventTarget = new WorkerRunnableEventTarget(runnable); runnable = new GarbageCollectRunnable(this, true, false); idleGCEventTarget = new WorkerRunnableEventTarget(runnable); idleGCEvent = runnable; } EnableMemoryReporter(); for (;;) { Status currentStatus; bool scheduleIdleGC; WorkerRunnable* event; { MutexAutoLock lock(mMutex); while (!mControlQueue.Pop(event) && !mQueue.Pop(event)) { WaitForWorkerEvents(); } bool eventIsNotIdleGCEvent; currentStatus = mStatus; { MutexAutoUnlock unlock(mMutex); if (!normalGCTimerRunning && event != idleGCEvent && currentStatus <= Terminating) { // Must always cancel before changing the timer's target. if (NS_FAILED(gcTimer->Cancel())) { NS_WARNING("Failed to cancel GC timer!"); } if (NS_SUCCEEDED(gcTimer->SetTarget(normalGCEventTarget)) && NS_SUCCEEDED(gcTimer->InitWithFuncCallback( DummyCallback, nullptr, NORMAL_GC_TIMER_DELAY_MS, nsITimer::TYPE_REPEATING_SLACK))) { normalGCTimerRunning = true; } else { JS_ReportError(aCx, "Failed to start normal GC timer!"); } } #ifdef EXTRA_GC // Find GC bugs... JS_GC(aCx); #endif // Keep track of whether or not this is the idle GC event. eventIsNotIdleGCEvent = event != idleGCEvent; static_cast<nsIRunnable*>(event)->Run(); NS_RELEASE(event); } currentStatus = mStatus; scheduleIdleGC = mControlQueue.IsEmpty() && mQueue.IsEmpty() && eventIsNotIdleGCEvent && JS_GetGlobalObject(aCx); } // Take care of the GC timer. If we're starting the close sequence then we // kill the timer once and for all. Otherwise we schedule the idle timeout // if there are no more events. if (currentStatus > Terminating || scheduleIdleGC) { if (NS_SUCCEEDED(gcTimer->Cancel())) { normalGCTimerRunning = false; } else { NS_WARNING("Failed to cancel GC timer!"); } } if (scheduleIdleGC) { NS_ASSERTION(JS_GetGlobalObject(aCx), "Should have global here!"); // Now *might* be a good time to GC. Let the JS engine make the decision. JSAutoCompartment ac(aCx, JS_GetGlobalObject(aCx)); JS_MaybeGC(aCx); if (NS_SUCCEEDED(gcTimer->SetTarget(idleGCEventTarget)) && NS_SUCCEEDED(gcTimer->InitWithFuncCallback( DummyCallback, nullptr, IDLE_GC_TIMER_DELAY_MS, nsITimer::TYPE_ONE_SHOT))) { } else { JS_ReportError(aCx, "Failed to start idle GC timer!"); } } #ifdef EXTRA_GC // Find GC bugs... JS_GC(aCx); #endif if (currentStatus != Running && !HasActiveFeatures()) { // If the close handler has finished and all features are done then we can // kill this thread. if (mCloseHandlerFinished && currentStatus != Killing) { if (!NotifyInternal(aCx, Killing)) { JS_ReportPendingException(aCx); } #ifdef DEBUG { MutexAutoLock lock(mMutex); currentStatus = mStatus; } NS_ASSERTION(currentStatus == Killing, "Should have changed status!"); #else currentStatus = Killing; #endif } // If we're supposed to die then we should exit the loop. if (currentStatus == Killing) { // Always make sure the timer is canceled. if (NS_FAILED(gcTimer->Cancel())) { NS_WARNING("Failed to cancel the GC timer!"); } DisableMemoryReporter(); StopAcceptingEvents(); return; } } } NS_NOTREACHED("Shouldn't get here!"); } bool WorkerPrivate::OperationCallback(JSContext* aCx) { AssertIsOnWorkerThread(); bool mayContinue = true; for (;;) { // Run all control events now. mayContinue = ProcessAllControlRunnables(); if (!mayContinue || !mSuspended) { break; } // Clean up before suspending. JS_GC(JS_GetRuntime(aCx)); while ((mayContinue = MayContinueRunning())) { MutexAutoLock lock(mMutex); if (!mControlQueue.IsEmpty()) { break; } WaitForWorkerEvents(PR_MillisecondsToInterval(RemainingRunTimeMS())); } } if (!mayContinue) { // We want only uncatchable exceptions here. NS_ASSERTION(!JS_IsExceptionPending(aCx), "Should not have an exception set here!"); return false; } return true; } void WorkerPrivate::ScheduleDeletion(bool aWasPending) { AssertIsOnWorkerThread(); NS_ASSERTION(mChildWorkers.IsEmpty(), "Live child workers!"); NS_ASSERTION(mSyncQueues.IsEmpty(), "Should have no sync queues here!"); StopAcceptingEvents(); nsIThread* currentThread; if (aWasPending) { // Don't want to close down this thread since we never got to run! currentThread = nullptr; } else { currentThread = NS_GetCurrentThread(); NS_ASSERTION(currentThread, "This should never be null!"); } WorkerPrivate* parent = GetParent(); if (parent) { nsRefPtr<WorkerFinishedRunnable> runnable = new WorkerFinishedRunnable(parent, this, currentThread); if (!runnable->Dispatch(nullptr)) { NS_WARNING("Failed to dispatch runnable!"); } } else { nsRefPtr<TopLevelWorkerFinishedRunnable> runnable = new TopLevelWorkerFinishedRunnable(this, currentThread); if (NS_FAILED(NS_DispatchToMainThread(runnable, NS_DISPATCH_NORMAL))) { NS_WARNING("Failed to dispatch runnable!"); } } } bool WorkerPrivate::BlockAndCollectRuntimeStats(bool aIsQuick, void* aData) { AssertIsOnMainThread(); mMutex.AssertCurrentThreadOwns(); NS_ASSERTION(aData, "Null data!"); NS_ASSERTION(!mMemoryReporterRunning, "How can we get reentered here?!"); // This signals the worker that it should block itself as soon as possible. mMemoryReporterRunning = true; NS_ASSERTION(mJSContext, "This must never be null!"); JSRuntime* rt = JS_GetRuntime(mJSContext); // If the worker is not already blocked (e.g. waiting for a worker event or // currently in a ctypes call) then we need to trigger the operation // callback to trap the worker. if (!mBlockedForMemoryReporter) { JS_TriggerOperationCallback(rt); // Wait until the worker actually blocks. while (!mBlockedForMemoryReporter) { mMemoryReportCondVar.Wait(); } } bool succeeded = false; // If mMemoryReporter is still set then we can do the actual report. Otherwise // we're trying to shut down and we don't want to do anything but clean up. if (mMemoryReporter) { // Don't hold the lock while doing the actual report. MutexAutoUnlock unlock(mMutex); if (aIsQuick) { *static_cast<int64_t*>(aData) = JS::GetExplicitNonHeapForRuntime(rt, JsWorkerMallocSizeOf); succeeded = true; } else { succeeded = JS::CollectRuntimeStats(rt, static_cast<JS::RuntimeStats*>(aData), nullptr); } } NS_ASSERTION(mMemoryReporterRunning, "This isn't possible!"); NS_ASSERTION(mBlockedForMemoryReporter, "Somehow we got unblocked!"); // Tell the worker that it can now continue its execution. mMemoryReporterRunning = false; // The worker may be waiting so we must notify. mMemoryReportCondVar.Notify(); return succeeded; } void WorkerPrivate::EnableMemoryReporter() { AssertIsOnWorkerThread(); // No need to lock here since the main thread can't race until we've // successfully registered the reporter. mMemoryReporter = new MemoryReporter(this); if (NS_FAILED(NS_RegisterMemoryMultiReporter(mMemoryReporter))) { NS_WARNING("Failed to register memory reporter!"); // No need to lock here since a failed registration means our memory // reporter can't start running. Just clean up. mMemoryReporter = nullptr; return; } } void WorkerPrivate::DisableMemoryReporter() { AssertIsOnWorkerThread(); nsRefPtr<MemoryReporter> memoryReporter; { MutexAutoLock lock(mMutex); // There is nothing to do here if the memory reporter was never successfully // registered. if (!mMemoryReporter) { return; } // We don't need this set any longer. Swap it out so that we can unregister // below. mMemoryReporter.swap(memoryReporter); // Next disable the memory reporter so that the main thread stops trying to // signal us. memoryReporter->Disable(); // If the memory reporter is waiting to start then we need to wait for it to // finish. if (mMemoryReporterRunning) { NS_ASSERTION(!mBlockedForMemoryReporter, "Can't be blocked in more than one place at the same time!"); mBlockedForMemoryReporter = true; // Tell the main thread that we're blocked. mMemoryReportCondVar.Notify(); // Wait for it the main thread to finish. Since we swapped out // mMemoryReporter above the main thread should respond quickly. while (mMemoryReporterRunning) { mMemoryReportCondVar.Wait(); } NS_ASSERTION(mBlockedForMemoryReporter, "Somehow we got unblocked!"); mBlockedForMemoryReporter = false; } } // Finally unregister the memory reporter. if (NS_FAILED(NS_UnregisterMemoryMultiReporter(memoryReporter))) { NS_WARNING("Failed to unregister memory reporter!"); } } void WorkerPrivate::WaitForWorkerEvents(PRIntervalTime aInterval) { AssertIsOnWorkerThread(); mMutex.AssertCurrentThreadOwns(); NS_ASSERTION(!mBlockedForMemoryReporter, "Can't be blocked in more than one place at the same time!"); // Let the main thread know that the worker is blocked and that memory // reporting may proceed. mBlockedForMemoryReporter = true; // The main thread may be waiting so we must notify. mMemoryReportCondVar.Notify(); // Now wait for an actual worker event. mCondVar.Wait(aInterval); // We've gotten some kind of signal but we can't continue until the memory // reporter has finished. Wait again. while (mMemoryReporterRunning) { mMemoryReportCondVar.Wait(); } NS_ASSERTION(mBlockedForMemoryReporter, "Somehow we got unblocked!"); // No need to notify here as the main thread isn't watching for this state. mBlockedForMemoryReporter = false; } bool WorkerPrivate::ProcessAllControlRunnables() { AssertIsOnWorkerThread(); bool result = true; for (;;) { WorkerRunnable* event; { MutexAutoLock lock(mMutex); // Block here if the memory reporter is trying to run. if (mMemoryReporterRunning) { NS_ASSERTION(!mBlockedForMemoryReporter, "Can't be blocked in more than one place at the same " "time!"); // Let the main thread know that we've received the block request and // that memory reporting may proceed. mBlockedForMemoryReporter = true; // The main thread is almost certainly waiting so we must notify here. mMemoryReportCondVar.Notify(); // Wait for the memory report to finish. while (mMemoryReporterRunning) { mMemoryReportCondVar.Wait(); } NS_ASSERTION(mBlockedForMemoryReporter, "Somehow we got unblocked!"); // No need to notify here as the main thread isn't watching for this // state. mBlockedForMemoryReporter = false; } if (!mControlQueue.Pop(event)) { break; } } if (NS_FAILED(static_cast<nsIRunnable*>(event)->Run())) { result = false; } NS_RELEASE(event); } return result; } bool WorkerPrivate::CheckXHRParamsAllowed(nsPIDOMWindow* aWindow) { AssertIsOnMainThread(); NS_ASSERTION(aWindow, "Wrong cannot be null"); if (!aWindow->GetDocShell()) { return false; } nsCOMPtr<nsIDocument> doc = do_QueryInterface(aWindow->GetExtantDocument()); if (!doc) { return false; } nsCOMPtr<nsIPermissionManager> permMgr = do_GetService(NS_PERMISSIONMANAGER_CONTRACTID); if (!permMgr) { return false; } uint32_t permission; nsresult rv = permMgr->TestPermissionFromPrincipal(doc->NodePrincipal(), "systemXHR", &permission); if (NS_FAILED(rv) || permission != nsIPermissionManager::ALLOW_ACTION) { return false; } return true; } bool WorkerPrivate::Dispatch(WorkerRunnable* aEvent, EventQueue* aQueue) { nsRefPtr<WorkerRunnable> event(aEvent); { MutexAutoLock lock(mMutex); if (mStatus == Dead) { // Nothing may be added after we've set Dead. return false; } if (aQueue == &mQueue) { // Check parent status. Status parentStatus = ParentStatus(); if (parentStatus >= Terminating) { // Throw. return false; } // Check inner status too. if (parentStatus >= Closing || mStatus >= Closing) { // Silently eat this one. return true; } } if (!aQueue->Push(event)) { return false; } if (aQueue == &mControlQueue && mJSContext) { JS_TriggerOperationCallback(JS_GetRuntime(mJSContext)); } mCondVar.Notify(); } event.forget(); return true; } bool WorkerPrivate::DispatchToSyncQueue(WorkerSyncRunnable* aEvent) { nsRefPtr<WorkerRunnable> event(aEvent); { MutexAutoLock lock(mMutex); NS_ASSERTION(mSyncQueues.Length() > aEvent->mSyncQueueKey, "Bad event!"); if (!mSyncQueues[aEvent->mSyncQueueKey]->mQueue.Push(event)) { return false; } mCondVar.Notify(); } event.forget(); return true; } void WorkerPrivate::ClearQueue(EventQueue* aQueue) { AssertIsOnWorkerThread(); mMutex.AssertCurrentThreadOwns(); WorkerRunnable* event; while (aQueue->Pop(event)) { if (event->WantsToRunDuringClear()) { MutexAutoUnlock unlock(mMutex); static_cast<nsIRunnable*>(event)->Run(); } event->Release(); } } uint32_t WorkerPrivate::RemainingRunTimeMS() const { if (mKillTime.IsNull()) { return UINT32_MAX; } TimeDuration runtime = mKillTime - TimeStamp::Now(); double ms = runtime > TimeDuration(0) ? runtime.ToMilliseconds() : 0; return ms > double(UINT32_MAX) ? UINT32_MAX : uint32_t(ms); } bool WorkerPrivate::SuspendInternal(JSContext* aCx) { AssertIsOnWorkerThread(); NS_ASSERTION(!mSuspended, "Already suspended!"); mSuspended = true; return true; } bool WorkerPrivate::ResumeInternal(JSContext* aCx) { AssertIsOnWorkerThread(); NS_ASSERTION(mSuspended, "Not yet suspended!"); mSuspended = false; return true; } void WorkerPrivate::TraceInternal(JSTracer* aTrc) { AssertIsOnWorkerThread(); for (uint32_t index = 0; index < mTimeouts.Length(); index++) { TimeoutInfo* info = mTimeouts[index]; JS_CALL_VALUE_TRACER(aTrc, info->mTimeoutVal, "WorkerPrivate timeout value"); for (uint32_t index2 = 0; index2 < info->mExtraArgVals.Length(); index2++) { JS_CALL_VALUE_TRACER(aTrc, info->mExtraArgVals[index2], "WorkerPrivate timeout extra argument value"); } } } bool WorkerPrivate::ModifyBusyCountFromWorker(JSContext* aCx, bool aIncrease) { AssertIsOnWorkerThread(); { MutexAutoLock lock(mMutex); // If we're in shutdown then the busy count is no longer being considered so // just return now. if (mStatus >= Killing) { return true; } } nsRefPtr<ModifyBusyCountRunnable> runnable = new ModifyBusyCountRunnable(this, aIncrease); return runnable->Dispatch(aCx); } bool WorkerPrivate::AddChildWorker(JSContext* aCx, ParentType* aChildWorker) { AssertIsOnWorkerThread(); Status currentStatus; { MutexAutoLock lock(mMutex); currentStatus = mStatus; } if (currentStatus > Running) { JS_ReportError(aCx, "Cannot create child workers from the close handler!"); return false; } NS_ASSERTION(!mChildWorkers.Contains(aChildWorker), "Already know about this one!"); mChildWorkers.AppendElement(aChildWorker); return mChildWorkers.Length() == 1 ? ModifyBusyCountFromWorker(aCx, true) : true; } void WorkerPrivate::RemoveChildWorker(JSContext* aCx, ParentType* aChildWorker) { AssertIsOnWorkerThread(); NS_ASSERTION(mChildWorkers.Contains(aChildWorker), "Didn't know about this one!"); mChildWorkers.RemoveElement(aChildWorker); if (mChildWorkers.IsEmpty() && !ModifyBusyCountFromWorker(aCx, false)) { NS_WARNING("Failed to modify busy count!"); } } bool WorkerPrivate::AddFeature(JSContext* aCx, WorkerFeature* aFeature) { AssertIsOnWorkerThread(); { MutexAutoLock lock(mMutex); if (mStatus >= Canceling) { return false; } } NS_ASSERTION(!mFeatures.Contains(aFeature), "Already know about this one!"); mFeatures.AppendElement(aFeature); return mFeatures.Length() == 1 ? ModifyBusyCountFromWorker(aCx, true) : true; } void WorkerPrivate::RemoveFeature(JSContext* aCx, WorkerFeature* aFeature) { AssertIsOnWorkerThread(); NS_ASSERTION(mFeatures.Contains(aFeature), "Didn't know about this one!"); mFeatures.RemoveElement(aFeature); if (mFeatures.IsEmpty() && !ModifyBusyCountFromWorker(aCx, false)) { NS_WARNING("Failed to modify busy count!"); } } void WorkerPrivate::NotifyFeatures(JSContext* aCx, Status aStatus) { AssertIsOnWorkerThread(); NS_ASSERTION(aStatus > Running, "Bad status!"); if (aStatus >= Closing) { CancelAllTimeouts(aCx); } nsAutoTArray<WorkerFeature*, 30> features; features.AppendElements(mFeatures); for (uint32_t index = 0; index < features.Length(); index++) { if (!features[index]->Notify(aCx, aStatus)) { NS_WARNING("Failed to notify feature!"); } } nsAutoTArray<ParentType*, 10> children; children.AppendElements(mChildWorkers); for (uint32_t index = 0; index < children.Length(); index++) { if (!children[index]->Notify(aCx, aStatus)) { NS_WARNING("Failed to notify child worker!"); } } } void WorkerPrivate::CancelAllTimeouts(JSContext* aCx) { AssertIsOnWorkerThread(); if (mTimerRunning) { NS_ASSERTION(mTimer, "Huh?!"); NS_ASSERTION(!mTimeouts.IsEmpty(), "Huh?!"); if (NS_FAILED(mTimer->Cancel())) { NS_WARNING("Failed to cancel timer!"); } for (uint32_t index = 0; index < mTimeouts.Length(); index++) { mTimeouts[index]->mCanceled = true; } if (!RunExpiredTimeouts(aCx)) { JS_ReportPendingException(aCx); } mTimerRunning = false; } #ifdef DEBUG else if (!mRunningExpiredTimeouts) { NS_ASSERTION(mTimeouts.IsEmpty(), "Huh?!"); } #endif mTimer = nullptr; } uint32_t WorkerPrivate::CreateNewSyncLoop() { AssertIsOnWorkerThread(); NS_ASSERTION(mSyncQueues.Length() < UINT32_MAX, "Should have bailed by now!"); mSyncQueues.AppendElement(new SyncQueue()); return mSyncQueues.Length() - 1; } bool WorkerPrivate::RunSyncLoop(JSContext* aCx, uint32_t aSyncLoopKey) { AssertIsOnWorkerThread(); NS_ASSERTION(!mSyncQueues.IsEmpty() || (aSyncLoopKey != mSyncQueues.Length() - 1), "Forgot to call CreateNewSyncLoop!"); if (aSyncLoopKey != mSyncQueues.Length() - 1) { return false; } SyncQueue* syncQueue = mSyncQueues[aSyncLoopKey].get(); for (;;) { WorkerRunnable* event; { MutexAutoLock lock(mMutex); while (!mControlQueue.Pop(event) && !syncQueue->mQueue.Pop(event)) { WaitForWorkerEvents(); } } #ifdef EXTRA_GC // Find GC bugs... JS_GC(mJSContext); #endif static_cast<nsIRunnable*>(event)->Run(); NS_RELEASE(event); #ifdef EXTRA_GC // Find GC bugs... JS_GC(mJSContext); #endif if (syncQueue->mComplete) { NS_ASSERTION(mSyncQueues.Length() - 1 == aSyncLoopKey, "Mismatched calls!"); NS_ASSERTION(syncQueue->mQueue.IsEmpty(), "Unprocessed sync events!"); bool result = syncQueue->mResult; DestroySyncLoop(aSyncLoopKey); #ifdef DEBUG syncQueue = nullptr; #endif return result; } } NS_NOTREACHED("Shouldn't get here!"); return false; } void WorkerPrivate::StopSyncLoop(uint32_t aSyncLoopKey, bool aSyncResult) { AssertIsOnWorkerThread(); NS_ASSERTION(mSyncQueues.IsEmpty() || (aSyncLoopKey == mSyncQueues.Length() - 1), "Forgot to call CreateNewSyncLoop!"); if (aSyncLoopKey != mSyncQueues.Length() - 1) { return; } SyncQueue* syncQueue = mSyncQueues[aSyncLoopKey].get(); NS_ASSERTION(!syncQueue->mComplete, "Already called StopSyncLoop?!"); syncQueue->mResult = aSyncResult; syncQueue->mComplete = true; } void WorkerPrivate::DestroySyncLoop(uint32_t aSyncLoopKey) { AssertIsOnWorkerThread(); mSyncQueues.RemoveElementAt(aSyncLoopKey); } bool WorkerPrivate::PostMessageToParent(JSContext* aCx, jsval aMessage, jsval aTransferable) { AssertIsOnWorkerThread(); JSStructuredCloneCallbacks* callbacks = IsChromeWorker() ? &gChromeWorkerStructuredCloneCallbacks : &gWorkerStructuredCloneCallbacks; nsTArray<nsCOMPtr<nsISupports> > clonedObjects; JSAutoStructuredCloneBuffer buffer; if (!buffer.write(aCx, aMessage, aTransferable, callbacks, &clonedObjects)) { return false; } nsRefPtr<MessageEventRunnable> runnable = new MessageEventRunnable(this, WorkerRunnable::ParentThread, buffer, clonedObjects); return runnable->Dispatch(aCx); } bool WorkerPrivate::NotifyInternal(JSContext* aCx, Status aStatus) { AssertIsOnWorkerThread(); NS_ASSERTION(aStatus > Running && aStatus < Dead, "Bad status!"); // Save the old status and set the new status. Status previousStatus; { MutexAutoLock lock(mMutex); if (mStatus >= aStatus) { return true; } previousStatus = mStatus; mStatus = aStatus; } // Now that status > Running, no-one can create a new mCrossThreadDispatcher // if we don't already have one. if (mCrossThreadDispatcher) { // Since we'll no longer process events, make sure we no longer allow // anyone to post them. // We have to do this without mMutex held, since our mutex must be // acquired *after* mCrossThreadDispatcher's mutex when they're both held. mCrossThreadDispatcher->Forget(); } NS_ASSERTION(previousStatus != Pending, "How is this possible?!"); NS_ASSERTION(previousStatus >= Canceling || mKillTime.IsNull(), "Bad kill time set!"); // Let all our features know the new status. NotifyFeatures(aCx, aStatus); // If this is the first time our status has changed then we need to clear the // main event queue. if (previousStatus == Running) { MutexAutoLock lock(mMutex); ClearQueue(&mQueue); } // If we've run the close handler, we don't need to do anything else. if (mCloseHandlerFinished) { return true; } // If the worker script never ran, or failed to compile, we don't need to do // anything else, except pretend that we ran the close handler. if (!JS_GetGlobalObject(aCx)) { mCloseHandlerStarted = true; mCloseHandlerFinished = true; return true; } // If this is the first time our status has changed we also need to schedule // the close handler unless we're being shut down. if (previousStatus == Running && aStatus != Killing) { NS_ASSERTION(!mCloseHandlerStarted && !mCloseHandlerFinished, "This is impossible!"); nsRefPtr<CloseEventRunnable> closeRunnable = new CloseEventRunnable(this); MutexAutoLock lock(mMutex); if (!mQueue.Push(closeRunnable)) { NS_WARNING("Failed to push closeRunnable!"); return false; } closeRunnable.forget(); } if (aStatus == Closing) { // Notify parent to stop sending us messages and balance our busy count. nsRefPtr<CloseRunnable> runnable = new CloseRunnable(this); if (!runnable->Dispatch(aCx)) { return false; } // Don't abort the script. return true; } if (aStatus == Terminating) { // Only abort the script if we're not yet running the close handler. return mCloseHandlerStarted; } if (aStatus == Canceling) { // We need to enforce a timeout on the close handler. NS_ASSERTION(previousStatus == Running || previousStatus == Closing || previousStatus == Terminating, "Bad previous status!"); uint32_t killSeconds = RuntimeService::GetCloseHandlerTimeoutSeconds(); if (killSeconds) { mKillTime = TimeStamp::Now() + TimeDuration::FromSeconds(killSeconds); if (!mCloseHandlerFinished && !ScheduleKillCloseEventRunnable(aCx)) { return false; } } // Only abort the script if we're not yet running the close handler. return mCloseHandlerStarted; } if (aStatus == Killing) { mKillTime = TimeStamp::Now(); if (!mCloseHandlerFinished && !ScheduleKillCloseEventRunnable(aCx)) { return false; } // Always abort the script. return false; } NS_NOTREACHED("Should never get here!"); return false; } bool WorkerPrivate::ScheduleKillCloseEventRunnable(JSContext* aCx) { AssertIsOnWorkerThread(); NS_ASSERTION(!mKillTime.IsNull(), "Must have a kill time!"); nsRefPtr<KillCloseEventRunnable> killCloseEventRunnable = new KillCloseEventRunnable(this); if (!killCloseEventRunnable->SetTimeout(aCx, RemainingRunTimeMS())) { return false; } MutexAutoLock lock(mMutex); if (!mQueue.Push(killCloseEventRunnable)) { NS_WARNING("Failed to push killCloseEventRunnable!"); return false; } killCloseEventRunnable.forget(); return true; } void WorkerPrivate::ReportError(JSContext* aCx, const char* aMessage, JSErrorReport* aReport) { AssertIsOnWorkerThread(); if (!MayContinueRunning() || mErrorHandlerRecursionCount == 2) { return; } NS_ASSERTION(mErrorHandlerRecursionCount == 0 || mErrorHandlerRecursionCount == 1, "Bad recursion logic!"); JS_ClearPendingException(aCx); nsString message, filename, line; uint32_t lineNumber, columnNumber, flags, errorNumber; if (aReport) { if (aReport->ucmessage) { message = aReport->ucmessage; } filename = NS_ConvertUTF8toUTF16(aReport->filename); line = aReport->uclinebuf; lineNumber = aReport->lineno; columnNumber = aReport->uctokenptr - aReport->uclinebuf; flags = aReport->flags; errorNumber = aReport->errorNumber; } else { lineNumber = columnNumber = errorNumber = 0; flags = nsIScriptError::errorFlag | nsIScriptError::exceptionFlag; } if (message.IsEmpty()) { message = NS_ConvertUTF8toUTF16(aMessage); } mErrorHandlerRecursionCount++; // Don't want to run the scope's error handler if this is a recursive error or // if there was an error in the close handler or if we ran out of memory. bool fireAtScope = mErrorHandlerRecursionCount == 1 && !mCloseHandlerStarted && errorNumber != JSMSG_OUT_OF_MEMORY; if (!ReportErrorRunnable::ReportError(aCx, this, fireAtScope, nullptr, message, filename, line, lineNumber, columnNumber, flags, errorNumber, 0)) { JS_ReportPendingException(aCx); } mErrorHandlerRecursionCount--; } bool WorkerPrivate::SetTimeout(JSContext* aCx, unsigned aArgc, jsval* aVp, bool aIsInterval) { AssertIsOnWorkerThread(); NS_ASSERTION(aArgc, "Huh?!"); const uint32_t timerId = mNextTimeoutId++; Status currentStatus; { MutexAutoLock lock(mMutex); currentStatus = mStatus; } // It's a script bug if setTimeout/setInterval are called from a close handler // so throw an exception. if (currentStatus == Closing) { JS_ReportError(aCx, "Cannot schedule timeouts from the close handler!"); } // If the worker is trying to call setTimeout/setInterval and the parent // thread has initiated the close process then just silently fail. if (currentStatus >= Closing) { return false; } nsAutoPtr<TimeoutInfo> newInfo(new TimeoutInfo()); newInfo->mIsInterval = aIsInterval; newInfo->mId = timerId; if (NS_UNLIKELY(timerId == UINT32_MAX)) { NS_WARNING("Timeout ids overflowed!"); mNextTimeoutId = 1; } JS::Value* argv = JS_ARGV(aCx, aVp); // Take care of the main argument. if (argv[0].isObject()) { if (JS_ObjectIsCallable(aCx, &argv[0].toObject())) { newInfo->mTimeoutVal = argv[0]; } else { JSString* timeoutStr = JS_ValueToString(aCx, argv[0]); if (!timeoutStr) { return false; } newInfo->mTimeoutVal.setString(timeoutStr); } } else if (argv[0].isString()) { newInfo->mTimeoutVal = argv[0]; } else { JS_ReportError(aCx, "Useless %s call (missing quotes around argument?)", aIsInterval ? "setInterval" : "setTimeout"); return false; } // See if any of the optional arguments were passed. if (aArgc > 1) { double intervalMS = 0; if (!JS_ValueToNumber(aCx, argv[1], &intervalMS)) { return false; } newInfo->mInterval = TimeDuration::FromMilliseconds(intervalMS); if (aArgc > 2 && newInfo->mTimeoutVal.isObject()) { nsTArray<jsval> extraArgVals(aArgc - 2); for (unsigned index = 2; index < aArgc; index++) { extraArgVals.AppendElement(argv[index]); } newInfo->mExtraArgVals.SwapElements(extraArgVals); } } newInfo->mTargetTime = TimeStamp::Now() + newInfo->mInterval; if (newInfo->mTimeoutVal.isString()) { const char* filenameChars; uint32_t lineNumber; if (nsJSUtils::GetCallingLocation(aCx, &filenameChars, &lineNumber)) { newInfo->mFilename = filenameChars; newInfo->mLineNumber = lineNumber; } else { NS_WARNING("Failed to get calling location!"); } } mTimeouts.InsertElementSorted(newInfo.get(), GetAutoPtrComparator(mTimeouts)); // If the timeout we just made is set to fire next then we need to update the // timer. if (mTimeouts[0] == newInfo) { nsresult rv; if (!mTimer) { mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv); if (NS_FAILED(rv)) { JS_ReportError(aCx, "Failed to create timer!"); return false; } nsRefPtr<TimerRunnable> timerRunnable = new TimerRunnable(this); nsCOMPtr<nsIEventTarget> target = new WorkerRunnableEventTarget(timerRunnable); rv = mTimer->SetTarget(target); if (NS_FAILED(rv)) { JS_ReportError(aCx, "Failed to set timer's target!"); return false; } } if (!mTimerRunning) { if (!ModifyBusyCountFromWorker(aCx, true)) { return false; } mTimerRunning = true; } if (!RescheduleTimeoutTimer(aCx)) { return false; } } JS_SET_RVAL(aCx, aVp, INT_TO_JSVAL(timerId)); newInfo.forget(); return true; } bool WorkerPrivate::ClearTimeout(JSContext* aCx, uint32 aId) { AssertIsOnWorkerThread(); if (!mTimeouts.IsEmpty()) { NS_ASSERTION(mTimerRunning, "Huh?!"); for (uint32_t index = 0; index < mTimeouts.Length(); index++) { nsAutoPtr<TimeoutInfo>& info = mTimeouts[index]; if (info->mId == aId) { info->mCanceled = true; break; } } } return true; } bool WorkerPrivate::RunExpiredTimeouts(JSContext* aCx) { AssertIsOnWorkerThread(); // We may be called recursively (e.g. close() inside a timeout) or we could // have been canceled while this event was pending, bail out if there is // nothing to do. if (mRunningExpiredTimeouts || !mTimerRunning) { return true; } NS_ASSERTION(mTimer, "Must have a timer!"); NS_ASSERTION(!mTimeouts.IsEmpty(), "Should have some work to do!"); bool retval = true; AutoPtrComparator<TimeoutInfo> comparator = GetAutoPtrComparator(mTimeouts); js::RootedObject global(aCx, JS_GetGlobalObject(aCx)); JSPrincipals* principal = GetWorkerPrincipal(); // We want to make sure to run *something*, even if the timer fired a little // early. Fudge the value of now to at least include the first timeout. const TimeStamp now = NS_MAX(TimeStamp::Now(), mTimeouts[0]->mTargetTime); nsAutoTArray<TimeoutInfo*, 10> expiredTimeouts; for (uint32_t index = 0; index < mTimeouts.Length(); index++) { nsAutoPtr<TimeoutInfo>& info = mTimeouts[index]; if (info->mTargetTime > now) { break; } expiredTimeouts.AppendElement(info); } // Guard against recursion. mRunningExpiredTimeouts = true; // Run expired timeouts. for (uint32_t index = 0; index < expiredTimeouts.Length(); index++) { TimeoutInfo*& info = expiredTimeouts[index]; if (info->mCanceled) { continue; } // Always call JS_ReportPendingException if something fails, and if // JS_ReportPendingException returns false (i.e. uncatchable exception) then // break out of the loop. if (info->mTimeoutVal.isString()) { JSString* expression = info->mTimeoutVal.toString(); JS::CompileOptions options(aCx); options.setPrincipals(principal) .setFileAndLine(info->mFilename.get(), info->mLineNumber); size_t stringLength; const jschar* string = JS_GetStringCharsAndLength(aCx, expression, &stringLength); if ((!string || !JS::Evaluate(aCx, global, options, string, stringLength, nullptr)) && !JS_ReportPendingException(aCx)) { retval = false; break; } } else { jsval rval; if (!JS_CallFunctionValue(aCx, global, info->mTimeoutVal, info->mExtraArgVals.Length(), info->mExtraArgVals.Elements(), &rval) && !JS_ReportPendingException(aCx)) { retval = false; break; } } NS_ASSERTION(mRunningExpiredTimeouts, "Someone changed this!"); } // No longer possible to be called recursively. mRunningExpiredTimeouts = false; // Now remove canceled and expired timeouts from the main list. // NB: The timeouts present in expiredTimeouts must have the same order // with respect to each other in mTimeouts. That is, mTimeouts is just // expiredTimeouts with extra elements inserted. There may be unexpired // timeouts that have been inserted between the expired timeouts if the // timeout event handler called setTimeout/setInterval. for (uint32_t index = 0, expiredTimeoutIndex = 0, expiredTimeoutLength = expiredTimeouts.Length(); index < mTimeouts.Length(); ) { nsAutoPtr<TimeoutInfo>& info = mTimeouts[index]; if ((expiredTimeoutIndex < expiredTimeoutLength && info == expiredTimeouts[expiredTimeoutIndex] && ++expiredTimeoutIndex) || info->mCanceled) { if (info->mIsInterval && !info->mCanceled) { // Reschedule intervals. info->mTargetTime = info->mTargetTime + info->mInterval; // Don't resort the list here, we'll do that at the end. ++index; } else { mTimeouts.RemoveElement(info); } } else { // If info did not match the current entry in expiredTimeouts, it // shouldn't be there at all. NS_ASSERTION(!expiredTimeouts.Contains(info), "Our timeouts are out of order!"); ++index; } } mTimeouts.Sort(comparator); // Either signal the parent that we're no longer using timeouts or reschedule // the timer. if (mTimeouts.IsEmpty()) { if (!ModifyBusyCountFromWorker(aCx, false)) { retval = false; } mTimerRunning = false; } else if (retval && !RescheduleTimeoutTimer(aCx)) { retval = false; } return retval; } bool WorkerPrivate::RescheduleTimeoutTimer(JSContext* aCx) { AssertIsOnWorkerThread(); NS_ASSERTION(!mTimeouts.IsEmpty(), "Should have some timeouts!"); NS_ASSERTION(mTimer, "Should have a timer!"); double delta = (mTimeouts[0]->mTargetTime - TimeStamp::Now()).ToMilliseconds(); uint32_t delay = delta > 0 ? NS_MIN(delta, double(UINT32_MAX)) : 0; nsresult rv = mTimer->InitWithFuncCallback(DummyCallback, nullptr, delay, nsITimer::TYPE_ONE_SHOT); if (NS_FAILED(rv)) { JS_ReportError(aCx, "Failed to start timer!"); return false; } return true; } void WorkerPrivate::UpdateJSContextOptionsInternal(JSContext* aCx, uint32_t aOptions) { AssertIsOnWorkerThread(); JS_SetOptions(aCx, aOptions); for (uint32_t index = 0; index < mChildWorkers.Length(); index++) { mChildWorkers[index]->UpdateJSContextOptions(aCx, aOptions); } } void WorkerPrivate::UpdateJSWorkerMemoryParameterInternal(JSContext* aCx, JSGCParamKey aKey, uint32_t aValue) { AssertIsOnWorkerThread(); NS_ASSERTION(aValue, "Can't handle 0 for these values!"); JS_SetGCParameter(JS_GetRuntime(aCx), aKey, aValue); for (uint32_t index = 0; index < mChildWorkers.Length(); index++) { mChildWorkers[index]->UpdateJSWorkerMemoryParameter(aCx, aKey, aValue); } } #ifdef JS_GC_ZEAL void WorkerPrivate::UpdateGCZealInternal(JSContext* aCx, uint8_t aGCZeal) { AssertIsOnWorkerThread(); uint32_t frequency = aGCZeal <= 2 ? JS_DEFAULT_ZEAL_FREQ : 1; JS_SetGCZeal(aCx, aGCZeal, frequency); for (uint32_t index = 0; index < mChildWorkers.Length(); index++) { mChildWorkers[index]->UpdateGCZeal(aCx, aGCZeal); } } #endif void WorkerPrivate::GarbageCollectInternal(JSContext* aCx, bool aShrinking, bool aCollectChildren) { AssertIsOnWorkerThread(); if (aCollectChildren) { JSRuntime* rt = JS_GetRuntime(aCx); js::PrepareForFullGC(rt); if (aShrinking) { js::ShrinkingGC(rt, js::gcreason::DOM_WORKER); } else { js::GCForReason(rt, js::gcreason::DOM_WORKER); } } else { // If aCollectChildren is false then it means this collection request was // not generated by the main thread. At the moment only the periodic GC // timer can end up here, so rather than force a collection let the JS // engine decide if we need one. JS_MaybeGC(aCx); } if (aCollectChildren) { for (uint32_t index = 0; index < mChildWorkers.Length(); index++) { mChildWorkers[index]->GarbageCollect(aCx, aShrinking); } } } #ifdef DEBUG template <class Derived> void WorkerPrivateParent<Derived>::AssertIsOnParentThread() const { if (GetParent()) { GetParent()->AssertIsOnWorkerThread(); } else { AssertIsOnMainThread(); } } template <class Derived> void WorkerPrivateParent<Derived>::AssertInnerWindowIsCorrect() const { AssertIsOnParentThread(); // Only care about top level workers from windows. if (mParent || !mWindow) { return; } AssertIsOnMainThread(); nsPIDOMWindow* outer = mWindow->GetOuterWindow(); NS_ASSERTION(outer && outer->GetCurrentInnerWindow() == mWindow, "Inner window no longer correct!"); } void WorkerPrivate::AssertIsOnWorkerThread() const { if (mThread) { bool current; if (NS_FAILED(mThread->IsOnCurrentThread(&current)) || !current) { NS_ERROR("Wrong thread!"); } } else { NS_ERROR("Trying to assert thread identity after thread has been " "shutdown!"); } } #endif WorkerCrossThreadDispatcher* WorkerPrivate::GetCrossThreadDispatcher() { mozilla::MutexAutoLock lock(mMutex); if (!mCrossThreadDispatcher && mStatus <= Running) { mCrossThreadDispatcher = new WorkerCrossThreadDispatcher(this); } return mCrossThreadDispatcher; } bool WorkerPrivate::GetContentSecurityPolicy(JSContext* aCx, nsIContentSecurityPolicy** aCSP) { AssertIsOnMainThread(); // Get the security manager nsCOMPtr<nsIScriptSecurityManager> ssm = nsContentUtils::GetSecurityManager(); if (!ssm) { NS_ERROR("Failed to get security manager service"); return false; } nsCOMPtr<nsIPrincipal> subjectPrincipal = ssm->GetCxSubjectPrincipal(aCx); NS_ASSERTION(subjectPrincipal, "Failed to get subjectPrincipal"); nsCOMPtr<nsIContentSecurityPolicy> csp; nsresult rv = subjectPrincipal->GetCsp(getter_AddRefs(csp)); if (NS_FAILED(rv)) { NS_ERROR("CSP: Failed to get CSP from principal."); return false; } csp.forget(aCSP); return true; } void WorkerPrivate::BeginCTypesCall() { AssertIsOnWorkerThread(); MutexAutoLock lock(mMutex); NS_ASSERTION(!mBlockedForMemoryReporter, "Can't be blocked in more than one place at the same time!"); // Let the main thread know that the worker is effectively blocked while in // this ctypes call. It isn't technically true (obviously the call could do // non-blocking things), but we're assuming that ctypes can't call back into // JSAPI here and therefore any work the ctypes call does will not alter the // data structures of this JS runtime. mBlockedForMemoryReporter = true; // The main thread may be waiting on us so it must be notified. mMemoryReportCondVar.Notify(); } void WorkerPrivate::EndCTypesCall() { AssertIsOnWorkerThread(); MutexAutoLock lock(mMutex); NS_ASSERTION(mBlockedForMemoryReporter, "Somehow we got unblocked!"); // Don't continue until the memory reporter has finished. while (mMemoryReporterRunning) { mMemoryReportCondVar.Wait(); } // No need to notify the main thread here as it shouldn't be waiting to see // this state. mBlockedForMemoryReporter = false; } BEGIN_WORKERS_NAMESPACE // Force instantiation. template class WorkerPrivateParent<WorkerPrivate>; WorkerPrivate* GetWorkerPrivateFromContext(JSContext* aCx) { NS_ASSERTION(!NS_IsMainThread(), "Wrong thread!"); return static_cast<WorkerPrivate*>(JS_GetRuntimePrivate(JS_GetRuntime(aCx))); } JSStructuredCloneCallbacks* WorkerStructuredCloneCallbacks(bool aMainRuntime) { return aMainRuntime ? &gMainThreadWorkerStructuredCloneCallbacks : &gWorkerStructuredCloneCallbacks; } JSStructuredCloneCallbacks* ChromeWorkerStructuredCloneCallbacks(bool aMainRuntime) { return aMainRuntime ? &gMainThreadChromeWorkerStructuredCloneCallbacks : &gChromeWorkerStructuredCloneCallbacks; } END_WORKERS_NAMESPACE
27.600847
92
0.660118
[ "object" ]
cd538f9c8368b1f5404255651aa212626ec61dae
3,389
cpp
C++
torch/lib/c10d/comm.cpp
MagiaSN/pytorch
7513455c743d3d644b45a804902c1a0d14b69f45
[ "Intel" ]
7
2021-05-29T16:31:51.000Z
2022-02-21T18:52:25.000Z
torch/lib/c10d/comm.cpp
MagiaSN/pytorch
7513455c743d3d644b45a804902c1a0d14b69f45
[ "Intel" ]
1
2022-01-18T12:17:29.000Z
2022-01-18T12:17:29.000Z
torch/lib/c10d/comm.cpp
MagiaSN/pytorch
7513455c743d3d644b45a804902c1a0d14b69f45
[ "Intel" ]
2
2021-07-02T10:18:21.000Z
2021-08-18T10:10:28.000Z
#include <c10d/comm.hpp> #include <deque> #include <ATen/core/functional.h> #include <c10d/reducer.hpp> #include <torch/csrc/jit/python/pybind_utils.h> #include <torch/csrc/utils/tensor_flatten.h> namespace c10d { namespace { class BroadcastWork { public: BroadcastWork( const c10::intrusive_ptr<c10d::ProcessGroup>& process_group, std::vector<at::Tensor> bucket_tensors, int root_rank = 0) : bucket_tensors_(std::move(bucket_tensors)), flat_tensor_({torch::utils::flatten_dense_tensors(bucket_tensors_)}) { BroadcastOptions broadcastOptions; broadcastOptions.rootRank = root_rank; work_ = process_group->broadcast(flat_tensor_, broadcastOptions); } void finish() { work_->wait(); // Copy the output of the broadcast operation back. auto output_tensors = torch::utils::unflatten_dense_tensors( flat_tensor_.front(), bucket_tensors_); TORCH_INTERNAL_ASSERT(output_tensors.size() == bucket_tensors_.size()); for (size_t i = 0; i < output_tensors.size(); i++) { bucket_tensors_[i].copy_(output_tensors[i], /*non_blocking=*/true); } } protected: // The list of tensors to broadcast. They are guaranteed to be // placed on the same device and have the same dtype. std::vector<at::Tensor> bucket_tensors_; // The vector with a single flattened tensor containing the contents // of the tensors in bucket_tensors_. It must be stored in a vector // because c10d::ProcessGroup::broadcast takes a vector argument. std::vector<at::Tensor> flat_tensor_; private: // The broadcast work that is kicked off upon construction. c10::intrusive_ptr<c10d::ProcessGroup::Work> work_; }; } // namespace // Broadcast many tensors to all processes in the process group. void broadcast_coalesced( c10::intrusive_ptr<c10d::ProcessGroup> process_group, at::TensorList tensors, size_t buffer_size, int rank) { // Coalesce tensors into buckets taking into account the maximum buffer size. // This routine is multi-device aware, so the tensors can be split across // multiple devices and can contain a mix of CPU and CUDA tensors. const auto buckets = compute_bucket_assignment_by_size(tensors.vec(), {buffer_size}); // Returns tensor at specified index in input tensor list. const auto lookup = [&tensors](size_t index) { return tensors[index]; }; // We maintain a maximum of 2 in flight broadcast operations to avoid // allocating too much memory (in case the specified tensors are very large). std::deque<BroadcastWork> in_flight; constexpr auto max_in_flight = 2; for (const auto& bucket : buckets) { if (in_flight.size() >= max_in_flight) { in_flight.front().finish(); in_flight.pop_front(); } in_flight.emplace_back(process_group, c10::fmap(bucket, lookup), rank); } while (!in_flight.empty()) { in_flight.front().finish(); in_flight.pop_front(); } } std::vector<at::Tensor> GradBucket::getPerParameterTensors() const { std::vector<at::Tensor> per_parameter_tensors; size_t num_parameters = offsets_.size(); per_parameter_tensors.reserve(num_parameters); for (size_t i = 0; i < num_parameters; ++i) { per_parameter_tensors.push_back( tensor_.slice(0, offsets_[i], offsets_[i] + lengths_[i]) .view(sizes_vec_[i])); } return per_parameter_tensors; } } // namespace c10d
33.22549
79
0.713485
[ "vector" ]
cd55cc712c5fabcc34668b06f3faa6010e7543a0
139,552
cpp
C++
qt-creator-opensource-src-4.6.1/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ // std::copy is perfectly fine, don't let MSVC complain about it being deprecated #pragma warning (disable: 4996) #ifndef NOMINMAX # define NOMINMAX #endif #include "symbolgroupvalue.h" #include "symbolgroup.h" #include "stringutils.h" #include "containers.h" #include "extensioncontext.h" #include <iomanip> #include <algorithm> #include <limits> #include <ctype.h> #include <unordered_map> typedef std::vector<int>::size_type VectorIndexType; typedef std::unordered_map<std::string, SymbolAncestorInfo> AncestorInfos; static std::unordered_map<std::string, AncestorInfos> typeAncestorInfos; /*! \class SymbolGroupValueContext \brief The SymbolGroupValueContext class passes all IDebug interfaces required for SymbolGroupValue. \ingroup qtcreatorcdbext */ /*! \class SymbolGroupValue \brief The SymbolGroupValue class is a flyweight tied to a SymbolGroupNode providing a convenient operator[] (name, index) and value getters for notation of dumpers. Inaccessible members return a SymbolGroupValue in state 'invalid'. Example: \code SymbolGroupValue container(symbolGroupNode, symbolGroupValueContext); if (SymbolGroupValue sizeV = container["d"]["size"]) int size = sizeV.intValue() \endcode \ingroup qtcreatorcdbext */ unsigned SymbolGroupValue::verbose = 0; SymbolGroupValue::SymbolGroupValue(const std::string &parentError) : m_errorMessage(parentError) { if (m_errorMessage.empty()) m_errorMessage = "Invalid"; } SymbolGroupValue::SymbolGroupValue(SymbolGroupNode *node, const SymbolGroupValueContext &ctx) : m_node(node), m_context(ctx) { if (m_node && !m_node->isMemoryAccessible()) { // Invalid if no value m_node = 0; if (SymbolGroupValue::verbose) DebugPrint() << node->name() << '/' << node->iName() << '/' << node->type() << " memory access error"; } } SymbolGroupValue::SymbolGroupValue() : m_errorMessage("Invalid") { } bool SymbolGroupValue::isValid() const { return m_node != 0 && m_context.dataspaces != 0; } // Debug helper static void formatNodeError(const AbstractSymbolGroupNode *n, std::ostream &os) { const AbstractSymbolGroupNode::AbstractSymbolGroupNodePtrVector &children = n->children(); const VectorIndexType size = children.size(); if (const SymbolGroupNode *sn = n->asSymbolGroupNode()) { os << "type: " << sn->type() << ", raw value: \"" << wStringToString(sn->symbolGroupRawValue()) << "\", 0x" << std::hex << sn->address() << ", " << std::dec; } if (size) { os << "children (" << size << "): ["; for (VectorIndexType i = 0; i < size; ++i) os << ' ' << children.at(i)->name(); os << ']'; } else { os << "No children"; } } SymbolGroupValue SymbolGroupValue::operator[](unsigned index) const { if (ensureExpanded()) if (index < m_node->children().size()) if (SymbolGroupNode *n = m_node->childAt(index)->asSymbolGroupNode()) return SymbolGroupValue(n, m_context); if (isValid() && SymbolGroupValue::verbose) { DebugPrint dp; dp << name() << "::operator[](#" << index << ") failed. "; formatNodeError(m_node, dp); } return SymbolGroupValue(m_errorMessage); } SymbolGroupValue SymbolGroupValue::addSymbolForAncestor(const std::string &ancestorName) const { const SymbolAncestorInfo info = infoOfAncestor(ancestorName); if (info.isValid()) { const ULONG64 base = isPointerType(type()) ? pointerValue() : address(); return addSymbol(base + info.offset, stripClassPrefixes(info.type)); } if (isValid() && SymbolGroupValue::verbose) { // Do not report subsequent errors DebugPrint dp; dp << this->name() << "::addSymbolForAncestor(\"" << ancestorName << "\") failed. "; formatNodeError(m_node, dp); } return SymbolGroupValue(m_errorMessage); } int SymbolGroupValue::readIntegerFromAncestor(const std::string &name, int defaultValue) const { return readPODFromAncestor<int>(name, defaultValue); } ULONG64 SymbolGroupValue::offsetOfChild(const SymbolGroupValue &child) const { const ULONG64 base = isPointerType(type()) ? pointerValue() : address(); const ULONG64 childAddress = child.address(); if (base == 0 || childAddress == 0) return 0; return childAddress - base; } LONG64 SymbolGroupValue::offsetOfAncestor(const std::string &name) const { return infoOfAncestor(name).offset; } ULONG64 SymbolGroupValue::addressOfAncestor(const std::string &name) const { const ULONG64 base = isPointerType(type()) ? pointerValue() : address(); LONG64 offset = offsetOfAncestor(name); return offset >= 0 ? base + ULONG64(offset) : 0; } std::string SymbolGroupValue::typeOfAncestor(const std::string &name) const { return infoOfAncestor(name).type; } SymbolAncestorInfo SymbolGroupValue::infoOfAncestor(const std::string &name) const { const std::string &typeName = type(); AncestorInfos &offsets = typeAncestorInfos[typeName]; auto offsetIt = offsets.find(name); if (offsetIt != offsets.end()) return offsetIt->second; SymbolAncestorInfo info; if (!ensureExpanded()) return info; if (AbstractSymbolGroupNode *abstractChildNode = m_node->childByIName(name.c_str())) { if (SymbolGroupNode *childNode = abstractChildNode->asSymbolGroupNode()) { SymbolGroupValue child(childNode, m_context); ULONG64 childAddress = child.address(); if (childAddress == 0) return info; const ULONG64 base = isPointerType(typeName) ? pointerValue() : address(); info.offset = LONG64(childAddress - base); info.type = child.type(); } } if (!info.isValid()) { // Search recursively for ancestor for (AbstractSymbolGroupNode *abstractChildNode : m_node->children()) { if (SymbolGroupNode *childNode = abstractChildNode->asSymbolGroupNode()) { SymbolGroupValue child(childNode, m_context); if (isPointerType(child.type())) continue; info = child.infoOfAncestor(name); if (info.isValid()) { info.offset += offsetOfChild(child); break; } } } } if (info.isValid()) offsets[name] = info; return info; } SymbolGroupValue SymbolGroupValue::addSymbol(const ULONG64 address, const std::string &type) const { const std::string &pointerToType = pointedToSymbolName(address, type); if (SymbolGroupNode *ancestorNode = node()->symbolGroup()->addSymbol(module(), pointerToType, "", "", &std::string())) { return SymbolGroupValue(ancestorNode, m_context); } if (isValid() && SymbolGroupValue::verbose) { // Do not report subsequent errors DebugPrint dp; dp << this->name() << "::addSymbol(\"" << address << "\", \"" << address << "\") failed. "; formatNodeError(m_node, dp); } return SymbolGroupValue(m_errorMessage); } unsigned SymbolGroupValue::childCount() const { if (ensureExpanded()) return unsigned(m_node->children().size()); return 0; } SymbolGroupValue SymbolGroupValue::parent() const { if (isValid()) if (AbstractSymbolGroupNode *aParent = m_node->parent()) if (SymbolGroupNode *parent = aParent->asSymbolGroupNode()) return SymbolGroupValue(parent, m_context); return SymbolGroupValue("parent() invoked on invalid value."); } bool SymbolGroupValue::ensureExpanded() const { if (!isValid() || !m_node->canExpand()) return false; if (m_node->isExpanded()) return true; // Set a flag indicating the node was expanded by SymbolGroupValue // and not by an explicit request from the watch model. if (m_node->expand(&m_errorMessage)) return true; if (SymbolGroupValue::verbose) DebugPrint() << "Expand failure of '" << name() << "': " << m_errorMessage; return false; } SymbolGroupValue SymbolGroupValue::operator[](const char *name) const { if (ensureExpanded()) if (AbstractSymbolGroupNode *child = m_node->childByIName(name)) if (SymbolGroupNode *n = child->asSymbolGroupNode()) return SymbolGroupValue(n, m_context); if (isValid() && SymbolGroupValue::verbose) { // Do not report subsequent errors DebugPrint dp; dp << this->name() << "::operator[](\"" << name << "\") failed. "; formatNodeError(m_node, dp); } return SymbolGroupValue(m_errorMessage); } std::string SymbolGroupValue::type() const { return isValid() ? m_node->type() : std::string(); } std::string SymbolGroupValue::name() const { return isValid() ? m_node->name() : std::string(); } unsigned SymbolGroupValue::size() const { return isValid() ? m_node->size() : 0; } std::wstring SymbolGroupValue::value() const { return isValid() ? m_node->symbolGroupFixedValue() : std::wstring(); } double SymbolGroupValue::floatValue(double defaultValue) const { double f = defaultValue; if (isValid()) { std::wistringstream str(value()); str >> f; if (str.fail()) f = defaultValue; } return f; } int SymbolGroupValue::intValue(int defaultValue) const { if (isValid()) { int rc = 0; // Is this an enumeration "EnumValue (0n12)", -> convert to integer std::wstring v = value(); const std::wstring::size_type enPos = v.find(L"(0n"); if (enPos != std::wstring::npos && v.at(v.size() - 1) == L')') v = v.substr(enPos + 3, v.size() - 4); if (integerFromString(wStringToString(v), &rc)) return rc; } if (SymbolGroupValue::verbose) DebugPrint() << name() << '/' << type() << '/'<< m_errorMessage << ": intValue() fails"; return defaultValue; } ULONG64 SymbolGroupValue::pointerValue(ULONG64 defaultValue) const { if (isValid()) { ULONG64 rc = 0; if (integerFromString(wStringToString(value()), &rc)) return rc; } if (SymbolGroupValue::verbose) DebugPrint() << name() << '/'<< type() << '/' << m_errorMessage << ": pointerValue() fails"; return defaultValue; } // Read a POD value from debuggee memory and convert into host variable type POD. // For unsigned integer types, it is possible to read a smaller debuggee-unsigned // into a big ULONG64 on the host side (due to endianness). template<class POD> POD readPODFromMemory(CIDebugDataSpaces *ds, ULONG64 address, ULONG debuggeeTypeSize, POD defaultValue, std::string *errorMessage /* = 0 */) { POD rc = defaultValue; if (debuggeeTypeSize == 0 || debuggeeTypeSize > sizeof(POD)) // Safety check. return rc; if (const unsigned char *buffer = SymbolGroupValue::readMemory(ds, address, debuggeeTypeSize, errorMessage)) { memcpy(&rc, buffer, debuggeeTypeSize); delete [] buffer; } return rc; } template<class POD> POD SymbolGroupValue::readPODFromAncestor(const std::string &name, POD defaultValue) const { ULONG64 address = addressOfAncestor(name.c_str()); if (address == 0) return defaultValue; return readPODFromMemory<POD>(m_context.dataspaces, address, sizeof(POD), defaultValue, 0); } ULONG64 SymbolGroupValue::readPointerValue(CIDebugDataSpaces *ds, ULONG64 address, std::string *errorMessage /* = 0 */) { return readPODFromMemory<ULONG64>(ds, address, SymbolGroupValue::pointerSize(), 0, errorMessage); } ULONG64 SymbolGroupValue::readPointerValueFromAncestor(const std::string &name) const { ULONG64 address = addressOfAncestor(name.c_str()); if (address == 0) return 0; return readPointerValue(m_context.dataspaces, address); } ULONG64 SymbolGroupValue::readUnsignedValue(CIDebugDataSpaces *ds, ULONG64 address, ULONG debuggeeTypeSize, ULONG64 defaultValue, std::string *errorMessage /* = 0 */) { return readPODFromMemory<ULONG64>(ds, address, debuggeeTypeSize, defaultValue, errorMessage); } LONG64 SymbolGroupValue::readSignedValue(CIDebugDataSpaces *ds, ULONG64 address, ULONG debuggeeTypeSize, LONG64 defaultValue, std::string *errorMessage /* = 0 */) { return readPODFromMemory<LONG64>(ds, address, debuggeeTypeSize, defaultValue, errorMessage); } // Note: sizeof(int) should always be 4 on Win32/Win64, no need to // differentiate between host and debuggee int types. When implementing // something like 'long', different size on host/debuggee must be taken // into account (shifting signedness bits around). int SymbolGroupValue::readIntValue(CIDebugDataSpaces *ds, ULONG64 address, int defaultValue, std::string *errorMessage /* = 0 */) { return readPODFromMemory<int>(ds, address, sizeof(int), defaultValue, errorMessage); } double SymbolGroupValue::readDouble(CIDebugDataSpaces *ds, ULONG64 address, double defaultValue, std::string *errorMessage /* = 0 */) { return readPODFromMemory<double>(ds, address, sizeof(double), defaultValue, errorMessage); } // Read memory and return allocated array unsigned char *SymbolGroupValue::readMemory(CIDebugDataSpaces *ds, ULONG64 address, ULONG length, std::string *errorMessage /* = 0 */) { unsigned char *buffer = new unsigned char[length]; std::fill(buffer, buffer + length, 0); ULONG received = 0; const HRESULT hr = ds->ReadVirtual(address, buffer, length, &received); if (FAILED(hr)) { delete [] buffer; if (errorMessage) { std::ostringstream estr; estr << "Cannot read " << length << " bytes from 0x" << std::hex << address << ": " << msgDebugEngineComFailed("ReadVirtual", hr); *errorMessage = estr.str(); } return 0; } if (received < length && errorMessage) { std::ostringstream estr; estr << "Warning: Received only " << received << " bytes of " << length << " requested at 0x" << std::hex << address << '.'; *errorMessage = estr.str(); } return buffer; } bool SymbolGroupValue::writeMemory(CIDebugDataSpaces *ds, ULONG64 address, const unsigned char *data, ULONG length, std::string *errorMessage /* =0 */) { ULONG filled = 0; const HRESULT hr = ds->FillVirtual(address, length, const_cast<unsigned char *>(data), length, &filled); if (FAILED(hr)) { if (errorMessage) { std::ostringstream estr; estr << "Cannot write " << length << " bytes to 0x" << std::hex << address << ": " << msgDebugEngineComFailed("FillVirtual", hr); *errorMessage = estr.str(); } return false; } if (filled < length) { if (errorMessage) { std::ostringstream estr; estr << "Filled only " << filled << " bytes of " << length << " at 0x" << std::hex << address << '.'; *errorMessage = estr.str(); } return false; } return true; } // Return allocated array of data unsigned char *SymbolGroupValue::pointerData(unsigned length) const { if (isValid()) if (const ULONG64 ptr = pointerValue()) return SymbolGroupValue::readMemory(m_context.dataspaces, ptr, length); return 0; } ULONG64 SymbolGroupValue::address() const { if (isValid()) return m_node->address(); return 0; } std::string SymbolGroupValue::module() const { return isValid() ? m_node->module() : std::string(); } // Temporary iname static inline std::string additionalSymbolIname(const SymbolGroup *g) { std::ostringstream str; str << "__additional" << g->root()->children().size(); return str.str(); } SymbolGroupValue SymbolGroupValue::typeCast(const char *type) const { return typeCastedValue(address(), type); } SymbolGroupValue SymbolGroupValue::pointerTypeCast(const char *type) const { return typeCastedValue(pointerValue(), type); } SymbolGroupValue SymbolGroupValue::typeCastedValue(ULONG64 address, const char *type) const { if (!address) return SymbolGroupValue(); const size_t len = strlen(type); if (!len) return SymbolGroupValue(); const bool nonPointer = type[len - 1] != '*'; SymbolGroup *sg = m_node->symbolGroup(); // A bit of magic: For desired pointer types, we can do // 'Foo *' -> '(Foo *)(address)'. // For non-pointers, we need to de-reference: // 'Foo' -> '*(Foo *)(address)' std::ostringstream str; if (nonPointer) str << '*'; str << '(' << type; if (nonPointer) str << " *"; str << ")(" << std::showbase << std::hex << address << ')'; if (SymbolGroupNode *node = sg->addSymbol(module(), str.str(), additionalSymbolIname(sg), &m_errorMessage)) return SymbolGroupValue(node, m_context); return SymbolGroupValue(); } SymbolGroupValue SymbolGroupValue::findMember(const SymbolGroupValue &start, const std::string &symbolName) { const unsigned count = start.childCount(); for (unsigned i = 0; i < count ; ++i) { // check members const SymbolGroupValue child = start[i]; if (child.name() == symbolName) return child; } // Recurse down base classes at the beginning that have class names // as value. for (unsigned i = 0; i < count; ++i) { const SymbolGroupValue child = start[i]; const std::wstring value = child.value(); if (value.compare(0, 6, L"class ") && value.compare(0, 7, L"struct ")) { break; } else { if (SymbolGroupValue r = findMember(child, symbolName)) return r; } } return SymbolGroupValue(); } std::wstring SymbolGroupValue::wcharPointerData(unsigned charCount, unsigned maxCharCount) const { const bool truncated = charCount > maxCharCount; if (truncated) charCount = maxCharCount; if (const unsigned char *ucData = pointerData(charCount * sizeof(wchar_t))) { const wchar_t *utf16Data = reinterpret_cast<const wchar_t *>(ucData); // Be smart about terminating 0-character if (charCount && utf16Data[charCount - 1] == 0) charCount--; std::wstring rc = std::wstring(utf16Data, charCount); if (truncated) rc += L"..."; delete [] ucData; return rc; } return std::wstring(); } std::string SymbolGroupValue::error() const { return m_errorMessage; } // Return number of characters to strip for pointer type unsigned SymbolGroupValue::isPointerType(const std::string &t) { if (endsWith(t, "**")) return 1; if (endsWith(t, " *")) return 2; return 0; } bool SymbolGroupValue::isArrayType(const std::string &t) { return endsWith(t, ']'); } // Return number of characters to strip for pointer type bool SymbolGroupValue::isVTableType(const std::string &t) { const char vtableTypeC[] = "__fptr()"; return t.compare(0, sizeof(vtableTypeC) - 1, vtableTypeC) == 0; } // add pointer type 'Foo' -> 'Foo *', 'Foo *' -> 'Foo **' std::string SymbolGroupValue::pointerType(const std::string &type) { std::string rc = type; if (!endsWith(type, '*')) rc.push_back(' '); rc.push_back('*'); return rc; } unsigned SymbolGroupValue::pointerSize() { static const unsigned ps = SymbolGroupValue::sizeOf("char *"); return ps; } unsigned SymbolGroupValue::intSize() { static const unsigned is = SymbolGroupValue::sizeOf("int"); return is; } unsigned SymbolGroupValue::pointerDiffSize() { static const unsigned is = SymbolGroupValue::sizeOf("ptrdiff_t"); return is; } unsigned SymbolGroupValue::sizeOf(const char *type) { const unsigned rc = GetTypeSize(type); if (!rc && SymbolGroupValue::verbose) DebugPrint() << "GetTypeSize fails for '" << type << '\''; return rc; } unsigned SymbolGroupValue::fieldOffset(const char *type, const char *field) { ULONG rc = 0; if (GetFieldOffset(type, field, &rc)) { if (SymbolGroupValue::verbose) DebugPrint() << "GetFieldOffset fails for '" << type << "' '" << field << '\''; return 0; } return rc; } std::string SymbolGroupValue::stripPointerType(const std::string &t) { // 'Foo *' -> 'Foo', 'Bar **' -> 'Bar *'. if (const unsigned stripLength = isPointerType(t)) return t.substr(0, t.size() - stripLength); return t; } // Strip "class Foo", "struct Bar"-> "Foo", "Bar " std::string SymbolGroupValue::stripClassPrefixes(const std::string &type) { std::string rc = type; if (rc.compare(0, 6, "class ") == 0) { rc.erase(0, 6); } else { if (rc.compare(0, 7, "struct ") == 0) rc.erase(0, 7); } return rc; } // Strip " const" from end of type ("XX const", "XX const *[*]" std::string SymbolGroupValue::stripConst(const std::string &type) { const std::string::size_type constPos = type.rfind(" const"); if (constPos == std::string::npos) return type; // Strip 'const' only if it is at the end 'QString const' // or of some pointer like 'foo ***' std::string rc = type; const std::string::size_type size = rc.size(); std::string::size_type nextPos = constPos + 6; if (nextPos == size) { // Ends with - easy. rc.erase(constPos, nextPos - constPos); return rc; } // Ensure it ends with ' ****'. if (rc.at(nextPos) != ' ') return rc; for (std::string::size_type i = nextPos + 1; i < size; ++i) if (rc.at(i) != '*') return rc; rc.erase(constPos, nextPos - constPos); return rc; } std::string SymbolGroupValue::addPointerType(const std::string &t) { // 'char' -> 'char *' -> 'char **' std::string rc = t; if (!endsWith(rc, '*')) rc.push_back(' '); rc.push_back('*'); return rc; } std::string SymbolGroupValue::stripArrayType(const std::string &t) { const std::string::size_type bracket = t.rfind('['); if (bracket != std::string::npos) { std::string rc = t.substr(0, bracket); trimBack(rc); return rc; } return t; } std::string SymbolGroupValue::stripModuleFromType(const std::string &type) { const std::string::size_type exclPos = type.find('!'); return exclPos != std::string::npos ? type.substr(exclPos + 1, type.size() - exclPos - 1) : type; } std::string SymbolGroupValue::moduleOfType(const std::string &type) { const std::string::size_type exclPos = type.find('!'); return exclPos != std::string::npos ? type.substr(0, exclPos) : std::string(); } // Symbol Name/(Expression) of a pointed-to instance ('Foo' at 0x10') ==> '*(Foo *)0x10' std::string SymbolGroupValue::pointedToSymbolName(ULONG64 address, const std::string &type) { std::ostringstream str; str << "*(" << type; if (!endsWith(type, '*')) str << ' '; str << "*)" << std::showbase << std::hex << address; return str.str(); } /*! \class QtInfo \brief The QtInfo class provides Qt information determined on demand. Namespace, modules, and basic class names containing the module for fast lookup. \ingroup qtcreatorcdbext */ const QtInfo &QtInfo::get(const SymbolGroupValueContext &ctx) { static QtInfo rc; if (!rc.libInfix.empty()) return rc; typedef std::list<std::string> StringList; typedef StringList::const_iterator StringListConstIt; std::string moduleName; std::string::size_type exclPos = std::string::npos; std::string::size_type libPos = std::string::npos; std::string::size_type qtPos = std::string::npos; const StringList &modules = SymbolGroupValue::getAllModuleNames(ctx); for (StringListConstIt module = modules.begin(), total = modules.end(); module != total; ++module) { moduleName = *module; qtPos = moduleName.find("Qt"); if (qtPos != std::string::npos) { libPos = moduleName.find("Core"); if (libPos != std::string::npos && (libPos - qtPos) < 4) break; } } if (libPos == std::string::npos) moduleName.clear(); else moduleName += '!'; const char* qstrdupSymbol = "*qstrdup"; std::string qualifiedSymbol; do { // Lookup qstrdup() to get the core module const std::string pattern = moduleName + qstrdupSymbol; const StringList &allMatches = SymbolGroupValue::resolveSymbolName(pattern.c_str(), ctx); if (!allMatches.empty()) { qualifiedSymbol = allMatches.front(); } else { if (!moduleName.empty()) { // If there is no qstrdup symbol in the module fall back to a global lookup. moduleName.clear(); continue; } } exclPos = qualifiedSymbol.find('!'); libPos = qualifiedSymbol.find("Core"); if (exclPos != std::string::npos) { if (!moduleName.empty()) { // found the core module // determine the qt version from the module name if (isdigit(qualifiedSymbol.at(2))) rc.version = qualifiedSymbol.at(2) - '0'; else rc.version = qualifiedSymbol.at(exclPos - 1) - '0'; rc.libInfix = qualifiedSymbol.substr(libPos + 4, exclPos - libPos - 4); } else { // Found the Qt symbol but in an unexpected module, most probably // it is a static build. rc.isStatic = true; rc.libInfix = qualifiedSymbol.substr(0, exclPos); // The Qt version cannot be determined by the module name. Looking up // qInstallMessageHandler which is in Qt since 5.0 to determine the version. const std::string pattern = rc.libInfix + "!*qInstallMessageHandler"; const StringList &allMatches = SymbolGroupValue::resolveSymbolName(pattern.c_str(), ctx); const StringListConstIt match = std::find_if(allMatches.begin(), allMatches.end(), SubStringPredicate(rc.libInfix.c_str())); rc.version = match == allMatches.end() ? 4 : 5; } // Any namespace? 'QtCored4!nsp::qstrdup' const std::string::size_type nameSpaceStart = exclPos + 1; const std::string::size_type colonPos = qualifiedSymbol.find(':', nameSpaceStart); if (colonPos != std::string::npos) rc.nameSpace = qualifiedSymbol.substr(nameSpaceStart, colonPos - nameSpaceStart); } else { // Can't find a basic Qt symbol so use a fallback rc.libInfix = "d4"; rc.version = 4; } } while (false); rc.qObjectType = rc.prependQtCoreModule("QObject"); rc.qObjectPrivateType = rc.prependQtCoreModule("QObjectPrivate"); rc.qWindowPrivateType = rc.prependQtGuiModule("QWindowPrivate"); rc.qWidgetPrivateType = rc.prependQtModule("QWidgetPrivate", rc.version >= 5 ? Widgets : Gui); if (SymbolGroupValue::verbose) DebugPrint() << rc; return rc; } std::string QtInfo::moduleName(Module m) const { if (isStatic) return libInfix; // Must match the enumeration static const char* modNames[] = {"Core", "Gui", "Widgets", "Network", "Script", "Qml" }; std::ostringstream result; result << "Qt"; if (version >= 5) result << version; result << modNames[m] << libInfix; return result.str(); } std::string QtInfo::prependModuleAndNameSpace(const std::string &type, const std::string &module, const std::string &aNameSpace) { // Strip the prefixes "class ", "struct ". std::string rc = SymbolGroupValue::stripClassPrefixes(type); // Is the namespace 'nsp::' missing? if (!aNameSpace.empty()) { const bool nameSpaceMissing = rc.size() <= aNameSpace.size() || rc.compare(0, aNameSpace.size(), aNameSpace) != 0 || rc.at(aNameSpace.size()) != ':'; if (nameSpaceMissing) { rc.insert(0, "::"); rc.insert(0, aNameSpace); } } // Is the module 'Foo!' missing? if (!module.empty()) { const bool moduleMissing = rc.size() <= module.size() || rc.compare(0, module.size(), module) != 0 || rc.at(module.size()) != '!'; if (moduleMissing) { rc.insert(0, 1, '!'); rc.insert(0, module); } } return rc; } int QtInfo::qtTypeInfoVersion(const SymbolGroupValueContext &ctx) { const QtInfo qtInfo = QtInfo::get(ctx); const std::string &hookDataSymbolName = qtInfo.prependQtCoreModule("qtHookData"); ULONG64 offset = 0; if (FAILED(ctx.symbols->GetOffsetByName(hookDataSymbolName.c_str(), &offset))) return 0; ULONG64 hookVer = SymbolGroupValue::readPointerValue(ctx.dataspaces, offset); if (hookVer < 3) return 0; offset += 6 * SymbolGroupValue::pointerSize(); return static_cast<int>(SymbolGroupValue::readPointerValue(ctx.dataspaces, offset)); } std::ostream &operator<<(std::ostream &os, const QtInfo &i) { os << "Qt Info: Version: " << i.version << " Modules '" << i.moduleName(QtInfo::Core) << "', '" << i.moduleName(QtInfo::Gui) << "', Namespace='" << i.nameSpace << "', types: " << i.qObjectType << ',' << i.qObjectPrivateType << ',' << i.qWidgetPrivateType; return os; } std::list<std::string> SymbolGroupValue::resolveSymbolName(const char *pattern, const SymbolGroupValueContext &c, std::string *errorMessage /* = 0 */) { // Extract the names const SymbolList symbols = resolveSymbol(pattern, c, errorMessage); std::list<std::string> rc; if (!symbols.empty()) { const SymbolList::const_iterator cend = symbols.end(); for (SymbolList::const_iterator it = symbols.begin(); it != cend; ++it) rc.push_back(it->first); } return rc; } SymbolGroupValue::SymbolList SymbolGroupValue::resolveSymbol(const char *pattern, const SymbolGroupValueContext &c, std::string *errorMessage /* = 0 */) { enum { bufSize = 2048 }; std::list<Symbol> rc; if (errorMessage) errorMessage->clear(); // Is it an incomplete symbol? if (!pattern[0]) return rc; ULONG64 handle = 0; // E_NOINTERFACE means "no match". Apparently, it does not always // set handle. HRESULT hr = c.symbols->StartSymbolMatch(pattern, &handle); if (hr == E_NOINTERFACE) { if (handle) c.symbols->EndSymbolMatch(handle); return rc; } if (FAILED(hr)) { if (errorMessage) *errorMessage= msgDebugEngineComFailed("StartSymbolMatch", hr); return rc; } char buf[bufSize]; ULONG64 offset; while (true) { hr = c.symbols->GetNextSymbolMatch(handle, buf, bufSize - 1, 0, &offset); if (hr == E_NOINTERFACE) break; if (hr == S_OK) rc.push_back(Symbol(std::string(buf), offset)); } c.symbols->EndSymbolMatch(handle); return rc; } std::list<std::string> SymbolGroupValue::getAllModuleNames(const SymbolGroupValueContext &c, std::string *errorMessage) { enum { bufSize = 2048 }; std::list<std::string> rc; ULONG moduleCount = 0; ULONG unloaded = 0; HRESULT hr = c.symbols->GetNumberModules(&moduleCount, &unloaded); if (FAILED(hr)) { if (errorMessage) *errorMessage = msgDebugEngineComFailed("GetNumberModules", hr); return rc; } moduleCount += unloaded; // lookup module names char moduleBuffer[bufSize]; for (ULONG index = 0; index < moduleCount; ++index) { hr = c.symbols->GetModuleNameString(DEBUG_MODNAME_MODULE, index, NULL, moduleBuffer, bufSize - 1, NULL); if (FAILED(hr)) { if (errorMessage) *errorMessage = msgDebugEngineComFailed("GetNumberModules", hr); return rc; } rc.push_back(moduleBuffer); } return rc; } // Resolve a type, that is, obtain its module name ('QString'->'QtCored4!QString') std::string SymbolGroupValue::resolveType(const std::string &typeIn, const SymbolGroupValueContext &ctx, const std::string &currentModule /* = "" */) { enum { BufSize = 512 }; if (typeIn.empty() || typeIn.find('!') != std::string::npos) return typeIn; const std::string stripped = SymbolGroupValue::stripClassPrefixes(typeIn); // Use the module of the current symbol group for templates. // This is because resolving some template types (std::list<> has been // observed to result in 'QtGui4d!std::list', which subsequently fails. if (!currentModule.empty() && stripped.find('<') != std::string::npos) { std::string trc = currentModule; trc.push_back('!'); trc += stripped; return trc; } // Obtain the base address of the module using an obscure ioctl() call. // See inline implementation of GetTypeSize() and docs. SYM_DUMP_PARAM symParameters = { sizeof (SYM_DUMP_PARAM), (PUCHAR)stripped.c_str(), DBG_DUMP_NO_PRINT, 0, NULL, NULL, NULL, 0, NULL }; const ULONG typeSize = Ioctl(IG_GET_TYPE_SIZE, &symParameters, symParameters.size); if (!typeSize || !symParameters.ModBase) // Failed? return stripped; const std::string module = moduleNameByOffset(ctx.symbols, symParameters.ModBase); if (module.empty()) return stripped; std::string rc = module; rc.push_back('!'); rc += stripped; return rc; } // get the inner types: "QMap<int, double>" -> "int", "double" std::vector<std::string> SymbolGroupValue::innerTypesOf(const std::string &t) { std::vector<std::string> rc; std::string::size_type pos = t.find('<'); if (pos == std::string::npos) return rc; rc.reserve(5); const std::string::size_type size = t.size(); // Record all elements of level 1 to work correctly for // 'std::map<std::basic_string< .. > >' unsigned level = 0; std::string::size_type start = 0; for ( ; pos < size ; pos++) { const char c = t.at(pos); switch (c) { case '<': if (++level == 1) start = pos + 1; break; case '>': if (--level == 0) { // last element std::string innerType = t.substr(start, pos - start); trimFront(innerType); trimBack(innerType); rc.push_back(innerType); return rc; } break; case ',': if (level == 1) { // std::map<a, b>: start anew at ','. std::string innerType = t.substr(start, pos - start); trimFront(innerType); trimBack(innerType); rc.push_back(innerType); start = pos + 1; } break; } } return rc; } std::ostream &operator<<(std::ostream &str, const SymbolGroupValue &v) { if (v) { str << '\'' << v.name() << "' 0x" << std::hex << v.address() << std::dec << ' ' << v.type() << ": '" << wStringToString(v.value()) << '\''; } else { str << "Invalid value '" << v.error() << '\''; } return str; } // -------------------- Simple dumping helpers // Courtesy of qdatetime.cpp static inline void getDateFromJulianDay(unsigned julianDay, int *year, int *month, int *day) { int y, m, d; if (julianDay >= 2299161) { typedef unsigned long long qulonglong; // Gregorian calendar starting from October 15, 1582 // This algorithm is from Henry F. Fliegel and Thomas C. Van Flandern qulonglong ell, n, i, j; ell = qulonglong(julianDay) + 68569; n = (4 * ell) / 146097; ell = ell - (146097 * n + 3) / 4; i = (4000 * (ell + 1)) / 1461001; ell = ell - (1461 * i) / 4 + 31; j = (80 * ell) / 2447; d = int(ell - (2447 * j) / 80); ell = j / 11; m = int(j + 2 - (12 * ell)); y = int(100 * (n - 49) + i + ell); } else { // Julian calendar until October 4, 1582 // Algorithm from Frequently Asked Questions about Calendars by Claus Toendering julianDay += 32082; int dd = (4 * julianDay + 3) / 1461; int ee = julianDay - (1461 * dd) / 4; int mm = ((5 * ee) + 2) / 153; d = ee - (153 * mm + 2) / 5 + 1; m = mm + 3 - 12 * (mm / 10); y = dd - 4800 + (mm / 10); if (y <= 0) --y; } if (year) *year = y; if (month) *month = m; if (day) *day = d; } const char *stdStringTypeC = "std::basic_string<char,std::char_traits<char>,std::allocator<char> >"; const char *stdWStringTypeC = "std::basic_string<unsigned short,std::char_traits<unsigned short>,std::allocator<unsigned short> >"; // Compiler option: -Zc:wchar_t-: const char *stdWStringWCharTypeC = "std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >"; static KnownType knownPODTypeHelper(const std::string &type, std::string::size_type endPos) { if (type.empty() || !endPos) return KT_Unknown; // Strip pointer types. const bool isPointer = type.at(endPos - 1) == '*'; if (isPointer) { endPos--; if (endPos > 0 && type.at(endPos - 1) == ' ') endPos--; } switch (type.at(0)) { case 'c': if (endPos == 4 && !type.compare(0, endPos, "char")) return isPointer ? KT_POD_PointerType : KT_Char; break; case 'd': if (endPos == 6 && !type.compare(0, endPos, "double")) return isPointer ? KT_POD_PointerType : KT_FloatType; break; case 'f': if (endPos == 5 && !type.compare(0, endPos, "float")) return isPointer ? KT_POD_PointerType : KT_FloatType; break; case 'l': if (endPos >= 4 && !type.compare(0, 4, "long")) if (endPos == 4 || type.at(4) == ' ') return isPointer ? KT_POD_PointerType : KT_IntType; break; case 'i': // 'int' 'int64' if (endPos >= 3 && !type.compare(0, 3, "int")) if (endPos == 3 || type.at(3) == ' ' || type.at(3) == '6') return isPointer ? KT_POD_PointerType : KT_IntType; break; case 's': if (endPos == 5 && !type.compare(0, 5, "short")) return isPointer ? KT_POD_PointerType : KT_IntType; if (endPos >= 6 && !type.compare(0, 6, "signed")) if (endPos == 6 || type.at(6) == ' ') return isPointer ? KT_POD_PointerType : KT_IntType; break; case 'u': if (endPos >= 8 && !type.compare(0, 8, "unsigned")) { if (endPos == 8 || type.at(8) == ' ') { if (isPointer) return KT_POD_PointerType; return type.compare(0, 13, "unsigned char") ? KT_UnsignedIntType : KT_UnsignedChar; } } break; } return isPointer ? KT_PointerType : KT_Unknown; } // Determine type starting from a position (with/without 'class '/'struct ' prefix). static KnownType knownClassTypeHelper(const std::string &type, std::string::size_type pos, std::string::size_type endPos) { // STL ? const std::wstring::size_type templatePos = type.find('<', pos); static const std::wstring::size_type stlClassLen = 5; if (!type.compare(pos, stlClassLen, "std::")) { // STL containers const std::wstring::size_type hPos = pos + stlClassLen; if (templatePos != std::string::npos) { switch (templatePos - stlClassLen - pos) { case 3: if (!type.compare(hPos, 3, "set")) return KT_StdSet; if (!type.compare(hPos, 3, "map")) return KT_StdMap; break; case 4: if (!type.compare(hPos, 4, "list")) return KT_StdList; break; case 5: if (!type.compare(hPos, 5, "stack")) return KT_StdStack; if (!type.compare(hPos, 5, "deque")) return KT_StdDeque; if (!type.compare(hPos, 5, "array")) return KT_StdArray; break; case 6: if (!type.compare(hPos, 6, "vector")) return KT_StdVector; break; case 7: if (!type.compare(hPos, 7, "complex")) return KT_StdComplex; break; case 8: if (!type.compare(hPos, 8, "multimap")) return KT_StdMultiMap; if (!type.compare(hPos, 8, "multiset")) return KT_StdMultiSet; if (!type.compare(hPos, 8, "valarray")) return KT_StdValArray; break; case 13: if (!type.compare(hPos, 13, "unordered_map")) return KT_StdUnorderedMap; if (!type.compare(hPos, 13, "unordered_set")) return KT_StdUnorderedSet; break; case 18: if (!type.compare(hPos, 18, "unordered_multimap")) return KT_StdUnorderedMultiMap; if (!type.compare(hPos, 18, "unordered_multiset")) return KT_StdUnorderedMultiSet; break; } } // STL strings if (!type.compare(pos, endPos - pos, stdStringTypeC)) return KT_StdString; if (!type.compare(pos, endPos - pos, stdWStringTypeC) || !type.compare(pos, endPos - pos, stdWStringWCharTypeC)) return KT_StdWString; return KT_Unknown; } // std::sth // Check for a 'Q' past the last namespace (beware of namespaced Qt: // 'nsp::QString'). const std::wstring::size_type lastNameSpacePos = type.rfind(':', templatePos); const std::wstring::size_type qPos = lastNameSpacePos == std::string::npos ? type.find('Q', pos) : lastNameSpacePos + 1; if (qPos == std::string::npos || qPos >= type.size() || type.at(qPos) != 'Q') return KT_Unknown; // Qt types (templates) if (templatePos != std::string::npos) { // Do not fall for QMap<K,T>::iterator, which is actually an inner class. if (endPos > templatePos && type.at(endPos - 1) != '>') return KT_Unknown; switch (templatePos - qPos) { case 4: if (!type.compare(qPos, 4, "QSet")) return KT_QSet; if (!type.compare(qPos, 4, "QMap")) return KT_QMap; break; case 5: if (!type.compare(qPos, 5, "QHash")) return KT_QHash; if (!type.compare(qPos, 5, "QList")) return KT_QList; break; case 6: if (!type.compare(qPos, 6, "QFlags")) return KT_QFlags; if (!type.compare(qPos, 6, "QStack")) return KT_QStack; if (!type.compare(qPos, 6, "QQueue")) return KT_QQueue; break; case 7: if (!type.compare(qPos, 7, "QVector")) return KT_QVector; break; case 9: if (!type.compare(qPos, 9, "QMultiMap")) return KT_QMultiMap; break; case 10: if (!type.compare(qPos, 10, "QMultiHash")) return KT_QMultiHash; break; case 11: if (!type.compare(qPos, 11, "QLinkedList")) return KT_QLinkedList; break; case 12: if (!type.compare(qPos, 12, "QWeakPointer")) return KT_QWeakPointer; break; case 14: if (!type.compare(qPos, 14, "QSharedPointer")) return KT_QSharedPointer; break; } } // Remaining non-template types switch (endPos - qPos) { case 4: if (!type.compare(qPos, 4, "QPen")) return KT_QPen; if (!type.compare(qPos, 4, "QUrl")) return KT_QUrl; if (!type.compare(qPos, 4, "QDir")) return KT_QDir; break; case 5: if (!type.compare(qPos, 5, "QChar")) return KT_QChar; if (!type.compare(qPos, 5, "QDate")) return KT_QDate; if (!type.compare(qPos, 5, "QTime")) return KT_QTime; if (!type.compare(qPos, 5, "QSize")) return KT_QSize; if (!type.compare(qPos, 5, "QLine")) return KT_QLine; if (!type.compare(qPos, 5, "QRect")) return KT_QRect; if (!type.compare(qPos, 5, "QIcon")) return KT_QIcon; if (!type.compare(qPos, 5, "QFile")) return KT_QFile; break; case 6: if (!type.compare(qPos, 6, "QColor")) return KT_QColor; if (!type.compare(qPos, 6, "QSizeF")) return KT_QSizeF; if (!type.compare(qPos, 6, "QPoint")) return KT_QPoint; if (!type.compare(qPos, 6, "QLineF")) return KT_QLineF; if (!type.compare(qPos, 6, "QRectF")) return KT_QRectF; if (!type.compare(qPos, 6, "QBrush")) return KT_QBrush; if (!type.compare(qPos, 6, "QImage")) return KT_QImage; if (!type.compare(qPos, 6, "QFixed")) return KT_QFixed; break; case 7: if (!type.compare(qPos, 7, "QString")) return KT_QString; if (!type.compare(qPos, 7, "QPointF")) return KT_QPointF; if (!type.compare(qPos, 7, "QObject")) return KT_QObject; if (!type.compare(qPos, 7, "QWidget")) return KT_QWidget; if (!type.compare(qPos, 7, "QWindow")) return KT_QWindow; if (!type.compare(qPos, 7, "QLocale")) return KT_QLocale; if (!type.compare(qPos, 7, "QMatrix")) return KT_QMatrix; if (!type.compare(qPos, 7, "QRegExp")) return KT_QRegExp; if (!type.compare(qPos, 7, "QRegion")) return KT_QRegion; if (!type.compare(qPos, 7, "QPixmap")) return KT_QPixmap; break; case 8: if (!type.compare(qPos, 8, "QVariant")) return KT_QVariant; if (!type.compare(qPos, 8, "QMargins")) return KT_QMargins; if (!type.compare(qPos, 8, "QXmlItem")) return KT_QXmltem; if (!type.compare(qPos, 8, "QXmlName")) return KT_QXmlName; if (!type.compare(qPos, 8, "QProcess")) return KT_QProcess; break; case 9: if (!type.compare(qPos, 9, "QBitArray")) return KT_QBitArray; if (!type.compare(qPos, 9, "QDateTime")) return KT_QDateTime; if (!type.compare(qPos, 9, "QFileInfo")) return KT_QFileInfo; if (!type.compare(qPos, 9, "QMetaEnum")) return KT_QMetaEnum; if (!type.compare(qPos, 9, "QTextItem")) return KT_QTextItem; if (!type.compare(qPos, 9, "QTimeZone")) return KT_QTimeZone; if (!type.compare(qPos, 9, "QVector2D")) return KT_QVector2D; if (!type.compare(qPos, 9, "QVector3D")) return KT_QVector3D; if (!type.compare(qPos, 9, "QVector4D")) return KT_QVector4D; break; case 10: if (!type.compare(qPos, 10, "QAtomicInt")) return KT_QAtomicInt; if (!type.compare(qPos, 10, "QByteArray")) return KT_QByteArray; if (!type.compare(qPos, 10, "QMatrix4x4")) return KT_QMatrix4x4; if (!type.compare(qPos, 10, "QTextBlock")) return KT_QTextBlock; if (!type.compare(qPos, 10, "QTransform")) return KT_QTransform; if (!type.compare(qPos, 10, "QFixedSize")) return KT_QFixedSize; if (!type.compare(qPos, 10, "QStringRef")) return KT_QStringRef; break; case 11: if (!type.compare(qPos, 11, "QStringList")) return KT_QStringList; if (!type.compare(qPos, 11, "QBasicTimer")) return KT_QBasicTimer; if (!type.compare(qPos, 11, "QMetaMethod")) return KT_QMetaMethod; if (!type.compare(qPos, 11, "QModelIndex")) return KT_QModelIndex; if (!type.compare(qPos, 11, "QQuaternion")) return KT_QQuaternion; if (!type.compare(qPos, 11, "QScriptItem")) return KT_QScriptItem; if (!type.compare(qPos, 11, "QFixedPoint")) return KT_QFixedPoint; if (!type.compare(qPos, 11, "QScriptLine")) return KT_QScriptLine; if (!type.compare(qPos, 11, "QTextCursor")) return KT_QTextCursor; break; case 12: if (!type.compare(qPos, 12, "QKeySequence")) return KT_QKeySequence; if (!type.compare(qPos, 12, "QHostAddress")) return KT_QHostAddress; if (!type.compare(qPos, 12, "QIPv6Address")) return KT_QIPv6Address; if (!type.compare(qPos, 12, "QScriptValue")) return KT_QScriptValue; break; case 13: if (!type.compare(qPos, 13, "QTextFragment")) return KT_QTextFragment; if (!type.compare(qPos, 13, "QTreeViewItem")) return KT_QTreeViewItem; break; case 14: if (!type.compare(qPos, 14, "QMetaClassInfo")) return KT_QMetaClassInfo; if (!type.compare(qPos, 14, "QNetworkCookie")) return KT_QNetworkCookie; break; case 15: if (!type.compare(qPos, 15, "QBasicAtomicInt")) return KT_QBasicAtomicInt; if (!type.compare(qPos, 15, "QHashDummyValue")) return KT_QHashDummyValue; if (!type.compare(qPos, 15, "QSourceLocation")) return KT_QSourceLocation; if (!type.compare(qPos, 15, "QScriptAnalysis")) return KT_QScriptAnalysis; break; case 16: if (!type.compare(qPos, 16, "QTextUndoCommand")) return KT_QTextUndoCommand; break; case 18: if (!type.compare(qPos, 18, "QNetworkProxyQuery")) return KT_QNetworkProxyQuery; if (!type.compare(qPos, 18, "QXmlNodeModelIndex")) return KT_QXmlNodeModelIndex; break; case 19: if (!type.compare(qPos, 19, "QItemSelectionRange")) return KT_QItemSelectionRange; if (!type.compare(qPos, 19, "QPaintBufferCommand")) return KT_QPaintBufferCommand; if (!type.compare(qPos, 19, "QTextHtmlParserNode")) return KT_QTextHtmlParserNode; if (!type.compare(qPos, 19, "QXmlStreamAttribute")) return KT_QXmlStreamAttribute; if (!type.compare(qPos, 19, "QGlyphJustification")) return KT_QGlyphJustification; break; case 20: if (!type.compare(qPos, 20, "QTextBlock::iterator")) return KT_QTextBlock_iterator; if (!type.compare(qPos, 20, "QTextFrame::iterator")) return KT_QTextFrame_iterator; break; case 21: if (!type.compare(qPos, 21, "QPersistentModelIndex")) return KT_QPersistentModelIndex; if (!type.compare(qPos, 21, "QPainterPath::Element")) return KT_QPainterPath_Element; break; case 22: if (!type.compare(qPos, 22, "QObjectPrivate::Sender")) return KT_QObjectPrivate_Sender; break; case 24: if (!type.compare(qPos, 24, "QPatternist::AtomicValue")) return KT_QPatternist_AtomicValue; if (!type.compare(qPos, 24, "QPatternist::Cardinality")) return KT_QPatternist_Cardinality; break; case 26: if (!type.compare(qPos, 26, "QObjectPrivate::Connection")) return KT_QObjectPrivate_Connection; if (!type.compare(qPos, 26, "QPatternist::ItemCacheCell")) return KT_QPatternist_ItemCacheCell; if (!type.compare(qPos, 26, "QPatternist::ItemType::Ptr")) return KT_QPatternist_ItemType_Ptr; if (!type.compare(qPos, 26, "QPatternist::NamePool::Ptr")) return KT_QPatternist_NamePool_Ptr; break; case 27: if (!type.compare(qPos, 27, "QXmlStreamEntityDeclaration")) return KT_QXmlStreamEntityDeclaration; break; case 28: if (!type.compare(qPos, 28, "QPatternist::Expression::Ptr")) return KT_QPatternist_Expression_Ptr; break; case 29: if (!type.compare(qPos, 29, "QXmlStreamNotationDeclaration")) return KT_QXmlStreamNotationDeclaration; break; case 30: if (!type.compare(qPos, 30, "QPatternist::SequenceType::Ptr")) return KT_QPatternist_SequenceType_Ptr; if (!type.compare(qPos, 30, "QXmlStreamNamespaceDeclaration")) return KT_QXmlStreamNamespaceDeclaration; break; case 32: break; if (!type.compare(qPos, 32, "QPatternist::Item::Iterator::Ptr")) return KT_QPatternist_Item_Iterator_Ptr; case 34: break; if (!type.compare(qPos, 34, "QPatternist::ItemSequenceCacheCell")) return KT_QPatternist_ItemSequenceCacheCell; case 37: break; if (!type.compare(qPos, 37, "QNetworkHeadersPrivate::RawHeaderPair")) return KT_QNetworkHeadersPrivate_RawHeaderPair; if (!type.compare(qPos, 37, "QPatternist::AccelTree::BasicNodeData")) return KT_QPatternist_AccelTree_BasicNodeData; break; } return KT_Unknown; } KnownType knownType(const std::string &type, unsigned flags) { if (type.empty()) return KT_Unknown; // Autostrip one pointer if desired const std::string::size_type endPos = (flags & KnownTypeAutoStripPointer) ? type.size() - SymbolGroupValue::isPointerType(type) : type.size(); // PODs first const KnownType podType = knownPODTypeHelper(type, endPos); if (podType != KT_Unknown) return podType; if (flags & KnownTypeHasClassPrefix) { switch (type.at(0)) { // Check 'class X' or 'struct X' case 'c': if (!type.compare(0, 6, "class ")) return knownClassTypeHelper(type, 6, endPos); break; case 's': if (!type.compare(0, 7, "struct ")) return knownClassTypeHelper(type, 7, endPos); break; } } else { // No prefix, full check return knownClassTypeHelper(type, 0, endPos); } return KT_Unknown; } void formatKnownTypeFlags(std::ostream &os, KnownType kt) { switch (kt) { case KT_Unknown: os << "<unknown>"; return; case KT_POD_PointerType: os << " pod_pointer"; break; case KT_PointerType: os << " pointer"; break; default: break; } if (kt & KT_POD_Type) os << " pod"; if (kt & KT_Qt_Type) os << " qt"; if (kt & KT_Qt_PrimitiveType) os << " qt_primitive"; if (kt & KT_Qt_MovableType) os << " qt_movable"; if (kt & KT_ContainerType) os << " container"; if (kt & KT_STL_Type) os << " stl"; if (kt & KT_HasSimpleDumper) os << " simple_dumper"; } unsigned SymbolGroupValue::isMovable(const std::string &t, const SymbolGroupValue &v) { KnownType kt = knownType(t, false); if (kt & (KT_POD_Type | KT_Qt_MovableType | KT_Qt_PrimitiveType)) return true; return kt == KT_QStringList && QtInfo::get(v.context()).version >= 5; } static inline DumpParameterRecodeResult checkCharArrayRecode(const SymbolGroupValue &v) { return DumpParameters::checkRecode(v.type(), std::string(), v.value(), v.context(), v.address()); } // Helper struct containing data Address and size/alloc information // from Qt's QString/QByteArray. struct QtStringAddressData { QtStringAddressData() : address(0), size(0), allocated(0) {} ULONG64 address; unsigned size; // Size and allocated are in ushort for QString's. unsigned allocated; }; /* Helper to determine the location and size of the data of * QStrings/QByteArrays for versions 4,5. In Qt 4, 'd' has a 'data' * pointer. In Qt 5, the d-elements and the data are in a storage pool * and the data are at an offset behind the d-structures (QString, * QByteArray, QVector). */ QtStringAddressData readQtStringAddressData(const SymbolGroupValue &dV, const QtInfo &qtInfo) { QtStringAddressData result; const std::string &arrayData = qtInfo.prependModuleAndNameSpace("QArrayData", std::string(), qtInfo.nameSpace); const SymbolGroupValue adV = qtInfo.version < 5 ? dV : dV[arrayData.c_str()]; if (!adV) return QtStringAddressData(); const SymbolGroupValue sizeV = adV["size"]; const SymbolGroupValue allocV = adV["alloc"]; if (!sizeV || !allocV) return QtStringAddressData(); result.size = sizeV.intValue(); result.allocated = allocV.intValue(); if (qtInfo.version < 5) { // Qt 4: Simple 'data' pointer. result.address = adV["data"].pointerValue(); } else { // Qt 5: Memory pool after the data element. const SymbolGroupValue offsetV = adV["offset"]; if (!offsetV) return QtStringAddressData(); // Take the address for QTypeArrayData of QByteArray, else // pointer value of D-pointer. const ULONG64 baseAddress = SymbolGroupValue::isPointerType(adV.type()) ? adV.pointerValue() : adV.address(); result.address = baseAddress + offsetV.intValue(); } return result; } // Retrieve data from a QByteArrayData(char)/QStringData(wchar_t) // in desired type. For empty arrays, no data are allocated. // All sizes are in CharType units. zeroTerminated means data are 0-terminated // in the data type, but "size" does not contain it. template <typename CharType> bool readQt5StringData(const SymbolGroupValue &dV, const QtInfo &qtInfo, bool zeroTerminated, unsigned position, unsigned sizeLimit, unsigned *fullSize, unsigned *arraySize, CharType **array) { *array = 0; const QtStringAddressData data = readQtStringAddressData(dV, qtInfo); if (!data.address || position > data.size) return false; const ULONG64 address = data.address + sizeof(CharType) * position; *fullSize = data.size - position; *arraySize = std::min(*fullSize, sizeLimit); if (!*fullSize) return true; const unsigned memorySize = sizeof(CharType) * (*arraySize + (zeroTerminated ? 1 : 0)); unsigned char *memory = SymbolGroupValue::readMemory(dV.context().dataspaces, address, memorySize); if (!memory) return false; *array = reinterpret_cast<CharType *>(memory); if ((*arraySize <= *fullSize) && zeroTerminated) *(*array + *arraySize) = CharType(0); return true; } static inline bool dumpQString(const SymbolGroupValue &v, std::wostream &str, MemoryHandle **memoryHandle = 0, unsigned position = 0, unsigned length = std::numeric_limits<unsigned>::max()) { const QtInfo &qtInfo = QtInfo::get(v.context()); const SymbolGroupValue dV = v["d"]; if (!dV) return false; // Qt 4. if (qtInfo.version < 5) { if (const SymbolGroupValue sizeValue = dV["size"]) { const int size = sizeValue.intValue(); if (size >= 0) { std::wstring stringData = dV["data"].wcharPointerData(size); if (position && position < stringData.size()) stringData.erase(0, position); if (length < stringData.size()) stringData.erase(length, stringData.size() - length); str << L'"' << stringData << L'"'; if (memoryHandle) *memoryHandle = MemoryHandle::fromStdWString(stringData); return true; } } return false; } // Qt 4. wchar_t *memory; unsigned fullSize; unsigned size; if (!readQt5StringData(dV, qtInfo, true, position, std::min(length, ExtensionContext::instance().parameters().maxStringLength), &fullSize, &size, &memory)) return false; if (size) { str << L'"' << memory; if (std::min(fullSize, length) > size) str << L"..."; str << L'"'; } else { str << L"\"\""; } if (memoryHandle) *memoryHandle = new MemoryHandle(memory, size); else delete [] memory; return true; } static inline bool dumpQStringRef(const SymbolGroupValue &v, std::wostream &str, MemoryHandle **memoryHandle = 0) { const int position = v["m_position"].intValue(); const int size = v["m_size"].intValue(); if (position < 0 || size < 0) return false; const SymbolGroupValue string = v["m_string"]; if (!string || !dumpQString(string, str, memoryHandle, position, size)) return false; str << L" (" << position << ',' << size << L')'; return true; } /* Pad a memory offset to align with pointer size */ static inline unsigned padOffset(unsigned offset) { const unsigned ps = SymbolGroupValue::pointerSize(); return (offset % ps) ? (1 + offset / ps) * ps : offset; } /* Return the offset to be accounted for "QSharedData" to access * the first member of a QSharedData-derived class */ static unsigned qSharedDataSize(const SymbolGroupValueContext &ctx) { unsigned offset = 0; if (!offset) { // As of 4.X, a QAtomicInt, which will be padded to 8 on a 64bit system. const std::string qSharedData = QtInfo::get(ctx).prependQtCoreModule("QSharedData"); offset = SymbolGroupValue::sizeOf(qSharedData.c_str()); } return offset; } /* Return the size of a QString */ static unsigned qStringSize(const SymbolGroupValueContext &/*ctx*/) { // static const unsigned size = SymbolGroupValue::sizeOf(QtInfo::get(ctx).prependQtCoreModule("QString").c_str()); // FIXME: Workaround the issue that GetTypeSize returns strange values; static const unsigned size = SymbolGroupValue::pointerSize(); return size; } /* Return the size of a QList via QStringList. */ static unsigned qListSize(const SymbolGroupValueContext &ctx) { static const unsigned size = SymbolGroupValue::sizeOf(QtInfo::get(ctx).prependQtCoreModule("QStringList").c_str()); return size; } /* Return the size of a QByteArray */ static unsigned qByteArraySize(const SymbolGroupValueContext &/*ctx*/) { // static const unsigned size = SymbolGroupValue::sizeOf(QtInfo::get(ctx).prependQtCoreModule("QByteArray").c_str()); // FIXME: Workaround the issue that GetTypeSize returns strange values; static const unsigned size = SymbolGroupValue::pointerSize(); return size; } /* Return the size of a QAtomicInt */ static unsigned qAtomicIntSize(const SymbolGroupValueContext &ctx) { static const unsigned size = SymbolGroupValue::sizeOf(QtInfo::get(ctx).prependQtCoreModule("QAtomicInt").c_str()); return size; } // Dump a QByteArray static inline bool dumpQByteArray(const SymbolGroupValue &v, std::wostream &str, std::string *encoding, MemoryHandle **memoryHandle = 0) { const QtInfo &qtInfo = QtInfo::get(v.context()); const SymbolGroupValue dV = v["d"]; if (!dV) return false; // Qt 4. if (qtInfo.version < 5) { if (const SymbolGroupValue data = dV["data"]) { const DumpParameterRecodeResult check = checkCharArrayRecode(data); if (check.buffer) { str << quotedWStringFromCharData(check.buffer, check.size); delete [] check.buffer; } else { str << data.value(); } return true; } return false; } // Qt 5: Data start at offset past the 'd' of type QByteArrayData. if (encoding) *encoding = "latin1"; wchar_t oldFill = str.fill(wchar_t('0')); str << std::hex; char *memory; unsigned fullSize; unsigned size; const unsigned &maxStringSize = ExtensionContext::instance().parameters().maxStringLength; if (!readQt5StringData(dV, qtInfo, false, 0, maxStringSize, &fullSize, &size, &memory)) return false; if (size) { char *memEnd = memory + size; for (char *p = memory; p < memEnd; p++) { const unsigned char c = *p; str << std::setw(2) << c; } if (fullSize > size) str << L"2e2e2e"; // ... } if (memoryHandle) *memoryHandle = new MemoryHandle(reinterpret_cast<unsigned char *>(memory), size); else delete [] memory; str << std::dec; str.fill(oldFill); return true; } /* Below are some helpers for simple dumpers for some Qt classes accessing their * private classes without the debugger's symbolic information (applicable to non-exported * private classes such as QFileInfoPrivate, etc). This is done by dereferencing the * d-ptr and obtaining the address of the variable (considering some offsets depending on type) * and adding a symbol for that QString or QByteArray (basically using raw memory). */ enum QPrivateDumpMode // Enumeration determining the offsets to be taken into consideration { QPDM_None, QPDM_qVirtual, // For classes with virtual functions (QObject-based): Skip vtable for d-address QPDM_qSharedData, // Private class is based on QSharedData, non-padded type QPDM_qSharedDataPadded // Private class is based on QSharedData, padded type (class) }; // Determine the address of private class member by dereferencing the d-ptr and using offsets. static ULONG64 addressOfQPrivateMember(const SymbolGroupValue &v, QPrivateDumpMode mode, unsigned additionalOffset = 0) { std::string errorMessage; // Dererence d-Ptr (Pointer/Value duality: Value or object address). ULONG64 dAddress = SymbolGroupValue::isPointerType(v.type()) ? v.pointerValue() : v.address(); if (!dAddress) return 0; if (mode == QPDM_qVirtual) // Skip vtable. dAddress += SymbolGroupValue::pointerSize(); const ULONG64 dptr = SymbolGroupValue::readPointerValue(v.context().dataspaces, dAddress, &errorMessage); if (!dptr) return 0; // Get address of type to be dumped. ULONG64 dumpAddress = dptr + additionalOffset; if (mode == QPDM_qSharedData) { // Simple type following QSharedData dumpAddress += qSharedDataSize(v.context()); } else if (mode == QPDM_qSharedDataPadded) { dumpAddress += padOffset(qSharedDataSize(v.context())); } return dumpAddress; } // Convenience to dump a QString from the unexported private class of a Qt class. static bool dumpQStringFromQPrivateClass(const SymbolGroupValue &v, QPrivateDumpMode mode, unsigned additionalOffset, std::wostream &str) { std::string errorMessage; const ULONG64 stringAddress = addressOfQPrivateMember(v, mode, additionalOffset); if (!stringAddress) return false; std::string dumpType = QtInfo::get(v.context()).prependQtCoreModule("QString"); std::string symbolName = SymbolGroupValue::pointedToSymbolName(stringAddress , dumpType); if (SymbolGroupValue::verbose > 1) DebugPrint() << "dumpQStringFromQPrivateClass of " << v.name() << '/' << v.type() << " mode=" << mode << " offset=" << additionalOffset << " address=0x" << std::hex << stringAddress << std::dec << " expr=" << symbolName; SymbolGroupNode *stringNode = v.node()->symbolGroup()->addSymbol(v.module(), symbolName, std::string(), &errorMessage); if (!stringNode && errorMessage.find("DEBUG_ANY_ID") != std::string::npos) { // HACK: // In some rare cases the AddSymbol can't create a node with a given module name, // but is able to add the symbol without any modulename. dumpType = QtInfo::get(v.context()).prependModuleAndNameSpace("QString", "", QtInfo::get(v.context()).nameSpace); symbolName = SymbolGroupValue::pointedToSymbolName(stringAddress , dumpType); stringNode = v.node()->symbolGroup()->addSymbol(v.module(), symbolName, std::string(), &errorMessage); if (!stringNode) return false; } return dumpQString(SymbolGroupValue(stringNode, v.context()), str); } // Convenience to dump a QByteArray from the unexported private class of a Qt class. static bool dumpQByteArrayFromQPrivateClass(const SymbolGroupValue &v, QPrivateDumpMode mode, unsigned additionalOffset, std::wostream &str, std::string *encoding) { std::string errorMessage; const ULONG64 byteArrayAddress = addressOfQPrivateMember(v, mode, additionalOffset); if (!byteArrayAddress) return false; std::string dumpType = QtInfo::get(v.context()).prependQtCoreModule("QByteArray"); std::string symbolName = SymbolGroupValue::pointedToSymbolName(byteArrayAddress , dumpType); if (SymbolGroupValue::verbose > 1) DebugPrint() << "dumpQByteArrayFromQPrivateClass of " << v.name() << '/' << v.type() << " mode=" << mode << " offset=" << additionalOffset << " address=0x" << std::hex << byteArrayAddress << std::dec << " expr=" << symbolName; SymbolGroupNode *byteArrayNode = v.node()->symbolGroup()->addSymbol(v.module(), symbolName, std::string(), &errorMessage); if (!byteArrayNode && errorMessage.find("DEBUG_ANY_ID") != std::string::npos) { // HACK: // In some rare cases the AddSymbol can't create a node with a given module name, // but is able to add the symbol without any modulename. dumpType = QtInfo::get(v.context()).prependModuleAndNameSpace("QByteArray", "", QtInfo::get(v.context()).nameSpace); symbolName = SymbolGroupValue::pointedToSymbolName(byteArrayAddress , dumpType); byteArrayNode = v.node()->symbolGroup()->addSymbol(v.module(), symbolName, std::string(), &errorMessage); if (!byteArrayNode) return false; } return dumpQByteArray(SymbolGroupValue(byteArrayNode, v.context()), str, encoding); } /* Dump QFileInfo, for whose private class no debugging information is available. * Dump 2nd string past its QSharedData base class. */ static inline bool dumpQFileInfo(const SymbolGroupValue &v, std::wostream &str) { return dumpQStringFromQPrivateClass(v, QPDM_qSharedDataPadded, 0, str); } /* Dump QDir, for whose private class no debugging information is available. * Dump 1st string past its QSharedData base class. */ static bool inline dumpQDir(const SymbolGroupValue &v, std::wostream &str) { const unsigned offset = v.fieldOffset(QtInfo::get(v.context()).prependQtCoreModule("QDirPrivate").c_str(), "dirEntry.m_filePath"); return dumpQStringFromQPrivateClass(v, QPDM_None, offset, str); } /* Dump QRegExp, for whose private class no debugging information is available. * Dump 1st string past of its base class. */ static inline bool dumpQRegExp(const SymbolGroupValue &v, std::wostream &str) { return dumpQStringFromQPrivateClass(v, QPDM_qSharedDataPadded, 0, str); } static inline bool dumpQRegion(const SymbolGroupValue &v, std::wostream &str, void **specialInfo) { const QtInfo info = QtInfo::get(v.context()); SymbolGroupValue d = v["d"]["qt_rgn"]; std::ostringstream namestr; namestr << "(" << info.prependQtGuiModule("QRegionPrivate *") << ")(" << std::showbase << std::hex << d.pointerValue() << ')'; SymbolGroupNode *qRegionPrivateNode = v.node()->symbolGroup()->addSymbol(v.module(), namestr.str(), std::string(), &std::string()); if (!qRegionPrivateNode) return false; const SymbolGroupValue qRegionPrivateValue = SymbolGroupValue(qRegionPrivateNode, v.context()); if (!qRegionPrivateValue) return false; const int size = containerSize(KT_QVector, qRegionPrivateValue["rects"]); if (size == -1) return false; str << L'<' << size << L" items>"; if (specialInfo) *specialInfo = qRegionPrivateNode; return true; } /* Dump QFile, for whose private class no debugging information is available. * Dump the 1st string first past its QIODevicePrivate base class. */ static inline bool dumpQFile(const SymbolGroupValue &v, std::wostream &str) { // Get address of the file name string, obtain value by dumping a QString at address static unsigned qFileBasePrivateSize = 0; if (!qFileBasePrivateSize) { const QtInfo info = QtInfo::get(v.context()); const std::string qIoDevicePrivateType =info.prependQtCoreModule( info.version < 5 ? "QIODevicePrivate" : "QFileDevicePrivate"); qFileBasePrivateSize = padOffset(SymbolGroupValue::sizeOf(qIoDevicePrivateType.c_str())); } if (!qFileBasePrivateSize) return false; return dumpQStringFromQPrivateClass(v, QPDM_qVirtual, qFileBasePrivateSize, str); } static inline bool dumpQIPv6Address(const SymbolGroupValue &v, std::wostream &str, std::string *encoding) { unsigned char *p = SymbolGroupValue::readMemory( v.context().dataspaces, v["c"].address(), 16); if (!p || !encoding) return false; const wchar_t oldFill = str.fill('0'); str << std::hex; for (unsigned char *it = p; it < p + 16; ++it) { if ((p - it) % 2 == 0 && it != p) str << ':'; str << std::setw(2) << *it; } str << std::dec; str.fill(oldFill); *encoding = "ipv6addressandhexscopeid"; return true; } /* Dump QHostAddress, for whose private class no debugging information is available. * Dump string 'ipString' past of its private class. Does not currently work? */ static inline bool dumpQHostAddress(const SymbolGroupValue &v, std::wostream &str, std::string *encoding) { // Determine offset in private struct: qIPv6AddressType (array, unaligned) + uint32 + enum. const QtInfo info = QtInfo::get(v.context()); SymbolGroupValue d = v["d"]["d"]; std::ostringstream namestr; namestr << '(' << info.prependQtNetworkModule("QHostAddressPrivate *") << ")(" << std::showbase << std::hex << d.pointerValue() << ')'; SymbolGroupNode *qHostAddressPrivateNode = v.node()->symbolGroup()->addSymbol(v.module(), namestr.str(), std::string(), &std::string()); if (!qHostAddressPrivateNode) return false; const SymbolGroupValue qHostAddressPrivateValue = SymbolGroupValue(qHostAddressPrivateNode, v.context()); const bool parsed = readPODFromMemory<bool>(qHostAddressPrivateValue.context().dataspaces, qHostAddressPrivateValue["isParsed"].address(), sizeof(bool), false, &std::string()); if (parsed) { const int protocol = qHostAddressPrivateValue["protocol"].intValue(-1); if (protocol < 0) { str << L"Uninitialized/Unknown protocol"; return true; } if (protocol == 1) { if (dumpQIPv6Address(qHostAddressPrivateValue["a6"], str, encoding)) return true; str << L"IPv6 protocol"; return true; } DebugPrint() << v.name().c_str() << ": " << parsed; const SymbolGroupValue a = qHostAddressPrivateValue["a"]; const unsigned int address = static_cast<unsigned int>(SymbolGroupValue::readIntValue(v.context().dataspaces, a.address())); str << (address >> 24) << '.' << (address << 8 >> 24) << '.' << (address << 16 >> 24) << '.' << (address << 24 >> 24); return true; } unsigned offset = 0; if (info.version < 5) { static unsigned qIPv6AddressSize = 0; if (!qIPv6AddressSize) { const std::string qIPv6AddressType = QtInfo::get(v.context()).prependQtNetworkModule("QIPv6Address"); qIPv6AddressSize = SymbolGroupValue::sizeOf(qIPv6AddressType.c_str()); } if (!qIPv6AddressSize) return false; offset = padOffset(8 + qIPv6AddressSize); } return dumpQStringFromQPrivateClass(v, QPDM_None, offset, str); } /* Dump QProcess, for whose private class no debugging information is available. * Dump string 'program' string with empirical offset. */ static inline bool dumpQProcess(const SymbolGroupValue &v, std::wostream &str) { const unsigned offset = SymbolGroupValue::pointerSize() == 8 ? 424 : 260; return dumpQStringFromQPrivateClass(v, QPDM_qVirtual, offset, str); } /* Dump QScriptValue, for whose private class no debugging information is available. * Private class has a pointer to engine, type enumeration and a JSC:JValue and double/QString * for respective types. */ static inline bool dumpQScriptValue(const SymbolGroupValue &v, std::wostream &str) { std::string errorMessage; // Read out type const ULONG64 privateAddress = addressOfQPrivateMember(v, QPDM_None, 0); if (!privateAddress) { // Can actually be 0 for default-constructed str << L"<Invalid>"; return true; } const unsigned ps = SymbolGroupValue::pointerSize(); // Offsets of QScriptValuePrivate const unsigned jscScriptValueSize = 8; // Union of double and rest. const unsigned doubleValueOffset = 2 * ps + jscScriptValueSize; const unsigned stringValueOffset = doubleValueOffset + sizeof(double); const ULONG64 type = SymbolGroupValue::readUnsignedValue(v.context().dataspaces, privateAddress + ps, 4, 0, &errorMessage); switch (type) { case 1: str << SymbolGroupValue::readDouble(v.context().dataspaces, privateAddress + doubleValueOffset); break; case 2: return dumpQStringFromQPrivateClass(v, QPDM_None, stringValueOffset, str); default: str << L"<JavaScriptCore>"; break; } return true; } /* Dump QUrl for whose private class no debugging information is available. * Dump the 'originally encoded' byte array of its private class. */ static inline bool dumpQUrl(const SymbolGroupValue &v, std::wostream &str) { // Get address of the original-encoded byte array, obtain value by dumping at address if (QtInfo::get(v.context()).version < 5) { const ULONG offset = padOffset(qAtomicIntSize(v.context())) + 6 * qStringSize(v.context()) + qByteArraySize(v.context()); return dumpQByteArrayFromQPrivateClass(v, QPDM_None, offset, str, 0); } ULONG offset = qAtomicIntSize(v.context()) + SymbolGroupValue::intSize(); const unsigned stringSize = qStringSize(v.context()); str << L"Scheme: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; offset += stringSize; str << L" User: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; offset += stringSize; str << L" Password: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; offset += stringSize; str << L" Host: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; offset += stringSize; str << L" Path: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; offset += stringSize; str << L" Query: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; offset += stringSize; str << L" Fragment: "; if (!dumpQStringFromQPrivateClass(v, QPDM_None, offset, str)) return false; return true; } // Dump QColor static bool dumpQColor(const SymbolGroupValue &v, std::wostream &str) { const SymbolGroupValue specV = v["cspec"]; if (!specV) return false; const int spec = specV.intValue(); if (spec == 0) { str << L"<Invalid color>"; return true; } if (spec < 1 || spec > 4) return false; const SymbolGroupValue arrayV = v["ct"]["array"]; if (!arrayV) return false; const int a0 = arrayV["0"].intValue(); const int a1 = arrayV["1"].intValue(); const int a2 = arrayV["2"].intValue(); const int a3 = arrayV["3"].intValue(); const int a4 = arrayV["4"].intValue(); if (a0 < 0 || a1 < 0 || a2 < 0 || a3 < 0 || a4 < 0) return false; switch (spec) { case 1: // Rgb str << L"RGB alpha=" << (a0 / 0x101) << L", red=" << (a1 / 0x101) << L", green=" << (a2 / 0x101) << ", blue=" << (a3 / 0x101); break; case 2: // Hsv str << L"HSV alpha=" << (a0 / 0x101) << L", hue=" << (a1 / 100) << L", sat=" << (a2 / 0x101) << ", value=" << (a3 / 0x101); break; case 3: // Cmyk str << L"CMYK alpha=" << (a0 / 0x101) << L", cyan=" << (a1 / 100) << L", magenta=" << (a2 / 0x101) << ", yellow=" << (a3 / 0x101) << ", black=" << (a4 / 0x101); break; case 4: // Hsl str << L"HSL alpha=" << (a0 / 0x101) << L", hue=" << (a1 / 100) << L", sat=" << (a2 / 0x101) << ", lightness=" << (a3 / 0x101); break; } return true; } // Dump Qt's core types static inline bool dumpQBasicAtomicInt(const SymbolGroupValue &v, std::wostream &str) { if (const SymbolGroupValue iValue = v["_q_value"]) { str << iValue.value(); return true; } return false; } static inline bool dumpQAtomicInt(const SymbolGroupValue &v, std::wostream &str) { if (const SymbolGroupValue base = v[unsigned(0)]) return dumpQBasicAtomicInt(base, str); return false; } static bool dumpQChar(const SymbolGroupValue &v, std::wostream &str) { if (SymbolGroupValue cValue = v["ucs"]) { const int utf16 = cValue.intValue(); if (utf16 >= 0) { // Print code = character, // exclude control characters and Pair indicator if (utf16 >= 32 && (utf16 < 0xD800 || utf16 > 0xDBFF)) str << '\'' << wchar_t(utf16) << "' "; str << '(' << utf16 << ')'; } return true; } return false; } static inline bool dumpQFlags(const SymbolGroupValue &v, std::wostream &str) { if (SymbolGroupValue iV = v["i"]) { const int i = iV.intValue(); if (i >= 0) { str << i; return true; } } return false; } static bool dumpQDate(const SymbolGroupValue &v, std::wostream &str, std::string *encoding) { if (const SymbolGroupValue julianDayV = v["jd"]) { if (julianDayV.intValue() > 0) { str << julianDayV.intValue(); if (encoding) *encoding = "juliandate"; } else { str << L"(invalid)"; } return true; } return false; } static bool dumpQTime(const SymbolGroupValue &v, std::wostream &str, std::string *encoding) { if (const SymbolGroupValue milliSecsV = v["mds"]) { const int milliSecs = milliSecsV.intValue(); str << milliSecs; if (encoding) *encoding = "millisecondssincemidnight"; return true; } return false; } static bool dumpQTimeZone(const SymbolGroupValue &v, std::wostream &str, std::string *encoding) { if (!dumpQByteArrayFromQPrivateClass(v, QPDM_qSharedDataPadded, SymbolGroupValue::pointerSize(), str, encoding)) str << L"(null)"; return true; } // Convenience to dump a QTimeZone from the unexported private class of a Qt class. static bool dumpQTimeZoneFromQPrivateClass(const SymbolGroupValue &v, QPrivateDumpMode mode, unsigned additionalOffset, std::wostream &str, std::string *encoding) { std::string errorMessage; const ULONG64 timeZoneAddress = addressOfQPrivateMember(v, mode, additionalOffset); if (!timeZoneAddress) return false; std::string dumpType = QtInfo::get(v.context()).prependQtCoreModule("QTimeZone"); std::string symbolName = SymbolGroupValue::pointedToSymbolName(timeZoneAddress , dumpType); if (SymbolGroupValue::verbose > 1) DebugPrint() << "dumpQTimeZoneFromQPrivateClass of " << v.name() << '/' << v.type() << " mode=" << mode << " offset=" << additionalOffset << " address=0x" << std::hex << timeZoneAddress << std::dec << " expr=" << symbolName; SymbolGroupNode *timeZoneNode = v.node()->symbolGroup()->addSymbol(v.module(), symbolName, std::string(), &errorMessage); if (!timeZoneNode && errorMessage.find("DEBUG_ANY_ID") != std::string::npos) { // HACK: // In some rare cases the AddSymbol can't create a node with a given module name, // but is able to add the symbol without any modulename. dumpType = QtInfo::get(v.context()).prependModuleAndNameSpace("QTimeZone", "", QtInfo::get(v.context()).nameSpace); symbolName = SymbolGroupValue::pointedToSymbolName(timeZoneAddress , dumpType); timeZoneNode = v.node()->symbolGroup()->addSymbol(v.module(), symbolName, std::string(), &errorMessage); if (!timeZoneNode) return false; } return dumpQTimeZone(SymbolGroupValue(timeZoneNode, v.context()), str, encoding); } // QDateTime has an unexported private class. Obtain date and time // from memory. static bool dumpQDateTime(const SymbolGroupValue &v, std::wostream &str, std::string *encoding) { // QDate is 64bit starting from Qt 5 which is always aligned 64bit. if (QtInfo::get(v.context()).version == 5) { // the dumper on the creator side expects msecs/spec/offset/tz/status/type info version const char separator = '/'; LONG64 msecs = 0; int spec = 0; int offset = 0; std::wstring timeZoneString; int status = 0; int tiVersion = QtInfo::qtTypeInfoVersion(v.context()); if (tiVersion > 10) { const ULONG64 address = SymbolGroupValue::isPointerType(v.type()) ? v.pointerValue() : v.address(); const ULONG64 data = SymbolGroupValue::readUnsignedValue( v.context().dataspaces, address, 8, 0); status = data & 0xFF; ULONG64 timeZone = 0; if (status & 0x01) { msecs = data >> 8; spec = (status & 0x30) >> 4; } else { ULONG64 addr = SymbolGroupValue::readPointerValue(v.context().dataspaces, address); msecs = SymbolGroupValue::readSignedValue(v.context().dataspaces, addr, 8, 0); addr += 8 /*int64*/; status = SymbolGroupValue::readIntValue(v.context().dataspaces, addr); addr += SymbolGroupValue::intSize(); offset = SymbolGroupValue::readIntValue(v.context().dataspaces, addr); addr += 2 * SymbolGroupValue::intSize(); timeZone = SymbolGroupValue::readPointerValue(v.context().dataspaces, addr); } timeZoneString = std::to_wstring(timeZone); } else { const ULONG64 msecsAddr = addressOfQPrivateMember(v, QPDM_None, 0); if (!msecsAddr) return false; int addrOffset = 8 /*QSharedData + padded*/; msecs = SymbolGroupValue::readSignedValue( v.context().dataspaces, msecsAddr + addrOffset, 8, 0); addrOffset += 8 /*int64*/; spec = SymbolGroupValue::readIntValue(v.context().dataspaces, msecsAddr + addrOffset); addrOffset += SymbolGroupValue::sizeOf("Qt::TimeSpec"); offset = SymbolGroupValue::readIntValue(v.context().dataspaces, msecsAddr + addrOffset); addrOffset += SymbolGroupValue::intSize(); std::wostringstream timeZoneStream; dumpQTimeZoneFromQPrivateClass(v, QPDM_None, addrOffset, timeZoneStream, 0); timeZoneString = timeZoneStream.str(); addrOffset += SymbolGroupValue::sizeOf("QTimeZone"); status = SymbolGroupValue::readIntValue(v.context().dataspaces, msecsAddr + addrOffset); } enum StatusFlag { ValidDate = 0x04, ValidTime = 0x08, ValidDateTime = 0x10 }; if (!(status & ValidDateTime || ((status & ValidDate) && (status & ValidTime)))) { str << L"(invalid)"; return true; } str << msecs << separator << spec << separator << offset << separator << timeZoneString << separator << status << separator << tiVersion; if (encoding) *encoding = "datetimeinternal"; return true; } const ULONG64 dateAddr = addressOfQPrivateMember(v, QPDM_qSharedData, 0); if (!dateAddr) return false; const int date = SymbolGroupValue::readIntValue(v.context().dataspaces, dateAddr, SymbolGroupValue::intSize(), 0); if (!date) { str << L"<null>"; return true; } const ULONG64 timeAddr = dateAddr + SymbolGroupValue::intSize(); const int time = SymbolGroupValue::readIntValue(v.context().dataspaces, timeAddr, SymbolGroupValue::intSize(), 0); str << date << '/' << time; if (encoding) *encoding = "juliandateandmillisecondssincemidnight"; return true; } static bool dumpQPixmap(const SymbolGroupValue &v, std::wostream &str) { const SymbolGroupValue pixmapSharedData = v["data"]["d"]; if (!pixmapSharedData.isValid()) return false; ULONG64 addr = pixmapSharedData.pointerValue(); if (addr) { const unsigned int width = SymbolGroupValue::readIntValue(v.context().dataspaces, addr += SymbolGroupValue::pointerSize(), SymbolGroupValue::intSize(), 0); const unsigned int height = SymbolGroupValue::readIntValue(v.context().dataspaces, addr += SymbolGroupValue::intSize(), SymbolGroupValue::intSize(), 0); const unsigned int depth = SymbolGroupValue::readIntValue(v.context().dataspaces, addr += SymbolGroupValue::intSize(), SymbolGroupValue::intSize(), 0); if (width && height) { str << width << L'x' << height << L", depth: " << depth; return true; } } str << L"<null>"; return true; } static bool dumpQImage(const SymbolGroupValue &v, std::wostream &str, MemoryHandle **memoryHandle) { struct CreatorImageHeader { // Header for image display as edit format, followed by data. int width; int height; int format; }; const QtInfo &qtInfo(QtInfo::get(v.context())); // Fetch data of unexported private class const ULONG64 address = v["d"].pointerValue(); if (!address) { str << L"<null>"; return true; } const std::string qImageDataType = qtInfo.prependQtGuiModule("QImageData"); const unsigned long size = SymbolGroupValue::sizeOf(qImageDataType.c_str()); if (!size) return false; unsigned char *qImageData = SymbolGroupValue::readMemory(v.context().dataspaces, address, size); if (!qImageData) return false; // read size data unsigned char *ptr = qImageData + qAtomicIntSize(v.context()); CreatorImageHeader header; header.width = *(reinterpret_cast<int *>(ptr)); ptr += SymbolGroupValue::intSize(); header.height = *(reinterpret_cast<int *>(ptr)); ptr += SymbolGroupValue::intSize(); const int depth = *(reinterpret_cast<int *>(ptr)); ptr += SymbolGroupValue::intSize(); const int nbytes = *(reinterpret_cast<int *>(ptr)); const unsigned dataOffset = SymbolGroupValue::fieldOffset(qImageDataType.c_str(), "data"); // Qt 4 has a Qt 3 support pointer member between 'data' and 'format'. const unsigned formatOffset = SymbolGroupValue::fieldOffset(qImageDataType.c_str(), "format"); if (!dataOffset || !formatOffset) return false; ptr = qImageData + dataOffset; // read data pointer ULONG64 data = 0; memcpy(&data, ptr, SymbolGroupValue::pointerSize()); // read format ptr = qImageData + formatOffset; header.format = *(reinterpret_cast<int *>(ptr)); if (header.width < 0 || header.height < 0 || header.format < 0 || header.format > 255 || nbytes < 0 || depth < 0) { return false; } str << header.width << L'x' << header.height << L", depth: " << depth << L", format: " << header.format << L", " << nbytes << L" bytes"; delete [] qImageData; // Create Creator Image data for display if reasonable size if (memoryHandle && data && nbytes > 0 && nbytes < 205824) { if (unsigned char *imageData = SymbolGroupValue::readMemory(v.context().dataspaces, data, nbytes)) { unsigned char *creatorImageData = new unsigned char[sizeof(CreatorImageHeader) + nbytes]; memcpy(creatorImageData, &header, sizeof(CreatorImageHeader)); memcpy(creatorImageData + sizeof(CreatorImageHeader), imageData, nbytes); delete [] imageData; *memoryHandle = new MemoryHandle(creatorImageData, sizeof(CreatorImageHeader) + nbytes); // cppcheck: don't delete[] creatorImageData here, it's taken over by MemoryHandle } } return true; } // Dump a rectangle in X11 syntax template <class T> inline void dumpRect(std::wostream &str, T x, T y, T width, T height) { str << width << 'x' << height; if (x >= 0) str << '+'; str << x; if (y >= 0) str << '+'; str << y; } // Dump Qt's simple geometrical types static inline bool dumpQSize_F(const SymbolGroupValue &v, std::wostream &str) { str << '(' << v["wd"].value() << ", " << v["ht"].value() << ')'; return true; } static inline bool dumpQPoint_F(const SymbolGroupValue &v, std::wostream &str) { str << '(' << v["xp"].value() << ", " << v["yp"].value() << ')'; return true; } static inline bool dumpQLine_F(const SymbolGroupValue &v, std::wostream &str) { const SymbolGroupValue p1 = v["pt1"]; const SymbolGroupValue p2 = v["pt2"]; if (p1 && p2) { str << '(' << p1["xp"].value() << ", " << p1["yp"].value() << ") (" << p2["xp"].value() << ", " << p2["yp"].value() << ')'; return true; } return false; } static inline bool dumpQRect(const SymbolGroupValue &v, std::wostream &str) { const int x1 = v["x1"].intValue(); const int y1 = v["y1"].intValue(); const int x2 = v["x2"].intValue(); const int y2 = v["y2"].intValue(); dumpRect(str, x1, y1, (x2 - x1 + 1), (y2 - y1 + 1)); return true; } static inline bool dumpQRectF(const SymbolGroupValue &v, std::wostream &str) { dumpRect(str, v["xp"].floatValue(), v["yp"].floatValue(), v["w"].floatValue(), v["h"].floatValue()); return true; } /* Return a SymbolGroupValue containing the private class of * a type (multiple) derived from QObject and something else * (QWidget: QObject,QPaintDevice or QWindow: QObject,QSurface). * We get differing behaviour for pointers and values on stack. * For 'QWidget *', the base class QObject usually can be accessed * by name (past the vtable). When browsing class hierarchies (stack), * typically only the uninteresting QPaintDevice is seen. */ SymbolGroupValue qobjectDerivedPrivate(const SymbolGroupValue &v, const std::string &qwPrivateType, const QtInfo &qtInfo) { if (const SymbolGroupValue base = v[SymbolGroupValue::stripModuleFromType(qtInfo.qObjectType).c_str()]) if (const SymbolGroupValue qwPrivate = base["d_ptr"]["d"].pointerTypeCast(qwPrivateType.c_str())) return qwPrivate; if (!SymbolGroupValue::isPointerType(v.type())) return SymbolGroupValue(); // Class hierarchy: Using brute force, add new symbol based on that // QScopedPointer<Private> is basically a 'X *' (first member). std::string errorMessage; std::ostringstream str; str << '(' << qwPrivateType << "*)(" << std::showbase << std::hex << v.address() << ')'; const std::string name = str.str(); SymbolGroupNode *qwPrivateNode = v.node()->symbolGroup()->addSymbol(v.module(), name, std::string(), &errorMessage); return SymbolGroupValue(qwPrivateNode, v.context()); } static bool dumpQObjectName(const SymbolGroupValue &qoPrivate, std::wostream &str) { // Qt 4: plain member. if (QtInfo::get(qoPrivate.context()).version < 5) { if (const SymbolGroupValue oName = qoPrivate["objectName"]) return dumpQString(oName, str); } // Qt 5: member of allocated extraData. if (const SymbolGroupValue extraData = qoPrivate["extraData"]) if (extraData.pointerValue()) if (const SymbolGroupValue oName = extraData["objectName"]) return dumpQString(oName, str); return false; } // Dump the object name static inline bool dumpQWidget(const SymbolGroupValue &v, std::wostream &str, void **specialInfoIn = 0) { const QtInfo &qtInfo = QtInfo::get(v.context()); const SymbolGroupValue qwPrivate = qobjectDerivedPrivate(v, qtInfo.qWidgetPrivateType, qtInfo); // QWidgetPrivate inherits QObjectPrivate if (!qwPrivate || !dumpQObjectName(qwPrivate[unsigned(0)], str)) return false; if (specialInfoIn) *specialInfoIn = qwPrivate.node(); return true; } // Dump the object name static inline bool dumpQObject(const SymbolGroupValue &v, std::wostream &str, void **specialInfoIn = 0) { const std::string &qoPrivateType = QtInfo::get(v.context()).qObjectPrivateType; const SymbolGroupValue qoPrivate = v["d_ptr"]["d"].pointerTypeCast(qoPrivateType.c_str()); if (!qoPrivate || !dumpQObjectName(qoPrivate, str)) return false; if (specialInfoIn) *specialInfoIn = qoPrivate.node(); return true; } // Dump the object name static inline bool dumpQWindow(const SymbolGroupValue &v, std::wostream &str, void **specialInfoIn = 0) { const QtInfo &qtInfo = QtInfo::get(v.context()); const SymbolGroupValue qwPrivate = qobjectDerivedPrivate(v, qtInfo.qWindowPrivateType, qtInfo); // QWindowPrivate inherits QObjectPrivate if (!qwPrivate || !dumpQObjectName(qwPrivate[unsigned(0)], str)) return false; if (specialInfoIn) *specialInfoIn = qwPrivate.node(); return true; } //Dump a QTextCursor static inline bool dumpQTextCursor(const SymbolGroupValue &v, std::wostream &str) { const unsigned offset = SymbolGroupValue::pointerSize() + SymbolGroupValue::sizeOf("double"); const ULONG64 posAddr = addressOfQPrivateMember(v, QPDM_qSharedDataPadded, offset); if (!posAddr) return false; const int position = SymbolGroupValue::readIntValue(v.context().dataspaces, posAddr); str << position; return true; } // Dump a std::string. static bool dumpStd_W_String(const SymbolGroupValue &v, int type, std::wostream &str, MemoryHandle **memoryHandle = 0) { // Find 'bx'. MSVC 2012 has 2 base classes, MSVC 2010 1, // and MSVC2008 none const SymbolGroupValue bx = SymbolGroupValue::findMember(v, "_Bx"); const int reserved = bx.parent()["_Myres"].intValue(); int size = bx.parent()["_Mysize"].intValue(); if (!bx || reserved < 0 || size < 0) return false; const bool truncated = unsigned(size) > ExtensionContext::instance().parameters().maxStringLength; if (truncated) size = ExtensionContext::instance().parameters().maxStringLength; // 'Buf' array for small strings, else pointer 'Ptr'. const int bufSize = type == KT_StdString ? 16 : 8; // see basic_string. const unsigned long memSize = type == KT_StdString ? size : 2 * size; const ULONG64 address = reserved >= bufSize ? bx["_Ptr"].pointerValue() : bx["_Buf"].address(); if (!address) return false; unsigned char *memory = SymbolGroupValue::readMemory(v.context().dataspaces, address, memSize); if (!memory) return false; str << (type == KT_StdString ? quotedWStringFromCharData(memory, memSize, truncated) : quotedWStringFromWCharData(memory, memSize, truncated)); if (memoryHandle) *memoryHandle = new MemoryHandle(memory, memSize); else delete [] memory; return true; } // Dump a std::complex. static bool dumpStd_Complex(const SymbolGroupValue &v, std::wostream &str) { if (const SymbolGroupValue &valArray = v[0u][0u]["_Val"]) { if (const SymbolGroupValue &val0 = valArray["0"]) { str << L'(' << val0.value(); if (const SymbolGroupValue &val1 = valArray["1"]) { str << L", " << val1.value() << L')'; return true; } } } return false; } // QVariant employs a template for storage where anything bigger than the data union // is pointed to by data.shared.ptr, else it is put into the data struct (pointer size) // itself (notably Qt types consisting of a d-ptr only). // The layout can vary between 32 /64 bit for some types: QPoint/QSize (of 2 ints) is bigger // as a pointer only on 32 bit. static inline SymbolGroupValue qVariantCast(const SymbolGroupValue &variantData, const char *type) { const ULONG typeSize = SymbolGroupValue::sizeOf(type); const std::string ptrType = std::string(type) + " *"; if (typeSize > variantData.size()) return variantData["shared"]["ptr"].pointerTypeCast(ptrType.c_str()); return variantData.typeCast(ptrType.c_str()); } // Qualify a local container template of Qt Types for QVariant // as 'QList' of 'QVariant' -> 'localModule!qtnamespace::QList<qtnamespace::QVariant> *' static inline std::string variantContainerType(const std::string &containerType, const std::string &innerType1, const std::string &innerType2 /* = "" */, const QtInfo &qtInfo, const SymbolGroupValue &contextHelper) { std::string rc = QtInfo::prependModuleAndNameSpace(containerType, contextHelper.module(), qtInfo.nameSpace); rc.push_back('<'); rc += QtInfo::prependModuleAndNameSpace(innerType1, std::string(), qtInfo.nameSpace); if (!innerType2.empty()) { rc.push_back(','); rc += QtInfo::prependModuleAndNameSpace(innerType2, std::string(), qtInfo.nameSpace); } rc += "> *"; return rc; } static bool dumpQVariant(const SymbolGroupValue &v, std::wostream &str, std::string *encoding, void **specialInfoIn = 0) { const QtInfo &qtInfo = QtInfo::get(v.context()); const SymbolGroupValue dV = v["d"]; if (!dV) return false; const SymbolGroupValue typeV = dV["type"]; const SymbolGroupValue dataV = dV["data"]; if (!typeV || !dataV) return false; const int typeId = typeV.intValue(); if (typeId <= 0) { str << L"<Invalid>"; return true; } switch (typeId) { case 1: // Bool str << L"(bool) " << dataV["b"].value(); break; case 2: // Int str << L"(int) " << dataV["i"].value(); break; case 3: // UInt str << L"(unsigned) " << dataV["u"].value(); break; case 4: // LongLong str << L"(long long) " << dataV["ll"].value(); break; case 5: // LongLong str << L"(unsigned long long) " << dataV["ull"].value(); break; case 6: // Double str << L"(double) " << dataV["d"].value(); break; case 7: // Char str << L"(char) " << dataV["c"].value(); break; case 8: { str << L"(QVariantMap) "; const std::string vmType = variantContainerType("QMap", "QString", "QVariant", qtInfo, dataV); if (const SymbolGroupValue mv = dataV.typeCast(vmType.c_str())) { SymbolGroupNode *mapNode = mv.node(); std::wstring value; if (dumpSimpleType(mapNode, dataV.context(), &value, &std::string()) == SymbolGroupNode::SimpleDumperOk) { str << value; if (specialInfoIn) *specialInfoIn = mapNode; } } } break; case 9: { // QVariantList str << L"(QVariantList) "; const std::string vLType = variantContainerType("QList", "QVariant", std::string(), qtInfo, dataV); if (const SymbolGroupValue vl = dataV.typeCast(vLType.c_str())) { SymbolGroupNode *vListNode = vl.node(); std::wstring value; if (dumpSimpleType(vListNode, dataV.context(), &value, &std::string()) == SymbolGroupNode::SimpleDumperOk) { str << value; if (specialInfoIn) *specialInfoIn = vListNode; } } } break; case 10: // String str << L"(QString) "; if (const SymbolGroupValue sv = dataV.typeCast(qtInfo.prependQtCoreModule("QString *").c_str())) { if (!dumpQString(sv, str)) { // HACK: // In some rare cases the AddSymbol can't create a node with a given module name, // but is able to add the symbol without any modulename. if (const SymbolGroupValue svc = dataV.typeCast("QString *")) dumpQString(svc, str); } } break; case 11: //StringList: Dump container size str << L"(QStringList) "; if (const SymbolGroupValue sl = dataV.typeCast(qtInfo.prependQtCoreModule("QStringList *").c_str())) { SymbolGroupNode *listNode = sl.node(); std::wstring value; if (dumpSimpleType(listNode, dataV.context(), &value, &std::string()) == SymbolGroupNode::SimpleDumperOk) { str << value; if (specialInfoIn) *specialInfoIn = listNode; } } break; case 12: //ByteArray str << L"(QByteArray) "; if (const SymbolGroupValue sv = dataV.typeCast(qtInfo.prependQtCoreModule("QByteArray *").c_str())) dumpQByteArray(sv, str, encoding); break; case 13: // BitArray str << L"(QBitArray)"; break; case 14: // Date: Do not qualify - fails non-deterministically with QtCored4!QDate str << L"(QDate) "; if (const SymbolGroupValue sv = dataV.typeCast("QDate *")) dumpQDate(sv, str, encoding); break; case 15: // Time: Do not qualify - fails non-deterministically with QtCored4!QTime str << L"(QTime) "; if (const SymbolGroupValue sv = dataV.typeCast("QTime *")) dumpQTime(sv, str, encoding); break; case 16: // DateTime str << L"(QDateTime)"; break; case 17: // Url str << L"(QUrl)"; break; case 18: // Locale str << L"(QLocale)"; break; case 19: // Rect: str << L"(QRect) "; if (const SymbolGroupValue sv = dataV["shared"]["ptr"].pointerTypeCast(qtInfo.prependQtCoreModule("QRect *").c_str())) dumpQRect(sv, str); break; case 20: // RectF str << L"(QRectF) "; if (const SymbolGroupValue sv = dataV["shared"]["ptr"].pointerTypeCast(qtInfo.prependQtCoreModule("QRectF *").c_str())) dumpQRectF(sv, str); break; case 21: // Size // Anything bigger than the data union is a pointer, else the data union is used str << L"(QSize) "; if (const SymbolGroupValue sv = qVariantCast(dataV, qtInfo.prependQtCoreModule("QSize").c_str())) dumpQSize_F(sv, str); break; case 22: // SizeF str << L"(QSizeF) "; if (const SymbolGroupValue sv = dataV["shared"]["ptr"].pointerTypeCast(qtInfo.prependQtCoreModule("QSizeF *").c_str())) dumpQSize_F(sv, str); break; case 23: // Line str << L"(QLine) "; if (const SymbolGroupValue sv = dataV["shared"]["ptr"].pointerTypeCast(qtInfo.prependQtCoreModule("QLine *").c_str())) dumpQLine_F(sv, str); break; case 24: // LineF str << L"(QLineF) "; if (const SymbolGroupValue sv = dataV["shared"]["ptr"].pointerTypeCast(qtInfo.prependQtCoreModule("QLineF *").c_str())) dumpQLine_F(sv, str); break; case 25: // Point str << L"(QPoint) "; if (const SymbolGroupValue sv = qVariantCast(dataV, qtInfo.prependQtCoreModule("QPoint").c_str())) dumpQPoint_F(sv, str); break; case 26: // PointF str << L"(QPointF) "; if (const SymbolGroupValue sv = dataV["shared"]["ptr"].pointerTypeCast(qtInfo.prependQtCoreModule("QPointF *").c_str())) dumpQPoint_F(sv, str); break; case 65: // QPixmap str << L"(QPixmap) "; if (const SymbolGroupValue sv = qVariantCast(dataV, qtInfo.prependQtGuiModule("QPixmap").c_str())) dumpQPixmap(sv, str); break; default: str << L"Type " << typeId; break; } return true; } static inline bool dumpQSharedPointer(const SymbolGroupValue &v, std::wostream &str, std::string *encoding, void **specialInfoIn = 0) { const SymbolGroupValue externalRefCountV = v[unsigned(0)]; const QtInfo qtInfo = QtInfo::get(v.context()); if (qtInfo.version < 5) { if (!externalRefCountV) return false; const SymbolGroupValue dV = externalRefCountV["d"]; if (!dV) return false; // Get value element from base and store in special info. const SymbolGroupValue valueV = externalRefCountV[unsigned(0)]["value"]; if (!valueV) return false; // Format references. const int strongRef = dV["strongref"]["_q_value"].intValue(); const int weakRef = dV["weakref"]["_q_value"].intValue(); if (strongRef < 0 || weakRef < 0) return false; str << L"References: " << strongRef << '/' << weakRef; if (specialInfoIn) *specialInfoIn = valueV.node(); return true; } else { // Qt 5 SymbolGroupValue value = v["value"]; if (value.pointerValue(0) == 0) { str << L"(null)"; return true; } if (knownType(value.type(), KnownTypeAutoStripPointer | KnownTypeHasClassPrefix) & KT_HasSimpleDumper) { str << value.node()->simpleDumpValue(v.context(), encoding); return true; } return false; } } // Dump builtin simple types using SymbolGroupValue expressions. unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx, std::wstring *s, std::string *encoding, int *knownTypeIn /* = 0 */, int *containerSizeIn /* = 0 */, void **specialInfoIn /* = 0 */, MemoryHandle **memoryHandleIn /* = 0 */) { QTC_TRACE_IN if (containerSizeIn) *containerSizeIn = -1; if (specialInfoIn) *specialInfoIn = 0; // Check for class types and strip pointer types (references appear as pointers as well) s->clear(); const KnownType kt = knownType(n->type(), KnownTypeHasClassPrefix|KnownTypeAutoStripPointer); if (knownTypeIn) *knownTypeIn = kt; if (kt == KT_Unknown || !(kt & KT_HasSimpleDumper)) { if (SymbolGroupValue::verbose > 1) DebugPrint() << "dumpSimpleType N/A " << n->name() << '/' << n->type(); QTC_TRACE_OUT return SymbolGroupNode::SimpleDumperNotApplicable; } std::wostringstream str; // Prefix by pointer value const SymbolGroupValue v(n, ctx); if (!v) // Value as such has memory read error? return SymbolGroupNode::SimpleDumperFailed; unsigned rc = SymbolGroupNode::SimpleDumperNotApplicable; // Simple dump of size for containers if (kt & KT_ContainerType) { const int size = containerSize(kt, v); if (SymbolGroupValue::verbose > 1) DebugPrint() << "dumpSimpleType Container " << n->name() << '/' << n->type() << " size=" << size; if (containerSizeIn) *containerSizeIn = size; if (size >= 0) { str << L'<' << size << L" items>"; rc = SymbolGroupNode::SimpleDumperOk; } else { rc = SymbolGroupNode::SimpleDumperFailed; } } else { switch (kt) { case KT_QChar: rc = dumpQChar(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QByteArray: rc = dumpQByteArray(v, str, encoding, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QFileInfo: rc = dumpQFileInfo(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QFile: rc = dumpQFile(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QDir: rc = dumpQDir(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QRegExp: rc = dumpQRegExp(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QRegion: rc = dumpQRegion(v, str, specialInfoIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QUrl: rc = dumpQUrl(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QHostAddress: rc = dumpQHostAddress(v, str, encoding) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QIPv6Address: rc = dumpQIPv6Address(v, str, encoding) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QProcess: rc = dumpQProcess(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QScriptValue: rc = dumpQScriptValue(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QString: rc = dumpQString(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QStringRef: rc = dumpQStringRef(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QColor: rc = dumpQColor(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QFlags: rc = dumpQFlags(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QDate: rc = dumpQDate(v, str, encoding) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QTime: rc = dumpQTime(v, str, encoding) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QDateTime: rc = dumpQDateTime(v, str, encoding) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QTimeZone: rc = dumpQTimeZone(v, str, encoding) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QPoint: case KT_QPointF: rc = dumpQPoint_F(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QSize: case KT_QSizeF: rc = dumpQSize_F(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QLine: case KT_QLineF: rc = dumpQLine_F(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QPixmap: rc = dumpQPixmap(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QImage: rc = dumpQImage(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QRect: rc = dumpQRect(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QRectF: rc = dumpQRectF(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QVariant: rc = dumpQVariant(v, str, encoding, specialInfoIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QAtomicInt: rc = dumpQAtomicInt(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QBasicAtomicInt: rc = dumpQBasicAtomicInt(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QObject: rc = dumpQObject(v, str, specialInfoIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QWidget: rc = dumpQWidget(v, str, specialInfoIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QWindow: rc = dumpQWindow(v, str, specialInfoIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QSharedPointer: case KT_QWeakPointer: rc = dumpQSharedPointer(v, str, encoding, specialInfoIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_StdString: case KT_StdWString: rc = dumpStd_W_String(v, kt, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_StdComplex: rc = dumpStd_Complex(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; case KT_QTextCursor: rc = dumpQTextCursor(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed; break; default: break; } } if (rc != SymbolGroupNode::SimpleDumperFailed && SymbolGroupValue::isPointerType(v.type()) && encoding->empty()) str << L" @" << std::showbase << std::hex << v.pointerValue() << std::dec << std::noshowbase; if (rc == SymbolGroupNode::SimpleDumperOk) *s = str.str(); QTC_TRACE_OUT if (SymbolGroupValue::verbose > 1) { DebugPrint dp; dp << "dumpSimpleType " << n->name() << '/' << n->type() << " knowntype= " << kt << " ["; formatKnownTypeFlags(dp, kt); dp << "] returns " << rc; } return rc; } static inline void formatEditValue(const std::string &displayFormat, const MemoryHandle *mh, std::ostream &str) { str << "editformat=\"" << displayFormat << "\",editvalue=\"" << mh->toHex() << "\","; } void dumpEditValue(const SymbolGroupNode *n, const SymbolGroupValueContext &, const std::string &desiredFormat, std::ostream &str) { if (SymbolGroupValue::verbose) DebugPrint() << __FUNCTION__ << ' ' << n->name() << '/' << desiredFormat; auto separatorPos = desiredFormat.find(':'); if (separatorPos == std::string::npos) return; if (desiredFormat.substr(separatorPos) != "separate") return; if (const MemoryHandle *mh = n->memory()) formatEditValue(desiredFormat, mh, str); } // Dump of QByteArray: Display as an array of unsigned chars. static inline std::vector<AbstractSymbolGroupNode *> complexDumpQByteArray(SymbolGroupNode *n, const SymbolGroupValueContext &ctx) { std::vector<AbstractSymbolGroupNode *> rc; const SymbolGroupValue baV(n, ctx); const SymbolGroupValue dV = baV["d"]; if (!dV) return rc; // Determine memory area. unsigned size = 0; ULONG64 address = 0; const QtStringAddressData data = readQtStringAddressData(dV, QtInfo::get(ctx)); size = data.size; address = data.address; if (size <= 0 || !address) return rc; if (size > 200) size = 200; rc.reserve(size); const std::string charType = "char"; std::string errorMessage; SymbolGroup *sg = n->symbolGroup(); for (int i = 0; i < (int)size; ++i, ++address) { SymbolGroupNode *en = sg->addSymbol(std::string(), SymbolGroupValue::pointedToSymbolName(address, charType), std::string(), &errorMessage); if (!en) { rc.clear(); return rc; } rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, en)); } return rc; } /* AssignmentStringData: Helper struct used for assigning values * to string classes. Contains an (allocated) data array with size for use * with IDebugDataSpaced::FillVirtual() + string length information and * provides a conversion function decodeString() to create the array * depending on the argument format (blow up ASCII to UTF16 or vice versa). */ struct AssignmentStringData { explicit AssignmentStringData(size_t dataLengthIn, size_t stringLengthIn); static AssignmentStringData decodeString(const char *begin, const char *end, int valueEncoding, bool toUtf16); static inline AssignmentStringData decodeString(const std::string &value, int valueEncoding, bool toUtf16) { return decodeString(value.c_str(), value.c_str() + value.size(), valueEncoding, toUtf16); } unsigned char *data; size_t dataLength; size_t stringLength; }; AssignmentStringData::AssignmentStringData(size_t dataLengthIn, size_t stringLengthIn) : data(new unsigned char[dataLengthIn]), dataLength(dataLengthIn), stringLength(stringLengthIn) { if (dataLength) memset(data, 0, dataLength); } AssignmentStringData AssignmentStringData::decodeString(const char *begin, const char *end, int valueEncoding, bool toUtf16) { if (toUtf16) { // Target is UTF16 consisting of unsigned short characters. switch (valueEncoding) { // Hex encoded ASCII/2 digits per char: Decode to plain characters and // recurse to expand them. case AssignHexEncoded: { const AssignmentStringData decoded = decodeString(begin, end, AssignHexEncoded, false); const char *source = reinterpret_cast<const char*>(decoded.data); const AssignmentStringData utf16 = decodeString(source, source + decoded.stringLength, AssignPlainValue, true); delete [] decoded.data; return utf16; } // Hex encoded UTF16: 4 hex digits per character: Decode sequence. case AssignHexEncodedUtf16: { const size_t stringLength = (end - begin) / 4; AssignmentStringData result(sizeof(unsigned short) *(stringLength + 1), stringLength); decodeHex(begin, end, result.data); return result; } default: break; } // Convert plain ASCII data to UTF16 by expanding. const size_t stringLength = end - begin; AssignmentStringData result(sizeof(unsigned short) *(stringLength + 1), stringLength); const unsigned char *source = reinterpret_cast<const unsigned char *>(begin); unsigned short *target = reinterpret_cast<unsigned short *>(result.data); std::copy(source, source + stringLength, target); return result; } // toUtf16 switch (valueEncoding) { case AssignHexEncoded: { // '0A5A'..2 digits per character const size_t stringLength = (end - begin) / 2; AssignmentStringData result(stringLength + 1, stringLength); decodeHex(begin, end, result.data); return result; } // Condense UTF16 characters to ASCII: Decode and use only every 2nd character // (little endian, first byte) case AssignHexEncodedUtf16: { const AssignmentStringData decoded = decodeString(begin, end, AssignHexEncoded, false); const size_t stringLength = decoded.stringLength / 2; const AssignmentStringData result(stringLength + 1, stringLength); const unsigned char *sourceEnd = decoded.data + decoded.stringLength; unsigned char *target = result.data; for (const unsigned char *source = decoded.data; source < sourceEnd; source += 2) *target++ = *source; delete [] decoded.data; return result; } break; default: break; } // Plain 0-terminated copy const size_t stringLength = end - begin; AssignmentStringData result(stringLength + 1, stringLength); memcpy(result.data, begin, stringLength); return result; } // Assignment helpers static inline std::string msgAssignStringFailed(const std::string &value, int errorCode) { std::ostringstream estr; estr << "Unable to assign a string of " << value.size() << " bytes: Error " << errorCode; return estr.str(); } /* QString assign helper: If QString instance has sufficiently allocated, * memory, write the data. Else invoke 'QString::resize' and * recurse (since 'd' might become invalid). This works for QString with UTF16 * data and for QByteArray with ASCII data due to the similar member * names and both using a terminating '\0' w_char/byte. */ static int assignQStringI(SymbolGroupNode *n, const char *className, const AssignmentStringData &data, const SymbolGroupValueContext &ctx, bool doAlloc = true) { const SymbolGroupValue v(n, ctx); SymbolGroupValue d = v["d"]; if (!d) return 1; const QtInfo &qtInfo = QtInfo::get(ctx); // Check the size, re-allocate if required. const QtStringAddressData addressData = readQtStringAddressData(d, qtInfo); if (!addressData.address) return 9; const bool needRealloc = addressData.allocated < data.stringLength; if (needRealloc) { if (!doAlloc) // Calling re-alloc failed somehow. return 3; std::ostringstream callStr; const std::string funcName = qtInfo.prependQtCoreModule(std::string(className) + "::resize"); callStr << funcName << '(' << std::hex << std::showbase << v.address() << ',' << data.stringLength << ')'; std::wstring wOutput; std::string errorMessage; return ExtensionContext::instance().call(callStr.str(), 0, &wOutput, &errorMessage) ? assignQStringI(n, className, data, ctx, false) : 5; } // Write data. if (!SymbolGroupValue::writeMemory(v.context().dataspaces, addressData.address, data.data, ULONG(data.dataLength))) return 11; // Correct size unless we re-allocated if (!needRealloc) { const std::string &arrayData = qtInfo.prependModuleAndNameSpace("QArrayData", std::string(), qtInfo.nameSpace); const SymbolGroupValue dV = qtInfo.version < 5 ? d : d[arrayData.c_str()]; if (!dV) return 14; const SymbolGroupValue size = dV["size"]; if (!size) return 16; if (!size.node()->assign(toString(data.stringLength))) return 17; } return 0; } // QString assignment static inline bool assignQString(SymbolGroupNode *n, int valueEncoding, const std::string &value, const SymbolGroupValueContext &ctx, std::string *errorMessage) { const AssignmentStringData utf16 = AssignmentStringData::decodeString(value, valueEncoding, true); const int errorCode = assignQStringI(n, "QString", utf16, ctx); delete [] utf16.data; if (errorCode) { *errorMessage = msgAssignStringFailed(value, errorCode); return false; } return true; } // QByteArray assignment static inline bool assignQByteArray(SymbolGroupNode *n, int valueEncoding, const std::string &value, const SymbolGroupValueContext &ctx, std::string *errorMessage) { const AssignmentStringData data = AssignmentStringData::decodeString(value, valueEncoding, false); const int errorCode = assignQStringI(n, "QByteArray", data, ctx); delete [] data.data; if (errorCode) { *errorMessage = msgAssignStringFailed(value, errorCode); return false; } return true; } // Helper to assign character data to std::string or std::wstring. static inline int assignStdStringI(SymbolGroupNode *n, int type, const AssignmentStringData &data, const SymbolGroupValueContext &ctx) { /* We do not reallocate and just write to the allocated buffer * (internal small buffer or _Ptr depending on reserved) provided sufficient * memory is there since it is apparently not possible to call the template * function std::string::resize(). * See the dumpStd_W_String() how to figure out if the internal buffer * or an allocated array is used. */ const SymbolGroupValue v(n, ctx); SymbolGroupValue base = v; SymbolGroupValue bx = base["_Bx"]; if (!bx) { base = base[unsigned(0)]; bx = base["_Bx"]; } if (!bx) { base = base[unsigned(0)][unsigned(1)]; bx = base["_Bx"]; } if (!bx) return 24; SymbolGroupValue size = base["_Mysize"]; int reserved = base["_Myres"].intValue(); if (reserved < 0 || !size || !bx) return 42; if (reserved <= (int)data.stringLength) return 1; // Insufficient memory. // Copy data: 'Buf' array for small strings, else pointer 'Ptr'. const int bufSize = type == KT_StdString ? 16 : 8; // see basic_string. const ULONG64 address = (bufSize <= reserved) ? bx["_Ptr"].pointerValue() : bx["_Buf"].address(); if (!address) return 3; if (!SymbolGroupValue::writeMemory(v.context().dataspaces, address, data.data, ULONG(data.dataLength))) return 7; // Correct size if (!size.node()->assign(toString(data.stringLength))) return 13; return 0; } // assignment of std::string assign via ASCII, std::wstring via UTF16 static inline bool assignStdString(SymbolGroupNode *n, int type, int valueEncoding, const std::string &value, const SymbolGroupValueContext &ctx, std::string *errorMessage) { const bool toUtf16 = type == KT_StdWString; const AssignmentStringData data = AssignmentStringData::decodeString(value, valueEncoding, toUtf16); const int errorCode = assignStdStringI(n, type, data, ctx); delete [] data.data; if (errorCode) { *errorMessage = msgAssignStringFailed(value, errorCode); return false; } return true; } bool assignType(SymbolGroupNode *n, int knownType, int valueEncoding, const std::string &value, const SymbolGroupValueContext &ctx, std::string *errorMessage) { switch (knownType) { case KT_QString: return assignQString(n, valueEncoding, value, ctx, errorMessage); case KT_QByteArray: return assignQByteArray(n, valueEncoding, value, ctx, errorMessage); case KT_StdString: case KT_StdWString: return assignStdString(n, knownType, valueEncoding, value, ctx, errorMessage); default: break; } return false; } std::vector<AbstractSymbolGroupNode *> dumpComplexType(SymbolGroupNode *n, int type, void *specialInfo, const SymbolGroupValueContext &ctx) { std::vector<AbstractSymbolGroupNode *> rc; if (!(type & KT_HasComplexDumper)) return rc; switch (type) { case KT_QByteArray: rc = complexDumpQByteArray(n, ctx); break; case KT_QRegion: if (specialInfo) { typedef AbstractSymbolGroupNode::AbstractSymbolGroupNodePtrVector NodeVector; NodeVector children = reinterpret_cast<SymbolGroupNode *>(specialInfo)->children(); for (NodeVector::iterator it = children.begin(); it != children.end(); ++it) { if (SymbolGroupNode *node = (*it)->asSymbolGroupNode()) rc.push_back(new ReferenceSymbolGroupNode(node->name(), node->iName(), node)); } } break; case KT_QWidget: // Special info by simple dumper is the QWidgetPrivate node case KT_QWindow: // Special info by simple dumper is the QWindowPrivate node case KT_QObject: // Special info by simple dumper is the QObjectPrivate node if (specialInfo) { SymbolGroupNode *qObjectPrivateNode = reinterpret_cast<SymbolGroupNode *>(specialInfo); rc.push_back(new ReferenceSymbolGroupNode("d", "d", qObjectPrivateNode)); } break; case KT_QVariant: // Special info by simple dumper is the container (stringlist, map,etc) if (specialInfo) { SymbolGroupNode *containerNode = reinterpret_cast<SymbolGroupNode *>(specialInfo); rc.push_back(new ReferenceSymbolGroupNode("children", "children", containerNode)); } case KT_QWeakPointer: case KT_QSharedPointer: // Special info by simple dumper is the value if (specialInfo) { SymbolGroupNode *valueNode = reinterpret_cast<SymbolGroupNode *>(specialInfo); rc.push_back(new ReferenceSymbolGroupNode("value", "value", valueNode)); } break; default: break; } if (SymbolGroupValue::verbose) { DebugPrint dp; dp << "<dumpComplexType" << rc.size() << ' ' << specialInfo << ' '; for (VectorIndexType i = 0; i < rc.size() ; ++i) dp << i << ' ' << rc.at(i)->name(); } return rc; }
38.454671
141
0.597068
[ "object", "vector", "model" ]
cd56998046d61d851a1ccfe9d9d491658eb19ad7
8,430
hpp
C++
3rdparty/GPSTk/core/lib/GNSSEph/RinexSatID.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/lib/GNSSEph/RinexSatID.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/lib/GNSSEph/RinexSatID.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #ifndef GPSTK_RINEX_SATID_HPP #define GPSTK_RINEX_SATID_HPP #include <iostream> #include <sstream> #include <iomanip> #include "Exception.hpp" #include "SatID.hpp" /** * @file RinexSatID.hpp * gpstk::RinexSatID - Navigation system-independent representation of a * satellite, as defined by the RINEX specification. */ namespace gpstk { /// @todo determine if this really belongs with the RINEX files /// @ingroup FileHandling //@{ class RinexSatID : public SatID { public: /// Empty constructor; creates an invalid object (Unknown, ID = -1). RinexSatID() throw() { id = -1; system = systemUnknown; } /// Explicit constructor, no defaults, RINEX systems only. RinexSatID(int p, const SatelliteSystem& s) throw() { id = p; system = s; switch(s) { case systemGPS: case systemGalileo: case systemGlonass: case systemGeosync: case systemTransit: case systemQZSS: case systemBeiDou: case systemIRNSS: case systemMixed: break; // Invalidate anything non-RINEX. default: system = systemUnknown; id = -1; } } /// Constructor from a string. RinexSatID(const std::string& str) throw(Exception) { try { fromString(str); } catch(Exception& e) { GPSTK_RETHROW(e); } } /// Cast a SatID to a RinexSatID. RinexSatID(const SatID& sat) throw() { *this = RinexSatID(sat.id,sat.system); } /// Set the fill character used in output and /// return the current fill character. char setfill(char c) throw() { char csave = fillchar; fillchar = c; return csave; } /// Get the fill character used in output. char getfill() const throw() { return fillchar; } // operator=, copy constructor and destructor built by compiler /// Return the single-character system descriptor. /// @note return only RINEX types, for non-RINEX systems return '?' char systemChar() const throw() { switch(system) { case systemGPS: return 'G'; case systemGalileo: return 'E'; case systemGlonass: return 'R'; case systemGeosync: return 'S'; case systemTransit: return 'T'; case systemQZSS: return 'J'; case systemBeiDou: return 'C'; case systemIRNSS: return 'I'; default: return '?'; } }; /// Return the system name as a string. /// @note Return only RINEX types or 'Unknown'. std::string systemString() const throw() { switch(system) { case systemGPS: return "GPS"; case systemGalileo: return "Galileo"; case systemGlonass: return "GLONASS"; case systemGeosync: return "Geosync"; case systemTransit: return "Transit"; case systemQZSS: return "QZSS"; case systemBeiDou: return "BeiDou"; case systemIRNSS: return "IRNSS"; default: return "Unknown"; } }; /// Return the system name as a string of length 3. /// @note Return only RINEX types or 'Unknown'. std::string systemString3() const throw() { switch(system) { case systemGPS: return "GPS"; case systemGalileo: return "GAL"; case systemGlonass: return "GLO"; case systemGeosync: return "GEO"; case systemTransit: return "TRN"; // RINEX ver 2 case systemQZSS: return "QZS"; case systemBeiDou: return "BDS"; case systemIRNSS: return "IRN"; // RINEX ver 3.03 default: return "Unk"; } }; /// Set the RinexSatID from a string (1 character plus 2-digit integer). /// @note GPS is default system (no or unknown system char) void fromString(const std::string& s) throw(Exception) { char c; std::istringstream iss(s); id = -1; system = systemGPS; // default if(s.find_first_not_of(std::string(" \t\n"), 0) == std::string::npos) return; // all whitespace yields the default iss >> c; // read one character (non-whitespace) switch(c) { // no leading system character case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': iss.putback(c); system = SatID::systemGPS; break; case 'R': case 'r': system = SatID::systemGlonass; break; case 'T': case 't': system = SatID::systemTransit; break; case 'S': case 's': system = SatID::systemGeosync; break; case 'E': case 'e': system = SatID::systemGalileo; break; case 'M': case 'm': system = SatID::systemMixed; break; case ' ': case 'G': case 'g': system = SatID::systemGPS; break; case 'J': case 'j': system = SatID::systemQZSS; break; case 'I': case 'i': system = SatID::systemIRNSS; break; case 'C': case 'c': system = SatID::systemBeiDou; break; default: // non-RINEX system character Exception e(std::string("Invalid system character \"") + c + std::string("\"")); GPSTK_THROW(e); } iss >> id; if(id <= 0) id = -1; } /// Convert the RinexSatID to string (1 character plus 2-digit integer). std::string toString() const throw() { std::ostringstream oss; oss.fill(fillchar); oss << systemChar() << std::setw(2) << id; return oss.str(); } private: static char fillchar; ///< Fill character used during stream output. }; // class RinexSatID /// Stream output for RinexSatID. inline std::ostream& operator<<(std::ostream& s, const RinexSatID& sat) { s << sat.toString(); return s; } //@} } // namespace gpstk #endif
29.787986
81
0.515896
[ "object" ]
cd5c4099051757dabfd9e70d05c9dacb8a0efc49
10,113
cpp
C++
src/TACSAssembler_thread.cpp
tchin-divergent/tacs
34743b370da4ab6ea16d24de7c574c3fec9d333a
[ "Apache-2.0" ]
null
null
null
src/TACSAssembler_thread.cpp
tchin-divergent/tacs
34743b370da4ab6ea16d24de7c574c3fec9d333a
[ "Apache-2.0" ]
null
null
null
src/TACSAssembler_thread.cpp
tchin-divergent/tacs
34743b370da4ab6ea16d24de7c574c3fec9d333a
[ "Apache-2.0" ]
null
null
null
/* This file is part of TACS: The Toolkit for the Analysis of Composite Structures, a parallel finite-element code for structural and multidisciplinary design optimization. Copyright (C) 2010 University of Toronto Copyright (C) 2012 University of Michigan Copyright (C) 2014 Georgia Tech Research Corporation Additional copyright (C) 2010 Graeme J. Kennedy and Joaquim R.R.A. Martins All rights reserved. TACS is licensed under the Apache License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 */ #include "TACSAssembler.h" #include "tacslapack.h" /*! Schedule the parts of the matrix/residual to assemble */ static pthread_mutex_t sched_mutex = PTHREAD_MUTEX_INITIALIZER; void TACSAssembler::schedPthreadJob( TACSAssembler *assembler, int *index, int total_size ){ pthread_mutex_lock(&sched_mutex); if (assembler->numCompletedElements < total_size){ *index = assembler->numCompletedElements; assembler->numCompletedElements += 1; } else { *index = -1; } pthread_mutex_unlock(&sched_mutex); } /*! The threaded-implementation of the residual assembly Note that the input must be the TACSAssemblerPthreadInfo data type. This function only uses the following data members: tacs: the pointer to the TACSAssembler object */ void *TACSAssembler::assembleRes_thread( void *t ){ TACSAssemblerPthreadInfo *pinfo = static_cast<TACSAssemblerPthreadInfo*>(t); // Un-pack information for this computation TACSAssembler *assembler = pinfo->assembler; TACSBVec *res = pinfo->res; // Allocate a temporary array large enough to store everything required int s = assembler->maxElementSize; int sx = 3*assembler->maxElementNodes; int dataSize = 4*s + sx; TacsScalar *data = new TacsScalar[ dataSize ]; // Set pointers to the allocate memory TacsScalar *vars = &data[0]; TacsScalar *dvars = &data[s]; TacsScalar *ddvars = &data[2*s]; TacsScalar *elemRes = &data[3*s]; TacsScalar *elemXpts = &data[4*s]; // Set the data for the auxiliary elements - if there are any int naux = 0, aux_count = 0; TACSAuxElem *aux = NULL; if (assembler->auxElements){ naux = assembler->auxElements->getAuxElements(&aux); } while (assembler->numCompletedElements < assembler->numElements){ int elemIndex = -1; TACSAssembler::schedPthreadJob(assembler, &elemIndex, assembler->numElements); if (elemIndex >= 0){ // Get the element object TACSElement *element = assembler->elements[elemIndex]; // Retrieve the variable values int ptr = assembler->elementNodeIndex[elemIndex]; int len = assembler->elementNodeIndex[elemIndex+1] - ptr; const int *nodes = &assembler->elementTacsNodes[ptr]; assembler->xptVec->getValues(len, nodes, elemXpts); assembler->varsVec->getValues(len, nodes, vars); assembler->dvarsVec->getValues(len, nodes, dvars); assembler->ddvarsVec->getValues(len, nodes, ddvars); // Generate the Jacobian of the element element->addResidual(elemIndex, assembler->time, elemXpts, vars, dvars, ddvars, elemRes); // Increment the aux counter until we possibly have // aux[aux_count].num == elemIndex while (aux_count < naux && aux[aux_count].num < elemIndex){ aux_count++; } // Add the residual from the auxiliary elements while (aux_count < naux && aux[aux_count].num == elemIndex){ aux[aux_count].elem->addResidual(elemIndex, assembler->time, elemXpts, vars, dvars, ddvars, elemRes); aux_count++; } // Add the values to the residual when the memory unlocks pthread_mutex_lock(&assembler->tacs_mutex); res->setValues(len, nodes, elemRes, TACS_ADD_VALUES); pthread_mutex_unlock(&assembler->tacs_mutex); } } delete [] data; pthread_exit(NULL); } /*! The threaded-implementation of the matrix assembly Note that the input must be the TACSAssemblerPthreadInfo data type. This function only uses the following data members: tacs: the pointer to the TACSAssembler object A: the generic TACSMat base class */ void *TACSAssembler::assembleJacobian_thread( void *t ){ TACSAssemblerPthreadInfo *pinfo = static_cast<TACSAssemblerPthreadInfo*>(t); // Un-pack information for this computation TACSAssembler *assembler = pinfo->assembler; TACSBVec *res = pinfo->res; TACSMat *A = pinfo->mat; TacsScalar alpha = pinfo->alpha; TacsScalar beta = pinfo->beta; TacsScalar gamma = pinfo->gamma; MatrixOrientation matOr = pinfo->matOr; // Allocate a temporary array large enough to store everything // required int s = assembler->maxElementSize; int sx = 3*assembler->maxElementNodes; int sw = assembler->maxElementIndepNodes; int dataSize = 4*s + sx + s*s + sw; TacsScalar *data = new TacsScalar[ dataSize ]; int *idata = new int[ sw + assembler->maxElementNodes + 1 ]; // Set pointers to the allocate memory TacsScalar *vars = &data[0]; TacsScalar *dvars = &data[s]; TacsScalar *ddvars = &data[2*s]; TacsScalar *elemRes = &data[3*s]; TacsScalar *elemXpts = &data[4*s]; TacsScalar *elemWeights = &data[4*s + sx]; TacsScalar *elemMat = &data[4*s + sx + sw]; // Set the data for the auxiliary elements - if there are any int naux = 0, aux_count = 0; TACSAuxElem *aux = NULL; if (assembler->auxElements){ naux = assembler->auxElements->getAuxElements(&aux); } while (assembler->numCompletedElements < assembler->numElements){ int elemIndex = -1; TACSAssembler::schedPthreadJob(assembler, &elemIndex, assembler->numElements); if (elemIndex >= 0){ // Get the element object TACSElement *element = assembler->elements[elemIndex]; // Retrieve the variable values int ptr = assembler->elementNodeIndex[elemIndex]; int len = assembler->elementNodeIndex[elemIndex+1] - ptr; const int *nodes = &assembler->elementTacsNodes[ptr]; assembler->xptVec->getValues(len, nodes, elemXpts); assembler->varsVec->getValues(len, nodes, vars); assembler->dvarsVec->getValues(len, nodes, dvars); assembler->ddvarsVec->getValues(len, nodes, ddvars); // Retrieve the number of element variables int nvars = element->getNumVariables(); memset(elemRes, 0, nvars*sizeof(TacsScalar)); memset(elemMat, 0, nvars*nvars*sizeof(TacsScalar)); // Generate the Jacobian of the element element->addJacobian(elemIndex, assembler->time, alpha, beta, gamma, elemXpts, vars, dvars, ddvars, elemRes, elemMat); // Increment the aux counter until we possibly have // aux[aux_count].num == elemIndex while (aux_count < naux && aux[aux_count].num < elemIndex){ aux_count++; } // Add the residual from the auxiliary elements while (aux_count < naux && aux[aux_count].num == elemIndex){ aux[aux_count].elem->addJacobian(elemIndex, assembler->time, alpha, beta, gamma, elemXpts, vars, dvars, ddvars, elemRes, elemMat); aux_count++; } pthread_mutex_lock(&assembler->tacs_mutex); // Add values to the residual if (res){ res->setValues(len, nodes, elemRes, TACS_ADD_VALUES); } // Add values to the matrix assembler->addMatValues(A, elemIndex, elemMat, idata, elemWeights, matOr); pthread_mutex_unlock(&assembler->tacs_mutex); } } delete [] data; delete [] idata; pthread_exit(NULL); } /*! The threaded-implementation of the matrix-type assembly This function uses the following information from the TACSAssemblerPthreadInfo class: A: the matrix to assemble (output) scaleFactor: scaling factor applied to the matrix matType: the matrix type defined in Element.h matOr: the matrix orientation: NORMAL or TRANSPOSE */ void *TACSAssembler::assembleMatType_thread( void *t ){ TACSAssemblerPthreadInfo *pinfo = static_cast<TACSAssemblerPthreadInfo*>(t); // Un-pack information for this computation TACSAssembler *assembler = pinfo->assembler; TACSMat *A = pinfo->mat; ElementMatrixType matType = pinfo->matType; MatrixOrientation matOr = pinfo->matOr; // Allocate a temporary array large enough to store everything required int s = assembler->maxElementSize; int sx = 3*assembler->maxElementNodes; int sw = assembler->maxElementIndepNodes; int dataSize = s + sx + s*s + sw; TacsScalar *data = new TacsScalar[ dataSize ]; int *idata = new int[ sw + assembler->maxElementNodes + 1 ]; TacsScalar *vars = &data[0]; TacsScalar *elemXpts = &data[s]; TacsScalar *elemWeights = &data[s + sx]; TacsScalar *elemMat = &data[s + sx + sw]; while (assembler->numCompletedElements < assembler->numElements){ int elemIndex = -1; TACSAssembler::schedPthreadJob(assembler, &elemIndex, assembler->numElements); if (elemIndex >= 0){ // Get the element TACSElement *element = assembler->elements[elemIndex]; // Retrieve the variable values // Retrieve the variable values int ptr = assembler->elementNodeIndex[elemIndex]; int len = assembler->elementNodeIndex[elemIndex+1] - ptr; const int *nodes = &assembler->elementTacsNodes[ptr]; assembler->xptVec->getValues(len, nodes, elemXpts); assembler->varsVec->getValues(len, nodes, vars); // Retrieve the type of the matrix element->getMatType(matType, elemIndex, assembler->time, elemXpts, vars, elemMat); pthread_mutex_lock(&assembler->tacs_mutex); // Add values to the matrix assembler->addMatValues(A, elemIndex, elemMat, idata, elemWeights, matOr); pthread_mutex_unlock(&assembler->tacs_mutex); } } delete [] data; pthread_exit(NULL); }
34.281356
88
0.679027
[ "object" ]
cd601d4dc0d00ba409706ea3ad1d9adc8ba5a03a
14,303
cc
C++
OJ/acm.hdu.edu.cn/2018multiUniversity01/1009.cc
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
14
2018-06-21T14:41:26.000Z
2021-12-19T14:43:51.000Z
OJ/acm.hdu.edu.cn/2018multiUniversity01/1009.cc
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
null
null
null
OJ/acm.hdu.edu.cn/2018multiUniversity01/1009.cc
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
2
2020-04-20T11:16:53.000Z
2021-01-02T15:58:35.000Z
#include <cstdio> #include <cassert> #include <vector> #include <functional> #include <algorithm> #include <cstring> using int64 = long long; using strings = std::vector<std::pair<int, int>>; const int N = 1e6 + 10; char s[N], buf[N]; template<class T, class Compare = std::less<T>> class SchieberVishkinRMQ { public: SchieberVishkinRMQ() = default; void build(const std::vector<T> &a) { build(a.data(), a.size()); } void build(const T *a, int n) { std::vector<int> left(n, -1), right(n, -1); std::vector<int> stk(n); // build Cartesian Tree for (int i = 0, top = 0; i < n; ++i) { int last = -1; while (top && compare(a[i], a[stk[top - 1]])) { last = stk[--top]; } if (top) right[stk[top - 1]] = i; left[i] = last; stk[top++] = i; } // find preorder int root = stk[0]; std::vector<int> parents(n, -1), order; indices.resize(n), inlabel.resize(n); for (int top = 1; top;) { int u = stk[--top]; order.push_back(u); indices[u] = inlabel[u] = order.size(); if (left[u] != -1) { stk[top++] = left[u]; parents[left[u]] = u; } if (right[u] != -1) { stk[top++] = right[u]; parents[right[u]] = u; } } // calc helper structures for Schieber-Vishkin LCA ascendant.resize(n), head.resize(n); for (int i = n - 1; i > 0; --i) { int v = order[i], p = parents[v]; if (lowbit(inlabel[p]) < lowbit(inlabel[v])) { inlabel[p] = inlabel[v]; } } ascendant[root] = 0; for (int i = 1; i < n; ++i) { int v = order[i], p = parents[v]; ascendant[v] = ascendant[p] | lowbit(inlabel[v]); } head[0] = root; for (int i = 1; i < n; ++i) { int v = order[i], p = parents[v]; if (inlabel[v] != inlabel[p]) head[indices[v] - 1] = p; else head[indices[v] - 1] = head[indices[p] - 1]; } } // return the index of the minimum value in [u, v] in O(1) int query(int u, int v) const { uint Iv = inlabel[v], Iu = inlabel[u]; uint hIv = lowbit(Iv), hIu = lowbit(Iu); uint mask = highbit((Iv ^ Iu) | hIv | hIu) - 1; uint j = lowbit(ascendant[v] & ascendant[u] & ~mask); int x, y; if (j == hIv) x = v; else { mask = highbit(ascendant[v] & (j - 1)) - 1; x = head[((indices[v] & ~mask) | (mask + 1)) - 1]; } if (j == hIu) y = u; else { mask = highbit(ascendant[u] & (j - 1)) - 1; y = head[((indices[u] & ~mask) | (mask + 1)) - 1]; } return indices[x] < indices[y] ? x : y; } private: using uint = unsigned int; static uint lowbit(uint x) { return x & (~x + 1); // x & (-x) or x & (x ^ (x - 1)) } static uint highbit(uint x) { return 1u << (31 - __builtin_clz(x)); } Compare compare; std::vector<uint> indices; std::vector<uint> inlabel; std::vector<uint> ascendant; std::vector<int> head; }; #define pushS(x) sa[--cur[(int)s[x]]] = x #define pushL(x) sa[cur[(int)s[x]]++] = x class SuffixArray { public: std::vector<int> sa; std::vector<int> rank; std::vector<int> lcp; SchieberVishkinRMQ<int> lcpRMQ; template<class T> void build(const T *s, int n); template<class T> void build(const T *s, int n, int m); int size() const { return sa.size() - 1; } int computeLCP(int i, int j) const { if (i == j) return size() - i; int x = rank[i], y = rank[j]; if (x > y) std::swap(x, y); return lcp[lcpRMQ.query(x + 1, y)]; } private: using SLTypes = std::vector<bool>; int *buffer, *freq, *cur; int len; void buildRankTable(); void buildLCPArrayRMQ(); template<class T> void computeLCPArray(const T *s); template<class T> void countFrequency(const T *s, int n, int m); template<class T> void induce(const T *s, int *sa, int m, const SLTypes &t); template<class T> void sa_is(const T *s, int *sa, int n, int m); }; template<class T> void SuffixArray::build(const T *s, int n) { this->len = n; int m = *std::max_element(s, s + n) + 1; build(s, n, m); buildRankTable(); computeLCPArray(s); buildLCPArrayRMQ(); } template<class T> void SuffixArray::build(const T *s, int n, int m) { sa.resize(n + 1); if (n == 0) sa[0] = 0; else { // memory usage: sa + buffer + types // = 4 * (n + max(m * 2, n)) + 2 * n / 8 + O(1) bytes std::vector<int> buffer((std::max(m, (n + 1) / 2) + 1) * 2); this->buffer = &buffer[0]; sa_is<T>(s, &sa[0], n + 1, m); } } void SuffixArray::buildRankTable() { int n = size() + 1; rank.resize(n); for (int i = 0; i < n; ++i) rank[sa[i]] = i; } void SuffixArray::buildLCPArrayRMQ() { lcpRMQ.build(&lcp[0], size() + 1); } template<class T> void SuffixArray::computeLCPArray(const T *s) { const int n = size() + 1; lcp.resize(n); for (int i = 0, h = lcp[0] = 0; i < n; ++i) { if (!rank[i]) continue; int j = sa[rank[i] - 1]; while (i + h < n && j + h < n && s[i + h] == s[j + h]) ++h; if ((lcp[rank[i]] = h)) --h; } } template<class T> void SuffixArray::countFrequency(const T *s, int n, int m) { memset(freq, 0, sizeof(int) * m); for (int i = 0; i < n; ++i) ++freq[(int) s[i]]; for (int i = 1; i < m; ++i) freq[i] += freq[i - 1]; memcpy(cur, freq, sizeof(int) * m); } template<class T> void SuffixArray::induce(const T *s, int *sa, int m, const SLTypes &t) { const int n = t.size(); memcpy(cur + 1, freq, sizeof(int) * (m - 1)); for (int i = 0; i < n; ++i) { int p = sa[i] - 1; if (p >= 0 && t[p]) pushL(p); } memcpy(cur, freq, sizeof(int) * m); for (int i = n - 1; i > 0; --i) { int p = sa[i] - 1; if (p >= 0 && !t[p]) pushS(p); } } template<class T> void SuffixArray::sa_is(const T *s, int *sa, int n, int m) { SLTypes t(n); memset(sa, 0, sizeof(int) * n); for (int i = n - 2; ~i; --i) { t[i] = (s[i] == s[i + 1]) ? t[i + 1] : s[i] > s[i + 1]; } freq = buffer, cur = buffer + m; countFrequency(s, n, m); for (int i = 1; i < n; ++i) if (t[i - 1] > t[i]) pushS(i); induce(s, sa, m, t); int n1 = 0, order = 0; for (int i = 0, p; i < n; ++i) { if ((p = sa[i]) && t[p - 1] > t[p]) sa[n1++] = p; } int *s1 = sa + n1; memset(s1, -1, sizeof(int) * (n - n1)); s1[(sa[0] - 1) / 2] = order++; for (int i = 1; i < n1; ++i) { bool diff = true; for (int x = sa[i - 1], y = sa[i];; ++x, ++y) { if (s[x] != s[y] || t[x] != t[y]) break; else if (t[x] > t[x + 1] && t[y] > t[y + 1]) { diff = (s[x + 1] != s[y + 1]); break; } } s1[(sa[i] - 1) / 2] = (order += diff) - 1; } for (int i = 0, x = 0; i < n - n1; ++i) { if (~s1[i]) s1[x++] = s1[i]; } if (order != n1) { sa_is<int>(s1, sa, n1, order); for (int i = 0; i < n1; ++i) s1[sa[i]] = i; } for (int i = 1, j = 0; i < n; ++i) { if (t[i - 1] > t[i]) sa[s1[j++]] = -i; } memset(s1, 0, sizeof(int) * (n - n1)); freq = buffer, cur = buffer + m; countFrequency(s, n, m); for (int i = n1 - 1; ~i; --i) pushS(-sa[i]); induce(s, sa, m, t); } std::vector<int> duval(const char s[]) { std::vector<int> ret; int n = strlen(s) + 1; // zero used here int start = 0, mid = 1, cur = 0; ret.push_back(0); for (int i = 0; i < n; ++i) { if (s[i] == s[cur]) { if (++cur == mid) cur = start; } else if (s[i] > s[cur]) { mid = i + 1; cur = start; } else if (s[i] < s[cur]) { int temp = mid - start; while (start + temp <= i) { start += temp; ret.push_back(start); } i = cur = start; mid = start + 1; } } return ret; } struct lyndon_t { int s, l, k; int prefix, suffix; lyndon_t(int a, int b, int c) : s(a), l(b), k(c) { prefix = suffix = l; } }; int main() { int T; scanf("%d", &T); for (int cas = 1; cas <= T; ++cas) { int n, m; scanf("%d%d", &n, &m); std::vector<int> offset(n + 1); for (int i = 0; i < n; ++i) { scanf("%s", s + offset[i]); offset[i + 1] = offset[i] + strlen(s + offset[i]); } SuffixArray sa; sa.build(s, offset[n]); // compare s[a..b] and s[c..d] auto compare = [&](int a, int b, int c, int d) { int lcp = sa.computeLCP(a, c); lcp = std::min(lcp, b - a + 1); lcp = std::min(lcp, d - c + 1); for (int i = 0; i < lcp; ++i) assert(s[a + i] == s[c + i]); char x = a + lcp <= b ? s[a + lcp] : 0; char y = c + lcp <= d ? s[c + lcp] : 0; /* printf("(%d %d) (%d %d)\n", a, b, c, d); printf("xxxx lcp=%d %d %d\n", lcp, int(x), int(y));*/ return x - y; }; auto compare2 = [&](std::vector<std::pair<int, int>> a, std::vector<std::pair<int, int>> b) -> int { /* std::string x = "", y = ""; for (auto &&e: a) for (int i = e.first; i <= e.second; ++i) x += s[i]; for (auto &&e: b) for (int i = e.first; i <= e.second; ++i) y += s[i]; //printf("%s %s\n", x.c_str(), y.c_str()); if (x == y) return 0; if (x < y) return -1; return 1;*/ int n = a.size(), m = b.size(); int i = 0, j = 0; while (i < n && j < m) { int lcp = sa.computeLCP(a[i].first, b[j].first); int la = a[i].second - a[i].first + 1; int lb = b[j].second - b[j].first + 1; lcp = std::min(lcp, std::min(la, lb)); if (lcp < la && lcp < lb) { return s[a[i].first + lcp] - s[b[j].first + lcp]; } else if (lcp == la && lcp < lb) { ++i; b[j].first += lcp; } else if (lcp < la && lcp == lb) { ++j; a[i].first += lcp; } else { ++i, ++j; } } if (i != n) return 1; else if (j != m) return -1; else return 0; }; std::vector<std::vector<lyndon_t>> lf(n); for (int i = 0; i < n; ++i) { memcpy(buf, s + offset[i], sizeof(char) * (offset[i + 1] - offset[i])); buf[offset[i + 1] - offset[i]] = 0; auto u = duval(buf); for (size_t j = 1, k; j < u.size(); j = k) { int l = offset[i] + u[j - 1], r = offset[i] + u[j] - 1; for (k = j; k < u.size(); ++k) { int x = offset[i] + u[k - 1], y = offset[i] + u[k] - 1; if (compare(l, r, x, y) != 0) break; } lf[i].push_back(lyndon_t(offset[i] + u[j - 1], u[j] - u[j - 1], k - j)); } for (size_t j = 1; j < lf[i].size(); ++j) { lf[i][j].prefix = std::max(lf[i][j].prefix, lf[i][j - 1].prefix); } for (int j = lf[i].size() - 2; j >= 0; --j) { lf[i][j].suffix = std::max(lf[i][j].suffix, lf[i][j + 1].suffix); } } for (int it = 0; it < m; ++it) { int x, y; scanf("%d%d", &x, &y); --x, --y; const auto &lfx = lf[x]; const auto &lfy = lf[y]; auto u = lfx.back(); auto v = lfy[0]; int a = u.s, b = u.s + u.l - 1; int c = v.s, d = v.s + v.l - 1; auto res = compare(a, b, c, d); /* for (auto &&e: lfx) printf("%d %d %d\n", e.s, e.l, e.k); puts(""); for (auto &&e: lfy) printf("%d %d %d\n", e.s, e.l, e.k); puts(""); printf("%d\n", res);*/ if (res >= 0) { printf("%d\n", std::max(u.prefix, v.suffix)); } else { strings left, right; int l = 0, r = lfx.size() - 1; while (l < r) { int m = (l + r - 1) >> 1; left = {{lfx[m].s, offset[x + 1] - 1}, {offset[y], offset[y + 1] - 1}}; if (m == lfx.size() - 1) right = {{offset[y], offset[y + 1] - 1}}; else right = {{lfx[m + 1].s, offset[x + 1] - 1}, {offset[y], offset[y + 1] - 1}}; if (compare2(left, right) < 0) r = m; else l = m + 1; } int ret = 0; if (r > 0) ret = std::max(ret, lfx[r - 1].prefix); int ext = offset[x + 1] - lfx[r].s; left = {{lfx[r].s, offset[x + 1] - 1}, {offset[y], offset[y + 1] - 1}}; l = 0, r = lfy.size(); while (l < r) { int m = (l + r - 1) >> 1; if (m == lfy.size()) right = {}; else right = {{lfy[m].s, offset[y + 1] - 1}}; int res = compare2(left, right); //printf("m = %d, res=%d\n", m, res); if (res > 0) r = m; else l = m + 1; } if (r != lfy.size()) { ret = std::max(ret, lfy[r].suffix); ext += lfy[r].s - offset[y]; } else { ext += offset[y + 1] - offset[y]; } ret = std::max(ret, ext); printf("%d\n", ret); } } } return 0; }
31.504405
108
0.40481
[ "vector" ]
cd6211272696ca835a90aa4753f7f29ba62a46e0
5,754
cpp
C++
PacMan/PacMan/Map.cpp
fuboki10/PacMan-Game
931fb5a26960b7a80cd5bcfd664de04f5187a6d3
[ "MIT" ]
1
2019-06-15T21:48:24.000Z
2019-06-15T21:48:24.000Z
PacMan/PacMan/Map.cpp
fuboki10/PacMan-Game
931fb5a26960b7a80cd5bcfd664de04f5187a6d3
[ "MIT" ]
null
null
null
PacMan/PacMan/Map.cpp
fuboki10/PacMan-Game
931fb5a26960b7a80cd5bcfd664de04f5187a6d3
[ "MIT" ]
null
null
null
#include "Map.h" #include <iostream> #include <string> Map::Map(const char* MapName, const char* HeartName, SDL_Renderer *renderer, int w, int h, Game* game) : renderer(renderer), game(game) { MapTexture = TextureManager::LoadTexture(MapName, renderer); HeartText = TextureManager::LoadTexture(HeartName, renderer); width = w; height = h; srcRect.x = 0; srcRect.y = 0; srcRect.w = 1920; srcRect.h = 1080; dstRect.x = 0; dstRect.y = 0; dstRect.h = height; dstRect.w = width; srcHeartRect.x = srcHeartRect.y = 0; srcHeartRect.w = srcHeartRect.h = 32; player = nullptr; fontPath = "Assets/Fonts/04B_30__.TTF"; } void Map::DrawScore() { SDL_Rect ScoreDst = {30, 10, 200, 200}; int sc = player->getScore(); std::string Score = "Score : "; Score += std::to_string(sc); TextureManager::DrawText(fontPath, Score.c_str(), ScoreDst, renderer, 24); } void Map::setPlayerMovement(Moves move) { player->setDirection(move); } Map::~Map(void) { Clean(); } void Map::LoadMap(int arr[20][25]) { CleanObjects(); Objects type = NOTHING; Coin* c; Monster* m; Wall* w; for (int row = 0; row < 20; row++) { for (int col = 0; col < 25; col++) { map[row][col] = arr[row][col]; type = Objects(map[row][col]); switch (type) { case COIN: c = new Coin("Assets/Images/Coin.png", renderer, col, row, 1); coins.push_back(c); break; case PLAYER: player = new Player("Assets/Images/Pac1.png", "Assets/Images/Pac2.png", "Assets/Images/PacUlt.png", renderer, col , row, 1, 3); break; case MONSTER: m = new Monster("Assets/Images/Monster.png", "Assets/Images/Spirit.png", renderer, col, row, 1); monsters.push_back(m); break; case WALL: w = new Wall("Assets/Images/Wall.png", renderer, col, row); walls.push_back(w); break; default: break; } } } } /* 0 =====> Nothing 1 =====> Coin 2 =====> Player 3 =====> Monster 4 =====> Obstacle */ void Map::DrawMap() { //TextureManager::Draw(MapTexture, srcRect, dstRect, renderer); Objects type = NOTHING; SDL_Rect dst; dst.h = 32; dst.w = 32; int cIdx = 0; Coin* c; int mIdx = 0; Monster* m; int wIdx = 0; Wall* w; for (int row = 0; row < 20; row++) { for (int col = 0; col < 25; col++) { dst.y = row * 32; dst.x = col * 32; type = Objects(map[row][col]); switch (type) { case COIN : c = coins[cIdx]; c->Draw(dst); ++cIdx; break; case PLAYER: player->Draw(dst); break; case MONSTER: m = monsters[mIdx]; m->Draw(dst); ++mIdx; break; case WALL: w = walls[wIdx]; w->Draw(dst); ++wIdx; break; default: break; } } } dst.y = 1 * 32; dst.x = 1 * 32; for (int i = 0; i < player->getLifes(); i++) { dst.x = (i + 1) * 32; TextureManager::Draw(HeartText, srcHeartRect, dst, renderer); } // make monster spirits if (!cIdx) game->Ultimate(1), player->Ultimate(1); DrawScore(); } int Map::Search(const Objects& object, SDL_Point p) { SDL_Point p2; if (object == COIN) { for (int i = 0; i < coins.size(); i++) { p2 = coins[i]->getPos(); if (p2.x == p.x && p2.y == p.y) { return i; } } } if (object == MONSTER) { for (int i = 0; i < monsters.size(); i++) { p2 = monsters[i]->getPos(); if (p2.x == p.x && p2.y == p.y) { if (player) player->setScore(player->getScore() + 5); return i; } } } } void Map::Delete(const Objects& object, const SDL_Point& p) { int index = -1; Coin* c; Monster* m; switch (object) { case COIN: index = Search(object, p); c = coins[index]; coins.erase(coins.begin() + index); delete c; break; case MONSTER: index = Search(object, p); m = monsters[index]; monsters.erase(monsters.begin() + index); delete m; break; case PLAYER: GameOver(); break; default: break; } } bool Map::valid(const SDL_Point& p) const { if (p.y >= 20 || p.y < 0 || p.x >= 25 || p.x < 0) { return 0; } if (SP[p.y][p.x] != -1) { return 0; } if (map[p.y][p.x] == WALL) { return 0; } return 1; } void Map::BFS() { std::queue<SDL_Point> q; SDL_Point p = player->getPos(); q.push(p); SP[p.y][p.x] = 0; while (!q.empty()) { SDL_Point cur = q.front(); q.pop(); for (int i = 0; i < 4; i++) { SDL_Point u; u.x = cur.x + dx[i]; u.y = cur.y + dy[i]; if (valid(u)) { SP[u.y][u.x] = SP[cur.y][cur.x] + 1; q.push(u); } } } } void Map::Update() { memset(SP, -1, sizeof SP); Objects object = NOTHING; if (player) player->Update(map, object); if (object != NOTHING) { if (player) Delete(object, player->getPos()); if (!game->running()) return; } // SP for Monsters AI BFS(); for (auto monster : monsters) { object = NOTHING; if (monster) monster->Update(map, object, SP); if (object != NOTHING) { if (monster) { Delete(object, monster->getPos()); break; } } } if (monsters.size() == 0) GameOver(); } void Map::render() { DrawMap(); } void Map::CleanObjects() { if (player) delete player; player = NULL; for (auto coin : coins) { if (coin) delete coin; coin = NULL; } coins.clear(); for (auto monster : monsters) { if (monster) delete monster; monster = NULL; } monsters.clear(); for (auto wall : walls) { if (wall) delete wall; wall = NULL; } walls.clear(); } void Map::Clean() { SDL_DestroyTexture(MapTexture); CleanObjects(); } void Map::GameOver() { if (player->getLifes() == 1) { game->Ultimate(0); int score = player->getScore(); game->GameOver(score); } else { player->setLifes(player->getLifes() - 1); } }
15.467742
135
0.562044
[ "render", "object" ]
cd6237cc59d1da034f096697e87b36d5f5f18cfd
13,964
cpp
C++
dbpage/dbpage.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
5
2020-06-19T00:41:27.000Z
2022-02-27T14:23:44.000Z
dbpage/dbpage.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
null
null
null
dbpage/dbpage.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
2
2021-04-12T07:47:47.000Z
2021-04-12T07:47:49.000Z
#pragma execution_character_set("utf-8") #include "dbpage.h" SqlQueryModel::SqlQueryModel(QObject *parent) : QSqlQueryModel(parent) { allCenter = false; alignCenterColumn.clear(); alignRightColumn.clear(); } QVariant SqlQueryModel::data(const QModelIndex &index, int role) const { QVariant value = QSqlQueryModel::data(index, role); if (allCenter) { if(role == Qt::TextAlignmentRole ) { value = Qt::AlignCenter; } } else { //逐个从列索引中查找是否当前列在其中 int column = index.column(); bool existCenter = alignCenterColumn.contains(column); bool existRight = alignRightColumn.contains(column); if(role == Qt::TextAlignmentRole) { if (existCenter) { value = Qt::AlignCenter; } if (existRight) { value = (QVariant)(Qt::AlignVCenter | Qt::AlignRight); } } } //实现鼠标经过整行换色,如果设置了hoverRow才需要处理 if (property("hoverRow").isValid()) { int row = property("hoverRow").toInt(); if (row == index.row()) { if(role == Qt::BackgroundRole) { value = QColor(property("hoverBgColor").toString()); } else if(role == Qt::TextColorRole) { value = QColor(property("hoverTextColor").toString()); } } } //实现隐藏部分显示,指定列和替换字符 if (property("hideColumn").isValid()) { int column = property("hideColumn").toInt(); if (column == index.column()) { if(role == Qt::DisplayRole) { QString letter = property("hideLetter").toString(); int start = property("hideStart").toInt(); int end = property("hideEnd").toInt(); QString str = value.toString(); QStringList list; for (int i = 0; i < str.length(); i++) { if (i >= start && i <= end) { list << letter; } else { list << str.at(i); } } value = list.join(""); } } } return value; } void SqlQueryModel::setAllCenter(bool allCenter) { this->allCenter = allCenter; } void SqlQueryModel::setAlignCenterColumn(const QList<int> &alignCenterColumn) { this->alignCenterColumn = alignCenterColumn; } void SqlQueryModel::setAlignRightColumn(const QList<int> &alignRightColumn) { this->alignRightColumn = alignRightColumn; } DbCountThread::DbCountThread(QObject *parent) : QThread(parent) { connName = "qt_sql_default_connection"; sql = "select 1"; connect(this, SIGNAL(finished()), this, SLOT(deleteLater())); } void DbCountThread::run() { select(); } void DbCountThread::setConnName(const QString &connName) { this->connName = connName; } void DbCountThread::setSql(const QString &sql) { this->sql = sql; } void DbCountThread::select() { //计算用时 QDateTime dtStart = QDateTime::currentDateTime(); QSqlQuery query(QSqlDatabase::database(connName)); query.exec(sql); query.next(); int count = query.value(0).toUInt(); QDateTime dtEnd = QDateTime::currentDateTime(); double msec = dtStart.msecsTo(dtEnd); emit receiveCount(count, msec); } QScopedPointer<DbPage> DbPage::self; DbPage *DbPage::Instance() { if (self.isNull()) { static QMutex mutex; QMutexLocker locker(&mutex); if (self.isNull()) { self.reset(new DbPage); } } return self.data(); } DbPage::DbPage(QObject *parent) : QObject(parent) { startIndex = 0; tempSql = ""; sql = ""; queryModel = new SqlQueryModel; pageCurrent = 1; pageCount = 0; resultCount = 0; resultCurrent = 0; labPageCount = 0; labPageCurrent = 0; labResultCount = 0; labResultCurrent = 0; labResult = 0; labInfo = 0; tableView = 0; btnFirst = 0; btnPre = 0; btnNext = 0; btnLast = 0; countName = "*"; connName = "qt_sql_default_connection"; dbType = DbType_Sqlite; pageCurrent = 0; pageCount = 0; resultCount = 0; resultCurrent = 30; tableName = ""; selectColumn = "*"; orderSql = ""; whereSql = ""; columnNames.clear(); columnWidths.clear(); insertColumnIndex = -1; insertColumnName = ""; insertColumnWidth = 50; } void DbPage::bindData(const QString &columnName, const QString &orderColumn, const QString &tableName, QComboBox *cbox, const QString &connName) { QSqlQuery query(QSqlDatabase::database(connName)); query.exec("select " + columnName + " from " + tableName + " order by " + orderColumn + " asc"); while (query.next()) { cbox->addItem(query.value(0).toString()); } } void DbPage::bindData(const QString &columnName, const QString &orderColumn, const QString &tableName, QList<QComboBox *> cboxs, const QString &connName) { QSqlQuery query(QSqlDatabase::database(connName)); query.exec("select " + columnName + " from " + tableName + " order by " + orderColumn + " asc"); while (query.next()) { foreach (QComboBox *cbox, cboxs) { cbox->addItem(query.value(0).toString()); } } } void DbPage::bindData(const QString &sql) { queryModel->setQuery(sql, QSqlDatabase::database(connName)); tableView->setModel(queryModel); //依次设置列标题列宽 int columnCount = tableView->model()->columnCount(); int nameCount = columnNames.count(); columnCount = columnCount > nameCount ? nameCount : columnCount; QList<QString> columnNames = this->columnNames; QList<int> columnWidths = this->columnWidths; //根据设置添加新列,将对应新列的标题名称和宽度按照索引位置插 if (insertColumnIndex >= 0) { columnCount++; columnNames.insert(insertColumnIndex, insertColumnName); columnWidths.insert(insertColumnIndex, insertColumnWidth); queryModel->insertColumn(insertColumnIndex); } //设置列标题和列宽度 for (int i = 0; i < columnCount; i++) { queryModel->setHeaderData(i, Qt::Horizontal, columnNames.at(i)); tableView->setColumnWidth(i, columnWidths.at(i)); } if (labPageCurrent != 0) { labPageCurrent->setText(QString("第 %1 页").arg(pageCurrent)); } if (labPageCount != 0) { labPageCount->setText(QString("共 %1 页").arg(pageCount)); } if (labResultCount != 0) { labResultCount->setText(QString("共 %1 条").arg(resultCount)); } if (labResultCurrent != 0) { labResultCurrent->setText(QString("每页 %1 条").arg(resultCurrent)); } if (labInfo != 0) { labInfo->setText(QString("共 %1 条 每页 %2 条 共 %3 页 第 %4 页").arg(resultCount).arg(resultCurrent).arg(pageCount).arg(pageCurrent)); } //发送结果信号 emit receivePage(pageCurrent, pageCount, resultCount, resultCurrent); } void DbPage::slot_receiveCount(quint32 count, double msec) { if (labResult != 0) { labResult->setText(QString("查询用时 %1 秒").arg(QString::number(msec / 1000, 'f', 3))); } resultCount = count; int yushu = resultCount % resultCurrent; //不存在余数,说明是整行,例如300%5==0 if (yushu == 0) { if (resultCount > 0 && resultCount < resultCurrent) { pageCount = 1; } else { pageCount = resultCount / resultCurrent; } } else { pageCount = (resultCount / resultCurrent) + 1; } //2014-10-9增加翻页按钮可用不可用处理,如果只有一页数据,则翻页按钮不可用 if (pageCount <= 1) { btnFirst->setEnabled(false); btnLast->setEnabled(false); btnNext->setEnabled(false); btnPre->setEnabled(false); } else { btnFirst->setEnabled(true); btnLast->setEnabled(true); btnNext->setEnabled(true); btnPre->setEnabled(true); } tempSql = QString("select %1 from %2 %3 order by %4").arg(selectColumn).arg(tableName).arg(whereSql).arg(orderSql); sql = QString("%1 limit %2,%3;").arg(tempSql).arg(startIndex).arg(resultCurrent); //组织分页SQL语句 bindData(sql); } void DbPage::first() { if (pageCount > 1) { startIndex = 0; pageCurrent = 1; sql = QString("%1 limit %2,%3;").arg(tempSql).arg(startIndex).arg(resultCurrent); bindData(sql); btnLast->setEnabled(true); btnNext->setEnabled(true); } btnFirst->setEnabled(false); btnPre->setEnabled(false); } void DbPage::previous() { if (pageCurrent > 1) { pageCurrent--; startIndex -= resultCurrent; sql = QString("%1 limit %2,%3;").arg(tempSql).arg(startIndex).arg(resultCurrent); bindData(sql); btnLast->setEnabled(true); btnNext->setEnabled(true); } if (pageCurrent == 1) { btnFirst->setEnabled(false); btnPre->setEnabled(false); } } void DbPage::next() { if (pageCurrent < pageCount) { pageCurrent++; startIndex += resultCurrent; sql = QString("%1 limit %2,%3;").arg(tempSql).arg(startIndex).arg(resultCurrent); bindData(sql); btnFirst->setEnabled(true); btnPre->setEnabled(true); } if (pageCurrent == pageCount) { btnLast->setEnabled(false); btnNext->setEnabled(false); } } void DbPage::last() { if (pageCount > 0) { startIndex = (pageCount - 1) * resultCurrent; pageCurrent = pageCount; sql = QString("%1 limit %2,%3;").arg(tempSql).arg(startIndex).arg(resultCurrent); bindData(sql); btnFirst->setEnabled(true); btnPre->setEnabled(true); } btnLast->setEnabled(false); btnNext->setEnabled(false); } //设置显示数据的表格控件,当前翻页信息的标签控件等 void DbPage::setControl(QTableView *tableView, QLabel *labPageCount, QLabel *labPageCurrent, QLabel *labResultCount, QLabel *labResultCurrent, QLabel *labResult, QLabel *labInfo, QAbstractButton *btnFirst, QAbstractButton *btnPre, QAbstractButton *btnNext, QAbstractButton *btnLast, const QString &countName, const QString &connName) { this->tableView = tableView; this->labPageCount = labPageCount; this->labPageCurrent = labPageCurrent; this->labResultCount = labResultCount; this->labResultCurrent = labResultCurrent; this->labResult = labResult; this->labInfo = labInfo; this->btnFirst = btnFirst; this->btnPre = btnPre; this->btnNext = btnNext; this->btnLast = btnLast; this->countName = countName; this->connName = connName; this->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); //挂载翻页按钮事件 connect(btnFirst, SIGNAL(clicked()), this, SLOT(first())); connect(btnPre, SIGNAL(clicked()), this, SLOT(previous())); connect(btnNext, SIGNAL(clicked()), this, SLOT(next())); connect(btnLast, SIGNAL(clicked()), this, SLOT(last())); } void DbPage::setConnName(const QString &connName) { this->connName = connName; } void DbPage::setDbType(const DbPage::DbType &dbType) { this->dbType = dbType; } void DbPage::setTableName(const QString &tableName) { this->tableName = tableName; } void DbPage::setSelectColumn(const QString &selectColumn) { this->selectColumn = selectColumn; } void DbPage::setOrderSql(const QString &orderSql) { this->orderSql = orderSql; } void DbPage::setWhereSql(const QString &whereSql) { this->whereSql = whereSql; } void DbPage::setResultCurrent(int resultCurrent) { this->resultCurrent = resultCurrent; } void DbPage::setColumnNames(const QList<QString> &columnNames) { this->columnNames = columnNames; } void DbPage::setColumnWidths(const QList<int> &columnWidths) { this->columnWidths = columnWidths; } void DbPage::setAllCenter(bool allCenter) { queryModel->setAllCenter(allCenter); } void DbPage::setAlignCenterColumn(const QList<int> &alignCenterColumn) { queryModel->setAlignCenterColumn(alignCenterColumn); } void DbPage::setAlignRightColumn(const QList<int> &alignRightColumn) { queryModel->setAlignRightColumn(alignRightColumn); } void DbPage::setInsertColumnIndex(int insertColumnIndex) { this->insertColumnIndex = insertColumnIndex; } void DbPage::setInsertColumnName(const QString &insertColumnName) { this->insertColumnName = insertColumnName; } void DbPage::setInsertColumnWidth(int insertColumnWidth) { this->insertColumnWidth = insertColumnWidth; } void DbPage::select() { //重置开始索引 startIndex = 0; pageCurrent = 1; //假设只有一页 slot_receiveCount(resultCurrent, 0); //全部禁用按钮,文本显示正在查询... btnFirst->setEnabled(false); btnLast->setEnabled(false); btnNext->setEnabled(false); btnPre->setEnabled(false); QString info = "正在查询..."; if (labInfo != 0) { labInfo->setText(info); } if (labPageCurrent != 0) { labPageCurrent->setText(info); } if (labPageCount != 0) { labPageCount->setText(info); } if (labResultCount != 0) { labResultCount->setText(info); } if (labResultCurrent != 0) { labResultCurrent->setText(info); } if (labResult != 0) { labResult->setText(info); } //开始分页绑定数据前,计算好总数据量以及行数 tempSql = QString("select count(%1) from %2 %3").arg(countName).arg(tableName).arg(whereSql); //采用线程执行查询复合条件的记录行数 DbCountThread *dbCountThread = new DbCountThread(this); //绑定查询结果信号槽,一旦收到结果则立即执行 connect(dbCountThread, SIGNAL(receiveCount(quint32, double)), this, SIGNAL(receiveCount(quint32, double))); connect(dbCountThread, SIGNAL(receiveCount(quint32, double)), this, SLOT(slot_receiveCount(quint32, double))); //设置数据库连接名称和查询语句,并启动线程 dbCountThread->setConnName(connName); dbCountThread->setSql(tempSql); //从5.10开始不支持数据库在线程中执行 #if (QT_VERSION <= QT_VERSION_CHECK(5,10,0)) dbCountThread->start(); #else dbCountThread->select(); #endif }
26.100935
137
0.621097
[ "model" ]
cd65d2fcde54f8ecf9b88a4e7b08c00690100184
86,437
cpp
C++
SmartMirror/performance_functional/performance_functional.cpp
mishless/smart-mirror
0f948d1fb05762d982b2eef925748877b6cf700e
[ "MIT" ]
1
2016-05-05T21:07:37.000Z
2016-05-05T21:07:37.000Z
SmartMirror/performance_functional/performance_functional.cpp
mishless/smart-mirror
0f948d1fb05762d982b2eef925748877b6cf700e
[ "MIT" ]
null
null
null
SmartMirror/performance_functional/performance_functional.cpp
mishless/smart-mirror
0f948d1fb05762d982b2eef925748877b6cf700e
[ "MIT" ]
null
null
null
/****************************************************************************************************************/ /* */ /* OpenNN: Open Neural Networks Library */ /* www.opennn.cimne.com */ /* */ /* P E R F O R M A N C E F U N C T I O N A L C L A S S */ /* */ /* Roberto Lopez */ /* International Center for Numerical Methods in Engineering (CIMNE) */ /* Technical University of Catalonia (UPC) */ /* Barcelona, Spain */ /* E-mail: rlopez@cimne.upc.edu */ /* */ /****************************************************************************************************************/ // System includes #include <string> #include <sstream> #include <iostream> #include <cmath> // OpenNN includes #include "../utilities/vector.h" #include "../utilities/matrix.h" #include "../utilities/numerical_differentiation.h" #include "performance_functional.h" #include "sum_squared_error.h" #include "mean_squared_error.h" #include "root_mean_squared_error.h" #include "normalized_squared_error.h" #include "minkowski_error.h" #include "cross_entropy_error.h" #include "inverse_sum_squared_error.h" #include "neural_parameters_norm.h" #include "outputs_integrals.h" #include "independent_parameters_error.h" #include "final_solutions_error.h" #include "solutions_error.h" // TinyXml includes #include "../../parsers/tinyxml/tinyxml.h" namespace OpenNN { // DEFAULT CONSTRUCTOR /// Default constructor. /// It creates a performance functional object with all pointers initialized to NULL. /// It also initializes all the rest of class members to their default values. PerformanceFunctional::PerformanceFunctional(void) : neural_network_pointer(NULL) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); construct_objective_term(objective_term_type); } // NEURAL NETWORK CONSTRUCTOR /// Neural network constructor. /// It creates a performance functional object associated to a neural network object. /// The rest of pointers are initialized to NULL. /// It also initializes all the rest of class members to their default values. /// @param new_neural_network_pointer Pointer to a neural network object. PerformanceFunctional::PerformanceFunctional(NeuralNetwork* new_neural_network_pointer) : neural_network_pointer(new_neural_network_pointer) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); construct_objective_term(objective_term_type); } // NEURAL NETWORK AND DATA SET CONSTRUCTOR /// Neural network and data set constructor. /// It creates a performance functional object associated to a neural network and a data set objects. /// The rest of pointers are initialized to NULL. /// It also initializes all the rest of class members to their default values. /// @param new_neural_network_pointer Pointer to a neural network object. /// @param new_data_set_pointer Pointer to a data set object. PerformanceFunctional::PerformanceFunctional(NeuralNetwork* new_neural_network_pointer, DataSet* new_data_set_pointer) : neural_network_pointer(new_neural_network_pointer) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); construct_objective_term(objective_term_type); objective_term_pointer->set_data_set_pointer(new_data_set_pointer); } // NEURAL NETWORK AND MATHEMATICAL MODEL CONSTRUCTOR /// Neural network and mathematical model constructor. /// It creates a performance functional object associated to a neural network and a mathematical model objects. /// The rest of pointers are initialized to NULL. /// It also initializes all the rest of class members to their default values. /// @param new_neural_network_pointer Pointer to a neural network object. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. PerformanceFunctional::PerformanceFunctional(NeuralNetwork* new_neural_network_pointer, MathematicalModel* new_mathematical_model_pointer) : neural_network_pointer(new_neural_network_pointer) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); construct_objective_term(objective_term_type); objective_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); } // NEURAL NETWORK, MATHEMATICAL MODEL AND DATA SET CONSTRUCTOR /// Neural network, mathematical model and data set constructor. /// It creates a performance functional object associated to a neural network, a mathematical model and a data set objects. /// The rest of pointers are initialized to NULL. /// It also initializes all the rest of class members to their default values. /// @param new_neural_network_pointer Pointer to a neural network object. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. /// @param new_data_set_pointer Pointer to a data set object. PerformanceFunctional::PerformanceFunctional(NeuralNetwork* new_neural_network_pointer, MathematicalModel* new_mathematical_model_pointer, DataSet* new_data_set_pointer) : neural_network_pointer(new_neural_network_pointer) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); construct_objective_term(objective_term_type, new_mathematical_model_pointer, new_data_set_pointer); } // OBJECTIVE TERM CONSTRUCTOR /// Objective term constructor. /// It creates a performance functional object with a given objective functional. /// The rest of pointers are initialized to NULL. /// The other members are set to their default values, but the objective term type, which is set to USER_PERFORMANCE_TERM. PerformanceFunctional::PerformanceFunctional(PerformanceTerm* new_objective_term_pointer) : neural_network_pointer(NULL) , objective_term_pointer(new_objective_term_pointer) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); objective_term_type = PerformanceFunctional::USER_PERFORMANCE_TERM; } // FILE CONSTRUCTOR /// File constructor. /// It creates a performance functional object by loading its members from an XML-type file. /// Please be careful with the format of that file, which is specified in the OpenNN manual. /// @param filename Name of performance functional file. PerformanceFunctional::PerformanceFunctional(const std::string& filename) : neural_network_pointer(NULL) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { set_default(); load(filename); } // COPY CONSTRUCTOR /// Copy constructor. /// It creates a copy of an existing performance functional object. /// @param other_performance_functional Performance functional object to be copied. /// @todo PerformanceFunctional::PerformanceFunctional(const PerformanceFunctional& other_performance_functional) : neural_network_pointer(NULL) , objective_term_pointer(NULL) , regularization_term_pointer(NULL) , constraints_term_pointer(NULL) { neural_network_pointer = other_performance_functional.neural_network_pointer; objective_term_type = other_performance_functional.objective_term_type; regularization_term_type = other_performance_functional.regularization_term_type; constraints_term_type = other_performance_functional.constraints_term_type; if(other_performance_functional.objective_term_pointer) { construct_objective_term(objective_term_type); objective_term_pointer->set(*other_performance_functional.objective_term_pointer); } if(other_performance_functional.regularization_term_pointer) { construct_regularization_term(regularization_term_type); regularization_term_pointer->set(*other_performance_functional.regularization_term_pointer); } if(other_performance_functional.constraints_term_pointer) { construct_constraints_term(constraints_term_type); constraints_term_pointer->set(*other_performance_functional.constraints_term_pointer); } objective_term_flag = other_performance_functional.objective_term_flag; regularization_term_flag = other_performance_functional.regularization_term_flag; constraints_term_flag = other_performance_functional.constraints_term_flag; display = other_performance_functional.display; } // DESTRUCTOR /// Destructor. /// It deletes the objective, regularization and constraints terms. PerformanceFunctional::~PerformanceFunctional(void) { delete objective_term_pointer; delete regularization_term_pointer; delete constraints_term_pointer; } // METHODS // const PerformanceTermType& get_objective_term_type(void) const method /// This method returns the type of objective term used in the performance functional expression. const PerformanceFunctional::PerformanceTermType& PerformanceFunctional::get_objective_term_type(void) const { return(objective_term_type); } // const PerformanceTermType& get_regularization_term_type(void) const method /// This method returns the type of regularization term used in the performance functional expression. const PerformanceFunctional::PerformanceTermType& PerformanceFunctional::get_regularization_term_type(void) const { return(regularization_term_type); } // const PerformanceTermType& get_constraints_term_type(void) const method /// This method returns the type of constraints term used in the performance functional expression. const PerformanceFunctional::PerformanceTermType& PerformanceFunctional::get_constraints_term_type(void) const { return(constraints_term_type); } // std::string write_objective_term_type(void) const /// This method returns a string with the type of objective term used in the performance functional expression. std::string PerformanceFunctional::write_objective_term_type(void) const { if(objective_term_type == NONE) { return("NONE"); } else if(objective_term_type == SUM_SQUARED_ERROR) { return("SUM_SQUARED_ERROR"); } else if(objective_term_type == MEAN_SQUARED_ERROR) { return("MEAN_SQUARED_ERROR"); } else if(objective_term_type == ROOT_MEAN_SQUARED_ERROR) { return("ROOT_MEAN_SQUARED_ERROR"); } else if(objective_term_type == NORMALIZED_SQUARED_ERROR) { return("NORMALIZED_SQUARED_ERROR"); } else if(objective_term_type == MINKOWSKI_ERROR) { return("MINKOWSKI_ERROR"); } else if(objective_term_type == CROSS_ENTROPY_ERROR) { return("CROSS_ENTROPY_ERROR"); } else if(objective_term_type == NEURAL_PARAMETERS_NORM) { return("NEURAL_PARAMETERS_NORM"); } else if(objective_term_type == OUTPUTS_INTEGRALS) { return("OUTPUTS_INTEGRALS"); } else if(objective_term_type == SOLUTION_ERROR) { return("SOLUTION_ERROR"); } else if(objective_term_type == FINAL_SOLUTIONS_ERROR) { return("FINAL_SOLUTIONS_ERROR"); } else if(objective_term_type == INDEPENDENT_PARAMETERS_ERROR) { return("INDEPENDENT_PARAMETERS_ERROR"); } else if(objective_term_type == INVERSE_SUM_SQUARED_ERROR) { return("INVERSE_SUM_SQUARED_ERROR"); } else if(objective_term_type == USER_PERFORMANCE_TERM) { return("USER_PERFORMANCE_TERM"); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "std::string write_objective_term_type(void) const method.\n" << "Unknown performance term type.\n"; throw std::logic_error(buffer.str()); } } // std::string write_regularization_term_type(void) const method /// This method returns a string with the type of regularization term used in the performance functional expression. std::string PerformanceFunctional::write_regularization_term_type(void) const { if(regularization_term_type == NONE) { return("NONE"); } else if(regularization_term_type == SUM_SQUARED_ERROR) { return("SUM_SQUARED_ERROR"); } else if(regularization_term_type == MEAN_SQUARED_ERROR) { return("MEAN_SQUARED_ERROR"); } else if(regularization_term_type == ROOT_MEAN_SQUARED_ERROR) { return("ROOT_MEAN_SQUARED_ERROR"); } else if(regularization_term_type == NORMALIZED_SQUARED_ERROR) { return("NORMALIZED_SQUARED_ERROR"); } else if(regularization_term_type == MINKOWSKI_ERROR) { return("MINKOWSKI_ERROR"); } else if(regularization_term_type == CROSS_ENTROPY_ERROR) { return("CROSS_ENTROPY_ERROR"); } else if(regularization_term_type == NEURAL_PARAMETERS_NORM) { return("NEURAL_PARAMETERS_NORM"); } else if(regularization_term_type == OUTPUTS_INTEGRALS) { return("OUTPUTS_INTEGRALS"); } else if(regularization_term_type == SOLUTION_ERROR) { return("SOLUTION_ERROR"); } else if(regularization_term_type == FINAL_SOLUTIONS_ERROR) { return("FINAL_SOLUTIONS_ERROR"); } else if(regularization_term_type == INDEPENDENT_PARAMETERS_ERROR) { return("INDEPENDENT_PARAMETERS_ERROR"); } else if(regularization_term_type == INVERSE_SUM_SQUARED_ERROR) { return("INVERSE_SUM_SQUARED_ERROR"); } else if(regularization_term_type == USER_PERFORMANCE_TERM) { return("USER_PERFORMANCE_TERM"); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "std::string write_regularization_term_type(void) const method.\n" << "Unknown performance term type.\n"; throw std::logic_error(buffer.str()); } } // std::string write_constraints_term_type(void) const method /// This method returns a string with the type of constraints term used in the performance functional expression. std::string PerformanceFunctional::write_constraints_term_type(void) const { if(constraints_term_type == NONE) { return("NONE"); } else if(constraints_term_type == SUM_SQUARED_ERROR) { return("SUM_SQUARED_ERROR"); } else if(constraints_term_type == MEAN_SQUARED_ERROR) { return("MEAN_SQUARED_ERROR"); } else if(constraints_term_type == ROOT_MEAN_SQUARED_ERROR) { return("ROOT_MEAN_SQUARED_ERROR"); } else if(constraints_term_type == NORMALIZED_SQUARED_ERROR) { return("NORMALIZED_SQUARED_ERROR"); } else if(constraints_term_type == MINKOWSKI_ERROR) { return("MINKOWSKI_ERROR"); } else if(constraints_term_type == CROSS_ENTROPY_ERROR) { return("CROSS_ENTROPY_ERROR"); } else if(constraints_term_type == NEURAL_PARAMETERS_NORM) { return("NEURAL_PARAMETERS_NORM"); } else if(constraints_term_type == OUTPUTS_INTEGRALS) { return("OUTPUTS_INTEGRALS"); } else if(constraints_term_type == SOLUTION_ERROR) { return("SOLUTION_ERROR"); } else if(constraints_term_type == FINAL_SOLUTIONS_ERROR) { return("FINAL_SOLUTIONS_ERROR"); } else if(constraints_term_type == INDEPENDENT_PARAMETERS_ERROR) { return("INDEPENDENT_PARAMETERS_ERROR"); } else if(constraints_term_type == INVERSE_SUM_SQUARED_ERROR) { return("INVERSE_SUM_SQUARED_ERROR"); } else if(constraints_term_type == USER_PERFORMANCE_TERM) { return("USER_PERFORMANCE_TERM"); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "std::string write_constraints_term_type(void) const method.\n" << "Unknown performance term type.\n"; throw std::logic_error(buffer.str()); } } // const bool& get_objective_term_flag(void) const method /// This method returns the flag value for including or not the objective term in the performance functional expression. const bool& PerformanceFunctional::get_objective_term_flag(void) const { return(objective_term_flag); } // const bool& get_regularization_term_flag(void) const method /// This method returns the flag value for using regularization or not. const bool& PerformanceFunctional::get_regularization_term_flag(void) const { return(regularization_term_flag); } // const bool& get_constraints_term_flag(void) const method /// This method returns true if constraints are to be included in the performance functional expression, /// and false otherwise. const bool& PerformanceFunctional::get_constraints_term_flag(void) const { return(constraints_term_flag); } // const bool& get_display(void) const method /// This method returns true if messages from this class can be displayed on the screen, or false if messages /// from this class can't be displayed on the screen. const bool& PerformanceFunctional::get_display(void) const { return(display); } // void set_neural_network_pointer(NeuralNetwork*) method /// This method sets a pointer to a multilayer perceptron object which is to be associated to the performance functional. /// @param new_neural_network_pointer Pointer to a neural network object to be associated to the performance functional. void PerformanceFunctional::set_neural_network_pointer(NeuralNetwork* new_neural_network_pointer) { neural_network_pointer = new_neural_network_pointer; } // void set_objective_term_pointer(PerformanceTerm*) method /// This method sets a new objective term into the performance functional. /// @param new_objective_term_pointer Pointer to a performance term representing the objective functional. void PerformanceFunctional::set_objective_term_pointer(PerformanceTerm* new_objective_term_pointer) { destruct_objective_term(); objective_term_pointer = new_objective_term_pointer; objective_term_flag = true; std::string objective_term_type = new_objective_term_pointer->write_performance_term_type(); set_objective_term_type(objective_term_type); } // void set_regularization_term_pointer(PerformanceTerm*) method /// This method sets a new regularization term into the performance functional. /// @param new_regularization_term_pointer Pointer to a performance term representing the regularization functional. void PerformanceFunctional::set_regularization_term_pointer(PerformanceTerm* new_regularization_term_pointer) { destruct_regularization_term(); regularization_term_pointer = new_regularization_term_pointer; regularization_term_flag = true; std::string regularization_term_type = new_regularization_term_pointer->write_performance_term_type(); set_regularization_term_type(regularization_term_type); } // void set_constraints_term_pointer(PerformanceTerm*) method /// This method sets a new constraints term into the performance functional. /// @param new_constraints_term_pointer Pointer to a performance term representing the constraints functional. void PerformanceFunctional::set_constraints_term_pointer(PerformanceTerm* new_constraints_term_pointer) { destruct_constraints_term(); constraints_term_pointer = new_constraints_term_pointer; constraints_term_flag = true; std::string constraints_term_type = new_constraints_term_pointer->write_performance_term_type(); set_constraints_term_type(constraints_term_type); } // void set_default(void) method /// This method sets the members of the performance functional object to their default values. void PerformanceFunctional::set_default(void) { set_objective_term_type(NORMALIZED_SQUARED_ERROR); set_regularization_term_type(NONE); set_constraints_term_type(NONE); objective_term_flag = true; regularization_term_flag = false; constraints_term_flag = false; display = true; } // void set_objective_term_type(const PerformanceTermType&) method /// This method sets a new type for the objective term. /// @param new_objective_term_type Type of objective term. void PerformanceFunctional::set_objective_term_type(const PerformanceTermType& new_objective_term_type) { objective_term_type = new_objective_term_type; } // void set_regularization_term_type(const PerformanceTermType&) method /// This method sets a new type for the regularization term. /// @param new_regularization_term_type Type of regularization term. void PerformanceFunctional::set_regularization_term_type(const PerformanceTermType& new_regularization_term_type) { regularization_term_type = new_regularization_term_type; } // void set_constraints_term_type(const PerformanceTermType&) method /// This method sets a new type for the constraints term. /// @param new_constraints_term_type Type of constraints term. void PerformanceFunctional::set_constraints_term_type(const PerformanceTermType& new_constraints_term_type) { constraints_term_type = new_constraints_term_type; } // void set_objective_term_type(const std::string&) method /// This method sets a new type for the objective term from a string. /// @param new_objective_term_type String with the type of objective term. void PerformanceFunctional::set_objective_term_type(const std::string& new_objective_term_type) { if(new_objective_term_type == "NONE") { set_objective_term_type(NONE); } else if(new_objective_term_type == "SUM_SQUARED_ERROR") { set_objective_term_type(SUM_SQUARED_ERROR); } else if(new_objective_term_type == "MEAN_SQUARED_ERROR") { set_objective_term_type(MEAN_SQUARED_ERROR); } else if(new_objective_term_type == "ROOT_MEAN_SQUARED_ERROR") { set_objective_term_type(ROOT_MEAN_SQUARED_ERROR); } else if(new_objective_term_type == "NORMALIZED_SQUARED_ERROR") { set_objective_term_type(NORMALIZED_SQUARED_ERROR); } else if(new_objective_term_type == "MINKOWSKI_ERROR") { set_objective_term_type(MINKOWSKI_ERROR); } else if(new_objective_term_type == "MINKOWSKI_ERROR") { set_objective_term_type(MINKOWSKI_ERROR); } else if(new_objective_term_type == "NEURAL_PARAMETERS_NORM") { set_objective_term_type(NEURAL_PARAMETERS_NORM); } else if(new_objective_term_type == "OUTPUTS_INTEGRALS") { set_objective_term_type(OUTPUTS_INTEGRALS); } else if(new_objective_term_type == "SOLUTION_ERROR") { set_objective_term_type(SOLUTION_ERROR); } else if(new_objective_term_type == "FINAL_SOLUTIONS_ERROR") { set_objective_term_type(FINAL_SOLUTIONS_ERROR); } else if(new_objective_term_type == "INDEPENDENT_PARAMETERS_ERROR") { set_objective_term_type(INDEPENDENT_PARAMETERS_ERROR); } else if(new_objective_term_type == "INVERSE_SUM_SQUARED_ERROR") { set_objective_term_type(INVERSE_SUM_SQUARED_ERROR); } else if(new_objective_term_type == "USER_PERFORMANCE_TERM") { set_objective_term_type(USER_PERFORMANCE_TERM); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void set_objective_term_type(const std::string&) method.\n" << "Unknown performance term type: " << new_objective_term_type << ".\n"; throw std::logic_error(buffer.str()); } } // void set_regularization_term_type(const std::string&) method /// This method sets a new type for the regularization term from a string. /// @param new_regularization_term_type String with the type of regularization term. void PerformanceFunctional::set_regularization_term_type(const std::string& new_regularization_term_type) { if(new_regularization_term_type == "NONE") { set_regularization_term_type(NONE); } else if(new_regularization_term_type == "SUM_SQUARED_ERROR") { set_regularization_term_type(SUM_SQUARED_ERROR); } else if(new_regularization_term_type == "MEAN_SQUARED_ERROR") { set_regularization_term_type(MEAN_SQUARED_ERROR); } else if(new_regularization_term_type == "ROOT_MEAN_SQUARED_ERROR") { set_regularization_term_type(ROOT_MEAN_SQUARED_ERROR); } else if(new_regularization_term_type == "NORMALIZED_SQUARED_ERROR") { set_regularization_term_type(NORMALIZED_SQUARED_ERROR); } else if(new_regularization_term_type == "MINKOWSKI_ERROR") { set_regularization_term_type(MINKOWSKI_ERROR); } else if(new_regularization_term_type == "MINKOWSKI_ERROR") { set_regularization_term_type(MINKOWSKI_ERROR); } else if(new_regularization_term_type == "NEURAL_PARAMETERS_NORM") { set_regularization_term_type(NEURAL_PARAMETERS_NORM); } else if(new_regularization_term_type == "OUTPUTS_INTEGRALS") { set_regularization_term_type(OUTPUTS_INTEGRALS); } else if(new_regularization_term_type == "SOLUTION_ERROR") { set_regularization_term_type(SOLUTION_ERROR); } else if(new_regularization_term_type == "FINAL_SOLUTIONS_ERROR") { set_regularization_term_type(FINAL_SOLUTIONS_ERROR); } else if(new_regularization_term_type == "INDEPENDENT_PARAMETERS_ERROR") { set_regularization_term_type(INDEPENDENT_PARAMETERS_ERROR); } else if(new_regularization_term_type == "INVERSE_SUM_SQUARED_ERROR") { set_regularization_term_type(INVERSE_SUM_SQUARED_ERROR); } else if(new_regularization_term_type == "USER_PERFORMANCE_TERM") { set_regularization_term_type(USER_PERFORMANCE_TERM); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void set_regularization_term_type(const std::string&) method.\n" << "Unknown performance functional type: " << new_regularization_term_type << ".\n"; throw std::logic_error(buffer.str()); } } // void set_constraints_term_type(const std::string&) method /// This method sets a new type for the constraints term from a string. /// @param new_constraints_term_type String with the type of constraints term. void PerformanceFunctional::set_constraints_term_type(const std::string& new_constraints_term_type) { if(new_constraints_term_type == "NONE") { set_constraints_term_type(NONE); } else if(new_constraints_term_type == "SUM_SQUARED_ERROR") { set_constraints_term_type(SUM_SQUARED_ERROR); } else if(new_constraints_term_type == "MEAN_SQUARED_ERROR") { set_constraints_term_type(MEAN_SQUARED_ERROR); } else if(new_constraints_term_type == "ROOT_MEAN_SQUARED_ERROR") { set_constraints_term_type(ROOT_MEAN_SQUARED_ERROR); } else if(new_constraints_term_type == "NORMALIZED_SQUARED_ERROR") { set_constraints_term_type(NORMALIZED_SQUARED_ERROR); } else if(new_constraints_term_type == "MINKOWSKI_ERROR") { set_constraints_term_type(MINKOWSKI_ERROR); } else if(new_constraints_term_type == "MINKOWSKI_ERROR") { set_constraints_term_type(MINKOWSKI_ERROR); } else if(new_constraints_term_type == "NEURAL_PARAMETERS_NORM") { set_constraints_term_type(NEURAL_PARAMETERS_NORM); } else if(new_constraints_term_type == "OUTPUTS_INTEGRALS") { set_constraints_term_type(OUTPUTS_INTEGRALS); } else if(new_constraints_term_type == "SOLUTION_ERROR") { set_constraints_term_type(SOLUTION_ERROR); } else if(new_constraints_term_type == "FINAL_SOLUTIONS_ERROR") { set_constraints_term_type(FINAL_SOLUTIONS_ERROR); } else if(new_constraints_term_type == "INDEPENDENT_PARAMETERS_ERROR") { set_constraints_term_type(INDEPENDENT_PARAMETERS_ERROR); } else if(new_constraints_term_type == "INVERSE_SUM_SQUARED_ERROR") { set_constraints_term_type(INVERSE_SUM_SQUARED_ERROR); } else if(new_constraints_term_type == "USER_PERFORMANCE_TERM") { set_constraints_term_type(USER_PERFORMANCE_TERM); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void set_constraints_term_type(const std::string&) method.\n" << "Unknown performance term type: " << new_constraints_term_type << ".\n"; throw std::logic_error(buffer.str()); } } // void set_objective_term_flag(const bool&) method /// This method sets a new flag value for using the objective term or not. /// @param new_objective_term_flag Flag value for the use of objective term. void PerformanceFunctional::set_objective_term_flag(const bool& new_objective_term_flag) { objective_term_flag = new_objective_term_flag; } // void set_regularization_term_flag(const bool&) method /// This method sets a new flag value for using regularization or not. /// @param new_regularization_term_flag Flag value for the use of regularization. void PerformanceFunctional::set_regularization_term_flag(const bool& new_regularization_term_flag) { regularization_term_flag = new_regularization_term_flag; } // void set_constraints_term_flag(const bool&) method /// This method sets a new flag value for using constraints or not in the performance functional expression. /// @param new_constraints_term_flag Flag value for the use of constraints. void PerformanceFunctional::set_constraints_term_flag(const bool& new_constraints_term_flag) { constraints_term_flag = new_constraints_term_flag; } // void set_display(const bool&) method /// This method sets a new display value. /// If it is set to true messages from this class are to be displayed on the screen; /// if it is set to false messages from this class are not to be displayed on the screen. /// @param new_display Display value. void PerformanceFunctional::set_display(const bool& new_display) { display = new_display; } // void construct_objective_term(const PerformanceTermType&) method /// This method creates a new objective term inside the performance functional of a given performance term type. /// @param new_objective_term_type Type of objective term to be created. void PerformanceFunctional::construct_objective_term(const PerformanceTermType& new_objective_term_type) { if(objective_term_pointer) { delete objective_term_pointer; } objective_term_type = new_objective_term_type; objective_term_flag = true; switch(new_objective_term_type) { case NONE: { objective_term_pointer = NULL; } break; case SUM_SQUARED_ERROR: { objective_term_pointer = new SumSquaredError(neural_network_pointer); } break; case MEAN_SQUARED_ERROR: { objective_term_pointer = new MeanSquaredError(neural_network_pointer); } break; case ROOT_MEAN_SQUARED_ERROR: { objective_term_pointer = new RootMeanSquaredError(neural_network_pointer); } break; case NORMALIZED_SQUARED_ERROR: { objective_term_pointer = new NormalizedSquaredError(neural_network_pointer); } break; case MINKOWSKI_ERROR: { objective_term_pointer = new MinkowskiError(neural_network_pointer); } break; case CROSS_ENTROPY_ERROR: { objective_term_pointer = new CrossEntropyError(neural_network_pointer); } break; case NEURAL_PARAMETERS_NORM: { objective_term_pointer = new NeuralParametersNorm(neural_network_pointer); } break; case OUTPUTS_INTEGRALS: { objective_term_pointer = new OutputsIntegrals(neural_network_pointer); } break; case SOLUTION_ERROR: { objective_term_pointer = new SolutionsError(neural_network_pointer); } break; case FINAL_SOLUTIONS_ERROR: { objective_term_pointer = new FinalSolutionsError(neural_network_pointer); } break; case INDEPENDENT_PARAMETERS_ERROR: { objective_term_pointer = new IndependentParametersError(neural_network_pointer); } break; case INVERSE_SUM_SQUARED_ERROR: { objective_term_pointer = new InverseSumSquaredError(neural_network_pointer); } break; case USER_PERFORMANCE_TERM: { objective_term_pointer = NULL; } break; default: { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void construct_objective_term(const PerformanceTermType&) method.\n" << "Unknown performance term type.\n"; throw std::logic_error(buffer.str().c_str()); } break; } } // void construct_regularization_term(const PerformanceTermType&) method /// This method creates a new regularization term inside the performance functional of a given performance term type. /// @param new_regularization_term_type Type of regularization term to be created. void PerformanceFunctional::construct_regularization_term(const PerformanceTermType& new_regularization_term_type) { if(regularization_term_pointer) { delete regularization_term_pointer; } regularization_term_type = new_regularization_term_type; regularization_term_flag = true; switch(regularization_term_type) { case NONE: { regularization_term_pointer = NULL; } break; case SUM_SQUARED_ERROR: { regularization_term_pointer = new SumSquaredError(neural_network_pointer); } break; case MEAN_SQUARED_ERROR: { regularization_term_pointer = new MeanSquaredError(neural_network_pointer); } break; case ROOT_MEAN_SQUARED_ERROR: { regularization_term_pointer = new RootMeanSquaredError(neural_network_pointer); } break; case NORMALIZED_SQUARED_ERROR: { regularization_term_pointer = new NormalizedSquaredError(neural_network_pointer); } break; case MINKOWSKI_ERROR: { regularization_term_pointer = new MinkowskiError(neural_network_pointer); } break; case CROSS_ENTROPY_ERROR: { regularization_term_pointer = new CrossEntropyError(neural_network_pointer); } break; case NEURAL_PARAMETERS_NORM: { regularization_term_pointer = new NeuralParametersNorm(neural_network_pointer); } break; case OUTPUTS_INTEGRALS: { regularization_term_pointer = new OutputsIntegrals(neural_network_pointer); } break; case SOLUTION_ERROR: { regularization_term_pointer = new SolutionsError(neural_network_pointer); } break; case FINAL_SOLUTIONS_ERROR: { regularization_term_pointer = new FinalSolutionsError(neural_network_pointer); } break; case INDEPENDENT_PARAMETERS_ERROR: { regularization_term_pointer = new IndependentParametersError(neural_network_pointer); } break; case INVERSE_SUM_SQUARED_ERROR: { regularization_term_pointer = new InverseSumSquaredError(neural_network_pointer); } break; case USER_PERFORMANCE_TERM: { regularization_term_pointer = NULL; } break; default: { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void set_regularization_term_type(const PerformanceTermType&) method.\n" << "Unknown performance term type.\n"; throw std::logic_error(buffer.str().c_str()); } break; } } // void construct_constraints_term_type(const PerformanceTermType&) method /// This method creates a new constraints term inside the performance functional of a given performance term type. /// @param new_constraints_term_type Type of constraints term to be created. void PerformanceFunctional::construct_constraints_term(const PerformanceTermType& new_constraints_term_type) { if(constraints_term_pointer) { delete constraints_term_pointer; } constraints_term_type = new_constraints_term_type; constraints_term_flag = true; switch(constraints_term_type) { case NONE: { constraints_term_pointer = NULL; } break; case SUM_SQUARED_ERROR: { constraints_term_pointer = new SumSquaredError(neural_network_pointer); } break; case MEAN_SQUARED_ERROR: { constraints_term_pointer = new MeanSquaredError(neural_network_pointer); } break; case ROOT_MEAN_SQUARED_ERROR: { constraints_term_pointer = new RootMeanSquaredError(neural_network_pointer); } break; case NORMALIZED_SQUARED_ERROR: { constraints_term_pointer = new NormalizedSquaredError(neural_network_pointer); } break; case MINKOWSKI_ERROR: { constraints_term_pointer = new MinkowskiError(neural_network_pointer); } break; case CROSS_ENTROPY_ERROR: { constraints_term_pointer = new CrossEntropyError(neural_network_pointer); } break; case NEURAL_PARAMETERS_NORM: { constraints_term_pointer = new NeuralParametersNorm(neural_network_pointer); } break; case OUTPUTS_INTEGRALS: { constraints_term_pointer = new OutputsIntegrals(neural_network_pointer); } break; case SOLUTION_ERROR: { constraints_term_pointer = new SolutionsError(neural_network_pointer); } break; case FINAL_SOLUTIONS_ERROR: { constraints_term_pointer = new FinalSolutionsError(neural_network_pointer); } break; case INDEPENDENT_PARAMETERS_ERROR: { constraints_term_pointer = new IndependentParametersError(neural_network_pointer); } break; case INVERSE_SUM_SQUARED_ERROR: { constraints_term_pointer = new InverseSumSquaredError(neural_network_pointer); } break; case USER_PERFORMANCE_TERM: { constraints_term_pointer = NULL; } break; default: { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void set_constraints_term_type(const PerformanceTermType&) method.\n" << "Unknown performance term type.\n"; throw std::logic_error(buffer.str().c_str()); } break; } } // void construct_objective_term(const PerformanceTermType&, MathematicalModel*) method /// This method creates a new objective term inside the performance functional. /// @param new_performance_term_type Type of objective term. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. void PerformanceFunctional::construct_objective_term(const PerformanceTermType& new_performance_term_type, MathematicalModel* new_mathematical_model_pointer) { construct_objective_term(new_performance_term_type); objective_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); } // void construct_regularization_term(const PerformanceTermType&, MathematicalModel*) /// This method creates a new regularization term inside the performance functional. /// @param new_performance_term_type Type of objective term. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. void PerformanceFunctional::construct_regularization_term(const PerformanceTermType& new_performance_term_type, MathematicalModel* new_mathematical_model_pointer) { construct_regularization_term(new_performance_term_type); regularization_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); } // void construct_constraints_term(const PerformanceTermType&, MathematicalModel*) /// This method creates a new constraints term inside the performance functional. /// @param new_performance_term_type Type of objective term. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. void PerformanceFunctional::construct_constraints_term(const PerformanceTermType& new_performance_term_type, MathematicalModel* new_mathematical_model_pointer) { construct_constraints_term(new_performance_term_type); constraints_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); } // void construct_objective_term(const PerformanceTermType&, DataSet*) /// This method creates a new objective term inside the performance functional. /// @param new_performance_term_type Type of objective term. /// @param new_data_set_pointer Pointer to a data set object. void PerformanceFunctional::construct_objective_term(const PerformanceTermType& new_performance_term_type, DataSet* new_data_set_pointer) { construct_objective_term(new_performance_term_type); objective_term_pointer->set_data_set_pointer(new_data_set_pointer); } // void construct_regularization_term(const PerformanceTermType&, DataSet*) /// This method creates a new regularization term inside the performance functional. /// @param new_performance_term_type Type of regularization term. /// @param new_data_set_pointer Pointer to a data set object. void PerformanceFunctional::construct_regularization_term(const PerformanceTermType& new_performance_term_type, DataSet* new_data_set_pointer) { construct_regularization_term(new_performance_term_type); regularization_term_pointer->set_data_set_pointer(new_data_set_pointer); } // void construct_constraints_term(const PerformanceTermType&, DataSet*) /// This method creates a new constraints term inside the performance functional. /// @param new_performance_term_type Type of constraints term. /// @param new_data_set_pointer Pointer to a data set object. void PerformanceFunctional::construct_constraints_term(const PerformanceTermType& new_performance_term_type, DataSet* new_data_set_pointer) { construct_constraints_term(new_performance_term_type); constraints_term_pointer->set_data_set_pointer(new_data_set_pointer); } // void construct_objective_term(const PerformanceTermType&, MathematicalModel*, DataSet*) /// This method creates a new objective term inside the performance functional. /// @param new_performance_term_type Type of objective term. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. /// @param new_data_set_pointer Pointer to a data set object. void PerformanceFunctional::construct_objective_term(const PerformanceTermType& new_performance_term_type, MathematicalModel* new_mathematical_model_pointer, DataSet* new_data_set_pointer) { construct_objective_term(new_performance_term_type); objective_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); objective_term_pointer->set_data_set_pointer(new_data_set_pointer); } // void construct_regularization_term(const PerformanceTermType&, MathematicalModel*, DataSet*) /// This method creates a new regularization term inside the performance functional. /// @param new_performance_term_type Type of regularization term. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. /// @param new_data_set_pointer Pointer to a data set object. void PerformanceFunctional::construct_regularization_term(const PerformanceTermType& new_performance_term_type, MathematicalModel* new_mathematical_model_pointer, DataSet* new_data_set_pointer) { construct_regularization_term(new_performance_term_type); regularization_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); regularization_term_pointer->set_data_set_pointer(new_data_set_pointer); } // void construct_constraints_term(const PerformanceTermType&, MathematicalModel*, DataSet*) /// This method creates a new constraints term inside the performance functional. /// @param new_performance_term_type Type of constraints term. /// @param new_mathematical_model_pointer Pointer to a mathematical model object. /// @param new_data_set_pointer Pointer to a data set object. void PerformanceFunctional::construct_constraints_term(const PerformanceTermType& new_performance_term_type, MathematicalModel* new_mathematical_model_pointer, DataSet* new_data_set_pointer) { construct_constraints_term(new_performance_term_type); constraints_term_pointer->set_mathematical_model_pointer(new_mathematical_model_pointer); constraints_term_pointer->set_data_set_pointer(new_data_set_pointer); } // void construct_objective_term_type(const std::string&) method /// This method creates a new objective term inside the performance functional of a given performance term type. /// @param new_objective_term_type String with the type of objective term to be created. void PerformanceFunctional::construct_objective_term(const std::string& new_objective_term_type) { if(new_objective_term_type == "NONE") { construct_objective_term(NONE); } else if(new_objective_term_type == "SUM_SQUARED_ERROR") { construct_objective_term(SUM_SQUARED_ERROR); } else if(new_objective_term_type == "MEAN_SQUARED_ERROR") { construct_objective_term(MEAN_SQUARED_ERROR); } else if(new_objective_term_type == "ROOT_MEAN_SQUARED_ERROR") { construct_objective_term(ROOT_MEAN_SQUARED_ERROR); } else if(new_objective_term_type == "NORMALIZED_SQUARED_ERROR") { construct_objective_term(NORMALIZED_SQUARED_ERROR); } else if(new_objective_term_type == "MINKOWSKI_ERROR") { construct_objective_term(MINKOWSKI_ERROR); } else if(new_objective_term_type == "MINKOWSKI_ERROR") { construct_objective_term(MINKOWSKI_ERROR); } else if(new_objective_term_type == "NEURAL_PARAMETERS_NORM") { construct_objective_term(NEURAL_PARAMETERS_NORM); } else if(new_objective_term_type == "OUTPUTS_INTEGRALS") { construct_objective_term(OUTPUTS_INTEGRALS); } if(new_objective_term_type == "SOLUTION_ERROR") { construct_objective_term(SOLUTION_ERROR); } if(new_objective_term_type == "FINAL_SOLUTIONS_ERROR") { construct_objective_term(FINAL_SOLUTIONS_ERROR); } else if(new_objective_term_type == "INDEPENDENT_PARAMETERS_ERROR") { construct_objective_term(INDEPENDENT_PARAMETERS_ERROR); } else if(new_objective_term_type == "INVERSE_SUM_SQUARED_ERROR") { construct_objective_term(INVERSE_SUM_SQUARED_ERROR); } else if(new_objective_term_type == "USER_PERFORMANCE_TERM") { construct_objective_term(USER_PERFORMANCE_TERM); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void construct_objective_term(const std::string&) method.\n" << "Unknown objective term type: " << new_objective_term_type << ".\n"; throw std::logic_error(buffer.str()); } } // void construct_regularization_term(const std::string&) method /// This method creates a new regularization term inside the performance functional of a given performance term type. /// @param new_regularization_term_type String with the type of regularization term to be created. void PerformanceFunctional::construct_regularization_term(const std::string& new_regularization_term_type) { if(new_regularization_term_type == "NONE") { construct_regularization_term(NONE); } else if(new_regularization_term_type == "SUM_SQUARED_ERROR") { construct_regularization_term(SUM_SQUARED_ERROR); } else if(new_regularization_term_type == "MEAN_SQUARED_ERROR") { construct_regularization_term(MEAN_SQUARED_ERROR); } else if(new_regularization_term_type == "ROOT_MEAN_SQUARED_ERROR") { construct_regularization_term(ROOT_MEAN_SQUARED_ERROR); } else if(new_regularization_term_type == "NORMALIZED_SQUARED_ERROR") { construct_regularization_term(NORMALIZED_SQUARED_ERROR); } else if(new_regularization_term_type == "MINKOWSKI_ERROR") { construct_regularization_term(MINKOWSKI_ERROR); } else if(new_regularization_term_type == "MINKOWSKI_ERROR") { construct_regularization_term(MINKOWSKI_ERROR); } else if(new_regularization_term_type == "NEURAL_PARAMETERS_NORM") { construct_regularization_term(NEURAL_PARAMETERS_NORM); } else if(new_regularization_term_type == "OUTPUTS_INTEGRALS") { construct_regularization_term(OUTPUTS_INTEGRALS); } if(new_regularization_term_type == "SOLUTION_ERROR") { construct_regularization_term(SOLUTION_ERROR); } if(new_regularization_term_type == "FINAL_SOLUTIONS_ERROR") { construct_regularization_term(FINAL_SOLUTIONS_ERROR); } else if(new_regularization_term_type == "INDEPENDENT_PARAMETERS_ERROR") { construct_regularization_term(INDEPENDENT_PARAMETERS_ERROR); } else if(new_regularization_term_type == "INVERSE_SUM_SQUARED_ERROR") { construct_regularization_term(INVERSE_SUM_SQUARED_ERROR); } else if(new_regularization_term_type == "USER_PERFORMANCE_TERM") { construct_regularization_term(USER_PERFORMANCE_TERM); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void construct_regularization_term(const std::string&) method.\n" << "Unknown regularization term type: " << new_regularization_term_type << ".\n"; throw std::logic_error(buffer.str()); } } // void set_constraints_term_type(const std::string&) method /// This method creates a new constraints term inside the performance functional of a given performance term type. /// @param new_constraints_term_type String with the type of constraints term to be created. void PerformanceFunctional::construct_constraints_term(const std::string& new_constraints_term_type) { if(new_constraints_term_type == "NONE") { construct_constraints_term(NONE); } else if(new_constraints_term_type == "SUM_SQUARED_ERROR") { construct_constraints_term(SUM_SQUARED_ERROR); } else if(new_constraints_term_type == "MEAN_SQUARED_ERROR") { construct_constraints_term(MEAN_SQUARED_ERROR); } else if(new_constraints_term_type == "ROOT_MEAN_SQUARED_ERROR") { construct_constraints_term(ROOT_MEAN_SQUARED_ERROR); } else if(new_constraints_term_type == "NORMALIZED_SQUARED_ERROR") { construct_constraints_term(NORMALIZED_SQUARED_ERROR); } else if(new_constraints_term_type == "MINKOWSKI_ERROR") { construct_constraints_term(MINKOWSKI_ERROR); } else if(new_constraints_term_type == "MINKOWSKI_ERROR") { construct_constraints_term(MINKOWSKI_ERROR); } else if(new_constraints_term_type == "NEURAL_PARAMETERS_NORM") { construct_constraints_term(NEURAL_PARAMETERS_NORM); } else if(new_constraints_term_type == "OUTPUTS_INTEGRALS") { construct_constraints_term(OUTPUTS_INTEGRALS); } if(new_constraints_term_type == "SOLUTION_ERROR") { construct_constraints_term(SOLUTION_ERROR); } if(new_constraints_term_type == "FINAL_SOLUTIONS_ERROR") { construct_constraints_term(FINAL_SOLUTIONS_ERROR); } else if(new_constraints_term_type == "INDEPENDENT_PARAMETERS_ERROR") { construct_constraints_term(INDEPENDENT_PARAMETERS_ERROR); } else if(new_constraints_term_type == "INVERSE_SUM_SQUARED_ERROR") { construct_constraints_term(INVERSE_SUM_SQUARED_ERROR); } else if(new_constraints_term_type == "USER_PERFORMANCE_TERM") { construct_constraints_term(USER_PERFORMANCE_TERM); } else { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void construct_constraints_term(const std::string&) method.\n" << "Unknown constraints term type: " << new_constraints_term_type << ".\n"; throw std::logic_error(buffer.str()); } } // void destruct_objective_term(void) method /// This method deletes the objective term object. /// It also sets the objective term type to NONE and the corresponding flag to false. void PerformanceFunctional::destruct_objective_term(void) { delete objective_term_pointer; objective_term_type = NONE; objective_term_pointer = NULL; objective_term_flag = false; } // void destruct_regularization_term(void) method /// This method deletes the regularization term object. /// It also sets the regularization term type to NONE and the corresponding flag to false. void PerformanceFunctional::destruct_regularization_term(void) { delete regularization_term_pointer; regularization_term_type = NONE; regularization_term_pointer = NULL; regularization_term_flag = false; } // void destruct_constraints_term(void) method /// This method deletes the constraints term object. /// It also sets the constraints term type to NONE and the corresponding flag to false. void PerformanceFunctional::destruct_constraints_term(void) { delete constraints_term_pointer; constraints_term_type = NONE; constraints_term_pointer = NULL; constraints_term_flag = false; } // void destruct_all_terms(void) method /// This method destructs the objective, regularization and constraints terms. void PerformanceFunctional::destruct_all_terms(void) { destruct_objective_term(); destruct_regularization_term(); destruct_constraints_term(); } // double calculate_evaluation(void) const method /// This method calculates the performance value of the performance functional, /// as the sum of the objective and the regularization terms. double PerformanceFunctional::calculate_evaluation(void) const { // Control sentence (if debug) #ifdef _DEBUG std::ostringstream buffer; if(!neural_network_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_evaluation(void) const method.\n" << "Pointer to neural network is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif double performance = 0.0; if(objective_term_flag) { #ifdef _DEBUG if(!objective_term_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_evaluation(void) const method.\n" << "Pointer to performance term is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif performance += objective_term_pointer->calculate_evaluation(); } if(regularization_term_flag) { #ifdef _DEBUG if(!regularization_term_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_evaluation(void) const method.\n" << "Pointer to regularization functional is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif performance += regularization_term_pointer->calculate_evaluation(); } if(constraints_term_flag) { #ifdef _DEBUG if(!constraints_term_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_evaluation(void) const method.\n" << "Pointer to constraints functional is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif performance += constraints_term_pointer->calculate_evaluation(); } return(performance); } // double calculate_evaluation(const Vector<double>&) const method /// This method returns the performance of a neural network for a given vector of parameters. /// It does not set that vector of parameters to the neural network. /// @param parameters Vector of parameters for the neural network associated to the performance functional. double PerformanceFunctional::calculate_evaluation(const Vector<double>& parameters) { // Control sentence (if debug) #ifdef _DEBUG const unsigned int size = parameters.size(); const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); if(size != parameters_number) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_evaluation(const Vector<double>&) method.\n" << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ").\n"; throw std::logic_error(buffer.str().c_str()); } #endif const Vector<double> original_parameters = neural_network_pointer->arrange_parameters(); neural_network_pointer->set_parameters(parameters); const double performance = calculate_evaluation(); neural_network_pointer->set_parameters(original_parameters); return(performance); } // double calculate_generalization_evaluation(void) const method /// This method calculates the performance value of the performance functional, /// as the sum of the objective and the regularization terms. double PerformanceFunctional::calculate_generalization_evaluation(void) const { // Control sentence (if debug) #ifdef _DEBUG if(!neural_network_pointer) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_generalization_evaluation(void) const method.\n" << "Pointer to neural network is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif double generalization_peformance = 0.0; if(objective_term_flag) { generalization_peformance += objective_term_pointer->calculate_generalization_evaluation(); } if(regularization_term_flag) { generalization_peformance += regularization_term_pointer->calculate_generalization_evaluation(); } if(constraints_term_flag) { generalization_peformance += constraints_term_pointer->calculate_generalization_evaluation(); } return(generalization_peformance); } // Vector<double> calculate_gradient(void) const method /// This method returns the objective function gradient, as the sum of the objective and the regularization gradient vectors. Vector<double> PerformanceFunctional::calculate_gradient(void) const { // Control sentence (if debug) #ifdef _DEBUG std::ostringstream buffer; if(!neural_network_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_gradient(void) const method.\n" << "Pointer to neural network is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif const unsigned int& parameters_number = neural_network_pointer->count_parameters_number(); Vector<double> gradient(parameters_number, 0.0); if(objective_term_flag) { #ifdef _DEBUG if(!objective_term_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_gradient(void) const method.\n" << "Pointer to objective term is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif gradient += objective_term_pointer->calculate_gradient(); } if(regularization_term_flag) { #ifdef _DEBUG if(!regularization_term_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_gradient(void) const method.\n" << "Pointer to regularization term is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif gradient += regularization_term_pointer->calculate_gradient(); } if(constraints_term_flag) { #ifdef _DEBUG if(!constraints_term_pointer) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_gradient(void) const method.\n" << "Pointer to constraints term is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif gradient += constraints_term_pointer->calculate_gradient(); } return(gradient); } // Vector<double> calculate_gradient(const Vector<double>&) method /// This method returns the performance gradient for a given vector of parameters. /// It does not set that vector of parameters to the neural network. /// @param parameters Vector of parameters for the neural network associated to the performance functional. Vector<double> PerformanceFunctional::calculate_gradient(const Vector<double>& parameters) { #ifdef _DEBUG if(!neural_network_pointer) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_gradient(const Vector<double>&) method.\n" << "Pointer to neural network is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } #endif #ifdef _DEBUG const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); const unsigned int size = parameters.size(); if(size != parameters_number) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_gradient(const Vector<double>&) method.\n" << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ").\n"; throw std::logic_error(buffer.str().c_str()); } #endif // Calculate potential gradient const Vector<double> original_parameters = neural_network_pointer->arrange_parameters(); // Set potential parameters neural_network_pointer->set_parameters(parameters); // Calcualate gradient const Vector<double> gradient = calculate_gradient(); // Restart original parameters neural_network_pointer->set_parameters(original_parameters); return(gradient); } // Matrix<double> calculate_Hessian(void) const method /// This method returns the default objective function Hessian matrix, which is computed using numerical /// differentiation. Matrix<double> PerformanceFunctional::calculate_Hessian(void) const { const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); Matrix<double> Hessian(parameters_number, parameters_number, 0.0); if(objective_term_flag) { Hessian += objective_term_pointer->calculate_Hessian(); } if(regularization_term_flag) { Hessian += regularization_term_pointer->calculate_Hessian(); } if(constraints_term_flag) { Hessian += constraints_term_pointer->calculate_Hessian(); } return(Hessian); } // Vector<double> calculate_Hessian(const Vector<double>&) method /// This method returns which would be the objective function Hessian of a multilayer perceptron for an /// hypothetical vector of parameters. /// It does not set that vector of parameters to the multilayer perceptron. /// @param parameters Vector of a potential parameters for the multilayer perceptron associated /// to the performance functional. Matrix<double> PerformanceFunctional::calculate_Hessian(const Vector<double>& parameters) { // Control sentence (if debug) #ifdef _DEBUG const unsigned int size = parameters.size(); const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); if(size != parameters_number) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_Hessian(const Vector<double>&) method.\n" << "Size must be equal to number of parameters.\n"; throw std::logic_error(buffer.str().c_str()); } #endif // Calculate potential Hessian const Vector<double> original_parameters = neural_network_pointer->arrange_parameters(); // Set potential parameters neural_network_pointer->set_parameters(parameters); // Get objective function Hessian const Matrix<double> Hessian = calculate_Hessian(); // Restart original parameters neural_network_pointer->set_parameters(original_parameters); return(Hessian); } // Matrix<double> calculate_inverse_Hessian(void) const method /// This method returns inverse matrix of the Hessian. /// It first computes the Hessian matrix and then computes its inverse. /// @todo Matrix<double> PerformanceFunctional::calculate_inverse_Hessian(void) const { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Matrix<double> calculate_inverse_Hessian(void) const method.\n" << "This method is not yet implemented.\n"; throw std::logic_error(buffer.str().c_str()); // const Matrix<double> Hessian = calculate_Hessian(); // return(Hessian.calculate_inverse()); } // Vector<double> calculate_vector_dot_Hessian(Vector<double>) const method /// This method returns the default product of some vector with the objective function Hessian matrix, which is /// computed using numerical differentiation. /// @param vector Vector in the dot product. Vector<double> PerformanceFunctional::calculate_vector_dot_Hessian(const Vector<double>& vector) const { // Control sentence const unsigned int size = vector.size(); const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); if(size != parameters_number) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "Vector<double> calculate_vector_dot_Hessian(Vector<double>) method.\n" << "Size of vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str().c_str()); } // Calculate vector Hessian product Vector<double> vector_Hessian_product(parameters_number); return(vector_Hessian_product); } // ZeroOrderEvaluation calculate_zero_order_evaluation(void) const method /// This method returns a zero order evaluation structure, which just contains the evaluation value of the performance function. PerformanceFunctional::ZeroOrderEvaluation PerformanceFunctional::calculate_zero_order_evaluation(void) const { ZeroOrderEvaluation zero_order_evaluation; zero_order_evaluation.performance = calculate_evaluation(); return(zero_order_evaluation); } // FirstOrderEvaluation calculate_first_order_evaluation(void) const method /// This method returns a first order evaluation structure, which contains the value and the gradient of the performance function. PerformanceFunctional::FirstOrderEvaluation PerformanceFunctional::calculate_first_order_evaluation(void) const { FirstOrderEvaluation first_order_evaluation; first_order_evaluation.performance = calculate_evaluation(); first_order_evaluation.gradient = calculate_gradient(); return(first_order_evaluation); } // SecondOrderEvaluation calculate_second_order_evaluation(void) const method /// This method returns a second order evaluation structure, which contains the value, the gradient and the Hessian of the performance function. PerformanceFunctional::SecondOrderEvaluation PerformanceFunctional::calculate_second_order_evaluation(void) const { SecondOrderEvaluation second_order_evaluation; second_order_evaluation.performance = calculate_evaluation(); second_order_evaluation.gradient = calculate_gradient(); second_order_evaluation.Hessian = calculate_Hessian(); return(second_order_evaluation); } // double calculate_zero_order_Taylor_approximation(const Vector<double>&) const method /// This method returns the Taylor approximation of the performance function at some point near the parameters. /// The order of the approximation here is zero, i.e., only the performance value is used. double PerformanceFunctional::calculate_zero_order_Taylor_approximation(const Vector<double>&) const { return(calculate_evaluation()); } // double calculate_first_order_Taylor_approximation(const Vector<double>&) const method /// This method returns the Taylor approximation of the performance function at some point near the parameters. /// The order of the approximation here is one, i.e., both the performance value and the performance gradient are used. /// @param parameters Approximation point. double PerformanceFunctional::calculate_first_order_Taylor_approximation(const Vector<double>& parameters) const { // Control sentence (if debug) #ifdef _DEBUG const unsigned int parameters_size = parameters.size(); const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); if(parameters_size != parameters_number) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_first_order_Taylor_approximation(const Vector<double>&) const method.\n" << "Size of potential parameters must be equal to number of parameters.\n"; throw std::logic_error(buffer.str().c_str()); } #endif const Vector<double> original_parameters = neural_network_pointer->arrange_parameters(); const double performance = calculate_evaluation(); const Vector<double> gradient = calculate_gradient(); const double first_order_Taylor_approximation = performance + gradient.dot(parameters-parameters); return(first_order_Taylor_approximation); } // double calculate_second_order_Taylor_approximation(const Vector<double>&) const method /// This method returns the Taylor approximation of the performance function at some point near the parameters. /// The order of the approximation here is two, i.e., the performance value, the performance gradient and the performance Hessian are used. /// @param parameters Approximation point. double PerformanceFunctional::calculate_second_order_Taylor_approximation(const Vector<double>& parameters) const { // Control sentence (if debug) #ifdef _DEBUG const unsigned int parameters_size = parameters.size(); const unsigned int parameters_number = neural_network_pointer->count_parameters_number(); if(parameters_size != parameters_number) { std::ostringstream buffer; buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "double calculate_second_order_Taylor_approximation(const Vector<double>&) const method.\n" << "Size of potential parameters must be equal to number of parameters.\n"; throw std::logic_error(buffer.str().c_str()); } #endif // Neural network stuff const Vector<double> original_parameters = neural_network_pointer->arrange_parameters(); const Vector<double> parameters_difference = parameters - parameters; // Performance functioal stuff const double performance = calculate_evaluation(); const Vector<double> gradient = calculate_gradient(); const Matrix<double> Hessian = calculate_Hessian(); const double second_order_Taylor_approximation = performance + gradient.dot(parameters_difference) + parameters_difference.dot(Hessian).dot(parameters_difference)/2.0; return(second_order_Taylor_approximation); } // double calculate_directional_performance(const Vector<double>&, double) const method /// This method returns the value of the performance function at some step along some direction. /// @param direction Direction vector. /// @param rate Step value. double PerformanceFunctional::calculate_directional_performance(const Vector<double>& direction, double rate) { return(calculate_evaluation(neural_network_pointer->arrange_parameters() + direction*rate)); } // double calculate_directional_performance_derivative(const Vector<double>&, double) const method /// This method returns the derivative of the performance function at some step along some direction. /// @param direction Direction vector. /// @param rate Step value. double PerformanceFunctional::calculate_directional_performance_derivative(const Vector<double>& direction, double rate) { const Vector<double> gradient = calculate_gradient(neural_network_pointer->arrange_parameters() + direction*rate); const Vector<double> normalized_direction = direction/direction.calculate_norm(); return(gradient.dot(normalized_direction)); } // double calculate_directional_performance_second_derivative(const Vector<double>&, double) const method /// This method returns the second derivative of the performance function at some step along some direction. /// @param direction Direction vector. /// @param rate Step value. double PerformanceFunctional::calculate_directional_performance_second_derivative(const Vector<double>& direction, double rate) { const Matrix<double> Hessian = calculate_Hessian(neural_network_pointer->arrange_parameters() + direction*rate); const Vector<double> normalized_direction = direction/direction.calculate_norm(); return(normalized_direction.dot(Hessian).dot(normalized_direction)); } // TiXmlElement* to_XML(void) const method /// This method serializes a default performance functional object into a XML element of the TinyXML library. /// See the OpenNN manual for more information about the format of this element. TiXmlElement* PerformanceFunctional::to_XML(void) const { std::ostringstream buffer; // Performance functional TiXmlElement* performance_functional_element = new TiXmlElement("PerformanceFunctional"); performance_functional_element->SetAttribute("Version", 4); // Objective term type TiXmlElement* objective_term_type_element = new TiXmlElement("ObjectiveTermType"); performance_functional_element->LinkEndChild(objective_term_type_element); buffer.str(""); buffer << write_objective_term_type(); TiXmlText* objective_term_type_text = new TiXmlText(buffer.str().c_str()); objective_term_type_element->LinkEndChild(objective_term_type_text); // Regularization term type TiXmlElement* regularization_term_type_element = new TiXmlElement("RegularizationTermType"); performance_functional_element->LinkEndChild(regularization_term_type_element); buffer.str(""); buffer << write_regularization_term_type(); TiXmlText* regularization_term_type_text = new TiXmlText(buffer.str().c_str()); regularization_term_type_element->LinkEndChild(regularization_term_type_text); // Constraints term type TiXmlElement* constraints_term_type_element = new TiXmlElement("ConstraintsTermType"); performance_functional_element->LinkEndChild(constraints_term_type_element); buffer.str(""); buffer << write_constraints_term_type(); TiXmlText* constraints_term_type_text = new TiXmlText(buffer.str().c_str()); constraints_term_type_element->LinkEndChild(constraints_term_type_text); // Objective flag TiXmlElement* objective_term_flag_element = new TiXmlElement("ObjectiveFlag"); performance_functional_element->LinkEndChild(objective_term_flag_element); buffer.str(""); buffer << objective_term_flag; TiXmlText* objective_term_flag_text = new TiXmlText(buffer.str().c_str()); objective_term_flag_element->LinkEndChild(objective_term_flag_text); // Regularization flag TiXmlElement* regularization_term_flag_element = new TiXmlElement("RegularizationFlag"); performance_functional_element->LinkEndChild(regularization_term_flag_element); buffer.str(""); buffer << regularization_term_flag; TiXmlText* regularization_term_flag_text = new TiXmlText(buffer.str().c_str()); regularization_term_flag_element->LinkEndChild(regularization_term_flag_text); // Constraints flag TiXmlElement* constraints_term_flag_element = new TiXmlElement("ConstraintsFlag"); performance_functional_element->LinkEndChild(constraints_term_flag_element); buffer.str(""); buffer << constraints_term_flag; TiXmlText* constraints_term_flag_text = new TiXmlText(buffer.str().c_str()); constraints_term_flag_element->LinkEndChild(constraints_term_flag_text); // Objective term if(objective_term_pointer) { TiXmlElement* objective_term_element = objective_term_pointer->to_XML(); performance_functional_element->LinkEndChild(objective_term_element); } // Regularization term if(regularization_term_pointer) { TiXmlElement* regularization_term_element = regularization_term_pointer->to_XML(); performance_functional_element->LinkEndChild(regularization_term_element); } // Constraints term if(constraints_term_pointer) { TiXmlElement* constraints_term_element = constraints_term_pointer->to_XML(); performance_functional_element->LinkEndChild(constraints_term_element); } // Display TiXmlElement* display_element = new TiXmlElement("Display"); performance_functional_element->LinkEndChild(display_element); buffer.str(""); buffer << display; TiXmlText* display_text = new TiXmlText(buffer.str().c_str()); display_element->LinkEndChild(display_text); return(performance_functional_element); } // void from_XML(TiXmlElement*) method /// This method sets the performance functional member data from an XML element. /// @param performance_functional_element Pointer to a TinyXML element with the performance functional data. void PerformanceFunctional::from_XML(TiXmlElement* performance_functional_element) { if(!performance_functional_element) { return; } // Objective term type TiXmlElement* objective_term_type_element = performance_functional_element->FirstChildElement("ObjectiveTermType"); if(objective_term_type_element) { const std::string new_objective_term_type = objective_term_type_element->GetText(); try { set_objective_term_type(new_objective_term_type); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Regularization term type TiXmlElement* regularization_term_type_element = performance_functional_element->FirstChildElement("RegularizationTermType"); if(regularization_term_type_element) { std::string new_regularization_term_type = regularization_term_type_element->GetText(); try { set_regularization_term_type(new_regularization_term_type); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Constraints term type TiXmlElement* constraints_term_type_element = performance_functional_element->FirstChildElement("ConstraintsTermType"); if(constraints_term_type_element) { std::string new_constraints_term_type = constraints_term_type_element->GetText(); try { set_constraints_term_type(new_constraints_term_type); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Objective flag TiXmlElement* objective_term_flag_element = performance_functional_element->FirstChildElement("ObjectiveFlag"); if(objective_term_flag_element) { std::string new_objective_term_flag_string = objective_term_flag_element->GetText(); try { set_objective_term_flag(new_objective_term_flag_string != "0"); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Regularization flag TiXmlElement* regularization_term_flag_element = performance_functional_element->FirstChildElement("RegularizationFlag"); if(regularization_term_flag_element) { std::string new_regularization_term_flag_string = regularization_term_flag_element->GetText(); try { set_regularization_term_flag(new_regularization_term_flag_string != "0"); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Constraints flag TiXmlElement* constraints_term_flag_element = performance_functional_element->FirstChildElement("ConstraintsFlag"); if(constraints_term_flag_element) { std::string new_constraints_term_flag_string = constraints_term_flag_element->GetText(); try { set_constraints_term_flag(new_constraints_term_flag_string != "0"); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Objective term // Regularization term // Constraints term // Display warnings TiXmlElement* display_element = performance_functional_element->FirstChildElement("Display"); if(display_element) { std::string new_display_string = display_element->GetText(); try { set_display(new_display_string != "0"); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } } // void print(void) method /// This method prints the members of the performance functional object to the screen in XML-type format. void PerformanceFunctional::print(void) const { } // void save(const std::string&) const method /// This method saves to a XML-type file a string representation of the performance functional object. /// @param filename Name of XML-type performance functional file. void PerformanceFunctional::save(const std::string& filename) const { TiXmlDocument document; // Declaration TiXmlDeclaration* declaration = new TiXmlDeclaration("1.0", "", ""); document.LinkEndChild(declaration); // Performance functional TiXmlElement* performance_functional_element = to_XML(); document.LinkEndChild(performance_functional_element); document.SaveFile(filename.c_str()); } // void load(const std::string&) method /// This method loads a default performance functional XML-type file. /// @param filename Name of default XML-type performance functional file. void PerformanceFunctional::load(const std::string& filename) { std::ostringstream buffer; TiXmlDocument document(filename.c_str()); if(!document.LoadFile()) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void load(const std::string&) method.\n" << "Cannot load XML file " << filename << ".\n"; throw std::logic_error(buffer.str()); } // Performance functional element TiXmlElement* performance_functional_element = document.FirstChildElement(); if(!performance_functional_element) { buffer << "OpenNN Exception: PerformanceFunctional class.\n" << "void load(const std::string&) method.\n" << "File " << filename << " is not a valid performance functional file.\n"; throw std::logic_error(buffer.str()); } from_XML(performance_functional_element); } // std::string write_information(void) method /// This method returns any useful information about the objective function during training. /// By default it is an empty string. std::string PerformanceFunctional::write_information(void) { std::ostringstream buffer; if(objective_term_pointer) { buffer << objective_term_pointer->write_information(); } if(regularization_term_pointer) { buffer << regularization_term_pointer->write_information(); } if(constraints_term_pointer) { buffer << constraints_term_pointer->write_information(); } return(buffer.str()); } //// TiXmlElement* calculate_performance_XML(void) const method // //TiXmlElement* PerformanceFunctional::calculate_performance_XML(void) const //{ // std::ostringstream buffer; // // TiXmlElement* performance_element = new TiXmlElement("Performance"); // // return(performance_element); //} // // //// TiXmlElement* calculate_generalization_evaluation_XML(void) const method // //TiXmlElement* PerformanceFunctional::calculate_generalization_evaluation_XML(void) const //{ // std::ostringstream buffer; // // TiXmlElement* generalization_evaluation_element = new TiXmlElement("GeneralizationPerformance"); // // return(generalization_evaluation_element); //} // // //// TiXmlElement* calculate_gradient_XML(void) method // //TiXmlElement* PerformanceFunctional::calculate_gradient_XML(void) const //{ // TiXmlElement* gradient_element = new TiXmlElement("Gradient"); // // return(gradient_element); //} } // OpenNN: Open Neural Networks Library. // Copyright (C) 2005-2012 Roberto Lopez // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or 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 // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31.081266
193
0.730127
[ "object", "vector", "model" ]
cd683a5ea8376ccb7cf66c1ff4d8706ce865a254
1,636
cpp
C++
Greedy/Cutting Boards.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Greedy/Cutting Boards.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Greedy/Cutting Boards.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
/* **************************************************************** **************************************************************** -> Coded by Stavros Chryselis -> Visit my github for more solved problems over multiple sites -> https://github.com/StavrosChryselis -> Feel free to email me at stavrikios@gmail.com **************************************************************** **************************************************************** */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define MOD 1000000007 using namespace std; int N, M; long long h, v; vector< pair<int, int> > V; //0 = h, 1 = v inline void init() { int i, num; V.clear(); h = v = 1; scanf("%d %d", &N, &M); for(i = 0; i< N - 1; i++) { scanf("%d", &num); V.push_back(make_pair(num, 0)); } for(i = 0; i< M - 1; i++) { scanf("%d", &num); V.push_back(make_pair(num, 1)); } sort(V.begin(), V.end()); } inline long long solve() { long long sum = 0, prod; int i; for(i = V.size() - 1; i >= 0; i--) { if(V[i].second) { prod = h * V[i].first; v++; sum += prod; sum %= MOD; } else { prod = v * V[i].first; h++; sum += prod; sum %= MOD; } } return sum; } int main() { int T; scanf("%d", &T); while(T--) { init(); printf("%lld\n", solve()); } return 0; }
18.590909
64
0.363081
[ "vector" ]
cd706caafcff851244ec6ce7205aa624c928911b
609
cpp
C++
MayLeetCodingChallenge/May 31st 2020/Edit Distance.cpp
SAITARUN55/100DaysofCodeinC-
d52e683f52abc9bc633af7e15bb970882efc3788
[ "MIT" ]
4
2020-05-18T05:12:36.000Z
2020-08-28T07:16:41.000Z
MayLeetCodingChallenge/May 31st 2020/Edit Distance.cpp
SAITARUN55/100DaysofCodeinC-
d52e683f52abc9bc633af7e15bb970882efc3788
[ "MIT" ]
null
null
null
MayLeetCodingChallenge/May 31st 2020/Edit Distance.cpp
SAITARUN55/100DaysofCodeinC-
d52e683f52abc9bc633af7e15bb970882efc3788
[ "MIT" ]
5
2020-05-01T04:56:26.000Z
2022-02-02T15:37:53.000Z
class Solution { public: int minDistance(string word1, string word2) { int M = word1.size(); int N = word2.size(); vector<vector<int>> dp(M + 1, vector<int>(N + 1, 0)); if (M * N == 0) return M + N; for (int i = 0; i <= M; i++) { dp[i][0] = i; } for (int i = 0; i <= N; i++) { dp[0][i] = i; } for (int i = 1; i <= M; i++) { for (int j = 1; j <= N; j++) { if (word1.at(i - 1) == word2.at(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = min(dp[i - 1][j], min(dp[i][j - 1], dp[i - 1][j - 1])) + 1; } } } return dp[M][N]; } };
21
75
0.410509
[ "vector" ]
cd72778363710725569b2b75ac7027b7936ccfb8
8,468
cpp
C++
unittests/process.cpp
cimplart/cercall
3ab6f6a55e577154a907a53ad02c5a012c42c9c5
[ "Apache-2.0" ]
null
null
null
unittests/process.cpp
cimplart/cercall
3ab6f6a55e577154a907a53ad02c5a012c42c9c5
[ "Apache-2.0" ]
null
null
null
unittests/process.cpp
cimplart/cercall
3ab6f6a55e577154a907a53ad02c5a012c42c9c5
[ "Apache-2.0" ]
null
null
null
/*! * \file * \brief Cercall tests - Process class interface * * Copyright (c) 2018, Arthur Wisz * 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 "process.h" #include <stdexcept> #include <string> #include <vector> #include <regex> #include <iostream> #ifdef __linux__ #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <errno.h> using cercall::test::Process; Process::Process() : myPid (-1) { } Process::~Process() { } static std::vector<std::string> split_args(const std::string& args) { static const std::regex re{"\\s+"}; std::vector<std::string> container { std::sregex_token_iterator(args.begin(), args.end(), re, -1), std::sregex_token_iterator() }; return container; } void Process::create(char const* programPath, char const* arguments) { if ((0 == programPath) || (strlen(programPath) < 1)) throw std::runtime_error("Process::create: path to executable file is empty."); pid_t result = fork(); if (result < 0) throw std::runtime_error("fork: " + std::string(strerror(errno))); else if (0 == result) { std::vector<std::string> args { std::string(programPath) }; if (arguments != nullptr) { std::vector<std::string> moreArgs = split_args(arguments); args.insert(args.end(), moreArgs.begin(), moreArgs.end()); } char* argv[args.size() + 1]; for(size_t i = 0; i < args.size(); ++i) argv[i] = const_cast<char*>(args[i].c_str()); argv[args.size()] = 0; execv(programPath, argv); // If execution is still here it means execl method failed. exit(-1); } else myPid = result; } bool Process::is_running() const { return ::kill(myPid, 0) == 0; } Process::ExitStatusType Process::wait() { int status; if (waitpid(myPid, &status, 0) < 0) throw std::runtime_error("waitpid: " + std::string(strerror(errno))); if (WIFEXITED(status)) return std::make_pair(true, WEXITSTATUS(status)); else if (WIFSIGNALED(status)) return std::make_pair(false, WTERMSIG(status)); throw std::logic_error("Process::wait: unexpected exit status"); } void Process::kill() { int res = ::kill( myPid, SIGKILL); if (res < 0) throw std::runtime_error("Process::kill: " + std::string(strerror(errno))); } void Process::kill(ProcessId pid) { int res = ::kill(pid, SIGKILL); if (res < 0) throw std::runtime_error("Process::kill(pid): " + std::string(strerror(errno))); } void Process::shutdown() { int res = ::kill(myPid, SIGTERM); if (res < 0) throw std::runtime_error("Process::shutdown(pid): " + std::string(strerror(errno))); } Process::ProcessId Process::get_pid() { return getpid(); } #elif defined(_WIN32) Process::Process() : myProcHandle(INVALID_HANDLE_VALUE) { } Process::~Process() { if (myProcHandle != INVALID_HANDLE_VALUE) CloseHandle(myProcHandle); } #ifdef UNICODE void Process::create(wchar_t const* programPath, wchar_t const* arguments) { if ((0 == programPath) || (wcslen(reinterpret_cast<const wchar_t*>(programPath)) < 1)) throw std::runtime_error("Process::create: path to executable file is empty."); wchar_t *path = const_cast<wchar_t*>(reinterpret_cast<const wchar_t*>(programPath)); wchar_t *args = const_cast<wchar_t*>(reinterpret_cast<const wchar_t*>(arguments)); uint32_t pathLen = wcslen(path); uint32_t argsLen = (0 != args) ? wcslen(args) : 0; wchar_t *cmdLine = new wchar_t[pathLen + argsLen + 2]; wcscpy_s(cmdLine, pathLen + argsLen + 2, path); if (0 < argsLen) { if (cmdLine != wcscat(cmdLine, L" ")) { delete [] cmdLine; throw std::runtime_error("Process::create: can't create command line."); } if (cmdLine != wcscat(cmdLine, args)) { delete [] cmdLine; throw std::runtime_error("Process::create: can't create command line."); } } BOOL success; PROCESS_INFORMATION processInfo; SetLastError(0); #if defined(_WIN32) STARTUPINFO startupInfo; GetStartupInfo(&startupInfo); success = CreateProcess(0, cmdLine, 0, 0, false, 0, 0, 0, &startupInfo, &processInfo); #else success = CreateProcess(path, args, 0, 0, false, 0, 0, 0, 0, &processInfo); #endif // #if defined(_WIN32) delete [] cmdLine; cmdLine = 0; if (!success) throw_error("Process::create: CreateProcess failed: "); CloseHandle(processInfo.hThread); //We must keep the handle for calling WaitForSingleObject and GetExitCodeProcess. myProcHandle = processInfo.hProcess; } #else void Process::create(char const* programPath, char const* arguments) { if ((0 == programPath) || (strlen(programPath) < 1)) throw std::runtime_error("Process::create: path to executable file is empty."); if (myProcHandle != INVALID_HANDLE_VALUE) CloseHandle(myProcHandle); BOOL success; PROCESS_INFORMATION processInfo; STARTUPINFO startupInfo; std::string cmdLine(programPath); if ((0 != arguments) && (0 < strlen(arguments))) { cmdLine += " "; cmdLine += arguments; } GetStartupInfo(&startupInfo); SetLastError(0); success = CreateProcess(0, const_cast<char*>(cmdLine.c_str()), 0, 0, false, 0, 0, 0, &startupInfo, &processInfo); if (!success) throw_error("Process::create: CreateProcess failed: "); CloseHandle(processInfo.hThread); //We must keep the handle for calling WaitForSingleObject and GetExitCodeProcess. myProcHandle = processInfo.hProcess; } #endif // #ifdef UNICODE Process::ExitStatusType Process::wait() { DWORD res = WaitForSingleObject(myProcHandle, INFINITE); if (res == WAIT_FAILED) throw_error("Process::kill: WaitForSingleObject failed: "); if (res == WAIT_TIMEOUT) throw std::runtime_error("Process::kill: WaitForSingleObject bad result WAIT_TIMEOUT"); if ( !GetExitCodeProcess(myProcHandle, &res)) throw_error("Process::kill: GetExitCodeProcess failed: "); if (res == STILL_ACTIVE) throw std::logic_error("Process::kill: exit code STILL_ACTIVE"); return std::make_pair((res < 256) == true, res); } void Process::kill() { if( !TerminateProcess(myProcHandle, ProcessTerminated)) throw_error("Process::kill: TerminateProcess failed: "); } void Process::kill(ProcessId pid) { HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid); if (h == NULL) throw_error("Process::kill(pid): OpenProcess failed: "); if( !TerminateProcess(h, ProcessTerminated)) throw_error("Process::kill(pid): TerminateProcess failed: "); } Process::ProcessId Process::get_pid() { return GetCurrentProcessId(); } void Process::throw_error(std::string const& errorMessage) { std::string systemErrorMessage("unknown error"); DWORD error = GetLastError(); if (0 != error) get_error_message(error, systemErrorMessage); systemErrorMessage = errorMessage + systemErrorMessage; throw std::runtime_error(systemErrorMessage); } void Process::get_error_message(DWORD error, std::string& errorMessage) { LPTSTR messageBuffer; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &messageBuffer, 0, NULL); #ifdef UNICODE static const int32_t asciiMaxLength(255); char asciiMessageBuffer[asciiMaxLength] = {0}; errno_t asciiErrno; asciiErrno = wcstombs(asciiMessageBuffer, messageBuffer, asciiMaxLength - 1); if (!asciiErrno) errorMessage = asciiMessageBuffer; else errorMessage = "unknown error"; #else errorMessage = messageBuffer; #endif LocalFree(messageBuffer); } #endif // #ifdef __linux__
28.13289
95
0.656708
[ "vector" ]
cd782537ca517048778beab381fa382e0d95ff02
10,079
cpp
C++
thirdparty/fluid/modules/gapi/src/streaming/gstreamer/gstreamer_pipeline_facade.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
56,632
2016-07-04T16:36:08.000Z
2022-03-31T18:38:14.000Z
thirdparty/fluid/modules/gapi/src/streaming/gstreamer/gstreamer_pipeline_facade.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
13,593
2016-07-04T13:59:03.000Z
2022-03-31T21:04:51.000Z
thirdparty/fluid/modules/gapi/src/streaming/gstreamer/gstreamer_pipeline_facade.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
54,986
2016-07-04T14:24:38.000Z
2022-03-31T22:51:18.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2021 Intel Corporation #include "gstreamerenv.hpp" #include "gstreamer_pipeline_facade.hpp" #include <opencv2/gapi/streaming/meta.hpp> #include <logger.hpp> #include <opencv2/imgproc.hpp> #ifdef HAVE_GSTREAMER #include <gst/app/gstappsink.h> #include <gst/gstbuffer.h> #include <gst/video/video-frame.h> #include <gst/pbutils/missing-plugins.h> namespace cv { namespace gapi { namespace wip { namespace gst { GStreamerPipelineFacade::GStreamerPipelineFacade(): m_isPrerolled(false), m_isPlaying(false) { } GStreamerPipelineFacade::GStreamerPipelineFacade(const std::string& pipelineDesc): GStreamerPipelineFacade() { m_pipelineDesc = pipelineDesc; // Initialize GStreamer library: GStreamerEnv::init(); // Create GStreamer pipeline: GError* error = NULL; // gst_parse_launch [transfer floating] m_pipeline = GST_ELEMENT(g_object_ref_sink( gst_parse_launch(m_pipelineDesc.c_str(), &error))); GStreamerPtr<GError> err(error); if (err) { cv::util::throw_error( std::runtime_error("Error in parsing pipeline: " + std::string(err->message))); } } // The destructors are noexcept by default (since C++11). GStreamerPipelineFacade::~GStreamerPipelineFacade() { // There is no mutex acquisition here, because we assume that no one will call this method // directly. // Destructor may be called on empty GStreamerSource object in case if // exception is thrown during construction. if (m_pipeline && GST_IS_ELEMENT(m_pipeline.get())) { try { setState(GST_STATE_NULL); } catch(...) { GAPI_LOG_WARNING(NULL, "Unable to stop pipeline in destructor.\n"); } m_pipeline.release(); } } std::vector<GstElement*> GStreamerPipelineFacade::getElementsByFactoryName( const std::string& factoryName) { std::vector<GstElement*> outElements = getElements( [&factoryName](GstElement* element) { GStreamerPtr<gchar> name( gst_object_get_name(GST_OBJECT(gst_element_get_factory(element)))); return name && (0 == strcmp(name, factoryName.c_str())); }); return outElements; } GstElement* GStreamerPipelineFacade::getElementByName(const std::string& elementName) { std::vector<GstElement*> outElements = getElements( [&elementName](GstElement* element) { GStreamerPtr<gchar> name(gst_element_get_name(element)); return name && (0 == strcmp(name, elementName.c_str())); }); if (outElements.empty()) { return nullptr; } else { GAPI_Assert(1ul == outElements.size()); return outElements[0]; } } void GStreamerPipelineFacade::completePreroll() { // FIXME: If there are multiple sources in pipeline and one of them is live, then pipeline // will return GST_STATE_CHANGE_NO_PREROLL while pipeline pausing. // But appsink may not be connected to this live source and only to anothers, // not-live ones. So, it is not required to start the playback for appsink to complete // the preroll. // Starting of playback for the not-live sources before the first frame pull will lead // to loosing of some amount of frames and pulling of the first frame can return frame // which is far from the first. // // Need to handle this case or forbid to mix multiples sources of different // categories(live, not-live) in the pipeline explicitly(assert). if (!m_isPrerolled.load(std::memory_order_acquire)) { std::lock_guard<std::mutex> lock(m_stateChangeMutex); if(!m_isPrerolled.load(std::memory_order_relaxed)) { PipelineState state = queryState(); // Only move forward in the pipeline's state machine GAPI_Assert(state.current != GST_STATE_PLAYING); GAPI_Assert(state.pending == GST_STATE_VOID_PENDING); GstStateChangeReturn status = gst_element_set_state(m_pipeline, GST_STATE_PAUSED); checkBusMessages(); if (status == GST_STATE_CHANGE_NO_PREROLL) { status = gst_element_set_state(m_pipeline, GST_STATE_PLAYING); m_isPlaying.store(true); } verifyStateChange(status); m_isPrerolled.store(true, std::memory_order_release); } } } void GStreamerPipelineFacade::play() { if (!m_isPlaying.load(std::memory_order_acquire)) { std::lock_guard<std::mutex> lock(m_stateChangeMutex); if (!m_isPlaying.load(std::memory_order_relaxed)) { setState(GST_STATE_PLAYING); m_isPlaying.store(true, std::memory_order_release); m_isPrerolled.store(true); } } } bool GStreamerPipelineFacade::isPlaying() { return m_isPlaying.load(); } std::vector<GstElement*> GStreamerPipelineFacade::getElements( std::function<bool(GstElement*)> comparator) { std::vector<GstElement*> outElements; GStreamerPtr<GstIterator> it(gst_bin_iterate_elements(GST_BIN(m_pipeline.get()))); GValue value = G_VALUE_INIT; GstIteratorResult status = gst_iterator_next(it, &value); while (status != GST_ITERATOR_DONE && status != GST_ITERATOR_ERROR) { if (status == GST_ITERATOR_OK) { GstElement* element = GST_ELEMENT(g_value_get_object(&value)); if (comparator(element)) { outElements.push_back(GST_ELEMENT(element)); } g_value_unset(&value); } else if (status == GST_ITERATOR_RESYNC) { gst_iterator_resync(it); } status = gst_iterator_next(it, &value); } return outElements; } PipelineState GStreamerPipelineFacade::queryState() { GAPI_Assert(m_pipeline && GST_IS_ELEMENT(m_pipeline.get()) && "GStreamer pipeline has not been created!"); PipelineState state; GstClockTime timeout = 5 * GST_SECOND; gst_element_get_state(m_pipeline, &state.current, &state.pending, timeout); return state; } void GStreamerPipelineFacade::setState(GstState newState) { PipelineState state = queryState(); GAPI_Assert(state.pending == GST_STATE_VOID_PENDING); if (state.current != newState) { GstStateChangeReturn status = gst_element_set_state(m_pipeline, newState); verifyStateChange(status); } } void GStreamerPipelineFacade::verifyStateChange(GstStateChangeReturn status) { if (status == GST_STATE_CHANGE_ASYNC) { // Wait for status update. status = gst_element_get_state(m_pipeline, NULL, NULL, GST_CLOCK_TIME_NONE); } if (status == GST_STATE_CHANGE_FAILURE) { checkBusMessages(); PipelineState state = queryState(); const gchar* currentState = gst_element_state_get_name(state.current); const gchar* pendingState = gst_element_state_get_name(state.pending); cv::util::throw_error( std::runtime_error(std::string("Unable to change pipeline state from ") + std::string(currentState) + std::string(" to ") + std::string(pendingState))); } checkBusMessages(); } // Handles GStreamer bus messages. // For debugging purposes. void GStreamerPipelineFacade::checkBusMessages() const { GStreamerPtr<GstBus> bus(gst_element_get_bus(m_pipeline)); while (gst_bus_have_pending(bus)) { GStreamerPtr<GstMessage> msg(gst_bus_pop(bus)); if (!msg || !GST_IS_MESSAGE(msg.get())) { continue; } if (gst_is_missing_plugin_message(msg)) { GStreamerPtr<gchar> descr(gst_missing_plugin_message_get_description(msg)); cv::util::throw_error( std::runtime_error("Your GStreamer installation is missing a required plugin!" "Details: " + std::string(descr))); } else { switch (GST_MESSAGE_TYPE(msg)) { case GST_MESSAGE_STATE_CHANGED: { if (GST_MESSAGE_SRC(msg.get()) == GST_OBJECT(m_pipeline.get())) { GstState oldState = GST_STATE_NULL, newState = GST_STATE_NULL; gst_message_parse_state_changed(msg, &oldState, &newState, NULL); const gchar* oldStateName = gst_element_state_get_name(oldState); const gchar* newStateName = gst_element_state_get_name(newState); GAPI_LOG_INFO(NULL, "Pipeline state changed from " << oldStateName << " to " << newStateName); } break; } case GST_MESSAGE_ERROR: { GError* error = NULL; gchar* debug = NULL; gst_message_parse_error(msg, &error, &debug); // transfer full for out args GStreamerPtr<GError> err(error); GStreamerPtr<gchar> deb(debug); GStreamerPtr<gchar> name(gst_element_get_name(GST_MESSAGE_SRC(msg.get()))); GAPI_LOG_WARNING(NULL, "Embedded video playback halted; module " << name.get() << " reported: " << err->message); GAPI_LOG_WARNING(NULL, "GStreamer debug: " << deb); break; } default: break; } } } } } // namespace gst } // namespace wip } // namespace gapi } // namespace cv #endif // HAVE_GSTREAMER
31.996825
100
0.617224
[ "object", "vector" ]
cd790927b7db5cd5fccdc5df8325d118fe4c8a74
30,545
cpp
C++
OREData/ored/utilities/xmlutils.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
OREData/ored/utilities/xmlutils.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
OREData/ored/utilities/xmlutils.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file ored/utilities/xmlutils.cpp \brief \ingroup utilities */ #include <boost/algorithm/string/join.hpp> #include <boost/lexical_cast.hpp> #include <ored/utilities/log.hpp> #include <ored/utilities/parsers.hpp> #include <ored/utilities/to_string.hpp> #include <ored/utilities/xmlutils.hpp> // we only want to include these here. #include <rapidxml.hpp> #include <rapidxml_print.hpp> #include <algorithm> #include <fstream> using namespace std; using namespace rapidxml; using QuantLib::Size; namespace ore { namespace data { namespace { // helper routine to convert a value of an arbitrary type to string string convertToString(const Real value) { // We want to write out a double that conforms to xs:double, this means no // scientific notation, so we check for really small numbers here and explicitly set // to 16 decimal places string result; if (std::abs(value) < 1.0e-6) { std::ostringstream obj1; obj1.precision(16); obj1 << std::fixed << value; result = obj1.str(); } else { // And here we just use boost::lexical_cast which is better // at precision than std::to_string() result = boost::lexical_cast<std::string>(value); } return result; } template <class T> string convertToString(const T& value) { return ore::data::to_string(value); } // FIXME another variant of the above routine, just for backwards compatibility, we should get // rid of one of these two string convertToString2(const std::string& s) { return s; } template <class T> string convertToString2(const T& value) { return std::to_string(value); } } // namespace XMLDocument::XMLDocument() : _doc(new rapidxml::xml_document<char>()), _buffer(NULL) {} XMLDocument::XMLDocument(const string& fileName) : _doc(new rapidxml::xml_document<char>()), _buffer(NULL) { // Need to load the entire file into memory to pass to doc.parse(). ifstream t(fileName.c_str()); QL_REQUIRE(t.is_open(), "Failed to open file " << fileName); t.seekg(0, std::ios::end); // go to the end Size length = static_cast<Size>(t.tellg()); // report location (this is the length) QL_REQUIRE(length > 0, "File " << fileName << " is empty."); t.seekg(0, std::ios::beg); // go back to the beginning _buffer = new char[length + 1]; // allocate memory for a buffer of appropriate dimension t.read(_buffer, length); // read the whole file into the buffer _buffer[static_cast<int>(t.gcount())] = '\0'; t.close(); // close file handle try { _doc->parse<0>(_buffer); } catch (rapidxml::parse_error& pe) { string where(pe.where<char>(), 30); // limit to first 30 chars. QL_FAIL("RapidXML Parse Error : " << pe.what() << ". where=" << where); } } XMLDocument::~XMLDocument() { if (_buffer != NULL) delete[] _buffer; if (_doc != NULL) delete _doc; } void XMLDocument::fromXMLString(const string& xmlString) { QL_REQUIRE(!_buffer, "XML Document is already loaded"); Size length = xmlString.size(); _buffer = new char[length + 1]; strcpy(_buffer, xmlString.c_str()); _buffer[length] = '\0'; try { _doc->parse<0>(_buffer); } catch (rapidxml::parse_error& pe) { string where(pe.where<char>(), 30); // limit to first 30 chars. QL_FAIL("RapidXML Parse Error : " << pe.what() << ". where=" << where); } } XMLNode* XMLDocument::getFirstNode(const string& name) { return _doc->first_node(name == "" ? NULL : name.c_str()); } void XMLDocument::appendNode(XMLNode* node) { _doc->append_node(node); } void XMLDocument::toFile(const string& fileName) { std::ofstream ofs(fileName.c_str()); ofs << *_doc; ofs.close(); } string XMLDocument::toString() { ostringstream oss; oss << *_doc; return oss.str(); } XMLNode* XMLDocument::allocNode(const string& nodeName) { XMLNode* n = _doc->allocate_node(node_element, allocString(nodeName)); QL_REQUIRE(n, "Failed to allocate XMLNode for " << nodeName); return n; } XMLNode* XMLDocument::allocNode(const string& nodeName, const string& nodeValue) { XMLNode* n = _doc->allocate_node(node_element, allocString(nodeName), allocString(nodeValue)); QL_REQUIRE(n, "Failed to allocate XMLNode for " << nodeName); return n; } char* XMLDocument::allocString(const string& str) { char* s = _doc->allocate_string(str.c_str()); QL_REQUIRE(s, "Failed to allocate string for " << str); return s; } void XMLSerializable::fromFile(const string& filename) { XMLDocument doc(filename); fromXML(doc.getFirstNode("")); } void XMLSerializable::toFile(const string& filename) { XMLDocument doc; XMLNode* node = toXML(doc); doc.appendNode(node); doc.toFile(filename); } void XMLSerializable::fromXMLString(const string& xml) { ore::data::XMLDocument doc; doc.fromXMLString(xml); fromXML(doc.getFirstNode("")); } string XMLSerializable::toXMLString() { XMLDocument doc; XMLNode* node = toXML(doc); doc.appendNode(node); return doc.toString(); } void XMLUtils::checkNode(XMLNode* node, const string& expectedName) { QL_REQUIRE(node, "XML Node is NULL (expected " << expectedName << ")"); QL_REQUIRE(node->name() == expectedName, "XML Node name " << node->name() << " does not match expected name " << expectedName); } XMLNode* XMLUtils::addChild(XMLDocument& doc, XMLNode* parent, const string& name) { QL_REQUIRE(parent, "XML Parent Node is NULL (adding Child " << name << ")"); XMLNode* node = doc.allocNode(name); parent->insert_node(0, node); return node; } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, const char* value) { addChild(doc, n, name, string(value)); } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, const string& value) { if (value.size() == 0) { addChild(doc, n, name); } else { XMLNode* node = doc.allocNode(name, value); QL_REQUIRE(n, "XML Node is NULL (adding " << name << ")"); n->insert_node(0, node); } } void XMLUtils::addChildAsCdata(XMLDocument& doc, XMLNode* n, const string& name, const string& value) { if (value.size() == 0) { addChild(doc, n, name); } else { QL_REQUIRE(n, "XML Node is NULL (adding " << name << ")"); XMLNode* node = doc.allocNode(name); n->insert_node(0, node); XMLNode* cdata_node = doc.doc()->allocate_node(node_cdata); cdata_node->value(doc.allocString(value)); QL_REQUIRE(cdata_node, "Failed to allocate cdata node for " << name); node->insert_node(0, cdata_node); } } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, const string& value, const string& attrName, const string& attr) { XMLNode* node; if (value.size() == 0) { node = addChild(doc, n, name); } else { node = doc.allocNode(name, value); QL_REQUIRE(n, "XML Node is NULL (adding " << name << ")"); n->insert_node(0, node); } if (attrName != "" || attr != "") { XMLUtils::addAttribute(doc, node, attrName, attr); } } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, Real value) { addChild(doc, n, name, convertToString(value)); } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, int value) { addChild(doc, n, name, convertToString(value)); } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, bool value) { string s = value ? "true" : "false"; addChild(doc, n, name, s); } void XMLUtils::addChild(XMLDocument& doc, XMLNode* n, const string& name, const Period& value) { addChild(doc, n, name, convertToString(value)); } void XMLUtils::addChild(XMLDocument& doc, XMLNode* parent, const string& name, const vector<Real>& values) { vector<string> strings(values.size()); std::transform(values.begin(), values.end(), strings.begin(), [](Real x) { return convertToString2(x); }); addChild(doc, parent, name, boost::algorithm::join(strings, ",")); } void XMLUtils::addChildren(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const string& firstName, const string& secondName, const map<string, string>& values) { QL_REQUIRE(parent, "XML Node is null (Adding " << names << ")"); XMLNode* node = addChild(doc, parent, names); map<string, string>::const_iterator it; for (it = values.begin(); it != values.end(); ++it) { XMLNode* n = addChild(doc, node, name); QL_REQUIRE(n, "XML AllocNode failure (" << name << ")"); addChild(doc, n, firstName, it->first); addChild(doc, n, secondName, it->second); } } string XMLUtils::getChildValue(XMLNode* node, const string& name, bool mandatory) { QL_REQUIRE(node, "XMLNode is NULL (was looking for child " << name << ")"); xml_node<>* child = node->first_node(name.c_str()); if (mandatory) { QL_REQUIRE(child, "Error: No XML Child Node " << name << " found."); } return child ? getNodeValue(child) : ""; } Real XMLUtils::getChildValueAsDouble(XMLNode* node, const string& name, bool mandatory, double defaultValue) { string s = getChildValue(node, name, mandatory); return s == "" ? defaultValue : parseReal(s); } int XMLUtils::getChildValueAsInt(XMLNode* node, const string& name, bool mandatory, int defaultValue) { string s = getChildValue(node, name, mandatory); return s == "" ? defaultValue : parseInteger(s); } bool XMLUtils::getChildValueAsBool(XMLNode* node, const string& name, bool mandatory, bool defaultValue) { string s = getChildValue(node, name, mandatory); return s == "" ? defaultValue : parseBool(s); } Period XMLUtils::getChildValueAsPeriod(XMLNode* node, const string& name, bool mandatory, const Period& defaultValue) { string s = getChildValue(node, name, mandatory); return s == "" ? defaultValue : parsePeriod(s); } vector<string> XMLUtils::getChildrenValues(XMLNode* parent, const string& names, const string& name, bool mandatory) { vector<string> vec; xml_node<>* node = parent->first_node(names.c_str()); if (mandatory) { QL_REQUIRE(node, "Error: No XML Node " << names << " found."); } if (node) { for (xml_node<>* child = node->first_node(name.c_str()); child; child = child->next_sibling(name.c_str())) vec.push_back(getNodeValue(child)); } return vec; } vector<Real> XMLUtils::getChildrenValuesAsDoubles(XMLNode* node, const string& names, const string& name, bool mandatory) { vector<string> vecS = getChildrenValues(node, names, name, mandatory); vector<Real> vecD(vecS.size()); std::transform(vecS.begin(), vecS.end(), vecD.begin(), parseReal); return vecD; } vector<Real> XMLUtils::getChildrenValuesAsDoublesCompact(XMLNode* node, const string& name, bool mandatory) { string s = getChildValue(node, name, mandatory); return parseListOfValues(s, std::function<Real(string)>(&parseReal)); } vector<Real> XMLUtils::getNodeValueAsDoublesCompact(XMLNode* node) { string s = getNodeValue(node); return parseListOfValues(s, std::function<Real(string)>(&parseReal)); } vector<Period> XMLUtils::getChildrenValuesAsPeriods(XMLNode* node, const string& name, bool mandatory) { string s = getChildValue(node, name, mandatory); return parseListOfValues(s, std::function<Period(string)>(&parsePeriod)); } vector<string> XMLUtils::getChildrenValuesAsStrings(XMLNode* node, const string& name, bool mandatory) { string s = getChildValue(node, name, mandatory); return parseListOfValues(s); } map<string, string> XMLUtils::getChildrenValues(XMLNode* parent, const string& names, const string& name, const string& firstName, const string& secondName, bool mandatory) { map<string, string> res; xml_node<>* node = parent->first_node(names.c_str()); if (mandatory) { QL_REQUIRE(node, "Error: No XML Node " << names << " found."); } if (node) { for (xml_node<>* child = node->first_node(name.c_str()); child; child = child->next_sibling(name.c_str())) { string first = getChildValue(child, firstName, mandatory); string second = getChildValue(child, secondName, mandatory); // res[first] = second; res.insert(pair<string, string>(first, second)); } } return res; } map<string, string> XMLUtils::getChildrenAttributesAndValues(XMLNode* parent, const string& names, const string& attributeName, bool mandatory) { map<string, string> res; for (XMLNode* child = getChildNode(parent, names.c_str()); child; child = XMLUtils::getNextSibling(child, names.c_str())) { string first = getAttribute(child, attributeName); string second = getNodeValue(child); if (mandatory) { QL_REQUIRE(first != "", "empty attribute for " << names); } res.insert(pair<string, string>(first, second)); } if (mandatory) { QL_REQUIRE(res.size() > 0, "Error: No XML Node " << names << " found."); } return res; } // returns first child node XMLNode* XMLUtils::getChildNode(XMLNode* n, const string& name) { QL_REQUIRE(n, "XMLUtils::getChildNode(" << name << "): XML Node is NULL"); return n->first_node(name == "" ? nullptr : name.c_str()); } // return first node in the hierarchy of n that matches name, maybe n itself XMLNode* XMLUtils::locateNode(XMLNode* n, const string& name) { QL_REQUIRE(n, "XMLUtils::locateNode(" << name << "): XML Node is NULL"); if (n->name() == name) return n; else { const char* p = name.size() == 0 ? nullptr : name.c_str(); XMLNode* node = n->first_node(p); QL_REQUIRE(node, "XML node with name " << name << " not found"); return node; } } // append child to parent void XMLUtils::appendNode(XMLNode* parent, XMLNode* child) { QL_REQUIRE(parent, "XMLUtils::appendNode() parent is NULL"); QL_REQUIRE(child, "XMLUtils::appendNode() child is NULL"); parent->append_node(child); } void XMLUtils::addAttribute(XMLDocument& doc, XMLNode* node, const string& attrName, const string& attrValue) { QL_REQUIRE(node, "XMLUtils::appendAttribute(" << attrName << "," << attrName << ") node is NULL"); char* name = doc.allocString(attrName.c_str()); char* value = doc.allocString(attrValue.c_str()); node->append_attribute(doc.doc()->allocate_attribute(name, value)); } string XMLUtils::getAttribute(XMLNode* node, const string& attrName) { QL_REQUIRE(node, "XMLUtils::getAttribute(" << attrName << ") node is NULL"); xml_attribute<>* attr = node->first_attribute(attrName.c_str()); if (attr && attr->value()) return string(attr->value()); else return ""; } vector<XMLNode*> XMLUtils::getChildrenNodes(XMLNode* node, const string& name) { QL_REQUIRE(node, "XMLUtils::getChildredNodes(" << name << ") node is NULL"); vector<XMLNode*> res; const char* p = name.size() == 0 ? nullptr : name.c_str(); for (xml_node<>* c = node->first_node(p); c; c = c->next_sibling(p)) res.push_back(c); return res; } string XMLUtils::getNodeName(XMLNode* node) { QL_REQUIRE(node, "XMLUtils::getNodeName(): XML Node is NULL"); return node->name(); } void XMLUtils::setNodeName(XMLDocument& doc, XMLNode* node, const string& name) { QL_REQUIRE(node, "XMLUtils::setNodeName(" << name << "): XML Node is NULL"); char* nodeName = doc.allocString(name); node->name(nodeName); } XMLNode* XMLUtils::getNextSibling(XMLNode* node, const string& name) { QL_REQUIRE(node, "XMLUtils::getNextSibling(" << name << "): XML Node is NULL"); return node->next_sibling(name == "" ? nullptr : name.c_str()); } string XMLUtils::getNodeValue(XMLNode* node) { QL_REQUIRE(node, "XMLUtils::getNodeValue(): XML Node is NULL"); // handle CDATA nodes XMLNode* n = node->first_node(); if (n && n->type() == node_cdata) return n->value(); // all other cases return node->value(); } // template implementations // FIXME only needed as long as we want convert2String2() here, can be removed once we have consolidated // convert2String() and convert2String() template <> void XMLUtils::addChildren(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<Real>& values) { vector<string> strings(values.size()); std::transform(values.begin(), values.end(), strings.begin(), [](Real x) { return convertToString2(x); }); addChildren(doc, parent, names, name, strings); } template <class T> void XMLUtils::addChildren(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<T>& values) { XMLNode* node = addChild(doc, parent, names); for (Size i = 0; i < values.size(); i++) addChild(doc, node, name, values[i]); } template <class T> void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<T>& values, const string& attrName, const vector<string>& attrs) { addChildrenWithAttributes(doc, parent, names, name, values, vector<string>{attrName}, vector<vector<string>>{attrs}); } template <class T> void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<T>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs) { QL_REQUIRE(attrNames.size() == attrs.size(), "attrNames size (" << attrNames.size() << ") must match attrs size (" << attrs.size() << ")"); if (values.size() > 0) { for (auto const& attr : attrs) { QL_REQUIRE(values.size() == attr.size(), "Values / Attribute vector size mismatch"); } QL_REQUIRE(parent, "XML Node is null (Adding " << names << ")"); XMLNode* node = addChild(doc, parent, names); for (Size i = 0; i < values.size(); i++) { XMLNode* c = doc.allocNode(name, convertToString2(values[i])); QL_REQUIRE(c, "XML AllocNode failure (" << name << ")"); QL_REQUIRE(node, "XML Node is NULL (" << name << ")"); node->insert_node(0, c); for (Size j = 0; j < attrs.size(); ++j) { if (attrs[j][i] != "") addAttribute(doc, c, attrNames[j], attrs[j][i]); } } } } template <class T> void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<T>& values, const string& attrName, const vector<string>& attrs) { addChildrenWithOptionalAttributes(doc, n, names, name, values, vector<string>{attrName}, vector<vector<string>>{attrs}); } template <class T> void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<T>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs) { QL_REQUIRE(attrNames.size() == attrs.size(), "attrNames size (" << attrNames.size() << ") must match attrs size (" << attrs.size() << ")"); for (auto const& attr : attrs) QL_REQUIRE(attr.empty() == attrs.front().empty(), "all attributes must be empty or non-empty at the same time"); if (attrs.empty() || attrs.front().empty()) XMLUtils::addChildren(doc, n, names, name, values); else XMLUtils::addChildrenWithAttributes(doc, n, names, name, values, attrNames, attrs); } vector<string> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const string& attrName, vector<string>& attrs, bool mandatory) { return getChildrenValuesWithAttributes<string>( parent, names, name, attrName, attrs, [](const string& x) { return x; }, mandatory); } template <class T> vector<T> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const string& attrName, vector<string>& attrs, const std::function<T(string)> parser, bool mandatory) { std::vector<std::reference_wrapper<vector<string>>> attrs_v; attrs_v.push_back(attrs); return getChildrenValuesWithAttributes(parent, names, name, vector<string>{attrName}, attrs_v, parser, mandatory); } vector<string> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const vector<string>& attrNames, const vector<std::reference_wrapper<vector<string>>>& attrs, bool mandatory) { return getChildrenValuesWithAttributes<string>( parent, names, name, attrNames, attrs, [](const string& x) { return x; }, mandatory); } template <class T> vector<T> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const vector<string>& attrNames, const vector<std::reference_wrapper<vector<string>>>& attrs, const std::function<T(string)> parser, bool mandatory) { QL_REQUIRE(parser, "XMLUtils::getChildrenValuesWithAttributes(): parser is null"); QL_REQUIRE(attrNames.size() == attrs.size(), "attrNames size (" << attrNames.size() << ") must match attrs size (" << attrs.size() << ")"); vector<T> vec; rapidxml::xml_node<>* node = parent->first_node(names.c_str()); if (mandatory) { QL_REQUIRE(node, "Error: No XML Node " << names << " found."); } if (node) { for (rapidxml::xml_node<>* child = node->first_node(name.c_str()); child; child = child->next_sibling(name.c_str())) { std::string vstr = getNodeValue(child); vec.push_back(parser(vstr)); for (Size i = 0; i < attrNames.size(); ++i) { xml_attribute<>* attr = child->first_attribute(attrNames[i].c_str()); if (attr && attr->value()) ((vector<string>&)attrs[i]).push_back(attr->value()); else ((vector<string>&)attrs[i]).push_back(""); } } } return vec; } /* Instantiate some template functions above for types T we want to support. Add instantiations for more types here, if required. This has two advantages over putting the templated version of the functions in the header file: - faster compile times - we do not need to include the rapid xml headers in xmlutils.hpp */ template void XMLUtils::addChildren(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<string>& values); // throws a warning currently, but that is ok, see the FIXME above in template <> void XMLUtils::addChildren(...) // template void XMLUtils::addChildren(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, // const vector<double>& values); template void XMLUtils::addChildren(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<bool>& values); template void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<string>& values, const string& attrName, const vector<string>& attrs); template void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<double>& values, const string& attrName, const vector<string>& attrs); template void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<bool>& values, const string& attrName, const vector<string>& attrs); template void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<string>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs); template void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<double>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs); template void XMLUtils::addChildrenWithAttributes(XMLDocument& doc, XMLNode* parent, const string& names, const string& name, const vector<bool>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs); template void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<string>& values, const string& attrName, const vector<string>& attrs); template void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<double>& values, const string& attrName, const vector<string>& attrs); template void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<bool>& values, const string& attrName, const vector<string>& attrs); template void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<string>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs); template void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<double>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs); template void XMLUtils::addChildrenWithOptionalAttributes(XMLDocument& doc, XMLNode* n, const string& names, const string& name, const vector<bool>& values, const vector<string>& attrNames, const vector<vector<string>>& attrs); template vector<std::string> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const string& attrName, vector<string>& attrs, std::function<string(string)> parser, bool mandatory); template vector<double> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const string& attrName, vector<string>& attrs, std::function<double(string)> parser, bool mandatory); template vector<bool> XMLUtils::getChildrenValuesWithAttributes(XMLNode* parent, const string& names, const string& name, const string& attrName, vector<string>& attrs, std::function<bool(string)> parser, bool mandatory); } // namespace data } // namespace ore
46.5625
120
0.603372
[ "vector", "model", "transform" ]
cd7afa14132b5462eb4ec535e7e76a0dbdcc1ffe
7,395
hpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ptp_datatypes.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ptp_datatypes.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ptp_datatypes.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_IOS_XR_PTP_DATATYPES_ #define _CISCO_IOS_XR_PTP_DATATYPES_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xr { namespace Cisco_IOS_XR_ptp_datatypes { class PtpTelecomClock : public ydk::Enum { public: static const ydk::Enum::YLeaf telecom_grandmaster; static const ydk::Enum::YLeaf telecom_boundary; static const ydk::Enum::YLeaf telecom_slave; static int get_enum_value(const std::string & name) { if (name == "telecom-grandmaster") return 0; if (name == "telecom-boundary") return 1; if (name == "telecom-slave") return 2; return -1; } }; class PtpInvalidUnicastGrantRequestResponse : public ydk::Enum { public: static const ydk::Enum::YLeaf reduce; static const ydk::Enum::YLeaf deny; static int get_enum_value(const std::string & name) { if (name == "reduce") return 0; if (name == "deny") return 1; return -1; } }; class PtpClockId : public ydk::Enum { public: static const ydk::Enum::YLeaf router_mac; static const ydk::Enum::YLeaf user_mac; static const ydk::Enum::YLeaf eui; static int get_enum_value(const std::string & name) { if (name == "router-mac") return 0; if (name == "user-mac") return 1; if (name == "eui") return 2; return -1; } }; class PtpClockSelectionMode : public ydk::Enum { public: static const ydk::Enum::YLeaf Y_1588v2; static const ydk::Enum::YLeaf telecom_profile; static int get_enum_value(const std::string & name) { if (name == "1588v2") return 0; if (name == "telecom-profile") return 1; return -1; } }; class PtpClockOperation : public ydk::Enum { public: static const ydk::Enum::YLeaf two_step; static const ydk::Enum::YLeaf one_step; static int get_enum_value(const std::string & name) { if (name == "two-step") return 0; if (name == "one-step") return 1; return -1; } }; class PtpTimePeriod : public ydk::Enum { public: static const ydk::Enum::YLeaf Y_1; static const ydk::Enum::YLeaf Y_2; static const ydk::Enum::YLeaf Y_4; static const ydk::Enum::YLeaf Y_8; static const ydk::Enum::YLeaf Y_16; static const ydk::Enum::YLeaf Y_32; static const ydk::Enum::YLeaf Y_64; static const ydk::Enum::YLeaf Y_128; static int get_enum_value(const std::string & name) { if (name == "1") return 0; if (name == "2") return 1; if (name == "4") return 2; if (name == "8") return 3; if (name == "16") return 4; if (name == "32") return 5; if (name == "64") return 6; if (name == "128") return 7; return -1; } }; class PtpTransport : public ydk::Enum { public: static const ydk::Enum::YLeaf unicast; static const ydk::Enum::YLeaf mixed_mode; static const ydk::Enum::YLeaf multicast; static int get_enum_value(const std::string & name) { if (name == "unicast") return 0; if (name == "mixed-mode") return 1; if (name == "multicast") return 2; return -1; } }; class PtpDelayAsymmetryUnits : public ydk::Enum { public: static const ydk::Enum::YLeaf nanoseconds; static const ydk::Enum::YLeaf microseconds; static const ydk::Enum::YLeaf milliseconds; static int get_enum_value(const std::string & name) { if (name == "nanoseconds") return 0; if (name == "microseconds") return 1; if (name == "milliseconds") return 2; return -1; } }; class PtpTimescale : public ydk::Enum { public: static const ydk::Enum::YLeaf ptp; static const ydk::Enum::YLeaf arb; static int get_enum_value(const std::string & name) { if (name == "ptp") return 0; if (name == "arb") return 1; return -1; } }; class PtpClockProfile : public ydk::Enum { public: static const ydk::Enum::YLeaf default_; static const ydk::Enum::YLeaf g82651; static const ydk::Enum::YLeaf g82751; static const ydk::Enum::YLeaf g82752; static int get_enum_value(const std::string & name) { if (name == "default") return 0; if (name == "g82651") return 1; if (name == "g82751") return 2; if (name == "g82752") return 3; return -1; } }; class PtpPortState : public ydk::Enum { public: static const ydk::Enum::YLeaf any; static const ydk::Enum::YLeaf slave_only; static const ydk::Enum::YLeaf master_only; static int get_enum_value(const std::string & name) { if (name == "any") return 0; if (name == "slave-only") return 1; if (name == "master-only") return 2; return -1; } }; class PtpTimeSource : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf atomic_clock; static const ydk::Enum::YLeaf gps; static const ydk::Enum::YLeaf terrestrial_radio; static const ydk::Enum::YLeaf ptp; static const ydk::Enum::YLeaf ntp; static const ydk::Enum::YLeaf hand_set; static const ydk::Enum::YLeaf other; static const ydk::Enum::YLeaf internal_oscillator; static int get_enum_value(const std::string & name) { if (name == "unknown") return 0; if (name == "atomic-clock") return 16; if (name == "gps") return 32; if (name == "terrestrial-radio") return 48; if (name == "ptp") return 64; if (name == "ntp") return 80; if (name == "hand-set") return 96; if (name == "other") return 144; if (name == "internal-oscillator") return 160; return -1; } }; class PtpEncap : public ydk::Enum { public: static const ydk::Enum::YLeaf ethernet; static const ydk::Enum::YLeaf ipv4; static const ydk::Enum::YLeaf ipv6; static int get_enum_value(const std::string & name) { if (name == "ethernet") return 1; if (name == "ipv4") return 2; if (name == "ipv6") return 3; return -1; } }; class PtpTime : public ydk::Enum { public: static const ydk::Enum::YLeaf interval; static const ydk::Enum::YLeaf frequency; static int get_enum_value(const std::string & name) { if (name == "interval") return 0; if (name == "frequency") return 1; return -1; } }; class PtpClockAdvertisementMode : public ydk::Enum { public: static const ydk::Enum::YLeaf Y_1588v2; static const ydk::Enum::YLeaf telecom_profile; static int get_enum_value(const std::string & name) { if (name == "1588v2") return 0; if (name == "telecom-profile") return 1; return -1; } }; } } #endif /* _CISCO_IOS_XR_PTP_DATATYPES_ */
28.886719
62
0.561866
[ "vector" ]
cd7dde76b9e4621508f9e3c23864102da40bc90c
1,996
hpp
C++
geometry/serialization.hpp
tnuvoletta/Principia
25cf2fb70c512cf86a842ed525f6ab10e57f937c
[ "MIT" ]
565
2015-01-04T21:47:18.000Z
2022-03-22T12:04:58.000Z
geometry/serialization.hpp
tnuvoletta/Principia
25cf2fb70c512cf86a842ed525f6ab10e57f937c
[ "MIT" ]
1,019
2015-01-03T11:42:27.000Z
2022-03-29T21:02:15.000Z
geometry/serialization.hpp
tnuvoletta/Principia
25cf2fb70c512cf86a842ed525f6ab10e57f937c
[ "MIT" ]
92
2015-02-11T23:08:58.000Z
2022-03-21T03:35:37.000Z
 #pragma once #include "base/not_constructible.hpp" namespace principia { namespace geometry { namespace internal_serialization { using base::not_constructible; // A helper class that serializes a |double|, a |Quantity|, a |Point| or a // |Multivector| to a protobuf structure like: // // message Message { // oneof message { // double double = 1; // Quantity quantity = 2; // Point point = 3; // Multivector multivector = 4; // } // } template<typename T, typename Message> struct DoubleOrQuantityOrPointOrMultivectorSerializer : not_constructible {}; // A helper class that serializes a |double|, a |Quantity| or a |Multivector| // to a protobuf structure like: // // message Message { // oneof message { // double double = 1; // Quantity quantity = 2; // Multivector multivector = 3; // } // } template<typename T, typename Message> struct DoubleOrQuantityOrMultivectorSerializer : not_constructible {}; // A helper class that serializes a |Point| or a |Multivector| to a protobuf // structure like: // // message Message { // oneof message { // Point point = 1; // Multivector multivector = 2; // } // } template<typename T, typename Message> struct PointOrMultivectorSerializer : not_constructible {}; // A helper class that serializes a |Quantity| or a |Multivector| to a protobuf // structure like: // // message Message { // oneof message { // Quantity quantity = 1; // Multivector multivector = 2; // } // } template<typename T, typename Message> struct QuantityOrMultivectorSerializer : not_constructible {}; } // namespace internal_serialization using internal_serialization::DoubleOrQuantityOrPointOrMultivectorSerializer; using internal_serialization::DoubleOrQuantityOrMultivectorSerializer; using internal_serialization::PointOrMultivectorSerializer; using internal_serialization::QuantityOrMultivectorSerializer; } // namespace geometry } // namespace principia #include "geometry/serialization_body.hpp"
26.972973
79
0.728958
[ "geometry" ]
cd821342b307db902fb67bd0740e1e8a19668516
4,952
hpp
C++
src/libraries/fvOptions/sources/derived/rotorDiskSource/trimModel/targetCoeff/targetCoeffTrim.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/fvOptions/sources/derived/rotorDiskSource/trimModel/targetCoeff/targetCoeffTrim.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/fvOptions/sources/derived/rotorDiskSource/trimModel/targetCoeff/targetCoeffTrim.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2012-2013 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of Caelus. Caelus is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Caelus 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 Caelus. If not, see <http://www.gnu.org/licenses/>. Class CML::targetCoeffTrim Description Target trim forces/coefficients Solves: c^old + J.d(theta) = c^target Where: n = time level c = coefficient vector (thrust force, roll moment, pitch moment) theta = pitch angle vector (collective, roll, pitch) J = Jacobian [3x3] matrix The trimmed pitch angles are found via solving the above with a Newton-Raphson iterative method. The solver tolerance can be user-input, using the 'tol' entry. If coefficients are requested (useCoeffs = true), the force and moments are normalised using: force c = --------------------------------- alpha*pi*rho*(omega^2)*(radius^4) and moment c = --------------------------------- alpha*pi*rho*(omega^2)*(radius^5) Where: alpha = user-input conversion coefficient (default = 1) rho = desity omega = rotor angulr velocity pi = mathematical pi SourceFiles targetCoeffTrim.cpp \*---------------------------------------------------------------------------*/ #ifndef targetCoeffTrim_HPP #define targetCoeffTrim_HPP #include "trimModel.hpp" #include "tensor.hpp" #include "vector.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class targetCoeffTrim Declaration \*---------------------------------------------------------------------------*/ class targetCoeffTrim : public trimModel { protected: // Protected data //- Number of iterations between calls to 'correct' label calcFrequency_; //- Flag to indicate whether to solve coeffs (true) or forces (false) bool useCoeffs_; //- Target coefficient vector (thrust force, roll moment, pitch moment) vector target_; //- Pitch angles (collective, roll, pitch) [rad] vector theta_; //- Maximum number of iterations in trim routine label nIter_; //- Convergence tolerance scalar tol_; //- Under-relaxation coefficient scalar relax_; //- Perturbation angle used to determine jacobian scalar dTheta_; //- Coefficient to allow for conversion between US and EU definitions scalar alpha_; // Protected member functions //- Calculate the rotor force and moment coefficients vector template<class RhoFieldType> vector calcCoeffs ( const RhoFieldType& rho, const vectorField& U, const scalarField& alphag, vectorField& force ) const; //- Correct the model template<class RhoFieldType> void correctTrim ( const RhoFieldType& rho, const vectorField& U, vectorField& force ); public: //- Run-time type information TypeName("targetCoeffTrim"); //- Constructor targetCoeffTrim(const fv::rotorDiskSource& rotor, const dictionary& dict); //- Destructor virtual ~targetCoeffTrim(); // Member functions //- Read void read(const dictionary& dict); //- Return the geometric angle of attack [rad] virtual tmp<scalarField> thetag() const; //- Correct the model virtual void correct ( const vectorField& U, vectorField& force ); //- Correct the model for compressible flow virtual void correct ( const volScalarField rho, const vectorField& U, vectorField& force ); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
26.201058
79
0.519588
[ "vector", "model" ]
cd853b21d9615782b75cd46448800e51f9f28c87
5,889
cpp
C++
Lab 3 HyperQuickSort using MPI/hypersort.cpp
AkshanshChahal/COL380-Parallel-Programming
097891fe9df6288eb211707b3969f99d036a4d98
[ "Apache-2.0" ]
null
null
null
Lab 3 HyperQuickSort using MPI/hypersort.cpp
AkshanshChahal/COL380-Parallel-Programming
097891fe9df6288eb211707b3969f99d036a4d98
[ "Apache-2.0" ]
null
null
null
Lab 3 HyperQuickSort using MPI/hypersort.cpp
AkshanshChahal/COL380-Parallel-Programming
097891fe9df6288eb211707b3969f99d036a4d98
[ "Apache-2.0" ]
null
null
null
// mpic++ sort.cpp -o hypersort -std=c++11 // mpirun -np 8 hypersort inputxx.txt #include <iostream> #include <vector> #include <string> #include <stdlib.h> #include <time.h> #include <fstream> #include <algorithm> #include <math.h> #include <utility> #include <stdio.h> #include <mpi.h> #include <sstream> #include <cmath> #define fr(i,n) for(int i=0; i<n; i++) #define frr(i,a,b) for(int i=a; i<=b; i++) #define INF (1<<30) using namespace std; int fun(const void *a, const void *b){ return *(int*)a >= *(int*)b ? 1 : -1; } int main(int argc, char *argv[]){ int *a; // Input Array int N; // Size of input array int P; // #Processes int rank; // My Rank int *ar; // my array int *l; // left array int *r; // right array int *rcv; // receive array int arx; // my array size int lx; // left size int rx; // right size int rcvx; // receive size int pivot; // median -> to receive int pi; // pivot index int ng; // #groups int gs; // group size ////////////////////////////////////// Taking input from input file ////////////////////////////////////// string ifile = argv[1]; ifstream infile(ifile.c_str()); infile >> N; int powersize = log2(N); stringstream ss; ss << powersize; string outname = "output_2power" + ss.str() + ".txt"; a = (int *)malloc(N*sizeof(int)); fr(i,N){ infile >> a[i]; } // utilities int i; bool islower; double starttime, endtime; MPI_Status status; ////////////////////////////////////////////// MPI ///////////////////////////////////////////// MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &P); MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Preparing the local arrays for each node arx = N/P; ar = (int *)malloc(arx*sizeof(int)); fr(k,arx){ ar[k] = a[ rank*arx + k ]; } ng = 1; gs = P/ng; starttime = MPI_Wtime(); // The log(n) iterations begin !! while(true){ qsort(ar,arx,sizeof(int),fun); if(rank%gs < gs/2) islower = true; // check this .. else islower = false; i = rank/gs; // The group number (0,1,2 ... ,ng-1) // The nodes in ith group are from i*gs to (i+1)*gs-1 // break if group size is 1 if(gs == 1) break; // Sending the pivot to its other group memebers // All others receiving the pivot and calculating the index of split if(rank%gs == 0){ pi = (arx-1)/2; pivot = ar[pi]; for(int j=i*gs+1; j<(i+1)*gs; j++){ MPI_Send(&pivot, 1, MPI_INT, j, 1 /*Tag*/, MPI_COMM_WORLD); } } else{ MPI_Recv(&pivot, 1, MPI_INT, i*gs, 1, MPI_COMM_WORLD, &status); pi = -1; for(int j=0; j<arx; j++){ if(ar[j]>pivot){ pi = j-1; if(j==0) pi = 0; break; } } if(pi == -1){ pi = arx-1; } } // Calculate the sizes of LOWER and UPPER arrays // And prepare those arrays : r and s, to send and receive // for the lower half nodes in a group the right half is going to be exchanged with the // left half of the upper half of the nodes of this group. // the lower node will send the size of its right half to upper node, and get upper's left size lx = pi+1; rx = arx-lx; if(arx==0){ lx = rx = 0; } l = (int *)malloc(lx*sizeof(int)); r = (int *)malloc(rx*sizeof(int)); // Preparing the left and right arrays for(int j=0;j<pi+1;j++){ l[j] = ar[j]; } for(int j=pi+1;j<arx;j++){ r[j-pi-1] = ar[j]; } // First send & recv the size of the array its going to receive if(islower){ MPI_Sendrecv(&rx, 1, MPI_INT, rank+gs/2, 1, &rcvx, 1, MPI_INT, rank+gs/2, 1, MPI_COMM_WORLD, &status); arx = lx + rcvx; } else{ MPI_Sendrecv(&lx, 1, MPI_INT, rank-gs/2, 1, &rcvx, 1, MPI_INT, rank-gs/2, 1, MPI_COMM_WORLD, &status); arx = rx + rcvx; } // allocating size for the receive array rcv = (int *)malloc(rcvx*sizeof(int)); // Time to exchange the split parts if(islower){ MPI_Sendrecv(r, rx, MPI_INT, rank+gs/2, 1, rcv, rcvx, MPI_INT, rank+gs/2, 1, MPI_COMM_WORLD, &status); } else{ MPI_Sendrecv(l, lx, MPI_INT, rank-gs/2, 1, rcv, rcvx, MPI_INT, rank-gs/2, 1, MPI_COMM_WORLD, &status); } free(ar); ar = (int *)malloc(arx*sizeof(int)); if(islower){ for(int j=0;j<lx;j++){ ar[j] = l[j]; } for(int j=lx;j<arx;j++){ ar[j] = rcv[j-lx]; } } else{ for(int j=0;j<rcvx;j++){ ar[j] = rcv[j]; } for(int j=rcvx;j<arx;j++){ ar[j] = r[j-rcvx]; } } free(l); free(r); free(rcv); ng = ng*2; gs = P/ng; } ////////////////////////////////////// Printing to the output file ////////////////////////////////////// // To output each process first prints its share of array in the output file // adn then sends a signal to the next process, which once receives that signal // prints its own share. This goes on till the last process // So effectively they all print sequentially in the output file // for the case of just one process if(P==1){ ofstream outfile; outfile.open(outname.c_str(), std::ofstream::app); fr(j,arx){ outfile << ar[j] << " "; } }else{ if(rank == 0){ ofstream outfile; outfile.open(outname.c_str(), std::ofstream::app); fr(j,arx){ outfile << ar[j] << " "; } int x = 0; MPI_Send(&x, 1, MPI_INT, rank+1, 1 /*Tag*/, MPI_COMM_WORLD); } else if(rank == P-1){ int x = 0; MPI_Recv(&x, 1, MPI_INT, rank-1, 1, MPI_COMM_WORLD, &status); ofstream outfile; outfile.open(outname.c_str(), std::ofstream::app); fr(j,arx){ outfile << ar[j] << " "; } } else{ int x = 0; MPI_Recv(&x, 1, MPI_INT, rank-1, 1, MPI_COMM_WORLD, &status); ofstream outfile; outfile.open(outname.c_str(), std::ofstream::app); fr(j,arx){ outfile << ar[j] << " "; } MPI_Send(&x, 1, MPI_INT, rank+1, 1 /*Tag*/, MPI_COMM_WORLD); } } MPI_Finalize(); endtime = MPI_Wtime(); printf("That took %f seconds\n",endtime-starttime); }
21.650735
107
0.565631
[ "vector" ]
cd88468ac7109e5c8c0745ee6a429dbf013b78b4
4,829
cc
C++
lib/packed_to_unpacked_impl.cc
pavelfpl/gr-gsSDR
141f5cd1f53b9691c7c7e084f32343bddc0d2d97
[ "MIT" ]
1
2021-06-16T14:35:29.000Z
2021-06-16T14:35:29.000Z
lib/packed_to_unpacked_impl.cc
pavelfpl/gr-gsSDR
141f5cd1f53b9691c7c7e084f32343bddc0d2d97
[ "MIT" ]
null
null
null
lib/packed_to_unpacked_impl.cc
pavelfpl/gr-gsSDR
141f5cd1f53b9691c7c7e084f32343bddc0d2d97
[ "MIT" ]
1
2021-03-03T14:51:02.000Z
2021-03-03T14:51:02.000Z
/* -*- c++ -*- */ /* MIT License * * Copyright (c) 2021 Pavel Fiala * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gnuradio/io_signature.h> #include "packed_to_unpacked_impl.h" #include <gnuradio/blocks/pdu.h> // ------------------- // System standard ... // ------------------- #include <sys/types.h> #include <sys/stat.h> #include <stdexcept> #include <cstdlib> #include <limits> #include <vector> #include <time.h> #include <stdio.h> namespace gr { namespace gsSDR { using namespace std; packed_to_unpacked::sptr packed_to_unpacked::make() { return gnuradio::get_initial_sptr (new packed_to_unpacked_impl()); } /* * The private constructor ... * --------------------------- */ packed_to_unpacked_impl::packed_to_unpacked_impl() : gr::block("packed_to_unpacked", gr::io_signature::make(0, 0, 0), // gr::io_signature::make(<+MIN_IN+>, <+MAX_IN+>, sizeof(<+ITYPE+>)), gr::io_signature::make(0, 0, 0)) // gr::io_signature::make(<+MIN_OUT+>, <+MAX_OUT+>, sizeof(<+OTYPE+>))) { out_port = pmt::mp("pdus_out"); message_port_register_in(pmt::mp("pdus")); message_port_register_out(out_port); // pdu - data - complex float ... set_msg_handler(pmt::mp("pdus"), boost::bind(&packed_to_unpacked_impl::packet_handler, this, _1)); } /* * Our virtual destructor ... * -------------------------- */ packed_to_unpacked_impl::~packed_to_unpacked_impl(){ } void packed_to_unpacked_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) { /* <+forecast+> e.g. ninput_items_required[0] = noutput_items */ } int packed_to_unpacked_impl::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { /* const <+ITYPE+> *in = (const <+ITYPE+> *) input_items[0]; <+OTYPE+> *out = (<+OTYPE+> *) output_items[0]; */ // Do <+signal processing+> // Tell runtime system how many input items we consumed on // each input stream. consume_each (noutput_items); // Tell runtime system how many output items we produced. return noutput_items; } // packet_handler - public function / callback ... // ----------------------------------------------- void packed_to_unpacked_impl::packet_handler(pmt::pmt_t msg){ // Do <+signal processing+> // Get parameters from the pdu / unpacked bits - unsigned char ... // --------------------------------------------------------------- vector<unsigned char> data_packet(pmt::u8vector_elements(pmt::cdr(msg))); int m_packetLength = data_packet.size(); pmt::pmt_t meta = pmt::make_dict(); // Data unpacked ... // ----------------- /* in 0b11110000 out 0b00000001 0b00000001 0b00000001 0b00000001 0b00000000 0b00000000 0b00000000 0b00000000 * https://stackoverflow.com/questions/50977399/what-do-packed-to-unpacked-blocks-do-in-gnu-radio * */ int unpackedLength = m_packetLength*8; vector<unsigned char> data_unpacked(unpackedLength,0x00); // unpacked bytes ... for (int i=0; i<unpackedLength; i++){ data_unpacked[i] = (unsigned char)((data_packet.at(i/8) & (1 << (7 - (i % 8)))) != 0); } pmt::pmt_t unpacked_vec = pmt::init_u8vector(unpackedLength, data_unpacked); message_port_pub(out_port, pmt::cons(meta, unpacked_vec)); } } /* namespace gsSDR */ } /* namespace gr */
34.741007
120
0.615241
[ "vector" ]
cd8a22a13548f16e54c4d0fcd324af4f7fa965d8
739
cpp
C++
src/top.chenqwwq/leetcode/daily/_20220401/array-of-doubled-pairs.cpp
chenqwwq/_leetcode
a8055c53c9a68cedb1b57a56f98e83709448e4cb
[ "Apache-2.0" ]
null
null
null
src/top.chenqwwq/leetcode/daily/_20220401/array-of-doubled-pairs.cpp
chenqwwq/_leetcode
a8055c53c9a68cedb1b57a56f98e83709448e4cb
[ "Apache-2.0" ]
null
null
null
src/top.chenqwwq/leetcode/daily/_20220401/array-of-doubled-pairs.cpp
chenqwwq/_leetcode
a8055c53c9a68cedb1b57a56f98e83709448e4cb
[ "Apache-2.0" ]
null
null
null
// // Created by 陈炳鑫 on 2022/4/1. // #include "stdc++.h" #include "common.h" using namespace std; class Solution { public: bool canReorderDoubled(vector<int> &arr) { auto comp = [](int n1, int n2) -> bool { return abs(n1) > abs(n2); }; priority_queue<int, vector<int>, decltype(comp)> pq(comp); unordered_map<int, int> del; int cnt = 0; for (int num: arr) pq.push(num); while (!pq.empty()) { int cur = pq.top(); pq.pop(); if (del[cur] > 0) { del[cur]--; cnt--; } else { cnt++; del[cur * 2]++; } } return cnt == 0; } };
21.114286
66
0.428958
[ "vector" ]
cd8a731457564df253852a7ed1ad966d2eb04763
1,207
cpp
C++
applications/main.cpp
phiwen96/phlex
a84e293f52f0e548aa9fd354ff1e98466ed6ef4a
[ "Apache-2.0" ]
null
null
null
applications/main.cpp
phiwen96/phlex
a84e293f52f0e548aa9fd354ff1e98466ed6ef4a
[ "Apache-2.0" ]
null
null
null
applications/main.cpp
phiwen96/phlex
a84e293f52f0e548aa9fd354ff1e98466ed6ef4a
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <phlex/phlex.hpp> #include <ph_file/file.hpp> #include <ph_concepts/concepts.hpp> using std::cout, std::endl; enum struct APPLICATION_MODE : int { CONSOLE = 1, FILE = 2, UNKNOWN }; auto start_console (auto conf) -> int { while (false) { cout << ">>"; } return 0; } #include <vector> int main (int argc, char** argv) { // kuken i = {3}; #ifdef DEBUG #ifndef TEST_DIR throw; #endif cout << "testing dir=" << TEST_DIR << endl; cout << "debug" << endl; #endif auto mode = (APPLICATION_MODE) argc; switch (mode) { case APPLICATION_MODE::CONSOLE: { start_console (2); break; } case APPLICATION_MODE::FILE: { break; } case APPLICATION_MODE::UNKNOWN: { break; } default: { break; } } return 0; } //#include <ostream> struct A { auto operator << (std::basic_ostream<char>& o) const noexcept -> std::basic_ostream<char>& { return o; } };
13.715909
94
0.48053
[ "vector" ]
cd9239c44eebf7e4049e21165fd104a8c2d1a7e1
1,088
cpp
C++
apps/tests/util/summable_to_one_sampler.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
27
2020-08-17T17:25:59.000Z
2022-03-01T05:49:12.000Z
apps/tests/util/summable_to_one_sampler.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
4
2020-08-26T13:54:59.000Z
2020-09-21T07:19:22.000Z
apps/tests/util/summable_to_one_sampler.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
5
2020-08-26T23:26:48.000Z
2021-01-04T09:06:07.000Z
#include <polyvec/utils/summable_to_one_sampler.hpp> // Optional using namespace polyvec; namespace polyvectest { namespace util { int test_summable_to_one_sampler ( int /*argc*/, char** /*argv*/ ) { const polyvec::index n_variables = 4; const polyvec::index n_values = 5; SummableToOneSampler sampler(n_variables, n_values); printf("n_variables = %d \n", (int)n_variables); printf("n_values = %d \n", (int)n_values); sampler.begin(); while(!sampler.has_finished()){ std::vector<double> iterate = sampler.get_current_iteration(); std::vector<polyvec::index> iterate_pos = sampler.get_positions_on_grid(); printf("%05d: ", (int)sampler.iteration_no()); for(polyvec::index i = 0 ; i < sampler.n_variables() ; ++i) { printf("%4.1f ", iterate[i]*(n_values-1)); } printf( "|" ); for(polyvec::index i = 0 ; i < sampler.n_variables() ; ++i) { printf("%4d ", (int)iterate_pos[i]); } printf("\n"); sampler.step(); } return 0; } } // globfitter } // polyvectest
26.536585
80
0.612132
[ "vector" ]
cd980e406c2c9699ca9e3afa43bd9099d53d5011
7,655
cpp
C++
CPURenderer/ExternalImporter.cpp
shamanDevel/IsosurfaceSuperresolution
0658e67b7ca9f633547c65e3e16f93d2e0c5a4a2
[ "MIT" ]
7
2019-10-14T09:36:57.000Z
2022-02-27T05:13:28.000Z
CPURenderer/ExternalImporter.cpp
shamanDevel/IsosurfaceSuperresolution
0658e67b7ca9f633547c65e3e16f93d2e0c5a4a2
[ "MIT" ]
null
null
null
CPURenderer/ExternalImporter.cpp
shamanDevel/IsosurfaceSuperresolution
0658e67b7ca9f633547c65e3e16f93d2e0c5a4a2
[ "MIT" ]
3
2020-01-07T16:49:17.000Z
2021-06-23T14:21:00.000Z
#include "pch.h" #include "ExternalImporter.h" #include <fstream> #include <boost/algorithm/algorithm.hpp> #include <boost/algorithm/string/predicate.hpp> #include <experimental/filesystem> #include <openvdb/tools/Dense.h> static void printProgress(const std::string& prefix, float progress) { int barWidth = 50; std::cout << prefix << " ["; int pos = barWidth * progress; for (int i = 0; i < barWidth; ++i) { if (i < pos) std::cout << "="; else if (i == pos) std::cout << ">"; else std::cout << " "; } std::cout << "] " << int(progress * 100.0) << " %\r"; std::cout.flush(); if (progress >= 1) std::cout << std::endl; } openvdb::FloatGrid::Ptr ExternalImporter::importRAW( const std::string& filename, int downsampling, float lowerThreshold) { if (!boost::algorithm::ends_with(filename, ".dat")) { std::cout << "Filename does not point to the .dat file" << std::endl; return nullptr; } //read descriptor file std::ifstream file(filename); if (!file.is_open()) { std::cout << "Unable to open file " << filename << std::endl; return nullptr; } std::string line; std::string objectFileName = ""; size_t resolutionX = 0; size_t resolutionY = 0; size_t resolutionZ = 0; std::string datatype = ""; const std::string DATATYPE_UCHAR = "UCHAR"; const std::string DATATYPE_USHORT = "USHORT"; const std::string DATATYPE_BYTE = "BYTE"; while (std::getline(file, line)) { if (line.empty()) continue; std::istringstream iss(line); std::string token; iss >> token; if (!iss) continue; //no token in the current line if (token == "ObjectFileName:") iss >> objectFileName; else if (token == "Resolution:") iss >> resolutionX >> resolutionY >> resolutionZ; else if (token == "Format:") iss >> datatype; if (!iss) { std::cout << "Unable to parse line with token " << token << std::endl; return nullptr; } } file.close(); if (objectFileName.empty() || resolutionX == 0 || datatype.empty()) { std::cout << "Descriptor file does not contain ObjectFileName, Resolution and Format" << std::endl; return nullptr; } if (!(datatype == DATATYPE_UCHAR || datatype == DATATYPE_USHORT || datatype == DATATYPE_BYTE)) { std::cout << "Unknown format " << datatype << std::endl; return nullptr; } std::cout << "Descriptor file read" << "\nObjectFileName: " << objectFileName << "\nResolution: " << resolutionX << ", " << resolutionY << ", " << resolutionZ << "\nFormat: " << datatype << std::endl; // read volume size_t bytesPerEntry = 0; if (datatype == DATATYPE_UCHAR) bytesPerEntry = 1; if (datatype == DATATYPE_BYTE) bytesPerEntry = 1; if (datatype == DATATYPE_USHORT) bytesPerEntry = 2; size_t bytesToRead = resolutionX * resolutionY * resolutionZ * bytesPerEntry; std::string bfilename = std::experimental::filesystem::path(filename).replace_filename(objectFileName).generic_string(); std::cout << "Load " << bytesToRead << " bytes from " << bfilename << std::endl; std::ifstream bfile(bfilename, std::ifstream::binary | std::ifstream::ate); if (!bfile.is_open()) { std::cout << "Unable to open file " << bfilename << std::endl; return nullptr; } size_t filesize = bfile.tellg(); int headersize = static_cast<int>(filesize - static_cast<long long>(bytesToRead)); if (headersize < 0) { std::cout << "File is too small, " << (-headersize) << " bytes missing" << std::endl; return nullptr; } std::cout << "Skipping header of length " << headersize << std::endl; bfile.seekg(std::ifstream::pos_type(headersize)); #if 1 bytesToRead = resolutionX * resolutionY * downsampling * bytesPerEntry; std::vector<char> data(bytesToRead); //convert to dense grid and build vdb grid slice by slice //openvdb::CoordBBox gridDim(0, 0, 0, resolutionX - 1, resolutionY - 1, resolutionZ - 1); //typedef openvdb::tools::Dense<float, openvdb::tools::LayoutZYX> DenseT; typedef openvdb::tools::Dense<float, openvdb::tools::LayoutXYZ> DenseT; openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(); const int sliceSize = resolutionX * resolutionY / (downsampling*downsampling); for (int z=0; z<resolutionZ/ downsampling; ++z) { bfile.read(&data[0], bytesToRead); if (!bfile) { std::cout << "Loading data file failed" << std::endl; return nullptr; } if (z%10 == 0) printProgress("Convert", z / float(resolutionZ)); openvdb::CoordBBox sliceDim(0, 0, z, resolutionX / downsampling - 1, resolutionY / downsampling - 1, z); DenseT d(sliceDim); if (datatype == DATATYPE_UCHAR || datatype==DATATYPE_BYTE) { const unsigned char* raw = reinterpret_cast<unsigned char*>(data.data()); #pragma omp parallel for for (int y = 0; y < resolutionY / downsampling; ++y) for (int x = 0; x < resolutionX / downsampling; ++x) { float value = 0; for (int iz = 0; iz < downsampling; ++iz) for (int iy=0; iy<downsampling; ++iy) for (int ix = 0; ix < downsampling; ++ix) { long long idx2 = (ix + downsampling * x) + resolutionX * ((iy + downsampling * y) + resolutionY * iz); float val = raw[idx2] / 255.0f; value += val; } long long idx = x + y * resolutionX; value /= downsampling*downsampling; if (value < lowerThreshold) value = 0; d.setValue(size_t(idx), value); } } else if (datatype == DATATYPE_USHORT) { const unsigned short* raw = reinterpret_cast<unsigned short*>(data.data()); #pragma omp parallel for for (int y = 0; y < resolutionY / downsampling; ++y) for (int x = 0; x < resolutionX / downsampling; ++x) { float value = 0; for (int iz = 0; iz < downsampling; ++iz) for (int iy=0; iy<downsampling; ++iy) for (int ix = 0; ix < downsampling; ++ix) { long long idx2 = (ix + downsampling * x) + resolutionX * ((iy + downsampling * y) + resolutionY * iz); float val = raw[idx2] / 65535.0f; value += val; } long long idx = x + y * resolutionX/ downsampling; value /= downsampling*downsampling; if (value < lowerThreshold) value = 0; d.setValue(size_t(idx), value); } } openvdb::tools::copyFromDense(d, *grid, 0.001f, false); } printProgress("Convert", 1.0f); #else std::vector<char> data(bytesToRead); bfile.read(&data[0], bytesToRead); if (!bfile) { std::cout << "Loading data file failed" << std::endl; return nullptr; } // convert to dense grid openvdb::CoordBBox gridDim(0, 0, 0, resolutionX - 1, resolutionY - 1, resolutionZ - 1); typedef openvdb::tools::Dense<float, openvdb::tools::LayoutXYZ> DenseT; DenseT d(gridDim); if (datatype == DATATYPE_UCHAR) { const unsigned char* raw = reinterpret_cast<unsigned char*>(data.data()); #pragma omp parallel for // I have no idea about the order in which the volume is stored. // Let's just try it out for (long long idx = 0; idx < resolutionX*resolutionY*resolutionZ; ++idx) { float value = raw[idx] / 255.0f; if (value < lowerThreshold) value = 0; d.setValue(size_t(idx), value); } } else if (datatype == DATATYPE_USHORT) { const unsigned short* raw = reinterpret_cast<unsigned short*>(data.data()); #pragma omp parallel for // I have no idea about the order in which the volume is stored. // Let's just try it out for (long long idx = 0; idx < resolutionX*resolutionY*resolutionZ; ++idx) { float value = raw[idx] / 65535.0f; if (value < lowerThreshold) value = 0; d.setValue(size_t(idx), value); } } //convert to vdb grid std::cout << "Build VDB grid" << std::endl; openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(); openvdb::tools::copyFromDense(d, *grid, 0.001f, false); #endif //done std::cout << "Done!" << std::endl; return grid; }
32.854077
121
0.652645
[ "vector" ]
cd9d891c854427dfcdeaf354167e3445906a8708
1,563
cpp
C++
leetcode/problems/medium/740-delete-and-earn.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/740-delete-and-earn.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/740-delete-and-earn.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Delete and Earn https://leetcode.com/problems/delete-and-earn/ You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times: Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1. Return the maximum number of points you can earn by applying the above operation some number of times. Example 1: Input: nums = [3,4,2] Output: 6 Explanation: You can perform the following operations: - Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2]. - Delete 2 to earn 2 points. nums = []. You earn a total of 6 points. Example 2: Input: nums = [2,2,3,3,3,4] Output: 9 Explanation: You can perform the following operations: - Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3]. - Delete a 3 again to earn 3 points. nums = [3]. - Delete a 3 once more to earn 3 points. nums = []. You earn a total of 9 points. Constraints: 1 <= nums.length <= 2 * 104 1 <= nums[i] <= 104 */ class Solution { public: int deleteAndEarn(vector<int>& nums) { int mxN = 10000 + 5; int n = nums.size(), cnt[mxN], dp[mxN]; memset(dp, 0, sizeof(dp)); memset(cnt, 0, sizeof(cnt)); for(auto x : nums) cnt[x] += x; dp[1] = cnt[1], dp[2] = max(cnt[1], cnt[2]); for(int i = 3; i <= mxN - 1 ; i++) { dp[i] = max(dp[i - 2] + cnt[i], dp[i - 1]); } return dp[mxN - 1]; } };
30.647059
157
0.631478
[ "vector" ]
cd9ff022feede055226a86f6c3dc686cd35b9b37
7,644
hpp
C++
source/problem/SWE/problem_input/swe_inputs.hpp
elenabac/dgswemv2
ecc776811de304cbae7bfa696b3d22c513e7d4de
[ "MIT" ]
null
null
null
source/problem/SWE/problem_input/swe_inputs.hpp
elenabac/dgswemv2
ecc776811de304cbae7bfa696b3d22c513e7d4de
[ "MIT" ]
null
null
null
source/problem/SWE/problem_input/swe_inputs.hpp
elenabac/dgswemv2
ecc776811de304cbae7bfa696b3d22c513e7d4de
[ "MIT" ]
null
null
null
#ifndef SWE_INPUTS_HPP #define SWE_INPUTS_HPP #include "problem/SWE/swe_definitions.hpp" #include <yaml-cpp/yaml.h> #include "utilities/file_exists.hpp" namespace SWE { // Problem specific preprocessing information containers struct SphericalProjection { SphericalProjectionType type = SphericalProjectionType::None; double longitude_o = 0.0; double latitude_o = 0.0; double R = 6378200.0; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type & longitude_o & latitude_o & R; // clang-format on } #endif }; struct InitialConditions { InitialConditionsType type = InitialConditionsType::Default; double ze_initial = 0.; double qx_initial = 0.; double qy_initial = 0.; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type & ze_initial & qx_initial & qy_initial; // clang-format on } #endif }; // Problem specific bcis information containers struct TideNode { std::vector<double> frequency; std::vector<double> forcing_fact; std::vector<double> equilib_arg; std::vector<double> amplitude; std::vector<double> phase; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & frequency & forcing_fact & equilib_arg & amplitude & phase; // clang-format on } #endif }; struct TideBoundary { std::map<uint, TideNode> tide_nodes; bool get_tide_data(const std::vector<uint>& node_ID, std::vector<TideNode>& tide) { for (uint node : node_ID) { // Check if the boundary segment belongs here if (this->tide_nodes.find(node) == this->tide_nodes.end()) { return false; } } for (uint node : node_ID) { tide.push_back(this->tide_nodes[node]); } return true; } #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & tide_nodes; // clang-format on } #endif }; struct FlowNode { std::vector<double> frequency; std::vector<double> forcing_fact; std::vector<double> equilib_arg; std::vector<double> amplitude; std::vector<double> phase; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & frequency & forcing_fact & equilib_arg & amplitude & phase; // clang-format on } #endif }; struct FlowBoundary { std::map<uint, FlowNode> flow_nodes; bool get_flow_data(const std::vector<uint>& node_ID, std::vector<FlowNode>& flow) { for (uint node : node_ID) { // Check if the boundary segment belongs here if (this->flow_nodes.find(node) == this->flow_nodes.end()) { return false; } } for (uint node : node_ID) { flow.push_back(this->flow_nodes[node]); } return true; } #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & flow_nodes; // clang-format on } #endif }; struct LeveeInput { double H_barrier; double C_subcritical; double C_supercritical; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & H_barrier & C_subcritical & C_supercritical; // clang-format on } #endif }; // Problem specific forcing terms information containers struct FunctionSource { FunctionSourceType type = FunctionSourceType::None; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type; // clang-format on } #endif }; struct BottomFriction { BottomFrictionType type = BottomFrictionType::None; double coefficient = 0.0; std::string manning_data_file; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type & coefficient & manning_data_file; // clang-format on } #endif }; struct MeteoForcing { MeteoForcingType type = MeteoForcingType::None; std::string meteo_data_type; std::string raw_meteo_data_file; std::string meteo_data_file; double frequency; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type & meteo_data_file & frequency; // clang-format on } #endif }; struct TidePotential { TidePotentialType type = TidePotentialType::None; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type; // clang-format on } #endif }; struct Coriolis { CoriolisType type = CoriolisType::None; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type; // clang-format on } #endif }; // Problem specific postprocessing information containers struct WettingDrying { WettingDryingType type = WettingDryingType::None; double h_o = 0.1; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type & h_o; // clang-format on } #endif }; struct SlopeLimiting { SlopeLimitingType type = SlopeLimitingType::None; std::string slope_limiting_type; double M = 1.0e-8; double nu = 1.5; #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & type & slope_limiting_type & M & nu; // clang-format on } #endif }; // Problem specific inputs struct Inputs { std::string name; double g = 9.81; double rho_air = 1.2250; double rho_water = 1000.0; SphericalProjection spherical_projection; InitialConditions initial_conditions; std::vector<TideBoundary> tide_bc_data; std::vector<FlowBoundary> flow_bc_data; std::map<std::pair<uint, uint>, LeveeInput> levee_is_data; FunctionSource function_source; BottomFriction bottom_friction; MeteoForcing meteo_forcing; TidePotential tide_potential; Coriolis coriolis; WettingDrying wet_dry; SlopeLimiting slope_limit; Inputs() = default; Inputs(YAML::Node& swe_node); void read_bcis(const std::string& bcis_file); YAML::Node as_yaml_node(); #ifdef HAS_HPX template <typename Archive> void serialize(Archive& ar, unsigned) { // clang-format off ar & g & rho_air & rho_water & spherical_projection & initial_conditions & tide_bc_data & flow_bc_data & levee_is_data & function_source & bottom_friction & meteo_forcing & tide_potential & coriolis & wet_dry & slope_limit; // clang-format on } #endif }; } #endif
23.163636
87
0.601648
[ "vector" ]
cda2d8771d90432487efb53e3ad18e035b927ce9
9,647
cpp
C++
projects/cli/src/data/PatientGenerator.cpp
faaizT/core
488b357deece8dd4f7be318eefb49f6330be8239
[ "Apache-2.0" ]
null
null
null
projects/cli/src/data/PatientGenerator.cpp
faaizT/core
488b357deece8dd4f7be318eefb49f6330be8239
[ "Apache-2.0" ]
null
null
null
projects/cli/src/data/PatientGenerator.cpp
faaizT/core
488b357deece8dd4f7be318eefb49f6330be8239
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------------------- //- Copyright 2017 Applied Research Associates, 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 "PatientGenerator.h" #include <fstream> #include <iostream> #include <biogears/string/manipulation.h> namespace biogears { std::string ConvertBeatUnits(std::string unit){ if(unit == "bpm"){ return "1/min"; } return unit; } PatientGenerator::PatientGenerator(std::string path) : CSVToXMLConvertor(path, "Patients.csv") { } //----------------------------------------------------------------------------- PatientGenerator::~PatientGenerator() { } //----------------------------------------------------------------------------- //! //! \brief Saves xml file for each patient //! \return bool, true if no exceptions are thrown, false otherwise //! bool PatientGenerator::save() const { for (auto& patient : _patients) { xml_schema::namespace_infomap info; info[""].name = "uri:/mil/tatrc/physiology/datamodel"; info[""].schema = "BioGearsDataModel.xsd"; try { std::ofstream file; file.open("patients/" + patient.Name() + ".xml"); mil::tatrc::physiology::datamodel::Patient(file, patient, info); file.close(); std::cout << "Saved patients/" + patient.Name() + ".xml" << "\n"; } catch (std::exception e) { std::cout << e.what() << std::endl; } } return false; } //----------------------------------------------------------------------------- //! //! \brief Populates _patients with PatientData objects to be read into xml's //! \return bool //! bool PatientGenerator::parse() { namespace CDM = mil::tatrc::physiology::datamodel; bool rValue = true; read_csv(); for (auto lineItr = begin(); lineItr != end(); ++lineItr) { if ("Name" == lineItr->first) { for (auto name : lineItr->second) { CDM::PatientData data; data.Name(name); _patients.push_back(std::move(data)); } } else { for (size_t index = 0; index < _patients.size() && index < lineItr->second.size(); ++index) { process(lineItr->first, lineItr->second[index], _patients[index]); } } } return rValue; } //----------------------------------------------------------------------------- void PatientGenerator::print() const { for (auto& env : _patients) { std::cout << env; } } //----------------------------------------------------------------------------- //! //! \brief Checks first cell of csv row and sets corresponding data of PatientData object //! \param name first cell of row //! \param value another cell of the same row //! \param patient PatientData object //! \return //! bool PatientGenerator::process(const std::string& name, const std::string& value, mil::tatrc::physiology::datamodel::PatientData& patient) { using namespace mil::tatrc::physiology::datamodel; bool rValue = true; if (value.empty()) { } else if ("Name" == name) { patient.Name(value); } else if ("Sex" == name) { patient.Sex(value); } else if ("Age" == name) { size_t pos; PatientData::Age_type a_data; try { a_data.value(std::stod(value, &pos)); a_data.unit(biogears::trim(value.substr(pos))); patient.Age(a_data); } catch (std::exception e) { rValue = false; } } else if ("Weight" == name) { size_t pos; PatientData::Weight_type w_data; try { w_data.value(std::stod(value, &pos)); w_data.unit(biogears::trim(value.substr(pos))); patient.Weight(w_data); } catch (std::exception e) { rValue = false; } } else if ("Height" == name) { size_t pos; PatientData::Height_type h_data; try { h_data.value(std::stod(value, &pos)); h_data.unit(biogears::trim(value.substr(pos))); patient.Height(h_data); } catch (std::exception e) { rValue = false; } } else if ("BodyFatFraction" == name) { PatientData::BodyFatFraction_type bff_data; try { bff_data.value(std::stod(value)); patient.BodyFatFraction(bff_data); } catch (std::exception e) { rValue = false; } } else if ("RightLungFraction" == name) { PatientData::RightLungRatio_type rlr_data; try { rlr_data.value(std::stod(value)); patient.RightLungRatio(rlr_data); } catch (std::exception e) { rValue = false; } } else if ("SkinSurfaceArea" == name) { size_t pos; PatientData::SkinSurfaceArea_type ssa_data; try { ssa_data.value(std::stod(value, &pos)); ssa_data.unit(biogears::trim(value.substr(pos))); patient.SkinSurfaceArea(ssa_data); } catch (std::exception e) { rValue = false; } } else if ("BasalMetabolicRate" == name) { size_t pos; PatientData::BasalMetabolicRate_type bmr_data; try { bmr_data.value(std::stod(value, &pos)); bmr_data.unit(biogears::trim(value.substr(pos))); patient.BasalMetabolicRate(bmr_data); } catch (std::exception e) { rValue = false; } } else if ("BloodVolumeBaseline" == name) { size_t pos; PatientData::BloodVolumeBaseline_type bvb_data; try { bvb_data.value(std::stod(value, &pos)); bvb_data.unit(biogears::trim(value.substr(pos))); patient.BloodVolumeBaseline(bvb_data); } catch (std::exception e) { rValue = false; } } else if ("DiastolicArterialPressureBaseline" == name) { size_t pos; PatientData::DiastolicArterialPressureBaseline_type dapb_data; try { dapb_data.value(std::stod(value, &pos)); dapb_data.unit(biogears::trim(value.substr(pos))); patient.DiastolicArterialPressureBaseline(dapb_data); } catch (std::exception e) { rValue = false; } } else if ("HeartRateBaseline" == name) { size_t pos; PatientData::HeartRateBaseline_type hrb_data; try { hrb_data.value(std::stod(value, &pos)); hrb_data.unit(ConvertBeatUnits(biogears::trim(value.substr(pos)))); patient.HeartRateBaseline(hrb_data); } catch (std::exception e) { rValue = false; } } else if ("RespirationRateBaseline" == name) { size_t pos; PatientData::RespirationRateBaseline_type rrb_data; try { rrb_data.value(std::stod(value, &pos)); rrb_data.unit(ConvertBeatUnits(biogears::trim(value.substr(pos)))); patient.RespirationRateBaseline(rrb_data); } catch (std::exception e) { rValue = false; } } else if ("SystolicArterialPressureBaseline" == name) { size_t pos; PatientData::SystolicArterialPressureBaseline_type sapb_data; try { sapb_data.value(std::stod(value, &pos)); sapb_data.unit(biogears::trim(value.substr(pos))); patient.SystolicArterialPressureBaseline(sapb_data); } catch (std::exception e) { rValue = false; } } else if ("HeartRateMaximum" == name) { size_t pos; PatientData::HeartRateMaximum_type hrm_data; try { hrm_data.value(std::stod(value, &pos)); hrm_data.unit(ConvertBeatUnits(biogears::trim(value.substr(pos)))); patient.HeartRateMaximum(hrm_data); } catch (std::exception e) { rValue = false; } } else if ("HeartRateMinimum" == name) { size_t pos; PatientData::HeartRateMinimum_type hrm_data; try { hrm_data.value(std::stod(value, &pos)); hrm_data.unit(ConvertBeatUnits(biogears::trim(value.substr(pos)))); patient.HeartRateMinimum(hrm_data); } catch (std::exception e) { rValue = false; } } else if ("FunctionalResidualCapacity" == name) { size_t pos; PatientData::FunctionalResidualCapacity_type frc_data; try { frc_data.value(std::stod(value, &pos)); frc_data.unit(biogears::trim(value.substr(pos))); patient.FunctionalResidualCapacity(frc_data); } catch (std::exception e) { rValue = false; } } else if ("TotalLungCapacity" == name) { size_t pos; PatientData::TotalLungCapacity_type tlc_data; try { tlc_data.value(std::stod(value, &pos)); tlc_data.unit(biogears::trim(value.substr(pos))); patient.TotalLungCapacity(tlc_data); } catch (std::exception e) { rValue = false; } } else if ("AlveoliSurfaceArea" == name) { size_t pos; PatientData::AlveoliSurfaceArea_type asa_data; try { asa_data.value(std::stod(value, &pos)); asa_data.unit(biogears::trim(value.substr(pos))); patient.AlveoliSurfaceArea(asa_data); } catch (std::exception e) { rValue = false; } } else if ("ResidualVolume" == name) { size_t pos; PatientData::ResidualVolume_type rv_data; try { rv_data.value(std::stod(value, &pos)); rv_data.unit(biogears::trim(value.substr(pos))); patient.ResidualVolume(rv_data); } catch (std::exception e) { rValue = false; } } return rValue; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } //end namespace biogears
32.812925
138
0.595626
[ "object" ]
cda4da4ec6e8aeecae35a8efa44b2c73b0e7aed9
2,359
cpp
C++
Codeforces/1073E/dfs_dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Codeforces/1073E/dfs_dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Codeforces/1073E/dfs_dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <vector> #include <queue> #include <map> #include <set> #include <stack> #include <functional> #include <iterator> using namespace std; #define SIZE 30 #define STATE_SIZE 2048 typedef struct _State { long long int num, sum; } State; State dp[SIZE][STATE_SIZE]; long long int factorialArr[SIZE]; int cntArr[SIZE]; const long long int mod = 998244353; unsigned int k; void initFactorial() { factorialArr[0] = 1; for (int i = 1; i < SIZE; i++) factorialArr[i] = factorialArr[i - 1] * 10 % mod; } State dfs(int pos, unsigned int cntState, bool hasLim, bool frontZero) { unsigned int cntDiff = __builtin_popcount(cntState); if (cntDiff > k) return {0, 0}; if (pos < 0) return {(cntDiff > k ? 0 : 1), 0}; if (!hasLim && dp[pos][cntState].num != -1) return dp[pos][cntState]; State ans = {0, 0}; int lim = hasLim ? cntArr[pos] : 9; for (int i = 0; i <= lim; i++) { if (frontZero && i == 0) { State tmp = dfs(pos - 1, cntState, hasLim && i == lim, true); ans.num += tmp.num; ans.num %= mod; ans.sum += (tmp.sum + (i * factorialArr[pos] % mod) * tmp.num % mod) % mod; ans.sum %= mod; continue; } State tmp = dfs(pos - 1, (cntState | (1u << i)), hasLim && i == lim, false); ans.num += tmp.num; ans.num %= mod; ans.sum += (tmp.sum + (i * factorialArr[pos] % mod) * tmp.num % mod) % mod; ans.sum %= mod; } if (!hasLim) dp[pos][cntState] = ans; return ans; } long long int work(long long int cnt) { int len = 0; while (cnt) { cntArr[len++] = cnt % 10; cnt /= 10; } cntArr[len] = 0; return dfs(len - 1, 0, true, true).sum; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); initFactorial(); memset(dp, -1, sizeof(dp)); long long int leftPt, rightPt; cin >> leftPt >> rightPt >> k; cout << (work(rightPt) - work(leftPt - 1) + mod) % mod << endl; return 0; }
21.842593
88
0.522679
[ "vector" ]
cdac71981aafe759dd9668a00ebb68b04acb6bd8
4,832
cpp
C++
dev/Code/Sandbox/Plugins/CryDesigner/Tools/Modify/BooleanTool.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
1
2020-03-24T04:54:22.000Z
2020-03-24T04:54:22.000Z
dev/Code/Sandbox/Plugins/CryDesigner/Tools/Modify/BooleanTool.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
null
null
null
dev/Code/Sandbox/Plugins/CryDesigner/Tools/Modify/BooleanTool.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
2
2019-07-09T00:03:08.000Z
2020-03-24T04:54:27.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "BooleanTool.h" #include "Tools/DesignerTool.h" #include "Serialization/Decorators/EditorActionButton.h" #include "Core/BrushHelper.h" #include "Objects/DesignerObject.h" using Serialization::ActionButton; void BooleanTool::Enter() { BaseTool::Enter(); CSelectionGroup* pGroup = GetIEditor()->GetSelection(); int nDesignerObjectCount = 0; int nOtherObjectCount = 0; for (int i = 0, iObjectCount(pGroup->GetCount()); i < iObjectCount; ++i) { CBaseObject* pObject = pGroup->GetObject(i); if (pObject->GetType() == OBJTYPE_SOLID) { ++nDesignerObjectCount; } else { ++nOtherObjectCount; } } if (nOtherObjectCount > 0 || nDesignerObjectCount < 2) { if (nOtherObjectCount > 0) { CD::MessageBox("Warning", "Only designer objects should be selected to use this tool"); } else if (nDesignerObjectCount < 2) { CD::MessageBox("Warning", "At least two designer objects should be selected to use this tool"); } CD::GetDesigner()->SwitchTool(CD::eDesigner_Object); } } void BooleanTool::BooleanOperation(CD::EBooleanOperationEnum booleanType) { CSelectionGroup* pSelection = GetIEditor()->GetObjectManager()->GetSelection(); std::vector< _smart_ptr<DesignerObject> > designerObjList; for (int i = 0, iSelectionCount(pSelection->GetCount()); i < iSelectionCount; ++i) { CBaseObject* pObj = pSelection->GetObject(iSelectionCount - i - 1); if (!qobject_cast<DesignerObject*>(pObj)) { continue; } designerObjList.push_back((DesignerObject*)pObj); } if (designerObjList.size() < 2) { CD::MessageBox("Warning", "More than 2 designer objects should be selected to be operated."); return; } QString undoMsg("Designer : Boolean."); if (booleanType == CD::eBOE_Union) { undoMsg += "Union"; } else if (booleanType == CD::eBOE_Intersection) { undoMsg += "Intersection"; } else if (booleanType == CD::eBOE_Difference) { undoMsg += "Difference"; } CUndo undo(undoMsg.toLatin1().data()); designerObjList[0]->StoreUndo(undoMsg.toLatin1().data()); CD::ResetXForm(designerObjList[0], designerObjList[0]->GetModel()); CD::GetDesigner()->SetBaseObject(NULL); for (int i = 1, iDesignerObjCount(designerObjList.size()); i < iDesignerObjCount; ++i) { BrushVec3 offset = designerObjList[i]->GetWorldTM().GetTranslation() - designerObjList[0]->GetWorldTM().GetTranslation(); Matrix34 targetTM(designerObjList[i]->GetWorldTM()); targetTM.SetTranslation(offset); designerObjList[i]->StoreUndo(undoMsg.toLatin1().data()); designerObjList[i]->GetModel()->Transform(targetTM); if (booleanType == CD::eBOE_Union) { designerObjList[0]->GetModel()->Union(designerObjList[i]->GetModel()); } else if (booleanType == CD::eBOE_Difference) { designerObjList[0]->GetModel()->Subtract(designerObjList[i]->GetModel()); } else if (booleanType == CD::eBOE_Intersection) { designerObjList[0]->GetModel()->Intersect(designerObjList[i]->GetModel()); } GetIEditor()->DeleteObject(designerObjList[i]); } CD::UpdateAll(designerObjList[0]->MainContext()); GetIEditor()->SelectObject(designerObjList[0]); DesignerTool* pDesignerTool = CD::GetDesigner(); if (pDesignerTool) { pDesignerTool->SetBaseObject(designerObjList[0]); pDesignerTool->SwitchTool(CD::eDesigner_Object); } } void BooleanTool::Serialize(Serialization::IArchive& ar) { ar(ActionButton([this] {Union(); }), "Union", "Union"); ar(ActionButton([this] {Subtract(); }), "Subtract", "Subtract"); ar(ActionButton([this] {Intersection(); }), "Intersection", "Intersection"); } #include "UIs/PropertyTreePanel.h" REGISTER_DESIGNER_TOOL_WITH_PANEL(CD::eDesigner_Boolean, CD::eToolGroup_Modify, "Boolean", BooleanTool, PropertyTreePanel<BooleanTool>)
33.324138
135
0.647351
[ "vector", "transform" ]
cdaeaa4c034a2aa7e1d8329aedbf105495279558
12,507
cpp
C++
linalg/tensor_davidson.cpp
ClarkResearchGroup/tensor-tools
25fe4553991d2680b43301aef1960e4c20f1e146
[ "Apache-2.0" ]
8
2020-07-14T01:55:51.000Z
2022-02-12T14:06:59.000Z
linalg/tensor_davidson.cpp
ClarkResearchGroup/tensor-tools
25fe4553991d2680b43301aef1960e4c20f1e146
[ "Apache-2.0" ]
1
2020-07-31T02:43:25.000Z
2020-08-08T16:18:36.000Z
linalg/tensor_davidson.cpp
ClarkResearchGroup/tensor-tools
25fe4553991d2680b43301aef1960e4c20f1e146
[ "Apache-2.0" ]
1
2020-12-01T03:40:26.000Z
2020-12-01T03:40:26.000Z
/* * Copyright 2020 Ryan Levy, Xiongjie Yu, and Bryan K. Clark * Portions copyright 2018 The Simons Foundation, Inc., with modifications * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DENSE_TENSOR_BASED_DAVIDSON_SOLVER #define DENSE_TENSOR_BASED_DAVIDSON_SOLVER #include "tensor_davidson.h" template <typename T> void elemWiseDivide(dtensor<T>& A, double theta, dtensor<T>& B){ assert(A._initted && B._initted); assert(A.size == B.size); /*for (unsigned i = 0; i < A.size; i++) { if( B._T.data()[i]!=T(theta) ) A._T.data()[i] = A._T.data()[i]/(B._T.data()[i] - theta); }*/ unordered_map<string,char> charMap; auto indA = indicesToChar(A.idx_set,charMap); auto indB = indicesToChar(B.idx_set,charMap); CTF::Transform<T,T>([theta](T b, T& a){ if(b!=T(theta)) a/=(b-theta); })(B.__T[indB.c_str()],A.__T[indA.c_str()]); } template void elemWiseDivide(dtensor<double>& A, double theta, dtensor<double>& B); template void elemWiseDivide(dtensor< std::complex<double> >& A, double theta, dtensor< std::complex<double> >& B); template <typename T> void elemWiseDivide(qtensor<T>& A, double theta, qtensor<T>& B){ assert(A._initted && B._initted); assert(A.rank == B.rank); unordered_map<string,char> charMap; auto indA = indicesToChar(A.idx_set,charMap); auto indB = indicesToChar(B.idx_set,charMap); for (auto i = A.block_id_by_qn_str.begin(); i != A.block_id_by_qn_str.end(); ++i){ string qn_str = i->first; unsigned A_id = i->second; if(B.block_id_by_qn_str.find(qn_str)!=B.block_id_by_qn_str.end()){ unsigned B_id = B.block_id_by_qn_str.at(qn_str); assert(A._block[A_id].get_tot_size(false) == B._block[B_id].get_tot_size(false)); CTF::Transform<T,T>([theta](T b, T& a){ if(b!=T(theta)) a/=(b-theta); })(B._block[B_id][indB.c_str()],A._block[A_id][indA.c_str()]); } } } template void elemWiseDivide(qtensor<double>& A, double theta, qtensor<double>& B); template void elemWiseDivide(qtensor< std::complex<double> >& A, double theta, qtensor< std::complex<double> >& B); template <typename T> void elemWiseDivide(qstensor<T>& A, double theta, qstensor<T>& B){ assert(A._initted && B._initted); assert(A.rank == B.rank); unordered_map<string,char> charMap; auto indA = indicesToChar(A.idx_set,charMap); auto indB = indicesToChar(B.idx_set,charMap); CTF::Transform<T,T>([theta](T b, T& a){ if(b!=T(theta)) a/=(b-theta); })(B._T[indB.c_str()],A._T[indA.c_str()]); } template void elemWiseDivide(qstensor<double>& A, double theta, qstensor<double>& B); template void elemWiseDivide(qstensor< std::complex<double> >& A, double theta, qstensor< std::complex<double> >& B); template <typename T, template <typename> class BigTensorType, template <typename> class TensorType> double tensor_davidson(BigTensorType<T>& A, TensorType<T>& x, int m, int max_restart, double tol, char mode){ assert(m>=1 && max_restart>=1 && tol>0); TensorType<T> u, ua, r; TensorType<T>* v = new TensorType<T> [m]; TensorType<T>* va = new TensorType<T> [m]; TensorType<T> D = std::move(A.diagonal()); // D.dag(); // uint_vec perm; // find_index_permutation(D.idx_set, x.idx_set, perm); // D.permute(perm); T* M = new T [(m+1)*(m+1)]; T* Mnext = new T [(m+1)*(m+1)]; double* evals = new double [m]; double eval = 0; double r_norm = 0.0; double u_norm = 0.0; // Restarded Jacobi-Davidson for (int i = 0; i < max_restart; i++) { // Restart for (int j = 0; j < m; j++) { // Davidson method v[j] = x; // (2) Orthogonalize v for (int k = j-1; k >= 0; k--) { T alpha = v[k].inner_product(v[j]); v[j].add(v[k], -alpha); } v[j].normalize(); // (3) Get va = (A*v)^{\dage} /*for (int k = 0; k < j+1; k++) { va[k] = std::move(A.product(v[k])); }*/ va[j] = std::move(A.product(v[j])); // (4) Update Hamiltonian projected to subspace /*for (int k = 0; k < j+1; k++) { for (int l = 0; l <= k; l++) { M[l + k*(j+1)] = va[l].inner_product(v[k]); M[k + l*(j+1)] = cconj(M[l + k*(j+1)]); } }*/ int l = j; for (int k = 0; k < j+1; k++) { M[l + k*(j+1)] = va[l].inner_product(v[k]); M[k + l*(j+1)] = cconj(M[l + k*(j+1)]); } for(int k =0;k<j+1;k++){ for(int l=0;l<=k;l++){ Mnext[l + k*(j+2)] = M[l + k*(j+1)]; Mnext[k + l*(j+2)] = M[k + l*(j+1)]; } } if(j>0){ // (5) Diagonalize M DIAG(j+1, M, evals); // (6) Get the Ritz vector u with smallest/largest eigenvalue if(mode == 'S'){ eval = evals[0]; for (int k = 0; k < j+1; k++) { if(k==0){ u = v[k]; u *= M[0]; ua = va[k]; ua *= M[0]; }else{ u.add(v[k], M[k]); ua.add(va[k], M[k]); } } }else if(mode == 'L'){ eval = evals[j]; for (int k = 0; k < j+1; k++) { if(k==0){ u = v[k]; u *= M[j*(j+1)]; ua = va[k]; ua *= M[j*(j+1)]; }else{ u.add(v[k], M[k+j*(j+1)]); ua.add(va[k], M[k+j*(j+1)]); } } } }else{ eval = std::real(M[0]); u = v[0]; ua = va[0]; } // (8) Get residue vector r = ua - evals[0] * u // u_norm = u.norm(); ua.add(u, -eval); r = ua; r_norm = r.norm(); // (9) Expand search space if(j<m-1){ x = r; elemWiseDivide(x, eval, D); x.normalize(); } // std::cout << "Residue norm = " << r_norm << '\n'; swap(M,Mnext); } x = u; if(r_norm<tol) break; } delete [] v; delete [] va; delete [] evals; delete [] M; return eval; } template double tensor_davidson(big_dtensor<double>& A, dtensor<double>& x, int m, int max_restart, double tol, char mode); template double tensor_davidson(big_dtensor< std::complex<double> >& A, dtensor< std::complex<double> >& x, int m, int max_restart, double tol, char mode); template double tensor_davidson(big_qtensor<double>& A, qtensor<double>& x, int m, int max_restart, double tol, char mode); template double tensor_davidson(big_qtensor< std::complex<double> >& A, qtensor< std::complex<double> >& x, int m, int max_restart, double tol, char mode); template double tensor_davidson(big_qstensor<double>& A, qstensor<double>& x, int m, int max_restart, double tol, char mode); template double tensor_davidson(big_qstensor< std::complex<double> >& A, qstensor< std::complex<double> >& x, int m, int max_restart, double tol, char mode); template <typename T, template <typename> class BigTensorType, template <typename> class TensorType> double tensor_davidsonIT(BigTensorType<T>& A, TensorType<T>& x, int m, int max_restart, double tol, char mode){ assert(m>=1 && max_restart>=1 && tol>0); auto x_norm = x.norm(); x *= 1./x_norm; int maxsize = A.size(); int actual_maxiter = std::min(max_restart,maxsize-1); TensorType<T>* v = new TensorType<T> [actual_maxiter+2]; TensorType<T>* va = new TensorType<T> [actual_maxiter+2]; T* M = new T [(actual_maxiter+2)*(actual_maxiter+2)]; T* Mnext = new T [(actual_maxiter+2)*(actual_maxiter+2)]; double* evals = new double [(actual_maxiter+2)]; double* evecs = new double [(actual_maxiter+2)*(actual_maxiter+2)]; double eval = 0; double qnorm = 0.; double last_lambda = 1000.; double Approx0 = 1e-12; v[0] = x; va[0] = std::move(A.product(v[0])); double initEn = std::real(va[0].inner_product(v[0])); //TODO check for cmplx size_t t = 0; size_t iter = 0; double lambda = 0.; for(int ii=0;ii<actual_maxiter+1;ii++){ //diag v*A*v //compute residual q int ni = ii+1; auto& q = v[ni]; //Step A (or I) of Davidson (1975) if(ii==0){ lambda = initEn; for(int mi=0;mi<ni;mi++){ //M is (ni,ni) M[mi] = lambda; Mnext[mi] = lambda; } q = va[0]; q.add(v[0],-lambda); } else{ /*for(int mi=0;mi<ni*ni;mi++) M[mi] *= -1;*/ //copy M->Mtemp since it gets destroyed //assume that we'll add a row/column for(int mi =0;mi<ni;mi++){ for(int mj=0;mj<=mi;mj++){ Mnext[mj + mi*(ni+1)] = M[mj + mi*(ni)]; Mnext[mi + mj*(ni+1)] = M[mi + mj*(ni)]; } } DIAG(ni,M,evals); /*for(int mi=0;mi<ni*ni;mi++) M[mi] *= -1; for(int k=0;k<ni;k++) evals[k]*=-1;*/ lambda = evals[0]; //perr<<"L="<<lambda<<endl; x = v[0]; x*=M[0];//x*=evals[0]; q = va[0]; q*=M[0];//q*=evals[0]; for(int k=1;k<=ii;k++){ x.add(v[k],M[k]); q.add(va[k],M[k]); } //Step B of Davidson (1975) //Calculate residual q q.add(x,-lambda); //this tries to stabilize the sign of a wave function if(std::real(M[0]) < 0.){ x *= -1.; q *= -1.; } } //Step C of Davidson (1975) //Check convergence qnorm = q.norm(); bool converged = (qnorm < tol && std::abs(lambda-last_lambda) < tol) || qnorm < std::max(Approx0,tol*1e-3); last_lambda = lambda; if((qnorm < 1e-20) || (converged && ii >= 1) || (ii==actual_maxiter)) goto done; //Step D of Davidson (1975) //Apply Davidson preconditioner //TODO //Step E and F of Davidson (1975) //Do Gram-Schmidt on d (Npass times) //to include it in the subbasis int Npass = 1; auto Vq = std::vector<T>(ni); int pass = 1; int tot_pass = 0; while(pass <=Npass){ ++tot_pass; for(int k=0;k<ni;k++){ Vq[k] = q.contract(v[k]); //includes dag } for(int k=0;k<ni;k++){ q.add(v[k],-Vq[k]); } auto qnrm = q.norm(); if(qnrm<1e-10){ //assert(1==2); //Orthogonalization failure, //try randomizing //perr<<"Randomizing"<<endl; q = v[ni-1]; q.setRandom(); qnrm = q.norm(); --pass; if(ni >= maxsize){ //Not be possible to orthogonalize if //max size of q (vecSize after randomize) //is size of current basis goto done; } if(tot_pass > Npass*3){ goto done; } } q *= 1./qnrm; ++pass; } //Step G of Davidson (1975) //Expand AV and M //for next step va[ni] = std::move(A.product(v[ni])); //Step H of Davidson (1975) //Add new row and column to M swap(Mnext,M); //for(int mi=0;mi<ni*ni;mi++) perr<<M[mi]<<" ";perr<<endl; int l = ni; for (int k = 0; k < ni+1; k++) { M[l + k*(ni+1)] = va[l].inner_product(v[k]); M[k + l*(ni+1)] = cconj(M[l + k*(ni+1)]); } //for(int mi=0;mi<(ni+1)*(ni+1);mi++) perr<<M[mi]<<" ";perr<<endl; } //(ii) done: x.normalize(); delete [] v; delete [] va; delete [] evals; delete [] M; delete [] Mnext; return lambda; } template double tensor_davidsonIT(big_dtensor<double>& A, dtensor<double>& x, int m, int max_restart, double tol, char mode); template double tensor_davidsonIT(big_dtensor< std::complex<double> >& A, dtensor< std::complex<double> >& x, int m, int max_restart, double tol, char mode); template double tensor_davidsonIT(big_qtensor<double>& A, qtensor<double>& x, int m, int max_restart, double tol, char mode); template double tensor_davidsonIT(big_qtensor< std::complex<double> >& A, qtensor< std::complex<double> >& x, int m, int max_restart, double tol, char mode); template double tensor_davidsonIT(big_qstensor<double>& A, qstensor<double>& x, int m, int max_restart, double tol, char mode); template double tensor_davidsonIT(big_qstensor< std::complex<double> >& A, qstensor< std::complex<double> >& x, int m, int max_restart, double tol, char mode); #endif
35.132022
159
0.565843
[ "vector", "transform" ]
cdb1f8e26fe07c4b1a6d8eaa850508fd994f1c26
474
hpp
C++
include/mango/core/crc32.hpp
diablodale/mango
2efce1d8e7c97dd89ca1e19634fe2014bf289824
[ "Zlib" ]
null
null
null
include/mango/core/crc32.hpp
diablodale/mango
2efce1d8e7c97dd89ca1e19634fe2014bf289824
[ "Zlib" ]
null
null
null
include/mango/core/crc32.hpp
diablodale/mango
2efce1d8e7c97dd89ca1e19634fe2014bf289824
[ "Zlib" ]
null
null
null
/* MANGO Multimedia Development Platform Copyright (C) 2012-2020 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include "configure.hpp" #include "memory.hpp" namespace mango { // CRC32 u32 crc32(u32 crc, ConstMemory memory); u32 crc32_combine(u32 crc0, u32 crc1, size_t length1); // Castagnoli CRC32 u32 crc32c(u32 crc, ConstMemory memory); u32 crc32c_combine(u32 crc0, u32 crc1, size_t length1); } // namespace mango
21.545455
76
0.704641
[ "3d" ]
cdb21651b5ce428d7e391c8ac015868dfe9c8652
4,059
cpp
C++
examples/read_image.cpp
rcodin/cnn_code
c6e1ce7e89e070518e244c241e9d899b6cef0208
[ "MIT" ]
null
null
null
examples/read_image.cpp
rcodin/cnn_code
c6e1ce7e89e070518e244c241e9d899b6cef0208
[ "MIT" ]
null
null
null
examples/read_image.cpp
rcodin/cnn_code
c6e1ce7e89e070518e244c241e9d899b6cef0208
[ "MIT" ]
null
null
null
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <vector> #include <opencv2/opencv.hpp> #include <input.hpp> using namespace cv; using namespace std; // -i input // -w weights int read_config(int argc, char** argv, string &weight_file, string &image_file) { if (argc != 5) { cerr<<"Error: invalid options"<<endl; return -1; } for (int i = 1; i < argc; i += 2) { if (String("-i").compare(argv[i])) { image_file = argv[i + 1]; } else if (String("-w").compare(argv[i])) { weight_file = argv[i + 1]; } else { return -1; } } return 0; } int main(int argc, char** argv) { int err; string weight_file; string image_file; err = read_config(argc, argv, weight_file, image_file); if (err) { return -1; } float *input; Image_cfg input_cfg = {224, 224}; input = (float *)malloc(input_cfg.rows * input_cfg.cols * 3); err = read_image_rgb(weight_file, input_cfg, input); if (err) { return -1; } size_t bytes = sizeof(float); int alignment = bytes * 8; //create input //conv1->relu->pool //Conv11 Conv_conf conv11_conf = {3, 3}; Data_conf input11_conf = {224, 224, 3}; Data_conf output11_conf = {224, 224, 64}; //conv12 Conv_conf conv12_conf = {3, 3}; Data_conf input12_conf = {224, 224, 64}; Data_conf output12_conf = {224, 224, 64}; //Pool1 Pool_conf pool1_conf = {2, 2}; Data_conf input13_conf = {224, 224, 64}; Data_conf output13_conf = {112, 112, 64}; //Conv21 Conv_conf conv21_conf = {3, 3}; Data_conf input21_conf = {112, 112, 64}; Data_conf output21_conf = {112, 112, 128}; //Conv22 Conv_conf conv22_conf = {3, 3}; Data_conf input22_conf = {112, 112, 128}; Data_conf output22_conf = {112, 112, 128}; //Pool2 Pool_conf pool2_conf = {2, 2}; Data_conf input23_conf = {112, 112, 128}; Data_conf output23_conf = {56, 56, 128}; //Conv31 Conv_conf conv31_conf = {3, 3}; Data_conf input31_conf = {56, 56, 128}; Data_conf output31_conf = {56, 56, 256}; //Conv32 Conv_conf conv32_conf = {3, 3}; Data_conf input32_conf = {56, 56, 256}; Data_conf output32_conf = {56, 56, 256}; //Conv33 Conv_conf conv33_conf = {3, 3}; Data_conf input33_conf = {56, 56, 256}; Data_conf output33_conf = {56, 56, 256}; //Pool3 Pool_conf pool3_conf = {2, 2}; Data_conf input34_conf = {56, 56, 256}; Data_conf output34_conf = {28, 28, 256}; //Conv41 Conv_conf conv41_conf = {3, 3}; Data_conf input41_conf = {28, 28, 256}; Data_conf output41_conf = {28, 28, 512}; //Conv42 Conv_conf conv42_conf = {3, 3}; Data_conf input42_conf = {28, 28, 512}; Data_conf output42_conf = {28, 28, 512}; //Conv43 Conv_conf conv43_conf = {3, 3}; Data_conf input43_conf = {28, 28, 512}; Data_conf output43_conf = {28, 28, 512}; //Pool4 Pool_conf pool4_conf = {2, 2}; Data_conf input44_conf = {28, 28, 512}; Data_conf output44_conf = {14, 14, 512}; //Conv51 Conv_conf conv51_conf = {3, 3}; Data_conf input51_conf = {14, 14, 512}; Data_conf output51_conf = {14, 14, 512}; //Conv52 Conv_conf conv52_conf = {3, 3}; Data_conf input52_conf = {14, 14, 512}; Data_conf output52_conf = {14, 14, 512}; //Conv53 Conv_conf conv53_conf = {3, 3}; Data_conf input53_conf = {14, 14, 512}; Data_conf output53_conf = {14, 14, 512}; //Pool5 Pool_conf pool5_conf = {3, 3}; Data_conf input54_conf = {14, 14, 512}; Data_conf output54_conf = {7, 7, 512}; //fc1 flattening Data_conf input6_conf = {7, 7, 512}; int output6_conf = 4096; //fc2 int input7_conf = 4096; int output7_conf = 4096; //fc3_softmax int input8_conf = 4096; int output8_conf = 1000; }
24.160714
81
0.592018
[ "vector" ]
cdb724ea17f71bc53e7b8f0879d496396a0fc24f
4,426
cpp
C++
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-iam/source/model/Statement.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-iam/source/model/Statement.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-iam/source/model/Statement.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/iam/model/Statement.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace IAM { namespace Model { Statement::Statement() : m_sourcePolicyIdHasBeenSet(false), m_sourcePolicyTypeHasBeenSet(false), m_startPositionHasBeenSet(false), m_endPositionHasBeenSet(false) { } Statement::Statement(const XmlNode& xmlNode) : m_sourcePolicyIdHasBeenSet(false), m_sourcePolicyTypeHasBeenSet(false), m_startPositionHasBeenSet(false), m_endPositionHasBeenSet(false) { *this = xmlNode; } Statement& Statement::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode sourcePolicyIdNode = resultNode.FirstChild("SourcePolicyId"); if(!sourcePolicyIdNode.IsNull()) { m_sourcePolicyId = StringUtils::Trim(sourcePolicyIdNode.GetText().c_str()); m_sourcePolicyIdHasBeenSet = true; } XmlNode sourcePolicyTypeNode = resultNode.FirstChild("SourcePolicyType"); if(!sourcePolicyTypeNode.IsNull()) { m_sourcePolicyType = PolicySourceTypeMapper::GetPolicySourceTypeForName(StringUtils::Trim(sourcePolicyTypeNode.GetText().c_str()).c_str()); m_sourcePolicyTypeHasBeenSet = true; } XmlNode startPositionNode = resultNode.FirstChild("StartPosition"); if(!startPositionNode.IsNull()) { m_startPosition = startPositionNode; m_startPositionHasBeenSet = true; } XmlNode endPositionNode = resultNode.FirstChild("EndPosition"); if(!endPositionNode.IsNull()) { m_endPosition = endPositionNode; m_endPositionHasBeenSet = true; } } return *this; } void Statement::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_sourcePolicyIdHasBeenSet) { oStream << location << index << locationValue << ".SourcePolicyId=" << StringUtils::URLEncode(m_sourcePolicyId.c_str()) << "&"; } if(m_sourcePolicyTypeHasBeenSet) { oStream << location << index << locationValue << ".SourcePolicyType=" << PolicySourceTypeMapper::GetNameForPolicySourceType(m_sourcePolicyType) << "&"; } if(m_startPositionHasBeenSet) { Aws::StringStream startPositionLocationAndMemberSs; startPositionLocationAndMemberSs << location << index << locationValue << ".StartPosition"; m_startPosition.OutputToStream(oStream, startPositionLocationAndMemberSs.str().c_str()); } if(m_endPositionHasBeenSet) { Aws::StringStream endPositionLocationAndMemberSs; endPositionLocationAndMemberSs << location << index << locationValue << ".EndPosition"; m_endPosition.OutputToStream(oStream, endPositionLocationAndMemberSs.str().c_str()); } } void Statement::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_sourcePolicyIdHasBeenSet) { oStream << location << ".SourcePolicyId=" << StringUtils::URLEncode(m_sourcePolicyId.c_str()) << "&"; } if(m_sourcePolicyTypeHasBeenSet) { oStream << location << ".SourcePolicyType=" << PolicySourceTypeMapper::GetNameForPolicySourceType(m_sourcePolicyType) << "&"; } if(m_startPositionHasBeenSet) { Aws::String startPositionLocationAndMember(location); startPositionLocationAndMember += ".StartPosition"; m_startPosition.OutputToStream(oStream, startPositionLocationAndMember.c_str()); } if(m_endPositionHasBeenSet) { Aws::String endPositionLocationAndMember(location); endPositionLocationAndMember += ".EndPosition"; m_endPosition.OutputToStream(oStream, endPositionLocationAndMember.c_str()); } } } // namespace Model } // namespace IAM } // namespace Aws
31.841727
157
0.734297
[ "model" ]
cdba0f7a58b5add19a274a2504df0c04d52e314c
2,018
cpp
C++
Cpp/UVa/MST/908.cpp
kchevali/OnlineJudge
c1d1894078fa45eef05c8785aba29758d9adf0c6
[ "MIT" ]
null
null
null
Cpp/UVa/MST/908.cpp
kchevali/OnlineJudge
c1d1894078fa45eef05c8785aba29758d9adf0c6
[ "MIT" ]
null
null
null
Cpp/UVa/MST/908.cpp
kchevali/OnlineJudge
c1d1894078fa45eef05c8785aba29758d9adf0c6
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <cmath> #include <functional> #include <queue> #include <fstream> using namespace std; //took a graph and return the MST, or don't return anything if just need the min cost int mst(vector<vector<int>> adj, vector<tuple<int, int, int>> edge) { int weight = 0; vector<bool> visited(adj.size(), false); visited[0] = true; priority_queue<tuple<int, int, int>> pq; for (auto x : adj[0]) pq.push(edge[x]); while (!pq.empty()) { tuple<int, int, int> t = pq.top(); pq.pop(); int w = abs(get<0>(t)); int a = get<1>(t), b = get<2>(t); if (!visited[b]) { weight += w; visited[b] = true; for (auto x : adj[b]) { tuple<int, int, int> n = edge[x]; if (!visited[get<2>(n)]) pq.push(n); } } } return weight; //return MST } int main() { int vertex; bool first = true; while (cin >> vertex) { if (first) first = false; else cout << endl; int c = 0; for (int i = vertex; i-- > 1;) { int a, b, w; cin >> a >> b >> w; c += w; } cout << c << endl; int index = 0; vector<vector<int>> adj(vertex, vector<int>()); vector<tuple<int, int, int>> edge; for (int i = 2; i-- > 0;) { int count; for (cin >> count; count-- > 0;) { int a, b, w; cin >> a >> b >> w; a--; b--; edge.push_back(make_tuple(-w, a, b)); adj[a].push_back(index++); edge.push_back(make_tuple(-w, b, a)); adj[b].push_back(index++); } } cout << mst(adj, edge) << endl; cin.ignore(); cin.ignore(); } return 0; } /* */
20.804124
85
0.418731
[ "vector" ]
cdbcb7a58237e73697befab7312f6cde06cb1616
22,497
cpp
C++
src/technique/fur_simulation/fur_simulation_opengl.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
2
2019-04-02T14:19:01.000Z
2021-05-27T13:42:20.000Z
src/technique/fur_simulation/fur_simulation_opengl.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
4
2016-11-05T14:17:14.000Z
2017-03-30T15:03:37.000Z
src/technique/fur_simulation/fur_simulation_opengl.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
null
null
null
#include "technique/fur_simulation/fur_simulation_opengl.h" #include <cassert> #include <limits> #include <utility> #include "cg/base/container.h" #include "cg/data/image.h" #include "cg/data/shader.h" using namespace cg; using cg::data::image_2d; using cg::data::pixel_format; using cg::sys::Key; namespace fur_simulation { // ----- Geometry_buffers ----- Geometry_buffers::Geometry_buffers(float strand_lenght, const char* geometry_filename) { Model_geometry_data geometry(strand_lenght, geometry_filename); _tbo_position_buffer = Texture_buffer<Buffer_immut>(GL_RGB32F, 0, geometry.position_buffer); _tbo_physics_buffer_0 = Texture_buffer<Buffer_immut>(GL_RGB32F, 0, geometry.simulation_buffer); _tbo_physics_buffer_1 = Texture_buffer<Buffer_immut>(GL_RGB32F, 0, byte_count(geometry.simulation_buffer), nullptr); _model_attribs_buffer = Buffer_immut(0, geometry.model_attribs_buffer); _index_buffer = Buffer_immut(0, geometry.index_buffer); _meshes = std::move(geometry.meshes); for (const auto& mesh : _meshes) _vertex_count += mesh.vertex_count; assert(_vertex_count <= size_t(std::numeric_limits<GLsizei>::max())); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, _tbo_physics_buffer_1.buffer().id()); init_physics_simulation_0_vao(geometry.layout); init_physics_simulation_1_vao(geometry.layout); init_render_0_vao(geometry.layout); init_render_1_vao(geometry.layout); // debug_slot_buffer settings _tbo_debug_slot = Texture_buffer<Buffer_immut>(GL_RGBA32F, 0, _vertex_count * 4 * sizeof(float), nullptr); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 1, _tbo_debug_slot.buffer().id()); } void Geometry_buffers::init_physics_simulation_0_vao(const Model_geometry_layout& layout) { constexpr GLuint position_buffer_binding_index = 0; constexpr GLuint simulation_buffer_binding_index = 1; // position_buffer glVertexArrayVertexBuffer(_physics_0_vao.id(), position_buffer_binding_index, _tbo_position_buffer.buffer().id(), 0, GLsizei(layout.position_buffer_byte_stride)); // p_base glEnableVertexArrayAttrib(_physics_0_vao.id(), 0); glVertexArrayAttribBinding(_physics_0_vao.id(), 0, position_buffer_binding_index); glVertexArrayAttribFormat(_physics_0_vao.id(), 0, 3, GL_FLOAT, false, GLsizei(layout.p_base_byte_offset)); // p_rest glEnableVertexArrayAttrib(_physics_0_vao.id(), 1); glVertexArrayAttribBinding(_physics_0_vao.id(), 1, position_buffer_binding_index); glVertexArrayAttribFormat(_physics_0_vao.id(), 1, 3, GL_FLOAT, false, GLsizei(layout.p_rest_byte_offset)); // simulation_buffer glVertexArrayVertexBuffer(_physics_0_vao.id(), simulation_buffer_binding_index, _tbo_physics_buffer_0.buffer().id(), 0, GLsizei(layout.simulation_buffer_byte_stride)); // p_curr glEnableVertexArrayAttrib(_physics_0_vao.id(), 2); glVertexArrayAttribBinding(_physics_0_vao.id(), 2, simulation_buffer_binding_index); glVertexArrayAttribFormat(_physics_0_vao.id(), 2, 3, GL_FLOAT, false, GLsizei(layout.p_curr_byte_offset)); // velocity glEnableVertexArrayAttrib(_physics_0_vao.id(), 3); glVertexArrayAttribBinding(_physics_0_vao.id(), 3, simulation_buffer_binding_index); glVertexArrayAttribFormat(_physics_0_vao.id(), 3, 3, GL_FLOAT, false, GLsizei(layout.velocity_byte_offset)); } void Geometry_buffers::init_physics_simulation_1_vao(const Model_geometry_layout& layout) { constexpr GLuint position_buffer_binding_index = 0; constexpr GLuint simulation_buffer_binding_index = 1; // position_buffer glVertexArrayVertexBuffer(_physics_1_vao.id(), position_buffer_binding_index, _tbo_position_buffer.buffer().id(), 0, GLsizei(layout.position_buffer_byte_stride)); // p_base glEnableVertexArrayAttrib(_physics_1_vao.id(), 0); glVertexArrayAttribBinding(_physics_1_vao.id(), 0, position_buffer_binding_index); glVertexArrayAttribFormat(_physics_1_vao.id(), 0, 3, GL_FLOAT, false, GLsizei(layout.p_base_byte_offset)); // p_rest glEnableVertexArrayAttrib(_physics_1_vao.id(), 1); glVertexArrayAttribBinding(_physics_1_vao.id(), 1, position_buffer_binding_index); glVertexArrayAttribFormat(_physics_1_vao.id(), 1, 3, GL_FLOAT, false, GLsizei(layout.p_rest_byte_offset)); // simulation_buffer glVertexArrayVertexBuffer(_physics_1_vao.id(), simulation_buffer_binding_index, _tbo_physics_buffer_1.buffer().id(), 0, GLsizei(layout.simulation_buffer_byte_stride)); // p_curr glEnableVertexArrayAttrib(_physics_1_vao.id(), 2); glVertexArrayAttribBinding(_physics_1_vao.id(), 2, simulation_buffer_binding_index); glVertexArrayAttribFormat(_physics_1_vao.id(), 2, 3, GL_FLOAT, false, GLsizei(layout.p_curr_byte_offset)); // velocity glEnableVertexArrayAttrib(_physics_1_vao.id(), 3); glVertexArrayAttribBinding(_physics_1_vao.id(), 3, simulation_buffer_binding_index); glVertexArrayAttribFormat(_physics_1_vao.id(), 3, 3, GL_FLOAT, false, GLsizei(layout.velocity_byte_offset)); } void Geometry_buffers::init_render_0_vao(const Model_geometry_layout& layout) { constexpr GLuint position_buffer_binding_index = 0; constexpr GLuint simulation_buffer_binding_index = 1; constexpr GLuint model_attribs_buffer_binding_index = 2; // position_buffer glVertexArrayVertexBuffer(_render_vao_0.id(), position_buffer_binding_index, _tbo_position_buffer.buffer().id(), 0, GLsizei(layout.position_buffer_byte_stride)); // p_base glEnableVertexArrayAttrib(_render_vao_0.id(), 0); glVertexArrayAttribBinding(_render_vao_0.id(), 0, position_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_0.id(), 0, 3, GL_FLOAT, false, GLuint(layout.p_base_byte_offset)); // p_rest glEnableVertexArrayAttrib(_render_vao_0.id(), 1); glVertexArrayAttribBinding(_render_vao_0.id(), 1, position_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_0.id(), 1, 3, GL_FLOAT, false, GLuint(layout.p_rest_byte_offset)); // simulation_buffer glVertexArrayVertexBuffer(_render_vao_0.id(), simulation_buffer_binding_index, _tbo_physics_buffer_0.buffer().id(), 0, GLsizei(layout.simulation_buffer_byte_stride)); // p_curr glEnableVertexArrayAttrib(_render_vao_0.id(), 2); glVertexArrayAttribBinding(_render_vao_0.id(), 2, simulation_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_0.id(), 2, 3, GL_FLOAT, false, GLuint(layout.p_curr_byte_offset)); // model_attribs_buffer glVertexArrayVertexBuffer(_render_vao_0.id(), model_attribs_buffer_binding_index, _model_attribs_buffer.id(), 0, GLsizei(layout.model_attribs_byte_stride)); // normal glEnableVertexArrayAttrib(_render_vao_0.id(), 3); glVertexArrayAttribBinding(_render_vao_0.id(), 3, model_attribs_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_0.id(), 3, 3, GL_FLOAT, false, GLuint(layout.normal_byte_offset)); // tex_coord glEnableVertexArrayAttrib(_render_vao_0.id(), 4); glVertexArrayAttribBinding(_render_vao_0.id(), 4, model_attribs_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_0.id(), 4, 2, GL_FLOAT, false, GLuint(layout.tex_coord_byte_offset)); // tangent_h glEnableVertexArrayAttrib(_render_vao_0.id(), 5); glVertexArrayAttribBinding(_render_vao_0.id(), 5, model_attribs_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_0.id(), 5, 4, GL_FLOAT, false, GLuint(layout.tangent_h_byte_offset)); // index_buffer glVertexArrayElementBuffer(_render_vao_0.id(), _index_buffer.id()); } void Geometry_buffers::init_render_1_vao(const Model_geometry_layout& layout) { constexpr GLuint position_buffer_binding_index = 0; constexpr GLuint simulation_buffer_binding_index = 1; constexpr GLuint model_attribs_buffer_binding_index = 2; // position_buffer glVertexArrayVertexBuffer(_render_vao_1.id(), position_buffer_binding_index, _tbo_position_buffer.buffer().id(), 0, GLsizei(layout.position_buffer_byte_stride)); // p_base glEnableVertexArrayAttrib(_render_vao_1.id(), 0); glVertexArrayAttribBinding(_render_vao_1.id(), 0, position_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_1.id(), 0, 3, GL_FLOAT, false, GLuint(layout.p_base_byte_offset)); // p_rest glEnableVertexArrayAttrib(_render_vao_1.id(), 1); glVertexArrayAttribBinding(_render_vao_1.id(), 1, position_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_1.id(), 1, 3, GL_FLOAT, false, GLuint(layout.p_rest_byte_offset)); // simulation_buffer glVertexArrayVertexBuffer(_render_vao_1.id(), simulation_buffer_binding_index, _tbo_physics_buffer_1.buffer().id(), 0, GLsizei(layout.simulation_buffer_byte_stride)); // p_curr glEnableVertexArrayAttrib(_render_vao_1.id(), 2); glVertexArrayAttribBinding(_render_vao_1.id(), 2, simulation_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_1.id(), 2, 3, GL_FLOAT, false, GLuint(layout.p_curr_byte_offset)); // model_attribs_buffer glVertexArrayVertexBuffer(_render_vao_1.id(), model_attribs_buffer_binding_index, _model_attribs_buffer.id(), 0, GLsizei(layout.model_attribs_byte_stride)); // normal glEnableVertexArrayAttrib(_render_vao_1.id(), 3); glVertexArrayAttribBinding(_render_vao_1.id(), 3, model_attribs_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_1.id(), 3, 3, GL_FLOAT, false, GLuint(layout.normal_byte_offset)); // tex_coord glEnableVertexArrayAttrib(_render_vao_1.id(), 4); glVertexArrayAttribBinding(_render_vao_1.id(), 4, model_attribs_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_1.id(), 4, 2, GL_FLOAT, false, GLuint(layout.tex_coord_byte_offset)); // tangent_h glEnableVertexArrayAttrib(_render_vao_1.id(), 5); glVertexArrayAttribBinding(_render_vao_1.id(), 5, model_attribs_buffer_binding_index); glVertexArrayAttribFormat(_render_vao_1.id(), 5, 4, GL_FLOAT, false, GLuint(layout.tangent_h_byte_offset)); // index_buffer glVertexArrayElementBuffer(_render_vao_1.id(), _index_buffer.id()); } void Geometry_buffers::swap_physics_source_dest_buffers() noexcept { _read_from_physics_0 = !_read_from_physics_0; // if data is read from #0 then tb points to #1 GLuint tf_buffer_id = (_read_from_physics_0) ? _tbo_physics_buffer_1.buffer().id() : _tbo_physics_buffer_0.buffer().id(); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tf_buffer_id); } // ----- Material_gallery ----- Material_gallery::Material_gallery() { const Sampler_desc fur_mask_sampler(GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT, GL_CLAMP_TO_EDGE); { // fur mask image_2d image_fur_mask("../../data/fur_simulation/noise-texture.png"); _tex_fur_mask = Texture_2d_immut(GL_R8, 1, fur_mask_sampler, image_fur_mask); } const Sampler_desc diffuse_rgb_sampler(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE); { // cat material image_2d image_diffuse_rgb("../../data/fur_simulation/cat-diffuse-rgb.png"); _tex_car_diffuse_rgb = Texture_2d_immut(GL_RGB8, 1, diffuse_rgb_sampler, image_diffuse_rgb); _cat_material = std::make_unique<Material>(_tex_car_diffuse_rgb, _tex_fur_mask, Strand_properties( /* curl_radius */ 0.0f, /* curl_frequency */ 0.0, /* shadow_factor_power */ 0.6f, /* shell_count */ 32, /* threshold_power */ 0.8f, /* fur_mask_uv_min_factor */ 1.0f, /* fur_mask_uv_max_factor */ 3.0f, /* mass */ 0.05f, /* k */ 4.0f, /* damping */ 0.5f)); } { // curly red material image_2d image_diffuse_rgb("../../data/fur_simulation/red-diffuse-rgb.png"); _tex_red_curl_material = Texture_2d_immut(GL_RGB8, 1, diffuse_rgb_sampler, image_diffuse_rgb); _curly_red_material = std::make_unique<Material>(_tex_red_curl_material, _tex_fur_mask, Strand_properties( /* curl_radius */ 0.007f, /* curl_frequency */ 4.0, /* shadow_factor_power */ 0.6f, /* shell_count */ 32, /* threshold_power */ 0.6f, /* fur_mask_uv_min_factor */ 2.0f, /* fur_mask_uv_max_factor */ 2.0f, /* mass */ 0.1f, /* k */ 100.5f, /* damping */ 5.5f)); } { // bunny material image_2d image_diffuse_rgb("../../data/fur_simulation/bunny-diffuse-rgb.png"); _tex_bunny_diffuse_rgb = Texture_2d_immut(GL_RGB8, 1, diffuse_rgb_sampler, image_diffuse_rgb); _bunny_material = std::make_unique<Material>(_tex_bunny_diffuse_rgb, _tex_fur_mask, Strand_properties( /* curl_radius */ 0.07f, /* curl_frequency */ 8.0, /* shadow_factor_power */ 1.0f, /* shell_count */ 64, /* threshold_power */ 1.1f, /* fur_mask_uv_min_factor */ 0.5f, /* fur_mask_uv_max_factor */ 3.0f, /* mass */ 0.1f, /* k */ 1.0f, /* damping */ 0.5f)); } } // ----- Fur_pass ----- void Fur_pass::perform(const Geometry_buffers& geometry_buffers, const Material& material, const float4x4& pvm_matrix, const float4x4& model_matrix, const float3& view_position_ws, const float3& light_dir_ws) noexcept { glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); glBindTextureUnit(0, material.tex_diffuse_rgb().id()); glBindTextureUnit(1, material.tex_fur_mask().id()); glBindVertexArray(geometry_buffers.render_vao_id()); _program.bind(pvm_matrix, model_matrix, view_position_ws, material.strand_props(), light_dir_ws); for (size_t mi = 0; mi < geometry_buffers.meshes().size(); ++mi) { glDrawElementsInstancedBaseVertex(GL_TRIANGLES, GLsizei(geometry_buffers.meshes()[mi].index_count), GL_UNSIGNED_INT, nullptr, GLsizei(material.strand_props().shell_count), GLint(geometry_buffers.meshes()[mi].base_vertex)); } glBindTextureUnit(0, Blank::texture_id); glBindTextureUnit(1, Blank::texture_id); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, Blank::framebuffer_id); glDisable(GL_BLEND); glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); } // ----- Opaque_model_pass ----- void Opaque_model_pass::perform(const Geometry_buffers& geometry_buffers, const Material& material, const float4x4& projection_view_matrix, const float4x4& model_matrix, const float3& dir_to_light_ws) noexcept { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glBindTextureUnit(0, material.tex_diffuse_rgb().id()); glBindVertexArray(geometry_buffers.render_vao_id()); _program.bind(projection_view_matrix, model_matrix, dir_to_light_ws); for (size_t mi = 0; mi < geometry_buffers.meshes().size(); ++mi) { glDrawElementsBaseVertex(GL_TRIANGLES, GLsizei(geometry_buffers.meshes()[mi].index_count), GL_UNSIGNED_INT, nullptr, GLint(geometry_buffers.meshes()[mi].base_vertex)); } glBindTextureUnit(0, Blank::texture_id); glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } // ----- Physics_simulation_pass ----- void Physics_simulation_pass::perform(Geometry_buffers& geometry_buffers, const float4& extern_accel_ms, const float3& angular_accel_ms, float strand_length, const Strand_properties& strand_props) noexcept { glDisable(GL_DEPTH_TEST); glEnable(GL_RASTERIZER_DISCARD); glBindVertexArray(geometry_buffers.physics_vao_id()); _program.bind(extern_accel_ms, angular_accel_ms, float4(strand_length, strand_props.mass, strand_props.k, strand_props.c)); glBeginTransformFeedback(GL_POINTS); glDrawArrays(GL_POINTS, 0, geometry_buffers.vertex_count()); glEndTransformFeedback(); glBindVertexArray(Blank::vao_id); geometry_buffers.swap_physics_source_dest_buffers(); glDisable(GL_RASTERIZER_DISCARD); glEnable(GL_DEPTH_TEST); } // ----- Strand_debug_pass ----- void Strand_debug_pass::perform(Geometry_buffers& geometry_buffers, const float4x4& pvm_matrix) noexcept { glEnable(GL_DEPTH_TEST); glBindTextureUnit(0, geometry_buffers.tbo_position_buffer().id()); glBindTextureUnit(1, geometry_buffers.tbo_physics_buffer().id()); glBindTextureUnit(2, geometry_buffers.tbo_debug_slot_buffer().id()); glBindVertexArray(geometry_buffers.blank_vao_id()); _program.bind(pvm_matrix); glDrawArrays(GL_LINES, 0, 4 * geometry_buffers.vertex_count()); glDisable(GL_DEPTH_TEST); glBindTextureUnit(0, Blank::texture_id); glBindTextureUnit(1, Blank::texture_id); glBindTextureUnit(2, Blank::texture_id); glBindVertexArray(Blank::vao_id); } // ----- Fur_simulation_opengl_example ----- Fur_simulation_opengl_example::Fur_simulation_opengl_example(const cg::sys::app_context& app_ctx, cg::rnd::rhi_context_i& rhi_ctx) : example(app_ctx, rhi_ctx), _curr_viewpoint(float3(0, 3, 7), float3(0, 0, 0)), _prev_viewpoint(_curr_viewpoint), _model_transform(float3(0, -0.5, 0), normalize(float3(0, 1, 0)), float3(2.0f)), //_geometry_buffers(0.3f, "../../data/rect_2x2.obj"), //_geometry_buffers(0.3f, "../../data/sphere-20x20.obj"), _geometry_buffers(0.1f, "../../data/models/bunny.obj"), _dir_to_light_ws(normalize(float3(50, 1, 100.0))) { update_projection_matrix(); _curr_material = &_material_gallery.cat_material(); } void Fur_simulation_opengl_example::on_keyboard() { /*if (_app_ctx.keyboard.is_down(Key::f)) { _wind_acceleration = 10.0f * normalize(-float3(0, 1, -1)); } else { _wind_acceleration = float3::zero; }*/ if (_app_ctx.keyboard.is_down(Key::r)) { _model_transform.rotation_angle_total += pi_8; _model_transform.rotation_angle = 5.6f * pi_8; } else { _model_transform.rotation_angle = 0.0f; } float3 movement_direction; if (_app_ctx.keyboard.is_down(Key::w)) movement_direction += float3::unit_y; if (_app_ctx.keyboard.is_down(Key::s)) movement_direction -= float3::unit_y; if (_app_ctx.keyboard.is_down(Key::a)) movement_direction -= float3::unit_x; if (_app_ctx.keyboard.is_down(Key::d)) movement_direction += float3::unit_x; _movement_acceleration = 5.0f * normalize(movement_direction); if (_app_ctx.keyboard.is_down(Key::space)) { _movement_speed = float3::zero; _movement_acceleration = float3::zero; _model_transform.position = float3(0, -0.5, 0); } if (_app_ctx.keyboard.is_down(Key::digit_1)) { _curr_material = &_material_gallery.cat_material(); } else if(_app_ctx.keyboard.is_down(Key::digit_2)) { _curr_material = &_material_gallery.curly_red_material(); } else if (_app_ctx.keyboard.is_down(Key::digit_3)) { _curr_material = &_material_gallery.bunny_material(); } } void Fur_simulation_opengl_example::on_mouse_move() { if (!_app_ctx.mouse.middle_down()) return; float2 pos_ndc = _app_ctx.mouse.get_ndc_position(_app_ctx.window.viewport_size()); float2 offset_ndc = pos_ndc - _prev_mouse_pos_ndc; if (offset_ndc == float2::zero) return; _prev_mouse_pos_ndc = pos_ndc; bool y_offset_satisfies = !approx_equal(offset_ndc.y, 0.f, 0.01f); bool x_offset_satisfies = !approx_equal(offset_ndc.x, 0.f, ((y_offset_satisfies) ? 0.01f : 0.001f)); // mouse offset by x means rotation around OY (yaw) if (x_offset_satisfies) { _view_roll_angles.y += (offset_ndc.x > 0.f) ? -pi_64 : pi_64; } // mouse offset by x means rotation around OX (pitch) if (y_offset_satisfies) { _view_roll_angles.x += (offset_ndc.y > 0.f) ? pi_64 : -pi_64; } } void Fur_simulation_opengl_example::on_window_resize() { auto vp_size = _app_ctx.window.viewport_size(); glViewport(0, 0, vp_size.x, vp_size.y); update_projection_matrix(); } void Fur_simulation_opengl_example::render(float interpolation_factor) { const float3 view_position = lerp(_prev_viewpoint.position, _curr_viewpoint.position, interpolation_factor); const float4x4 view_matrix = ::view_matrix(_prev_viewpoint, _curr_viewpoint, interpolation_factor); const float4x4 projection_view_matrix = _projection_matrix* view_matrix; const float4x4 pvm_matrix = projection_view_matrix * _model_matrix; _prev_viewpoint = _curr_viewpoint; static const float3 color = rgb(0x817c6e); glClearColor(color.x, color.y, color.z, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //_opaque_model_pass.perform(_geometry_buffers, *_curr_material, // projection_view_matrix, _model_matrix, _dir_to_light_ws); _fur_pass.perform(_geometry_buffers, *_curr_material, pvm_matrix, _model_matrix, view_position, _dir_to_light_ws); //_strand_debug_pass.perform(_geometry_buffers, pvm_matrix); } void Fur_simulation_opengl_example::update(float dt_msec) { const float dt = dt_msec / 1000.0f; const float3 angular_velocity = _model_transform.rotation_angle * _model_transform.rotation_axis; update_curr_viewpoint(); _movement_speed += _movement_acceleration * dt; _model_transform.position += 0.008f * _movement_speed; _model_matrix = trs_matrix(_model_transform.position, from_axis_angle_rotation(_model_transform.rotation_axis, 0.1f * _model_transform.rotation_angle_total), _model_transform.scale); const float3 external_accelerations = float3(0.0f, -9.81f, 0.0f) - _movement_acceleration; const float3x3 inv_model_matrix(_model_matrix); const float4 extern_accel_ms(mul(inv_model_matrix, external_accelerations), dt); const float3 angular_ms(mul(inv_model_matrix, -angular_velocity)); _physics_pass.perform(_geometry_buffers, extern_accel_ms, angular_ms, 0.1f, _curr_material->strand_props()); } void Fur_simulation_opengl_example::update_curr_viewpoint() { if (_view_roll_angles != float2::zero) { float dist = distance(_curr_viewpoint); float3 ox = cross(forward(_curr_viewpoint), _curr_viewpoint.up); ox.y = 0.0f; // ox is always parallel the world's OX. ox = normalize(ox); if (!approx_equal(_view_roll_angles.y, 0.0f)) { quat q = from_axis_angle_rotation(float3::unit_y, _view_roll_angles.y); _curr_viewpoint.position = dist * normalize(rotate(q, _curr_viewpoint.position)); ox = rotate(q, ox); ox.y = 0.0f; ox = normalize(ox); } if (!approx_equal(_view_roll_angles.x, 0.0f)) { quat q = from_axis_angle_rotation(ox, _view_roll_angles.x); _curr_viewpoint.position = dist * normalize(rotate(q, _curr_viewpoint.position)); } _curr_viewpoint.up = normalize(cross(ox, forward(_curr_viewpoint))); } _view_roll_angles = float2::zero; } void Fur_simulation_opengl_example::update_projection_matrix() { _projection_matrix = perspective_matrix_opengl(pi_3, aspect_ratio(_app_ctx.window.viewport_size()), 0.1f, 1000.0f); } } // fur_simulation
39.125217
126
0.759346
[ "mesh", "geometry", "render" ]
02cc79fd47a75e6cb68d42ed0ec246f8e15dadb2
28,961
cpp
C++
VulkanExample/triangle/triangle.cpp
metora/MesaGLSLCompiler
83227892b03a2bd1ebe0ee9d0b394665f5a61e8b
[ "MIT" ]
2
2018-07-27T20:01:32.000Z
2021-08-03T09:17:36.000Z
VulkanExample/triangle/triangle.cpp
metora/MesaGLSLCompiler
83227892b03a2bd1ebe0ee9d0b394665f5a61e8b
[ "MIT" ]
null
null
null
VulkanExample/triangle/triangle.cpp
metora/MesaGLSLCompiler
83227892b03a2bd1ebe0ee9d0b394665f5a61e8b
[ "MIT" ]
1
2017-08-17T08:13:01.000Z
2017-08-17T08:13:01.000Z
/* * Vulkan Example - Basic indexed triangle rendering * * Note : * This is a "pedal to the metal" example to show off how to get Vulkan up an displaying something * Contrary to the other examples, this one won't make use of helper functions or initializers * Except in a few cases (swap chain setup e.g.) * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <vector> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vulkan/vulkan.h> #include "vulkanexamplebase.h" #define VERTEX_BUFFER_BIND_ID 0 // Set to "true" to enable Vulkan's validation layers // See vulkandebug.cpp for details #define ENABLE_VALIDATION false class VulkanExample : public VulkanExampleBase { public: struct { VkBuffer buf; VkDeviceMemory mem; VkPipelineVertexInputStateCreateInfo vi; std::vector<VkVertexInputBindingDescription> bindingDescriptions; std::vector<VkVertexInputAttributeDescription> attributeDescriptions; } vertices; struct { int count; VkBuffer buf; VkDeviceMemory mem; } indices; struct { VkBuffer buffer; VkDeviceMemory memory; VkDescriptorBufferInfo descriptor; } uniformDataVS; struct { glm::mat4 projectionMatrix; glm::mat4 modelMatrix; glm::mat4 viewMatrix; } uboVS; struct { VkPipeline solid; } pipelines; VkPipelineLayout pipelineLayout; VkDescriptorSet descriptorSet; VkDescriptorSetLayout descriptorSetLayout; // Synchronization semaphores struct { VkSemaphore presentComplete; VkSemaphore renderComplete; } semaphores; VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) { width = 1280; height = 720; zoom = -2.5f; title = "Vulkan Example - Basic indexed triangle"; // Values not set here are initialized in the base class constructor } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class vkDestroyPipeline(device, pipelines.solid, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); vkDestroyBuffer(device, vertices.buf, nullptr); vkFreeMemory(device, vertices.mem, nullptr); vkDestroyBuffer(device, indices.buf, nullptr); vkFreeMemory(device, indices.mem, nullptr); vkDestroySemaphore(device, semaphores.presentComplete, nullptr); vkDestroySemaphore(device, semaphores.renderComplete, nullptr); vkDestroyBuffer(device, uniformDataVS.buffer, nullptr); vkFreeMemory(device, uniformDataVS.memory, nullptr); } // Build separate command buffers for every framebuffer image // Unlike in OpenGL all rendering commands are recorded once // into command buffers that are then resubmitted to the queue void buildCommandBuffers() { VkCommandBufferBeginInfo cmdBufInfo = {}; cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmdBufInfo.pNext = NULL; VkClearValue clearValues[2]; clearValues[0].color = defaultClearColor; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo = {}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.pNext = NULL; renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = width; renderPassBeginInfo.renderArea.extent.height = height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; VkResult err; for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[i]; err = vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo); assert(!err); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); // Update dynamic viewport state VkViewport viewport = {}; viewport.height = (float)height; viewport.width = (float)width; viewport.minDepth = (float) 0.0f; viewport.maxDepth = (float) 1.0f; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); // Update dynamic scissor state VkRect2D scissor = {}; scissor.extent.width = width; scissor.extent.height = height; scissor.offset.x = 0; scissor.offset.y = 0; vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); // Bind descriptor sets describing shader binding points vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL); // Bind the rendering pipeline (including the shaders) vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.solid); // Bind triangle vertices VkDeviceSize offsets[1] = { 0 }; vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &vertices.buf, offsets); // Bind triangle indices vkCmdBindIndexBuffer(drawCmdBuffers[i], indices.buf, 0, VK_INDEX_TYPE_UINT32); // Draw indexed triangle vkCmdDrawIndexed(drawCmdBuffers[i], indices.count, 1, 0, 0, 1); vkCmdEndRenderPass(drawCmdBuffers[i]); // Add a present memory barrier to the end of the command buffer // This will transform the frame buffer color attachment to a // new layout for presenting it to the windowing system integration VkImageMemoryBarrier prePresentBarrier = {}; prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; prePresentBarrier.pNext = NULL; prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; prePresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; prePresentBarrier.image = swapChain.buffers[i].image; VkImageMemoryBarrier *pMemoryBarrier = &prePresentBarrier; vkCmdPipelineBarrier( drawCmdBuffers[i], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_FLAGS_NONE, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); err = vkEndCommandBuffer(drawCmdBuffers[i]); assert(!err); } } void draw() { VkResult err; // Get next image in the swap chain (back/front buffer) err = swapChain.acquireNextImage(semaphores.presentComplete, &currentBuffer); assert(!err); // Add a post present image memory barrier // This will transform the frame buffer color attachment back // to it's initial layout after it has been presented to the // windowing system VkImageMemoryBarrier postPresentBarrier = {}; postPresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; postPresentBarrier.pNext = NULL; postPresentBarrier.srcAccessMask = 0; postPresentBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; postPresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; postPresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; postPresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; postPresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; postPresentBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; postPresentBarrier.image = swapChain.buffers[currentBuffer].image; // Use dedicated command buffer from example base class for submitting the post present barrier VkCommandBufferBeginInfo cmdBufInfo = {}; cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; err = vkBeginCommandBuffer(postPresentCmdBuffer, &cmdBufInfo); assert(!err); // Put post present barrier into command buffer vkCmdPipelineBarrier( postPresentCmdBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_FLAGS_NONE, 0, nullptr, 0, nullptr, 1, &postPresentBarrier); err = vkEndCommandBuffer(postPresentCmdBuffer); assert(!err); // Submit to the queue submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &postPresentCmdBuffer; err = vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE); assert(!err); err = vkQueueWaitIdle(queue); assert(!err); // The submit infor strcuture contains a list of // command buffers and semaphores to be submitted to a queue // If you want to submit multiple command buffers, pass an array VkPipelineStageFlags pipelineStages = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pWaitDstStageMask = &pipelineStages; // The wait semaphore ensures that the image is presented // before we start submitting command buffers agein submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &semaphores.presentComplete; // Submit the currently active command buffer submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; // The signal semaphore is used during queue presentation // to ensure that the image is not rendered before all // commands have been submitted submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &semaphores.renderComplete; // Submit to the graphics queue err = vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE); assert(!err); // Present the current buffer to the swap chain // We pass the signal semaphore from the submit info // to ensure that the image is not rendered until // all commands have been submitted err = swapChain.queuePresent(queue, currentBuffer, semaphores.renderComplete); assert(!err); } // Create synchronzation semaphores void prepareSemaphore() { VkSemaphoreCreateInfo semaphoreCreateInfo = {}; semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphoreCreateInfo.pNext = NULL; // This semaphore ensures that the image is complete // before starting to submit again VkResult err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete); assert(!err); // This semaphore ensures that all commands submitted // have been finished before submitting the image to the queue err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete); assert(!err); } // Setups vertex and index buffers for an indexed triangle, // uploads them to the VRAM and sets binding points and attribute // descriptions to match locations inside the shaders void prepareVertices() { struct Vertex { float pos[3]; float col[3]; }; // Setup vertices std::vector<Vertex> vertexBuffer = { { { 1.0f, 1.0f, 0.0f },{ 1.0f, 0.0f, 0.0f } }, { { -1.0f, 1.0f, 0.0f },{ 0.0f, 1.0f, 0.0f } }, { { 0.0f, -1.0f, 0.0f },{ 0.0f, 0.0f, 1.0f } } }; int vertexBufferSize = vertexBuffer.size() * sizeof(Vertex); // Setup indices std::vector<uint32_t> indexBuffer = { 0, 1, 2 }; int indexBufferSize = indexBuffer.size() * sizeof(uint32_t); VkMemoryAllocateInfo memAlloc = {}; memAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memAlloc.pNext = NULL; memAlloc.allocationSize = 0; memAlloc.memoryTypeIndex = 0; VkMemoryRequirements memReqs; VkResult err; void *data; // Generate vertex buffer // Setup VkBufferCreateInfo bufInfo = {}; bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufInfo.pNext = NULL; bufInfo.size = vertexBufferSize; bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; bufInfo.flags = 0; // Copy vertex data to VRAM memset(&vertices, 0, sizeof(vertices)); err = vkCreateBuffer(device, &bufInfo, nullptr, &vertices.buf); assert(!err); vkGetBufferMemoryRequirements(device, vertices.buf, &memReqs); memAlloc.allocationSize = memReqs.size; getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memAlloc.memoryTypeIndex); err = vkAllocateMemory(device, &memAlloc, nullptr, &vertices.mem); assert(!err); err = vkMapMemory(device, vertices.mem, 0, memAlloc.allocationSize, 0, &data); assert(!err); memcpy(data, vertexBuffer.data(), vertexBufferSize); vkUnmapMemory(device, vertices.mem); err = vkBindBufferMemory(device, vertices.buf, vertices.mem, 0); assert(!err); // Generate index buffer // Setup VkBufferCreateInfo indexbufferInfo = {}; indexbufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; indexbufferInfo.pNext = NULL; indexbufferInfo.size = indexBufferSize; indexbufferInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT; indexbufferInfo.flags = 0; // Copy index data to VRAM memset(&indices, 0, sizeof(indices)); err = vkCreateBuffer(device, &indexbufferInfo, nullptr, &indices.buf); assert(!err); vkGetBufferMemoryRequirements(device, indices.buf, &memReqs); memAlloc.allocationSize = memReqs.size; getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memAlloc.memoryTypeIndex); err = vkAllocateMemory(device, &memAlloc, nullptr, &indices.mem); assert(!err); err = vkMapMemory(device, indices.mem, 0, indexBufferSize, 0, &data); assert(!err); memcpy(data, indexBuffer.data(), indexBufferSize); vkUnmapMemory(device, indices.mem); err = vkBindBufferMemory(device, indices.buf, indices.mem, 0); assert(!err); indices.count = indexBuffer.size(); // Binding description vertices.bindingDescriptions.resize(1); vertices.bindingDescriptions[0].binding = VERTEX_BUFFER_BIND_ID; vertices.bindingDescriptions[0].stride = sizeof(Vertex); vertices.bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // Attribute descriptions // Describes memory layout and shader attribute locations vertices.attributeDescriptions.resize(2); // Location 0 : Position vertices.attributeDescriptions[0].binding = VERTEX_BUFFER_BIND_ID; vertices.attributeDescriptions[0].location = 0; vertices.attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; vertices.attributeDescriptions[0].offset = 0; vertices.attributeDescriptions[0].binding = 0; // Location 1 : Color vertices.attributeDescriptions[1].binding = VERTEX_BUFFER_BIND_ID; vertices.attributeDescriptions[1].location = 1; vertices.attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; vertices.attributeDescriptions[1].offset = sizeof(float) * 3; vertices.attributeDescriptions[1].binding = 0; // Assign to vertex buffer vertices.vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertices.vi.pNext = NULL; vertices.vi.vertexBindingDescriptionCount = vertices.bindingDescriptions.size(); vertices.vi.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); vertices.vi.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size(); vertices.vi.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); } void setupDescriptorPool() { // We need to tell the API the number of max. requested descriptors per type VkDescriptorPoolSize typeCounts[1]; // This example only uses one descriptor type (uniform buffer) and only // requests one descriptor of this type typeCounts[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; typeCounts[0].descriptorCount = 1; // For additional types you need to add new entries in the type count list // E.g. for two combined image samplers : // typeCounts[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; // typeCounts[1].descriptorCount = 2; // Create the global descriptor pool // All descriptors used in this example are allocated from this pool VkDescriptorPoolCreateInfo descriptorPoolInfo = {}; descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPoolInfo.pNext = NULL; descriptorPoolInfo.poolSizeCount = 1; descriptorPoolInfo.pPoolSizes = typeCounts; // Set the max. number of sets that can be requested // Requesting descriptors beyond maxSets will result in an error descriptorPoolInfo.maxSets = 1; VkResult vkRes = vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool); assert(!vkRes); } void setupDescriptorSetLayout() { // Setup layout of descriptors used in this example // Basically connects the different shader stages to descriptors // for binding uniform buffers, image samplers, etc. // So every shader binding should map to one descriptor set layout // binding // Binding 0 : Uniform buffer (Vertex shader) VkDescriptorSetLayoutBinding layoutBinding = {}; layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; layoutBinding.descriptorCount = 1; layoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; layoutBinding.pImmutableSamplers = NULL; VkDescriptorSetLayoutCreateInfo descriptorLayout = {}; descriptorLayout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorLayout.pNext = NULL; descriptorLayout.bindingCount = 1; descriptorLayout.pBindings = &layoutBinding; VkResult err = vkCreateDescriptorSetLayout(device, &descriptorLayout, NULL, &descriptorSetLayout); assert(!err); // Create the pipeline layout that is used to generate the rendering pipelines that // are based on this descriptor set layout // In a more complex scenario you would have different pipeline layouts for different // descriptor set layouts that could be reused VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {}; pPipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pPipelineLayoutCreateInfo.pNext = NULL; pPipelineLayoutCreateInfo.setLayoutCount = 1; pPipelineLayoutCreateInfo.pSetLayouts = &descriptorSetLayout; err = vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout); assert(!err); } void setupDescriptorSet() { // Update descriptor sets determining the shader binding points // For every binding point used in a shader there needs to be one // descriptor set matching that binding point VkWriteDescriptorSet writeDescriptorSet = {}; VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &descriptorSetLayout; VkResult vkRes = vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet); assert(!vkRes); // Binding 0 : Uniform buffer writeDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSet.dstSet = descriptorSet; writeDescriptorSet.descriptorCount = 1; writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeDescriptorSet.pBufferInfo = &uniformDataVS.descriptor; // Binds this uniform buffer to binding point 0 writeDescriptorSet.dstBinding = 0; vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, NULL); } void preparePipelines() { // Create our rendering pipeline used in this example // Vulkan uses the concept of rendering pipelines to encapsulate // fixed states // This replaces OpenGL's huge (and cumbersome) state machine // A pipeline is then stored and hashed on the GPU making // pipeline changes much faster than having to set dozens of // states // In a real world application you'd have dozens of pipelines // for every shader set used in a scene // Note that there are a few states that are not stored with // the pipeline. These are called dynamic states and the // pipeline only stores that they are used with this pipeline, // but not their states VkGraphicsPipelineCreateInfo pipelineCreateInfo = {}; VkResult err; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; // The layout used for this pipeline pipelineCreateInfo.layout = pipelineLayout; // Renderpass this pipeline is attached to pipelineCreateInfo.renderPass = renderPass; // Vertex input state // Describes the topoloy used with this pipeline VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = {}; inputAssemblyState.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; // This pipeline renders vertex data as triangle lists inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // Rasterization state VkPipelineRasterizationStateCreateInfo rasterizationState = {}; rasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; // Solid polygon mode rasterizationState.polygonMode = VK_POLYGON_MODE_FILL; // No culling rasterizationState.cullMode = VK_CULL_MODE_NONE; rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationState.depthClampEnable = VK_FALSE; rasterizationState.rasterizerDiscardEnable = VK_FALSE; rasterizationState.depthBiasEnable = VK_FALSE; // Color blend state // Describes blend modes and color masks VkPipelineColorBlendStateCreateInfo colorBlendState = {}; colorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; // One blend attachment state // Blending is not used in this example VkPipelineColorBlendAttachmentState blendAttachmentState[1] = {}; blendAttachmentState[0].colorWriteMask = 0xf; blendAttachmentState[0].blendEnable = VK_FALSE; colorBlendState.attachmentCount = 1; colorBlendState.pAttachments = blendAttachmentState; // Viewport state VkPipelineViewportStateCreateInfo viewportState = {}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; // One viewport viewportState.viewportCount = 1; // One scissor rectangle viewportState.scissorCount = 1; // Enable dynamic states // Describes the dynamic states to be used with this pipeline // Dynamic states can be set even after the pipeline has been created // So there is no need to create new pipelines just for changing // a viewport's dimensions or a scissor box VkPipelineDynamicStateCreateInfo dynamicState = {}; // The dynamic state properties themselves are stored in the command buffer std::vector<VkDynamicState> dynamicStateEnables; dynamicStateEnables.push_back(VK_DYNAMIC_STATE_VIEWPORT); dynamicStateEnables.push_back(VK_DYNAMIC_STATE_SCISSOR); dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicState.pDynamicStates = dynamicStateEnables.data(); dynamicState.dynamicStateCount = dynamicStateEnables.size(); // Depth and stencil state // Describes depth and stenctil test and compare ops VkPipelineDepthStencilStateCreateInfo depthStencilState = {}; // Basic depth compare setup with depth writes and depth test enabled // No stencil used depthStencilState.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencilState.depthTestEnable = VK_TRUE; depthStencilState.depthWriteEnable = VK_TRUE; depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; depthStencilState.depthBoundsTestEnable = VK_FALSE; depthStencilState.back.failOp = VK_STENCIL_OP_KEEP; depthStencilState.back.passOp = VK_STENCIL_OP_KEEP; depthStencilState.back.compareOp = VK_COMPARE_OP_ALWAYS; depthStencilState.stencilTestEnable = VK_FALSE; depthStencilState.front = depthStencilState.back; // Multi sampling state VkPipelineMultisampleStateCreateInfo multisampleState = {}; multisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampleState.pSampleMask = NULL; // No multi sampling used in this example multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // Load shaders // Shaders are loaded from the SPIR-V format, which can be generated from glsl VkPipelineShaderStageCreateInfo shaderStages[2] = { {},{} }; shaderStages[0] = loadShaderGLSL("./../data/shaders/triangle150.vert", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShaderGLSL("./../data/shaders/triangle150.frag", VK_SHADER_STAGE_FRAGMENT_BIT); // Assign states // Two shader stages pipelineCreateInfo.stageCount = 2; // Assign pipeline state create information pipelineCreateInfo.pVertexInputState = &vertices.vi; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pStages = shaderStages; pipelineCreateInfo.renderPass = renderPass; pipelineCreateInfo.pDynamicState = &dynamicState; // Create rendering pipeline err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.solid); assert(!err); } void prepareUniformBuffers() { // Prepare and initialize uniform buffer containing shader uniforms VkMemoryRequirements memReqs; // Vertex shader uniform buffer block VkBufferCreateInfo bufferInfo = {}; VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = NULL; allocInfo.allocationSize = 0; allocInfo.memoryTypeIndex = 0; VkResult err; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = sizeof(uboVS); bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; // Create a new buffer err = vkCreateBuffer(device, &bufferInfo, nullptr, &uniformDataVS.buffer); assert(!err); // Get memory requirements including size, alignment and memory type vkGetBufferMemoryRequirements(device, uniformDataVS.buffer, &memReqs); allocInfo.allocationSize = memReqs.size; // Gets the appropriate memory type for this type of buffer allocation // Only memory types that are visible to the host getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex); // Allocate memory for the uniform buffer err = vkAllocateMemory(device, &allocInfo, nullptr, &(uniformDataVS.memory)); assert(!err); // Bind memory to buffer err = vkBindBufferMemory(device, uniformDataVS.buffer, uniformDataVS.memory, 0); assert(!err); // Store information in the uniform's descriptor uniformDataVS.descriptor.buffer = uniformDataVS.buffer; uniformDataVS.descriptor.offset = 0; uniformDataVS.descriptor.range = sizeof(uboVS); updateUniformBuffers(); } void updateUniformBuffers() { // Update matrices uboVS.projectionMatrix = glm::perspective(glm::radians(60.0f), (float)width / (float)height, 0.1f, 256.0f); uboVS.viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, zoom)); uboVS.modelMatrix = glm::mat4(); uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); // Map uniform buffer and update it uint8_t *pData; VkResult err = vkMapMemory(device, uniformDataVS.memory, 0, sizeof(uboVS), 0, (void **)&pData); assert(!err); memcpy(pData, &uboVS, sizeof(uboVS)); vkUnmapMemory(device, uniformDataVS.memory); assert(!err); } void prepare() { VulkanExampleBase::prepare(); prepareSemaphore(); prepareVertices(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; vkDeviceWaitIdle(device); draw(); vkDeviceWaitIdle(device); } virtual void viewChanged() { // This function is called by the base example class // each time the view is changed by user input updateUniformBuffers(); } }; VulkanExample *vulkanExample; #ifdef _WIN32 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (vulkanExample != NULL) { vulkanExample->handleMessages(hWnd, uMsg, wParam, lParam); } return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } #else static void handleEvent(const xcb_generic_event_t *event) { if (vulkanExample != NULL) { vulkanExample->handleEvent(event); } } #endif #ifdef _WIN32 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) #else int main(const int argc, const char *argv[]) #endif { vulkanExample = new VulkanExample(); #ifdef _WIN32 vulkanExample->setupWindow(hInstance, WndProc); #else vulkanExample->setupWindow(); #endif vulkanExample->initSwapchain(); vulkanExample->prepare(); vulkanExample->renderLoop(); delete(vulkanExample); return 0; }
37.034527
126
0.772314
[ "render", "vector", "transform", "solid" ]
02d0339bf0d7e614c2b69f7e14fac2a85753cc8f
4,015
hpp
C++
src/_viennacl/compressed_matrix.hpp
viennacl/pyviennacl-dev
3509318db9eb4cc788f262f4e3924775f0cf3a01
[ "MIT" ]
26
2015-01-03T20:06:05.000Z
2021-09-09T09:23:14.000Z
src/_viennacl/compressed_matrix.hpp
viennacl/pyviennacl-dev
3509318db9eb4cc788f262f4e3924775f0cf3a01
[ "MIT" ]
18
2015-01-12T00:08:42.000Z
2021-01-18T10:31:06.000Z
src/_viennacl/compressed_matrix.hpp
viennacl/pyviennacl-dev
3509318db9eb4cc788f262f4e3924775f0cf3a01
[ "MIT" ]
5
2015-09-17T16:42:58.000Z
2022-03-21T19:21:43.000Z
#ifndef _PYVIENNACL_COMPRESSED_MATRIX_HPP #define _PYVIENNACL_COMPRESSED_MATRIX_HPP #include "sparse_matrix.hpp" #define EXPORT_COMPRESSED_MATRIX(TYPE) \ DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::compressed_matrix<TYPE>, \ vcl::compressed_matrix<TYPE>::handle_type&, \ handle, \ get_compressed_matrix_##TYPE##_handle, \ ()); \ DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::compressed_matrix<TYPE>, \ vcl::compressed_matrix<TYPE>::handle_type&, \ handle1, \ get_compressed_matrix_##TYPE##_handle1, \ ()); \ DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::compressed_matrix<TYPE>, \ vcl::compressed_matrix<TYPE>::handle_type&, \ handle2, \ get_compressed_matrix_##TYPE##_handle2, \ ()); \ bp::class_<vcl::compressed_matrix<TYPE>, \ vcl::tools::shared_ptr<vcl::compressed_matrix<TYPE> > > \ ("compressed_matrix_" #TYPE, bp::no_init) \ .add_property("memory_domain", \ &vcl::compressed_matrix<TYPE>::memory_context, \ &vcl::compressed_matrix<TYPE>::switch_memory_context) \ .add_property("handle", bp::make_function \ (get_compressed_matrix_##TYPE##_handle, \ bp::return_internal_reference<>())) \ .add_property("handle1", bp::make_function \ (get_compressed_matrix_##TYPE##_handle1, \ bp::return_internal_reference<>())) \ .add_property("handle2", bp::make_function \ (get_compressed_matrix_##TYPE##_handle2, \ bp::return_internal_reference<>())) \ .add_property("size1", \ make_function(&vcl::compressed_matrix<TYPE>::size1, \ bp::return_value_policy<bp::return_by_value>())) \ .add_property("size2", \ make_function(&vcl::compressed_matrix<TYPE>::size2, \ bp::return_value_policy<bp::return_by_value>())) \ .add_property("nnz", \ make_function(&vcl::compressed_matrix<TYPE>::nnz, \ bp::return_value_policy<bp::return_by_value>())) \ .def("prod", pyvcl_do_2ary_op<vcl::vector<TYPE>, \ vcl::compressed_matrix<TYPE>&, vcl::vector<TYPE>&, \ op_prod>) \ ; /* .def("inplace_solve", pyvcl_do_3ary_op<vcl::compressed_matrix<TYPE>, vcl::compressed_matrix<TYPE>&, vcl::vector<TYPE>&, vcl::linalg::lower_tag, op_inplace_solve>) .def("inplace_solve", pyvcl_do_3ary_op<vcl::compressed_matrix<TYPE>, vcl::compressed_matrix<TYPE>&, vcl::vector<TYPE>&, vcl::linalg::unit_lower_tag, op_inplace_solve>) .def("inplace_solve", pyvcl_do_3ary_op<vcl::compressed_matrix<TYPE>, vcl::compressed_matrix<TYPE>&, vcl::vector<TYPE>&, vcl::linalg::unit_upper_tag, op_inplace_solve>) .def("inplace_solve", pyvcl_do_3ary_op<vcl::compressed_matrix<TYPE>, vcl::compressed_matrix<TYPE>&, vcl::vector<TYPE>&, vcl::linalg::upper_tag, op_inplace_solve>) */ #endif
56.549296
79
0.476214
[ "vector" ]
02d35c5f12a8ce2841a545b49014f8a4b51bb246
4,799
cpp
C++
src/GafferUIBindings/RenderableGadgetBinding.cpp
dboogert/gaffer
d2ce0eb7134a33ceee375d0a3676129a9bdcfbc6
[ "BSD-3-Clause" ]
null
null
null
src/GafferUIBindings/RenderableGadgetBinding.cpp
dboogert/gaffer
d2ce0eb7134a33ceee375d0a3676129a9bdcfbc6
[ "BSD-3-Clause" ]
null
null
null
src/GafferUIBindings/RenderableGadgetBinding.cpp
dboogert/gaffer
d2ce0eb7134a33ceee375d0a3676129a9bdcfbc6
[ "BSD-3-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "boost/python/suite/indexing/container_utils.hpp" #include "IECoreGL/State.h" #include "IECorePython/ScopedGILRelease.h" #include "GafferBindings/SignalBinding.h" #include "GafferUIBindings/RenderableGadgetBinding.h" #include "GafferUIBindings/GadgetBinding.h" #include "GafferUI/RenderableGadget.h" using namespace boost::python; using namespace GafferBindings; using namespace GafferUIBindings; using namespace GafferUI; static IECoreGL::StatePtr baseState( RenderableGadget &g ) { return g.baseState(); } static RenderableGadgetPtr construct( IECore::VisibleRenderablePtr renderable ) { // we must release the GIL because the renderable might include a python procedural // which might get invoked on a separate thread by the renderer that VisibleRenderable // uses internally. IECorePython::ScopedGILRelease gilRelease; return new RenderableGadget( renderable ); } static void setRenderable( RenderableGadget &g, IECore::VisibleRenderablePtr renderable ) { // we must release the GIL because the renderable might include a python procedural // which might get invoked on a separate thread by the renderer that VisibleRenderable // uses internally. IECorePython::ScopedGILRelease gilRelease; g.setRenderable( renderable ); } static void setSelection( RenderableGadget &g, object pythonSelection ) { std::vector<std::string> vectorSelection; boost::python::container_utils::extend_container( vectorSelection, pythonSelection ); RenderableGadget::Selection selection( vectorSelection.begin(), vectorSelection.end() ); g.setSelection( selection ); } static object getSelection( RenderableGadget &g ) { const RenderableGadget::Selection &selection = g.getSelection(); boost::python::list selectionList; for( RenderableGadget::Selection::const_iterator it = selection.begin(); it != selection.end(); it++ ) { selectionList.append( *it ); } PyObject *selectionSet = PySet_New( selectionList.ptr() ); return object( handle<>( selectionSet ) ); } void GafferUIBindings::bindRenderableGadget() { GadgetClass<RenderableGadget>() .def( "__init__", make_constructor( construct, default_call_policies(), ( boost::python::arg( "renderable" ) = IECore::VisibleRenderablePtr() ) ) ) .def( "setRenderable", &setRenderable ) .def( "getRenderable", (IECore::VisibleRenderablePtr (RenderableGadget::*)())&RenderableGadget::getRenderable ) .def( "baseState", &baseState ) .def( "objectAt", &RenderableGadget::objectAt ) .def( "setSelection", &setSelection ) .def( "getSelection", &getSelection ) .def( "selectionChangedSignal", &RenderableGadget::selectionChangedSignal, return_internal_reference<1>() ) .def( "selectionBound", (Imath::Box3f (RenderableGadget::*)() const)&RenderableGadget::selectionBound ) ; SignalBinder<RenderableGadget::SelectionChangedSignal>::bind( "SelectionChangedSignal" ); }
41.37069
149
0.730152
[ "object", "vector" ]
02d6a20359017c93956d33db69f9ee15c9078e3f
1,080
cpp
C++
graphics-library/src/scene/scene_shape.cpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
graphics-library/src/scene/scene_shape.cpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
graphics-library/src/scene/scene_shape.cpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
#include "geometry/line.hpp" #include "math/matrix.hpp" #include "scene/scene_shape.hpp" namespace gl::scene { std::shared_ptr<SceneShape> SceneShape::create(const std::shared_ptr<geometry::Shape> &shape) { return std::shared_ptr<SceneShape>(new SceneShape(shape)); } SceneShape::SceneShape(const std::shared_ptr<geometry::Shape> &shape) : m_shape(shape) { } void SceneShape::drawSelf() const { glm::mat4 globalModel { getGlobalModel() }; glm::vec3 globalTranslation { gl::math::getTranslationFromMat4(globalModel) }; // Draw the object stored in this scene object m_shape->draw(getGlobalModel()); // Draw a line to the parent to easily visualise the scene tree if (m_parent != nullptr) { glm::mat4 parentModel { m_parent->getGlobalModel() }; glm::vec3 parentTranslation { gl::math::getTranslationFromMat4(parentModel) }; geometry::Line line(parentTranslation, globalTranslation); line.draw(); } } }
34.83871
100
0.633333
[ "geometry", "object", "shape" ]
02d8018dacfec30473424e2dba6805772758d12d
1,532
cpp
C++
aws-cpp-sdk-iotevents/source/model/IotSiteWiseAssetModelPropertyIdentifier.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-iotevents/source/model/IotSiteWiseAssetModelPropertyIdentifier.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-iotevents/source/model/IotSiteWiseAssetModelPropertyIdentifier.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-02-28T21:36:42.000Z
2022-02-28T21:36:42.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotevents/model/IotSiteWiseAssetModelPropertyIdentifier.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace IoTEvents { namespace Model { IotSiteWiseAssetModelPropertyIdentifier::IotSiteWiseAssetModelPropertyIdentifier() : m_assetModelIdHasBeenSet(false), m_propertyIdHasBeenSet(false) { } IotSiteWiseAssetModelPropertyIdentifier::IotSiteWiseAssetModelPropertyIdentifier(JsonView jsonValue) : m_assetModelIdHasBeenSet(false), m_propertyIdHasBeenSet(false) { *this = jsonValue; } IotSiteWiseAssetModelPropertyIdentifier& IotSiteWiseAssetModelPropertyIdentifier::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("assetModelId")) { m_assetModelId = jsonValue.GetString("assetModelId"); m_assetModelIdHasBeenSet = true; } if(jsonValue.ValueExists("propertyId")) { m_propertyId = jsonValue.GetString("propertyId"); m_propertyIdHasBeenSet = true; } return *this; } JsonValue IotSiteWiseAssetModelPropertyIdentifier::Jsonize() const { JsonValue payload; if(m_assetModelIdHasBeenSet) { payload.WithString("assetModelId", m_assetModelId); } if(m_propertyIdHasBeenSet) { payload.WithString("propertyId", m_propertyId); } return payload; } } // namespace Model } // namespace IoTEvents } // namespace Aws
20.426667
112
0.763708
[ "model" ]
02d911315898f526a1138a171af4c44b3021699e
73,963
cpp
C++
MMOCoreORB/src/server/zone/managers/auction/AuctionManagerImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/managers/auction/AuctionManagerImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/managers/auction/AuctionManagerImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * AuctionManagerImplementation.cpp * * Created on: 13/03/2010 * Author: victor */ #include "server/zone/managers/auction/AuctionManager.h" #include "server/zone/managers/auction/AuctionsMap.h" #include "server/zone/managers/object/ObjectManager.h" #include "templates/manager/TemplateManager.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/auction/AuctionItem.h" #include "server/zone/packets/auction/ItemSoldMessage.h" #include "server/zone/packets/auction/CancelLiveAuctionResponseMessage.h" #include "server/zone/packets/auction/AuctionQueryHeadersResponseMessage.h" #include "server/zone/packets/auction/RetrieveAuctionItemResponseMessage.h" #include "server/zone/packets/auction/BidAuctionResponseMessage.h" #include "server/zone/packets/scene/AttributeListMessage.h" #include "server/chat/StringIdChatParameter.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/waypoint/WaypointObject.h" #include "server/zone/Zone.h" #include "server/zone/ZoneServer.h" #include "server/chat/ChatManager.h" #include "CheckAuctionsTask.h" #include "ExpireAuctionTask.h" #include "server/zone/managers/vendor/VendorManager.h" #include "server/zone/objects/tangible/components/vendor/VendorDataComponent.h" #include "server/zone/objects/tangible/components/vendor/AuctionTerminalDataComponent.h" #include "server/zone/objects/player/sessions/TradeSession.h" #include "AuctionSearchTask.h" #include "server/zone/objects/factorycrate/FactoryCrate.h" #include "server/zone/objects/tangible/powerup/PowerupObject.h" #include "server/zone/objects/tangible/weapon/WeaponObject.h" void AuctionManagerImplementation::initialize() { Locker locker(_this.getReferenceUnsafeStaticCast()); Core::getTaskManager()->initializeCustomQueue("AuctionSearchQueue", ConfigManager::instance()->getMaxAuctionSearchJobs(), true); auctionMap = new AuctionsMap(); ObjectDatabase* auctionDatabase = ObjectDatabaseManager::instance()->loadObjectDatabase("auctionitems", true); ObjectDatabaseManager::instance()->commitLocalTransaction(); ObjectDatabaseIterator iterator(auctionDatabase); uint64 objectID = 0; Vector<ManagedReference<AuctionItem*> > orphanedBazaarItems; ManagedReference<SceneObject*> defaultBazaar = nullptr; ManagedReference<PlayerManager*> playerManager = zoneServer->getPlayerManager(); while (iterator.getNextKey(objectID)) { Reference<AuctionItem*> auctionItem = Core::getObjectBroker()->lookUp(objectID).castTo<AuctionItem*>(); ObjectDatabaseManager::instance()->commitLocalTransaction(); if(auctionItem == nullptr) { error("unable to load auction item: " + String::valueOf(objectID)); continue; } ManagedReference<SceneObject*> vendor = zoneServer->getObject(auctionItem->getVendorID()); if(vendor == nullptr || vendor->getZone() == nullptr) { if(auctionItem->isOnBazaar()) { orphanedBazaarItems.add(auctionItem); continue; } if(vendor != nullptr) { vendor->destroyObjectFromWorld(true); vendor->destroyObjectFromDatabase(); } ObjectManager::instance()->destroyObjectFromDatabase(auctionItem->_getObjectID()); warning("Auction Item's vendor is gone, deleting auction item: " + String::valueOf(auctionItem->_getObjectID())); continue; } String ownerName = playerManager->getPlayerName(auctionItem->getOwnerID()); if (ownerName.isEmpty()) { error("Auction for item " + String::valueOf(auctionItem->getAuctionedItemObjectID()) + " had invalid owner, oid: " + String::valueOf(auctionItem->getOwnerID()) + ", deleting item."); uint64 sellingId = auctionItem->getAuctionedItemObjectID(); auctionMap->deleteItem(vendor, auctionItem); Core::getTaskManager()->executeTask([this, sellingId] () { ManagedReference<SceneObject*> sceno = zoneServer->getObject(sellingId); if (sceno != nullptr) { Locker locker(sceno); sceno->destroyObjectFromDatabase(true); } }, "DeleteAuctionItemLambda", "slowQueue"); continue; } uint64 vendorExpire = time(0) + AuctionManager::VENDOREXPIREPERIOD; uint64 commodityExpire = time(0) + AuctionManager::COMMODITYEXPIREPERIOD; uint64 oldExpire = 0; if (auctionItem->getStatus() == AuctionItem::FORSALE && auctionItem->getExpireTime() > vendorExpire) { oldExpire = auctionItem->getExpireTime(); auctionItem->setExpireTime(vendorExpire); error("Auction for item " + String::valueOf(auctionItem->getAuctionedItemObjectID()) + " had invalid expiration time. Old: " + String::valueOf(oldExpire) + ", new: " + String::valueOf(auctionItem->getExpireTime()) + ", owner: " + ownerName); } if (auctionItem->getStatus() == AuctionItem::OFFERED && auctionItem->getExpireTime() > commodityExpire) { oldExpire = auctionItem->getExpireTime(); auctionItem->setExpireTime(commodityExpire); error("Auction for item " + String::valueOf(auctionItem->getAuctionedItemObjectID()) + " had invalid expiration time. Old: " + String::valueOf(oldExpire) + ", new: " + String::valueOf(auctionItem->getExpireTime()) + ", owner: " + ownerName); } if(vendor->isBazaarTerminal() && defaultBazaar == nullptr) defaultBazaar = vendor; auctionMap->addItem(nullptr, vendor, auctionItem); if(auctionItem->isOnBazaar() || auctionItem->getStatus() == AuctionItem::OFFERED) auctionMap->addToCommodityLimit(auctionItem); if(auctionItem->isAuction()) { Reference<Task*> newTask = new ExpireAuctionTask(_this.getReferenceUnsafeStaticCast(), auctionItem); newTask->schedule((auctionItem->getExpireTime() - time(0)) * 1000); Locker locker(&auctionEvents); auctionEvents.put(auctionItem->getAuctionedItemObjectID(), newTask); } } /// This is in case a bazaar is removed, it could move and item /// to a difference city, but at least it doesn't poof if(defaultBazaar != nullptr) { for(int i = 0; i < orphanedBazaarItems.size(); ++i) { ManagedReference<AuctionItem*> auctionItem = orphanedBazaarItems.get(i); String vuid = getVendorUID(defaultBazaar); auctionMap->addItem(nullptr, defaultBazaar, auctionItem); Locker alocker(auctionItem); auctionItem->setVendorID(defaultBazaar->getObjectID()); if(auctionItem->isAuction()) { Reference<Task*> newTask = new ExpireAuctionTask(_this.getReferenceUnsafeStaticCast(), auctionItem); newTask->schedule((auctionItem->getExpireTime() - time(0)) * 1000); Locker locker(&auctionEvents); auctionEvents.put(auctionItem->getAuctionedItemObjectID(), newTask); } } } for(int i = 0; i < pendingUIDUpdates.size(); ++i) { ManagedReference<SceneObject*> vendor = pendingUIDUpdates.elementAt(i).getKey(); String uid = pendingUIDUpdates.get(vendor); String oldUID = pendingOldUIDUpdates.get(vendor); auctionMap->updateUID(vendor, oldUID, uid); } locker.release(); Core::getTaskManager()->executeTask([=] () { checkAuctions(true); checkVendorItems(true); }, "StartupAuctionManagerCheck", "slowQueue"); info("loaded auctionsMap of size: " + String::valueOf(auctionMap->getTotalItemCount()), true); marketEnabled = true; } void AuctionManagerImplementation::checkVendorItems(bool startupTask) { if (startupTask) info("checkVendorItems initial startup task", true); Timer timer(Time::MONOTONIC_TIME); timer.start(); TerminalListVector items = auctionMap->getVendorTerminalData("", "", 0); info("Checking " + String::valueOf(items.size()) + " vendor terminals", true); doAuctionMaint(&items, "vendor", startupTask); auto elapsed = timer.stopMs(); info("Vendor terminal checks completed in " + String::valueOf(elapsed) + "ms", true); } void AuctionManagerImplementation::checkAuctions(bool startupTask) { if (startupTask) info("checkAuctions initial startup task", true); Reference<CheckAuctionsTask*> task = new CheckAuctionsTask(_this.getReferenceUnsafeStaticCast()); task->schedule(CHECKEVERY * 60 * 1000); Timer timer(Time::MONOTONIC_TIME); timer.start(); TerminalListVector items = auctionMap->getBazaarTerminalData("", "", 0); info("Checking " + String::valueOf(items.size()) + " bazaar terminals", true); doAuctionMaint(&items, "bazaar", startupTask); auto elapsed = timer.stopMs(); info("Bazaar terminal checks completed in " + String::valueOf(elapsed) + "ms", true); } void AuctionManagerImplementation::doAuctionMaint(TerminalListVector* items, const String& logTag, bool startupTask) { Time expireTime; uint64 currentTime = expireTime.getMiliTime() / 1000; int count_total = 0; int count_updated = 0; for (int i = 0; i < items->size(); ++i) { Reference<TerminalItemList*>& list = items->get(i); if (list == nullptr || list->size() == 0) continue; for (int j = 0; j < list->size(); ++j) { ManagedReference<AuctionItem*> item = list->get(j); if (item == nullptr) continue; Locker locker(item); count_total++; ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); ManagedReference<PlayerManager*> playerManager = zoneServer->getPlayerManager(); String ownerName = playerManager->getPlayerName(item->getOwnerID()); if(vendor == nullptr || vendor->getZone() == nullptr || ownerName.isEmpty()) { uint64 sellingId = item->getAuctionedItemObjectID(); auctionMap->deleteItem(vendor, item); if (ownerName.isEmpty()) error("Auction for item " + String::valueOf(item->getAuctionedItemObjectID()) + " had invalid owner, oid: " + String::valueOf(item->getOwnerID()) + ", deleting item."); Core::getTaskManager()->executeTask([this, sellingId] () { ManagedReference<SceneObject*> sceno = zoneServer->getObject(sellingId); if (sceno != nullptr) { Locker locker(sceno); sceno->destroyObjectFromDatabase(true); } }, "DeleteAuctionItemLambda", "slowQueue"); continue; } uint64 vendorExpire = time(0) + AuctionManager::VENDOREXPIREPERIOD; uint64 commodityExpire = time(0) + AuctionManager::COMMODITYEXPIREPERIOD; bool updatedExpire = false; uint64 oldExpire = 0; if (item->getStatus() == AuctionItem::FORSALE && item->getExpireTime() > vendorExpire) { oldExpire = item->getExpireTime(); item->setExpireTime(vendorExpire); updatedExpire = true; } if (item->getStatus() == AuctionItem::OFFERED && item->getExpireTime() > commodityExpire) { oldExpire = item->getExpireTime(); item->setExpireTime(commodityExpire); updatedExpire = true; } if (updatedExpire) { if(item->isAuction() && auctionEvents.contains(item->getAuctionedItemObjectID())) { Reference<Task*> newTask = auctionEvents.get(item->getAuctionedItemObjectID()); if(newTask != nullptr) newTask->reschedule((item->getExpireTime() - time(0)) * 1000); } error("Auction for item " + String::valueOf(item->getAuctionedItemObjectID()) + " had invalid expiration time. Old: " + String::valueOf(oldExpire) + ", new: " + String::valueOf(item->getExpireTime()) + ", owner: " + ownerName); } if (item->getExpireTime() <= currentTime) { if (item->getStatus() == AuctionItem::EXPIRED) { expireSale(item); continue; } } if (item->getStatus() == AuctionItem::RETRIEVED) { auctionMap->deleteItem(vendor, item); continue; } if (startupTask && !item->isUpdated()) { uint64 sellingId = item->getAuctionedItemObjectID(); ManagedReference<SceneObject*> sellingItem = zoneServer->getObject(sellingId); if (sellingItem != nullptr) { if (sellingItem->isFactoryCrate()) { Locker clocker(sellingItem, item); Reference<FactoryCrate*> crate = sellingItem.castTo<FactoryCrate*>(); if (crate != nullptr) { ManagedReference<TangibleObject*> prototype = crate->getPrototype(); if (prototype != nullptr) { item->setFactoryCrate(true); item->setCratedItemType(prototype->getClientGameObjectType()); } } } else { if (item->isFactoryCrate()) { item->setFactoryCrate(false); } if (item->getCratedItemType() != 0) { item->setCratedItemType(0); } } } item->setUpdated(true); count_updated++; } } } info(logTag + " Checked " + String::valueOf(count_total) + " auction item(s) and updated " + String::valueOf(count_updated) + " item(s)", true); } void AuctionManagerImplementation::addSaleItem(CreatureObject* player, uint64 objectid, SceneObject* vendor, const UnicodeString& description, int price, uint32 duration, bool auction, bool premium, bool isRelist) { int bank = player->getBankCredits(); int cash = player->getCashCredits(); int totalFunds = bank + cash; if (vendor == nullptr || (!vendor->isVendor() && !vendor->isBazaarTerminal())) { error("terminal is not a valid vendor object"); ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::VENDORNOTWORKING); player->sendMessage(soldMessage); return; } if (player->isDead() || player->isIncapacitated()) { ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::UNKNOWNERROR); player->sendMessage(soldMessage); return; } ManagedReference<TradeSession*> tradeContainer = player->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>(); if (tradeContainer != nullptr) { zoneServer->getPlayerManager()->handleAbortTradeMessage(player); } ManagedReference<AuctionItem*> oldItem = auctionMap->getItem(objectid); ManagedReference<SceneObject*> objectToSell = zoneServer->getObject(objectid); if (objectToSell->isWeaponObject()) { ManagedReference<WeaponObject*> weapon = cast<WeaponObject*>(objectToSell.get()); if (weapon->hasPowerup()) { Locker wlocker(weapon); ManagedReference<PowerupObject*> pup = weapon->removePowerup(); if (pup != NULL) { Locker puplocker(pup); pup->destroyObjectFromWorld(true); pup->destroyObjectFromDatabase(true); } } } String vendorUID = getVendorUID(vendor); bool stockroomSale = false; if (objectToSell == nullptr || objectToSell->isNoTrade() || objectToSell->containsNoTradeObjectRecursive()) { ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::INVALIDITEM); player->sendMessage(soldMessage); return; } if(oldItem == nullptr) { if (objectToSell == nullptr || !objectToSell->isASubChildOf(player)) { if(objectToSell != nullptr) error("trying to add invalid object"); ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::INVALIDITEM); player->sendMessage(soldMessage); return; } } else { if(oldItem->getStatus() == AuctionItem::FORSALE) { ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::ALREADYFORSALE); player->sendMessage(soldMessage); return; } /// Is it being sold from the stockroom if (oldItem->getOwnerID() != player->getObjectID()) { error("trying to add invalid object"); ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::INVALIDITEM); player->sendMessage(soldMessage); return; } stockroomSale = true; ManagedReference<SceneObject*> oldVendor = zoneServer->getObject(oldItem->getVendorID()); if (oldVendor != nullptr && oldVendor->isVendor()) vendor = oldVendor; } ManagedReference<Zone*> zone = vendor->getZone(); if (zone == nullptr) { error("null vendor zone"); ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::UNKNOWNERROR); player->sendMessage(soldMessage); return; } int res = checkSaleItem(player, objectToSell, vendor, price, premium, stockroomSale); if (res != 0) { ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, res); player->sendMessage(soldMessage); return; } if (oldItem != nullptr) auctionMap->deleteItem(vendor, oldItem); if(auctionMap->containsItem(objectToSell->getObjectID())) { ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::ALREADYFORSALE); player->sendMessage(soldMessage); return; } // add city tax to the price ManagedReference<CityRegion*> city = vendor->getCityRegion().get(); if (city != nullptr && !isRelist) { price *= (1.0f + (city->getSalesTax() / 100.0f)); } ManagedReference<AuctionItem*> item = createVendorItem(player, objectToSell.get(), vendor, description, price, duration, auction, premium); if(item == nullptr) { error("Unable to create vendor item"); ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, ItemSoldMessage::UNKNOWNERROR); player->sendMessage(soldMessage); return; } Locker locker(item); int result = auctionMap->addItem(player, vendor, item); if(result != ItemSoldMessage::SUCCESS) { ItemSoldMessage* soldMessage = new ItemSoldMessage(objectid, result); player->sendMessage(soldMessage); auctionMap->removeFromCommodityLimit(item); return; } Locker objectToSellLocker(objectToSell); objectToSell->destroyObjectFromWorld(true); objectToSellLocker.release(); if (vendor->isBazaarTerminal()) { StringIdChatParameter str("@base_player:sale_fee"); // The fee for your listing is %DI credits. float costReduction = 1; if(player->hasSkill("crafting_merchant_sales_01")) costReduction = .80f; if(player->hasSkill("crafting_merchant_sales_03")) costReduction = .60f; if (item->isPremiumAuction()) { int listCost = costReduction * (SALESFEE * 5); if (bank < listCost) { int diff = listCost - bank; if (diff > cash) { player->sendSystemMessage("You do not have enough credits to cover the listing fee"); return; } player->subtractBankCredits(bank); //Take all from bank, since they didn't have enough to cover. player->subtractCashCredits(diff); //Take the rest from cash. str.setDI(listCost); } else { player->subtractBankCredits(listCost); //Take all of the payment from bank. str.setDI(listCost); } } else { int listCost = costReduction * SALESFEE; if (bank < listCost) { int diff = listCost - bank; if (diff > cash) { player->sendSystemMessage("You do not have enough credits to cover the listing fee"); return; } player->subtractBankCredits(bank); //Take all from bank, since they didn't have enough to cover. player->subtractCashCredits(diff); //Take the rest from cash. str.setDI(listCost); } else { player->subtractBankCredits(listCost); //Take all of the payment from bank. str.setDI(listCost); } } player->sendSystemMessage(str); } if (item->getStatus() == AuctionItem::OFFERED) { VendorDataComponent* vendorData = nullptr; DataObjectComponentReference* data = vendor->getDataObjectComponent(); if(data != nullptr && data->get() != nullptr && data->get()->isVendorData()) vendorData = cast<VendorDataComponent*>(data->get()); if(vendorData != nullptr) { ManagedReference<SceneObject*> strongRef = zoneServer->getObject(vendorData->getOwnerId()); if (strongRef != nullptr && strongRef->isPlayerCreature()) { ManagedReference<CreatureObject*> strongOwnerRef = cast<CreatureObject*>(strongRef.get()); if(strongOwnerRef->isOnline()) { strongOwnerRef->sendSystemMessage(player->getFirstName() + " has offered an item to " + vendor->getDisplayedName()); } // Flurry: Email player about offer to vendor UnicodeString subject("@auction:vedor_offer_subject"); // An item has been offered to your vendor StringIdChatParameter offerBody("@auction:vedor_offer_body"); // %TU has been offered %TO by %TT for %DI credits. offerBody.setTU(vendor->getDisplayedName()); offerBody.setTO(item->getItemName()); offerBody.setTT(player->getDisplayedName()); offerBody.setDI(item->getPrice()); float waypointX = vendor->getWorldPositionX(); float waypointY = vendor->getWorldPositionY(); ManagedReference<WaypointObject*> waypointObject = ( zoneServer->createObject(STRING_HASHCODE("object/waypoint/world_waypoint_blue.iff"), 1)).castTo<WaypointObject*>(); Locker lockerWaypointObject(waypointObject); waypointObject->setCustomObjectName(vendor->getDisplayedName(), false); waypointObject->setActive(false); waypointObject->setPosition(waypointX, 0, waypointY); waypointObject->setPlanetCRC(vendor->getPlanetCRC()); lockerWaypointObject.release(); ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); if (cman != NULL) cman->sendMail(vendor->getDisplayedName(), subject, offerBody, strongOwnerRef->getFirstName(), waypointObject); } } } item->setPersistent(1); if(item->isAuction()) { Reference<Task*> newTask = new ExpireAuctionTask(_this.getReferenceUnsafeStaticCast(), item); newTask->schedule((item->getExpireTime() - time(0)) * 1000); Locker locker(&auctionEvents); auctionEvents.put(item->getAuctionedItemObjectID(), newTask); } BaseMessage* msg = new ItemSoldMessage(objectid, 0); player->sendMessage(msg); } String AuctionManagerImplementation::getVendorUID(SceneObject* vendor) { //planet.region.vendorname.oid#x,y if(vendor->getZone() == nullptr) { error("no zone for our poor vendor"); return "nozone.nozone.sadpandavendor." + String::valueOf(vendor->getObjectID()) + "#0,0"; } String uid = "error.error.errorvendor." + String::valueOf(vendor->getObjectID()) + "#0,0"; AuctionTerminalDataComponent* terminalData = nullptr; DataObjectComponentReference* data = vendor->getDataObjectComponent(); if(data != nullptr && data->get() != nullptr && data->get()->isAuctionTerminalData()) terminalData = cast<AuctionTerminalDataComponent*>(data->get()); if(terminalData != nullptr) uid = terminalData->getUID(); return uid; } int AuctionManagerImplementation::checkSaleItem(CreatureObject* player, SceneObject* object, SceneObject* vendor, int price, bool premium, bool stockroomSale) { if (vendor == nullptr) { error("nullptr Vendor"); return ItemSoldMessage::UNKNOWNERROR; } if (price < 1) return ItemSoldMessage::INVALIDSALEPRICE; if (player->getPlayerObject()->getVendorCount() > player->getSkillMod("manage_vendor")) return ItemSoldMessage::TOOMANYITEMS; if (vendor->isVendor()) { VendorDataComponent* vendorData = cast<VendorDataComponent*>(vendor->getDataObjectComponent()->get()); if (vendorData == nullptr) { return ItemSoldMessage::UNKNOWNERROR; } if (player->getObjectID() == vendorData->getOwnerId()) { if (stockroomSale) { if (auctionMap->getPlayerItemCount(player) > player->getSkillMod("vendor_item_limit")) return ItemSoldMessage::TOOMANYITEMS; } else { if ((auctionMap->getPlayerItemCount(player) + object->getSizeOnVendorRecursive()) > player->getSkillMod("vendor_item_limit")) return ItemSoldMessage::TOOMANYITEMS; } } else { if (auctionMap->getCommodityCount(player) >= MAXSALES) return ItemSoldMessage::TOOMANYITEMS; } if (price > MAXVENDORPRICE) return ItemSoldMessage::INVALIDSALEPRICE; } if (vendor->isBazaarTerminal()) { if (auctionMap->getCommodityCount(player) >= MAXSALES) return ItemSoldMessage::TOOMANYITEMS; if (price > MAXBAZAARPRICE) return ItemSoldMessage::INVALIDSALEPRICE; int bank = player->getBankCredits(); int cash = player->getCashCredits(); int availableCredits = bank + cash; if (availableCredits < SALESFEE) return ItemSoldMessage::NOTENOUGHCREDITS; if (premium && availableCredits < SALESFEE * 5) return ItemSoldMessage::NOTENOUGHCREDITS; } if (object->isIntangibleObject() && !object->isManufactureSchematic()) return ItemSoldMessage::INVALIDITEM; for (int i = 0; i < object->getArrangementDescriptorSize(); ++i) { const Vector<String>* descriptors = object->getArrangementDescriptor(i); for (int j = 0; j < descriptors->size(); ++j) { const String& descriptor = descriptors->get(j); if (descriptor == "inventory" || descriptor == "datapad" || descriptor == "default_weapon" || descriptor == "mission_bag" || descriptor == "ghost" || descriptor == "bank" || descriptor == "hair") return ItemSoldMessage::INVALIDITEM; } } return 0; } AuctionItem* AuctionManagerImplementation::createVendorItem(CreatureObject* player, SceneObject* objectToSell, SceneObject* vendor, const UnicodeString& description, int price, unsigned int duration, bool auction, bool premium) { Zone* zone = vendor->getZone(); if (zone == nullptr) return nullptr; uint64 vendorExpire = time(0) + AuctionManager::VENDOREXPIREPERIOD; uint64 commodityExpire = time(0) + AuctionManager::COMMODITYEXPIREPERIOD; String playername = player->getFirstName().toLowerCase(); String descr = description.toString(); String planetStr = zone->getZoneName(); AuctionItem* item = new AuctionItem(objectToSell->getObjectID()); ManagedReference<CityRegion*> cityRegion = vendor->getCityRegion().get(); String region = "@planet_n:" + planetStr; if (cityRegion != nullptr) region = cityRegion->getRegionName(); String name = objectToSell->getDisplayedName(); Locker locker(item); item->setVendorUID(getVendorUID(vendor)); item->setOnBazaar(vendor->isBazaarTerminal()); if (premium) item->setAuctionPremium(); item->setVendorID(vendor->getObjectID()); item->setItemName(name); item->setItemDescription(description.toString()); if (objectToSell->isFactoryCrate()) { ManagedReference<FactoryCrate*> crate = cast<FactoryCrate*>(objectToSell); if (crate != nullptr) { ManagedReference<TangibleObject*> prototype = crate->getPrototype(); if (prototype != nullptr) { item->setFactoryCrate(true); item->setCratedItemType(prototype->getClientGameObjectType()); item->setUpdated(true); } } } item->setItemType(objectToSell->getClientGameObjectType()); item->setPrice(price); item->setAuction(auction); item->setStatus(AuctionItem::FORSALE); item->setBuyerID(0); item->setBidderName(""); item->setSize(objectToSell->getSizeOnVendorRecursive()); VendorDataComponent* vendorData = nullptr; DataObjectComponentReference* data = vendor->getDataObjectComponent(); if(data != nullptr && data->get() != nullptr && data->get()->isVendorData()) vendorData = cast<VendorDataComponent*>(data->get()); if (!vendor->isBazaarTerminal()) { if(vendorData == nullptr) return nullptr; // Someone else's Vendor (making this sell item an offer) if(vendorData->getOwnershipRightsOf(player) == 1) { item->setStatus(AuctionItem::OFFERED); item->setOfferToID(vendorData->getOwnerId()); item->setExpireTime(commodityExpire); } else { item->setExpireTime(vendorExpire); if(auctionMap->getVendorItemCount(vendor, true) == 0) sendVendorUpdateMail(vendor, false); } } else { item->setExpireTime(commodityExpire); } updateAuctionOwner(item, player); ObjectManager::instance()->persistObject(item, 0, "auctionitems"); return item; } int AuctionManagerImplementation::checkBidAuction(CreatureObject* player, AuctionItem* item, int price1, int price2) { if ((price1 > MAXBAZAARPRICE || price2 > MAXBAZAARPRICE) && item->isOnBazaar()) { return BidAuctionResponseMessage::PRICEOVERFLOW; } if (price1 < 1 || price2 < 1 || price1 < item->getPrice()) { return BidAuctionResponseMessage::INVALIDPRICE; } int bank = player->getBankCredits(); int cash = player->getCashCredits(); int availableCredits = bank + cash; if (availableCredits < price1) { // Credit Check return BidAuctionResponseMessage::NOTENOUGHCREDITS; } return 0; } void AuctionManagerImplementation::doInstantBuy(CreatureObject* player, AuctionItem* item) { ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if (vendor == nullptr) return; int tax = 0; int bank = player->getBankCredits(); int cash = player->getCashCredits(); int availableCredits = bank + cash; ManagedReference<CityRegion*> city = nullptr; String vendorPlanetName("@planet_n:" + vendor->getZone()->getZoneName()); String vendorRegionName = vendorPlanetName; city = vendor->getCityRegion().get(); if( city != nullptr) { tax = item->getPrice() - ( item->getPrice() / ( 1.0f + (city->getSalesTax() / 100.f))); vendorRegionName = city->getRegionName(); } String playername = player->getFirstName().toLowerCase(); ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); ManagedReference<PlayerManager*> pman = zoneServer->getPlayerManager(); ManagedReference<CreatureObject*> seller = pman->getPlayer(item->getOwnerName()); String sender = "auctioner"; String sellerName = item->getOwnerName(); Time expireTime; uint64 currentTime = expireTime.getMiliTime() / 1000; uint64 availableTime = 0; Locker locker(item); if(item->isOnBazaar() || item->getStatus() == AuctionItem::OFFERED) availableTime = currentTime + AuctionManager::COMMODITYEXPIREPERIOD; else availableTime = currentTime + AuctionManager::VENDOREXPIREPERIOD; updateAuctionOwner(item, player); item->setStatus(AuctionItem::SOLD); item->setExpireTime(availableTime); item->setBuyerID(player->getObjectID()); item->setBidderName(playername); item->clearAuctionWithdraw(); int itemPrice = item->getPrice(); if (bank < itemPrice) { int diff = itemPrice - bank; if (diff > cash){ player->sendSystemMessage("You lack sufficent credits to make this purchase."); return; } player->subtractBankCredits(bank); //Take all from bank, since they didn't have enough to cover. player->subtractCashCredits(diff); //Take the rest from cash. } else { player->subtractBankCredits(itemPrice); //Take all of the payment from bank. } BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), 0); player->sendMessage(msg); // Waypoint to Vendor / bazaar float waypointX = vendor->getWorldPositionX(); float waypointY = vendor->getWorldPositionY(); WaypointChatParameter waypointParam; waypointParam.set(vendor->getDisplayedName(), waypointX, 0, waypointY, vendor->getPlanetCRC()); String itemName = removeColorCodes(item->getItemName()); if (!item->isOnBazaar()) { //Setup the mail to the vendor owner PlayerManager* pman = zoneServer->getPlayerManager(); /*ManagedReference<CreatureObject*> seller = pman->getPlayer(item->getOwnerName()); Locker _locker(seller);*/ StringIdChatParameterVector sellerBodyVector; WaypointChatParameterVector sellerWaypointVector; UnicodeString sellerSubject("@auction:subject_vendor_seller"); // Vendor Sale Complete StringIdChatParameter sellerBodySale("@auction:seller_success_vendor"); // %TU has sold %TO to %TT for %DI credits. sellerBodySale.setTU(vendor->getDisplayedName()); sellerBodySale.setTO(itemName); sellerBodySale.setTT(item->getBidderName()); sellerBodySale.setDI(item->getPrice()); StringIdChatParameter sellerBodyLoc("@auction:seller_success_location"); // The sale took place at %TT, on %TO. sellerBodyLoc.setTO(vendorPlanetName); sellerBodyLoc.setTT(vendorRegionName); sellerBodyVector.add(sellerBodySale); sellerBodyVector.add(sellerBodyLoc); sellerWaypointVector.add(waypointParam); //Setup the mail to the buyer /*ManagedReference<CreatureObject*> buyer = pman->getPlayer(item->getBidderName()); Locker _locker2(buyer);*/ StringIdChatParameterVector buyerBodyVector; WaypointChatParameterVector buyerWaypointVector; UnicodeString buyerSubject("@auction:subject_vendor_buyer"); // Vendor Item Purchased StringIdChatParameter buyerBodySale("@auction:buyer_success"); // You have won the auction of "%TO" from "%TT" for %DI credits. See the attached waypoint for location. buyerBodySale.setTO(itemName); buyerBodySale.setTT(sellerName); buyerBodySale.setDI(item->getPrice()); StringIdChatParameter buyerBodyLoc("@auction:buyer_success_location"); // The sale took place at %TT, on %TO. buyerBodyLoc.setTO(vendorPlanetName); buyerBodyLoc.setTT(vendorRegionName); buyerBodyVector.add(buyerBodySale); buyerBodyVector.add(buyerBodyLoc); buyerWaypointVector.add(waypointParam); //Send the Mail locker.release(); UnicodeString blankBody; cman->sendMail(sender, sellerSubject, blankBody, sellerName, &sellerBodyVector, &sellerWaypointVector); cman->sendMail(sender, buyerSubject, blankBody, item->getBidderName(), &buyerBodyVector, &buyerWaypointVector); if(auctionMap->getVendorItemCount(vendor, true) == 0) sendVendorUpdateMail(vendor, true); } else { StringIdChatParameterVector sellerBodyVector; WaypointChatParameterVector sellerWaypointVector; // Setup the mail to the seller UnicodeString sellerSubject("@auction:subject_instant_seller"); // Instant Sale Complete StringIdChatParameter sellerBodySale("@auction:seller_success"); // Your auction of %TO has been sold to %TT for %DI credits sellerBodySale.setTO(itemName); sellerBodySale.setTT(item->getBidderName()); sellerBodySale.setDI(item->getPrice()); StringIdChatParameter sellerBodyLoc("@auction:seller_success_location"); // The sale took place at %TT, on %TO. sellerBodyLoc.setTO(vendorPlanetName); sellerBodyLoc.setTT(vendorRegionName); sellerBodyVector.add(sellerBodySale); sellerBodyVector.add(sellerBodyLoc); sellerWaypointVector.add(waypointParam); // Setup the mail to the buyer StringIdChatParameterVector buyerBodyVector; WaypointChatParameterVector buyerWaypointVector; UnicodeString buyerSubject("@auction:subject_instant_buyer"); // Instant Sale Item Purchased StringIdChatParameter buyerBodySale("@auction:buyer_success"); // You have won the auction of "%TO" from "%TT" for %DI credits. See the attached waypoint for location. buyerBodySale.setTO(itemName); buyerBodySale.setTT(sellerName); buyerBodySale.setDI(item->getPrice()); StringIdChatParameter buyerBodyLoc("@auction:buyer_success_location"); // The sale took place at %TT, on %TO. buyerBodyLoc.setTO(vendorPlanetName); buyerBodyLoc.setTT(vendorRegionName); buyerBodyVector.add(buyerBodySale); buyerBodyVector.add(buyerBodyLoc); locker.release(); buyerWaypointVector.add(waypointParam); //Send the Mail UnicodeString blankBody; cman->sendMail(sender, sellerSubject, blankBody, sellerName, &sellerBodyVector, &sellerWaypointVector); cman->sendMail(sender, buyerSubject, blankBody, item->getBidderName(), &buyerBodyVector, &buyerWaypointVector); } if (seller == nullptr) { error("seller null for name " + item->getOwnerName()); return; } locker.release(); // Skim % of vendor sale into vendor maint int skim = 0; if (!item->isOnBazaar() && item->getPrice() > 10){ VendorDataComponent* vendorData = NULL; DataObjectComponentReference* data = vendor->getDataObjectComponent(); if(data != NULL && data->get() != NULL && data->get()->isVendorData()) vendorData = cast<VendorDataComponent*>(data->get()); if(vendorData != NULL){ skim = item->getPrice() * 0.05; // 5% if(skim > 100000) // Respecting hard cap in VendorData handlePayMaintanence() skim = 100000; vendorData->skimMaintanence(skim); } } Locker slocker(seller); seller->addBankCredits(item->getPrice() - tax - skim); slocker.release(); if(city != nullptr && !city->isClientRegion() && tax){ Locker clock(city); city->addToCityTreasury(tax); } } void AuctionManagerImplementation::doAuctionBid(CreatureObject* player, AuctionItem* item, int price1, int proxyBid) { if(price1 <= item->getPrice() || proxyBid <= price1) { BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), 1); player->sendMessage(msg); return; } String playername = player->getFirstName().toLowerCase(); ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); ManagedReference<PlayerManager*> pman = zoneServer->getPlayerManager(); // don't allow owner bid on the item. don't allow old auction info // send auctioner invalid message if (playername == item->getOwnerName() || price1 <= item->getPrice() || proxyBid <= price1) { BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), 1); player->sendMessage(msg); return; } ManagedReference<CreatureObject*> priorBidder = pman->getPlayer(item->getBidderName()); /// Use previous proxy if(priorBidder != nullptr && proxyBid < item->getProxy()) { Locker locker(item); Locker plocker(priorBidder); int increase = price1 - item->getPrice(); int fullPrice = proxyBid + increase - item->getPrice(); int priorBank = priorBidder->getBankCredits(); int priorCash = priorBidder->getCashCredits(); int priorAvailableCredits = priorBank + priorCash; //TODO: prior didnt have enough money -> assert.. fix properly if (priorAvailableCredits < fullPrice) { BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), BidAuctionResponseMessage::NOTENOUGHCREDITS); player->sendMessage(msg); return; } if (priorBank < fullPrice) { int priorDiff = fullPrice - priorBank; //TODO: prior didnt have enough money -> assert.. fix properly if (priorDiff > priorCash){ BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), BidAuctionResponseMessage::NOTENOUGHCREDITS); player->sendMessage(msg); return; } priorBidder->subtractBankCredits(priorBank); //Take all from bank, since they didn't have enough to cover. priorBidder->subtractCashCredits(priorDiff); //Take the rest from cash. } else { priorBidder->subtractBankCredits(fullPrice); //Take all of the payment from bank. } item->setPrice(proxyBid + increase); BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), BidAuctionResponseMessage::SUCCEDED); player->sendMessage(msg); if(priorBidder != player) { StringIdChatParameter body("@auction:bidder_outbid"); body.setTO(item->getItemName()); priorBidder->sendSystemMessage(body); } return; } Locker locker(item); Locker plocker(player); int playerBank = player->getBankCredits(); int playerCash = player->getCashCredits(); int playerAvailableCredits = playerBank + playerCash; if (playerAvailableCredits < price1 || playerAvailableCredits < item->getPrice()) { BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), BidAuctionResponseMessage::NOTENOUGHCREDITS); player->sendMessage(msg); return; } item->setProxy(proxyBid); // send prior bidder their money back if (item->getBidderName().length() > 0) { String itemName = removeColorCodes(item->getItemName()); StringIdChatParameter bidderBody("@auction:bidder_outbid"); // You have been outbid on the "%TO" that you were bidding on. bidderBody.setTO(itemName); // mail prior bidder with outcome UnicodeString bidderSubject("@auction:subject_auction_outbid"); // Auction Outbid item->setPrice(price1); item->setBuyerID(player->getObjectID()); item->setBidderName(playername); // take money from high bidder if (playerBank < item->getPrice()) { int playerDiff = item->getPrice() - playerBank; if (playerDiff > playerCash){ player->sendSystemMessage("You lack sufficent funds to make this purchase."); return; } player->subtractBankCredits(playerBank); //Take all from bank, since they didn't have enough to cover. player->subtractCashCredits(playerDiff); //Take the rest from cash. } else { player->subtractBankCredits(item->getPrice()); //Take all of the payment from bank. } if (priorBidder != nullptr) { Locker clocker(priorBidder, player); if (priorBidder != player) priorBidder->sendSystemMessage(bidderBody); priorBidder->addBankCredits(item->getPrice()); } plocker.release(); locker.release(); String sender = "auctioner"; cman->sendMail(sender, bidderSubject, bidderBody, item->getBidderName()); // no prior bidder, just take the money } else { item->setPrice(price1); item->setBuyerID(player->getObjectID()); item->setBidderName(playername); if (playerBank < item->getPrice()) { int playerDiff = item->getPrice() - playerBank; if (playerDiff > playerCash){ player->sendSystemMessage("You lack sufficent funds to make this purchase."); return; } player->subtractBankCredits(playerBank); //Take all from bank, since they didn't have enough to cover. player->subtractCashCredits(playerDiff); //Take the rest from cash. } else { player->subtractBankCredits(item->getPrice()); //Take all of the payment from bank. } } BaseMessage* msg = new BidAuctionResponseMessage(item->getAuctionedItemObjectID(), 0); player->sendMessage(msg); } void AuctionManagerImplementation::buyItem(CreatureObject* player, uint64 objectid, int price1, int price2) { ManagedReference<AuctionItem*> item = auctionMap->getItem(objectid); if (item == nullptr) { BaseMessage* msg = new BidAuctionResponseMessage(objectid, BidAuctionResponseMessage::INVALIDITEM); player->sendMessage(msg); return; } ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if (vendor == nullptr || item->getStatus() == AuctionItem::SOLD) { BaseMessage* msg = new BidAuctionResponseMessage(objectid, BidAuctionResponseMessage::INVALIDITEM); player->sendMessage(msg); return; } if (item->getOwnerID() == player->getObjectID()) { BaseMessage* msg = new BidAuctionResponseMessage(objectid, BidAuctionResponseMessage::PURCHASEFAILED); player->sendMessage(msg); return; } ManagedReference<CityRegion*> city = vendor->getCityRegion().get(); int totalPrice = item->getPrice(); int res = checkBidAuction(player, item, totalPrice , price2); if (res != 0) { BaseMessage* msg = new BidAuctionResponseMessage(objectid, res); player->sendMessage(msg); return; } if (!item->isAuction()) { // Instant buy doInstantBuy(player, item); } else { // For Auction Bids if (price1 < 1) { BaseMessage* msg = new BidAuctionResponseMessage(objectid, BidAuctionResponseMessage::INVALIDPRICE); player->sendMessage(msg); return; } doAuctionBid(player, item, price1, price2); } } int AuctionManagerImplementation::checkRetrieve(CreatureObject* player, uint64 objectIdToRetrieve, SceneObject* vendor) { // Check both Bazaar and Vendors if (!auctionMap->containsItem(objectIdToRetrieve)) return RetrieveAuctionItemResponseMessage::NOTALLOWED; ManagedReference<SceneObject*> saleItem = zoneServer->getObject(objectIdToRetrieve); if (saleItem == nullptr) { return RetrieveAuctionItemResponseMessage::NOTALLOWED; } ManagedReference<AuctionItem*> item = auctionMap->getItem(objectIdToRetrieve); if (item == nullptr || item->getStatus() == AuctionItem::RETRIEVED) { return RetrieveAuctionItemResponseMessage::NOTALLOWED; } if(item->isAuction() && item->getStatus() == AuctionItem::FORSALE) return RetrieveAuctionItemResponseMessage::NOTALLOWED; int size = item->getSize(); if(saleItem->isIntangibleObject()) { ManagedReference<SceneObject*> datapad = player->getSlottedObject("datapad"); if (datapad->getCountableObjectsRecursive() + size > datapad->getContainerVolumeLimit()) return RetrieveAuctionItemResponseMessage::FULLINVENTORY; } else { ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (inventory->getCountableObjectsRecursive() + size > inventory->getContainerVolumeLimit()) return RetrieveAuctionItemResponseMessage::FULLINVENTORY; } /* if(item->getStatus() == AuctionItem::SOLD && player->getObjectID() == item->getOwnerID()) { item->setStatus(AuctionItem::EXPIRED); return RetrieveAuctionItemResponseMessage::DONTRETRIEVE; } */ String playername = player->getFirstName(); // only the owner can yank his own auction off the vendor if (item->getStatus() != AuctionItem::SOLD && (player->getObjectID() != item->getOwnerID())) return RetrieveAuctionItemResponseMessage::NOTALLOWED; // the bidder is the only one who can get his auction after expiration if (item->getStatus() == AuctionItem::SOLD && item->getBuyerID() != player->getObjectID()) { player->sendSystemMessage(item->getBidderName() + " bought this, " + player->getFirstName() + " trying to retrieve"); error(item->getBidderName() + " bought this, " + player->getFirstName() + " trying to retrieve"); return RetrieveAuctionItemResponseMessage::NOTALLOWED; } if(vendor->isVendor() && !vendor->isInRange(player, 8.0f)) return RetrieveAuctionItemResponseMessage::TOOFAR; if (vendor->isBazaarTerminal()) { ManagedReference<CityRegion*> region = vendor->getCityRegion().get(); String location = vendor->getZone()->getZoneName() + "."; if (region != nullptr) { location += region->getRegionName(); //String region = terminal->getBazaarRegion(); if (!item->getVendorUID().beginsWith(location)) { return RetrieveAuctionItemResponseMessage::TOOFAR; } } else { StringBuffer msg; msg << "null area for bazaar terminal at" << vendor->getPositionX() << " " << vendor->getPositionY() << " zone " << vendor->getZone()->getZoneName(); error(msg); } if (!item->getVendorUID().beginsWith(location)) { return RetrieveAuctionItemResponseMessage::TOOFAR; } } return 0; } void AuctionManagerImplementation::refundAuction(AuctionItem* item) { ManagedReference<PlayerManager*> pman = zoneServer->getPlayerManager(); ManagedReference<CreatureObject*> bidder = pman->getPlayer(item->getBidderName()); ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); String itemName = removeColorCodes(item->getItemName()); // send the player a mail and system message UnicodeString buyerSubject("@auction:subject_auction_cancelled"); // Auction Cancelled Reference<StringIdChatParameter*> buyerBody = new StringIdChatParameter("auction", "buyer_canceled"); // The auction of "%TO" that you were bidding on has been canceled by %TT. buyerBody->setTO(itemName); buyerBody->setTT(item->getOwnerName()); if (bidder != nullptr) { int itemPrice = item->getPrice(); Core::getTaskManager()->executeTask([=] () { Locker locker(bidder); bidder->addBankCredits(itemPrice); bidder->sendSystemMessage(*(buyerBody.get())); }, "RefundAuctionLambda"); } String sender = "auctioner"; cman->sendMail(sender, buyerSubject, *(buyerBody.get()), item->getBidderName()); } void AuctionManagerImplementation::retrieveItem(CreatureObject* player, uint64 objectid, uint64 vendorID) { ManagedReference<SceneObject*> vendor = zoneServer->getObject(vendorID); RetrieveAuctionItemResponseMessage* msg = nullptr; // check for valid vendor terminal if ((vendor == nullptr || !vendor->isVendor()) && !vendor->isBazaarTerminal()) { msg = new RetrieveAuctionItemResponseMessage(objectid, RetrieveAuctionItemResponseMessage::NOTALLOWED); player->sendMessage(msg); return; } int res = checkRetrieve(player, objectid, vendor); if (res != 0) { if(res != RetrieveAuctionItemResponseMessage::TOOFAR) { if(res == RetrieveAuctionItemResponseMessage::DONTRETRIEVE) res = 0; msg = new RetrieveAuctionItemResponseMessage(objectid, res); player->sendMessage(msg); } return; } ManagedReference<AuctionItem*> item = auctionMap->getItem(objectid); if (item == nullptr) { error("nullptr item in retrieveItem()"); return; } ManagedReference<SceneObject*> objectToRetrieve = zoneServer->getObject(objectid); if (objectToRetrieve == nullptr) { error("null objectToRetrieve in retrieveItem()"); msg = new RetrieveAuctionItemResponseMessage(objectid, 0); player->sendMessage(msg); return; } Locker locker(item); Locker plocker(player); ManagedReference<SceneObject*> destination = nullptr; if(objectToRetrieve->isIntangibleObject()) destination = player->getSlottedObject("datapad"); else destination = player->getSlottedObject("inventory"); if(destination->transferObject(objectToRetrieve, -1, false)) { destination->broadcastObject(objectToRetrieve, true); item->setStatus(AuctionItem::RETRIEVED); String vuid = getVendorUID(vendor); auctionMap->deleteItem(vendor, item); msg = new RetrieveAuctionItemResponseMessage(objectid, 0); player->sendMessage(msg); } else { msg = new RetrieveAuctionItemResponseMessage(objectid, RetrieveAuctionItemResponseMessage::NOTALLOWED); player->sendMessage(msg); } } bool AuctionManagerImplementation::checkItemCategory(int category, AuctionItem* item) { int itemType = item->getItemType(); bool isCrate = item->isFactoryCrate(); int cratedItemType = item->getCratedItemType(); if (category & 255) { // Searching a sub category if (itemType == category || (isCrate && cratedItemType > 0 && cratedItemType == category)) { return true; } } else if ((itemType & category) || (isCrate && cratedItemType > 0 && (cratedItemType & category))) { // Searching main category return true; } else if ((category == 8192) && (itemType < 256 || (isCrate && cratedItemType < 256))) { return true; } else if (category == 0) { // Searching all items return true; } return false; } AuctionQueryHeadersResponseMessage* AuctionManagerImplementation::fillAuctionQueryHeadersResponseMessage(CreatureObject* player, SceneObject* vendor, TerminalListVector* terminalList, int searchType, uint32 itemCategory, const UnicodeString& filterText, int minPrice, int maxPrice, bool includeEntranceFee, int clientCounter, int offset) { AuctionQueryHeadersResponseMessage* reply = new AuctionQueryHeadersResponseMessage(searchType, clientCounter, player); String pname = player->getFirstName().toLowerCase(); uint32 now = time(0); int displaying = 0; /*System::out << "Screen =" + String::valueOf(screen) << endl; System::out << "Category =" + String::valueOf(category) << endl; System::out << "VendorItemSize =" + String::valueOf(auctionMap->getVendorItemCount()) << endl; System::out << "AuctionItemSize =" + String::valueOf(auctionMap->getAuctionCount()) << endl; System::out << "______________________________" << endl;*/ for (int j = 0; (j < terminalList->size()) && (displaying < (offset + 100)); ++j) { auto& items = terminalList->get(j); if(items == nullptr) continue; /// Exclude non-searchable vendor Items if(vendor->isBazaarTerminal() && searchType == ST_VENDOR_SELLING && !items->isSearchable()) continue; try { items->rlock(); for (int i = 0; (i < items->size()) && (displaying < (offset + 100)); i++) { ManagedReference<AuctionItem*>& item = items->get(i); if(item == nullptr) continue; if(!item->isAuction() && item->getExpireTime() <= now) { Core::getTaskManager()->executeTask([=] () { expireSale(item); }, "ExpireSaleLambda"); continue; } switch(searchType) { case ST_VENDOR_SELLING: // Vendor search Bazaar && Vendor if(vendor->isVendor() && item->getVendorID() != vendor->getObjectID()) { if(item->getOwnerID() != player->getObjectID()) continue; } case ST_ALL: // All Auctions (Bazaar) if (item->getStatus() == AuctionItem::FORSALE) { if (!checkItemCategory(itemCategory, item)) continue; if (minPrice != 0 || maxPrice != 0) { int itemPrice = item->getPrice(); if (includeEntranceFee) { ManagedReference<SceneObject*> itemVendor = player->getZoneServer()->getObject(item->getVendorID()); if (itemVendor != nullptr && itemVendor->isVendor()) { int accessFee = 0; ManagedReference<SceneObject*> parent = itemVendor->getRootParent(); if(parent != nullptr && parent->isBuildingObject()) { BuildingObject* building = cast<BuildingObject*>(parent.get()); if(building != nullptr) accessFee = building->getAccessFee(); } itemPrice += accessFee; } } if ((minPrice != 0 && itemPrice < minPrice) || (maxPrice != 0 && itemPrice > maxPrice)) continue; } if (!filterText.isEmpty()) { String lowerFilter = filterText.toString().toLowerCase(); String itemName = item->getItemName().toLowerCase(); if (itemName.indexOf(lowerFilter) == -1) continue; } if (displaying >= offset) { reply->addItemToList(item); } displaying++; } break; case ST_PLAYER_SALES: // My auctions/sales if (item->getStatus() == AuctionItem::FORSALE && (item->getOwnerID() == player->getObjectID())) { if(checkItemCategory(itemCategory, item)) { if (displaying >= offset) { reply->addItemToList(item); } displaying++; } } break; case ST_PLAYER_BIDS: // My Bids if (item->isAuction() && item->getStatus() == AuctionItem::FORSALE && (item->getBidderName() == pname)) { reply->addItemToList(item); } break; case ST_PLAYER_STOCKROOM: // Retrieve items screen if ((item->getStatus() == AuctionItem::SOLD && item->getBuyerID() == player->getObjectID()) || (item->getStatus() == AuctionItem::EXPIRED && item->getOwnerID() == player->getObjectID())) { reply->addItemToList(item); } break; case ST_VENDOR_OFFERS: // Offers to Vendor (vendor owner) if (item->getStatus() == AuctionItem::OFFERED && item->getOfferToID() == player->getObjectID()) { if(checkItemCategory(itemCategory, item)) { if (displaying >= offset) { reply->addItemToList(item); } displaying++; } } break; case ST_VENDOR_STOCKROOM: // Stockroom if ((item->getStatus() == AuctionItem::EXPIRED && item->getOwnerID() == player->getObjectID()) || (item->getStatus() == AuctionItem::SOLD && item->getBuyerID() == player->getObjectID())) { if(checkItemCategory(itemCategory, item)) { if (displaying >= offset) { reply->addItemToList(item); } displaying++; } } break; case ST_PLAYER_OFFERS_TO_VENDOR: // Offers to vendor (browsing player) if (item->getStatus() == AuctionItem::OFFERED && item->getOwnerID() == player->getObjectID()) { if(checkItemCategory(itemCategory, item)) { if (displaying >= offset) { reply->addItemToList(item); } displaying++; } } break; } } items->runlock(); } catch(Exception& e) { error(e.getMessage()); items->runlock(); } } if (displaying == (offset + 100)) reply->createMessage(offset, true); else reply->createMessage(offset); return reply; } void AuctionManagerImplementation::getData(CreatureObject* player, int locationType, uint64 vendorObjectID, int searchType, unsigned int itemCategory, const UnicodeString& filterText, int minPrice, int maxPrice, bool includeEntranceFee, int clientCounter, int offset) { if (player->getAuctionSearchTask().get() != nullptr) return; ManagedReference<TangibleObject*> vendorInUse = (zoneServer->getObject(vendorObjectID)).castTo<TangibleObject*>(); if (vendorInUse == nullptr || (!vendorInUse->isVendor() && !vendorInUse->isBazaarTerminal())) { error("null vendor in getData()"); return; } ManagedReference<SceneObject*> parent = vendorInUse->getRootParent(); if (parent != nullptr && parent != player->getRootParent()) return; if(player->getZone() == nullptr) { error("player not in a zone"); return; } ManagedReference<BuildingObject*> rootParent = cast<BuildingObject*>(parent.get()); if(rootParent != nullptr && !rootParent->isAllowedEntry(player)) return; //Handle Merchant XP for players using other players vendors... if (!vendorInUse->isBazaarTerminal()) { DataObjectComponentReference* data = vendorInUse->getDataObjectComponent(); if(data == nullptr || data->get() == nullptr || !data->get()->isVendorData()) { error("Vendor has no data component in getData"); return; } VendorDataComponent* vendorData = cast<VendorDataComponent*>(data->get()); if(vendorData == nullptr) { error("Vendor has wrong data component in getData"); return; } vendorData->awardUseXP(); } String planet = ""; String region = ""; ManagedReference<SceneObject*> vendor = nullptr; ManagedReference<CityRegion*> city = nullptr; switch (locationType) { case LT_MARKET: vendor = vendorInUse; case LT_REGION: city = player->getCityRegion().get(); if (city != nullptr) region = city->getRegionName(); else { region = "@planet_n:" + player->getZone()->getZoneName(); vendor = vendorInUse; } case LT_PLANET: planet = player->getZone()->getZoneName(); default: break; } AuctionSearchTask* task = new AuctionSearchTask(_this.getReferenceUnsafeStaticCast(), player, vendorInUse, planet, region, vendor, searchType, itemCategory, filterText, minPrice, maxPrice, includeEntranceFee, clientCounter, offset); player->setAuctionSearchTask(task); task->schedule(100); } void AuctionManagerImplementation::getAuctionData(CreatureObject* player, SceneObject* usedVendor, const String& planet, const String& region, SceneObject* vendor, int searchType, uint32 itemCategory, const UnicodeString& filterText, int minPrice, int maxPrice, bool includeEntranceFee, int clientCounter, int offset) { TerminalListVector terminalList; if (usedVendor->isBazaarTerminal() && searchType != ST_VENDOR_SELLING) { // This is to prevent bazaar items from showing on Vendor Search terminalList = auctionMap->getBazaarTerminalData(planet, region, vendor); } else { terminalList = auctionMap->getVendorTerminalData(planet, region, vendor); } AuctionQueryHeadersResponseMessage* msg = fillAuctionQueryHeadersResponseMessage(player, usedVendor, &terminalList, searchType, itemCategory, filterText, minPrice, maxPrice, includeEntranceFee, clientCounter, offset); player->sendMessage(msg); } void AuctionManagerImplementation::getItemAttributes(CreatureObject* player, uint64 objectid) { ManagedReference<AuctionItem*> auctionItem = auctionMap->getItem(objectid); if(auctionItem == nullptr) return; ManagedReference<SceneObject*> object = zoneServer->getObject(auctionItem->getAuctionedItemObjectID()); if (object == nullptr) { error("not a valid object in getItemAttributes"); return; } UnicodeString description(auctionItem->getItemDescription()); AttributeListMessage* msg = new AttributeListMessage(objectid, description); // For objects that don't fill the attribute list normally... if (object->getAttributeListComponent() != nullptr) { object->getAttributeListComponent()->fillAttributeList(msg, player, object); } else object->fillAttributeList(msg, player); PlayerObject* ghost = player->getPlayerObject(); if (ghost != nullptr && ghost->isPrivileged()) { msg->insertAttribute("Item Type", auctionItem->getItemType()); bool isCrate = auctionItem->isFactoryCrate(); msg->insertAttribute("Is Factory Crate:", isCrate); if (isCrate) { msg->insertAttribute("Crated Item Type:", auctionItem->getCratedItemType()); } } //msg->insertInt(0); String templateFile = TemplateManager::instance()->getTemplateFile(object->getClientObjectCRC()); msg->insertAscii(templateFile); String cust = ""; if(object->isTangibleObject()) { ManagedReference<TangibleObject*> tano = cast<TangibleObject*>(object.get()); if(tano != nullptr) tano->getCustomizationString(cust); } msg->insertAscii(cust); player->sendMessage(msg); } void AuctionManagerImplementation::cancelItem(CreatureObject* player, uint64 objectID) { ManagedReference<AuctionItem*> item = auctionMap->getItem(objectID); // Item wasnt found. it doesn't exist if (item == nullptr) { error("null item in cancelItem()"); BaseMessage* msg = new CancelLiveAuctionResponseMessage(objectID, CancelLiveAuctionResponseMessage::INVALIDITEM); player->sendMessage(msg); return; } Time expireTime; uint64 currentTime = expireTime.getMiliTime() / 1000; uint64 availableTime = 0; bool forSaleOnVendor = false; if (item->getStatus() == AuctionItem::FORSALE) { if(item->getOwnerID() != player->getObjectID()) { error("not the owner of the item in cancelItem()"); BaseMessage* msg = new CancelLiveAuctionResponseMessage(objectID, CancelLiveAuctionResponseMessage::NOTOWNER); player->sendMessage(msg); return; } if(item->isOnBazaar()) availableTime = currentTime + AuctionManager::COMMODITYEXPIREPERIOD; else { availableTime = currentTime + AuctionManager::VENDOREXPIREPERIOD; forSaleOnVendor = true; } } else if (item->getStatus() == AuctionItem::OFFERED) { if(item->getOfferToID() != player->getObjectID() && item->getOwnerID() != player->getObjectID()) { error("not the target of offered item in cancelItem()"); BaseMessage* msg = new CancelLiveAuctionResponseMessage(objectID, CancelLiveAuctionResponseMessage::INVALIDITEM); player->sendMessage(msg); return; } /// 7 Days availableTime = currentTime + AuctionManager::COMMODITYEXPIREPERIOD; } else { BaseMessage* msg = new CancelLiveAuctionResponseMessage(objectID, CancelLiveAuctionResponseMessage::ALREADYCOMPLETED); player->sendMessage(msg); return; } if (item->getExpireTime() <= 0) { BaseMessage* msg = new CancelLiveAuctionResponseMessage(objectID, CancelLiveAuctionResponseMessage::ALREADYCOMPLETED); player->sendMessage(msg); return; } // refund auction money if (item->isAuction()) { refundAuction(item); Locker locker(&auctionEvents); if(auctionEvents.contains(item->getAuctionedItemObjectID())) { Reference<Task*> newTask = auctionEvents.get(item->getAuctionedItemObjectID()); if(newTask != nullptr) newTask->cancel(); auctionEvents.drop(item->getAuctionedItemObjectID()); } } /// If the offeree cancels if(item->getStatus() == AuctionItem::OFFERED && item->getOfferToID() == player->getObjectID()) { ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if(vendor != nullptr) { ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); String sender = "auctioner"; // Waypoint to Vendor / bazaar float waypointX = vendor->getWorldPositionX(); float waypointY = vendor->getWorldPositionY(); ManagedReference<WaypointObject*> waypoint = zoneServer->createObject(0xc456e788, 0).castTo<WaypointObject*>(); Locker waypointLocker(waypoint); waypoint->setPlanetCRC(vendor->getPlanetCRC()); waypoint->setPosition(waypointX, 0, waypointY); waypoint->setCustomObjectName(vendor->getDisplayedName(), false); String itemName = removeColorCodes(item->getItemName()); UnicodeString sellerSubject("@auction:subject_auction_unsuccessful"); // Auction Unsuccessful StringIdChatParameter sellerBody("@auction:seller_fail"); // Your auction of %TO has been completed and has not been purchased. sellerBody.setTO(itemName); //Send the Mail cman->sendMail(sender, sellerSubject, sellerBody, item->getOwnerName(), waypoint); } } Locker locker(item); item->setStatus(AuctionItem::EXPIRED); item->setExpireTime(availableTime); item->clearAuctionWithdraw(); BaseMessage* msg = new CancelLiveAuctionResponseMessage(objectID, 0); player->sendMessage(msg); if(forSaleOnVendor) { ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if(vendor != nullptr && auctionMap->getVendorItemCount(vendor, true) == 0) sendVendorUpdateMail(vendor, true); } } void AuctionManagerImplementation::expireSale(AuctionItem* item) { Locker locker(item); if(item->getStatus() == AuctionItem::EXPIRED) { deleteExpiredSale(item); return; } ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); String itemName = removeColorCodes(item->getItemName()); //Send the mail to the vendor owner String sender = "auctioner"; UnicodeString sellerSubject("@auction:subject_auction_unsuccessful"); // Auction Unsuccessful StringIdChatParameter sellerBody("@auction:seller_fail"); // Your auction of %TO has been completed and has not been purchased. sellerBody.setTO(itemName); Time expireTime; uint64 currentTime = expireTime.getMiliTime() / 1000; uint64 availableTime = 0; if(item->isOnBazaar()) availableTime = currentTime + AuctionManager::COMMODITYEXPIREPERIOD; else availableTime = currentTime + AuctionManager::VENDOREXPIREPERIOD; item->setStatus(AuctionItem::EXPIRED); item->setExpireTime(availableTime); item->clearAuctionWithdraw(); locker.release(); cman->sendMail(sender, sellerSubject, sellerBody, item->getOwnerName()); if (!item->isOnBazaar()) { ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if(vendor != nullptr && auctionMap->getVendorItemCount(vendor, true) == 0) sendVendorUpdateMail(vendor, true); } } void AuctionManagerImplementation::expireBidAuction(AuctionItem* item) { Locker locker(item); ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); String itemName = removeColorCodes(item->getItemName()); //Send the mail to the vendor owner String sender = "auctioner"; UnicodeString sellerSubject("@auction:subject_auction_item_expired"); // Auction Item Expired StringIdChatParameter sellerBody("@auction:seller_fail"); // Your auction of %TO has been completed and has not been purchased. sellerBody.setTO(itemName); Time expireTime; uint64 currentTime = expireTime.getMiliTime() / 1000; uint64 availableTime = 0; if(item->isOnBazaar()) availableTime = currentTime + AuctionManager::COMMODITYEXPIREPERIOD; else availableTime = currentTime + AuctionManager::VENDOREXPIREPERIOD; item->setStatus(AuctionItem::EXPIRED); item->setExpireTime(availableTime); item->clearAuctionWithdraw(); locker.release(); cman->sendMail(sender, sellerSubject, sellerBody, item->getOwnerName()); } void AuctionManagerImplementation::expireAuction(AuctionItem* item) { ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if (vendor == nullptr) return; String playername = item->getBidderName(); String sellerName = item->getOwnerName(); ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); ManagedReference<PlayerManager*> pman = zoneServer->getPlayerManager(); Zone* zone = vendor->getZone(); String vendorPlanetName; if (zone != nullptr) { vendorPlanetName = "@planet_n:" + zone->getZoneName(); } String vendorRegionName = vendorPlanetName; ManagedReference<CityRegion*> city = vendor->getCityRegion().get(); if (city != nullptr) { vendorRegionName = city->getRegionName(); } Time expireTime; uint64 currentTime = expireTime.getMiliTime() / 1000; uint64 availableTime = currentTime + AuctionManager::COMMODITYEXPIREPERIOD; Locker locker(item); item->setExpireTime(availableTime); item->clearAuctionWithdraw(); if (playername.isEmpty()) { locker.release(); expireBidAuction(item); } else { // Someone won the auction ManagedReference<CreatureObject*> buyer = pman->getPlayer(item->getBidderName()); if (buyer == nullptr) { locker.release(); expireBidAuction(item); return; } item->setStatus(AuctionItem::SOLD); updateAuctionOwner(item, buyer); // Waypoint to Vendor / bazaar float waypointX = vendor->getWorldPositionX(); float waypointY = vendor->getWorldPositionY(); WaypointChatParameter waypointParam; waypointParam.set(vendor->getDisplayedName(), waypointX, 0, waypointY, vendor->getPlanetCRC()); String sender = "auctioner"; StringIdChatParameterVector sellerBodyVector; WaypointChatParameterVector sellerWaypointVector; StringIdChatParameter sellerBodySale; UnicodeString sellerSubject; String itemName = removeColorCodes(item->getItemName()); if (!item->isOnBazaar()) { sellerSubject = "@auction:subject_vendor_seller"; // Vendor Sale Complete sellerBodySale.setStringId("@auction:seller_success_vendor"); // %TU has sold %TO to %TT for %DI credits. sellerBodySale.setTU(vendor->getDisplayedName()); } else { sellerSubject = "@auction:subject_auction_seller"; // Auction Complete sellerBodySale.setStringId("@auction:seller_success"); // Your auction of %TO has been sold to %TT for %DI credits } sellerBodySale.setTO(itemName); sellerBodySale.setTT(item->getBidderName()); sellerBodySale.setDI(item->getPrice()); StringIdChatParameter sellerBodyLoc("@auction:seller_success_location"); // The sale took place at %TT, on %TO. sellerBodyLoc.setTO(vendorPlanetName); sellerBodyLoc.setTT(vendorRegionName); sellerBodyVector.add(sellerBodySale); sellerBodyVector.add(sellerBodyLoc); sellerWaypointVector.add(waypointParam); StringIdChatParameterVector buyerBodyVector; WaypointChatParameterVector buyerWaypointVector; UnicodeString buyerSubject; if (!item->isOnBazaar()) { buyerSubject = "@auction:subject_vendor_buyer"; // Vendor Item Purchased } else { buyerSubject = "@auction:subject_auction_buyer"; // Auction Won } StringIdChatParameter buyerBodySale("@auction:buyer_success"); // You have won the auction of "%TO" from "%TT" for %DI credits. See the attached waypoint for location. buyerBodySale.setTO(itemName); buyerBodySale.setTT(sellerName); buyerBodySale.setDI(item->getPrice()); StringIdChatParameter buyerBodyLoc("@auction:buyer_success_location"); // The sale took place at %TT, on %TO. buyerBodyLoc.setTO(vendorPlanetName); buyerBodyLoc.setTT(vendorRegionName); buyerBodyVector.add(buyerBodySale); buyerBodyVector.add(buyerBodyLoc); buyerWaypointVector.add(waypointParam); //Send the Mail locker.release(); UnicodeString blankBody; cman->sendMail(sender, sellerSubject, blankBody, sellerName, &sellerBodyVector, &sellerWaypointVector); cman->sendMail(sender, buyerSubject, blankBody, item->getBidderName(), &buyerBodyVector, &buyerWaypointVector); } } void AuctionManagerImplementation::deleteExpiredSale(AuctionItem* item) { Locker locker(item); ManagedReference<SceneObject*> vendor = zoneServer->getObject(item->getVendorID()); if (vendor != nullptr) { ManagedReference<ChatManager*> cman = zoneServer->getChatManager(); String sender = "auctioner"; // Waypoint to Vendor / bazaar float waypointX = vendor->getWorldPositionX(); float waypointY = vendor->getWorldPositionY(); ManagedReference<WaypointObject*> waypoint = zoneServer->createObject(0xc456e788, 0).castTo<WaypointObject*>(); Locker lockerWaypoint(waypoint); waypoint->setPlanetCRC(vendor->getPlanetCRC()); waypoint->setPosition(waypointX, 0, waypointY); waypoint->setCustomObjectName(vendor->getDisplayedName(), false); lockerWaypoint.release(); String itemName = removeColorCodes(item->getItemName()); UnicodeString sellerSubject("@auction:subject_auction_unsuccessful"); // Auction Unsuccessful StringIdChatParameter sellerBody("@auction:item_expired"); // Because you failed to pick it up in time, the "%TO" that you were auctioning has expired. sellerBody.setTO(itemName); //Send the Mail locker.release(); cman->sendMail(sender, sellerSubject, sellerBody, item->getOwnerName(), waypoint); } uint64 oid = item->getAuctionedItemObjectID(); auctionMap->deleteItem(vendor, item); ManagedReference<SceneObject*> sceno = zoneServer->getObject(oid); if (sceno != nullptr) { Locker locker(sceno); sceno->destroyObjectFromDatabase(true); } } void AuctionManagerImplementation::displayInfo(CreatureObject* player) { ManagedReference<SuiListBox*> list = new SuiListBox(player, SuiWindowType::MARKET_INFO, 0x00); list->setPromptTitle("Market Info"); list->setPromptText("Information about the commodities market"); list->addMenuItem("Terminals with items"); list->addMenuItem("\tBazaars: " + String::valueOf(auctionMap->getBazaarCount())); list->addMenuItem("\tVendors: " + String::valueOf(auctionMap->getVendorCount())); list->addMenuItem("Total Items: " + String::valueOf(auctionMap->getTotalItemCount())); player->sendMessage(list->generateMessage()); } void AuctionManagerImplementation::updateAuctionOwner(AuctionItem* item, CreatureObject* player) { Locker locker(item); ManagedReference<PlayerManager*> pman = zoneServer->getPlayerManager(); ManagedReference<CreatureObject*> previousOwner = pman->getPlayer(item->getOwnerName()); if(player == previousOwner) return; auctionMap->removeFromCommodityLimit(item); item->setOwnerID(player->getObjectID()); item->setOwnerName(player->getFirstName()); if(!item->isOnBazaar() && item->getStatus() != AuctionItem::OFFERED) return; auctionMap->addToCommodityLimit(item); } void AuctionManagerImplementation::sendVendorUpdateMail(SceneObject* vendor, bool isEmpty) { //Send the mail to the vendor owner if (vendor == nullptr || !vendor->isVendor()) return; VendorDataComponent* vendorData = nullptr; DataObjectComponentReference* data = vendor->getDataObjectComponent(); if(data != nullptr && data->get() != nullptr && data->get()->isVendorData()) vendorData = cast<VendorDataComponent*>(data->get()); if(vendorData == nullptr) return; ManagedReference<ChatManager*> cman = vendor->getZoneServer()->getChatManager(); ManagedReference<CreatureObject*> owner = vendor->getZoneServer()->getObject(vendorData->getOwnerId()).castTo<CreatureObject*>(); String sender = vendor->getDisplayedName(); UnicodeString subject("@auction:vendor_status_subject"); if (cman == nullptr || owner == nullptr) return; if (isEmpty) { StringIdChatParameter body("@auction:vendor_status_empty"); body.setTO(vendor->getDisplayedName()); cman->sendMail(sender, subject, body, owner->getFirstName()); vendorData->setEmpty(); if (vendorData->isRegistered()) VendorManager::instance()->handleUnregisterVendor(owner, cast<TangibleObject*>(vendor)); } else { StringIdChatParameter body("@auction:vendor_status_normal"); body.setTO(vendor->getDisplayedName()); cman->sendMail(sender, subject, body, owner->getFirstName()); } } String AuctionManagerImplementation::removeColorCodes(const String& name) { String itemName = name; while (itemName.contains("\\#")) { int index = itemName.indexOf("\\#"); String sub = "\\" + itemName.subString(index, index + 2); itemName = itemName.replaceFirst(sub,""); } return itemName; }
34.131518
339
0.726701
[ "object", "vector" ]
02dbb168f8e51e0972c708900e41fb9dbeac9935
2,874
cpp
C++
algorithms/kernel/stump/inner/stump_train.cpp
KalyanovD/daal
b354b68f83a213102bca6e03d7a11f55ab751f92
[ "Apache-2.0" ]
null
null
null
algorithms/kernel/stump/inner/stump_train.cpp
KalyanovD/daal
b354b68f83a213102bca6e03d7a11f55ab751f92
[ "Apache-2.0" ]
null
null
null
algorithms/kernel/stump/inner/stump_train.cpp
KalyanovD/daal
b354b68f83a213102bca6e03d7a11f55ab751f92
[ "Apache-2.0" ]
null
null
null
/* file: stump_train.cpp */ /******************************************************************************* * Copyright 2014-2019 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. *******************************************************************************/ /* //++ // Implementation of stump algorithm and types methods. //-- */ #include "stump_training_types.h" #include "serialization_utils.h" #include "daal_strings.h" using namespace daal::data_management; using namespace daal::services; namespace daal { namespace algorithms { namespace stump { namespace interface1 { __DAAL_REGISTER_SERIALIZATION_CLASS(Model, SERIALIZATION_STUMP_MODEL_ID); } namespace training { namespace interface1 { __DAAL_REGISTER_SERIALIZATION_CLASS(Result, SERIALIZATION_STUMP_TRAINING_RESULT_ID); Result::Result() {} /** * Returns the model trained with the Stump algorithm * \param[in] id Identifier of the result, \ref classifier::training::ResultId * \return Model trained with the Stump algorithm */ daal::algorithms::stump::ModelPtr Result::get(classifier::training::ResultId id) const { return services::staticPointerCast<daal::algorithms::stump::Model, data_management::SerializationIface>(Argument::get(id)); } /** * Sets the result of the training stage of the stump algorithm * \param[in] id Identifier of the result, \ref classifier::training::ResultId * \param[in] value Pointer to the training result */ void Result::set(classifier::training::ResultId id, daal::algorithms::stump::ModelPtr & value) { Argument::set(id, value); } /** * Check the correctness of the Result object * \param[in] input Pointer to the input object * \param[in] parameter Pointer to the parameters structure * \param[in] method Algorithm computation method */ services::Status Result::check(const daal::algorithms::Input * input, const daal::algorithms::Parameter * parameter, int method) const { services::Status s; DAAL_CHECK_STATUS(s, checkImpl(input, parameter)); const classifier::interface1::Parameter * algPar = static_cast<const classifier::interface1::Parameter *>(parameter); DAAL_CHECK(algPar->nClasses == 2, services::ErrorModelNotFullInitialized); return services::Status(); } } // namespace interface1 } // namespace training } // namespace stump } // namespace algorithms } // namespace daal
32.292135
134
0.706333
[ "object", "model" ]
02dbd0b385f6dd2b5c058de4dee426d41487fff9
39,557
hpp
C++
dynadjust/include/functions/dnatemplategeodesyfuncs.hpp
nicgowans/DynAdjust
7443f0a3a0487876dd2f568efaa6c7be0e3e75e3
[ "Apache-2.0" ]
44
2018-08-30T04:18:27.000Z
2022-02-01T05:37:18.000Z
dynadjust/include/functions/dnatemplategeodesyfuncs.hpp
nicgowans/DynAdjust
7443f0a3a0487876dd2f568efaa6c7be0e3e75e3
[ "Apache-2.0" ]
112
2018-08-30T09:33:42.000Z
2022-03-30T00:32:29.000Z
dynadjust/include/functions/dnatemplategeodesyfuncs.hpp
nicgowans/DynAdjust
7443f0a3a0487876dd2f568efaa6c7be0e3e75e3
[ "Apache-2.0" ]
29
2018-08-30T09:07:36.000Z
2022-02-25T05:16:08.000Z
//============================================================================ // Name : dnatemplategeodesyfuncs.hpp // Author : Roger Fraser // Contributors : // Version : 1.00 // Copyright : Copyright 2017 Geoscience Australia // // 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. // // Description : Basic Geodetic Functions //============================================================================ #ifndef DNATEMPLATEGEODESYFUNCS_H_ #define DNATEMPLATEGEODESYFUNCS_H_ #if defined(_MSC_VER) #if defined(LIST_INCLUDES_ON_BUILD) #pragma message(" " __FILE__) #endif #endif #include <algorithm> #include <functional> #include <sstream> #include <string> #include <vector> #include <stdlib.h> #include <math.h> #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <include/parameters/dnaellipsoid.hpp> #include <include/parameters/dnaprojection.hpp> #include <include/config/dnatypes.hpp> using namespace std; using namespace boost; using namespace dynadjust::datum_parameters; // nu helper template <class T> T primeVertical(const CDnaEllipsoid* ellipsoid, const T& latitude) { return primeVertical_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude); } // rho helper template <class T> double primeMeridian(const CDnaEllipsoid* ellipsoid, const T& latitude) { return primeMeridian_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude); } // nu and rho helper template <class T> void primeVerticalandMeridian(const CDnaEllipsoid* ellipsoid, const T& latitude, T& nu, T& rho) { primeVerticalandMeridian_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude, nu, rho); } // average radius of curvature helper template <class T> T averageRadiusofCurvature(const CDnaEllipsoid* ellipsoid, const T& latitude) { return averageRadiusofCurvature_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude); } template <class T> void GeoToCart(const T& Latitude, const T& Longitude, const T& Height, T* X, T* Y, T* Z, const CDnaEllipsoid* ellipsoid) { // copy variables in case the caller overwrites original values T latitude(Latitude), longitude(Longitude), height(Height); // calculate prime vertical (once) T Nu(primeVertical(ellipsoid, latitude)); *X = (Nu + height) * cos(latitude) * cos(longitude); *Y = (Nu + height) * cos(latitude) * sin(longitude); *Z = ((Nu * (1. - ellipsoid->GetE1sqd())) + height) * sin(latitude); } template <class T> void CartToGeo_SimpleIteration(const T& X, const T& Y, const T& Z, T* latitude, T* longitude, T* height, const CDnaEllipsoid* ellipsoid) // ellipsoid parameters { // copy variables in case the caller overwrites original values T x(X), y(Y), z(Z); T f(ellipsoid->GetFlattening()); T e2(ellipsoid->GetE1sqd()); T p(pow(((x * x) + (y * y)), 0.5)); // "Cartesian to geographic" conversion problem resides in the // equation to compute latitude (phi)...latitude is required on both // sides of the equation. A simple iterative method is used to determine // the latitude, whereby the starting latitude is computed from // tan(phi) = z / p // Compute starting lat value from second eccentricity squared T lat1(atan(z / p)); *latitude = atan2((z + (e2 * ellipsoid->GetSemiMajor() * sin(lat1))), p); T Nu(primeVertical(ellipsoid, *latitude)); for (UINT16 i(0); i<16; i++) { lat1 = atan2((z + (e2 * Nu * sin(*latitude))), p); //Nu = ellipsoid->PrimeVertical(*latitude); Nu = primeVertical(ellipsoid, *latitude); *latitude = atan2((z + (e2 * Nu * sin(lat1))), p); if (fabs(lat1 - *latitude) < PRECISION_1E16) break; } // Compute longitude *longitude = atan(y / x); // determine correct quadrant and apply negative long accordingly if (x < 0.0 && y > 0.0) *longitude += PI; else if (x < 0.0 && y < 0.0) *longitude = -(PI - *longitude); // Compute height *height = (p / cos(*latitude)) - Nu; } template <class T> // K Lin and J Wang's method based on Newton's iteration // double dXAxis(-3563081.362), dYAxis(-2057145.984), dZAxis(-4870449.482), dHeight(0.); // CDnaEllipsoid e; // CartToGeo<double>(dXAxis, dYAxis, dZAxis, &dXAxis, &dYAxis, &dHeight, &e); // stringstream ss; // ss << setw(MSR) << right << FormatDmsString(RadtoDms(dXAxis), 5, true, false) << ", "; // ss << setw(MSR) << right << FormatDmsString(RadtoDms(dYAxis), 5, true, false) << ", "; // ss << setw(MSR) << setprecision(4) << fixed << right << dHeight; // string comp(ss.str()); // comp should equal "-50 00 00.0000, -150 00 00.0000, 10000.000" // void CartToGeo(const T& X, const T& Y, const T& Z, T* latitude, T* longitude, T* height, const CDnaEllipsoid* ellipsoid) // ellipsoid parameters { // copy variables in case the caller overwrites original values T x(X), y(Y), z(Z); T p2((x * x) + (y * y)); T p(sqrt(p2)); T a2(ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMajor()); T b2(ellipsoid->GetSemiMinor() * ellipsoid->GetSemiMinor()); T Z2(z * z); T a2Z2(a2 * Z2); T b2p2(b2 * p2); T A(a2Z2 + b2p2); // Compute initial approximation of m (Lin and Wang 1995, eq. 9, p. 301) T m0((ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMinor() * sqrt(A) * A - a2 * b2 * A) / (2. * ((a2 * a2Z2) + (b2 * b2p2)))); T twom, a2twom, b2twom, f, df, m; // Generally converges after one iteration and // so shouldn't need more than five iterations. for (UINT16 i(0); i<5; ++i) { m = m0; twom = m * 2.; a2twom = a2 + twom; b2twom = b2 + twom; f = (a2 * p2 / (a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom)) - 1.; // if f is sufficiently close to zero, break. if (fabs(f) < PRECISION_1E12) break; df = -4. * ((a2 * p2 / (a2twom * a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom * b2twom))); // recompute new value for m m0 = m - (f / df); m = m0; } twom = m * 2.; T p_E(a2 * p / (a2 + twom)); T Z_E(b2 * z / (b2 + twom)); // Compute latitude *latitude = atan(a2 * Z_E / (b2 * p_E)); // Compute longitude *longitude = atan(y / x); // determine correct quadrant and apply negative long accordingly if (x < 0.0 && y > 0.0) *longitude += PI; else if (x < 0.0 && y < 0.0) *longitude = -(PI - *longitude); // The following line causes an issue for west longitudes, which by nature are negative! // Not sure why this was introduced. Removing the conditional absolute has no adverse impact on // positions which are located in the eastern hemisphere, //if (*longitude < 0.) // *longitude += TWO_PI; // Compute height *height = sqrt(((p - p_E) * (p - p_E)) + ((z - Z_E) * (z - Z_E))); if ((p + fabs(z)) < (p_E + fabs(Z_E))) *height *= -1.; } template <class T> // K Lin and J Wang's method based on Newton's iteration T CartToLat(const T& X, const T& Y, const T& Z, const CDnaEllipsoid* ellipsoid) { // copy variables in case the caller overwrites original values T x(X), y(Y), z(Z); T p2((x * x) + (y * y)); T p(sqrt(p2)); T a2(ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMajor()); T b2(ellipsoid->GetSemiMinor() * ellipsoid->GetSemiMinor()); T Z2(z * z); T a2Z2(a2 * Z2); T b2p2(b2 * p2); T A(a2Z2 + b2p2); // Compute initial approximation of m (Lin and Wang 1995, eq. 9, p. 301) T m0((ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMinor() * sqrt(A) * A - a2 * b2 * A) / (2. * ((a2 * a2Z2) + (b2 * b2p2)))); T twom, a2twom, b2twom, f, df, m; // Generally converges after one iteration and // so shouldn't need more than five iterations. for (UINT16 i(0); i<5; ++i) { m = m0; twom = m * 2.; a2twom = a2 + twom; b2twom = b2 + twom; f = (a2 * p2 / (a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom)) - 1.; // if f is sufficiently close to zero, break. if (fabs(f) < PRECISION_1E12) break; df = -4. * ((a2 * p2 / (a2twom * a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom * b2twom))); // recompute new value for m m0 = m - (f / df); m = m0; } twom = m * 2.; T p_E(a2 * p / (a2 + twom)); T Z_E(b2 * z / (b2 + twom)); // Compute latitude return atan(a2 * Z_E / (b2 * p_E)); } template <class T> T PartialD_Latitude(const T& X, const T& Y, const T& Z, const _CART_ELEM_& element, const T& latitude, const CDnaEllipsoid* ellipsoid) { if (element > z_element) return 0.; const T small_inc = PRECISION_1E4; // Compute the partial derivative. // 1. add small increment to the required element T cart[3] = { X, Y, Z }; cart[element] += small_inc; // 2. f(x + small_inc) T fx_small_inc(CartToLat( cart[x_element], // X1 cart[y_element], // Y1 cart[z_element], // Z1 ellipsoid)); // f(x + small_inc) - f(x) // 3. f'(x) = ----------------------- // small_inc return (fx_small_inc - latitude) / small_inc; } template <class T> T PartialD_Latitude_F(const T& X, const T& Y, const T& Z, const _CART_ELEM_& element, T* latitude, const CDnaEllipsoid* ellipsoid) { if (element > z_element) return 0.; // compute the new latitude *latitude = CartToLat(X, Y, Z, ellipsoid); return PartialD_Latitude(X, Y, Z, element, *latitude, ellipsoid); } template <class T> T PartialD_HorizAngle(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T X3, const T Y3, const T Z3, const T currentLatitude, const T currentLongitude, const _STATION_ELEM_& station, const _CART_ELEM_& element, const T angle) { if (element > z_element) return 0.; const T small_inc = PRECISION_1E4; // Compute the partial derivative. // 1. add small increment to the required element T cart[3][3] = { X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3 }; cart[station][element] += small_inc; // Temporary variables T dir12, dir13, loc12e, loc12n, loc13e, loc13n; // 2. f(x + small_inc) T fx_small_inc(HorizontalAngle( cart[station_1][x_element], // X1 cart[station_1][y_element], // Y1 cart[station_1][z_element], // Z1 cart[station_2][x_element], // X2 cart[station_2][y_element], // Y2 cart[station_2][z_element], // Z2 cart[station_3][x_element], // X3 cart[station_3][y_element], // Y3ZONE cart[station_3][z_element], // Z3 currentLatitude, currentLongitude, &dir12, &dir13, &loc12e, &loc12n, &loc13e, &loc13n)); // f(x + small_inc) - f(x) // 3. f'(x) = ----------------------- // small_inc return (fx_small_inc - angle) / small_inc; } template <class T> // latitude and longitude in radians void GeoToGrid(const T& Latitude, const T& Longitude, T* easting, T* northing, T* zone, const CDnaEllipsoid* ellipsoid, const CDnaProjection* projection, bool COMPUTE_ZONE) { T latitude(Latitude); T longitude(Longitude); // Compute Zone if not previously specified if (COMPUTE_ZONE) *zone = floor((Degrees(longitude) - projection->GetLongWesternEdgeZone0()) / projection->GetZoneWidth()); // Compute Geodetic Longitude of the Central Meridian of pGeoValue->dNum3 (the UTM Zone) T CMeridian((*zone * projection->GetZoneWidth()) + projection->GetLongCentralMeridianZone0()); // Compute diff in Longitude between CMeridian and Longitude T omega(longitude - Radians(CMeridian)); T e2(ellipsoid->GetE1sqd()); T e2_2(pow(e2, 2.0)); T e2_3(pow(e2, 3.0)); T Nu, Rho, Nu_div_Rho; primeVerticalandMeridian(ellipsoid, latitude, Nu, Rho); Nu_div_Rho = Nu / Rho; T A0(1.0 - (e2 / 4.0) - (3.0 * e2_2 / 64.0) - (5.0 * e2_3 / 256.0)); T A2(3.0 / 8.0 * (e2 + (e2_2 / 4.0) + (15.0 * e2_3 / 128.0))); T A4(15.0 / 256.0 * (e2_2 + (3.0 * e2_3 / 4.0))); T A6(35.0 * e2_3 / 3072.0); T m(ellipsoid->GetSemiMajor() * ((A0 * latitude) - (A2 * sin(2.0 * latitude)) + (A4 * sin(4.0 * latitude)) - (A6 * sin(6.0 * latitude)))); T cos_lat(cos(latitude)); T sin_lat(sin(latitude)); T Num1(K0 * Nu * omega * cos_lat); T tan_lat_2(pow(tan(latitude), 2.0)); T tan_lat_4(pow(tan(latitude), 4.0)); // Compute Easting T Term1((pow(omega, 2.0) / 6.0) * (pow(cos_lat, 2.0)) * (Nu_div_Rho - tan_lat_2)); T Term2((pow(omega, 4.0) / 120) * (pow(cos_lat, 4.0)) * (((4.0 * pow(Nu_div_Rho, 3.0)) * (1.0 - (6.0 * tan_lat_2))) + ((pow(Nu_div_Rho, 2.0)) * (1.0 + (8.0 * tan_lat_2))) - (Nu_div_Rho * 2.0 * tan_lat_2) + tan_lat_4)); T Term3((pow(omega, 6.0) / 5040) * (pow(cos_lat, 6.0)) * (61.0 - (479.0 * tan_lat_2) + (179.0 * tan_lat_4) - (tan_lat_4))); *easting = (Num1 * (1.0 + Term1 + Term2 + Term3)) + FALSE_E; // Compute Northing Term1 = (pow(omega, 2.0) / 2.0 * Nu * sin_lat * cos_lat); Term2 = (pow(omega, 4.0) / 24.0 * Nu * sin_lat * pow(cos_lat, 3.0)); Term2 *= ((4.0 * pow(Nu_div_Rho, 2.0)) + Nu_div_Rho - tan_lat_2); Term3 = (pow(omega, 6.0) / 720.0 * Nu * sin_lat * pow(cos_lat, 5.0)); Term3 *= ((8.0 * pow(Nu_div_Rho, 4.0) * (11.0 - (24.0 * tan_lat_2))) - (28.0 * pow(Nu_div_Rho, 3.0) * (1.0 - (6.0 * tan_lat_2))) + (pow(Nu_div_Rho, 2.0) * (1.0 - (32.0 * tan_lat_2))) - (Nu_div_Rho * 2.0 * tan_lat_2) + tan_lat_4); T Term4(pow(omega, 8.0) / 40320 * Nu * sin_lat * pow(cos_lat, 7.0)); Term4 *= (1385.0 - (3111.0 * tan_lat_2) + (543.0 * tan_lat_4) - (pow(tan(latitude), 6.0))); *northing = (K0 * (m + Term1 + Term2 + Term3 + Term4)) + FALSE_N; } // returns lat/long values in radians template <class T, typename U> void GridToGeo(const T& easting, const T& northing, const U& zone, T* latitude, T* longitude, const T& a, const T& inv_f, // ellipsoid parameters const T& FALSE_E, const T& FALSE_N, const T& kO, const T& lcmZ1, const T& zW) // projecton parameters { T f = 1 / inv_f; T b = a * (1 - f); T e2 = (2 * f) - (f * f); //T e = sqrt(e2); //T Seconde2 = e2 / (1 - e2); //T Seconde = sqrt(Seconde2); T n = (a - b) / (a + b); T n2 = pow(n, 2.0); T n3 = pow(n, 3.0); T n4 = pow(n, 4.0); T G = a * (1 - n) * (1 - n2); G *= (1 + (9 * n2 / 4) + (225 * n4 / 64)); G *= (PI / 180.); T ePrime = easting - FALSE_E; T nPrime = northing - FALSE_N; T m = nPrime / kO; T sigma = (m * PI) / (180 * G); T latPrime = sigma + (( (3 * n / 2) - (27 * n3 / 32) ) * sin(2 * sigma)); latPrime += ( (21 * n2 / 16) - (55 * n4 / 32) ) * sin(4 * sigma); latPrime += (151 * n3 / 96) * sin(6 * sigma); latPrime += (1097 * n4 / 512) * sin(8 * sigma); T rho = a * (1 - e2) / pow( (1 - (e2 * pow(sin(latPrime), 2.0))), 1.5); T nu = a / pow( (1 - (e2 * pow(sin(latPrime), 2.0))), 0.5); T num1 = tan(latPrime) / (kO * rho); T x = ePrime / (kO * nu); T term1 = num1 * x * ePrime / 2; T term2 = num1 * ePrime * pow(x, 3.0) / 24; term2 *= ( (-4 * pow((nu / rho), 2.0)) + (9 * nu / rho * (1 - pow((tan(latPrime)), 2.0))) + (12 * pow((tan(latPrime)), 2.0)) ); T term3 = num1 * ePrime * pow(x, 5.0) / 720; term3 *= ( (8 * pow((nu / rho), 4.0) * (11 - (24 * pow((tan(latPrime)), 2.0)))) - (12 * pow((nu / rho), 3.0) * (21 - (71 * pow((tan(latPrime)), 2.0)))) + (15 * pow((nu / rho), 2.0) * (15 - (98 * pow((tan(latPrime)), 2.0)) + (15 * pow((tan(latPrime)), 4.0)))) + (180 * (nu / rho) * ((5 * pow((tan(latPrime)), 2.0))-(3 * pow((tan(latPrime)), 4.0))))+ (360 * pow((tan(latPrime)), 4.0)) ); T term4 = num1 * ePrime * pow(x, 7.0) / 40320; term4 *= (1385 + (3633 * pow((tan(latPrime)), 2.0)) + (4095 * pow((tan(latPrime)), 4.0)) + (1575 * pow((tan(latPrime)), 6.0)) ); // Store radians value of Geodetic Latitude *latitude = latPrime - term1 + term2 - term3 + term4; // Compute Geodetic Longitude of the Central Meridian of pGridValue->dNum3 (the UTM Zone) in radians T centralMeridian = ((zone * zW) + lcmZ1 - zW) * PI / 180; num1 = 1 / (cos(latPrime)); term1 = x * num1; term2 = ( pow(x, 3.0) / 6 * num1 * ((nu / rho) + (2. * tan(latPrime) * tan(latPrime))) ); term3 = ( pow(x, 5.0) / 120 * num1 * ( (-4 * pow((nu / rho), 3.0) * (1 - (6 * tan(latPrime) * tan(latPrime)))) + (pow((nu / rho), 2.0) * (9 - (68 * tan(latPrime) * tan(latPrime)))) + (72 * (nu / rho) * tan(latPrime) * tan(latPrime)) + (24 * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime)) )); term4 = ( pow(x, 7.0) / 5040 * num1 * ( 61 + (662 * tan(latPrime) * tan(latPrime)) + (1320 * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime)) + (720 * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime)) )); // Store radians value of Geodetic Longitude *longitude = centralMeridian + term1 - term2 + term3 - term4; } // Great Circle Distance template <class T> T GreatCircleDistance(const T& dLatitudeAT, const T& dLongitudeAT, const T& dLatitudeTO, const T& dLongitudeTO) { T deltaLatitude(dLatitudeTO - dLatitudeAT); T deltaLongitude(dLongitudeTO - dLongitudeAT); T a(sin(deltaLatitude / 2) * sin(deltaLatitude / 2) + cos(dLatitudeAT) * cos(dLatitudeTO) * sin(deltaLongitude / 2) * sin(deltaLongitude / 2)); T c(2 * atan2(sqrt(a), sqrt(1 - a))); return c * T(6372797.); } // Rigorous Geodesic via Robbins' formula // Robbins, A. R. (1962). �Long lines on the spheroid.� Surv. Rev., XVI(125), 301�309. template <class T> T RobbinsReverse(const T& dLatitudeAT, const T& dLongitudeAT, const T& dLatitudeTO, const T& dLongitudeTO, T* pAzimuth, const CDnaEllipsoid* ellipsoid) { T s, z, c, g, h, h2, chi; T sinsigma, sigma, sigma2, sigma3, sigma4, sigma5; T dPVertA(primeVertical(ellipsoid, dLatitudeAT)); T dPVertB(primeVertical(ellipsoid, dLatitudeTO)); T tanzeta2 = (1 - ellipsoid->GetE1sqd()) * tan(dLatitudeTO) + ellipsoid->GetE1sqd() * dPVertA * sin(dLatitudeAT) / (dPVertB * cos(dLatitudeTO)); T tau1 = cos(dLatitudeAT) * tanzeta2 - sin(dLatitudeAT) * cos(dLongitudeTO - dLongitudeAT); T tanazimuthAB; if (fabs (dLongitudeTO - dLongitudeAT) < PRECISION_1E15) tanazimuthAB = 0.0; else tanazimuthAB = sin (dLongitudeTO - dLongitudeAT) / tau1; // Compute the azimuth, check for the correct sign, quadrant etc. - *pAzimuth = atan(tanazimuthAB); if ((*pAzimuth) < 0.0) *pAzimuth += PI; if (dLongitudeTO < dLongitudeAT) *pAzimuth += PI; if ((fabs (*pAzimuth) < PRECISION_1E15) && (dLatitudeTO < dLatitudeAT)) *pAzimuth += PI; // Check here for the sign of the computed azimuth - eg to add pi or 2pi etc. s = sin (*pAzimuth); z = atan (tanzeta2); c = cos (z); // If sin (alpha12) is close to zero then chi is calculated one way // otherwise it is calculated differently. An arbitrary // "boundary value" of 0.2 has been used. if (fabs (s) < 0.2) chi = tau1 / cos(*pAzimuth); else chi = sin(dLongitudeTO - dLongitudeAT) / s; sinsigma = chi * c; sigma = asin (sinsigma); sigma2 = sigma * sigma; sigma3 = sigma2 * sigma; sigma4 = sigma2 * sigma2; sigma5 = sigma3 * sigma2; g = ellipsoid->GetE2() * sin (dLatitudeAT); h = ellipsoid->GetE2() * cos (dLatitudeAT) * cos (*pAzimuth); h2 = h * h; return (dPVertA * sigma * (1 - sigma2 * h2 * (1 - h2) / 6 + sigma3 * g * h * (1 - 2 * h2) / 8 + sigma4 * (h2 * (4 - 7 * h2) - 3 * g * g * (1 - 7 * h2)) / 120 - sigma5 * g * h / 48)); } template <class T> void VincentyDirect(const T& dLatitudeAT, const T& dLongitudeAT, const T& dAzimuth, const T& dDistance, T *dLatitudeTO, T *dLongitudeTO, const CDnaEllipsoid* ellipsoid) { // calculate fundamentals T f = ellipsoid->GetFlattening(); T b = ellipsoid->GetSemiMinor(); // parametric latitude of P' T tanUI = (1.0 - f) * tan(dLatitudeAT); // angular distance T tanSigma1 = tanUI / cos(dAzimuth); // parametric latitude of the geodesic vertex, or // azimuth of the geodesic at the equator T sinAlpha = cos(atan(tanUI)) * sin(dAzimuth); T Alpha = asin(sinAlpha); T cosAlpha = cos(Alpha); // geodesic constant T u2 = pow(cosAlpha, 2.0) * (pow(ellipsoid->GetSemiMajor(), 2.0) - pow(b, 2.0)) / pow(b, 2.0); // Vincenty's constants A' and B' T A = 1.0 + (u2/16384.0) * (4096.0 + (u2 * (-768.0 + (u2 * (320.0 - (175.0 * u2)))))); T B = (u2/1024.0) * (256.0 + (u2 * (-128.0 + (u2 * (74.0 - (47.0 * u2)))))); T Sigma = dDistance / (b * A); T twoSigmam, deltaSigma, SigmaDiff(99.); // iterate until no signigicant change in sigma for (UINT16 i(0); i<10; i++) { twoSigmam = (2.0 * atan(tanSigma1)) + Sigma; deltaSigma = B * sin(Sigma) * (cos(twoSigmam) + (B / 4.0 * ((cos(Sigma) * (-1.0 + (2.0 * pow(cos(twoSigmam), 2.0)))) - (B / 6.0 * cos(twoSigmam) * (-3.0 + (4.0 * pow(sin(Sigma), 2.0))) * ((-3.0 + (4.0 * pow(cos(twoSigmam), 2.0)))))))); SigmaDiff = Sigma; Sigma = (dDistance / (b * A)) + deltaSigma; SigmaDiff -= Sigma; if (fabs(SigmaDiff) < PRECISION_1E16) break; } // latitude of new position *dLatitudeTO = atan2(((sin(atan(tanUI)) * cos(Sigma)) + (cos(atan(tanUI)) * sin(Sigma) * cos(dAzimuth))), ((1.0 - f) * pow((pow(sinAlpha, 2.0) + pow(((sin(atan(tanUI)) * sin(Sigma)) - (cos(atan(tanUI)) * cos(Sigma) * cos(dAzimuth))), 2.0)), 0.5))); T Lambda = atan2((sin(Sigma) * sin(dAzimuth)), ((cos(atan(tanUI)) * cos(Sigma)) - (sin(atan(tanUI))*sin(Sigma)*cos(dAzimuth)))); T C = (f / 16.0) * pow(cosAlpha, 2.0) * (4.0 + (f * (4.0 - (3.0 * pow(cosAlpha, 2.0))))); T Omega = Lambda - ((1.0 - C) * f * sinAlpha * (Sigma + (C * sin(Sigma) * (cos(twoSigmam) + (C * cos(Sigma) * (-1 + (2 * pow(cos(twoSigmam), 2.0)))))))); // longitude of new position *dLongitudeTO = dLongitudeAT + Omega; } template <class T> void ComputeLocalElements3D(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T currentLatitude, const T currentLongitude, T* local_12e, T* local_12n, T* local_12up) { // 1->2 T dX12(X2 - X1); T dY12(Y2 - Y1); T dZ12(Z2 - Z1); // helpers T sin_lat(sin(currentLatitude)); T cos_lat(cos(currentLatitude)); T sin_long(sin(currentLongitude)); T cos_long(cos(currentLongitude)); *local_12e = -sin_long * dX12 + cos_long * dY12; *local_12n = -sin_lat * cos_long * dX12 - sin_lat * sin_long * dY12 + cos_lat * dZ12; *local_12up = cos_lat * cos_long * dX12 + cos_lat * sin_long * dY12 + sin_lat * dZ12; } template <class T> void ComputeLocalElements2D(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T currentLatitude, const T currentLongitude, T* local_12e, T* local_12n) { // 1->2 T dX12(X2 - X1); T dY12(Y2 - Y1); T dZ12(Z2 - Z1); // helpers T sin_lat(sin(currentLatitude)); T cos_lat(cos(currentLatitude)); T sin_long(sin(currentLongitude)); T cos_long(cos(currentLongitude)); *local_12e = -sin_long * dX12 + cos_long * dY12; *local_12n = -sin_lat * cos_long * dX12 - sin_lat * sin_long * dY12 + cos_lat * dZ12; } template <class T> T Direction(const T local_12e, const T local_12n) { // "computed" direction 1->2 T direction12; if (fabs(local_12e) < fabs(local_12n)) direction12 = atan_2(local_12e, local_12n); else direction12 = HALF_PI - atan_2(local_12n, local_12e); if (direction12 < 0) direction12 += TWO_PI; return direction12; } template <class T> T Direction(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T currentLatitude, const T currentLongitude, T* local_12e, T* local_12n) { ComputeLocalElements2D(X1, Y1, Z1, X2, Y2, Z2, currentLatitude, currentLongitude, local_12e, local_12n); return Direction(*local_12e, *local_12n); } template <class T> // helper function T Direction(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T currentLatitude, const T currentLongitude) { T local_12e, local_12n; return Direction(X1, Y1, Z1, X2, Y2, Z2, currentLatitude, currentLongitude, &local_12e, &local_12n); } template <class T> T HorizontalAngle(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T X3, const T Y3, const T Z3, const T currentLatitude, const T currentLongitude, T* direction12, T* direction13, T* local_12e, T* local_12n, T* local_13e, T* local_13n) { // compute vectors [1->2] & [1->3] in the local reference frame // // 1->2 *direction12 = Direction(X1, Y1, Z1, X2, Y2, Z2, currentLatitude, currentLongitude, local_12e, local_12n); *direction13 = Direction(X1, Y1, Z1, X3, Y3, Z3, currentLatitude, currentLongitude, local_13e, local_13n); if (*direction12 > *direction13) *direction13 += TWO_PI; // angle 123 T angle = *direction13 - *direction12; return angle; } template <class T> // helper function T HorizontalAngle(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T X3, const T Y3, const T Z3, const T currentLatitude, const T currentLongitude, T* direction12, T* direction13) { T local_12e, local_12n, local_13e, local_13n; return HorizontalAngle(X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3, currentLatitude, currentLongitude, direction12, direction13, &local_12e, &local_12n, &local_13e, &local_13n); } template <class T> void CartesianElementsFromInstrumentHeight(const T height, T* dX, T* dY, T* dZ, const T Latitude, const T Longitude) { // Use rotation matrix for local vector -> cartesian vector, whereby // local elements for e and n are zero *dX = cos(Latitude) * cos(Longitude) * height; *dY = cos(Latitude) * sin(Longitude) * height; *dZ = sin(Latitude) * height; } template <class T> // The return value is the true vertical between the (local) horizontal plane // and the instrument-target vector. The local_12e/n/up elements represent // the geometric difference between the two stations T VerticalAngle(const T& local_12e, const T& local_12n, const T& local_12up) { return atan2(local_12up, sqrt((local_12e * local_12e) + (local_12n * local_12n))); } template <class T> // The return value is the true vertical between the (local) horizontal plane // and the instrument-target vector. The local_12e/n/up elements represent // the geometric difference between the two stations T VerticalAngle(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T latitude1, const T longitude1, const T latitude2, const T longitude2, const T instrumentHeight, const T targetHeight, T* local_12e, T* local_12n, T* local_12up) { // helpers T sin_lat1(sin(latitude1)); T cos_lat1(cos(latitude1)); T sin_long1(sin(longitude1)); T cos_long1(cos(longitude1)); // Compute cartesian elements dX, dY, dZ for instrument to target // First, compute cartesian vector for both instrument and target T dXih, dYih, dZih, dXth, dYth, dZth; CartesianElementsFromInstrumentHeight(instrumentHeight, &dXih, &dYih, &dZih, latitude1, longitude1); CartesianElementsFromInstrumentHeight(targetHeight, &dXth, &dYth, &dZth, latitude2, longitude2); T dX12(X2 - X1 + dXth - dXih); T dY12(Y2 - Y1 + dYth - dYih); T dZ12(Z2 - Z1 + dZth - dZih); // compute local reference frame elements (station1 to station2) *local_12e = -sin_long1 * dX12 + cos_long1 * dY12; *local_12n = -sin_lat1 * cos_long1 * dX12 - sin_lat1 * sin_long1 * dY12 + cos_lat1 * dZ12; *local_12up = cos_lat1 * cos_long1 * dX12 + cos_lat1 * sin_long1 * dY12 + sin_lat1 * dZ12; // compute angle (instrument to target) return VerticalAngle(*local_12e, *local_12n, *local_12up); //return atan2((*local_12up), sqrt(((*local_12e) * (*local_12e)) + ((*local_12n) * (*local_12n)))); ////////////////////////////////////////////////////// } template <class T> // helper function T VerticalAngle(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T latitude1, const T longitude1, const T latitude2, const T longitude2, const T instrumentHeight, const T targetHeight) { T local_12e, local_12n, local_12up; return VerticalAngle( X1, Y1, Z1, X2, Y2, Z2, latitude1, longitude1, latitude2, longitude2, instrumentHeight, targetHeight, &local_12e, &local_12n, &local_12up); } template <class T> // The return value is the true zenith distance between the ellipsoid normal // and the instrument-target vector. The local_12e/n/up elements represent // the geometric difference between the two stations T ZenithDistance(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T latitude1, const T longitude1, const T latitude2, const T longitude2, const T instrumentHeight, const T targetHeight, T* local_12e, T* local_12n, T* local_12up) { // helpers T sin_lat1(sin(latitude1)); T cos_lat1(cos(latitude1)); T sin_long1(sin(longitude1)); T cos_long1(cos(longitude1)); // Compute cartesian elements dX, dY, dZ for instrument to target // First, compute cartesian vector for both instrument and target T dXih, dYih, dZih, dXth, dYth, dZth; CartesianElementsFromInstrumentHeight(instrumentHeight, &dXih, &dYih, &dZih, latitude1, longitude1); CartesianElementsFromInstrumentHeight(targetHeight, &dXth, &dYth, &dZth, latitude2, longitude2); T dX12(X2 - X1 + dXth - dXih); T dY12(Y2 - Y1 + dYth - dYih); T dZ12(Z2 - Z1 + dZth - dZih); // compute local reference frame elements (station1 to station2) *local_12e = -sin_long1 * dX12 + cos_long1 * dY12; *local_12n = -sin_lat1 * cos_long1 * dX12 - sin_lat1 * sin_long1 * dY12 + cos_lat1 * dZ12; *local_12up = cos_lat1 * cos_long1 * dX12 + cos_lat1 * sin_long1 * dY12 + sin_lat1 * dZ12; // compute angle (instrument to target) return atan2(sqrt((*local_12e) * (*local_12e) + (*local_12n) * (*local_12n)), (*local_12up)); ////////////////////////////////////////////////////// } template <class T> // helper function T ZenithDistance(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T latitude1, const T longitude1, const T latitude2, const T longitude2, const T instrumentHeight, const T targetHeight) { T local_12e, local_12n, local_12up; return ZenithDistance( X1, Y1, Z1, X2, Y2, Z2, latitude1, longitude1, latitude2, longitude2, instrumentHeight, targetHeight, &local_12e, &local_12n, &local_12up); } template <class T> T EllipsoidHeight(const T X, const T Y, const T Z, const T latitude, T* nu, T* Zn, const CDnaEllipsoid* ellipsoid) { *nu = primeVertical(ellipsoid, latitude); // Zn is the z coordinate element of the point on the z-axis // which intersects with the the normal at the given Latitude *Zn = ellipsoid->GetE1sqd() * (*nu) * sin(latitude); return sqrt(X*X + Y*Y + pow(Z+(*Zn), (int)2)) - (*nu); } template <class T> T EllipsoidHeightDifference(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T Latitude1, const T Latitude2, T* h1, T* h2, T* nu1, T* nu2, T* Zn1, T* Zn2, const CDnaEllipsoid* ellipsoid) { return ((*h2 = EllipsoidHeight(X2, Y2, Z2, Latitude2, nu2, Zn2, ellipsoid)) - (*h1 = EllipsoidHeight(X1, Y1, Z1, Latitude1, nu1, Zn1, ellipsoid))); } template <class T> T magnitude(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2) { return sqrt(((X2 - X1) * (X2 - X1)) + ((Y2 - Y1) * (Y2 - Y1)) + ((Z2 - Z1) * (Z2 - Z1))); } template <class T> T magnitude(const T dX, const T dY, const T dZ) { return sqrt((dX * dX) + (dY * dY) + (dZ * dZ)); } template <class T> T magnitude(const T X1, const T N1, const T X2, const T N2) { return sqrt(((X2 - X1) * (X2 - X1)) + ((N2 - N1) * (N2 - N1))); } template <class T> T magnitude(const T dX, const T dN) { return sqrt((dX * dX) + (dN * dN)); } template <class T> T EllipsoidChordDistance(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T latitude1, const T latitude2, const T Height1, const T Height2, T* dX, T* dY, T* dZ, const CDnaEllipsoid* ellipsoid) { T nu1(primeVertical(ellipsoid, latitude1)); T nu2(primeVertical(ellipsoid, latitude2)); T scale1(nu1 / (nu1 + Height1)); T scale2(nu2 / (nu2 + Height2)); // Zn1,2 is the z coordinate element of the point on the z-axis // which intersects with the the normal at the given Latitude T Zn1(ellipsoid->GetE1sqd() * nu1 * sin(latitude1)); T Zn2(ellipsoid->GetE1sqd() * nu2 * sin(latitude2)); // station 1 T x1(X1 * scale1); T y1(Y1 * scale1); T z1((Z1 + Zn1) * scale1 - Zn1); // station 2 T x2(X2 * scale2); T y2(Y2 * scale2); T z2((Z2 + Zn2) * scale2 - Zn2); *dX = x2 - x1; *dY = y2 - y1; *dZ = z2 - z1; return magnitude(*dX, *dY, *dZ); } template <class T> T RadiusCurvatureInChordDirection(const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T latitude1, const T longitude1, const T latitude2, const CDnaEllipsoid* ellipsoid) { T nu, rho; primeVerticalandMeridian(ellipsoid, average(latitude1, latitude2), nu, rho); T local_12e, local_12n; T direction12(Direction(X1, Y1, Z1, X2, Y2, Z2, latitude1, longitude1, &local_12e, &local_12n)); T cos_dir(cos(direction12)); T sin_dir(sin(direction12)); return rho * nu / ((nu * cos_dir * cos_dir) + (rho * sin_dir * sin_dir)); } template <class T> T EllipsoidArctoEllipsoidChord(const T arc, const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T Latitude1, const T Longitude1, const T Latitude2, const CDnaEllipsoid* ellipsoid) { T r(RadiusCurvatureInChordDirection(X1, Y1, Z1, X2, Y2, Z2, Latitude1, Longitude1, Latitude2, ellipsoid)); return 2.0 * r * sin(arc / 2.0 / r); } template <class T> T EllipsoidChordtoEllipsoidArc(const T chord, const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T Latitude1, const T Longitude1, const T Latitude2, const CDnaEllipsoid* ellipsoid) { T r(RadiusCurvatureInChordDirection(X1, Y1, Z1, X2, Y2, Z2, Latitude1, Longitude1, Latitude2, ellipsoid)); return asin(chord / 2.0 / r) * 2.0 * r; } template <class T> T EllipsoidArcDistance( const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T Latitude1, const T Longitude1, const T Latitude2, const T Height1, const T Height2, const CDnaEllipsoid* ellipsoid) { T dx, dy, dz, ellipsoid_chord; ellipsoid_chord = EllipsoidChordDistance<T>( X1, Y1, Z1, X2, Y2, Z2, Latitude1, Latitude2, Height1, Height2, &dx, &dy, &dz, ellipsoid); return EllipsoidChordtoEllipsoidArc<T>( ellipsoid_chord, X1, Y1, Z1, X2, Y2, Z2, Latitude1, Longitude1, Latitude2, ellipsoid); } template <class T> T MSLChordtoMSLArc(const T chord, const T latitude1, const T latitude2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { T nu, rho; primeVerticalandMeridian(ellipsoid, average(latitude1, latitude2), nu, rho); T r(sqrt(nu*rho) + average(N1, N2)); return asin(chord / 2.0 / r) * 2.0 * r; } template <class T> T MSLArctoMSLChord(const T arc, const T latitude1, const T latitude2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { T nu, rho; primeVerticalandMeridian(ellipsoid, average(latitude1, latitude2), nu, rho); T r(sqrt(nu*rho) + average(N1, N2)); return 2.0 * r * sin(arc / 2.0 / r); } template <class T> T MSLChordtoEllipsoidChord(const T msl_chord, const T Latitude1, const T Latitude2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { T ellipsoid_chord(msl_chord * msl_chord); ellipsoid_chord -= pow(N2 - N1, (int)2); T meanLat(average(Latitude1, Latitude2)); ellipsoid_chord /= 1. + N1 / averageRadiusofCurvature(ellipsoid, meanLat); ellipsoid_chord /= 1. + N2 / averageRadiusofCurvature(ellipsoid, meanLat); return sqrt(ellipsoid_chord); } template <class T> T MSLArctoEllipsoidChord(const T msl_arc, const T Latitude1, const T Latitude2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { // 1. Convert MSL Arc -> MSL Chord T msl_chord = MSLArctoMSLChord<T>(msl_arc, Latitude1, Latitude2, N1, N2, ellipsoid); // 2. Convert MSL Chord -> Ellipsoid Chord return MSLChordtoEllipsoidChord<T>(msl_chord, Latitude1, Latitude2, N1, N2, ellipsoid); } template <class T> T EllipsoidChordtoMSLChord(const T ellipsoid_chord, const T Latitude1, const T Latitude2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { T msl_chord(ellipsoid_chord * ellipsoid_chord); T meanLat(average(Latitude1, Latitude2)); msl_chord *= 1. + N1 / averageRadiusofCurvature(ellipsoid, meanLat); msl_chord *= 1. + N2 / averageRadiusofCurvature(ellipsoid, meanLat); msl_chord += pow(N2 - N1, (int)2); return sqrt(msl_chord); } template <class T> T EllipsoidChordtoMSLArc(const T ellipsoid_chord, const T Latitude1, const T Latitude2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { // 1. Convert Ellipsoid Chord -> MSL Chord T msl_chord = EllipsoidChordtoMSLChord<T>( ellipsoid_chord, Latitude1, Latitude2, N1, N2, ellipsoid); // 2. Convert MSL Chord to MSL Arc return MSLChordtoMSLArc<T>( msl_chord, Latitude1, Latitude2, N1, N2, ellipsoid); } template <class T> T MSLArcDistance( const T X1, const T Y1, const T Z1, const T X2, const T Y2, const T Z2, const T Latitude1, const T Longitude1, const T Latitude2, const T Height1, const T Height2, const T N1, const T N2, const CDnaEllipsoid* ellipsoid) { // 1. Calculate Ellipsoid Chord T dx, dy, dz, chord; chord = EllipsoidChordDistance<T>( X1, Y1, Z1, X2, Y2, Z2, Latitude1, Latitude2, Height1, Height2, &dx, &dy, &dz, ellipsoid); // 2. Convert Ellipsoid Chord -> MSL Chord chord = EllipsoidChordtoMSLChord<T>( chord, Latitude1, Latitude2, N1, N2, ellipsoid); // 3. Convert MSL Chord -> MSL Arc return MSLChordtoMSLArc<T>( chord, Latitude1, Latitude2, N1, N2, ellipsoid); } template <class T> T LaplaceCorrection(const T azimuth, const T zenith, const T deflPrimeV, const T deflPrimeM, const T Latitude) { return deflPrimeV * tan(Latitude) + ((deflPrimeM * sin(azimuth) - deflPrimeV * cos(azimuth)) / tan(zenith)); // cot(z) = 1/tan(z) } template <class T> T ZenithDeflectionCorrection(const T azimuth, const T deflPrimeV, const T deflPrimeM) { return deflPrimeM * cos(azimuth) + deflPrimeV * sin(azimuth); } template <class T> T DirectionDeflectionCorrection(const T azimuth, const T zenith, const T deflPrimeV, const T deflPrimeM) { return (deflPrimeM * sin(azimuth) - deflPrimeV * cos(azimuth)) / tan(zenith); // cot(z) = 1/tan(z) } template <class T> T HzAngleDeflectionCorrection(const T azimuth12, const T zenith12, const T azimuth13, const T zenith13, const T deflPrimeV, const T deflPrimeM) { return DirectionDeflectionCorrection(azimuth13, zenith13, deflPrimeV, deflPrimeM) - DirectionDeflectionCorrection(azimuth12, zenith12, deflPrimeV, deflPrimeM); } template <class T> T HzAngleDeflectionCorrections(const T azimuth12, const T zenith12, const T azimuth13, const T zenith13, const T deflPrimeV, const T deflPrimeM, T& correction12, T& correction13) { return (correction13 = DirectionDeflectionCorrection(azimuth13, zenith13, deflPrimeV, deflPrimeM)) - (correction12 = DirectionDeflectionCorrection(azimuth12, zenith12, deflPrimeV, deflPrimeM)); } #endif /* DNATEMPLATEGEODESYFUNCS_H_ */
32.31781
249
0.644285
[ "vector" ]
02dda8d2e0d5da787b9c6b2bc8b75ba0859e5f12
20,347
cc
C++
src/xenia/kernel/xam/xam_user.cc
randprint/xenia
ae3b68c7b602b34412db5de16e20bd933e0ab1bd
[ "BSD-3-Clause" ]
1
2020-11-19T00:46:24.000Z
2020-11-19T00:46:24.000Z
src/xenia/kernel/xam/xam_user.cc
randprint/xenia
ae3b68c7b602b34412db5de16e20bd933e0ab1bd
[ "BSD-3-Clause" ]
null
null
null
src/xenia/kernel/xam/xam_user.cc
randprint/xenia
ae3b68c7b602b34412db5de16e20bd933e0ab1bd
[ "BSD-3-Clause" ]
1
2020-07-06T08:04:32.000Z
2020-07-06T08:04:32.000Z
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <cstring> #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/xam/xam_private.h" #include "xenia/kernel/xenumerator.h" #include "xenia/kernel/xthread.h" #include "xenia/xbox.h" namespace xe { namespace kernel { namespace xam { X_HRESULT_result_t XamUserGetXUID(dword_t user_index, dword_t type_mask, lpqword_t xuid_ptr) { if (!xuid_ptr) { return X_E_INVALIDARG; } assert_true(type_mask == 1 || type_mask == 2 || type_mask == 3 || type_mask == 4 || type_mask == 7); uint32_t result = X_E_NO_SUCH_USER; uint64_t xuid = 0; if (user_index < 4) { if (user_index == 0) { const auto& user_profile = kernel_state()->user_profile(); if (type_mask & (2 | 4)) { xuid = user_profile->xuid(); result = X_E_SUCCESS; } else if (type_mask & 1) { xuid = user_profile->xuid(); result = X_E_SUCCESS; } else { result = X_E_INVALIDARG; } } } else { result = X_E_INVALIDARG; } *xuid_ptr = xuid; return result; } DECLARE_XAM_EXPORT1(XamUserGetXUID, kUserProfiles, kImplemented); dword_result_t XamUserGetSigninState(dword_t user_index) { // Yield, as some games spam this. xe::threading::MaybeYield(); uint32_t signin_state = 0; if (user_index < 4) { if (user_index == 0) { const auto& user_profile = kernel_state()->user_profile(); signin_state = user_profile->signin_state(); } } return signin_state; } DECLARE_XAM_EXPORT2(XamUserGetSigninState, kUserProfiles, kImplemented, kHighFrequency); typedef struct { xe::be<uint64_t> xuid; xe::be<uint32_t> unk08; // maybe zero? xe::be<uint32_t> signin_state; xe::be<uint32_t> unk10; // ? xe::be<uint32_t> unk14; // ? char name[16]; } X_USER_SIGNIN_INFO; static_assert_size(X_USER_SIGNIN_INFO, 40); X_HRESULT_result_t XamUserGetSigninInfo(dword_t user_index, dword_t flags, pointer_t<X_USER_SIGNIN_INFO> info) { if (!info) { return X_E_INVALIDARG; } std::memset(info, 0, sizeof(X_USER_SIGNIN_INFO)); if (user_index) { return X_E_NO_SUCH_USER; } const auto& user_profile = kernel_state()->user_profile(); info->xuid = user_profile->xuid(); info->signin_state = user_profile->signin_state(); std::strncpy(info->name, user_profile->name().data(), 15); return X_E_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserGetSigninInfo, kUserProfiles, kImplemented); dword_result_t XamUserGetName(dword_t user_index, lpstring_t buffer, dword_t buffer_len) { if (user_index) { return X_ERROR_NO_SUCH_USER; } if (!buffer_len) { return X_ERROR_SUCCESS; } const auto& user_profile = kernel_state()->user_profile(); const auto& user_name = user_profile->name(); // Real XAM will only copy a maximum of 15 characters out. size_t copy_length = std::min( {size_t(15), user_name.size(), static_cast<size_t>(buffer_len) - 1}); std::memcpy(buffer, user_name.data(), copy_length); buffer[copy_length] = '\0'; return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserGetName, kUserProfiles, kImplemented); typedef struct { xe::be<uint32_t> setting_count; xe::be<uint32_t> settings_ptr; } X_USER_READ_PROFILE_SETTINGS; static_assert_size(X_USER_READ_PROFILE_SETTINGS, 8); typedef struct { xe::be<uint32_t> from; xe::be<uint32_t> unk04; xe::be<uint32_t> user_index; xe::be<uint32_t> unk0C; xe::be<uint32_t> setting_id; xe::be<uint32_t> unk14; uint8_t setting_data[16]; } X_USER_READ_PROFILE_SETTING; static_assert_size(X_USER_READ_PROFILE_SETTING, 40); // https://github.com/oukiar/freestyledash/blob/master/Freestyle/Tools/Generic/xboxtools.cpp uint32_t xeXamUserReadProfileSettingsEx(uint32_t title_id, uint32_t user_index, uint32_t xuid_count, lpqword_t xuids, uint32_t setting_count, lpdword_t setting_ids, uint32_t unk, lpdword_t buffer_size_ptr, lpvoid_t buffer_ptr, uint32_t overlapped_ptr) { if (!xuid_count) { assert_null(xuids); } else { assert_true(xuid_count == 1); assert_not_null(xuids); // TODO(gibbed): allow proper lookup of arbitrary XUIDs const auto& user_profile = kernel_state()->user_profile(); assert_true(static_cast<uint64_t>(xuids[0]) == user_profile->xuid()); } assert_zero(unk); // must have at least 1 to 32 settings if (setting_count < 1 || setting_count > 32) { return X_ERROR_INVALID_PARAMETER; } // buffer size pointer must be valid if (!buffer_size_ptr) { return X_ERROR_INVALID_PARAMETER; } // if buffer size is non-zero, buffer pointer must be valid auto buffer_size = static_cast<uint32_t>(*buffer_size_ptr); if (buffer_size && !buffer_ptr) { return X_ERROR_INVALID_PARAMETER; } uint32_t needed_header_size = 0; uint32_t needed_extra_size = 0; for (uint32_t i = 0; i < setting_count; ++i) { needed_header_size += sizeof(X_USER_READ_PROFILE_SETTING); UserProfile::Setting::Key setting_key; setting_key.value = static_cast<uint32_t>(setting_ids[i]); switch (static_cast<UserProfile::Setting::Type>(setting_key.type)) { case UserProfile::Setting::Type::WSTRING: case UserProfile::Setting::Type::BINARY: { needed_extra_size += setting_key.size; break; } default: { break; } } } if (xuids) { // needed_header_size *= xuid_count; // needed_extra_size *= !xuid_count; } needed_header_size += sizeof(X_USER_READ_PROFILE_SETTINGS); uint32_t needed_size = needed_header_size + needed_extra_size; if (!buffer_ptr || buffer_size < needed_size) { if (!buffer_size) { *buffer_size_ptr = needed_size; } return X_ERROR_INSUFFICIENT_BUFFER; } // Title ID = 0 means us. // 0xfffe07d1 = profile? if (user_index) { // Only support user 0. if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_NO_SUCH_USER); return X_ERROR_IO_PENDING; } return X_ERROR_NO_SUCH_USER; } const auto& user_profile = kernel_state()->user_profile(); // First call asks for size (fill buffer_size_ptr). // Second call asks for buffer contents with that size. // TODO(gibbed): setting validity checking without needing a user profile // object. bool any_missing = false; for (uint32_t i = 0; i < setting_count; ++i) { auto setting_id = static_cast<uint32_t>(setting_ids[i]); auto setting = user_profile->GetSetting(setting_id); if (!setting) { any_missing = true; XELOGE( "xeXamUserReadProfileSettingsEx requested unimplemented setting " "{:08X}", setting_id); } } if (any_missing) { // TODO(benvanik): don't fail? most games don't even check! if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_INVALID_PARAMETER); return X_ERROR_IO_PENDING; } return X_ERROR_INVALID_PARAMETER; } auto out_header = buffer_ptr.as<X_USER_READ_PROFILE_SETTINGS*>(); out_header->setting_count = static_cast<uint32_t>(setting_count); out_header->settings_ptr = buffer_ptr.guest_address() + 8; auto out_setting = reinterpret_cast<X_USER_READ_PROFILE_SETTING*>(&out_header[1]); size_t buffer_offset = needed_header_size; for (uint32_t n = 0; n < setting_count; ++n) { uint32_t setting_id = setting_ids[n]; auto setting = user_profile->GetSetting(setting_id); std::memset(out_setting, 0, sizeof(X_USER_READ_PROFILE_SETTING)); out_setting->from = !setting || !setting->is_set ? 0 : setting->is_title_specific() ? 2 : 1; out_setting->user_index = static_cast<uint32_t>(user_index); out_setting->setting_id = setting_id; if (setting && setting->is_set) { buffer_offset = setting->Append(&out_setting->setting_data[0], buffer_ptr, buffer_ptr.guest_address(), buffer_offset); } // TODO(benvanik): why did I do this? /*else { std::memset(&out_setting->setting_data[0], 0, sizeof(out_setting->setting_data)); }*/ ++out_setting; } if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS); return X_ERROR_IO_PENDING; } return X_ERROR_SUCCESS; } dword_result_t XamUserReadProfileSettings( dword_t title_id, dword_t user_index, dword_t xuid_count, lpqword_t xuids, dword_t setting_count, lpdword_t setting_ids, lpdword_t buffer_size_ptr, lpvoid_t buffer_ptr, dword_t overlapped_ptr) { return xeXamUserReadProfileSettingsEx( title_id, user_index, xuid_count, xuids, setting_count, setting_ids, 0, buffer_size_ptr, buffer_ptr, overlapped_ptr); } DECLARE_XAM_EXPORT1(XamUserReadProfileSettings, kUserProfiles, kImplemented); dword_result_t XamUserReadProfileSettingsEx( dword_t title_id, dword_t user_index, dword_t xuid_count, lpqword_t xuids, dword_t setting_count, lpdword_t setting_ids, lpdword_t buffer_size_ptr, dword_t unk_2, lpvoid_t buffer_ptr, dword_t overlapped_ptr) { return xeXamUserReadProfileSettingsEx( title_id, user_index, xuid_count, xuids, setting_count, setting_ids, unk_2, buffer_size_ptr, buffer_ptr, overlapped_ptr); } DECLARE_XAM_EXPORT1(XamUserReadProfileSettingsEx, kUserProfiles, kImplemented); typedef struct { xe::be<uint32_t> from; xe::be<uint32_t> unk_04; xe::be<uint32_t> unk_08; xe::be<uint32_t> unk_0c; xe::be<uint32_t> setting_id; xe::be<uint32_t> unk_14; // UserProfile::Setting::Type. Appears to be 8-in-32 field, and the upper 24 // are not always zeroed by the game. uint8_t type; xe::be<uint32_t> unk_1c; // TODO(sabretooth): not sure if this is a union, but it seems likely. // Haven't run into cases other than "binary data" yet. union { struct { xe::be<uint32_t> length; xe::be<uint32_t> ptr; } binary; }; } X_USER_WRITE_PROFILE_SETTING; dword_result_t XamUserWriteProfileSettings( dword_t title_id, dword_t user_index, dword_t setting_count, pointer_t<X_USER_WRITE_PROFILE_SETTING> settings, dword_t overlapped_ptr) { if (!setting_count || !settings) { return X_ERROR_INVALID_PARAMETER; } if (user_index) { // Only support user 0. if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_NO_SUCH_USER); return X_ERROR_IO_PENDING; } return X_ERROR_NO_SUCH_USER; } // Update and save settings. const auto& user_profile = kernel_state()->user_profile(); for (uint32_t n = 0; n < setting_count; ++n) { const X_USER_WRITE_PROFILE_SETTING& settings_data = settings[n]; XELOGD( "XamUserWriteProfileSettings: setting index [{}]:" " from={} setting_id={:08X} data.type={}", n, (uint32_t)settings_data.from, (uint32_t)settings_data.setting_id, settings_data.type); xam::UserProfile::Setting::Type settingType = static_cast<xam::UserProfile::Setting::Type>(settings_data.type); switch (settingType) { case UserProfile::Setting::Type::CONTENT: case UserProfile::Setting::Type::BINARY: { uint8_t* settings_data_ptr = kernel_state()->memory()->TranslateVirtual( settings_data.binary.ptr); size_t settings_data_len = settings_data.binary.length; std::vector<uint8_t> data_vec; if (settings_data.binary.ptr) { // Copy provided data data_vec.resize(settings_data_len); std::memcpy(data_vec.data(), settings_data_ptr, settings_data_len); } else { // Data pointer was NULL, so just fill with zeroes data_vec.resize(settings_data_len, 0); } user_profile->AddSetting( std::make_unique<xam::UserProfile::BinarySetting>( settings_data.setting_id, data_vec)); } break; case UserProfile::Setting::Type::WSTRING: case UserProfile::Setting::Type::DOUBLE: case UserProfile::Setting::Type::FLOAT: case UserProfile::Setting::Type::INT32: case UserProfile::Setting::Type::INT64: case UserProfile::Setting::Type::DATETIME: default: { XELOGE("XamUserWriteProfileSettings: Unimplemented data type {}", settingType); } break; }; } if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS); return X_ERROR_IO_PENDING; } return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserWriteProfileSettings, kUserProfiles, kImplemented); dword_result_t XamUserCheckPrivilege(dword_t user_index, dword_t mask, lpdword_t out_value) { if (user_index) { return X_ERROR_NO_SUCH_USER; } // If we deny everything, games should hopefully not try to do stuff. *out_value = 0; return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserCheckPrivilege, kUserProfiles, kStub); dword_result_t XamUserContentRestrictionGetFlags(dword_t user_index, lpdword_t out_flags) { if (user_index) { return X_ERROR_NO_SUCH_USER; } // No restrictions? *out_flags = 0; return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserContentRestrictionGetFlags, kUserProfiles, kStub); dword_result_t XamUserContentRestrictionGetRating(dword_t user_index, dword_t unk1, lpdword_t out_unk2, lpdword_t out_unk3) { if (user_index) { return X_ERROR_NO_SUCH_USER; } // Some games have special case paths for 3F that differ from the failure // path, so my guess is that's 'don't care'. *out_unk2 = 0x3F; *out_unk3 = 0; return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserContentRestrictionGetRating, kUserProfiles, kStub); dword_result_t XamUserContentRestrictionCheckAccess(dword_t user_index, dword_t unk1, dword_t unk2, dword_t unk3, dword_t unk4, lpdword_t out_unk5, dword_t overlapped_ptr) { *out_unk5 = 1; if (overlapped_ptr) { // TODO(benvanik): does this need the access arg on it? kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS); } return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserContentRestrictionCheckAccess, kUserProfiles, kStub); dword_result_t XamUserIsOnlineEnabled(dword_t user_index) { return 1; } DECLARE_XAM_EXPORT1(XamUserIsOnlineEnabled, kUserProfiles, kStub); dword_result_t XamUserAreUsersFriends(dword_t user_index, dword_t unk1, dword_t unk2, lpdword_t out_value, dword_t overlapped_ptr) { uint32_t are_friends = 0; X_RESULT result; if (user_index >= 4) { result = X_ERROR_INVALID_PARAMETER; } else { if (user_index == 0) { const auto& user_profile = kernel_state()->user_profile(); if (user_profile->signin_state() == 0) { result = X_ERROR_NOT_LOGGED_ON; } else { // No friends! are_friends = 0; result = X_ERROR_SUCCESS; } } else { // Only support user 0. result = X_ERROR_NO_SUCH_USER; // if user is local -> X_ERROR_NOT_LOGGED_ON } } if (out_value) { assert_true(!overlapped_ptr); *out_value = result == X_ERROR_SUCCESS ? are_friends : 0; return result; } else if (overlapped_ptr) { assert_true(!out_value); kernel_state()->CompleteOverlappedImmediateEx( overlapped_ptr, result == X_ERROR_SUCCESS ? X_ERROR_SUCCESS : X_ERROR_FUNCTION_FAILED, X_HRESULT_FROM_WIN32(result), result == X_ERROR_SUCCESS ? are_friends : 0); return X_ERROR_IO_PENDING; } else { assert_always(); return X_ERROR_INVALID_PARAMETER; } } DECLARE_XAM_EXPORT1(XamUserAreUsersFriends, kUserProfiles, kStub); dword_result_t XamShowSigninUI(dword_t unk, dword_t unk_mask) { // Mask values vary. Probably matching user types? Local/remote? // Games seem to sit and loop until we trigger this notification. kernel_state()->BroadcastNotification(0x00000009, 0); return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamShowSigninUI, kUserProfiles, kStub); dword_result_t XamUserCreateAchievementEnumerator(dword_t title_id, dword_t user_index, dword_t xuid, dword_t flags, dword_t offset, dword_t count, lpdword_t buffer_size_ptr, lpdword_t handle_ptr) { if (buffer_size_ptr) { *buffer_size_ptr = 500 * count; } auto e = new XStaticEnumerator(kernel_state(), count, 500); e->Initialize(); *handle_ptr = e->handle(); return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamUserCreateAchievementEnumerator, kUserProfiles, kSketchy); dword_result_t XamParseGamerTileKey(lpdword_t key_ptr, lpdword_t out1_ptr, lpdword_t out2_ptr, lpdword_t out3_ptr) { *out1_ptr = 0xC0DE0001; *out2_ptr = 0xC0DE0002; *out3_ptr = 0xC0DE0003; return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamParseGamerTileKey, kUserProfiles, kStub); dword_result_t XamReadTileToTexture(dword_t unk1, dword_t unk2, dword_t unk3, dword_t unk4, lpvoid_t buffer_ptr, dword_t stride, dword_t height, dword_t overlapped_ptr) { // unk1: const? // unk2: out0 from XamParseGamerTileKey // unk3: some variant of out1/out2 // unk4: const? if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS); return X_ERROR_IO_PENDING; } return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamReadTileToTexture, kUserProfiles, kStub); dword_result_t XamWriteGamerTile(dword_t arg1, dword_t arg2, dword_t arg3, dword_t arg4, dword_t arg5, dword_t overlapped_ptr) { if (overlapped_ptr) { kernel_state()->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS); return X_ERROR_IO_PENDING; } return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamWriteGamerTile, kUserProfiles, kStub); dword_result_t XamSessionCreateHandle(lpdword_t handle_ptr) { *handle_ptr = 0xCAFEDEAD; return X_ERROR_SUCCESS; } DECLARE_XAM_EXPORT1(XamSessionCreateHandle, kUserProfiles, kStub); dword_result_t XamSessionRefObjByHandle(dword_t handle, lpdword_t obj_ptr) { assert_true(handle == 0xCAFEDEAD); *obj_ptr = 0; return X_ERROR_FUNCTION_FAILED; } DECLARE_XAM_EXPORT1(XamSessionRefObjByHandle, kUserProfiles, kStub); } // namespace xam } // namespace kernel } // namespace xe void xe::kernel::xam::RegisterUserExports( xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {}
34.254209
92
0.646778
[ "object", "vector" ]
02e24675e981082d47d3051640c292a90d107c45
17,292
cpp
C++
cyber.token/src/cyber.token.cpp
cyberway/cyberway.contracts
a6a7d6e25a225a1de2537f5a224decdea2066d77
[ "MIT" ]
3
2019-10-16T04:39:49.000Z
2019-10-16T05:01:01.000Z
cyber.token/src/cyber.token.cpp
GolosChain/cyberway.contracts
a6a7d6e25a225a1de2537f5a224decdea2066d77
[ "MIT" ]
110
2018-10-23T09:18:39.000Z
2019-07-25T03:16:21.000Z
cyber.token/src/cyber.token.cpp
cyberway/cyberway.contracts
a6a7d6e25a225a1de2537f5a224decdea2066d77
[ "MIT" ]
2
2020-10-28T14:49:29.000Z
2020-10-28T15:33:18.000Z
/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosio/event.hpp> #include <cyber.token/cyber.token.hpp> #include <set> namespace eosio { namespace config { static constexpr size_t max_memo_size = 384; static constexpr char memo_error[] = "memo has more than 384 bytes"; const uint32_t seconds_per_day = 24 * 60 * 60; // TODO: move to some global consts static constexpr uint32_t safe_max_delay = 30 * seconds_per_day; // max delay and max lock period } void token::send_currency_event(const currency_stats& stat) { eosio::event(_self, "currency"_n, stat).send(); } void token::send_balance_event(name acc, const account& accinfo) { balance_event data{acc, accinfo.balance, accinfo.payments}; eosio::event(_self, "balance"_n, data).send(); } void token::create( name issuer, asset maximum_supply ) { require_auth( _self ); eosio::check(is_account(issuer), "issuer account does not exist"); auto sym = maximum_supply.symbol; eosio::check( sym.is_valid(), "invalid symbol name" ); eosio::check( maximum_supply.is_valid(), "invalid supply"); eosio::check( maximum_supply.amount > 0, "max-supply must be positive"); stats statstable( _self, sym.code().raw() ); auto existing = statstable.find( sym.code().raw() ); eosio::check( existing == statstable.end(), "token with symbol already exists" ); statstable.emplace( _self, [&]( auto& s ) { s.supply.symbol = maximum_supply.symbol; s.max_supply = maximum_supply; s.issuer = issuer; send_currency_event(s); }); } void token::issue( name to, asset quantity, string memo ) { auto sym = quantity.symbol; eosio::check( sym.is_valid(), "invalid symbol name" ); eosio::check( memo.size() <= config::max_memo_size, config::memo_error ); stats statstable( _self, sym.code().raw() ); auto existing = statstable.find( sym.code().raw() ); eosio::check( existing != statstable.end(), "token with symbol does not exist, create token before issue" ); const auto& st = *existing; require_auth( st.issuer ); eosio::check( quantity.is_valid(), "invalid quantity" ); eosio::check( quantity.amount > 0, "must issue positive quantity" ); eosio::check( quantity.symbol == st.supply.symbol, "symbol precision mismatch" ); eosio::check( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply"); statstable.modify( st, same_payer, [&]( auto& s ) { s.supply += quantity; send_currency_event(s); }); add_balance( st.issuer, quantity, st.issuer ); if( to != st.issuer ) { SEND_INLINE_ACTION( *this, transfer, { {st.issuer, "active"_n} }, { st.issuer, to, quantity, memo } ); } } void token::retire( asset quantity, string memo ) { auto sym = quantity.symbol; eosio::check( sym.is_valid(), "invalid symbol name" ); eosio::check( memo.size() <= config::max_memo_size, config::memo_error ); stats statstable( _self, sym.code().raw() ); auto existing = statstable.find( sym.code().raw() ); eosio::check( existing != statstable.end(), "token with symbol does not exist" ); const auto& st = *existing; require_auth( st.issuer ); eosio::check( quantity.is_valid(), "invalid quantity" ); eosio::check( quantity.amount > 0, "must retire positive quantity" ); eosio::check( quantity.symbol == st.supply.symbol, "symbol precision mismatch" ); statstable.modify( st, same_payer, [&]( auto& s ) { s.supply -= quantity; send_currency_event(s); }); sub_balance( st.issuer, quantity ); } void token::transfer( name from, name to, asset quantity, string memo ) { require_recipient( from ); require_recipient( to ); do_transfer(from, to, quantity, memo); } void token::payment( name from, name to, asset quantity, string memo ) { do_transfer(from, to, quantity, memo, true); } void token::do_transfer( name from, name to, const asset& quantity, const string& memo, bool payment ) { if (!payment) eosio::check( from != to, "cannot transfer to self" ); require_auth( from ); eosio::check( is_account( to ), "to account does not exist"); auto sym = quantity.symbol.code(); stats statstable( _self, sym.raw() ); const auto& st = statstable.get( sym.raw() ); eosio::check( quantity.is_valid(), "invalid quantity" ); eosio::check( quantity.amount > 0, "must transfer positive quantity" ); eosio::check( quantity.symbol == st.supply.symbol, "symbol precision mismatch" ); eosio::check( memo.size() <= config::max_memo_size, config::memo_error ); auto payer = has_auth( to ) ? to : from; sub_balance( from, quantity ); if (payment) add_payment( to, quantity, payer ); else add_balance( to, quantity, payer ); } void token::sub_balance( name owner, asset value ) { accounts from_acnts( _self, owner.value ); const auto& from = from_acnts.get( value.symbol.code().raw(), "no balance object found" ); eosio::check( from.balance.amount >= value.amount, "overdrawn balance" ); from_acnts.modify( from, owner, [&]( auto& a ) { a.balance -= value; send_balance_event(owner, a); }); check(!is_locked(_self, owner), "balance locked in safe"); if (from.has_safe()) { from_acnts.modify(from, owner, [&](auto& a) { auto safe = a.get_safe(); safe.unlocked -= value.amount; check(safe.unlocked >= 0, "overdrawn safe unlocked balance"); a.modify_safe(safe); }); } } void token::add_balance( name owner, asset value, name ram_payer ) { accounts to_acnts( _self, owner.value ); auto to = to_acnts.find( value.symbol.code().raw() ); if( to == to_acnts.end() ) { to_acnts.emplace( ram_payer, [&]( auto& a ){ a.balance = value; a.payments.symbol = value.symbol; send_balance_event(owner, a); }); } else { to_acnts.modify( to, same_payer, [&]( auto& a ) { a.balance += value; send_balance_event(owner, a); }); } } void token::add_payment( name owner, asset value, name ram_payer ) { accounts to_acnts( _self, owner.value ); auto to = to_acnts.find( value.symbol.code().raw() ); if( to == to_acnts.end() ) { to_acnts.emplace( ram_payer, [&]( auto& a ){ a.balance.symbol = value.symbol; a.payments = value; send_balance_event(owner, a); }); } else { to_acnts.modify( to, same_payer, [&]( auto& a ) { a.payments += value; send_balance_event(owner, a); }); } } void token::open( name owner, const symbol& symbol, name ram_payer ) { require_auth( ram_payer ); eosio::check( is_account( owner ), "owner account does not exist"); auto sym_code_raw = symbol.code().raw(); stats statstable( _self, sym_code_raw ); const auto& st = statstable.get( sym_code_raw, "symbol does not exist" ); eosio::check( st.supply.symbol == symbol, "symbol precision mismatch" ); accounts acnts( _self, owner.value ); auto it = acnts.find( sym_code_raw ); if( it == acnts.end() ) { acnts.emplace( ram_payer, [&]( auto& a ){ a.balance = asset{0, symbol}; a.payments = asset{0, symbol}; }); } } void token::close( name owner, const symbol& symbol ) { require_auth( owner ); accounts acnts( _self, owner.value ); auto it = acnts.find( symbol.code().raw() ); eosio::check( it != acnts.end(), "Balance row already deleted or never existed. Action won't have any effect." ); eosio::check( it->balance.amount == 0, "Cannot close because the balance is not zero." ); eosio::check( it->payments.amount == 0, "Cannot close because account has payments." ); eosio::check( !it->has_safe(), "Cannot close because safe enabled." ); it->validate(); acnts.erase( it ); } void token::claim( name owner, asset quantity ) { require_auth( owner ); eosio::check( quantity.is_valid(), "invalid quantity" ); eosio::check( quantity.amount > 0, "must transfer positive quantity" ); accounts owner_acnts( _self, owner.value ); auto account = owner_acnts.find( quantity.symbol.code().raw() ); eosio::check( account != owner_acnts.end(), "not found object account" ); eosio::check( quantity.symbol == account->payments.symbol, "symbol precision mismatch" ); eosio::check( account->payments >= quantity, "insufficient funds" ); owner_acnts.modify( account, owner, [&]( auto& a ) { a.balance += quantity; a.payments -= quantity; send_balance_event(owner, a); }); } void token::bulktransfer(name from, vector<recipient> recipients) { require_recipient(from); eosio::check(recipients.size(), "recipients must not be empty"); symbol temp_symbol = recipients.at(0).quantity.symbol; std::set<name> require_recipients; for (auto recipient_obj : recipients) { eosio::check(temp_symbol == recipient_obj.quantity.symbol, "transfer of different tokens is prohibited"); do_transfer(from, recipient_obj.to, recipient_obj.quantity, recipient_obj.memo); auto result = require_recipients.insert(recipient_obj.to); if (result.second) require_recipient(recipient_obj.to); } } void token::bulkpayment(name from, vector<recipient> recipients) { require_recipient(from); eosio::check(recipients.size(), "recipients must not be empty"); symbol temp_symbol = recipients.at(0).quantity.symbol; for (auto recipient_obj : recipients) { eosio::check(temp_symbol == recipient_obj.quantity.symbol, "payment of different tokens is prohibited"); do_transfer(from, recipient_obj.to, recipient_obj.quantity, recipient_obj.memo, true); } } //////////////////////////////////////////////////////////////// // safe related actions using std::optional; void check_safe_params(name owner, optional<uint32_t> delay, optional<name> trusted) { if (delay) { check(*delay > 0, "delay must be > 0"); check(*delay <= config::safe_max_delay, "delay must be <= " + std::to_string(config::safe_max_delay)); } if (trusted && *trusted != name()) { check(owner != *trusted, "trusted and owner must be different accounts"); check(is_account(*trusted), "trusted account does not exist"); } } void token::enablesafe(name owner, asset unlock, uint32_t delay, name trusted) { require_auth(owner); check(unlock.amount >= 0, "unlock amount must be >= 0"); check_safe_params(owner, delay, trusted); if (unlock.symbol != symbol{}) { validate_symbol(_self, unlock); } accounts tbl(_self, owner.value); const auto scode = unlock.symbol.code(); const auto& acc = tbl.get(scode.raw(), "no token account object found"); check(!acc.has_safe(), "safe already enabled"); // Do not allow to have delayed changes when enable the safe, they came from the previously enabled safe // and should be cancelled to make clean safe setup. safemod_tbl mods(_self, owner.value); auto idx = mods.get_index<"bysymbolcode"_n>(); auto itr = idx.lower_bound(scode); check(itr == idx.end() || itr->sym_code != scode, "can't enable safe with existing delayed mods"); tbl.modify(acc, owner, [&](auto& a) { a.create_safe(safe_t{unlock.amount, delay, trusted}); }); } template<typename Tbl, typename S> void instant_safe_change(Tbl& tbl, S& acc, name owner, int64_t unlock, optional<uint32_t> delay, optional<name> trusted, bool ensure_change ) { if (delay && *delay == 0) { check(!unlock && !trusted, "SYS: incorrect disabling safe mod"); tbl.modify(acc, owner, [](auto& a){ a.remove_safe(); }); } else { bool changed = !ensure_change; auto safe = acc.get_safe(); if (unlock) { safe.unlocked += unlock; check(safe.unlocked >= 0 && safe.unlocked <= asset::max_amount, "unlocked overflow"); changed = true; } if (delay && *delay != safe.delay) { safe.delay = *delay; changed = true; } if (trusted && *trusted != safe.trusted) { safe.trusted = *trusted; changed = true; } check(changed, "change has no effect and can be cancelled"); tbl.modify(acc, owner, [&](auto& a) { a.modify_safe(safe); }); } } // helper for actions which do not change `unlocked` and have incomplete asset symbol void token::delay_safe_change( name owner, symbol_code scode, name mod_id, optional<uint32_t> delay, optional<name> trusted, bool check_params/*=true*/ ) { const asset fake_asset{0, symbol{scode, 0}}; delay_safe_change(owner, fake_asset, mod_id, delay, trusted, check_params, false); } void token::delay_safe_change( name owner, asset unlock, name mod_id, optional<uint32_t> delay, optional<name> trusted, bool check_params/*=true*/, bool check_sym/*=true*/ ) { if (check_params) { check_safe_params(owner, delay, trusted); } if (check_sym) { validate_symbol(_self, unlock); } const auto scode = unlock.symbol.code(); accounts tbl(_self, owner.value); const auto& acc = tbl.get(scode.raw(), "no token account object found"); auto safe = acc.get_safe(); const bool have_id = mod_id != name(); const auto trusted_acc = safe.trusted; if (trusted_acc != name() && has_auth(trusted_acc)) { check(!have_id, "mod_id must be empty for trusted action"); check(!delay || *delay != safe.delay, "can't set same delay"); check(!trusted || *trusted != trusted_acc, "can't set same trusted"); instant_safe_change(tbl, acc, owner, unlock.amount, delay, trusted, false); } else { check(have_id, "mod_id must not be empty"); safemod_tbl mods(_self, owner.value); check(mods.find(mod_id.value) == mods.end(), "safe mod with the same id is already exists"); mods.emplace(owner, [&](auto& d) { d.id = mod_id; d.sym_code = scode; d.date = eosio::current_time_point() + eosio::seconds(safe.delay); d.unlock = unlock.amount; d.delay = delay; d.trusted = trusted; }); } } void token::disablesafe(name owner, symbol_code sym_code, name mod_id) { require_auth(owner); delay_safe_change(owner, sym_code, mod_id, 0, {}, false); } void token::unlocksafe(name owner, asset unlock, name mod_id) { require_auth(owner); check(unlock.amount > 0, "unlock amount must be > 0"); delay_safe_change(owner, unlock, mod_id, {}, {}); } void token::locksafe(name owner, asset lock) { require_auth(owner); check(lock.amount >= 0, "lock amount must be >= 0"); validate_symbol(_self, lock); // checked within "<= unlocked", but have confusing message, so check here const auto scode = lock.symbol.code(); accounts tbl(_self, owner.value); const auto& acc = tbl.get(scode.raw(), "no token account object found"); auto safe = acc.get_safe(); check(safe.unlocked > 0, "nothing to lock"); check(safe.unlocked >= lock.amount, "lock must be <= unlocked"); bool lock_all = lock.amount == 0; tbl.modify(acc, owner, [&](auto& a) { safe.unlocked -= lock_all ? safe.unlocked : lock.amount; a.modify_safe(safe); }); } void token::modifysafe( name owner, symbol_code sym_code, name mod_id, optional<uint32_t> delay, optional<name> trusted ) { require_auth(owner); check(delay || trusted, "delay and/or trusted must be set"); delay_safe_change(owner, sym_code, mod_id, delay, trusted); } void token::applysafemod(name owner, name mod_id) { require_auth(owner); safemod_tbl mods(_self, owner.value); const auto& mod = mods.get(mod_id.value, "safe mod not found"); accounts tbl(_self, owner.value); const auto& acc = tbl.get(mod.sym_code.raw(), "no token account object found"); const auto& safe = acc.get_safe(); bool trusted_apply = safe.trusted != name() && has_auth(safe.trusted); if (!trusted_apply) { check(mod.date <= eosio::current_time_point(), "safe change is time locked"); check(!is_locked(_self, owner), "safe locked globally"); } instant_safe_change(tbl, acc, owner, mod.unlock, mod.delay, mod.trusted, true); mods.erase(mod); } void token::cancelsafemod(name owner, name mod_id) { require_auth(owner); safemod_tbl mods(_self, owner.value); const auto& mod = mods.get(mod_id.value, "safe mod not found"); mods.erase(mod); } void token::globallock(name owner, uint32_t period) { require_auth(owner); check(period > 0, "period must be > 0"); check(period <= config::safe_max_delay, "period must be <= " + std::to_string(config::safe_max_delay)); time_point_sec unlocks{eosio::current_time_point() + eosio::seconds(period)}; lock_singleton lock(_self, owner.value); check(unlocks > lock.get_or_default().unlocks, "new unlock time must be greater than current"); lock.set({unlocks}, owner); } } /// namespace eosio
35.075051
116
0.638908
[ "object", "vector" ]
02e36bef708795ac4f15d9c46021dc760ea7d7d7
5,278
cpp
C++
be/src/storage/compaction_utils.cpp
hiliuxg/starrocks
04640294c794291e31c132bc6217cc62e71be17c
[ "Zlib", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
be/src/storage/compaction_utils.cpp
hiliuxg/starrocks
04640294c794291e31c132bc6217cc62e71be17c
[ "Zlib", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
be/src/storage/compaction_utils.cpp
hiliuxg/starrocks
04640294c794291e31c132bc6217cc62e71be17c
[ "Zlib", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. #include "storage/compaction_utils.h" #include "storage/base_and_cumulative_compaction_policy.h" #include "storage/row_source_mask.h" #include "storage/rowset/rowset_factory.h" #include "storage/rowset/rowset_writer.h" #include "storage/rowset/rowset_writer_context.h" #include "storage/storage_engine.h" #include "storage/tablet.h" namespace starrocks { const char* CompactionUtils::compaction_algorithm_to_string(CompactionAlgorithm v) { switch (v) { case HORIZONTAL_COMPACTION: return "HORIZONTAL_COMPACTION"; case VERTICAL_COMPACTION: return "VERTICAL_COMPACTION"; default: return "[Unknown CompactionAlgorithm]"; } } int32_t CompactionUtils::get_read_chunk_size(int64_t mem_limit, int32_t config_chunk_size, int64_t total_num_rows, int64_t total_mem_footprint, size_t source_num) { uint64_t chunk_size = config_chunk_size; if (mem_limit > 0) { int64_t avg_row_size = (total_mem_footprint + 1) / (total_num_rows + 1); // The result of the division operation be zero, so added one chunk_size = 1 + mem_limit / (source_num * avg_row_size + 1); } if (chunk_size > config_chunk_size) { chunk_size = config_chunk_size; } return chunk_size; } Status CompactionUtils::construct_output_rowset_writer(Tablet* tablet, uint32_t max_rows_per_segment, CompactionAlgorithm algorithm, Version version, std::unique_ptr<RowsetWriter>* output_rowset_writer) { RowsetWriterContext context(kDataFormatV2, config::storage_format_version); context.rowset_id = StorageEngine::instance()->next_rowset_id(); context.tablet_uid = tablet->tablet_uid(); context.tablet_id = tablet->tablet_id(); context.partition_id = tablet->partition_id(); context.tablet_schema_hash = tablet->schema_hash(); context.rowset_type = BETA_ROWSET; context.rowset_path_prefix = tablet->schema_hash_path(); context.tablet_schema = &(tablet->tablet_schema()); context.rowset_state = VISIBLE; context.version = version; context.segments_overlap = NONOVERLAPPING; context.max_rows_per_segment = max_rows_per_segment; context.writer_type = (algorithm == VERTICAL_COMPACTION ? RowsetWriterType::kVertical : RowsetWriterType::kHorizontal); Status st = RowsetFactory::create_rowset_writer(context, output_rowset_writer); if (!st.ok()) { std::stringstream ss; ss << "Fail to create rowset writer. tablet_id=" << context.tablet_id << " err=" << st; LOG(WARNING) << ss.str(); return Status::InternalError(ss.str()); } return Status::OK(); } uint32_t CompactionUtils::get_segment_max_rows(int64_t max_segment_file_size, int64_t input_row_num, int64_t input_size) { // The range of config::max_segments_file_size is between [1, INT64_MAX] // If the configuration is set wrong, the config::max_segments_file_size will be a negtive value. // Using division instead multiplication can avoid the overflow int64_t max_segment_rows = max_segment_file_size / (input_size / (input_row_num + 1) + 1); if (max_segment_rows > INT32_MAX || max_segment_rows <= 0) { max_segment_rows = INT32_MAX; } return max_segment_rows; } void CompactionUtils::split_column_into_groups(size_t num_columns, size_t num_key_columns, int64_t max_columns_per_group, std::vector<std::vector<uint32_t>>* column_groups) { std::vector<uint32_t> key_columns; for (size_t i = 0; i < num_key_columns; ++i) { key_columns.emplace_back(i); } column_groups->emplace_back(std::move(key_columns)); for (size_t i = num_key_columns; i < num_columns; ++i) { if ((i - num_key_columns) % max_columns_per_group == 0) { column_groups->emplace_back(); } column_groups->back().emplace_back(i); } } CompactionAlgorithm CompactionUtils::choose_compaction_algorithm(size_t num_columns, int64_t max_columns_per_group, size_t source_num) { // if the number of columns in the schema is less than or equal to max_columns_per_group, use HORIZONTAL_COMPACTION. if (num_columns <= max_columns_per_group) { return HORIZONTAL_COMPACTION; } // if source_num is less than or equal to 1, heap merge iterator is not used in compaction, // and row source mask is not created. // if source_num is more than MAX_SOURCES, mask in RowSourceMask may overflow. if (source_num <= 1 || source_num > vectorized::RowSourceMask::MAX_SOURCES) { return HORIZONTAL_COMPACTION; } return VERTICAL_COMPACTION; } std::unique_ptr<CompactionPolicy> CompactionUtils::create_compaction_policy(CompactionContext* context) { // now only support BaseAndCumulativeCompactionPolicy return std::make_unique<BaseAndCumulativeCompactionPolicy>(context); } } // namespace starrocks
43.619835
120
0.684161
[ "vector" ]
02e45fac1e90ab8d4f6c650f520fa3233c7b5dbb
25,105
cpp
C++
src/low_module.cpp
kennell/lowjs
e71ad63d4a26ba0eb1ba453e27b114d4ce0e1413
[ "MIT" ]
null
null
null
src/low_module.cpp
kennell/lowjs
e71ad63d4a26ba0eb1ba453e27b114d4ce0e1413
[ "MIT" ]
null
null
null
src/low_module.cpp
kennell/lowjs
e71ad63d4a26ba0eb1ba453e27b114d4ce0e1413
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // low_module.cpp // ----------------------------------------------------------------------------- #include "low_module.h" #include "low_main.h" #include "low_system.h" #include "low_alloc.h" #include "low_config.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> // Global variables extern low_system_t g_low_system; extern duk_function_list_entry g_low_native_methods[]; #if LOW_ESP32_LWIP_SPECIALITIES extern duk_function_list_entry g_low_native_neon_methods[]; #endif /* LOW_ESP32_LWIP_SPECIALITIES */ // ----------------------------------------------------------------------------- // low_module_init // ----------------------------------------------------------------------------- void low_module_init(duk_context *ctx) { // Initialize internal require cache duk_push_global_stash(ctx); duk_push_object(ctx); duk_put_prop_string(ctx, -2, "modules"); duk_push_object(ctx); // Add native object, only resolvable from lib: duk_push_object(ctx); duk_push_object(ctx); duk_put_function_list(ctx, -1, g_low_native_methods); #if LOW_ESP32_LWIP_SPECIALITIES duk_put_function_list(ctx, -1, g_low_native_neon_methods); #endif /* LOW_ESP32_LWIP_SPECIALITIES */ duk_put_prop_string(ctx, -2, "exports"); duk_put_prop_string(ctx, -2, "lib:native"); duk_put_prop_string(ctx, -2, "lib_modules"); duk_pop(ctx); } // ----------------------------------------------------------------------------- // low_module_main // ----------------------------------------------------------------------------- void neonious_start_result(const char *code); static duk_ret_t low_module_main_safe(duk_context *ctx, void *udata) { char *path = (char *)udata; if(path) { char *res_id = (char *)duk_push_fixed_buffer(ctx, 1024); if(!low_module_resolve_c(path, ".", res_id)) { #if LOW_ESP32_LWIP_SPECIALITIES neonious_start_result("FILE_NOT_FOUND"); #endif /* LOW_ESP32_LWIP_SPECIALITIES */ duk_type_error(ctx, "cannot resolve module '%s'", path); return 1; } #if LOW_ESP32_LWIP_SPECIALITIES neonious_start_result(NULL); #endif /* LOW_ESP32_LWIP_SPECIALITIES */ low_module_run(ctx, res_id, LOW_MODULE_FLAG_MAIN); } else low_module_run(ctx, "lib:main", LOW_MODULE_FLAG_MAIN); return 0; } bool low_module_main(low_main_t *low, const char *path) { if(duk_safe_call(low->duk_ctx, low_module_main_safe, (void *)path, 0, 1) != DUK_EXEC_SUCCESS) { if(!low->duk_flag_stop) // flag stop also produces error low_duk_print_error(low->duk_ctx); duk_pop(low->duk_ctx); return low->duk_flag_stop; } duk_pop(low->duk_ctx); return true; } // ----------------------------------------------------------------------------- // low_module_run // ----------------------------------------------------------------------------- #if LOW_ESP32_LWIP_SPECIALITIES bool get_data_block(const char *path, unsigned char **data, int *len, bool showErr, bool escapeZero = false); #endif /* LOW_ESP32_LWIP_SPECIALITIES */ void low_module_run(duk_context *ctx, const char *path, int flags) { low_main_t *low = low_duk_get_low(ctx); unsigned char *data; int len; struct stat st; bool isLib = memcmp(path, "lib:", 4) == 0; #if LOW_ESP32_LWIP_SPECIALITIES char *txt; len = strlen(path); if(len > 1000) goto cantLoad; txt = (char *)low_alloc(1024); if(!txt) goto cantLoad; if(isLib) { sprintf(txt, "/lib/%s.low", path + 4); flags |= LOW_MODULE_FLAG_DUK_FORMAT; } /* else if(memcmp(path, "module:", 7) == 0) { for(len--; len >= 0; len--) if(path[len] == '.') break; if(path[len] == '.' && (path[len + 1] == 'j' || path[len + 1] == 'J') && (path[len + 2] == 's' || path[len + 2] == 'S') && (path[len + 3] == 'o' || path[len + 3] == 'O') && (path[len + 4] == 'n' || path[len + 4] == 'N')) { type |= MODULE_LOAD_JSON; strcpy(txt, "/fs/modules/"); memcpy(txt + 12, path + 7, len - 7 + 6); } else { type |= MODULE_LOAD_DUK_FORMAT; strcpy(txt, "/fs/modules/"); memcpy(txt + 12, path + 7, len - 7); strcpy(txt + 12 + len - 7, ".duk"); } } */ else if(path[0] == '/') sprintf(txt, "/fs/user/.build%s", path); else { low_free(txt); goto cantFind; } if(!get_data_block(txt, &data, &len, true)) { struct stat st; if(stat(txt, &st) == 0) { low_free(txt); goto cantLoad; } else { if(path[0] == '/') { sprintf(txt, "/fs/user%s", path); if(!get_data_block(txt, &data, &len, true)) { low_free(txt); struct stat st; if(stat(txt, &st) == 0) goto cantLoad; else goto cantFind; } } else { low_free(txt); goto cantFind; } } } low_free(txt); if(0) { cantFind: duk_type_error(ctx, "cannot find module '%s'", path); } #else int fd; if(isLib) { if(strlen(path) > 1000) goto cantLoad; char *txt = (char *)low_alloc(1024); if(!txt) goto cantLoad; sprintf(txt, "%s%s.low", g_low_system.lib_path, path + 4); flags |= LOW_MODULE_FLAG_DUK_FORMAT; fd = open(txt, O_RDONLY); low_free(txt); } else fd = open(path, O_RDONLY); if(fd < 0) duk_type_error(ctx, "cannot find module '%s'", path); if(fstat(fd, &st) < 0) { close(fd); goto cantLoad; } len = st.st_size; // TODO: use buffer object so we no longer have a memory // leak! data = (unsigned char *)low_alloc(len); if(!data) { close(fd); goto cantLoad; } if(read(fd, data, len) != len) { low_free(data); close(fd); goto cantLoad; } close(fd); #endif /* LOW_ESP32_LWIP_SPECIALITIES */ duk_push_object(ctx); // our new module! if(flags & LOW_MODULE_FLAG_MAIN) { duk_dup(ctx, -1); duk_put_prop_string(ctx, -2, "main"); } else if(!(flags & LOW_MODULE_FLAG_GLOBAL)) { duk_get_prop_string(ctx, -2, "main"); duk_put_prop_string(ctx, -2, "main"); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "parent"); } duk_push_string(ctx, path); duk_dup(ctx, -1); duk_put_prop_string(ctx, -3, "filename"); duk_put_prop_string(ctx, -2, "id"); if(!(flags & LOW_MODULE_FLAG_JSON)) { if(flags & LOW_MODULE_FLAG_GLOBAL) duk_push_global_object(ctx); else duk_push_object(ctx); duk_put_prop_string(ctx, -2, "exports"); } duk_push_false(ctx); duk_put_prop_string(ctx, -2, "loaded"); // Not supported yet // duk_push_array(ctx); // duk_put_prop_string(ctx, -2, "paths"); duk_push_array(ctx); duk_put_prop_string(ctx, -2, "children"); duk_push_object(ctx); duk_put_prop_string(ctx, -2, "\xff" "childrenMap"); // [... module] // require function duk_push_c_function(ctx, low_module_require, 1); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "\xff" "module"); duk_push_string(ctx, "name"); duk_push_string(ctx, "require"); // this is used in call stack duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "module"); // [... module require] // require.cache duk_push_global_stash(low->stash_ctx); if(low->stash_ctx != ctx) duk_xmove_top(ctx, low->stash_ctx, 1); duk_get_prop_string(ctx, -1, "modules"); duk_put_prop_string(ctx, -3, "cache"); duk_pop(ctx); // require.resolve duk_push_c_function(ctx, low_module_resolve, 1); duk_dup(ctx, -3); duk_put_prop_string(ctx, -2, "\xff" "module"); duk_push_string(ctx, "name"); duk_push_string(ctx, "resolve"); // this is used in call stack duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); duk_put_prop_string(ctx, -2, "resolve"); // require.main duk_get_prop_string(ctx, -2, "main"); duk_put_prop_string(ctx, -2, "main"); if(!isLib && !(flags & LOW_MODULE_FLAG_JSON)) // security problem duk_put_prop_string(ctx, -2, "require"); // [... module [require]] if(!(flags & LOW_MODULE_FLAG_GLOBAL)) { // Cache module duk_push_global_stash(low->stash_ctx); if(low->stash_ctx != ctx) duk_xmove_top(ctx, low->stash_ctx, 1); duk_get_prop_string( ctx, -1, memcmp(path, "lib:", 4) == 0 ? "lib_modules" : "modules"); duk_dup(ctx, !isLib && !(flags & LOW_MODULE_FLAG_JSON) ? -3 : -4); duk_put_prop_string(ctx, -2, path); duk_pop_2(ctx); } if(flags & LOW_MODULE_FLAG_JSON) { duk_push_lstring(ctx, (char *)data, len); low_free(data); duk_json_decode(ctx, -1); /* [ ... module exports ] */ duk_put_prop_string(ctx, -2, "exports"); } else { if(flags & LOW_MODULE_FLAG_DUK_FORMAT) { memcpy(duk_push_fixed_buffer(ctx, len), data, len); // TODO: remove copy low_free(data); duk_load_function(ctx); } else { // TODO: remove concat bool shebang = len >= 2 && data[0] == '#' && data[1] == '!'; duk_push_string( ctx, shebang ? "function(exports,require,module,__filename,__dirname){//" : "function(exports,require,module,__filename,__dirname){"); duk_push_lstring(ctx, (char *)data, len); low_free(data); duk_push_string(ctx, "\n}"); /* Newline allows module last line to contain a // comment. */ duk_concat(ctx, 3); duk_push_string(ctx, path); duk_compile(ctx, DUK_COMPILE_FUNCTION); } /* [ ... module [require] func ] */ /* call the function wrapper */ duk_get_prop_string(ctx, isLib ? -3 : -2, "exports"); /* exports */ if(isLib) { duk_dup(ctx, -3); /* require */ duk_remove(ctx, -4); } else duk_get_prop_string(ctx, -3, "require"); /* require */ duk_dup(ctx, -4); /* module */ duk_push_string(ctx, path); /* __filename */ for(len = strlen(path) - 1; len > 0; len--) if(path[len] == '/') break; duk_push_lstring(ctx, path, len); /* __dirname */ duk_call(ctx, 5); /* [ ... module result ] */ duk_pop(ctx); } /* module.loaded = true */ duk_push_true(ctx); duk_put_prop_string(ctx, -2, "loaded"); return; cantLoad: duk_type_error(ctx, "cannot read module '%s' into memory", path); } // ----------------------------------------------------------------------------- // low_module_require - returns cached module or loads it // ----------------------------------------------------------------------------- duk_ret_t low_module_require(duk_context *ctx) { char *res_id = (char *)duk_push_fixed_buffer(ctx, 1024); const char *id = duk_require_string(ctx, 0); // Get parent ID duk_push_current_function(ctx); duk_get_prop_string(ctx, -1, "\xff" "module"); duk_remove(ctx, -2); duk_get_prop_string(ctx, -1, "id"); const char *parent_id = duk_get_string(ctx, -1); duk_pop(ctx); // We always resolve with our own function if(!low_module_resolve_c(id, parent_id, res_id)) { duk_type_error(ctx, "cannot resolve module '%s', parent '%s'", id, parent_id); return 1; } // Try to find in cache low_main_t *low = low_duk_get_low(ctx); duk_push_global_stash(low->stash_ctx); if(low->stash_ctx != ctx) duk_xmove_top(ctx, low->stash_ctx, 1); duk_get_prop_string( ctx, -1, memcmp(res_id, "lib:", 4) == 0 ? "lib_modules" : "modules"); if(duk_get_prop_string(ctx, -1, res_id)) { duk_remove(ctx, -2); duk_remove(ctx, -2); } else { duk_pop_3(ctx); // [ id parent ] low_module_run(ctx, res_id, 0); } // [ id parent module ] if(memcmp(parent_id, "lib:", 4) != 0) // security check { duk_get_prop_string(ctx, -2, "\xff" "childrenMap"); if(duk_get_prop_string(ctx, -1, res_id)) duk_pop_2(ctx); else { duk_push_boolean(ctx, true); duk_put_prop_string(ctx, -3, res_id); duk_pop_2(ctx); // Add to children duk_get_prop_string(ctx, -2, "children"); duk_get_prop_string(ctx, -1, "length"); duk_dup(ctx, -3); duk_put_prop(ctx, -3); duk_pop(ctx); } } duk_get_prop_string(ctx, -1, "exports"); return 1; } // ----------------------------------------------------------------------------- // low_module_resolve - resolves path to module // ----------------------------------------------------------------------------- duk_ret_t low_module_resolve(duk_context *ctx) { char *res_id = (char *)duk_push_fixed_buffer(ctx, 1024); const char *id = duk_require_string(ctx, 0); // Get parent ID duk_push_current_function(ctx); duk_get_prop_string(ctx, -1, "\xff" "module"); duk_remove(ctx, -2); duk_get_prop_string(ctx, -1, "id"); const char *parent_id = duk_get_string(ctx, -1); duk_pop_2(ctx); if(low_module_resolve_c(id, parent_id, res_id)) { duk_push_string(ctx, res_id); return 1; } else { duk_type_error(ctx, "cannot resolve module '%s', parent '%s'", id, parent_id); return 1; } } // ----------------------------------------------------------------------------- // low_module_make // ----------------------------------------------------------------------------- duk_ret_t low_module_make(duk_context *ctx) { duk_push_object(ctx); // our new module! duk_get_prop_string(ctx, -2, "main"); duk_put_prop_string(ctx, -2, "main"); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "parent"); duk_dup(ctx, 0); duk_dup(ctx, -1); duk_put_prop_string(ctx, -3, "filename"); duk_put_prop_string(ctx, -2, "id"); duk_push_object(ctx); duk_put_prop_string(ctx, -2, "exports"); duk_push_false(ctx); duk_put_prop_string(ctx, -2, "loaded"); // Not supported yet // duk_push_array(ctx); // duk_put_prop_string(ctx, -2, "paths"); duk_push_array(ctx); duk_put_prop_string(ctx, -2, "children"); duk_push_object(ctx); duk_put_prop_string(ctx, -2, "\xff" "childrenMap"); // [... module] // require function duk_push_c_function(ctx, low_module_require, 1); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "\xff" "module"); duk_push_string(ctx, "name"); duk_push_string(ctx, "require"); // this is used in call stack duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "module"); // [... module require] // require.cache low_main_t *low = low_duk_get_low(ctx); duk_push_global_stash(low->stash_ctx); if(low->stash_ctx != ctx) duk_xmove_top(ctx, low->stash_ctx, 1); duk_get_prop_string(ctx, -1, "modules"); duk_put_prop_string(ctx, -3, "cache"); duk_pop(ctx); // require.resolve duk_push_c_function(ctx, low_module_resolve, 2); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "\xff" "module"); duk_push_string(ctx, "name"); duk_push_string(ctx, "resolve"); // this is used in call stack duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); duk_put_prop_string(ctx, -2, "resolve"); // require.main duk_get_prop_string(ctx, -2, "main"); duk_put_prop_string(ctx, -2, "main"); duk_put_prop_string(ctx, -2, "require"); // [... module] /* module.loaded = true */ duk_push_true(ctx); duk_put_prop_string(ctx, -2, "loaded"); return 1; } // ----------------------------------------------------------------------------- // low_module_resolve_c - the C version of our resolve function // result must be min 1024 bytes // ----------------------------------------------------------------------------- bool low_module_resolve_c(const char *module_id, const char *parent_id, char *res_id) { struct stat st; // lib: may get native if(strcmp(module_id, "native") == 0 && (memcmp(parent_id, "lib:", 4) == 0 || memcmp(parent_id, "module:", 7) == 0)) { strcpy(res_id, "lib:native"); return true; } bool is_not_absolute_path = false; int i; for(i = 0; module_id[i]; i++) if(module_id[i] == '.') { is_not_absolute_path = true; break; } if(!is_not_absolute_path && i < 1000 && strcmp(module_id, "init") != 0 && strcmp(module_id, "main") != 0) { // system module sprintf(res_id, "%s%s.low", g_low_system.lib_path, module_id); if(stat(res_id, &st) == 0) { sprintf(res_id, "lib:%s", module_id); return true; } /* // package manager module sprintf(res_id, "/fs/modules/%s/index.low", module_id); if (stat(res_id, &st) == 0) { sprintf(res_id, "module:%s/index.js", module_id); return true; } sprintf(res_id, "/fs/modules/%s.low", module_id); if (stat(res_id, &st) == 0) { sprintf(res_id, "module:%s.js", module_id); return true; } */ } if(memcmp(parent_id, "lib:", 4) == 0) return false; char *start, *path; bool isModule; #if LOW_ESP32_LWIP_SPECIALITIES if(memcmp(parent_id, "module:", 7) == 0 && module_id[0] != '/') { strcpy(res_id, "/fs/modules/"); path = start = res_id + 12; parent_id += 7; isModule = true; } else { strcpy(res_id, "/fs/user/"); start = res_id + 8; path = res_id + 9; isModule = false; } #else path = start = res_id; isModule = false; #endif /* LOW_ESP32_LWIP_SPECIALITIES */ path[0] = 0; if(module_id[0] != '/') { for(const char *parent_path = parent_id; *parent_path; parent_path++) { if(path != start) { if(path[-1] == '/' && parent_path[0] == '/') continue; else if(path[-1] == '/' && parent_path[0] == '.' && (!parent_path[1] || parent_path[1] == '/')) { parent_path++; if(!*parent_path) break; continue; } else if(path[-1] == '/' && parent_path[0] == '.' && parent_path[1] == '.' && (!parent_path[2] || parent_path[2] == '/') #if !LOW_ESP32_LWIP_SPECIALITIES && !(path - start > 2 && path[-2] == '.' && path[-3] == '.' && (path - start == 3 || path[-4] == '/')) #endif /* LOW_ESP32_LWIP_SPECIALITIES */ ) { path--; while(path != start && path[-1] != '/') path--; #if LOW_ESP32_LWIP_SPECIALITIES if(path == start) return false; #endif /* LOW_ESP32_LWIP_SPECIALITIES */ parent_path += 2; if(!*parent_path) break; } else *path++ = *parent_path; } else *path++ = *parent_path; if(path - res_id == 1024) return false; } while(path != start && path[-1] != '/') path--; #if LOW_ESP32_LWIP_SPECIALITIES if(path == start) return false; #endif /* LOW_ESP32_LWIP_SPECIALITIES */ } for(const char *module_path = module_id; *module_path; module_path++) { if(path != start) { if(path[-1] == '/' && module_path[0] == '/') continue; else if(path[-1] == '/' && module_path[0] == '.' && (!module_path[1] || module_path[1] == '/')) { module_path++; if(!*module_path) break; continue; } else if(path[-1] == '/' && module_path[0] == '.' && module_path[1] == '.' && (!module_path[2] || module_path[2] == '/') #if !LOW_ESP32_LWIP_SPECIALITIES && !(path - start > 2 && path[-2] == '.' && path[-3] == '.' && (path - start == 3 || path[-4] == '/')) #endif /* LOW_ESP32_LWIP_SPECIALITIES */ ) { path--; while(path != start && path[-1] != '/') path--; #if LOW_ESP32_LWIP_SPECIALITIES if(path == start) return false; #endif /* LOW_ESP32_LWIP_SPECIALITIES */ module_path += 2; if(!*module_path) break; } else *path++ = *module_path; } else *path++ = *module_path; if(path - res_id == 1024) return false; } bool isFolder = path[-1] == '/'; if(isFolder) path--; if(path[-3] == '.' && (path[-2] == 'j' || path[-2] == 'J') && (path[-1] == 's' || path[-1] == 'S')) path -= 3; if(isModule) { if(!isFolder) { if(path + 4 - res_id >= 1024) return false; strcpy(path, ".low"); if(stat(res_id, &st) == 0) { strcpy(path, ".js"); memmove(res_id + 7, start, path + 4 - start); memcpy(res_id, "module:", 7); return true; } } if(path + 10 - res_id >= 1024) return false; strcpy(path, "/index.low"); if(stat(res_id, &st) == 0) { strcpy(path, "/index.js"); memmove(res_id + 7, start, path + 10 - start); memcpy(res_id, "module:", 7); return true; } if(!isFolder) { // For example JSON if(path - res_id >= 1024) return false; path[0] = '\0'; if(stat(res_id, &st) == 0) { memmove(res_id + 7, start, path + 1 - start); memcpy(res_id, "module:", 7); return true; } } } else { if(!isFolder) { if(path + 3 - res_id >= 1024) return false; strcpy(path, ".js"); if(stat(res_id, &st) == 0) { memmove(res_id, start, path + 4 - start); return true; } } if(path + 9 - res_id >= 1024) return false; strcpy(path, "/index.js"); if(stat(res_id, &st) == 0) { memmove(res_id, start, path + 10 - start); return true; } if(!isFolder) { // For example JSON if(path - res_id >= 1024) return false; path[0] = '\0'; if(stat(res_id, &st) == 0) { memmove(res_id, start, path + 1 - start); return true; } } } return false; }
27.771018
80
0.476041
[ "object" ]
02e512d9725a7f8d27e2f08756f41d50abc1f091
3,642
cpp
C++
Pack/app.cpp
Kerndog73/Simpleton-Engine
ab1905f805d1e1c951d96775d0d6646a3548b4ce
[ "MIT" ]
52
2017-08-12T14:41:58.000Z
2022-01-12T01:18:57.000Z
Pack/app.cpp
Kerndog73/Simpleton-Engine
ab1905f805d1e1c951d96775d0d6646a3548b4ce
[ "MIT" ]
null
null
null
Pack/app.cpp
Kerndog73/Simpleton-Engine
ab1905f805d1e1c951d96775d0d6646a3548b4ce
[ "MIT" ]
5
2018-11-20T04:02:15.000Z
2020-03-02T19:15:16.000Z
// // app.cpp // Pack // // Created by Indi Kernick on 24/2/18. // Copyright © 2018 Indi Kernick. All rights reserved. // #include "app.hpp" #include <iostream> #include "search dir.hpp" #include "sort by frame.hpp" #include "load images.hpp" #include "rects from images.hpp" #include "pack rects.hpp" #include "blit images.hpp" #include "write atlas.hpp" #include "write image.hpp" #include <Simpleton/Graphics 2D/write surface.hpp> #include <Simpleton/Utils/profiler.hpp> void printUsage() { std::cout << R"(pack [in=<in>] [out=<out>] [sep=<sep>] [white=<white>] [rec=<rec>] [bpp=<bpp>] in Input directory to search for images [default=.] out Output file name without extension [default=sprites] sep Number of pixels separating each image [default=1] white Radius of the whitepixel [default=0] rec Maximum recursive search depth [default=1] bpp Bytes Per Pixel. Valid values are [1, 2, 3, 4] [default=4] )"; } unsigned long parseInt(const char *str) { // std::from_chars should have been in C++ 20 years ago // I'M STILL WAITING char *end; const unsigned long n = std::strtoul(str, &end, 10); if (n == 0 && end[-1] != '0') { throw std::runtime_error("Invalid integer"); } return n; } void runApp(int argc, const char **argv) { PROFILE(runApp); std::string in = "."; std::string out = "sprites"; stbrp_coord sep = 1; stbrp_coord white = 0; size_t rec = 1; int bpp = 4; const char **const end = argv + argc; for (; argv != end; ++argv) { if (std::strncmp(*argv, "in", 2) == 0) { if (argv[0][2] != '=' || argv[0][3] == 0) { throw ArgError(); } in.clear(); in.append(argv[0] + 3); } else if (std::strncmp(*argv, "out", 3) == 0) { if (argv[0][3] != '=' || argv[0][4] == 0) { throw ArgError(); } out.clear(); out.append(argv[0] + 4); } else if (std::strncmp(*argv, "sep", 3) == 0) { if (argv[0][3] != '=' || argv[0][4] == 0) { throw ArgError(); } sep = static_cast<stbrp_coord>(parseInt(argv[0] + 4)); } else if (std::strncmp(*argv, "white", 5) == 0) { if (argv[0][5] != '=' || argv[0][6] == 0) { throw ArgError(); } white = static_cast<stbrp_coord>(parseInt(argv[0] + 6)); } else if (std::strncmp(*argv, "rec", 3) == 0) { if (argv[0][3] != '=' || argv[0][4] == 0) { throw ArgError(); } rec = static_cast<size_t>(parseInt(argv[0] + 4)); } else if (std::strncmp(*argv, "bpp", 3) == 0) { if (argv[0][3] != '=' || argv[0][4] == 0) { throw ArgError(); } bpp = static_cast<int>(parseInt(argv[0] + 4)); if (bpp < 1 || bpp > 4) { throw std::runtime_error("Invalid bpp. Valid values are [1, 2, 3, 4]"); } } else { throw ArgError(); } } std::remove((out + ".png").c_str()); std::vector<std::string> paths = findFiles(in, extIsImage, rec); sortByFrame(paths); std::vector<G2D::Surface> images = loadImages(paths, bpp); if (white) { const stbrp_coord size = 1 + white * 2; images.emplace_back( size, size, images.empty() ? 4 : images.front().bytesPerPixel(), 255 ); paths.emplace_back("__WHITEPIXEL__.png"); } std::vector<stbrp_rect> rects = rectsFromImages(images, sep); const stbrp_coord length = packRects(rects); writeImage(out + ".png", blitImages(images, rects, length)); writeAtlas(out + ".atlas", paths, rects, length, sep); }
30.099174
81
0.548051
[ "vector" ]
02e5cd38e1d6c1deb5fb747615f1e5890e0c24d2
99,194
cpp
C++
Source/Rendering/DirectX/vaDirectXTools.cpp
rohankumardubey/XeGTAO
e7698f874e90f2516fca26c696ec3cd2c70e505a
[ "MIT" ]
1
2022-01-15T00:40:59.000Z
2022-01-15T00:40:59.000Z
Source/Rendering/DirectX/vaDirectXTools.cpp
rohankumardubey/XeGTAO
e7698f874e90f2516fca26c696ec3cd2c70e505a
[ "MIT" ]
null
null
null
Source/Rendering/DirectX/vaDirectXTools.cpp
rohankumardubey/XeGTAO
e7698f874e90f2516fca26c696ec3cd2c70e505a
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2016-2021, Intel Corporation // // SPDX-License-Identifier: MIT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@intel.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "vaDirectXTools.h" //#include "DirectX\vaDirectXCanvas.h" #include "IntegratedExternals/DirectXTex/DDSTextureLoader/DDSTextureLoader.h" #include "IntegratedExternals/DirectXTex/WICTextureLoader/WICTextureLoader.h" #include "IntegratedExternals/DirectXTex/DDSTextureLoader/DDSTextureLoader12.h" #include "IntegratedExternals/DirectXTex/WICTextureLoader/WICTextureLoader12.h" #include "IntegratedExternals/DirectXTex/DirectXTex/DirectXTex.h" //#include "DirectXTex\DirectXTex.h" #include "Rendering/Shaders/vaSharedTypes.h" #include "Rendering/DirectX/vaRenderDeviceDX12.h" #include "Rendering/DirectX/vaRenderDeviceContextDX12.h" #include "Rendering/DirectX/vaShaderDX12.h" #include "Rendering/DirectX/vaRenderMaterialDX12.h" #include "Rendering/Shaders/vaRaytracingShared.h" #include "Core/System/vaFileTools.h" #include <stdarg.h> #include <dxgiformat.h> #include <assert.h> #include <memory> #include <algorithm> #include "Core/Misc/vaXXHash.h" //#include <iostream> #include <iomanip> #include <sstream> #pragma warning (default : 4995) #pragma warning ( disable : 4238 ) // warning C4238: nonstandard extension used: class rvalue used as lvalue using namespace std; using namespace Vanilla; template<typename T> struct AnyStructComparer { bool operator()( const T & Left, const T & Right ) const { // comparison logic goes here return memcmp( &Left, &Right, sizeof( Right ) ) < 0; } }; //////////////////////////////////////////////////////////////////////////////// bool vaDirectXTools12::SaveDDSTexture( Vanilla::vaStream& outStream, _In_ ID3D12CommandQueue* pCommandQueue, _In_ ID3D12Resource* pSource, _In_ bool isCubeMap, _In_ D3D12_RESOURCE_STATES beforeState, _In_ D3D12_RESOURCE_STATES afterState ) { DirectX::ScratchImage scratchImage; HRESULT hr = DirectX::CaptureTexture( pCommandQueue, pSource, isCubeMap, scratchImage, beforeState, afterState ); if( FAILED( hr ) ) { assert( false ); return false; } DirectX::Blob blob; hr = DirectX::SaveToDDSMemory( scratchImage.GetImages( ), scratchImage.GetImageCount( ), scratchImage.GetMetadata( ), DirectX::DDS_FLAGS_NONE, blob ); if( FAILED( hr ) ) { assert( false ); return false; } return outStream.Write( blob.GetBufferPointer( ), blob.GetBufferSize( ) ); } bool vaDirectXTools12::FillShaderResourceViewDesc( D3D12_SHADER_RESOURCE_VIEW_DESC & outDesc, ID3D12Resource * resource, DXGI_FORMAT format, int mipSliceMin, int mipSliceCount, int arraySliceMin, int arraySliceCount, bool isCubemap ) { assert( mipSliceMin >= 0 ); assert( arraySliceMin >= 0 ); assert( arraySliceCount >= -1 ); // -1 means all D3D12_RESOURCE_DESC resourceDesc = resource->GetDesc(); outDesc.Format = (format == DXGI_FORMAT_UNKNOWN)?(resourceDesc.Format):(format); outDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ) { if( !isCubemap ) { if( mipSliceCount == -1 ) mipSliceCount = resourceDesc.MipLevels-mipSliceMin; if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize-arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( mipSliceMin+mipSliceCount > 0 && (UINT)mipSliceMin+mipSliceCount <= resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin+arraySliceCount > 0 && (UINT)arraySliceMin+arraySliceCount <= resourceDesc.DepthOrArraySize ); if( resourceDesc.SampleDesc.Count > 1 ) outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_SRV_DIMENSION_TEXTURE2DMS ) : ( D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY ); else outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_SRV_DIMENSION_TEXTURE2D ) : ( D3D12_SRV_DIMENSION_TEXTURE2DARRAY ); if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D ) { outDesc.Texture2D.MostDetailedMip = mipSliceMin; outDesc.Texture2D.MipLevels = mipSliceCount; outDesc.Texture2D.PlaneSlice = 0; outDesc.Texture2D.ResourceMinLODClamp = 0.0f; assert( arraySliceMin == 0 ); assert( arraySliceCount == 1 ); } else if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY ) { outDesc.Texture2DArray.MostDetailedMip = mipSliceMin; outDesc.Texture2DArray.MipLevels = mipSliceCount; outDesc.Texture2DArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DArray.ArraySize = arraySliceCount; outDesc.Texture2DArray.PlaneSlice = 0; outDesc.Texture2DArray.ResourceMinLODClamp = 0.0f; } else if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS ) { outDesc.Texture2DMS.UnusedField_NothingToDefine = 42; assert( mipSliceMin == 0 ); assert( mipSliceCount == 1 ); assert( arraySliceMin == 0 ); assert( arraySliceCount == 1 ); } else if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY ) { assert( mipSliceMin == 0 ); assert( arraySliceCount == 1 ); outDesc.Texture2DMSArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DMSArray.ArraySize = arraySliceCount; } else { assert( false ); } } else // is a cubemap { if( mipSliceCount == -1 ) mipSliceCount = resourceDesc.MipLevels - mipSliceMin; if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( mipSliceMin + mipSliceCount > 0 && (UINT)mipSliceMin + mipSliceCount <= resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); outDesc.ViewDimension = (resourceDesc.DepthOrArraySize==6)?(D3D12_SRV_DIMENSION_TEXTURECUBE):(D3D12_SRV_DIMENSION_TEXTURECUBEARRAY); assert( resourceDesc.DepthOrArraySize % 6 == 0 ); if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE ) { outDesc.TextureCube.MostDetailedMip = mipSliceMin; outDesc.TextureCube.MipLevels = mipSliceCount; outDesc.TextureCube.ResourceMinLODClamp = 0.0f; assert( arraySliceMin == 0 ); assert( arraySliceCount == 6 ); } else if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY ) { outDesc.TextureCubeArray.MostDetailedMip = mipSliceMin; outDesc.TextureCubeArray.MipLevels = mipSliceCount; outDesc.TextureCubeArray.First2DArrayFace = arraySliceMin/6; outDesc.TextureCubeArray.NumCubes = arraySliceCount/6; outDesc.TextureCubeArray.ResourceMinLODClamp= 0.0f; } else { assert(false); } } return true; } else if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ) { assert( !isCubemap ); // can't be 3D cubemap if( mipSliceCount == -1 ) mipSliceCount = resourceDesc.MipLevels - mipSliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( mipSliceMin + mipSliceCount > 0 && (UINT)mipSliceMin + mipSliceCount <= resourceDesc.MipLevels ); // no array slices for 3D textures assert( arraySliceMin == 0 ); assert( arraySliceCount == resourceDesc.DepthOrArraySize ); outDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; outDesc.Texture3D.MostDetailedMip = mipSliceMin; outDesc.Texture3D.MipLevels = mipSliceCount; outDesc.Texture3D.ResourceMinLODClamp = 0.0f; return true; } else if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ) { assert( !isCubemap ); // can't be 1D cubemap if( mipSliceCount == -1 ) mipSliceCount = resourceDesc.MipLevels - mipSliceMin; if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( mipSliceMin + mipSliceCount > 0 && (UINT)mipSliceMin + mipSliceCount <= resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_SRV_DIMENSION_TEXTURE1D ) : ( D3D12_SRV_DIMENSION_TEXTURE1DARRAY ); if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D ) { outDesc.Texture1D.MostDetailedMip = mipSliceMin; outDesc.Texture1D.MipLevels = mipSliceCount; outDesc.Texture1D.ResourceMinLODClamp = 0.0f; } else if( outDesc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1DARRAY ) { outDesc.Texture1DArray.MostDetailedMip = mipSliceMin; outDesc.Texture1DArray.MipLevels = mipSliceCount; outDesc.Texture1DArray.FirstArraySlice = arraySliceMin; outDesc.Texture1DArray.ArraySize = arraySliceCount; outDesc.Texture1DArray.ResourceMinLODClamp = 0.0f; } else { assert( false ); } return true; } else if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ) { assert( false ); // not intended for buffers return false; //outDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; //outDesc.Buffer. } else { assert( false ); // resource not recognized; additional code might be needed above return false; } } bool vaDirectXTools12::FillDepthStencilViewDesc( D3D12_DEPTH_STENCIL_VIEW_DESC & outDesc, ID3D12Resource * resource, DXGI_FORMAT format, int mipSliceMin, int arraySliceMin, int arraySliceCount ) { assert( mipSliceMin >= 0 ); assert( arraySliceMin >= 0 ); assert( arraySliceCount >= -1 ); // -1 means all D3D12_RESOURCE_DESC resourceDesc = resource->GetDesc(); outDesc.Format = (format == DXGI_FORMAT_UNKNOWN)?(resourceDesc.Format):(format); outDesc.Flags = D3D12_DSV_FLAG_NONE; // D3D12_DSV_FLAG_READ_ONLY_DEPTH / D3D12_DSV_FLAG_READ_ONLY_STENCIL if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ) { if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); if( resourceDesc.SampleDesc.Count > 1 ) outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_DSV_DIMENSION_TEXTURE2DMS ) : ( D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY ); else outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_DSV_DIMENSION_TEXTURE2D ) : ( D3D12_DSV_DIMENSION_TEXTURE2DARRAY ); if( outDesc.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2D ) { outDesc.Texture2D.MipSlice = mipSliceMin; assert( arraySliceMin == 0 ); } else if( outDesc.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DARRAY ) { outDesc.Texture2DArray.MipSlice = mipSliceMin; outDesc.Texture2DArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DArray.ArraySize = arraySliceCount; } else if( outDesc.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMS ) { outDesc.Texture2DMS.UnusedField_NothingToDefine = 42; assert( mipSliceMin == 0 ); assert( arraySliceMin == 0 ); } else if( outDesc.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY ) { outDesc.Texture2DMSArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DMSArray.ArraySize = arraySliceCount; assert( mipSliceMin == 0 ); } else { assert( false ); return false; } return true; } assert( false ); // not implemented / supported return false; } bool vaDirectXTools12::FillRenderTargetViewDesc( D3D12_RENDER_TARGET_VIEW_DESC & outDesc, ID3D12Resource * resource, DXGI_FORMAT format, int mipSliceMin, int arraySliceMin, int arraySliceCount ) { assert( mipSliceMin >= 0 ); assert( arraySliceMin >= 0 ); assert( arraySliceCount >= -1 ); // -1 means all D3D12_RESOURCE_DESC resourceDesc = resource->GetDesc(); outDesc.Format = (format == DXGI_FORMAT_UNKNOWN)?(resourceDesc.Format):(format); if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ) { if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); if( resourceDesc.SampleDesc.Count > 1 ) outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_RTV_DIMENSION_TEXTURE2DMS ) : ( D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY ); else outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_RTV_DIMENSION_TEXTURE2D ) : ( D3D12_RTV_DIMENSION_TEXTURE2DARRAY ); if( outDesc.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D ) { outDesc.Texture2D.MipSlice = mipSliceMin; outDesc.Texture2D.PlaneSlice = 0; assert( arraySliceMin == 0 ); } else if( outDesc.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY ) { outDesc.Texture2DArray.MipSlice = mipSliceMin; outDesc.Texture2DArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DArray.ArraySize = arraySliceCount; outDesc.Texture2DArray.PlaneSlice = 0; } else if( outDesc.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS ) { outDesc.Texture2DMS.UnusedField_NothingToDefine = 42; assert( mipSliceMin == 0 ); assert( arraySliceMin == 0 ); } else if( outDesc.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY ) { outDesc.Texture2DMSArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DMSArray.ArraySize = arraySliceCount; assert( mipSliceMin == 0 ); } else { assert( false ); return false; } return true; } assert( false ); // not implemented / supported return false; } bool vaDirectXTools12::FillUnorderedAccessViewDesc( D3D12_UNORDERED_ACCESS_VIEW_DESC & outDesc, ID3D12Resource * resource, DXGI_FORMAT format, int mipSliceMin, int arraySliceMin, int arraySliceCount ) { assert( mipSliceMin >= 0 ); assert( arraySliceMin >= 0 ); assert( arraySliceCount >= -1 ); // -1 means all D3D12_RESOURCE_DESC resourceDesc = resource->GetDesc(); outDesc.Format = (format == DXGI_FORMAT_UNKNOWN)?(resourceDesc.Format):(format); if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ) { if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_UAV_DIMENSION_TEXTURE2D ) : ( D3D12_UAV_DIMENSION_TEXTURE2DARRAY ); if( outDesc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D ) { outDesc.Texture2D.MipSlice = mipSliceMin; outDesc.Texture2D.PlaneSlice = 0; assert( arraySliceMin == 0 ); } else if( outDesc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY ) { outDesc.Texture2DArray.MipSlice = mipSliceMin; outDesc.Texture2DArray.FirstArraySlice = arraySliceMin; outDesc.Texture2DArray.ArraySize = arraySliceCount; outDesc.Texture2DArray.PlaneSlice = 0; } else { assert( false ); } return true; } else if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ) { if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); outDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; outDesc.Texture3D.MipSlice = mipSliceMin; outDesc.Texture3D.FirstWSlice = arraySliceMin; outDesc.Texture3D.WSize = arraySliceCount; return true; } else if( resourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ) { if( arraySliceCount == -1 ) arraySliceCount = resourceDesc.DepthOrArraySize - arraySliceMin; assert( mipSliceMin >= 0 && (UINT)mipSliceMin < resourceDesc.MipLevels ); assert( arraySliceMin >= 0 && (UINT)arraySliceMin < resourceDesc.DepthOrArraySize ); assert( arraySliceMin + arraySliceCount > 0 && (UINT)arraySliceMin + arraySliceCount <= resourceDesc.DepthOrArraySize ); outDesc.ViewDimension = ( resourceDesc.DepthOrArraySize == 1 ) ? ( D3D12_UAV_DIMENSION_TEXTURE1D ) : ( D3D12_UAV_DIMENSION_TEXTURE1DARRAY ); if( outDesc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE1D ) { outDesc.Texture1D.MipSlice = mipSliceMin; } else if( outDesc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE1DARRAY ) { outDesc.Texture1DArray.MipSlice = mipSliceMin; outDesc.Texture1DArray.FirstArraySlice = arraySliceMin; outDesc.Texture1DArray.ArraySize = arraySliceCount; } else { assert( false ); return false; } return true; } assert( false ); // resource not recognized; additional code might be needed above return false; } //////////////////////////////////////////////////////////////////////////////// void vaResourceStateTransitionHelperDX12::RSTHTransitionSubResUnroll( vaRenderDeviceContextBaseDX12 & context ) { // unroll all subres transitions because they are evil for( auto subRes : m_rsthSubResStates ) { if( subRes.second != m_rsthCurrent ) context.GetCommandList( )->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition( m_rsthResource.Get(), subRes.second, m_rsthCurrent, subRes.first ) ); } m_rsthSubResStates.clear(); } bool vaResourceStateTransitionHelperDX12::IsRSTHTransitionRequired( vaRenderDeviceContextBaseDX12 & context, D3D12_RESOURCE_STATES target, uint32 subResIndex ) { context; if( subResIndex == -1 ) return (m_rsthSubResStates.size() > 0) || (m_rsthCurrent != target); else { for( auto subRes : m_rsthSubResStates ) if( subRes.first == subResIndex && subRes.second == target ) return false; return true; } } void vaResourceStateTransitionHelperDX12::RSTHTransition( vaRenderDeviceContextBaseDX12 & context, D3D12_RESOURCE_STATES target, uint32 subResIndex ) { assert( context.GetRenderDevice().IsRenderThread() ); assert( AsDX12( context.GetRenderDevice() ).GetMainContext() == &context ); // we must be the main context for now assert( !context.IsWorker() ); assert( m_rsthResource != nullptr ); if( subResIndex != -1 ) { RSTHTransitionSubRes( context, target, subResIndex ); return; } if( m_rsthSubResStates.size() > 0 ) RSTHTransitionSubResUnroll( context ); if( m_rsthCurrent == target ) return; auto trans = CD3DX12_RESOURCE_BARRIER::Transition( m_rsthResource.Get(), m_rsthCurrent, target ); context.GetCommandList( )->ResourceBarrier(1, &trans ); m_rsthCurrent = target; } void vaResourceStateTransitionHelperDX12::RSTHTransitionSubRes( vaRenderDeviceContextBaseDX12 & context, D3D12_RESOURCE_STATES target, uint32 subResIndex ) { // if already in, just transition that one for( auto it = m_rsthSubResStates.begin(); it < m_rsthSubResStates.end(); it++ ) { auto & subRes = *it; if( subRes.first == subResIndex ) { if( target != subRes.second ) context.GetCommandList( )->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition( m_rsthResource.Get(), subRes.second, target, subResIndex ) ); subRes.second = target; if( target == m_rsthCurrent ) m_rsthSubResStates.erase( it ); return; } } if( target == m_rsthCurrent ) return; m_rsthSubResStates.push_back( make_pair( subResIndex, target ) ) ; context.GetCommandList( )->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition( m_rsthResource.Get(), m_rsthCurrent, target, subResIndex ) ); } void vaResourceStateTransitionHelperDX12::RSTHAdoptResourceState( vaRenderDeviceContextBaseDX12 & context, D3D12_RESOURCE_STATES target, uint32 subResIndex ) { assert( context.GetRenderDevice().IsRenderThread() ); assert( AsDX12( context.GetRenderDevice() ).GetMainContext() == &context ); // we must be the main context for now assert( !context.IsWorker() ); assert( m_rsthResource != nullptr ); context; if( subResIndex != -1 ) { assert( false ); // not implemented/tested for subresources return; } if( m_rsthSubResStates.size() > 0 ) { assert( false ); // not implemented/tested for subresources m_rsthSubResStates.clear(); } if( m_rsthCurrent == target ) return; m_rsthCurrent = target; } vaResourceViewDX12::~vaResourceViewDX12( ) { SafeRelease( ); } void vaResourceViewDX12::Allocate( bool allocateCPUReadableToo ) { assert( !IsCreated() ); m_device.AllocatePersistentResourceView( m_type, m_heapIndex, m_CPUHandle, m_GPUHandle ); if( allocateCPUReadableToo ) { assert( m_type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); m_device.AllocatePersistentResourceView( D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES, m_CPUReadableHeapIndex, m_CPUReadableCPUHandle, m_CPUReadableGPUHandle ); } assert( IsCreated() ); } void vaResourceViewDX12::SafeRelease( ) { if( !IsCreated() ) return; auto type = m_type; int heapIndex = m_heapIndex; if( m_GPUHandle.ptr == D3D12_GPU_DESCRIPTOR_HANDLE{0}.ptr ) { // these are now CPU-side only so we can remove them immediately m_device.ReleasePersistentResourceView( type, heapIndex ); if( m_CPUReadableHeapIndex != -1 ) m_device.ReleasePersistentResourceView( D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES, m_CPUReadableHeapIndex ); } else { // let the resource be removed until we can guarantee GPU finished using it m_device.ExecuteAfterCurrentGPUFrameDone( [type = m_type, heapIndex = m_heapIndex, CPUReadableHeapIndex = m_CPUReadableHeapIndex]( vaRenderDeviceDX12 & device ) { device.ReleasePersistentResourceView( type, heapIndex ); if( CPUReadableHeapIndex != -1 ) device.ReleasePersistentResourceView( D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES, CPUReadableHeapIndex ); } ); } m_heapIndex = -1; // mark as destroyed m_CPUHandle = { 0 }; // avoid any confusion later m_GPUHandle = { 0 }; // avoid any confusion later m_CPUReadableHeapIndex = -1; m_CPUReadableCPUHandle = { 0 }; m_CPUReadableGPUHandle = { 0 }; } void vaConstantBufferViewDX12::Create( const D3D12_CONSTANT_BUFFER_VIEW_DESC & desc ) { Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateConstantBufferView( &desc, m_CPUHandle ); } else { assert( false ); } } void vaConstantBufferViewDX12::CreateNull( ) { D3D12_CONSTANT_BUFFER_VIEW_DESC desc = { 0, 0 }; Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateConstantBufferView( &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaShaderResourceViewDX12::Create( ID3D12Resource * resource, const D3D12_SHADER_RESOURCE_VIEW_DESC & desc ) { Allocate( true ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateShaderResourceView( resource, &desc, m_CPUHandle ); } else { assert( false ); } if( m_CPUReadableHeapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice( )->CreateShaderResourceView( resource, &desc, m_CPUReadableCPUHandle ); } else { assert( false ); } } void vaShaderResourceViewDX12::CreateNull( ) { D3D12_SHADER_RESOURCE_VIEW_DESC desc = { DXGI_FORMAT_R32_FLOAT, D3D12_SRV_DIMENSION_TEXTURE1D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, {0, 0, 0} }; Allocate( true ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateShaderResourceView( nullptr, &desc, m_CPUHandle ); } else { assert( false ); } if( m_CPUReadableHeapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice( )->CreateShaderResourceView( nullptr, &desc, m_CPUReadableCPUHandle ); } else { assert( false ); } } void vaUnorderedAccessViewDX12::Create( ID3D12Resource *resource, ID3D12Resource * counterResource, const D3D12_UNORDERED_ACCESS_VIEW_DESC & desc ) { Allocate( true ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateUnorderedAccessView( resource, counterResource, &desc, m_CPUHandle ); } else { assert( false ); } if( m_CPUReadableHeapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice( )->CreateUnorderedAccessView( resource, counterResource, &desc, m_CPUReadableCPUHandle ); } else { assert( false ); } } void vaUnorderedAccessViewDX12::CreateNull( D3D12_UAV_DIMENSION dimension ) { D3D12_UNORDERED_ACCESS_VIEW_DESC desc = { DXGI_FORMAT_R32_FLOAT, dimension, { 0 } }; Allocate( true ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateUnorderedAccessView( nullptr, nullptr, &desc, m_CPUHandle ); } else { assert( false ); } if( m_CPUReadableHeapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice( )->CreateUnorderedAccessView( nullptr, nullptr, &desc, m_CPUReadableCPUHandle ); } else { assert( false ); } } void vaRenderTargetViewDX12::Create( ID3D12Resource *resource, const D3D12_RENDER_TARGET_VIEW_DESC & desc ) { Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateRenderTargetView( resource, &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaRenderTargetViewDX12::CreateNull( ) { D3D12_RENDER_TARGET_VIEW_DESC desc = { DXGI_FORMAT_R32_FLOAT, D3D12_RTV_DIMENSION_TEXTURE1D, { 0 } }; Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateRenderTargetView( nullptr, &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaDepthStencilViewDX12::Create( ID3D12Resource *resource, const D3D12_DEPTH_STENCIL_VIEW_DESC & desc ) { Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateDepthStencilView( resource, &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaDepthStencilViewDX12::CreateNull( ) { D3D12_DEPTH_STENCIL_VIEW_DESC desc = { DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE1D, D3D12_DSV_FLAG_NONE, { 0 } }; Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateDepthStencilView( nullptr, &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaSamplerViewDX12::Create( const D3D12_SAMPLER_DESC & desc ) { assert( false ); // never tested Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateSampler( &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaSamplerViewDX12::CreateNull( ) { D3D12_SAMPLER_DESC desc = { D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_WRAP, 0.0f, 0, D3D12_COMPARISON_FUNC_NEVER, {0.0f, 0.0f, 0.0f, 0.0f}, 0.0f, 0.0f }; Allocate( false ); if( m_heapIndex >= 0 ) { m_desc = desc; m_device.GetPlatformDevice()->CreateSampler( &desc, m_CPUHandle ); } else { assert( false ); } assert( m_CPUReadableHeapIndex == -1 ); } void vaDirectXTools12::FillSamplerStatePointClamp( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC( ); outDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_POINTCLAMP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillSamplerStatePointWrap( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC( ); outDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_POINTWRAP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillSamplerStateLinearClamp( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC( ); outDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_LINEARCLAMP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillSamplerStateLinearWrap( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC( ); outDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_LINEARWRAP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillSamplerStateAnisotropicClamp( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC(); outDesc.Filter = D3D12_FILTER_ANISOTROPIC; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_ANISOTROPICCLAMP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillSamplerStateAnisotropicWrap( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC( ); outDesc.Filter = D3D12_FILTER_ANISOTROPIC; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_ANISOTROPICWRAP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillSamplerStateShadowCmp( D3D12_STATIC_SAMPLER_DESC & outDesc ) { outDesc = CD3DX12_STATIC_SAMPLER_DESC( ); outDesc.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; // D3D12_FILTER_COMPARISON_ANISOTROPIC; outDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; outDesc.MipLODBias = 0; outDesc.MaxAnisotropy = 16; outDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; // D3D12_COMPARISON_FUNC_LESS_EQUAL; outDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; outDesc.MinLOD = 0.0f; outDesc.MaxLOD = D3D12_FLOAT32_MAX; outDesc.ShaderRegister = SHADERGLOBAL_SHADOWCMP_SAMPLERSLOT; outDesc.RegisterSpace = 0; outDesc.ShaderVisibility= D3D12_SHADER_VISIBILITY_ALL; } void vaDirectXTools12::FillBlendState( D3D12_BLEND_DESC & outDesc, vaBlendMode blendMode ) { outDesc.AlphaToCoverageEnable = false; outDesc.IndependentBlendEnable = false; const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = { FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL, }; for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) outDesc.RenderTarget[ i ] = defaultRenderTargetBlendDesc; switch( blendMode ) { case vaBlendMode::Opaque: // already in default break; case vaBlendMode::Additive: outDesc.RenderTarget[0].BlendEnable = true; outDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_ONE; outDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; outDesc.RenderTarget[0].DestBlend = D3D12_BLEND_ONE; outDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; break; case vaBlendMode::AlphaBlend: outDesc.RenderTarget[0].BlendEnable = true; outDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; outDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ZERO; outDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; outDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; break; case vaBlendMode::PremultAlphaBlend: outDesc.RenderTarget[0].BlendEnable = true; outDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_ONE; outDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ZERO; outDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; outDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; break; case vaBlendMode::Mult: outDesc.RenderTarget[0].BlendEnable = true; outDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_ZERO; outDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ZERO; outDesc.RenderTarget[0].DestBlend = D3D12_BLEND_SRC_COLOR; outDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_SRC_ALPHA; break; case vaBlendMode::OffscreenAccumulate: outDesc.RenderTarget[0].BlendEnable = true; outDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; outDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; outDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; outDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; outDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; break; default: assert( false ); } } bool vaDirectXTools12::LoadTexture( ID3D12Device * device, void * dataBuffer, uint64 dataBufferSize, vaTextureLoadFlags loadFlags, vaResourceBindSupportFlags bindFlags, ID3D12Resource *& outResource, std::vector<D3D12_SUBRESOURCE_DATA> & outSubresources, std::unique_ptr<Vanilla::byte[]> & outDecodedData, bool & outIsCubemap ) { D3D12_RESOURCE_FLAGS resourceFlags = ResourceFlagsDX12FromVA( bindFlags ); if( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) != 0 ) { assert( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) == 0 ); } // both at the same time don't make sense if( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) != 0 ) { assert( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) == 0 ); } // both at the same time don't make sense // assert( (loadFlags & vaTextureLoadFlags::AutogenerateMIPsIfMissing) == 0 ); // not supported anymore assert( outSubresources.size() == 0 ); outSubresources.clear(); HRESULT hr; // at least 16 bytes in size needed (don't think there's any format that would work with less) if( dataBufferSize < 16 ) return false; outIsCubemap = false; const uint32_t DDS_MAGIC = 0x20534444; // "DDS " const char HDRSignature[] = "#?RADIANCE"; // for the .hdr - https://en.wikipedia.org/wiki/RGBE_image_format format const char HDRSignatureAlt[] = "#?RGBE"; if( (*(reinterpret_cast<uint32_t*>( dataBuffer ))==DDS_MAGIC) ) { assert( outDecodedData == nullptr || outDecodedData.get() == dataBuffer ); // loading inplace from provided data uint32 dxLoadFlags = 0; dxLoadFlags |= ( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) != 0 ) ? ( DirectX::DDS_LOADER_FORCE_SRGB ) : ( 0 ); hr = DirectX::LoadDDSTextureFromMemoryEx( device, (const uint8_t *)dataBuffer, (size_t)dataBufferSize, 0, resourceFlags, dxLoadFlags, &outResource, outSubresources, nullptr, &outIsCubemap ); } else if( (memcmp(dataBuffer, HDRSignature, sizeof(HDRSignature) - 1) == 0) || (memcmp(dataBuffer, HDRSignatureAlt, sizeof(HDRSignatureAlt) - 1) == 0) ) { auto image = std::make_unique<DirectX::ScratchImage>(); DirectX::TexMetadata metadata; hr = DirectX::LoadFromHDRMemory( dataBuffer, dataBufferSize, &metadata, *image ); if( FAILED(hr) ) { assert( false ); return hr; } const DirectX::Image* imgLoaded = image->GetImage( 0, 0, 0 ); if( imgLoaded == nullptr ) { assert( false ); return false; } assert( outDecodedData == nullptr ); outDecodedData = std::make_unique<Vanilla::byte[]>( imgLoaded->slicePitch ); DirectX::Image imgLoadedExternalStorage = *imgLoaded; imgLoadedExternalStorage.pixels = outDecodedData.get( ); memcpy( imgLoadedExternalStorage.pixels, imgLoaded->pixels, imgLoaded->slicePitch ); hr = DirectX::CreateTextureEx( device, metadata, resourceFlags, false, &outResource ); if( FAILED(hr) ) { assert( false ); return false; } hr = DirectX::PrepareUpload( device, &imgLoadedExternalStorage, 1, metadata, outSubresources ); } else { outIsCubemap = false; assert( outDecodedData == nullptr ); // will create data outSubresources.resize(1); uint32 wicLoadFlags = 0; wicLoadFlags |= ( ( loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB ) != 0 ) ? ( DirectX::WIC_LOADER_FORCE_SRGB ) : ( 0 ); wicLoadFlags |= ( ( loadFlags & vaTextureLoadFlags::PresumeDataIsLinear ) != 0 ) ? ( DirectX::WIC_LOADER_IGNORE_SRGB ) : ( 0 ); hr = DirectX::LoadWICTextureFromMemoryEx( device, (const uint8_t *)dataBuffer, (size_t)dataBufferSize, 0, resourceFlags, wicLoadFlags, &outResource, outDecodedData, outSubresources[0] ); } if( SUCCEEDED( hr ) ) { D3D12_RESOURCE_DESC desc = outResource->GetDesc(); if( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) != 0 ) { // wanted sRGB but didn't get it? there's something wrong assert( DirectX::IsSRGB( desc.Format ) ); } if( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) != 0 ) { // there is no support for this at the moment in DirectX tools so asserting if the result is not as requested; fix in the future assert( !DirectX::IsSRGB( desc.Format ) ); } return true; } outResource = nullptr; outDecodedData = nullptr; outSubresources.clear(); return false; } bool vaDirectXTools12::LoadTexture( ID3D12Device * device, const wchar_t * filePath, bool isDDS, vaTextureLoadFlags loadFlags, vaResourceBindSupportFlags bindFlags, ID3D12Resource *& outResource, std::vector<D3D12_SUBRESOURCE_DATA> & outSubresources, std::unique_ptr<Vanilla::byte[]> & outDecodedData, bool & outIsCubemap ) { auto buffer = vaFileTools::LoadMemoryStream( filePath ); if( buffer == nullptr ) return nullptr; if( isDDS ) { outDecodedData = std::make_unique<Vanilla::byte[]>( buffer->GetLength() ); memcpy( outDecodedData.get(), buffer->GetBuffer(), buffer->GetLength() ); return LoadTexture( device, outDecodedData.get(), buffer->GetLength( ), loadFlags, bindFlags, outResource, outSubresources, outDecodedData, outIsCubemap ); } else { return LoadTexture( device, buffer->GetBuffer( ), buffer->GetLength( ), loadFlags, bindFlags, outResource, outSubresources, outDecodedData, outIsCubemap ); } } #if 0 ID3D12Resource * vaDirectXTools12::LoadTextureDDS( ID3D12Device * device, void * dataBuffer, int64 dataSize, vaTextureLoadFlags loadFlags, vaResourceBindSupportFlags bindFlags, uint64 * outCRC ) { outCRC; // unreferenced, not implemented assert( outCRC == nullptr ); // not implemented ID3D12Resource * texture = nullptr; // std::vector<D3D12_SUBRESOURCE_DATA> subresources; <- ok need to output this and isCubemap! hr = DirectX::LoadDDSTextureFromMemoryEx( device, (const uint8_t *)dataBuffer, (size_t)dataSize, 0, resourceFlags, dxLoadFlags, &texture, subresources, NULL ); if( SUCCEEDED( hr ) ) { D3D12_SHADER_RESOURCE_VIEW_DESC desc; textureSRV->GetDesc( &desc ); if( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) != 0 ) { // wanted sRGB but didn't get it? there's something wrong assert( DirectX::IsSRGB( desc.Format ) ); } if( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) != 0 ) { // there is no support for this at the moment in DirectX tools so asserting if the result is not as requested; fix in the future assert( !DirectX::IsSRGB( desc.Format ) ); } if( (loadFlags & vaTextureLoadFlags::AutogenerateMIPsIfMissing) != 0 ) { // check for mips here maybe? // assert( desc. ); } SAFE_RELEASE( textureSRV ); return texture; } else { SAFE_RELEASE( texture ); SAFE_RELEASE( textureSRV ); assert( false ); // check hr throw "Error creating the texture from the stream"; } } ID3D12Resource * vaDirectXTools12::LoadTextureDDS( ID3D12Device * device, const wchar_t * path, vaTextureLoadFlags loadFlags, vaResourceBindSupportFlags bindFlags, uint64 * outCRC ) { outCRC; // unreferenced, not implemented assert( outCRC == nullptr ); // not implemented auto buffer = vaFileTools::LoadMemoryStream( path ); if( buffer == nullptr ) return nullptr; return LoadTextureDDS( device, buffer->GetBuffer( ), buffer->GetLength( ), loadFlags, bindFlags, outCRC ); } ID3D12Resource * vaDirectXTools12::LoadTextureWIC( ID3D12Device * device, void * dataBuffer, int64 dataSize, vaTextureLoadFlags loadFlags, vaResourceBindSupportFlags bindFlags, uint64 * outCRC ) { outCRC; // unreferenced, not implemented assert( outCRC == nullptr ); // not implemented ID3D12DeviceContext * immediateContext = nullptr; device->GetImmediateContext( &immediateContext ); immediateContext->Release(); // yeah, ugly - we know device will guarantee immediate context persistence but still... ID3D12Resource * texture = NULL; UINT dxBindFlags = BindFlagsDX12FromVA( bindFlags ); // not actually used, needed internally for mipmap generation ID3D12ShaderResourceView * textureSRV = NULL; DirectX::WIC_LOADER_FLAGS wicLoaderFlags = DirectX::WIC_LOADER_DEFAULT; if( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) != 0 ) { assert( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) == 0 ); // both at the same time don't make sense wicLoaderFlags = (DirectX::WIC_LOADER_FLAGS)(wicLoaderFlags | DirectX::WIC_LOADER_FORCE_SRGB); } if( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) != 0 ) { assert( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) == 0 ); // both at the same time don't make sense wicLoaderFlags = (DirectX::WIC_LOADER_FLAGS)(wicLoaderFlags | DirectX::WIC_LOADER_IGNORE_SRGB); } bool dontAutogenerateMIPs = (loadFlags & vaTextureLoadFlags::AutogenerateMIPsIfMissing) == 0; HRESULT hr; if( dontAutogenerateMIPs ) { hr = DirectX::CreateWICTextureFromMemoryEx( device, (const uint8_t *)dataBuffer, (size_t)dataSize, 0, D3D11_USAGE_DEFAULT, dxBindFlags, 0, 0, wicLoaderFlags, &texture, &textureSRV ); } else { hr = DirectX::CreateWICTextureFromMemoryEx( device, immediateContext, (const uint8_t *)dataBuffer, (size_t)dataSize, 0, D3D11_USAGE_DEFAULT, dxBindFlags, 0, 0, wicLoaderFlags, &texture, &textureSRV ); } if( SUCCEEDED( hr ) ) { D3D12_SHADER_RESOURCE_VIEW_DESC desc; textureSRV->GetDesc( &desc ); if( (loadFlags & vaTextureLoadFlags::PresumeDataIsSRGB) != 0 ) { // wanted sRGB but didn't get it? there's something wrong assert( DirectX::IsSRGB( desc.Format ) ); } if( (loadFlags & vaTextureLoadFlags::PresumeDataIsLinear) != 0 ) { // there is no support for this at the moment in DirectX tools so asserting if the result is not as requested; fix in the future assert( !DirectX::IsSRGB( desc.Format ) ); } SAFE_RELEASE( textureSRV ); return texture; } else { SAFE_RELEASE( texture ); SAFE_RELEASE( textureSRV ); VA_LOG_ERROR_STACKINFO( L"Error loading texture" ); return nullptr; } } ID3D12Resource * vaDirectXTools12::LoadTextureWIC( ID3D12Device * device, const wchar_t * path, vaTextureLoadFlags loadFlags, vaResourceBindSupportFlags bindFlags, uint64 * outCRC ) { outCRC; // unreferenced, not implemented assert( outCRC == nullptr ); // not implemented auto buffer = vaFileTools::LoadMemoryStream( path ); if( buffer == nullptr ) return nullptr; return LoadTextureWIC( device, buffer->GetBuffer( ), buffer->GetLength( ), loadFlags, bindFlags, outCRC ); } #endif /*bool vaGraphicsPSODescDX12::operator == ( const vaGraphicsPSODescDX12 & other ) const { if( VSBlob != other.VSBlob || VSInputLayout != other.VSInputLayout || VSUniqueContentsID != other.VSUniqueContentsID || PSBlob != other.PSBlob || PSUniqueContentsID != other.PSUniqueContentsID || DSBlob != other.DSBlob || DSUniqueContentsID != other.DSUniqueContentsID || HSBlob != other.HSBlob || HSUniqueContentsID != other.HSUniqueContentsID || GSBlob != other.GSBlob || GSUniqueContentsID != other.GSUniqueContentsID ) return false; if( BlendMode != other.BlendMode || FillMode != other.FillMode || CullMode != other.CullMode || FrontCounterClockwise != other.FrontCounterClockwise || MultisampleEnable != other.MultisampleEnable || DepthEnable != other.DepthEnable || DepthWriteEnable != other.DepthWriteEnable || DepthFunc != other.DepthFunc || Topology != other.Topology ) return false; if( NumRenderTargets != other.NumRenderTargets || DSVFormat != other.DSVFormat || SampleDescCount != other.SampleDescCount ) return false; bool retVal = true; for( int i = 0; i < countof(RTVFormats); i++ ) retVal &= RTVFormats[i] == other.RTVFormats[i]; return retVal; }*/ void vaGraphicsPSODescDX12::PartialReset( ) { VSBlob = nullptr; VSInputLayout = nullptr; VSUniqueContentsID = -1; PSBlob = nullptr; PSUniqueContentsID = -1; DSBlob = nullptr; DSUniqueContentsID = -1; HSBlob = nullptr; HSUniqueContentsID = -1; GSBlob = nullptr; GSUniqueContentsID = -1; } void vaGraphicsPSODescDX12::CleanPointers( ) { VSBlob = nullptr; VSInputLayout = nullptr; PSBlob = nullptr; DSBlob = nullptr; HSBlob = nullptr; GSBlob = nullptr; } void vaGraphicsPSODescDX12::InvalidateCache( ) { VSUniqueContentsID = -1; } void vaGraphicsPSODescDX12::FillGraphicsPipelineStateDesc( D3D12_GRAPHICS_PIPELINE_STATE_DESC & outDesc, ID3D12RootSignature * pRootSignature ) const { assert( VSBlob != nullptr ); outDesc.pRootSignature = pRootSignature; outDesc.VS = (VSBlob != nullptr)?( CD3DX12_SHADER_BYTECODE(VSBlob.Get()) ):(D3D12_SHADER_BYTECODE({0, 0})); outDesc.PS = (PSBlob != nullptr)?( CD3DX12_SHADER_BYTECODE(PSBlob.Get()) ):(D3D12_SHADER_BYTECODE({0, 0})); outDesc.DS = (DSBlob != nullptr)?( CD3DX12_SHADER_BYTECODE(DSBlob.Get()) ):(D3D12_SHADER_BYTECODE({0, 0})); outDesc.HS = (HSBlob != nullptr)?( CD3DX12_SHADER_BYTECODE(HSBlob.Get()) ):(D3D12_SHADER_BYTECODE({0, 0})); outDesc.GS = (GSBlob != nullptr)?( CD3DX12_SHADER_BYTECODE(GSBlob.Get()) ):(D3D12_SHADER_BYTECODE({0, 0})); outDesc.StreamOutput = D3D12_STREAM_OUTPUT_DESC({nullptr, 0, nullptr, 0, 0}); vaDirectXTools12::FillBlendState( outDesc.BlendState, BlendMode ); outDesc.SampleMask = UINT_MAX; // rasterizer state { D3D12_RASTERIZER_DESC rastDesc; rastDesc.CullMode = (CullMode == vaFaceCull::None)?(D3D12_CULL_MODE_NONE):( (CullMode == vaFaceCull::Front)?(D3D12_CULL_MODE_FRONT):(D3D12_CULL_MODE_BACK) ); rastDesc.FillMode = (FillMode == vaFillMode::Solid)?(D3D12_FILL_MODE_SOLID):(D3D12_FILL_MODE_WIREFRAME); rastDesc.FrontCounterClockwise = FrontCounterClockwise; rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS; rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; rastDesc.DepthClipEnable = true; rastDesc.MultisampleEnable = MultisampleEnable; //rastDesc.ScissorEnable = true; rastDesc.AntialiasedLineEnable = false; rastDesc.ForcedSampleCount = 0; rastDesc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; outDesc.RasterizerState = rastDesc; } // depth stencil state { D3D12_DEPTH_STENCIL_DESC dsDesc; dsDesc.DepthEnable = DepthEnable; dsDesc.DepthWriteMask = (DepthWriteEnable)?(D3D12_DEPTH_WRITE_MASK_ALL):(D3D12_DEPTH_WRITE_MASK_ZERO); dsDesc.DepthFunc = (D3D12_COMPARISON_FUNC)DepthFunc; dsDesc.StencilEnable = false; dsDesc.StencilReadMask = 0; dsDesc.StencilWriteMask = 0; dsDesc.FrontFace = {D3D12_STENCIL_OP_KEEP,D3D12_STENCIL_OP_KEEP,D3D12_STENCIL_OP_KEEP,D3D12_COMPARISON_FUNC_ALWAYS}; dsDesc.BackFace = {D3D12_STENCIL_OP_KEEP,D3D12_STENCIL_OP_KEEP,D3D12_STENCIL_OP_KEEP,D3D12_COMPARISON_FUNC_ALWAYS}; outDesc.DepthStencilState = dsDesc; } // input layout { if( VSInputLayout != nullptr ) { outDesc.InputLayout.NumElements = (UINT)VSInputLayout->Layout().size(); outDesc.InputLayout.pInputElementDescs = &(VSInputLayout->Layout()[0]); } else outDesc = { 0, nullptr }; } outDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; // topology { outDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; // TODO: "If the HS and DS members are specified, the PrimitiveTopologyType member for topology type must be set to D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH." assert( HSBlob == nullptr ); assert( DSBlob == nullptr ); switch( Topology ) { case vaPrimitiveTopology::PointList: outDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; break; case vaPrimitiveTopology::LineList: outDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; break; case vaPrimitiveTopology::TriangleList: outDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; break; case vaPrimitiveTopology::TriangleStrip: outDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; break; default: assert( false ); break; // for hull shader } } outDesc.NumRenderTargets = NumRenderTargets; for( int i = 0; i < _countof(outDesc.RTVFormats); i++ ) outDesc.RTVFormats[i] = DXGIFormatFromVA(RTVFormats[i]); outDesc.DSVFormat = DXGIFormatFromVA(DSVFormat); outDesc.SampleDesc = { SampleDescCount, 0 }; outDesc.NodeMask = 0; outDesc.CachedPSO = { nullptr, 0 }; outDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; // for warp devices automatically use D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG? } //void vaGraphicsPSODescDX12::FillKey( vaMemoryStream & outStream ) const //{ // size_t dbgSizeOfThis = sizeof(*this); dbgSizeOfThis; // assert( dbgSizeOfThis == 168 ); // size of the structure changed, did you change the key creation too? // // assert( outStream.GetPosition() == 0 ); // // // add space for the 64bit hash // outStream.WriteValue<uint64>( 0ui64 ); // // outStream.WriteValue<int64>( VSUniqueContentsID ); // outStream.WriteValue<int64>( PSUniqueContentsID ); // outStream.WriteValue<int64>( DSUniqueContentsID ); // outStream.WriteValue<int64>( HSUniqueContentsID ); // outStream.WriteValue<int64>( GSUniqueContentsID ); // // outStream.WriteValue<int32>( static_cast<int32>(this->BlendMode) ); // outStream.WriteValue<int32>( static_cast<int32>(this->FillMode) ); // outStream.WriteValue<int32>( static_cast<int32>(this->CullMode) ); // outStream.WriteValue<bool>( this->FrontCounterClockwise ); // outStream.WriteValue<bool>( this->MultisampleEnable ); // // outStream.WriteValue<bool>( this->ScissorEnable ); // outStream.WriteValue<bool>( this->DepthEnable ); // outStream.WriteValue<bool>( this->DepthWriteEnable ); // outStream.WriteValue<int32>( static_cast<int32>(this->DepthFunc) ); // outStream.WriteValue<int32>( static_cast<int32>(this->Topology) ); // outStream.WriteValue<int32>( this->NumRenderTargets ); // // for( int i = 0; i < countof(this->RTVFormats); i++ ) // outStream.WriteValue<int32>( static_cast<int32>(this->RTVFormats[i]) ); // outStream.WriteValue<int32>( static_cast<int32>(this->DSVFormat) ); // outStream.WriteValue<uint32>( this->SampleDescCount ); // // *reinterpret_cast<uint64*>(outStream.GetBuffer()) = vaXXHash64::Compute( outStream.GetBuffer() + sizeof(uint64), outStream.GetPosition() - sizeof(uint64), 0 ); //} uint32 vaGraphicsPSODescDX12::FillKeyFast( uint8 * __restrict buffer ) const { size_t dbgSizeOfThis = sizeof( *this ); dbgSizeOfThis; assert( dbgSizeOfThis == 208 ); // size of the structure changed, did you change the key creation too? struct Data { uint64 HashKey; int64 VSUniqueContentsID; int64 PSUniqueContentsID; int64 DSUniqueContentsID; int64 HSUniqueContentsID; int64 GSUniqueContentsID; int32 RTVFormats[countof( vaGraphicsPSODescDX12::RTVFormats )]; int32 DSVFormat; uint32 SampleDescCount; int8 BlendMode; int8 FillMode; int8 CullMode; int8 DepthFunc; int8 Topology; int8 NumRenderTargets; int8 FrontCounterClockwise; int8 MultisampleEnable; int8 DepthEnable; int8 DepthWriteEnable; // Last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member int16 Padding0; uint32 Padding1; }; Data & __restrict data = *reinterpret_cast<Data*>(buffer); data.VSUniqueContentsID = VSUniqueContentsID; data.PSUniqueContentsID = PSUniqueContentsID; data.DSUniqueContentsID = DSUniqueContentsID; data.HSUniqueContentsID = HSUniqueContentsID; data.GSUniqueContentsID = GSUniqueContentsID; data.BlendMode = (int8)BlendMode; data.FillMode = (int8)FillMode; data.CullMode = (int8)CullMode; data.FrontCounterClockwise = (FrontCounterClockwise)?(1):(0); data.MultisampleEnable = (MultisampleEnable )?(1):(0); data.DepthEnable = (DepthEnable )?(1):(0); data.DepthWriteEnable = (DepthWriteEnable )?(1):(0); data.DepthFunc = (int8)DepthFunc; data.Topology = (int8)Topology; data.NumRenderTargets = (int8)NumRenderTargets; data.Padding0 = 0; data.Padding1 = 0; for( int i = 0; i < countof( this->RTVFormats ); i++ ) data.RTVFormats[i ] = static_cast<int32>( this->RTVFormats[i] ); data.DSVFormat = static_cast<int32>( this->DSVFormat );; data.SampleDescCount = this->SampleDescCount; int sizeofData = sizeof( Data ); assert( sizeofData == 104 ); assert( sizeofData < vaGraphicsPSODX12::c_keyStorageSize ); data.HashKey = vaXXHash64::Compute( buffer + sizeof( uint64 ), sizeofData - sizeof( uint64 ), 0 ); return sizeofData; } void vaComputePSODescDX12::FillComputePipelineStateDesc( D3D12_COMPUTE_PIPELINE_STATE_DESC & outDesc, ID3D12RootSignature * pRootSignature ) const { assert( CSBlob != nullptr && CSUniqueContentsID != -1 ); outDesc.pRootSignature = pRootSignature; outDesc.CS = (CSBlob != nullptr)?( CD3DX12_SHADER_BYTECODE(CSBlob.Get()) ):(D3D12_SHADER_BYTECODE({0, 0})); outDesc.NodeMask = 0; outDesc.CachedPSO = { nullptr, 0 }; outDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; // for warp devices automatically use D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG? } //void vaComputePSODescDX12::FillKey( vaMemoryStream & outStream ) const //{ // size_t dbgSizeOfThis = sizeof(*this); dbgSizeOfThis; // assert( dbgSizeOfThis == 16 ); // size of the structure changed, did you change the key creation too? // // assert( outStream.GetPosition() == 0 ); // // outStream.WriteValue<int64>( CSUniqueContentsID ); //} uint32 vaComputePSODescDX12::FillKeyFast( uint8 * buffer ) const { size_t dbgSizeOfThis = sizeof( *this ); dbgSizeOfThis; assert( dbgSizeOfThis == 24 ); // size of the structure changed, did you change the key creation too? struct Data { uint64 HashKey; int64 CSUniqueContentsID; }; Data& data = *reinterpret_cast<Data*>( buffer ); data.CSUniqueContentsID = CSUniqueContentsID; int sizeofData = sizeof( Data ); sizeofData; assert( sizeofData == 16 ); assert( sizeofData < vaComputePSODX12::c_keyStorageSize ); data.HashKey = vaXXHash64::Compute( buffer + sizeof( uint64 ), sizeofData - sizeof( uint64 ), 0 ); return sizeofData; } void vaGraphicsPSODX12::CreatePSO( vaRenderDeviceDX12 & device, ID3D12RootSignature * rootSignature ) { #ifdef _DEBUG // this should never happen - only one thread can ever call CreatePSO if( m_pso != nullptr ) { assert( false ); m_desc.CleanPointers(); return; } #endif D3D12_GRAPHICS_PIPELINE_STATE_DESC desc; m_desc.FillGraphicsPipelineStateDesc( desc, rootSignature ); // VA_TRACE_CPU_SCOPE( D3D12_CreateGraphicsPipelineState ); ID3D12PipelineState * pso = nullptr; auto res = device.GetPlatformDevice()->CreateGraphicsPipelineState( &desc, IID_PPV_ARGS(&pso) ); assert( SUCCEEDED(res) ); res; m_desc.CleanPointers( ); pso = m_pso.exchange( pso, std::memory_order_relaxed ); assert( pso == nullptr ); // this should never happen SAFE_RELEASE( pso ); } void vaComputePSODX12::CreatePSO( vaRenderDeviceDX12 & device, ID3D12RootSignature * rootSignature ) { if( m_pso != nullptr ) { assert( false ); m_desc.CleanPointers( ); return; } D3D12_COMPUTE_PIPELINE_STATE_DESC desc; m_desc.FillComputePipelineStateDesc( desc, rootSignature ); ID3D12PipelineState* pso = nullptr; auto res = device.GetPlatformDevice()->CreateComputePipelineState( &desc, IID_PPV_ARGS(&pso) ); assert( SUCCEEDED(res) ); res; m_desc.CleanPointers( ); pso = m_pso.exchange( pso, std::memory_order_relaxed ); assert( pso == nullptr ); // this should never happen SAFE_RELEASE( pso ); } // Local raytracing stuff here namespace { // Shader record = {{Shader ID}, {RootArguments}} class ShaderRecord { public: ShaderRecord( void* pShaderIdentifier, UINT shaderIdentifierSize ) : shaderIdentifier( pShaderIdentifier, shaderIdentifierSize ) { } ShaderRecord( void* pShaderIdentifier, UINT shaderIdentifierSize, void* pLocalRootArguments, UINT localRootArgumentsSize ) : shaderIdentifier( pShaderIdentifier, shaderIdentifierSize ), localRootArguments( pLocalRootArguments, localRootArgumentsSize ) { } void CopyTo( void * dest ) const { uint8_t* byteDest = static_cast<uint8_t*>( dest ); // it's fine for the record to be null in the setup (because you have to PusBack something), just don't actually call it from the shaders if( shaderIdentifier.ptr == nullptr ) memset( byteDest, 0, shaderIdentifier.size ); else memcpy( byteDest, shaderIdentifier.ptr, shaderIdentifier.size ); if( localRootArguments.ptr ) { memcpy( byteDest + shaderIdentifier.size, localRootArguments.ptr, localRootArguments.size ); } } struct PointerWithSize { void* ptr; UINT size; PointerWithSize( ) : ptr( nullptr ), size( 0 ) {} PointerWithSize( void* _ptr, UINT _size ) : ptr( _ptr ), size( _size ) {}; }; PointerWithSize shaderIdentifier; PointerWithSize localRootArguments; }; // Shader table = {{ ShaderRecord 1}, {ShaderRecord 2}, ...} class ShaderTable { uint8_t* m_mappedShaderRecords; UINT m_shaderRecordSize; shared_ptr<vaRenderBuffer> m_bufferGPU; // Debug support std::string m_name; std::vector<ShaderRecord> m_shaderRecords; ShaderTable( ) { } public: ShaderTable( vaRenderDevice & device, UINT numShaderRecords, UINT shaderRecordSize, const string & resourceName = nullptr ) : m_name( resourceName ) { m_shaderRecordSize = vaMath::Align( shaderRecordSize, D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT ); m_shaderRecords.reserve( numShaderRecords ); UINT bufferSize = numShaderRecords * m_shaderRecordSize; m_bufferGPU = vaRenderBuffer::Create( device, (uint64)bufferSize, 1, vaRenderBufferFlags::Upload, resourceName ); //m_bufferGPU->Map( vaResourceMapType::Write ); m_mappedShaderRecords = (uint8_t*)m_bufferGPU->GetMappedData(); } void PushBack( const ShaderRecord & shaderRecord ) { if( m_shaderRecords.size( ) >= m_shaderRecords.capacity( ) ) { assert( false ); abort(); } m_shaderRecords.push_back( shaderRecord ); shaderRecord.CopyTo( m_mappedShaderRecords ); m_mappedShaderRecords += m_shaderRecordSize; if( m_shaderRecords.size( ) == m_shaderRecords.capacity( ) ) { //m_bufferGPU->Unmap(); m_mappedShaderRecords = nullptr; } } UINT GetShaderRecordSize( ) { return m_shaderRecordSize; } // Pretty-print the shader records. void DebugPrint( std::unordered_map<void*, std::string> shaderIdToStringMap ) { std::stringstream str; str << "|--------------------------------------------------------------------\n"; str << "|Shader table - " << m_name.c_str( ) << ": " << m_shaderRecordSize << " | " << m_shaderRecords.size( ) * m_shaderRecordSize << " bytes\n"; for( UINT i = 0; i < m_shaderRecords.size( ); i++ ) { str << "| [" << i << "]: "; str << shaderIdToStringMap[m_shaderRecords[i].shaderIdentifier.ptr] << ", "; str << m_shaderRecords[i].shaderIdentifier.size << " + " << m_shaderRecords[i].localRootArguments.size << " bytes \n"; } str << "|--------------------------------------------------------------------\n"; str << "\n"; OutputDebugStringA( str.str( ).c_str( ) ); } const shared_ptr<vaRenderBuffer> & GetBuffer( ) { return m_bufferGPU; } }; // Pretty-print a state object tree. void PrintStateObjectDesc(const D3D12_STATE_OBJECT_DESC* desc) { std::wstringstream str; str << L"\n"; str << L"--------------------------------------------------------------------\n"; str << L"| D3D12 State Object 0x" << static_cast<const void*>(desc) << L": "; if (desc->Type == D3D12_STATE_OBJECT_TYPE_COLLECTION) str << L"Collection\n"; if (desc->Type == D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE) str << L"Raytracing Pipeline\n"; auto ExportTree = [](UINT depth, UINT numExports, const D3D12_EXPORT_DESC* exports) { std::wostringstream woss; for (UINT i = 0; i < numExports; i++) { woss << L"|"; if (depth > 0) { for (UINT j = 0; j < 2 * depth - 1; j++) woss << L" "; } woss << L" [" << i << L"]: "; if (exports[i].ExportToRename) woss << exports[i].ExportToRename << L" --> "; woss << exports[i].Name << L"\n"; } return woss.str(); }; for (UINT i = 0; i < desc->NumSubobjects; i++) { str << L"| [" << i << L"]: "; switch (desc->pSubobjects[i].Type) { case D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE: str << L"Global Root Signature 0x" << desc->pSubobjects[i].pDesc << L"\n"; break; case D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE: str << L"Local Root Signature 0x" << desc->pSubobjects[i].pDesc << L"\n"; break; case D3D12_STATE_SUBOBJECT_TYPE_NODE_MASK: str << L"Node Mask: 0x" << std::hex << std::setfill(L'0') << std::setw(8) << *static_cast<const UINT*>(desc->pSubobjects[i].pDesc) << std::setw(0) << std::dec << L"\n"; break; case D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY: { str << L"DXIL Library 0x"; auto lib = static_cast<const D3D12_DXIL_LIBRARY_DESC*>(desc->pSubobjects[i].pDesc); str << lib->DXILLibrary.pShaderBytecode << L", " << lib->DXILLibrary.BytecodeLength << L" bytes\n"; str << ExportTree(1, lib->NumExports, lib->pExports); break; } case D3D12_STATE_SUBOBJECT_TYPE_EXISTING_COLLECTION: { str << L"Existing Library 0x"; auto collection = static_cast<const D3D12_EXISTING_COLLECTION_DESC*>(desc->pSubobjects[i].pDesc); str << collection->pExistingCollection << L"\n"; str << ExportTree(1, collection->NumExports, collection->pExports); break; } case D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION: { str << L"Subobject to Exports Association (Subobject ["; auto association = static_cast<const D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION*>(desc->pSubobjects[i].pDesc); UINT index = static_cast<UINT>(association->pSubobjectToAssociate - desc->pSubobjects); str << index << L"])\n"; for (UINT j = 0; j < association->NumExports; j++) { str << L"| [" << j << L"]: " << association->pExports[j] << L"\n"; } break; } case D3D12_STATE_SUBOBJECT_TYPE_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION: { str << L"DXIL Subobjects to Exports Association ("; auto association = static_cast<const D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION*>(desc->pSubobjects[i].pDesc); str << association->SubobjectToAssociate << L")\n"; for (UINT j = 0; j < association->NumExports; j++) { str << L"| [" << j << L"]: " << association->pExports[j] << L"\n"; } break; } case D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG: { str << L"Raytracing Shader Config\n"; auto config = static_cast<const D3D12_RAYTRACING_SHADER_CONFIG*>(desc->pSubobjects[i].pDesc); str << L"| [0]: Max Payload Size: " << config->MaxPayloadSizeInBytes << L" bytes\n"; str << L"| [1]: Max Attribute Size: " << config->MaxAttributeSizeInBytes << L" bytes\n"; break; } case D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG: { str << L"Raytracing Pipeline Config\n"; auto config = static_cast<const D3D12_RAYTRACING_PIPELINE_CONFIG*>(desc->pSubobjects[i].pDesc); str << L"| [0]: Max Recursion Depth: " << config->MaxTraceRecursionDepth << L"\n"; break; } case D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP: { str << L"Hit Group ("; auto hitGroup = static_cast<const D3D12_HIT_GROUP_DESC*>(desc->pSubobjects[i].pDesc); str << (hitGroup->HitGroupExport ? hitGroup->HitGroupExport : L"[none]") << L")\n"; str << L"| [0]: Any Hit Import: " << (hitGroup->AnyHitShaderImport ? hitGroup->AnyHitShaderImport : L"[none]") << L"\n"; str << L"| [1]: Closest Hit Import: " << (hitGroup->ClosestHitShaderImport ? hitGroup->ClosestHitShaderImport : L"[none]") << L"\n"; str << L"| [2]: Intersection Import: " << (hitGroup->IntersectionShaderImport ? hitGroup->IntersectionShaderImport : L"[none]") << L"\n"; break; } } str << L"|--------------------------------------------------------------------\n"; } str << L"\n"; OutputDebugStringW(str.str().c_str()); } } void vaRaytracePSODescDX12::CleanPointers( ) { ItemSLBlob = nullptr; } uint32 vaRaytracePSODescDX12::FillKeyFast( uint8 * __restrict buffer ) const { size_t dbgSizeOfThis = sizeof( *this ); dbgSizeOfThis; assert( dbgSizeOfThis == 400 ); // size of the structure changed, did you change the key creation too? struct Data { uint64 HashKey; int64 ItemSLUniqueContentsID; int64 MaterialsSLUniqueContentsID; wchar_t ItemSLEntryRayGen[c_maxNameBufferSize]; wchar_t ItemSLEntryAnyHit[c_maxNameBufferSize]; wchar_t ItemSLEntryClosestHit[c_maxNameBufferSize]; wchar_t ItemSLEntryMiss[c_maxNameBufferSize]; wchar_t ItemSLEntryMissSecondary[c_maxNameBufferSize]; wchar_t ItemMaterialAnyHit[c_maxNameBufferSize]; wchar_t ItemMaterialClosestHit[c_maxNameBufferSize]; wchar_t ItemMaterialCallable[c_maxNameBufferSize]; wchar_t ItemMaterialMissCallable[c_maxNameBufferSize]; uint32 MaxRecursionDepth; uint32 MaxPayloadSize; // Last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member // uint32 Padding0; // uint32 Padding1; }; Data & __restrict data = *reinterpret_cast<Data*>(buffer); data.ItemSLUniqueContentsID = ItemSLUniqueContentsID; data.MaterialsSLUniqueContentsID = MaterialsSLUniqueContentsID; memset( data.ItemSLEntryRayGen, 0, sizeof(data.ItemSLEntryRayGen) ); memset( data.ItemSLEntryAnyHit, 0, sizeof(data.ItemSLEntryAnyHit) ); memset( data.ItemSLEntryClosestHit, 0, sizeof(data.ItemSLEntryClosestHit) ); memset( data.ItemSLEntryMiss, 0, sizeof(data.ItemSLEntryMiss) ); memset( data.ItemSLEntryMissSecondary, 0, sizeof(data.ItemSLEntryMissSecondary) ); memset( data.ItemMaterialAnyHit, 0, sizeof(data.ItemMaterialAnyHit ) ); memset( data.ItemMaterialClosestHit, 0, sizeof(data.ItemMaterialClosestHit) ); memset( data.ItemMaterialCallable, 0, sizeof(data.ItemMaterialCallable ) ); memset( data.ItemMaterialMissCallable, 0, sizeof(data.ItemMaterialMissCallable ) ); ItemSLEntryRayGen .copy( data.ItemSLEntryRayGen , std::string::npos ); ItemSLEntryAnyHit .copy( data.ItemSLEntryAnyHit , std::string::npos ); ItemSLEntryClosestHit .copy( data.ItemSLEntryClosestHit , std::string::npos ); ItemSLEntryMiss .copy( data.ItemSLEntryMiss , std::string::npos ); ItemSLEntryMissSecondary.copy( data.ItemSLEntryMissSecondary, std::string::npos ); ItemMaterialAnyHit .copy( data.ItemMaterialAnyHit , std::string::npos ); ItemMaterialClosestHit .copy( data.ItemMaterialClosestHit , std::string::npos ); ItemMaterialCallable .copy( data.ItemMaterialCallable , std::string::npos ); ItemMaterialMissCallable.copy( data.ItemMaterialMissCallable, std::string::npos ); data.MaxRecursionDepth = MaxRecursionDepth; data.MaxPayloadSize = MaxPayloadSize; int sizeofData = sizeof( Data ); assert( sizeofData == 896 ); assert( sizeofData < vaRaytracePSODX12::c_keyStorageSize ); data.HashKey = vaXXHash64::Compute( buffer + sizeof( uint64 ), sizeofData - sizeof( uint64 ), 0 ); return sizeofData; } bool vaRaytracePSODescDX12::FillPipelineStateDesc( CD3DX12_STATE_OBJECT_DESC & outDesc, ID3D12RootSignature * pRootSignature, const vaRenderMaterialManagerDX12 & materialManager12 ) const { // expecting to be inited with CD3DX12_STATE_OBJECT_DESC raytracingPipeline{ D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE }; assert( ItemSLBlob != nullptr ); assert( ItemSLEntryRayGen .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemSLEntryAnyHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemSLEntryClosestHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemSLEntryMiss .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemSLEntryMissSecondary.size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemMaterialAnyHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemMaterialClosestHit .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemMaterialCallable .size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); assert( ItemMaterialMissCallable.size() < vaRaytracePSODescDX12::c_maxNameBufferSize ); const std::vector<vaRenderMaterialManagerDX12::CallableShaders> & materialCallablesTable = materialManager12.GetCallablesTable( ); // this is per-material const std::unordered_map<vaFramePtr<vaShaderDataDX12>, uint32> & uniqueCallableLibraries = materialManager12.GetUniqueCallableLibraries( ); // this is per-material-shader - some materials share the same set of shaders // At the moment disallow incomplete raytracing PSO-s - all shaders must compile for any to work for( auto matLibIt : uniqueCallableLibraries ) { if( matLibIt.first == nullptr ) { // null entry in shader table should be valid as per the specs return false; continue; } const vaRenderMaterialManagerDX12::CallableShaders & materialCallables = materialCallablesTable[matLibIt.second]; if( materialCallables.LibraryBlob == nullptr ) { // to find out which material has broken shaders use this: materialCallables.MaterialID VA_LOG( " ** Unable to build raytracing PSO - compile errors or waiting on all shaders to complete compiling (in which case, please wait a bit longer :) ) ** " ); return false; } } // Create the subobjects that combine into a RTPSO // The "item" shader library contains the raygen and (optionally) AnyHit, ClosestHit and Miss shaders { auto itemLib = outDesc.CreateSubobject<CD3DX12_DXIL_LIBRARY_SUBOBJECT>( ); D3D12_SHADER_BYTECODE libdxil = CD3DX12_SHADER_BYTECODE( ItemSLBlob->GetBufferPointer(), ItemSLBlob->GetBufferSize() ); //(void*)g_pRaytracing, ARRAYSIZE( g_pRaytracing ) ); itemLib->SetDXILLibrary( &libdxil ); // Define which shader exports to surface from the library. { assert( ItemSLEntryRayGen != L"" ); itemLib->DefineExport( ItemSLEntryRayGen.c_str() ); if( ItemSLEntryAnyHit != L"" ) itemLib->DefineExport( ItemSLEntryAnyHit.c_str() ); if( ItemSLEntryClosestHit != L"" ) itemLib->DefineExport( ItemSLEntryClosestHit.c_str() ); if( ItemSLEntryMiss != L"" ) itemLib->DefineExport( ItemSLEntryMiss.c_str() ); if( ItemSLEntryMissSecondary != L"" ) itemLib->DefineExport( ItemSLEntryMissSecondary.c_str() ); } } assert( MaterialsSLUniqueContentsID == materialManager12.GetCallablesTableID( ) ); // Expose all material callables - anyhit/closesthit for hitgroups or standalone callables for( auto matLibIt : uniqueCallableLibraries ) { if( matLibIt.first == nullptr ) { // null entry in shader table should be valid as per the specs return false; continue; } const vaRenderMaterialManagerDX12::CallableShaders & materialCallables = materialCallablesTable[matLibIt.second]; assert( materialCallables.LibraryBlob == matLibIt.first ); auto libSubObj = outDesc.CreateSubobject<CD3DX12_DXIL_LIBRARY_SUBOBJECT>( ); D3D12_SHADER_BYTECODE libdxil = CD3DX12_SHADER_BYTECODE( materialCallables.LibraryBlob->GetBufferPointer(), materialCallables.LibraryBlob->GetBufferSize() ); libSubObj->SetDXILLibrary( &libdxil ); // "surface" per-material-library shaders (and rename to unique per material-shader ID) if( ItemMaterialAnyHit != L"" ) libSubObj->DefineExport( (ItemMaterialAnyHit+materialCallables.UniqueIDString).c_str(), ItemMaterialAnyHit.c_str(), D3D12_EXPORT_FLAG_NONE ); if( ItemMaterialClosestHit != L"" ) libSubObj->DefineExport( (ItemMaterialClosestHit+materialCallables.UniqueIDString).c_str(), ItemMaterialClosestHit.c_str(), D3D12_EXPORT_FLAG_NONE ); if( ItemMaterialCallable != L"" ) libSubObj->DefineExport( (ItemMaterialCallable+materialCallables.UniqueIDString).c_str(), ItemMaterialCallable.c_str(), D3D12_EXPORT_FLAG_NONE ); if( ItemMaterialMissCallable != L"" ) libSubObj->DefineExport( (ItemMaterialMissCallable+materialCallables.UniqueIDString).c_str(), ItemMaterialMissCallable.c_str(), D3D12_EXPORT_FLAG_NONE ); // and now define the hit group! also name it so it's per material-shader unique { auto hitGroup = outDesc.CreateSubobject<CD3DX12_HIT_GROUP_SUBOBJECT>( ); // ClosestHit if( ItemSLEntryClosestHit != L"" ) hitGroup->SetClosestHitShaderImport( ItemSLEntryClosestHit.c_str() ); else if( ItemMaterialClosestHit != L"" ) hitGroup->SetClosestHitShaderImport( (ItemMaterialClosestHit+materialCallables.UniqueIDString).c_str() ); else { assert( false ); } // no default closest hit exposed by materials yet but that could be done easily // AnyHit if( ItemSLEntryAnyHit != L"" ) hitGroup->SetAnyHitShaderImport( ItemSLEntryAnyHit.c_str() ); else if( ItemMaterialAnyHit != L"" ) hitGroup->SetAnyHitShaderImport( (ItemMaterialAnyHit+materialCallables.UniqueIDString).c_str() ); else { assert( false ); } // no default closest hit exposed by materials yet but that could be done easily hitGroup->SetHitGroupExport( (L"HitGroup_"+materialCallables.UniqueIDString).c_str() ); hitGroup->SetHitGroupType( D3D12_HIT_GROUP_TYPE_TRIANGLES ); } } // Some additional shader config // Maximum sizes in bytes for the ray payload and attribute structure is hacked in here but this could/should be a parameter in vaRaytraceItem auto shaderConfig = outDesc.CreateSubobject<CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT>( ); UINT payloadSize = MaxPayloadSize; assert( MaxPayloadSize > 0 ); UINT attributeSize = 2 * sizeof( float ); // float2 barycentrics shaderConfig->Config( payloadSize, attributeSize ); // Local root signature and shader association - a root signature that enables a shader to have unique arguments that come from shader tables. We don't use them at the moment!! // CreateLocalRootSignatureSubobjects( m_raytracingLocalRootSignature, &outDesc ); // Global root signature // This is a root signature that is shared across all raytracing shaders invoked during a DispatchRays() call. auto globalRootSignature = outDesc.CreateSubobject<CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT>( ); globalRootSignature->SetRootSignature( pRootSignature ); // <- this is Vanilla's global root signature // Pipeline config // Defines the maximum TraceRay() recursion depth. auto pipelineConfig = outDesc.CreateSubobject<CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT>( ); // PERFOMANCE TIP: Set max recursion depth as low as needed as drivers may apply optimization strategies for low recursion depths. pipelineConfig->Config( MaxRecursionDepth ); // #if _DEBUG // PrintStateObjectDesc( outDesc ); // #endif VA_LOG( "===================================================================================================" ); VA_LOG( "Raytracing PSO rebuilt, number of materials: %d, number of unique hitgroups & callables: %d", (int)materialCallablesTable.size(), (int)uniqueCallableLibraries.size() ); VA_LOG( "===================================================================================================" ); return true; } void vaRaytracePSODX12::CreatePSO( vaRenderDeviceDX12 & device, ID3D12RootSignature * rootSignature ) { VA_GENERIC_RAII_SCOPE( ;, m_desc.CleanPointers( ); ); // clean pointers when leaving the function (success/fail) if( m_pso != nullptr ) { assert( false ); return; } const auto & materialManager12 = AsDX12(device.GetMaterialManager()); std::unique_lock meshLock( materialManager12.Mutex( ) ); CD3DX12_STATE_OBJECT_DESC desc{ D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE }; if( !m_desc.FillPipelineStateDesc( desc, rootSignature, materialManager12 ) ) return; Inner * inner = new Inner(); auto deviceDX12 = device.GetPlatformDevice(); // Create the state object. HRESULT hr = deviceDX12->CreateStateObject( desc, IID_PPV_ARGS( &inner->PSO ) ); // fail gracefully here? :) if( FAILED( hr ) ) { assert( false ); delete inner; return; } inner->PSO->SetName( L"vaRaytracePSODX12_PSO" ); ComPtr<ID3D12StateObjectProperties> stateObjectProperties; hr = inner->PSO.As( &stateObjectProperties ); assert( SUCCEEDED( hr ) ); hr; inner->Incomplete = false; // build shader tables { assert( m_desc.MaterialsSLUniqueContentsID == materialManager12.GetCallablesTableID( ) ); UINT shaderIdentifierSize = D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES; const std::vector<vaRenderMaterialManagerDX12::CallableShaders> & materialCallablesTable = materialManager12.GetCallablesTable( ); { void * rayGenShaderIdentifier = stateObjectProperties->GetShaderIdentifier( m_desc.ItemSLEntryRayGen.c_str() ); void * missShaderIdentifier = stateObjectProperties->GetShaderIdentifier( m_desc.ItemSLEntryMiss.c_str() ); void * missShaderSecondaryIdentifier = (m_desc.ItemSLEntryMissSecondary!=L"")?(stateObjectProperties->GetShaderIdentifier( m_desc.ItemSLEntryMissSecondary.c_str() )):(nullptr); assert( rayGenShaderIdentifier != nullptr ); assert( missShaderIdentifier != nullptr ); // Ray gen shader table { struct ShaderRayGenConstants { vaVector4 Something; }; struct RootArguments { ShaderRayGenConstants cb; } rootArguments; rootArguments.cb = {}; UINT numShaderRecords = 1; UINT shaderRecordSize = shaderIdentifierSize + sizeof( rootArguments ); ShaderTable rayGenShaderTable( device, numShaderRecords, shaderRecordSize, "RayGenShaderTable" ); rayGenShaderTable.PushBack( ShaderRecord( rayGenShaderIdentifier, shaderIdentifierSize, &rootArguments, sizeof( rootArguments ) ) ); inner->RayGenShaderTable = rayGenShaderTable.GetBuffer( ); } // Miss shader table { UINT numShaderRecords = (m_desc.ItemMaterialMissCallable != L"")?(2+(UINT)materialCallablesTable.size() * vaRenderMaterialManagerDX12::CallableShaders::CallablesPerMaterial):(2); //(missShaderSecondaryIdentifier==nullptr)?(1):(2); UINT shaderRecordSize = shaderIdentifierSize; ShaderTable missShaderTable( device, numShaderRecords, shaderRecordSize, "MissShaderTable" ); missShaderTable.PushBack( ShaderRecord( missShaderIdentifier, shaderIdentifierSize ) ); if( missShaderSecondaryIdentifier != nullptr ) missShaderTable.PushBack( ShaderRecord( missShaderSecondaryIdentifier, shaderIdentifierSize ) ); else missShaderTable.PushBack( ShaderRecord( nullptr, shaderIdentifierSize ) ); // need to insert empty one for correct VA_RAYTRACING_SHADER_MISS_CALLABLES_SHADE_OFFSET static_assert( VA_RAYTRACING_SHADER_MISS_CALLABLES_SHADE_OFFSET == 2 ); // optional Miss-Callables if( m_desc.ItemMaterialMissCallable != L"" ) { for( uint32 index = 0; index < materialCallablesTable.size(); index++ ) { const vaRenderMaterialManagerDX12::CallableShaders & materialCallables = materialCallablesTable[index]; if( materialCallables.LibraryBlob == nullptr ) { // this is actually fine - it should never get referenced - only unique ones do //inner->Incomplete = true; for( int i = 0; i < vaRenderMaterialManagerDX12::CallableShaders::CallablesPerMaterial; i++ ) missShaderTable.PushBack( ShaderRecord( nullptr, shaderIdentifierSize ) ); } else { void * shaderIdentifier = stateObjectProperties->GetShaderIdentifier( (m_desc.ItemMaterialMissCallable+materialCallables.UniqueIDString).c_str() ); assert( shaderIdentifier != nullptr ); missShaderTable.PushBack( ShaderRecord( shaderIdentifier, shaderIdentifierSize ) ); } } } inner->MissShaderTable = missShaderTable.GetBuffer( ); inner->MissShaderTableStride = shaderRecordSize; } } // Hit groups shader table { UINT numShaderRecords = (UINT)materialCallablesTable.size(); UINT shaderRecordSize = shaderIdentifierSize; ShaderTable hitGroupShaderTable( device, numShaderRecords, shaderRecordSize, "HitGroupShaderTable" ); for( uint32 index = 0; index < materialCallablesTable.size(); index++ ) { const vaRenderMaterialManagerDX12::CallableShaders & materialCallables = materialCallablesTable[index]; if( materialCallables.LibraryBlob == nullptr ) { // this is actually fine - it should never get referenced - only unique ones do // inner->Incomplete = true; hitGroupShaderTable.PushBack( ShaderRecord( nullptr, shaderIdentifierSize ) ); } else { void * hitGroupShaderIdentifier = stateObjectProperties->GetShaderIdentifier( (L"HitGroup_"+materialCallables.UniqueIDString).c_str() ); assert( hitGroupShaderIdentifier != nullptr ); hitGroupShaderTable.PushBack( ShaderRecord( hitGroupShaderIdentifier, shaderIdentifierSize ) ); } } inner->HitGroupShaderTable = hitGroupShaderTable.GetBuffer( ); inner->HitGroupShaderTableStride = shaderRecordSize; } // Callables shader table (if any) if( m_desc.ItemMaterialCallable != L"" ) { UINT numShaderRecords = (UINT)materialCallablesTable.size() * vaRenderMaterialManagerDX12::CallableShaders::CallablesPerMaterial; UINT shaderRecordSize = shaderIdentifierSize; ShaderTable callableShaderTable( device, numShaderRecords, shaderRecordSize, "CallablesShaderTable" ); for( uint32 index = 0; index < materialCallablesTable.size(); index++ ) { const vaRenderMaterialManagerDX12::CallableShaders & materialCallables = materialCallablesTable[index]; if( materialCallables.LibraryBlob == nullptr ) { inner->Incomplete = true; for( int i = 0; i < vaRenderMaterialManagerDX12::CallableShaders::CallablesPerMaterial; i++ ) callableShaderTable.PushBack( ShaderRecord( nullptr, shaderIdentifierSize ) ); } else { void * shaderIdentifier = stateObjectProperties->GetShaderIdentifier( (m_desc.ItemMaterialCallable+materialCallables.UniqueIDString).c_str() ); assert( shaderIdentifier != nullptr ); //callableShaderTable.PushBack( ShaderRecord( hitTestIdentifier, shaderIdentifierSize ) ); callableShaderTable.PushBack( ShaderRecord( shaderIdentifier, shaderIdentifierSize ) ); } } inner->CallableShaderTable = callableShaderTable.GetBuffer( ); inner->CallableShaderTableStride = shaderRecordSize; } else { inner->CallableShaderTable = nullptr; inner->CallableShaderTableStride = 0; } } // 'incomplete' means some shader identifiers are set to null (shaders still compiling, etc.) - this should be perfectly legal from // the API side as far the docs say but example 'ShaderRecord' code didn't support it and there's a random crash that could be // associated with it, so let's not allow it for now. if( inner->Incomplete ) { VA_LOG( "ray tracing PSO incomplete - shader had an error or did not finish compiling" ); delete inner; inner = nullptr; hr = E_FAIL; } inner = m_pso.exchange( inner, std::memory_order_relaxed ); assert( inner == nullptr ); // this should never happen if( inner != nullptr ) delete inner; }
45.585478
327
0.64391
[ "object", "vector", "3d", "solid" ]
02eb84ba900b024da05432acecb61c6c5fa22e89
1,482
cpp
C++
MilaTest/Dnn/RNN/RnnDataSet.cpp
ToddThomson/Mila
f1ec60d026f3b94d0b4dc084ae40708803242fa2
[ "MIT" ]
1
2022-01-09T01:13:03.000Z
2022-01-09T01:13:03.000Z
MilaTest/Dnn/RNN/RnnDataSet.cpp
ToddThomson/Mila
f1ec60d026f3b94d0b4dc084ae40708803242fa2
[ "MIT" ]
1
2022-01-19T20:04:58.000Z
2022-01-19T20:04:58.000Z
MilaTest/Dnn/RNN/RnnDataSet.cpp
ToddThomson/Mila
f1ec60d026f3b94d0b4dc084ae40708803242fa2
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../Common.h" #include <iostream> #include <vector> import Dnn.RnnModel; import Dnn.RnnDataSetDescriptor; import CuDnn.Utils; namespace Mila::Tests::Dnn { TEST( Dnn_Descriptor, Create_RnnDataSet_Float ) { auto options = GetDefaultRnnOptions(); auto model = Mila::Dnn::RnnModel<float>( options ); cudnnDataType_t dataType = CUDNN_DATA_FLOAT; double paddingFill = 0.0; std::vector<int> seqLengthArray; for ( int i = 0; i < options.batchSize; i++ ) { seqLengthArray.push_back( options.sequenceLength ); } auto builder = model.GetModelBuilder(); RnnDataSet xDesc = builder.Create<RnnDataSet>(); xDesc.SetDataType( dataType ) .SetLayout( CUDNN_RNN_DATA_LAYOUT_SEQ_MAJOR_PACKED ) .SetBatchSize( options.batchSize ) .SetMaxSequenceLength( options.sequenceLength ) .SetVectorSize( options.vectorSize ) .SetSequenceLengthArray( seqLengthArray ) .SetPaddingFill( paddingFill ); xDesc.Finalize(); auto status = xDesc.get_status(); std::cout << "RNN data set, input x tensor: " << std::endl << xDesc.ToString() << std::endl << "Status: " << Mila::Dnn::CuDnn::to_string( status ) << std::endl << "Error Msg: " << xDesc.get_error() << std::endl; EXPECT_TRUE( status == CUDNN_STATUS_SUCCESS ); }; }
29.058824
79
0.610661
[ "vector", "model" ]
02ec45a448be950d36094b42507e5756bd2fe165
4,835
cc
C++
libsrc/cencalvm/query/f77vmquery.cc
baagaard-usgs/cencalvm
c6cca356c722f150178416e5f98a1506dd733db6
[ "CC0-1.0" ]
null
null
null
libsrc/cencalvm/query/f77vmquery.cc
baagaard-usgs/cencalvm
c6cca356c722f150178416e5f98a1506dd733db6
[ "CC0-1.0" ]
null
null
null
libsrc/cencalvm/query/f77vmquery.cc
baagaard-usgs/cencalvm
c6cca356c722f150178416e5f98a1506dd733db6
[ "CC0-1.0" ]
null
null
null
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard // U.S. Geological Survey // // {LicenseText} // // ====================================================================== // #include <portinfo> #include <sys/types.h> // USES size_t #include "f77vmquery.h" extern "C" { #include "cvmquery.h" } #include <sstream> // USES std::istringstream #include <string.h> // USE strncpy #include <assert.h> // USES assert() // ---------------------------------------------------------------------- // Create velocity model query object. void cencalvm_createquery_f(size_t* handle) { // createquery assert(0 != handle); *handle = (size_t) cencalvm_createQuery(); } // createquery // ---------------------------------------------------------------------- // Destroy velocity model query object. void cencalvm_destroyquery_f(size_t* handleAddr, int* err) { // destroyQuery assert(0 != err); *err = cencalvm_destroyQuery((void*) *handleAddr); } // destroyQuery // ---------------------------------------------------------------------- // Open database for querying. void cencalvm_open_f(size_t* handleAddr, int* err) { // open assert(0 != err); *err = cencalvm_open((void*) *handleAddr); } // open // ---------------------------------------------------------------------- // Close the database. void cencalvm_close_f(size_t* handleAddr, int* err) { // close assert(0 != err); *err = cencalvm_close((void*) *handleAddr); } // close // ---------------------------------------------------------------------- // Set query type. void cencalvm_querytype_f(size_t* handleAddr, const int* queryType, int* err) { // queryType assert(0 != err); *err = cencalvm_queryType((void*) *handleAddr, *queryType); } // queryType // ---------------------------------------------------------------------- // Set query resolution. void cencalvm_queryres_f(size_t* handleAddr, const double* res, int* err) { // queryRes assert(0 != err); *err = cencalvm_queryRes((void*) *handleAddr, *res); } // queryRes // ---------------------------------------------------------------------- // Set the database filename. void cencalvm_filename_f(size_t* handleAddr, const char* filename, int* err, const int len) { // filename assert(0 != err); assert(0 != filename); assert(len > 0); std::istringstream sin(filename); std::string cfilename; sin >> cfilename; *err = cencalvm_filename((void*) *handleAddr, cfilename.c_str()); } // filename // ---------------------------------------------------------------------- // Set size of cache during queries. void cencalvm_cachesize_f(size_t* handleAddr, const int* size, int* err) { // cacheSize assert(0 != err); *err = cencalvm_cacheSize((void*) *handleAddr, *size); } // cacheSize // ---------------------------------------------------------------------- // Set the extended database filename. void cencalvm_filenameext_f(size_t* handleAddr, const char* filename, int* err, const int len) { // filenameExt assert(0 != err); assert(0 != filename); assert(len > 0); std::istringstream sin(filename); std::string cfilename; sin >> cfilename; *err = cencalvm_filenameExt((void*) *handleAddr, cfilename.c_str()); } // filenameExt // ---------------------------------------------------------------------- // Set size of cache during queries. void cencalvm_cachesizeext_f(size_t* handleAddr, const int* size, int* err) { // cacheSizeExt assert(0 != err); *err = cencalvm_cacheSizeExt((void*) *handleAddr, *size); } // cacheSizeExt // ---------------------------------------------------------------------- // Set squashed topography/bathymetry flag and minimum elevation of // squashing. Squashing is turned off by default. void cencalvm_squash_f(size_t* handleAddr, const int* flag, const double* limit, int* err) { // squash assert(0 != err); *err = cencalvm_squash((void*) *handleAddr, *flag, *limit); } // squash // ---------------------------------------------------------------------- // Query the database. void cencalvm_query_f(size_t* handleAddr, double* pVals, const int* numVals, const double* lon, const double* lat, const double* elev, int *err) { // query assert(0 != err); *err = cencalvm_query((void*) *handleAddr, &pVals, *numVals, *lon, *lat, *elev); } // query // ---------------------------------------------------------------------- // Get handle to error handler. void cencalvm_errorhandler_f(size_t* handleAddr, size_t* errAddr) { // errorHandler assert(0 != errAddr); *errAddr = (size_t) cencalvm_errorHandler((void*) *handleAddr); } // errorHandler // End of file
24.419192
73
0.50486
[ "object", "model" ]
02ec515e6a008c62f8ba9f6597884233edc2e743
4,187
cpp
C++
ml/src/SelectionModel.cpp
georgephilipp/cppgstd_legacy
e130860da7700aae42b915bc36a7efa4cae06d56
[ "MIT" ]
null
null
null
ml/src/SelectionModel.cpp
georgephilipp/cppgstd_legacy
e130860da7700aae42b915bc36a7efa4cae06d56
[ "MIT" ]
null
null
null
ml/src/SelectionModel.cpp
georgephilipp/cppgstd_legacy
e130860da7700aae42b915bc36a7efa4cae06d56
[ "MIT" ]
null
null
null
/* * File: SelectionModel.cpp * Author: gschoenh * * Created on December 5, 2013, 11:57 AM */ #include "stdafx.h" #include "SelectionModel.h" #include "gstd/src/Map.h" #include "gstd/src/Vector.h" #include "gstd/src/Primitives.h" namespace msii810161816 { namespace ml { SelectionModel::SelectionModel() { selectionCacheProfile.selection = false; numFolds = -1; crossValidationDocSweep = false; } SelectionModel::~SelectionModel() {} void SelectionModel::cacheSelectionModel() { SelectionCache cache; cache.lambda = lambda; if(selectionCacheProfile.selection) cache.selection = selection; selectionCache.push_back(cache); } void SelectionModel::rank() { int numLambdas = selectionCache.size(); int size = parameter.size(); std::vector<int> scores(size,-numLambdas); for(int l=numLambdas-1;l>=0;l--) for(int i=0;i<size;i++) if(selectionCache[l].selection.count(i)) scores[i] = -l; ranks = gstd::vector::rank(scores, false); } //Base package std::string SelectionModel::toString() { std::stringstream res; res << "This is a ml::SelectionModel" << std::endl; res << "lambda is: " << lambda << std::endl; res << "Snippet from selection is: " << gstd::Printer::vp(gstd::vector::sub(gstd::map::keys(selection),0,10,true)) << std::endl; res << "Snippet from targetSelection is: " << gstd::Printer::vp(gstd::vector::sub(gstd::map::keys(targetSelection),0,10,true)) << std::endl; res << "Size of selectionCache is: " << selectionCache.size() << std::endl; if(lambdaSweepSchedule.isNull()) res << "Sweep schedule not set" << std::endl; else res << lambdaSweepSchedule.get(false)->toString(); return res.str(); } //Standard Fns void SelectionModel::sweepStd() { //backup some parameters double cachedLambda = lambda; bool cachedDoc = doc; //initialize lambdaSweepSchedule.get(false)->reset(); double nextLambda = lambdaSweepSchedule.get(false)->next(); doc = false; int P = 0; int cursor = 0; std::vector<double> rankscores; while (nextLambda >= 0) { cursor++; if (cachedDoc) gstd::Printer::c("starting next parameter value. Iteration is " + std::to_string(cursor) + " Lambda is " + std::to_string(nextLambda)); lambda = nextLambda; fit(); if (cachedDoc) gstd::Printer::c("Selection is: " + gstd::Printer::vp(gstd::map::keys(selection))); if (rankscores.size() == 0) { P = parameter.size(); rankscores = std::vector<double>(P, -1); } for (int p = 0; p<P; p++) if (selection.count(p) == 1 && rankscores[p] < 0) rankscores[p] = nextLambda; nextLambda = lambdaSweepSchedule.get(false)->next(); } //set outputs ranks = gstd::vector::rank(rankscores, false); //restore model lambda = cachedLambda; doc = cachedDoc; //print results if (cachedDoc) sweepDocStd(); } void SelectionModel::fitDocStd() { gstd::Printer::c("Target model was:"); gstd::Printer::vc(target); gstd::Printer::c("Learnt model is:"); gstd::Printer::vc(parameter); gstd::Printer::c("Target selection is:"); gstd::Printer::vc(gstd::map::keys(targetSelection)); gstd::Printer::c("selection is:"); gstd::Printer::vc(gstd::map::keys(selection)); } void SelectionModel::sweepDocStd() { std::vector<int> tsVector = gstd::map::keys(targetSelection); gstd::Printer::c("Target selection is:"); gstd::Printer::vc(tsVector); gstd::Printer::c("Target parameters of target selection are: "); if ((int)target.size() > 0) gstd::Printer::vc(gstd::vector::getmany(target, tsVector)); gstd::Printer::c("Ranks of targets are:"); gstd::Printer::vc(gstd::vector::getmany(ranks, tsVector)); } } }
30.122302
152
0.57989
[ "vector", "model" ]
02ed7d7f503aeb44603aec4302a7e291fed7b7f5
97,651
cpp
C++
source/d3d9/d3d9_device.cpp
clayne/reshade
fbbe43d474f38ebbd778f07e00fcb2d7415b78ce
[ "BSD-3-Clause" ]
1
2021-04-15T02:37:12.000Z
2021-04-15T02:37:12.000Z
source/d3d9/d3d9_device.cpp
motz61/reshade
fbbe43d474f38ebbd778f07e00fcb2d7415b78ce
[ "BSD-3-Clause" ]
null
null
null
source/d3d9/d3d9_device.cpp
motz61/reshade
fbbe43d474f38ebbd778f07e00fcb2d7415b78ce
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "d3d9_device.hpp" #include "d3d9_swapchain.hpp" #include "d3d9_impl_type_convert.hpp" #include "dll_log.hpp" // Include late to get HRESULT log overloads #include "com_utils.hpp" using reshade::d3d9::to_handle; extern void dump_and_modify_present_parameters(D3DPRESENT_PARAMETERS &pp, IDirect3D9 *d3d, UINT adapter_index); extern void dump_and_modify_present_parameters(D3DPRESENT_PARAMETERS &pp, D3DDISPLAYMODEEX &fullscreen_desc, IDirect3D9 *d3d, UINT adapter_index); static inline const reshade::api::subresource_box *convert_rect_to_box(const RECT *rect, reshade::api::subresource_box &box) { if (rect == nullptr) return nullptr; box.left = rect->left; box.top = rect->top; box.front = 0; box.right = rect->right; box.bottom = rect->bottom; box.back = 1; return &box; } static inline const reshade::api::subresource_box *convert_rect_to_box(const POINT *point, LONG width, LONG height, reshade::api::subresource_box &box) { if (point == nullptr) return nullptr; box.left = point->x; box.top = point->y; box.front = 0; box.right = point->x + width; box.bottom = point->y + height; box.back = 1; return &box; } Direct3DDevice9::Direct3DDevice9(IDirect3DDevice9 *original, bool use_software_rendering) : device_impl(original), _extended_interface(0), _use_software_rendering(use_software_rendering) { assert(_orig != nullptr); } Direct3DDevice9::Direct3DDevice9(IDirect3DDevice9Ex *original, bool use_software_rendering) : device_impl(original), _extended_interface(1), _use_software_rendering(use_software_rendering) { assert(_orig != nullptr); } bool Direct3DDevice9::check_and_upgrade_interface(REFIID riid) { if (riid == __uuidof(this) || riid == __uuidof(IUnknown) || riid == __uuidof(IDirect3DDevice9)) return true; if (riid != __uuidof(IDirect3DDevice9Ex)) return false; if (!_extended_interface) { IDirect3DDevice9Ex *new_interface = nullptr; if (FAILED(_orig->QueryInterface(IID_PPV_ARGS(&new_interface)))) return false; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Upgrading IDirect3DDevice9 object " << this << " to IDirect3DDevice9Ex."; #endif _orig->Release(); _orig = new_interface; _extended_interface = true; } return true; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::QueryInterface(REFIID riid, void **ppvObj) { if (ppvObj == nullptr) return E_POINTER; if (check_and_upgrade_interface(riid)) { AddRef(); *ppvObj = this; return S_OK; } return _orig->QueryInterface(riid, ppvObj); } ULONG STDMETHODCALLTYPE Direct3DDevice9::AddRef() { _orig->AddRef(); return InterlockedIncrement(&_ref); } ULONG STDMETHODCALLTYPE Direct3DDevice9::Release() { const ULONG ref = InterlockedDecrement(&_ref); if (ref != 0) { _orig->Release(); return ref; } // Release remaining references to this device _implicit_swapchain->Release(); assert(_additional_swapchains.empty()); const auto orig = _orig; const bool extended_interface = _extended_interface; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Destroying " << "IDirect3DDevice9" << (extended_interface ? "Ex" : "") << " object " << this << " (" << orig << ")."; #endif delete this; const ULONG ref_orig = orig->Release(); if (ref_orig != 0) // Verify internal reference count LOG(WARN) << "Reference count for " << "IDirect3DDevice9" << (extended_interface ? "Ex" : "") << " object " << this << " (" << orig << ") is inconsistent (" << ref_orig << ")."; return 0; } #if RESHADE_ADDON && RESHADE_ADDON_LOAD #include "hook_manager.hpp" #undef IDirect3DSurface9_LockRect #undef IDirect3DSurface9_UnlockRect static HRESULT STDMETHODCALLTYPE IDirect3DSurface9_LockRect(IDirect3DSurface9 *pSurface, D3DLOCKED_RECT *pLockedRect, const RECT *pRect, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DSurface9_LockRect, vtable_from_instance(pSurface) + 13)(pSurface, pLockedRect, pRect, Flags); if (SUCCEEDED(hr)) { assert(pLockedRect != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pSurface)) { uint32_t subresource; reshade::api::subresource_box box; reshade::api::subresource_data data; data.data = pLockedRect->pBits; data.row_pitch = pLockedRect->Pitch; data.slice_pitch = 0; reshade::invoke_addon_event<reshade::addon_event::map_texture_region>( device_proxy, device_proxy->get_resource_from_view(to_handle(pSurface), &subresource), subresource, convert_rect_to_box(pRect, box), reshade::d3d9::convert_access_flags(Flags), &data); pLockedRect->pBits = data.data; pLockedRect->Pitch = data.row_pitch; } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DSurface9_UnlockRect(IDirect3DSurface9 *pSurface) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pSurface)) { uint32_t subresource; reshade::invoke_addon_event<reshade::addon_event::unmap_texture_region>( device_proxy, device_proxy->get_resource_from_view(to_handle(pSurface), &subresource), subresource); } return reshade::hooks::call(IDirect3DSurface9_UnlockRect, vtable_from_instance(pSurface) + 14)(pSurface); } #undef IDirect3DVolume9_LockBox #undef IDirect3DVolume9_UnlockBox static HRESULT STDMETHODCALLTYPE IDirect3DVolume9_LockBox(IDirect3DVolume9 *pVolume, D3DLOCKED_BOX *pLockedVolume, const D3DBOX *pBox, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DVolume9_LockBox, vtable_from_instance(pVolume) + 9)(pVolume, pLockedVolume, pBox, Flags); if (SUCCEEDED(hr)) { assert(pLockedVolume != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pVolume)) { uint32_t subresource; reshade::api::subresource_data data; data.data = pLockedVolume->pBits; data.row_pitch = pLockedVolume->RowPitch; data.slice_pitch = pLockedVolume->SlicePitch; reshade::invoke_addon_event<reshade::addon_event::map_texture_region>( device_proxy, device_proxy->get_resource_from_view(to_handle(pVolume), &subresource), subresource, reinterpret_cast<const reshade::api::subresource_box *>(pBox), reshade::d3d9::convert_access_flags(Flags), &data); pLockedVolume->pBits = data.data; pLockedVolume->RowPitch = data.row_pitch; pLockedVolume->SlicePitch = data.slice_pitch; } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DVolume9_UnlockBox(IDirect3DVolume9 *pVolume) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pVolume)) { uint32_t subresource; reshade::invoke_addon_event<reshade::addon_event::unmap_texture_region>( device_proxy, device_proxy->get_resource_from_view(to_handle(pVolume), &subresource), subresource); } return reshade::hooks::call(IDirect3DVolume9_UnlockBox, vtable_from_instance(pVolume) + 10)(pVolume); } #undef IDirect3DTexture9_LockRect #undef IDirect3DTexture9_UnlockRect static HRESULT STDMETHODCALLTYPE IDirect3DTexture9_LockRect(IDirect3DTexture9 *pTexture, UINT Level, D3DLOCKED_RECT *pLockedRect, const RECT *pRect, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DTexture9_LockRect, vtable_from_instance(pTexture) + 19)(pTexture, Level, pLockedRect, pRect, Flags); if (SUCCEEDED(hr)) { assert(pLockedRect != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pTexture)) { reshade::api::subresource_box box; reshade::api::subresource_data data; data.data = pLockedRect->pBits; data.row_pitch = pLockedRect->Pitch; data.slice_pitch = 0; reshade::invoke_addon_event<reshade::addon_event::map_texture_region>( device_proxy, to_handle(pTexture), Level, convert_rect_to_box(pRect, box), reshade::d3d9::convert_access_flags(Flags), &data); pLockedRect->pBits = data.data; pLockedRect->Pitch = data.row_pitch; } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DTexture9_UnlockRect(IDirect3DTexture9 *pTexture, UINT Level) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pTexture)) { reshade::invoke_addon_event<reshade::addon_event::unmap_texture_region>(device_proxy, to_handle(pTexture), Level); } return reshade::hooks::call(IDirect3DTexture9_UnlockRect, vtable_from_instance(pTexture) + 20)(pTexture, Level); } #undef IDirect3DVolumeTexture9_LockBox #undef IDirect3DVolumeTexture9_UnlockBox static HRESULT STDMETHODCALLTYPE IDirect3DVolumeTexture9_LockBox(IDirect3DVolumeTexture9 *pTexture, UINT Level, D3DLOCKED_BOX *pLockedVolume, const D3DBOX *pBox, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DVolumeTexture9_LockBox, vtable_from_instance(pTexture) + 19)(pTexture, Level, pLockedVolume, pBox, Flags); if (SUCCEEDED(hr)) { assert(pLockedVolume != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pTexture)) { reshade::api::subresource_data data; data.data = pLockedVolume->pBits; data.row_pitch = pLockedVolume->RowPitch; data.slice_pitch = pLockedVolume->SlicePitch; reshade::invoke_addon_event<reshade::addon_event::map_texture_region>( device_proxy, to_handle(pTexture), Level, reinterpret_cast<const reshade::api::subresource_box *>(pBox), reshade::d3d9::convert_access_flags(Flags), &data); pLockedVolume->pBits = data.data; pLockedVolume->RowPitch = data.row_pitch; pLockedVolume->SlicePitch = data.slice_pitch; } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DVolumeTexture9_UnlockBox(IDirect3DVolumeTexture9 *pTexture, UINT Level) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pTexture)) { reshade::invoke_addon_event<reshade::addon_event::unmap_texture_region>(device_proxy, to_handle(pTexture), Level); } return reshade::hooks::call(IDirect3DVolumeTexture9_UnlockBox, vtable_from_instance(pTexture) + 20)(pTexture, Level); } #undef IDirect3DCubeTexture9_LockRect #undef IDirect3DCubeTexture9_UnlockRect static HRESULT STDMETHODCALLTYPE IDirect3DCubeTexture9_LockRect(IDirect3DCubeTexture9 *pTexture, D3DCUBEMAP_FACES FaceType, UINT Level, D3DLOCKED_RECT *pLockedRect, const RECT *pRect, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DCubeTexture9_LockRect, vtable_from_instance(pTexture) + 19)(pTexture, FaceType, Level, pLockedRect, pRect, Flags); if (SUCCEEDED(hr)) { assert(pLockedRect != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pTexture)) { const uint32_t subresource = Level + static_cast<uint32_t>(FaceType) * pTexture->GetLevelCount(); reshade::api::subresource_box box; reshade::api::subresource_data data; data.data = pLockedRect->pBits; data.row_pitch = pLockedRect->Pitch; data.slice_pitch = 0; reshade::invoke_addon_event<reshade::addon_event::map_texture_region>( device_proxy, to_handle(pTexture), subresource, convert_rect_to_box(pRect, box), reshade::d3d9::convert_access_flags(Flags), &data); pLockedRect->pBits = data.data; pLockedRect->Pitch = data.row_pitch; } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DCubeTexture9_UnlockRect(IDirect3DCubeTexture9 *pTexture, D3DCUBEMAP_FACES FaceType, UINT Level) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pTexture)) { const uint32_t subresource = Level + static_cast<uint32_t>(FaceType) * pTexture->GetLevelCount(); reshade::invoke_addon_event<reshade::addon_event::unmap_texture_region>(device_proxy, to_handle(pTexture), subresource); } return reshade::hooks::call(IDirect3DCubeTexture9_UnlockRect, vtable_from_instance(pTexture) + 20)(pTexture, FaceType, Level); } #undef IDirect3DVertexBuffer9_Lock #undef IDirect3DVertexBuffer9_Unlock static HRESULT STDMETHODCALLTYPE IDirect3DVertexBuffer9_Lock(IDirect3DVertexBuffer9 *pVertexBuffer, UINT OffsetToLock, UINT SizeToLock, void **ppbData, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DVertexBuffer9_Lock, vtable_from_instance(pVertexBuffer) + 11)(pVertexBuffer, OffsetToLock, SizeToLock, ppbData, Flags); if (SUCCEEDED(hr)) { assert(ppbData != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pVertexBuffer)) { reshade::invoke_addon_event<reshade::addon_event::map_buffer_region>( device_proxy, to_handle(pVertexBuffer), OffsetToLock, SizeToLock != 0 ? SizeToLock : UINT64_MAX, reshade::d3d9::convert_access_flags(Flags), ppbData); } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DVertexBuffer9_Unlock(IDirect3DVertexBuffer9 *pVertexBuffer) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pVertexBuffer)) { reshade::invoke_addon_event<reshade::addon_event::unmap_buffer_region>(device_proxy, to_handle(pVertexBuffer)); } return reshade::hooks::call(IDirect3DVertexBuffer9_Unlock, vtable_from_instance(pVertexBuffer) + 12)(pVertexBuffer); } #undef IDirect3DIndexBuffer9_Lock #undef IDirect3DIndexBuffer9_Unlock static HRESULT STDMETHODCALLTYPE IDirect3DIndexBuffer9_Lock(IDirect3DIndexBuffer9 *pIndexBuffer, UINT OffsetToLock, UINT SizeToLock, void **ppbData, DWORD Flags) { const HRESULT hr = reshade::hooks::call(IDirect3DIndexBuffer9_Lock, vtable_from_instance(pIndexBuffer) + 11)(pIndexBuffer, OffsetToLock, SizeToLock, ppbData, Flags); if (SUCCEEDED(hr)) { assert(ppbData != nullptr); if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pIndexBuffer)) { reshade::invoke_addon_event<reshade::addon_event::map_buffer_region>( device_proxy, to_handle(pIndexBuffer), OffsetToLock, SizeToLock != 0 ? SizeToLock : UINT64_MAX, reshade::d3d9::convert_access_flags(Flags), ppbData); } } return hr; } static HRESULT STDMETHODCALLTYPE IDirect3DIndexBuffer9_Unlock(IDirect3DIndexBuffer9 *pIndexBuffer) { if (const auto device_proxy = get_private_pointer_d3d9<Direct3DDevice9>(pIndexBuffer)) { reshade::invoke_addon_event<reshade::addon_event::unmap_buffer_region>(device_proxy, to_handle(pIndexBuffer)); } return reshade::hooks::call(IDirect3DIndexBuffer9_Unlock, vtable_from_instance(pIndexBuffer) + 12)(pIndexBuffer); } #endif HRESULT STDMETHODCALLTYPE Direct3DDevice9::TestCooperativeLevel() { return _orig->TestCooperativeLevel(); } UINT STDMETHODCALLTYPE Direct3DDevice9::GetAvailableTextureMem() { return _orig->GetAvailableTextureMem(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::EvictManagedResources() { return _orig->EvictManagedResources(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDirect3D(IDirect3D9 **ppD3D9) { return _orig->GetDirect3D(ppD3D9); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDeviceCaps(D3DCAPS9 *pCaps) { return _orig->GetDeviceCaps(pCaps); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDisplayMode(UINT iSwapChain, D3DDISPLAYMODE *pMode) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } return _implicit_swapchain->GetDisplayMode(pMode); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters) { return _orig->GetCreationParameters(pParameters); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetCursorProperties(UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9 *pCursorBitmap) { return _orig->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap); } void STDMETHODCALLTYPE Direct3DDevice9::SetCursorPosition(int X, int Y, DWORD Flags) { return _orig->SetCursorPosition(X, Y, Flags); } BOOL STDMETHODCALLTYPE Direct3DDevice9::ShowCursor(BOOL bShow) { return _orig->ShowCursor(bShow); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DSwapChain9 **ppSwapChain) { LOG(INFO) << "Redirecting " << "IDirect3DDevice9::CreateAdditionalSwapChain" << '(' << "this = " << this << ", pPresentationParameters = " << pPresentationParameters << ", ppSwapChain = " << ppSwapChain << ')' << " ..."; if (pPresentationParameters == nullptr) return D3DERR_INVALIDCALL; D3DPRESENT_PARAMETERS pp = *pPresentationParameters; dump_and_modify_present_parameters(pp, _d3d.get(), _cp.AdapterOrdinal); const HRESULT hr = _orig->CreateAdditionalSwapChain(&pp, ppSwapChain); // Update output values (see https://docs.microsoft.com/windows/win32/api/d3d9/nf-d3d9-idirect3ddevice9-createadditionalswapchain) pPresentationParameters->BackBufferWidth = pp.BackBufferWidth; pPresentationParameters->BackBufferHeight = pp.BackBufferHeight; pPresentationParameters->BackBufferFormat = pp.BackBufferFormat; pPresentationParameters->BackBufferCount = pp.BackBufferCount; if (FAILED(hr)) { LOG(WARN) << "IDirect3DDevice9::CreateAdditionalSwapChain" << " failed with error code " << hr << '.'; return hr; } AddRef(); // Add reference which is released when the swap chain is destroyed (see 'Direct3DSwapChain9::Release') const auto swapchain_proxy = new Direct3DSwapChain9(this, *ppSwapChain); _additional_swapchains.push_back(swapchain_proxy); *ppSwapChain = swapchain_proxy; #if RESHADE_VERBOSE_LOG LOG(INFO) << "Returning IDirect3DSwapChain9 object " << swapchain_proxy << " (" << swapchain_proxy->_orig << ")."; #endif return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetSwapChain(UINT iSwapChain, IDirect3DSwapChain9 **ppSwapChain) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } if (ppSwapChain == nullptr) return D3DERR_INVALIDCALL; _implicit_swapchain->AddRef(); *ppSwapChain = _implicit_swapchain; return D3D_OK; } UINT STDMETHODCALLTYPE Direct3DDevice9::GetNumberOfSwapChains() { return 1; // Multi-head swap chains are not supported } HRESULT STDMETHODCALLTYPE Direct3DDevice9::Reset(D3DPRESENT_PARAMETERS *pPresentationParameters) { LOG(INFO) << "Redirecting " << "IDirect3DDevice9::Reset" << '(' << "this = " << this << ", pPresentationParameters = " << pPresentationParameters << ')' << " ..."; if (pPresentationParameters == nullptr) return D3DERR_INVALIDCALL; D3DPRESENT_PARAMETERS pp = *pPresentationParameters; dump_and_modify_present_parameters(pp, _d3d.get(), _cp.AdapterOrdinal); // Release all resources before performing reset _implicit_swapchain->on_reset(); device_impl::on_reset(); const HRESULT hr = _orig->Reset(&pp); // Update output values (see https://docs.microsoft.com/windows/win32/api/d3d9/nf-d3d9-idirect3ddevice9-reset) pPresentationParameters->BackBufferWidth = pp.BackBufferWidth; pPresentationParameters->BackBufferHeight = pp.BackBufferHeight; pPresentationParameters->BackBufferFormat = pp.BackBufferFormat; pPresentationParameters->BackBufferCount = pp.BackBufferCount; if (FAILED(hr)) { LOG(ERROR) << "IDirect3DDevice9::Reset" << " failed with error code " << hr << '!'; return hr; } device_impl::on_init(pp); _implicit_swapchain->on_init(pp); return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion) { // Only call into the effect runtime if the entire surface is presented, to avoid partial updates messing up effects and the GUI if (Direct3DSwapChain9::is_presenting_entire_surface(pSourceRect, hDestWindowOverride)) { #if RESHADE_ADDON reshade::invoke_addon_event<reshade::addon_event::present>(this, _implicit_swapchain); #endif _implicit_swapchain->on_present(); } return _orig->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetBackBuffer(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } return _implicit_swapchain->GetBackBuffer(iBackBuffer, Type, ppBackBuffer); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRasterStatus(UINT iSwapChain, D3DRASTER_STATUS *pRasterStatus) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } return _implicit_swapchain->GetRasterStatus(pRasterStatus); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetDialogBoxMode(BOOL bEnableDialogs) { return _orig->SetDialogBoxMode(bEnableDialogs); } void STDMETHODCALLTYPE Direct3DDevice9::SetGammaRamp(UINT iSwapChain, DWORD Flags, const D3DGAMMARAMP *pRamp) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return; } return _orig->SetGammaRamp(0, Flags, pRamp); } void STDMETHODCALLTYPE Direct3DDevice9::GetGammaRamp(UINT iSwapChain, D3DGAMMARAMP *pRamp) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return; } return _orig->GetGammaRamp(0, pRamp); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9 **ppTexture, HANDLE *pSharedHandle) { #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_TEXTURE, Usage, Pool, D3DMULTISAMPLE_NONE, 0, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, Levels, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc, &Levels, _caps); const HRESULT hr = _orig->CreateTexture(internal_desc.Width, internal_desc.Height, Levels, internal_desc.Usage, internal_desc.Format, internal_desc.Pool, ppTexture, pSharedHandle); #else const HRESULT hr = _orig->CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppTexture != nullptr); #if RESHADE_ADDON IDirect3DTexture9 *const resource = *ppTexture; Levels = resource->GetLevelCount(); #if RESHADE_ADDON_LOAD const auto device_proxy = this; resource->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DTexture9::LockRect", vtable_from_instance(resource), 19, reinterpret_cast<reshade::hook::address>(IDirect3DTexture9_LockRect)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DTexture9::UnlockRect", vtable_from_instance(resource), 20, reinterpret_cast<reshade::hook::address>(IDirect3DTexture9_UnlockRect)); // Hook surfaces explicitly here, since some applications lock textures via its individual surfaces and they use a different vtable than standalone surfaces for (UINT level = 0; level < Levels; ++level) { com_ptr<IDirect3DSurface9> surface; if (SUCCEEDED(resource->GetSurfaceLevel(level, &surface))) { surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DSurface9::LockRect", vtable_from_instance(surface.get()), 13, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_LockRect)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DSurface9::UnlockRect", vtable_from_instance(surface.get()), 14, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_UnlockRect)); } } #endif InterlockedIncrement(&_ref); reshade::invoke_addon_event<reshade::addon_event::init_resource>(this, desc, nullptr, reshade::api::resource_usage::general, to_handle(resource)); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, to_handle(resource)); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); // Register all surfaces of this texture too if (const reshade::api::resource_usage view_usage = desc.usage & (reshade::api::resource_usage::render_target | reshade::api::resource_usage::depth_stencil); view_usage != 0) { for (UINT level = 0; level < Levels; ++level) { com_ptr<IDirect3DSurface9> surface; if (SUCCEEDED(resource->GetSurfaceLevel(level, &surface))) { reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, to_handle(resource), view_usage, reshade::api::resource_view_desc(desc.texture.format, level, 1, 0, 1), to_handle(surface.get())); register_destruction_callback_d3d9(surface.get(), [this, resource_view = surface.get()]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(resource_view)); }); } } } if ((desc.usage & reshade::api::resource_usage::shader_resource) != 0) { reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, to_handle(resource), reshade::api::resource_usage::shader_resource, reshade::api::resource_view_desc(desc.texture.format, 0, UINT32_MAX, 0, UINT32_MAX), reshade::api::resource_view { reinterpret_cast<uintptr_t>(resource) }); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, reshade::api::resource_view { reinterpret_cast<uintptr_t>(resource) }); }, 1); } #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateTexture" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9 **ppVolumeTexture, HANDLE *pSharedHandle) { #if RESHADE_ADDON D3DVOLUME_DESC internal_desc { Format, D3DRTYPE_VOLUMETEXTURE, Usage, Pool, Width, Height, Depth }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, Levels, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc, &Levels, _caps); const HRESULT hr = _orig->CreateVolumeTexture(internal_desc.Width, internal_desc.Height, internal_desc.Depth, Levels, internal_desc.Usage, internal_desc.Format, internal_desc.Pool, ppVolumeTexture, pSharedHandle); #else const HRESULT hr = _orig->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppVolumeTexture != nullptr); #if RESHADE_ADDON IDirect3DVolumeTexture9 *const resource = *ppVolumeTexture; Levels = resource->GetLevelCount(); #if RESHADE_ADDON_LOAD const auto device_proxy = this; resource->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DVolumeTexture9::LockBox", vtable_from_instance(resource), 19, reinterpret_cast<reshade::hook::address>(IDirect3DVolumeTexture9_LockBox)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DVolumeTexture9::UnlockBox", vtable_from_instance(resource), 20, reinterpret_cast<reshade::hook::address>(IDirect3DVolumeTexture9_UnlockBox)); for (UINT level = 0; level < Levels; ++level) { com_ptr<IDirect3DVolume9> volume; if (SUCCEEDED(resource->GetVolumeLevel(level, &volume))) { volume->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DVolume9::LockBox", vtable_from_instance(volume.get()), 9, reinterpret_cast<reshade::hook::address>(IDirect3DVolume9_LockBox)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DVolume9::UnlockBox", vtable_from_instance(volume.get()), 10, reinterpret_cast<reshade::hook::address>(IDirect3DVolume9_UnlockBox)); } } #endif InterlockedIncrement(&_ref); reshade::invoke_addon_event<reshade::addon_event::init_resource>(this, desc, nullptr, reshade::api::resource_usage::general, to_handle(resource)); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, to_handle(resource)); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); if ((desc.usage & reshade::api::resource_usage::shader_resource) != 0) { reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, to_handle(resource), reshade::api::resource_usage::shader_resource, reshade::api::resource_view_desc(desc.texture.format, 0, UINT32_MAX, 0, UINT32_MAX), reshade::api::resource_view { reinterpret_cast<uintptr_t>(resource) }); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, reshade::api::resource_view { reinterpret_cast<uintptr_t>(resource) }); }, 1); } #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateVolumeTexture" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateCubeTexture(UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9 **ppCubeTexture, HANDLE *pSharedHandle) { #if RESHADE_ADDON D3DSURFACE_DESC internal_desc { Format, D3DRTYPE_CUBETEXTURE, Usage, Pool, D3DMULTISAMPLE_NONE, 0, EdgeLength, EdgeLength }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, Levels, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc, &Levels, _caps); const HRESULT hr = _orig->CreateCubeTexture(internal_desc.Width, Levels, internal_desc.Usage, internal_desc.Format, internal_desc.Pool, ppCubeTexture, pSharedHandle); #else const HRESULT hr = _orig->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppCubeTexture != nullptr); #if RESHADE_ADDON IDirect3DCubeTexture9 *const resource = *ppCubeTexture; Levels = resource->GetLevelCount(); #if RESHADE_ADDON_LOAD const auto device_proxy = this; resource->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DCubeTexture9::LockRect", vtable_from_instance(resource), 19, reinterpret_cast<reshade::hook::address>(IDirect3DCubeTexture9_LockRect)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DCubeTexture9::UnlockRect", vtable_from_instance(resource), 20, reinterpret_cast<reshade::hook::address>(IDirect3DCubeTexture9_UnlockRect)); // Hook surfaces explicitly here, since some applications lock textures via its individual surfaces and they use a different vtable than standalone surfaces for (UINT level = 0; level < Levels; ++level) { for (D3DCUBEMAP_FACES face = D3DCUBEMAP_FACE_POSITIVE_X; face <= D3DCUBEMAP_FACE_NEGATIVE_Z; face = static_cast<D3DCUBEMAP_FACES>(face + 1)) { com_ptr<IDirect3DSurface9> surface; if (SUCCEEDED(resource->GetCubeMapSurface(face, level, &surface))) { surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DSurface9::LockRect", vtable_from_instance(surface.get()), 13, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_LockRect)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DSurface9::UnlockRect", vtable_from_instance(surface.get()), 14, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_UnlockRect)); } } } #endif InterlockedIncrement(&_ref); reshade::invoke_addon_event<reshade::addon_event::init_resource>(this, desc, nullptr, reshade::api::resource_usage::general, to_handle(resource)); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, to_handle(resource)); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); // Register all surfaces of this texture too if (const reshade::api::resource_usage view_usage = desc.usage & (reshade::api::resource_usage::render_target | reshade::api::resource_usage::depth_stencil); view_usage != 0) { for (UINT level = 0; level < Levels; ++level) { for (D3DCUBEMAP_FACES face = D3DCUBEMAP_FACE_POSITIVE_X; face <= D3DCUBEMAP_FACE_NEGATIVE_Z; face = static_cast<D3DCUBEMAP_FACES>(face + 1)) { com_ptr<IDirect3DSurface9> surface; if (SUCCEEDED(resource->GetCubeMapSurface(face, level, &surface))) { reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, to_handle(resource), view_usage, reshade::api::resource_view_desc(desc.texture.format, level, 1, face, 1), to_handle(surface.get())); register_destruction_callback_d3d9(surface.get(), [this, resource_view = surface.get()]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(resource_view)); }); } } } } if ((desc.usage & reshade::api::resource_usage::shader_resource) != reshade::api::resource_usage::undefined) { reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, to_handle(resource), reshade::api::resource_usage::shader_resource, reshade::api::resource_view_desc(desc.texture.format, 0, UINT32_MAX, 0, UINT32_MAX), reshade::api::resource_view { reinterpret_cast<uintptr_t>(resource) }); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, reshade::api::resource_view { reinterpret_cast<uintptr_t>(resource) }); }, 1); } #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateCubeTexture" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexBuffer(UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9 **ppVertexBuffer, HANDLE *pSharedHandle) { // Need to allow buffer for use in software vertex processing, since application uses software and not hardware processing, but device was created with both if (_use_software_rendering) Usage |= D3DUSAGE_SOFTWAREPROCESSING; #if RESHADE_ADDON D3DVERTEXBUFFER_DESC internal_desc = { D3DFMT_UNKNOWN, D3DRTYPE_VERTEXBUFFER, Usage, Pool, Length, FVF }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc); const HRESULT hr = _orig->CreateVertexBuffer(internal_desc.Size, internal_desc.Usage, internal_desc.FVF, internal_desc.Pool, ppVertexBuffer, pSharedHandle); #else const HRESULT hr = _orig->CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppVertexBuffer != nullptr); #if RESHADE_ADDON IDirect3DVertexBuffer9 *const resource = *ppVertexBuffer; #if RESHADE_ADDON_LOAD const auto device_proxy = this; resource->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_buffer_region>()) reshade::hooks::install("IDirect3DVertexBuffer9::Lock", vtable_from_instance(resource), 11, reinterpret_cast<reshade::hook::address>(IDirect3DVertexBuffer9_Lock)); if (reshade::has_addon_event<reshade::addon_event::unmap_buffer_region>()) reshade::hooks::install("IDirect3DVertexBuffer9::Unlock", vtable_from_instance(resource), 12, reinterpret_cast<reshade::hook::address>(IDirect3DVertexBuffer9_Unlock)); #endif InterlockedIncrement(&_ref); reshade::invoke_addon_event<reshade::addon_event::init_resource>(this, desc, nullptr, reshade::api::resource_usage::general, to_handle(*ppVertexBuffer)); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, to_handle(resource)); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateVertexBuffer" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9 **ppIndexBuffer, HANDLE *pSharedHandle) { if (_use_software_rendering) Usage |= D3DUSAGE_SOFTWAREPROCESSING; #if RESHADE_ADDON D3DINDEXBUFFER_DESC internal_desc = { Format, D3DRTYPE_INDEXBUFFER, Usage, Pool, Length }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc); const HRESULT hr = _orig->CreateIndexBuffer(internal_desc.Size, internal_desc.Usage, internal_desc.Format, internal_desc.Pool, ppIndexBuffer, pSharedHandle); #else const HRESULT hr = _orig->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppIndexBuffer != nullptr); #if RESHADE_ADDON IDirect3DIndexBuffer9 *const resource = *ppIndexBuffer; #if RESHADE_ADDON_LOAD const auto device_proxy = this; resource->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_buffer_region>()) reshade::hooks::install("IDirect3DIndexBuffer9::Lock", vtable_from_instance(resource), 11, reinterpret_cast<reshade::hook::address>(IDirect3DIndexBuffer9_Lock)); if (reshade::has_addon_event<reshade::addon_event::unmap_buffer_region>()) reshade::hooks::install("IDirect3DIndexBuffer9::Unlock", vtable_from_instance(resource), 12, reinterpret_cast<reshade::hook::address>(IDirect3DIndexBuffer9_Unlock)); #endif InterlockedIncrement(&_ref); reshade::invoke_addon_event<reshade::addon_event::init_resource>(this, desc, nullptr, reshade::api::resource_usage::general, to_handle(resource)); register_destruction_callback_d3d9(resource, [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, to_handle(resource)); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateIndexBuffer" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateRenderTarget(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle) { #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_SURFACE, D3DUSAGE_RENDERTARGET, D3DPOOL_DEFAULT, MultiSample, MultisampleQuality, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, 1, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::render_target)) reshade::d3d9::convert_resource_desc(desc, internal_desc, nullptr, _caps); const HRESULT hr = ((desc.usage & reshade::api::resource_usage::shader_resource) != 0) && !Lockable ? create_surface_replacement(internal_desc, ppSurface, pSharedHandle) : _orig->CreateRenderTarget(internal_desc.Width, internal_desc.Height, internal_desc.Format, internal_desc.MultiSampleType, internal_desc.MultiSampleQuality, Lockable, ppSurface, pSharedHandle); #else const HRESULT hr = _orig->CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppSurface != nullptr); #if RESHADE_ADDON IDirect3DSurface9 *const surface = *ppSurface; #if RESHADE_ADDON_LOAD const auto device_proxy = this; surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); #endif // In case surface was replaced with a texture resource const reshade::api::resource resource = get_resource_from_view(to_handle(surface)); reshade::invoke_addon_event<reshade::addon_event::init_resource>( this, desc, nullptr, reshade::api::resource_usage::render_target, resource); reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, resource, reshade::api::resource_usage::render_target, reshade::api::resource_view_desc(desc.texture.format), to_handle(surface)); InterlockedIncrement(&_ref); register_destruction_callback_d3d9(reinterpret_cast<IDirect3DResource9 *>(resource.handle), [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, resource); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); register_destruction_callback_d3d9(surface, [this, surface]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(surface)); }, to_handle(surface).handle == resource.handle ? 1 : 0); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateRenderTarget" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle) { #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_SURFACE, D3DUSAGE_DEPTHSTENCIL, D3DPOOL_DEFAULT, MultiSample, MultisampleQuality, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, 1, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::depth_stencil)) reshade::d3d9::convert_resource_desc(desc, internal_desc, nullptr, _caps); const HRESULT hr = ((desc.usage & reshade::api::resource_usage::shader_resource) != 0) ? create_surface_replacement(internal_desc, ppSurface, pSharedHandle) : _orig->CreateDepthStencilSurface(internal_desc.Width, internal_desc.Height, internal_desc.Format, internal_desc.MultiSampleType, internal_desc.MultiSampleQuality, Discard, ppSurface, pSharedHandle); #else const HRESULT hr = _orig->CreateDepthStencilSurface(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppSurface != nullptr); #if RESHADE_ADDON IDirect3DSurface9 *const surface = *ppSurface; #if RESHADE_ADDON_LOAD const auto device_proxy = this; surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); #endif // In case surface was replaced with a texture resource const reshade::api::resource resource = get_resource_from_view(to_handle(surface)); reshade::invoke_addon_event<reshade::addon_event::init_resource>( this, desc, nullptr, reshade::api::resource_usage::depth_stencil, resource); reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, resource, reshade::api::resource_usage::depth_stencil, reshade::api::resource_view_desc(desc.texture.format), to_handle(surface)); InterlockedIncrement(&_ref); register_destruction_callback_d3d9(reinterpret_cast<IDirect3DResource9 *>(resource.handle), [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, resource); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); register_destruction_callback_d3d9(surface, [this, surface]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(surface)); }, to_handle(surface).handle == resource.handle ? 1 : 0); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateDepthStencilSurface" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::UpdateSurface(IDirect3DSurface9 *pSrcSurface, const RECT *pSrcRect, IDirect3DSurface9 *pDstSurface, const POINT *pDstPoint) { #if RESHADE_ADDON && RESHADE_ADDON_LOAD assert(pSrcSurface != nullptr && pDstSurface != nullptr); if (reshade::has_addon_event<reshade::addon_event::copy_texture_region>()) { uint32_t src_subresource; reshade::api::subresource_box src_box; const reshade::api::resource src_resource = get_resource_from_view(to_handle(pSrcSurface), &src_subresource); uint32_t dst_subresource; reshade::api::subresource_box dst_box; const reshade::api::resource dst_resource = get_resource_from_view(to_handle(pDstSurface), &dst_subresource); if (pSrcRect != nullptr) { convert_rect_to_box(pDstPoint, pSrcRect->right - pSrcRect->left, pSrcRect->bottom - pSrcRect->top, dst_box); } else { D3DSURFACE_DESC desc; pSrcSurface->GetDesc(&desc); convert_rect_to_box(pDstPoint, desc.Width, desc.Height, dst_box); } if (reshade::invoke_addon_event<reshade::addon_event::copy_texture_region>(this, src_resource, src_subresource, convert_rect_to_box(pSrcRect, src_box), dst_resource, dst_subresource, pDstPoint != nullptr ? &dst_box : nullptr, reshade::api::filter_mode::min_mag_mip_point)) return D3D_OK; } #endif return _orig->UpdateSurface(pSrcSurface, pSrcRect, pDstSurface, pDstPoint); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::UpdateTexture(IDirect3DBaseTexture9 *pSrcTexture, IDirect3DBaseTexture9 *pDstTexture) { #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (reshade::invoke_addon_event<reshade::addon_event::copy_resource>(this, to_handle(pSrcTexture), to_handle(pDstTexture))) return D3D_OK; #endif return _orig->UpdateTexture(pSrcTexture, pDstTexture); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderTargetData(IDirect3DSurface9 *pSrcSurface, IDirect3DSurface9 *pDstSurface) { #if RESHADE_ADDON && RESHADE_ADDON_LOAD assert(pSrcSurface != nullptr && pDstSurface != nullptr); if (reshade::has_addon_event<reshade::addon_event::copy_texture_region>()) { uint32_t src_subresource; const reshade::api::resource src_resource = get_resource_from_view(to_handle(pSrcSurface), &src_subresource); uint32_t dst_subresource; const reshade::api::resource dst_resource = get_resource_from_view(to_handle(pDstSurface), &dst_subresource); if (reshade::invoke_addon_event<reshade::addon_event::copy_texture_region>(this, src_resource, src_subresource, nullptr, dst_resource, dst_subresource, nullptr, reshade::api::filter_mode::min_mag_mip_point)) return D3D_OK; } #endif return _orig->GetRenderTargetData(pSrcSurface, pDstSurface); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetFrontBufferData(UINT iSwapChain, IDirect3DSurface9 *pDestSurface) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } return _implicit_swapchain->GetFrontBufferData(pDestSurface); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::StretchRect(IDirect3DSurface9 *pSrcSurface, const RECT *pSrcRect, IDirect3DSurface9 *pDstSurface, const RECT *pDstRect, D3DTEXTUREFILTERTYPE Filter) { #if RESHADE_ADDON && RESHADE_ADDON_LOAD assert(pSrcSurface != nullptr && pDstSurface != nullptr); if (reshade::has_addon_event<reshade::addon_event::copy_texture_region>() || reshade::has_addon_event<reshade::addon_event::resolve_texture_region>()) { D3DSURFACE_DESC desc; pSrcSurface->GetDesc(&desc); uint32_t src_subresource; const reshade::api::resource src_resource = get_resource_from_view(to_handle(pSrcSurface), &src_subresource); uint32_t dst_subresource; const reshade::api::resource dst_resource = get_resource_from_view(to_handle(pDstSurface), &dst_subresource); if (desc.MultiSampleType == D3DMULTISAMPLE_NONE) { reshade::api::subresource_box src_box, dst_box; if (reshade::invoke_addon_event<reshade::addon_event::copy_texture_region>(this, src_resource, src_subresource, convert_rect_to_box(pSrcRect, src_box), dst_resource, dst_subresource, convert_rect_to_box(pDstRect, dst_box), Filter == D3DTEXF_NONE || Filter == D3DTEXF_POINT ? reshade::api::filter_mode::min_mag_mip_point : reshade::api::filter_mode::min_mag_mip_linear)) return D3D_OK; } else { if (reshade::invoke_addon_event<reshade::addon_event::resolve_texture_region>(this, src_resource, src_subresource, reinterpret_cast<const reshade::api::rect *>(pSrcRect), dst_resource, dst_subresource, pDstRect != nullptr ? pDstRect->left : 0, pDstRect != nullptr ? pDstRect->top : 0, reshade::d3d9::convert_format(desc.Format))) return D3D_OK; } } #endif return _orig->StretchRect(pSrcSurface, pSrcRect, pDstSurface, pDstRect, Filter); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::ColorFill(IDirect3DSurface9 *pSurface, const RECT *pRect, D3DCOLOR Color) { #if RESHADE_ADDON if (const float color[4] = { ((Color >> 16) & 0xFF) / 255.0f, ((Color >> 8) & 0xFF) / 255.0f, (Color & 0xFF) / 255.0f, ((Color >> 24) & 0xFF) / 255.0f }; reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(this, to_handle(pSurface), color, pRect != nullptr ? 1 : 0, reinterpret_cast<const reshade::api::rect *>(pRect))) return D3D_OK; #endif return _orig->ColorFill(pSurface, pRect, Color); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateOffscreenPlainSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle) { #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_SURFACE, 0, Pool, D3DMULTISAMPLE_NONE, 0, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, 1, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc, nullptr, _caps); const HRESULT hr = _orig->CreateOffscreenPlainSurface(internal_desc.Width, internal_desc.Height, internal_desc.Format, internal_desc.Pool, ppSurface, pSharedHandle); #else const HRESULT hr = _orig->CreateOffscreenPlainSurface(Width, Height, Format, Pool, ppSurface, pSharedHandle); #endif if (SUCCEEDED(hr)) { assert(ppSurface != nullptr); #if RESHADE_ADDON IDirect3DSurface9 *const surface = *ppSurface; #if RESHADE_ADDON_LOAD const auto device_proxy = this; surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DSurface9::LockRect", vtable_from_instance(surface), 13, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_LockRect)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DSurface9::UnlockRect", vtable_from_instance(surface), 14, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_UnlockRect)); #endif const reshade::api::resource resource = get_resource_from_view(to_handle(surface)); reshade::invoke_addon_event<reshade::addon_event::init_resource>( this, desc, nullptr, reshade::api::resource_usage::render_target, resource); reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, resource, reshade::api::resource_usage::render_target, reshade::api::resource_view_desc(desc.texture.format), to_handle(surface)); InterlockedIncrement(&_ref); register_destruction_callback_d3d9(reinterpret_cast<IDirect3DResource9 *>(resource.handle), [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, resource); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); register_destruction_callback_d3d9(surface, [this, surface]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(surface)); }, to_handle(surface).handle == resource.handle ? 1 : 0); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateOffscreenPlainSurface" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 *pRenderTarget) { const HRESULT hr = _orig->SetRenderTarget(RenderTargetIndex, pRenderTarget); #if RESHADE_ADDON if (SUCCEEDED(hr) && ( reshade::has_addon_event<reshade::addon_event::bind_render_targets_and_depth_stencil>() || reshade::has_addon_event<reshade::addon_event::bind_viewports>())) { DWORD count = 0; com_ptr<IDirect3DSurface9> surface; reshade::api::resource_view rtvs[8] = {}, dsv = {}; for (DWORD i = 0; i < _caps.NumSimultaneousRTs; ++i, surface.reset()) { if (FAILED(_orig->GetRenderTarget(i, &surface))) continue; // All surfaces that can be used as render target should be registered at this point rtvs[i] = to_handle(surface.get()); count = i + 1; } if (SUCCEEDED(_orig->GetDepthStencilSurface(&surface))) { // All surfaces that can be used as depth-stencil should be registered at this point dsv = to_handle(surface.get()); } reshade::invoke_addon_event<reshade::addon_event::bind_render_targets_and_depth_stencil>(this, count, rtvs, dsv); if (pRenderTarget != nullptr) { // Setting a new render target will cause the viewport to be set to the full size of the new render target // See https://docs.microsoft.com/windows/win32/api/d3d9helper/nf-d3d9helper-idirect3ddevice9-setrendertarget D3DSURFACE_DESC desc; pRenderTarget->GetDesc(&desc); const reshade::api::viewport viewport_data = { 0.0f, 0.0f, static_cast<float>(desc.Width), static_cast<float>(desc.Height), 0.0f, 1.0f }; reshade::invoke_addon_event<reshade::addon_event::bind_viewports>(this, 0, 1, &viewport_data); } } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 **ppRenderTarget) { return _orig->GetRenderTarget(RenderTargetIndex, ppRenderTarget); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetDepthStencilSurface(IDirect3DSurface9 *pNewZStencil) { const HRESULT hr = _orig->SetDepthStencilSurface(pNewZStencil); #if RESHADE_ADDON if (SUCCEEDED(hr) && reshade::has_addon_event<reshade::addon_event::bind_render_targets_and_depth_stencil>()) { DWORD count = 0; com_ptr<IDirect3DSurface9> surface; reshade::api::resource_view rtvs[8] = {}; for (DWORD i = 0; i < _caps.NumSimultaneousRTs; ++i, surface.reset()) { if (FAILED(_orig->GetRenderTarget(i, &surface))) continue; rtvs[i] = to_handle(surface.get()); count = i + 1; } reshade::invoke_addon_event<reshade::addon_event::bind_render_targets_and_depth_stencil>(this, count, rtvs, to_handle(pNewZStencil)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDepthStencilSurface(IDirect3DSurface9 **ppZStencilSurface) { return _orig->GetDepthStencilSurface(ppZStencilSurface); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::BeginScene() { return _orig->BeginScene(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::EndScene() { return _orig->EndScene(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::Clear(DWORD Count, const D3DRECT *pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil) { #if RESHADE_ADDON if (Flags & (D3DCLEAR_TARGET) && reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()) { com_ptr<IDirect3DSurface9> surface; for (DWORD i = 0; i < _caps.NumSimultaneousRTs; ++i, surface.reset()) { if (FAILED(_orig->GetRenderTarget(i, &surface))) continue; if (const float color[4] = { ((Color >> 16) & 0xFF) / 255.0f, ((Color >> 8) & 0xFF) / 255.0f, (Color & 0xFF) / 255.0f, ((Color >> 24) & 0xFF) / 255.0f }; reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(this, to_handle(surface.get()), color, Count, reinterpret_cast<const reshade::api::rect *>(pRects))) Flags &= ~(D3DCLEAR_TARGET); } } if (Flags & (D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL) && reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>()) { com_ptr<IDirect3DSurface9> surface; if (SUCCEEDED(_orig->GetDepthStencilSurface(&surface))) { if (reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(this, to_handle(surface.get()), Flags & D3DCLEAR_ZBUFFER ? &Z : nullptr, Flags & D3DCLEAR_STENCIL ? reinterpret_cast<const uint8_t *>(&Stencil) : nullptr, Count, reinterpret_cast<const reshade::api::rect *>(pRects))) Flags &= ~(D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL); } } if (Flags == 0) return D3D_OK; #endif return _orig->Clear(Count, pRects, Flags, Color, Z, Stencil); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix) { return _orig->SetTransform(State, pMatrix); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX *pMatrix) { return _orig->GetTransform(State, pMatrix); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::MultiplyTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix) { return _orig->MultiplyTransform(State, pMatrix); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetViewport(const D3DVIEWPORT9 *pViewport) { const HRESULT hr = _orig->SetViewport(pViewport); #if RESHADE_ADDON if (SUCCEEDED(hr) && reshade::has_addon_event<reshade::addon_event::bind_viewports>()) { const reshade::api::viewport viewport_data = { static_cast<float>(pViewport->X), static_cast<float>(pViewport->Y), static_cast<float>(pViewport->Width), static_cast<float>(pViewport->Height), pViewport->MinZ, pViewport->MaxZ }; reshade::invoke_addon_event<reshade::addon_event::bind_viewports>(this, 0, 1, &viewport_data); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetViewport(D3DVIEWPORT9 *pViewport) { return _orig->GetViewport(pViewport); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetMaterial(const D3DMATERIAL9 *pMaterial) { return _orig->SetMaterial(pMaterial); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetMaterial(D3DMATERIAL9 *pMaterial) { return _orig->GetMaterial(pMaterial); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetLight(DWORD Index, const D3DLIGHT9 *pLight) { return _orig->SetLight(Index, pLight); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetLight(DWORD Index, D3DLIGHT9 *pLight) { return _orig->GetLight(Index, pLight); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::LightEnable(DWORD Index, BOOL Enable) { return _orig->LightEnable(Index, Enable); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetLightEnable(DWORD Index, BOOL *pEnable) { return _orig->GetLightEnable(Index, pEnable); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetClipPlane(DWORD Index, const float *pPlane) { return _orig->SetClipPlane(Index, pPlane); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetClipPlane(DWORD Index, float *pPlane) { return _orig->GetClipPlane(Index, pPlane); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetRenderState(D3DRENDERSTATETYPE State, DWORD Value) { const HRESULT hr = _orig->SetRenderState(State, Value); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr) && reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>()) { switch (State) { case D3DRS_BLENDOP: case D3DRS_BLENDOPALPHA: Value = static_cast<uint32_t>(reshade::d3d9::convert_blend_op(static_cast<D3DBLENDOP>(Value))); break; case D3DRS_SRCBLEND: case D3DRS_DESTBLEND: case D3DRS_SRCBLENDALPHA: case D3DRS_DESTBLENDALPHA: Value = static_cast<uint32_t>(reshade::d3d9::convert_blend_factor(static_cast<D3DBLEND>(Value))); break; case D3DRS_FILLMODE: Value = static_cast<uint32_t>(reshade::d3d9::convert_fill_mode(static_cast<D3DFILLMODE>(Value))); break; case D3DRS_CULLMODE: Value = static_cast<uint32_t>(reshade::d3d9::convert_cull_mode(static_cast<D3DCULL>(Value), false)); break; case D3DRS_ZFUNC: case D3DRS_ALPHAFUNC: case D3DRS_STENCILFUNC: case D3DRS_CCW_STENCILFUNC: Value = static_cast<uint32_t>(reshade::d3d9::convert_compare_op(static_cast<D3DCMPFUNC>(Value))); break; case D3DRS_STENCILFAIL: case D3DRS_STENCILZFAIL: case D3DRS_STENCILPASS: case D3DRS_CCW_STENCILFAIL: case D3DRS_CCW_STENCILZFAIL: case D3DRS_CCW_STENCILPASS: Value = static_cast<uint32_t>(reshade::d3d9::convert_stencil_op(static_cast<D3DSTENCILOP>(Value))); break; } const reshade::api::dynamic_state state = reshade::d3d9::convert_dynamic_state(State); const uint32_t value = Value; reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(this, 1, &state, &value); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderState(D3DRENDERSTATETYPE State, DWORD *pValue) { return _orig->GetRenderState(State, pValue); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateStateBlock(D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9 **ppSB) { return _orig->CreateStateBlock(Type, ppSB); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::BeginStateBlock() { return _orig->BeginStateBlock(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::EndStateBlock(IDirect3DStateBlock9 **ppSB) { return _orig->EndStateBlock(ppSB); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetClipStatus(const D3DCLIPSTATUS9 *pClipStatus) { return _orig->SetClipStatus(pClipStatus); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetClipStatus(D3DCLIPSTATUS9 *pClipStatus) { return _orig->GetClipStatus(pClipStatus); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTexture(DWORD Stage, IDirect3DBaseTexture9 **ppTexture) { return _orig->GetTexture(Stage, ppTexture); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTexture(DWORD Stage, IDirect3DBaseTexture9 *pTexture) { const HRESULT hr = _orig->SetTexture(Stage, pTexture); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr) && reshade::has_addon_event<reshade::addon_event::push_descriptors>()) { reshade::api::shader_stage shader_stage = reshade::api::shader_stage::pixel; if (Stage >= D3DVERTEXTEXTURESAMPLER0) { shader_stage = reshade::api::shader_stage::vertex; Stage -= D3DVERTEXTEXTURESAMPLER0; } // There are no sampler state objects in D3D9, so cannot deduce a handle to one here meaningfully reshade::api::sampler_with_resource_view descriptor_data = { reshade::api::sampler { 0 }, reshade::api::resource_view { reinterpret_cast<uintptr_t>(pTexture) } }; reshade::invoke_addon_event<reshade::addon_event::push_descriptors>( this, shader_stage, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, shader_stage == reshade::api::shader_stage::vertex ? 0 : 1, reshade::api::descriptor_set_update { {}, Stage, 0, 1, reshade::api::descriptor_type::sampler_with_resource_view, &descriptor_data }); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD *pValue) { return _orig->GetTextureStageState(Stage, Type, pValue); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value) { return _orig->SetTextureStageState(Stage, Type, Value); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD *pValue) { return _orig->GetSamplerState(Sampler, Type, pValue); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value) { return _orig->SetSamplerState(Sampler, Type, Value); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::ValidateDevice(DWORD *pNumPasses) { return _orig->ValidateDevice(pNumPasses); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPaletteEntries(UINT PaletteNumber, const PALETTEENTRY *pEntries) { return _orig->SetPaletteEntries(PaletteNumber, pEntries); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY *pEntries) { return _orig->GetPaletteEntries(PaletteNumber, pEntries); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetCurrentTexturePalette(UINT PaletteNumber) { return _orig->SetCurrentTexturePalette(PaletteNumber); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetCurrentTexturePalette(UINT *PaletteNumber) { return _orig->GetCurrentTexturePalette(PaletteNumber); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetScissorRect(const RECT *pRect) { const HRESULT hr = _orig->SetScissorRect(pRect); #if RESHADE_ADDON if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::bind_scissor_rects>(this, 0, 1, reinterpret_cast<const reshade::api::rect *>(pRect)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetScissorRect(RECT *pRect) { return _orig->GetScissorRect(pRect); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetSoftwareVertexProcessing(BOOL bSoftware) { return _orig->SetSoftwareVertexProcessing(bSoftware); } BOOL STDMETHODCALLTYPE Direct3DDevice9::GetSoftwareVertexProcessing() { return _orig->GetSoftwareVertexProcessing(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetNPatchMode(float nSegments) { return _orig->SetNPatchMode(nSegments); } float STDMETHODCALLTYPE Direct3DDevice9::GetNPatchMode() { return _orig->GetNPatchMode(); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount) { #if RESHADE_ADDON if (PrimitiveType != _current_prim_type) { _current_prim_type = PrimitiveType; const reshade::api::dynamic_state state = reshade::api::dynamic_state::primitive_topology; const uint32_t value = static_cast<uint32_t>(reshade::d3d9::convert_primitive_topology(PrimitiveType)); reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(this, 1, &state, &value); } if (reshade::invoke_addon_event<reshade::addon_event::draw>(this, reshade::d3d9::calc_vertex_from_prim_count(PrimitiveType, PrimitiveCount), 1, StartVertex, 0)) return D3D_OK; #endif return _orig->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT StartIndex, UINT PrimitiveCount) { #if RESHADE_ADDON if (PrimitiveType != _current_prim_type) { _current_prim_type = PrimitiveType; const reshade::api::dynamic_state state = reshade::api::dynamic_state::primitive_topology; const uint32_t value = static_cast<uint32_t>(reshade::d3d9::convert_primitive_topology(PrimitiveType)); reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(this, 1, &state, &value); } if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(this, reshade::d3d9::calc_vertex_from_prim_count(PrimitiveType, PrimitiveCount), 1, StartIndex, BaseVertexIndex, 0)) return D3D_OK; #endif return _orig->DrawIndexedPrimitive(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, StartIndex, PrimitiveCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride) { #if RESHADE_ADDON if (PrimitiveType != _current_prim_type) { _current_prim_type = PrimitiveType; const reshade::api::dynamic_state state = reshade::api::dynamic_state::primitive_topology; const uint32_t value = static_cast<uint32_t>(reshade::d3d9::convert_primitive_topology(PrimitiveType)); reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(this, 1, &state, &value); } if (reshade::invoke_addon_event<reshade::addon_event::draw>(this, reshade::d3d9::calc_vertex_from_prim_count(PrimitiveType, PrimitiveCount), 1, 0, 0)) return D3D_OK; #endif return _orig->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, const void *pIndexData, D3DFORMAT IndexDataFormat, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride) { #if RESHADE_ADDON if (PrimitiveType != _current_prim_type) { _current_prim_type = PrimitiveType; const reshade::api::dynamic_state state = reshade::api::dynamic_state::primitive_topology; const uint32_t value = static_cast<uint32_t>(reshade::d3d9::convert_primitive_topology(PrimitiveType)); reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(this, 1, &state, &value); } if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(this, reshade::d3d9::calc_vertex_from_prim_count(PrimitiveType, PrimitiveCount), 1, 0, 0, 0)) return D3D_OK; #endif return _orig->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9 *pDestBuffer, IDirect3DVertexDeclaration9 *pVertexDecl, DWORD Flags) { return _orig->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexDeclaration(const D3DVERTEXELEMENT9 *pVertexElements, IDirect3DVertexDeclaration9 **ppDecl) { #if RESHADE_ADDON auto desc = reshade::d3d9::convert_pipeline_desc(pVertexElements); std::vector<D3DVERTEXELEMENT9> internal_elements; if (reshade::invoke_addon_event<reshade::addon_event::create_pipeline>(this, desc, 0, nullptr)) { reshade::d3d9::convert_pipeline_desc(desc, internal_elements); pVertexElements = internal_elements.data(); } #endif const HRESULT hr = _orig->CreateVertexDeclaration(pVertexElements, ppDecl); if (SUCCEEDED(hr)) { assert(ppDecl != nullptr); #if RESHADE_ADDON reshade::invoke_addon_event<reshade::addon_event::init_pipeline>(this, desc, 0, nullptr, to_handle(*ppDecl)); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateVertexDeclaration" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexDeclaration(IDirect3DVertexDeclaration9 *pDecl) { const HRESULT hr = _orig->SetVertexDeclaration(pDecl); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::bind_pipeline>(this, reshade::api::pipeline_stage::input_assembler, to_handle(pDecl)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexDeclaration(IDirect3DVertexDeclaration9 **ppDecl) { return _orig->GetVertexDeclaration(ppDecl); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetFVF(DWORD FVF) { return _orig->SetFVF(FVF); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetFVF(DWORD *pFVF) { return _orig->GetFVF(pFVF); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexShader(const DWORD *pFunction, IDirect3DVertexShader9 **ppShader) { #if RESHADE_ADDON if (pFunction == nullptr) return D3DERR_INVALIDCALL; // First token should be version token (https://docs.microsoft.com/windows-hardware/drivers/display/version-token), so verify its shader type assert((pFunction[0] >> 16) == 0xFFFE); reshade::api::pipeline_desc desc = { reshade::api::pipeline_stage::vertex_shader }; desc.graphics.vertex_shader.code = pFunction; // Find the end token to calculate token stream size (https://docs.microsoft.com/windows-hardware/drivers/display/end-token) desc.graphics.vertex_shader.code_size = sizeof(DWORD); for (int i = 0; pFunction[i] != 0x0000FFFF; ++i) desc.graphics.vertex_shader.code_size += sizeof(DWORD); if (reshade::invoke_addon_event<reshade::addon_event::create_pipeline>(this, desc, 0, nullptr)) { pFunction = static_cast<const DWORD *>(desc.graphics.vertex_shader.code); } #endif const HRESULT hr = _orig->CreateVertexShader(pFunction, ppShader); if (SUCCEEDED(hr)) { assert(ppShader != nullptr); #if RESHADE_ADDON reshade::invoke_addon_event<reshade::addon_event::init_pipeline>(this, desc, 0, nullptr, to_handle(*ppShader)); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreateVertexShader" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShader(IDirect3DVertexShader9 *pShader) { const HRESULT hr = _orig->SetVertexShader(pShader); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::bind_pipeline>(this, reshade::api::pipeline_stage::vertex_shader, to_handle(pShader)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShader(IDirect3DVertexShader9 **ppShader) { return _orig->GetVertexShader(ppShader); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount) { const HRESULT hr = _orig->SetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::push_constants>( this, reshade::api::shader_stage::vertex, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, 2, StartRegister, Vector4fCount, reinterpret_cast<const uint32_t *>(pConstantData)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount) { return _orig->GetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount) { const HRESULT hr = _orig->SetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::push_constants>( this, reshade::api::shader_stage::vertex, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, 3, StartRegister, Vector4iCount, reinterpret_cast<const uint32_t *>(pConstantData)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount) { return _orig->GetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount) { const HRESULT hr = _orig->SetVertexShaderConstantB(StartRegister, pConstantData, BoolCount); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::push_constants>( this, reshade::api::shader_stage::vertex, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, 4, StartRegister, BoolCount, reinterpret_cast<const uint32_t *>(pConstantData)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount) { return _orig->GetVertexShaderConstantB(StartRegister, pConstantData, BoolCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 *pStreamData, UINT OffsetInBytes, UINT Stride) { const HRESULT hr = _orig->SetStreamSource(StreamNumber, pStreamData, OffsetInBytes, Stride); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr) && reshade::has_addon_event<reshade::addon_event::bind_vertex_buffers>()) { const reshade::api::resource buffer = to_handle(pStreamData); const uint64_t offset_64 = OffsetInBytes; reshade::invoke_addon_event<reshade::addon_event::bind_vertex_buffers>(this, StreamNumber, 1, &buffer, &offset_64, &Stride); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 **ppStreamData, UINT *OffsetInBytes, UINT *pStride) { return _orig->GetStreamSource(StreamNumber, ppStreamData, OffsetInBytes, pStride); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetStreamSourceFreq(UINT StreamNumber, UINT Divider) { return _orig->SetStreamSourceFreq(StreamNumber, Divider); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetStreamSourceFreq(UINT StreamNumber, UINT *Divider) { return _orig->GetStreamSourceFreq(StreamNumber, Divider); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetIndices(IDirect3DIndexBuffer9 *pIndexData) { const HRESULT hr = _orig->SetIndices(pIndexData); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr) && reshade::has_addon_event<reshade::addon_event::bind_index_buffer>()) { uint32_t index_size = 0; if (pIndexData != nullptr) { D3DINDEXBUFFER_DESC desc; pIndexData->GetDesc(&desc); index_size = (desc.Format == D3DFMT_INDEX16) ? 2 : 4; } reshade::invoke_addon_event<reshade::addon_event::bind_index_buffer>(this, to_handle(pIndexData), 0, index_size); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetIndices(IDirect3DIndexBuffer9 **ppIndexData) { return _orig->GetIndices(ppIndexData); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreatePixelShader(const DWORD *pFunction, IDirect3DPixelShader9 **ppShader) { #if RESHADE_ADDON if (pFunction == nullptr) return D3DERR_INVALIDCALL; // First token should be version token (https://docs.microsoft.com/windows-hardware/drivers/display/version-token), so verify its shader type assert((pFunction[0] >> 16) == 0xFFFF); reshade::api::pipeline_desc desc = { reshade::api::pipeline_stage::pixel_shader }; desc.graphics.pixel_shader.code = pFunction; // Find the end token to calculate token stream size (https://docs.microsoft.com/windows-hardware/drivers/display/end-token) desc.graphics.pixel_shader.code_size = sizeof(DWORD); for (int i = 0; pFunction[i] != 0x0000FFFF; ++i) desc.graphics.pixel_shader.code_size += sizeof(DWORD); if (reshade::invoke_addon_event<reshade::addon_event::create_pipeline>(this, desc, 0, nullptr)) { pFunction = static_cast<const DWORD *>(desc.graphics.pixel_shader.code); } #endif const HRESULT hr = _orig->CreatePixelShader(pFunction, ppShader); if (SUCCEEDED(hr)) { assert(ppShader != nullptr); #if RESHADE_ADDON reshade::invoke_addon_event<reshade::addon_event::init_pipeline>(this, desc, 0, nullptr, to_handle(*ppShader)); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9::CreatePixelShader" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShader(IDirect3DPixelShader9 *pShader) { const HRESULT hr = _orig->SetPixelShader(pShader); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::bind_pipeline>(this, reshade::api::pipeline_stage::pixel_shader, to_handle(pShader)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShader(IDirect3DPixelShader9 **ppShader) { return _orig->GetPixelShader(ppShader); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount) { const HRESULT hr = _orig->SetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::push_constants>( this, reshade::api::shader_stage::pixel, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, 5, StartRegister, Vector4fCount, reinterpret_cast<const uint32_t *>(pConstantData)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount) { return _orig->GetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount) { const HRESULT hr = _orig->SetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::push_constants>( this, reshade::api::shader_stage::pixel, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, 6, StartRegister, Vector4iCount, reinterpret_cast<const uint32_t *>(pConstantData)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount) { return _orig->GetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount) { const HRESULT hr = _orig->SetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); #if RESHADE_ADDON && RESHADE_ADDON_LOAD if (SUCCEEDED(hr)) { reshade::invoke_addon_event<reshade::addon_event::push_constants>( this, reshade::api::shader_stage::pixel, // See global pipeline layout specified in 'device_impl::on_init' reshade::d3d9::global_pipeline_layout, 7, StartRegister, BoolCount, reinterpret_cast<const uint32_t *>(pConstantData)); } #endif return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount) { return _orig->GetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawRectPatch(UINT Handle, const float *pNumSegs, const D3DRECTPATCH_INFO *pRectPatchInfo) { return _orig->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawTriPatch(UINT Handle, const float *pNumSegs, const D3DTRIPATCH_INFO *pTriPatchInfo) { return _orig->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::DeletePatch(UINT Handle) { return _orig->DeletePatch(Handle); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateQuery(D3DQUERYTYPE Type, IDirect3DQuery9 **ppQuery) { return _orig->CreateQuery(Type, ppQuery); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetConvolutionMonoKernel(UINT width, UINT height, float *rows, float *columns) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->SetConvolutionMonoKernel(width, height, rows, columns); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::ComposeRects(IDirect3DSurface9 *pSrc, IDirect3DSurface9 *pDst, IDirect3DVertexBuffer9 *pSrcRectDescs, UINT NumRects, IDirect3DVertexBuffer9 *pDstRectDescs, D3DCOMPOSERECTSOP Operation, int Xoffset, int Yoffset) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->ComposeRects(pSrc, pDst, pSrcRectDescs, NumRects, pDstRectDescs, Operation, Xoffset, Yoffset); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::PresentEx(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags) { if (Direct3DSwapChain9::is_presenting_entire_surface(pSourceRect, hDestWindowOverride)) { #if RESHADE_ADDON reshade::invoke_addon_event<reshade::addon_event::present>(this, _implicit_swapchain); #endif _implicit_swapchain->on_present(); } assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->PresentEx(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetGPUThreadPriority(INT *pPriority) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->GetGPUThreadPriority(pPriority); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetGPUThreadPriority(INT Priority) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->SetGPUThreadPriority(Priority); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::WaitForVBlank(UINT iSwapChain) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->WaitForVBlank(0); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CheckResourceResidency(IDirect3DResource9 **pResourceArray, UINT32 NumResources) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->CheckResourceResidency(pResourceArray, NumResources); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetMaximumFrameLatency(UINT MaxLatency) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->SetMaximumFrameLatency(MaxLatency); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetMaximumFrameLatency(UINT *pMaxLatency) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->GetMaximumFrameLatency(pMaxLatency); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CheckDeviceState(HWND hDestinationWindow) { assert(_extended_interface); return static_cast<IDirect3DDevice9Ex *>(_orig)->CheckDeviceState(hDestinationWindow); } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateRenderTargetEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) { assert(_extended_interface); #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_SURFACE, Usage, D3DPOOL_DEFAULT, MultiSample, MultisampleQuality, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, 1, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::render_target)) reshade::d3d9::convert_resource_desc(desc, internal_desc, nullptr, _caps); const HRESULT hr = ((desc.usage & reshade::api::resource_usage::shader_resource) != 0) && !Lockable ? create_surface_replacement(internal_desc, ppSurface, pSharedHandle) : static_cast<IDirect3DDevice9Ex *>(_orig)->CreateRenderTargetEx(internal_desc.Width, internal_desc.Height, internal_desc.Format, internal_desc.MultiSampleType, internal_desc.MultiSampleQuality, Lockable, ppSurface, pSharedHandle, internal_desc.Usage); #else const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(_orig)->CreateRenderTargetEx(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle, Usage); #endif if (SUCCEEDED(hr)) { assert(ppSurface != nullptr); #if RESHADE_ADDON IDirect3DSurface9 *const surface = *ppSurface; #if RESHADE_ADDON_LOAD const auto device_proxy = this; surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); #endif // In case surface was replaced with a texture resource const reshade::api::resource resource = get_resource_from_view(to_handle(surface)); reshade::invoke_addon_event<reshade::addon_event::init_resource>( this, desc, nullptr, reshade::api::resource_usage::render_target, resource); reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, resource, reshade::api::resource_usage::render_target, reshade::api::resource_view_desc(desc.texture.format), to_handle(surface)); InterlockedIncrement(&_ref); register_destruction_callback_d3d9(reinterpret_cast<IDirect3DResource9 *>(resource.handle), [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, resource); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); register_destruction_callback_d3d9(surface, [this, surface]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(surface)); }, to_handle(surface).handle == resource.handle ? 1 : 0); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9Ex::CreateRenderTargetEx" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateOffscreenPlainSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) { assert(_extended_interface); #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_SURFACE, Usage, Pool, D3DMULTISAMPLE_NONE, 0, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, 1, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::general)) reshade::d3d9::convert_resource_desc(desc, internal_desc, nullptr, _caps); const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(_orig)->CreateOffscreenPlainSurfaceEx(internal_desc.Width, internal_desc.Height, internal_desc.Format, internal_desc.Pool, ppSurface, pSharedHandle, internal_desc.Usage); #else const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(_orig)->CreateOffscreenPlainSurfaceEx(Width, Height, Format, Pool, ppSurface, pSharedHandle, Usage); #endif if (SUCCEEDED(hr)) { assert(ppSurface != nullptr); #if RESHADE_ADDON IDirect3DSurface9 *const surface = *ppSurface; #if RESHADE_ADDON_LOAD const auto device_proxy = this; surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); if (reshade::has_addon_event<reshade::addon_event::map_texture_region>()) reshade::hooks::install("IDirect3DSurface9::LockRect", vtable_from_instance(surface), 13, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_LockRect)); if (reshade::has_addon_event<reshade::addon_event::unmap_texture_region>()) reshade::hooks::install("IDirect3DSurface9::UnlockRect", vtable_from_instance(surface), 14, reinterpret_cast<reshade::hook::address>(IDirect3DSurface9_UnlockRect)); #endif const reshade::api::resource resource = get_resource_from_view(to_handle(surface)); reshade::invoke_addon_event<reshade::addon_event::init_resource>( this, desc, nullptr, reshade::api::resource_usage::render_target, resource); reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, resource, reshade::api::resource_usage::render_target, reshade::api::resource_view_desc(desc.texture.format), to_handle(surface)); InterlockedIncrement(&_ref); register_destruction_callback_d3d9(reinterpret_cast<IDirect3DResource9 *>(resource.handle), [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, resource); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); register_destruction_callback_d3d9(surface, [this, surface]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(surface)); }, to_handle(surface).handle == resource.handle ? 1 : 0); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9Ex::CreateOffscreenPlainSurfaceEx" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateDepthStencilSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) { assert(_extended_interface); #if RESHADE_ADDON D3DSURFACE_DESC internal_desc = { Format, D3DRTYPE_SURFACE, Usage, D3DPOOL_DEFAULT, MultiSample, MultisampleQuality, Width, Height }; auto desc = reshade::d3d9::convert_resource_desc(internal_desc, 1, _caps, pSharedHandle != nullptr); if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(this, desc, nullptr, reshade::api::resource_usage::depth_stencil)) reshade::d3d9::convert_resource_desc(desc, internal_desc, nullptr, _caps); const HRESULT hr = ((desc.usage & reshade::api::resource_usage::shader_resource) != 0) ? create_surface_replacement(internal_desc, ppSurface, pSharedHandle) : static_cast<IDirect3DDevice9Ex *>(_orig)->CreateDepthStencilSurfaceEx(internal_desc.Width, internal_desc.Height, internal_desc.Format, internal_desc.MultiSampleType, internal_desc.MultiSampleQuality, Discard, ppSurface, pSharedHandle, internal_desc.Usage); #else const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(_orig)->CreateDepthStencilSurfaceEx(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle, Usage); #endif if (SUCCEEDED(hr)) { assert(ppSurface != nullptr); #if RESHADE_ADDON IDirect3DSurface9 *const surface = *ppSurface; #if RESHADE_ADDON_LOAD const auto device_proxy = this; surface->SetPrivateData(__uuidof(Direct3DDevice9), &device_proxy, sizeof(device_proxy), 0); #endif // In case surface was replaced with a texture resource const reshade::api::resource resource = get_resource_from_view(to_handle(surface)); reshade::invoke_addon_event<reshade::addon_event::init_resource>( this, desc, nullptr, reshade::api::resource_usage::depth_stencil, resource); reshade::invoke_addon_event<reshade::addon_event::init_resource_view>( this, resource, reshade::api::resource_usage::depth_stencil, reshade::api::resource_view_desc(desc.texture.format), to_handle(surface)); InterlockedIncrement(&_ref); register_destruction_callback_d3d9(reinterpret_cast<IDirect3DResource9 *>(resource.handle), [this, resource]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(this, resource); const ULONG ref = InterlockedDecrement(&_ref); assert(ref != 0); }); register_destruction_callback_d3d9(surface, [this, surface]() { reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(this, to_handle(surface)); }, to_handle(surface).handle == resource.handle ? 1 : 0); #endif } else { #if RESHADE_VERBOSE_LOG LOG(WARN) << "IDirect3DDevice9Ex::CreateDepthStencilSurfaceEx" << " failed with error code " << hr << '.'; #endif } return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::ResetEx(D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode) { LOG(INFO) << "Redirecting " << "IDirect3DDevice9Ex::ResetEx" << '(' << "this = " << this << ", pPresentationParameters = " << pPresentationParameters << ", pFullscreenDisplayMode = " << pFullscreenDisplayMode << ')' << " ..."; if (pPresentationParameters == nullptr) return D3DERR_INVALIDCALL; D3DDISPLAYMODEEX fullscreen_mode = { sizeof(fullscreen_mode) }; if (pFullscreenDisplayMode != nullptr) fullscreen_mode = *pFullscreenDisplayMode; D3DPRESENT_PARAMETERS pp = *pPresentationParameters; dump_and_modify_present_parameters(pp, fullscreen_mode, _d3d.get(), _cp.AdapterOrdinal); // Release all resources before performing reset _implicit_swapchain->on_reset(); device_impl::on_reset(); assert(_extended_interface); const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(_orig)->ResetEx(&pp, pp.Windowed ? nullptr : &fullscreen_mode); // Update output values (see https://docs.microsoft.com/windows/win32/api/d3d9/nf-d3d9-idirect3ddevice9ex-resetex) pPresentationParameters->BackBufferWidth = pp.BackBufferWidth; pPresentationParameters->BackBufferHeight = pp.BackBufferHeight; pPresentationParameters->BackBufferFormat = pp.BackBufferFormat; pPresentationParameters->BackBufferCount = pp.BackBufferCount; if (FAILED(hr)) { LOG(ERROR) << "IDirect3DDevice9Ex::ResetEx" << " failed with error code " << hr << '!'; return hr; } device_impl::on_init(pp); _implicit_swapchain->on_init(pp); return hr; } HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDisplayModeEx(UINT iSwapChain, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation) { if (iSwapChain != 0) { LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported."; return D3DERR_INVALIDCALL; } assert(_extended_interface); assert(_implicit_swapchain->_extended_interface); return static_cast<IDirect3DSwapChain9Ex *>(_implicit_swapchain)->GetDisplayModeEx(pMode, pRotation); }
39.296177
299
0.776541
[ "render", "object", "vector" ]
02ef30eb68877ca83f4681769a82f4a85f8a8955
2,655
cpp
C++
archives/books/CP3-materials/ch3/ch3_03_UVa11450_bu.cpp
cbarnson/UVa
0dd73fae656613e28b5aaf5880c5dad529316270
[ "Unlicense", "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
archives/books/CP3-materials/ch3/ch3_03_UVa11450_bu.cpp
cbarnson/UVa
0dd73fae656613e28b5aaf5880c5dad529316270
[ "Unlicense", "MIT" ]
null
null
null
archives/books/CP3-materials/ch3/ch3_03_UVa11450_bu.cpp
cbarnson/UVa
0dd73fae656613e28b5aaf5880c5dad529316270
[ "Unlicense", "MIT" ]
null
null
null
/* UVa 11450 - Wedding Shopping - Bottom Up */ #include <cstdio> #include <cstring> using namespace std; int main() { int i, j, k, TC, M, C; int price[25][25]; // price[g (<= 20)][model (<= 20)] bool reachable[25][210]; // reachable table[g (<= 20)][money (<= 200)] scanf("%d", &TC); while (TC--) { scanf("%d %d", &M, &C); for (i = 0; i < C; i++) { scanf("%d", &price[i][0]); // we store K in price[i][0] for (j = 1; j <= price[i][0]; j++) scanf("%d", &price[i][j]); } memset(reachable, false, sizeof reachable); // clear everything for (i = 1; i <= price[0][0]; i++) // initial values (base cases) if (M - price[0][i] >= 0) // to prevent array index out of bound reachable[0][M - price[0][i]] = true; // using first garment g = 0 for (i = 1; i < C; i++) // for each remaining garment for (j = 0; j < M; j++) if (reachable[i - 1][j]) // a reachable state for (k = 1; k <= price[i][0]; k++) if (j - price[i][k] >= 0) reachable[i][j - price[i][k]] = true; // also a reachable state for (j = 0; j <= M && !reachable[C - 1][j]; j++); // the answer in here if (j == M + 1) printf("no solution\n"); // last row has on bit else printf("%d\n", M - j); } } // return 0; /* // same as above, but using space saving trick #include <cstdio> #include <cstring> using namespace std; int main() { int i, j, k, TC, M, C, cur; int price[25][25]; bool reachable[2][210]; // reachable table[ONLY TWO ROWS][money (<= 200)] scanf("%d", &TC); while (TC--) { scanf("%d %d", &M, &C); for (i = 0; i < C; i++) { scanf("%d", &price[i][0]); for (j = 1; j <= price[i][0]; j++) scanf("%d", &price[i][j]); } memset(reachable, false, sizeof reachable); for (i = 1; i <= price[0][0]; i++) if (M - price[0][i] >= 0) reachable[0][M - price[0][i]] = true; cur = 1; // we start with this row for (i = 1; i < C; i++) { memset(reachable[cur], false, sizeof reachable[cur]); // reset row for (j = 0; j < M; j++) if (reachable[!cur][j]) // notice !cur for (k = 1; k <= price[i][0]; k++) if (j - price[i][k] >= 0) reachable[cur][j - price[i][k]] = true; cur = !cur; // flip the two rows } for (j = 0; j <= M && !reachable[!cur][j]; j++); // notice !cur if (j == M + 1) printf("no solution\n"); // last row has on bit else printf("%d\n", M - j); } } // return 0; */
35.878378
75
0.462524
[ "model" ]
02f1ed5ac1f95c0661e44d3dc84163dd58dc4857
4,500
cpp
C++
torch/csrc/api/src/optim/sgd.cpp
YifanShenSZ/pytorch
b4232f7cbe407909f9d95b91304c73fdc4c66a50
[ "Intel" ]
null
null
null
torch/csrc/api/src/optim/sgd.cpp
YifanShenSZ/pytorch
b4232f7cbe407909f9d95b91304c73fdc4c66a50
[ "Intel" ]
null
null
null
torch/csrc/api/src/optim/sgd.cpp
YifanShenSZ/pytorch
b4232f7cbe407909f9d95b91304c73fdc4c66a50
[ "Intel" ]
null
null
null
#include <torch/optim/sgd.h> #include <torch/csrc/autograd/variable.h> #include <torch/nn/pimpl.h> #include <torch/optim/optimizer.h> #include <torch/optim/serialize.h> #include <torch/types.h> #include <torch/utils.h> #include <ATen/ATen.h> #include <c10/util/irange.h> #include <functional> namespace torch { namespace optim { SGDOptions::SGDOptions(double lr) : lr_(lr) {} bool operator==(const SGDOptions& lhs, const SGDOptions& rhs) { return (lhs.lr() == rhs.lr()) && (lhs.momentum() == rhs.momentum()) && (lhs.dampening() == rhs.dampening()) && (lhs.weight_decay() == rhs.weight_decay()) && (lhs.nesterov() == rhs.nesterov()); } void SGDOptions::serialize(torch::serialize::OutputArchive& archive) const { _TORCH_OPTIM_SERIALIZE_TORCH_ARG(lr); _TORCH_OPTIM_SERIALIZE_TORCH_ARG(momentum); _TORCH_OPTIM_SERIALIZE_TORCH_ARG(dampening); _TORCH_OPTIM_SERIALIZE_TORCH_ARG(weight_decay); _TORCH_OPTIM_SERIALIZE_TORCH_ARG(nesterov); } void SGDOptions::serialize(torch::serialize::InputArchive& archive) { _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(double, lr); _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(double, momentum); _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(double, dampening); _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(double, weight_decay); _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(bool, nesterov); } double SGDOptions::get_lr() const { return lr(); } void SGDOptions::set_lr(const double lr) { this->lr(lr); } bool operator==(const SGDParamState& lhs, const SGDParamState& rhs) { return torch::equal(lhs.momentum_buffer(), rhs.momentum_buffer()); } void SGDParamState::serialize(torch::serialize::OutputArchive& archive) const { _TORCH_OPTIM_SERIALIZE_TORCH_ARG(momentum_buffer); } void SGDParamState::serialize(torch::serialize::InputArchive& archive) { _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(Tensor, momentum_buffer); } Tensor SGD::step(LossClosure closure) { NoGradGuard no_grad; Tensor loss = {}; if (closure != nullptr) { at::AutoGradMode enable_grad(true); loss = closure(); } for (auto& group : param_groups_) { auto& options = static_cast<SGDOptions&>(group.options()); auto weight_decay = options.weight_decay(); auto momentum = options.momentum(); auto dampening = options.dampening(); auto nesterov = options.nesterov(); for (auto& p : group.params()) { if (!p.grad().defined()) { continue; } auto d_p = p.grad().data(); if (weight_decay != 0) { d_p = d_p.add(p.data(), weight_decay); } if (momentum != 0) { Tensor buf; auto param_state = state_.find(c10::guts::to_string(p.unsafeGetTensorImpl())); if (param_state == state_.end()) { buf = torch::clone(d_p).detach(); auto state = std::make_unique<SGDParamState>(); state->momentum_buffer(buf); state_[c10::guts::to_string(p.unsafeGetTensorImpl())] = std::move(state); } else { buf = static_cast<SGDParamState&>(*param_state->second) .momentum_buffer(); buf.mul_(momentum).add_(d_p, 1 - dampening); } if (nesterov) { d_p = d_p.add(buf, momentum); } else { d_p = buf; } } p.data().add_(d_p, -1 * options.lr()); } } return loss; } void SGD::save(serialize::OutputArchive& archive) const { serialize(*this, archive); } void SGD::load(serialize::InputArchive& archive) { IValue pytorch_version; if (archive.try_read("pytorch_version", pytorch_version)) { serialize(*this, archive); } else { // deserializing archives saved in old format (prior to // version 1.5.0) TORCH_WARN( "Your serialized SGD optimizer is still using the old serialization format. " "You should re-save your SGD optimizer to use the new serialization format."); std::vector<Tensor> momentum_buffers; torch::optim::serialize(archive, "momentum_buffers", momentum_buffers); // since there were no param_groups prior to version 1.5.0, assuming all // tensors are now in one param_group std::vector<Tensor> params = param_groups_.at(0).params(); for (const auto idx : c10::irange(momentum_buffers.size())) { auto state = std::make_unique<SGDParamState>(); state->momentum_buffer(momentum_buffers[idx]); state_[c10::guts::to_string(params[idx].unsafeGetTensorImpl())] = std::move(state); } } } } // namespace optim } // namespace torch
32.142857
86
0.670667
[ "vector" ]