hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
809df21ef9969a171e4b2592b26fb7645d008cdc
32,988
tcc
C++
libraries/math/test/tcc/Tensor_test.tcc
siddu1998/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
1
2018-11-08T06:19:31.000Z
2018-11-08T06:19:31.000Z
libraries/math/test/tcc/Tensor_test.tcc
vishnoitanuj/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
null
null
null
libraries/math/test/tcc/Tensor_test.tcc
vishnoitanuj/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
1
2019-12-19T10:02:48.000Z
2019-12-19T10:02:48.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: Tensor_test.tcc (math_test) // Authors: Ofer Dekel, Kern Handa // //////////////////////////////////////////////////////////////////////////////////////////////////// // math #include "TensorOperations.h" // utilities #include "testing.h" // stl #include <cstdlib> // rand template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorIndexer() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto S = T.GetSubTensor({ 0,1,2 }, { 2,2,2 }); T(1, 2, 3) = 7; T(0, 1, 2) = 8; auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,8,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,7 } } }; auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 8, 4 },{ 3, 4 } }, { { 3, 4 },{ 3, 7 } } }; testing::ProcessTest("Tensor::operator()", T == R1 && S == R2); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorSize() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); auto S = T.GetSubTensor({ 0,1,2 }, { 2,2,2 }); testing::ProcessTest("Tensor::Size", T.Size() == 10*20*30 && S.Size() == 2*2*2); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorNumRows() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); testing::ProcessTest("Tensor::NumRows", T.NumRows() == 10); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorNumColumns() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); testing::ProcessTest("Tensor::NumColumns", T.NumColumns() == 20); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorNumChannels() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); testing::ProcessTest("Tensor::NumChannels", T.NumChannels() == 30); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetShape() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); auto shape = T.GetShape(); testing::ProcessTest("Tensor::GetShape", shape == math::TensorShape{10,20,30}); } template<typename ElementType> void TestTensorNumSlices() { math::ColumnRowChannelTensor<ElementType> T(10, 20, 30); math::ChannelColumnRowTensor<ElementType> S(10, 20, 30); testing::ProcessTest("Tensor::NumSlices", math::NumSlices<math::Dimension::column, math::Dimension::row>(T) == 30 && math::NumSlices<math::Dimension::row, math::Dimension::column>(T) == 30 && math::NumSlices<math::Dimension::column, math::Dimension::channel>(T) == 10 && math::NumSlices<math::Dimension::channel, math::Dimension::column>(T) == 10 && math::NumSlices<math::Dimension::channel, math::Dimension::row>(S) == 20 && math::NumSlices<math::Dimension::row, math::Dimension::channel>(S) == 20 && math::NumSlices<math::Dimension::column, math::Dimension::channel>(S) == 10 && math::NumSlices<math::Dimension::channel, math::Dimension::column>(S) == 10); auto test1DNumSlices = [](auto T) { testing::ProcessTest("Tensor::NumSlices", math::NumSlices<math::Dimension::channel>(T) == (10 * 20) && math::NumSlices<math::Dimension::column>(T) == (10 * 30) && math::NumSlices<math::Dimension::row>(T) == (20 * 30)); }; test1DNumSlices(T); test1DNumSlices(S); } template<typename ElementType> void TestTensorNumPrimarySlices() { math::ColumnRowChannelTensor<ElementType> T(10, 20, 30); math::ChannelColumnRowTensor<ElementType> S(10, 20, 30); testing::ProcessTest("Tensor::NumPrimarySlices", T.NumPrimarySlices() == 30 && S.NumPrimarySlices() == 10); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorIsEqual() { auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("Tensor::IsEqual", S.IsEqual(T) && T.GetSubTensor({ 0,1,2 }, { 2,2,2 }).IsEqual(S.GetSubTensor({ 0,1,2 }, { 2,2,2 }))); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorEqualityOperator() { auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("Tensor::operator==", T == S && T.GetSubTensor({ 0,1,2 }, {2,2,2}) == S.GetSubTensor({ 0,1,2 }, { 2,2,2 })); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorInequalityOoperator() { auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,8,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto U = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("Tensor::operator!=", T != S && T.GetSubTensor({ 0,1,2 }, { 2,2,2 }) != S.GetSubTensor({ 0,1,2 }, { 2,2,2 }) && T != U); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetConstReference() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; auto S = T.GetSubTensor({ 0,1,2 }, { 2,2,2 }); testing::ProcessTest("Tensor::operator==", T == T.GetConstReference() && S == S.GetConstReference()); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetSubTensor() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2>(4, 6, 8); auto subT = T.GetSubTensor({ 1,2,3 }, { 2,3,4 }); subT.Fill(1); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2>(4, 6, 8); for (size_t i = 1; i < 3; ++i) { for (size_t j = 2; j < 5; ++j) { for (size_t k = 3; k < 7; ++k) { S(i, j, k) = 1; } } } testing::ProcessTest("TestGetSubTensor()", T == S); } template <typename ElementType> void TestTensorGetSlice() { math::ColumnRowChannelTensor<ElementType> T1(3, 4, 5); T1(0, 0, 0) = 1; T1(1, 2, 3) = 2; T1(0, 3, 3) = 3; T1(2, 2, 4) = 3; auto T1Test2DSlice = [](auto T) { auto M1 = math::GetSlice<math::Dimension::column, math::Dimension::row>(T, 3); testing::ProcessTest("TensorReference::GetSlice()", M1(2, 1) == 2 && M1(3, 0) == 3); auto M2 = math::GetSlice<math::Dimension::row, math::Dimension::column>(T, 3); testing::ProcessTest("TensorReference::GetSlice()", M2(1, 2) == 2 && M2(0, 3) == 3); auto M3 = math::GetSlice<math::Dimension::column, math::Dimension::channel>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M3(0, 0) == 1 && M3(3, 3) == 3); auto M4 = math::GetSlice<math::Dimension::channel, math::Dimension::column>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M4(0, 0) == 1 && M4(3, 3) == 3); }; T1Test2DSlice(T1); T1Test2DSlice(T1.GetConstReference()); math::ChannelColumnRowTensor<ElementType> T2(3, 4, 5); T2(0, 0, 0) = 1; T2(1, 2, 3) = 2; T2(0, 3, 3) = 3; T2(2, 2, 4) = 4; auto T2Test2DSlice = [](auto T) { auto M1 = math::GetSlice<math::Dimension::column, math::Dimension::channel>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M1(0, 0) == 1 && M1(3, 3) == 3); auto M2 = math::GetSlice<math::Dimension::channel, math::Dimension::column>(T, 0); testing::ProcessTest("TensorReference::GetSlice()", M2(0, 0) == 1 && M2(3, 3) == 3); auto M3 = math::GetSlice<math::Dimension::row, math::Dimension::channel>(T, 2); testing::ProcessTest("TensorReference::GetSlice()", M3(1, 3) == 2 && M3(2, 4) == 4); auto M4 = math::GetSlice<math::Dimension::channel, math::Dimension::row>(T, 2); testing::ProcessTest("TensorReference::GetSlice()", M4(3, 1) == 2 && M4(4, 2) == 4); }; T2Test2DSlice(T2); T2Test2DSlice(T2.GetConstReference()); auto vectorSliceTest = [](auto _) { using TensorType = decltype(_); // T = numpy.arange(5 * 7 * 11).reshape(5, 7, 11) TensorType T(5, 7, 11); for (unsigned i = 0; i < 5; ++i) { for (unsigned j = 0; j < 7; ++j) { for (unsigned k = 0; k < 11; ++k) { T(i, j, k) = static_cast<typename TensorType::TensorElementType>(k + j * 11 + i * 77); } } } auto test1DGetSlice = [](auto T) { // equivalent of NumPy's T[4, 6, ...] auto V1 = math::GetSlice<math::Dimension::channel>(T, 4, 6); testing::ProcessTest("TensorReference::GetSlice()", V1 == math::ColumnVector<ElementType>({ 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384 })); // equivalent of NumPy's T[4, ..., 8] auto V2 = math::GetSlice<math::Dimension::column>(T, 4, 8); testing::ProcessTest("TensorReference::GetSlice()", V2 == math::ColumnVector<ElementType>({ 316, 327, 338, 349, 360, 371, 382 })); // equivalent of NumPy's T[..., 6, 8] auto V3 = math::GetSlice<math::Dimension::row>(T, 6, 8); testing::ProcessTest("TensorReference::GetSlice()", V3 == math::ColumnVector<ElementType>({ 74, 151, 228, 305, 382 })); }; test1DGetSlice(T); test1DGetSlice(T.GetConstReference()); typename TensorType::TensorElementType originalElementVal = 0; // T[..., 6, 8][0] = 0 auto V1 = math::GetSlice<math::Dimension::channel>(T, 4, 6); std::swap(originalElementVal, V1[0]); testing::ProcessTest("TensorReference::GetSlice() after modification", V1 == math::ColumnVector<ElementType>({ 0, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384 })); testing::ProcessTest("T(4, 6, 0) == 0", T(4, 6, 0) == 0); std::swap(originalElementVal, V1[0]); // T[4..., 8][0] = 0 auto V2 = math::GetSlice<math::Dimension::column>(T, 4, 8); std::swap(originalElementVal, V2[0]); testing::ProcessTest("TensorReference::GetSlice() after modification", V2 == math::ColumnVector<ElementType>({ 0, 327, 338, 349, 360, 371, 382 })); testing::ProcessTest("T(4, 0, 8) == 0", T(4, 0, 8) == 0); std::swap(originalElementVal, V2[0]); // T[4, 6, ...][0] = 0 auto V3 = math::GetSlice<math::Dimension::row>(T, 6, 8); std::swap(originalElementVal, V3[0]); testing::ProcessTest("TensorReference::GetSlice() after modification", V3 == math::ColumnVector<ElementType>({ 0, 151, 228, 305, 382 })); testing::ProcessTest("T(0, 6, 8) == 0", T(0, 6, 8) == 0); std::swap(originalElementVal, V3[0]); }; vectorSliceTest(math::ChannelColumnRowTensor<ElementType>{}); vectorSliceTest(math::ColumnRowChannelTensor<ElementType>{}); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGetPrimarySlice(){} template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorReferenceAsVector() { math::ChannelColumnRowTensor<ElementType> T(3, 4, 2); T(0, 0, 0) = 1; T(0, 0, 1) = 2; T(0, 1, 0) = 3; T(0, 1, 1) = 4; math::ColumnRowChannelTensor<ElementType> S(T); auto u = T.ReferenceAsVector(); auto v = S.ReferenceAsVector(); math::RowVector<ElementType> r1{ 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; math::RowVector<ElementType> r2{ 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; testing::ProcessTest("TensorReference::ReferenceAsVector()", u == r1 && v == r2); } template<typename ElementType> void TestTensorReferenceAsMatrix() { math::ChannelColumnRowTensor<ElementType> T(3, 4, 2); T(0, 0, 0) = 1; T(0, 0, 1) = 2; T(0, 1, 0) = 3; T(0, 1, 1) = 4; math::ColumnRowChannelTensor<ElementType> S(T); auto M = T.ReferenceAsMatrix(); auto N = S.ReferenceAsMatrix(); math::RowMatrix<ElementType> R1 { { 1, 2, 3, 4, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 } }; math::RowMatrix<ElementType> R2 { { 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; testing::ProcessTest("TensorReference::ReferenceAsMatrix", M == R1 && N == R2); } template <typename ElementType> void TestTensorReferenceAsMatrixCopy() { math::ChannelColumnRowTensor<ElementType> T(2, 4, 1); float x = 1; for (size_t i = 0; i < 2; i++) { for (size_t j = 0; j < 4; j++) { T(i, j, 0) = x++; } } math::RowMatrix<ElementType> E{ { 1, 5 }, { 2, 6 }, { 3, 7 }, { 4, 8 } }; auto r = T.GetConstReference(); auto result = math::RowMatrix<ElementType>(r.ReferenceAsMatrix().Transpose()); testing::ProcessTest("TensorReference::ReferenceAsMatrix.Transpose and copy", result.IsEqual(E)); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorCopyFrom() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; math::Tensor<ElementType, dimension0, dimension1, dimension2> S(2, 3, 4); S.CopyFrom(T); math::Tensor<ElementType, math::Dimension::column, math::Dimension::row, math::Dimension::channel> S2(2, 3, 4); S2.CopyFrom(T); auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; auto N = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 5,6 },{ 9,0 } }, { { 4,5 },{ 7,8 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).CopyFrom(N); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,5,6 },{ 9,0,9,0 } }, { { 3,4,5,6 },{ 7,8,4,5 },{ 1,2,7,8 } } }; testing::ProcessTest("TensorReference::CopyFrom", S == T && S2 == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorReset() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Reset(); math::Tensor<ElementType, dimension0, dimension1, dimension2> S(2, 3, 4); auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Reset(); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,0,0 },{ 9,0,0,0 } }, { { 3,4,5,6 },{ 7,8,0,0 },{ 1,2,0,0 } } }; testing::ProcessTest("TensorReference::Reset", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorFill() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Fill (3); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } }, { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Fill(3); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,3,3 },{ 9,0,3,3 } }, { { 3,4,5,6 },{ 7,8,3,3 },{ 1,2,3,3 } } }; testing::ProcessTest("TensorReference::Fill", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorGenerate() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Generate([]()->ElementType {return 3; }); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } }, { { 3,3,3,3 },{ 3,3,3,3 },{ 3,3,3,3 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Generate([]()->ElementType {return 3; }); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,3,3 },{ 9,0,3,3 } }, { { 3,4,5,6 },{ 7,8,3,3 },{ 1,2,3,3 } } }; testing::ProcessTest("TensorReference::Generate", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorTransform() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T.Transform([](ElementType x) {return 2*x; }); auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 2,4,6,8 },{ 10,12,14,16 },{ 18,0,2,4 } }, { { 6,8,10,12 },{ 14,16,18,0 },{ 2,4,6,8 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }).Transform([](ElementType x) {return 2 * x; }); auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,14,16 },{ 9,0,2,4 } }, { { 3,4,5,6 },{ 7,8,18,0 },{ 1,2,6,8 } } }; testing::ProcessTest("TensorReference::Transform", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorPlusEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T += 2; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,4,5,6 },{ 7,8,9,10 },{ 11,2,3,4 } }, { { 5,6,7,8 },{ 9,10,11,2 },{ 3,4,5,6 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) += 2; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,9,10 },{ 9,0,3,4 } }, { { 3,4,5,6 },{ 7,8,11,2 },{ 1,2,5,6 } } }; testing::ProcessTest("TensorReference::operator+=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorMinusEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T -= -2; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 3,4,5,6 },{ 7,8,9,10 },{ 11,2,3,4 } }, { { 5,6,7,8 },{ 9,10,11,2 },{ 3,4,5,6 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) -= -2; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,9,10 },{ 9,0,3,4 } }, { { 3,4,5,6 },{ 7,8,11,2 },{ 1,2,5,6 } } }; testing::ProcessTest("TensorReference::operator-=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorTimesEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T *= 2; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 2,4,6,8 },{ 10,12,14,16 },{ 18,0,2,4 } }, { { 6,8,10,12 },{ 14,16,18,0 },{ 2,4,6,8 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) *= 2; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,14,16 },{ 9,0,2,4 } }, { { 3,4,5,6 },{ 7,8,18,0 },{ 1,2,6,8 } } }; testing::ProcessTest("TensorReference::operator*=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorDivideEqualsOperator() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; T /=0.5; auto S = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 2,4,6,8 },{ 10,12,14,16 },{ 18,0,2,4 } }, { { 6,8,10,12 },{ 14,16,18,0 },{ 2,4,6,8 } } }; auto M = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,7,8 },{ 9,0,1,2 } }, { { 3,4,5,6 },{ 7,8,9,0 },{ 1,2,3,4 } } }; M.GetSubTensor({ 0,1,2 }, { 2,2,2 }) /= 0.5; auto R = math::Tensor<ElementType, dimension0, dimension1, dimension2> { { { 1,2,3,4 },{ 5,6,14,16 },{ 9,0,2,4 } }, { { 3,4,5,6 },{ 7,8,18,0 },{ 1,2,6,8 } } }; testing::ProcessTest("TensorReference::operator/=", S == T && M == R); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2, math::ImplementationType implementation> void TestTensorVectorAddUpdate() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); auto v1 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2 }; math::AddUpdate<math::Dimension::row, implementation>(v1, T); auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 }, { 1,1,1,1 }, { 1,1,1,1 } }, { { 2,2,2,2 }, { 2,2,2,2 }, { 2,2,2,2 } } }; testing::ProcessTest("void TestTensorVectorAddUpdate()", T == R1); T.Fill(0); auto v2 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3 }; math::AddUpdate<math::Dimension::column, implementation>(v2, T); auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } }, { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } } }; testing::ProcessTest("void TestTensorVectorAddUpdate()", T == R2); T.Fill(0); auto v3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3,4 }; math::AddUpdate<math::Dimension::channel, implementation>(v3, T); auto R3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; testing::ProcessTest("void TestTensorVectorAddUpdate()", T == R3); // subtensors auto TT = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto TR = TT.GetSubTensor({ 5,3,1 }, {2,3,4}); TR.Fill(0); math::AddUpdate<math::Dimension::row, implementation>(v1, TR); testing::ProcessTest("void TestTensorVectorAddUpdate() with subtensor", TR == R1); TR.Fill(0); math::AddUpdate<math::Dimension::column, implementation>(v2, TR); testing::ProcessTest("void TestTensorVectorAddUpdate() with subtensor", TR == R2); TR.Fill(0); math::AddUpdate<math::Dimension::channel, implementation>(v3, TR); testing::ProcessTest("void TestTensorVectorAddUpdate() with subtensor", TR == R3); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2, math::ImplementationType implementation> void TestTensorVectorMultiply() { auto implementationName = math::Internal::MatrixOperations<implementation>::GetImplementationName(); auto T1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T1.Fill(1); auto v1 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2 }; math::ScaleUpdate<math::Dimension::row, implementation>(v1, T1); auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 },{ 1,1,1,1 },{ 1,1,1,1 } }, { { 2,2,2,2 },{ 2,2,2,2 },{ 2,2,2,2 } } }; auto T2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T2.Fill(1); auto v2 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3 }; math::ScaleUpdate<math::Dimension::column, implementation>(v2, T2); auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } }, { { 1,1,1,1 },{ 2,2,2,2 },{ 3,3,3,3 } } }; auto T3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T3.Fill(1); auto v3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3,4 }; math::ScaleUpdate<math::Dimension::channel, implementation>(v3, T3); auto R3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } }, { { 1,2,3,4 },{ 1,2,3,4 },{ 1,2,3,4 } } }; // subtensors auto S1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto M1 = S1.GetSubTensor({ 5,3,1 }, { 2,3,4 }); M1.Fill(1); math::ScaleUpdate<math::Dimension::row, implementation>(v1, M1); auto S2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto M2 = S2.GetSubTensor({ 5,3,1 }, { 2,3,4 }); M2.Fill(1); math::ScaleUpdate<math::Dimension::column, implementation>(v2, M2); auto S3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto M3 = S3.GetSubTensor({ 5,3,1 }, { 2,3,4 }); M3.Fill(1); math::ScaleUpdate<math::Dimension::channel, implementation>(v3, M3); testing::ProcessTest(implementationName + "::Multiply(Vector, Tensor)", T1 == R1 && T2 == R2 && T3 == R3 && M1 == R1 && M2 == R2 && M3 == R3); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2, math::ImplementationType implementation> void TestTensorVectorScaleAddUpdate() { auto T = math::Tensor<ElementType, dimension0, dimension1, dimension2>(2, 3, 4); T.Fill(1); auto s1 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2 }; auto b1 = math::Vector<ElementType, math::VectorOrientation::row>{ 3,4 }; math::ScaleAddUpdate<math::Dimension::row, implementation>(s1, b1, T); auto R1 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 4,4,4,4 },{ 4,4,4,4 },{ 4,4,4,4 } }, { { 6,6,6,6 },{ 6,6,6,6 },{ 6,6,6,6 } } }; testing::ProcessTest("void TestTensorVectorScaleAddUpdate()", T == R1); T.Fill(1); auto s2 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3 }; auto b2 = math::Vector<ElementType, math::VectorOrientation::row>{ 4,5,6 }; math::ScaleAddUpdate<math::Dimension::column, implementation>(s2, b2, T); auto R2 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 5,5,5,5 },{ 7,7,7,7 },{ 9,9,9,9 } }, { { 5,5,5,5 },{ 7,7,7,7 },{ 9,9,9,9 } } }; testing::ProcessTest("void TestTensorVectorScaleAddUpdate()", T == R2); T.Fill(1); auto s3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,2,3,4 }; auto b3 = math::Vector<ElementType, math::VectorOrientation::row>{ 1,1,2,2 }; math::ScaleAddUpdate<math::Dimension::channel, implementation>(s3, b3, T); auto R3 = math::Tensor<ElementType, dimension0, dimension1, dimension2>{ { { 2,3,5,6 },{ 2,3,5,6 },{ 2,3,5,6 } }, { { 2,3,5,6 },{ 2,3,5,6 },{ 2,3,5,6 } } }; testing::ProcessTest("void TestTensorVectorScaleAddUpdate()", T == R3); // subtensors auto TT = math::Tensor<ElementType, dimension0, dimension1, dimension2>(10, 10, 10); auto TR = TT.GetSubTensor({ 5,3,1 }, { 2,3,4 }); TR.Fill(1); math::ScaleAddUpdate<math::Dimension::row, implementation>(s1, b1, TR); testing::ProcessTest("void TestTensorVectorScaleAddUpdate() with subtensor", TR == R1); TR.Fill(1); math::ScaleAddUpdate<math::Dimension::column, implementation>(s2, b2, TR); testing::ProcessTest("void TestTensorVectorScaleAddUpdate() with subtensor", TR == R2); TR.Fill(1); math::ScaleAddUpdate<math::Dimension::channel, implementation>(s3, b3, TR); testing::ProcessTest("void TestTensorVectoScaleAddUpdate() with subtensor", TR == R3); } template<typename ElementType, math::Dimension dimension0, math::Dimension dimension1, math::Dimension dimension2> void TestTensorArchiver() { math::Tensor<ElementType, dimension0, dimension1, dimension2> T(10, 20, 30); T(3, 2, 1) = 2.0; T(4, 3, 2) = 3.0; T(3, 3, 3) = 4.0; utilities::SerializationContext context; std::stringstream strstream; utilities::JsonArchiver archiver(strstream); math::TensorArchiver::Write(T, "test", archiver); utilities::JsonUnarchiver unarchiver(strstream, context); math::Tensor<ElementType, dimension0, dimension1, dimension2> Ta(0, 0, 0); math::TensorArchiver::Read(Ta, "test", unarchiver); testing::ProcessTest("void TestTensorArchiver(), write and read tensor", Ta == T); }
37.743707
175
0.563084
siddu1998
80a01ec5d4887398844160006ac6f8eb80bb30ce
18,036
cpp
C++
libraries/plugins/apis/sig_by_key_api/sig_by_key_api.cpp
sityck/steem_paper
9490b7ec929282a63d342a2364d03b268e51d756
[ "MIT" ]
null
null
null
libraries/plugins/apis/sig_by_key_api/sig_by_key_api.cpp
sityck/steem_paper
9490b7ec929282a63d342a2364d03b268e51d756
[ "MIT" ]
null
null
null
libraries/plugins/apis/sig_by_key_api/sig_by_key_api.cpp
sityck/steem_paper
9490b7ec929282a63d342a2364d03b268e51d756
[ "MIT" ]
null
null
null
#include <steem/plugins/sig_by_key_api/sig_by_key_api.hpp> #include <steem/plugins/sig_by_key_api/sig_by_key_api_plugin.hpp> #include <steem/plugins/sig_by_key_api/HibeGS.hpp> #include <iostream> using namespace relicxx; using namespace forwardsec; namespace steem { namespace plugins { namespace sig_by_key { namespace detail { class sig_by_key_api_impl { public: relicResourceHandle relic; PairingGroup group; MasterPublicKey mpk; relicxx::G2 msk; //如果需要新建多个群,则需要修改代码,改为获取对应群组的私钥 //目前的需求只存在一个群组,所以无需修改 //同一个群,提交论文和审稿对应的群公私钥是同一对 GroupSecretKey gsk; UserSecretKey usk; sig_by_key_api_impl() {} ~sig_by_key_api_impl() {} set_group_return set_group(const set_group_args &args) { set_up(); groupSetup(args.groupID, msk, gsk, mpk); //返回gsk给group manager,先假设只返回给一个人 set_group_return final; //此处需保存每个group的私钥 final.a0 = g2ToStr(gsk.a0); final.a2 = g2ToStr(gsk.a2); final.a3 = g2ToStr(gsk.a3); final.a4 = g2ToStr(gsk.a4); final.a5 = g1ToStr(gsk.a5); return final; } join_group_return join_group(const join_group_args &args) { set_up(); string groupID = args.groupID; string userID = args.userID; join(groupID, userID, gsk, usk, mpk); join_group_return final; final.b0 = g2ToStr(usk.b0); final.b3 = g2ToStr(usk.b3); final.b4 = g2ToStr(usk.b4); final.b5 = g1ToStr(usk.b5); return final; } // 返回用户签名 get_sig_return get_sig(const get_sig_args &args) { set_up(); get_sig_return final; UserSecretKey usk; usk.b0 = strToG2(args.b0); usk.b3 = strToG2(args.b3); usk.b4 = strToG2(args.b4); usk.b5 = strToG1(args.b5); Signature sig; relicxx::ZR m = group.hashListToZR(args.m); sign(args.groupID, args.userID, m, usk, sig, mpk); final.c0 = g2ToStr(sig.c0); final.c5 = g1ToStr(sig.c5); final.c6 = g2ToStr(sig.c6); final.e1 = g1ToStr(sig.e1); final.e2 = g2ToStr(sig.e2); final.e3 = gtToStr(sig.e3); final.x = zrToStr(sig.x); final.y = zrToStr(sig.y); final.z = zrToStr(sig.z); return final; } open_paper_return open_paper(const open_paper_args args) { set_up(); open_paper_return final; Signature sig; sig.c0 = strToG2(args.c0); sig.c5 = strToG1(args.c5); sig.c6 = strToG2(args.c6); sig.e1 = strToG1(args.e1); sig.e2 = strToG2(args.e2); sig.e3 = strToGT(args.e3); sig.x = strToZR(args.x); sig.y = strToZR(args.y); sig.z = strToZR(args.z); final.result = open(mpk, gsk, sig, args.userID); return final; } verify_user_return verify_user(const verify_user_args args) { set_up(); verify_user_return final; Signature sig; sig.c0 = strToG2(args.c0); sig.c5 = strToG1(args.c5); sig.c6 = strToG2(args.c6); sig.e1 = strToG1(args.e1); sig.e2 = strToG2(args.e2); sig.e3 = strToGT(args.e3); sig.x = strToZR(args.x); sig.y = strToZR(args.y); sig.z = strToZR(args.z); final.result = verify(group.hashListToZR(args.m), sig, args.groupID, mpk); return final; } test_return test(const test_args &args) { test_return final; setup(mpk, msk); string groupID = "science"; const set_group_args set_args{.groupID = groupID}; set_group_return sgr = set_group(set_args); GroupSecretKey gsk2; gsk2.a0 = strToG2(sgr.a0); gsk2.a2 = strToG2(sgr.a2); gsk2.a3 = strToG2(sgr.a3); gsk2.a4 = strToG2(sgr.a4); gsk2.a5 = strToG1(sgr.a5); const join_group_args join_args{.groupID = "science", .userID = "www"}; join_group_return jgr = join_group(join_args); UserSecretKey usk2; usk2.b0 = strToG2(jgr.b0); usk2.b3 = strToG2(jgr.b3); usk2.b4 = strToG2(jgr.b4); usk2.b5 = strToG1(jgr.b5); string str = "123"; get_sig_args sig_args{.groupID = "science", .userID = "www", .m = str, .b0 = jgr.b0, .b3 = jgr.b3, .b4 = jgr.b4, .b5 = jgr.b5}; get_sig_return gsr = get_sig(sig_args); Signature sig; sig.c0 = strToG2(gsr.c0); sig.c5 = strToG1(gsr.c5); sig.c6 = strToG2(gsr.c6); sig.e1 = strToG1(gsr.e1); sig.e2 = strToG2(gsr.e2); sig.e3 = strToGT(gsr.e3); sig.x = strToZR(gsr.x); sig.y = strToZR(gsr.y); sig.z = strToZR(gsr.z); open_paper_args open_args{.userID = "www", .c0 = gsr.c0, .c5 = gsr.c5, .c6 = gsr.c6, .e1 = gsr.e1, .e2 = gsr.e2, .e3 = gsr.e3, .x = gsr.x, .y = gsr.y, .z = gsr.z}; open_paper_return opr = open_paper(open_args); verify_user_args ver_args{.groupID = "science", .m = str, .c0 = gsr.c0, .c5 = gsr.c5, .c6 = gsr.c6, .e1 = gsr.e1, .e2 = gsr.e2, .e3 = gsr.e3, .x = gsr.x, .y = gsr.y, .z = gsr.z}; if (verify_user(ver_args).result == true && opr.result == true) final.result = "true"; else final.result = "false"; /* GroupSecretKey gsk; UserSecretKey usk; Signature sig; const relicxx::ZR m = group.randomZR(); groupSetup("science", msk, gsk, mpk); join("science", "www", gsk, usk, mpk); sign(m, usk, sig, mpk); verify(m, sig, "science", mpk); if (open(mpk, gsk, sig) && verify(m, sig, "science", mpk)) final.result = "true"; else { final.result = "false"; } */ return final; } private: void setup(MasterPublicKey &mpk, relicxx::G2 &msk) const { const unsigned int l = 4; ZR alpha = group.randomZR(); mpk.g = group.randomG1(); mpk.g2 = group.randomG2(); mpk.hibeg1 = group.exp(mpk.g, alpha); //we setup four level HIBE here,the first level is Group identity,the second level is user identity //the third level is the signed message,the last level is a random identity mpk.l = 4; for (unsigned int i = 0; i <= l; i++) { ZR h = group.randomZR(); mpk.hG2.push_back(group.exp(mpk.g2, h)); } mpk.n = group.randomGT(); msk = group.exp(mpk.g2, alpha); } void groupSetup(const std::string &groupID, const G2 &msk, GroupSecretKey &gsk, const MasterPublicKey &mpk) const { const ZR e = group.hashListToZR(groupID); const ZR r1 = group.randomZR(); gsk.a0 = group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), e)), r1); gsk.a0 = group.mul(msk, gsk.a0); gsk.a2 = group.exp(mpk.hG2.at(2), r1); gsk.a3 = group.exp(mpk.hG2.at(3), r1); ; gsk.a4 = group.exp(mpk.hG2.at(4), r1); gsk.a5 = group.exp(mpk.g, r1); } void join(const string &groupID, const string &userID, const GroupSecretKey &gsk, UserSecretKey &usk, const MasterPublicKey &mpk) const { const ZR gUserID = group.hashListToZR(userID); const ZR gGroupID = group.hashListToZR(groupID); const ZR r2 = group.randomZR(); relicxx::G2 res = group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)); res = group.exp(group.mul(res, group.exp(mpk.hG2.at(2), gUserID)), r2); usk.b0 = group.mul(gsk.a0, group.exp(gsk.a2, gUserID)); usk.b0 = group.mul(usk.b0, res); usk.b3 = group.mul(gsk.a3, group.exp(mpk.hG2.at(3), r2)); usk.b4 = group.mul(gsk.a4, group.exp(mpk.hG2.at(4), r2)); usk.b5 = group.mul(gsk.a5, group.exp(mpk.g, r2)); } void sign(string groupID, string userID, const ZR &m, const UserSecretKey &usk, Signature &sig, const MasterPublicKey &mpk) { const ZR gUserID = group.hashListToZR(userID); const ZR gGroupID = group.hashListToZR(groupID); //G(UserID),G(r4),k are public const ZR r3 = group.randomZR(); //r4 use to blind identity const ZR r4 = group.randomZR(); //user to encrypt identity to the group manager const ZR k = group.randomZR(); relicxx::G2 res = group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)); res = group.mul(res, group.exp(mpk.hG2.at(2), gUserID)); res = group.mul(res, group.exp(mpk.hG2.at(3), m)); res = group.exp(group.mul(res, group.exp(mpk.hG2.at(4), r4)), r3); sig.c0 = group.mul(usk.b0, group.exp(usk.b3, m)); sig.c0 = group.mul(group.mul(sig.c0, group.exp(usk.b4, r4)), res); sig.c5 = group.mul(usk.b5, group.exp(mpk.g, r3)); sig.c6 = group.mul(group.exp(mpk.hG2.at(2), gUserID), group.exp(mpk.hG2.at(4), r4)); sig.e1 = group.exp(mpk.g, k); sig.e2 = group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)), k); sig.e3 = group.exp(group.pair(mpk.g2, mpk.hibeg1), k); sig.e3 = group.mul(sig.e3, group.exp(mpk.n, gUserID)); sig.x = gUserID; sig.y = r4; sig.z = k; } bool verify(const ZR &m, const Signature &sig, const string &groupID, const MasterPublicKey &mpk) { const ZR gGroupID = group.hashListToZR(groupID); const ZR y = sig.y; const ZR t = group.randomZR(); const GT M = group.randomGT(); const ZR k = sig.z; relicxx::G1 d1 = group.exp(mpk.g, t); relicxx::G2 d2 = group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)); d2 = group.exp(group.mul(d2, group.mul(group.exp(mpk.hG2.at(3), m), sig.c6)), t); relicxx::GT delta3 = group.mul(M, group.exp(group.pair(mpk.hibeg1, mpk.g2), t)); relicxx::GT result = group.mul(delta3, group.div(group.pair(sig.c5, d2), group.pair(d1, sig.c0))); cout << (M == result) << (sig.c6 == group.mul(group.exp(mpk.hG2.at(2), sig.x), group.exp(mpk.hG2.at(4), y))) << (sig.e1 == group.exp(mpk.g, k)) << (sig.e2 == group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)), k)) << (sig.e3 == group.mul(group.exp(mpk.n, sig.x), group.exp(group.pair(mpk.hibeg1, mpk.g2), k))); return M == result && sig.c6 == group.mul(group.exp(mpk.hG2.at(2), sig.x), group.exp(mpk.hG2.at(4), y)) && sig.e1 == group.exp(mpk.g, k) && sig.e2 == group.exp(group.mul(mpk.hG2.at(0), group.exp(mpk.hG2.at(1), gGroupID)), k) && sig.e3 == group.mul(group.exp(mpk.n, sig.x), group.exp(group.pair(mpk.hibeg1, mpk.g2), k)); } bool open(const MasterPublicKey &mpk, const GroupSecretKey &gsk, const Signature &sig, string userID) { const ZR gUserID = group.hashListToZR(userID); relicxx::GT t = group.exp(group.pair(mpk.hibeg1, mpk.g2), sig.z); //goes through all user identifiers here if (sig.e3 == group.mul(group.exp(mpk.n, gUserID), t)) return true; else return false; } void set_up() { mpk.l = 4; string g = "021780706f0a7afbfc7e5c2fde178c4a0fa86ff9612c233743cadc96c2e85b99eb000000000000000a00000000000000736369656e636500207e580300000000f03b9904000000000384b2c61a7f00006077e8c61a7f0000e05429c61a7f00000a000000000000004b33b2c61a7f0000207e5803000000006077e8c61a7f0000a0"; string g2 = "02675cbaedec16f50d576a451f813e28d235f8176ab3c748c3e7071197c9c300e404674f3d853347d6f91532a2ca2d27697324275c63c8ed3b8931458e21c394753b9904000000000384b2c61a7f00006077e8c61a7f0000e05429c61a7f00000a000000000000004b33b2c61a7f0000207e5803000000000fab4dc81a7f000043"; string hibeg1 = "022fcc465af6de5155ecbe906c11a221e6c4ea065c94b64f9c128c69e45127a7f65429c61a7f00000700000000000000f03b9904000000007a5c55c71a7f000067687a020000000000000000000000006077e8c61a7f0000e05429c61a7f00000100000000000000207e580300000000207e580300000000000fbb96801eca69a0"; string u0 = "038c714d1457e3630c45d809b7a9db159a7d18d4a2e981f492b017a44d75082ede4d4e0d863b3e77731c85a74acb8c187be285a03d4b1cb79b5c8b099ea3ce656bd2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000038"; string u1 = "033f62f51761b537d105b9343871fe486b582e567bc0f9ee605de4f53f88639022a4cb9b83d85504632770869911cdb388b2b1082168fec8a244f80c44cf22560bd2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f0000a0"; string u2 = "0391aaf47f42654a1c1cac4267b0e3df1985da3e0c341d8ab12d29597af64bddcd6657d290c86175522cd2da1c7652e4fbd381445332d6b5977550abf320c0fb98d2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000060"; string u3 = "035a3ed74532bda53e84441f4571088468b458c4b83cf2294e4360b85468f6f6835a69507209cfbabbc105f1b8d4fdeecf06093d11c773e3bfa16df653a93fdb10d2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000065"; string u4 = "03023afaeeb25eb44de70edee8b47f24f681592f820c4e5874837fb09f2bdfb05c3661488e917ea489240c3f2b2f4c202ab314f4ad0281cd611e90e7568d584f25d2c902000000000000000000000000287e580300000000c66155c71a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f0000c3"; string n = "0066f837d6aaf4d69618917009d0b3c61dc670e614a50d98788cd22400f93c6f22fc9fd14feaff20528338278548c68b71f2a60caed5c8568a61301de0c3256997d26fcf602973721435f651bc6ca3d9230ad04d0b261ae18ca2ab9ae3de01097d518908191408010a85b1ef849579f68286da897c699f394fc48cfb8c1ce3e4a32fa6404a88d40b6d6f571434d7fff3a376c16f25848e8cc3a3cd09236dead65ad8203d97d42b68e76bd2dda61e4edebd1dac6ef620af540bb5a776720633537808a32b1f57b7427849becb1ad34577f089fa78e471fc273d9c6ed9b950aaec23f2be2d40fdb004b6ab3b16c7550eaebc585921acc0acf8eefc928356bdf553801800f40c7f0000207e580300000000287e580300000000b03a990400000000c05429c61a7f0000020000000000000010040000000000007a5c55c71a7f0000d59991020000000000000000000000006077e8c61a7f0000e05429c61a7f00000100000000000000207e580300000000207e580300000000000fbb96801eca69"; string smsk = "02852d3c40a12f7b1b1d930b0324d90c7a2bd28b4eda25e0210318d2c4d9b33eacb32c094e3b48c78cfaf99272b69c5004b072e725145d1624ed35177810e022d8687a020000000000000000000000006077e8c61a7f0000e05429c61a7f00000100000000000000207e580300000000207e5803000000000fab4dc81a7f000083"; mpk.g = strToG1(g); mpk.g2 = strToG2(g2); mpk.hibeg1 = strToG1(hibeg1); mpk.hG2.push_back(strToG2(u0)); mpk.hG2.push_back(strToG2(u1)); mpk.hG2.push_back(strToG2(u2)); mpk.hG2.push_back(strToG2(u3)); mpk.hG2.push_back(strToG2(u4)); mpk.n = strToGT(n); msk = strToG2(smsk); //setup(mpk, msk); } relicxx::G2 getGsk() const { //此处需读取数据库返回群私钥 return group.randomG2(); } string g1ToStr(relicxx::G1 g) const { int len = 4 * FP_BYTES + 1; uint8_t bin[len]; int l; l = g1_size_bin(g.g, 1); g1_write_bin(bin, l, g.g, 1); //bin to str string str = ""; for (int i = 0; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::G1 strToG1(string str) const { relicxx::G1 g; relicxx::G1 g2 = group.randomG1(); int len = 4 * FP_BYTES + 1; int l; l = g1_size_bin(g2.g, 1); uint8_t bin[len]; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin[i / 2] = ::strtol(pair.c_str(), 0, 16); } g1_read_bin(g.g, bin, l); return g; } string g2ToStr(relicxx::G2 g) const { int len = 4 * FP_BYTES + 1; uint8_t bin[len]; int l; l = g2_size_bin(g.g, 1); g2_write_bin(bin, l, g.g, 1); //bin to str string str = ""; for (int i = 0; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::G2 strToG2(string str) const { relicxx::G2 g; relicxx::G2 g2 = group.randomG2(); int len = 4 * FP_BYTES + 1; int l; l = g2_size_bin(g2.g, 1); uint8_t bin[len]; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin[i / 2] = ::strtol(pair.c_str(), 0, 16); } g2_read_bin(g.g, bin, l); return g; } string gtToStr(relicxx::GT g) const { int len = 12 * PC_BYTES; uint8_t bin[len]; int l; l = gt_size_bin(g.g, 1); gt_write_bin(bin, l, g.g, 1); //bin to str string str = ""; for (int i = 0; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::GT strToGT(string str) const { relicxx::GT g; relicxx::GT g2 = group.randomGT(); int len = 12 * PC_BYTES; int l; l = gt_size_bin(g2.g, 1); uint8_t bin[len]; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin[i / 2] = ::strtol(pair.c_str(), 0, 16); } gt_read_bin(g.g, bin, l); return g; } string zrToStr(relicxx::ZR zr) const { int len = CEIL(RELIC_BN_BITS, 8); uint8_t bin[RELIC_BN_BITS / 8 + 1]; bn_write_bin(bin, len, zr.z); //bin to str string str = ""; for (int i = 96; i < len; i++) { int m = atoi(to_string((unsigned int)bin[i]).c_str()); const char *a = inttohex(m); str += a; } return str; } relicxx::ZR strToZR(string str) const { int len = CEIL(RELIC_BN_BITS, 8); relicxx::ZR zr; uint8_t bin2[RELIC_BN_BITS / 8 + 1]; for (int i = 0; i < 96; i++) bin2[i] = '\0'; for (unsigned int i = 0; i < str.length(); i += 2) { std::string pair = str.substr(i, 2); bin2[i / 2 + 96] = ::strtol(pair.c_str(), 0, 16); } bn_read_bin(zr.z, bin2, len); return zr; } char *inttohex(int a) const { char *buffer = new char[3]; if (a / 16 < 10) buffer[0] = a / 16 + '0'; else buffer[0] = a / 16 - 10 + 'a'; if (a % 16 < 10) buffer[1] = a % 16 + '0'; else buffer[1] = a % 16 - 10 + 'a'; buffer[2] = '\0'; return buffer; } }; } // namespace detail sig_by_key_api::sig_by_key_api() : my(new detail::sig_by_key_api_impl()) { JSON_RPC_REGISTER_API(STEEM_sig_by_key_api_plugin_NAME); } sig_by_key_api::~sig_by_key_api() {} // 需要注意创建sig_by_key的时机,因W为sig_by_key的构造函数中会调用JSON RPC插件去注册API,因此 // 需要等JSON RPC先初始化好,plugin_initialize被调用时,会先注册sig_by_key_api_plugin的依赖 // 模块,因此可以确保此时JSON RPC插件此时已经注册完毕。 void sig_by_key_api_plugin::plugin_initialize(const appbase::variables_map &options) { api = std::make_shared<sig_by_key_api>(); } DEFINE_LOCKLESS_APIS(sig_by_key_api, (set_group)(join_group)(get_sig)(open_paper)(test)(verify_user)) } // namespace sig_by_key } // namespace plugins } // namespace steem
36.144289
786
0.672599
sityck
80a4990400db649039841ecce7cc738faf606a06
50,359
cc
C++
chromeos/services/device_sync/device_sync_service_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chromeos/services/device_sync/device_sync_service_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chromeos/services/device_sync/device_sync_service_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "base/memory/scoped_refptr.h" #include "base/no_destructor.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/null_task_runner.h" #include "base/test/scoped_task_environment.h" #include "base/test/simple_test_clock.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/services/device_sync/device_sync_impl.h" #include "chromeos/services/device_sync/device_sync_service.h" #include "chromeos/services/device_sync/fake_device_sync_observer.h" #include "chromeos/services/device_sync/public/mojom/constants.mojom.h" #include "chromeos/services/device_sync/public/mojom/device_sync.mojom.h" #include "components/cryptauth/cryptauth_device_manager_impl.h" #include "components/cryptauth/cryptauth_enrollment_manager_impl.h" #include "components/cryptauth/cryptauth_gcm_manager_impl.h" #include "components/cryptauth/fake_cryptauth_device_manager.h" #include "components/cryptauth/fake_cryptauth_enrollment_manager.h" #include "components/cryptauth/fake_cryptauth_gcm_manager.h" #include "components/cryptauth/fake_gcm_device_info_provider.h" #include "components/cryptauth/fake_remote_device_provider.h" #include "components/cryptauth/fake_software_feature_manager.h" #include "components/cryptauth/remote_device_provider_impl.h" #include "components/cryptauth/remote_device_test_util.h" #include "components/cryptauth/software_feature_manager_impl.h" #include "components/gcm_driver/fake_gcm_driver.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" #include "net/url_request/url_request_context_getter.h" #include "services/identity/public/cpp/identity_test_environment.h" #include "services/service_manager/public/cpp/test/test_connector_factory.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace device_sync { namespace { const char kTestEmail[] = "example@gmail.com"; const char kTestGcmDeviceInfoLongDeviceId[] = "longDeviceId"; const char kTestCryptAuthGCMRegistrationId[] = "cryptAuthRegistrationId"; const char kLocalDevicePublicKey[] = "localDevicePublicKey"; const size_t kNumTestDevices = 5u; const cryptauth::GcmDeviceInfo& GetTestGcmDeviceInfo() { static const base::NoDestructor<cryptauth::GcmDeviceInfo> gcm_device_info([] { cryptauth::GcmDeviceInfo gcm_device_info; gcm_device_info.set_long_device_id(kTestGcmDeviceInfoLongDeviceId); return gcm_device_info; }()); return *gcm_device_info; } cryptauth::RemoteDeviceList GenerateTestRemoteDevices() { cryptauth::RemoteDeviceList devices = cryptauth::CreateRemoteDeviceListForTest(kNumTestDevices); // One of the synced devices refers to the current (i.e., local) device. // Arbitrarily choose the 0th device as the local one and set its public key // accordingly. devices[0].public_key = kLocalDevicePublicKey; // Load an empty set of BeaconSeeds for each device. // TODO(khorimoto): Adjust device_sync_mojom_traits.h/cc to allow passing // devices without BeaconSeeds to be sent across Mojo. for (auto& device : devices) device.LoadBeaconSeeds(std::vector<cryptauth::BeaconSeed>()); return devices; } std::vector<cryptauth::ExternalDeviceInfo> GenerateTestExternalDeviceInfos( const cryptauth::RemoteDeviceList& remote_devices) { std::vector<cryptauth::ExternalDeviceInfo> device_infos; for (const auto& remote_device : remote_devices) { cryptauth::ExternalDeviceInfo info; info.set_public_key(remote_device.public_key); device_infos.push_back(info); } return device_infos; } std::vector<cryptauth::IneligibleDevice> GenerateTestIneligibleDevices( const std::vector<cryptauth::ExternalDeviceInfo>& device_infos) { std::vector<cryptauth::IneligibleDevice> ineligible_devices; for (const auto& device_info : device_infos) { cryptauth::IneligibleDevice device; device.mutable_device()->CopyFrom(device_info); ineligible_devices.push_back(device); } return ineligible_devices; } // Delegate which invokes the Closure provided to its constructor when a // delegate function is invoked. class FakeSoftwareFeatureManagerDelegate : public cryptauth::FakeSoftwareFeatureManager::Delegate { public: FakeSoftwareFeatureManagerDelegate(base::Closure on_delegate_call_closure) : on_delegate_call_closure_(on_delegate_call_closure) {} ~FakeSoftwareFeatureManagerDelegate() override = default; // cryptauth::FakeSoftwareFeatureManager::Delegate: void OnSetSoftwareFeatureStateCalled() override { on_delegate_call_closure_.Run(); } void OnFindEligibleDevicesCalled() override { on_delegate_call_closure_.Run(); } private: base::Closure on_delegate_call_closure_; }; class FakeCryptAuthGCMManagerFactory : public cryptauth::CryptAuthGCMManagerImpl::Factory { public: FakeCryptAuthGCMManagerFactory(gcm::FakeGCMDriver* fake_gcm_driver, TestingPrefServiceSimple* test_pref_service) : fake_gcm_driver_(fake_gcm_driver), test_pref_service_(test_pref_service) {} ~FakeCryptAuthGCMManagerFactory() override = default; cryptauth::FakeCryptAuthGCMManager* instance() { return instance_; } // cryptauth::CryptAuthGCMManagerImpl::Factory: std::unique_ptr<cryptauth::CryptAuthGCMManager> BuildInstance( gcm::GCMDriver* gcm_driver, PrefService* pref_service) override { EXPECT_EQ(fake_gcm_driver_, gcm_driver); EXPECT_EQ(test_pref_service_, pref_service); // Only one instance is expected to be created per test. EXPECT_FALSE(instance_); auto instance = std::make_unique<cryptauth::FakeCryptAuthGCMManager>( kTestCryptAuthGCMRegistrationId); instance_ = instance.get(); return std::move(instance); } private: gcm::FakeGCMDriver* fake_gcm_driver_; TestingPrefServiceSimple* test_pref_service_; cryptauth::FakeCryptAuthGCMManager* instance_ = nullptr; }; class FakeCryptAuthDeviceManagerFactory : public cryptauth::CryptAuthDeviceManagerImpl::Factory { public: FakeCryptAuthDeviceManagerFactory( base::SimpleTestClock* simple_test_clock, FakeCryptAuthGCMManagerFactory* fake_cryptauth_gcm_manager_factory, TestingPrefServiceSimple* test_pref_service) : simple_test_clock_(simple_test_clock), fake_cryptauth_gcm_manager_factory_(fake_cryptauth_gcm_manager_factory), test_pref_service_(test_pref_service) {} ~FakeCryptAuthDeviceManagerFactory() override = default; cryptauth::FakeCryptAuthDeviceManager* instance() { return instance_; } // cryptauth::CryptAuthDeviceManagerImpl::Factory: std::unique_ptr<cryptauth::CryptAuthDeviceManager> BuildInstance( base::Clock* clock, cryptauth::CryptAuthClientFactory* client_factory, cryptauth::CryptAuthGCMManager* gcm_manager, PrefService* pref_service) override { EXPECT_EQ(simple_test_clock_, clock); EXPECT_EQ(fake_cryptauth_gcm_manager_factory_->instance(), gcm_manager); EXPECT_EQ(test_pref_service_, pref_service); // Only one instance is expected to be created per test. EXPECT_FALSE(instance_); auto instance = std::make_unique<cryptauth::FakeCryptAuthDeviceManager>(); instance_ = instance.get(); return std::move(instance); } private: base::SimpleTestClock* simple_test_clock_; FakeCryptAuthGCMManagerFactory* fake_cryptauth_gcm_manager_factory_; TestingPrefServiceSimple* test_pref_service_; cryptauth::FakeCryptAuthDeviceManager* instance_ = nullptr; }; class FakeCryptAuthEnrollmentManagerFactory : public cryptauth::CryptAuthEnrollmentManagerImpl::Factory { public: FakeCryptAuthEnrollmentManagerFactory( base::SimpleTestClock* simple_test_clock, FakeCryptAuthGCMManagerFactory* fake_cryptauth_gcm_manager_factory, TestingPrefServiceSimple* test_pref_service) : simple_test_clock_(simple_test_clock), fake_cryptauth_gcm_manager_factory_(fake_cryptauth_gcm_manager_factory), test_pref_service_(test_pref_service) {} ~FakeCryptAuthEnrollmentManagerFactory() override = default; void set_device_already_enrolled_in_cryptauth( bool device_already_enrolled_in_cryptauth) { device_already_enrolled_in_cryptauth_ = device_already_enrolled_in_cryptauth; } cryptauth::FakeCryptAuthEnrollmentManager* instance() { return instance_; } // cryptauth::CryptAuthEnrollmentManagerImpl::Factory: std::unique_ptr<cryptauth::CryptAuthEnrollmentManager> BuildInstance( base::Clock* clock, std::unique_ptr<cryptauth::CryptAuthEnrollerFactory> enroller_factory, std::unique_ptr<cryptauth::SecureMessageDelegate> secure_message_delegate, const cryptauth::GcmDeviceInfo& device_info, cryptauth::CryptAuthGCMManager* gcm_manager, PrefService* pref_service) override { EXPECT_EQ(simple_test_clock_, clock); EXPECT_EQ(kTestGcmDeviceInfoLongDeviceId, device_info.long_device_id()); EXPECT_EQ(fake_cryptauth_gcm_manager_factory_->instance(), gcm_manager); EXPECT_EQ(test_pref_service_, pref_service); // Only one instance is expected to be created per test. EXPECT_FALSE(instance_); auto instance = std::make_unique<cryptauth::FakeCryptAuthEnrollmentManager>(); instance->set_user_public_key(kLocalDevicePublicKey); instance->set_is_enrollment_valid(device_already_enrolled_in_cryptauth_); instance_ = instance.get(); return std::move(instance); } private: base::SimpleTestClock* simple_test_clock_; FakeCryptAuthGCMManagerFactory* fake_cryptauth_gcm_manager_factory_; TestingPrefServiceSimple* test_pref_service_; bool device_already_enrolled_in_cryptauth_ = false; cryptauth::FakeCryptAuthEnrollmentManager* instance_ = nullptr; }; class FakeRemoteDeviceProviderFactory : public cryptauth::RemoteDeviceProviderImpl::Factory { public: FakeRemoteDeviceProviderFactory( const cryptauth::RemoteDeviceList& initial_devices, identity::IdentityManager* identity_manager, FakeCryptAuthDeviceManagerFactory* fake_cryptauth_device_manager_factory, FakeCryptAuthEnrollmentManagerFactory* fake_cryptauth_enrollment_manager_factory) : initial_devices_(initial_devices), identity_manager_(identity_manager), fake_cryptauth_device_manager_factory_( fake_cryptauth_device_manager_factory), fake_cryptauth_enrollment_manager_factory_( fake_cryptauth_enrollment_manager_factory) {} ~FakeRemoteDeviceProviderFactory() override = default; cryptauth::FakeRemoteDeviceProvider* instance() { return instance_; } // cryptauth::RemoteDeviceProviderImpl::Factory: std::unique_ptr<cryptauth::RemoteDeviceProvider> BuildInstance( cryptauth::CryptAuthDeviceManager* device_manager, const std::string& user_id, const std::string& user_private_key) override { EXPECT_EQ(fake_cryptauth_device_manager_factory_->instance(), device_manager); EXPECT_EQ(identity_manager_->GetPrimaryAccountInfo().account_id, user_id); EXPECT_EQ(fake_cryptauth_enrollment_manager_factory_->instance() ->GetUserPrivateKey(), user_private_key); // Only one instance is expected to be created per test. EXPECT_FALSE(instance_); auto instance = std::make_unique<cryptauth::FakeRemoteDeviceProvider>(); instance->set_synced_remote_devices(initial_devices_); instance_ = instance.get(); return std::move(instance); } private: const cryptauth::RemoteDeviceList& initial_devices_; identity::IdentityManager* identity_manager_; FakeCryptAuthDeviceManagerFactory* fake_cryptauth_device_manager_factory_; FakeCryptAuthEnrollmentManagerFactory* fake_cryptauth_enrollment_manager_factory_; cryptauth::FakeRemoteDeviceProvider* instance_ = nullptr; }; class FakeSoftwareFeatureManagerFactory : public cryptauth::SoftwareFeatureManagerImpl::Factory { public: FakeSoftwareFeatureManagerFactory() = default; ~FakeSoftwareFeatureManagerFactory() override = default; cryptauth::FakeSoftwareFeatureManager* instance() { return instance_; } // cryptauth::SoftwareFeatureManagerImpl::Factory: std::unique_ptr<cryptauth::SoftwareFeatureManager> BuildInstance( cryptauth::CryptAuthClientFactory* cryptauth_client_factory) override { // Only one instance is expected to be created per test. EXPECT_FALSE(instance_); auto instance = std::make_unique<cryptauth::FakeSoftwareFeatureManager>(); instance_ = instance.get(); return std::move(instance); } private: cryptauth::FakeSoftwareFeatureManager* instance_ = nullptr; }; class FakeURLRequestContextGetter : public net::URLRequestContextGetter { public: FakeURLRequestContextGetter() : null_task_runner_(new base::NullTaskRunner) {} net::URLRequestContext* GetURLRequestContext() override { return nullptr; } scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() const override { return null_task_runner_; } private: ~FakeURLRequestContextGetter() override {} scoped_refptr<base::SingleThreadTaskRunner> null_task_runner_; }; } // namespace class DeviceSyncServiceTest : public testing::Test { public: class FakePrefConnectionDelegate : public DeviceSyncImpl::PrefConnectionDelegate { public: FakePrefConnectionDelegate( std::unique_ptr<TestingPrefServiceSimple> test_pref_service) : test_pref_service_(std::move(test_pref_service)), test_pref_registry_( base::WrapRefCounted(test_pref_service_->registry())) {} ~FakePrefConnectionDelegate() override = default; void InvokePendingCallback() { EXPECT_FALSE(pending_callback_.is_null()); std::move(pending_callback_).Run(std::move(test_pref_service_)); // Note: |pending_callback_| was passed from within the service, so it is // necessary to let the rest of the current RunLoop run to ensure that // the callback is executed before returning from this function. base::RunLoop().RunUntilIdle(); } bool HasStartedPrefConnection() { return HasFinishedPrefConnection() || !pending_callback_.is_null(); } bool HasFinishedPrefConnection() { return !test_pref_service_.get(); } // DeviceSyncImpl::PrefConnectionDelegate: scoped_refptr<PrefRegistrySimple> CreatePrefRegistry() override { return test_pref_registry_; } void ConnectToPrefService(service_manager::Connector* connector, scoped_refptr<PrefRegistrySimple> pref_registry, prefs::ConnectCallback callback) override { EXPECT_EQ(test_pref_service_->registry(), pref_registry.get()); pending_callback_ = std::move(callback); } private: std::unique_ptr<TestingPrefServiceSimple> test_pref_service_; scoped_refptr<PrefRegistrySimple> test_pref_registry_; prefs::ConnectCallback pending_callback_; }; class FakeDeviceSyncImplFactory : public DeviceSyncImpl::Factory { public: FakeDeviceSyncImplFactory(std::unique_ptr<FakePrefConnectionDelegate> fake_pref_connection_delegate, base::SimpleTestClock* simple_test_clock) : fake_pref_connection_delegate_( std::move(fake_pref_connection_delegate)), simple_test_clock_(simple_test_clock) {} ~FakeDeviceSyncImplFactory() override = default; // DeviceSyncImpl::Factory: std::unique_ptr<DeviceSyncImpl> BuildInstance( identity::IdentityManager* identity_manager, gcm::GCMDriver* gcm_driver, service_manager::Connector* connector, cryptauth::GcmDeviceInfoProvider* gcm_device_info_provider, scoped_refptr<net::URLRequestContextGetter> url_request_context) override { return base::WrapUnique(new DeviceSyncImpl( identity_manager, gcm_driver, connector, gcm_device_info_provider, std::move(url_request_context), simple_test_clock_, std::move(fake_pref_connection_delegate_))); } private: std::unique_ptr<FakePrefConnectionDelegate> fake_pref_connection_delegate_; base::SimpleTestClock* simple_test_clock_; }; DeviceSyncServiceTest() : test_devices_(GenerateTestRemoteDevices()), test_device_infos_(GenerateTestExternalDeviceInfos(test_devices_)), test_ineligible_devices_( GenerateTestIneligibleDevices(test_device_infos_)) {} ~DeviceSyncServiceTest() override = default; void SetUp() override { DBusThreadManager::Initialize(); fake_gcm_driver_ = std::make_unique<gcm::FakeGCMDriver>(); auto test_pref_service = std::make_unique<TestingPrefServiceSimple>(); test_pref_service_ = test_pref_service.get(); simple_test_clock_ = std::make_unique<base::SimpleTestClock>(); // Note: The primary account is guaranteed to be available when the service // starts up since this is a CrOS-only service, and CrOS requires that // the user logs in. identity_test_environment_ = std::make_unique<identity::IdentityTestEnvironment>(); identity_test_environment_->MakePrimaryAccountAvailable(kTestEmail); fake_cryptauth_gcm_manager_factory_ = std::make_unique<FakeCryptAuthGCMManagerFactory>(fake_gcm_driver_.get(), test_pref_service_); cryptauth::CryptAuthGCMManagerImpl::Factory::SetInstanceForTesting( fake_cryptauth_gcm_manager_factory_.get()); fake_cryptauth_device_manager_factory_ = std::make_unique<FakeCryptAuthDeviceManagerFactory>( simple_test_clock_.get(), fake_cryptauth_gcm_manager_factory_.get(), test_pref_service_); cryptauth::CryptAuthDeviceManagerImpl::Factory::SetInstanceForTesting( fake_cryptauth_device_manager_factory_.get()); fake_cryptauth_enrollment_manager_factory_ = std::make_unique<FakeCryptAuthEnrollmentManagerFactory>( simple_test_clock_.get(), fake_cryptauth_gcm_manager_factory_.get(), test_pref_service_); cryptauth::CryptAuthEnrollmentManagerImpl::Factory::SetInstanceForTesting( fake_cryptauth_enrollment_manager_factory_.get()); fake_remote_device_provider_factory_ = std::make_unique<FakeRemoteDeviceProviderFactory>( test_devices_, identity_test_environment_->identity_manager(), fake_cryptauth_device_manager_factory_.get(), fake_cryptauth_enrollment_manager_factory_.get()); cryptauth::RemoteDeviceProviderImpl::Factory::SetInstanceForTesting( fake_remote_device_provider_factory_.get()); fake_software_feature_manager_factory_ = std::make_unique<FakeSoftwareFeatureManagerFactory>(); cryptauth::SoftwareFeatureManagerImpl::Factory::SetInstanceForTesting( fake_software_feature_manager_factory_.get()); auto fake_pref_connection_delegate = std::make_unique<FakePrefConnectionDelegate>( std::move(test_pref_service)); fake_pref_connection_delegate_ = fake_pref_connection_delegate.get(); fake_device_sync_impl_factory_ = std::make_unique<FakeDeviceSyncImplFactory>( std::move(fake_pref_connection_delegate), simple_test_clock_.get()); DeviceSyncImpl::Factory::SetInstanceForTesting( fake_device_sync_impl_factory_.get()); fake_gcm_device_info_provider_ = std::make_unique<cryptauth::FakeGcmDeviceInfoProvider>( GetTestGcmDeviceInfo()); fake_url_request_context_getter_ = base::MakeRefCounted<FakeURLRequestContextGetter>(); fake_device_sync_observer_ = std::make_unique<FakeDeviceSyncObserver>(); connector_factory_ = service_manager::TestConnectorFactory::CreateForUniqueService( std::make_unique<DeviceSyncService>( identity_test_environment_->identity_manager(), fake_gcm_driver_.get(), fake_gcm_device_info_provider_.get(), fake_url_request_context_getter_.get())); } void TearDown() override { DBusThreadManager::Shutdown(); } void ConnectToDeviceSyncService(bool device_already_enrolled_in_cryptauth) { // Used in CompleteConnectionToPrefService(). device_already_enrolled_in_cryptauth_ = device_already_enrolled_in_cryptauth; fake_cryptauth_enrollment_manager_factory_ ->set_device_already_enrolled_in_cryptauth( device_already_enrolled_in_cryptauth); // Must not have already connected. EXPECT_FALSE(connector_); // Create the Connector and bind it to |device_sync_|. connector_ = connector_factory_->CreateConnector(); connector_->BindInterface(mojom::kServiceName, &device_sync_); // Set |fake_device_sync_observer_|. CallAddObserver(); } void CompleteConnectionToPrefService() { EXPECT_TRUE(fake_pref_connection_delegate()->HasStartedPrefConnection()); EXPECT_FALSE(fake_pref_connection_delegate()->HasFinishedPrefConnection()); fake_pref_connection_delegate_->InvokePendingCallback(); EXPECT_TRUE(fake_pref_connection_delegate()->HasFinishedPrefConnection()); // When connection to preferences is complete, CryptAuth classes are // expected to be created and initialized. EXPECT_TRUE(fake_cryptauth_gcm_manager_factory_->instance() ->has_started_listening()); EXPECT_TRUE( fake_cryptauth_enrollment_manager_factory_->instance()->has_started()); // If the device was already enrolled in CryptAuth, initialization should // now be complete; otherwise, enrollment needs to finish before // the flow has finished up. VerifyInitializationStatus( device_already_enrolled_in_cryptauth_ /* expected_to_be_initialized */); if (!device_already_enrolled_in_cryptauth_) return; // Now that the service is initialized, RemoteDeviceProvider is expected to // load all relevant RemoteDevice objects. fake_remote_device_provider_factory_->instance() ->NotifyObserversDeviceListChanged(); } void VerifyInitializationStatus(bool expected_to_be_initialized) { // CryptAuthDeviceManager::Start() is called as the last step of the // initialization flow. EXPECT_EQ( expected_to_be_initialized, fake_cryptauth_device_manager_factory_->instance()->has_started()); } // Simulates an enrollment with success == |success|. If enrollment was not // yet in progress before this call, it is started before it is completed. void SimulateEnrollment(bool success) { cryptauth::FakeCryptAuthEnrollmentManager* enrollment_manager = fake_cryptauth_enrollment_manager_factory_->instance(); bool had_valid_enrollment_before_call = enrollment_manager->IsEnrollmentValid(); if (!enrollment_manager->IsEnrollmentInProgress()) { enrollment_manager->ForceEnrollmentNow( cryptauth::InvocationReason::INVOCATION_REASON_MANUAL); } enrollment_manager->FinishActiveEnrollment(success); // If this was the first successful enrollment for this device, // RemoteDeviceProvider is expected to load all relevant RemoteDevice // objects. if (success && !had_valid_enrollment_before_call) { fake_remote_device_provider_factory_->instance() ->NotifyObserversDeviceListChanged(); } } // Simulates a device sync with success == |success|. Optionally, if // |updated_devices| is provided, these devices will set on the // FakeRemoteDeviceProvider. void SimulateSync(bool success, const cryptauth::RemoteDeviceList& updated_devices = cryptauth::RemoteDeviceList()) { cryptauth::FakeCryptAuthDeviceManager* device_manager = fake_cryptauth_device_manager_factory_->instance(); cryptauth::FakeRemoteDeviceProvider* remote_device_provider = fake_remote_device_provider_factory_->instance(); EXPECT_TRUE(device_manager->IsSyncInProgress()); device_manager->FinishActiveSync( success ? cryptauth::CryptAuthDeviceManager::SyncResult::SUCCESS : cryptauth::CryptAuthDeviceManager::SyncResult::FAILURE, updated_devices.empty() ? cryptauth::CryptAuthDeviceManager::DeviceChangeResult::UNCHANGED : cryptauth::CryptAuthDeviceManager::DeviceChangeResult::CHANGED); if (!updated_devices.empty()) { remote_device_provider->set_synced_remote_devices(updated_devices); remote_device_provider->NotifyObserversDeviceListChanged(); } } void InitializeServiceSuccessfully() { ConnectToDeviceSyncService(true /* device_already_enrolled_in_cryptauth */); CompleteConnectionToPrefService(); VerifyInitializationStatus(true /* expected_to_be_initialized */); base::RunLoop().RunUntilIdle(); // Enrollment did not occur since the device was already in a valid state. EXPECT_EQ(0u, fake_device_sync_observer()->num_enrollment_events()); // The initial set of synced devices was set. EXPECT_EQ(1u, fake_device_sync_observer()->num_sync_events()); } const cryptauth::RemoteDeviceList& test_devices() { return test_devices_; } const std::vector<cryptauth::ExternalDeviceInfo>& test_device_infos() { return test_device_infos_; } const std::vector<cryptauth::IneligibleDevice>& test_ineligible_devices() { return test_ineligible_devices_; } FakeDeviceSyncObserver* fake_device_sync_observer() { return fake_device_sync_observer_.get(); } FakePrefConnectionDelegate* fake_pref_connection_delegate() { return fake_pref_connection_delegate_; } cryptauth::FakeCryptAuthEnrollmentManager* fake_cryptauth_enrollment_manager() { return fake_cryptauth_enrollment_manager_factory_->instance(); } cryptauth::FakeCryptAuthDeviceManager* fake_cryptauth_device_manager() { return fake_cryptauth_device_manager_factory_->instance(); } cryptauth::FakeSoftwareFeatureManager* fake_software_feature_manager() { return fake_software_feature_manager_factory_->instance(); } std::unique_ptr<base::Optional<std::string>> GetLastSetSoftwareFeatureStateResponseAndReset() { return std::move(last_set_software_feature_state_response_); } std::unique_ptr<std::pair<base::Optional<std::string>, mojom::FindEligibleDevicesResponsePtr>> GetLastFindEligibleDevicesResponseAndReset() { return std::move(last_find_eligible_devices_response_); } // Verifies that API functions return error codes before initialization has // completed. This function should not be invoked after initialization. void VerifyApiFunctionsFailBeforeInitialization() { // Force*Now() functions return false when they are not handled. EXPECT_FALSE(CallForceEnrollmentNow()); EXPECT_FALSE(CallForceSyncNow()); // GetSyncedDevices() returns a null list before initialization. EXPECT_FALSE(CallGetSyncedDevices()); // GetLocalDeviceMetadata() returns a null RemoteDevice before // initialization. EXPECT_FALSE(CallGetLocalDeviceMetadata()); // SetSoftwareFeatureState() should return a struct with the special // kErrorNotInitialized error code. CallSetSoftwareFeatureState( test_devices()[0].public_key, cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, true /* enabled */, true /* is_exclusive */); auto last_set_response = GetLastSetSoftwareFeatureStateResponseAndReset(); EXPECT_EQ(mojom::kErrorNotInitialized, *last_set_response); // Likewise, FindEligibleDevices() should also return a struct with the same // error code. CallFindEligibleDevices(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST); auto last_find_response = GetLastFindEligibleDevicesResponseAndReset(); EXPECT_EQ(mojom::kErrorNotInitialized, last_find_response->first); EXPECT_FALSE(last_find_response->second /* response */); // GetDebugInfo() returns a null DebugInfo before initialization. EXPECT_FALSE(CallGetDebugInfo()); } void CallAddObserver() { base::RunLoop run_loop; device_sync_->AddObserver( fake_device_sync_observer_->GenerateInterfacePtr(), base::BindOnce(&DeviceSyncServiceTest::OnAddObserverCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } bool CallForceEnrollmentNow() { base::RunLoop run_loop; device_sync_->ForceEnrollmentNow( base::BindOnce(&DeviceSyncServiceTest::OnForceEnrollmentNowCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); if (fake_cryptauth_enrollment_manager_factory_->instance()) { EXPECT_EQ(last_force_enrollment_now_result_, fake_cryptauth_enrollment_manager_factory_->instance() ->IsEnrollmentInProgress()); } return last_force_enrollment_now_result_; } bool CallForceSyncNow() { base::RunLoop run_loop; device_sync_->ForceSyncNow( base::BindOnce(&DeviceSyncServiceTest::OnForceSyncNowCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); if (fake_cryptauth_device_manager_factory_->instance()) { EXPECT_EQ(last_force_sync_now_result_, fake_cryptauth_device_manager_factory_->instance() ->IsSyncInProgress()); } return last_force_sync_now_result_; } const base::Optional<cryptauth::RemoteDevice>& CallGetLocalDeviceMetadata() { base::RunLoop run_loop; device_sync_->GetLocalDeviceMetadata(base::BindOnce( &DeviceSyncServiceTest::OnGetLocalDeviceMetadataCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); return last_local_device_metadata_result_; } const base::Optional<cryptauth::RemoteDeviceList>& CallGetSyncedDevices() { base::RunLoop run_loop; device_sync_->GetSyncedDevices( base::BindOnce(&DeviceSyncServiceTest::OnGetSyncedDevicesCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); return last_synced_devices_result_; } void CallSetSoftwareFeatureState(const std::string& public_key, cryptauth::SoftwareFeature software_feature, bool enabled, bool is_exclusive) { base::RunLoop run_loop; cryptauth::FakeSoftwareFeatureManager* manager = fake_software_feature_manager(); // If the manager has not yet been created, the service has not been // initialized. SetSoftwareFeatureState() is expected to respond // synchronously with an error. if (!manager) { device_sync_->SetSoftwareFeatureState( public_key, software_feature, enabled, is_exclusive, base::Bind(&DeviceSyncServiceTest:: OnSetSoftwareFeatureStateCompletedSynchronously, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); return; } // If the manager has been created, the service responds asynchronously. FakeSoftwareFeatureManagerDelegate delegate(run_loop.QuitClosure()); fake_software_feature_manager_factory_->instance()->set_delegate(&delegate); device_sync_->SetSoftwareFeatureState( public_key, software_feature, enabled, is_exclusive, base::Bind(&DeviceSyncServiceTest::OnSetSoftwareFeatureStateCompleted, base::Unretained(this))); run_loop.Run(); fake_software_feature_manager_factory_->instance()->set_delegate(nullptr); } void CallFindEligibleDevices(cryptauth::SoftwareFeature software_feature) { base::RunLoop run_loop; cryptauth::FakeSoftwareFeatureManager* manager = fake_software_feature_manager(); // If the manager has not yet been created, the service has not been // initialized. FindEligibleDevices() is expected to respond synchronously // with an error. if (!manager) { device_sync_->FindEligibleDevices( software_feature, base::Bind(&DeviceSyncServiceTest:: OnFindEligibleDevicesCompletedSynchronously, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); return; } // If the manager has been created, the service responds asynchronously. FakeSoftwareFeatureManagerDelegate delegate(run_loop.QuitClosure()); fake_software_feature_manager_factory_->instance()->set_delegate(&delegate); device_sync_->FindEligibleDevices( software_feature, base::Bind(&DeviceSyncServiceTest::OnFindEligibleDevicesCompleted, base::Unretained(this))); run_loop.Run(); fake_software_feature_manager_factory_->instance()->set_delegate(nullptr); } const base::Optional<mojom::DebugInfo>& CallGetDebugInfo() { base::RunLoop run_loop; device_sync_->GetDebugInfo( base::BindOnce(&DeviceSyncServiceTest::OnGetDebugInfoCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); return last_debug_info_result_; } private: void OnAddObserverCompleted(base::OnceClosure quit_closure) { std::move(quit_closure).Run(); } void OnForceEnrollmentNowCompleted(base::OnceClosure quit_closure, bool success) { last_force_enrollment_now_result_ = success; std::move(quit_closure).Run(); } void OnForceSyncNowCompleted(base::OnceClosure quit_closure, bool success) { last_force_sync_now_result_ = success; std::move(quit_closure).Run(); } void OnGetLocalDeviceMetadataCompleted( base::OnceClosure quit_closure, const base::Optional<cryptauth::RemoteDevice>& local_device_metadata) { last_local_device_metadata_result_ = local_device_metadata; std::move(quit_closure).Run(); } void OnGetSyncedDevicesCompleted( base::OnceClosure quit_closure, const base::Optional<cryptauth::RemoteDeviceList>& synced_devices) { last_synced_devices_result_ = synced_devices; std::move(quit_closure).Run(); } void OnSetSoftwareFeatureStateCompleted( const base::Optional<std::string>& error_code) { EXPECT_FALSE(last_set_software_feature_state_response_); last_set_software_feature_state_response_ = std::make_unique<base::Optional<std::string>>(error_code); } void OnSetSoftwareFeatureStateCompletedSynchronously( base::OnceClosure quit_closure, const base::Optional<std::string>& error_code) { OnSetSoftwareFeatureStateCompleted(error_code); std::move(quit_closure).Run(); } void OnFindEligibleDevicesCompleted( const base::Optional<std::string>& error_code, mojom::FindEligibleDevicesResponsePtr response) { EXPECT_FALSE(last_find_eligible_devices_response_); last_find_eligible_devices_response_ = std::make_unique<std::pair<base::Optional<std::string>, mojom::FindEligibleDevicesResponsePtr>>( error_code, std::move(response)); } void OnFindEligibleDevicesCompletedSynchronously( base::OnceClosure quit_closure, const base::Optional<std::string>& error_code, mojom::FindEligibleDevicesResponsePtr response) { OnFindEligibleDevicesCompleted(error_code, std::move(response)); std::move(quit_closure).Run(); } void OnGetDebugInfoCompleted(base::OnceClosure quit_closure, mojom::DebugInfoPtr debug_info) { EXPECT_FALSE(last_debug_info_result_); if (debug_info) last_debug_info_result_ = *debug_info; else last_debug_info_result_.reset(); std::move(quit_closure).Run(); } const base::test::ScopedTaskEnvironment scoped_task_environment_; const cryptauth::RemoteDeviceList test_devices_; const std::vector<cryptauth::ExternalDeviceInfo> test_device_infos_; const std::vector<cryptauth::IneligibleDevice> test_ineligible_devices_; TestingPrefServiceSimple* test_pref_service_; FakePrefConnectionDelegate* fake_pref_connection_delegate_; std::unique_ptr<base::SimpleTestClock> simple_test_clock_; std::unique_ptr<FakeDeviceSyncImplFactory> fake_device_sync_impl_factory_; std::unique_ptr<FakeCryptAuthGCMManagerFactory> fake_cryptauth_gcm_manager_factory_; std::unique_ptr<FakeCryptAuthDeviceManagerFactory> fake_cryptauth_device_manager_factory_; std::unique_ptr<FakeCryptAuthEnrollmentManagerFactory> fake_cryptauth_enrollment_manager_factory_; std::unique_ptr<FakeRemoteDeviceProviderFactory> fake_remote_device_provider_factory_; std::unique_ptr<FakeSoftwareFeatureManagerFactory> fake_software_feature_manager_factory_; std::unique_ptr<identity::IdentityTestEnvironment> identity_test_environment_; std::unique_ptr<gcm::FakeGCMDriver> fake_gcm_driver_; std::unique_ptr<cryptauth::FakeGcmDeviceInfoProvider> fake_gcm_device_info_provider_; scoped_refptr<FakeURLRequestContextGetter> fake_url_request_context_getter_; std::unique_ptr<service_manager::TestConnectorFactory> connector_factory_; std::unique_ptr<service_manager::Connector> connector_; bool device_already_enrolled_in_cryptauth_; bool last_force_enrollment_now_result_; bool last_force_sync_now_result_; base::Optional<cryptauth::RemoteDeviceList> last_synced_devices_result_; base::Optional<cryptauth::RemoteDevice> last_local_device_metadata_result_; std::unique_ptr<base::Optional<std::string>> last_set_software_feature_state_response_; std::unique_ptr<std::pair<base::Optional<std::string>, mojom::FindEligibleDevicesResponsePtr>> last_find_eligible_devices_response_; base::Optional<mojom::DebugInfo> last_debug_info_result_; std::unique_ptr<FakeDeviceSyncObserver> fake_device_sync_observer_; mojom::DeviceSyncPtr device_sync_; DISALLOW_COPY_AND_ASSIGN(DeviceSyncServiceTest); }; TEST_F(DeviceSyncServiceTest, PreferencesNeverConnect) { ConnectToDeviceSyncService(false /* device_already_enrolled_in_cryptauth */); // A connection to the Preferences service should have started. EXPECT_TRUE(fake_pref_connection_delegate()->HasStartedPrefConnection()); EXPECT_FALSE(fake_pref_connection_delegate()->HasFinishedPrefConnection()); // Do not complete the connection; without this step, the other API functions // should fail. VerifyApiFunctionsFailBeforeInitialization(); // No observer callbacks should have been invoked. base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, fake_device_sync_observer()->num_enrollment_events()); EXPECT_EQ(0u, fake_device_sync_observer()->num_sync_events()); } TEST_F(DeviceSyncServiceTest, DeviceNotAlreadyEnrolledInCryptAuth_FailsEnrollment) { ConnectToDeviceSyncService(false /* device_already_enrolled_in_cryptauth */); CompleteConnectionToPrefService(); // Simulate enrollment failing. SimulateEnrollment(false /* success */); VerifyInitializationStatus(false /* success */); // Fail again; initialization still should not complete. SimulateEnrollment(false /* success */); VerifyInitializationStatus(false /* expected_to_be_initialized */); // Other API functions should still fail since initialization never completed. VerifyApiFunctionsFailBeforeInitialization(); // No observer callbacks should have been invoked. base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, fake_device_sync_observer()->num_enrollment_events()); EXPECT_EQ(0u, fake_device_sync_observer()->num_sync_events()); } TEST_F(DeviceSyncServiceTest, DeviceNotAlreadyEnrolledInCryptAuth_FailsEnrollment_ThenSucceeds) { ConnectToDeviceSyncService(false /* device_already_enrolled_in_cryptauth */); CompleteConnectionToPrefService(); // Initialization has not yet completed, so no devices should be available. EXPECT_FALSE(CallGetSyncedDevices()); // Simulate enrollment failing. SimulateEnrollment(false /* success */); VerifyInitializationStatus(false /* success */); // Simulate enrollment succeeding; this should result in a fully-initialized // service. SimulateEnrollment(true /* success */); VerifyInitializationStatus(true /* expected_to_be_initialized */); // Enrollment occurred successfully, and the initial set of synced devices was // set. base::RunLoop().RunUntilIdle(); EXPECT_EQ(1u, fake_device_sync_observer()->num_enrollment_events()); EXPECT_EQ(1u, fake_device_sync_observer()->num_sync_events()); // Now that the service is initialized, API functions should be operation and // synced devices should be available. EXPECT_TRUE(CallForceEnrollmentNow()); EXPECT_TRUE(CallForceSyncNow()); EXPECT_EQ(test_devices(), CallGetSyncedDevices()); } TEST_F(DeviceSyncServiceTest, DeviceAlreadyEnrolledInCryptAuth_InitializationFlow) { InitializeServiceSuccessfully(); // Now that the service is initialized, API functions should be operation and // synced devices should be available. EXPECT_TRUE(CallForceEnrollmentNow()); EXPECT_TRUE(CallForceSyncNow()); EXPECT_EQ(test_devices(), CallGetSyncedDevices()); } TEST_F(DeviceSyncServiceTest, EnrollAgainAfterInitialization) { InitializeServiceSuccessfully(); // Force an enrollment. EXPECT_TRUE(CallForceEnrollmentNow()); // Simulate that enrollment failing. SimulateEnrollment(false /* success */); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, fake_device_sync_observer()->num_enrollment_events()); // Force an enrollment again. EXPECT_TRUE(CallForceEnrollmentNow()); // This time, simulate the enrollment succeeding. SimulateEnrollment(true /* success */); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1u, fake_device_sync_observer()->num_enrollment_events()); } TEST_F(DeviceSyncServiceTest, GetLocalDeviceMetadata) { InitializeServiceSuccessfully(); const auto& result = CallGetLocalDeviceMetadata(); EXPECT_TRUE(result); EXPECT_EQ(kLocalDevicePublicKey, result->public_key); // Note: In GenerateTestRemoteDevices(), the 0th test device is arbitrarily // chosen as the local device. EXPECT_EQ(test_devices()[0], *result); } TEST_F(DeviceSyncServiceTest, SyncedDeviceUpdates) { InitializeServiceSuccessfully(); EXPECT_EQ(1u, fake_device_sync_observer()->num_sync_events()); // Force a device sync. EXPECT_TRUE(CallForceSyncNow()); // Simulate failed sync. SimulateSync(false /* success */); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1u, fake_device_sync_observer()->num_sync_events()); // Force a sync again. EXPECT_TRUE(CallForceSyncNow()); // Simulate successful sync which does not change the synced device list. SimulateSync(true /* success */); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1u, fake_device_sync_observer()->num_sync_events()); // Force a sync again. EXPECT_TRUE(CallForceSyncNow()); // Create a new list which is the same as the initial test devices except that // the first device is removed. cryptauth::RemoteDeviceList updated_device_list(test_devices().begin() + 1, test_devices().end()); EXPECT_EQ(kNumTestDevices - 1, updated_device_list.size()); // Simulate successful sync which does change the synced device list. SimulateSync(true /* success */, updated_device_list); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2u, fake_device_sync_observer()->num_sync_events()); // The updated list should be available via GetSyncedDevices(). EXPECT_EQ(updated_device_list, CallGetSyncedDevices()); } TEST_F(DeviceSyncServiceTest, SetSoftwareFeatureState) { InitializeServiceSuccessfully(); const auto& set_software_calls = fake_software_feature_manager()->set_software_feature_state_calls(); EXPECT_EQ(0u, set_software_calls.size()); // Enable BETTER_TOGETHER_HOST for device 0. CallSetSoftwareFeatureState(test_devices()[0].public_key, cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, true /* enabled */, true /* is_exclusive */); EXPECT_EQ(1u, set_software_calls.size()); EXPECT_EQ(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, set_software_calls[0]->software_feature); EXPECT_TRUE(set_software_calls[0]->enabled); EXPECT_TRUE(set_software_calls[0]->is_exclusive); // The callback has not yet been invoked. EXPECT_FALSE(GetLastSetSoftwareFeatureStateResponseAndReset()); // Now, invoke the success callback. set_software_calls[0]->success_callback.Run(); base::RunLoop().RunUntilIdle(); auto last_response = GetLastSetSoftwareFeatureStateResponseAndReset(); EXPECT_TRUE(last_response); EXPECT_FALSE(*last_response /* error_code */); // Disable BETTER_TOGETHER_HOST for device 0. CallSetSoftwareFeatureState(test_devices()[0].public_key, cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, false /* enabled */, false /* is_exclusive */); EXPECT_EQ(2u, set_software_calls.size()); EXPECT_EQ(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, set_software_calls[1]->software_feature); EXPECT_FALSE(set_software_calls[1]->enabled); EXPECT_FALSE(set_software_calls[1]->is_exclusive); // The callback has not yet been invoked. EXPECT_FALSE(GetLastSetSoftwareFeatureStateResponseAndReset()); // Now, invoke the error callback. set_software_calls[1]->error_callback.Run("error"); base::RunLoop().RunUntilIdle(); last_response = GetLastSetSoftwareFeatureStateResponseAndReset(); EXPECT_TRUE(last_response); EXPECT_EQ("error", *last_response /* error_code */); } TEST_F(DeviceSyncServiceTest, FindEligibleDevices) { InitializeServiceSuccessfully(); const auto& find_eligible_calls = fake_software_feature_manager()->find_eligible_multidevice_host_calls(); EXPECT_EQ(0u, find_eligible_calls.size()); // Find devices which are BETTER_TOGETHER_HOSTs. CallFindEligibleDevices(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST); EXPECT_EQ(1u, find_eligible_calls.size()); EXPECT_EQ(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, find_eligible_calls[0]->software_feature); // The callback has not yet been invoked. EXPECT_FALSE(GetLastFindEligibleDevicesResponseAndReset()); // Now, invoke the success callback, simultating that device 0 is eligible and // devices 1-4 are not. find_eligible_calls[0]->success_callback.Run( std::vector<cryptauth::ExternalDeviceInfo>(test_device_infos().begin(), test_device_infos().begin()), std::vector<cryptauth::IneligibleDevice>( test_ineligible_devices().begin() + 1, test_ineligible_devices().end())); base::RunLoop().RunUntilIdle(); auto last_response = GetLastFindEligibleDevicesResponseAndReset(); EXPECT_TRUE(last_response); EXPECT_FALSE(last_response->first /* error_code */); EXPECT_EQ(last_response->second->eligible_devices, cryptauth::RemoteDeviceList(test_devices().begin(), test_devices().begin())); EXPECT_EQ(last_response->second->ineligible_devices, cryptauth::RemoteDeviceList(test_devices().begin() + 1, test_devices().end())); // Find devices which are BETTER_TOGETHER_HOSTs again. CallFindEligibleDevices(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST); EXPECT_EQ(2u, find_eligible_calls.size()); EXPECT_EQ(cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST, find_eligible_calls[1]->software_feature); // The callback has not yet been invoked. EXPECT_FALSE(GetLastFindEligibleDevicesResponseAndReset()); // Now, invoke the error callback. find_eligible_calls[1]->error_callback.Run("error"); base::RunLoop().RunUntilIdle(); last_response = GetLastFindEligibleDevicesResponseAndReset(); EXPECT_TRUE(last_response); EXPECT_EQ("error", last_response->first /* error_code */); EXPECT_FALSE(last_response->second /* response */); } TEST_F(DeviceSyncServiceTest, GetDebugInfo) { static const base::TimeDelta kTimeBetweenEpochAndLastEnrollment = base::TimeDelta::FromDays(365 * 50); // 50 years static const base::TimeDelta kTimeUntilNextEnrollment = base::TimeDelta::FromDays(10); static const base::TimeDelta kTimeBetweenEpochAndLastSync = base::TimeDelta::FromDays(366 * 50); // 50 years and 1 day static const base::TimeDelta kTimeUntilNextSync = base::TimeDelta::FromDays(11); InitializeServiceSuccessfully(); fake_cryptauth_enrollment_manager()->set_last_enrollment_time( base::Time::FromDeltaSinceWindowsEpoch( kTimeBetweenEpochAndLastEnrollment)); fake_cryptauth_enrollment_manager()->set_time_to_next_attempt( kTimeUntilNextEnrollment); fake_cryptauth_enrollment_manager()->set_is_recovering_from_failure(false); fake_cryptauth_enrollment_manager()->set_is_enrollment_in_progress(true); fake_cryptauth_device_manager()->set_last_sync_time( base::Time::FromDeltaSinceWindowsEpoch(kTimeBetweenEpochAndLastSync)); fake_cryptauth_device_manager()->set_time_to_next_attempt(kTimeUntilNextSync); fake_cryptauth_device_manager()->set_is_recovering_from_failure(true); fake_cryptauth_device_manager()->set_is_sync_in_progress(false); const auto& result = CallGetDebugInfo(); EXPECT_TRUE(result); EXPECT_EQ(base::Time::FromDeltaSinceWindowsEpoch( kTimeBetweenEpochAndLastEnrollment), result->last_enrollment_time); EXPECT_EQ(base::TimeDelta(kTimeUntilNextEnrollment), result->time_to_next_enrollment_attempt); EXPECT_FALSE(result->is_recovering_from_enrollment_failure); EXPECT_TRUE(result->is_enrollment_in_progress); EXPECT_EQ( base::Time::FromDeltaSinceWindowsEpoch(kTimeBetweenEpochAndLastSync), result->last_sync_time); EXPECT_EQ(base::TimeDelta(kTimeUntilNextSync), result->time_to_next_sync_attempt); EXPECT_TRUE(result->is_recovering_from_sync_failure); EXPECT_FALSE(result->is_sync_in_progress); } } // namespace device_sync } // namespace chromeos
39.652756
80
0.751862
zipated
80a49d0b178fd45b17cea7f733fbad3dd6c45773
1,424
hpp
C++
Win32/MMKV/PBEncodeItem.hpp
SimonRHW/MMKV
b5ced7120b542e59ccce8c33e29a101dd93d4298
[ "Apache-2.0" ]
2
2021-10-03T19:29:23.000Z
2021-11-17T10:34:27.000Z
Win32/MMKV/PBEncodeItem.hpp
LuckyPerry/MMKV
01ad79e8031c6700537e412f290c392088de1460
[ "Apache-2.0" ]
null
null
null
Win32/MMKV/PBEncodeItem.hpp
LuckyPerry/MMKV
01ad79e8031c6700537e412f290c392088de1460
[ "Apache-2.0" ]
1
2020-03-06T07:14:57.000Z
2020-03-06T07:14:57.000Z
/* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 MMKV_PBENCODEITEM_HPP #define MMKV_PBENCODEITEM_HPP #include "MMBuffer.h" #include <cstdint> #include <memory.h> #include <string> namespace mmkv { enum PBEncodeItemType { PBEncodeItemType_None, PBEncodeItemType_String, PBEncodeItemType_Data, PBEncodeItemType_Container, }; struct PBEncodeItem { PBEncodeItemType type; uint32_t compiledSize; uint32_t valueSize; union { const std::string *strValue; const MMBuffer *bufferValue; } value; PBEncodeItem() : type(PBEncodeItemType_None), compiledSize(0), valueSize(0) { memset(&value, 0, sizeof(value)); } }; } // namespace mmkv #endif //MMKV_PBENCODEITEM_HPP
25.890909
81
0.722612
SimonRHW
80b0f3e0ba55bd103b47a0208fe1c079d70a15d7
19,155
cpp
C++
src/corehost/cli/deps_resolver.cpp
krytarowski/cli
e4d7fa5bc4841f55662804c6999ff29e2b7075b0
[ "MIT" ]
null
null
null
src/corehost/cli/deps_resolver.cpp
krytarowski/cli
e4d7fa5bc4841f55662804c6999ff29e2b7075b0
[ "MIT" ]
null
null
null
src/corehost/cli/deps_resolver.cpp
krytarowski/cli
e4d7fa5bc4841f55662804c6999ff29e2b7075b0
[ "MIT" ]
7
2017-04-11T14:01:50.000Z
2022-03-30T21:52:56.000Z
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <set> #include <functional> #include <cassert> #include "trace.h" #include "deps_entry.h" #include "deps_format.h" #include "deps_resolver.h" #include "utils.h" #include "fx_ver.h" #include "libhost.h" namespace { // ----------------------------------------------------------------------------- // A uniqifying append helper that doesn't let two entries with the same // "asset_name" be part of the "output" paths. // void add_tpa_asset( const pal::string_t& asset_name, const pal::string_t& asset_path, std::set<pal::string_t>* items, pal::string_t* output) { if (items->count(asset_name)) { return; } trace::verbose(_X("Adding tpa entry: %s"), asset_path.c_str()); // Workaround for CoreFX not being able to resolve sym links. pal::string_t real_asset_path = asset_path; pal::realpath(&real_asset_path); output->append(real_asset_path); output->push_back(PATH_SEPARATOR); items->insert(asset_name); } // ----------------------------------------------------------------------------- // A uniqifying append helper that doesn't let two "paths" to be identical in // the "output" string. // void add_unique_path( deps_entry_t::asset_types asset_type, const pal::string_t& path, std::set<pal::string_t>* existing, pal::string_t* output) { // Resolve sym links. pal::string_t real = path; pal::realpath(&real); if (existing->count(real)) { return; } trace::verbose(_X("Adding to %s path: %s"), deps_entry_t::s_known_asset_types[asset_type], real.c_str()); output->append(real); output->push_back(PATH_SEPARATOR); existing->insert(real); } } // end of anonymous namespace // ----------------------------------------------------------------------------- // Load local assemblies by priority order of their file extensions and // unique-fied by their simple name. // void deps_resolver_t::get_dir_assemblies( const pal::string_t& dir, const pal::string_t& dir_name, dir_assemblies_t* dir_assemblies) { trace::verbose(_X("Adding files from %s dir %s"), dir_name.c_str(), dir.c_str()); // Managed extensions in priority order, pick DLL over EXE and NI over IL. const pal::string_t managed_ext[] = { _X(".ni.dll"), _X(".dll"), _X(".ni.exe"), _X(".exe") }; // List of files in the dir std::vector<pal::string_t> files; pal::readdir(dir, &files); for (const auto& ext : managed_ext) { for (const auto& file : files) { // Nothing to do if file length is smaller than expected ext. if (file.length() <= ext.length()) { continue; } auto file_name = file.substr(0, file.length() - ext.length()); auto file_ext = file.substr(file_name.length()); // Ext did not match expected ext, skip this file. if (pal::strcasecmp(file_ext.c_str(), ext.c_str())) { continue; } // Already added entry for this asset, by priority order skip this ext if (dir_assemblies->count(file_name)) { trace::verbose(_X("Skipping %s because the %s already exists in %s assemblies"), file.c_str(), dir_assemblies->find(file_name)->second.c_str(), dir_name.c_str()); continue; } // Add entry for this asset pal::string_t file_path = dir + DIR_SEPARATOR + file; trace::verbose(_X("Adding %s to %s assembly set from %s"), file_name.c_str(), dir_name.c_str(), file_path.c_str()); dir_assemblies->emplace(file_name, file_path); } } } bool deps_resolver_t::try_roll_forward(const deps_entry_t& entry, const pal::string_t& probe_dir, pal::string_t* candidate) { trace::verbose(_X("Attempting a roll forward for [%s/%s/%s] in [%s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str(), probe_dir.c_str()); const pal::string_t& lib_ver = entry.library_version; fx_ver_t cur_ver(-1, -1, -1); if (!fx_ver_t::parse(lib_ver, &cur_ver, false)) { trace::verbose(_X("No roll forward as specified version [%s] could not be parsed"), lib_ver.c_str()); return false; } // Extract glob string of the form: 1.0.* from the version 1.0.0-prerelease-00001. size_t pat_start = lib_ver.find(_X('.'), lib_ver.find(_X('.')) + 1); pal::string_t maj_min_star = lib_ver.substr(0, pat_start + 1) + _X('*'); pal::string_t path = probe_dir; append_path(&path, entry.library_name.c_str()); pal::string_t cache_key = path; append_path(&cache_key, maj_min_star.c_str()); pal::string_t max_str; if (m_roll_forward_cache.count(cache_key)) { max_str = m_roll_forward_cache[cache_key]; trace::verbose(_X("Found cached roll forward version [%s] -> [%s]"), lib_ver.c_str(), max_str.c_str()); } else { try_patch_roll_forward_in_dir(path, cur_ver, &max_str, true); m_roll_forward_cache[cache_key] = max_str; } append_path(&path, max_str.c_str()); return entry.to_rel_path(path, candidate); } void deps_resolver_t::setup_probe_config( const corehost_init_t* init, const runtime_config_t& config, const arguments_t& args) { if (pal::directory_exists(args.dotnet_extensions)) { pal::string_t ext_ni = args.dotnet_extensions; append_path(&ext_ni, get_arch()); if (pal::directory_exists(ext_ni)) { // Servicing NI probe. m_probes.push_back(probe_config_t::svc_ni(ext_ni, config.get_fx_roll_fwd())); } // Servicing normal probe. m_probes.push_back(probe_config_t::svc(args.dotnet_extensions, config.get_fx_roll_fwd())); } if (pal::directory_exists(args.dotnet_packages_cache)) { pal::string_t ni_packages_cache = args.dotnet_packages_cache; append_path(&ni_packages_cache, get_arch()); if (pal::directory_exists(ni_packages_cache)) { // Packages cache NI probe m_probes.push_back(probe_config_t::cache_ni(ni_packages_cache)); } // Packages cache probe m_probes.push_back(probe_config_t::cache(args.dotnet_packages_cache)); } if (pal::directory_exists(m_fx_dir)) { // FX probe m_probes.push_back(probe_config_t::fx(m_fx_dir, m_fx_deps.get())); } for (const auto& probe : m_additional_probes) { // Additional paths bool roll_fwd = config.get_fx_roll_fwd(); m_probes.push_back(probe_config_t::additional(probe, roll_fwd)); } if (trace::is_enabled()) { trace::verbose(_X("-- Listing probe configurations...")); for (const auto& pc : m_probes) { pc.print(); } } } void deps_resolver_t::setup_additional_probes(const std::vector<pal::string_t>& probe_paths) { m_additional_probes.assign(probe_paths.begin(), probe_paths.end()); for (auto iter = m_additional_probes.begin(); iter != m_additional_probes.end(); ) { if (pal::directory_exists(*iter)) { ++iter; } else { iter = m_additional_probes.erase(iter); } } } bool deps_resolver_t::probe_entry_in_configs(const deps_entry_t& entry, pal::string_t* candidate) { candidate->clear(); for (const auto& config : m_probes) { trace::verbose(_X(" Considering entry [%s/%s/%s] and probe dir [%s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str(), config.probe_dir.c_str()); if (config.only_serviceable_assets && !entry.is_serviceable) { trace::verbose(_X(" Skipping... not serviceable asset")); continue; } if (config.only_runtime_assets && entry.asset_type != deps_entry_t::asset_types::runtime) { trace::verbose(_X(" Skipping... not runtime asset")); continue; } pal::string_t probe_dir = config.probe_dir; if (config.match_hash) { if (entry.to_hash_matched_path(probe_dir, candidate)) { assert(!config.roll_forward); trace::verbose(_X(" Matched hash for [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... match hash failed")); } else if (config.probe_deps_json) { // If the deps json has it then someone has already done rid selection and put the right stuff in the dir. // So checking just package name and version would suffice. No need to check further for the exact asset relative path. if (config.probe_deps_json->has_package(entry.library_name, entry.library_version) && entry.to_dir_path(probe_dir, candidate)) { trace::verbose(_X(" Probed deps json and matched [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... probe in deps json failed")); } else if (!config.roll_forward) { if (entry.to_full_path(probe_dir, candidate)) { trace::verbose(_X(" Specified no roll forward; matched [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... not found in probe dir")); } else if (config.roll_forward) { if (try_roll_forward(entry, probe_dir, candidate)) { trace::verbose(_X(" Specified roll forward; matched [%s]"), candidate->c_str()); return true; } trace::verbose(_X(" Skipping... could not roll forward and match in probe dir")); } // continue to try next probe config } return false; } // ----------------------------------------------------------------------------- // Resolve coreclr directory from the deps file. // // Description: // Look for CoreCLR from the dependency list in the package cache and then // the packages directory. // pal::string_t deps_resolver_t::resolve_coreclr_dir() { auto process_coreclr = [&] (bool is_portable, const pal::string_t& deps_dir, deps_json_t* deps) -> pal::string_t { pal::string_t candidate; if (deps->has_coreclr_entry()) { const deps_entry_t& entry = deps->get_coreclr_entry(); if (probe_entry_in_configs(entry, &candidate)) { return get_directory(candidate); } else if (entry.is_rid_specific && entry.to_rel_path(deps_dir, &candidate)) { return get_directory(candidate); } } else { trace::verbose(_X("Deps has no coreclr entry.")); } // App/FX main dir or standalone app dir. trace::verbose(_X("Probing for CoreCLR in deps directory=[%s]"), deps_dir.c_str()); if (coreclr_exists_in_dir(deps_dir)) { return deps_dir; } return pal::string_t(); }; trace::info(_X("-- Starting CoreCLR Probe from app deps.json")); pal::string_t clr_dir = process_coreclr(m_portable, m_app_dir, m_deps.get()); if (clr_dir.empty() && m_portable) { trace::info(_X("-- Starting CoreCLR Probe from FX deps.json")); clr_dir = process_coreclr(false, m_fx_dir, m_fx_deps.get()); } if (!clr_dir.empty()) { return clr_dir; } // Use platform-specific search algorithm pal::string_t install_dir; if (pal::find_coreclr(&install_dir)) { return install_dir; } return pal::string_t(); } void deps_resolver_t::resolve_tpa_list( const pal::string_t& clr_dir, pal::string_t* output) { const std::vector<deps_entry_t> empty(0); // Obtain the local assemblies in the app dir. get_dir_assemblies(m_app_dir, _X("local"), &m_local_assemblies); if (m_portable) { // For portable also obtain FX dir assemblies. get_dir_assemblies(m_fx_dir, _X("fx"), &m_fx_assemblies); } std::set<pal::string_t> items; auto process_entry = [&](const pal::string_t& deps_dir, deps_json_t* deps, const dir_assemblies_t& dir_assemblies, const deps_entry_t& entry) { if (items.count(entry.asset_name)) { return; } pal::string_t candidate; trace::info(_X("Processing TPA for deps entry [%s, %s, %s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str()); // Try to probe from the shared locations. if (probe_entry_in_configs(entry, &candidate)) { add_tpa_asset(entry.asset_name, candidate, &items, output); } // The rid asset should be picked up from app relative subpath. else if (entry.is_rid_specific && entry.to_rel_path(deps_dir, &candidate)) { add_tpa_asset(entry.asset_name, candidate, &items, output); } // The rid-less asset should be picked up from the app base. else if (dir_assemblies.count(entry.asset_name)) { add_tpa_asset(entry.asset_name, dir_assemblies.find(entry.asset_name)->second, &items, output); } else { // FIXME: Consider this error as a fail fast? trace::verbose(_X("Error: Could not resolve path to assembly: [%s, %s, %s]"), entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str()); } }; const auto& deps_entries = m_deps->get_entries(deps_entry_t::asset_types::runtime); std::for_each(deps_entries.begin(), deps_entries.end(), [&](const deps_entry_t& entry) { process_entry(m_app_dir, m_deps.get(), m_local_assemblies, entry); }); // Finally, if the deps file wasn't present or has missing entries, then // add the app local assemblies to the TPA. for (const auto& kv : m_local_assemblies) { add_tpa_asset(kv.first, kv.second, &items, output); } const auto& fx_entries = m_portable ? m_fx_deps->get_entries(deps_entry_t::asset_types::runtime) : empty; std::for_each(fx_entries.begin(), fx_entries.end(), [&](const deps_entry_t& entry) { process_entry(m_fx_dir, m_fx_deps.get(), m_fx_assemblies, entry); }); for (const auto& kv : m_fx_assemblies) { add_tpa_asset(kv.first, kv.second, &items, output); } } // ----------------------------------------------------------------------------- // Resolve the directories order for resources/native lookup // // Description: // This general purpose function specifies priority order of directory lookup // for both native images and resources specific resource images. Lookup for // resources assemblies is done by looking up two levels above from the file // path. Lookup for native images is done by looking up one level from the // file path. // // Parameters: // asset_type - The type of the asset that needs lookup, currently // supports "resources" and "native" // app_dir - The application local directory // package_dir - The directory path to where packages are restored // package_cache_dir - The directory path to secondary cache for packages // clr_dir - The directory where the host loads the CLR // // Returns: // output - Pointer to a string that will hold the resolved lookup dirs // void deps_resolver_t::resolve_probe_dirs( deps_entry_t::asset_types asset_type, const pal::string_t& clr_dir, pal::string_t* output) { bool is_resources = asset_type == deps_entry_t::asset_types::resources; assert(is_resources || asset_type == deps_entry_t::asset_types::native); // For resources assemblies, we need to provide the base directory of the resources path. // For example: .../Foo/en-US/Bar.dll, then, the resolved path is .../Foo std::function<pal::string_t(const pal::string_t&)> resources = [] (const pal::string_t& str) { return get_directory(get_directory(str)); }; // For native assemblies, obtain the directory path from the file path std::function<pal::string_t(const pal::string_t&)> native = [] (const pal::string_t& str) { return get_directory(str); }; std::function<pal::string_t(const pal::string_t&)>& action = is_resources ? resources : native; std::set<pal::string_t> items; std::vector<deps_entry_t> empty(0); const auto& entries = m_deps->get_entries(asset_type); const auto& fx_entries = m_portable ? m_fx_deps->get_entries(asset_type) : empty; pal::string_t candidate; auto add_package_cache_entry = [&](const deps_entry_t& entry) { if (probe_entry_in_configs(entry, &candidate)) { add_unique_path(asset_type, action(candidate), &items, output); } }; std::for_each(entries.begin(), entries.end(), add_package_cache_entry); std::for_each(fx_entries.begin(), fx_entries.end(), add_package_cache_entry); // For portable rid specific assets, the app relative directory must be used. if (m_portable) { std::for_each(entries.begin(), entries.end(), [&](const deps_entry_t& entry) { if (entry.is_rid_specific && entry.asset_type == asset_type && entry.to_rel_path(m_app_dir, &candidate)) { add_unique_path(asset_type, action(candidate), &items, output); } }); } // App local path add_unique_path(asset_type, m_app_dir, &items, output); // FX path if present if (!m_fx_dir.empty()) { add_unique_path(asset_type, m_fx_dir, &items, output); } // CLR path add_unique_path(asset_type, clr_dir, &items, output); } // ----------------------------------------------------------------------------- // Entrypoint to resolve TPA, native and resources path ordering to pass to CoreCLR. // // Parameters: // app_dir - The application local directory // package_dir - The directory path to where packages are restored // package_cache_dir - The directory path to secondary cache for packages // clr_dir - The directory where the host loads the CLR // probe_paths - Pointer to struct containing fields that will contain // resolved path ordering. // // bool deps_resolver_t::resolve_probe_paths(const pal::string_t& clr_dir, probe_paths_t* probe_paths) { resolve_tpa_list(clr_dir, &probe_paths->tpa); resolve_probe_dirs(deps_entry_t::asset_types::native, clr_dir, &probe_paths->native); resolve_probe_dirs(deps_entry_t::asset_types::resources, clr_dir, &probe_paths->resources); return true; }
35.472222
194
0.612895
krytarowski
80b100f60c6d0e763ea6b43dcf91ef52b9133aa0
2,376
cpp
C++
samples/View3D/code/view3d.cpp
elementsinteractive/edgelib
dedd72a05af274a5c30c076748c7c6f459fbd040
[ "BSD-3-Clause" ]
14
2017-08-22T22:27:18.000Z
2021-05-04T09:00:09.000Z
samples/View3D/code/view3d.cpp
elementsinteractive/edgelib
dedd72a05af274a5c30c076748c7c6f459fbd040
[ "BSD-3-Clause" ]
1
2018-03-15T06:06:01.000Z
2018-03-20T01:44:44.000Z
samples/View3D/code/view3d.cpp
elementsinteractive/edgelib
dedd72a05af274a5c30c076748c7c6f459fbd040
[ "BSD-3-Clause" ]
4
2018-03-22T17:14:14.000Z
2020-08-02T18:42:55.000Z
// code/view3d.cpp // One of the Edge samples // Shows how to create a 3D model manually and how to load a .3DS // file. Rotate the model based on input. // // Show a 3D model on the screen, rotate it with the d-pad or stylus // // Copyright (c) 2004-2017 Elements Interactive B.V. ///////////////////////////////////////////////////////////////////// //Use Windows Desktop OpenGL by default #if !defined(__EDGEIDE__) #if !defined(DEVICE_LINUX) #define EGL_PC #endif #endif ///////////////////////////////////////////////////////////////////// // Include and link the library // ///////////////////////////////////////////////////////////////////// //Use a GL library if an implementation has been defined in the workspace #if defined(EGL_PC) || defined(EGL_SYMBIAN) || defined(EGL_RASTEROID) || defined(EGL_POWERVR) || defined(EGL_NVIDIA) #define EGL_USEGL #if !defined(EGL_PC) #define EGL_USEGLES #endif #endif //Include Edge #include "edgemain.h" //Link the Edge static library #pragma comment(lib, "edge.lib") //Include headers and link OpenGL libraries #if defined(EGL_USEGL) #if defined(EGL_USEGLES) #include "GLES\\gl.h" #include "GLES\\egl.h" #else #include "GL\\gl.h" #endif #if defined(DEVICE_WIN32) #if defined(EGL_PC) #pragma comment(lib, "plugingl.lib") #else #if defined(DEVICE_DESKTOP) #if defined(EGL_POWERVR) #pragma comment(lib, "pluginpowervr.lib") #elif defined(EGL_RASTEROID) #pragma comment(lib, "pluginrasteroid.lib") #endif #else #pragma comment(lib, "plugin1-0.lib") #endif #endif #if defined(EGL_PC) #pragma comment(lib, "opengl32.lib") #elif defined(EGL_POWERVR) #pragma comment(lib, "libgles_cl.lib") #elif defined(EGL_NVIDIA) #pragma comment(lib, "libgles_cm.lib") #elif defined(EGL_RASTEROID) #pragma comment(lib, "libEGL.lib") #pragma comment(lib, "libGLES_CM_NoE.lib") #endif #endif #endif //Contains ClassMain, the application framework #include "main.h" ///////////////////////////////////////////////////////////////////// // The program entry point // ///////////////////////////////////////////////////////////////////// ClassEdge *EdgeMain(EDGESTARTUP *data){ return(new ClassMain); }
29.7
117
0.558923
elementsinteractive
80b2d3a6805b8fade32a858d5ffeec00f33b0fac
869
cpp
C++
Engine/Flora/Application/Window.cpp
chgalante/flora
17db42ce92925c5e9e5e3a9084747553a27cfa96
[ "MIT" ]
1
2021-07-09T03:32:51.000Z
2021-07-09T03:32:51.000Z
Engine/Flora/Application/Window.cpp
chgalante/flora
17db42ce92925c5e9e5e3a9084747553a27cfa96
[ "MIT" ]
1
2021-08-21T19:13:15.000Z
2021-08-21T19:13:15.000Z
Engine/Flora/Application/Window.cpp
chgalante/flora
17db42ce92925c5e9e5e3a9084747553a27cfa96
[ "MIT" ]
null
null
null
#include "Window.hpp" #include "Flora/Base.hpp" #include "Flora/Utilities/Log.hpp" namespace FloraEngine { Window::Window() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwInit(); pWindow = glfwCreateWindow(1280, 720, "FloraEngine", NULL, NULL); if (!pWindow) { FE_CORE_CRITICAL("GLFW failed to create window"); } glfwMakeContextCurrent(pWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { FE_CORE_CRITICAL("Failed to initialize OpenGL Context!"); } glViewport(0, 0, 640, 480); } bool Window::OnUpdate() { glfwPollEvents(); glfwSwapBuffers(pWindow); /* Returns false if the window should close to signal app termination */ return !glfwWindowShouldClose(pWindow); } } // namespace FloraEngine
24.828571
74
0.742232
chgalante
80b36556e1621a6cafe80a83abb7340d361e92c2
7,859
cpp
C++
src/Tools/GenerateMap.cpp
Chae4ek/7bits-CG-2020
81cefb5b88ce39751d6bab0c4fe9177bcf5210ee
[ "Apache-2.0" ]
null
null
null
src/Tools/GenerateMap.cpp
Chae4ek/7bits-CG-2020
81cefb5b88ce39751d6bab0c4fe9177bcf5210ee
[ "Apache-2.0" ]
null
null
null
src/Tools/GenerateMap.cpp
Chae4ek/7bits-CG-2020
81cefb5b88ce39751d6bab0c4fe9177bcf5210ee
[ "Apache-2.0" ]
null
null
null
#include "Tools/GenerateMap.h" unsigned int Generate::_SEED_RANDOM = 1; Generate::Generate(MapManager* map_manager, Position* player) : map_manager(map_manager), player(player) {} void Generate::TryGenerateChunk(const chunk_coords_t chunk_coords) { if (!map_manager->ChunkIsEmpty(chunk_coords)) return; map_manager->entities[map_manager->GetLevel()][chunk_coords].reserve(0); const chunk_coords_t chunk_global_pos = std::make_pair(chunk_coords.first * map_manager->size_x, chunk_coords.second * map_manager->size_y); for (int x = 0; x < map_manager->size_x; ++x) { for (int y = 0; y < map_manager->size_y; ++y) { const int structure_type = GetStructureType(chunk_global_pos, x + chunk_global_pos.first, y + chunk_global_pos.second); FILE* file = nullptr; ReaderStruct reader(x, y); bool generate = true; std::string struct_path = ""; if (map_manager->GetLevel() < 0) struct_path = "./Structures/hub" + std::to_string(map_manager->GetLevel()); else if (structure_type < 0) struct_path = "./Structures/struct" + std::to_string(structure_type); if (struct_path != "") { file = fopen(struct_path.c_str(), "rb"); generate = reader.SetStruct(file); } const struct_info info = reader.GetInfo(); if (info.x_bot < map_manager->size_x && info.y_bot < map_manager->size_y) { auto info_it = std::find_if(temp_structures.begin(), temp_structures.end(), [info](struct_info i) { // checking intersection of "info" and "i" structures return info.x_top <= i.x_bot && info.y_top <= i.y_bot && info.x_bot >= i.x_top && info.y_bot >= i.y_top; }); if (info_it != temp_structures.end()) { y = info_it->y_bot; // for speed up if (info_it->x_bot == x) temp_structures.erase(info_it); } else { // if none intersection if (generate) { if (info.x_top == info.x_bot && info.y_top == info.y_bot) { CreateEntity(&reader, ENTITY_TYPE(structure_type), chunk_coords, info.x_top, info.y_top); } else { if (info.x_top != info.x_bot) temp_structures.push_back(info); // if(...) for speed up for (int i = info.x_top; i <= info.x_bot; ++i) for (int j = info.y_top; j <= info.y_bot; ++j) CreateEntity(&reader, ENTITY_TYPE(reader.GetNext()), chunk_coords, i, j); } } } } if (file) fclose(file); } } } void Generate::CreateEntity(const ReaderStruct* reader, const ENTITY_TYPE type, const chunk_coords_t chunk_coords, const int x, const int y) { if (type == TYPE_PLAYER) { if (map_manager->LevelIsEmpty(map_manager->GetLevel())) { player->pos_x = x; player->pos_y = y; map_manager->SaveFirstPlayerPosition(); } } else if (type != TYPE_NULL) { Entity entity(Type(type), map_manager->GlobalToLocal(Position(x, y)), Sprite(PREFABS.at(type).texture, PREFABS.at(type).color, PREFABS.at(type).hex_texture)); // TODO: replace to dictionary ? if (type == TYPE_EXIT) { int level = reader->GetNext(); if (map_manager->GetLevel() > 0) level += map_manager->GetLevel(); if (!level) --level; entity.Add(LevelExit(level)); } else if (type == TYPE_SWORD || type == TYPE_BOMB || type == TYPE_CHEST) { const int durability = Random() % 3 + 1; const int health_damage = Random() % 5 + 1; const int armor_damage = Random() % 3 + 1; entity.Add(Weapon(durability, health_damage, armor_damage)); const int type = Random() % 2; if (type == TYPE_CHEST) entity.Add(ChestType(type ? TYPE_SWORD : TYPE_BOMB)); } else if (type == TYPE_ENEMY) { const int health = Random() % 4 + 1; const int armor = Random() % 5; entity.Add(Defense(health, armor), GameStats()); } map_manager->CreateEntity(chunk_coords, std::move(entity)); } } int Generate::GetStructureType(const chunk_coords_t chunk_global_pos, const int x, const int y) const { if (map_manager->GetLevel() < 6) return L1(chunk_global_pos, x, y); else return L2(chunk_global_pos, x, y); } int Generate::L1(const chunk_coords_t chunk_global_pos, const int x, const int y) const { if (!x && !y) return -104781600; const double noise = PerlinNoise(x / smooth, y / smooth); Srand(map_manager->seed, x * map_manager->size_x, y * map_manager->size_y); const bool rand = Random() % 2; if ((noise > threshold + sharp || rand) && ((noise > threshold - sharp && rand) || noise > threshold)) return TYPE_WALL; const int seed1 = Random() + chunk_global_pos.first; const int seed2 = Random() + chunk_global_pos.second; Srand(map_manager->seed, seed1, seed2); if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / coin_chance) == 0) return TYPE_COIN; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / chest_chance) == 0) return TYPE_CHEST; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / sword_chance) == 0) return TYPE_SWORD; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / bomb_chance) == 0) return TYPE_BOMB; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / enemy_chance) == 0) return TYPE_ENEMY; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / structures_chance) == 0) return -Random() % structures_count - 1; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / exit_chance) == 0) return -10477; return TYPE_NULL; } int Generate::L2(const chunk_coords_t chunk_global_pos, const int x, const int y) const { const int x0 = x - map_manager->size_x / 2; const int y0 = y - map_manager->size_y / 2; if (!x0 && !y0) return -104781600; Srand(map_manager->seed, x * map_manager->size_x, y * map_manager->size_y); const int seed1 = Random() + chunk_global_pos.first; const int seed2 = Random() + chunk_global_pos.second; Srand(map_manager->seed, seed1, seed2); if (x0 * x0 + y0 * y0 > 120) return TYPE_WALL; if (Random() % static_cast<int>(map_manager->size_x * map_manager->size_y / coin_chance / coin_chance) == 0) return TYPE_COIN; // TODO: something else return TYPE_NULL; } double Generate::PerlinNoise(const double x, const double y) const { const int x0 = static_cast<int>(x); const int y0 = static_cast<int>(y); const int x1 = x0 + 1; const int y1 = y0 + 1; const double tx = x - x0; double d1, d2, lerp_x_top, lerp_x_bottom; d1 = DotGradient(x0, y0, x, y); d2 = DotGradient(x1, y0, x, y); lerp_x_top = Lerp(d1, d2, tx); d1 = DotGradient(x0, y1, x, y); d2 = DotGradient(x1, y1, x, y); lerp_x_bottom = Lerp(d1, d2, tx); double lerp_xy = Lerp(lerp_x_top, lerp_x_bottom, y - y0); if (lerp_xy < 0) lerp_xy *= -1; return lerp_xy; } double Generate::DotGradient(int rand_x, int rand_y, double x, double y) const { Srand(map_manager->seed, rand_x, rand_y); const int r = Random() % 4; x -= rand_x; y -= rand_y; if (r == 0) rand_x = 0, rand_y = 1; else if (r == 1) rand_x = 0, rand_y = -1; else if (r == 2) rand_x = 1, rand_y = 0; else rand_x = -1, rand_y = 0; return x * rand_x + y * rand_y; } constexpr double Generate::Lerp(const double a, const double b, double t) const { t = t * t * t * (t * (t * 6 - 15) + 10); return a + (b - a) * t; } inline int Generate::Random() { _SEED_RANDOM = 214013 * _SEED_RANDOM + 2531011; return static_cast<unsigned int>(_SEED_RANDOM / 65536) % 32768; } inline void Generate::Srand(const unsigned int seed, const int seed1, const int seed2) { _SEED_RANDOM = seed; _SEED_RANDOM = seed1 + Random(); _SEED_RANDOM = seed2 + Random(); }
38.336585
116
0.641048
Chae4ek
80b794261b24c116f1d8fc931963ea076b4bd6da
238,988
cpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_mobileip_cfg.cpp
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_ip_mobileip_cfg.cpp
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_ip_mobileip_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XR_ip_mobileip_cfg.hpp" using namespace ydk; namespace cisco_ios_xr { namespace Cisco_IOS_XR_ip_mobileip_cfg { MobileIp::MobileIp() : domains(std::make_shared<MobileIp::Domains>()) , lmas(std::make_shared<MobileIp::Lmas>()) { domains->parent = this; lmas->parent = this; yang_name = "mobile-ip"; yang_parent_name = "Cisco-IOS-XR-ip-mobileip-cfg"; is_top_level_class = true; has_list_ancestor = false; } MobileIp::~MobileIp() { } bool MobileIp::has_data() const { if (is_presence_container) return true; return (domains != nullptr && domains->has_data()) || (lmas != nullptr && lmas->has_data()); } bool MobileIp::has_operation() const { return is_set(yfilter) || (domains != nullptr && domains->has_operation()) || (lmas != nullptr && lmas->has_operation()); } std::string MobileIp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ip-mobileip-cfg:mobile-ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "domains") { if(domains == nullptr) { domains = std::make_shared<MobileIp::Domains>(); } return domains; } if(child_yang_name == "lmas") { if(lmas == nullptr) { lmas = std::make_shared<MobileIp::Lmas>(); } return lmas; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(domains != nullptr) { _children["domains"] = domains; } if(lmas != nullptr) { _children["lmas"] = lmas; } return _children; } void MobileIp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> MobileIp::clone_ptr() const { return std::make_shared<MobileIp>(); } std::string MobileIp::get_bundle_yang_models_location() const { return ydk_cisco_ios_xr_models_path; } std::string MobileIp::get_bundle_name() const { return "cisco_ios_xr"; } augment_capabilities_function MobileIp::get_augment_capabilities_function() const { return cisco_ios_xr_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> MobileIp::get_namespace_identity_lookup() const { return cisco_ios_xr_namespace_identity_lookup; } bool MobileIp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "domains" || name == "lmas") return true; return false; } MobileIp::Domains::Domains() : domain(this, {"domain_name"}) { yang_name = "domains"; yang_parent_name = "mobile-ip"; is_top_level_class = false; has_list_ancestor = false; } MobileIp::Domains::~Domains() { } bool MobileIp::Domains::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<domain.len(); index++) { if(domain[index]->has_data()) return true; } return false; } bool MobileIp::Domains::has_operation() const { for (std::size_t index=0; index<domain.len(); index++) { if(domain[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Domains::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ip-mobileip-cfg:mobile-ip/" << get_segment_path(); return path_buffer.str(); } std::string MobileIp::Domains::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "domains"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "domain") { auto ent_ = std::make_shared<MobileIp::Domains::Domain>(); ent_->parent = this; domain.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : domain.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Domains::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Domains::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Domains::has_leaf_or_child_of_name(const std::string & name) const { if(name == "domain") return true; return false; } MobileIp::Domains::Domain::Domain() : domain_name{YType::str, "domain-name"}, enable{YType::empty, "enable"} , mags(std::make_shared<MobileIp::Domains::Domain::Mags>()) , nais(std::make_shared<MobileIp::Domains::Domain::Nais>()) , authenticate_option(std::make_shared<MobileIp::Domains::Domain::AuthenticateOption>()) , lmas(std::make_shared<MobileIp::Domains::Domain::Lmas>()) { mags->parent = this; nais->parent = this; authenticate_option->parent = this; lmas->parent = this; yang_name = "domain"; yang_parent_name = "domains"; is_top_level_class = false; has_list_ancestor = false; } MobileIp::Domains::Domain::~Domain() { } bool MobileIp::Domains::Domain::has_data() const { if (is_presence_container) return true; return domain_name.is_set || enable.is_set || (mags != nullptr && mags->has_data()) || (nais != nullptr && nais->has_data()) || (authenticate_option != nullptr && authenticate_option->has_data()) || (lmas != nullptr && lmas->has_data()); } bool MobileIp::Domains::Domain::has_operation() const { return is_set(yfilter) || ydk::is_set(domain_name.yfilter) || ydk::is_set(enable.yfilter) || (mags != nullptr && mags->has_operation()) || (nais != nullptr && nais->has_operation()) || (authenticate_option != nullptr && authenticate_option->has_operation()) || (lmas != nullptr && lmas->has_operation()); } std::string MobileIp::Domains::Domain::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ip-mobileip-cfg:mobile-ip/domains/" << get_segment_path(); return path_buffer.str(); } std::string MobileIp::Domains::Domain::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "domain"; ADD_KEY_TOKEN(domain_name, "domain-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (domain_name.is_set || is_set(domain_name.yfilter)) leaf_name_data.push_back(domain_name.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mags") { if(mags == nullptr) { mags = std::make_shared<MobileIp::Domains::Domain::Mags>(); } return mags; } if(child_yang_name == "nais") { if(nais == nullptr) { nais = std::make_shared<MobileIp::Domains::Domain::Nais>(); } return nais; } if(child_yang_name == "authenticate-option") { if(authenticate_option == nullptr) { authenticate_option = std::make_shared<MobileIp::Domains::Domain::AuthenticateOption>(); } return authenticate_option; } if(child_yang_name == "lmas") { if(lmas == nullptr) { lmas = std::make_shared<MobileIp::Domains::Domain::Lmas>(); } return lmas; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(mags != nullptr) { _children["mags"] = mags; } if(nais != nullptr) { _children["nais"] = nais; } if(authenticate_option != nullptr) { _children["authenticate-option"] = authenticate_option; } if(lmas != nullptr) { _children["lmas"] = lmas; } return _children; } void MobileIp::Domains::Domain::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "domain-name") { domain_name = value; domain_name.value_namespace = name_space; domain_name.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } } void MobileIp::Domains::Domain::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "domain-name") { domain_name.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } } bool MobileIp::Domains::Domain::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mags" || name == "nais" || name == "authenticate-option" || name == "lmas" || name == "domain-name" || name == "enable") return true; return false; } MobileIp::Domains::Domain::Mags::Mags() : mag(this, {"mag_name"}) { yang_name = "mags"; yang_parent_name = "domain"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::Mags::~Mags() { } bool MobileIp::Domains::Domain::Mags::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mag.len(); index++) { if(mag[index]->has_data()) return true; } return false; } bool MobileIp::Domains::Domain::Mags::has_operation() const { for (std::size_t index=0; index<mag.len(); index++) { if(mag[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Domains::Domain::Mags::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mags"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::Mags::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::Mags::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mag") { auto ent_ = std::make_shared<MobileIp::Domains::Domain::Mags::Mag>(); ent_->parent = this; mag.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::Mags::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mag.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Domains::Domain::Mags::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Domains::Domain::Mags::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Domains::Domain::Mags::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mag") return true; return false; } MobileIp::Domains::Domain::Mags::Mag::Mag() : mag_name{YType::str, "mag-name"} { yang_name = "mag"; yang_parent_name = "mags"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::Mags::Mag::~Mag() { } bool MobileIp::Domains::Domain::Mags::Mag::has_data() const { if (is_presence_container) return true; return mag_name.is_set; } bool MobileIp::Domains::Domain::Mags::Mag::has_operation() const { return is_set(yfilter) || ydk::is_set(mag_name.yfilter); } std::string MobileIp::Domains::Domain::Mags::Mag::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mag"; ADD_KEY_TOKEN(mag_name, "mag-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::Mags::Mag::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mag_name.is_set || is_set(mag_name.yfilter)) leaf_name_data.push_back(mag_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::Mags::Mag::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::Mags::Mag::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Domains::Domain::Mags::Mag::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mag-name") { mag_name = value; mag_name.value_namespace = name_space; mag_name.value_namespace_prefix = name_space_prefix; } } void MobileIp::Domains::Domain::Mags::Mag::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mag-name") { mag_name.yfilter = yfilter; } } bool MobileIp::Domains::Domain::Mags::Mag::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mag-name") return true; return false; } MobileIp::Domains::Domain::Nais::Nais() : nai(this, {"nai_name"}) { yang_name = "nais"; yang_parent_name = "domain"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::Nais::~Nais() { } bool MobileIp::Domains::Domain::Nais::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<nai.len(); index++) { if(nai[index]->has_data()) return true; } return false; } bool MobileIp::Domains::Domain::Nais::has_operation() const { for (std::size_t index=0; index<nai.len(); index++) { if(nai[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Domains::Domain::Nais::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "nais"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::Nais::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::Nais::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "nai") { auto ent_ = std::make_shared<MobileIp::Domains::Domain::Nais::Nai>(); ent_->parent = this; nai.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::Nais::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : nai.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Domains::Domain::Nais::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Domains::Domain::Nais::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Domains::Domain::Nais::has_leaf_or_child_of_name(const std::string & name) const { if(name == "nai") return true; return false; } MobileIp::Domains::Domain::Nais::Nai::Nai() : nai_name{YType::str, "nai-name"}, lma{YType::str, "lma"}, apn{YType::str, "apn"}, customer{YType::str, "customer"}, service{YType::enumeration, "service"}, network{YType::str, "network"} { yang_name = "nai"; yang_parent_name = "nais"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::Nais::Nai::~Nai() { } bool MobileIp::Domains::Domain::Nais::Nai::has_data() const { if (is_presence_container) return true; return nai_name.is_set || lma.is_set || apn.is_set || customer.is_set || service.is_set || network.is_set; } bool MobileIp::Domains::Domain::Nais::Nai::has_operation() const { return is_set(yfilter) || ydk::is_set(nai_name.yfilter) || ydk::is_set(lma.yfilter) || ydk::is_set(apn.yfilter) || ydk::is_set(customer.yfilter) || ydk::is_set(service.yfilter) || ydk::is_set(network.yfilter); } std::string MobileIp::Domains::Domain::Nais::Nai::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "nai"; ADD_KEY_TOKEN(nai_name, "nai-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::Nais::Nai::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (nai_name.is_set || is_set(nai_name.yfilter)) leaf_name_data.push_back(nai_name.get_name_leafdata()); if (lma.is_set || is_set(lma.yfilter)) leaf_name_data.push_back(lma.get_name_leafdata()); if (apn.is_set || is_set(apn.yfilter)) leaf_name_data.push_back(apn.get_name_leafdata()); if (customer.is_set || is_set(customer.yfilter)) leaf_name_data.push_back(customer.get_name_leafdata()); if (service.is_set || is_set(service.yfilter)) leaf_name_data.push_back(service.get_name_leafdata()); if (network.is_set || is_set(network.yfilter)) leaf_name_data.push_back(network.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::Nais::Nai::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::Nais::Nai::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Domains::Domain::Nais::Nai::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "nai-name") { nai_name = value; nai_name.value_namespace = name_space; nai_name.value_namespace_prefix = name_space_prefix; } if(value_path == "lma") { lma = value; lma.value_namespace = name_space; lma.value_namespace_prefix = name_space_prefix; } if(value_path == "apn") { apn = value; apn.value_namespace = name_space; apn.value_namespace_prefix = name_space_prefix; } if(value_path == "customer") { customer = value; customer.value_namespace = name_space; customer.value_namespace_prefix = name_space_prefix; } if(value_path == "service") { service = value; service.value_namespace = name_space; service.value_namespace_prefix = name_space_prefix; } if(value_path == "network") { network = value; network.value_namespace = name_space; network.value_namespace_prefix = name_space_prefix; } } void MobileIp::Domains::Domain::Nais::Nai::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "nai-name") { nai_name.yfilter = yfilter; } if(value_path == "lma") { lma.yfilter = yfilter; } if(value_path == "apn") { apn.yfilter = yfilter; } if(value_path == "customer") { customer.yfilter = yfilter; } if(value_path == "service") { service.yfilter = yfilter; } if(value_path == "network") { network.yfilter = yfilter; } } bool MobileIp::Domains::Domain::Nais::Nai::has_leaf_or_child_of_name(const std::string & name) const { if(name == "nai-name" || name == "lma" || name == "apn" || name == "customer" || name == "service" || name == "network") return true; return false; } MobileIp::Domains::Domain::AuthenticateOption::AuthenticateOption() : spi{YType::str, "spi"}, key{YType::str, "key"} { yang_name = "authenticate-option"; yang_parent_name = "domain"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::AuthenticateOption::~AuthenticateOption() { } bool MobileIp::Domains::Domain::AuthenticateOption::has_data() const { if (is_presence_container) return true; return spi.is_set || key.is_set; } bool MobileIp::Domains::Domain::AuthenticateOption::has_operation() const { return is_set(yfilter) || ydk::is_set(spi.yfilter) || ydk::is_set(key.yfilter); } std::string MobileIp::Domains::Domain::AuthenticateOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "authenticate-option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::AuthenticateOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (spi.is_set || is_set(spi.yfilter)) leaf_name_data.push_back(spi.get_name_leafdata()); if (key.is_set || is_set(key.yfilter)) leaf_name_data.push_back(key.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::AuthenticateOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::AuthenticateOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Domains::Domain::AuthenticateOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "spi") { spi = value; spi.value_namespace = name_space; spi.value_namespace_prefix = name_space_prefix; } if(value_path == "key") { key = value; key.value_namespace = name_space; key.value_namespace_prefix = name_space_prefix; } } void MobileIp::Domains::Domain::AuthenticateOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "spi") { spi.yfilter = yfilter; } if(value_path == "key") { key.yfilter = yfilter; } } bool MobileIp::Domains::Domain::AuthenticateOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "spi" || name == "key") return true; return false; } MobileIp::Domains::Domain::Lmas::Lmas() : lma(this, {"lma_name"}) { yang_name = "lmas"; yang_parent_name = "domain"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::Lmas::~Lmas() { } bool MobileIp::Domains::Domain::Lmas::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<lma.len(); index++) { if(lma[index]->has_data()) return true; } return false; } bool MobileIp::Domains::Domain::Lmas::has_operation() const { for (std::size_t index=0; index<lma.len(); index++) { if(lma[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Domains::Domain::Lmas::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lmas"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::Lmas::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::Lmas::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lma") { auto ent_ = std::make_shared<MobileIp::Domains::Domain::Lmas::Lma>(); ent_->parent = this; lma.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::Lmas::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : lma.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Domains::Domain::Lmas::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Domains::Domain::Lmas::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Domains::Domain::Lmas::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lma") return true; return false; } MobileIp::Domains::Domain::Lmas::Lma::Lma() : lma_name{YType::str, "lma-name"} { yang_name = "lma"; yang_parent_name = "lmas"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Domains::Domain::Lmas::Lma::~Lma() { } bool MobileIp::Domains::Domain::Lmas::Lma::has_data() const { if (is_presence_container) return true; return lma_name.is_set; } bool MobileIp::Domains::Domain::Lmas::Lma::has_operation() const { return is_set(yfilter) || ydk::is_set(lma_name.yfilter); } std::string MobileIp::Domains::Domain::Lmas::Lma::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lma"; ADD_KEY_TOKEN(lma_name, "lma-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Domains::Domain::Lmas::Lma::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lma_name.is_set || is_set(lma_name.yfilter)) leaf_name_data.push_back(lma_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Domains::Domain::Lmas::Lma::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Domains::Domain::Lmas::Lma::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Domains::Domain::Lmas::Lma::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lma-name") { lma_name = value; lma_name.value_namespace = name_space; lma_name.value_namespace_prefix = name_space_prefix; } } void MobileIp::Domains::Domain::Lmas::Lma::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lma-name") { lma_name.yfilter = yfilter; } } bool MobileIp::Domains::Domain::Lmas::Lma::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lma-name") return true; return false; } MobileIp::Lmas::Lmas() : lma(this, {"lma_name", "domain_name"}) { yang_name = "lmas"; yang_parent_name = "mobile-ip"; is_top_level_class = false; has_list_ancestor = false; } MobileIp::Lmas::~Lmas() { } bool MobileIp::Lmas::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<lma.len(); index++) { if(lma[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::has_operation() const { for (std::size_t index=0; index<lma.len(); index++) { if(lma[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ip-mobileip-cfg:mobile-ip/" << get_segment_path(); return path_buffer.str(); } std::string MobileIp::Lmas::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lmas"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lma") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma>(); ent_->parent = this; lma.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : lma.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lma") return true; return false; } MobileIp::Lmas::Lma::Lma() : lma_name{YType::str, "lma-name"}, domain_name{YType::str, "domain-name"}, generate{YType::empty, "generate"}, mobile_route_ad{YType::uint32, "mobile-route-ad"}, ani{YType::empty, "ani"}, multipath{YType::empty, "multipath"}, dynamic{YType::empty, "dynamic"}, enforce{YType::empty, "enforce"}, default_profile{YType::str, "default-profile"}, interface{YType::str, "interface"}, mobile_map{YType::str, "mobile-map"}, pgw_subs_cont{YType::empty, "pgw-subs-cont"} , binding_revocation_attributes(std::make_shared<MobileIp::Lmas::Lma::BindingRevocationAttributes>()) , rat_attributes(std::make_shared<MobileIp::Lmas::Lma::RatAttributes>()) , heart_beat_attributes(std::make_shared<MobileIp::Lmas::Lma::HeartBeatAttributes>()) , lmaipv6_addresses(std::make_shared<MobileIp::Lmas::Lma::Lmaipv6Addresses>()) , hnp(std::make_shared<MobileIp::Lmas::Lma::Hnp>()) , redistribute(std::make_shared<MobileIp::Lmas::Lma::Redistribute>()) , aaa(std::make_shared<MobileIp::Lmas::Lma::Aaa>()) , dscp(std::make_shared<MobileIp::Lmas::Lma::Dscp>()) , lmaipv4_addresses(std::make_shared<MobileIp::Lmas::Lma::Lmaipv4Addresses>()) , roles(std::make_shared<MobileIp::Lmas::Lma::Roles>()) , binding_attributes(std::make_shared<MobileIp::Lmas::Lma::BindingAttributes>()) , mags(std::make_shared<MobileIp::Lmas::Lma::Mags>()) , tunnel_attributes(std::make_shared<MobileIp::Lmas::Lma::TunnelAttributes>()) , services(std::make_shared<MobileIp::Lmas::Lma::Services>()) , networks(std::make_shared<MobileIp::Lmas::Lma::Networks>()) , replay_protection(std::make_shared<MobileIp::Lmas::Lma::ReplayProtection>()) { binding_revocation_attributes->parent = this; rat_attributes->parent = this; heart_beat_attributes->parent = this; lmaipv6_addresses->parent = this; hnp->parent = this; redistribute->parent = this; aaa->parent = this; dscp->parent = this; lmaipv4_addresses->parent = this; roles->parent = this; binding_attributes->parent = this; mags->parent = this; tunnel_attributes->parent = this; services->parent = this; networks->parent = this; replay_protection->parent = this; yang_name = "lma"; yang_parent_name = "lmas"; is_top_level_class = false; has_list_ancestor = false; } MobileIp::Lmas::Lma::~Lma() { } bool MobileIp::Lmas::Lma::has_data() const { if (is_presence_container) return true; return lma_name.is_set || domain_name.is_set || generate.is_set || mobile_route_ad.is_set || ani.is_set || multipath.is_set || dynamic.is_set || enforce.is_set || default_profile.is_set || interface.is_set || mobile_map.is_set || pgw_subs_cont.is_set || (binding_revocation_attributes != nullptr && binding_revocation_attributes->has_data()) || (rat_attributes != nullptr && rat_attributes->has_data()) || (heart_beat_attributes != nullptr && heart_beat_attributes->has_data()) || (lmaipv6_addresses != nullptr && lmaipv6_addresses->has_data()) || (hnp != nullptr && hnp->has_data()) || (redistribute != nullptr && redistribute->has_data()) || (aaa != nullptr && aaa->has_data()) || (dscp != nullptr && dscp->has_data()) || (lmaipv4_addresses != nullptr && lmaipv4_addresses->has_data()) || (roles != nullptr && roles->has_data()) || (binding_attributes != nullptr && binding_attributes->has_data()) || (mags != nullptr && mags->has_data()) || (tunnel_attributes != nullptr && tunnel_attributes->has_data()) || (services != nullptr && services->has_data()) || (networks != nullptr && networks->has_data()) || (replay_protection != nullptr && replay_protection->has_data()); } bool MobileIp::Lmas::Lma::has_operation() const { return is_set(yfilter) || ydk::is_set(lma_name.yfilter) || ydk::is_set(domain_name.yfilter) || ydk::is_set(generate.yfilter) || ydk::is_set(mobile_route_ad.yfilter) || ydk::is_set(ani.yfilter) || ydk::is_set(multipath.yfilter) || ydk::is_set(dynamic.yfilter) || ydk::is_set(enforce.yfilter) || ydk::is_set(default_profile.yfilter) || ydk::is_set(interface.yfilter) || ydk::is_set(mobile_map.yfilter) || ydk::is_set(pgw_subs_cont.yfilter) || (binding_revocation_attributes != nullptr && binding_revocation_attributes->has_operation()) || (rat_attributes != nullptr && rat_attributes->has_operation()) || (heart_beat_attributes != nullptr && heart_beat_attributes->has_operation()) || (lmaipv6_addresses != nullptr && lmaipv6_addresses->has_operation()) || (hnp != nullptr && hnp->has_operation()) || (redistribute != nullptr && redistribute->has_operation()) || (aaa != nullptr && aaa->has_operation()) || (dscp != nullptr && dscp->has_operation()) || (lmaipv4_addresses != nullptr && lmaipv4_addresses->has_operation()) || (roles != nullptr && roles->has_operation()) || (binding_attributes != nullptr && binding_attributes->has_operation()) || (mags != nullptr && mags->has_operation()) || (tunnel_attributes != nullptr && tunnel_attributes->has_operation()) || (services != nullptr && services->has_operation()) || (networks != nullptr && networks->has_operation()) || (replay_protection != nullptr && replay_protection->has_operation()); } std::string MobileIp::Lmas::Lma::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ip-mobileip-cfg:mobile-ip/lmas/" << get_segment_path(); return path_buffer.str(); } std::string MobileIp::Lmas::Lma::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lma"; ADD_KEY_TOKEN(lma_name, "lma-name"); ADD_KEY_TOKEN(domain_name, "domain-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lma_name.is_set || is_set(lma_name.yfilter)) leaf_name_data.push_back(lma_name.get_name_leafdata()); if (domain_name.is_set || is_set(domain_name.yfilter)) leaf_name_data.push_back(domain_name.get_name_leafdata()); if (generate.is_set || is_set(generate.yfilter)) leaf_name_data.push_back(generate.get_name_leafdata()); if (mobile_route_ad.is_set || is_set(mobile_route_ad.yfilter)) leaf_name_data.push_back(mobile_route_ad.get_name_leafdata()); if (ani.is_set || is_set(ani.yfilter)) leaf_name_data.push_back(ani.get_name_leafdata()); if (multipath.is_set || is_set(multipath.yfilter)) leaf_name_data.push_back(multipath.get_name_leafdata()); if (dynamic.is_set || is_set(dynamic.yfilter)) leaf_name_data.push_back(dynamic.get_name_leafdata()); if (enforce.is_set || is_set(enforce.yfilter)) leaf_name_data.push_back(enforce.get_name_leafdata()); if (default_profile.is_set || is_set(default_profile.yfilter)) leaf_name_data.push_back(default_profile.get_name_leafdata()); if (interface.is_set || is_set(interface.yfilter)) leaf_name_data.push_back(interface.get_name_leafdata()); if (mobile_map.is_set || is_set(mobile_map.yfilter)) leaf_name_data.push_back(mobile_map.get_name_leafdata()); if (pgw_subs_cont.is_set || is_set(pgw_subs_cont.yfilter)) leaf_name_data.push_back(pgw_subs_cont.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "binding-revocation-attributes") { if(binding_revocation_attributes == nullptr) { binding_revocation_attributes = std::make_shared<MobileIp::Lmas::Lma::BindingRevocationAttributes>(); } return binding_revocation_attributes; } if(child_yang_name == "rat-attributes") { if(rat_attributes == nullptr) { rat_attributes = std::make_shared<MobileIp::Lmas::Lma::RatAttributes>(); } return rat_attributes; } if(child_yang_name == "heart-beat-attributes") { if(heart_beat_attributes == nullptr) { heart_beat_attributes = std::make_shared<MobileIp::Lmas::Lma::HeartBeatAttributes>(); } return heart_beat_attributes; } if(child_yang_name == "lmaipv6-addresses") { if(lmaipv6_addresses == nullptr) { lmaipv6_addresses = std::make_shared<MobileIp::Lmas::Lma::Lmaipv6Addresses>(); } return lmaipv6_addresses; } if(child_yang_name == "hnp") { if(hnp == nullptr) { hnp = std::make_shared<MobileIp::Lmas::Lma::Hnp>(); } return hnp; } if(child_yang_name == "redistribute") { if(redistribute == nullptr) { redistribute = std::make_shared<MobileIp::Lmas::Lma::Redistribute>(); } return redistribute; } if(child_yang_name == "aaa") { if(aaa == nullptr) { aaa = std::make_shared<MobileIp::Lmas::Lma::Aaa>(); } return aaa; } if(child_yang_name == "dscp") { if(dscp == nullptr) { dscp = std::make_shared<MobileIp::Lmas::Lma::Dscp>(); } return dscp; } if(child_yang_name == "lmaipv4-addresses") { if(lmaipv4_addresses == nullptr) { lmaipv4_addresses = std::make_shared<MobileIp::Lmas::Lma::Lmaipv4Addresses>(); } return lmaipv4_addresses; } if(child_yang_name == "roles") { if(roles == nullptr) { roles = std::make_shared<MobileIp::Lmas::Lma::Roles>(); } return roles; } if(child_yang_name == "binding-attributes") { if(binding_attributes == nullptr) { binding_attributes = std::make_shared<MobileIp::Lmas::Lma::BindingAttributes>(); } return binding_attributes; } if(child_yang_name == "mags") { if(mags == nullptr) { mags = std::make_shared<MobileIp::Lmas::Lma::Mags>(); } return mags; } if(child_yang_name == "tunnel-attributes") { if(tunnel_attributes == nullptr) { tunnel_attributes = std::make_shared<MobileIp::Lmas::Lma::TunnelAttributes>(); } return tunnel_attributes; } if(child_yang_name == "services") { if(services == nullptr) { services = std::make_shared<MobileIp::Lmas::Lma::Services>(); } return services; } if(child_yang_name == "networks") { if(networks == nullptr) { networks = std::make_shared<MobileIp::Lmas::Lma::Networks>(); } return networks; } if(child_yang_name == "replay-protection") { if(replay_protection == nullptr) { replay_protection = std::make_shared<MobileIp::Lmas::Lma::ReplayProtection>(); } return replay_protection; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(binding_revocation_attributes != nullptr) { _children["binding-revocation-attributes"] = binding_revocation_attributes; } if(rat_attributes != nullptr) { _children["rat-attributes"] = rat_attributes; } if(heart_beat_attributes != nullptr) { _children["heart-beat-attributes"] = heart_beat_attributes; } if(lmaipv6_addresses != nullptr) { _children["lmaipv6-addresses"] = lmaipv6_addresses; } if(hnp != nullptr) { _children["hnp"] = hnp; } if(redistribute != nullptr) { _children["redistribute"] = redistribute; } if(aaa != nullptr) { _children["aaa"] = aaa; } if(dscp != nullptr) { _children["dscp"] = dscp; } if(lmaipv4_addresses != nullptr) { _children["lmaipv4-addresses"] = lmaipv4_addresses; } if(roles != nullptr) { _children["roles"] = roles; } if(binding_attributes != nullptr) { _children["binding-attributes"] = binding_attributes; } if(mags != nullptr) { _children["mags"] = mags; } if(tunnel_attributes != nullptr) { _children["tunnel-attributes"] = tunnel_attributes; } if(services != nullptr) { _children["services"] = services; } if(networks != nullptr) { _children["networks"] = networks; } if(replay_protection != nullptr) { _children["replay-protection"] = replay_protection; } return _children; } void MobileIp::Lmas::Lma::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lma-name") { lma_name = value; lma_name.value_namespace = name_space; lma_name.value_namespace_prefix = name_space_prefix; } if(value_path == "domain-name") { domain_name = value; domain_name.value_namespace = name_space; domain_name.value_namespace_prefix = name_space_prefix; } if(value_path == "generate") { generate = value; generate.value_namespace = name_space; generate.value_namespace_prefix = name_space_prefix; } if(value_path == "mobile-route-ad") { mobile_route_ad = value; mobile_route_ad.value_namespace = name_space; mobile_route_ad.value_namespace_prefix = name_space_prefix; } if(value_path == "ani") { ani = value; ani.value_namespace = name_space; ani.value_namespace_prefix = name_space_prefix; } if(value_path == "multipath") { multipath = value; multipath.value_namespace = name_space; multipath.value_namespace_prefix = name_space_prefix; } if(value_path == "dynamic") { dynamic = value; dynamic.value_namespace = name_space; dynamic.value_namespace_prefix = name_space_prefix; } if(value_path == "enforce") { enforce = value; enforce.value_namespace = name_space; enforce.value_namespace_prefix = name_space_prefix; } if(value_path == "default-profile") { default_profile = value; default_profile.value_namespace = name_space; default_profile.value_namespace_prefix = name_space_prefix; } if(value_path == "interface") { interface = value; interface.value_namespace = name_space; interface.value_namespace_prefix = name_space_prefix; } if(value_path == "mobile-map") { mobile_map = value; mobile_map.value_namespace = name_space; mobile_map.value_namespace_prefix = name_space_prefix; } if(value_path == "pgw-subs-cont") { pgw_subs_cont = value; pgw_subs_cont.value_namespace = name_space; pgw_subs_cont.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lma-name") { lma_name.yfilter = yfilter; } if(value_path == "domain-name") { domain_name.yfilter = yfilter; } if(value_path == "generate") { generate.yfilter = yfilter; } if(value_path == "mobile-route-ad") { mobile_route_ad.yfilter = yfilter; } if(value_path == "ani") { ani.yfilter = yfilter; } if(value_path == "multipath") { multipath.yfilter = yfilter; } if(value_path == "dynamic") { dynamic.yfilter = yfilter; } if(value_path == "enforce") { enforce.yfilter = yfilter; } if(value_path == "default-profile") { default_profile.yfilter = yfilter; } if(value_path == "interface") { interface.yfilter = yfilter; } if(value_path == "mobile-map") { mobile_map.yfilter = yfilter; } if(value_path == "pgw-subs-cont") { pgw_subs_cont.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::has_leaf_or_child_of_name(const std::string & name) const { if(name == "binding-revocation-attributes" || name == "rat-attributes" || name == "heart-beat-attributes" || name == "lmaipv6-addresses" || name == "hnp" || name == "redistribute" || name == "aaa" || name == "dscp" || name == "lmaipv4-addresses" || name == "roles" || name == "binding-attributes" || name == "mags" || name == "tunnel-attributes" || name == "services" || name == "networks" || name == "replay-protection" || name == "lma-name" || name == "domain-name" || name == "generate" || name == "mobile-route-ad" || name == "ani" || name == "multipath" || name == "dynamic" || name == "enforce" || name == "default-profile" || name == "interface" || name == "mobile-map" || name == "pgw-subs-cont") return true; return false; } MobileIp::Lmas::Lma::BindingRevocationAttributes::BindingRevocationAttributes() : retry{YType::uint32, "retry"} , delay(std::make_shared<MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay>()) { delay->parent = this; yang_name = "binding-revocation-attributes"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::BindingRevocationAttributes::~BindingRevocationAttributes() { } bool MobileIp::Lmas::Lma::BindingRevocationAttributes::has_data() const { if (is_presence_container) return true; return retry.is_set || (delay != nullptr && delay->has_data()); } bool MobileIp::Lmas::Lma::BindingRevocationAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(retry.yfilter) || (delay != nullptr && delay->has_operation()); } std::string MobileIp::Lmas::Lma::BindingRevocationAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "binding-revocation-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::BindingRevocationAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (retry.is_set || is_set(retry.yfilter)) leaf_name_data.push_back(retry.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::BindingRevocationAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "delay") { if(delay == nullptr) { delay = std::make_shared<MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay>(); } return delay; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::BindingRevocationAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(delay != nullptr) { _children["delay"] = delay; } return _children; } void MobileIp::Lmas::Lma::BindingRevocationAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "retry") { retry = value; retry.value_namespace = name_space; retry.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::BindingRevocationAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "retry") { retry.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::BindingRevocationAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "delay" || name == "retry") return true; return false; } MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::Delay() : br_min{YType::uint32, "br-min"}, br_max{YType::uint32, "br-max"} { yang_name = "delay"; yang_parent_name = "binding-revocation-attributes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::~Delay() { } bool MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::has_data() const { if (is_presence_container) return true; return br_min.is_set || br_max.is_set; } bool MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::has_operation() const { return is_set(yfilter) || ydk::is_set(br_min.yfilter) || ydk::is_set(br_max.yfilter); } std::string MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "delay"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (br_min.is_set || is_set(br_min.yfilter)) leaf_name_data.push_back(br_min.get_name_leafdata()); if (br_max.is_set || is_set(br_max.yfilter)) leaf_name_data.push_back(br_max.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "br-min") { br_min = value; br_min.value_namespace = name_space; br_min.value_namespace_prefix = name_space_prefix; } if(value_path == "br-max") { br_max = value; br_max.value_namespace = name_space; br_max.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "br-min") { br_min.yfilter = yfilter; } if(value_path == "br-max") { br_max.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::BindingRevocationAttributes::Delay::has_leaf_or_child_of_name(const std::string & name) const { if(name == "br-min" || name == "br-max") return true; return false; } MobileIp::Lmas::Lma::RatAttributes::RatAttributes() : lma_rat{YType::enumeration, "lma-rat"}, priority_value{YType::uint32, "priority-value"} { yang_name = "rat-attributes"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::RatAttributes::~RatAttributes() { } bool MobileIp::Lmas::Lma::RatAttributes::has_data() const { if (is_presence_container) return true; return lma_rat.is_set || priority_value.is_set; } bool MobileIp::Lmas::Lma::RatAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(lma_rat.yfilter) || ydk::is_set(priority_value.yfilter); } std::string MobileIp::Lmas::Lma::RatAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "rat-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::RatAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lma_rat.is_set || is_set(lma_rat.yfilter)) leaf_name_data.push_back(lma_rat.get_name_leafdata()); if (priority_value.is_set || is_set(priority_value.yfilter)) leaf_name_data.push_back(priority_value.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::RatAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::RatAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::RatAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lma-rat") { lma_rat = value; lma_rat.value_namespace = name_space; lma_rat.value_namespace_prefix = name_space_prefix; } if(value_path == "priority-value") { priority_value = value; priority_value.value_namespace = name_space; priority_value.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::RatAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lma-rat") { lma_rat.yfilter = yfilter; } if(value_path == "priority-value") { priority_value.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::RatAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lma-rat" || name == "priority-value") return true; return false; } MobileIp::Lmas::Lma::HeartBeatAttributes::HeartBeatAttributes() : interval{YType::uint32, "interval"}, retries{YType::uint32, "retries"}, timeout{YType::uint32, "timeout"} { yang_name = "heart-beat-attributes"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::HeartBeatAttributes::~HeartBeatAttributes() { } bool MobileIp::Lmas::Lma::HeartBeatAttributes::has_data() const { if (is_presence_container) return true; return interval.is_set || retries.is_set || timeout.is_set; } bool MobileIp::Lmas::Lma::HeartBeatAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter) || ydk::is_set(retries.yfilter) || ydk::is_set(timeout.yfilter); } std::string MobileIp::Lmas::Lma::HeartBeatAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "heart-beat-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::HeartBeatAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); if (retries.is_set || is_set(retries.yfilter)) leaf_name_data.push_back(retries.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::HeartBeatAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::HeartBeatAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::HeartBeatAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } if(value_path == "retries") { retries = value; retries.value_namespace = name_space; retries.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::HeartBeatAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } if(value_path == "retries") { retries.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::HeartBeatAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval" || name == "retries" || name == "timeout") return true; return false; } MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Addresses() : lmaipv6_address(this, {"address"}) { yang_name = "lmaipv6-addresses"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Lmaipv6Addresses::~Lmaipv6Addresses() { } bool MobileIp::Lmas::Lma::Lmaipv6Addresses::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<lmaipv6_address.len(); index++) { if(lmaipv6_address[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Lmaipv6Addresses::has_operation() const { for (std::size_t index=0; index<lmaipv6_address.len(); index++) { if(lmaipv6_address[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Lmaipv6Addresses::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lmaipv6-addresses"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Lmaipv6Addresses::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Lmaipv6Addresses::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lmaipv6-address") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address>(); ent_->parent = this; lmaipv6_address.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Lmaipv6Addresses::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : lmaipv6_address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Lmaipv6Addresses::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Lmaipv6Addresses::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Lmaipv6Addresses::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lmaipv6-address") return true; return false; } MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::Lmaipv6Address() : address{YType::str, "address"} { yang_name = "lmaipv6-address"; yang_parent_name = "lmaipv6-addresses"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::~Lmaipv6Address() { } bool MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::has_data() const { if (is_presence_container) return true; return address.is_set; } bool MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address.yfilter); } std::string MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lmaipv6-address"; ADD_KEY_TOKEN(address, "address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address") { address = value; address.value_namespace = name_space; address.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address") { address.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Lmaipv6Addresses::Lmaipv6Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address") return true; return false; } MobileIp::Lmas::Lma::Hnp::Hnp() : maximum{YType::uint32, "maximum"} { yang_name = "hnp"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Hnp::~Hnp() { } bool MobileIp::Lmas::Lma::Hnp::has_data() const { if (is_presence_container) return true; return maximum.is_set; } bool MobileIp::Lmas::Lma::Hnp::has_operation() const { return is_set(yfilter) || ydk::is_set(maximum.yfilter); } std::string MobileIp::Lmas::Lma::Hnp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "hnp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Hnp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (maximum.is_set || is_set(maximum.yfilter)) leaf_name_data.push_back(maximum.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Hnp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Hnp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Hnp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "maximum") { maximum = value; maximum.value_namespace = name_space; maximum.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Hnp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "maximum") { maximum.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Hnp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "maximum") return true; return false; } MobileIp::Lmas::Lma::Redistribute::Redistribute() : redist_type{YType::enumeration, "redist-type"}, redist_sub_type{YType::enumeration, "redist-sub-type"} { yang_name = "redistribute"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Redistribute::~Redistribute() { } bool MobileIp::Lmas::Lma::Redistribute::has_data() const { if (is_presence_container) return true; return redist_type.is_set || redist_sub_type.is_set; } bool MobileIp::Lmas::Lma::Redistribute::has_operation() const { return is_set(yfilter) || ydk::is_set(redist_type.yfilter) || ydk::is_set(redist_sub_type.yfilter); } std::string MobileIp::Lmas::Lma::Redistribute::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "redistribute"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Redistribute::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (redist_type.is_set || is_set(redist_type.yfilter)) leaf_name_data.push_back(redist_type.get_name_leafdata()); if (redist_sub_type.is_set || is_set(redist_sub_type.yfilter)) leaf_name_data.push_back(redist_sub_type.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Redistribute::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Redistribute::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Redistribute::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "redist-type") { redist_type = value; redist_type.value_namespace = name_space; redist_type.value_namespace_prefix = name_space_prefix; } if(value_path == "redist-sub-type") { redist_sub_type = value; redist_sub_type.value_namespace = name_space; redist_sub_type.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Redistribute::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "redist-type") { redist_type.yfilter = yfilter; } if(value_path == "redist-sub-type") { redist_sub_type.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Redistribute::has_leaf_or_child_of_name(const std::string & name) const { if(name == "redist-type" || name == "redist-sub-type") return true; return false; } MobileIp::Lmas::Lma::Aaa::Aaa() : accounting(std::make_shared<MobileIp::Lmas::Lma::Aaa::Accounting>()) { accounting->parent = this; yang_name = "aaa"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Aaa::~Aaa() { } bool MobileIp::Lmas::Lma::Aaa::has_data() const { if (is_presence_container) return true; return (accounting != nullptr && accounting->has_data()); } bool MobileIp::Lmas::Lma::Aaa::has_operation() const { return is_set(yfilter) || (accounting != nullptr && accounting->has_operation()); } std::string MobileIp::Lmas::Lma::Aaa::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "aaa"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Aaa::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Aaa::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "accounting") { if(accounting == nullptr) { accounting = std::make_shared<MobileIp::Lmas::Lma::Aaa::Accounting>(); } return accounting; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Aaa::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(accounting != nullptr) { _children["accounting"] = accounting; } return _children; } void MobileIp::Lmas::Lma::Aaa::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Aaa::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Aaa::has_leaf_or_child_of_name(const std::string & name) const { if(name == "accounting") return true; return false; } MobileIp::Lmas::Lma::Aaa::Accounting::Accounting() : enable{YType::empty, "enable"}, interim_interval{YType::uint32, "interim-interval"} { yang_name = "accounting"; yang_parent_name = "aaa"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Aaa::Accounting::~Accounting() { } bool MobileIp::Lmas::Lma::Aaa::Accounting::has_data() const { if (is_presence_container) return true; return enable.is_set || interim_interval.is_set; } bool MobileIp::Lmas::Lma::Aaa::Accounting::has_operation() const { return is_set(yfilter) || ydk::is_set(enable.yfilter) || ydk::is_set(interim_interval.yfilter); } std::string MobileIp::Lmas::Lma::Aaa::Accounting::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "accounting"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Aaa::Accounting::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); if (interim_interval.is_set || is_set(interim_interval.yfilter)) leaf_name_data.push_back(interim_interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Aaa::Accounting::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Aaa::Accounting::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Aaa::Accounting::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } if(value_path == "interim-interval") { interim_interval = value; interim_interval.value_namespace = name_space; interim_interval.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Aaa::Accounting::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enable") { enable.yfilter = yfilter; } if(value_path == "interim-interval") { interim_interval.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Aaa::Accounting::has_leaf_or_child_of_name(const std::string & name) const { if(name == "enable" || name == "interim-interval") return true; return false; } MobileIp::Lmas::Lma::Dscp::Dscp() : value_{YType::uint32, "value"}, force{YType::empty, "force"} { yang_name = "dscp"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Dscp::~Dscp() { } bool MobileIp::Lmas::Lma::Dscp::has_data() const { if (is_presence_container) return true; return value_.is_set || force.is_set; } bool MobileIp::Lmas::Lma::Dscp::has_operation() const { return is_set(yfilter) || ydk::is_set(value_.yfilter) || ydk::is_set(force.yfilter); } std::string MobileIp::Lmas::Lma::Dscp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dscp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Dscp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (value_.is_set || is_set(value_.yfilter)) leaf_name_data.push_back(value_.get_name_leafdata()); if (force.is_set || is_set(force.yfilter)) leaf_name_data.push_back(force.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Dscp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Dscp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Dscp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "value") { value_ = value; value_.value_namespace = name_space; value_.value_namespace_prefix = name_space_prefix; } if(value_path == "force") { force = value; force.value_namespace = name_space; force.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Dscp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "value") { value_.yfilter = yfilter; } if(value_path == "force") { force.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Dscp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "value" || name == "force") return true; return false; } MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Addresses() : lmaipv4_address(this, {"address"}) { yang_name = "lmaipv4-addresses"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Lmaipv4Addresses::~Lmaipv4Addresses() { } bool MobileIp::Lmas::Lma::Lmaipv4Addresses::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<lmaipv4_address.len(); index++) { if(lmaipv4_address[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Lmaipv4Addresses::has_operation() const { for (std::size_t index=0; index<lmaipv4_address.len(); index++) { if(lmaipv4_address[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Lmaipv4Addresses::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lmaipv4-addresses"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Lmaipv4Addresses::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Lmaipv4Addresses::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "lmaipv4-address") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address>(); ent_->parent = this; lmaipv4_address.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Lmaipv4Addresses::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : lmaipv4_address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Lmaipv4Addresses::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Lmaipv4Addresses::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Lmaipv4Addresses::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lmaipv4-address") return true; return false; } MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::Lmaipv4Address() : address{YType::str, "address"} { yang_name = "lmaipv4-address"; yang_parent_name = "lmaipv4-addresses"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::~Lmaipv4Address() { } bool MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::has_data() const { if (is_presence_container) return true; return address.is_set; } bool MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::has_operation() const { return is_set(yfilter) || ydk::is_set(address.yfilter); } std::string MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lmaipv4-address"; ADD_KEY_TOKEN(address, "address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (address.is_set || is_set(address.yfilter)) leaf_name_data.push_back(address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "address") { address = value; address.value_namespace = name_space; address.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "address") { address.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Lmaipv4Addresses::Lmaipv4Address::has_leaf_or_child_of_name(const std::string & name) const { if(name == "address") return true; return false; } MobileIp::Lmas::Lma::Roles::Roles() : role(this, {"lma_role"}) { yang_name = "roles"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Roles::~Roles() { } bool MobileIp::Lmas::Lma::Roles::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<role.len(); index++) { if(role[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Roles::has_operation() const { for (std::size_t index=0; index<role.len(); index++) { if(role[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Roles::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "roles"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Roles::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Roles::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "role") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Roles::Role>(); ent_->parent = this; role.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Roles::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : role.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Roles::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Roles::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Roles::has_leaf_or_child_of_name(const std::string & name) const { if(name == "role") return true; return false; } MobileIp::Lmas::Lma::Roles::Role::Role() : lma_role{YType::enumeration, "lma-role"} { yang_name = "role"; yang_parent_name = "roles"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Roles::Role::~Role() { } bool MobileIp::Lmas::Lma::Roles::Role::has_data() const { if (is_presence_container) return true; return lma_role.is_set; } bool MobileIp::Lmas::Lma::Roles::Role::has_operation() const { return is_set(yfilter) || ydk::is_set(lma_role.yfilter); } std::string MobileIp::Lmas::Lma::Roles::Role::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "role"; ADD_KEY_TOKEN(lma_role, "lma-role"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Roles::Role::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lma_role.is_set || is_set(lma_role.yfilter)) leaf_name_data.push_back(lma_role.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Roles::Role::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Roles::Role::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Roles::Role::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lma-role") { lma_role = value; lma_role.value_namespace = name_space; lma_role.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Roles::Role::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lma-role") { lma_role.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Roles::Role::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lma-role") return true; return false; } MobileIp::Lmas::Lma::BindingAttributes::BindingAttributes() : refresh_time{YType::uint32, "refresh-time"}, delete_wait_interval{YType::uint32, "delete-wait-interval"}, create_wait_interval{YType::uint32, "create-wait-interval"}, max_life_time{YType::uint32, "max-life-time"}, maximum{YType::uint32, "maximum"} { yang_name = "binding-attributes"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::BindingAttributes::~BindingAttributes() { } bool MobileIp::Lmas::Lma::BindingAttributes::has_data() const { if (is_presence_container) return true; return refresh_time.is_set || delete_wait_interval.is_set || create_wait_interval.is_set || max_life_time.is_set || maximum.is_set; } bool MobileIp::Lmas::Lma::BindingAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(refresh_time.yfilter) || ydk::is_set(delete_wait_interval.yfilter) || ydk::is_set(create_wait_interval.yfilter) || ydk::is_set(max_life_time.yfilter) || ydk::is_set(maximum.yfilter); } std::string MobileIp::Lmas::Lma::BindingAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "binding-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::BindingAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (refresh_time.is_set || is_set(refresh_time.yfilter)) leaf_name_data.push_back(refresh_time.get_name_leafdata()); if (delete_wait_interval.is_set || is_set(delete_wait_interval.yfilter)) leaf_name_data.push_back(delete_wait_interval.get_name_leafdata()); if (create_wait_interval.is_set || is_set(create_wait_interval.yfilter)) leaf_name_data.push_back(create_wait_interval.get_name_leafdata()); if (max_life_time.is_set || is_set(max_life_time.yfilter)) leaf_name_data.push_back(max_life_time.get_name_leafdata()); if (maximum.is_set || is_set(maximum.yfilter)) leaf_name_data.push_back(maximum.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::BindingAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::BindingAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::BindingAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "refresh-time") { refresh_time = value; refresh_time.value_namespace = name_space; refresh_time.value_namespace_prefix = name_space_prefix; } if(value_path == "delete-wait-interval") { delete_wait_interval = value; delete_wait_interval.value_namespace = name_space; delete_wait_interval.value_namespace_prefix = name_space_prefix; } if(value_path == "create-wait-interval") { create_wait_interval = value; create_wait_interval.value_namespace = name_space; create_wait_interval.value_namespace_prefix = name_space_prefix; } if(value_path == "max-life-time") { max_life_time = value; max_life_time.value_namespace = name_space; max_life_time.value_namespace_prefix = name_space_prefix; } if(value_path == "maximum") { maximum = value; maximum.value_namespace = name_space; maximum.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::BindingAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "refresh-time") { refresh_time.yfilter = yfilter; } if(value_path == "delete-wait-interval") { delete_wait_interval.yfilter = yfilter; } if(value_path == "create-wait-interval") { create_wait_interval.yfilter = yfilter; } if(value_path == "max-life-time") { max_life_time.yfilter = yfilter; } if(value_path == "maximum") { maximum.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::BindingAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "refresh-time" || name == "delete-wait-interval" || name == "create-wait-interval" || name == "max-life-time" || name == "maximum") return true; return false; } MobileIp::Lmas::Lma::Mags::Mags() : mag(this, {"mag_name", "domain_name"}) { yang_name = "mags"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Mags::~Mags() { } bool MobileIp::Lmas::Lma::Mags::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mag.len(); index++) { if(mag[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Mags::has_operation() const { for (std::size_t index=0; index<mag.len(); index++) { if(mag[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Mags::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mags"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Mags::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Mags::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mag") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Mags::Mag>(); ent_->parent = this; mag.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Mags::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mag.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Mags::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Mags::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Mags::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mag") return true; return false; } MobileIp::Lmas::Lma::Mags::Mag::Mag() : mag_name{YType::str, "mag-name"}, domain_name{YType::str, "domain-name"}, encap_option{YType::enumeration, "encap-option"}, ipv4_address{YType::str, "ipv4-address"}, ipv6_address{YType::str, "ipv6-address"}, tunnel{YType::str, "tunnel"} , authenticate_option(std::make_shared<MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption>()) , dscp(std::make_shared<MobileIp::Lmas::Lma::Mags::Mag::Dscp>()) { authenticate_option->parent = this; dscp->parent = this; yang_name = "mag"; yang_parent_name = "mags"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Mags::Mag::~Mag() { } bool MobileIp::Lmas::Lma::Mags::Mag::has_data() const { if (is_presence_container) return true; return mag_name.is_set || domain_name.is_set || encap_option.is_set || ipv4_address.is_set || ipv6_address.is_set || tunnel.is_set || (authenticate_option != nullptr && authenticate_option->has_data()) || (dscp != nullptr && dscp->has_data()); } bool MobileIp::Lmas::Lma::Mags::Mag::has_operation() const { return is_set(yfilter) || ydk::is_set(mag_name.yfilter) || ydk::is_set(domain_name.yfilter) || ydk::is_set(encap_option.yfilter) || ydk::is_set(ipv4_address.yfilter) || ydk::is_set(ipv6_address.yfilter) || ydk::is_set(tunnel.yfilter) || (authenticate_option != nullptr && authenticate_option->has_operation()) || (dscp != nullptr && dscp->has_operation()); } std::string MobileIp::Lmas::Lma::Mags::Mag::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mag"; ADD_KEY_TOKEN(mag_name, "mag-name"); ADD_KEY_TOKEN(domain_name, "domain-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Mags::Mag::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mag_name.is_set || is_set(mag_name.yfilter)) leaf_name_data.push_back(mag_name.get_name_leafdata()); if (domain_name.is_set || is_set(domain_name.yfilter)) leaf_name_data.push_back(domain_name.get_name_leafdata()); if (encap_option.is_set || is_set(encap_option.yfilter)) leaf_name_data.push_back(encap_option.get_name_leafdata()); if (ipv4_address.is_set || is_set(ipv4_address.yfilter)) leaf_name_data.push_back(ipv4_address.get_name_leafdata()); if (ipv6_address.is_set || is_set(ipv6_address.yfilter)) leaf_name_data.push_back(ipv6_address.get_name_leafdata()); if (tunnel.is_set || is_set(tunnel.yfilter)) leaf_name_data.push_back(tunnel.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Mags::Mag::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "authenticate-option") { if(authenticate_option == nullptr) { authenticate_option = std::make_shared<MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption>(); } return authenticate_option; } if(child_yang_name == "dscp") { if(dscp == nullptr) { dscp = std::make_shared<MobileIp::Lmas::Lma::Mags::Mag::Dscp>(); } return dscp; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Mags::Mag::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(authenticate_option != nullptr) { _children["authenticate-option"] = authenticate_option; } if(dscp != nullptr) { _children["dscp"] = dscp; } return _children; } void MobileIp::Lmas::Lma::Mags::Mag::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mag-name") { mag_name = value; mag_name.value_namespace = name_space; mag_name.value_namespace_prefix = name_space_prefix; } if(value_path == "domain-name") { domain_name = value; domain_name.value_namespace = name_space; domain_name.value_namespace_prefix = name_space_prefix; } if(value_path == "encap-option") { encap_option = value; encap_option.value_namespace = name_space; encap_option.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv4-address") { ipv4_address = value; ipv4_address.value_namespace = name_space; ipv4_address.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6-address") { ipv6_address = value; ipv6_address.value_namespace = name_space; ipv6_address.value_namespace_prefix = name_space_prefix; } if(value_path == "tunnel") { tunnel = value; tunnel.value_namespace = name_space; tunnel.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Mags::Mag::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mag-name") { mag_name.yfilter = yfilter; } if(value_path == "domain-name") { domain_name.yfilter = yfilter; } if(value_path == "encap-option") { encap_option.yfilter = yfilter; } if(value_path == "ipv4-address") { ipv4_address.yfilter = yfilter; } if(value_path == "ipv6-address") { ipv6_address.yfilter = yfilter; } if(value_path == "tunnel") { tunnel.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Mags::Mag::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authenticate-option" || name == "dscp" || name == "mag-name" || name == "domain-name" || name == "encap-option" || name == "ipv4-address" || name == "ipv6-address" || name == "tunnel") return true; return false; } MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::AuthenticateOption() : spi{YType::str, "spi"}, key{YType::str, "key"} { yang_name = "authenticate-option"; yang_parent_name = "mag"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::~AuthenticateOption() { } bool MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::has_data() const { if (is_presence_container) return true; return spi.is_set || key.is_set; } bool MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::has_operation() const { return is_set(yfilter) || ydk::is_set(spi.yfilter) || ydk::is_set(key.yfilter); } std::string MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "authenticate-option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (spi.is_set || is_set(spi.yfilter)) leaf_name_data.push_back(spi.get_name_leafdata()); if (key.is_set || is_set(key.yfilter)) leaf_name_data.push_back(key.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "spi") { spi = value; spi.value_namespace = name_space; spi.value_namespace_prefix = name_space_prefix; } if(value_path == "key") { key = value; key.value_namespace = name_space; key.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "spi") { spi.yfilter = yfilter; } if(value_path == "key") { key.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Mags::Mag::AuthenticateOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "spi" || name == "key") return true; return false; } MobileIp::Lmas::Lma::Mags::Mag::Dscp::Dscp() : value_{YType::uint32, "value"}, force{YType::empty, "force"} { yang_name = "dscp"; yang_parent_name = "mag"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Mags::Mag::Dscp::~Dscp() { } bool MobileIp::Lmas::Lma::Mags::Mag::Dscp::has_data() const { if (is_presence_container) return true; return value_.is_set || force.is_set; } bool MobileIp::Lmas::Lma::Mags::Mag::Dscp::has_operation() const { return is_set(yfilter) || ydk::is_set(value_.yfilter) || ydk::is_set(force.yfilter); } std::string MobileIp::Lmas::Lma::Mags::Mag::Dscp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dscp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Mags::Mag::Dscp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (value_.is_set || is_set(value_.yfilter)) leaf_name_data.push_back(value_.get_name_leafdata()); if (force.is_set || is_set(force.yfilter)) leaf_name_data.push_back(force.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Mags::Mag::Dscp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Mags::Mag::Dscp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Mags::Mag::Dscp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "value") { value_ = value; value_.value_namespace = name_space; value_.value_namespace_prefix = name_space_prefix; } if(value_path == "force") { force = value; force.value_namespace = name_space; force.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Mags::Mag::Dscp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "value") { value_.yfilter = yfilter; } if(value_path == "force") { force.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Mags::Mag::Dscp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "value" || name == "force") return true; return false; } MobileIp::Lmas::Lma::TunnelAttributes::TunnelAttributes() : mtu{YType::uint32, "mtu"}, acl{YType::str, "acl"} { yang_name = "tunnel-attributes"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::TunnelAttributes::~TunnelAttributes() { } bool MobileIp::Lmas::Lma::TunnelAttributes::has_data() const { if (is_presence_container) return true; return mtu.is_set || acl.is_set; } bool MobileIp::Lmas::Lma::TunnelAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(mtu.yfilter) || ydk::is_set(acl.yfilter); } std::string MobileIp::Lmas::Lma::TunnelAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "tunnel-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::TunnelAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mtu.is_set || is_set(mtu.yfilter)) leaf_name_data.push_back(mtu.get_name_leafdata()); if (acl.is_set || is_set(acl.yfilter)) leaf_name_data.push_back(acl.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::TunnelAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::TunnelAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::TunnelAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mtu") { mtu = value; mtu.value_namespace = name_space; mtu.value_namespace_prefix = name_space_prefix; } if(value_path == "acl") { acl = value; acl.value_namespace = name_space; acl.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::TunnelAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mtu") { mtu.yfilter = yfilter; } if(value_path == "acl") { acl.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::TunnelAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mtu" || name == "acl") return true; return false; } MobileIp::Lmas::Lma::Services::Services() : service(this, {"lma_service"}) { yang_name = "services"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::~Services() { } bool MobileIp::Lmas::Lma::Services::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<service.len(); index++) { if(service[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Services::has_operation() const { for (std::size_t index=0; index<service.len(); index++) { if(service[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Services::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "services"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "service") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Services::Service>(); ent_->parent = this; service.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : service.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Services::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::has_leaf_or_child_of_name(const std::string & name) const { if(name == "service") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Service() : lma_service{YType::enumeration, "lma-service"}, mnp_customer{YType::uint32, "mnp-customer"}, mnp_ipv4_lmn{YType::uint32, "mnp-ipv4-lmn"}, mnp_ipv6_lmn{YType::uint32, "mnp-ipv6-lmn"}, mnp_lmn{YType::uint32, "mnp-lmn"}, ignore_home_address{YType::empty, "ignore-home-address"}, mnp_ipv4_customer{YType::uint32, "mnp-ipv4-customer"}, mnp_ipv6_customer{YType::uint32, "mnp-ipv6-customer"} , customers(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers>()) { customers->parent = this; yang_name = "service"; yang_parent_name = "services"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::~Service() { } bool MobileIp::Lmas::Lma::Services::Service::has_data() const { if (is_presence_container) return true; return lma_service.is_set || mnp_customer.is_set || mnp_ipv4_lmn.is_set || mnp_ipv6_lmn.is_set || mnp_lmn.is_set || ignore_home_address.is_set || mnp_ipv4_customer.is_set || mnp_ipv6_customer.is_set || (customers != nullptr && customers->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::has_operation() const { return is_set(yfilter) || ydk::is_set(lma_service.yfilter) || ydk::is_set(mnp_customer.yfilter) || ydk::is_set(mnp_ipv4_lmn.yfilter) || ydk::is_set(mnp_ipv6_lmn.yfilter) || ydk::is_set(mnp_lmn.yfilter) || ydk::is_set(ignore_home_address.yfilter) || ydk::is_set(mnp_ipv4_customer.yfilter) || ydk::is_set(mnp_ipv6_customer.yfilter) || (customers != nullptr && customers->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "service"; ADD_KEY_TOKEN(lma_service, "lma-service"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lma_service.is_set || is_set(lma_service.yfilter)) leaf_name_data.push_back(lma_service.get_name_leafdata()); if (mnp_customer.is_set || is_set(mnp_customer.yfilter)) leaf_name_data.push_back(mnp_customer.get_name_leafdata()); if (mnp_ipv4_lmn.is_set || is_set(mnp_ipv4_lmn.yfilter)) leaf_name_data.push_back(mnp_ipv4_lmn.get_name_leafdata()); if (mnp_ipv6_lmn.is_set || is_set(mnp_ipv6_lmn.yfilter)) leaf_name_data.push_back(mnp_ipv6_lmn.get_name_leafdata()); if (mnp_lmn.is_set || is_set(mnp_lmn.yfilter)) leaf_name_data.push_back(mnp_lmn.get_name_leafdata()); if (ignore_home_address.is_set || is_set(ignore_home_address.yfilter)) leaf_name_data.push_back(ignore_home_address.get_name_leafdata()); if (mnp_ipv4_customer.is_set || is_set(mnp_ipv4_customer.yfilter)) leaf_name_data.push_back(mnp_ipv4_customer.get_name_leafdata()); if (mnp_ipv6_customer.is_set || is_set(mnp_ipv6_customer.yfilter)) leaf_name_data.push_back(mnp_ipv6_customer.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "customers") { if(customers == nullptr) { customers = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers>(); } return customers; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(customers != nullptr) { _children["customers"] = customers; } return _children; } void MobileIp::Lmas::Lma::Services::Service::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lma-service") { lma_service = value; lma_service.value_namespace = name_space; lma_service.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-customer") { mnp_customer = value; mnp_customer.value_namespace = name_space; mnp_customer.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv4-lmn") { mnp_ipv4_lmn = value; mnp_ipv4_lmn.value_namespace = name_space; mnp_ipv4_lmn.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv6-lmn") { mnp_ipv6_lmn = value; mnp_ipv6_lmn.value_namespace = name_space; mnp_ipv6_lmn.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-lmn") { mnp_lmn = value; mnp_lmn.value_namespace = name_space; mnp_lmn.value_namespace_prefix = name_space_prefix; } if(value_path == "ignore-home-address") { ignore_home_address = value; ignore_home_address.value_namespace = name_space; ignore_home_address.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv4-customer") { mnp_ipv4_customer = value; mnp_ipv4_customer.value_namespace = name_space; mnp_ipv4_customer.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv6-customer") { mnp_ipv6_customer = value; mnp_ipv6_customer.value_namespace = name_space; mnp_ipv6_customer.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lma-service") { lma_service.yfilter = yfilter; } if(value_path == "mnp-customer") { mnp_customer.yfilter = yfilter; } if(value_path == "mnp-ipv4-lmn") { mnp_ipv4_lmn.yfilter = yfilter; } if(value_path == "mnp-ipv6-lmn") { mnp_ipv6_lmn.yfilter = yfilter; } if(value_path == "mnp-lmn") { mnp_lmn.yfilter = yfilter; } if(value_path == "ignore-home-address") { ignore_home_address.yfilter = yfilter; } if(value_path == "mnp-ipv4-customer") { mnp_ipv4_customer.yfilter = yfilter; } if(value_path == "mnp-ipv6-customer") { mnp_ipv6_customer.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::has_leaf_or_child_of_name(const std::string & name) const { if(name == "customers" || name == "lma-service" || name == "mnp-customer" || name == "mnp-ipv4-lmn" || name == "mnp-ipv6-lmn" || name == "mnp-lmn" || name == "ignore-home-address" || name == "mnp-ipv4-customer" || name == "mnp-ipv6-customer") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customers() : customer(this, {"customer_name", "vrf_name"}) { yang_name = "customers"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::~Customers() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<customer.len(); index++) { if(customer[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Services::Service::Customers::has_operation() const { for (std::size_t index=0; index<customer.len(); index++) { if(customer[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "customers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "customer") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer>(); ent_->parent = this; customer.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : customer.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "customer") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Customer() : customer_name{YType::str, "customer-name"}, vrf_name{YType::str, "vrf-name"}, mnp_customer{YType::uint32, "mnp-customer"}, mnp_ipv4_lmn{YType::uint32, "mnp-ipv4-lmn"}, mnp_ipv6_lmn{YType::uint32, "mnp-ipv6-lmn"}, mnp_lmn{YType::uint32, "mnp-lmn"}, mnp_ipv4_customer{YType::uint32, "mnp-ipv4-customer"}, mnp_ipv6_customer{YType::uint32, "mnp-ipv6-customer"}, mobile_route_ad{YType::uint32, "mobile-route-ad"}, bandwidth_aggregate{YType::uint32, "bandwidth-aggregate"} , authenticate_option(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption>()) , heart_beat_attributes(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes>()) , transports(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports>()) , network_attributes(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes>()) , gre_key(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey>()) , binding_attributes(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes>()) { authenticate_option->parent = this; heart_beat_attributes->parent = this; transports->parent = this; network_attributes->parent = this; gre_key->parent = this; binding_attributes->parent = this; yang_name = "customer"; yang_parent_name = "customers"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::~Customer() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::has_data() const { if (is_presence_container) return true; return customer_name.is_set || vrf_name.is_set || mnp_customer.is_set || mnp_ipv4_lmn.is_set || mnp_ipv6_lmn.is_set || mnp_lmn.is_set || mnp_ipv4_customer.is_set || mnp_ipv6_customer.is_set || mobile_route_ad.is_set || bandwidth_aggregate.is_set || (authenticate_option != nullptr && authenticate_option->has_data()) || (heart_beat_attributes != nullptr && heart_beat_attributes->has_data()) || (transports != nullptr && transports->has_data()) || (network_attributes != nullptr && network_attributes->has_data()) || (gre_key != nullptr && gre_key->has_data()) || (binding_attributes != nullptr && binding_attributes->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::has_operation() const { return is_set(yfilter) || ydk::is_set(customer_name.yfilter) || ydk::is_set(vrf_name.yfilter) || ydk::is_set(mnp_customer.yfilter) || ydk::is_set(mnp_ipv4_lmn.yfilter) || ydk::is_set(mnp_ipv6_lmn.yfilter) || ydk::is_set(mnp_lmn.yfilter) || ydk::is_set(mnp_ipv4_customer.yfilter) || ydk::is_set(mnp_ipv6_customer.yfilter) || ydk::is_set(mobile_route_ad.yfilter) || ydk::is_set(bandwidth_aggregate.yfilter) || (authenticate_option != nullptr && authenticate_option->has_operation()) || (heart_beat_attributes != nullptr && heart_beat_attributes->has_operation()) || (transports != nullptr && transports->has_operation()) || (network_attributes != nullptr && network_attributes->has_operation()) || (gre_key != nullptr && gre_key->has_operation()) || (binding_attributes != nullptr && binding_attributes->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "customer"; ADD_KEY_TOKEN(customer_name, "customer-name"); ADD_KEY_TOKEN(vrf_name, "vrf-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (customer_name.is_set || is_set(customer_name.yfilter)) leaf_name_data.push_back(customer_name.get_name_leafdata()); if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata()); if (mnp_customer.is_set || is_set(mnp_customer.yfilter)) leaf_name_data.push_back(mnp_customer.get_name_leafdata()); if (mnp_ipv4_lmn.is_set || is_set(mnp_ipv4_lmn.yfilter)) leaf_name_data.push_back(mnp_ipv4_lmn.get_name_leafdata()); if (mnp_ipv6_lmn.is_set || is_set(mnp_ipv6_lmn.yfilter)) leaf_name_data.push_back(mnp_ipv6_lmn.get_name_leafdata()); if (mnp_lmn.is_set || is_set(mnp_lmn.yfilter)) leaf_name_data.push_back(mnp_lmn.get_name_leafdata()); if (mnp_ipv4_customer.is_set || is_set(mnp_ipv4_customer.yfilter)) leaf_name_data.push_back(mnp_ipv4_customer.get_name_leafdata()); if (mnp_ipv6_customer.is_set || is_set(mnp_ipv6_customer.yfilter)) leaf_name_data.push_back(mnp_ipv6_customer.get_name_leafdata()); if (mobile_route_ad.is_set || is_set(mobile_route_ad.yfilter)) leaf_name_data.push_back(mobile_route_ad.get_name_leafdata()); if (bandwidth_aggregate.is_set || is_set(bandwidth_aggregate.yfilter)) leaf_name_data.push_back(bandwidth_aggregate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "authenticate-option") { if(authenticate_option == nullptr) { authenticate_option = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption>(); } return authenticate_option; } if(child_yang_name == "heart-beat-attributes") { if(heart_beat_attributes == nullptr) { heart_beat_attributes = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes>(); } return heart_beat_attributes; } if(child_yang_name == "transports") { if(transports == nullptr) { transports = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports>(); } return transports; } if(child_yang_name == "network-attributes") { if(network_attributes == nullptr) { network_attributes = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes>(); } return network_attributes; } if(child_yang_name == "gre-key") { if(gre_key == nullptr) { gre_key = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey>(); } return gre_key; } if(child_yang_name == "binding-attributes") { if(binding_attributes == nullptr) { binding_attributes = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes>(); } return binding_attributes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(authenticate_option != nullptr) { _children["authenticate-option"] = authenticate_option; } if(heart_beat_attributes != nullptr) { _children["heart-beat-attributes"] = heart_beat_attributes; } if(transports != nullptr) { _children["transports"] = transports; } if(network_attributes != nullptr) { _children["network-attributes"] = network_attributes; } if(gre_key != nullptr) { _children["gre-key"] = gre_key; } if(binding_attributes != nullptr) { _children["binding-attributes"] = binding_attributes; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "customer-name") { customer_name = value; customer_name.value_namespace = name_space; customer_name.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf-name") { vrf_name = value; vrf_name.value_namespace = name_space; vrf_name.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-customer") { mnp_customer = value; mnp_customer.value_namespace = name_space; mnp_customer.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv4-lmn") { mnp_ipv4_lmn = value; mnp_ipv4_lmn.value_namespace = name_space; mnp_ipv4_lmn.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv6-lmn") { mnp_ipv6_lmn = value; mnp_ipv6_lmn.value_namespace = name_space; mnp_ipv6_lmn.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-lmn") { mnp_lmn = value; mnp_lmn.value_namespace = name_space; mnp_lmn.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv4-customer") { mnp_ipv4_customer = value; mnp_ipv4_customer.value_namespace = name_space; mnp_ipv4_customer.value_namespace_prefix = name_space_prefix; } if(value_path == "mnp-ipv6-customer") { mnp_ipv6_customer = value; mnp_ipv6_customer.value_namespace = name_space; mnp_ipv6_customer.value_namespace_prefix = name_space_prefix; } if(value_path == "mobile-route-ad") { mobile_route_ad = value; mobile_route_ad.value_namespace = name_space; mobile_route_ad.value_namespace_prefix = name_space_prefix; } if(value_path == "bandwidth-aggregate") { bandwidth_aggregate = value; bandwidth_aggregate.value_namespace = name_space; bandwidth_aggregate.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "customer-name") { customer_name.yfilter = yfilter; } if(value_path == "vrf-name") { vrf_name.yfilter = yfilter; } if(value_path == "mnp-customer") { mnp_customer.yfilter = yfilter; } if(value_path == "mnp-ipv4-lmn") { mnp_ipv4_lmn.yfilter = yfilter; } if(value_path == "mnp-ipv6-lmn") { mnp_ipv6_lmn.yfilter = yfilter; } if(value_path == "mnp-lmn") { mnp_lmn.yfilter = yfilter; } if(value_path == "mnp-ipv4-customer") { mnp_ipv4_customer.yfilter = yfilter; } if(value_path == "mnp-ipv6-customer") { mnp_ipv6_customer.yfilter = yfilter; } if(value_path == "mobile-route-ad") { mobile_route_ad.yfilter = yfilter; } if(value_path == "bandwidth-aggregate") { bandwidth_aggregate.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authenticate-option" || name == "heart-beat-attributes" || name == "transports" || name == "network-attributes" || name == "gre-key" || name == "binding-attributes" || name == "customer-name" || name == "vrf-name" || name == "mnp-customer" || name == "mnp-ipv4-lmn" || name == "mnp-ipv6-lmn" || name == "mnp-lmn" || name == "mnp-ipv4-customer" || name == "mnp-ipv6-customer" || name == "mobile-route-ad" || name == "bandwidth-aggregate") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::AuthenticateOption() : spi{YType::str, "spi"}, key{YType::str, "key"} { yang_name = "authenticate-option"; yang_parent_name = "customer"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::~AuthenticateOption() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::has_data() const { if (is_presence_container) return true; return spi.is_set || key.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::has_operation() const { return is_set(yfilter) || ydk::is_set(spi.yfilter) || ydk::is_set(key.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "authenticate-option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (spi.is_set || is_set(spi.yfilter)) leaf_name_data.push_back(spi.get_name_leafdata()); if (key.is_set || is_set(key.yfilter)) leaf_name_data.push_back(key.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "spi") { spi = value; spi.value_namespace = name_space; spi.value_namespace_prefix = name_space_prefix; } if(value_path == "key") { key = value; key.value_namespace = name_space; key.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "spi") { spi.yfilter = yfilter; } if(value_path == "key") { key.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::AuthenticateOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "spi" || name == "key") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::HeartBeatAttributes() : interval{YType::uint32, "interval"}, retries{YType::uint32, "retries"}, timeout{YType::uint32, "timeout"} { yang_name = "heart-beat-attributes"; yang_parent_name = "customer"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::~HeartBeatAttributes() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::has_data() const { if (is_presence_container) return true; return interval.is_set || retries.is_set || timeout.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(interval.yfilter) || ydk::is_set(retries.yfilter) || ydk::is_set(timeout.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "heart-beat-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interval.is_set || is_set(interval.yfilter)) leaf_name_data.push_back(interval.get_name_leafdata()); if (retries.is_set || is_set(retries.yfilter)) leaf_name_data.push_back(retries.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interval") { interval = value; interval.value_namespace = name_space; interval.value_namespace_prefix = name_space_prefix; } if(value_path == "retries") { retries = value; retries.value_namespace = name_space; retries.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interval") { interval.yfilter = yfilter; } if(value_path == "retries") { retries.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::HeartBeatAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interval" || name == "retries" || name == "timeout") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transports() : transport(this, {"vrf_name"}) { yang_name = "transports"; yang_parent_name = "customer"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::~Transports() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<transport.len(); index++) { if(transport[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::has_operation() const { for (std::size_t index=0; index<transport.len(); index++) { if(transport[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "transports"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "transport") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport>(); ent_->parent = this; transport.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : transport.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::has_leaf_or_child_of_name(const std::string & name) const { if(name == "transport") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::Transport() : vrf_name{YType::str, "vrf-name"}, ipv4_address{YType::str, "ipv4-address"}, ipv6_address{YType::str, "ipv6-address"} { yang_name = "transport"; yang_parent_name = "transports"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::~Transport() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::has_data() const { if (is_presence_container) return true; return vrf_name.is_set || ipv4_address.is_set || ipv6_address.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf_name.yfilter) || ydk::is_set(ipv4_address.yfilter) || ydk::is_set(ipv6_address.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "transport"; ADD_KEY_TOKEN(vrf_name, "vrf-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata()); if (ipv4_address.is_set || is_set(ipv4_address.yfilter)) leaf_name_data.push_back(ipv4_address.get_name_leafdata()); if (ipv6_address.is_set || is_set(ipv6_address.yfilter)) leaf_name_data.push_back(ipv6_address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf-name") { vrf_name = value; vrf_name.value_namespace = name_space; vrf_name.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv4-address") { ipv4_address = value; ipv4_address.value_namespace = name_space; ipv4_address.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6-address") { ipv6_address = value; ipv6_address.value_namespace = name_space; ipv6_address.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf-name") { vrf_name.yfilter = yfilter; } if(value_path == "ipv4-address") { ipv4_address.yfilter = yfilter; } if(value_path == "ipv6-address") { ipv6_address.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::Transports::Transport::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrf-name" || name == "ipv4-address" || name == "ipv6-address") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::NetworkAttributes() : unauthorize{YType::empty, "unauthorize"} , authorizes(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes>()) { authorizes->parent = this; yang_name = "network-attributes"; yang_parent_name = "customer"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::~NetworkAttributes() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::has_data() const { if (is_presence_container) return true; return unauthorize.is_set || (authorizes != nullptr && authorizes->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(unauthorize.yfilter) || (authorizes != nullptr && authorizes->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "network-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (unauthorize.is_set || is_set(unauthorize.yfilter)) leaf_name_data.push_back(unauthorize.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "authorizes") { if(authorizes == nullptr) { authorizes = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes>(); } return authorizes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(authorizes != nullptr) { _children["authorizes"] = authorizes; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "unauthorize") { unauthorize = value; unauthorize.value_namespace = name_space; unauthorize.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "unauthorize") { unauthorize.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authorizes" || name == "unauthorize") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorizes() : authorize(this, {"name"}) { yang_name = "authorizes"; yang_parent_name = "network-attributes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::~Authorizes() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<authorize.len(); index++) { if(authorize[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::has_operation() const { for (std::size_t index=0; index<authorize.len(); index++) { if(authorize[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "authorizes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "authorize") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize>(); ent_->parent = this; authorize.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : authorize.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authorize") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::Authorize() : name{YType::str, "name"} , pool_attributes(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes>()) { pool_attributes->parent = this; yang_name = "authorize"; yang_parent_name = "authorizes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::~Authorize() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::has_data() const { if (is_presence_container) return true; return name.is_set || (pool_attributes != nullptr && pool_attributes->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::has_operation() const { return is_set(yfilter) || ydk::is_set(name.yfilter) || (pool_attributes != nullptr && pool_attributes->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "authorize"; ADD_KEY_TOKEN(name, "name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "pool-attributes") { if(pool_attributes == nullptr) { pool_attributes = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes>(); } return pool_attributes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(pool_attributes != nullptr) { _children["pool-attributes"] = pool_attributes; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "name") { name = value; name.value_namespace = name_space; name.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "name") { name.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::has_leaf_or_child_of_name(const std::string & name) const { if(name == "pool-attributes" || name == "name") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::PoolAttributes() : mobile_node(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode>()) , mobile_network(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork>()) { mobile_node->parent = this; mobile_network->parent = this; yang_name = "pool-attributes"; yang_parent_name = "authorize"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::~PoolAttributes() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::has_data() const { if (is_presence_container) return true; return (mobile_node != nullptr && mobile_node->has_data()) || (mobile_network != nullptr && mobile_network->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::has_operation() const { return is_set(yfilter) || (mobile_node != nullptr && mobile_node->has_operation()) || (mobile_network != nullptr && mobile_network->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "pool-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mobile-node") { if(mobile_node == nullptr) { mobile_node = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode>(); } return mobile_node; } if(child_yang_name == "mobile-network") { if(mobile_network == nullptr) { mobile_network = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork>(); } return mobile_network; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(mobile_node != nullptr) { _children["mobile-node"] = mobile_node; } if(mobile_network != nullptr) { _children["mobile-network"] = mobile_network; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mobile-node" || name == "mobile-network") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::MobileNode() : ipv4_pool(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool>()) , ipv6_pool(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool>()) { ipv4_pool->parent = this; ipv6_pool->parent = this; yang_name = "mobile-node"; yang_parent_name = "pool-attributes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::~MobileNode() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::has_data() const { if (is_presence_container) return true; return (ipv4_pool != nullptr && ipv4_pool->has_data()) || (ipv6_pool != nullptr && ipv6_pool->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::has_operation() const { return is_set(yfilter) || (ipv4_pool != nullptr && ipv4_pool->has_operation()) || (ipv6_pool != nullptr && ipv6_pool->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mobile-node"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv4-pool") { if(ipv4_pool == nullptr) { ipv4_pool = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool>(); } return ipv4_pool; } if(child_yang_name == "ipv6-pool") { if(ipv6_pool == nullptr) { ipv6_pool = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool>(); } return ipv6_pool; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(ipv4_pool != nullptr) { _children["ipv4-pool"] = ipv4_pool; } if(ipv6_pool != nullptr) { _children["ipv6-pool"] = ipv6_pool; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv4-pool" || name == "ipv6-pool") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::Ipv4Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"} { yang_name = "ipv4-pool"; yang_parent_name = "mobile-node"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::~Ipv4Pool() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv4-pool"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv4Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::Ipv6Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"} { yang_name = "ipv6-pool"; yang_parent_name = "mobile-node"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::~Ipv6Pool() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6-pool"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNode::Ipv6Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::MobileNetwork() : mripv6_pools(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools>()) , mripv4_pools(std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools>()) { mripv6_pools->parent = this; mripv4_pools->parent = this; yang_name = "mobile-network"; yang_parent_name = "pool-attributes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::~MobileNetwork() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::has_data() const { if (is_presence_container) return true; return (mripv6_pools != nullptr && mripv6_pools->has_data()) || (mripv4_pools != nullptr && mripv4_pools->has_data()); } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::has_operation() const { return is_set(yfilter) || (mripv6_pools != nullptr && mripv6_pools->has_operation()) || (mripv4_pools != nullptr && mripv4_pools->has_operation()); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mobile-network"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mripv6-pools") { if(mripv6_pools == nullptr) { mripv6_pools = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools>(); } return mripv6_pools; } if(child_yang_name == "mripv4-pools") { if(mripv4_pools == nullptr) { mripv4_pools = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools>(); } return mripv4_pools; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(mripv6_pools != nullptr) { _children["mripv6-pools"] = mripv6_pools; } if(mripv4_pools != nullptr) { _children["mripv4-pools"] = mripv4_pools; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mripv6-pools" || name == "mripv4-pools") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pools() : mripv6_pool(this, {"start_address"}) { yang_name = "mripv6-pools"; yang_parent_name = "mobile-network"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::~Mripv6Pools() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mripv6_pool.len(); index++) { if(mripv6_pool[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::has_operation() const { for (std::size_t index=0; index<mripv6_pool.len(); index++) { if(mripv6_pool[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv6-pools"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mripv6-pool") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool>(); ent_->parent = this; mripv6_pool.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mripv6_pool.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mripv6-pool") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::Mripv6Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"}, network_prefix{YType::uint32, "network-prefix"} { yang_name = "mripv6-pool"; yang_parent_name = "mripv6-pools"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::~Mripv6Pool() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set || network_prefix.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter) || ydk::is_set(network_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv6-pool"; ADD_KEY_TOKEN(start_address, "start-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); if (network_prefix.is_set || is_set(network_prefix.yfilter)) leaf_name_data.push_back(network_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } if(value_path == "network-prefix") { network_prefix = value; network_prefix.value_namespace = name_space; network_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } if(value_path == "network-prefix") { network_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix" || name == "network-prefix") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pools() : mripv4_pool(this, {"start_address"}) { yang_name = "mripv4-pools"; yang_parent_name = "mobile-network"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::~Mripv4Pools() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mripv4_pool.len(); index++) { if(mripv4_pool[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::has_operation() const { for (std::size_t index=0; index<mripv4_pool.len(); index++) { if(mripv4_pool[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv4-pools"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mripv4-pool") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool>(); ent_->parent = this; mripv4_pool.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mripv4_pool.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mripv4-pool") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::Mripv4Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"}, network_prefix{YType::uint32, "network-prefix"} { yang_name = "mripv4-pool"; yang_parent_name = "mripv4-pools"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::~Mripv4Pool() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set || network_prefix.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter) || ydk::is_set(network_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv4-pool"; ADD_KEY_TOKEN(start_address, "start-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); if (network_prefix.is_set || is_set(network_prefix.yfilter)) leaf_name_data.push_back(network_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } if(value_path == "network-prefix") { network_prefix = value; network_prefix.value_namespace = name_space; network_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } if(value_path == "network-prefix") { network_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::NetworkAttributes::Authorizes::Authorize::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix" || name == "network-prefix") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::GreKey() : gre_key_type{YType::enumeration, "gre-key-type"}, gre_key_value{YType::uint32, "gre-key-value"} { yang_name = "gre-key"; yang_parent_name = "customer"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::~GreKey() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::has_data() const { if (is_presence_container) return true; return gre_key_type.is_set || gre_key_value.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::has_operation() const { return is_set(yfilter) || ydk::is_set(gre_key_type.yfilter) || ydk::is_set(gre_key_value.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "gre-key"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (gre_key_type.is_set || is_set(gre_key_type.yfilter)) leaf_name_data.push_back(gre_key_type.get_name_leafdata()); if (gre_key_value.is_set || is_set(gre_key_value.yfilter)) leaf_name_data.push_back(gre_key_value.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "gre-key-type") { gre_key_type = value; gre_key_type.value_namespace = name_space; gre_key_type.value_namespace_prefix = name_space_prefix; } if(value_path == "gre-key-value") { gre_key_value = value; gre_key_value.value_namespace = name_space; gre_key_value.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "gre-key-type") { gre_key_type.yfilter = yfilter; } if(value_path == "gre-key-value") { gre_key_value.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::GreKey::has_leaf_or_child_of_name(const std::string & name) const { if(name == "gre-key-type" || name == "gre-key-value") return true; return false; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::BindingAttributes() : max_life_time{YType::uint32, "max-life-time"} { yang_name = "binding-attributes"; yang_parent_name = "customer"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::~BindingAttributes() { } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::has_data() const { if (is_presence_container) return true; return max_life_time.is_set; } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(max_life_time.yfilter); } std::string MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "binding-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (max_life_time.is_set || is_set(max_life_time.yfilter)) leaf_name_data.push_back(max_life_time.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "max-life-time") { max_life_time = value; max_life_time.value_namespace = name_space; max_life_time.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "max-life-time") { max_life_time.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Services::Service::Customers::Customer::BindingAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "max-life-time") return true; return false; } MobileIp::Lmas::Lma::Networks::Networks() : network(this, {"lma_network"}) { yang_name = "networks"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::~Networks() { } bool MobileIp::Lmas::Lma::Networks::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<network.len(); index++) { if(network[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Networks::has_operation() const { for (std::size_t index=0; index<network.len(); index++) { if(network[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Networks::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "networks"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "network") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Networks::Network>(); ent_->parent = this; network.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : network.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Networks::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Networks::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Networks::has_leaf_or_child_of_name(const std::string & name) const { if(name == "network") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::Network() : lma_network{YType::str, "lma-network"} , pool_attributes(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes>()) { pool_attributes->parent = this; yang_name = "network"; yang_parent_name = "networks"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::~Network() { } bool MobileIp::Lmas::Lma::Networks::Network::has_data() const { if (is_presence_container) return true; return lma_network.is_set || (pool_attributes != nullptr && pool_attributes->has_data()); } bool MobileIp::Lmas::Lma::Networks::Network::has_operation() const { return is_set(yfilter) || ydk::is_set(lma_network.yfilter) || (pool_attributes != nullptr && pool_attributes->has_operation()); } std::string MobileIp::Lmas::Lma::Networks::Network::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "network"; ADD_KEY_TOKEN(lma_network, "lma-network"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lma_network.is_set || is_set(lma_network.yfilter)) leaf_name_data.push_back(lma_network.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "pool-attributes") { if(pool_attributes == nullptr) { pool_attributes = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes>(); } return pool_attributes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(pool_attributes != nullptr) { _children["pool-attributes"] = pool_attributes; } return _children; } void MobileIp::Lmas::Lma::Networks::Network::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lma-network") { lma_network = value; lma_network.value_namespace = name_space; lma_network.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Networks::Network::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lma-network") { lma_network.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Networks::Network::has_leaf_or_child_of_name(const std::string & name) const { if(name == "pool-attributes" || name == "lma-network") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::PoolAttributes() : mobile_node(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode>()) , mobile_network(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork>()) { mobile_node->parent = this; mobile_network->parent = this; yang_name = "pool-attributes"; yang_parent_name = "network"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::~PoolAttributes() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::has_data() const { if (is_presence_container) return true; return (mobile_node != nullptr && mobile_node->has_data()) || (mobile_network != nullptr && mobile_network->has_data()); } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::has_operation() const { return is_set(yfilter) || (mobile_node != nullptr && mobile_node->has_operation()) || (mobile_network != nullptr && mobile_network->has_operation()); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "pool-attributes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mobile-node") { if(mobile_node == nullptr) { mobile_node = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode>(); } return mobile_node; } if(child_yang_name == "mobile-network") { if(mobile_network == nullptr) { mobile_network = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork>(); } return mobile_network; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(mobile_node != nullptr) { _children["mobile-node"] = mobile_node; } if(mobile_network != nullptr) { _children["mobile-network"] = mobile_network; } return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mobile-node" || name == "mobile-network") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::MobileNode() : ipv4_pool(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool>()) , ipv6_pool(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool>()) { ipv4_pool->parent = this; ipv6_pool->parent = this; yang_name = "mobile-node"; yang_parent_name = "pool-attributes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::~MobileNode() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::has_data() const { if (is_presence_container) return true; return (ipv4_pool != nullptr && ipv4_pool->has_data()) || (ipv6_pool != nullptr && ipv6_pool->has_data()); } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::has_operation() const { return is_set(yfilter) || (ipv4_pool != nullptr && ipv4_pool->has_operation()) || (ipv6_pool != nullptr && ipv6_pool->has_operation()); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mobile-node"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv4-pool") { if(ipv4_pool == nullptr) { ipv4_pool = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool>(); } return ipv4_pool; } if(child_yang_name == "ipv6-pool") { if(ipv6_pool == nullptr) { ipv6_pool = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool>(); } return ipv6_pool; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(ipv4_pool != nullptr) { _children["ipv4-pool"] = ipv4_pool; } if(ipv6_pool != nullptr) { _children["ipv6-pool"] = ipv6_pool; } return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv4-pool" || name == "ipv6-pool") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::Ipv4Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"} { yang_name = "ipv4-pool"; yang_parent_name = "mobile-node"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::~Ipv4Pool() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set; } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv4-pool"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv4Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::Ipv6Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"} { yang_name = "ipv6-pool"; yang_parent_name = "mobile-node"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::~Ipv6Pool() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set; } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6-pool"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNode::Ipv6Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::MobileNetwork() : mripv6_pools(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools>()) , mripv4_pools(std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools>()) { mripv6_pools->parent = this; mripv4_pools->parent = this; yang_name = "mobile-network"; yang_parent_name = "pool-attributes"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::~MobileNetwork() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::has_data() const { if (is_presence_container) return true; return (mripv6_pools != nullptr && mripv6_pools->has_data()) || (mripv4_pools != nullptr && mripv4_pools->has_data()); } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::has_operation() const { return is_set(yfilter) || (mripv6_pools != nullptr && mripv6_pools->has_operation()) || (mripv4_pools != nullptr && mripv4_pools->has_operation()); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mobile-network"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mripv6-pools") { if(mripv6_pools == nullptr) { mripv6_pools = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools>(); } return mripv6_pools; } if(child_yang_name == "mripv4-pools") { if(mripv4_pools == nullptr) { mripv4_pools = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools>(); } return mripv4_pools; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(mripv6_pools != nullptr) { _children["mripv6-pools"] = mripv6_pools; } if(mripv4_pools != nullptr) { _children["mripv4-pools"] = mripv4_pools; } return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mripv6-pools" || name == "mripv4-pools") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pools() : mripv6_pool(this, {"start_address"}) { yang_name = "mripv6-pools"; yang_parent_name = "mobile-network"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::~Mripv6Pools() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mripv6_pool.len(); index++) { if(mripv6_pool[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::has_operation() const { for (std::size_t index=0; index<mripv6_pool.len(); index++) { if(mripv6_pool[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv6-pools"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mripv6-pool") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool>(); ent_->parent = this; mripv6_pool.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mripv6_pool.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mripv6-pool") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::Mripv6Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"}, network_prefix{YType::uint32, "network-prefix"} { yang_name = "mripv6-pool"; yang_parent_name = "mripv6-pools"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::~Mripv6Pool() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set || network_prefix.is_set; } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter) || ydk::is_set(network_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv6-pool"; ADD_KEY_TOKEN(start_address, "start-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); if (network_prefix.is_set || is_set(network_prefix.yfilter)) leaf_name_data.push_back(network_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } if(value_path == "network-prefix") { network_prefix = value; network_prefix.value_namespace = name_space; network_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } if(value_path == "network-prefix") { network_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv6Pools::Mripv6Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix" || name == "network-prefix") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pools() : mripv4_pool(this, {"start_address"}) { yang_name = "mripv4-pools"; yang_parent_name = "mobile-network"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::~Mripv4Pools() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mripv4_pool.len(); index++) { if(mripv4_pool[index]->has_data()) return true; } return false; } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::has_operation() const { for (std::size_t index=0; index<mripv4_pool.len(); index++) { if(mripv4_pool[index]->has_operation()) return true; } return is_set(yfilter); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv4-pools"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mripv4-pool") { auto ent_ = std::make_shared<MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool>(); ent_->parent = this; mripv4_pool.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mripv4_pool.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::set_filter(const std::string & value_path, YFilter yfilter) { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mripv4-pool") return true; return false; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::Mripv4Pool() : start_address{YType::str, "start-address"}, pool_prefix{YType::uint32, "pool-prefix"}, network_prefix{YType::uint32, "network-prefix"} { yang_name = "mripv4-pool"; yang_parent_name = "mripv4-pools"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::~Mripv4Pool() { } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::has_data() const { if (is_presence_container) return true; return start_address.is_set || pool_prefix.is_set || network_prefix.is_set; } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::has_operation() const { return is_set(yfilter) || ydk::is_set(start_address.yfilter) || ydk::is_set(pool_prefix.yfilter) || ydk::is_set(network_prefix.yfilter); } std::string MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mripv4-pool"; ADD_KEY_TOKEN(start_address, "start-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (start_address.is_set || is_set(start_address.yfilter)) leaf_name_data.push_back(start_address.get_name_leafdata()); if (pool_prefix.is_set || is_set(pool_prefix.yfilter)) leaf_name_data.push_back(pool_prefix.get_name_leafdata()); if (network_prefix.is_set || is_set(network_prefix.yfilter)) leaf_name_data.push_back(network_prefix.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "start-address") { start_address = value; start_address.value_namespace = name_space; start_address.value_namespace_prefix = name_space_prefix; } if(value_path == "pool-prefix") { pool_prefix = value; pool_prefix.value_namespace = name_space; pool_prefix.value_namespace_prefix = name_space_prefix; } if(value_path == "network-prefix") { network_prefix = value; network_prefix.value_namespace = name_space; network_prefix.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "start-address") { start_address.yfilter = yfilter; } if(value_path == "pool-prefix") { pool_prefix.yfilter = yfilter; } if(value_path == "network-prefix") { network_prefix.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::Networks::Network::PoolAttributes::MobileNetwork::Mripv4Pools::Mripv4Pool::has_leaf_or_child_of_name(const std::string & name) const { if(name == "start-address" || name == "pool-prefix" || name == "network-prefix") return true; return false; } MobileIp::Lmas::Lma::ReplayProtection::ReplayProtection() : timestamp_window{YType::uint32, "timestamp-window"} { yang_name = "replay-protection"; yang_parent_name = "lma"; is_top_level_class = false; has_list_ancestor = true; } MobileIp::Lmas::Lma::ReplayProtection::~ReplayProtection() { } bool MobileIp::Lmas::Lma::ReplayProtection::has_data() const { if (is_presence_container) return true; return timestamp_window.is_set; } bool MobileIp::Lmas::Lma::ReplayProtection::has_operation() const { return is_set(yfilter) || ydk::is_set(timestamp_window.yfilter); } std::string MobileIp::Lmas::Lma::ReplayProtection::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "replay-protection"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > MobileIp::Lmas::Lma::ReplayProtection::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (timestamp_window.is_set || is_set(timestamp_window.yfilter)) leaf_name_data.push_back(timestamp_window.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> MobileIp::Lmas::Lma::ReplayProtection::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> MobileIp::Lmas::Lma::ReplayProtection::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void MobileIp::Lmas::Lma::ReplayProtection::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "timestamp-window") { timestamp_window = value; timestamp_window.value_namespace = name_space; timestamp_window.value_namespace_prefix = name_space_prefix; } } void MobileIp::Lmas::Lma::ReplayProtection::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "timestamp-window") { timestamp_window.yfilter = yfilter; } } bool MobileIp::Lmas::Lma::ReplayProtection::has_leaf_or_child_of_name(const std::string & name) const { if(name == "timestamp-window") return true; return false; } const Enum::YLeaf ServiceType::ipv4 {1, "ipv4"}; const Enum::YLeaf ServiceType::ipv6 {2, "ipv6"}; const Enum::YLeaf ServiceType::dual {3, "dual"}; const Enum::YLeaf LmaService::service_mll {1, "service-mll"}; const Enum::YLeaf EncapOpt::greipv4 {4, "greipv4"}; const Enum::YLeaf EncapOpt::greipv6 {5, "greipv6"}; const Enum::YLeaf EncapOpt::mgreipv4 {7, "mgreipv4"}; const Enum::YLeaf EncapOpt::mgreipv6 {8, "mgreipv6"}; const Enum::YLeaf RedistSubType::host_prefix {1, "host-prefix"}; const Enum::YLeaf RedistSubType::disable {2, "disable"}; const Enum::YLeaf LmaRole::Y_3gma {0, "3gma"}; const Enum::YLeaf RedistType::home_address {1, "home-address"}; const Enum::YLeaf GreKeyType::symmetric {1, "symmetric"}; const Enum::YLeaf LmaRat::virtual_ {0, "virtual"}; const Enum::YLeaf LmaRat::ppp {1, "ppp"}; const Enum::YLeaf LmaRat::ethernet {2, "ethernet"}; const Enum::YLeaf LmaRat::wlan {3, "wlan"}; const Enum::YLeaf LmaRat::wi_max {4, "wi-max"}; const Enum::YLeaf LmaRat::Y_3gppgeran {5, "3gppgeran"}; const Enum::YLeaf LmaRat::Y_3gpputran {6, "3gpputran"}; const Enum::YLeaf LmaRat::Y_3gppeutran {7, "3gppeutran"}; const Enum::YLeaf LmaRat::Y_3gpp2ehrpd {8, "3gpp2ehrpd"}; const Enum::YLeaf LmaRat::Y_3gpp2hrpd {9, "3gpp2hrpd"}; const Enum::YLeaf LmaRat::Y_3gpp21rtt {10, "3gpp21rtt"}; const Enum::YLeaf LmaRat::Y_3gpp2umb {11, "3gpp2umb"}; } }
32.400759
708
0.690361
CiscoDevNet
80b8280507d0875ee79783a046e73a5fcc256e4d
9,436
cpp
C++
Source/AllProjects/CQCDrvDev/CQCDrvDev_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCDrvDev/CQCDrvDev_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCDrvDev/CQCDrvDev_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCDrvDev_ThisFacility.cpp // // AUTHOR: Dean Roddey // // CREATED: 02/14/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CQCDrvDev.hpp" // --------------------------------------------------------------------------- // Do our RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TFacCQCDrvDev,TGUIFacility) // --------------------------------------------------------------------------- // CLASS: TFacCQCDrvDev // PREFIX: fac // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TFacCQCDrvDev: Constructors and operators // --------------------------------------------------------------------------- TFacCQCDrvDev::TFacCQCDrvDev() : TGUIFacility ( L"CQCDrvDev" , tCIDLib::EModTypes::Exe , kCIDLib::c4MajVersion , kCIDLib::c4MinVersion , kCIDLib::c4Revision , tCIDLib::EModFlags::HasMsgsAndRes ) { m_strTitleText = strMsg(kDrvDevMsgs::midMsg_Title); } TFacCQCDrvDev::~TFacCQCDrvDev() { } // --------------------------------------------------------------------------- // TFacCQCDrvDev: Public, non-virtual methods // --------------------------------------------------------------------------- const TCQCUserCtx& TFacCQCDrvDev::cuctxToUse() const { return m_cuctxToUse; } tCIDLib::EExitCodes TFacCQCDrvDev::eMainThread(TThread& thrThis, tCIDLib::TVoid*) { // Let our caller go thrThis.Sync(); // // Ask CQCKit to load core environment/parm stuff. If we can't do this, // then we are doomed and just have to exit. // TString strFailReason; if (!facCQCKit().bLoadEnvInfo(strFailReason, kCIDLib::True)) { TErrBox msgbTest(m_strTitleText, strMsg(kDrvDevMsgs::midStatus_BadEnv, strFailReason)); msgbTest.ShowIt(TWindow::wndDesktop()); return tCIDLib::EExitCodes::BadEnvironment; } TLogSrvLogger* plgrLogSrv = nullptr; try { // // First thing of all, check to see if there is already an instance // running. If so, activate it and just exit. // TResourceName rsnInstance(L"CQSL", L"CQCDrvDev", L"SingleInstanceInfo"); if (TProcess::bSetSingleInstanceInfo(rsnInstance, kCIDLib::True)) return tCIDLib::EExitCodes::Normal; // // Now we can initialize the client side ORB, which we have to // do, despite being mostly standalone, because of the need to // read/write macros from the data server. // facCIDOrb().InitClient(); // // The next thing we want to do is to install a log server logger. We // just use the standard one that's provided by CIDLib. It logs to // the standard CIDLib log server, and uses a local file for fallback // if it cannot connect. // plgrLogSrv = new TLogSrvLogger(facCQCKit().strLocalLogDir()); TModule::InstallLogger(plgrLogSrv, tCIDLib::EAdoptOpts::Adopt); // Parse the command line parms tCIDLib::TBoolean bNoState = kCIDLib::False; if (!bParseParms(bNoState)) return tCIDLib::EExitCodes::BadParameters; // Do a version check against the master server and exit if not valid if (!facCQCIGKit().bCheckCQCVersion(TWindow::wndDesktop(), m_strTitleText)) return tCIDLib::EExitCodes::InitFailed; // We have to log on before we can do anything. If that works if (!bDoLogon()) return tCIDLib::EExitCodes::Normal; // Initialize the local config store facCQCGKit().InitObjectStore ( kCQCDrvDev::strStoreKey, m_cuctxToUse.strUserName(), bNoState ); // // We have to install some class loaders on the macro engine // facility, so that the standard CQC runtime classes and driver // classes are available. // facCQCMEng().InitCMLRuntime(m_cuctxToUse.sectUser()); facCQCMedia().InitCMLRuntime(); facCQCGenDrvS().InitCMLRuntime(); // // Enable the sending out of events, so that any user action events // the driver might send out can be tested. // facCQCKit().StartEventProcessing(tCQCKit::EEvProcTypes::Send, m_cuctxToUse.sectUser()); // // Register any local serial port factories we want to make available. // facGC100Ser().bUpdateFactory(m_cuctxToUse.sectUser()); facJAPwrSer().bUpdateFactory(m_cuctxToUse.sectUser()); // // Load any previous config we might have had (assuming it wasn't // tossed via the 'no state' command line parm above. // TCQCFrameState fstMain; facCQCGKit().bReadFrameState(kCQCDrvDev::strCfgKey_Frame, fstMain, TSize(640, 480)); m_wndMainFrame.Create(fstMain); } catch(const TError& errToCatch) { TExceptDlg dlgErr ( TWindow::wndDesktop() , m_strTitleText , strMsg(kDrvDevMsgs::midMsg_Exception) , errToCatch ); return tCIDLib::EExitCodes::InitFailed; } catch(...) { TErrBox msgbErr(m_strTitleText, strMsg(kDrvDevMsgs::midMsg_UnknownExcept)); msgbErr.ShowIt(TWindow::wndDesktop()); return tCIDLib::EExitCodes::InitFailed; } // // Call the window processing loop. We won't come back until the // program exits. No exceptions will come out of here, so we don't // have to protect it. We use the MDI enabled loop here. // facCIDCtrls().uMainMsgLoop(m_wndMainFrame); try { m_wndMainFrame.Destroy(); } catch(TError& errToCatch) { if (bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); LogEventObj(errToCatch); } } // Terminate the local config store try { facCQCGKit().TermObjectStore(); } catch(TError& errToCatch) { if (bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); LogEventObj(errToCatch); } } // Force the log server logger to local logging, and terminate the orb try { if (plgrLogSrv) plgrLogSrv->bForceLocal(kCIDLib::True); facCIDOrb().Terminate(); } catch(TError& errToCatch) { if (bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); LogEventObj(errToCatch); } } // And finally make the logger stop logging try { if (plgrLogSrv) plgrLogSrv->Cleanup(); } catch(...) { } try { // Turn event processing back off facCQCKit().StopEventProcessing(); } catch(...) { } return tCIDLib::EExitCodes::Normal; } // --------------------------------------------------------------------------- // TFacCQCDrvDev: Private, non-virtual methods // --------------------------------------------------------------------------- // // This method runs the standard CQC logon dialog. If it succeeds, we get // back the security token for the user, which we set on CQCKit for subsequent // use by the app. // tCIDLib::TBoolean TFacCQCDrvDev::bDoLogon() { // // We'll get a temp security token, which we'll store on the CQCKit // facility if we succeed, and it'll fill in a user account object of // ours, which we'll use for a few things. The last parameter allows // environmentally based logon. // TCQCUserAccount uaccLogin; TCQCSecToken sectTmp; if (facCQCGKit().bLogon(TWindow::wndDesktop() , sectTmp , uaccLogin , tCQCKit::EUserRoles::SystemAdmin , m_strTitleText , kCIDLib::False , L"DriverIDE")) { // // Ok, they can log on, so let's set up our user context for // later user. // m_cuctxToUse.Set(uaccLogin, sectTmp); m_cuctxToUse.LoadEnvRTVsFromHost(); return kCIDLib::True; } return kCIDLib::False; } tCIDLib::TBoolean TFacCQCDrvDev::bParseParms(tCIDLib::TBoolean& bIgnoreState) { // // Most of our parms are handled by CQCKit, but we support a /NoState flag, to ignore // the saved state and start with default window positions. Assume not to ignore unless // told to. // bIgnoreState = kCIDLib::False; TSysInfo::TCmdLineCursor cursParms = TSysInfo::cursCmdLineParms(); for (; cursParms; ++cursParms) { if (cursParms->bCompareI(L"/NoState")) bIgnoreState = kCIDLib::True; } return kCIDLib::True; }
29.033846
95
0.54769
MarkStega
01eafe7fbc1f18a52ae6170123916fadc06473b2
1,983
cpp
C++
src/shaders/shader_loader.cpp
sardok/minecraft-challenge
709fe9ca887cf492fd48d49f84af0029fa996781
[ "MIT" ]
null
null
null
src/shaders/shader_loader.cpp
sardok/minecraft-challenge
709fe9ca887cf492fd48d49f84af0029fa996781
[ "MIT" ]
null
null
null
src/shaders/shader_loader.cpp
sardok/minecraft-challenge
709fe9ca887cf492fd48d49f84af0029fa996781
[ "MIT" ]
null
null
null
#include <stdexcept> #include <iostream> #include <shaders/shader_loader.hpp> #include <utils/file_utils.hpp> namespace { GLuint compile_shader(const GLchar *source, GLenum shader_type) { auto shader_id = glCreateShader(shader_type); glShaderSource(shader_id, 1, &source, nullptr); glCompileShader(shader_id); GLint success = 0; GLchar info_log[512]; glGetShaderiv(shader_id, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader_id, 512, nullptr, info_log); throw std::runtime_error("Unable to load a shader: " + std::string(info_log)); } return shader_id; } GLuint link_program(GLuint vertex_shader_id, GLuint fragment_shader_id) { auto id = glCreateProgram(); glAttachShader(id, vertex_shader_id); glAttachShader(id, fragment_shader_id); glLinkProgram(id); return id; } void check_link_success(GLuint shader_id) { GLint success = 0; GLchar info_log[512]; glGetProgramiv(shader_id, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader_id, 512, nullptr, info_log); throw std::runtime_error("Failed shader linking: " + std::string(info_log)); } } } // namespace GLuint load_shaders( const std::string &vertex_shader, const std::string &fragment_shader) { auto vertex_source = get_file_contents("shaders/" + vertex_shader + ".glsl"); auto fragment_source = get_file_contents("shaders/" + fragment_shader + ".glsl"); auto vertex_shader_id = compile_shader(vertex_source.c_str(), GL_VERTEX_SHADER); auto fragment_shader_id = compile_shader(fragment_source.c_str(), GL_FRAGMENT_SHADER); auto shader_id = link_program(vertex_shader_id, fragment_shader_id); check_link_success(shader_id); glDetachShader(shader_id, vertex_shader_id); glDetachShader(shader_id, fragment_shader_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); return shader_id; }
27.164384
90
0.723651
sardok
01f18891798599673655af558f6b7d1308d60d8d
701
cpp
C++
Problems/Timus/2056_Scholarship/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
Problems/Timus/2056_Scholarship/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
1
2019-05-09T19:17:00.000Z
2019-05-09T19:17:00.000Z
Problems/Timus/2056_Scholarship/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); // freopen("output.txt", "wt", stdout); #endif int marks; cin >> marks; bool has3 = false; bool only5 = true; float total = 0; for (int i = 0; i < marks; ++i) { int m; cin >> m; total += m; if (m != 5) { only5 = false; if (m == 3) has3 = true; } } if (only5) cout << "Named"; else if (!has3) { if(total / marks >= 4.5f) cout << "High"; else cout << "Common"; } else cout << "None"; }
16.302326
41
0.415121
grand87
01f2ce88c0667647af9032d4fc99a3b7a10f8a78
1,352
cpp
C++
Lab_3/DllStringReplacement/StringReplacer.cpp
BSUIR-SFIT-Labs/OSaSP-Labs-Windows
d32278525e1301ae61debb3d185495cf6130cdb6
[ "MIT" ]
4
2020-09-06T14:56:03.000Z
2022-03-11T10:42:06.000Z
Lab_3/DllStringReplacement/StringReplacer.cpp
BSUIR-SFIT-Labs/OSaSP-Labs-Windows
d32278525e1301ae61debb3d185495cf6130cdb6
[ "MIT" ]
null
null
null
Lab_3/DllStringReplacement/StringReplacer.cpp
BSUIR-SFIT-Labs/OSaSP-Labs-Windows
d32278525e1301ae61debb3d185495cf6130cdb6
[ "MIT" ]
null
null
null
#include <Windows.h> #include <vector> extern "C" void __declspec(dllexport) __stdcall ReplaceString( DWORD pid, const char* srcString, const char* resString) { HANDLE hProcess = OpenProcess( PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, pid); if (hProcess) { SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); MEMORY_BASIC_INFORMATION memoryInfo; std::vector<char> chunk; char* p = 0; while (p < systemInfo.lpMaximumApplicationAddress) { if (VirtualQueryEx(hProcess, p, &memoryInfo, sizeof(memoryInfo)) == sizeof(memoryInfo)) { if (memoryInfo.State == MEM_COMMIT && memoryInfo.AllocationProtect == PAGE_READWRITE) { p = (char*)memoryInfo.BaseAddress; chunk.resize(memoryInfo.RegionSize); SIZE_T bytesRead; try { if (ReadProcessMemory(hProcess, p, &chunk[0], memoryInfo.RegionSize, &bytesRead)) { for (size_t i = 0; i < (bytesRead - strlen(srcString)); ++i) { if (memcmp(srcString, &chunk[i], strlen(srcString)) == 0) { char* ref = (char*)p + i; for (int j = 0; j < strlen(resString); j++) ref[j] = resString[j]; ref[strlen(resString)] = 0; } } } } catch (std::bad_alloc& e) { } } p += memoryInfo.RegionSize; } } } }
21.806452
90
0.611686
BSUIR-SFIT-Labs
01f456ad347704771c52dc7f8d669f1b52702892
534
cpp
C++
Cpp/1657.determine-if-two-strings-are-close.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/1657.determine-if-two-strings-are-close.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/1657.determine-if-two-strings-are-close.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: bool closeStrings(string word1, string word2) { int mask1 = 0, mask2 = 0; for (char &c : word1) mask1 |= (1 << (c - 'a')); for (char &c : word2) mask2 |= (1 << (c - 'a')); if (mask1 != mask2) return false; vector<int> cnt1(26), cnt2(26); for (char &c : word1) cnt1[c-'a'] ++; for (char &c : word2) cnt2[c-'a'] ++; sort(cnt1.begin(), cnt1.end()); sort(cnt2.begin(), cnt2.end()); return cnt1 == cnt2; } };
31.411765
56
0.468165
zszyellow
01f7518d3da06eca30974d08aed74fc225cbc47f
10,137
cpp
C++
zombie2/zombie2/source/applicationtasktestparticle.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
zombie2/zombie2/source/applicationtasktestparticle.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
zombie2/zombie2/source/applicationtasktestparticle.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
// // applicationtask.cpp // Great Little Shooter // // Created by David Coen on 2011 05 30 // Copyright Pleasure seeking morons 2011. All rights reserved. // #include <vld.h> #include "ApplicationTaskTestParticle.h" #include <gapplicationwindow.h> #include <grender.h> #include <gresourcemanager.h> #include <gfilesystem.h> #include <gcamera.h> #include <gmath.h> #include <GStringUtility.h> #include <GScratchPad.h> #include <GGuiManager.h> #include <GMissionMaster.h> #include <GView.h> #include <GResourceManager.h> #include <GMeshStreamInfo.h> #include <GMeshManual.h> #include <GMaterialType.h> #include <GStringUtility.h> #include <GMaterial.h> #include <GMaterialInstance.h> #include <GCamera.h> #include <GRender.h> #include <GMesh.h> #include <GScene.h> #include <GSceneNodeFactory.h> #include <GSceneVisitorRender.h> #include <GCameraInput.h> #include <GInput.h> #include <GInputButton.h> #include <GSceneVisitorAll.h> #include <GSceneNodeComponentAnimation.h> #include <GSceneNodeComponentNodeAttach.h> #include <GSceneNodeComponentClient.h> #include <GSceneNodeComponentVisual.h> #include <GRenderBlur.h> #include <GRenderWash.h> #include <GColour4Float.h> #include <GColour4Byte.h> #include <GRenderShadow.h> #include <GParticleManager.h> #include <GSceneNodeComponentParticleLoad.h> #include <GScenePostLoadCallback.h> #include <GSceneNodeComponentParticle.h> #ifdef IPHONE #include <GIPhoneView.h> #elif WIN32 #include <GWin32View.h> #endif typedef std::vector<GMeshStreamInfo> TArrayStreamInfo; typedef std::vector<GU8> TArrayByte; typedef std::vector<GScenePostLoadCallback> TArrayScenePostLoadCallback; typedef boost::shared_ptr<GSceneNodeComponentBase> TPointerSceneNodeComponentBase; typedef TPointerSceneNodeComponentBase (*TComponentFactoryClientCallback)( GScene& inout_scene, //access to mesh/ material manager boost::shared_ptr< GSceneNode >& inout_owner, //pain, some components may want access to owner. means we need to create components after node, so node needs ablity to add component TArrayScenePostLoadCallback& inout_arrayPostLoadCallback, void* const in_data ); typedef std::pair<TComponentFactoryClientCallback, void*> TPairFactoryClientCallbackData; typedef std::map<std::string, TPairFactoryClientCallbackData> TMapStringPairFactoryClientCallbackData; typedef boost::shared_ptr<GSceneNodeFactory> TPointerSceneNodeFactory; static const float sDefaultCameraPerspectiveNear = 0.1F; static const float sDefaultCameraPerspectiveFar = 100.0F; static const float sDefaultCameraBounds = 0.05F; /////////////////////////////////////////////////////// //constructor ApplicationTaskTestParticle::ApplicationTaskTestParticle() : mApplicationWindow() , mViewRender() , mRender() , mFileSystem() , mResourceManager() { mApplicationWindow.reset(new GApplicationWindow); mViewRender = mApplicationWindow->CreateViewRender(mRender, false, true, false, 1.0F); mApplicationWindow->PushViewFront(mViewRender); mFileSystem.reset(new GFileSystem); mScratchPad.reset(new GScratchPad); mResourceManager.reset(new GResourceManager(mFileSystem, mRender)); mApplicationWindow->Show(); m_cameraInput.reset(new GCameraInput( sDefaultCameraPerspectiveNear, sDefaultCameraPerspectiveFar, sDefaultCameraBounds, -GVector3Float::sUnitZ, GVector3Float::sUnitY, GVector3Float(0.0F, 0.0F, 0.0F), -4.0F )); { TArrayStreamInfo arrayStreamLoad; GMeshStreamInfo::AppendStreamInfo( arrayStreamLoad, GMeshType::TStreamType::TFloat, 3, GMeshType::TStreamUsage::TPosition ); GMeshStreamInfo::AppendStreamInfo( arrayStreamLoad, GMeshType::TStreamType::TFloat, 2, GMeshType::TStreamUsage::TUv0 ); TArrayByte arrayVertexIndex; arrayVertexIndex.push_back(0); arrayVertexIndex.push_back(1); arrayVertexIndex.push_back(2); arrayVertexIndex.push_back(0); arrayVertexIndex.push_back(2); arrayVertexIndex.push_back(3); arrayVertexIndex.push_back(0); arrayVertexIndex.push_back(3); arrayVertexIndex.push_back(1); arrayVertexIndex.push_back(1); arrayVertexIndex.push_back(3); arrayVertexIndex.push_back(2); m_mesh.reset(new GMeshManual( GMeshType::TPrimitiveType::TTriangle, arrayVertexIndex, 4, arrayStreamLoad )); //GetFloatRef(const GS32 in_vertexDataIndex, const GS32 in_streamIndex, const GS32 in_subIndex) m_mesh->GetFloatRef(0, 0, 0) = 0.0f; m_mesh->GetFloatRef(0, 0, 1) = 0.0f; m_mesh->GetFloatRef(0, 0, 2) = 0.0f; m_mesh->GetFloatRef(1, 0, 0) = 1.0f; m_mesh->GetFloatRef(1, 0, 1) = 0.0f; m_mesh->GetFloatRef(1, 0, 2) = 0.0f; m_mesh->GetFloatRef(2, 0, 0) = 0.0f; m_mesh->GetFloatRef(2, 0, 1) = 2.0f; m_mesh->GetFloatRef(2, 0, 2) = 0.0f; m_mesh->GetFloatRef(3, 0, 0) = 0.0f; m_mesh->GetFloatRef(3, 0, 1) = 0.0f; m_mesh->GetFloatRef(3, 0, 2) = 1.0f; m_mesh->GetFloatRef(0, 1, 0) = 1.0f; m_mesh->GetFloatRef(0, 1, 1) = 1.0f; m_mesh->GetFloatRef(1, 1, 0) = 1.0f; m_mesh->GetFloatRef(1, 1, 1) = 0.0f; m_mesh->GetFloatRef(2, 1, 0) = 0.0f; m_mesh->GetFloatRef(2, 1, 1) = 1.0f; m_mesh->GetFloatRef(3, 1, 0) = 0.0f; m_mesh->GetFloatRef(3, 1, 1) = 0.0f; } TMapStringPairFactoryClientCallbackData clientComponentFactory; TPointerSceneNodeFactory sceneNodeFactory; mParticleManager = GParticleManager::Factory( mResourceManager->GetFileManager(), "particlemanager.data" ); #if 0 m_scene = GScene::Factory(mResourceManager, clientComponentFactory, sceneNodeFactory, "scenetest.data", particleManager); #else m_scene.reset(new GScene( mResourceManager, clientComponentFactory, sceneNodeFactory, mParticleManager )); if (m_scene) { TArrayScenePostLoadCallback arrayPostLoad; m_sceneNodeParticle.reset(new GSceneNode("sceneNodeParticle")); GMatrix16Float matrix(GMatrix16Float::sIdentity); matrix.SetPosition(GVector3Float(1.0F, 1.0F, 1.0F)); m_sceneNodeParticle->SetWorldTransform(matrix); boost::shared_ptr<GSceneNodeComponentBase> pComponent = GSceneNodeComponentParticle::FactoryManual( *m_scene, m_sceneNodeParticle, "material_particle00a.data", 2.0F, 1000, 1000, 2 ); m_sceneNodeParticle->AddComponent(pComponent); m_sceneNodeComponentParticle = boost::dynamic_pointer_cast< GSceneNodeComponentParticle >(pComponent); boost::shared_ptr< GSceneNode > sceneNodeRoot(new GSceneNode("root")); sceneNodeRoot->AddChildNode(m_sceneNodeParticle); m_scene->AddSceneRoot(sceneNodeRoot); GScene::FactoryPostLoad(arrayPostLoad, *m_scene); } #endif m_material = mResourceManager->GetMaterialInstance( "material_particle00a.data", true, false ); if (m_sceneNodeComponentParticle) { m_sceneNodeComponentParticle->RequestParticle( 1, GVector3Float::sZero, GVector3Float::sUnitX, GVector3Float::sUnitY, 10000000.0, 1.0F, 1.0F, 0.5F, 0.5F ); m_sceneNodeComponentParticle->RequestEmittor(1, 0.0F); } return; } /*virtual*/ ApplicationTaskTestParticle::~ApplicationTaskTestParticle() { mApplicationWindow.reset(); return; } /////////////////////////////////////////////////////// //implement GApplicationTask /*virtual*/ const GBOOL ApplicationTaskTestParticle::OnTick(const GR32 in_timeDelta) { #ifdef AUTO_BAIL static int sLimit = 0; sLimit += 1; if (100 < sLimit) { VLDReportLeaks (); return false; } #endif GBOOL result = GTRUE; GR32 localTick = in_timeDelta; if (mApplicationWindow) { mApplicationWindow->PreTick(localTick); result = mApplicationWindow->Tick(localTick); if (result && mRender) { GApplicationWindowType::TOrientation::TEnum screenOrientation = GApplicationWindowType::TOrientation::TCount; int width = 10; int height = 10; mApplicationWindow->GetScreenDimention(screenOrientation, width, height); SetScreen(width, height, screenOrientation); Input(mApplicationWindow->GetInput()); Tick(localTick); Draw(*mRender); } mApplicationWindow->PostTick(localTick); } return result; } /*virtual*/ void ApplicationTaskTestParticle::OnSetActive(const GBOOL in_active) { return; } /*virtual*/ GVOID ApplicationTaskTestParticle::Input(const GInput& in_input) { if (m_cameraInput) { if ((0 < in_input.GetButtonCount()) && in_input.GetButton(0).GetDown()) { m_cameraInput->Reset( -GVector3Float::sUnitZ, GVector3Float::sUnitY, GVector3Float::sZero, -5.0F ); } m_cameraInput->Input(in_input); } } GVOID ApplicationTaskTestParticle::Tick(const GR32 in_timeDelta) { if (m_cameraInput) { m_cameraInput->Tick(in_timeDelta); } if (m_scene) { GScene& scene = *m_scene; GSceneVisitorAllTick<GSceneNodeComponentAnimation>::Run(scene, in_timeDelta); GSceneVisitorAllUpdate<GSceneNodeComponentNodeAttach>::Run(scene); GSceneVisitorAllTick<GSceneNodeComponentParticle>::Run(scene, in_timeDelta); GSceneVisitorAllCamera<GSceneNodeComponentParticle>::Run(scene, m_cameraInput->GetCamera()); GSceneVisitorAllTick<GSceneNodeComponentVisual>::Run(scene, in_timeDelta); } } GVOID ApplicationTaskTestParticle::Draw(GRender& inout_render) { inout_render.RenderStart(true, GColour4Float::sBlack, true); //boost::shared_ptr<GMaterialInstance> materialInstance = m_material.lock(); //if (materialInstance) //{ // inout_render.SetMaterial(*materialInstance); //} if (m_cameraInput) { inout_render.SetCamera(m_cameraInput->GetCamera()); } //inout_render.SetObjectTransform(GMatrix16Float::sIdentity); //if (m_mesh) //{ // inout_render.DrawMesh(m_mesh->GetMesh(), m_mesh->GetMesh().GetVertexData()); // } if (m_cameraInput && m_scene) { GSceneVisitorRender::Run( *m_scene, inout_render, m_cameraInput->GetCamera() ); #ifdef DSC_DEBUG m_scene->DebugDraw( inout_render, m_cameraInput->GetCamera() ); m_scene->GetArrayDebugMatrix().clear(); #endif } inout_render.Present(); } GVOID ApplicationTaskTestParticle::SetScreen( const GS32 in_screenWidth, const GS32 in_screenHeight, const GApplicationWindowType::TOrientation::TEnum in_screenOrientation ) { m_cameraInput->SetScreen( in_screenWidth, in_screenHeight, in_screenOrientation ); }
25.534005
181
0.742626
DavidCoenFish
01fb74b0642cf6deb39f72c162891b962fded70f
70
cpp
C++
subprojects/docs/src/samples/native-binaries/google-test/src/operators/cpp/minus.cpp
Vestmark/vestmark-gradle
77078ad580b546410d52e9df34f96d1d57dc51ff
[ "Apache-2.0" ]
158
2015-04-18T23:39:02.000Z
2021-07-01T18:28:29.000Z
subprojects/docs/src/samples/native-binaries/google-test/src/operators/cpp/minus.cpp
Vestmark/vestmark-gradle
77078ad580b546410d52e9df34f96d1d57dc51ff
[ "Apache-2.0" ]
31
2015-04-29T18:52:40.000Z
2020-06-29T19:25:24.000Z
subprojects/docs/src/samples/native-binaries/google-test/src/operators/cpp/minus.cpp
Vestmark/vestmark-gradle
77078ad580b546410d52e9df34f96d1d57dc51ff
[ "Apache-2.0" ]
32
2016-01-05T21:58:24.000Z
2021-06-21T21:56:34.000Z
#include "operators.h" int minus(int a, int b) { return a - b; }
11.666667
25
0.585714
Vestmark
bf02c58e8b0c6d0e8834ed1bb3a49aa6a7c0ec73
5,145
cpp
C++
util/UF-3.2/DTM/ufDataCharacteristics.cpp
mattjr/benthicQT
bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8
[ "Apache-2.0" ]
9
2016-06-07T09:38:03.000Z
2021-11-25T17:30:59.000Z
util/UF-3.2/DTM/ufDataCharacteristics.cpp
mattjr/benthicQT
bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8
[ "Apache-2.0" ]
null
null
null
util/UF-3.2/DTM/ufDataCharacteristics.cpp
mattjr/benthicQT
bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8
[ "Apache-2.0" ]
4
2016-06-16T16:55:33.000Z
2019-04-29T02:34:46.000Z
// // C++ Implementation: DataCharacteristics // // Description: // // // Author: Andrew J. P. Maclean <a.maclean@cas.edu.au>, (C) 2005 // // Copyright: See COPYING file that comes with this distribution // // #include "ufDataCharacteristics.h" #include <iostream> #include <stdexcept> #include <string> #include <fstream> #include <iomanip> #include <vtkPolyData.h> #include <vtkImageData.h> namespace { /** * Print the scalars. * @param DataPtr Pointer to the array of scalars. * @param dims[] The dimensions of the array of scalars. */ template < typename T > void PrintScalars ( T * DataPtr, int dims[] ) { T *ptr = (T *) DataPtr; for ( int i = 0; i < dims[0]; ++i ) { cout << "Row :" << i << ": "; for ( int j = 0; j < dims[1]; ++j ) { for ( int k = 0; k < dims[2]; ++k ) { cout << *ptr++ << " "; } } cout << endl; } } /** * Print the scalars. * @param DataPtr Pointer to the array of scalars. * @param dims[] The dimensions of the array of scalars. */ template < > void PrintScalars <char>( char * DataPtr, int dims[] ) { char *ptr = (char *) DataPtr; for ( int i = 0; i < dims[0]; ++i ) { cout << "Row :" << i << ": "; for ( int j = 0; j < dims[1]; ++j ) { for ( int k = 0; k < dims[2]; ++k ) { cout << (int)*ptr++ << " "; } } cout << endl; } } /** * Print the scalars. * @param DataPtr Pointer to the array of scalars. * @param dims[] The dimensions of the array of scalars. */ template < > void PrintScalars <unsigned char>( unsigned char * DataPtr, int dims[] ) { unsigned char *ptr = (unsigned char *) DataPtr; for ( int i = 0; i < dims[0]; ++i ) { cout << "Row :" << i << ": "; for ( int j = 0; j < dims[1]; ++j ) { for ( int k = 0; k < dims[2]; ++k ) { cout << (int)*ptr++ << " "; } } cout << endl; } } } using namespace UF::DTM; DataCharacteristics::DataCharacteristics() { } DataCharacteristics::~DataCharacteristics() { } void DataCharacteristics::PrintPolyDataCharacteristics( vtkPolyData * PolyData ) { std::ios::fmtflags flags = cout.setf(std::ios::fmtflags()); cout << vtkstd::fixed << setprecision(2); cout << "Number of: " << endl; cout << " Points: " << PolyData->GetNumberOfPoints() << endl; cout << " Vertices: " << PolyData->GetNumberOfVerts() << endl; cout << " Cells: " << PolyData->GetNumberOfCells() << endl; cout << " Lines: " << PolyData->GetNumberOfLines() << endl; cout << " Polys: " << PolyData->GetNumberOfPolys() << endl; cout << " Strips: " << PolyData->GetNumberOfStrips() << endl; cout << " Pieces: " << PolyData->GetNumberOfPieces() << endl; double bounds[6]; PolyData->GetBounds(bounds); cout << " Bounds: "; for ( int i = 0; i < 6; ++i ) { cout << bounds[i] << " "; } cout << std::endl; double scalarRange[2]; PolyData->GetScalarRange(scalarRange); cout << " Scalar Range: "; for ( int i = 0; i < 2; ++i) { cout << scalarRange[i] << " "; } cout << setprecision(6) << endl; std::ios::fmtflags newflags = cout.setf(std::ios::fmtflags()); cout.setf(flags,newflags); } void DataCharacteristics::PolyDataCharacteristics( vtkPolyData * PolyData, int components[], double bounds[], double scalarRange[] ) { components[0] = PolyData->GetNumberOfPoints(); components[1] = PolyData->GetNumberOfVerts(); components[2] = PolyData->GetNumberOfCells(); components[3] = PolyData->GetNumberOfLines(); components[4] = PolyData->GetNumberOfPolys(); components[5] = PolyData->GetNumberOfStrips(); components[6] = PolyData->GetNumberOfPieces(); PolyData->GetBounds(bounds); PolyData->GetScalarRange(scalarRange); } void DataCharacteristics::PrintImageDataCharacteristics( vtkImageData * ImageData ) { int dims[3]; ImageData->GetDimensions(dims); std::ios::fmtflags flags = cout.setf(std::ios::fmtflags()); cout << vtkstd::fixed << setprecision(2); cout << " Dimensions "; for ( int i = 0; i < 3; ++i ) cout << dims[i] << " "; cout << endl; double orig[3]; ImageData->GetOrigin(orig); cout << " Origin "; for ( int i = 0; i < 3; ++i ) cout << orig[i] << " "; cout << endl; double spac[3]; ImageData->GetSpacing(spac); cout << " Spacing "; for ( int i = 0; i < 3; ++i ) cout << spac[i] << " "; cout << endl; vtkIdType inc[3]; ImageData->GetIncrements(inc); cout << " Increments "; for ( int i = 0; i < 3; ++i ) cout << inc[i] << " "; cout << endl; cout << setprecision(6) << endl; std::ios::fmtflags newflags = cout.setf(std::ios::fmtflags()); cout.setf(flags,newflags); } void DataCharacteristics::PrintImageDataScalars ( vtkImageData * ImageData ) { int dims[3]; ImageData->GetDimensions(dims); switch(ImageData->GetScalarType()) { vtkTemplateMacro(PrintScalars(static_cast<VTK_TT*>(ImageData->GetScalarPointer()),dims)); } }
26.25
92
0.566569
mattjr
bf058fcac6e12ef075732a6a8ae062e58600d10a
813
cpp
C++
Graphs/Floyd Warshall Algo.cpp
ans-coder-human/Java
f82a380d4f02a084f1ddf4b03d7317254dca39b8
[ "MIT" ]
null
null
null
Graphs/Floyd Warshall Algo.cpp
ans-coder-human/Java
f82a380d4f02a084f1ddf4b03d7317254dca39b8
[ "MIT" ]
10
2021-10-04T08:04:42.000Z
2021-10-13T08:27:56.000Z
Graphs/Floyd Warshall Algo.cpp
ans-coder-human/Java
f82a380d4f02a084f1ddf4b03d7317254dca39b8
[ "MIT" ]
5
2020-10-14T10:38:08.000Z
2021-10-30T11:08:40.000Z
void shortest_distance(vector<vector<int>>&matrix){ int n = matrix.size(); for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { if(matrix[i][j]==-1) matrix[i][j]=INT_MAX/2; } } for(int k=0;k<n;k++) { for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { matrix[i][j]=min(matrix[i][j],matrix[i][k]+matrix[k][j]); } } } for(int i =0;i<n;i++) { for(int j=0;j<n;j++) { if(matrix[i][j]==INT_MAX/2) matrix[i][j]=-1; } } } //to detect negative cycle for(int i=0;i<n;i++){ if(matrix[i][i]<0){ cout<<"\n Its a negative weight cycle"; }
20.846154
72
0.360394
ans-coder-human
bf06fc52956ac06fe47bcb450d8fbd43c9604118
1,098
cpp
C++
kernel/src/synch/spinlock.cpp
egranata/puppy
dc8b9bd7620966d94b18cbfaf50c9c5e142b9f6c
[ "Apache-2.0" ]
28
2018-06-01T07:01:55.000Z
2022-01-09T23:30:14.000Z
kernel/src/synch/spinlock.cpp
egranata/puppy
dc8b9bd7620966d94b18cbfaf50c9c5e142b9f6c
[ "Apache-2.0" ]
175
2018-05-30T03:06:15.000Z
2019-02-06T23:54:24.000Z
kernel/src/synch/spinlock.cpp
egranata/puppy
dc8b9bd7620966d94b18cbfaf50c9c5e142b9f6c
[ "Apache-2.0" ]
2
2019-07-16T02:57:27.000Z
2021-06-25T17:01:13.000Z
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <kernel/synch/spinlock.h> spinlock::spinlock() : mLock(0) {} spinlock::unlock_t spinlock::lock() { while(!tryLock()) { __asm__ volatile ("pause\n"); } __sync_synchronize(); return unlock_t(*this); } bool spinlock::tryLock() { return __sync_bool_compare_and_swap(&mLock, 0, 1); } void spinlock::unlock() { __sync_synchronize(); mLock = 0; } spinlock::unlock_t::unlock_t(spinlock& lock) : mLock(lock) {} spinlock::unlock_t::~unlock_t() { mLock.unlock(); }
26.780488
75
0.697632
egranata
bf0709420a565f5212755dec90126cf26c00b536
17,928
cpp
C++
sourceCode/application/logic/model/core/InputFilesCheckerForComputation.cpp
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
2
2022-02-27T20:08:04.000Z
2022-03-03T13:45:40.000Z
sourceCode/application/logic/model/core/InputFilesCheckerForComputation.cpp
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
1
2021-06-07T17:09:04.000Z
2021-06-11T11:48:23.000Z
sourceCode/application/logic/model/core/InputFilesCheckerForComputation.cpp
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
1
2021-06-03T21:06:55.000Z
2021-06-03T21:06:55.000Z
#include <OpenImageIO/imageio.h> using namespace OIIO; #include <QDebug> #include "InputFilesCheckerForComputation.h" #include "../../io/InputImageFormatChecker.h" #include "../../toolbox/toolbox_pathAndFile.h" InputFilesForComputationMatchWithRequierement::InputFilesForComputationMatchWithRequierement( const S_InputFiles& inputFiles, e_mainComputationMode e_mainComputationMode, U_CorrelationScoreMapFileUseFlags correlationScoreUsageFlags): _inputFiles(inputFiles), _e_mainComputationMode(e_mainComputationMode), _correlationScoreUsageFlags(correlationScoreUsageFlags), _qvect_eSFC_PX1_PX2_DeltaZ{e_sFC_notSet, e_sFC_notSet, e_sFC_notSet}, _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ {e_sFC_notSet, e_sFC_notSet, e_sFC_notSet} { qDebug() << __FUNCTION__<< "inputFiles:"; qDebug() << __FUNCTION__<< inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__<< inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__<< "_inputFiles:"; qDebug() << __FUNCTION__<< _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__<< _inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ; } bool InputFilesForComputationMatchWithRequierement::getLayerToUseForComputationFlag(e_LayersAcces eLA) { qDebug() << __FUNCTION__<< "_eSFC_PX1_PX2_DeltaZ[" << eLA << "] =" << _qvect_eSFC_PX1_PX2_DeltaZ[eLA]; return(_qvect_eSFC_PX1_PX2_DeltaZ[eLA] == e_sFC_OK); } int InputFilesForComputationMatchWithRequierement::getQVectorLayersForComputationFlag(QVector<bool> &qvectb_LayersForComputationFlag) { qvectb_LayersForComputationFlag.clear(); qvectb_LayersForComputationFlag.fill(false, eLA_LayersCount); int count_sFC_OK = 0; for (int iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { if (_qvect_eSFC_PX1_PX2_DeltaZ[iela] == e_sFC_OK) { qvectb_LayersForComputationFlag[iela] = true; count_sFC_OK++; } } return(count_sFC_OK); } int InputFilesForComputationMatchWithRequierement::getQVectorCorrelationScoreMapFilesAvailabilityFlag(QVector<bool> &qvectb_correlationScoreMapFilesAvailability) { qvectb_correlationScoreMapFilesAvailability.clear(); qvectb_correlationScoreMapFilesAvailability.fill(false, eLA_LayersCount); //e_mCM_Typical_PX1PX2Together_DeltazAlone: optionnal but together: (PX1, PX2), optionnal and alone: DeltaZ if (_e_mainComputationMode != e_mCM_Typical_PX1PX2Together_DeltazAlone) { //strMsgErrorDetails = "Dev error 901# mainComputationMode not supported"; return(false); } int count_OK = 0; qvectb_correlationScoreMapFilesAvailability[eLA_CorrelScoreForPX1PX2Together] = (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] == e_sFC_OK); qvectb_correlationScoreMapFilesAvailability[eLA_CorrelScoreForDeltaZAlone] = (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] == e_sFC_OK); return(qvectb_correlationScoreMapFilesAvailability.count(true)); } //routeset file check for importation is not considered in this method bool InputFilesForComputationMatchWithRequierement::check_PX1PX2Together_DeltazAlone(QString& strMsgErrorDetails) { strMsgErrorDetails.clear(); QString _tqstrDescName_image[3] {"PX1", "PX2", "DeltaZ or Other"}; QString _tqstrDescName_correlScoreMap[3] {"(PX1,PX2)", "(PX1,PX2)", "DeltaZ or Other"}; _qvect_eSFC_PX1_PX2_DeltaZ = {e_sFC_notSet, e_sFC_notSet, e_sFC_notSet}; _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = {e_sFC_notSet, e_sFC_notSet, e_sFC_notSet}; //input files (PX1, PX2, deltaZ): //e_mCM_Typical_PX1PX2Together_DeltazAlone: optionnal but together: (PX1, PX2), optionnal and alone: DeltaZ if (_e_mainComputationMode != e_mCM_Typical_PX1PX2Together_DeltazAlone) { strMsgErrorDetails = "Dev error #9 mainComputationMode not supported"; return(false); } qDebug() << __FUNCTION__ << __LINE__ << "_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ = " << _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ; //test if (PX1, PX2) needs to be computed bool bPX1PX2_empty = false; e_statusFileCheck esFC_PX1PX2 = e_sFC_notSet; bool bPX1_empty = _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX1].isEmpty(); bool bPX2_empty = _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX2].isEmpty(); if (bPX1_empty && bPX2_empty) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX1] = e_sFC_notRequiered; _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX2] = e_sFC_notRequiered; esFC_PX1PX2 = e_sFC_notRequiered; bPX1PX2_empty = true; } else { if (bPX1_empty) { strMsgErrorDetails = "Missing mandatory input file for " + _tqstrDescName_image[eLA_PX1];//'Missing mandatory non independent input file' qDebug() << __FUNCTION__<< strMsgErrorDetails; return(false); } if (bPX2_empty) { strMsgErrorDetails = "Missing mandatory input file for " + _tqstrDescName_image[eLA_PX2]; //'Missing mandatory non independent input file' qDebug() << __FUNCTION__<< strMsgErrorDetails; return(false); } _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX1] = e_sFC_checkInProgress; _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX2] = e_sFC_checkInProgress; esFC_PX1PX2 = e_sFC_checkInProgress; } //test if deltaZOther needs to be computed bool bdeltaZ_empty = _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_deltaZ].isEmpty(); if (bdeltaZ_empty) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] = e_sFC_notRequiered; } else { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] = e_sFC_checkInProgress; } if (bPX1PX2_empty && bdeltaZ_empty) { strMsgErrorDetails = "None input image file"; return(false); } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that input correlation score files are set if usage at true //PX1PX2 if (!_correlationScoreUsageFlags._sCSF_PX1PX2Together_DeltazAlone._b_onPX1PX2) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = e_sFC_notRequiered; } else { bool bNoError = !_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together].isEmpty(); if (!bNoError) { strMsgErrorDetails = "Missing correlation score map input file for Px1,Px2"; return(false); } _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = e_sFC_checkInProgress; } //DeltaZ if (!_correlationScoreUsageFlags._sCSF_PX1PX2Together_DeltazAlone._b_onDeltaZ) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = e_sFC_notRequiered; } else { bool bNoError = !_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone].isEmpty(); if (!bNoError) { strMsgErrorDetails = "Missing correlation score map input file for deltaZ"; return(false); } _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = e_sFC_checkInProgress; } if (esFC_PX1PX2 == e_sFC_checkInProgress) { //check that input files PX1 and PX2 are different when e_mCM_Typical_PX1PX2Together_DeltazAlone if (!_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX1].compare( _inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[eLA_PX2], Qt::CaseInsensitive)) { strMsgErrorDetails = "Input files for Px1 and Px2 have to be different"; //'Mandatory non independant input files have to be different' return(false); } } //check that files exists: PX1, PX2, DeltaZ for (uint iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { if (_qvect_eSFC_PX1_PX2_DeltaZ[iela] == e_sFC_checkInProgress) { if (!fileExists(_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[iela])) { _qvect_eSFC_PX1_PX2_DeltaZ[iela] = e_sFC_NotOK; strMsgErrorDetails = "Input file does not exist for " + _tqstrDescName_image[iela]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; QVector<uint> qvect_iela_forCorrelScoreMap = {eLA_CorrelScoreForPX1PX2Together, eLA_CorrelScoreForDeltaZAlone }; //check that files exists: correlation score map for (PX1,PX2) for (auto iter_iela_forCorScoMap : qvect_iela_forCorrelScoreMap) { if (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] == e_sFC_checkInProgress) { if (!fileExists(_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[iter_iela_forCorScoMap])) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; strMsgErrorDetails = "(correlation score map) input file does not exist for " + _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that PX1 and PX2 files format are valid for DisplacementMap file //added deltaZ here InputImageFormatChecker IIFC; ImageSpec imgSpec_PX1_PX2_deltaZ[eLA_LayersCount]; for (uint iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { if (_qvect_eSFC_PX1_PX2_DeltaZ[iela] == e_sFC_checkInProgress) { bool bNoError = true; bNoError &= IIFC.getImageSpec(_inputFiles._qvectStr_inputFile_PX1_PX2_DeltaZ[iela].toStdString(), imgSpec_PX1_PX2_deltaZ[iela]); if (!bNoError) { strMsgErrorDetails = "(displacement map) failed to getImageSpec for file " + _tqstrDescName_image[iela]; _qvect_eSFC_PX1_PX2_DeltaZ[iela]=e_sFC_NotOK; return(false); } if (!IIFC.formatIsAnAcceptedFormatForDisplacementMap(imgSpec_PX1_PX2_deltaZ[iela])) { _qvect_eSFC_PX1_PX2_DeltaZ[iela]=e_sFC_NotOK; strMsgErrorDetails = "(displacement map) file format not supported for file " + _tqstrDescName_image[iela]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; if (esFC_PX1PX2 == e_sFC_checkInProgress) { //check that PX1 and PX2 have the same size and typeDescBaseType if (!IIFC.checkSameWidthHeightBaseType(imgSpec_PX1_PX2_deltaZ[eLA_PX1],imgSpec_PX1_PX2_deltaZ[eLA_PX2], true)) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX1]=e_sFC_NotOK; _qvect_eSFC_PX1_PX2_DeltaZ[eLA_PX2]=e_sFC_NotOK; strMsgErrorDetails = _tqstrDescName_image[eLA_PX1] + " and " + _tqstrDescName_image[eLA_PX2] + " don't have the same width, height or basetype"; return(false); } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that correlation score map for (PX1,PX2) deltaZalone are valid for correlation score map ImageSpec imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[eLA_LayersCount]; for (auto iter_iela_forCorScoMap : qvect_iela_forCorrelScoreMap) { if (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] == e_sFC_checkInProgress) { bool bNoError = true; bNoError &= IIFC.getImageSpec(_inputFiles._qvectStr_correlationScore_PX1_PX2_DeltaZ[iter_iela_forCorScoMap].toStdString(), imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[iter_iela_forCorScoMap]); if (!bNoError) { strMsgErrorDetails = "(correlation score map) failed to getImageSpec for file " + _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap]; _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; return(false); } if (!IIFC.formatIsAnAcceptedFormatForCorrelationScoreMap(imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[iter_iela_forCorScoMap])) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; strMsgErrorDetails = "(correlation score map) file format not supported for file " + _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap]; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //check that all the input file have the same width and height // //. PX1 and PX2 together already check above about w/h/basetype //. check that deltaZ have same w/h than PX1 // do not check about basetype, it's ok to be different if ( (esFC_PX1PX2 == e_sFC_checkInProgress) &&(_qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] == e_sFC_checkInProgress)) { if (!IIFC.checkSameWidthHeightBaseType( imgSpec_PX1_PX2_deltaZ[eLA_deltaZ], imgSpec_PX1_PX2_deltaZ[eLA_PX1], false)) { _qvect_eSFC_PX1_PX2_DeltaZ[eLA_deltaZ] = e_sFC_NotOK; strMsgErrorDetails = _tqstrDescName_image[eLA_deltaZ] + " don't have the same width or height than " + _tqstrDescName_image[eLA_PX1] + " and " + _tqstrDescName_image[eLA_PX2]; return(false); } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; //the file to use for comparison needs to be adjusted, depending of what is provided as input files e_LayersAcces ela_forWHComparison = eLA_PX1; if (esFC_PX1PX2 == e_sFC_notRequiered) { ela_forWHComparison = eLA_deltaZ; } //check now about correlation score map for (auto iter_iela_forCorScoMap : qvect_iela_forCorrelScoreMap) { if (_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] == e_sFC_checkInProgress) { if (!IIFC.checkSameWidthHeightBaseType(imgSpec_CorScoMap_PX1PX2_PX1PX2_deltaZ[iter_iela_forCorScoMap], imgSpec_PX1_PX2_deltaZ[ela_forWHComparison], false)) { _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[iter_iela_forCorScoMap] = e_sFC_NotOK; strMsgErrorDetails = _tqstrDescName_correlScoreMap[iter_iela_forCorScoMap] + "don't have the same width or height than the other"; return(false); } } } qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << __LINE__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; for (uint iela = eLA_PX1; iela <= eLA_deltaZ; iela++) { _qvect_eSFC_PX1_PX2_DeltaZ[iela] = convertInProgressToFinalValue(_qvect_eSFC_PX1_PX2_DeltaZ[iela]); } qDebug() << __FUNCTION__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together]; qDebug() << __FUNCTION__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone]; _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] = convertInProgressToFinalValue( _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForPX1PX2Together] ); _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone] = convertInProgressToFinalValue( _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ[eLA_CorrelScoreForDeltaZAlone]); qDebug() << __FUNCTION__ << "_qvect_eSFC_PX1_PX2_DeltaZ = " << _qvect_eSFC_PX1_PX2_DeltaZ; qDebug() << __FUNCTION__ << "_qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ = " << _qvect_eSFC_correlScoreFilesFor_PX1_PX2_DeltaZ; return(true); } InputFilesForComputationMatchWithRequierement::e_statusFileCheck InputFilesForComputationMatchWithRequierement::convertInProgressToFinalValue(e_statusFileCheck esFC) { if (esFC == e_sFC_checkInProgress) { return(e_sFC_OK); } else { return(esFC); } }
50.644068
167
0.71564
lp-rep
bf0d3e10e5cb760e4c8222263f045e241fa4a11c
493
cpp
C++
src/UserInterface/uiTitle.cpp
KURUJISU/Top_P
d218656e13cbe05b01926366e114b34b8d430035
[ "MIT" ]
null
null
null
src/UserInterface/uiTitle.cpp
KURUJISU/Top_P
d218656e13cbe05b01926366e114b34b8d430035
[ "MIT" ]
null
null
null
src/UserInterface/uiTitle.cpp
KURUJISU/Top_P
d218656e13cbe05b01926366e114b34b8d430035
[ "MIT" ]
null
null
null
#include "precompiled.h" uiTitle::uiTitle() {} void uiTitle::setup(){ shared_ptr<uiInformation> uiInfo = make_shared<uiInformation>(); uiInfo->setPos(ofVec2f(0, g_local->HalfHeight())); AddUI(uiInfo); wp_uiInfo_ = uiInfo; shared_ptr<uiScoreRank> uiScore = make_shared<uiScoreRank>(); uiScore->disableDrawCurrentScore(); uiScore->setPos(ofVec2f(0, g_local->HalfHeight())); AddUI(uiScore); wp_uiScore_ = uiScore; } void uiTitle::update(float deltaTime){} void uiTitle::draw(){ }
20.541667
65
0.730223
KURUJISU
bf0f7c93ae7f1cece7cf59cbdea79bb10f563f13
345
hpp
C++
Source/Runtime/Engine/Public/Components/SkyLightComponent.hpp
Othereum/NoEngineGame
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
[ "MIT" ]
23
2020-05-21T06:25:29.000Z
2021-04-06T03:37:28.000Z
Source/Runtime/Engine/Public/Components/SkyLightComponent.hpp
Othereum/NoEngineGame
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
[ "MIT" ]
72
2020-06-09T04:46:27.000Z
2020-12-07T03:20:51.000Z
Source/Runtime/Engine/Public/Components/SkyLightComponent.hpp
Othereum/NoEngineGame
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
[ "MIT" ]
4
2020-06-10T02:23:54.000Z
2022-03-28T07:22:08.000Z
#pragma once #include "SceneComponent.hpp" namespace oeng { inline namespace engine { class ENGINE_API SkyLightComponent : public SceneComponent { CLASS_BODY(SkyLightComponent) public: Vec3 color{All{}, 0.2}; protected: void OnBeginPlay() override; void OnEndPlay() override; }; } // namespace engine } // namespace oeng
15.681818
58
0.718841
Othereum
bf10d1e469dde07c463b53135f98489f29947b1f
6,241
cpp
C++
srcs/molenet/mysqldataprovider.cpp
FLynnGame/moleserver
d79e84f4afc4017c983deb4d6bfe0f5851eccedd
[ "Apache-2.0" ]
37
2020-05-15T08:29:39.000Z
2022-03-21T05:18:35.000Z
srcs/molenet/mysqldataprovider.cpp
FLynnGame/moleserver
d79e84f4afc4017c983deb4d6bfe0f5851eccedd
[ "Apache-2.0" ]
null
null
null
srcs/molenet/mysqldataprovider.cpp
FLynnGame/moleserver
d79e84f4afc4017c983deb4d6bfe0f5851eccedd
[ "Apache-2.0" ]
23
2020-07-06T08:55:07.000Z
2022-03-31T06:38:31.000Z
#include "../../include/molnet/mysqldataprovider.h" #include "../../include/molnet/common.h" #include "../../include/molnet/dalexcept.h" /** * 构造函数 */ MySqlDataProvider::MySqlDataProvider(void) throw() { } /** * 析构函数 */ MySqlDataProvider::~MySqlDataProvider(void) throw() { if(mIsConnected) disconnect(); } /** * 得到数据库的类型 * * @return 用于返回当前数据库的类型 */ DbBackends MySqlDataProvider::getDbBackend(void) const throw() { return DB_BKEND_MYSQL; } /** * 建立与数据库的连接 * * @param host 要连接的数据库的IP地址 * @param username 要连接数据库的用户名 * @param password 要连接数据库的用户密码 * @param dbName 要连接的数据库名称 * @param port 要连接的数据库的端口号 */ bool MySqlDataProvider::connect(std::string host,std::string username,std::string password, std::string dbName,unsigned int port) { if(mIsConnected) return false; if(!m_ConnectPool.Init(MOL_CONN_POOL_MAX, host.c_str(), username.c_str(), password.c_str(), dbName.c_str(), port)) return false; mysql_thread_init(); mDbName = dbName; mIsConnected = true; return true; } /** * 执行SQL语句 * * @param sql 要执行的SQL语句 * @param refresh 是否要刷新数据,也就是重新从数据库中获取数据 * * @return 如果成功获取到数据返回这个数据记录,否则抛出异常 */ const RecordSetList MySqlDataProvider::execSql(const std::string& sql,const bool refresh) { if(!mIsConnected) throw std::runtime_error("没有与数据库建立连接。"); RecordSetList pRecordSetList; try { if(refresh || (sql != mSql)) { MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return pRecordSetList; if(mysql_query(m_curWorkingConn,sql.c_str()) != 0) { m_ConnectPool.PutConnet(m_curWorkingConn); throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)+sql); } do { int fieldCount = mysql_field_count(m_curWorkingConn); if(fieldCount > 0) { RecordSet pRecordSet; MYSQL_RES* res = NULL; if(!(res = mysql_store_result(m_curWorkingConn))) { m_ConnectPool.PutConnet(m_curWorkingConn); throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); } unsigned int nFields = mysql_num_fields(res); //MYSQL_FIELD* fields = mysql_fetch_fields(res); Row fieldNames; for(unsigned int i=0;i<nFields;i++) { MYSQL_FIELD* fields = NULL; fields=mysql_fetch_field_direct(res,i); if(fields) fieldNames.push_back(fields->name ? fields->name : ""); } pRecordSet.setColumnHeaders(fieldNames); MYSQL_ROW row; while((row = mysql_fetch_row(res))) { Row r; for(unsigned int i = 0;i < nFields; i++) { char *tmpStr = static_cast<char*>(row[i]); r.push_back(tmpStr ? tmpStr : ""); } pRecordSet.add(r); } if(!pRecordSet.isEmpty()) pRecordSetList.add(pRecordSet); mysql_free_result(res); } } while (!mysql_next_result( m_curWorkingConn )); m_ConnectPool.PutConnet(m_curWorkingConn); } } catch(std::exception e) { LOG_ERROR(e.what()); } return pRecordSetList; } /** * 关闭与数据库的连接 */ void MySqlDataProvider::disconnect(void) { if(!mIsConnected) return; m_ConnectPool.Close(); mysql_thread_end(); mysql_library_end(); mIsConnected = false; } /** * 开始一项事物 */ void MySqlDataProvider::beginTransaction(void) throw (std::runtime_error) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下开始一项事务!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return; mysql_autocommit(m_curWorkingConn,AUTOCOMMIT_OFF); execSql("BEGIN"); m_ConnectPool.PutConnet(m_curWorkingConn); } /** * 提交一项事物 */ void MySqlDataProvider::commitTransaction(void) throw (std::runtime_error) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下提交一项事务!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return; if(mysql_commit(m_curWorkingConn) != 0) throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); mysql_autocommit(m_curWorkingConn,AUTOCOMMIT_ON); m_ConnectPool.PutConnet(m_curWorkingConn); } /** * 回滚一项事物 */ void MySqlDataProvider::rollbackTransaction(void) throw (std::runtime_error) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下回滚一项事务!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return; if(mysql_rollback(m_curWorkingConn) != 0) throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); mysql_autocommit(m_curWorkingConn,AUTOCOMMIT_ON); m_ConnectPool.PutConnet(m_curWorkingConn); } /** * 得到最近执行SQL语句后改变的行的个数 * * @return 返回最近改变的行数 */ unsigned int MySqlDataProvider::getModifiedRows(void) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下试图执行getModifiedRows!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return 0; const my_ulonglong affected = mysql_affected_rows(m_curWorkingConn); if(affected > INT_MAX) throw std::runtime_error("MySqlDataProvider: getModifiedRows 超出范围."); if(affected == (my_ulonglong)-1) { throw DbSqlQueryExecFailure(mysql_error(m_curWorkingConn)); } m_ConnectPool.PutConnet(m_curWorkingConn); return (unsigned int)affected; } /** * 得到最近插入的数据的行号 * * @return 返回改变数据的最新的行号 */ unsigned int MySqlDataProvider::getLastId(void) { if(!mIsConnected) { const std::string error = "在没有连接数据库的情况下试图执行getLastId!"; throw std::runtime_error(error); } MYSQL *m_curWorkingConn = m_ConnectPool.GetConnet(); if(m_curWorkingConn == NULL) return 0; const my_ulonglong lastId = mysql_insert_id(m_curWorkingConn); if(lastId > UINT_MAX) throw std::runtime_error("MySqlDataProvider: getLastId 超出范围."); m_ConnectPool.PutConnet(m_curWorkingConn); return (unsigned int)lastId; } /// 用于维护数据库连接 void MySqlDataProvider::Update(void) { m_ConnectPool.Update(); }
20.59736
92
0.670405
FLynnGame
bf12d6bfad3f44587af409e992843ca0556392f0
549
cpp
C++
Codes/jxdeng3264/1001-1100/1013.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/tango.cpp
liuxiaohui1221/algorithm
d80e64185ceb4798ac5389bfbd226dc1d406f6b5
[ "Apache-2.0" ]
256
2017-10-25T13:02:15.000Z
2022-02-25T13:47:59.000Z
Codes/jxdeng3264/1001-1100/1013.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/tango.cpp
liuxiaohui1221/algorithm
d80e64185ceb4798ac5389bfbd226dc1d406f6b5
[ "Apache-2.0" ]
56
2017-10-27T01:34:20.000Z
2022-03-01T00:20:55.000Z
Codes/jxdeng3264/1001-1100/1013.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/tango.cpp
liuxiaohui1221/algorithm
d80e64185ceb4798ac5389bfbd226dc1d406f6b5
[ "Apache-2.0" ]
83
2017-10-25T12:51:53.000Z
2022-02-15T08:27:03.000Z
class Solution { public: int numPairsDivisibleBy60(vector<int>& time) { map<int, int> m; for (int i = 0; i<time.size(); ++i) { m[time[i]%60]++; time[i] %= 60; } int cnt = 0; for (int i = 0 ; i <=30; ++i) { if (m.find(i) != m.end()) { int n1 = m[i]; int ii = (60-i)%60;// n1= 0 , n2=0; if (m.find(ii) != m.end()) { int n2 = m[ii]; cout<<n1<<" "<<n2<<endl; if (i != 0 && i != 30) { cnt += n1*n2; } else cnt += (n1)*(n1-1)/2; } } } return cnt; } };
15.25
47
0.404372
liuxiaohui1221
bf15d382e043c444c2e0254fb449fa91241b0f00
2,131
hpp
C++
NetworkLib/src/Float.hpp
Bousk/Net
bb77d61f870a28752fdf7509c111d446819aff31
[ "MIT" ]
2
2021-12-29T16:29:13.000Z
2022-03-27T15:48:20.000Z
NetworkLib/src/Float.hpp
Bousk/Net
bb77d61f870a28752fdf7509c111d446819aff31
[ "MIT" ]
null
null
null
NetworkLib/src/Float.hpp
Bousk/Net
bb77d61f870a28752fdf7509c111d446819aff31
[ "MIT" ]
1
2020-10-31T23:50:23.000Z
2020-10-31T23:50:23.000Z
#pragma once #include <RangedInteger.hpp> #include <Serialization/Serialization.hpp> #include <Serialization/Serializer.hpp> #include <Serialization/Deserializer.hpp> namespace Bousk { template<class FLOATTYPE, int32 MIN, int32 MAX, uint8 NBDECIMALS, uint8 STEP = 1 > class Float : public Serialization::Serializable { static_assert(std::is_same_v<FLOATTYPE, float32> || std::is_same_v<FLOATTYPE, float64>, "Float can only be used with float32 or float64"); static_assert(MIN < MAX, "Min & Max values must be strictly ordered"); static_assert(NBDECIMALS > 0, "At least 1 decimal"); static_assert(NBDECIMALS < 10, "Maximum 10 decimals"); static_assert(STEP != 0, "Step must not be 0"); static_assert(STEP % 10 != 0, "Step should not be a multiple of 10. Remove a decimal"); using FloatType = FLOATTYPE; static constexpr int32 Min = MIN; static constexpr int32 Max = MAX; static constexpr uint32 Diff = Max - Min; static constexpr uint8 NbDecimals = NBDECIMALS; static constexpr uint32 Multiple = Pow<10, NbDecimals>::Value; static constexpr uint8 Step = STEP; static constexpr uint32 Domain = (MAX - MIN) * Multiple / STEP; public: Float() = default; Float(FloatType value) { mQuantizedValue = Quantize(value); } static uint32 Quantize(FloatType value) { assert(value >= Min && value <= Max); return static_cast<uint32>(((value - Min) * Multiple) / Step); } inline FloatType get() const { return static_cast<FloatType>((mQuantizedValue.get() * Step * 1.) / Multiple + Min); } inline operator FloatType() const { return get(); } bool write(Serialization::Serializer& serializer) const override { return mQuantizedValue.write(serializer); } bool read(Serialization::Deserializer& deserializer) override { return mQuantizedValue.read(deserializer); } private: RangedInteger<0, Domain> mQuantizedValue; }; template<int32 MIN, int32 MAX, uint8 NBDECIMALS, uint8 STEP = 1> using Float32 = Float<float32, MIN, MAX, NBDECIMALS, STEP>; template<int32 MIN, int32 MAX, uint8 NBDECIMALS, uint8 STEP = 1> using Float64 = Float<float64, MIN, MAX, NBDECIMALS, STEP>; }
38.745455
140
0.727358
Bousk
bf19a050a9d17181e6ef289ba3c576590fae4e9e
4,062
cpp
C++
src/prod/src/ServiceModel/PagingStatus.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/PagingStatus.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/PagingStatus.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Federation; StringLiteral const TraceSource("PagingStatus"); PagingStatus::PagingStatus() : continuationToken_() { } PagingStatus::PagingStatus(wstring && continuationToken) : continuationToken_(move(continuationToken)) { } PagingStatus::PagingStatus(PagingStatus && other) : continuationToken_(move(other.continuationToken_)) { } PagingStatus & PagingStatus::operator =(PagingStatus && other) { if (this != &other) { continuationToken_ = move(other.continuationToken_); } return *this; } PagingStatus::~PagingStatus() { } void PagingStatus::ToPublicApi( __in ScopedHeap & heap, __out FABRIC_PAGING_STATUS & publicPagingStatus) const { publicPagingStatus.ContinuationToken = heap.AddString(continuationToken_); } ErrorCode PagingStatus::FromPublicApi(FABRIC_PAGING_STATUS const & publicPagingStatus) { auto hr = StringUtility::LpcwstrToWstring(publicPagingStatus.ContinuationToken, true, ParameterValidator::MinStringSize, ParameterValidator::MaxStringSize, continuationToken_); if (FAILED(hr)) { Trace.WriteInfo(TraceSource, "Error parsing continuation token in FromPublicAPI: {0}", hr); return ErrorCode::FromHResult(hr); } return ErrorCode::Success(); } // // Templated methods // // This will return an error if the continuation token is empty (same as other specializations of this template's base template) template <> ErrorCode PagingStatus::GetContinuationTokenData<wstring>( std::wstring const & continuationToken, __inout wstring & data) { if (continuationToken.empty()) { return ErrorCode( ErrorCodeValue::ArgumentNull, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } data = continuationToken; return ErrorCode::Success(); } template <> std::wstring PagingStatus::CreateContinuationToken<Uri>(Uri const & data) { return data.ToString(); } template <> std::wstring PagingStatus::CreateContinuationToken<NodeId>(NodeId const & nodeId) { return wformatString("{0}", nodeId); } template <> ErrorCode PagingStatus::GetContinuationTokenData<NodeId>( std::wstring const & continuationToken, __inout NodeId & nodeId) { if (!NodeId::TryParse(continuationToken, nodeId)) { return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } return ErrorCode::Success(); } template <> std::wstring PagingStatus::CreateContinuationToken<Guid>(Guid const & guid) { return wformatString("{0}", guid); } template <> ErrorCode PagingStatus::GetContinuationTokenData<Guid>( std::wstring const & continuationToken, __inout Guid & guid) { if (!Guid::TryParse(continuationToken, guid)) { return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } return ErrorCode::Success(); } template <> std::wstring PagingStatus::CreateContinuationToken<FABRIC_REPLICA_ID>(FABRIC_REPLICA_ID const & replicaId) { return wformatString("{0}", replicaId); } template <> ErrorCode PagingStatus::GetContinuationTokenData<FABRIC_REPLICA_ID>( std::wstring const & continuationToken, __inout FABRIC_REPLICA_ID & replicaId) { if (!StringUtility::TryFromWString<FABRIC_REPLICA_ID>(continuationToken, replicaId)) { return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString(GET_COMMON_RC(Invalid_Continuation_Token), continuationToken)); } return ErrorCode::Success(); }
28.405594
180
0.70384
vishnuk007
bf19ff78ce13c6a0a25b2beaeb8ceb8f82c6c866
10,008
cxx
C++
inetcore/urlmon/urltrack/util.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/urlmon/urltrack/util.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/urlmon/urltrack/util.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*-------------------------------------------------------*/ //Copyright (c) 1997 Microsoft Corporation // // Util.cpp // //Author: // // //Environment: // // User Mode - Win32 // //Revision History: /*-------------------------------------------------------*/ #include "urltrk.h" #include <inetreg.h> const CHAR c_szLogFormat[] = "hh':'mm':'ss"; const CHAR c_szMode[] = "U"; // unknown const CHAR c_szLogContainerA[] = "Log"; #define MY_CACHE_ENTRY_INFO_SIZE 512 #define MY_MAX_STRING_LEN 512 BOOL ConvertToPrefixedURL(LPCSTR lpszUrl, LPSTR *lplpPrefixedUrl); LPINTERNET_CACHE_ENTRY_INFOA QueryCacheEntry(LPCSTR lpUrl); HANDLE GetLogFile(LPCSTR lpUrl, LPINTERNET_CACHE_ENTRY_INFOA pce, LPSTR lpFile); LPSTR GetLogString(LPMY_LOGGING_INFO lpLogInfo); ULONG _IsLoggingEnabled(LPCSTR pszUrl) { LPINTERNET_CACHE_ENTRY_INFOA pce; LPSTR lpPfxUrl = NULL; ULONG dwTrack; // ConvertToPrefixedURL(pszUrl, &lpPfxUrl); if (!lpPfxUrl) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return 0; } pce = QueryCacheEntry(lpPfxUrl); if (!pce) { GlobalFree(lpPfxUrl); SetLastError(ERROR_FILE_NOT_FOUND); return 0; } dwTrack = pce->CacheEntryType; GlobalFree(pce); GlobalFree(lpPfxUrl); return dwTrack; } BOOL _WriteHitLogging(LPMY_LOGGING_INFO pmLi) { LPSTR lpLogString = NULL; LPSTR lpPfxUrl = NULL; LPINTERNET_CACHE_ENTRY_INFOA pce = NULL; HANDLE hFile; CHAR lpFile[MAX_PATH]; DWORD dwWritten = 0; BOOL fuseCache; BOOL bRet = FALSE; // ConvertToPrefixedURL(pmLi->pLogInfo->lpszLoggedUrlName, &lpPfxUrl); if (!lpPfxUrl) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return bRet; } pce = QueryCacheEntry(lpPfxUrl); if (!pce) { GlobalFree(lpPfxUrl); SetLastError(ERROR_FILE_NOT_FOUND); return bRet; } hFile = GetLogFile(lpPfxUrl, pce, &lpFile[0]); if (hFile == NULL) { GlobalFree(lpPfxUrl); GlobalFree(pce); SetLastError(ERROR_FILE_NOT_FOUND); return bRet; } pmLi->fuseCache = GetUrlCacheEntryInfoExA(pmLi->pLogInfo->lpszLoggedUrlName, NULL, NULL, NULL, NULL, NULL, 0); lpLogString = GetLogString(pmLi); if (!lpLogString) { GlobalFree(lpPfxUrl); GlobalFree(pce); CloseHandle(hFile); return bRet; } bRet = WriteFile(hFile, lpLogString, lstrlenA(lpLogString), &dwWritten, NULL); CloseHandle(hFile); GlobalFree(lpLogString); // commit change to cache if(bRet) { bRet = CommitUrlCacheEntry(lpPfxUrl, lpFile, // pce->ExpireTime, //ExpireTime pce->LastModifiedTime, //LastModifiedTime pce->CacheEntryType, NULL, //lpHeaderInfo 0, //dwHeaderSize NULL, //lpszFileExtension 0); //reserved } // free pce GlobalFree(pce); GlobalFree(lpPfxUrl); return bRet; } BOOL IsGlobalOffline(void) { DWORD dwState = 0, dwSize = sizeof(DWORD); BOOL fRet = FALSE; #ifdef _SBS_ HMODULE hModuleHandle = GetModuleHandleA("sbswinet.dll"); #else HMODULE hModuleHandle = GetModuleHandleA("wininet.dll"); #endif // _SBS_ if(!hModuleHandle) return FALSE; if(InternetQueryOptionA(NULL, INTERNET_OPTION_CONNECTED_STATE, &dwState, &dwSize)) { if(dwState & INTERNET_STATE_DISCONNECTED_BY_USER) fRet = TRUE; } return fRet; } // // Helper Functions // LPSTR GetLogString(LPMY_LOGGING_INFO pmLi) { FILETIME ftIn, ftOut; ULARGE_INTEGER ulIn, ulOut, ulTotal; SYSTEMTIME stIn, stOut; LPSTR lpData = NULL; CHAR pTimeIn[10], pTimeOut[10]; lpData = (LPSTR)GlobalAlloc(LPTR, lstrlenA(pmLi->pLogInfo->lpszExtendedInfo)+MY_MAX_STRING_LEN); if (!lpData) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return NULL; } // calculate delta of time SystemTimeToFileTime(&(pmLi->pLogInfo->StartTime), &ftIn); SystemTimeToFileTime(&(pmLi->pLogInfo->EndTime), &ftOut); ulIn.LowPart = ftIn.dwLowDateTime; ulIn.HighPart = ftIn.dwHighDateTime; ulOut.LowPart = ftOut.dwLowDateTime; ulOut.HighPart = ftOut.dwHighDateTime; #ifndef unix ulTotal.QuadPart = ulOut.QuadPart - ulIn.QuadPart; #else U_QUAD_PART(ulTotal) = U_QUAD_PART(ulOut) - U_QUAD_PART(ulIn); #endif /* unix */ ftOut.dwLowDateTime = ulTotal.LowPart; ftOut.dwHighDateTime = ulTotal.HighPart; FileTimeToSystemTime(&ftOut, &stOut); stIn = pmLi->pLogInfo->StartTime; // log string: timeEnter+Duration GetTimeFormat(LOCALE_SYSTEM_DEFAULT, TIME_FORCE24HOURFORMAT, &stIn, c_szLogFormat, pTimeIn, 10); GetTimeFormat(LOCALE_SYSTEM_DEFAULT, TIME_FORCE24HOURFORMAT, &stOut, c_szLogFormat, pTimeOut, 10); if (!pmLi->pLogInfo->lpszExtendedInfo) { wsprintf(lpData, "%s %d %.2d-%.2d-%d %s %s\r\n", c_szMode, pmLi->fuseCache, stIn.wMonth, stIn.wDay, stIn.wYear, pTimeIn, pTimeOut); } else { wsprintf(lpData, "%s %d %.2d-%.2d-%d %s %s %s\r\n", c_szMode, pmLi->fuseCache, stIn.wMonth, stIn.wDay, stIn.wYear, pTimeIn, pTimeOut, pmLi->pLogInfo->lpszExtendedInfo); } return lpData; } LPSTR ReadTrackingPrefix(void) { LPSTR lpPfx = NULL; DWORD cbPfx = 0; struct { INTERNET_CACHE_CONTAINER_INFOA cInfo; CHAR szBuffer[MAX_PATH+INTERNET_MAX_URL_LENGTH+1]; } ContainerInfo; DWORD dwModified, dwContainer; HANDLE hEnum; dwContainer = sizeof(ContainerInfo); hEnum = FindFirstUrlCacheContainerA(&dwModified, &ContainerInfo.cInfo, &dwContainer, 0); if (hEnum) { for (;;) { if (!lstrcmpiA(ContainerInfo.cInfo.lpszName, c_szLogContainerA)) { if (ContainerInfo.cInfo.lpszCachePrefix[0]) { DWORD cb = lstrlenA(ContainerInfo.cInfo.lpszCachePrefix)+sizeof(CHAR); lpPfx = (LPSTR)GlobalAlloc(LPTR, cb); if (!lpPfx) { SetLastError(ERROR_OUTOFMEMORY); break; } lstrcpynA(lpPfx, ContainerInfo.cInfo.lpszCachePrefix, cb); } break; } dwContainer = sizeof(ContainerInfo); if (!FindNextUrlCacheContainerA(hEnum, &ContainerInfo.cInfo, &dwContainer)) { if (GetLastError() == ERROR_NO_MORE_ITEMS) break; } } FindCloseUrlCache(hEnum); } return lpPfx; } // caller must free lplpPrefixedUrl BOOL ConvertToPrefixedURL(LPCSTR lpszUrl, LPSTR *lplpPrefixedUrl) { BOOL bret = FALSE; LPTSTR lpPfx = NULL; if (!lpszUrl) return bret; lpPfx = ReadTrackingPrefix(); if (lpPfx) { *lplpPrefixedUrl = (LPSTR)GlobalAlloc(LPTR, lstrlenA(lpszUrl)+lstrlenA(lpPfx)+1); if (*lplpPrefixedUrl) { wsprintf(*lplpPrefixedUrl, "%s%s", lpPfx, lpszUrl); bret = TRUE; } GlobalFree(lpPfx); } return bret; } LPINTERNET_CACHE_ENTRY_INFOA QueryCacheEntry(LPCSTR lpUrl) { // get cache entry info LPINTERNET_CACHE_ENTRY_INFOA lpCE = NULL; DWORD dwEntrySize; BOOL bret = FALSE; lpCE = (LPINTERNET_CACHE_ENTRY_INFOA)GlobalAlloc(LPTR, MY_CACHE_ENTRY_INFO_SIZE); if (lpCE) { dwEntrySize = MY_CACHE_ENTRY_INFO_SIZE; while (!(bret = GetUrlCacheEntryInfoA(lpUrl, lpCE, &dwEntrySize))) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { GlobalFree(lpCE); lpCE = (LPINTERNET_CACHE_ENTRY_INFOA)GlobalAlloc(LPTR, dwEntrySize); if (!lpCE) break; } else break; } } if (!bret && lpCE) { GlobalFree(lpCE); lpCE = NULL; SetLastError(ERROR_FILE_NOT_FOUND); } return lpCE; } HANDLE GetLogFile(LPCSTR lpUrl, LPINTERNET_CACHE_ENTRY_INFOA pce, LPSTR lpFile) { HANDLE hFile = NULL; // work around -- begin if (!CreateUrlCacheEntry(lpUrl, 512, "log", lpFile, 0)) return NULL; if (pce->lpszLocalFileName) { if (!CopyFile(pce->lpszLocalFileName, lpFile, FALSE)) return NULL; DeleteFile(pce->lpszLocalFileName); } // work around -- end hFile = CreateFile(lpFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, // | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) return NULL; // move file pointer to end if (0xFFFFFFFF == SetFilePointer(hFile, 0, 0, FILE_END)) { CloseHandle(hFile); hFile = NULL; } return hFile; }
26.688
115
0.543465
npocmaka
bf1de2f3df0da97ff919eab5836172f884161245
2,852
cpp
C++
MaterialLib/MPL/Properties/ThermalConductivity/CreateSoilThermalConductivitySomerton.cpp
garibay-j/ogs
33340f22e9dbe0b7ccc60f0c828c2a528737c81e
[ "BSD-3-Clause" ]
null
null
null
MaterialLib/MPL/Properties/ThermalConductivity/CreateSoilThermalConductivitySomerton.cpp
garibay-j/ogs
33340f22e9dbe0b7ccc60f0c828c2a528737c81e
[ "BSD-3-Clause" ]
null
null
null
MaterialLib/MPL/Properties/ThermalConductivity/CreateSoilThermalConductivitySomerton.cpp
garibay-j/ogs
33340f22e9dbe0b7ccc60f0c828c2a528737c81e
[ "BSD-3-Clause" ]
null
null
null
/** * \file * \copyright * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * * Created on February 17, 2021, 3:47 PM */ #include "CreateSoilThermalConductivitySomerton.h" #include <string> #include "BaseLib/ConfigTree.h" #include "MaterialLib/MPL/Property.h" #include "ParameterLib/CoordinateSystem.h" #include "ParameterLib/Parameter.h" #include "ParameterLib/Utils.h" #include "SoilThermalConductivitySomerton.h" namespace MaterialPropertyLib { std::unique_ptr<Property> createSoilThermalConductivitySomerton( int const geometry_dimension, BaseLib::ConfigTree const& config, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, ParameterLib::CoordinateSystem const* const local_coordinate_system) { //! \ogs_file_param{properties__property__type} config.checkConfigParameter("type", "SoilThermalConductivitySomerton"); //! \ogs_file_param{properties__property__name} auto property_name = config.peekConfigParameter<std::string>("name"); DBUG("Create SoilThermalConductivitySomerton medium property"); std::string const& dry_thermal_conductivity_parameter_name = //! \ogs_file_param{properties__property__SoilThermalConductivitySomerton__dry_thermal_conductivity} config.getConfigParameter<std::string>("dry_thermal_conductivity"); auto const& dry_thermal_conductivity = ParameterLib::findParameter<double>( dry_thermal_conductivity_parameter_name, parameters, 0, nullptr); std::string const& wet_thermal_conductivity_parameter_name = //! \ogs_file_param{properties__property__SoilThermalConductivitySomerton__wet_thermal_conductivity} config.getConfigParameter<std::string>("wet_thermal_conductivity"); auto const& wet_thermal_conductivity = ParameterLib::findParameter<double>( wet_thermal_conductivity_parameter_name, parameters, 0, nullptr); if (geometry_dimension == 1) { return std::make_unique<SoilThermalConductivitySomerton<1>>( std::move(property_name), dry_thermal_conductivity, wet_thermal_conductivity, local_coordinate_system); } if (geometry_dimension == 2) { return std::make_unique<SoilThermalConductivitySomerton<2>>( std::move(property_name), dry_thermal_conductivity, wet_thermal_conductivity, local_coordinate_system); } return std::make_unique<SoilThermalConductivitySomerton<3>>( std::move(property_name), dry_thermal_conductivity, wet_thermal_conductivity, local_coordinate_system); } } // namespace MaterialPropertyLib
37.526316
108
0.736676
garibay-j
bf1f059e5368aebbc9e23f9c3aea0a796b21d911
4,328
cpp
C++
Libraries/Resources/Hcsr501/Hcsr501.cpp
automacaoiot/ESP8266-SDK
ee8028a9dce00dab7dee13afdc3b7a7c51af6d03
[ "MIT" ]
null
null
null
Libraries/Resources/Hcsr501/Hcsr501.cpp
automacaoiot/ESP8266-SDK
ee8028a9dce00dab7dee13afdc3b7a7c51af6d03
[ "MIT" ]
null
null
null
Libraries/Resources/Hcsr501/Hcsr501.cpp
automacaoiot/ESP8266-SDK
ee8028a9dce00dab7dee13afdc3b7a7c51af6d03
[ "MIT" ]
null
null
null
/** *MIT License * * Copyright (c) 2017 Automa��o-IOT * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Hcsr501.h" #ifdef WIFI int Hcsr501::counterHcsr501 = 0; Hcsr501::Hcsr501(GpiosEnum gpio, unsigned long refreshHcsr501,String nameHCSR501) { resourceJson = "Hcsr501"+String(counterHcsr501++); resourcesJson[indexJson++] = resourceJson; counterJson = counterHcsr501; this->gpio = gpio; refresh = refreshHcsr501; name = nameHCSR501+String(counterHcsr501); resourceWifiMode = true; } #endif Hcsr501::Hcsr501(unsigned long id, GpiosEnum gpio, unsigned long refreshHcsr501,String nameHCSR501) { this->id = id; this->gpio = gpio; refresh = refreshHcsr501; name = nameHCSR501+id; resourceWifiMode = false; } void ICACHE_FLASH_ATTR Hcsr501::setModeConfigNetwork() { #ifdef WIFI if(selectModeNetwork()==1) set(this->gpio,refresh); else if(selectModeNetwork()==2) set(this->id,this->gpio,refresh); #else set(this->id,this->gpio,refresh); #endif return; } void ICACHE_FLASH_ATTR Hcsr501::set(unsigned long id, GpiosEnum gpio, unsigned long refresh) { resourceWifi = true; pinMode(gpio, INPUT); return; } #ifdef WIFI void ICACHE_FLASH_ATTR Hcsr501::set(GpiosEnum gpio, unsigned long refresh) { this->id = idResource(resourceJson); if(this->id!=0) set(this->id,gpio,refresh); else { resourceWifi = false; debugIOT(MSG_ERROR,"Resource Hcsr501 referenced in main was not sent by JSON"); refreshTimer.stop(); } return; } #endif void ICACHE_FLASH_ATTR Hcsr501::responseHttpCallback() { if(!systemCall) { read(); refreshTimer.start(); } return; } void ICACHE_FLASH_ATTR Hcsr501::actionStart() { if((clientDeviceHTTP!=200) ||(clientHTTP->code==403)) { serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds/last"; sendHTTP(BLANK,GET); } if(RequestQueueOn) { String heap = String(system_get_free_heap_size()); debugIOT(MSG_INFO,name+" - Memory HEAP",heap); if(filter) { if(this->hcsr501Presence != json->response->feed.rawData.toInt()) { doCallback(CallbackEvents::DATA_CHANGED); serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds"; sendHTTP(json->parseJson(this->hcsr501Presence),POST); } else { serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds/last"; sendHTTP(BLANK,GET); } } else { doCallback(CallbackEvents::DATA_CHANGED); serverConfig->url = deviceConfig.server+"/api/device/"+deviceConfig.publicKey+"/resource/"+String(this->id)+"/feeds"; sendHTTP(json->parseJson(this->hcsr501Presence),POST); } } return; } unsigned long ICACHE_FLASH_ATTR Hcsr501::read() { this->hcsr501Presence = digitalRead(this->gpio); return this->hcsr501Presence; }
34.903226
138
0.658965
automacaoiot
bf20e580313e9f5c94688e5c207df5d622bc3fff
604
cpp
C++
C++/iLab/Minggu 4/Activity/suhu2.cpp
rafipriatna/Belajar-Bahasa-Pemrograman
e6e1f00526897a9d37065d70f9509cb4db5a61f8
[ "MIT" ]
1
2019-11-26T06:06:34.000Z
2019-11-26T06:06:34.000Z
C++/iLab/Minggu 4/Activity/suhu2.cpp
rafipriatna/Belajar-Bahasa-Pemrograman
e6e1f00526897a9d37065d70f9509cb4db5a61f8
[ "MIT" ]
null
null
null
C++/iLab/Minggu 4/Activity/suhu2.cpp
rafipriatna/Belajar-Bahasa-Pemrograman
e6e1f00526897a9d37065d70f9509cb4db5a61f8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ // Deklarasi variabel const int JUM_ELEMEN = 5; float suhu[JUM_ELEMEN], rata_rata, total; // Input cout << "Masukkan " << JUM_ELEMEN << " data suhu" << endl; // Looping input for (int i = 0; i < JUM_ELEMEN; i++){ cout << i + 1 << " : "; cin >> suhu[i]; } // Hitung rata-rata suhu for (int i = 0; i < JUM_ELEMEN; i++){ total += suhu[i]; } rata_rata = total / JUM_ELEMEN; // Output isi array cout << "Suhu rata-rata: " << rata_rata << endl; return 0; }
20.133333
62
0.521523
rafipriatna
bf213da706fcc816c12313ec662a8e583798c00d
2,375
hpp
C++
math/geometry.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
math/geometry.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
math/geometry.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_MATH_GEOMETRY_HPP___ #define ___INANITY_MATH_GEOMETRY_HPP___ #include "basic.hpp" BEGIN_INANITY_MATH template <typename T> xmat<T, 4, 4> CreateTranslationMatrix(const xvec<T, 3>& translation) { xmat<T, 4, 4> r = identity_mat<T, 4>(); r(0, 3) = translation(0); r(1, 3) = translation(1); r(2, 3) = translation(2); return r; } template <typename T> xmat<T, 4, 4> CreateScalingMatrix(const xvec<T, 3>& scaling) { xmat<T, 4, 4> r = identity_mat<T, 4>(); r(0, 0) = scaling(0); r(1, 1) = scaling(1); r(2, 2) = scaling(2); return r; } template <typename T> xmat<T, 4, 4> CreateLookAtMatrix(const xvec<T, 3>& eye, const xvec<T, 3>& target, const xvec<T, 3>& up) { xmat<T, 4, 4> r; xvec<T, 3> z = normalize(eye - target); xvec<T, 3> x = normalize(cross(up, z)); xvec<T, 3> y = cross(z, x); r(0, 0) = x.x; r(1, 0) = y.x; r(2, 0) = z.x; r(3, 0) = 0; r(0, 1) = x.y; r(1, 1) = y.y; r(2, 1) = z.y; r(3, 1) = 0; r(0, 2) = x.z; r(1, 2) = y.z; r(2, 2) = z.z; r(3, 2) = 0; r(0, 3) = -dot(x, eye); r(1, 3) = -dot(y, eye); r(2, 3) = -dot(z, eye); r(3, 3) = 1; return r; } template <typename T> xmat<T, 4, 4> CreateProjectionPerspectiveFovMatrix(T fovY, T aspect, T zn, T zf) { xmat<T, 4, 4> r = zero_mat<T, 4, 4>(); T yScale = 1 / tan(fovY / 2); T xScale = yScale / aspect; r(0, 0) = xScale; r(1, 1) = yScale; r(2, 2) = zf / (zn - zf); r(2, 3) = zn * zf / (zn - zf); r(3, 2) = -1; return r; } template <typename T> xvec<T, 4> axis_rotation(const xvec<T, 3>& axis, T angle) { angle /= 2; T angleSin = sin(angle); T angleCos = cos(angle); return xvec<T, 4>( axis.x * angleSin, axis.y * angleSin, axis.z * angleSin, angleCos); } template <typename T> xmat<T, 4, 4> QuaternionToMatrix(const xquat<T>& q) { xmat<T, 4, 4> r; T ww = q.w * q.w; T xx = q.x * q.x; T yy = q.y * q.y; T zz = q.z * q.z; T wx2 = q.w * q.x * 2.0f; T wy2 = q.w * q.y * 2.0f; T wz2 = q.w * q.z * 2.0f; T xy2 = q.x * q.y * 2.0f; T xz2 = q.x * q.z * 2.0f; T yz2 = q.y * q.z * 2.0f; r(0, 0) = ww + xx - yy - zz; r(0, 1) = xy2 - wz2; r(0, 2) = xz2 + wy2; r(0, 3) = 0; r(1, 0) = xy2 + wz2; r(1, 1) = ww - xx + yy - zz; r(1, 2) = yz2 - wx2; r(1, 3) = 0; r(2, 0) = xz2 - wy2; r(2, 1) = yz2 + wx2; r(2, 2) = ww - xx - yy + zz; r(2, 3) = 0; r(3, 0) = 0; r(3, 1) = 0; r(3, 2) = 0; r(3, 3) = 1; return r; } END_INANITY_MATH #endif
20.299145
103
0.532211
quyse
bf222b8459571e85368deec0c2b8d337de4c5ddd
10,280
cpp
C++
mcrng/mcrng.cpp
tectrolabs/microrng
586576107d510374d0a5b8536da45b4743dcadbf
[ "MIT" ]
null
null
null
mcrng/mcrng.cpp
tectrolabs/microrng
586576107d510374d0a5b8536da45b4743dcadbf
[ "MIT" ]
null
null
null
mcrng/mcrng.cpp
tectrolabs/microrng
586576107d510374d0a5b8536da45b4743dcadbf
[ "MIT" ]
1
2020-04-21T20:43:01.000Z
2020-04-21T20:43:01.000Z
/** * Copyright (C) 2014-2022 TectroLabs LLC, https://tectrolabs.com * * 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. */ /** * @file mcrng.cpp * @author Andrian Belinski * @date 06/-7/2022 * @version 1.1 * * @brief downloads random bytes from MicroRNG device through SPI interface on Raspberry PI 3+ or other Linux-based single-board computers. * */ #include "mcrng.h" /** * Display usage message * */ void displayUsage() { printf("---------------------------------------------------------------------------\n"); printf("--- TectroLabs - mcrng - MicroRNG download utility Version 1.0 ---\n"); printf("--- Use with RPI 3+ or other Linux-based single-board computers ---\n"); printf("---------------------------------------------------------------------------\n"); printf("NAME\n"); printf(" mcrng - True Random Number Generator MicroRNG download utility \n"); printf("SYNOPSIS\n"); printf(" mcrng [options] \n"); printf("\n"); printf("DESCRIPTION\n"); printf(" Mcrng downloads random bytes from MicroRNG device into a data file.\n"); printf("\n"); printf("OPTIONS\n"); printf(" Operation modifiers:\n"); printf("\n"); printf(" -fn FILE, --file-name FILE\n"); printf(" a FILE name for storing random data. Use STDOUT to send bytes\n"); printf(" to standard output\n"); printf("\n"); printf(" -nb NUMBER, --number-bytes NUMBER\n"); printf(" NUMBER of random bytes to download, max value 200000000000,\n"); printf(" skip this option for continuous download of random bytes\n"); printf("\n"); printf(" -dp PATH, --device-path PATH\n"); printf(" SPI device path, default value: /dev/spidev0.0\n"); printf("\n"); printf(" -cf NUMBER, --clock-frequency NUMBER\n"); printf(" SPI master clock frequency in KHz, max value 60000,\n"); printf(" skip this option for default 250 KHz frequency.\n"); printf(" Setting this value too high may result in miscommunication.\n"); printf(" Use 'mcdiag' utility to determine the max frequency.\n"); printf("EXAMPLES:\n"); printf(" It may require 'sudo' permissions to run this utility.\n"); printf(" To download 12 MB of true random bytes to 'rnd.bin' file\n"); printf(" mcrng -dd -fn rnd.bin -nb 12000000\n"); printf(" To download 12 MB of true random bytes to a file using device path\n"); printf(" mcrng -dd -fn rnd.bin -nb 12000000 -dp /dev/spidev0.0\n"); printf(" To download 12 MB of true random bytes to standard output\n"); printf(" mcrng -dd -fn STDOUT -nb 12000000 -dp /dev/spidev0.0\n"); printf("\n"); } /** * Validate command line argument count * * @param int curIdx * @param int actualArgumentCount * @return true if run successfully */ bool validateArgumentCount(int curIdx, int actualArgumentCount) { if (curIdx >= actualArgumentCount) { fprintf(stderr, "\nMissing command line arguments\n\n"); displayUsage(); return false; } return true; } /** * Parse device path if specified * * @param int idx - current parameter number * @param int argc - number of parameters * @param char ** argv - parameters * @return int - 0 when successfully parsed */ int parseDevicePath(int idx, int argc, char **argv) { if (idx < argc) { if (strcmp("-dp", argv[idx]) == 0 || strcmp("--device-path", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } strcpy(devicePath, argv[idx++]); } } return 0; } /** * Parse arguments for extracting command line parameters * * @param int argc * @param char** argv * @return int - 0 when run successfully */ int processArguments(int argc, char **argv) { int idx = 1; strcpy(devicePath, DEFAULT_SPI_DEV_PATH); if (argc < 2) { displayUsage(); return -1; } while (idx < argc) { if (strcmp("-nb", argv[idx]) == 0 || strcmp("--number-bytes", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } numGenBytes = atoll(argv[idx++]); if (numGenBytes > 200000000000) { fprintf(stderr, "Number of bytes cannot exceed 200000000000\n"); return -1; } } else if (strcmp("-fn", argv[idx]) == 0 || strcmp("--file-name", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } filePathName = argv[idx++]; } else if (strcmp("-cf", argv[idx]) == 0 || strcmp("--clock-frequency", argv[idx]) == 0) { if (validateArgumentCount(++idx, argc) == false) { return -1; } maxSpiMasterClock = (uint32_t)atoi(argv[idx++]) * 1000; } else if (parseDevicePath(idx, argc, argv) == -1) { return -1; } else { // Could not handle the argument, skip to the next one ++idx; } } return processDownloadRequest(); } /** * Close file handle * */ void closeHandle() { if (pOutputFile != NULL) { fclose(pOutputFile); pOutputFile = NULL; } } /** * Write bytes out to the file * * @param uint8_t* bytes - pointer to the byte array * @param uint32_t numBytes - number of bytes to write */ void writeBytes(uint8_t *bytes, uint32_t numBytes) { FILE *handle = pOutputFile; fwrite(bytes, 1, numBytes, handle); } /** * Handle download request * * @return int - 0 when run successfully */ int handleDownloadRequest() { uint8_t receiveByteBuffer[MCR_BUFF_FILE_SIZE_BYTES]; if (!spi.connect(devicePath)) { fprintf(stderr, " Cannot open SPI device %s, error: %s ... \n", devicePath, spi.getLastErrMsg()); return -1; } spi.setMaxClockFrequency(maxSpiMasterClock); if (!spi.validateDevice()) { fprintf(stderr, " Cannot access device, error: %s ... \n", spi.getLastErrMsg()); return -1; } if (filePathName == NULL) { fprintf(stderr, "No file name defined.\n"); return -1; } if (isOutputToStandardOutput == true) { pOutputFile = fdopen(dup(fileno(stdout)), "wb"); } else { pOutputFile = fopen(filePathName, "wb"); } if (pOutputFile == NULL) { fprintf(stderr, "Cannot open file: %s in write mode\n", filePathName); return -1; } while (numGenBytes == -1) { // Infinite loop for downloading unlimited random bytes if (!spi.retrieveRandomBytes(MCR_BUFF_FILE_SIZE_BYTES, receiveByteBuffer)) { fprintf(stderr, "Failed to receive %d bytes for unlimited download, error: %s. \n", MCR_BUFF_FILE_SIZE_BYTES, spi.getLastErrMsg()); return -1; } writeBytes(receiveByteBuffer, MCR_BUFF_FILE_SIZE_BYTES); } // Calculate number of complete random byte chunks to download int64_t numCompleteChunks = numGenBytes / MCR_BUFF_FILE_SIZE_BYTES; // Calculate number of bytes in the last incomplete chunk uint32_t chunkRemaindBytes = (uint32_t)(numGenBytes % MCR_BUFF_FILE_SIZE_BYTES); // Process each chunk int64_t chunkNum; for (chunkNum = 0; chunkNum < numCompleteChunks; chunkNum++) { if (!spi.retrieveRandomBytes(MCR_BUFF_FILE_SIZE_BYTES, receiveByteBuffer)) { fprintf(stderr, "Failed to receive %d bytes, error: %s. \n", MCR_BUFF_FILE_SIZE_BYTES, spi.getLastErrMsg()); return -1; } writeBytes(receiveByteBuffer, MCR_BUFF_FILE_SIZE_BYTES); } if (chunkRemaindBytes > 0) { //Process incomplete chunk if (!spi.retrieveRandomBytes(chunkRemaindBytes, receiveByteBuffer)) { fprintf(stderr, "Failed to receive %d bytes for last chunk, error: code %s. ", chunkRemaindBytes,spi.getLastErrMsg()); return -1; } writeBytes(receiveByteBuffer, chunkRemaindBytes); } closeHandle(); return 0; } /** * Process Request * * @return int - 0 when run successfully */ int processDownloadRequest() { if (filePathName != NULL && (!strcmp(filePathName, "STDOUT") || !strcmp(filePathName, "/dev/stdout"))) { isOutputToStandardOutput = true; } else { isOutputToStandardOutput = false; } int status = handleDownloadRequest(); return status; } /** * Main entry * * @param int argc - number of parameters * @param char ** argv - parameters * */ int main(int argc, char **argv) { if (!processArguments(argc, argv)) { return -1; }; return 0; }
30.146628
142
0.580156
tectrolabs
bf2272beb17c6a29e36bf0ac51694f94df9d1c9b
3,957
cpp
C++
src/writer/verilog/dataflow_state.cpp
robtaylor/iroha
e7713910ee64ca98f999b98b0c77c02fcfe2da09
[ "BSD-3-Clause" ]
34
2016-02-07T17:43:55.000Z
2021-12-18T12:01:08.000Z
src/writer/verilog/dataflow_state.cpp
robtaylor/iroha
e7713910ee64ca98f999b98b0c77c02fcfe2da09
[ "BSD-3-Clause" ]
5
2016-04-12T09:27:31.000Z
2021-06-29T10:59:18.000Z
src/writer/verilog/dataflow_state.cpp
robtaylor/iroha
e7713910ee64ca98f999b98b0c77c02fcfe2da09
[ "BSD-3-Clause" ]
5
2015-12-26T10:58:46.000Z
2021-06-25T18:58:40.000Z
#include "writer/verilog/dataflow_state.h" #include "design/design_util.h" #include "iroha/i_design.h" #include "iroha/logging.h" #include "iroha/resource_class.h" #include "writer/verilog/dataflow_table.h" #include "writer/verilog/fifo.h" #include "writer/verilog/insn_writer.h" #include "writer/verilog/shared_reg.h" namespace iroha { namespace writer { namespace verilog { DataFlowState::DataFlowState(IState *state, DataFlowTable *table, Names *names) : State(state, table, names), df_table_(table) { } DataFlowState::~DataFlowState() { } void DataFlowState::BuildIncomingTransitions(const vector<DataFlowStateTransition> &trs) { if (trs.size() == 0) { return; } vector<string> conds; for (auto &tr : trs) { const IState *prev_st = tr.from->GetIState(); string s; if (prev_st->GetTable()->GetInitialState() == prev_st) { // Comes from initial state. IInsn *insn = DesignUtil::FindDataFlowInInsn(prev_st->GetTable()); s = StartCondition(insn); } else { s = StateVariable(prev_st); } if (df_table_->CanBlock()) { if (tr.from->IsCompoundCycle()) { s = "(" + StateWaitVariable(prev_st) + ")"; } else { s = "(" + s + " || " + StateWaitVariable(prev_st) + ")"; } } if (!tr.cond.empty()) { s = "(" + s + " && " + tr.cond + ")"; } conds.push_back(s); } string c = Util::Join(conds, " || "); if (df_table_->CanBlock()) { c = "!" + df_table_->BlockingCondition() + " && (" + c + ")"; } incoming_transitions_ = " " + StateVariable(i_state_) + " <= " + c + ";\n"; } void DataFlowState::Write(ostream &os) { os << " // State: " << i_state_->GetId() << "\n"; os << incoming_transitions_; if (df_table_->CanBlock()) { os << " " << StateWaitVariable(i_state_) << " <= " << df_table_->BlockingCondition() << " && (" << StateVariable(i_state_) << " || " << StateWaitVariable(i_state_) << ");\n"; } string s; if (i_state_->GetTable()->GetInitialState() == i_state_) { CHECK(!is_compound_cycle_) << "Can't process compound && initial state"; IInsn *insn = DesignUtil::FindDataFlowInInsn(i_state_->GetTable()); s = StartCondition(insn); } else if (is_compound_cycle_) { s = StateVariable(i_state_) + " || " + StateWaitVariable(i_state_); } else { s = StateVariable(i_state_); } os << " if (" << s << ") begin\n"; WriteStateBody(os); if (is_compound_cycle_) { ClearMultiCycleState(os); } os << " end\n"; } string DataFlowState::StateVariable(const IState *st) { return "st_" + Util::Itoa(st->GetTable()->GetId()) + "_" + Util::Itoa(st->GetId()); } string DataFlowState::StateWaitVariable(const IState *st) { return StateVariable(st) + "_w"; } vector<DataFlowStateTransition> DataFlowState::GetTransitions() { vector<DataFlowStateTransition> trs; if (transition_insn_ == nullptr) { return trs; } for (IState *ts : transition_insn_->target_states_) { DataFlowStateTransition tr; tr.to = nullptr; tr.to_raw = ts; tr.from = this; if (transition_insn_->target_states_.size() == 2) { IRegister *cond = transition_insn_->inputs_[0]; if (ts == transition_insn_->target_states_[0]) { tr.cond = "!" + InsnWriter::RegisterValue(*cond, names_); } else { tr.cond = InsnWriter::RegisterValue(*cond, names_); } } trs.push_back(tr); } return trs; } string DataFlowState::StartCondition(IInsn *insn) { IResource *res = insn->GetResource(); IResource *p = res->GetParentResource(); if (p != nullptr) { if (resource::IsSharedReg(*(p->GetClass()))) { return SharedReg::RegNotifierName(*p); } if (resource::IsFifo(*(p->GetClass()))) { return Fifo::RAck(*p, res); } CHECK(false); return ""; } else { return InsnWriter::RegisterValue(*insn->inputs_[0], names_); } } } // namespace verilog } // namespace writer } // namespace iroha
28.883212
90
0.618398
robtaylor
bf2278af946938a3377b419a537b09a9254a8cda
34,726
cpp
C++
src/plzma_path.cpp
readdle/PLzmaSDK
9587bbbb507249c66b90209e115bf0edd8d88274
[ "MIT" ]
null
null
null
src/plzma_path.cpp
readdle/PLzmaSDK
9587bbbb507249c66b90209e115bf0edd8d88274
[ "MIT" ]
null
null
null
src/plzma_path.cpp
readdle/PLzmaSDK
9587bbbb507249c66b90209e115bf0edd8d88274
[ "MIT" ]
null
null
null
// // By using this Software, you are accepting original [LZMA SDK] and MIT license below: // // The MIT License (MIT) // // Copyright (c) 2015 - 2021 Oleh Kulykov <olehkulykov@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <cstddef> #include "../libplzma.hpp" #include "plzma_private.hpp" #include "plzma_path_utils.hpp" namespace plzma { using namespace pathUtils; /// Iterator enum PathIteratorFlags: uint16_t { PathIteratorFlagIsDir = 1 << 0, PathIteratorFlagSkipPathConcat = 1 << 1, PathIteratorFlagDone = 1 << 2, PathIteratorFlagSkipFindNext = 1 << 3 }; Path Path::Iterator::path() const { Path res(_path); if ( !(_flags & PathIteratorFlagSkipPathConcat) ) { res.append(_component); } return res; } const Path & Path::Iterator::component() const noexcept { return _component; } Path Path::Iterator::fullPath() const { Path res(_root); if ( !(_flags & PathIteratorFlagSkipPathConcat) ) { res.append(_component); } return res; } bool Path::Iterator::isDir() const noexcept { return (_flags & PathIteratorFlagIsDir) ? true : false; } void Path::Iterator::clearPaths() noexcept { _root.clear(plzma_erase_zero); _path.clear(plzma_erase_zero); _component.clear(plzma_erase_zero); } Path::Iterator::Iterator(const Path & root, const plzma_open_dir_mode_t mode) : _root(root), _mode(mode) { } #if defined(LIBPLZMA_MSC) class PathIteratorMSC final : public Path::Iterator { private: HANDLE _findHandle = INVALID_HANDLE_VALUE; Vector<HANDLE> _stack; WIN32_FIND_DATAW _findData; plzma_size_t _referenceCounter = 0; void closeMSC() noexcept { _flags |= PathIteratorFlagDone; plzma_size_t i = _stack.count(); if (i > 0) { do { FindClose(_stack.at(--i)); } while (i > 0); _stack.clear(); } if (_findHandle != INVALID_HANDLE_VALUE) { FindClose(_findHandle); _findHandle = INVALID_HANDLE_VALUE; } clearPaths(); } LIBPLZMA_NON_COPYABLE_NON_MOVABLE(PathIteratorMSC) protected: virtual void retain() noexcept override final { LIBPLZMA_RETAIN_IMPL(_referenceCounter) } virtual void release() noexcept override final { LIBPLZMA_RELEASE_IMPL(_referenceCounter) } public: virtual void close() noexcept override final { closeMSC(); } virtual bool next() override final { if (_flags & PathIteratorFlagDone) { return false; } BOOL reading = TRUE; BOOL findNextRes = (_flags & PathIteratorFlagSkipFindNext) ? TRUE : FALSE; _flags = 0; do { if (!findNextRes) { findNextRes = FindNextFileW(_findHandle, &_findData); } if (findNextRes) { findNextRes = FALSE; if (wcscmp(_findData.cFileName, L".") == 0 || wcscmp(_findData.cFileName, L"..") == 0) { continue; } const bool isLink = ((_findData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && (_findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) ? true : false; if (isLink && !(_mode & plzma_open_dir_mode_follow_symlinks)) { continue; } _component.set(_findData.cFileName); if (_findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { Path root(_root); root.append(_component); root.append(L"*"); RAIIFindHANDLE subHandle; subHandle.handle = FindFirstFileW(root.wide(), &_findData); if (subHandle.handle == INVALID_HANDLE_VALUE) { continue; } else { _stack.push(_findHandle); _findHandle = subHandle.handle; subHandle.handle = INVALID_HANDLE_VALUE; root.removeLastComponent(); // remove '/*' _root = static_cast<Path &&>(root); _path.append(_component); _flags |= (PathIteratorFlagSkipPathConcat | PathIteratorFlagIsDir | PathIteratorFlagSkipFindNext); return true; // report dir } } else { //TODO: filter & skip unsupported attribs if needed //https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants return true; // report file } } else if (_stack.count() > 0) { _root.removeLastComponent(); _path.removeLastComponent(); _findHandle = _stack.at(_stack.count() - 1); _stack.pop(); continue; } else { reading = FALSE; // no files, exit } } while (reading); _flags |= PathIteratorFlagDone; return false; } PathIteratorMSC(const Path & root, const plzma_open_dir_mode_t mode) : Path::Iterator(root, mode) { Path path(root); if (path.count() > 0) { path.append(L"*"); } else { path.set(L"." CLZMA_SEP_WSTR L"*"); } RAIIFindHANDLE subHandle; subHandle.handle = FindFirstFileW(path.wide(), &_findData); if (subHandle.handle == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { // function fails because no matching files can be found clearPaths(); _flags |= PathIteratorFlagDone; } else { Exception exception(plzma_error_code_io, nullptr, __FILE__, __LINE__); exception.setWhat("Can't open and iterate path: ", _root.utf8(), nullptr); exception.setReason("Path not found or not a directory.", nullptr); clearPaths(); throw exception; } } else { _findHandle = subHandle.handle; subHandle.handle = INVALID_HANDLE_VALUE; _flags |= PathIteratorFlagSkipFindNext; } } virtual ~PathIteratorMSC() noexcept { closeMSC(); } }; #elif defined(LIBPLZMA_POSIX) class PathIteratorPosix final : public Path::Iterator { private: DIR * _dir = nullptr; Vector<DIR *> _stack; plzma_size_t _referenceCounter = 0; void closePosix() noexcept { _flags |= PathIteratorFlagDone; plzma_size_t i = _stack.count(); if (i > 0) { do { closedir(_stack.at(--i)); } while (i > 0); _stack.clear(); } if (_dir) { closedir(_dir); _dir = nullptr; } clearPaths(); } LIBPLZMA_NON_COPYABLE_NON_MOVABLE(PathIteratorPosix) protected: virtual void retain() noexcept override final { LIBPLZMA_RETAIN_IMPL(_referenceCounter) } virtual void release() noexcept override final { LIBPLZMA_RELEASE_IMPL(_referenceCounter) } public: virtual void close() noexcept override final { closePosix(); } virtual bool next() override final { if (_flags & PathIteratorFlagDone) { return false; } _flags = 0; Path root; const char * rootUtf8; struct dirent d, * dp; int readRes; do { if ( (readRes = readdir_r(_dir, &d, &dp)) == 0 && dp) { if (strcmp(d.d_name, ".") == 0 || strcmp(d.d_name, "..") == 0) { continue; } bool isDir = false, isFile = false, isLink = false; rootUtf8 = nullptr; if (d.d_type != DT_UNKNOWN) { isDir = d.d_type == DT_DIR; isFile = d.d_type == DT_REG; isLink = d.d_type == DT_LNK; } else { root.set(_root); root.append(d.d_name); rootUtf8 = root.utf8(); struct stat statbuf; if (access(rootUtf8, F_OK) == 0 && stat(rootUtf8, &statbuf) == 0) { isDir = S_ISDIR(statbuf.st_mode); isFile = S_ISREG(statbuf.st_mode); isLink = S_ISLNK(statbuf.st_mode); } else { continue; } } if (isLink && !(_mode & plzma_open_dir_mode_follow_symlinks)) { continue; } _component.set(d.d_name); if (isFile) { return true; } else if (isDir || isLink) { if (!rootUtf8) { root.set(_root); root.append(_component); rootUtf8 = root.utf8(); } RAIIDIR dir; dir.dir = opendir(rootUtf8); if (dir.dir) { _stack.push(_dir); _dir = dir.dir; dir.dir = nullptr; _root = static_cast<Path &&>(root); rootUtf8 = nullptr; _path.append(_component); } else { continue; } _flags |= (PathIteratorFlagSkipPathConcat | PathIteratorFlagIsDir); return true; // report dir } else { continue; } } if (readRes == 0 && !dp && _stack.count() > 0) { _root.removeLastComponent(); _path.removeLastComponent(); closedir(_dir); _dir = _stack.at(_stack.count() - 1); _stack.pop(); dp = &d; continue; } } while (readRes == 0 && dp); _flags |= PathIteratorFlagDone; return false; } PathIteratorPosix(const Path & root, const plzma_open_dir_mode_t mode) : Path::Iterator(root, mode) { const char * path = nullptr; if (_root.count() > 0) { const char * utf8 = _root.utf8(); bool isDir = false; if (pathExists<char>(utf8, &isDir) && isDir) { path = utf8; } else { Exception exception(plzma_error_code_io, nullptr, __FILE__, __LINE__); exception.setWhat("Can't open and iterate path: ", _root.utf8(), nullptr); exception.setReason("Path not found or not a directory.", nullptr); clearPaths(); _flags |= PathIteratorFlagDone; throw exception; } } else { path = "."; } if ( !(_dir = opendir(path)) ) { Exception exception(plzma_error_code_io, nullptr, __FILE__, __LINE__); exception.setWhat("Can't open directory: ", _root.utf8(), nullptr); exception.setReason("No open directory permissions.", nullptr); clearPaths(); _flags |= PathIteratorFlagDone; throw exception; } } virtual ~PathIteratorPosix() noexcept { closePosix(); } }; #endif void Path::set(const String & str) { #if defined(LIBPLZMA_MSC) set(str.wide()); #elif defined(LIBPLZMA_POSIX) set(str.utf8()); #endif } void Path::set(const wchar_t * LIBPLZMA_NULLABLE str) { copyFrom(str, plzma_erase_zero); const auto reduced = normalize<wchar_t>(_ws); if (reduced > 0) { _size -= reduced; } } void Path::set(const char * LIBPLZMA_NULLABLE str) { copyFrom(str, plzma_erase_zero); const auto reduced = normalize<char>(_cs); if (reduced > 0) { _size -= reduced; _cslen -= reduced; } } void Path::append(const wchar_t * LIBPLZMA_NULLABLE str) { syncWide(); const size_t len = str ? wcslen(str) : 0; if (len > 0) { const wchar_t * stringsList[2]; Pair<size_t, size_t> sizesList[2]; size_t count = 0; if (requireSeparator<wchar_t>(_ws, _size, str)) { stringsList[count] = CLZMA_SEP_WSTR; sizesList[count].first = sizesList[count].second = 1; count++; } stringsList[count] = str; sizesList[count].first = sizesList[count].second = len; String::append(stringsList, sizesList, ++count, plzma_erase_zero); const auto reduced = normalize<wchar_t>(_ws); if (reduced > 0) { _size -= reduced; } } } void Path::append(const char * LIBPLZMA_NULLABLE str) { syncUtf8(); const auto len = lengthMaxCount(str, static_cast<size_t>(plzma_max_size())); if (len.first > 0) { const char * stringsList[2]; Pair<size_t, size_t> sizesList[2]; size_t count = 0; if (requireSeparator<char>(_cs, _cslen, str)) { stringsList[count] = CLZMA_SEP_CSTR; sizesList[count].first = sizesList[count].second = 1; count++; } stringsList[count] = str; sizesList[count] = len; String::append(stringsList, sizesList, ++count, plzma_erase_zero); const auto reduced = normalize<char>(_cs); if (reduced > 0) { _size -= reduced; _cslen -= reduced; } } } void Path::append(const Path & path) { #if defined(LIBPLZMA_MSC) append(path.wide()); #elif defined(LIBPLZMA_POSIX) append(path.utf8()); #endif } Path Path::appending(const wchar_t * LIBPLZMA_NULLABLE str) const { Path result(*this); result.append(str); return result; } Path Path::appending(const char * LIBPLZMA_NULLABLE str) const { Path result(*this); result.append(str); return result; } Path Path::appending(const Path & path) const { Path result(*this); result.append(path); return result; } void Path::appendRandomComponent() { #if defined(LIBPLZMA_MSC) syncWide(); _cs.clear(plzma_erase_zero, sizeof(char) * _cslen); _size += appendRandComp<wchar_t>(_ws, _size); #elif defined(LIBPLZMA_POSIX) syncUtf8(); _ws.clear(plzma_erase_zero, sizeof(wchar_t) * _size); const auto appended = appendRandComp<char>(_cs, _cslen); _size += appended; _cslen += appended; #endif } Path Path::appendingRandomComponent() const { Path result(*this); result.appendRandomComponent(); return result; } Path Path::lastComponent() const { Path res; #if defined(LIBPLZMA_MSC) syncWide(); if (_ws && _size > 0) { const auto comp = lastComp<wchar_t>(_ws, _size); if (comp.second > 0) { const wchar_t * stringsList[1] = { comp.first }; Pair<size_t, size_t> sizesList[1]; sizesList[0].first = sizesList[0].second = comp.second; res.String::append(stringsList, sizesList, 1, plzma_erase_zero); } } #elif defined(LIBPLZMA_POSIX) syncUtf8(); if (_cs && _cslen > 0) { const auto comp = lastComp<char>(_cs, _cslen); if (comp.second > 0) { const char * stringsList[1] = { comp.first }; Pair<size_t, size_t> sizesList[1] = { lengthMaxLength(comp.first, comp.second) }; res.String::append(stringsList, sizesList, 1, plzma_erase_zero); } } #endif return res; } void Path::removeLastComponent() { #if defined(LIBPLZMA_MSC) syncWide(); if (_ws && _size > 0 && removeLastComp<wchar_t>(_ws, _size)) { _size = static_cast<plzma_size_t>(wcslen(_ws)); _cs.clear(plzma_erase_zero, sizeof(char) * _cslen); _cslen = 0; } #elif defined(LIBPLZMA_POSIX) syncUtf8(); if (_cs && _cslen > 0 && removeLastComp<char>(_cs, _cslen)) { const auto len = String::lengthMaxCount(_cs, static_cast<size_t>(plzma_max_size())); _ws.clear(plzma_erase_zero, sizeof(wchar_t) * _size); _cslen = static_cast<plzma_size_t>(len.first); _size = static_cast<plzma_size_t>(len.second); } #endif } Path Path::removingLastComponent() const { Path result(*this); result.removeLastComponent(); return result; } bool Path::exists(bool * LIBPLZMA_NULLABLE isDir /* = nullptr */) const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathExists<wchar_t>(wide(), isDir) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathExists<char>(utf8(), isDir) : false; #endif } bool Path::readable() const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathReadable<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathReadable<char>(utf8()) : false; #endif } bool Path::writable() const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathWritable<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathWritable<char>(utf8()) : false; #endif } bool Path::readableAndWritable() const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? pathReadableAndWritable<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? pathReadableAndWritable<char>(utf8()) : false; #endif } plzma_path_stat Path::stat() const { #if defined(LIBPLZMA_MSC) return pathStat<wchar_t>(wide()); #elif defined(LIBPLZMA_POSIX) return pathStat<char>(utf8()); #endif } bool Path::remove(const bool skipErrors) const { #if defined(LIBPLZMA_MSC) return (_size > 0) ? removePath<wchar_t>(wide(), skipErrors) : true; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? removePath<char>(utf8(), skipErrors) : true; #endif } bool Path::createDir(const bool withIntermediates) const { if (withIntermediates) { #if defined(LIBPLZMA_MSC) return (_size > 0) ? createIntermediateDirs<wchar_t>(wide(), _size) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? createIntermediateDirs<char>(utf8(), _cslen) : false; #endif } #if defined(LIBPLZMA_MSC) return (_size > 0) ? createSingleDir<wchar_t>(wide()) : false; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? createSingleDir<char>(utf8()) : false; #endif } FILE * LIBPLZMA_NULLABLE Path::openFile(const char * LIBPLZMA_NONNULL mode) const { #if defined(LIBPLZMA_MSC) if (_size > 0) { wchar_t wmode[32] = { 0 }; // more than enough for a max mode: "w+b, ccs=UNICODE" for (size_t i = 0, n = strlen(mode); ((i < n) && (i < 31)); i++) { wmode[i] = static_cast<wchar_t>(mode[i]); } return _wfopen(wide(), wmode); } return nullptr; #elif defined(LIBPLZMA_POSIX) return (_size > 0) ? fopen(utf8(), mode) : nullptr; #endif } SharedPtr<Path::Iterator> Path::openDir(const plzma_open_dir_mode_t mode /* = 0 */ ) const { #if defined(LIBPLZMA_MSC) return SharedPtr<Path::Iterator>(new PathIteratorMSC(*this, mode)); #elif defined(LIBPLZMA_POSIX) return SharedPtr<Path::Iterator>(new PathIteratorPosix(*this, mode)); #endif } bool Path::operator == (const Path & path) const { #if defined(LIBPLZMA_MSC) return pathsAreEqual<wchar_t>(wide(), path.wide(), _size, path._size); #elif defined(LIBPLZMA_POSIX) return pathsAreEqual<char>(utf8(), path.utf8(), _cslen, path._cslen); #endif } Path & Path::operator = (Path && path) noexcept { moveFrom(static_cast<Path &&>(path), plzma_erase_zero); return *this; } Path::Path(Path && path) noexcept : String(static_cast<Path &&>(path)) { } Path & Path::operator = (const Path & path) { copyFrom(path, plzma_erase_zero); return *this; } Path::Path(const Path & path) : String(path) { } Path::Path(const wchar_t * LIBPLZMA_NULLABLE path) : String(path) { const auto reduced = normalize<wchar_t>(_ws); if (reduced > 0) { _size -= reduced; } } Path::Path(const char * LIBPLZMA_NULLABLE path) : String(path) { const auto reduced = normalize<char>(_cs); if (reduced > 0) { _size -= reduced; _cslen -= reduced; } } Path::~Path() noexcept { _ws.erase(plzma_erase_zero, sizeof(wchar_t) * _size); _cs.erase(plzma_erase_zero, sizeof(char) * _cslen); } #if !defined(PATH_MAX) #define PATH_MAX 1024 #endif Path Path::tmpPath() { Path path; #if defined(__APPLE__) && defined(_CS_DARWIN_USER_TEMP_DIR) char buff[PATH_MAX]; const size_t res = confstr(_CS_DARWIN_USER_TEMP_DIR, buff, PATH_MAX); if (res > 0 && res < PATH_MAX && initializeTmpPath<char>(buff, "libplzma", path)) { return path; } #endif #if defined(LIBPLZMA_MSC) static const wchar_t * const wevs[4] = { L"TMPDIR", L"TEMPDIR", L"TEMP", L"TMP" }; for (size_t i = 0; i < 4; i++) { const wchar_t * p = _wgetenv(wevs[i]); if (p && initializeTmpPath<wchar_t>(p, L"libplzma", path)) { return path; } } #endif static const char * const cevs[4] = { "TMPDIR", "TEMPDIR", "TEMP", "TMP" }; for (size_t i = 0; i < 4; i++) { char * p = getenv(cevs[i]); if (p && initializeTmpPath<char>(p, "libplzma", path)) { return path; } } #if !defined(LIBPLZMA_OS_WINDOWS) if (initializeTmpPath<char>("/tmp", "libplzma", path)) { return path; } #endif return Path(); } } // namespace plzma #include "plzma_c_bindings_private.hpp" #if !defined(LIBPLZMA_NO_C_BINDINGS) using namespace plzma; plzma_path plzma_path_create_with_wide_string(const wchar_t * LIBPLZMA_NULLABLE path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_TRY(plzma_path) createdCObject.object = static_cast<void *>(new Path(path)); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_create_with_utf8_string(const char * LIBPLZMA_NULLABLE path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_TRY(plzma_path) createdCObject.object = static_cast<void *>(new Path(path)); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_create_with_tmp_dir(void) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_TRY(plzma_path) auto tmp = Path::tmpPath(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(tmp))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_size_t plzma_path_count(const plzma_path * LIBPLZMA_NONNULL path) { return path->exception ? 0 : static_cast<const Path *>(path->object)->count(); } void plzma_path_set_wide_string(plzma_path * LIBPLZMA_NONNULL path, const wchar_t * LIBPLZMA_NULLABLE str) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->set(str); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } void plzma_path_set_utf8_string(plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NULLABLE str) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->set(str); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } void plzma_path_append_wide_component(plzma_path * LIBPLZMA_NONNULL path, const wchar_t * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->append(component); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_appending_wide_component(const plzma_path * LIBPLZMA_NONNULL path, const wchar_t * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->appending(component); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_append_utf8_component(plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->append(component); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_appending_utf8_component(const plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NULLABLE component) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->appending(component); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_append_random_component(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->appendRandomComponent(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_appending_random_component(const plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->appendingRandomComponent(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } const wchar_t * LIBPLZMA_NULLABLE plzma_path_wide_string(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, nullptr) return static_cast<Path *>(path->object)->wide(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, nullptr) } const char * LIBPLZMA_NULLABLE plzma_path_utf8_string(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, nullptr) return static_cast<Path *>(path->object)->utf8(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, nullptr) } bool plzma_path_exists(plzma_path * LIBPLZMA_NONNULL path, bool * LIBPLZMA_NULLABLE isDir) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->exists(isDir); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } bool plzma_path_readable(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->readable(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } bool plzma_path_writable(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->writable(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } bool plzma_path_readable_and_writable(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->readableAndWritable(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } plzma_path_stat plzma_path_get_stat(plzma_path * LIBPLZMA_NONNULL path) { plzma_path_stat emptyStat{0, 0, 0, 0}; LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, emptyStat) return static_cast<Path *>(path->object)->stat(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, emptyStat) } void plzma_path_clear(plzma_path * LIBPLZMA_NONNULL path, const plzma_erase erase_type) { plzma_object_exception_release(path); static_cast<Path *>(path->object)->clear(erase_type); } bool plzma_path_remove(plzma_path * LIBPLZMA_NONNULL path, const bool skip_errors) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->remove(skip_errors); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } plzma_path plzma_path_last_component(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) auto comp = static_cast<Path *>(path->object)->lastComponent(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(comp))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_remove_last_component(plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY(path) static_cast<Path *>(path->object)->removeLastComponent(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH(path) } plzma_path plzma_path_removing_last_component(const plzma_path * LIBPLZMA_NONNULL path) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, path) Path result = static_cast<const Path *>(path->object)->removingLastComponent(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(result))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } bool plzma_path_create_dir(plzma_path * LIBPLZMA_NONNULL path, const bool with_intermediates) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, false) return static_cast<Path *>(path->object)->createDir(with_intermediates); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, false) } FILE * LIBPLZMA_NULLABLE plzma_path_open_file(plzma_path * LIBPLZMA_NONNULL path, const char * LIBPLZMA_NONNULL mode) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(path, nullptr) return static_cast<Path *>(path->object)->openFile(mode); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(path, nullptr) } plzma_path_iterator plzma_path_open_dir(plzma_path * LIBPLZMA_NONNULL path, const plzma_open_dir_mode_t mode) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path_iterator, path) auto it = static_cast<Path *>(path->object)->openDir(mode); createdCObject.object = static_cast<void *>(it.take()); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } void plzma_path_release(plzma_path * LIBPLZMA_NULLABLE path) { plzma_object_exception_release(path); delete static_cast<Path *>(path->object); path->object = nullptr; } plzma_path plzma_path_iterator_component(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, iterator) auto comp = static_cast<const Path::Iterator *>(iterator->object)->component(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(comp))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_iterator_path(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, iterator) auto path = static_cast<const Path::Iterator *>(iterator->object)->path(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(path))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } plzma_path plzma_path_iterator_full_path(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_CREATE_OBJECT_FROM_TRY(plzma_path, iterator) auto fullPath = static_cast<const Path::Iterator *>(iterator->object)->fullPath(); createdCObject.object = static_cast<void *>(new Path(static_cast<Path &&>(fullPath))); LIBPLZMA_C_BINDINGS_CREATE_OBJECT_CATCH } bool plzma_path_iterator_is_dir(const plzma_path_iterator * LIBPLZMA_NONNULL iterator) { return iterator->exception ? false : static_cast<const Path::Iterator *>(iterator->object)->isDir(); } bool plzma_path_iterator_next(plzma_path_iterator * LIBPLZMA_NONNULL iterator) { LIBPLZMA_C_BINDINGS_OBJECT_EXEC_TRY_RETURN(iterator, false) return static_cast<Path::Iterator *>(iterator->object)->next(); LIBPLZMA_C_BINDINGS_OBJECT_EXEC_CATCH_RETURN(iterator, false) } void plzma_path_iterator_close(plzma_path_iterator * LIBPLZMA_NONNULL iterator) { if (!iterator->exception) { static_cast<Path::Iterator *>(iterator->object)->close(); } } void plzma_path_iterator_release(plzma_path_iterator * LIBPLZMA_NULLABLE iterator) { plzma_object_exception_release(iterator); SharedPtr<Path::Iterator> iteratorSPtr; iteratorSPtr.assign(static_cast<Path::Iterator *>(iterator->object)); iterator->object = nullptr; } #endif // # !LIBPLZMA_NO_C_BINDINGS
38.076754
170
0.607384
readdle
bf28e1de4bb0ce3a2e2cc31e0877d1c8cb2f539a
120
hpp
C++
libs/shared/itsuptoyou.hpp
zepadovani/generic-makefile-withlibs
5c8da8f87a23c414700013efd569339f3fb798e6
[ "Unlicense" ]
null
null
null
libs/shared/itsuptoyou.hpp
zepadovani/generic-makefile-withlibs
5c8da8f87a23c414700013efd569339f3fb798e6
[ "Unlicense" ]
null
null
null
libs/shared/itsuptoyou.hpp
zepadovani/generic-makefile-withlibs
5c8da8f87a23c414700013efd569339f3fb798e6
[ "Unlicense" ]
null
null
null
#ifndef ITSUPTOYOU_HPP_INCLUDED #define ITSUPTOYOU_HPP_INCLUDED void itsuptoyou( ); #endif // ITSUPTOYOU_HPP_INCLUDED
17.142857
33
0.833333
zepadovani
bf294b7bfce9d40ebb6da5882bfb8327b03fed87
10,021
cpp
C++
src/chip8.cpp
Akaito/csaru-chip8
b30d2de2fac5493d5da13d38571936dd21a25e36
[ "Zlib" ]
null
null
null
src/chip8.cpp
Akaito/csaru-chip8
b30d2de2fac5493d5da13d38571936dd21a25e36
[ "Zlib" ]
null
null
null
src/chip8.cpp
Akaito/csaru-chip8
b30d2de2fac5493d5da13d38571936dd21a25e36
[ "Zlib" ]
null
null
null
// This is *heavily* based on Laurence Muller's tutorial at // http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/ #include <cstdlib> #include <cstdio> #include <cstring> #include "../include/chip8.hpp" //===================================================================== // // Static locals // //===================================================================== //===================================================================== // XXXX ..X. // X..X .XX. // X..X ..x. // X..X ..x. // XXXX .xxx static const uint8_t s_fontSet[80] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80, // F }; //===================================================================== // // Chip8 definitions // //===================================================================== //===================================================================== void Chip8::Initialize (unsigned randSeed) { CSaruCore::SecureZero(m_memory, s_memoryBytes); CSaruCore::SecureZero(m_v, s_registerCount); m_i = 0x0000; m_pc = s_progRomRamBegin; m_delayTimer = 0; m_soundTimer = 0; CSaruCore::SecureZero(m_keyStates, s_keyCount); m_opcode = 0x0000; CSaruCore::SecureZero(m_stack, s_stackSize); m_sp = 0x00; CSaruCore::SecureZero(m_renderOut, s_renderWidth * s_renderHeight); m_drawFlag = false; // Load default Chip8 font. std::memcpy(m_memory + s_fontBegin, s_fontSet, sizeof(s_fontSet)); // TODO : Replace with a per-Chip8 random number generator. std::srand(randSeed); } //===================================================================== void Chip8::EmulateCycle () { // Fetch opcode. m_opcode = m_memory[m_pc] << 8 | m_memory[m_pc + 1]; // Prepare common portions of opcode. const uint8_t x = (m_opcode & 0x0F00) >> 8; uint8_t & vx = m_v[x]; const uint8_t y = (m_opcode & 0x00F0) >> 4; uint8_t & vy = m_v[y]; const uint8_t n = m_opcode & 0x000F; const uint8_t nn = m_opcode & 0x00FF; const uint16_t nnn = m_opcode & 0x0FFF; // Decode opcode // https://en.wikipedia.org/wiki/CHIP-8#Opcode_table if (m_opcode == 0x00E0) { // 0x00E0: clear the screen CSaruCore::SecureZero(m_renderOut, s_renderWidth * s_renderHeight); m_pc += 2; m_drawFlag = true; } else if (m_opcode == 0x00EE) { // 0x00EE: return from call if (m_sp <= 0) { std::fprintf( stderr, "Chip8: stack underflow; pc {0x%04X}.", m_pc ); } else m_pc = m_stack[--m_sp] + 2; } /* else if ((m_opcode & 0xF000) == 0x0000) { // 0x0NNN // call RCA 1802 program at NNN // TODO : jump, or call? m_pc = nnn; } */ else if ((m_opcode & 0xF000) == 0x1000) { // 0x1NNN: jump to NNN m_pc = nnn; } else if ((m_opcode & 0xF000) == 0x2000) { // 0x2NNN: call NNN if (m_sp >= s_stackSize) { std::fprintf( stderr, "Chip8: stack overflow; pc {0x%04X}.", m_pc ); } else { m_stack[m_sp++] = m_pc; m_pc = m_opcode & 0x0FFF; } } else if ((m_opcode & 0xF000) == 0x3000) { // 0x3XNN // skip next instruction if VX == NN m_pc += (vx == nn) ? 4 : 2; } else if ((m_opcode & 0xF000) == 0x4000) { // 0x4XNN // skip next instruction if VX != NN m_pc += (vx != nn) ? 4 : 2; } else if ((m_opcode & 0xF000) == 0x6000) { // 0x6XNN: set VX to NN vx = nn; m_pc += 2; } else if ((m_opcode & 0xF000) == 0x7000) { // 0x7XNN: add NN to VX vx += nn; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8000) { // 0x8XY0: set VX to VY vx = vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8001) { // 0x8XY1: VX = VX | VY vx |= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8002) { // 0x8XY2: VX = VX & VY vx &= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8003) { // 0x8003: VX = VX ^ VY vx ^= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8004) { // 0x8XY4 // add VY to VX; VF is set to 1 on carry, 0 otherwise. m_v[0xF] = ((vx + vy) < vx) ? 1 : 0; vx += vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8005) { // 0x8XY5: VX -= VY // VF is set to 0 on borrow; 1 otherwise. m_v[0xF] = (vy > vx) ? 0 : 1; vx -= vy; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x8006) { // 0x8XY6 // VX >>= 1; VF = least-significant bit before shift m_v[0xF] = vx & 0x01; vx >>= 1; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x800E) { // 0x8XYE // VX <<= 1; VF = most-significant bit before shift m_v[0xF] = vx & 0x80; vx <<= 1; m_pc += 2; } else if ((m_opcode & 0xF00F) == 0x9000) { // 0x9XY0 // skip next instruction if VX != VY m_pc += (vx != vy) ? 4 : 2; } else if ((m_opcode & 0xF000) == 0xA000) { // 0xANNN: I = NNN m_i = nnn; m_pc += 2; } else if ((m_opcode & 0xF000) == 0xB000) { // 0xBNNN: jump to MMM + V0 m_pc = nnn + m_v[0]; } else if ((m_opcode & 0xF000) == 0xC000) { // 0xCXNN: VX = (rand & NN) // TODO : Replace with a per-Chip8 random number generator. vx = std::rand() & nn; m_pc += 2; } else if ((m_opcode & 0xF000) == 0xD000) { // 0xDXYN // XOR-draw N rows of 8-bit-wide sprites from I // at (VX, VY), (VX, VY+1), etc. // VF set to 1 if a pixel is toggled off, otherwise 0. m_v[0xF] = 0x0; // clear collision flag for (unsigned spriteTexY = 0; spriteTexY < n; ++spriteTexY) { const uint8_t spriteByte = m_memory[ m_i + spriteTexY ]; for (unsigned spriteTexX = 0; spriteTexX < 8; ++spriteTexX) { // shift b1000'0000 right to current column if (spriteByte & (0x80 >> spriteTexX)) { // rendering wraps on all edges uint16_t pixelX = (vx + spriteTexX) % s_renderWidth; uint16_t pixelY = ((vy + spriteTexY) % s_renderHeight) * s_renderWidth; auto & renderPixel = m_renderOut[pixelY + pixelX]; if (renderPixel) { renderPixel = 0; m_v[0xF] = 0x1; // collision! set flag } else { renderPixel = 1; } } } } m_pc += 2; m_drawFlag = true; } else if ((m_opcode & 0xF0FF) == 0xE09E) { // 0xEX9E // skip next instruction if key at VX is pressed m_pc += (m_keyStates[vx]) ? 4 : 2; } else if ((m_opcode & 0xF0FF) == 0xE0A1) { // 0xEXA1 // skip next instruction if key at VX isn't pressed m_pc += (!m_keyStates[vx]) ? 4 : 2; } else if ((m_opcode & 0xF0FF) == 0xF007) { // 0xFX07: VX = delay vx = m_delayTimer; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF00A) { // 0xFX0A // wait for key press, then store in VX for (uint8_t key = 0x0; key < s_keyCount; ++key) { if (m_keyStates[key]) { m_v[ (m_opcode & 0x0F00) >> 8 ] = key; m_pc += 2; } } } else if ((m_opcode & 0xF0FF) == 0xF015) { // 0xFX15: delay = VX m_delayTimer = vx; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF018) { // 0xFX18 m_soundTimer = vx; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF01E) { // 0xFX1E: I += VX // undocumented: VF = 1 on overflow; 0 otherwise // (used by "Spaceflight 2091!") m_v[0xF] = (m_i + vx < m_i) ? 1 : 0; m_i += vx; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF029) { // 0xFX29 // set I to location of character VX m_i = s_fontBegin + (0xF & vx) * 5; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF033) { // 0xFX33 // store binary-coded decimal representation of VX in memory // 100s digit at I, 10s at I+1, 1s at I+2 // (I unchanged) m_memory[ m_i ] = vx / 100; m_memory[ m_i+1 ] = (vx / 10) % 10; m_memory[ m_i+2 ] = (vx % 100) % 10; m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF055) { // 0xFX55 // store V0...VX in memory, starting at I for (uint8_t i = 0; i <= vx; ++i) m_memory[ m_i + i ] = m_v[i]; m_i += vx + 1; // From BYTE magazine code comment: (I = I + X + 1). m_pc += 2; } else if ((m_opcode & 0xF0FF) == 0xF065) { // 0xFX65 // fill V0 to VX from memory starting at I for (uint8_t i = 0; i <= x; ++i) m_v[i] = m_memory[m_i + i]; m_i += x + 1; // From BYTE magazine code comment: (I = I + X + 1). m_pc += 2; } else { std::fprintf( stderr, "Chip8: Bad opcode {0x%04X} at {0x%04X} ({0x%04X}).\n", m_opcode, m_pc, m_pc - s_progRomRamBegin ); } // Update timers if (m_delayTimer) --m_delayTimer; if (m_soundTimer) { CSaruCore::Beep(); // beep the PC speaker --m_soundTimer; // play sound if non-zero std::printf(" -- beep! -- \n"); // temporary } } //===================================================================== bool Chip8::LoadProgram (const char * path) { std::FILE * progFile = std::fopen(path, "rb"); if (!progFile) { std::fprintf(stderr, "Chip8: Failed to open program file at {%s}.\n", path); return false; } std::size_t readCount = std::fread( m_memory + s_progRomRamBegin, 1, /* size of element to read (in bytes) */ s_progRomRamEnd - s_progRomRamBegin, /* number of element to read */ progFile ); fclose(progFile); if (!readCount) { std::fprintf(stderr, "Chip8: Failed to read from program file {%s}.\n", path); return false; } return true; }
29.130814
86
0.518312
Akaito
bf2b753c4fde73e43ef8bae782b4a7954b1da8b3
106
cpp
C++
tutorials/learncpp.com#1.0#1/inheritance/multiple_inheritance/source3.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/inheritance/multiple_inheritance/source3.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/inheritance/multiple_inheritance/source3.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
int main() { WirelessAdaptor c54G(5442, 181742); cout << c54G.USBDevice::GetID(); return 0; }
15.142857
39
0.613208
officialrafsan
bf2c8bf4bc92893840806d84d0309123ed0e9d69
7,977
cpp
C++
src/renderer/resource_managers/model_manager.cpp
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
4
2017-10-04T11:38:48.000Z
2021-11-16T20:35:37.000Z
src/renderer/resource_managers/model_manager.cpp
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
4
2018-06-07T23:27:02.000Z
2018-10-18T12:19:57.000Z
src/renderer/resource_managers/model_manager.cpp
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
null
null
null
#include "model_manager.h" #include "core/file/blob.h" #include "core/parsing/json.h" #include "../renderer.h" namespace Veng { ResourceType Model::RESOURCE_TYPE("model"); static ResourceType MATERIAL_TYPE("material"); ModelManager::ModelManager(Allocator& allocator, FileSystem& fileSystem, DependencyManager* depManager) : ResourceManager(Model::RESOURCE_TYPE, allocator, fileSystem, depManager) {} ModelManager::~ModelManager() {} const char* const * ModelManager::GetSupportedFileExt() const { static const char* buffer[] = { "model" }; return buffer; } size_t ModelManager::GetSupportedFileExtCount() const { return 1; } void ModelManager::SetRenderSystem(RenderSystem* renderSystem) { m_renderSystem = renderSystem; } Resource* ModelManager::CreateResource() { Resource* res = NEW_OBJECT(m_allocator, Model)(m_allocator); return res; } void ModelManager::DestroyResource(Resource* resource) { Model* model = static_cast<Model*>(resource); for (Mesh& mesh : model->meshes) { m_renderSystem->DestroyMeshData(mesh.renderDataHandle); m_allocator.Deallocate(mesh.verticesData); m_allocator.Deallocate(mesh.indicesData); m_depManager->UnloadResource(MATERIAL_TYPE, static_cast<resourceHandle>(mesh.material)); } DELETE_OBJECT(m_allocator, model); } void ModelManager::ReloadResource(Resource* resource) { ASSERT2(false, "Not implemented yet"); } void ModelManager::ResourceLoaded(resourceHandle handle, InputBlob& data) { Model* model = static_cast<Model*>(GetResource(handle)); Mesh& mesh = model->meshes.PushBack(); mesh.type = Mesh::PrimitiveType::Triangles;//todo: read from mesh char errorBuffer[64] = { 0 }; JsonValue parsedJson; ASSERT(JsonParseError((char*)data.GetData(), &m_allocator, &parsedJson, errorBuffer)); ASSERT(JsonIsObject(&parsedJson)); JsonKeyValue* verticesData = JsonObjectFind(&parsedJson, "vertices"); if (verticesData != nullptr) { ASSERT(JsonIsObject(&verticesData->value)); JsonKeyValue* countJson = JsonObjectFind(&verticesData->value, "count"); ASSERT(countJson != nullptr && JsonIsInt(&countJson->value)); size_t count = (size_t)JsonGetInt(&countJson->value); if (count < MAX_U32) { mesh.verticesCount = (u32)count; } else { ASSERT2(false, "Too many vertices, limit is 2^32 - 1, clamped count to this number"); mesh.verticesCount = MAX_U32; } JsonKeyValue* positions = JsonObjectFind(&verticesData->value, "positions"); JsonKeyValue* colors = JsonObjectFind(&verticesData->value, "colors"); JsonKeyValue* texCoords = JsonObjectFind(&verticesData->value, "uvs"); JsonKeyValue* normals = JsonObjectFind(&verticesData->value, "normals"); JsonKeyValue* tangents = JsonObjectFind(&verticesData->value, "tangents"); JsonValue* positionArr = nullptr; JsonValue* colorsArr = nullptr; JsonValue* texCoordArr = nullptr; JsonValue* normalsArr = nullptr; JsonValue* tangentsArr = nullptr; size_t bufferSize = 0; if (positions != nullptr) { ASSERT(JsonIsArray(&positions->value) && JsonArrayCount(&positions->value) == count * 3); positionArr = JsonArrayBegin(&positions->value); bufferSize += 3 * count * sizeof(float); mesh.varyings |= ShaderVarying_Position; } if (colors != nullptr) { ASSERT(JsonIsArray(&colors->value) && JsonArrayCount(&colors->value) == count); colorsArr = JsonArrayBegin(&colors->value); bufferSize += 4 * count * sizeof(u8); mesh.varyings |= ShaderVarying_Color0; } if (texCoords != nullptr) { ASSERT(JsonIsArray(&texCoords->value) && JsonArrayCount(&texCoords->value) == count * 2); texCoordArr = JsonArrayBegin(&texCoords->value); bufferSize += 2 * count * sizeof(float); mesh.varyings |= ShaderVarying_Texcoords0; } if(normals != nullptr) { ASSERT(JsonIsArray(&normals->value) && JsonArrayCount(&normals->value) == count * 3); normalsArr = JsonArrayBegin(&normals->value); bufferSize += 3 * count * sizeof(float); mesh.varyings |= ShaderVarying_Normal; } if (tangents != nullptr) { ASSERT(JsonIsArray(&tangents->value) && JsonArrayCount(&tangents->value) == count * 3); tangentsArr = JsonArrayBegin(&tangents->value); bufferSize += 3 * count * sizeof(float); mesh.varyings |= ShaderVarying_Tangent; } mesh.verticesData = (u8*)m_allocator.Allocate(bufferSize, alignof(float)); u8* dataBuffer = mesh.verticesData; for (size_t i = 0; i < count; ++i) { if (positionArr != nullptr) { float* posBuffer = (float*)dataBuffer; *posBuffer = (float)JsonGetDouble(positionArr++); *(posBuffer + 1) = (float)JsonGetDouble(positionArr++); *(posBuffer + 2) = (float)JsonGetDouble(positionArr++); dataBuffer = (u8*)(posBuffer + 3); } if (colorsArr != nullptr) { u32* colBuffer = (u32*)dataBuffer; *colBuffer = (u32)JsonGetInt(colorsArr++); dataBuffer = (u8*)(colBuffer + 1); } if (texCoordArr != nullptr) { float* uvBuffer = (float*)dataBuffer; *uvBuffer = (float)JsonGetDouble(texCoordArr++); *(uvBuffer + 1) = (float)JsonGetDouble(texCoordArr++); dataBuffer = (u8*)(uvBuffer + 2); } if(normalsArr != nullptr) { float* normalBuffer = (float*)dataBuffer; *normalBuffer = (float)JsonGetDouble(normalsArr++); *(normalBuffer + 1) = (float)JsonGetDouble(normalsArr++); *(normalBuffer + 2) = (float)JsonGetDouble(normalsArr++); dataBuffer = (u8*)(normalBuffer + 3); } if (tangentsArr != nullptr) { float* tangentBuffer = (float*)dataBuffer; *tangentBuffer = (float)JsonGetDouble(tangentsArr++); *(tangentBuffer + 1) = (float)JsonGetDouble(tangentsArr++); *(tangentBuffer + 2) = (float)JsonGetDouble(tangentsArr++); dataBuffer = (u8*)(tangentBuffer + 3); } } } else { ASSERT2(false, "Missing vertex data"); mesh.verticesData = nullptr; } JsonKeyValue* indicesData = JsonObjectFind(&parsedJson, "indices"); if (indicesData != nullptr) { ASSERT(JsonIsObject(&indicesData->value)); JsonKeyValue* countJson = JsonObjectFind(&indicesData->value, "count"); ASSERT(countJson != nullptr && JsonIsInt(&countJson->value)); size_t count = (size_t)JsonGetInt(&countJson->value); if (count < MAX_U32) { mesh.indicesCount = (u32)count; } else { ASSERT2(false, "Too many indices, limit is 2^32 - 1, clamped count to this number"); mesh.indicesCount = MAX_U32; } count *= 3;//hard coded triangles here JsonKeyValue* indices = JsonObjectFind(&indicesData->value, "data"); ASSERT(JsonIsArray(&indices->value) && JsonArrayCount(&indices->value) == count); JsonValue* indexArr = JsonArrayBegin(&indices->value); mesh.indicesData = (u16*)m_allocator.Allocate(count * sizeof(u16), alignof(u16)); u16* dataBuffer = mesh.indicesData; for (size_t i = 0; i < count; ++i) { *dataBuffer = (u16)JsonGetInt(indexArr++); dataBuffer++; } } else { ASSERT2(false, "Missing indices"); mesh.indicesData = nullptr; } JsonKeyValue* material = JsonObjectFind(&parsedJson, "material"); if(material != nullptr) { ASSERT(JsonIsString(&material->value)); const char* materialRawStr = JsonGetString(&material->value); Path materialPath(materialRawStr); mesh.material = m_depManager->LoadResource(Model::RESOURCE_TYPE, MATERIAL_TYPE, materialPath); Resource* material = GetResource(mesh.material); if(material->GetState() == Resource::State::Ready || material->GetState() == Resource::State::Failure) { FinalizeModel(model); } } JsonDeinit(&parsedJson); mesh.renderDataHandle = m_renderSystem->CreateMeshData(mesh); } void ModelManager::ChildResourceLoaded(resourceHandle handle, ResourceType type) { for (auto& res : m_resources) { Model* model = static_cast<Model*>(res.value); if (model->meshes[0].material == handle) { FinalizeModel(model); } } } void ModelManager::FinalizeModel(Model* model) { model->SetState(Resource::State::Ready); m_depManager->ResourceLoaded(Model::RESOURCE_TYPE, GetResourceHandle(model)); } }
28.694245
104
0.701642
JakubLukas
bf2d73bf2b9cc2c1f7a96fdecad2f840fbd3ddb2
421
hpp
C++
source/ashes/renderer/TestRenderer/Command/Commands/TestBeginQueryCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/TestRenderer/Command/Commands/TestBeginQueryCommand.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/TestRenderer/Command/Commands/TestBeginQueryCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder */ #pragma once #include "renderer/TestRenderer/Command/Commands/TestCommandBase.hpp" namespace ashes::test { class BeginQueryCommand : public CommandBase { public: BeginQueryCommand( VkDevice device , VkQueryPool pool , uint32_t query , VkQueryControlFlags flags ); void apply()const override; CommandPtr clone()const override; }; }
17.541667
69
0.745843
DragonJoker
bf3166d2389ca3917d2b6707c9142288ae7209a1
9,289
inl
C++
Base/PLCore/include/PLCore/Container/HashMapKeyIterator.inl
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/include/PLCore/Container/HashMapKeyIterator.inl
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/include/PLCore/Container/HashMapKeyIterator.inl
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: HashMapKeyIterator.inl * * Hash map iterator template implementation * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLCore/Container/HashMap.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HashMapKeyIterator(const HashMap<KeyType, ValueType, Hasher, Comparer, Grower> &mapOwner, uint32 nIndex) : m_pmapOwner(&mapOwner), m_pNextSlot(nullptr), m_pPreviousSlot(nullptr) { // Is there at least one element within the hash map? (we do not need to check whether the slots are already created :) if (m_pmapOwner->GetNumOfElements()) { // Find start slot if (nIndex <= m_pmapOwner->GetNumOfElements()/2) { // Find the first slot for (m_nNextSlots=0; m_nNextSlots<m_pmapOwner->GetNumOfSlots(); m_nNextSlots++) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot) { // Ok, we found a slots list which has any slots within it m_pNextSlot = m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot; break; } } // Find the correct start slot m_nPreviousSlots = m_nNextSlots; m_pPreviousSlot = nullptr; uint32 nCurrentIndex = 0; while (HasNext() && nCurrentIndex < nIndex) { m_nPreviousSlots = m_nNextSlots; m_pPreviousSlot = m_pNextSlot; Next(); nCurrentIndex++; } } else { // Find the last slot m_nPreviousSlots = m_pmapOwner->GetNumOfSlots()-1; int nPreviousSlots = m_nPreviousSlots; for (; nPreviousSlots>=0; nPreviousSlots--) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot) { // Ok, we found a slots list which has any slots within it m_pPreviousSlot = m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot; break; } } m_nPreviousSlots = (nPreviousSlots < 0) ? 0 : nPreviousSlots; // Find the correct start slot m_nNextSlots = m_nPreviousSlots; m_pNextSlot = nullptr; uint32 nCurrentIndex = m_pmapOwner->GetNumOfElements()-1; while (HasPrevious() && nCurrentIndex > nIndex) { m_nNextSlots = m_nPreviousSlots; m_pNextSlot = m_pPreviousSlot; Previous(); nCurrentIndex--; } } } } /** * @brief * Constructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HashMapKeyIterator(const HashMap<KeyType, ValueType, Hasher, Comparer, Grower> &mapOwner) : m_pmapOwner(&mapOwner), m_pNextSlot(nullptr), m_pPreviousSlot(nullptr) { // Is there at least one element within the hash map? (we do not need to check whether the slots are already created :) if (m_pmapOwner->GetNumOfElements()) { // Find the last slot m_nPreviousSlots = m_pmapOwner->GetNumOfSlots()-1; int nPreviousSlots = m_nPreviousSlots; for (; nPreviousSlots>=0; nPreviousSlots--) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot) { // Ok, we found a slots list which has any slots within it m_pPreviousSlot = m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot; break; } } m_nPreviousSlots = (nPreviousSlots < 0) ? 0 : nPreviousSlots; // Find the correct start slot m_nNextSlots = m_nPreviousSlots; m_pNextSlot = nullptr; } } /** * @brief * Copy constructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HashMapKeyIterator(const HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower> &cSource) : m_pmapOwner(cSource.m_pmapOwner), m_nNextSlots(cSource.m_nNextSlots), m_pNextSlot(cSource.m_pNextSlot), m_nPreviousSlots(cSource.m_nPreviousSlots), m_pPreviousSlot(cSource.m_pPreviousSlot) { } /** * @brief * Destructor */ template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::~HashMapKeyIterator() { } //[-------------------------------------------------------] //[ Private virtual IteratorImpl functions ] //[-------------------------------------------------------] template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> IteratorImpl<KeyType> *HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::Clone() const { return new HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>(*this); } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> bool HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HasNext() const { return (m_pNextSlot != nullptr); } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> KeyType &HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::Next() { // Is there's a next slot? if (!m_pNextSlot) return HashMap<KeyType, ValueType, Hasher, Comparer, Grower>::NullKey; // Error! // Get the next slot m_nPreviousSlots = m_nNextSlots; m_pPreviousSlot = m_pNextSlot; m_pNextSlot = m_pNextSlot->pNextSlot; // Is there a next slot? if (!m_pNextSlot && m_nNextSlots < m_pmapOwner->GetNumOfSlots()-1) { // Ok, now it becomes a bit tricky... look for the next slots list which has any slots within it m_nNextSlots++; for (; m_nNextSlots<m_pmapOwner->GetNumOfSlots(); m_nNextSlots++) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot) { // Ok, we found a slots list which has any slots within it m_pNextSlot = m_pmapOwner->m_plstSlots[m_nNextSlots].m_pFirstSlot; break; } } } // Return the key of the 'current' slot return m_pPreviousSlot->Key; } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> bool HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::HasPrevious() const { return (m_pPreviousSlot != nullptr); } template <class KeyType, class ValueType, class Hasher, class Comparer, class Grower> KeyType &HashMapKeyIterator<KeyType, ValueType, Hasher, Comparer, Grower>::Previous() { // Is there's a previous slot? if (!m_pPreviousSlot) return HashMap<KeyType, ValueType, Hasher, Comparer, Grower>::NullKey; // Error! // Get the previous slot m_nNextSlots = m_nPreviousSlots; m_pNextSlot = m_pPreviousSlot; m_pPreviousSlot = m_pPreviousSlot->pPreviousSlot; // Is there a previous slot? if (!m_pPreviousSlot && m_nPreviousSlots > 0) { // Ok, now it becomes a bit tricky... look for the previous slots list which has any slots within it int nPreviousSlots; m_nPreviousSlots--; for (nPreviousSlots=m_nPreviousSlots; nPreviousSlots>=0; nPreviousSlots--) { // Are there any slots within this list? if (m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot) { // Ok, we found a slots list which has any slots within it m_pPreviousSlot = m_pmapOwner->m_plstSlots[nPreviousSlots].m_pLastSlot; break; } } m_nPreviousSlots = (nPreviousSlots < 0) ? 0 : nPreviousSlots; } // Return the key of the 'current' slot return m_pNextSlot->Key; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
37.760163
172
0.659705
ktotheoz
bf336c1c43956c888f5aec54109deeec9b052c61
4,196
cpp
C++
box2dweldjoint.cpp
folibis/qml-box2d
b564712492a2c5c9e8bdfbe2ba09a6e8cbbe7d54
[ "Zlib" ]
null
null
null
box2dweldjoint.cpp
folibis/qml-box2d
b564712492a2c5c9e8bdfbe2ba09a6e8cbbe7d54
[ "Zlib" ]
null
null
null
box2dweldjoint.cpp
folibis/qml-box2d
b564712492a2c5c9e8bdfbe2ba09a6e8cbbe7d54
[ "Zlib" ]
null
null
null
/* * box2dweldjoint.cpp * Copyright (c) 2011 Joonas Erkinheimo <joonas.erkinheimo@nokia.com> * * This file is part of the Box2D QML plugin. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "box2dweldjoint.h" #include "box2dworld.h" #include "box2dbody.h" Box2DWeldJoint::Box2DWeldJoint(QObject *parent) : Box2DJoint(parent), mWeldJoint(0), anchorsAuto(true) { } Box2DWeldJoint::~Box2DWeldJoint() { cleanup(world()); } float Box2DWeldJoint::referenceAngle() const { return mWeldJointDef.referenceAngle; } void Box2DWeldJoint::setReferenceAngle(float referenceAngle) { float referenceAngleRad = referenceAngle * b2_pi / -180; if (qFuzzyCompare(mWeldJointDef.referenceAngle, referenceAngleRad)) return; mWeldJointDef.referenceAngle = referenceAngleRad; emit referenceAngleChanged(); } float Box2DWeldJoint::frequencyHz() const { return mWeldJointDef.frequencyHz; } void Box2DWeldJoint::setFrequencyHz(float frequencyHz) { if (qFuzzyCompare(mWeldJointDef.frequencyHz, frequencyHz)) return; mWeldJointDef.frequencyHz = frequencyHz; if (mWeldJoint) mWeldJoint->SetFrequency(frequencyHz); emit frequencyHzChanged(); } float Box2DWeldJoint::dampingRatio() const { return mWeldJointDef.dampingRatio; } void Box2DWeldJoint::setDampingRatio(float dampingRatio) { if (qFuzzyCompare(mWeldJointDef.dampingRatio, dampingRatio)) return; mWeldJointDef.dampingRatio = dampingRatio; if (mWeldJoint) mWeldJoint->SetDampingRatio(dampingRatio); emit dampingRatioChanged(); } QPointF Box2DWeldJoint::localAnchorA() const { return QPointF(mWeldJointDef.localAnchorA.x * scaleRatio, -mWeldJointDef.localAnchorA.y * scaleRatio); } void Box2DWeldJoint::setLocalAnchorA(const QPointF &localAnchorA) { mWeldJointDef.localAnchorA = b2Vec2(localAnchorA.x() / scaleRatio,-localAnchorA.y() / scaleRatio); anchorsAuto = false; emit localAnchorAChanged(); } QPointF Box2DWeldJoint::localAnchorB() const { return QPointF(mWeldJointDef.localAnchorB.x * scaleRatio, -mWeldJointDef.localAnchorB.y * scaleRatio); } void Box2DWeldJoint::setLocalAnchorB(const QPointF &localAnchorB) { mWeldJointDef.localAnchorB = b2Vec2(localAnchorB.x() / scaleRatio,-localAnchorB.y() / scaleRatio); anchorsAuto = false; emit localAnchorBChanged(); } void Box2DWeldJoint::nullifyJoint() { mWeldJoint = 0; } void Box2DWeldJoint::createJoint() { if (anchorsAuto) mWeldJointDef.Initialize(bodyA()->body(), bodyB()->body(),bodyA()->body()->GetWorldCenter()); else { mWeldJointDef.bodyA = bodyA()->body(); mWeldJointDef.bodyB = bodyB()->body(); } mWeldJointDef.collideConnected = collideConnected(); mWeldJoint = static_cast<b2WeldJoint*> (world()->CreateJoint(&mWeldJointDef)); mWeldJoint->SetUserData(this); mInitializePending = false; emit created(); } void Box2DWeldJoint::cleanup(b2World *world) { if (!world) { qWarning() << "WeldJoint: There is no world connected"; return; } if (mWeldJoint && bodyA() && bodyB()) { mWeldJoint->SetUserData(0); world->DestroyJoint(mWeldJoint); mWeldJoint = 0; } } b2Joint *Box2DWeldJoint::joint() const { return mWeldJoint; }
27.070968
102
0.709009
folibis
bf342d66f2b1af88dfd27c9857a3b310ee6f330c
780
cpp
C++
Raven.CppClient.Tests/CanGetBuildNumberTest.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient.Tests/CanGetBuildNumberTest.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient.Tests/CanGetBuildNumberTest.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
#include "pch.h" #include "RavenTestDriver.h" #include "raven_test_definitions.h" #include "MaintenanceOperationExecutor.h" #include "GetBuildNumberOperation.h" namespace ravendb::client::tests::client::documents::commands { class CanGetBuildNumberTest : public driver::RavenTestDriver { protected: void customise_store(std::shared_ptr<ravendb::client::documents::DocumentStore> store) override { //store->set_before_perform(infrastructure::set_for_fiddler); } }; TEST_F(CanGetBuildNumberTest, CanGetBuildNumber) { auto store = get_document_store(TEST_NAME); auto build_number = store->maintenance()->server()->send(serverwide::operations::GetBuildNumberOperation()); ASSERT_TRUE(build_number); ASSERT_FALSE(build_number->product_version.empty()); } }
27.857143
110
0.778205
mlawsonca
bf37847469af68ebbe2355db500c70a8b26dd48b
1,818
hpp
C++
driver/utils/include/ethosn_utils/Span.hpp
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
4
2019-05-31T18:48:24.000Z
2019-06-04T07:59:39.000Z
driver/utils/include/ethosn_utils/Span.hpp
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
null
null
null
driver/utils/include/ethosn_utils/Span.hpp
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
null
null
null
// // Copyright © 2021-2022 Arm Limited. // SPDX-License-Identifier: Apache-2.0 // #pragma once #if (__cplusplus >= 202002L) || (_MSVC_LANG >= 202002L) #include <span> #else #include <array> #include <type_traits> #include <vector> namespace std { template <typename T> class span { public: constexpr span() noexcept = default; template <typename U> constexpr span(U* const data, const size_t size) noexcept : m_Data(data) , m_Size(size) { static_assert(std::is_same<std::remove_cv_t<U>, std::remove_cv_t<T>>::value, ""); } template <typename U, size_t N> constexpr span(const std::array<U, N>& array) noexcept : span(array.data(), N) {} template <typename U, size_t N> constexpr span(std::array<U, N>& array) noexcept : span(array.data(), N) {} template <typename U, size_t N> constexpr span(const U (&array)[N]) noexcept : span(array, N) {} template <typename U, size_t N> constexpr span(U (&array)[N]) noexcept : span(array, N) {} template <typename U> constexpr span(const std::vector<U>& vec) noexcept : span(vec.data(), vec.size()) {} template <typename U> constexpr span(std::vector<U>& vec) noexcept : span(vec.data(), vec.size()) {} constexpr auto data() const noexcept { return m_Data; } constexpr auto size() const noexcept { return m_Size; } constexpr auto begin() const noexcept { return m_Data; } constexpr auto end() const noexcept { return begin() + m_Size; } constexpr auto& operator[](const size_t i) const noexcept { return m_Data[i]; } private: T* m_Data{}; size_t m_Size{}; }; } // namespace std #endif
19.136842
89
0.590759
ARM-software
bf3a57b050c065e9002d643392f3301a907d5ba3
118,628
cpp
C++
src/mame/drivers/galaxold.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/galaxold.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/galaxold.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Nicola Salmoria,Stephane Humbert /*************************************************************************** Galaxian/Moon Cresta hardware NOTE: Eventually to be merged into GALAXIAN.CPP Main clock: XTAL = 18.432 MHz Z80 Clock: XTAL/6 = 3.072 MHz Horizontal video frequency: HSYNC = XTAL/3/192/2 = 16 kHz Video frequency: VSYNC = HSYNC/132/2 = 60.606060 Hz VBlank duration: 1/VSYNC * (20/132) = 2500 us Notes: ----- - The only code difference between 'galaxian' and 'galmidw' is that the 'BONUS SHIP' text is printed on a different line. TODO: ---- - Problems with Galaxian based on the observation of a real machine: - Starfield is incorrect. The speed and flashing frequency is fine, but the stars appear in different positions. - Background humming is incorrect. It's faster on a real machine - Explosion sound is much softer. Filter involved? - $4800-4bff in Streaking/Ghost Muncher Stephh's notes (based on the games Z80 code and some tests) for other games : 1) 'scramblb' and 'scramb2' - Player 2 controls are used for player 2 regardless of the "Cabinet" Dip Switch (check code at 0x1043 which changes player and routines that handle players inputs : 0x1741 UP and DOWN - 0x1796 LEFT and RIGHT - 0x24e6 BUTTON1 - 0x2615 BUTTON2). 2) 'tazzmang' - If you press COIN2 during the boot-up sequence, you enter sort of "test mode" where you can access to all inputs, but this doesn't give a clue about what they do (only the status - 0 or 1 - is displayed). - IN1 bit 0 has 2 effects : it starts a one player game (code at 0x5585), but it also acts as 2nd button (bomb) for BOTH players regardless of "Cabinet" settings (code at 0x5805 for player 1 and player 2 in "Upright" cabinet, or 0x5563 for player 2 in "Cocktail" cabinet). ***************************************************************************/ #include "emu.h" #include "includes/galaxold.h" #include "audio/galaxian.h" #include "cpu/z80/z80.h" #include "cpu/s2650/s2650.h" #include "machine/watchdog.h" #include "sound/sn76496.h" #include "speaker.h" /************************************* * * Constants * *************************************/ #define MASTER_CLOCK (XTAL(18'432'000)) #define PIXEL_CLOCK (MASTER_CLOCK/3) // H counts from 128->511, HBLANK starts at 128 and ends at 256 #define HTOTAL (384) #define HBEND (0) // (256) #define HBSTART (256) // (128) #define VTOTAL (264) #define VBEND (16) #define VBSTART (224+16) // Send sound data to the sound CPU and cause an NMI uint8_t galaxold_state::drivfrcg_port0_r() { switch (m_maincpu->pc()) { case 0x002e: case 0x0297: return 0x01; } return 0; } void galaxold_state::galaxold_map(address_map &map) { map(0x0000, 0x3fff).rom(); map(0x4000, 0x47ff).ram(); map(0x5000, 0x53ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x5400, 0x57ff).r(FUNC(galaxold_state::galaxold_videoram_r)); map(0x5800, 0x583f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x5840, 0x585f).ram().share("spriteram"); map(0x5860, 0x587f).ram().share("bulletsram"); map(0x5880, 0x58ff).ram(); map(0x6000, 0x6000).portr("IN0"); map(0x6000, 0x6001).w(FUNC(galaxold_state::galaxold_leds_w)); map(0x6002, 0x6002).w(FUNC(galaxold_state::galaxold_coin_lockout_w)); map(0x6003, 0x6003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x6004, 0x6007).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x6800, 0x6800).portr("IN1"); map(0x6800, 0x6802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0x6803, 0x6803).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); map(0x6805, 0x6805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0x6806, 0x6807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0x7000, 0x7000).portr("IN2"); map(0x7001, 0x7001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x7004, 0x7004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x7006, 0x7006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x7007, 0x7007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x7800, 0x7fff).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0x7800, 0x7800).w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0xfffc, 0xffff).ram(); } void galaxold_state::mooncrst_map(address_map &map) { map(0x0000, 0x5fff).rom(); map(0x8000, 0x87ff).ram(); map(0x9000, 0x93ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x9400, 0x97ff).r(FUNC(galaxold_state::galaxold_videoram_r)); map(0x9800, 0x983f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x9840, 0x985f).ram().share("spriteram"); map(0x9860, 0x987f).ram().share("bulletsram"); map(0x9880, 0x98ff).ram(); map(0xa000, 0xa000).portr("IN0"); map(0xa002, 0xa002).w(FUNC(galaxold_state::galaxold_gfxbank_w)); map(0xa003, 0xa003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0xa004, 0xa007).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0xa800, 0xa800).portr("IN1"); map(0xa800, 0xa802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0xa803, 0xa803).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); map(0xa805, 0xa805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0xa806, 0xa807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0xb000, 0xb000).portr("DSW0").w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0xb004, 0xb004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0xb006, 0xb006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0xb007, 0xb007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0xb800, 0xb800).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0xb800, 0xb800).w("cust", FUNC(galaxian_sound_device::pitch_w)); } void galaxold_state::hustlerb3_map(address_map &map) { map.unmap_value_high(); map(0x0000, 0x7fff).rom(); map(0x8000, 0x87ff).ram(); map(0x9000, 0x93ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x9800, 0x983f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x9840, 0x985f).ram().share("spriteram"); map(0x9860, 0x987f).ram().share("bulletsram"); map(0x9880, 0x98ff).ram(); map(0xb001, 0xb001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0xb006, 0xb006).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0xb007, 0xb007).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0xa000, 0xa000).portr("IN0"); map(0xa800, 0xa800).portr("IN1"); map(0xb000, 0xb000).portr("DSW0"); map(0xb800, 0xb800).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0xa004, 0xa007).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0xa800, 0xa802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0xa803, 0xa803).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); map(0xa805, 0xa805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0xa806, 0xa807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0xb800, 0xb800).w("cust", FUNC(galaxian_sound_device::pitch_w)); } void galaxold_state::scramblb_map(address_map &map) { map(0x0000, 0x3fff).rom(); map(0x4000, 0x47ff).ram(); map(0x4800, 0x4bff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x5000, 0x503f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x5040, 0x505f).ram().share("spriteram"); map(0x5060, 0x507f).ram().share("bulletsram"); map(0x5080, 0x50ff).ram(); map(0x6000, 0x6000).portr("IN0"); map(0x6000, 0x6001).nopw(); // sound triggers map(0x6003, 0x6003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x6004, 0x6007).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x6800, 0x6800).portr("IN1"); map(0x6800, 0x6802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0x6803, 0x6803).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); map(0x6805, 0x6805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0x6806, 0x6807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0x7000, 0x7000).portr("IN2"); map(0x7001, 0x7001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x7002, 0x7002).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x7003, 0x7003).w(FUNC(galaxold_state::scrambold_background_enable_w)); map(0x7004, 0x7004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x7006, 0x7006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x7007, 0x7007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x7800, 0x7800).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0x7800, 0x7800).w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0x8102, 0x8102).r(FUNC(galaxold_state::scramblb_protection_1_r)); map(0x8202, 0x8202).r(FUNC(galaxold_state::scramblb_protection_2_r)); } uint8_t galaxold_state::scramb2_protection_r(){ return 0x25; } uint8_t galaxold_state::scramb2_port0_r(offs_t offset){ return (ioport("IN0")->read() >> offset) & 0x1; } uint8_t galaxold_state::scramb2_port1_r(offs_t offset){ return (ioport("IN1")->read() >> offset) & 0x1; } uint8_t galaxold_state::scramb2_port2_r(offs_t offset){ return (ioport("IN2")->read() >> offset) & 0x1; } void galaxold_state::scramb_common_map(address_map &map) { map(0x0000, 0x3fff).rom(); map(0x4000, 0x47ff).ram(); map(0x4800, 0x4bff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x4c00, 0x4fff).w(FUNC(galaxold_state::galaxold_videoram_w)); // mirror map(0x5000, 0x503f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x5040, 0x505f).ram().share("spriteram"); map(0x5060, 0x507f).ram().share("bulletsram"); map(0x5080, 0x50ff).ram(); map(0x5800, 0x5fff).r(FUNC(galaxold_state::scramb2_protection_r)); // must return 0x25 map(0x6000, 0x6007).r(FUNC(galaxold_state::scramb2_port0_r)); // reads from 8 addresses, 1 bit per address map(0x6800, 0x6807).r(FUNC(galaxold_state::scramb2_port1_r)); // reads from 8 addresses, 1 bit per address map(0x6801, 0x6801).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x6804, 0x6804).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x6806, 0x6806).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x6807, 0x6807).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x7000, 0x7007).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0x7006, 0x7006).nopw(); map(0x7007, 0x7007).nopw(); map(0x7800, 0x7807).r(FUNC(galaxold_state::scramb2_port2_r)); // reads from 8 addresses, 1 bit per address map(0x7800, 0x7800).w("cust", FUNC(galaxian_sound_device::pitch_w)); } void galaxold_state::scramb2_map(address_map &map) { scramb_common_map(map); map(0x6802, 0x6802).w(FUNC(galaxold_state::galaxold_coin_counter_w)); } void galaxold_state::scramb3_map(address_map &map) { scramb_common_map(map); map(0x6003, 0x6003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); } uint8_t galaxold_state::scrambler_protection_2_r() { // if this doesn't return a value the code is happy with then it jumps out of ROM space after reading the port return 0xff; } // there are still unmapped reads / writes, it's not really clear what gets hooked up to where on these bootlegs, if they go anywhere at all void galaxold_state::scrambler_map(address_map &map) { map(0x0000, 0x3fff).rom(); map(0x4000, 0x47ff).ram(); map(0x4800, 0x4bff).ram(); // mirror, leftovers? map(0x5000, 0x53ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x5800, 0x587f).ram(); map(0x5880, 0x58bf).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x58c0, 0x58df).ram().share("spriteram"); map(0x58e0, 0x58ff).ram().share("bulletsram"); map(0x6000, 0x6000).portr("IN0"); map(0x6000, 0x6001).nopw(); // sound triggers map(0x6003, 0x6003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x6004, 0x6007).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x6800, 0x6800).portr("IN1"); map(0x6800, 0x6802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0x6803, 0x6803).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); // should this disable the stars too? map(0x6805, 0x6805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0x6806, 0x6807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0x7000, 0x7000).portr("IN2").w(FUNC(galaxold_state::galaxold_nmi_enable_w)); // map(0x7001, 0x7001) map(0x7002, 0x7002).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x7003, 0x7003).w(FUNC(galaxold_state::scrambold_background_enable_w)); map(0x7004, 0x7004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x7006, 0x7006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x7007, 0x7007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x7800, 0x7800).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0x7800, 0x7800).w("cust", FUNC(galaxian_sound_device::pitch_w)); // map(0x8102, 0x8102).r(FUNC(galaxold_state::scramblb_protection_1_r)); map(0x8202, 0x8202).r(FUNC(galaxold_state::scrambler_protection_2_r)); } void galaxold_state::scrambleo_map(address_map &map) { scrambler_map(map); map(0x7000, 0x7000).unmapw(); map(0x7001, 0x7001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); } void galaxold_state::_4in1_map(address_map &map) { map(0x0000, 0x3fff).bankr("bank1"); // banked game code map(0x4000, 0x47ff).ram(); map(0x5000, 0x53ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x5400, 0x57ff).r(FUNC(galaxold_state::galaxold_videoram_r)); map(0x5800, 0x583f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x5840, 0x585f).ram().share("spriteram"); map(0x5860, 0x587f).ram().share("bulletsram"); map(0x5880, 0x58ff).ram(); map(0x6000, 0x6000).portr("IN0"); map(0x6000, 0x6001).w(FUNC(galaxold_state::galaxold_leds_w)); // map(0x6002, 0x6002).w(FUNC(galaxold_state::galaxold_coin_lockout_w)); map(0x6003, 0x6003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x6004, 0x6007).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x6800, 0x6800).portr("IN1"); map(0x6800, 0x6802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); // map(0x6803, 0x6803).w(FUNC(galaxold_state::galaxian_noise_enable_w)); // not hooked up? map(0x6805, 0x6805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0x6806, 0x6807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0x7000, 0x7000).portr("DSW0"); map(0x7001, 0x7001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x7004, 0x7004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x7006, 0x7006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x7007, 0x7007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x7800, 0x78ff).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0x7800, 0x78ff).w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0x8000, 0x8000).w(FUNC(galaxold_state::_4in1_bank_w)); map(0xc000, 0xdfff).rom(); // fixed menu code } void galaxold_state::dkongjrm_map(address_map &map) { map(0x0000, 0x5fff).rom(); map(0x6000, 0x6fff).ram(); map(0x7000, 0x7fff).rom(); map(0x9000, 0x93ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x9800, 0x983f).w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x9840, 0x987f).writeonly().share("spriteram"); map(0x98c0, 0x98ff).writeonly().share("spriteram2"); map(0xa000, 0xa0ff).portr("IN0"); map(0xa003, 0xa003).w(FUNC(galaxold_state::galaxold_coin_counter_w)); //map(0xa004, 0xa007).w(FUNC(galaxold_state::galaxian_lfo_freq_w)); map(0xa800, 0xa8ff).portr("IN1"); map(0xa800, 0xa802).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0xa803, 0xa803).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); //map(0xa805, 0xa805).w(FUNC(galaxold_state::galaxian)); map(0xa806, 0xa807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0xb000, 0xb0ff).portr("DSW"); map(0xb000, 0xb000).w(FUNC(galaxold_state::galaxold_gfxbank_w)); map(0xb001, 0xb001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); //map(0xb004, 0xb004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0xb006, 0xb006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0xb007, 0xb007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0xb800, 0xb800).r("watchdog", FUNC(watchdog_timer_device::reset_r)).w("cust", FUNC(galaxian_sound_device::pitch_w)); } void galaxold_state::dkongjrmc_map(address_map &map) { map(0x0000, 0x5fff).rom(); map(0x6000, 0x6fff).ram(); map(0x7000, 0x70ff).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x7100, 0x71ff).ram().share("spriteram"); map(0x7400, 0x77ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x7800, 0x7800).portr("DSW"); map(0x7801, 0x7801).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x7802, 0x7802).w(FUNC(galaxold_state::galaxold_leds_w)); map(0x7804, 0x7804).w(FUNC(galaxold_state::galaxold_gfxbank_w)); map(0x7806, 0x7806).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x7807, 0x7807).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x7d00, 0x7d02).mirror(0x0080).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0x7d03, 0x7d03).mirror(0x0080).w("cust", FUNC(galaxian_sound_device::noise_enable_w)); map(0x7d05, 0x7d05).mirror(0x0080).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0x7d06, 0x7d07).mirror(0x0080).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0x8000, 0x8000).portr("IN0"); map(0x8100, 0x8100).portr("IN1"); map(0x8103, 0x8103).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x8104, 0x8107).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x8200, 0x8200).w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0x9000, 0x9fff).rom(); } void galaxold_state::tazzmang_map(address_map &map) { map(0x0000, 0x5fff).rom(); map(0x7000, 0x7000).portr("DSW0"); // mirror map(0x8000, 0x87ff).ram(); map(0x8800, 0x883f).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x8840, 0x885f).ram().share("spriteram"); map(0x8860, 0x887f).ram().share("bulletsram"); map(0x8880, 0x8bff).nopw(); map(0x9000, 0x93ff).ram().w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x9800, 0x9800).r("watchdog", FUNC(watchdog_timer_device::reset_r)); map(0xa000, 0xa000).portr("IN0"); map(0xa7ff, 0xa7ff).portr("IN0"); // mirror map(0xa800, 0xa800).portr("IN1").w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0xa803, 0xa803).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0xa805, 0xa805).w("cust", FUNC(galaxian_sound_device::fire_enable_w)); map(0xa806, 0xa807).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0xb000, 0xb000).portr("DSW0"); map(0xb001, 0xb001).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0xb004, 0xb004).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0xb006, 0xb006).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0xb007, 0xb007).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0xb800, 0xb800).r("watchdog", FUNC(watchdog_timer_device::reset_r)).w("cust", FUNC(galaxian_sound_device::pitch_w)); } void galaxold_state::hunchbkg_map(address_map &map) { map(0x0000, 0x0fff).rom(); map(0x1480, 0x14bf).mirror(0x6000).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x14c0, 0x14ff).mirror(0x6000).writeonly().share("spriteram"); map(0x1500, 0x1500).mirror(0x6000).portr("IN0"); map(0x1500, 0x1501).mirror(0x6000).w(FUNC(galaxold_state::galaxold_leds_w)); // not connected... map(0x1502, 0x1502).mirror(0x6000).w(FUNC(galaxold_state::galaxold_coin_lockout_w)); // not connected... map(0x1503, 0x1503).mirror(0x6000).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x1504, 0x1507).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x1580, 0x1580).mirror(0x6000).portr("IN1"); map(0x1580, 0x1587).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::sound_w)); map(0x1600, 0x1600).mirror(0x6000).portr("DSW0"); map(0x1601, 0x1601).mirror(0x6000).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x1604, 0x1604).mirror(0x6000).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x1606, 0x1606).mirror(0x6000).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x1607, 0x1607).mirror(0x6000).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x1680, 0x1680).mirror(0x6000).r("watchdog", FUNC(watchdog_timer_device::reset_r)).w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0x1800, 0x1bff).mirror(0x6000).w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x1c00, 0x1fff).mirror(0x6000).ram(); map(0x2000, 0x2fff).rom(); map(0x4000, 0x4fff).rom(); map(0x6000, 0x6fff).rom(); } // hunchbkg style void galaxold_state::spcwarp_map(address_map &map) { map(0x0000, 0x0fff).rom(); map(0x1480, 0x14bf).mirror(0x6000).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x14c0, 0x14ff).mirror(0x6000).writeonly().share("spriteram"); map(0x1500, 0x1500).mirror(0x6000).portr("IN0"); map(0x1500, 0x1501).mirror(0x6000).w(FUNC(galaxold_state::galaxold_leds_w)); map(0x1502, 0x1502).mirror(0x6000).w(FUNC(galaxold_state::galaxold_coin_lockout_w)); map(0x1503, 0x1503).mirror(0x6000).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x1504, 0x1507).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x1580, 0x1580).mirror(0x6000).portr("IN1"); map(0x1580, 0x1587).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::sound_w)); // everything else in the $16xx range is moved to $17xx map(0x1680, 0x1680).mirror(0x6000).r("watchdog", FUNC(watchdog_timer_device::reset_r)).w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0x1700, 0x1700).mirror(0x6000).portr("DSW0"); map(0x1701, 0x1701).mirror(0x6000).w(FUNC(galaxold_state::galaxold_nmi_enable_w)); map(0x1704, 0x1704).mirror(0x6000).w(FUNC(galaxold_state::galaxold_stars_enable_w)); map(0x1706, 0x1706).mirror(0x6000).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x1707, 0x1707).mirror(0x6000).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); // the rest map(0x1800, 0x1bff).mirror(0x6000).w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x1c00, 0x1fff).mirror(0x6000).ram(); map(0x2000, 0x2fff).rom(); map(0x4000, 0x4fff).rom(); map(0x6000, 0x6fff).rom(); } void galaxold_state::hunchbkg_data(address_map &map) { map(S2650_DATA_PORT, S2650_DATA_PORT).nopr(); // not used } void galaxold_state::drivfrcg_program(address_map &map) { map(0x0000, 0x0fff).rom(); map(0x1480, 0x14bf).mirror(0x6000).w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x14c0, 0x14ff).mirror(0x6000).writeonly().share("spriteram"); map(0x1500, 0x1500).mirror(0x6000).portr("IN0"); map(0x1503, 0x1503).mirror(0x6000).w(FUNC(galaxold_state::galaxold_coin_counter_w)); map(0x1580, 0x1580).mirror(0x6000).portr("IN1"); map(0x1580, 0x1582).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::background_enable_w)); map(0x1583, 0x1583).mirror(0x6000).nopw(); map(0x1585, 0x1585).mirror(0x6000).nopw(); map(0x1586, 0x1587).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::lfo_freq_w)); map(0x1600, 0x1600).mirror(0x6000).portr("DSW0").w("cust", FUNC(galaxian_sound_device::pitch_w)); map(0x1700, 0x1700).mirror(0x6000).portr("DSW1").nopw(); map(0x1701, 0x1701).mirror(0x6000).nopw(); map(0x1704, 0x1707).mirror(0x6000).w("cust", FUNC(galaxian_sound_device::vol_w)); map(0x1800, 0x1bff).mirror(0x6000).w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x1c00, 0x1fff).mirror(0x6000).ram(); map(0x2000, 0x2fff).rom(); map(0x4000, 0x4fff).rom(); map(0x6000, 0x6fff).rom(); } void galaxold_state::drivfrcg_io(address_map &map) { map(0x00, 0x00).r(FUNC(galaxold_state::drivfrcg_port0_r)); } void galaxold_state::racknrol_map(address_map &map) { map(0x0000, 0x0fff).rom(); map(0x1400, 0x143f).mirror(0x6000).ram().w(FUNC(galaxold_state::galaxold_attributesram_w)).share("attributesram"); map(0x1440, 0x14bf).mirror(0x6000).ram().share("spriteram"); map(0x14c0, 0x14ff).mirror(0x6000).ram(); map(0x1500, 0x1500).mirror(0x6000).portr("IN0"); map(0x1580, 0x1580).mirror(0x6000).portr("IN1"); map(0x1600, 0x1600).mirror(0x6000).portr("DSW0"); map(0x1600, 0x1601).mirror(0x6000).nopw(); map(0x1606, 0x1606).mirror(0x6000).w(FUNC(galaxold_state::galaxold_flip_screen_x_w)); map(0x1607, 0x1607).mirror(0x6000).w(FUNC(galaxold_state::galaxold_flip_screen_y_w)); map(0x1680, 0x1680).mirror(0x6000).nopr(); // map(0x1700, 0x1700).mirror(0x6000).r(FUNC(galaxold_state::trvchlng_question_r)); // map(0x1701, 0x1703).mirror(0x6000).w(FUNC(galaxold_state::trvchlng_question_w)); map(0x1800, 0x1bff).mirror(0x6000).w(FUNC(galaxold_state::galaxold_videoram_w)).share("videoram"); map(0x1c00, 0x1fff).mirror(0x6000).ram(); map(0x2000, 0x2fff).rom(); map(0x4000, 0x4fff).rom(); map(0x6000, 0x6fff).rom(); } void galaxold_state::racknrol_io(address_map &map) { map(0x1d, 0x1d).w("snsnd", FUNC(sn76489a_device::write)); // map(0x1e, 0x1e).nopw(); // map(0x1f, 0x1f).nopw(); map(0x20, 0x3f).w(FUNC(galaxold_state::racknrol_tiles_bank_w)).share("racknrol_tbank"); } uint8_t galaxold_state::hexpoola_data_port_r() { switch (m_maincpu->pc()) { case 0x0022: return 0; case 0x0031: return 1; } return 0; } void galaxold_state::hexpoola_io(address_map &map) { map(0x00, 0x00).nopr(); map(0x20, 0x3f).w(FUNC(galaxold_state::racknrol_tiles_bank_w)).share("racknrol_tbank"); } void galaxold_state::hexpoola_data(address_map &map) { map(S2650_DATA_PORT, S2650_DATA_PORT).r(FUNC(galaxold_state::hexpoola_data_port_r)).w("snsnd", FUNC(sn76496_device::write)); } uint8_t galaxold_state::bullsdrtg_data_port_r() { switch (m_maincpu->pc()) { case 0x0083: case 0x008c: case 0x0092: case 0x6b54: return 0; case 0x009b: case 0x6b58: return 1; default: logerror("Reading data port at PC=%04X\n", m_maincpu->pc()); break; } return 0; } void galaxold_state::bullsdrtg_data_map(address_map &map) { map(S2650_DATA_PORT, S2650_DATA_PORT).r(FUNC(galaxold_state::bullsdrtg_data_port_r)).w("snsnd", FUNC(sn76496_device::write)); } // Lives Dips are spread across two input ports template <int Mask> READ_LINE_MEMBER(galaxold_state::vpool_lives_r) { switch (Mask) { case 0x40: // vpool : IN1 (0xa800) bit 6 return ((ioport("LIVES")->read() & Mask) >> 6); case 0x01: // vpool : DSW (0xb000) bit 0 return ((ioport("LIVES")->read() & Mask) >> 0); default: logerror("vpool_lives_r : invalid %02X bit_mask\n",Mask); return 0; } } // verified from Z80 code static INPUT_PORTS_START( vpool ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_SERVICE1 ) // uses same coinage as COIN1 and COIN2 PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, vpool_lives_r<0x40>) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("DSW0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, vpool_lives_r<0x01>) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x02, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_2C ) ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("LIVES") PORT_DIPNAME( 0x41, 0x01, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x41, "1" ) PORT_DIPSETTING( 0x40, "2" ) PORT_DIPSETTING( 0x01, "3" ) PORT_DIPSETTING( 0x00, "Infinite (Cheat)" ) // also gives 99 credits after coin insertion regardless of coinage INPUT_PORTS_END static INPUT_PORTS_START( hustlerb3 ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) // 6-pos dipswitch on mainboard K4 PORT_DIPNAME( 0x40, 0x00, "Half Coinage" ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x80, DEF_STR( Cocktail ) ) PORT_START("DSW0") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x40) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x00) PORT_DIPSETTING( 0x01, DEF_STR( 1C_3C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x40) PORT_DIPSETTING( 0x01, DEF_STR( 1C_6C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x00) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x40) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x00) PORT_DIPSETTING( 0x02, DEF_STR( 1C_3C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x40) PORT_DIPSETTING( 0x02, DEF_STR( 1C_6C ) ) PORT_CONDITION("IN1", 0x40, EQUALS, 0x00) PORT_DIPNAME( 0x0c, 0x08, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "1" ) PORT_DIPSETTING( 0x04, "2" ) PORT_DIPSETTING( 0x08, "3" ) PORT_DIPSETTING( 0x0c, "Infinite (Cheat)" ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) INPUT_PORTS_END static INPUT_PORTS_START( froggerv ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_COCKTAIL PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) // 6-pos dipswitch on mainboard K4 PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown )) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x80, DEF_STR( Cocktail ) ) PORT_START("DSW0") PORT_DIPNAME( 0x03, 0x01, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x01, "5" ) PORT_DIPSETTING( 0x02, "7" ) PORT_DIPSETTING( 0x03, "256 (Cheat)" ) PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x04, "A 2/1 B 2/1" ) PORT_DIPSETTING( 0x08, "A 2/1 B 1/3" ) PORT_DIPSETTING( 0x00, "A 1/1 B 1/1" ) PORT_DIPSETTING( 0x0c, "A 1/1 B 1/6" ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) INPUT_PORTS_END // verified from Z80 code static INPUT_PORTS_START( scramblb ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x40, DEF_STR( Cocktail ) ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_START("IN2") PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 1C_4C ) ) PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x04, "4" ) PORT_DIPSETTING( 0x08, "5" ) PORT_DIPSETTING( 0x0c, "255 (Cheat)") PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) INPUT_PORTS_END // verified from Z80 code static INPUT_PORTS_START( scramb2 ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_SERVICE1 ) // uses same coinage as COIN1 PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_START("IN1") PORT_DIPNAME( 0x03, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x01, "4" ) PORT_DIPSETTING( 0x02, "5" ) PORT_DIPSETTING( 0x03, "255 (Cheat)") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_DIPNAME( 0x06, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, "A 1/1 B 2/1" ) PORT_DIPSETTING( 0x02, "A 1/2 B 1/1" ) PORT_DIPSETTING( 0x04, "A 1/3 B 3/1" ) PORT_DIPSETTING( 0x06, "A 1/4 B 4/1" ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x08, DEF_STR( Cocktail ) ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) INPUT_PORTS_END static INPUT_PORTS_START( scrambler ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_COCKTAIL PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_START("IN1") // cocktail mode inputs conflict with player 1 inputs, either wiring would be attached to the same bit as the flipscreen, or this set never worked in cocktail mode PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(1) // also ends up being P2 left in cocktail mode PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) // also ends up being P2 right in cocktail mode PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_COCKTAIL PORT_DIPNAME( 0xc0, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, "A 1/1 B 1/6" ) PORT_DIPSETTING( 0x40, "A 2/1 B 1/3" ) PORT_DIPSETTING( 0x80, "A 1/2 B 1/6" ) PORT_DIPSETTING( 0xc0, "A 2/2 B 1/3" ) PORT_START("IN2") PORT_DIPNAME( 0x03, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x01, "4" ) PORT_DIPSETTING( 0x02, "5" ) PORT_DIPSETTING( 0x03, "255 (Cheat)") PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x04, DEF_STR( Cocktail ) ) // probably unused PORT_DIPNAME( 0x08, 0x08, "IN4:3" ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, "IN4:4" ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, "IN4:5" ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "IN4:6" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "IN4:7" ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END static INPUT_PORTS_START( scrambleo ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_COCKTAIL PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_NAME("P1 Button 1 / Start 1") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_NAME("P1 Button 2 / Start 2") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_COCKTAIL PORT_DIPNAME( 0xc0, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, "A 1/1 B 1/6" ) PORT_DIPSETTING( 0x40, "A 2/1 B 1/3" ) PORT_DIPSETTING( 0x80, "A 1/2 B 1/6" ) PORT_DIPSETTING( 0xc0, "A 2/2 B 1/3" ) PORT_START("IN2") PORT_DIPNAME( 0x03, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x01, "4" ) PORT_DIPSETTING( 0x02, "5" ) PORT_DIPSETTING( 0x03, "255 (Cheat)") PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x04, DEF_STR( Cocktail ) ) // probably unused PORT_DIPNAME( 0x08, 0x08, "IN4:3" ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, "IN4:4" ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, "IN4:5" ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "IN4:6" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "IN4:7" ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END template <int Mask> READ_LINE_MEMBER(galaxold_state::_4in1_fake_port_r) { static const char *const portnames[] = { "FAKE1", "FAKE2", "FAKE3", "FAKE4" }; return (ioport(portnames[m__4in1_bank])->read() & Mask) ? 1 : 0; } static INPUT_PORTS_START( 4in1 ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x20, DEF_STR( Cocktail ) ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x40>) // See fake ports PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x80>) // See fake ports PORT_START("DSW0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x01>) // See fake ports PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x02>) // See fake ports PORT_DIPNAME( 0x04, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) // 2 when continue (Scramble PT2) PORT_DIPSETTING( 0x04, "5" ) // 2 when continue (Scramble PT2) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x08>) // See fake ports PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x10>) // See fake ports PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(galaxold_state, _4in1_fake_port_r<0x20>) // fake ports PORT_BIT( 0xc0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("FAKE1") // The Ghost Muncher PT3 - FAKE DSW0 (bits 0 to 5) and IN1 (bits 6 and 7) PORT_DIPNAME( 0x03, 0x00, "Bonus Life (GM PT3)" ) PORT_DIPSETTING( 0x01, "10000" ) PORT_DIPSETTING( 0x02, "15000" ) PORT_DIPSETTING( 0x03, "20000" ) PORT_DIPSETTING( 0x00, DEF_STR( None ) ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_CUSTOM ) // Lives // PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x08, DEF_STR( On ) ) // PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x10, DEF_STR( On ) ) // PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0xc0, 0x00, "Coinage (GM PT3)" ) PORT_DIPSETTING( 0x40, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( Free_Play ) ) PORT_START("FAKE2") // Scramble PT2 - FAKE DSW0 (bits 0 to 5) and IN1 (bits 6 and 7) // PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x01, DEF_STR( On ) ) // PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_CUSTOM ) // Lives PORT_DIPNAME( 0x08, 0x00, "Allow Continue (S PT2)" ) PORT_DIPSETTING( 0x08, DEF_STR( No ) ) PORT_DIPSETTING( 0x00, DEF_STR( Yes ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) // Scramble PT2 - Check code at 0x00c2 PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) // Scramble PT2 - Check code at 0x00cc PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0xc0, 0x00, "Coinage (S PT2)" ) PORT_DIPSETTING( 0x40, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( Free_Play ) ) PORT_START("FAKE3") // Galaxian PT5 - FAKE DSW0 (bits 0 to 5) and IN1 (bits 6 and 7) PORT_DIPNAME( 0x03, 0x00, "Bonus Life (G PT5)" ) PORT_DIPSETTING( 0x01, "4000" ) PORT_DIPSETTING( 0x02, "5000" ) PORT_DIPSETTING( 0x03, "7000" ) PORT_DIPSETTING( 0x00, DEF_STR( None ) ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_CUSTOM ) // Lives // PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x08, DEF_STR( On ) ) // PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x10, DEF_STR( On ) ) // PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0xc0, 0x00, "Coinage (G PT5)" ) PORT_DIPSETTING( 0x40, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) // PORT_DIPSETTING( 0x80, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( Free_Play ) ) PORT_START("FAKE4") // Galactic Convoy - FAKE DSW0 (bits 0 to 5) and IN1 (bits 6 and 7) PORT_DIPNAME( 0x01, 0x00, "Bonus Life (GC)" ) PORT_DIPSETTING( 0x00, "50000" ) PORT_DIPSETTING( 0x01, "80000" ) // PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_CUSTOM ) // Lives // PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x08, DEF_STR( On ) ) // PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x10, DEF_STR( On ) ) // PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unused ) ) // PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0xc0, 0x00, "Coinage (GC)" ) PORT_DIPSETTING( 0x40, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) // PORT_DIPSETTING( 0x80, DEF_STR( 2C_1C ) ) // 1 credit for 1st coin ! PORT_DIPSETTING( 0xc0, DEF_STR( Free_Play ) ) INPUT_PORTS_END // Coinage Dips are spread across two input ports template <int Mask> CUSTOM_INPUT_MEMBER(galaxold_state::dkongjrm_coinage_r) { switch (Mask) { case 0xc0: // dkongjrm : IN1 (0xa8??) bits 6 and 7 return ((ioport("COINAGE")->read() & Mask) >> 6); case 0x01: // dkongjrm : DSW (0xb0??) bit 0 return ((ioport("COINAGE")->read() & Mask) >> 0); default: logerror("dkongjrm_coinage_r : invalid %02X bit_mask\n",Mask); return 0; } } // verified from Z80 code static INPUT_PORTS_START( dkongjrm ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_4WAY PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0xc0, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(galaxold_state, dkongjrm_coinage_r<0xc0>) PORT_START("DSW") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_CUSTOM_MEMBER(galaxold_state, dkongjrm_coinage_r<0x01>) PORT_DIPNAME( 0x06, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x02, "4" ) PORT_DIPSETTING( 0x04, "5" ) PORT_DIPSETTING( 0x06, "6" ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x08, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("COINAGE") PORT_DIPNAME( 0xc1, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0xc1, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x41, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x40, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x81, DEF_STR( 1C_4C ) ) INPUT_PORTS_END static INPUT_PORTS_START( dkongjrmc ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_4WAY PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_4WAY PORT_COCKTAIL PORT_DIPNAME( 0xc0, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x40, "4" ) PORT_DIPSETTING( 0x80, "5" ) PORT_DIPSETTING( 0xc0, "6" ) PORT_START("DSW") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x00, "10000" ) PORT_DIPSETTING( 0x02, "20000" ) PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_3C ) ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) INPUT_PORTS_END // verified from Z80 code static INPUT_PORTS_START( tazzmang ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_NAME("Start 1 / P1 and P2 Button 2") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL PORT_DIPNAME( 0x40, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x80, "5" ) PORT_START("DSW0") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x01, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x06, 0x04, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, "A 4C/1C B 1C/4C" ) PORT_DIPSETTING( 0x02, "A 3C/1C B 1C/3C" ) PORT_DIPSETTING( 0x06, "A 2C/1C B 1C/2C" ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_1C ) ) PORT_DIPUNUSED( 0x08, IP_ACTIVE_LOW ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) INPUT_PORTS_END static INPUT_PORTS_START( hunchbkg ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED ) // labeled "NOT USED" in galaxian schematics PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_NAME("P2 Down") PORT_COCKTAIL PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_NAME("P1 Down") PORT_PLAYER(1) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_NAME("P1 Start/Red") PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_NAME("P2 Start/Red") PORT_COCKTAIL PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_COCKTAIL PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED ) // labeled "TABLE" in galaxian schematics PORT_DIPNAME( 0x40, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x40, "A 2C/1C B 1C/3C" ) PORT_DIPSETTING( 0x00, "A 1C/1C B 1C/5C" ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x80, "3" ) PORT_DIPSETTING( 0x00, "5" ) PORT_START("DSW0") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x01, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x06, 0x00, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x00, "10000" ) PORT_DIPSETTING( 0x02, "20000" ) PORT_DIPSETTING( 0x04, "40000" ) PORT_DIPSETTING( 0x06, "80000" ) PORT_DIPUNUSED( 0x08, 0x00 ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) INPUT_PORTS_END static INPUT_PORTS_START( drivfrcg ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x40, "A 2C/1C B 1C/3C" ) PORT_DIPSETTING( 0x00, "A 1C/1C B 1C/5C" ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START("DSW0") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x08, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) PORT_START("DSW1") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x08, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) INPUT_PORTS_END static INPUT_PORTS_START( racknrol ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_8WAY PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x08, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) PORT_START("DSW0") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x08, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) INPUT_PORTS_END static INPUT_PORTS_START( trvchlng ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON4) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x08, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) PORT_START("DSW0") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x08, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) INPUT_PORTS_END static const gfx_layout galaxold_charlayout = { 8,8, RGN_FRAC(1,2), 2, { RGN_FRAC(0,2), RGN_FRAC(1,2) }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 }; static const gfx_layout galaxold_spritelayout = { 16,16, RGN_FRAC(1,2), 2, { RGN_FRAC(0,2), RGN_FRAC(1,2) }, { 0, 1, 2, 3, 4, 5, 6, 7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8 }, 32*8 }; #if 0 static const gfx_layout pacmanbl_spritelayout = { 16,16, 64, 2, { 0, 64*16*16 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8 }, 32*8 }; #endif static const gfx_layout _4in1_charlayout = { 8,8, 1024, 2, { 0, 1024*8*8 }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 }; static const gfx_layout _4in1_spritelayout = { 16,16, 256, 2, { 0, 256*16*16 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8 }, 32*8 }; static GFXDECODE_START( gfx_galaxian ) GFXDECODE_ENTRY( "gfx1", 0x0000, galaxold_charlayout, 0, 8 ) GFXDECODE_ENTRY( "gfx1", 0x0000, galaxold_spritelayout, 0, 8 ) GFXDECODE_END static GFXDECODE_START( gfx_gmgalax ) GFXDECODE_ENTRY( "gfx1", 0x0000, galaxold_charlayout, 0, 16 ) GFXDECODE_ENTRY( "gfx1", 0x0000, galaxold_spritelayout, 0, 16 ) GFXDECODE_END static GFXDECODE_START( gfx_4in1 ) GFXDECODE_ENTRY( "gfx1", 0x0000, _4in1_charlayout, 0, 8 ) GFXDECODE_ENTRY( "gfx1", 0x4000, _4in1_spritelayout, 0, 8 ) GFXDECODE_END void galaxold_state::galaxold_base(machine_config &config) { // basic machine hardware Z80(config, m_maincpu, PIXEL_CLOCK/2); // 3.072 MHz m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::galaxold_map); MCFG_MACHINE_RESET_OVERRIDE(galaxold_state,galaxold) TTL7474(config, m_7474_9m_1, 0); m_7474_9m_1->output_cb().set(FUNC(galaxold_state::galaxold_7474_9m_1_callback)); TTL7474(config, m_7474_9m_2, 0); m_7474_9m_2->comp_output_cb().set(FUNC(galaxold_state::galaxold_7474_9m_2_q_callback)); TIMER(config, "int_timer").configure_generic(FUNC(galaxold_state::galaxold_interrupt_timer)); WATCHDOG_TIMER(config, "watchdog"); // video hardware GFXDECODE(config, m_gfxdecode, m_palette, gfx_galaxian); PALETTE(config, m_palette, FUNC(galaxold_state::galaxold_palette), 32+2+64); // 32 for the characters, 2 for the bullets, 64 for the stars SCREEN(config, m_screen, SCREEN_TYPE_RASTER); m_screen->set_raw(PIXEL_CLOCK, HTOTAL, HBEND, HBSTART, VTOTAL, VBEND, VBSTART); m_screen->set_screen_update(FUNC(galaxold_state::screen_update_galaxold)); m_screen->set_palette(m_palette); MCFG_VIDEO_START_OVERRIDE(galaxold_state,galaxold) // sound hardware SPEAKER(config, "speaker").front_center(); } void galaxold_state::galaxian_audio(machine_config &config) { GALAXIAN_SOUND(config, "cust", 0); } void galaxold_state::mooncrst_audio(machine_config &config) { MOONCRST_SOUND(config, "cust", 0); } void galaxold_state::galaxian(machine_config &config) { galaxold_base(config); // basic machine hardware // sound hardware galaxian_audio(config); } void galaxold_state::mooncrst(machine_config &config) { galaxold_base(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::mooncrst_map); // video hardware MCFG_VIDEO_START_OVERRIDE(galaxold_state,mooncrst) // sound hardware mooncrst_audio(config); } // 'Videotron' // this is a 'cartridge' based system, taking plug-in game boards. // a large sub-PCB actually contains an additional Z80 and AY8910 (with a socket for another AY8910) // but neither of the games we have (froggerv and hustlerb3) make use of either. There are a number // of unpopulated positions on the game board which presumably can be populated with code for the // 2nd Z80. void galaxold_state::videotron(machine_config &config) { galaxian(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::hustlerb3_map); // video hardware MCFG_VIDEO_START_OVERRIDE(galaxold_state,mooncrst) } void galaxold_state::scramblb(machine_config &config) { galaxian(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::scramblb_map); // video hardware m_palette->set_entries(32+2+64+1); // 32 for the characters, 2 for the bullets, 64 for the stars, 1 for background m_palette->set_init(FUNC(galaxold_state::scrambold_palette)); MCFG_VIDEO_START_OVERRIDE(galaxold_state,scrambold) } void galaxold_state::scramb2(machine_config &config) { galaxian(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::scramb2_map); // video hardware m_palette->set_entries(32+2+64+1); // 32 for the characters, 2 for the bullets, 64 for the stars, 1 for background m_palette->set_init(FUNC(galaxold_state::scrambold_palette)); MCFG_VIDEO_START_OVERRIDE(galaxold_state,scrambold) } void galaxold_state::scramb3(machine_config &config) { scramb2(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::scramb3_map); } void galaxold_state::scrambler(machine_config &config) { galaxian(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::scrambler_map); // video hardware m_palette->set_entries(32+2+64+1); // 32 for the characters, 2 for the bullets, 64 for the stars, 1 for background m_palette->set_init(FUNC(galaxold_state::scrambold_palette)); MCFG_VIDEO_START_OVERRIDE(galaxold_state,scrambold) } void galaxold_state::scrambleo(machine_config &config) { scrambler(config); m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::scrambleo_map); } void galaxold_state::_4in1(machine_config &config) { galaxian(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::_4in1_map); // video hardware m_gfxdecode->set_info(gfx_4in1); MCFG_VIDEO_START_OVERRIDE(galaxold_state,pisces) } void galaxold_state::dkongjrm(machine_config &config) { mooncrst(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::dkongjrm_map); // video hardware MCFG_VIDEO_START_OVERRIDE(galaxold_state,dkongjrm) } void galaxold_state::dkongjrmc(machine_config &config) { mooncrst(config); m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::dkongjrmc_map); MCFG_VIDEO_START_OVERRIDE(galaxold_state,dkongjrmc) } void galaxold_state::drivfrcg(machine_config &config) { // basic machine hardware s2650_device &maincpu(S2650(config, m_maincpu, MASTER_CLOCK/6)); maincpu.set_addrmap(AS_PROGRAM, &galaxold_state::drivfrcg_program); maincpu.set_addrmap(AS_IO, &galaxold_state::drivfrcg_io); maincpu.sense_handler().set("screen", FUNC(screen_device::vblank)); // ??? maincpu.intack_handler().set(FUNC(galaxold_state::hunchbkg_intack)); // video hardware SCREEN(config, m_screen, SCREEN_TYPE_RASTER); m_screen->set_refresh_hz(16000.0/132/2); m_screen->set_vblank_time(ATTOSECONDS_IN_USEC(2500)); // not accurate m_screen->set_size(32*8, 32*8); m_screen->set_visarea(0*8, 32*8-1, 2*8, 30*8-1); m_screen->set_screen_update(FUNC(galaxold_state::screen_update_galaxold)); m_screen->set_palette(m_palette); m_screen->screen_vblank().set_inputline(m_maincpu, 0, ASSERT_LINE); PALETTE(config, m_palette, FUNC(galaxold_state::s2650_palette), 64); GFXDECODE(config, m_gfxdecode, m_palette, gfx_gmgalax); MCFG_VIDEO_START_OVERRIDE(galaxold_state,drivfrcg) // sound hardware SPEAKER(config, "speaker").front_center(); galaxian_audio(config); } void galaxold_state::hunchbkg(machine_config &config) { galaxold_base(config); // basic machine hardware s2650_device &s2650(S2650(config.replace(), m_maincpu, PIXEL_CLOCK / 4)); s2650.set_addrmap(AS_PROGRAM, &galaxold_state::hunchbkg_map); s2650.set_addrmap(AS_DATA, &galaxold_state::hunchbkg_data); s2650.intack_handler().set(FUNC(galaxold_state::hunchbkg_intack)); // the NMI line seems to be inverted on the CPU plugin board m_7474_9m_1->comp_output_cb().set_inputline("maincpu", S2650_SENSE_LINE); MCFG_MACHINE_RESET_OVERRIDE(galaxold_state,hunchbkg) galaxian_audio(config); } void galaxold_state::spcwarp(machine_config &config) { hunchbkg(config); // hunchbkg, but with a different memory map // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::spcwarp_map); } void galaxold_state::tazzmang(machine_config &config) { galaxian(config); // basic machine hardware m_maincpu->set_addrmap(AS_PROGRAM, &galaxold_state::tazzmang_map); } void galaxold_state::racknrol(machine_config &config) { // basic machine hardware s2650_device &maincpu(S2650(config, m_maincpu, PIXEL_CLOCK/2)); maincpu.set_addrmap(AS_PROGRAM, &galaxold_state::racknrol_map); maincpu.set_addrmap(AS_IO, &galaxold_state::racknrol_io); maincpu.sense_handler().set(m_screen, FUNC(screen_device::vblank)).invert(); // ??? maincpu.intack_handler().set(FUNC(galaxold_state::hunchbkg_intack)); // video hardware GFXDECODE(config, m_gfxdecode, m_palette, gfx_galaxian); PALETTE(config, m_palette, FUNC(galaxold_state::s2650_palette), 32); SCREEN(config, m_screen, SCREEN_TYPE_RASTER); m_screen->set_raw(PIXEL_CLOCK, HTOTAL, HBEND, HBSTART, VTOTAL, VBEND, VBSTART); m_screen->set_screen_update(FUNC(galaxold_state::screen_update_galaxold)); m_screen->set_palette(m_palette); m_screen->screen_vblank().set_inputline(m_maincpu, 0, ASSERT_LINE); MCFG_VIDEO_START_OVERRIDE(galaxold_state,racknrol) // sound hardware SPEAKER(config, "speaker").front_center(); SN76489A(config, "snsnd", PIXEL_CLOCK/2).add_route(ALL_OUTPUTS, "speaker", 1.0); // SN76489AN } void galaxold_state::hexpoola(machine_config &config) { // basic machine hardware s2650_device &maincpu(S2650(config, m_maincpu, PIXEL_CLOCK/2)); maincpu.set_addrmap(AS_PROGRAM, &galaxold_state::racknrol_map); maincpu.set_addrmap(AS_IO, &galaxold_state::hexpoola_io); maincpu.set_addrmap(AS_DATA, &galaxold_state::hexpoola_data); maincpu.sense_handler().set(m_screen, FUNC(screen_device::vblank)).invert(); // ??? maincpu.intack_handler().set(FUNC(galaxold_state::hunchbkg_intack)); GFXDECODE(config, m_gfxdecode, m_palette, gfx_galaxian); PALETTE(config, m_palette, FUNC(galaxold_state::s2650_palette), 32); SCREEN(config, m_screen, SCREEN_TYPE_RASTER); m_screen->set_raw(PIXEL_CLOCK, HTOTAL, HBEND, HBSTART, VTOTAL, VBEND, VBSTART); m_screen->set_screen_update(FUNC(galaxold_state::screen_update_galaxold)); m_screen->set_palette(m_palette); m_screen->screen_vblank().set_inputline(m_maincpu, 0, ASSERT_LINE); MCFG_VIDEO_START_OVERRIDE(galaxold_state,racknrol) // sound hardware SPEAKER(config, "speaker").front_center(); SN76496(config, "snsnd", PIXEL_CLOCK/2).add_route(ALL_OUTPUTS, "speaker", 1.0); } void galaxold_state::bullsdrtg(machine_config &config) { hexpoola(config); m_maincpu->set_addrmap(AS_DATA, &galaxold_state::bullsdrtg_data_map); } /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( vpool ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "vidpool1.bin", 0x0000, 0x0800, CRC(333f4732) SHA1(b57460c039c69137645bd4280ad877aa789277d6) ) ROM_CONTINUE( 0x2000, 0x0800 ) ROM_LOAD( "vidpool2.bin", 0x0800, 0x0800, CRC(eea6c0f1) SHA1(5b18caa78e246f55fd9cd778d6e83f79f0b3f157) ) ROM_CONTINUE( 0x2800, 0x0800 ) ROM_LOAD( "vidpool3.bin", 0x1000, 0x0800, CRC(309972a6) SHA1(8269d2f677f55dda71d6a7b0796d2d53a4def59d) ) ROM_CONTINUE( 0x3000, 0x0800 ) ROM_LOAD( "vidpool4.bin", 0x1800, 0x0800, CRC(c4f71c1d) SHA1(e1d01135d5ccc1a53308ce89dc2a8fc0992207d5) ) ROM_CONTINUE( 0x3800, 0x0800 ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "hustler.5f", 0x0000, 0x0800, CRC(0bdfad0e) SHA1(8e6f1737604f3801c03fa2e9a5e6a2778b54bae8) ) // vidpoolh.bin ROM_LOAD( "hustler.5h", 0x0800, 0x0800, CRC(8e062177) SHA1(7e52a1669804b6c2f694cfc64b04abc8246bb0c2) ) // vidpoolk.bin ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "hustler.clr", 0x0000, 0x0020, CRC(aa1f7f5e) SHA1(311dd17aa11490a1173c76223e4ccccf8ea29850) ) ROM_END ROM_START( hustlerb3 ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "billiard_ic4.a4", 0x0000, 0x2000, CRC(545a27fd) SHA1(8b064dd6a9a82248301e0f53dc1c4fd91e506025) ) ROM_LOAD( "billiard_ic3.a3", 0x2000, 0x2000, CRC(bec503b1) SHA1(cdbe650b829cd4424141058467cd64cfffe1b1e1) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "billiard_ic11.d1", 0x0000, 0x0800, CRC(0bdfad0e) SHA1(8e6f1737604f3801c03fa2e9a5e6a2778b54bae8) ) ROM_LOAD( "billiard_ic12.d2", 0x0800, 0x0800, CRC(8e062177) SHA1(7e52a1669804b6c2f694cfc64b04abc8246bb0c2) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "ic10.c3", 0x0000, 0x0020, CRC(aa1f7f5e) SHA1(311dd17aa11490a1173c76223e4ccccf8ea29850) ) ROM_REGION( 0x0020, "user1", 0 ) // decode PROMs ROM_LOAD( "ic7.b3", 0x0000, 0x0020, CRC(4ac17114) SHA1(1fa34a556fe445a6bdabfe75b4b679cab6553c8b) ) ROM_END // https://www.youtube.com/watch?v=r7di0_Yt1l8 ROM_START( froggerv ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "rana_ic4.ic4", 0x0000, 0x2000, CRC(ed39f6d8) SHA1(8ca60be30dfc5c54fbc129fa0024987d853aad39) ) ROM_LOAD( "rana_ic3.ic3", 0x2000, 0x2000, CRC(f8313d5d) SHA1(76f8e382d5cfad4eafbcd8d42bc9a9f03a5eb5f8) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "rana_ic11.ic11", 0x0000, 0x0800, CRC(a1199087) SHA1(4492b021a6b5ae9a9e2ab97914ce1a5e5e5b64ab) ) ROM_LOAD( "rana_ic12.ic12", 0x0800, 0x0800, CRC(c1690dfc) SHA1(c6fdb1b9ec4fb7da2566b0c71e3e2f931cdece68) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "ic10", 0x0000, 0x0020, CRC(4e3caeab) SHA1(a25083c3e36d28afdefe4af6e6d4f3155e303625) ) // SN74288 or equivalent BPROM ROM_REGION( 0x0020, "user1", 0 ) // decode PROMs ROM_LOAD( "ic7", 0x0000, 0x0020, CRC(4ac17114) SHA1(1fa34a556fe445a6bdabfe75b4b679cab6553c8b) ) // SN74288 or equivalent BPROM ROM_END ROM_START( scramblb ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "scramble.1k", 0x0000, 0x0800, CRC(9e025c4a) SHA1(a8cc9391bdd01a5a2fe7f0c4e889b4e2495df891) ) ROM_LOAD( "scramble.2k", 0x0800, 0x0800, CRC(306f783e) SHA1(92d19f90f1123cd211706294d668ab23c8b0760b) ) ROM_LOAD( "scramble.3k", 0x1000, 0x0800, CRC(0500b701) SHA1(54c84ccad2aae34f42fdddcfcd92cd9da2cd7119) ) ROM_LOAD( "scramble.4k", 0x1800, 0x0800, CRC(dd380a22) SHA1(125e713a58cc5f2c1e38f67dad29f8c985ce5a8b) ) ROM_LOAD( "scramble.5k", 0x2000, 0x0800, CRC(df0b9648) SHA1(4ae9150c9441897d5ab7c5a0b3f10e1e8c8e2f6c) ) ROM_LOAD( "scramble.1j", 0x2800, 0x0800, CRC(b8c07b3c) SHA1(33eaedef4b7f49eeef072425541c17206d0a00ec) ) ROM_LOAD( "scramble.2j", 0x3000, 0x0800, CRC(88ac07a0) SHA1(c57061db5984b472039356bf84a050b5b66e3813) ) ROM_LOAD( "scramble.3j", 0x3800, 0x0800, CRC(c67d57ca) SHA1(ba8b14289aef47d48d9750cf2ef3c368e74a60e8) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "5f.k", 0x0000, 0x0800, CRC(4708845b) SHA1(a8b1ad19a95a9d35050a2ab7194cc96fc5afcdc9) ) ROM_LOAD( "5h.k", 0x0800, 0x0800, CRC(11fd2887) SHA1(69844e48bb4d372cac7ae83c953df573c7ecbb7f) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "82s123.6e", 0x0000, 0x0020, CRC(4e3caeab) SHA1(a25083c3e36d28afdefe4af6e6d4f3155e303625) ) ROM_END ROM_START( scramb2 ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "r1.7f1", 0x0000, 0x0800, CRC(4a43148c) SHA1(ea27fd3acf661101296a58a7a50fb8e4d5292760) ) ROM_LOAD( "r1.7f2", 0x0800, 0x0800, CRC(215a3b86) SHA1(bfddfea9f74064123629d89556240c7a59f7bea2) ) ROM_LOAD( "r2.7h1", 0x1000, 0x0800, CRC(28779444) SHA1(0abd3a89c8cdd5af2ac06afd38bcd2dcd6010bee) ) ROM_LOAD( "r2.7h2", 0x1800, 0x0800, CRC(5b4b300b) SHA1(6d69dbdab66bc8f4a16c3d9d3b4581799e4bbfab) ) ROM_LOAD( "r3.7k1", 0x2000, 0x0800, CRC(b478aa53) SHA1(68cf134482092534ef0a3ceee3aa842f86660065) ) ROM_LOAD( "r3.7k2", 0x2800, 0x0800, CRC(c33f072e) SHA1(28d61e35f3d5c971e070d7e0cc20b831fe8d52c5) ) ROM_LOAD( "r4.7l1", 0x3000, 0x0800, CRC(88ac07a0) SHA1(c57061db5984b472039356bf84a050b5b66e3813) ) ROM_LOAD( "r4.7l2", 0x3800, 0x0800, CRC(321fd003) SHA1(61f33c2709913da4cb20f311501df707d755917e) ) // Also exists in the following ROM config // ROM_LOAD( "r1.7f", 0x0000, 0x1000, CRC(75208a74) SHA1(e77afe4b906d08d6763f31dd70d7cb772be97102) ) // ROM_LOAD( "r2.7h", 0x1000, 0x1000, CRC(f2179cf5) SHA1(5c38aa9bd1d5ebdccf16d2e50acc56f0b3f042d0) ) // ROM_LOAD( "r3.7k", 0x2000, 0x1000, CRC(941c804e) SHA1(f1eedf719a234cf98071e6a46120765e231f0730) ) // ROM_LOAD( "r4.7l", 0x3000, 0x1000, CRC(f1506edc) SHA1(66689bb3d7570848e4d020a5f44d6de03b4bff99) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "r6.1j", 0x0000, 0x0800, CRC(4708845b) SHA1(a8b1ad19a95a9d35050a2ab7194cc96fc5afcdc9) ) ROM_LOAD( "r5.1l", 0x0800, 0x0800, CRC(11fd2887) SHA1(69844e48bb4d372cac7ae83c953df573c7ecbb7f) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "82s123.6e", 0x0000, 0x0020, CRC(4e3caeab) SHA1(a25083c3e36d28afdefe4af6e6d4f3155e303625) ) ROM_END ROM_START( scramb3 ) ROM_REGION( 0x4000, "maincpu", 0 ) ROM_LOAD( "ra.7f", 0x0000, 0x1000, CRC(979be487) SHA1(74817d4d7f616e244ca331d05f1dcea30050a98e) ) ROM_LOAD( "r2.7h", 0x1000, 0x1000, CRC(f2179cf5) SHA1(5c38aa9bd1d5ebdccf16d2e50acc56f0b3f042d0) ) ROM_LOAD( "r3.7k", 0x2000, 0x1000, CRC(941c804e) SHA1(f1eedf719a234cf98071e6a46120765e231f0730) ) ROM_LOAD( "top32", 0x3000, 0x1000, CRC(0c3297a6) SHA1(6d6bb183139b30e78d74e8272d3a9f7234d394c6) ) // on a smaller top PCB ROM_REGION( 0x1000, "gfx1", 0 ) // identical to scramble and a lot of other sets ROM_LOAD( "6.1h", 0x0000, 0x0800, CRC(4708845b) SHA1(a8b1ad19a95a9d35050a2ab7194cc96fc5afcdc9) ) ROM_LOAD( "5.1k", 0x0800, 0x0800, CRC(11fd2887) SHA1(69844e48bb4d372cac7ae83c953df573c7ecbb7f) ) ROM_REGION( 0x0020, "proms", 0 ) // identical to scramble ROM_LOAD( "c01s.6e", 0x0000, 0x0020, CRC(4e3caeab) SHA1(a25083c3e36d28afdefe4af6e6d4f3155e303625) ) ROM_END ROM_START( scrambler ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "principal 1.bin", 0x0000, 0x0800, CRC(926958d2) SHA1(eda1ddca0d43f40d684886d5ec54d40d40ce5715) ) ROM_LOAD( "principal 2.bin", 0x0800, 0x0800, CRC(655c6eca) SHA1(a9f4484d9c5c6716018e234563798b3c54124878) ) ROM_LOAD( "principal 3.bin", 0x1000, 0x0800, CRC(cd31749a) SHA1(0250530e76cf5019df61bfe3e0a85969e011b8f9) ) ROM_LOAD( "principal 4.bin", 0x1800, 0x0800, CRC(f055e1e3) SHA1(51eabb4915ceade37def5fe39129b15f0a37bd65) ) ROM_LOAD( "principal 5.bin", 0x2000, 0x0800, CRC(15f10df7) SHA1(93c9abcd61fbe5c5dd33a9387527565af6117c40) ) ROM_LOAD( "principal 6.bin", 0x2800, 0x0800, CRC(4bd1c703) SHA1(b91465d6ef2ae8e1b1d24bc9895e7e596b9e422b) ) ROM_LOAD( "principal 7.bin", 0x3000, 0x0800, CRC(0bb49470) SHA1(05a6fe3010c2136284ca76352dac147797c79778) ) // == s7.2m ROM_LOAD( "principal 8.bin", 0x3800, 0x0800, CRC(6db9f380) SHA1(0678ffe16886ba76314ea14f15b4bb5752366dd5) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "graph hj.bin", 0x0000, 0x0800, CRC(4c017c9c) SHA1(36ea77be224aac16578b26c6f69601c7f10d1c7b) ) ROM_LOAD( "graph kl.bin", 0x0800, 0x0800, CRC(28a66399) SHA1(fe4c900e80a3a04c5c12e037ae2ae23339b9a9f8) ) ROM_REGION( 0x0020, "proms", 0 ) // not dumped, assumed to be the same ROM_LOAD( "c01s.6e", 0x0000, 0x0020, CRC(4e3caeab) SHA1(a25083c3e36d28afdefe4af6e6d4f3155e303625) ) ROM_END ROM_START( scrambleo ) // MR-1A + MP-28 PCBs ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "1.bin", 0x0000, 0x0800, CRC(55313343) SHA1(3a5988e108aaf7af6498fb1cabef12b2f75858d5) ) ROM_LOAD( "2.bin", 0x0800, 0x0800, CRC(af61bdfe) SHA1(f3414adc243e4687db3ae9c4f003663215a52b6b) ) ROM_LOAD( "3.bin", 0x1000, 0x0800, CRC(c85c613b) SHA1(622d8566dc199624aad02380f69280c8b4c06bf2) ) ROM_LOAD( "4.bin", 0x1800, 0x0800, CRC(f055e1e3) SHA1(51eabb4915ceade37def5fe39129b15f0a37bd65) ) ROM_LOAD( "5.bin", 0x2000, 0x0800, CRC(cc059dc5) SHA1(2a80637f6fb38b8db06293e92d80b4be640e23d2) ) ROM_LOAD( "6.bin", 0x2800, 0x0800, CRC(dd15f10e) SHA1(d7efd498ab7702127dc48c5ab57d207732924c38) ) ROM_LOAD( "7.bin", 0x3000, 0x0800, CRC(0bb49470) SHA1(05a6fe3010c2136284ca76352dac147797c79778) ) ROM_LOAD( "8.bin", 0x3800, 0x0800, CRC(29a15aec) SHA1(bf98bb931b934eeca7c996143b0900ffe8757f18) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "gfx_h.bin", 0x0000, 0x0800, CRC(4708845b) SHA1(a8b1ad19a95a9d35050a2ab7194cc96fc5afcdc9) ) ROM_LOAD( "gfx_m.bin", 0x0800, 0x0800, CRC(11fd2887) SHA1(69844e48bb4d372cac7ae83c953df573c7ecbb7f) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "sc_cprom.bin", 0x0000, 0x0020, CRC(413703bf) SHA1(66648b2b28d3dcbda5bdb2605d1977428939dd3c) ) ROM_END ROM_START( 4in1 ) ROM_REGION( 0x20000, "maincpu", 0 ) // 64k for code 64k for banked code, encrypted // Menu Code, Fixed at 0xc000 - 0xdfff ROM_LOAD( "rom1a", 0xc000, 0x1000, CRC(ce1af4d9) SHA1(260d81cb703ab33fa5f282454214dea06e59a5d6) ) ROM_LOAD( "rom1b", 0xd000, 0x1000, CRC(18484f9b) SHA1(2439841ba5882c287bd9656fbf79190ff9efe4ee) ) // Ghost Muncher PT3 - banked at 0x0000 - 0x3fff ROM_LOAD( "rom1c", 0x10000, 0x1000, CRC(83248a8b) SHA1(65af22b9a4516ab52c3327cb3b714d90c2c77284) ) ROM_LOAD( "rom1d", 0x11000, 0x1000, CRC(053f6da0) SHA1(fa69de09a2162dfaa82ea566f0808433f26e4854) ) ROM_LOAD( "rom1e", 0x12000, 0x1000, CRC(43c546f3) SHA1(c32a2281f8dca1f2b218dc76192d8e09f2eee460) ) ROM_LOAD( "rom1f", 0x13000, 0x1000, CRC(3a086b46) SHA1(1fd65fd139a650a5c246cead5141b81764faf98c) ) // Scramble PT2 - banked at 0x0000 - 0x3fff ROM_LOAD( "rom1g", 0x14000, 0x1000, CRC(ac0e2050) SHA1(02961a41f54d55f2ae07a2694a14fb6e6e4a766b) ) ROM_LOAD( "rom1h", 0x15000, 0x1000, CRC(dc11a513) SHA1(2785c08d890f2f8e86b7f793f7989d7605570cc3) ) ROM_LOAD( "rom1i", 0x16000, 0x1000, CRC(a5fb6be4) SHA1(f575ca70037134084aff152fcee7fdd0a1163c33) ) ROM_LOAD( "rom1j", 0x17000, 0x1000, CRC(9054cfbe) SHA1(99ad74491cf8682daf45f2786e0bf275160c9826) ) // Galaxian PT5 - banked at 0x0000 - 0x3fff ROM_LOAD( "rom2c", 0x18000, 0x1000, CRC(7cd98e11) SHA1(7ef49866a5c5fd871acf5bfe3d899a9ae0d37405) ) ROM_LOAD( "rom2d", 0x19000, 0x1000, CRC(9402f32e) SHA1(feb5cb09ea719612a22949f34fb97e172305c7b0) ) ROM_LOAD( "rom2e", 0x1a000, 0x1000, CRC(468e81df) SHA1(4ac30c170ce63637c77227833cef8839e2b0b8ab) ) // Galactic Convoy - banked at 0x0000 - 0x3fff ROM_LOAD( "rom2g", 0x1c000, 0x1000, CRC(b1ce3976) SHA1(365e643948e982126198714bb1e07340ded7d4a5) ) ROM_LOAD( "rom2h", 0x1d000, 0x1000, CRC(7eab5670) SHA1(d9648fc314bc6a685536c6acb17b17737813d902) ) ROM_LOAD( "rom2i", 0x1e000, 0x1000, CRC(44565ac5) SHA1(cc8141cbdb9280a15b40761448e00a3b30a94ec7) ) ROM_REGION( 0x8000, "gfx1", 0 ) // Ghost Muncher PT3 GFX ROM_LOAD( "rom4b", 0x4000, 0x0800, CRC(7e6495af) SHA1(32db70bca5c60eea6b37a943e076bc5a8dc3870b) ) ROM_CONTINUE( 0x0000, 0x0800 ) ROM_LOAD( "rom3b", 0x6000, 0x0800, CRC(7475f72f) SHA1(834873b6a587760cbbd0ac9435af55f6cb20097a) ) ROM_CONTINUE( 0x2000, 0x0800 ) // Scramble PT2 GFX ROM_LOAD( "rom4c", 0x4800, 0x0800, CRC(3355d46d) SHA1(e5476d2053298958f141e11a97017ea465621d89) ) ROM_RELOAD( 0x0800, 0x0800) ROM_LOAD( "rom3c", 0x6800, 0x0800, CRC(ac755a25) SHA1(70af05d32554682be6c3f74936e57b4050d283c7) ) ROM_RELOAD( 0x2800, 0x0800) // Galaxians PT5 GFX ROM_LOAD( "rom4d", 0x5000, 0x0800, CRC(bbdddb65) SHA1(fc2dcfd969b1ee51a6413117e83f8a0c29278658) ) ROM_CONTINUE( 0x1000, 0x0800) ROM_LOAD( "rom3d", 0x7000, 0x0800, CRC(91a00204) SHA1(eea8a8bd8439260dde9131693e9b53b0238ce7a7) ) ROM_CONTINUE( 0x3000, 0x0800) // Galactic Convoy GFX ROM_LOAD( "rom4e", 0x5800, 0x0800, CRC(0cb9e297) SHA1(a9be2951851deed0ffefb980fc7751a399dc131e) ) ROM_CONTINUE( 0x1800, 0x0800 ) ROM_LOAD( "rom3e", 0x7800, 0x0800, CRC(a1fe77f9) SHA1(dc7972b7aa77fb4f95d7349d4cd7fc4674f9032d) ) ROM_CONTINUE( 0x3800, 0x0800 ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "6l.bpr", 0x0000, 0x0020, CRC(6a0c7d87) SHA1(140335d85c67c75b65689d4e76d29863c209cf32) ) ROM_END ROM_START( dkongjrm ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "a1", 0x0000, 0x1000, CRC(299486e9) SHA1(cc4143ff8cb7a37c151bebab007a932381ae733b) ) ROM_LOAD( "a2", 0x1000, 0x1000, CRC(a74a193b) SHA1(46f208293c0944b468550738d1238de9b672f403) ) ROM_LOAD( "b2", 0x2000, 0x1000, CRC(7bc4f236) SHA1(84e7f5fcbea7d047f2a9a9006ae3ed646417c5e0) ) ROM_LOAD( "c1", 0x3000, 0x1000, CRC(0f594c21) SHA1(eb15bd9cc37794786e2ad24753172e88aa7c4f98) ) ROM_LOAD( "d1", 0x4000, 0x1000, CRC(cf7d7296) SHA1(9a817eca2ebef3f5208bb29ee7eece2ec0efe158) ) ROM_LOAD( "e2", 0x5000, 0x1000, CRC(f7528a52) SHA1(e9d3c57934ee97fcc1f17ecdf3bc954574212220) ) ROM_LOAD( "f1", 0x7000, 0x1000, CRC(9b1d4cc5) SHA1(9a412fec82f39b9389ff99cceba2e49b2a74df17) ) ROM_REGION( 0x4000, "gfx1", 0 ) ROM_LOAD( "v_3pa.bin", 0x0000, 0x1000, CRC(4974ffef) SHA1(7bb1e207dd3c5214e405bf32c57ec1b048061050) ) ROM_LOAD( "a2.gfx", 0x1000, 0x1000, CRC(51845eaf) SHA1(43970d69329f3d49ea1ff57d54abe8340ceef275) ) ROM_LOAD( "v_3na.bin", 0x2000, 0x1000, CRC(a95c4c63) SHA1(75e312b6872958f3bfc7bafd0743efdf7a74e8f0) ) ROM_LOAD( "b2.gfx", 0x3000, 0x1000, CRC(7b39c3d0) SHA1(4b8cebb4cdaaca9e1b6fd378f6c390ab05984590) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "hustler.clr", 0x0000, 0x0020, CRC(aa1f7f5e) SHA1(311dd17aa11490a1173c76223e4ccccf8ea29850) ) ROM_END ROM_START( dkongjrmc ) // "CENTROMATIC - G/G" main board ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "2732-1.bin", 0x0000, 0x1000, CRC(1bcb41be) SHA1(74b1700babd26cb0c781bc702130a63da0386463) ) ROM_LOAD( "2732-2.bin", 0x1000, 0x1000, CRC(f027a6b9) SHA1(557ab9737c31b4c57b1d37d62bb5ce51c574c4b9) ) ROM_LOAD( "2732-3.bin", 0x2000, 0x1000, CRC(e2484ff4) SHA1(fdd77db1ba0dc7876e0503aace7273d7a8dedd53) ) ROM_LOAD( "2732-4.bin", 0x3000, 0x1000, CRC(37e5dd92) SHA1(69bbc765a54e98b69cf6831342469a9c94659f8f) ) ROM_LOAD( "2732-5.bin", 0x4000, 0x1000, CRC(b2d89348) SHA1(209f3ca7c97afa3e746f778df0c34664f8791855) ) ROM_LOAD( "2732-6.bin", 0x5000, 0x1000, CRC(24b0c560) SHA1(0b7e099ad2aace542fedb8b7c8c28204d3ea7a46) ) ROM_LOAD( "2732-7.bin", 0x9000, 0x1000, CRC(7428eefa) SHA1(82e5c8461fe48e5d6222bb5d0a259e6fd0c5cac7) ) ROM_REGION( 0x4000, "gfx1", 0 ) // GFX ROM sub board marked "CALFESA" on solder side ROM_LOAD( "2732-a.bin", 0x0000, 0x1000, CRC(526ed721) SHA1(5fd317908b9d9aa70768f8f7cfbfdfa6d1e654b6) ) ROM_LOAD( "2732-b.bin", 0x1000, 0x1000, CRC(d2cb5130) SHA1(b87d2c74cc74782fec7268f0a637613450a2fb4b) ) ROM_LOAD( "2732-c.bin", 0x2000, 0x1000, CRC(7ceae713) SHA1(1f85d3b34cf10bd6277b408aed051a18cf9b1090) ) ROM_LOAD( "2732-d.bin", 0x3000, 0x1000, CRC(2aa1acf1) SHA1(fdf58e737253ca5f0cf3667d3a74efeafdb66e21) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "82s123.bin", 0x0000, 0x0020, CRC(6a0c7d87) SHA1(140335d85c67c75b65689d4e76d29863c209cf32) ) ROM_REGION( 0x0200, "mainproms", 0 ) ROM_LOAD( "tbp28l22n-8240a.bin", 0x0000, 0x0100, CRC(df72ed74) SHA1(fce9a846b7238c2cc8898e6338485f3df0a56755) ) ROM_LOAD( "tbp28l22n-a8240a.bin", 0x0100, 0x0100, CRC(9575df2b) SHA1(9360730fc230d17f6be5fc7f8d46d79566839cfa) ) ROM_END ROM_START( tazzmang ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "tazzm1.4k", 0x0000, 0x1000, CRC(a14480a1) SHA1(60dac6b57e8331cc4daedaf87faf3e3acc68f378) ) ROM_LOAD( "tazzm2.5j", 0x1000, 0x1000, CRC(5609f5db) SHA1(3fc50109ea0e012e3e310ae4f5dd0cf460bdca52) ) ROM_LOAD( "tazzm3.6f", 0x2000, 0x1000, CRC(fe7f7002) SHA1(ac4134c07a798328b18994010bcaf6b3f728466a) ) ROM_LOAD( "tazzm4.7e", 0x3000, 0x1000, CRC(c9ca1d0a) SHA1(d420ca2e926174e17215212278c86ba9bbb3d9dc) ) ROM_LOAD( "tazzm5.7l", 0x4000, 0x1000, CRC(f50cd8a6) SHA1(b59ca37171b9acc9854f1beae43cfa5643219a5f) ) ROM_LOAD( "tazzm6.7l", 0x5000, 0x1000, CRC(5cf2e7d2) SHA1(ad89e2655164e0fc5ecc9af70c5f0dd9b094d432) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "tazm8.1lk", 0x0000, 0x0800, CRC(2c5b612b) SHA1(32e3a41a9a4a8b1285b6a195213ff0d98012360a) ) ROM_LOAD( "tazzm7.1jh", 0x0800, 0x0800, CRC(3f5ff3ac) SHA1(bc70eef54a45b52c14e35464e5f06b5eec554eb6) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "prom.6l", 0x0000, 0x0020, CRC(6a0c7d87) SHA1(140335d85c67c75b65689d4e76d29863c209cf32) ) ROM_END ROM_START( tazzmang2 ) // Original Sparcade set ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "tazmania.1", 0x000000, 0x000800, CRC(6ecc84a2) SHA1(6f31e69bd613b93e1fac26163f39676299c65a76) ) ROM_LOAD( "tazmania.2", 0x000800, 0x000800, CRC(e27b09f6) SHA1(1a419c8f45639e2c2351eeb94bf62fca35d5928e) ) ROM_LOAD( "tazmania.3", 0x001000, 0x000800, CRC(954868f3) SHA1(3882e17ffd9bcfcff383ed95279606962f89dafd) ) ROM_LOAD( "tazmania.4", 0x001800, 0x000800, CRC(238520e6) SHA1(eec76b54058a6a6139f13f188d243f20d1a7aa12) ) ROM_LOAD( "tazmania.5", 0x002000, 0x000800, CRC(0527e513) SHA1(20175c293f1cf45fa21dd400cb2718dd8ee0dcea) ) ROM_LOAD( "tazmania.6", 0x002800, 0x000800, CRC(af2b92d8) SHA1(5642666eb66d549390cd5b13a7029daede6d3ff8) ) ROM_LOAD( "tazmania.7", 0x003000, 0x000800, CRC(bbdc41d3) SHA1(17de825efd56541dbdbacdc83f77f3ccaef2d07f) ) ROM_LOAD( "tazmania.8", 0x003800, 0x000800, CRC(eb35f49c) SHA1(0f2bf1043092e746fdbc5d2e0292aeaa7b7f0218) ) ROM_LOAD( "tazmania.a", 0x004000, 0x001000, CRC(38f326f8) SHA1(5c5463666b6ed15cbcc874faf79cc06ae1cba59a) ) ROM_LOAD( "tazmania.b", 0x005000, 0x001000, CRC(2a22a9dc) SHA1(07aecdff852065671e488682cf710fd48273b88c) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "tazm8.1lk", 0x0000, 0x0800, CRC(2c5b612b) SHA1(32e3a41a9a4a8b1285b6a195213ff0d98012360a) ) // tazmania.g1 ROM_LOAD( "tazzm7.1jh", 0x0800, 0x0800, CRC(3f5ff3ac) SHA1(bc70eef54a45b52c14e35464e5f06b5eec554eb6) ) // tazmania.g2 ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "prom.6l", 0x0000, 0x0020, CRC(6a0c7d87) SHA1(140335d85c67c75b65689d4e76d29863c209cf32) ) ROM_END ROM_START( hunchbkg ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "gal_hb_1", 0x0000, 0x0800, CRC(46590e9b) SHA1(5d26578c91adec20d8d8a17d5dade9ef2febcbe5) ) ROM_LOAD( "gal_hb_2", 0x0800, 0x0800, CRC(4e6e671c) SHA1(5948fc7f390f0343b367d333395427ce2f9b2931) ) ROM_LOAD( "gal_hb_3", 0x2000, 0x0800, CRC(d29dc242) SHA1(3f6087fe962ee63c2886ad3f502c1a37d357ba87) ) ROM_LOAD( "gal_hb_4", 0x2800, 0x0800, CRC(d409d292) SHA1(d631c9106106b31b605b6fdf1d4f40e237a725ac) ) ROM_LOAD( "gal_hb_5", 0x4000, 0x0800, CRC(29d3a8c4) SHA1(2e1ef20d980e5033503d8095e9576dcb8f532f41) ) ROM_LOAD( "gal_hb_6", 0x4800, 0x0800, CRC(b016fd15) SHA1(cdfbd531e23438f05a7c3aad99a94ce55912aac3) ) ROM_LOAD( "gal_hb_7", 0x6000, 0x0800, CRC(d2731d27) SHA1(8c4a3d2303d85c3b11803c577a9ad21e6e69011e) ) ROM_LOAD( "gal_hb_8", 0x6800, 0x0800, CRC(e4b1a666) SHA1(9f73d17cff208374d587536e783be024fc9ab700) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "gal_hb_kl", 0x0000, 0x0800, CRC(3977650e) SHA1(1de05d6ceed3f2ed0925caa8235b63a93f03f61e) ) ROM_LOAD( "gal_hb_hj", 0x0800, 0x0800, CRC(db489c3d) SHA1(df08607ad07222c1c1c4b3589b50b785bdeefbf2) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "gal_hb_cp", 0x0000, 0x0020, CRC(cbff6762) SHA1(4515a6e12a0a5c485a55291feee17a571120a549) ) ROM_END ROM_START( hunchbgb ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "1.bin", 0x0000, 0x0800, CRC(46590e9b) SHA1(5d26578c91adec20d8d8a17d5dade9ef2febcbe5) ) ROM_LOAD( "2.bin", 0x0800, 0x0800, CRC(4e6e671c) SHA1(5948fc7f390f0343b367d333395427ce2f9b2931) ) ROM_LOAD( "3.bin", 0x2000, 0x0800, CRC(d29dc242) SHA1(3f6087fe962ee63c2886ad3f502c1a37d357ba87) ) ROM_LOAD( "4.bin", 0x2800, 0x0800, CRC(d409d292) SHA1(d631c9106106b31b605b6fdf1d4f40e237a725ac) ) ROM_LOAD( "5.bin", 0x4000, 0x0800, CRC(29d3a8c4) SHA1(2e1ef20d980e5033503d8095e9576dcb8f532f41) ) ROM_LOAD( "6.bin", 0x4800, 0x0800, CRC(b016fd15) SHA1(cdfbd531e23438f05a7c3aad99a94ce55912aac3) ) ROM_LOAD( "7.bin", 0x6000, 0x0800, CRC(d2731d27) SHA1(8c4a3d2303d85c3b11803c577a9ad21e6e69011e) ) ROM_LOAD( "8.bin", 0x6800, 0x0800, CRC(e4b1a666) SHA1(9f73d17cff208374d587536e783be024fc9ab700) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "lk.bin", 0x0000, 0x0800, CRC(83ecf8f4) SHA1(1eb8ca1ed9d82001fc4a62fef5e13d63a5ab7884) ) ROM_LOAD( "jh.bin", 0x0800, 0x0800, CRC(106889ec) SHA1(bbeca0d36e3f117bcd1e6361c808368d2f90f00a) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "74s288n.bin", 0x0000, 0x0020, CRC(2430f47c) SHA1(f7725f4768cb57717feb18891766642f6d7cbcde) ) ROM_END /* For all we know, this could be anything, but the text in ROM confirms the copyright (swarpt7f.bin): "COPYRIGHT 1983" "CENTURY ELECTRONICS LTD" ...and the GFX ROMs contain graphics similar to Cosmos, so it could be Space Warp after all. Due to how incomplete this dump is (missing ROM, one corrupted), there is very little to be worked on, but so far, using a variation of hunchbkg's memory map and inputs work, atleast until it crashes on the title screen. */ ROM_START( spcwarp ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "swarpt7f.bin", 0x0000, 0x1000, CRC(04d744e3) SHA1(db8218510052a05670cb0b722b73d3f10464788c) ) ROM_LOAD( "swarpt7h.bin", 0x2000, 0x1000, CRC(34a36536) SHA1(bc438515618683b2a7c29637871ee00ed95ad7f8) ) // missing ROM at $4000 ROM_LOAD( "swarpt7m.bin", 0x6000, 0x1000, BAD_DUMP CRC(a2dff6c8) SHA1(d1c72848450dc5ff386dc94a26e4bf704ccc7121) ) // ROMCMP reports "BADADDR xxxxxx-xxxxx". Observed data sequence repeated every 32 bytes ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "swarpb1h.bin", 0x0000, 0x0800, CRC(6ee3b5f7) SHA1(8150f2ecd59d3a165c0541b550664c56d049edd5) ) ROM_LOAD( "swarpb1k.bin", 0x0800, 0x0800, CRC(da4cee6b) SHA1(28b91381658f598fa62049489beee443232825c6) ) // using hunchbkg PROMs for now ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "gal_hb_cp", 0x0000, 0x0020, BAD_DUMP CRC(cbff6762) SHA1(4515a6e12a0a5c485a55291feee17a571120a549) ) ROM_END ROM_START( drivfrcg ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "dfgp1.bin", 0x2800, 0x0400, CRC(52d5e77d) SHA1(4e68ac1274bbc8cb5b6a7dfb511232bd83482453) ) ROM_CONTINUE( 0x2c00, 0x0400 ) ROM_CONTINUE( 0x0000, 0x0400 ) ROM_CONTINUE( 0x0400, 0x0400 ) ROM_LOAD( "dfgp2.bin", 0x0800, 0x0400, CRC(9cf4dbce) SHA1(028c168ad0987f21d76c6ac4f756f4fa86c2f8e3) ) ROM_CONTINUE( 0x0c00, 0x0400 ) ROM_CONTINUE( 0x2000, 0x0400 ) ROM_CONTINUE( 0x2400, 0x0400 ) ROM_LOAD( "dfgp3.bin", 0x6800, 0x0400, CRC(79763f62) SHA1(2bb8921fcd2a8b9543e398e248fd47d7e03dc24d) ) ROM_CONTINUE( 0x6c00, 0x0400 ) ROM_CONTINUE( 0x4000, 0x0400 ) ROM_CONTINUE( 0x4400, 0x0400 ) ROM_LOAD( "dfgp4.bin", 0x4800, 0x0400, CRC(dd95338b) SHA1(9054986f7b8fee36f458362836ae969e7d1e2456) ) ROM_CONTINUE( 0x4c00, 0x0400 ) ROM_CONTINUE( 0x6000, 0x0400 ) ROM_CONTINUE( 0x6400, 0x0400 ) ROM_REGION( 0x4000, "gfx1", 0 ) ROM_LOAD( "dfgj2.bin", 0x0000, 0x1000, CRC(8e19f1e7) SHA1(addd5add2117ef29ce38c0c80584e5d481b9d820) ) ROM_LOAD( "dfgj1.bin", 0x1000, 0x1000, CRC(86b60ca8) SHA1(be266e2d69e12a196c2195d48b495c0fb9ef8a43) ) ROM_LOAD( "dfgl2.bin", 0x2000, 0x1000, CRC(ea5e9959) SHA1(6b638d22adf19224cf741458c8ad34d7f7e17e58) ) ROM_LOAD( "dfgl1.bin", 0x3000, 0x1000, CRC(b7ed195c) SHA1(81b2b444153dacb962a33a5d86a280ed5088637a) ) // piggy-backed colour PROMs ROM_REGION( 0x0040, "proms", 0 ) ROM_LOAD( "top.clr", 0x0000, 0x0020, CRC(3110ddae) SHA1(53b2e1cc07915592f6c868131ec296c63a407f04) ) ROM_LOAD( "bot.clr", 0x0020, 0x0020, CRC(0f0782af) SHA1(32c0dd09ead5c70cee2657e9cb8cb9fcf54c5a6a) ) ROM_END ROM_START( drivfrcsg ) // This PCB has a big epoxy block by Tanaka Enterprises marked E-0010, providing ROM addressing ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "6n-2-2764a.bin", 0x2800, 0x0400, CRC(85242241) SHA1(bad2609c7f6d83a15809b602a0c141793909ceb0) ) ROM_CONTINUE( 0x2c00, 0x0400 ) ROM_CONTINUE( 0x0000, 0x0400 ) ROM_CONTINUE( 0x0400, 0x0400 ) ROM_CONTINUE( 0x0800, 0x0400 ) ROM_CONTINUE( 0x0c00, 0x0400 ) ROM_CONTINUE( 0x2000, 0x0400 ) ROM_CONTINUE( 0x2400, 0x0400 ) ROM_LOAD( "6m-1-2764a.bin", 0x6800, 0x0400, CRC(42d99594) SHA1(1b03132279a3a6edd2281a2f55ef2d3133003a16) ) ROM_CONTINUE( 0x6c00, 0x0400 ) ROM_CONTINUE( 0x4000, 0x0400 ) ROM_CONTINUE( 0x4400, 0x0400 ) ROM_CONTINUE( 0x4800, 0x0400 ) ROM_CONTINUE( 0x4c00, 0x0400 ) ROM_CONTINUE( 0x6000, 0x0400 ) ROM_CONTINUE( 0x6400, 0x0400 ) ROM_REGION( 0x4000, "gfx1", 0 ) ROM_LOAD( "1j-2764a.bin", 0x0000, 0x2000, CRC(156e20bd) SHA1(8ec4020d179674856f43e543ce5e54730752568a) ) ROM_LOAD( "1l-2764a.bin", 0x2000, 0x2000, CRC(88d0f70b) SHA1(c91aa798f7450c0cf1a8db4225d4a4efa25555d8) ) // piggy-backed colour PROMs ROM_REGION( 0x0040, "proms", 0 ) ROM_LOAD( "82s123-1.bin", 0x0000, 0x0020, CRC(3110ddae) SHA1(53b2e1cc07915592f6c868131ec296c63a407f04) ) ROM_LOAD( "82s123-2.bin", 0x0020, 0x0020, CRC(0f0782af) SHA1(32c0dd09ead5c70cee2657e9cb8cb9fcf54c5a6a) ) ROM_END ROM_START( drivfrcsga ) // This PCB has a big epoxy block by Tanaka Enterprises marked E-0237, possibly providing ROM addressing ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "xx.bin", 0x2800, 0x0400, NO_DUMP ) // missing ROM_CONTINUE( 0x2c00, 0x0400 ) ROM_CONTINUE( 0x0000, 0x0400 ) ROM_CONTINUE( 0x0400, 0x0400 ) ROM_CONTINUE( 0x0800, 0x0400 ) ROM_CONTINUE( 0x0c00, 0x0400 ) ROM_CONTINUE( 0x2000, 0x0400 ) ROM_CONTINUE( 0x2400, 0x0400 ) ROM_LOAD( "1p.bin", 0x6800, 0x0400, CRC(58b12215) SHA1(73c8bd16994704d8b1d007c5924ba5e83f7233ea) ) // unique ROM_CONTINUE( 0x6c00, 0x0400 ) ROM_CONTINUE( 0x4000, 0x0400 ) ROM_CONTINUE( 0x4400, 0x0400 ) ROM_CONTINUE( 0x4800, 0x0400 ) ROM_CONTINUE( 0x4c00, 0x0400 ) ROM_CONTINUE( 0x6000, 0x0400 ) ROM_CONTINUE( 0x6400, 0x0400 ) ROM_REGION( 0x4000, "gfx1", 0 ) ROM_LOAD( "kj_5.22.bin", 0x0000, 0x2000, CRC(7b6d837a) SHA1(925ca351635e77cacfb5a2d6e31487c5e4aaf0ec) ) // unique ROM_LOAD( "kl_5.22.bin", 0x2000, 0x2000, CRC(86cd5438) SHA1(c921d8cd031fd0fa78488ae95a1570dd1be919e9) ) // unique // piggy-backed colour PROMs ROM_REGION( 0x0040, "proms", 0 ) // missing ROM_LOAD( "82s123-1.bin", 0x0000, 0x0020, NO_DUMP ) ROM_LOAD( "82s123-2.bin", 0x0020, 0x0020, NO_DUMP ) ROM_END ROM_START( drivfrcb ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "dfp.bin", 0x2800, 0x0400, CRC(b5b2981d) SHA1(c9ff19791895bf05b569457b1e53dfa0aaeb8e95) ) ROM_CONTINUE( 0x2c00, 0x0400 ) ROM_CONTINUE( 0x0000, 0x0400 ) ROM_CONTINUE( 0x0400, 0x0400 ) ROM_CONTINUE( 0x0800, 0x0400 ) ROM_CONTINUE( 0x0c00, 0x0400 ) ROM_CONTINUE( 0x2000, 0x0400 ) ROM_CONTINUE( 0x2400, 0x0400 ) ROM_CONTINUE( 0x6800, 0x0400 ) ROM_CONTINUE( 0x6c00, 0x0400 ) ROM_CONTINUE( 0x4000, 0x0400 ) ROM_CONTINUE( 0x4400, 0x0400 ) ROM_CONTINUE( 0x4800, 0x0400 ) ROM_CONTINUE( 0x4c00, 0x0400 ) ROM_CONTINUE( 0x6000, 0x0400 ) ROM_CONTINUE( 0x6400, 0x0400 ) ROM_REGION( 0x4000, "gfx1", 0 ) ROM_LOAD( "df1.bin", 0x1000, 0x1000, CRC(8adc3de0) SHA1(046fb92913171c621bb62edb0174f04298bfd283) ) ROM_CONTINUE( 0x0000, 0x1000 ) ROM_LOAD( "df2.bin", 0x3000, 0x1000, CRC(6d95ec35) SHA1(c745ee2bc7b1fb53e8bc1ac3a4238bbe00f30cfe) ) ROM_CONTINUE( 0x2000, 0x1000 ) // piggy-backed colour PROMs ROM_REGION( 0x0040, "proms", 0 ) ROM_LOAD( "top.clr", 0x0000, 0x0020, CRC(3110ddae) SHA1(53b2e1cc07915592f6c868131ec296c63a407f04) ) ROM_LOAD( "bot.clr", 0x0020, 0x0020, CRC(0f0782af) SHA1(32c0dd09ead5c70cee2657e9cb8cb9fcf54c5a6a) ) ROM_END ROM_START( drivfrct ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "03.bin", 0x2800, 0x0400, CRC(9ab604cb) SHA1(772a5c0d93377f5bd7fc1f5e4050d44321a1bb8d) ) ROM_CONTINUE( 0x2c00, 0x0400 ) ROM_CONTINUE( 0x0000, 0x0400 ) ROM_CONTINUE( 0x0400, 0x0400 ) ROM_CONTINUE( 0x0800, 0x0400 ) ROM_CONTINUE( 0x0c00, 0x0400 ) ROM_CONTINUE( 0x2000, 0x0400 ) ROM_CONTINUE( 0x2400, 0x0400 ) ROM_CONTINUE( 0x6800, 0x0400 ) ROM_CONTINUE( 0x6c00, 0x0400 ) ROM_CONTINUE( 0x4000, 0x0400 ) ROM_CONTINUE( 0x4400, 0x0400 ) ROM_CONTINUE( 0x4800, 0x0400 ) ROM_CONTINUE( 0x4c00, 0x0400 ) ROM_CONTINUE( 0x6000, 0x0400 ) ROM_CONTINUE( 0x6400, 0x0400 ) ROM_REGION( 0x4000, "gfx1", 0 ) ROM_LOAD( "01.bin", 0x1000, 0x1000, CRC(300a6750) SHA1(0760eb852706ef72c61e889309ee94edc49a13dc) ) ROM_CONTINUE( 0x0000, 0x1000 ) ROM_LOAD( "02.bin", 0x3000, 0x1000, CRC(f04e14c4) SHA1(f628da48ad19c86000c56345fd96d415992bf9a9) ) ROM_CONTINUE( 0x2000, 0x1000 ) // piggy-backed colour PROMs ROM_REGION( 0x0040, "proms", 0 ) ROM_LOAD( "tbp18s030.02", 0x0000, 0x0020, CRC(3110ddae) SHA1(53b2e1cc07915592f6c868131ec296c63a407f04) ) ROM_LOAD( "tbp18s030.01", 0x0020, 0x0020, CRC(0f0782af) SHA1(32c0dd09ead5c70cee2657e9cb8cb9fcf54c5a6a) ) // PROMs inside epoxy block with CPU ROM_REGION( 0x0300, "user1", 0 ) ROM_LOAD( "tbp24s10.bin", 0x0000, 0x0100, CRC(8c0d886d) SHA1(03bb942861a639f30797fcb22f048f7908404955) ) ROM_LOAD( "tbp28s42.bin", 0x0100, 0x0200, CRC(9b8f310a) SHA1(8e17cc1adf441aec56d98d0809e1359d5175e8ed) ) ROM_END ROM_START( racknrol ) // has an AY-3-8910 on main pcb, but is unused? SN76489AN on daughterboard is used. ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "horz_p.bin", 0x0000, 0x1000, CRC(32ca5b43) SHA1(f3e7662f947dcdd80f6eae4f002d2fe64a825aff) ) ROM_CONTINUE( 0x2000, 0x1000 ) ROM_CONTINUE( 0x4000, 0x1000 ) ROM_CONTINUE( 0x6000, 0x1000 ) ROM_REGION( 0x8000, "gfx1", 0 ) ROM_LOAD( "horz_g.bin", 0x0000, 0x4000, CRC(97069ad5) SHA1(50199c7bc5083be23a34849cff17906795bf4067) ) ROM_LOAD( "horz_r.bin", 0x4000, 0x4000, CRC(ff64e84b) SHA1(ceabd522bae26743804987632f35f3c4b5aff179) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "82s123.bin", 0x0000, 0x0020, CRC(737802bf) SHA1(9b0476c51ce63898cd690e01e16ee83bae361cb2) ) ROM_REGION( 0x0200, "user1", 0 ) // unknown ROM_LOAD( "82s147.bin", 0x0000, 0x0200, CRC(aace7fa5) SHA1(6761530bb3585d2eaa97b7ae77b52e96782ffe0a) ) ROM_END ROM_START( hexpool ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "vert_p.bin", 0x0000, 0x1000, CRC(bdb078fc) SHA1(85a65c3038dc05a98eae71edf9efdd6659a2966a) ) ROM_CONTINUE( 0x2000, 0x1000 ) ROM_CONTINUE( 0x4000, 0x1000 ) ROM_CONTINUE( 0x6000, 0x1000 ) ROM_REGION( 0x8000, "gfx1", 0 ) ROM_LOAD( "vert_g.bin", 0x0000, 0x4000, CRC(7e257e80) SHA1(dabb10d076dc49fc130f58e6d1c4b04e6debce55) ) ROM_LOAD( "vert_r.bin", 0x4000, 0x4000, CRC(c5f0851e) SHA1(cedcdb29962c6cd65af9d57d0cb2533397d58f99) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "82s123.bin", 0x0000, 0x0020, CRC(737802bf) SHA1(9b0476c51ce63898cd690e01e16ee83bae361cb2) ) ROM_REGION( 0x0200, "user1", 0 ) // unknown ROM_LOAD( "82s147.bin", 0x0000, 0x0200, CRC(aace7fa5) SHA1(6761530bb3585d2eaa97b7ae77b52e96782ffe0a) ) ROM_END ROM_START( hexpoola ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "rom.4l", 0x0000, 0x1000, CRC(2ca8018d) SHA1(f0784d18bc7e77515bf2140d8993ae8178919853) ) ROM_CONTINUE( 0x2000, 0x1000 ) ROM_CONTINUE( 0x4000, 0x1000 ) ROM_CONTINUE( 0x6000, 0x1000 ) ROM_REGION( 0x8000, "gfx1", 0 ) ROM_LOAD( "rom.1m", 0x0000, 0x4000, CRC(7e257e80) SHA1(dabb10d076dc49fc130f58e6d1c4b04e6debce55) ) ROM_LOAD( "rom.1l", 0x4000, 0x4000, CRC(c5f0851e) SHA1(cedcdb29962c6cd65af9d57d0cb2533397d58f99) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "82s123.11r", 0x0000, 0x0020, CRC(deb2fcf4) SHA1(cdec737a9d9feae912f7cc04ca0adb48f859b5c2) ) ROM_REGION( 0x0200, "user1", 0 ) // unknown ROM_LOAD( "82s147.5pr", 0x0000, 0x0200, CRC(cf496b1e) SHA1(5b5ca52b3cc46e18990dae53a98984aeaf264241) ) ROM_REGION( 0x00eb, "plds", 0 ) ROM_LOAD( "82s153.6pr.bin", 0x0000, 0x00eb, CRC(bc07939a) SHA1(615b085575ad215662eab2777a2d8b9167c4b9c3) ) ROM_END ROM_START( trvchlng ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "senko11.bin", 0x0000, 0x1000, CRC(3657331d) SHA1(d9a9a4e4e2e696e70dfb888725c959ec8ce24e3d) ) ROM_CONTINUE( 0x2000, 0x1000 ) ROM_CONTINUE( 0x4000, 0x1000 ) ROM_CONTINUE( 0x6000, 0x1000 ) ROM_REGION( 0x100000, "user1", 0 ) ROM_LOAD( "questions", 0x000000, 0x100000, NO_DUMP ) ROM_REGION( 0x8000, "gfx1", 0 ) ROM_LOAD( "senko10.bin", 0x0000, 0x4000, CRC(234b59d0) SHA1(5eafdfc6d6a73575835b68361fe29a2dc61e8a83) ) ROM_LOAD( "senko12.bin", 0x4000, 0x4000, CRC(0bf6b92d) SHA1(6ca993c0642949a52fafea3bc57a08c6881e8120) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "senko1.bin", 0x0000, 0x0020, CRC(1434c7ff) SHA1(0ee5f5351dd84fbf8d3d8eaafbdbe86dd29960f8) ) ROM_END /* Bulls Eye Darts conversion by Senko Industries Ltd (1984) The base board for the conversion dates from 1981. Base Board ---------- There are 2 x Toshiba 2114, 2 x Mitsubushi 2101 and 5 x Intel 2115 making up the video RAM. There are 6 ROM sockets for the video ROM but the daughter card only connects to two of them. I believe that this is a version of Scramble/Galaxians video hardware. There are 4 x Toshiba 2114 that make up the CPU RAM. There are 8 ROM sockets for the CPU ROM. Tha daughter board does not connect to any of them but instead connects into the CPU socket (I'm guessing originally a Z80). Sound is provided at least by an AY-3-8910. Daughter Board -------------- The daughter board houses a 2650A CPU and another 40-pin cermet coated uncased device with the number scratched off. There is an 82S153 and an 82S147 hooked into the 2650. Amongst the TTL near the video ROMS is a single 2114. Now the bad news... There are three EPROMS and one PROM on the board. Alas, one of the graphics EPROMS does not verify consistently so I have provided three reads. A quick compare suggest one data line is random :-( */ ROM_START( bullsdrtg ) ROM_REGION( 0x8000, "maincpu", 0 ) ROM_LOAD( "cpu.bin", 0x0000, 0x1000, CRC(db34f130) SHA1(691f8a69a7157df49460f5927728ba52660eeede) ) ROM_CONTINUE( 0x2000, 0x1000 ) ROM_CONTINUE( 0x4000, 0x1000 ) ROM_CONTINUE( 0x6000, 0x1000 ) ROM_REGION( 0x8000, "gfx1", 0 ) ROM_LOAD( "vid_j1.bin", 0x0000, 0x4000, BAD_DUMP CRC(c2ad5c84) SHA1(8e3048607693afc40a775000f45790910e4d9312) ) ROM_LOAD( "vid_p.bin", 0x4000, 0x4000, CRC(535be505) SHA1(c20c7ac4e74e29e8954c443cca9dcc0df453a512) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "prom.bin", 0x0000, 0x0020, CRC(16b19bfa) SHA1(a0e9217f9bc5b06212d5f22dcc3dc4b2838788ba) ) ROM_END // Z80 games // YEAR NAME PARENT MACHINE INPUT STATE INIT ROT COMPANY, FULLNAME, FLAGS GAME( 1981, vpool, hustler, mooncrst, vpool, galaxold_state, empty_init, ROT90, "bootleg", "Video Pool (bootleg on Moon Cresta hardware)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1981, scramblb, scramble, scramblb, scramblb, galaxold_state, empty_init, ROT90, "bootleg", "Scramble (bootleg on Galaxian hardware)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1981, scramb2, scramble, scramb2, scramb2, galaxold_state, empty_init, ROT90, "bootleg", "Scramble (bootleg, set 1)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1981, scramb3, scramble, scramb3, scramb2, galaxold_state, empty_init, ROT90, "bootleg", "Scramble (bootleg, set 2)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1981, scrambler, scramble, scrambler, scrambler, galaxold_state, empty_init, ROT90, "bootleg (Reben S.A.)", "Scramble (Reben S.A. Spanish bootleg)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1981, scrambleo, scramble, scrambleo, scrambleo, galaxold_state, empty_init, ROT90, "bootleg (Okapi)", "Scramble (Okapi bootleg)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1981, 4in1, 0, _4in1, 4in1, galaxold_state, init_4in1, ROT90, "Armenia / Food and Fun", "4 Fun in 1", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) GAME( 1982, dkongjrm, dkongjr, dkongjrm, dkongjrm, galaxold_state, empty_init, ROT90, "bootleg", "Donkey Kong Jr. (bootleg on Moon Cresta hardware, set 1)", MACHINE_WRONG_COLORS | MACHINE_IMPERFECT_SOUND | MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1982, dkongjrmc, dkongjr, dkongjrmc, dkongjrmc, galaxold_state, empty_init, ROT90, "bootleg (Centromatic)", "Donkey Kong Jr. (bootleg on Moon Cresta hardware, set 2)", MACHINE_WRONG_COLORS | MACHINE_IMPERFECT_GRAPHICS | MACHINE_IMPERFECT_SOUND | MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) // sprites leave artifacts GAME( 1982, tazzmang, tazmania, tazzmang, tazzmang, galaxold_state, empty_init, ROT90, "bootleg", "Tazz-Mania (bootleg on Galaxian hardware)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1982, tazzmang2, tazmania, tazzmang, tazzmang, galaxold_state, empty_init, ROT90, "bootleg", "Tazz-Mania (bootleg on Galaxian hardware with Starfield)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) // Videotron cartridge system GAME( 1981, hustlerb3, hustler, videotron, hustlerb3, galaxold_state, empty_init, ROT90, "bootleg (Videotron)", "Video Pool (Video Hustler bootleg)", MACHINE_SUPPORTS_SAVE ) GAME( 1981, froggerv, frogger, videotron, froggerv, galaxold_state, empty_init, ROT90, "bootleg (Videotron / Gamepack)", "Frogger (Videotron bootleg)", MACHINE_SUPPORTS_SAVE ) // S2650 games // YEAR NAME PARENT MACHINE INPUT STATE INIT ROT COMPANY, FULLNAME, FLAGS GAME( 1983, hunchbkg, hunchbak, hunchbkg, hunchbkg, galaxold_state, empty_init, ROT90, "Century Electronics", "Hunchback (Galaxian hardware)", MACHINE_SUPPORTS_SAVE ) GAME( 1983, hunchbgb, hunchbak, hunchbkg, hunchbkg, galaxold_state, empty_init, ROT90, "bootleg (FAR S.A.)", "Hunchback (FAR S.A. bootleg on Galaxian hardware)", MACHINE_SUPPORTS_SAVE ) GAME( 1983, spcwarp, 0, spcwarp, hunchbkg, galaxold_state, empty_init, ROT90, "Century Electronics", "Space Warp? (Cosmos conversion on Galaxian hardware)", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE | MACHINE_WRONG_COLORS ) // bad dump GAME( 1984, drivfrcg, drivfrcp, drivfrcg, drivfrcg, galaxold_state, empty_init, ROT90, "Shinkai Inc. (Magic Electronics USA license)", "Driving Force (Galaxian conversion)", MACHINE_SUPPORTS_SAVE ) GAME( 1984, drivfrct, drivfrcp, drivfrcg, drivfrcg, galaxold_state, empty_init, ROT90, "bootleg (EMT Germany)", "Top Racer (bootleg of Driving Force)", MACHINE_SUPPORTS_SAVE ) // Video Klein PCB GAME( 1985, drivfrcb, drivfrcp, drivfrcg, drivfrcg, galaxold_state, empty_init, ROT90, "bootleg (Elsys Software)", "Driving Force (Galaxian conversion bootleg)", MACHINE_SUPPORTS_SAVE ) GAME( 1985, drivfrcsg, drivfrcp, drivfrcg, drivfrcg, galaxold_state, empty_init, ROT90, "Seatongrove UK", "Driving Force (Galaxian conversion, Seatongrove UK, E-0010)", MACHINE_SUPPORTS_SAVE ) GAME( 1985, drivfrcsga,drivfrcp, drivfrcg, drivfrcg, galaxold_state, empty_init, ROT90, "Seatongrove UK", "Driving Force (Galaxian conversion, Seatongrove UK, E-0237)", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE ) // incomplete dump GAME( 1986, racknrol, 0, racknrol, racknrol, galaxold_state, empty_init, ROT0, "Senko Industries (Status license from Shinkai Inc.)", "Rack + Roll", MACHINE_SUPPORTS_SAVE ) GAME( 1986, hexpool, racknrol, racknrol, racknrol, galaxold_state, empty_init, ROT90, "Senko Industries (Shinkai Inc. license)", "Hex Pool (Shinkai)", MACHINE_SUPPORTS_SAVE ) // still has Senko logo in gfx rom GAME( 1985, hexpoola, racknrol, hexpoola, racknrol, galaxold_state, empty_init, ROT90, "Senko Industries", "Hex Pool (Senko)", MACHINE_SUPPORTS_SAVE ) GAME( 1985, trvchlng, 0, racknrol, trvchlng, galaxold_state, empty_init, ROT90, "Joyland (Senko license)", "Trivia Challenge", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE ) GAME( 1985, bullsdrtg, bullsdrt, bullsdrtg, racknrol, galaxold_state, init_bullsdrtg, ROT90, "Senko Industries", "Bulls Eye Darts (Galaxian conversion)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_GRAPHICS | MACHINE_WRONG_COLORS )
47.130711
338
0.723902
Robbbert
bf3ce54d91f05f168fec944a8115782b462a599b
10,018
cpp
C++
shared/linux/LinuxUtils.cpp
iProgramMC/proton
1c383134b44a22cebab8e8db1afb17afd59dd543
[ "XFree86-1.1" ]
47
2018-07-30T12:05:15.000Z
2022-03-31T04:12:03.000Z
shared/linux/LinuxUtils.cpp
iProgramMC/proton
1c383134b44a22cebab8e8db1afb17afd59dd543
[ "XFree86-1.1" ]
11
2019-03-31T13:05:10.000Z
2021-11-03T11:37:18.000Z
shared/linux/LinuxUtils.cpp
iProgramMC/proton
1c383134b44a22cebab8e8db1afb17afd59dd543
[ "XFree86-1.1" ]
16
2019-07-09T07:59:00.000Z
2022-02-25T15:49:06.000Z
#include "LinuxUtils.h" #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <sys/time.h> #include <cstdlib> #include <cstdarg> #include <cassert> #include "PlatformSetup.h" #include <sys/stat.h> //for mkdir #ifndef _CONSOLE //if console is defined, we might be a linux command line server or something, we don't know what GL/GLES stuff //is and don't use BaseApp #include "BaseApp.h" #endif #include <time.h> using namespace std; void StringReplace(const std::string& what, const std::string& with, std::string& in); vector<string> StringTokenize (const string & theString, const string & theDelimiter ); string GetDateAndTimeAsString(); void AppendStringToFile(string filename, string text); #ifndef RT_CUSTOM_LOGMSG void LogMsg( const char* traceStr, ... ) { va_list argsVA; const int logSize = 4096; char buffer[logSize]; memset ( (void*)buffer, 0, logSize ); va_start ( argsVA, traceStr ); vsnprintf( buffer, logSize, traceStr, argsVA ); va_end( argsVA ); //__Linux_log_write(Linux_LOG_ERROR,GetAppName(), buffer); printf ((char*)buffer); printf ("\r\n"); fflush(stdout); AppendStringToFile( GetBaseAppPath()+"log.txt", GetDateAndTimeAsString()+": "+string(buffer)+"\r\n"); #ifndef _CONSOLE if (IsBaseAppInitted()) { GetBaseApp()->GetConsole()->AddLine(buffer); } #endif } #endif string GetBaseAppPath() { char szDir[1024]; getcwd( szDir, 1024); return string(szDir)+"/"; } string GetSavePath() { return ""; } //returns the SD card user save path (will be deleted when app is uninstalled on 2.2+) //returns "" if no SD card/external writable storage available string GetAppCachePath() { return ""; //invalid } void LaunchEmail(string subject, string content) { } void LaunchURL(string url) { LogMsg("LaunchURL: %s", url.c_str()); } string GetClipboardText() { return ""; } float GetDeviceOSVersion() { //TODO return 0.0f; } string GetMacAddress() { //TODO return ""; //unimplemented } bool IsIPhone3GS() { return false; } bool IsDesktop() { switch (GetEmulatedPlatformID()) { case PLATFORM_ID_WINDOWS: case PLATFORM_ID_OSX: case PLATFORM_ID_LINUX: return true; default: return false; } } ePlatformID GetPlatformID() { return PLATFORM_ID_LINUX; } bool IsIphoneOriPad() { return false; } bool IsIphone() { return false; } bool IsIphone4() { return false; } bool IsIPAD() { return false; } eDeviceMemoryClass GetDeviceMemoryClass() { return C_DEVICE_MEMORY_CLASS_1; } int GetYOffset() { return 0; } unsigned int GetSystemTimeTick() { //Note: Due to using an unsigned int for millseconds, the timer kept rolling over on my linux game server I wrote for //Tanked - so I changed this to start at 0, which gives me 46 days of running before the roll-over. Why don't I just change //my stuff to handle timing roll-overs or perhaps use a bigger type for timing? Well.. hmm. Ok, maybe, but for now this. -Seth static unsigned int incrementingTimer = 0; static double buildUp = 0; static double lastTime = 0; struct timespec time; clock_gettime(CLOCK_MONOTONIC, &time); double timeDouble = time.tv_sec*1000 + time.tv_nsec/1000000; double change = timeDouble -lastTime; if (change > 0 && change < (1000*120) ) { incrementingTimer += change; } lastTime = timeDouble; return incrementingTimer; } uint64 GetSystemTimeTickLong() { struct timespec time; clock_gettime(CLOCK_MONOTONIC, &time); uint64 accum; accum = time.tv_sec*1000 + time.tv_nsec/1000000; return accum; } string GetDateAndTimeAsString() { time_t ltime; time( &ltime ); tm today = *localtime( &ltime ); char stTemp[128]; sprintf(stTemp, "%d/%d %d:%d:%d", today.tm_mday, today.tm_mon+1, today.tm_hour, today.tm_min, today.tm_sec); return string(stTemp); } void GetDateAndTime(int *monthOut, int *dayOut, int *yearOut, int *hourOut, int *minOut, int *secOut) { time_t ltime; time( &ltime ); tm today = *localtime( &ltime ); *monthOut = today.tm_mon+1; *dayOut = today.tm_mday; *yearOut = today.tm_year+1900; *hourOut = today.tm_hour; *minOut = today.tm_min; *secOut = today.tm_sec; } double GetSystemTimeAccurate() { return double(GetSystemTimeTick()); return 0; } unsigned int GetFreeMemory() { return 0; //don't care on the PC } string g_string; void SetLastStringInput( string s ) { g_string = s; } std::string GetLastStringInput() { return g_string; } eNetworkType IsNetReachable( string url ) { return C_NETWORK_WIFI; } int GetSystemData() { return C_PIRATED_NO; } void RemoveFile( string fileName, bool bAddSavePath) { if (bAddSavePath) { fileName = GetSavePath()+fileName; } if (unlink(fileName.c_str()) == -1) { switch (errno) { case EACCES: LogMsg("Warning: Unable to delete file %s, no access", fileName.c_str()); break; case EBUSY: LogError("Warning: Unable to delete file %s, file is being used", fileName.c_str()); break; case EPERM: LogMsg("Warning: Unable to delete file %s, may be a dir", fileName.c_str()); break; case EROFS: LogMsg("Warning: Unable to delete file %s, File system is read only", fileName.c_str()); break; default: //LogMsg("Warning: Unable to delete file %s, unknown error", fileName.c_str()); //file doesn't exist break; } } } string GetRegionString() { return "en_us"; } //month is 1-12 btw int GetDaysSinceDate(int month,int day, int year) { //LogMsg("GetDaysSinceDate url not done"); assert(!"no!"); return 0; } bool RTCreateDirectory(const std::string &dir_name) { #ifdef _DEBUG LogMsg("CreateDirectory: %s", dir_name.c_str()); #endif if (dir_name.empty()) return false; // this will be a full path std::string full_path; // calculate the full path // TODO: add here Linux version of GetFullPathName full_path = dir_name; return ::mkdir(full_path.c_str(), 0755) == 0; } void CreateDirectoryRecursively(string basePath, string path) { StringReplace("\\", "/", path); StringReplace("\\", "/", basePath); vector<string> tok = StringTokenize(path, "/"); if (!basePath.empty()) { if (basePath[basePath.size()-1] != '/') basePath += "/"; } path = ""; for (unsigned int i=0; i < tok.size(); i++) { path += tok[i].c_str(); //LogMsg("Creating %s%s", basePath.c_str(), path.c_str()); RTCreateDirectory(basePath+path); path += "/"; } } vector<string> GetDirectoriesAtPath(string path) { vector<string> v; #ifdef _DEBUG //LogMsg("GetDirectoriesAtPath: %s", path.c_str()); #endif dirent * buf, * ent; DIR *dp; dp = opendir(path.c_str()); if (!dp) { LogError("GetDirectoriesAtPath: opendir failed"); return v; } buf = (dirent*) malloc(sizeof(dirent)+512); while (readdir_r(dp, buf, &ent) == 0 && ent) { if (ent->d_name[0] == '.' && ent->d_name[1] == 0) continue; if (ent->d_name[0] == '.' && ent->d_name[1] == '.' && ent->d_name[2] == 0) continue; //LogMsg("Got %s. type %d", ent->d_name, int(ent->d_type)); if (ent->d_type == DT_DIR) { v.push_back(ent->d_name); } } free (buf); closedir(dp); return v; } vector<string> GetFilesAtPath(string path) { #ifdef _DEBUG //LogMsg("GetFilesAtPath: %s", path.c_str()); #endif vector<string> v; dirent * buf, * ent; DIR *dp; dp = opendir(path.c_str()); if (!dp) { LogError("GetDirectoriesAtPath: opendir failed"); return v; } buf = (dirent*) malloc(sizeof(dirent)+512); while (readdir_r(dp, buf, &ent) == 0 && ent) { if (ent->d_name[0] == '.' && ent->d_name[1] == 0) continue; if (ent->d_name[0] == '.' && ent->d_name[1] == '.' && ent->d_name[2] == 0) continue; //LogMsg("Got %s. type %d", ent->d_name, int(ent->d_type)); if (ent->d_type != DT_DIR) //regular file { v.push_back(ent->d_name); } } free (buf); closedir(dp); return v; } bool RemoveDirectoryRecursively(string path) { // LogMsg(" RemoveDirectoryRecursively: %s", path.c_str()); dirent * buf, * ent; DIR *dp; dp = opendir(path.c_str()); if (!dp) { string error = "unknown"; switch (errno) { case EACCES: error = "EACCES"; break; case EAGAIN: error = "EBADFID"; break; case EBUSY: error = "EBUSY"; break; case EEXIST: error = "EEXIST"; break; case EFAULT: error = "EFAULT"; break; default: ; } LogError("RemoveDirectoryRecursively: opendir of %s failed with error %d (%s)", path.c_str(), errno, error.c_str()); return false; } buf = (dirent*) malloc(sizeof(dirent)+512); while (readdir_r(dp, buf, &ent) == 0 && ent) { if (ent->d_name[0] == '.' && ent->d_name[1] == 0) continue; if (ent->d_name[0] == '.' && ent->d_name[1] == '.' && ent->d_name[2] == 0) continue; // LogMsg("Got %s. type %d", ent->d_name, int(ent->d_type)); if (ent->d_type != DT_DIR) //regular file { string fName = path+string("/")+ent->d_name; // LogMsg("Deleting %s", fName.c_str()); unlink( fName.c_str()); } if (ent->d_type == DT_DIR) //regular file { string fName = path+string("/")+ent->d_name; // LogMsg("Entering DIR %s",fName.c_str()); if (!RemoveDirectoryRecursively(fName.c_str())) { LogError("Error removing dir %s", fName.c_str()); break; } } } free (buf); closedir(dp); //delete the final dir as well rmdir( path.c_str()); return true; //success } bool CheckIfOtherAudioIsPlaying() { return false; } void CreateAppCacheDirIfNeeded() { //only applicable to iOS } void NotifyOSOfOrientationPreference(eOrientationMode orientation) { } bool HasVibration() { return true; } string GetNetworkType() { return "none"; // not supported for this OS }
20.197581
130
0.632561
iProgramMC
bf3d26bbed40fcdc015a95d6113f6f6785b9e6b6
574
cpp
C++
src/bug_01.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_01.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_01.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
#include "advent.h" void BugFix<1>::solve1st() { std::string input; std::getline(*mIn, input); int repeatsSum = 0; for (size_t i = 0; i <= input.size(); ++i) { if (input[i] == input[(i + 1) % input.size()]) repeatsSum += input[i] - '0'; } *mOut << repeatsSum << std::endl; } void BugFix<1>::solve2nd() { std::string input; std::getline(*mIn, input); int repeatsSum = 0; for (size_t i = 0; i <= input.size(); ++i) { if (input[i] == input[(i + input.size() / 2) % input.size()]) repeatsSum += input[i] - '0'; } *mOut << repeatsSum << std::endl; }
18.516129
63
0.559233
happanda
bf42262f17fe893e0a6135815e8120ecd9d29e36
18,889
cpp
C++
modules/newbase/newbase/NFmiGdalArea.cpp
fmidev/smartmet-workstation-vtk
ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99
[ "MIT" ]
null
null
null
modules/newbase/newbase/NFmiGdalArea.cpp
fmidev/smartmet-workstation-vtk
ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99
[ "MIT" ]
null
null
null
modules/newbase/newbase/NFmiGdalArea.cpp
fmidev/smartmet-workstation-vtk
ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99
[ "MIT" ]
null
null
null
// ====================================================================== /*! * \file NFmiGdalArea.cpp * \brief Implementation of class NFmiGdalArea */ // ====================================================================== #ifdef UNIX #include "NFmiGdalArea.h" #include "NFmiString.h" #include "NFmiStringTools.h" #include <boost/math/constants/constants.hpp> #include <gdal/ogr_spatialref.h> #include <cmath> #include <iomanip> using namespace std; // See also NFmiLatLonArea::WKT() std::string fmiwkt = R"(GEOGCS["FMI_Sphere",DATUM["FMI_2007",SPHEROID["FMI_Sphere",6371220,0]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]])"; // ---------------------------------------------------------------------- /*! * \brief Destructor does nothing special */ // ---------------------------------------------------------------------- NFmiGdalArea::~NFmiGdalArea() = default; // ---------------------------------------------------------------------- /*! * \brief Default constructor */ // ---------------------------------------------------------------------- NFmiGdalArea::NFmiGdalArea() : NFmiArea(), itsDatum("WGS84"), itsDescription(), itsWKT(), itsBottomLeftLatLon(), itsTopRightLatLon(), itsWorldRect(), itsSpatialReference(), itsLatLonToWorldXYTransformation(), itsWorldXYToLatLonTransformation() { } // ---------------------------------------------------------------------- /*! * \brief Copy constructor */ // ---------------------------------------------------------------------- NFmiGdalArea::NFmiGdalArea(const NFmiGdalArea &theArea) = default; // ---------------------------------------------------------------------- /*! * \brief Assignment operator */ // ---------------------------------------------------------------------- NFmiGdalArea &NFmiGdalArea::operator=(const NFmiGdalArea &theArea) = default; // ---------------------------------------------------------------------- /*! * \brief Construct from user input */ // ---------------------------------------------------------------------- NFmiGdalArea::NFmiGdalArea(const std::string &theDatum, const std::string &theDescription, const NFmiPoint &theBottomLeftLatLon, const NFmiPoint &theTopRightLatLon, const NFmiPoint &theTopLeftXY, const NFmiPoint &theBottomRightXY, bool usePacificView) : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView), itsDatum(theDatum), itsDescription(theDescription), itsBottomLeftLatLon(theBottomLeftLatLon), itsTopRightLatLon(theTopRightLatLon), itsWorldRect() { init(); } // ---------------------------------------------------------------------- /*! * \brief Construct from user input */ // ---------------------------------------------------------------------- NFmiGdalArea::NFmiGdalArea(const std::string &theDatum, const OGRSpatialReference &theCRS, const NFmiPoint &theBottomLeftLatLon, const NFmiPoint &theTopRightLatLon, const NFmiPoint &theTopLeftXY, const NFmiPoint &theBottomRightXY, bool usePacificView) : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView), itsDatum(theDatum), itsDescription(), itsBottomLeftLatLon(theBottomLeftLatLon), itsTopRightLatLon(theTopRightLatLon), itsWorldRect(), itsSpatialReference(new OGRSpatialReference(theCRS)) { // Guess a good value for itsDescription const char *auth = theCRS.GetAuthorityName(nullptr); if (auth != nullptr) { itsDescription = std::string(auth); const char *code = theCRS.GetAuthorityCode(nullptr); if (code != nullptr) itsDescription += ":" + std::string(code); } else { char *out; theCRS.exportToWkt(&out); itsDescription = out; OGRFree(out); } init(); } // ---------------------------------------------------------------------- /*! * \brief Construct from bounding box */ // ---------------------------------------------------------------------- NFmiGdalArea::NFmiGdalArea(const std::string &theDatum, const OGRSpatialReference &theCRS, double theXmin, double theYmin, double theXmax, double theYmax, const NFmiPoint &theTopLeftXY, const NFmiPoint &theBottomRightXY, bool usePacificView) : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView), itsDatum(theDatum), itsDescription(), itsBottomLeftLatLon(), itsTopRightLatLon(), itsWorldRect(NFmiPoint(theXmin, theYmin), NFmiPoint(theXmax, theYmax)), itsSpatialReference(new OGRSpatialReference(theCRS)) { // Guess a good value for itsDescription const char *auth = theCRS.GetAuthorityName(nullptr); if (auth != nullptr) { itsDescription = std::string(auth); const char *code = theCRS.GetAuthorityCode(nullptr); if (code != nullptr) itsDescription += ":" + std::string(code); } else { char *out; theCRS.exportToWkt(&out); itsDescription = out; OGRFree(out); } // The needed spatial references if (!itsSpatialReference) { itsSpatialReference.reset(new OGRSpatialReference); OGRErr err = itsSpatialReference->SetFromUserInput(itsDescription.c_str()); if (err != OGRERR_NONE) throw std::runtime_error("GDAL does not understand projection spec: '" + itsDescription + "'"); } OGRErr err; boost::shared_ptr<OGRSpatialReference> datum(new OGRSpatialReference); if (itsDatum == "FMI") err = datum->SetFromUserInput(fmiwkt.c_str()); else err = datum->SetFromUserInput(itsDatum.c_str()); if (err != OGRERR_NONE) throw std::runtime_error("Failed to set datum: '" + itsDatum + "'"); // The needed coordinate transformations itsWorldXYToLatLonTransformation.reset( OGRCreateCoordinateTransformation(itsSpatialReference.get(), datum.get())); if (!itsWorldXYToLatLonTransformation) throw std::runtime_error("Projection spec unsable with the chosen datum (" + itsDatum + "): '" + itsDescription + "'"); itsLatLonToWorldXYTransformation.reset( OGRCreateCoordinateTransformation(datum.get(), itsSpatialReference.get())); if (!itsLatLonToWorldXYTransformation) throw std::runtime_error("Projection spec unsable with the chosen datum (" + itsDatum + "): '" + itsDescription + "'"); // Bottom left and top right coordinates - needed only for geographic projections (Width() // calculations) // The same data could be extracted from the WorldXYRect too though - and these variables // would not be needed. double x1 = theXmin; double y1 = theYmin; double x2 = theXmax; double y2 = theYmax; itsWorldXYToLatLonTransformation->Transform(1, &x1, &y1); itsWorldXYToLatLonTransformation->Transform(1, &x2, &y2); itsBottomLeftLatLon = NFmiPoint(x1, y1); itsTopRightLatLon = NFmiPoint(x2, y2); // Initialize itsWKT char *out; itsSpatialReference->exportToWkt(&out); itsWKT = out; OGRFree(out); } // ---------------------------------------------------------------------- /*! * \brief Return class ID */ // ---------------------------------------------------------------------- unsigned long NFmiGdalArea::ClassId() const { return kNFmiGdalArea; } // ---------------------------------------------------------------------- /*! * \brief Return class name */ // ---------------------------------------------------------------------- const char *NFmiGdalArea::ClassName() const { return "kNFmiGdalArea"; } // ---------------------------------------------------------------------- /*! * \brief Return a clone */ // ---------------------------------------------------------------------- NFmiArea *NFmiGdalArea::Clone() const { return new NFmiGdalArea(*this); } // ---------------------------------------------------------------------- /*! * \brief Area descriptor */ // ---------------------------------------------------------------------- const std::string NFmiGdalArea::AreaStr() const { return itsDescription; } // ---------------------------------------------------------------------- /*! * \brief Datum */ // ---------------------------------------------------------------------- const std::string &NFmiGdalArea::Datum() const { return itsDatum; } // ---------------------------------------------------------------------- /*! * \brief Return the WKT description */ // ---------------------------------------------------------------------- const std::string NFmiGdalArea::WKT() const { return itsWKT; } // ---------------------------------------------------------------------- /*! * \brief Equality comparison */ // ---------------------------------------------------------------------- bool NFmiGdalArea::operator==(const NFmiGdalArea &theArea) const { return (itsBottomLeftLatLon == theArea.itsBottomLeftLatLon && itsTopRightLatLon == theArea.itsTopRightLatLon && itsWorldRect == theArea.itsWorldRect && itsDescription == theArea.itsDescription && itsDatum == theArea.itsDatum); } // ---------------------------------------------------------------------- /*! * \brief Inequality comparison */ // ---------------------------------------------------------------------- bool NFmiGdalArea::operator!=(const NFmiGdalArea &theArea) const { return !(*this == theArea); } // ---------------------------------------------------------------------- /*! * \brief Equality comparison */ // ---------------------------------------------------------------------- bool NFmiGdalArea::operator==(const NFmiArea &theArea) const { return *this == static_cast<const NFmiGdalArea &>(theArea); } // ---------------------------------------------------------------------- /*! * \brief Inequality comparison */ // ---------------------------------------------------------------------- bool NFmiGdalArea::operator!=(const NFmiArea &theArea) const { return !(*this == theArea); } // ---------------------------------------------------------------------- /*! * \brief Write the projection definition to a file */ // ---------------------------------------------------------------------- std::ostream &NFmiGdalArea::Write(std::ostream &file) const { NFmiString tmp1 = itsDatum; NFmiString tmp2 = itsDescription; NFmiArea::Write(file); file << itsBottomLeftLatLon << itsTopRightLatLon << tmp1 << tmp2; return file; } // ---------------------------------------------------------------------- /*! * \brief Read new projection definition from the input stream */ // ---------------------------------------------------------------------- std::istream &NFmiGdalArea::Read(std::istream &file) { NFmiString tmp1; NFmiString tmp2; NFmiArea::Read(file); file >> itsBottomLeftLatLon >> itsTopRightLatLon >> tmp1 >> tmp2; itsDatum = tmp1.CharPtr(); itsDescription = tmp2.CharPtr(); init(); return file; } // ---------------------------------------------------------------------- /*! * \brief XY coordinate to LatLon */ // ---------------------------------------------------------------------- const NFmiPoint NFmiGdalArea::ToLatLon(const NFmiPoint &theXYPoint) const { double xscale = Width() / itsWorldRect.Width(); double yscale = Height() / itsWorldRect.Height(); double worldx = itsWorldRect.Left() + (theXYPoint.X() - Left()) / xscale; double worldy = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / yscale; return WorldXYToLatLon(NFmiPoint(worldx, worldy)); } // ---------------------------------------------------------------------- /*! * \brief LatLon to XY-coordinate */ // ---------------------------------------------------------------------- const NFmiPoint NFmiGdalArea::ToXY(const NFmiPoint &theLatLonPoint) const { NFmiPoint latlon(FixLongitude(theLatLonPoint.X()), theLatLonPoint.Y()); NFmiPoint worldxy = LatLonToWorldXY(latlon); double xscale = Width() / itsWorldRect.Width(); double yscale = Height() / itsWorldRect.Height(); double x = Left() + xscale * (worldxy.X() - itsWorldRect.Left()); double y = Top() + yscale * (itsWorldRect.Bottom() - worldxy.Y()); return NFmiPoint(x, y); } // ---------------------------------------------------------------------- /*! * \brief XY-coordinate to World coordinates */ // ---------------------------------------------------------------------- const NFmiPoint NFmiGdalArea::XYToWorldXY(const NFmiPoint &theXYPoint) const { double xscale = Width() / itsWorldRect.Width(); double yscale = Height() / itsWorldRect.Height(); double worldx = itsWorldRect.Left() + (theXYPoint.X() - Left()) / xscale; double worldy = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / yscale; return NFmiPoint(worldx, worldy); } // ---------------------------------------------------------------------- /*! * \brief World coordinates to LatLon */ // ---------------------------------------------------------------------- const NFmiPoint NFmiGdalArea::WorldXYToLatLon(const NFmiPoint &theXYPoint) const { if (!itsWorldXYToLatLonTransformation) throw std::runtime_error("Trying to use an uninitialized GDAL area"); double x = theXYPoint.X(); double y = theXYPoint.Y(); if (!itsWorldXYToLatLonTransformation->Transform(1, &x, &y)) return NFmiPoint(kFloatMissing, kFloatMissing); return NFmiPoint(x, y); } // ---------------------------------------------------------------------- /*! * \brief LatLon to world coordinates */ // ---------------------------------------------------------------------- const NFmiPoint NFmiGdalArea::LatLonToWorldXY(const NFmiPoint &theLatLonPoint) const { if (!itsLatLonToWorldXYTransformation) throw std::runtime_error("Trying to use an uninitialized GDAL area"); double x = theLatLonPoint.X(); double y = theLatLonPoint.Y(); if (!itsLatLonToWorldXYTransformation->Transform(1, &x, &y)) return NFmiPoint(kFloatMissing, kFloatMissing); return NFmiPoint(x, y); } // ---------------------------------------------------------------------- /*! * \brief Return the world rectangle */ // ---------------------------------------------------------------------- const NFmiRect NFmiGdalArea::WorldRect() const { return itsWorldRect; } // ---------------------------------------------------------------------- /*! * \brief */ // ---------------------------------------------------------------------- NFmiArea *NFmiGdalArea::NewArea(const NFmiPoint &theBottomLeftLatLon, const NFmiPoint &theTopRightLatLon, bool allowPacificFix) const { if (allowPacificFix) { PacificPointFixerData fix = NFmiArea::PacificPointFixer(theBottomLeftLatLon, theTopRightLatLon); return new NFmiGdalArea(itsDatum, itsDescription, fix.itsBottomLeftLatlon, fix.itsTopRightLatlon, TopLeft(), BottomRight(), fix.fIsPacific); } else return new NFmiGdalArea(itsDatum, itsDescription, theBottomLeftLatLon, theTopRightLatLon, TopLeft(), BottomRight(), PacificView()); } // ---------------------------------------------------------------------- /*! * \brief Initialize the projection transformation objects */ // ---------------------------------------------------------------------- void NFmiGdalArea::init() { // The needed spatial references if (!itsSpatialReference) { itsSpatialReference.reset(new OGRSpatialReference); OGRErr err = itsSpatialReference->SetFromUserInput(itsDescription.c_str()); if (err != OGRERR_NONE) throw std::runtime_error("GDAL does not understand projection spec: '" + itsDescription + "'"); } OGRErr err; boost::shared_ptr<OGRSpatialReference> datum(new OGRSpatialReference); if (itsDatum == "FMI") err = datum->SetFromUserInput(fmiwkt.c_str()); else err = datum->SetFromUserInput(itsDatum.c_str()); if (err != OGRERR_NONE) throw std::runtime_error("Failed to set datum: '" + itsDatum + "'"); // The needed coordinate transformations itsWorldXYToLatLonTransformation.reset( OGRCreateCoordinateTransformation(itsSpatialReference.get(), datum.get())); if (!itsWorldXYToLatLonTransformation) throw std::runtime_error("Projection spec unsable with the chosen datum (" + itsDatum + "): '" + itsDescription + "'"); itsLatLonToWorldXYTransformation.reset( OGRCreateCoordinateTransformation(datum.get(), itsSpatialReference.get())); if (!itsLatLonToWorldXYTransformation) throw std::runtime_error("Projection spec unsable with the chosen datum (" + itsDatum + "): '" + itsDescription + "'"); // The needed world XY rectangle itsWorldRect = NFmiRect(LatLonToWorldXY(itsBottomLeftLatLon), LatLonToWorldXY(itsTopRightLatLon)); // Initialize itsWKT char *out; itsSpatialReference->exportToWkt(&out); itsWKT = out; OGRFree(out); } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- double NFmiGdalArea::WorldXYWidth() const { if (!itsSpatialReference->IsGeographic()) return WorldRect().Width(); else { double pi = boost::math::constants::pi<double>(); double circumference = 2 * pi * 6371220; double dlon = itsTopRightLatLon.X() - itsBottomLeftLatLon.X(); if (dlon < 0) dlon += 360; double clat = 0.5 * (itsBottomLeftLatLon.Y() + itsTopRightLatLon.Y()); return dlon / 360 * circumference * cos(clat * pi / 180); } } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- double NFmiGdalArea::WorldXYHeight() const { if (!itsSpatialReference->IsGeographic()) return WorldRect().Height(); else { double pi = boost::math::constants::pi<double>(); double circumference = 2 * pi * 6371220; double dlat = itsTopRightLatLon.Y() - itsBottomLeftLatLon.Y(); return dlat / 360.0 * circumference; // angle -> meters } } #endif // UNIX // ======================================================================
33.196837
137
0.498015
fmidev
bf440988370b8e4e7597f6cc29eadafaad586aa7
1,100
cpp
C++
virtual-base-class.cpp
rsds8540/cpp-solved-problems
cbd63e0743d7653d8e06401026c16aa1dd5f775b
[ "Apache-2.0" ]
1
2021-04-27T18:23:05.000Z
2021-04-27T18:23:05.000Z
virtual-base-class.cpp
rsds8540/cpp-solved-problems
cbd63e0743d7653d8e06401026c16aa1dd5f775b
[ "Apache-2.0" ]
null
null
null
virtual-base-class.cpp
rsds8540/cpp-solved-problems
cbd63e0743d7653d8e06401026c16aa1dd5f775b
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class student { protected: int roll; public: void setroll(int r) { roll = r; } void getroll() { cout << "Roll No." << roll << endl; } }; class test : virtual public student { protected: float che, phy; public: void setmarks(float c, float p) { che = c; phy = p; } void getmarks() { cout<<"Marks in Phy and Che are "<<phy<<" and "<<che<<endl; } }; class sports: virtual public student { protected: int score; public: void setscore(int s) { score = s; } void getscore() { cout<<"Score is "<<score<<endl; } }; class result : public test,public sports { protected: float res; public: void display() { getroll(); getmarks(); getscore(); cout<<"Your total result is "<<(res+score+che+phy)<<endl; } }; int main() { result rohit; rohit.setroll(54); rohit.setmarks(63,62); rohit.setscore(78); rohit.display(); return 0; }
14.285714
67
0.519091
rsds8540
bf44380203645d8829ff51d0c1aaa496b20ab063
257
cpp
C++
examples/03_module/06_value_and_reference_params/sample_value_ref.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri
91322930bedf6897b6244c778c707231560ccb15
[ "MIT" ]
null
null
null
examples/03_module/06_value_and_reference_params/sample_value_ref.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri
91322930bedf6897b6244c778c707231560ccb15
[ "MIT" ]
null
null
null
examples/03_module/06_value_and_reference_params/sample_value_ref.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri
91322930bedf6897b6244c778c707231560ccb15
[ "MIT" ]
null
null
null
#include "sample_value_ref.h" // void pass_by_val_and_ref(int num1, int & num2, const int & num3) { num1 = 20; // modifying this value is local to function num2 = 50; // modifying this value will change caller variable //num3 = 100; can't be modified }
25.7
64
0.712062
acc-cosc-1337-spring-2019
bf44bc72b3fd86735b662c04470c43fabd94984a
5,271
hpp
C++
Query/GpDbQueryRes.hpp
ITBear/GpDbClient
877f1fba2816509d06c8c798fbc788a706859644
[ "Apache-2.0" ]
null
null
null
Query/GpDbQueryRes.hpp
ITBear/GpDbClient
877f1fba2816509d06c8c798fbc788a706859644
[ "Apache-2.0" ]
null
null
null
Query/GpDbQueryRes.hpp
ITBear/GpDbClient
877f1fba2816509d06c8c798fbc788a706859644
[ "Apache-2.0" ]
null
null
null
#pragma once #include "GpDbQueryResState.hpp" namespace GPlatform { class GPDBCLIENT_API GpDbQueryRes { public: CLASS_REMOVE_CTRS_MOVE_COPY(GpDbQueryRes) CLASS_DECLARE_DEFAULTS(GpDbQueryRes) using StateTE = GpDbQueryResState::EnumT; public: GpDbQueryRes (void) noexcept; virtual ~GpDbQueryRes (void) noexcept; virtual void Clear (void) = 0; [[nodiscard]] virtual StateTE State (void) const = 0; [[nodiscard]] virtual count_t RowsCount (void) const = 0; [[nodiscard]] virtual count_t ColumnsCount (void) const = 0; [[nodiscard]] virtual s_int_16 GetInt16 (const count_t aRowId, const count_t aColId, std::optional<s_int_16> aOnNullValue) const = 0; [[nodiscard]] virtual s_int_32 GetInt32 (const count_t aRowId, const count_t aColId, std::optional<s_int_32> aOnNullValue) const = 0; [[nodiscard]] virtual s_int_64 GetInt64 (const count_t aRowId, const count_t aColId, std::optional<s_int_64> aOnNullValue) const = 0; [[nodiscard]] virtual std::string_view GetStr (const count_t aRowId, const count_t aColId, std::optional<std::string_view> aOnNullValue) const = 0; [[nodiscard]] virtual GpRawPtrCharRW GetStrRW (const count_t aRowId, const count_t aColId, std::optional<GpRawPtrCharRW> aOnNullValue) = 0; [[nodiscard]] virtual const GpVector<std::string>& GetStrArray (const count_t aRowId, const count_t aColId, std::optional<std::string_view> aOnNullValue) const = 0; [[nodiscard]] virtual std::string_view GetJsonStr (const count_t aRowId, const count_t aColId, std::optional<std::string_view> aOnNullValue) const = 0; [[nodiscard]] virtual GpRawPtrCharRW GetJsonStrRW (const count_t aRowId, const count_t aColId, std::optional<GpRawPtrCharRW> aOnNullValue) = 0; [[nodiscard]] virtual GpUUID GetUUID (const count_t aRowId, const count_t aColId, std::optional<GpUUID> aOnNullValue) const = 0; [[nodiscard]] virtual GpRawPtrByteR GetBLOB (const count_t aRowId, const count_t aColId, std::optional<GpRawPtrByteR> aOnNullValue) const = 0; [[nodiscard]] virtual bool GetBoolean (const count_t aRowId, const count_t aColId, std::optional<bool> aOnNullValue) const = 0; template<typename T> [[nodiscard]] typename T::EnumT GetEnum (const count_t aRowId, const count_t aColId, std::optional<typename T::EnumT> aOnNullValue) const; }; template<typename T> [[nodiscard]] typename T::EnumT GpDbQueryRes::GetEnum (const count_t aRowId, const count_t aColId, std::optional<typename T::EnumT> aOnNullValue) const { std::string_view strVal = GetStr(aRowId, aColId, ""_sv); if (strVal.length() == 0) { THROW_GPE_COND ( aOnNullValue.has_value(), [&](){return "Value on ["_sv + aRowId + ", "_sv + aColId + "] is empty"_sv;} ); return aOnNullValue.value(); } return T::SFromString(strVal); } }//GPlatform
46.646018
113
0.393474
ITBear
bf46f1dffc6d8db3ecb94e41062baff97c9016e5
2,058
hpp
C++
src/HookManager.hpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
1
2022-03-13T19:55:55.000Z
2022-03-13T19:55:55.000Z
src/HookManager.hpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
null
null
null
src/HookManager.hpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <functional> #include <vector> #include <memory> #include <mutex> #include <asmjit/asmjit.h> #include "utility/FunctionHook.hpp" #include "sdk/RETypeDB.hpp" class HookManager { public: enum class PreHookResult : int { CALL_ORIGINAL, SKIP_ORIGINAL, }; struct HookedFn; using PreHookFn = std::function<PreHookResult(std::vector<uintptr_t>& args, std::vector<sdk::RETypeDefinition*>& arg_tys)>; using PostHookFn = std::function<void(uintptr_t& ret_val, sdk::RETypeDefinition* ret_ty)>; using HookId = size_t; struct HookCallback { HookId id{}; PreHookFn pre_fn{}; PostHookFn post_fn{}; }; struct HookedFn { HookManager& hookman; void* target_fn{}; std::vector<HookCallback> cbs{}; HookId next_hook_id{}; std::unique_ptr<FunctionHook> fn_hook{}; uintptr_t facilitator_fn{}; std::vector<uintptr_t> args{}; std::vector<sdk::RETypeDefinition*> arg_tys{}; uintptr_t ret_addr{}; uintptr_t ret_val{}; sdk::RETypeDefinition* ret_ty{}; std::recursive_mutex mux{}; HookedFn(HookManager& hm); ~HookedFn(); PreHookResult on_pre_hook(); void on_post_hook(); __declspec(noinline) static void lock_static(HookedFn* fn) { fn->mux.lock(); } __declspec(noinline) static void unlock_static(HookedFn* fn) { fn->mux.unlock(); } __declspec(noinline) static PreHookResult on_pre_hook_static(HookedFn* fn) { return fn->on_pre_hook(); } __declspec(noinline) static void on_post_hook_static(HookedFn* fn) { fn->on_post_hook(); } }; HookId add(sdk::REMethodDefinition* fn, PreHookFn pre_fn, PostHookFn post_fn, bool ignore_jmp = false); void remove(sdk::REMethodDefinition* fn, HookId id); private: asmjit::JitRuntime m_jit{}; std::mutex m_jit_mux{}; std::unordered_map<sdk::REMethodDefinition*, std::unique_ptr<HookedFn>> m_hooked_fns{}; }; inline HookManager g_hookman{};
30.716418
127
0.662779
fengjixuchui
bf49c45dbf46170f481e40607065e16940e0ddae
1,965
cpp
C++
CommonLib/MainInfo.cpp
chrishoen/Dev_NP_TTA_NewCProc
95a0d59e6079e6f42a11cfe5da5ec41221f67227
[ "MIT" ]
null
null
null
CommonLib/MainInfo.cpp
chrishoen/Dev_NP_TTA_NewCProc
95a0d59e6079e6f42a11cfe5da5ec41221f67227
[ "MIT" ]
null
null
null
CommonLib/MainInfo.cpp
chrishoen/Dev_NP_TTA_NewCProc
95a0d59e6079e6f42a11cfe5da5ec41221f67227
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "BirthCertificate.h" #include "SoftwareVersion.h" #include "FactoryTestRecordCUESS.h" #include "FactoryTestRecordCUSA.h" #include "SysInfo.h" #include "smShare.h" #include "CProcInfo.h" //****************************************************************************** //****************************************************************************** //****************************************************************************** // Initialize program info. void main_info_initialize() { //*************************************************************************** //*************************************************************************** //*************************************************************************** // Update the some info. Prn::print(Prn::CProc1, "CU Update cprocinfo"); gCProcInfo.doProtectedRead(); //*************************************************************************** //*************************************************************************** //*************************************************************************** // Update the system info. // Read the birth certificate. Prn::print(Prn::CProc1, "CU Update birth certificate"); BirthCertificateCU tBirthCertificateCU; tBirthCertificateCU.doReadFromJsonFile(); // Read from the sysinfo json file, update it with variables, // and write to it. Prn::print(Prn::CProc1, "CU Update sysinfo with birth certificate"); Prn::print(Prn::CProc1, "CU Update sysinfo with software version"); gSysInfo.doReadModifyWriteBegin(); gSysInfo.readFrom(&tBirthCertificateCU); gSysInfo.mCU_SoftwareVersion = cSoftwareVersion; gSysInfo.doReadModifyWriteEnd(); } //****************************************************************************** //****************************************************************************** //******************************************************************************
40.102041
80
0.378117
chrishoen
bf49f09b76323dfb7f009f5a507f3ac43b6365e5
2,650
hpp
C++
include/kmeans/InitializeRandom.hpp
LTLA/CppKmeans
924ea37c55edbfbd2aacd3c55954d167f15a7922
[ "MIT" ]
2
2021-07-22T03:01:49.000Z
2021-11-11T11:07:30.000Z
include/kmeans/InitializeRandom.hpp
LTLA/CppKmeans
924ea37c55edbfbd2aacd3c55954d167f15a7922
[ "MIT" ]
3
2021-07-21T07:37:16.000Z
2022-02-15T06:55:38.000Z
vendor/kmeans/InitializeRandom.hpp
kojix2/umap
92404e3afe312393fb849227e0d6e91ad4355d8d
[ "MIT" ]
1
2021-11-12T22:02:46.000Z
2021-11-12T22:02:46.000Z
#ifndef KMEANS_INITIALIZE_RANDOM_HPP #define KMEANS_INITIALIZE_RANDOM_HPP #include <algorithm> #include <cstdint> #include <random> #include "Base.hpp" #include "random.hpp" /** * @file InitializeRandom.hpp * * @brief Class for random initialization. */ namespace kmeans { /** * @cond */ template<class V, typename DATA_t> void copy_into_array(const V& chosen, int ndim, const DATA_t* in, DATA_t* out) { for (auto c : chosen) { auto ptr = in + c * ndim; std::copy(ptr, ptr + ndim, out); out += ndim; } return; } /** * @endcond */ /** * @brief Initialize starting points by sampling random observations without replacement. * * @tparam DATA_t Floating-point type for the data and centroids. * @tparam CLUSTER_t Integer type for the cluster index. * @tparam INDEX_t Integer type for the observation index. */ template<typename DATA_t = double, typename CLUSTER_t = int, typename INDEX_t = int> class InitializeRandom : public Initialize<DATA_t, CLUSTER_t, INDEX_t> { public: /** * @brief Default parameter settings. */ struct Defaults { /** * See `set_seed()` for more details. */ static constexpr uint64_t seed = 6523u; }; /** * @param Random seed to use to construct the PRNG prior to sampling. * * @return A reference to this `InitializeRandom` object. */ InitializeRandom& set_seed(uint64_t s = Defaults::seed) { seed = s; return *this; } private: uint64_t seed = Defaults::seed; public: /* * @param ndim Number of dimensions. * @param nobs Number of observations. * @param data Pointer to an array where the dimensions are rows and the observations are columns. * Data should be stored in column-major format. * @param ncenters Number of centers to pick. * @param[out] centers Pointer to a `ndim`-by-`ncenters` array where columns are cluster centers and rows are dimensions. * On output, this will contain the final centroid locations for each cluster. * Data should be stored in column-major order. * @param clusters Ignored in this method. * * @return `centers` is filled with the new cluster centers. * The number of filled centers is returned, see `Initializer::run()`. */ CLUSTER_t run(int ndim, INDEX_t nobs, const DATA_t* data, CLUSTER_t ncenters, DATA_t* centers, CLUSTER_t* clusters) { std::mt19937_64 eng(seed); auto chosen = sample_without_replacement(nobs, ncenters, eng); copy_into_array(chosen, ndim, data, centers); return chosen.size(); } }; } #endif
28.804348
126
0.663019
LTLA
bf4ba4442addcd0775e1ac38a7f2bde3cee63fb7
10,521
cpp
C++
dsr_emeraldenvysrc/src/intro.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
20
2017-12-12T16:37:25.000Z
2022-02-19T10:35:46.000Z
dsr_emeraldenvysrc/src/intro.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
null
null
null
dsr_emeraldenvysrc/src/intro.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
7
2017-12-29T23:19:18.000Z
2021-08-17T09:53:15.000Z
//--------------------------------------------------------------------------// // iq / rgba . tiny codes . 2008 // //--------------------------------------------------------------------------// #define WIN32_LEAN_AND_MEAN #define WIN32_EXTRA_LEAN #include <windows.h> #include <mmsystem.h> #include <GL/gl.h> #include <math.h> #include "config.h" #include "ext.h" #include "shaders/fsh_rayt.inl" #include "shaders/vsh_2d.inl" #include "fp.h" #include "sync/sync.h" #include "sync.h" #include "emerald.h" struct sync_device *rocket; const struct sync_track *fades_rocket; const struct sync_track *sync_rocket; const struct sync_track *shader_rocket; const struct sync_track *snarehit1_rocket; const struct sync_track *snarehit2_rocket; const struct sync_track *colordistort_rocket; const struct sync_track * stripcnt_rocket; const struct sync_track * stripintense_rocket; const struct sync_track * striptransintense_rocket; const struct sync_track * striprgbdistort_rocket; //================================================================================================================= static void initShader( int *pid, const char *vs, const char *fs ) { pid[0] = oglCreateProgram(); const int vsId = oglCreateShader( GL_VERTEX_SHADER ); const int fsId = oglCreateShader( GL_FRAGMENT_SHADER ); oglShaderSource( vsId, 1, &vs, 0 ); oglShaderSource( fsId, 1, &fs, 0 ); oglCompileShader( vsId ); oglCompileShader( fsId ); oglAttachShader( pid[0], fsId ); oglAttachShader( pid[0], vsId ); oglLinkProgram( pid[0] ); #ifdef DEBUG int result; char info[1536]; oglGetObjectParameteriv( vsId, GL_OBJECT_COMPILE_STATUS_ARB, &result ); oglGetInfoLog( vsId, 1024, NULL, (char *)info ); if( !result ) DebugBreak(); oglGetObjectParameteriv( fsId, GL_OBJECT_COMPILE_STATUS_ARB, &result ); oglGetInfoLog( fsId, 1024, NULL, (char *)info ); if( !result ) DebugBreak(); oglGetObjectParameteriv( pid[0], GL_OBJECT_LINK_STATUS_ARB, &result ); oglGetInfoLog( pid[0], 1024, NULL, (char*)info ); if( !result ) DebugBreak(); #endif } #ifndef WAVE_FORMAT_PCM # define WAVE_FORMAT_PCM 0x0001 #endif #ifndef WAVE_FORMAT_IEEE_FLOAT # define WAVE_FORMAT_IEEE_FLOAT 0x0003 #endif #ifndef WAVE_FORMAT_EXTENSIBLE # define WAVE_FORMAT_EXTENSIBLE 0xfffe #endif SAMPLE_TYPE lpSoundBuffer[MAX_SAMPLES * 2]; HWAVEOUT hWaveOut; #pragma data_seg(".wavefmt") WAVEFORMATEX WaveFMT = { #ifdef FLOAT_32BIT WAVE_FORMAT_IEEE_FLOAT, #else WAVE_FORMAT_PCM, #endif 2, // channels SAMPLE_RATE, // samples per sec SAMPLE_RATE*sizeof(SAMPLE_TYPE) * 2, // bytes per sec sizeof(SAMPLE_TYPE) * 2, // block alignment; sizeof(SAMPLE_TYPE) * 8, // bits per sample 0 // extension not needed }; #pragma data_seg(".wavehdr") WAVEHDR WaveHDR = { (LPSTR)lpSoundBuffer, MAX_SAMPLES*sizeof(SAMPLE_TYPE) * 2, // MAX_SAMPLES*sizeof(float)*2(stereo) 0, 0, 0, 0, 0, 0 }; MMTIME MMTime = { TIME_SAMPLES, 0 }; #pragma code_seg(".initsnd") void InitSound() { // thx to xTr1m/blu-flame for providing a smarter and smaller way to create the thread :) CreateThread(0, 0, (LPTHREAD_START_ROUTINE)_4klang_render, lpSoundBuffer, 0, 0); //_4klang_render(lpSoundBuffer); waveOutOpen(&hWaveOut, WAVE_MAPPER, &WaveFMT, NULL, 0, CALLBACK_NULL); waveOutPrepareHeader(hWaveOut, &WaveHDR, sizeof(WaveHDR)); waveOutWrite(hWaveOut, &WaveHDR, sizeof(WaveHDR)); } //================================================================================================================= //shader 1 - creditsintro_frag //shader 2 - pillars_frag //shader 3 - circular/maze2_frag //shader 4 - ballmaze1_frag //shader 5 - ballmaze2_frag static int pid[6]; static int vhs_shader; static int distort_shader; GLuint vhs_texture; //================================================================================================================= int intro_init( void ) { if( !EXT_Init() ) return( 0 ); initShader( &pid[0], raymarch_vert, creditsintro_frag ); initShader(&pid[1], raymarch_vert, pillars_frag); initShader(&pid[2], raymarch_vert, circular_frag); initShader(&pid[3], raymarch_vert, ballmaze1_frag); initShader(&pid[4], raymarch_vert, ballmaze2_frag); initShader(&pid[5], raymarch_vert, ballmaze3_frag); initShader(&vhs_shader, vhs_vert, vhs_frag); initShader(&distort_shader,vhs_vert, image_distort); Resize(XRES, YRES); vhs_texture = init_rendertexture(XRES, YRES); rocket = sync_create_device("sync"); #ifndef DEBUG rocket = sync_create_device("sync"); fades_rocket = sync_get_track_mem(rocket, "fade", sync_fade_data, sizeof(sync_fade_data)); shader_rocket = sync_get_track_mem(rocket, "shadernum", sync_shadernum_data, sizeof(sync_shadernum_data)); sync_rocket = sync_get_track_mem(rocket, "sync", sync_sync_data, sizeof(sync_sync_data)); snarehit1_rocket = sync_get_track_mem(rocket, "snarehit1", sync_snarehit1_data, sizeof(sync_snarehit1_data)); snarehit2_rocket =sync_get_track_mem(rocket, "snarehit2", sync_snarehit2_data, sizeof(sync_snarehit2_data)); colordistort_rocket=sync_get_track_mem(rocket, "colordistort", sync_colordistort_data, sizeof(sync_colordistort_data)); stripcnt_rocket = sync_get_track_mem(rocket, "strp_cnt", sync_strp_cnt_data, sizeof(sync_strp_cnt_data)); stripintense_rocket = sync_get_track_mem(rocket, "strp_intens", sync_strp_intens_data, sizeof(sync_strp_intens_data)); striptransintense_rocket = sync_get_track_mem(rocket, "strp_trnsinst", sync_strp_trnsinst_data, sizeof(sync_strp_trnsinst_data)); striprgbdistort_rocket = sync_get_track_mem(rocket, "rgb_distort", sync_rgb_distort_data, sizeof(sync_rgb_distort_data)); #else if (sync_connect(rocket, "localhost", SYNC_DEFAULT_PORT)) { return 0; } fades_rocket = sync_get_track(rocket, "fade"); sync_rocket = sync_get_track(rocket, "sync"); shader_rocket = sync_get_track(rocket, "shadernum"); snarehit1_rocket = sync_get_track(rocket, "snarehit1"); snarehit2_rocket = sync_get_track(rocket, "snarehit2"); colordistort_rocket = sync_get_track(rocket, "colordistort"); stripcnt_rocket = sync_get_track(rocket, "strp_cnt"); stripintense_rocket = sync_get_track(rocket, "strp_intens"); striptransintense_rocket = sync_get_track(rocket, "strp_trnsinst"); striprgbdistort_rocket = sync_get_track(rocket, "rgb_distort"); #endif InitSound(); return 1; } //================================================================================================================= int intro_do( long time ) { //--- update parameters ----------------------------------------- static long lastTime = timeGetTime(); long currTime = timeGetTime(); static double delta = 0.0; long diff = currTime - lastTime; delta = diff; lastTime = currTime; static float sceneTime = 0; sceneTime += (float)delta / 1000.f; waveOutGetPosition(hWaveOut, &MMTime, sizeof(MMTIME)); static float synctime = 0.0; double row = synctime * 5.0; synctime += (float)delta / 1000.f; int rowtimes = (int)floor(row); if (rowtimes > 1049) return 1; #ifndef SYNC_PLAYER if (sync_update(rocket, (int)floor(row), NULL, NULL)) sync_connect(rocket, "localhost", SYNC_DEFAULT_PORT); #endif float fade_f = sync_get_val(fades_rocket, row); float sync_f = sync_get_val(sync_rocket, row); float shader_f = sync_get_val(shader_rocket, row); float stripcnt_f = sync_get_val(stripcnt_rocket, row); float stripintense_f = sync_get_val(stripintense_rocket, row); float striptransintense_f = sync_get_val(striptransintense_rocket, row); float striprgbdistort_f = sync_get_val(striprgbdistort_rocket, row); float snarehit1_f = 0; float snarehit2_f = 0; float colordistort_f =1.0; //1 - snare 2 - bassline 3 - flanger bass 4 - lead voice 5 - hi - hat 6 - bass drum float aha = (&_4klang_envelope_buffer)[((MMTime.u.sample >> 8) << 5) + 2 * 0 + 0]; int aha1 = (&_4klang_note_buffer)[((MMTime.u.sample >> 8) << 5) + 2 *0 + 0]; if (aha1 && aha > 0.55) { snarehit1_f = 1.0f; colordistort_f = 1.0; } if (!aha1 || aha < 0.55) { snarehit1_f = 0.0f; colordistort_f = 0.0; } const float fade = fade_f; const float sync = sync_f; const float t = sceneTime; int fragnum = shader_f; //--- render ----------------------------------------- float res[2] = { (float)XRES, (float)YRES }; glClear(GL_COLOR_BUFFER_BIT); oglUseProgram( pid[fragnum] ); oglUniform2fv(oglGetUniformLocation(pid[fragnum], "resolution"), 1, res); oglUniform1fv(oglGetUniformLocation(pid[fragnum], "time"), 1, &t); oglUniform1fv(oglGetUniformLocation(pid[fragnum], "fade"), 1, &fade); oglUniform1fv(oglGetUniformLocation(pid[fragnum], "sync"), 1, &sync); glRects( -1, -1, 1, 1 ); oglUseProgram(0); //copy tex to image for postproc glBindTexture(GL_TEXTURE_2D, vhs_texture); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, XRES, YRES); glBindTexture(GL_TEXTURE_2D, 0); GLuint shadertexture; oglUseProgram(distort_shader); oglActiveTextureARB(GL_TEXTURE0_ARB); shadertexture = oglGetUniformLocation(distort_shader, "tex"); oglUniform2fv(oglGetUniformLocation(distort_shader, "resolution"), 1, res); oglUniform1fv(oglGetUniformLocation(distort_shader, "time"), 1, &t); oglUniform1fv(oglGetUniformLocation(distort_shader, "strp_cnt"), 1, &stripcnt_f); oglUniform1fv(oglGetUniformLocation(distort_shader, "strp_intens"), 1, &stripintense_f); oglUniform1fv(oglGetUniformLocation(distort_shader, "strp_trnsinst"), 1, &striptransintense_f); oglUniform1fv(oglGetUniformLocation(distort_shader, "rgb_distort"), 1, &striprgbdistort_f); oglUniform1i(shadertexture, 0); draw_fbotexture(vhs_texture, XRES, YRES); oglUseProgram(0); glBindTexture(GL_TEXTURE_2D, vhs_texture); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, XRES, YRES); glBindTexture(GL_TEXTURE_2D, 0); //do vhs shader oglUseProgram(vhs_shader); oglActiveTextureARB(GL_TEXTURE0_ARB); shadertexture = oglGetUniformLocation(vhs_shader, "tex"); oglUniform2fv(oglGetUniformLocation(vhs_shader, "resolution"), 1, res); oglUniform1fv(oglGetUniformLocation(vhs_shader, "time"), 1, &t); oglUniform1fv(oglGetUniformLocation(vhs_shader, "snarehit"), 1, &snarehit1_f); oglUniform1fv(oglGetUniformLocation(vhs_shader, "snarehit2"), 1, &snarehit2_f); oglUniform1fv(oglGetUniformLocation(vhs_shader, "colordistort"), 1, &colordistort_f); oglUniform1i(shadertexture, 0); draw_fbotexture(vhs_texture, XRES, YRES); oglUseProgram(0); return 0; }
34.495082
160
0.690999
mudlord
bf4c4c29603944e5e62b8379a721ae33c6959824
2,017
cpp
C++
Solutions/Ch7/7-16 Vector Modification.cpp
menarus/C-Course
ac56ec4215a69f6a755e766b9d113e4a4e08b087
[ "MIT" ]
1
2017-09-14T01:07:44.000Z
2017-09-14T01:07:44.000Z
Solutions/Ch7/7-16 Vector Modification.cpp
menarus/C-Course
ac56ec4215a69f6a755e766b9d113e4a4e08b087
[ "MIT" ]
null
null
null
Solutions/Ch7/7-16 Vector Modification.cpp
menarus/C-Course
ac56ec4215a69f6a755e766b9d113e4a4e08b087
[ "MIT" ]
null
null
null
/* Project : 7-16 Vector Modification Author : Mohammad Al-Husseini Description : Change pin1, pin2, and pin3 to be Vectors. And modify testPin to accept Vectors. */ /////////////////////////////////////////////////////////////////////////////////////////////////// // This program is a driver that tests a function comparing the // contents of two int arrays. #include <iostream> #include <vector> using namespace std; // Function Prototype bool testPIN(vector<int>, vector<int>, int); int main() { const int NUM_DIGITS = 7; // Number of digits in a PIN vector<int> pin1 = { 2, 4, 1, 8, 7, 9, 0 }; // Base set of values. vector<int> pin2 = { 2, 4, 6, 8, 7, 9, 0 }; // Only 1 element is // different from pin1. vector<int> pin3 = { 1, 2, 3, 4, 5, 6, 7 }; // All elements are // different from pin1. if (testPIN(pin1, pin2, NUM_DIGITS)) cout << "ERROR: pin1 and pin2 report to be the same.\n"; else cout << "SUCCESS: pin1 and pin2 are different.\n"; if (testPIN(pin1, pin3, NUM_DIGITS)) cout << "ERROR: pin1 and pin3 report to be the same.\n"; else cout << "SUCCESS: pin1 and pin3 are different.\n"; if (testPIN(pin1, pin1, NUM_DIGITS)) cout << "SUCCESS: pin1 and pin1 report to be the same.\n"; else cout << "ERROR: pin1 and pin1 report to be different.\n"; return 0; } //****************************************************************** // The following function accepts two int arrays. The arrays are * // compared. If they contain the same values, true is returned. * // If the contain different values, false is returned. * //****************************************************************** bool testPIN(vector<int> custPIN, vector<int> databasePIN, int size) { for (int index = 0; index < size; index++) { if (custPIN[index] != databasePIN[index]) return false; // We've found two different values. } return true; // If we make it this far, the values are the same. }
36.017857
100
0.563213
menarus
bf4d029035b1315d7732082d299580db2ee936cc
3,477
cpp
C++
tests/string/tao/hello.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tests/string/tao/hello.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tests/string/tao/hello.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file hello.cpp * @author Mark Drijver * * @brief CORBA C++ server application * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "hello.h" #include <iostream> #include "testdata.h" Hello::Hello(CORBA::ORB_ptr orb, int& result) : orb_(CORBA::ORB::_duplicate(orb)), result_(result) { } char * Hello::get_string() { return CORBA::string_dup("Hello there!"); } void Hello::set_string(const char * text) { if (strcmp(text, "Hello there!") != 0) { std::cout << "ERROR: Hello::set_string parameter value expected 'Hello there!', received " << text << std::endl; ++result_; } } void Hello::out_string(CORBA::String_out text) { text = CORBA::string_dup("I hear you!"); } void Hello::inout_string(char *& text) { if (strcmp(text, "Hello there!") != 0) { std::cout << "ERROR: Hello::inout_string parameter value expected 'Hello there!', received " << text << std::endl; ++result_; } CORBA::string_free (text); text = CORBA::string_dup("I hear you!"); } char * Hello::get_lstring() { std::string longText; longText.assign(66000, 'a'); return CORBA::string_dup(longText.c_str()); } void Hello::set_lstring(const char * text) { std::string longText; longText.assign(66000, 'a'); if (longText.compare(text) != 0) { std::cout << "ERROR: Hello::set_lstring parameter value expected 66000 times 'a', received different." << std::endl; ++result_; } } void Hello::out_lstring(CORBA::String_out text) { std::string longText; longText.assign(66000, 'b'); text = CORBA::string_dup(longText.c_str()); } void Hello::inout_lstring(char *& text) { std::string longText; longText.assign(66000, 'c'); if (longText.compare(text) != 0) { std::cout << "ERROR: Hello::inout_string parameter value expected 66000 times 'c', received different." << std::endl; ++result_; } CORBA::string_free (text); std::string longText2; longText2.assign(66000, 'd'); text = CORBA::string_dup(longText2.c_str()); } // string sequence CORBA::StringSeq * Hello::get_stringSeq() { CORBA::StringSeq_var seq = Array2Seq(stringOutArr); return seq._retn (); } void Hello::set_stringSeq(const CORBA::StringSeq& seq) { CORBA::StringSeq_var seq2 = Array2Seq(stringArr); if (!(eqv(seq, seq2))) { { std::cout << "ERROR: Hello::set_stringSeq parameter unexpected value." << std::endl; ++result_; } } } void Hello::out_stringSeq(CORBA::StringSeq_out text) { CORBA::StringSeq_var seq = Array2Seq(stringOutArr); text = seq._retn (); } void Hello::inout_stringSeq(CORBA::StringSeq& seq) { CORBA::StringSeq_var seq2 = Array2Seq(stringArr); if (!(eqv(seq, seq2))) { std::cout << "ERROR: Hello::inout_stringSeq parameter unexpected value." << std::endl; ++result_; } seq2 = Array2Seq(stringOutArr); seq = seq2; } void Hello::bounded_string (const char * text) { std::string test (text); if (test.length () != 5) { std::cout << "ERROR: Hello::bounded_string parameter unexpected length : " << "expected <5> - found <" << test.length () << ">." << std::endl; ++this->result_; } if (test.compare ("12345") != 0) { std::cout << "ERROR: Hello::bounded_string parameter unexpected value : " << "expected <12345> - found <" << test << ">." << std::endl; ++this->result_; } } void Hello::shutdown() { this->orb_->shutdown(0); }
21.596273
101
0.626977
ClausKlein
bf4f0935893509b949163a2a7bedb3372f46c628
1,244
cpp
C++
src/main/cpp/autocommands/AutoCmdTimer.cpp
BlueCrewRobotics/2022-RapidReact
83d5bb57e68cbb5ef5c7f2100e30ce95a023a86b
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/autocommands/AutoCmdTimer.cpp
BlueCrewRobotics/2022-RapidReact
83d5bb57e68cbb5ef5c7f2100e30ce95a023a86b
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/autocommands/AutoCmdTimer.cpp
BlueCrewRobotics/2022-RapidReact
83d5bb57e68cbb5ef5c7f2100e30ce95a023a86b
[ "BSD-3-Clause" ]
null
null
null
/*-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=*/ /* Blue Crew Robotics #6153 */ /* Rapid React 2022 */ /*-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=*/ // Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "autocommands/AutoCmdTimer.h" AutoCmdTimer::AutoCmdTimer(frc::Timer* timer, double time) : m_timer(timer), m_time(time) { // Use addRequirements() here to declare subsystem dependencies. } // Called when the command is initially scheduled. void AutoCmdTimer::Initialize() { m_timer->Reset(); } // Called repeatedly when this Command is scheduled to run void AutoCmdTimer::Execute() { m_timer->Start(); } // Called once the command ends or is interrupted. void AutoCmdTimer::End(bool interrupted) {} // Returns true when the command should end. bool AutoCmdTimer::IsFinished() { if(m_timer->HasElapsed((units::time::second_t)m_time)==true) { return true; } else { return false; } }
32.736842
91
0.565113
BlueCrewRobotics
bf50eb991a1b263fb8e6b6d17d78f2f86c1abbec
250
cpp
C++
R113-edu/b.cpp
patwadeepak/codeforces
5da8c79ad6f27a4a2436d19fc8cbf274ecd452e2
[ "Apache-2.0" ]
null
null
null
R113-edu/b.cpp
patwadeepak/codeforces
5da8c79ad6f27a4a2436d19fc8cbf274ecd452e2
[ "Apache-2.0" ]
null
null
null
R113-edu/b.cpp
patwadeepak/codeforces
5da8c79ad6f27a4a2436d19fc8cbf274ecd452e2
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; vector<vector<char>> table(n, vector<char>(n, 'X')); } int main() { int t; cin >> t; while(t--) solve(); }
13.157895
56
0.484
patwadeepak
bf5208b3e9ea852dcc52d95d52c359331585fdf2
5,550
cpp
C++
src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-03-23T06:41:14.000Z
2022-03-23T06:41:14.000Z
src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-03-31T23:58:31.000Z
2022-03-31T23:58:31.000Z
src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.cpp
philass/onnx-mlir
09965003137f82d8891676c986ec6403faa9c3cb
[ "Apache-2.0" ]
1
2022-01-11T09:39:03.000Z
2022-01-11T09:39:03.000Z
/* * SPDX-License-Identifier: Apache-2.0 */ //===-------- ZHighHelper.cpp - NNPA ZHigh Helper Functions ---------------===// // // Copyright 2019-2022 The IBM Research Authors. // // ============================================================================= // //===----------------------------------------------------------------------===// #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighHelper.hpp" #include "src/Accelerators/NNPA/Dialect/ZHigh/ZHighOps.hpp" #include "src/Accelerators/NNPA/Support/LayoutHelper.hpp" using namespace mlir; namespace onnx_mlir { namespace zhigh { /// Check if a value type is ranked or unranked. bool hasRankedType(Value val) { ShapedType shapedType = val.getType().cast<ShapedType>(); return (shapedType && shapedType.hasRank()); } /// Get a ztensor data layout by StringAttr. ZTensorEncodingAttr::DataLayout convertStringAttrToDataLayout( StringAttr layoutAttr) { if (layoutAttr) { StringRef layoutStr = layoutAttr.getValue(); if (layoutStr.equals_insensitive(LAYOUT_1D)) return ZTensorEncodingAttr::DataLayout::_1D; else if (layoutStr.equals_insensitive(LAYOUT_2D)) return ZTensorEncodingAttr::DataLayout::_2D; else if (layoutStr.equals_insensitive(LAYOUT_2DS)) return ZTensorEncodingAttr::DataLayout::_2DS; else if (layoutStr.equals_insensitive(LAYOUT_3D)) return ZTensorEncodingAttr::DataLayout::_3D; else if (layoutStr.equals_insensitive(LAYOUT_3DS)) return ZTensorEncodingAttr::DataLayout::_3DS; else if (layoutStr.equals_insensitive(LAYOUT_4D)) return ZTensorEncodingAttr::DataLayout::_4D; else if (layoutStr.equals_insensitive(LAYOUT_4DS)) return ZTensorEncodingAttr::DataLayout::_4DS; else if (layoutStr.equals_insensitive(LAYOUT_NCHW)) return ZTensorEncodingAttr::DataLayout::NCHW; else if (layoutStr.equals_insensitive(LAYOUT_NHWC)) return ZTensorEncodingAttr::DataLayout::NHWC; else if (layoutStr.equals_insensitive(LAYOUT_HWCK)) return ZTensorEncodingAttr::DataLayout::HWCK; else if (layoutStr.equals_insensitive(LAYOUT_FICO)) return ZTensorEncodingAttr::DataLayout::FICO; else if (layoutStr.equals_insensitive(LAYOUT_ZRH)) return ZTensorEncodingAttr::DataLayout::ZRH; else if (layoutStr.equals_insensitive(LAYOUT_BFICO)) return ZTensorEncodingAttr::DataLayout::BFICO; else if (layoutStr.equals_insensitive(LAYOUT_BZRH)) return ZTensorEncodingAttr::DataLayout::BZRH; else llvm_unreachable("Invalid data layout string"); } else llvm_unreachable("Could not get layout by an empty StringAttr"); } /// Get a ztensor data layout by rank. ZTensorEncodingAttr::DataLayout getDataLayoutByRank(int64_t rank) { if (rank == 1) return ZTensorEncodingAttr::DataLayout::_1D; else if (rank == 2) return ZTensorEncodingAttr::DataLayout::_2D; else if (rank == 3) return ZTensorEncodingAttr::DataLayout::_3D; else if (rank == 4) return ZTensorEncodingAttr::DataLayout::_4D; else llvm_unreachable( "Could not get layout by rank. Rank must be 1, 2, 3, or 4"); } /// Convert a data layout to StringAttr. StringAttr convertDataLayoutToStringAttr( OpBuilder &builder, ZTensorEncodingAttr::DataLayout layout) { StringAttr attr; switch (layout) { case ZTensorEncodingAttr::DataLayout::_1D: attr = builder.getStringAttr(LAYOUT_1D); break; case ZTensorEncodingAttr::DataLayout::_2D: attr = builder.getStringAttr(LAYOUT_2D); break; case ZTensorEncodingAttr::DataLayout::_2DS: attr = builder.getStringAttr(LAYOUT_2DS); break; case ZTensorEncodingAttr::DataLayout::_3D: attr = builder.getStringAttr(LAYOUT_3D); break; case ZTensorEncodingAttr::DataLayout::_3DS: attr = builder.getStringAttr(LAYOUT_3DS); break; case ZTensorEncodingAttr::DataLayout::_4D: attr = builder.getStringAttr(LAYOUT_4D); break; case ZTensorEncodingAttr::DataLayout::_4DS: attr = builder.getStringAttr(LAYOUT_4DS); break; case ZTensorEncodingAttr::DataLayout::NCHW: attr = builder.getStringAttr(LAYOUT_NCHW); break; case ZTensorEncodingAttr::DataLayout::NHWC: attr = builder.getStringAttr(LAYOUT_NHWC); break; case ZTensorEncodingAttr::DataLayout::HWCK: attr = builder.getStringAttr(LAYOUT_HWCK); break; case ZTensorEncodingAttr::DataLayout::FICO: attr = builder.getStringAttr(LAYOUT_FICO); break; case ZTensorEncodingAttr::DataLayout::BFICO: attr = builder.getStringAttr(LAYOUT_BFICO); break; case ZTensorEncodingAttr::DataLayout::ZRH: attr = builder.getStringAttr(LAYOUT_ZRH); break; case ZTensorEncodingAttr::DataLayout::BZRH: attr = builder.getStringAttr(LAYOUT_BZRH); break; default: break; } return attr; } //===----------------------------------------------------------------------===// // Utility functions to query ztensor information. bool isZTensor(Type type) { if (auto ttp = type.dyn_cast<RankedTensorType>()) if (ttp.getEncoding().dyn_cast_or_null<ZTensorEncodingAttr>()) return true; return false; } ZTensorEncodingAttr getZTensorEncoding(Type type) { if (auto ttp = type.dyn_cast<RankedTensorType>()) return ttp.getEncoding().dyn_cast_or_null<ZTensorEncodingAttr>(); return nullptr; } ZTensorEncodingAttr::DataLayout getZTensorLayout(Type type) { if (auto encoding = getZTensorEncoding(type)) return encoding.getDataLayout(); return ZTensorEncodingAttr::DataLayout::UNDEFINED; } } // namespace zhigh } // namespace onnx_mlir
34.90566
80
0.706847
philass
bf5523e9093395b9240320258c1644e61f65e7ad
2,536
cpp
C++
src/runtime_src/xdp/profile/device/aieTraceS2MM.cpp
mariodruiz/XRT
c2fe15ff3c3b3d329645d40073cf9f71b8222e15
[ "Apache-2.0" ]
null
null
null
src/runtime_src/xdp/profile/device/aieTraceS2MM.cpp
mariodruiz/XRT
c2fe15ff3c3b3d329645d40073cf9f71b8222e15
[ "Apache-2.0" ]
null
null
null
src/runtime_src/xdp/profile/device/aieTraceS2MM.cpp
mariodruiz/XRT
c2fe15ff3c3b3d329645d40073cf9f71b8222e15
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2022 Advanced Micro Devices, Inc. * * 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://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 "aieTraceS2MM.h" namespace xdp { void AIETraceS2MM::init(uint64_t bo_size, int64_t bufaddr, bool circular) { if (out_stream) (*out_stream) << " TraceS2MM::init " << std::endl; if (isActive()) reset(); // Configure DDR Offset write32(TS2MM_WRITE_OFFSET_LOW, static_cast<uint32_t>(bufaddr)); write32(TS2MM_WRITE_OFFSET_HIGH, static_cast<uint32_t>(bufaddr >> BITS_PER_WORD)); // Configure Number of trace words uint64_t word_count = bo_size / mDatawidthBytes; write32(TS2MM_COUNT_LOW, static_cast<uint32_t>(word_count)); write32(TS2MM_COUNT_HIGH, static_cast<uint32_t>(word_count >> BITS_PER_WORD)); // Enable use of circular buffer if (supportsCircBuf()) { uint32_t reg = circular ? 0x1 : 0x0; write32(TS2MM_CIRCULAR_BUF, reg); } // Start Data Mover write32(TS2MM_AP_CTRL, TS2MM_AP_START); } uint64_t AIETraceS2MM::getWordCount(bool final) { if (out_stream) (*out_stream) << " AIETraceS2MM::getWordCount " << std::endl; // Call flush on V2 datamover to ensure all data is written if (final && isVersion2()) reset(); uint32_t regValue = 0; read(TS2MM_WRITTEN_LOW, BYTES_PER_WORD, &regValue); uint64_t wordCount = static_cast<uint64_t>(regValue); read(TS2MM_WRITTEN_HIGH, BYTES_PER_WORD, &regValue); wordCount |= static_cast<uint64_t>(regValue) << BITS_PER_WORD; return adjustWordCount(wordCount, final); } uint64_t AIETraceS2MM::adjustWordCount(uint64_t wordCount, bool final) { // No adjustment for old datamovers if (!isVersion2()) return wordCount; // V2 datamover only writes data in bursts // Only the final write can be a non multiple of burst length if (!final) wordCount -= wordCount % TS2MM_V2_BURST_LEN; // Wordcount is always in 64 bit return wordCount * (mDatawidthBytes / BYTES_64BIT); } } // namespace xdp
31.308642
86
0.701104
mariodruiz
bf587f5647fa6585f26b6e88da7b178c3c8a2324
1,348
cpp
C++
Projects/Skylicht/Audio/Source/Decoder/CAudioDecoderRawWav.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
Projects/Skylicht/Audio/Source/Decoder/CAudioDecoderRawWav.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
Projects/Skylicht/Audio/Source/Decoder/CAudioDecoderRawWav.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CAudioDecoderRawWav.h" namespace SkylichtAudio { CAudioDecoderRawWav::CAudioDecoderRawWav(IStream* stream) :IAudioDecoder(stream) { m_streamCursor = stream->createCursor(); } CAudioDecoderRawWav::~CAudioDecoderRawWav() { delete m_streamCursor; } EStatus CAudioDecoderRawWav::initDecode() { return Success; } EStatus CAudioDecoderRawWav::decode(void* outputBuffer, int bufferSize) { // silent buffer memset(outputBuffer, 0, bufferSize); // need wait data // check safe data avaiable will be encode if (m_streamCursor->readyReadData(bufferSize) == false) { // return state wait data return WaitData; } // copy data from stream to waveBuffer m_streamCursor->read((unsigned char*)outputBuffer, bufferSize); // trim the readed memory m_streamCursor->trim(); return Success; } int CAudioDecoderRawWav::seek(int bufferSize) { return 0; } void CAudioDecoderRawWav::getTrackParam(STrackParams* track) { track->NumChannels = m_stream->getChannels(); track->SamplingRate = m_stream->getSampleRate(); track->BitsPerSample = 16; // 16bit } float CAudioDecoderRawWav::getCurrentTime() { // implement later return 0.0f; } void CAudioDecoderRawWav::stopStream() { m_streamCursor->seek(0, IStreamCursor::OriginStart); m_stream->stopStream(); } }
20.119403
72
0.727003
tsukoyumi
bf58ef26a145e3d12e63966e16a9725a4257cb68
777
cpp
C++
src/greeter/tests/greeter_api_tests.cpp
tstraus/cpp_starter
519c30945ac752ce95974df7826eeaec5949bd96
[ "MIT" ]
null
null
null
src/greeter/tests/greeter_api_tests.cpp
tstraus/cpp_starter
519c30945ac752ce95974df7826eeaec5949bd96
[ "MIT" ]
null
null
null
src/greeter/tests/greeter_api_tests.cpp
tstraus/cpp_starter
519c30945ac752ce95974df7826eeaec5949bd96
[ "MIT" ]
null
null
null
#include "greeter_api.h" #include "gtest/gtest.h" #define TEST_NAME "Margot" TEST(GreeterApiTests, Greet) { auto* g = greeter_new(); ASSERT_NE(g, nullptr); EXPECT_GT(greeter_greet(g, TEST_NAME), 0); auto* gc = g; greeter_free(g); ASSERT_EQ(g, gc); } TEST(GreeterApiTests, Length) { auto* g = greeter_new(); const auto length = greeter_greet(g, TEST_NAME); EXPECT_EQ(length, 6); greeter_free(g); } TEST(GreeterApiTests, Count) { auto* g = greeter_new(); ASSERT_EQ(greeter_total_greeted(g), 0); greeter_greet(g, "one"); ASSERT_EQ(greeter_total_greeted(g), 1); greeter_greet(g, "two"); ASSERT_EQ(greeter_total_greeted(g), 2); greeter_greet(g, "three"); ASSERT_EQ(greeter_total_greeted(g), 3); }
17.659091
52
0.655084
tstraus
bf5e2a27ae9978c1497d32e2e0c953ec5d386fdf
5,198
cc
C++
media/learning/common/target_histogram_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
media/learning/common/target_histogram_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
media/learning/common/target_histogram_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/learning/common/target_histogram.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { namespace learning { class TargetHistogramTest : public testing::Test { public: TargetHistogramTest() : value_1(123), value_2(456), value_3(789) {} TargetHistogram histogram_; TargetValue value_1; const size_t counts_1 = 100; TargetValue value_2; const size_t counts_2 = 10; TargetValue value_3; }; TEST_F(TargetHistogramTest, EmptyTargetHistogramHasZeroCounts) { EXPECT_EQ(histogram_.total_counts(), 0u); } TEST_F(TargetHistogramTest, AddingCountsWorks) { histogram_[value_1] = counts_1; EXPECT_EQ(histogram_.total_counts(), counts_1); EXPECT_EQ(histogram_[value_1], counts_1); histogram_[value_1] += counts_1; EXPECT_EQ(histogram_.total_counts(), counts_1 * 2u); EXPECT_EQ(histogram_[value_1], counts_1 * 2u); } TEST_F(TargetHistogramTest, MultipleValuesAreSeparate) { histogram_[value_1] = counts_1; histogram_[value_2] = counts_2; EXPECT_EQ(histogram_.total_counts(), counts_1 + counts_2); EXPECT_EQ(histogram_[value_1], counts_1); EXPECT_EQ(histogram_[value_2], counts_2); } TEST_F(TargetHistogramTest, AddingTargetValues) { histogram_ += value_1; EXPECT_EQ(histogram_.total_counts(), 1u); EXPECT_EQ(histogram_[value_1], 1u); EXPECT_EQ(histogram_[value_2], 0u); histogram_ += value_1; EXPECT_EQ(histogram_.total_counts(), 2u); EXPECT_EQ(histogram_[value_1], 2u); EXPECT_EQ(histogram_[value_2], 0u); histogram_ += value_2; EXPECT_EQ(histogram_.total_counts(), 3u); EXPECT_EQ(histogram_[value_1], 2u); EXPECT_EQ(histogram_[value_2], 1u); } TEST_F(TargetHistogramTest, AddingTargetHistograms) { histogram_[value_1] = counts_1; TargetHistogram rhs; rhs[value_2] = counts_2; histogram_ += rhs; EXPECT_EQ(histogram_.total_counts(), counts_1 + counts_2); EXPECT_EQ(histogram_[value_1], counts_1); EXPECT_EQ(histogram_[value_2], counts_2); } TEST_F(TargetHistogramTest, FindSingularMaxFindsTheSingularMax) { histogram_[value_1] = counts_1; histogram_[value_2] = counts_2; ASSERT_TRUE(counts_1 > counts_2); TargetValue max_value(0); double max_counts = 0; EXPECT_TRUE(histogram_.FindSingularMax(&max_value, &max_counts)); EXPECT_EQ(max_value, value_1); EXPECT_EQ(max_counts, counts_1); } TEST_F(TargetHistogramTest, FindSingularMaxFindsTheSingularMaxAlternateOrder) { // Switch the order, to handle sorting in different directions. histogram_[value_1] = counts_2; histogram_[value_2] = counts_1; ASSERT_TRUE(counts_1 > counts_2); TargetValue max_value(0); double max_counts = 0; EXPECT_TRUE(histogram_.FindSingularMax(&max_value, &max_counts)); EXPECT_EQ(max_value, value_2); EXPECT_EQ(max_counts, counts_1); } TEST_F(TargetHistogramTest, FindSingularMaxReturnsFalsForNonSingularMax) { histogram_[value_1] = counts_1; histogram_[value_2] = counts_1; TargetValue max_value(0); double max_counts = 0; EXPECT_FALSE(histogram_.FindSingularMax(&max_value, &max_counts)); } TEST_F(TargetHistogramTest, FindSingularMaxIgnoresNonSingularNonMax) { histogram_[value_1] = counts_1; // |value_2| and |value_3| are tied, but not the max. histogram_[value_2] = counts_2; histogram_[value_3] = counts_2; ASSERT_TRUE(counts_1 > counts_2); TargetValue max_value(0); double max_counts = 0; EXPECT_TRUE(histogram_.FindSingularMax(&max_value, &max_counts)); EXPECT_EQ(max_value, value_1); EXPECT_EQ(max_counts, counts_1); } TEST_F(TargetHistogramTest, FindSingularMaxDoesntRequireCounts) { histogram_[value_1] = counts_1; TargetValue max_value(0); EXPECT_TRUE(histogram_.FindSingularMax(&max_value)); EXPECT_EQ(max_value, value_1); } TEST_F(TargetHistogramTest, EqualDistributionsCompareAsEqual) { histogram_[value_1] = counts_1; TargetHistogram histogram_2; histogram_2[value_1] = counts_1; EXPECT_TRUE(histogram_ == histogram_2); } TEST_F(TargetHistogramTest, UnequalDistributionsCompareAsNotEqual) { histogram_[value_1] = counts_1; TargetHistogram histogram_2; histogram_2[value_2] = counts_2; EXPECT_FALSE(histogram_ == histogram_2); } TEST_F(TargetHistogramTest, WeightedLabelledExamplesCountCorrectly) { LabelledExample example = {{}, value_1}; example.weight = counts_1; histogram_ += example; TargetHistogram histogram_2; for (size_t i = 0; i < counts_1; i++) histogram_2 += value_1; EXPECT_EQ(histogram_, histogram_2); } TEST_F(TargetHistogramTest, Normalize) { histogram_[value_1] = counts_1; histogram_[value_2] = counts_2; histogram_.Normalize(); EXPECT_EQ(histogram_[value_1], counts_1 / static_cast<double>(counts_1 + counts_2)); EXPECT_EQ(histogram_[value_2], counts_2 / static_cast<double>(counts_1 + counts_2)); } TEST_F(TargetHistogramTest, NormalizeEmptyDistribution) { // Normalizing an empty distribution should result in an empty distribution. histogram_.Normalize(); EXPECT_EQ(histogram_.total_counts(), 0); } } // namespace learning } // namespace media
28.718232
79
0.76087
zealoussnow
bf5ed1dff104ce61358cca50b4ea00c49b957dff
3,913
cpp
C++
src/internal/partition_kahip_process_mapping.cpp
cwpearson/tempi
fe16ae7692da83e9cd247782f596a46a1d010699
[ "BSL-1.0" ]
4
2021-03-15T20:21:46.000Z
2021-12-22T09:43:03.000Z
src/internal/partition_kahip_process_mapping.cpp
zhangjie119/tempi
fe16ae7692da83e9cd247782f596a46a1d010699
[ "BSL-1.0" ]
7
2021-02-12T19:38:44.000Z
2022-01-25T18:54:49.000Z
src/internal/partition_kahip_process_mapping.cpp
zhangjie119/tempi
fe16ae7692da83e9cd247782f596a46a1d010699
[ "BSL-1.0" ]
4
2021-02-10T16:11:26.000Z
2022-03-23T16:16:34.000Z
// Copyright Carl Pearson 2020 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // https://www.boost.org/LICENSE_1_0.txt) #include "partition.hpp" #include "logging.hpp" #include "kaHIP_interface.h" #include <algorithm> #include <cassert> #include <limits> #include <vector> partition::Result partition::kahip_process_mapping( const int nParts, const std::vector<int> &rowPtrs, const std::vector<int> &colInd, const std::vector<int> &colVal) { partition::Result result; result.part = std::vector<int>(rowPtrs.size() - 1, -1); /* process_mapping only works for unweighted graphs. To convert the graph to unweighted, delete any edge less than 1/10th the weight of the max */ std::vector<int> unRowPtr = rowPtrs; std::vector<int> unColInd = colInd; std::vector<int> unColVal = colVal; // zero all weights < 1/10 of max int maxWeight = 0; for (int e : colVal) { maxWeight = std::max(e, maxWeight); } for (int &e : unColVal) { if (e < maxWeight / 10) { e = 0; } } // remove all zero values from CSR bool changed = true; while (changed) { changed = false; auto it = std::find(unColVal.begin(), unColVal.end(), 0); if (unColVal.end() != it) { changed = true; int off = it - unColVal.begin(); unColVal.erase(it); unColInd.erase(unColInd.begin() + off); // reduce all rowPtr values pointing after the removed value auto lb = std::lower_bound(unRowPtr.begin(), unRowPtr.end(), off); if (lb != unRowPtr.end()) { assert(*lb <= off); ++lb; assert(*lb > off); for (; lb != unRowPtr.end(); ++lb) { --(*lb); } } } } std::cerr << "rowPtr: "; for (int e : unRowPtr) { std::cerr << e << " "; } std::cerr << "\n"; std::cerr << "colInd: "; for (int e : unColInd) { std::cerr << e << " "; } std::cerr << "\n"; int n = rowPtrs.size() - 1; int *vwgt = nullptr; // unweighted vertices // process_mapping won't modify these int *xadj = const_cast<int *>(unRowPtr.data()); int *adjcwgt = nullptr; // unweighted int *adjncy = const_cast<int *>(unColInd.data()); int mode_partitioning = FAST; int mode_mapping = MAPMODE_MULTISECTION; int edgecut; int qap; int *part = result.part.data(); int nRanks = (unRowPtr.size() - 1) / nParts; LOG_SPEW("nParts=" << nParts << " nRanks=" << nRanks); std::vector<int> hierarchy_parameter{nRanks, nParts}; std::vector<int> distance_parameter{1, 5}; int hierarchy_depth = distance_parameter.size(); double imbalance = 0.00; bool suppress_output = false; assert(n >= 0); // try some variable initial conditions int bestQap = std::numeric_limits<int>::max(); std::vector<int> best; for (int seed = 0; seed < 20; ++seed) { /* int* n, int* vwgt, int* xadj, int* adjcwgt, int* adjncy, int* hierarchy_parameter, int* distance_parameter, int hierarchy_depth, int mode_partitioning, int mode_mapping, double* imbalance, bool suppress_output, int seed, int* edgecut, int* qap, int* part */ // https://raw.githubusercontent.com/KaHIP/KaHIP/master/manual/kahip.pdf process_mapping_enforcebalance(&n, vwgt, xadj, adjcwgt, adjncy, hierarchy_parameter.data(), distance_parameter.data(), hierarchy_depth, mode_partitioning, mode_mapping, &imbalance, suppress_output, seed, &edgecut, &qap, part); LOG_SPEW("seed= " << seed << " qap=" << qap); if (qap < bestQap) { best = result.part; bestQap = qap; } if (bestQap == 0) { break; } } result.objective = bestQap; LOG_DEBUG("KaHIP process_mapping qap=" << result.objective); return result; }
27.556338
95
0.603373
cwpearson
bf5f3ddbf3c5107ba81a536e295076fb4bd4fbfd
3,622
cpp
C++
src/cic-plan/src/cic/plan/Target.cpp
Mezozoysky/cic
103a623db2b9d14c212867bd3319fb577cbcae1d
[ "Zlib" ]
null
null
null
src/cic-plan/src/cic/plan/Target.cpp
Mezozoysky/cic
103a623db2b9d14c212867bd3319fb577cbcae1d
[ "Zlib" ]
null
null
null
src/cic-plan/src/cic/plan/Target.cpp
Mezozoysky/cic
103a623db2b9d14c212867bd3319fb577cbcae1d
[ "Zlib" ]
null
null
null
// cic // // cic - Copyright (C) 2017-2018 Stanislav Demyanovich <mezozoysky@gmail.com> // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. /// \file /// \brief Target class implementation /// \author Stanislav Demyanovich <mezozoysky@gmail.com> /// \date 2018 /// \copyright cic is released under the terms of zlib/png license #include <cic/plan/Target.hpp> #include <cic/plan/Phase.hpp> #include <fmt/format.h> #include <Poco/Exception.h> #include <Poco/String.h> #include <cic/plan/Act.hpp> #include <cic/plan/Report.hpp> #include <Poco/DOM/Element.h> #include <Poco/AutoPtr.h> #include <Poco/DOM/NodeList.h> #include <algorithm> #include <functional> #include <Poco/Util/Application.h> using Poco::XML::Element; using Poco::XML::NodeList; using namespace fmt::literals; using Poco::AutoPtr; using cic::industry::Industry; namespace cic { namespace plan { Target::Target() : PerformConfig() { } void Target::loadFromXML( Element* root, Industry* industry ) { assert( Poco::XML::fromXMLString( root->nodeName() ) == "target" ); PerformConfig::loadFromXML( root, industry ); Element* elem{ root->getChildElement( "planPath" ) }; if ( elem != nullptr ) { std::string value{ Poco::trim( Poco::trim( elem->getAttribute( "value" ) ) ) }; // value can be empty setPlanPath( value ); } elem = root->getChildElement( "phases" ); if ( elem != nullptr ) { loadPhasesFromXML( elem, industry ); } } void Target::saveToXML( Element* root ) const {} void Target::setPlanPath( const std::string& planPath ) { onSetPlanPath( planPath ); mPlanPath = planPath; } void Target::onSetPlanPath( const std::string& planPath ) { return; } void Target::setPhases( const std::vector< std::string >& phaseList ) { onSetPhases( phaseList ); mPhases = phaseList; } void Target::onSetPhases( const std::vector< std::string >& phaseList ) { return; } void Target::loadPhasesFromXML( Element* root, Industry* industry ) { AutoPtr< NodeList > list{ root->childNodes() }; Element* elem{ nullptr }; std::vector< std::string > phaseNames; for ( std::size_t i{ 0 }; i < list->length(); ++i ) { elem = static_cast< Element* >( list->item( i ) ); if ( elem != nullptr && elem->nodeName() == "phase" ) { std::string value{ Poco::trim( elem->getAttribute( "value" ) ) }; if ( value.empty() ) { Poco::Util::Application::instance().logger().error( "Element 'phase' has no (or has empty) 'value' attribute" ); } else { phaseNames.push_back( value ); } } } setPhases( phaseNames ); } } // namespace plan } // namespace cic
26.437956
128
0.647156
Mezozoysky
bf607d50afdfd91d2462cc8c984bad9f5e3b0c3f
3,914
cpp
C++
library/celestia/source/catalogxref.cpp
Sphinkie/LongForgottenEarth
9008e4381091579e38feee03c56c5e3435419474
[ "MIT" ]
null
null
null
library/celestia/source/catalogxref.cpp
Sphinkie/LongForgottenEarth
9008e4381091579e38feee03c56c5e3435419474
[ "MIT" ]
null
null
null
library/celestia/source/catalogxref.cpp
Sphinkie/LongForgottenEarth
9008e4381091579e38feee03c56c5e3435419474
[ "MIT" ]
null
null
null
// catalogxref.cpp // // Copyright (C) 2001, Chris Laurel <claurel@shatters.net> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. #include <cctype> #include <algorithm> #include <celutil/util.h> #include "catalogxref.h" #include "stardb.h" using namespace std; CatalogCrossReference::CatalogCrossReference() { } CatalogCrossReference::~CatalogCrossReference() { } string CatalogCrossReference::getPrefix() const { return prefix; } void CatalogCrossReference::setPrefix(const string& _prefix) { prefix = _prefix; } bool operator<(const CatalogCrossReference::Entry& a, const CatalogCrossReference::Entry& b) { return a.catalogNumber < b.catalogNumber; } struct XrefEntryPredicate { int dummy; XrefEntryPredicate() : dummy(0) {}; bool operator()(const CatalogCrossReference::Entry& a, const CatalogCrossReference::Entry& b) const { return a.catalogNumber < b.catalogNumber; } }; Star* CatalogCrossReference::lookup(uint32 catalogNumber) const { Entry e; e.catalogNumber = catalogNumber; e.star = NULL; XrefEntryPredicate pred; vector<Entry>::const_iterator iter = lower_bound(entries.begin(), entries.end(), e, pred); if (iter != entries.end() && iter->catalogNumber == catalogNumber) return iter->star; else return NULL; } Star* CatalogCrossReference::lookup(const string& name) const { uint32 catalogNumber = parse(name); if (catalogNumber == InvalidCatalogNumber) return NULL; else return lookup(catalogNumber); } uint32 CatalogCrossReference::parse(const string& name) const { if (compareIgnoringCase(name, prefix, prefix.length()) != 0) return InvalidCatalogNumber; unsigned int i = prefix.length(); unsigned int n = 0; bool readDigit = false; // Optional space between prefix and number if (name[i] == ' ') i++; while (isdigit(name[i])) { n = n * 10 + ((unsigned int) name[i] - (unsigned int) '0'); readDigit = true; // Limited to 24 bits if (n >= 0x1000000) return InvalidCatalogNumber; } // Must have read at least one digit if (!readDigit) return InvalidCatalogNumber; // Check for garbage at the end of the string if (i != prefix.length()) return InvalidCatalogNumber; else return n; } void CatalogCrossReference::addEntry(uint32 catalogNumber, Star* star) { Entry e; e.catalogNumber = catalogNumber; e.star = star; entries.insert(entries.end(), e); } void CatalogCrossReference::sortEntries() { XrefEntryPredicate pred; sort(entries.begin(), entries.end(), pred); } void CatalogCrossReference::reserve(size_t n) { if (n > entries.size()) entries.reserve(n); } static uint32 readUint32(istream& in) { unsigned char b[4]; in.read(reinterpret_cast<char*>(b), 4); return ((uint32) b[3] << 24) + ((uint32) b[2] << 16) + ((uint32) b[1] << 8) + (uint32) b[0]; } CatalogCrossReference* ReadCatalogCrossReference(istream& in, const StarDatabase& stardb) { CatalogCrossReference* xref = new CatalogCrossReference(); uint32 nEntries = readUint32(in); if (!in.good()) { delete xref; return NULL; } xref->reserve(nEntries); for (uint32 i = 0; i < nEntries; i++) { uint32 catNo1 = readUint32(in); uint32 catNo2 = readUint32(in); Star* star = stardb.find(catNo2); if (star != NULL) xref->addEntry(catNo1, star); } return xref; }
22.112994
77
0.628769
Sphinkie
bf69ca037c6ce7c337383dd06ea19a5b82da1e85
9,938
cpp
C++
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/control_ak4558.cpp
Pocketart/typhoonclawvex
eb4b523c13541b2b9136d32259bd0399b46a289e
[ "MIT" ]
4
2017-10-06T05:48:30.000Z
2018-03-30T06:20:22.000Z
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/control_ak4558.cpp
Pocketart/typhoonclawvex
eb4b523c13541b2b9136d32259bd0399b46a289e
[ "MIT" ]
null
null
null
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/control_ak4558.cpp
Pocketart/typhoonclawvex
eb4b523c13541b2b9136d32259bd0399b46a289e
[ "MIT" ]
3
2017-10-06T06:01:44.000Z
2018-05-25T06:37:19.000Z
/* * HiFi Audio Codec Module support library for Teensy 3.x * * Copyright 2015, Michele Perla * */ #include "control_ak4558.h" #include "Wire.h" void AudioControlAK4558::initConfig(void) { // puts all default registers values inside an array // this allows us to modify registers locally using annotation like follows: // // registers[AK4558_CTRL_1] &= ~AK4558_DIF2; // registers[AK4558_CTRL_1] |= AK4558_DIF1 | AK4558_DIF0; // // after manipulation, we can write the entire register value on the CODEC uint8_t n = 0; Wire.requestFrom(AK4558_I2C_ADDR,10); while(Wire.available()) { #if AK4558_SERIAL_DEBUG > 0 Serial.print("Register "); Serial.print(n); Serial.print(" = "); #endif registers[n++] = Wire.read(); #if AK4558_SERIAL_DEBUG > 0 Serial.println(registers[n-1], BIN); #endif } } void AudioControlAK4558::readConfig(void) { // reads registers values uint8_t n = 0; uint8_t c = 0; Wire.requestFrom(AK4558_I2C_ADDR, 10); while(Wire.available()) { Serial.print("Register "); Serial.print(n++); Serial.print(" = "); c = Wire.read(); Serial.println(c, BIN); } } bool AudioControlAK4558::write(unsigned int reg, unsigned int val) { Wire.beginTransmission(AK4558_I2C_ADDR); Wire.write(reg); Wire.write(val); return (Wire.endTransmission(true)==0); } bool AudioControlAK4558::enableIn(void) { // ADC setup (datasheet page 74 #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable ADC"); #endif // ignore this, leaving default values - ADC: Set up the de-emphasis filter (Addr = 07H). registers[AK4558_PWR_MNGT] |= AK4558_PMADR | AK4558_PMADL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif delay(300); // Power up the ADC: PMADL = PMADR bits = “0” → “1” // Initialization cycle of the ADC is 5200/fs @Normal mode. The SDTO pin outputs “L” during initialization. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable ADC - Done"); #endif return true; } bool AudioControlAK4558::enableOut(void) { #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable DAC"); #endif // DAC Output setup (datasheet page 75) registers[AK4558_MODE_CTRL] |= AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Set the DAC output to power-save mode: LOPS bit “0” → “1” // ignore this, leaving default values - DAC: Set up the digital filter mode. // ignore this, leaving default values - Set up the digital output volume (Address = 08H, 09H). registers[AK4558_PWR_MNGT] |= AK4558_PMDAR | AK4558_PMDAL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif delay(300); // Power up the DAC: PMDAL = PMDAR bits = “0” → “1” // Outputs of the LOUT and ROUT pins start rising. Rise time is 300ms (max.) when C = 1μF. registers[AK4558_MODE_CTRL] &= ~AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Release power-save mode of the DAC output: LOPS bit = “1” → “0” // Set LOPS bit to “0” after the LOUT and ROUT pins output “H”. Sound data will be output from the // LOUT and ROUT pins after this setting. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable DAC - Done"); #endif return true; } bool AudioControlAK4558::enable(void) { #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable device"); #endif // Power Up and Reset // Clock Setup (datasheet page 72) pinMode(PIN_PDN, OUTPUT); digitalWrite(0, LOW); delay(1); digitalWrite(0, HIGH); // After Power Up: PDN pin “L” → “H” // “L” time of 150ns or more is needed to reset the AK4558. delay(20); #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: PDN is HIGH (device reset)"); #endif // Control register settings become available in 10ms (min.) when LDOE pin = “H” Wire.begin(); initConfig(); // access all registers to store locally their default values // DIF2-0, DFS1-0 and ACKS bits must be set before MCKI, LRCK and BICK are supplied // PMPLL = 0 (EXT Slave Mode; disables internal PLL and uses ext. clock) (by DEFAULT) // ACKS = 0 (Manual Setting Mode; disables automatic clock selection) (by DEFAULT) // DFS1-0 = 00 (Sampling Speed = Normal Speed Mode) (by DEFAULT) // TDM1-0 = 00 (Time Division Multiplexing mode OFF) (by DEFAULT) registers[AK4558_CTRL_1] &= ~AK4558_DIF2; registers[AK4558_CTRL_1] |= AK4558_DIF1 | AK4558_DIF0; #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: CTRL_1 set to "); Serial.println(registers[AK4558_CTRL_1], BIN); #endif // DIF2-1-0 = 011 ( 16 bit I2S compatible when BICK = 32fs) registers[AK4558_CTRL_2] &= ~AK4558_MCKS1; #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: CTRL_2 set to "); Serial.println(registers[AK4558_CTRL_2], BIN); #endif // MCKS1-0 = 00 (Master Clock Input Frequency Select, set 256fs for Normal Speed Mode -> 11.2896 MHz) registers[AK4558_MODE_CTRL] &= ~AK4558_BCKO0; // BCKO1-0 = 00 (BICK Output Frequency at Master Mode = 32fs = 1.4112 MHz) registers[AK4558_MODE_CTRL] |= AK4558_FS1; // Set up the sampling frequency (FS3-0 bits). The ADC must be powered-up in consideration of PLL // lock time. (in this case (ref. table 17): Set clock to mode 5 / 44.100 KHz) #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // BCKO1-0 = 00 (BICK Output Frequency at Master Mode = 32fs = 1.4112 MHz) Wire.beginTransmission(AK4558_I2C_ADDR); Wire.write(AK4558_CTRL_1); Wire.write(registers[AK4558_CTRL_1]); Wire.write(registers[AK4558_CTRL_2]); Wire.write(registers[AK4558_MODE_CTRL]); Wire.endTransmission(); // Write configuration registers in a single write operation (datasheet page 81): // The AK4558 can perform more than one byte write operation per sequence. After receipt of the third byte // the AK4558 generates an acknowledge and awaits the next data. The master can transmit more than // one byte instead of terminating the write cycle after the first data byte is transferred. After receiving each // data packet the internal address counter is incremented by one, and the next data is automatically taken // into the next address. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable device - Done"); #endif return true; } bool AudioControlAK4558::disableIn(void) { // ADC power-down (datasheet page 74 registers[AK4558_PWR_MNGT] &= ~AK4558_PMADR | ~AK4558_PMADL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif // Power down ADC: PMADL = PMADR bits = “1” → “0” #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Enable ADC - Done"); #endif return true; } bool AudioControlAK4558::disableOut(void) { #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Disable DAC"); #endif // DAC Output power-down (datasheet page 75) registers[AK4558_MODE_CTRL] |= AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Set the DAC output to power-save mode: LOPS bit “0” → “1” registers[AK4558_PWR_MNGT] &= ~AK4558_PMDAR | ~AK4558_PMDAL; write(AK4558_PWR_MNGT, registers[AK4558_PWR_MNGT]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: PWR_MNGT set to "); Serial.println(registers[AK4558_PWR_MNGT], BIN); #endif delay(300); // Power down the DAC: PMDAL = PMDAR bits = “1” → “0” // Outputs of the LOUT and ROUT pins start falling. Rise time is 300ms (max.) when C = 1μF. registers[AK4558_MODE_CTRL] &= ~AK4558_LOPS; write(AK4558_MODE_CTRL, registers[AK4558_MODE_CTRL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: MODE_CTRL set to "); Serial.println(registers[AK4558_MODE_CTRL], BIN); #endif // Release power-save mode of the DAC output: LOPS bit = “1” → “0” // Set LOPS bit to “0” after outputs of the LOUT and ROUT pins fall to “L”. #if AK4558_SERIAL_DEBUG > 0 Serial.println("AK4558: Disable DAC - Done"); #endif return true; } uint8_t AudioControlAK4558::convertVolume(float vol) { // Convert float (range 0.0-1.0) to unsigned char (range 0x00-0xFF) uint8_t temp = ((uint32_t)vol)>>22; return temp; } bool AudioControlAK4558::volume(float n) { // Set DAC output volume uint8_t vol = convertVolume(n); registers[AK4558_LOUT_VOL] = vol; registers[AK4558_ROUT_VOL] = vol; Wire.beginTransmission(AK4558_I2C_ADDR); Wire.write(AK4558_LOUT_VOL); Wire.write(registers[AK4558_LOUT_VOL]); Wire.write(registers[AK4558_ROUT_VOL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: LOUT_VOL set to "); Serial.println(registers[AK4558_LOUT_VOL], BIN); Serial.print("AK4558: ROUT_VOL set to "); Serial.println(registers[AK4558_ROUT_VOL], BIN); #endif return (Wire.endTransmission(true)==0); } bool AudioControlAK4558::volumeLeft(float n) { // Set DAC left output volume uint8_t vol = convertVolume(n); registers[AK4558_LOUT_VOL] = vol; bool ret = write(AK4558_LOUT_VOL, registers[AK4558_LOUT_VOL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: LOUT_VOL set to "); Serial.println(registers[AK4558_LOUT_VOL], BIN); #endif return ret; } bool AudioControlAK4558::volumeRight(float n) { // Set DAC right output volume uint8_t vol = convertVolume(n); registers[AK4558_ROUT_VOL] = vol; bool ret = write(AK4558_ROUT_VOL, registers[AK4558_ROUT_VOL]); #if AK4558_SERIAL_DEBUG > 0 Serial.print("AK4558: ROUT_VOL set to "); Serial.println(registers[AK4558_ROUT_VOL], BIN); #endif return ret; }
33.016611
114
0.732642
Pocketart
bf6b647a11daff2589ffce149e9cad4eb08677be
4,914
cpp
C++
src/lib/pubkey/rw/rw.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
src/lib/pubkey/rw/rw.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
src/lib/pubkey/rw/rw.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
/* * Rabin-Williams * (C) 1999-2008 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/pk_utils.h> #include <botan/rw.h> #include <botan/keypair.h> #include <botan/parsing.h> #include <botan/reducer.h> #include <botan/blinding.h> #include <algorithm> #include <future> namespace Botan { /* * Create a Rabin-Williams private key */ RW_PrivateKey::RW_PrivateKey(RandomNumberGenerator& rng, size_t bits, size_t exp) { if(bits < 1024) throw Invalid_Argument(algo_name() + ": Can't make a key that is only " + std::to_string(bits) + " bits long"); if(exp < 2 || exp % 2 == 1) throw Invalid_Argument(algo_name() + ": Invalid encryption exponent"); m_e = exp; do { m_p = random_prime(rng, (bits + 1) / 2, m_e / 2, 3, 4); m_q = random_prime(rng, bits - m_p.bits(), m_e / 2, ((m_p % 8 == 3) ? 7 : 3), 8); m_n = m_p * m_q; } while(m_n.bits() != bits); m_d = inverse_mod(m_e, lcm(m_p - 1, m_q - 1) >> 1); m_d1 = m_d % (m_p - 1); m_d2 = m_d % (m_q - 1); m_c = inverse_mod(m_q, m_p); gen_check(rng); } /* * Check Private Rabin-Williams Parameters */ bool RW_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!IF_Scheme_PrivateKey::check_key(rng, strong)) return false; if(!strong) return true; if((m_e * m_d) % (lcm(m_p - 1, m_q - 1) / 2) != 1) return false; return KeyPair::signature_consistency_check(rng, *this, "EMSA2(SHA-1)"); } namespace { /** * Rabin-Williams Signature Operation */ class RW_Signature_Operation : public PK_Ops::Signature_with_EMSA { public: typedef RW_PrivateKey Key_Type; RW_Signature_Operation(const RW_PrivateKey& rw, const std::string& emsa) : PK_Ops::Signature_with_EMSA(emsa), m_n(rw.get_n()), m_e(rw.get_e()), m_q(rw.get_q()), m_c(rw.get_c()), m_powermod_d1_p(rw.get_d1(), rw.get_p()), m_powermod_d2_q(rw.get_d2(), rw.get_q()), m_mod_p(rw.get_p()), m_blinder(m_n, [this](const BigInt& k) { return power_mod(k, m_e, m_n); }, [this](const BigInt& k) { return inverse_mod(k, m_n); }) { } size_t max_input_bits() const override { return (m_n.bits() - 1); } secure_vector<byte> raw_sign(const byte msg[], size_t msg_len, RandomNumberGenerator& rng) override; private: const BigInt& m_n; const BigInt& m_e; const BigInt& m_q; const BigInt& m_c; Fixed_Exponent_Power_Mod m_powermod_d1_p, m_powermod_d2_q; Modular_Reducer m_mod_p; Blinder m_blinder; }; secure_vector<byte> RW_Signature_Operation::raw_sign(const byte msg[], size_t msg_len, RandomNumberGenerator&) { BigInt i(msg, msg_len); if(i >= m_n || i % 16 != 12) throw Invalid_Argument("Rabin-Williams: invalid input"); if(jacobi(i, m_n) != 1) i >>= 1; i = m_blinder.blind(i); auto future_j1 = std::async(std::launch::async, m_powermod_d1_p, i); const BigInt j2 = m_powermod_d2_q(i); BigInt j1 = future_j1.get(); j1 = m_mod_p.reduce(sub_mul(j1, j2, m_c)); const BigInt r = m_blinder.unblind(mul_add(j1, m_q, j2)); return BigInt::encode_1363(std::min(r, m_n - r), m_n.bytes()); } /** * Rabin-Williams Verification Operation */ class RW_Verification_Operation : public PK_Ops::Verification_with_EMSA { public: typedef RW_PublicKey Key_Type; RW_Verification_Operation(const RW_PublicKey& rw, const std::string& emsa) : PK_Ops::Verification_with_EMSA(emsa), m_n(rw.get_n()), m_powermod_e_n(rw.get_e(), rw.get_n()) {} size_t max_input_bits() const override { return (m_n.bits() - 1); } bool with_recovery() const override { return true; } secure_vector<byte> verify_mr(const byte msg[], size_t msg_len) override; private: const BigInt& m_n; Fixed_Exponent_Power_Mod m_powermod_e_n; }; secure_vector<byte> RW_Verification_Operation::verify_mr(const byte msg[], size_t msg_len) { BigInt m(msg, msg_len); if((m > (m_n >> 1)) || m.is_negative()) throw Invalid_Argument("RW signature verification: m > n / 2 || m < 0"); BigInt r = m_powermod_e_n(m); if(r % 16 == 12) return BigInt::encode_locked(r); if(r % 8 == 6) return BigInt::encode_locked(2*r); r = m_n - r; if(r % 16 == 12) return BigInt::encode_locked(r); if(r % 8 == 6) return BigInt::encode_locked(2*r); throw Invalid_Argument("RW signature verification: Invalid signature"); } BOTAN_REGISTER_PK_SIGNATURE_OP("RW", RW_Signature_Operation); BOTAN_REGISTER_PK_VERIFY_OP("RW", RW_Verification_Operation); } }
26.852459
87
0.614774
el-forkorama
bf6dad0efa8f4b117237b4443ee57524dfcbf432
4,213
hpp
C++
zen/bones/framework/bones_framework_accessor.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
1
2016-12-10T07:21:17.000Z
2016-12-10T07:21:17.000Z
zen/bones/framework/bones_framework_accessor.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
null
null
null
zen/bones/framework/bones_framework_accessor.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
null
null
null
#ifndef __ZEN__BONES_FRAMEWORK_ACCESSOR__HPP #define __ZEN__BONES_FRAMEWORK_ACCESSOR__HPP /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// #include <zen/bones/bones_framework.h> #include <zen/bones/framework/bones_framework_dispatcher.hpp> #include <unordered_map> #include <functional> #include <iostream> #include <sys/socket.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <netdb.h> #include <thread> /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// class zen::bones_framework_accessor : public std::enable_shared_from_this< zen::bones_framework_accessor > { using entangled_shared = types< zen::bones_framework_accessor >::weak; using event_callback_function = std::function< void( zen::bones_framework_event_shared & ) >; using callbacks_type = std::unordered_map< std::string, event_callback_function >; bones_framework_accessor( const zen::bones_framework_accessor & ) = delete; bones_framework_accessor & operator=( zen::bones_framework_accessor ) = delete; bones_framework_accessor( zen::bones_framework_accessor && ) = delete; bones_framework_accessor & operator=( zen::bones_framework_accessor && ) = delete; public: ~bones_framework_accessor(); bones_framework_accessor( zen::bones_framework_dispatcher_shared dispatcher_, std::string name_, zen::bones_framework_accessor_shared ownership_ ); bones_framework_accessor( const zen::bones_framework_dispatcher_shared &dispatcher_, const std::string &name_ ); const std::string& name() const { return _name; } static zen::bones_framework_accessor_shared factory( zen::bones_framework_dispatcher_shared dispatcher_, const std::string &name_ ); static zen::bones_framework_accessor_shared factory( zen::bones_framework_dispatcher_shared dispatcher_, const std::string &host_, int port_ ); void start_dispatcher( zen::bones_framework_accessor_shared me_shared_, int sock_fd_ ); void set_entangled( zen::bones_framework_accessor_shared &entangled_ ); void set_session_ownership( zen::bones_framework_session_shared &session_instance_ ); template< typename Session > void callback( const std::string &name_, void (Session::*callback_function_)( const zen::bones_framework_event_shared &event_ ), Session *callback_session_ ); void uncallback( const std::string &name_ ); void deliver( const zen::bones_framework_event_shared &event_ ); void dispatch( const zen::bones_framework_event_shared &event_ ); void dispatch( const std::string &tag_, const std::string &payload_ = "" ); private: void dispatcher( zen::bones_framework_accessor_shared keep_me_alive_, int sock_fd_ ); private: int _sock_fd{ -1 }; std::string _name; entangled_shared _entangled; callbacks_type _callbacks; zen::bones_framework_dispatcher_shared _service_dispatcher{ nullptr }; zen::bones_framework_accessor_shared _accessor_ownership{ nullptr }; zen::bones_framework_session_shared _session_ownership{ nullptr }; }; /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// template< typename Session > void zen::bones_framework_accessor::callback( const std::string &name_, void (Session::*callback_function_)( const zen::bones_framework_event_shared &event_ ), Session *callback_session_ ) { auto callback = [ callback_session_, callback_function_ ]( zen::bones_framework_event_shared &event_ ) { ( callback_session_->*callback_function_ )( event_ ); }; _callbacks[ name_ ] = callback; } /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// #endif // __ZEN__BONES_FRAMEWORK_ACCESSOR__HPP
25.533333
99
0.631379
shauncroton
bf726d78631657925f855300541b782988ea76b3
2,014
hpp
C++
etl/_functional/invoke.hpp
tobanteAudio/taetl
0aa6365aa156b297745f395882ff366a8626e5e0
[ "BSL-1.0" ]
null
null
null
etl/_functional/invoke.hpp
tobanteAudio/taetl
0aa6365aa156b297745f395882ff366a8626e5e0
[ "BSL-1.0" ]
null
null
null
etl/_functional/invoke.hpp
tobanteAudio/taetl
0aa6365aa156b297745f395882ff366a8626e5e0
[ "BSL-1.0" ]
1
2019-04-29T20:09:19.000Z
2019-04-29T20:09:19.000Z
/// \copyright Tobias Hienzsch 2019-2021 /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt #ifndef TETL_FUNCTIONAL_INVOKE_HPP #define TETL_FUNCTIONAL_INVOKE_HPP #include "etl/_type_traits/decay.hpp" #include "etl/_type_traits/invoke_result.hpp" #include "etl/_type_traits/is_base_of.hpp" #include "etl/_type_traits/is_function.hpp" #include "etl/_type_traits/is_member_pointer.hpp" #include "etl/_type_traits/is_object.hpp" #include "etl/_utility/forward.hpp" namespace etl { namespace detail { template <typename C, typename Pointed, typename T1, typename... Args> constexpr auto invoke_memptr(Pointed C::*f, T1&& t1, Args&&... args) -> decltype(auto) { if constexpr (etl::is_function_v<Pointed>) { if constexpr (etl::is_base_of_v<C, etl::decay_t<T1>>) { return (etl::forward<T1>(t1).*f)(etl::forward<Args>(args)...); } else if constexpr (is_reference_wrapper_v<etl::decay_t<T1>>) { return (t1.get().*f)(etl::forward<Args>(args)...); } else { return ((*etl::forward<T1>(t1)).*f)(etl::forward<Args>(args)...); } } else { static_assert(etl::is_object_v<Pointed> && sizeof...(args) == 0); if constexpr (etl::is_base_of_v<C, etl::decay_t<T1>>) { return etl::forward<T1>(t1).*f; } else if constexpr (is_reference_wrapper_v<etl::decay_t<T1>>) { return t1.get().*f; } else { return (*etl::forward<T1>(t1)).*f; } } } } // namespace detail // todo Add noexcept(is_nothrow_invocable_v<F, Args...>) template <typename F, typename... Args> constexpr auto invoke(F&& f, Args&&... args) -> invoke_result_t<F, Args...> { if constexpr (is_member_pointer_v<decay_t<F>>) { return detail::invoke_memptr(f, forward<Args>(args)...); } else { return forward<F>(f)(forward<Args>(args)...); } } } // namespace etl #endif // TETL_FUNCTIONAL_INVOKE_HPP
34.724138
77
0.648461
tobanteAudio
bf73c8565bb825a44bedfc152cb1df858b7db48b
1,208
cpp
C++
prog-lab-I/VE2019/ve_17029_Q1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
prog-lab-I/VE2019/ve_17029_Q1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
prog-lab-I/VE2019/ve_17029_Q1.cpp
hsnavarro/CompIME
b4f285826d001b6f818d94636a6294782f1cedf2
[ "MIT" ]
null
null
null
// Feito por Henrique Navarro - 17029 #include<bits/stdc++.h> using namespace std; // usando funcionalidades do C++11 class burrowsWheeler{ string palavra; string modificarEntrada(){ return '^' + palavra + '|'; } vector<string> rotacoes(string modificada){ vector<string> resposta; resposta.push_back(modificada); while(true){ char ultima = modificada.back(); modificada = ultima + modificada; modificada.pop_back(); if(modificada == resposta[0]) break; resposta.push_back(modificada); } return resposta; } vector<string> ordena(vector<string> rotacoes){ sort(rotacoes.begin(), rotacoes.end()); return rotacoes; } string destacaColuna(vector<string> ordenado){ string ans; //C++ 11 for(auto x : ordenado) ans += x.back(); return ans; } public: burrowsWheeler(string palavra) : palavra(palavra) {} string getPalavra() { return palavra; } void transformada(){ vector<string> rot = rotacoes(modificarEntrada()); rot = ordena(rot); palavra = destacaColuna(rot); } }; int main(){ burrowsWheeler A("BANANA"); A.transformada(); cout << A.getPalavra() << endl; }
23.686275
56
0.638245
hsnavarro
bf746556bb6ca8905c14c54009b2b0c27f3b3b38
526
cpp
C++
apps/sequence/values/interval_parameter_controller.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
apps/sequence/values/interval_parameter_controller.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
apps/sequence/values/interval_parameter_controller.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#include "interval_parameter_controller.h" #include <cmath> using namespace Shared; namespace Sequence { bool IntervalParameterController::setParameterAtIndex(int parameterIndex, double f) { if (f < 0) { Escher::Container::activeApp()->displayWarning(I18n::Message::ForbiddenValue); return false; } double parameter = std::round(f); if (parameterIndex == 2 && parameter == 0.0f) { parameter = 1.0f; } return Shared::IntervalParameterController::setParameterAtIndex(parameterIndex, parameter); } }
23.909091
93
0.730038
VersiraSec
bf7645fa5a548be2ddf9ef41cf6268c8cde945b3
995
hpp
C++
CS791x_Fall14/Project02_ConsensusFilter/code/target_field.hpp
T-R0D/Past-Courses
0edc83a7bf09515f0d01d23a26df2ff90c0f458a
[ "MIT" ]
7
2017-03-13T17:32:26.000Z
2021-09-27T16:51:22.000Z
CS791x_Fall14/Project02_ConsensusFilter/code/target_field.hpp
T-R0D/Past-Courses
0edc83a7bf09515f0d01d23a26df2ff90c0f458a
[ "MIT" ]
1
2021-05-29T19:54:02.000Z
2021-05-29T19:54:52.000Z
CS791x_Fall14/Project02_ConsensusFilter/code/target_field.hpp
T-R0D/Past-Courses
0edc83a7bf09515f0d01d23a26df2ff90c0f458a
[ "MIT" ]
25
2016-10-18T03:31:44.000Z
2020-12-29T13:23:10.000Z
#ifndef __TARGET_FIELD_HPP__ #define __TARGET_FIELD_HPP__ 1 #include <list> #include <vector> #include <Eigen/Dense> class TargetField { public: const double ignore = -666.666; class Target { public: Target( const double p_value, const std::pair<double, double> p_coordinates ); ~Target(); double value() const; std::pair<double, double> coordinates() const; private: double value_; std::pair<double, double> coordinates_; }; TargetField( const double p_x_size, const double p_y_size, const int p_num_cells ); ~TargetField(); TargetField& add_target(const Target& p_target); std::vector<Target> get_targets() const; Eigen::MatrixXd as_cells() const; std::pair<double, double> coordinates_of_cell( const int p_cell_x, const int p_cell_y ) const; private: int num_cells_; double x_size_; double y_size_; std::vector<Target> targets_; }; #endif //__TARGET_FIELD_HPP__
17.767857
51
0.672362
T-R0D
bf7716ed7210313346d7886dde4b744d86b388aa
370
cpp
C++
lib/src/ast/ast_base.cpp
rhysd/rill
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
[ "BSL-1.0" ]
null
null
null
lib/src/ast/ast_base.cpp
rhysd/rill
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
[ "BSL-1.0" ]
null
null
null
lib/src/ast/ast_base.cpp
rhysd/rill
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
[ "BSL-1.0" ]
null
null
null
// // Copyright yutopp 2013 - . // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <rill/ast/ast_base.hpp> namespace rill { namespace ast { detail::ast_id_generator ast_base::igen_ = {}; } // namespace ast } // namespace rill
18.5
61
0.667568
rhysd
bf78ce060d8b93791d53aaf5d3cdc29b4743d110
1,465
cc
C++
LeetCode/Medium/GenerateParanthesis.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
LeetCode/Medium/GenerateParanthesis.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
LeetCode/Medium/GenerateParanthesis.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/generate-parentheses/description/ /*Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] */ #include <iostream> #include <algorithm> #include <vector> #include <stack> using namespace std; class Solution { public: bool valid_paranthesis(string s) { bool flag = true; stack<char> stk; for (int i = 0; i < s.length(); i++) { if (s[i] == '(') stk.push(s[i]); if (s[i] == ')') { if (stk.empty()) return false; else stk.pop(); } } return flag; } vector<string> generateParenthesis(int n) { if (n <= 0) return {}; vector<string> v; string s; for (int i = 0; i < n; i++) s += "("; for (int i = 0; i < n; i++) s += ")"; do { if (valid_paranthesis(s)) v.push_back(s); } while (next_permutation(s.begin(), s.end())); return v; } }; int main() { Solution obj; int count = 1; vector<string> v = obj.generateParenthesis(6); for (string i : v) { cout << count << ":\t" << i << endl; count++; } }
20.347222
105
0.43959
ChakreshSinghUC
bf7aa0fff25188cfa7e25e89e340e723447887d0
3,982
cc
C++
src/iohal/translators/vm_i386_pae.cc
MarkMankins/libosi
2d67ed8066098bc798a53c06dffb5ba257d89bde
[ "BSD-3-Clause" ]
3
2021-02-23T09:13:07.000Z
2021-08-13T14:15:06.000Z
src/iohal/translators/vm_i386_pae.cc
MarkMankins/libosi
2d67ed8066098bc798a53c06dffb5ba257d89bde
[ "BSD-3-Clause" ]
3
2021-12-02T17:51:48.000Z
2022-03-04T20:02:32.000Z
src/iohal/translators/vm_i386_pae.cc
MarkMankins/libosi
2d67ed8066098bc798a53c06dffb5ba257d89bde
[ "BSD-3-Clause" ]
2
2021-12-07T00:42:31.000Z
2022-03-04T15:42:12.000Z
#include <cstdio> #include <cstdlib> #include "iohal/memory/physical_memory.h" #include "iohal/memory/virtual_memory.h" #include "vm_i386_pae.h" namespace i386_pae_translator { #define HW_PTE_MASK 0xFFFFFFFFFF000 static inline pm_addr_t get_page_directory_pointer_index(vm_addr_t vaddr) { uint64_t pdpimask = 0xC0000000; return ((vaddr & pdpimask) >> 30); } static inline pm_addr_t get_page_directory_index(vm_addr_t vaddr) // index * sizeof(QUAD) { uint64_t pdimask = 0x3FE00000; return ((vaddr & pdimask) >> 21); } static inline pm_addr_t get_page_table_index(vm_addr_t vaddr) // index * sizeof(QUAD) { uint64_t ptimask = 0x1FF000; return ((vaddr & ptimask) >> 12); } static inline pm_addr_t get_byte_offset(vm_addr_t vaddr) // index * sizeof(QUAD) { uint64_t byteoffsetmask = 0xFFF; return (vaddr & byteoffsetmask); } static inline pm_addr_t get_2MB_byte_offset(vm_addr_t vaddr) { uint64_t byteoffsetmask = 0x1FFFFF; return (vaddr & byteoffsetmask); } static inline bool entry_present(vm_addr_t entry, TranslateProfile profile) { bool present = ((entry & 1) == 1); bool in_transition = ((entry & (1 << 11)) && !(entry & (1 << 10))); bool global = (entry & (1 << 8)); if (profile == TPROF_GENERIC_LINUX) { return present || global; } else if (profile == TPROF_GENERIC_WINDOWS) { return present || in_transition; } return present; } static inline bool is_large_page(pm_addr_t entry) { return ((entry & (1 << 7)) > 0); } static inline pm_addr_t get_pdpe(PhysicalMemory* pmem, vm_addr_t addr, pm_addr_t pdpt_base_addr) { int size_of_pdpe = 8; auto pdpe_index = get_page_directory_pointer_index(addr); auto pdpe_addr = pdpt_base_addr + (pdpe_index * size_of_pdpe); pm_addr_t pdpe_entry = 0; pmem->read(pmem, pdpe_addr, (uint8_t*)&pdpe_entry, size_of_pdpe); return pdpe_entry; } static inline pm_addr_t get_pde(struct PhysicalMemory* pmem, vm_addr_t addr, pm_addr_t pdt_base_addr) { size_t size_of_pde = 8; auto pde_index = get_page_directory_index(addr); auto pde_addr = pdt_base_addr + (pde_index * size_of_pde); pm_addr_t pde = 0; pmem->read(pmem, pde_addr, (uint8_t*)&pde, size_of_pde); return pde; } static inline pm_addr_t get_pte(struct PhysicalMemory* pmem, vm_addr_t addr, pm_addr_t pt_base_addr) { size_t size_of_pte = 8; auto pte_index = get_page_table_index(addr); auto pte_addr = pt_base_addr + (pte_index * size_of_pte); pm_addr_t pte = 0; pmem->read(pmem, pte_addr, (uint8_t*)&pte, size_of_pte); return pte; } TranslateStatus translate_address(struct PhysicalMemory* pm, vm_addr_t vm_addr, pm_addr_t* pm_addr, pm_addr_t asid, TranslateProfile profile) { // Read the base address of the page directory pointer table (pdpt) from cr4 uint64_t cr3_pfn = asid & 0xFFFFFFE0; auto pdp_entry = get_pdpe(pm, vm_addr, cr3_pfn); if (!entry_present(pdp_entry, profile)) { return TSTAT_INVALID_ADDRESS; } uint64_t pdp_pfn = pdp_entry & 0xFFFFFFFFFF000; auto pde = get_pde(pm, vm_addr, pdp_pfn); if (!entry_present(pde, profile)) { return TSTAT_INVALID_ADDRESS; // TODO check if paged out } // Handle large pages if (is_large_page(pde)) { *pm_addr = (pde & 0xFFFFFFFE00000) + get_2MB_byte_offset(vm_addr); return TSTAT_SUCCESS; } uint64_t pd_pfn = pde & HW_PTE_MASK; // Read the base address of the page table (PT) from the PDT auto pte = get_pte(pm, vm_addr, pd_pfn); if (!entry_present(pte, profile)) { return TSTAT_PAGED_OUT; // TODO check if paged out } // Read the physical page offset from the PT *pm_addr = (pte & HW_PTE_MASK) + get_byte_offset(vm_addr); return TSTAT_SUCCESS; } } // namespace i386_pae_translator
30.630769
89
0.67328
MarkMankins
bf7bfcad92fac0f3947c948f99e433763fcab4ff
3,986
cpp
C++
wz_strategic_plugin/test/test_transition_table.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
112
2020-04-27T17:06:46.000Z
2022-03-31T15:27:14.000Z
wz_strategic_plugin/test/test_transition_table.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
982
2020-04-17T11:28:04.000Z
2022-03-31T21:12:19.000Z
wz_strategic_plugin/test/test_transition_table.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
57
2020-05-07T15:48:11.000Z
2022-03-09T23:31:45.000Z
/* * Copyright (C) 2021 LEIDOS. * * 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 <gtest/gtest.h> #include <ros/console.h> #include "test_fixture.h" #include "wz_strategic_plugin/wz_state_transition_table.h" // Unit tests for transition table namespace wz_strategic_plugin { /** * \brief Helper function to assert that the provided list of signals do not change the current state of the provided * transition table */ void testNonTransitionSignals(WorkZoneStateTransitionTable& table, const std::vector<TransitEvent>& signals) { TransitState initial_state = table.getState(); for (TransitEvent signal : signals) { table.signal(signal); ASSERT_EQ(initial_state, table.getState()); } } TEST_F(WorkZoneTestFixture, getState) { WorkZoneStateTransitionTable table; ASSERT_EQ(TransitState::UNAVAILABLE, table.getState()); table.signal(TransitEvent::IN_STOPPING_RANGE); ASSERT_EQ(TransitState::APPROACHING, table.getState()); } // Unit test to evaluate all state transitions TEST_F(WorkZoneTestFixture, signal) { WorkZoneStateTransitionTable table; ASSERT_EQ(TransitState::UNAVAILABLE, table.getState()); testNonTransitionSignals(table, { TransitEvent::STOPPED, TransitEvent::RED_TO_GREEN_LIGHT, TransitEvent::CROSSED_STOP_BAR, TransitEvent::INTERSECTION_EXIT }); table.signal(TransitEvent::IN_STOPPING_RANGE); ASSERT_EQ(TransitState::APPROACHING, table.getState()); testNonTransitionSignals( table, { TransitEvent::IN_STOPPING_RANGE, TransitEvent::RED_TO_GREEN_LIGHT, TransitEvent::INTERSECTION_EXIT }); table.signal(TransitEvent::STOPPED); ASSERT_EQ(TransitState::WAITING, table.getState()); testNonTransitionSignals(table, { TransitEvent::IN_STOPPING_RANGE, TransitEvent::STOPPED, TransitEvent::CROSSED_STOP_BAR, TransitEvent::INTERSECTION_EXIT }); table.signal(TransitEvent::RED_TO_GREEN_LIGHT); ASSERT_EQ(TransitState::DEPARTING, table.getState()); testNonTransitionSignals(table, { TransitEvent::IN_STOPPING_RANGE, TransitEvent::STOPPED, TransitEvent::RED_TO_GREEN_LIGHT, TransitEvent::CROSSED_STOP_BAR }); table.signal(TransitEvent::INTERSECTION_EXIT); ASSERT_EQ(TransitState::UNAVAILABLE, table.getState()); // Reset table to test non-stopping case table = WorkZoneStateTransitionTable(); table.signal(TransitEvent::IN_STOPPING_RANGE); ASSERT_EQ(TransitState::APPROACHING, table.getState()); table.signal(TransitEvent::CROSSED_STOP_BAR); ASSERT_EQ(TransitState::DEPARTING, table.getState()); } TEST_F(WorkZoneTestFixture, setTransitionCallback) { WorkZoneStateTransitionTable table; boost::optional<TransitState> prev, current; boost::optional<TransitEvent> sig; table.setTransitionCallback([&](TransitState prev_state, TransitState new_state, TransitEvent signal) { prev = prev_state; current = new_state; sig = signal; }); ASSERT_FALSE(!!prev); ASSERT_FALSE(!!current); ASSERT_FALSE(!!sig); ASSERT_EQ(TransitState::UNAVAILABLE, table.getState()); table.signal(TransitEvent::IN_STOPPING_RANGE); ASSERT_EQ(TransitState::APPROACHING, table.getState()); ASSERT_TRUE(!!prev); ASSERT_TRUE(!!current); ASSERT_TRUE(!!sig); ASSERT_EQ(TransitState::UNAVAILABLE, prev.get()); ASSERT_EQ(TransitState::APPROACHING, current.get()); ASSERT_EQ(TransitEvent::IN_STOPPING_RANGE, sig.get()); } } // namespace wz_strategic_plugin
32.672131
117
0.749624
adamlm
bf7e24e015b068926fc1bf134e00fc8cbfa5d71a
1,379
hpp
C++
Svc/CmdSequencer/test/ut/SequenceFiles/BadDescriptorFile.hpp
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
5
2019-10-22T03:41:02.000Z
2022-01-16T12:48:31.000Z
Svc/CmdSequencer/test/ut/SequenceFiles/BadDescriptorFile.hpp
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
42
2021-06-10T23:31:10.000Z
2021-06-25T00:35:31.000Z
Svc/CmdSequencer/test/ut/SequenceFiles/BadDescriptorFile.hpp
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
3
2020-09-05T18:17:21.000Z
2020-11-15T04:06:24.000Z
// ====================================================================== // \title BadDescriptorFile.hpp // \author Rob Bocchino // \brief BadDescriptorFile interface // // \copyright // Copyright (C) 2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef Svc_SequenceFiles_BadDescriptorFile_HPP #define Svc_SequenceFiles_BadDescriptorFile_HPP #include "Svc/CmdSequencer/test/ut/SequenceFiles/File.hpp" #include "Svc/CmdSequencer/CmdSequencerImpl.hpp" namespace Svc { namespace SequenceFiles { //! A file with a bad record descriptor class BadDescriptorFile : public File { public: //! Construct a BadDescriptorFile BadDescriptorFile( const U32 n, //!< The number of records const Format::t = Format::F_PRIME //!< The file format ); public: //! Serialize the file in F Prime format void serializeFPrime( Fw::SerializeBufferBase& buffer //!< The buffer ); //! Serialize the file in AMPCS format void serializeAMPCS( Fw::SerializeBufferBase& buffer //!< The buffer ); public: //! The number of records const U32 n; }; } } #endif
22.983333
74
0.572879
SSteve
bf81a58df9838c786792dbb2904cf32b7cf74f85
1,314
cpp
C++
vr/vr_rt/src/vr/market/books/execution_order_book.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
4
2019-09-09T22:08:40.000Z
2021-05-17T13:43:31.000Z
vr/vr_rt/src/vr/market/books/execution_order_book.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
null
null
null
vr/vr_rt/src/vr/market/books/execution_order_book.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
1
2019-09-09T15:46:20.000Z
2019-09-09T15:46:20.000Z
#include "vr/market/books/execution_order_book.h" #include "vr/util/ops_int.h" //---------------------------------------------------------------------------- namespace vr { namespace market { namespace ex { //............................................................................ std::ostream & operator<< (std::ostream & os, fsm_state const & obj) VR_NOEXCEPT { os << print (obj.order_state ()); auto ps = obj.pending_state (); if (ps) { os << " {"; bool first { true }; while (ps > 0) { int32_t const bit = (ps & - ps); ps ^= bit; if (first) first = false; else os << '|'; os << static_cast<fsm_state::pending::enum_t> (bit); } os << '}'; } return os; } //............................................................................ std::ostream & operator<< (std::ostream & os, fsm_error const & obj) VR_NOEXCEPT { if (VR_LIKELY (obj.m_lineno <= 0)) return os << "N/A"; else return os << "[line: " << obj.m_lineno << ", src state: " << print (obj.m_state) << ']'; } } // end of 'ex' } // end of 'market' } // end of namespace //----------------------------------------------------------------------------
22.271186
96
0.376712
vladium
bf867f5b556810900c9ef783fdbc96f4ae343e0e
13,265
cpp
C++
test/test_set.cpp
raitechnology/raids
da203e992c03e651f56b282c885db179eb7121fd
[ "Apache-2.0" ]
3
2021-04-27T22:05:35.000Z
2022-01-18T03:19:58.000Z
test/test_set.cpp
raitechnology/raids
da203e992c03e651f56b282c885db179eb7121fd
[ "Apache-2.0" ]
null
null
null
test/test_set.cpp
raitechnology/raids
da203e992c03e651f56b282c885db179eb7121fd
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <raids/redis_cmd.h> #include <raids/redis_msg.h> #include <raids/redis_exec.h> #include <raikv/work.h> #include <raikv/key_hash.h> #include <raimd/md_set.h> #include <raids/set_bits.h> static const char * set_status_string[] = { "ok", "not found", "full", "updated", "exists" }; using namespace rai; using namespace ds; using namespace md; static SetData * resize_set( SetData *curr, size_t add_len, bool is_copy = false ) { size_t count; size_t data_len; count = ( add_len >> 3 ) | 1; data_len = add_len + 1; if ( curr != NULL ) { data_len = add_len + curr->data_len(); data_len += data_len / 2 + 2; count = curr->count(); count += count / 2 + 2; } size_t asize = SetData::alloc_size( count, data_len ); printf( "asize %ld, count %ld, data_len %ld\n", asize, count, data_len ); void *m = malloc( sizeof( SetData ) + asize ); void *p = &((char *) m)[ sizeof( SetData ) ]; SetData *newbe = new ( m ) SetData( p, asize ); newbe->init( count, data_len ); if ( curr != NULL ) { int x, y; printf( "verify curr: %d\n", x = curr->sverify() ); curr->copy( *newbe ); printf( "verify newbe: %d\n", y = newbe->sverify() ); if ( x != 0 || y != 0 ) { printf( "curr: " ); curr->lprint(); printf( "newbe: " ); newbe->lprint(); } if ( ! is_copy ) delete curr; } printf( "%.2f%% data %.2f%% hash\n", ( newbe->data_len() + add_len ) * 100.0 / newbe->data_size(), ( newbe->count() + 1 ) * 100.0 / newbe->max_count() ); return newbe; } struct SetKey { void * operator new( size_t, void *ptr ) { return ptr; } void operator delete( void *ptr ) { ::free( ptr ); } SetKey * next; SetData * set; uint32_t hash; SetKey() : next( 0 ), set( 0 ), hash( 0 ) {} ~SetKey() { if ( this->set != NULL ) delete this->set; } SetKey *copy( void ) { void *p = ::malloc( sizeof( SetKey ) ); if ( p == NULL ) return NULL; SetKey *sk = new ( p ) SetKey(); sk->hash = this->hash; sk->set = resize_set( this->set, 0, true ); sk->next = NULL; return sk; } }; struct SetDB { SetKey *list; SetKey *fetch( const char *k, size_t klen ) { SetKey *sk = this->list; uint32_t h = kv_crc_c( k, klen, 0 ); for ( ; sk != NULL; sk = sk->next ) { if ( sk->hash == h ) return sk; } void *p = ::malloc( sizeof( SetKey ) ); if ( p == NULL ) return NULL; sk = new ( p ) SetKey(); sk->hash = h; sk->set = resize_set( NULL, 16 ); sk->next = this->list; this->list = sk; return sk; } void save( const char *k, size_t klen, SetKey *sk ) { sk->hash = kv_crc_c( k, klen, 0 ); sk->next = this->list; this->list = sk; for ( SetKey *p = sk; p->next != NULL; p = p->next ) { if ( p->next->hash == sk->hash ) { SetKey *q = p->next; p->next = q->next; delete q; break; } } } } setdb; int main( int, char ** ) { SetKey *sk, *sk2; char buf[ 1024 ], buf2[ 1024 ], key[ 1024 ]; RedisMsg msg; kv::WorkAllocT< 4096 > tmp; size_t sz, i, j, count, namelen, keylen; size_t cmdlen, arglen, argcount; const char *cmdbuf, *arg, *name; ListVal lv; HashPos pos; kv::rand::xoroshiro128plus rand; int64_t ival; SetBits bits; RedisMsgStatus mstatus; RedisCmd cmd; SetStatus sstat; uint64_t t = kv::current_monotonic_time_ns(); printf( "%lx\n", t ); rand.init( &t, 8 ); printf( "> " ); fflush( stdout ); for (;;) { if ( fgets( buf, sizeof( buf ), stdin ) == NULL ) break; if ( buf[ 0 ] == '#' || buf[ 0 ] == '\n' ) continue; tmp.reset(); cmdlen = ::strlen( buf ); if ( buf[ 0 ] == '[' ) mstatus = msg.unpack_json( buf, cmdlen, tmp ); else mstatus = msg.unpack( buf, cmdlen, tmp ); if ( mstatus != DS_MSG_STATUS_OK ) { printf( "error %d/%s\n", mstatus, ds_msg_status_string( mstatus ) ); continue; } cmdbuf = msg.command( cmdlen, argcount ); if ( cmdlen >= 32 ) { printf( "cmd to large\n" ); continue; } if ( cmdlen == 0 ) continue; cmd = get_redis_cmd( get_redis_cmd_hash( cmdbuf, cmdlen ) ); if ( cmd == NO_CMD ) { printf( "no cmd\n" ); continue; } sz = msg.to_almost_json( buf2 ); printf( "\nexec %.*s\n", (int) sz, buf2 ); if ( cmd == SDIFFSTORE_CMD || cmd == SINTERSTORE_CMD || cmd == SUNIONSTORE_CMD ) { if ( ! msg.get_arg( 2, name, namelen ) ) goto bad_args; } else { if ( ! msg.get_arg( 1, name, namelen ) ) goto bad_args; } sk = setdb.fetch( name, namelen ); if ( sk == NULL ) { printf( "out of memory\n" ); return 1; } switch ( cmd ) { case SADD_CMD: /* SADD key mem [mem ...] */ for ( i = 2; i < argcount; i++ ) { if ( ! msg.get_arg( i, arg, arglen ) ) goto bad_args; pos.init( arg, arglen ); for (;;) { sstat = sk->set->sadd( arg, arglen, pos ); printf( "%s\n", set_status_string[ sstat ] ); if ( sstat != SET_FULL ) break; sk->set = resize_set( sk->set, arglen ); } } break; case SCARD_CMD: /* SCARD key */ count = sk->set->count(); if ( count > 0 ) count -= 1; printf( "%ld\n", count ); break; case SISMEMBER_CMD: /* SISMEMBER key mem */ if ( ! msg.get_arg( 2, arg, arglen ) ) goto bad_args; pos.init( arg, arglen ); sstat = sk->set->sismember( arg, arglen, pos ); printf( "%s\n", sstat == SET_OK ? "true" : "false" ); break; case SDIFFSTORE_CMD: /* SDIFFSTORE dest key [key ...] */ case SINTERSTORE_CMD: /* SINTERSTORE dest key [key ...] */ case SUNIONSTORE_CMD: /* SUNIONSTORE dest key [key ...] */ i = 3; if ( 0 ) { case SDIFF_CMD: /* SDIFF key [key ...] */ case SINTER_CMD: /* SINTER key [key ...] */ case SUNION_CMD: /* SUNION key [key ...] */ i = 2; } sk = sk->copy(); if ( sk == NULL ) { printf( "out of memory\n" ); return 1; } for ( ; i < argcount; i++ ) { MergeCtx ctx; if ( ! msg.get_arg( i, name, namelen ) ) goto bad_args; sk2 = setdb.fetch( name, namelen ); ctx.init(); for (;;) { if ( cmd == SUNION_CMD || cmd == SUNIONSTORE_CMD ) sstat = sk->set->sunion( *sk2->set, ctx ); else if ( cmd == SINTER_CMD || cmd == SINTERSTORE_CMD ) sstat = sk->set->sinter( *sk2->set, ctx ); else if ( cmd == SDIFF_CMD || cmd == SDIFFSTORE_CMD ) sstat = sk->set->sdiff( *sk2->set, ctx ); else sstat = SET_OK; printf( "%s\n", set_status_string[ sstat ] ); if ( sstat != SET_FULL ) break; sk->set = resize_set( sk->set, sk2->set->data_len() ); } } /* FALLTHRU */ case SMEMBERS_CMD: /* SMEMBERS key */ count = sk->set->count(); for ( i = 1; i < count; i++ ) { sstat = (SetStatus) sk->set->lindex( i, lv ); if ( sstat == SET_OK ) { printf( "%ld. off(%ld) ", i, sk->set->offset( i ) ); printf( "%.*s", (int) lv.sz, (const char *) lv.data ); if ( lv.sz2 > 0 ) printf( "%.*s", (int) lv.sz2, (const char *) lv.data2 ); printf( "\n" ); } } printf( "count %lu of %lu\n", count > 0 ? (size_t) count - 1 : 0, sk->set->max_count() - 1 ); printf( "bytes %lu of %lu\n", (size_t) sk->set->data_len(), sk->set->data_size() ); printf( "[" ); sk->set->print_hashes(); printf( "]\n" ); for ( i = 1; i < count; i++ ) { sstat = (SetStatus) sk->set->lindex( i, lv ); if ( sstat == SET_OK ) { keylen = kv::min<size_t>( lv.sz, sizeof( key ) ); ::memcpy( key, lv.data, keylen ); sz = kv::min<size_t>( sizeof( key ) - keylen, lv.sz2 ); ::memcpy( &key[ keylen ], lv.data2, sz ); keylen += sz; pos.init( key, keylen ); sstat = sk->set->sismember( key, keylen, pos ); if ( sstat == SET_OK ) printf( "%ld. idx(%ld) h(%u) %.*s\n", i, pos.i, (uint8_t) pos.h, (int) keylen, key ); else printf( "%ld. idx(****) h(%u) %.*s\n", i, (uint8_t) pos.h, (int) keylen, key ); } else { printf( "%ld. status=%d\n", i, (int) sstat ); } } if ( cmd != SMEMBERS_CMD ) { if ( cmd == SDIFFSTORE_CMD || cmd == SINTERSTORE_CMD || cmd == SUNIONSTORE_CMD ) { if ( ! msg.get_arg( 1, name, namelen ) ) goto bad_args; setdb.save( name, namelen, sk ); } else { delete sk; } } break; case SMOVE_CMD: /* SMOVE src dest mem */ if ( ! msg.get_arg( 2, name, namelen ) ) goto bad_args; sk2 = setdb.fetch( name, namelen ); if ( ! msg.get_arg( 3, arg, arglen ) ) goto bad_args; pos.init( arg, arglen ); sstat = sk->set->srem( arg, arglen, pos ); if ( sstat == SET_OK ) { for (;;) { sstat = sk2->set->sadd( arg, arglen, pos ); printf( "%s\n", set_status_string[ sstat ] ); if ( sstat != SET_FULL ) break; sk2->set = resize_set( sk2->set, arglen ); } printf( "1\n" ); } else { printf( "0\n" ); } break; case SPOP_CMD: /* SPOP key [count] */ case SRANDMEMBER_CMD: /* SRANDMEMBER key [count] */ ival = 1; if ( argcount > 2 ) { if ( ! msg.get_arg( 2, ival ) ) goto bad_args; } count = sk->set->count(); bits.reset(); if ( count <= 1 ) sstat = SET_NOT_FOUND; else { bool flip = false; count -= 1; if ( count < (size_t) ival ) ival = count; if ( (size_t) ival > count / 2 ) { flip = true; ival = count - ival; } if ( ival > 0 ) { for (;;) { size_t n = rand.next(); for ( int i = 0; i < 64; i += 16 ) { size_t m = n & sk->set->index_mask; while ( m >= count ) m >>= 1; if ( ! bits.test_set( m ) ) if ( --ival == 0 ) goto break_loop; n >>= 16; } } } break_loop:; sstat = SET_OK; if ( flip ) { printf( "flip\n" ); bits.flip( count ); } } printf( "forward\n" ); for ( i = 0; sstat == SET_OK; ) { if ( ! bits.next( i ) ) break; i += 1; sstat = (SetStatus) sk->set->lindex( i, lv ); if ( sstat == SET_OK ) { printf( "%ld. off(%ld) ", i, sk->set->offset( i ) ); printf( "%.*s", (int) lv.sz, (const char *) lv.data ); if ( lv.sz2 > 0 ) printf( "%.*s", (int) lv.sz2, (const char *) lv.data2 ); printf( "\n" ); } else { printf( "%ld. %s\n", i, set_status_string[ sstat ] ); } } printf( "backward\n" ); for ( j = count; sstat == SET_OK; ) { if ( ! bits.prev( j ) ) break; i = j + 1; sstat = (SetStatus) sk->set->lindex( i, lv ); if ( sstat == SET_OK ) { printf( "%ld. off(%ld) ", i, sk->set->offset( i ) ); printf( "%.*s", (int) lv.sz, (const char *) lv.data ); if ( lv.sz2 > 0 ) printf( "%.*s", (int) lv.sz2, (const char *) lv.data2 ); printf( "\n" ); } else { printf( "%ld. %s\n", i, set_status_string[ sstat ] ); } } if ( sstat == SET_OK && cmd == SPOP_CMD ) { for ( j = count; sstat == SET_OK; ) { if ( ! bits.prev( j ) ) break; i = j + 1; sstat = sk->set->spopn( i ); } } break; case SREM_CMD: /* SREM key mem [mem ...] */ sz = 0; for ( i = 2; i < argcount; i++ ) { if ( ! msg.get_arg( i, arg, arglen ) ) goto bad_args; pos.init( arg, arglen ); sstat = sk->set->srem( arg, arglen, pos ); if ( sstat == SET_OK ) sz++; } printf( "%ld\n", sz ); break; case SSCAN_CMD: /* SSCAN key curs [match pat] [count cnt] */ break; default: printf( "bad cmd\n" ); if ( 0 ) { bad_args:; printf( "bad args\n" ); } break; } printf( "> " ); fflush( stdout ); } return 0; }
31.138498
78
0.453675
raitechnology
bf89befe1e73dfacdfc45fa9caac351aca29b8cb
22,099
cpp
C++
Samples/Common/CropResize/CropResize.cpp
huaweiatlasTest/samples
5d1fcd6dc1b25bca3bf0a82f3e40d95d03f6995b
[ "BSD-3-Clause" ]
23
2019-07-29T02:15:20.000Z
2020-01-09T02:20:32.000Z
Samples/Common/CropResize/CropResize.cpp
huaweiatlasTest/samples
5d1fcd6dc1b25bca3bf0a82f3e40d95d03f6995b
[ "BSD-3-Clause" ]
4
2019-09-26T07:50:26.000Z
2019-11-29T06:01:29.000Z
Samples/Common/CropResize/CropResize.cpp
huaweiatlasTest/samples
5d1fcd6dc1b25bca3bf0a82f3e40d95d03f6995b
[ "BSD-3-Clause" ]
14
2019-08-14T07:54:55.000Z
2020-01-14T08:09:21.000Z
/** * ============================================================================ * * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. * Description: Atlas Sample * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1 Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2 Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3 Neither the names of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ============================================================================ */ #include "CropResize.h" /* 0:do not change format, 1:change format(RGBA->RGB) */ const int TRANSFORM_NOT_CHANGE = 0; const int TRANSFORM_CHANGE = 1; /** * @brief DecodeJpeg * @param [in] : fileSize, the size of buff size * @param [in] : dataBuff, the jpeg data buffer * @param [out] : decodeOutputImage, the decode output * @return : HIAI_StatusT, HIAI_OK: success */ HIAI_StatusT CropResize::DecodeJpeg(const uint32_t fileSize, const std::shared_ptr<uint8_t> dataBuff, std::shared_ptr<DecodeOutputImage> decodeOutputImage) { if ((dataBuff == nullptr) || (decodeOutputImage == nullptr)) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "Input Parameter should not be NULL.\n"); return HIAI_ERROR; } HIAI_ENGINE_LOG(HIAI_IDE_INFO, "DecodeJpeg process start !"); jpegdInData.jpegDataSize = fileSize; jpegdInData.jpegData = (unsigned char *)(dataBuff.get()); // JpegdOut jpegdOutData; dvppapiCtlMsg.in = (void *)&jpegdInData; dvppapiCtlMsg.in_size = sizeof(jpegdInData); dvppapiCtlMsg.out = (void *)&jpegdOutData; dvppapiCtlMsg.out_size = sizeof(jpegdOutData); // create api int ret = CreateDvppApi(pidvppapi); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "create dvpp api fail.!\n"); return ret; } // decode jpeg ret = DvppCtl(pidvppapi, DVPP_CTL_JPEGD_PROC, &dvppapiCtlMsg); if (ret != 0) { DestroyDvppApi(pidvppapi); HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "dvpp process error.\n"); return HIAI_ERROR; } else { DestroyDvppApi(pidvppapi); HIAI_ENGINE_LOG(HIAI_IDE_INFO, "dvpp process success.\n"); } decodeOutputImage->imgWidth = jpegdOutData.imgWidth; decodeOutputImage->imgHeight = jpegdOutData.imgHeight; decodeOutputImage->imgWidthAligned = jpegdOutData.imgWidthAligned; decodeOutputImage->imgHeightAligned = jpegdOutData.imgHeightAligned; decodeOutputImage->inBuffer = jpegdOutData.yuvData; decodeOutputImage->inBufferSize = jpegdOutData.yuvDataSize; HIAI_ENGINE_LOG(HIAI_IDE_INFO, "DecodeJpeg process end !"); return HIAI_OK; } /** * @brief Decode Png image * @param [in] : fileSize, the size of buff size * @param [in] : dataBuff, the png data buffer * @param [out] : decodeOutputImage, the decode output * @return : HIAI_StatusT, HIAI_OK: success */ HIAI_StatusT CropResize::DecodePng(const uint32_t fileSize, const std::shared_ptr<uint8_t> dataBuff, std::shared_ptr<DecodeOutputImage> decodeOutputImage) { inputPngData.inputData = (unsigned char *)(dataBuff.get()); inputPngData.inputSize = fileSize; //0:do not change format, 1:change format inputPngData.transformFlag = TRANSFORM_CHANGE; dvppapiCtlMsg.in = (void*)&inputPngData; dvppapiCtlMsg.in_size = sizeof(inputPngData); dvppapiCtlMsg.out = (void*)&outputPngData; dvppapiCtlMsg.out_size = sizeof(outputPngData); int ret = DvppGetOutParameter((void*)(&inputPngData), (void*)(&outputPngData), GET_PNGD_OUT_PARAMETER); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "call DvppGetOutParameter process failed"); return HIAI_ERROR; } outputPngData.address = HIAI_DVPP_DMalloc(outputPngData.size); if (outputPngData.address == nullptr) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "can not alloc output buffer"); return HIAI_ERROR; } ret = CreateDvppApi(pidvppapi); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "create dvpp api fail.\n"); return HIAI_ERROR; } ret = DvppCtl(pidvppapi, DVPP_CTL_PNGD_PROC, &dvppapiCtlMsg); if (ret != 0) { DestroyDvppApi(pidvppapi); HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "dvpp process error\n"); return HIAI_ERROR; } else { DestroyDvppApi(pidvppapi); HIAI_ENGINE_LOG(HIAI_IDE_INFO, "dvpp process success\n"); } decodeOutputImage->imgWidth = (uint32_t)outputPngData.width; decodeOutputImage->imgHeight = (uint32_t)outputPngData.high; decodeOutputImage->imgWidthAligned = outputPngData.widthAlign; decodeOutputImage->imgHeightAligned = outputPngData.highAlign; decodeOutputImage->inBuffer = (uint8_t*)outputPngData.address; decodeOutputImage->inBufferSize = outputPngData.outputSize; HIAI_ENGINE_LOG(HIAI_IDE_INFO, "Decode png end.\n"); return HIAI_OK; } /* construct image configure. */ void CropResize::ConstructImageConfigure(const std::shared_ptr<DecodeOutputImage> decodeOutputImage, std::shared_ptr<VpcUserImageConfigure> imageConfigure, const enum VpcInputFormat inputFormat, const enum VpcOutputFormat outputFormat) { imageConfigure->bareDataAddr = decodeOutputImage->inBuffer; imageConfigure->bareDataBufferSize = decodeOutputImage->inBufferSize; imageConfigure->isCompressData = false; imageConfigure->widthStride = decodeOutputImage->imgWidthAligned; imageConfigure->heightStride = decodeOutputImage->imgHeightAligned; imageConfigure->inputFormat = inputFormat; imageConfigure->outputFormat = outputFormat; imageConfigure->yuvSumEnable = false; imageConfigure->cmdListBufferAddr = nullptr; imageConfigure->cmdListBufferSize = 0; } /* construct roi input configure. */ void CropResize::ConstructRoiInputConfigure(CropArea cropArea, VpcUserRoiInputConfigure *&inputConfigure) { inputConfigure->cropArea.leftOffset = cropArea.cropLeftOffset; inputConfigure->cropArea.rightOffset = cropArea.cropRightOffset; inputConfigure->cropArea.upOffset = cropArea.cropUpOffset; inputConfigure->cropArea.downOffset = cropArea.cropDownOffset; } /* construct roi output configure. */ void CropResize::ConstructRoiOutputConfigure(const std::shared_ptr<DecodeOutputImage> decodeOutputImage, VpcUserRoiOutputConfigure *&outputConfigure, const CropResizePara cropResizePara, uint8_t *outBuffer, const uint32_t outBufferSize) { uint32_t outWidth = (uint32_t)decodeOutputImage->imgWidth * cropResizePara.resizeFactorW; uint32_t outHeight = (uint32_t)decodeOutputImage->imgHeight * cropResizePara.resizeFactorH; uint32_t outWidthAligned = ALIGN_UP(outWidth, WIDTH_ALIGNED); uint32_t outHeightAligned = ALIGN_UP(outHeight, HEIGHT_ALIGNED); outputConfigure->widthStride = outWidthAligned; outputConfigure->heightStride = outHeightAligned; outputConfigure->addr = outBuffer; outputConfigure->bufferSize = outBufferSize; outputConfigure->outputArea.leftOffset = cropResizePara.cropAreaArray[0].outputLeftOffset; outputConfigure->outputArea.rightOffset = cropResizePara.cropAreaArray[0].outputRightOffset; outputConfigure->outputArea.upOffset = cropResizePara.cropAreaArray[0].outputUpOffset; outputConfigure->outputArea.downOffset = cropResizePara.cropAreaArray[0].outputDownOffset; } /* construct roi output configure. */ void CropResize::ConstructRoiOutputConfigure(const std::shared_ptr<DecodeOutputImage> decodeOutputImage, VpcUserRoiOutputConfigure *&outputConfigure, const CropResizePara cropResizePara, std::shared_ptr<CropResizeOutputImage> cropResizeOutputImage) { uint32_t outWidth = (uint32_t)decodeOutputImage->imgWidth * cropResizePara.resizeFactorW; uint32_t outHeight = (uint32_t)decodeOutputImage->imgHeight * cropResizePara.resizeFactorH; uint32_t outWidthAligned = ALIGN_UP(outWidth, WIDTH_ALIGNED); uint32_t outHeightAligned = ALIGN_UP(outHeight, HEIGHT_ALIGNED); outputConfigure->widthStride = outWidthAligned; outputConfigure->heightStride = outHeightAligned; outputConfigure->addr = cropResizeOutputImage->outBuffer; outputConfigure->bufferSize = cropResizeOutputImage->outBufferSize; outputConfigure->outputArea.leftOffset = cropResizePara.cropAreaArray[0].outputLeftOffset; outputConfigure->outputArea.rightOffset = cropResizePara.cropAreaArray[0].outputRightOffset; outputConfigure->outputArea.upOffset = cropResizePara.cropAreaArray[0].outputUpOffset; outputConfigure->outputArea.downOffset = cropResizePara.cropAreaArray[0].outputDownOffset; cropResizeOutputImage->imgWidth = outWidth; cropResizeOutputImage->imgHeight = outHeight; cropResizeOutputImage->imgWidthAligned = outWidthAligned; cropResizeOutputImage->imgHeightAligned = outHeightAligned; } /** * @brief crop or resize image * @param [in] : decodeOutputImage, the decode output, the crop or resize input * @param [in] : cropResizePara, the param of crop or resize * @param [in] : outBufferSize, output buffer size * @param [out] : outBuffer, output buffer * @return : HIAI_StatusT, HIAI_OK: success */ HIAI_StatusT CropResize::CropResizeImage(const std::shared_ptr<DecodeOutputImage> decodeOutputImage, const CropResizePara cropResizePara, uint8_t *outBuffer, const uint32_t outBufferSize) { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "CropResize process start !"); ConstructImageConfigure(decodeOutputImage, imageConfigure, cropResizePara.inputFormat, cropResizePara.outputFormat); std::shared_ptr<VpcUserRoiConfigure> lastRoi; // record the last roi configuration for (int i = 0; i < cropResizePara.cropAreaArray.size(); i++) { std::shared_ptr<VpcUserRoiConfigure> roiConfigure(new VpcUserRoiConfigure); roiConfigure->next = nullptr; VpcUserRoiInputConfigure *inputConfigure = &roiConfigure->inputConfigure; ConstructRoiInputConfigure(cropResizePara.cropAreaArray[i], inputConfigure); // set roi configuration VpcUserRoiOutputConfigure *outputConfigure = &roiConfigure->outputConfigure; CropResizePara outputCropResizePara; outputCropResizePara.cropAreaArray.push_back(cropResizePara.cropAreaArray[i]); outputCropResizePara.resizeFactorW = cropResizePara.resizeFactorW; outputCropResizePara.resizeFactorH = cropResizePara.resizeFactorH; outputCropResizePara.outputFormat = cropResizePara.outputFormat; outputCropResizePara.inputFormat = INPUT_YUV400; //not use, init 0 ConstructRoiOutputConfigure(decodeOutputImage, outputConfigure, outputCropResizePara, outBuffer, outBufferSize); imageConfigure->roiConfigure = roiConfigure.get(); // if it is the first one, set it to imageConfigure if (i == 0) { imageConfigure->roiConfigure = roiConfigure.get(); lastRoi = roiConfigure; } else { lastRoi->next = roiConfigure.get(); lastRoi = roiConfigure; } IDVPPAPI *pidvppapi = nullptr; int ret = CreateDvppApi(pidvppapi); if (ret != 0) { while (imageConfigure->roiConfigure != nullptr) { imageConfigure->roiConfigure = imageConfigure->roiConfigure->next; } return HIAI_ERROR; } // control msg dvppapi_ctl_msg dvppApiCtlMsg; dvppApiCtlMsg.in = static_cast<void *>(imageConfigure.get()); dvppApiCtlMsg.in_size = sizeof(VpcUserImageConfigure); // resize the yuv ret = DvppCtl(pidvppapi, DVPP_CTL_VPC_PROC, &dvppApiCtlMsg); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "call vpc dvppctl process faild!\n"); ret = DestroyDvppApi(pidvppapi); return HIAI_ERROR; } else { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "call vpc dvppctl process success!\n"); } } return HIAI_OK; } /** * @brief crop or resize image * @param [in] : decodeOutputImage, the decode output, the crop or resize input * @param [in] : cropResizePara, the param of crop or resize * @param [in] : outBufferSize, output buffer size * @param [out] : outBuffer, output buffer * @return : HIAI_StatusT, HIAI_OK: success */ HIAI_StatusT CropResize::CropResizeImage(const std::shared_ptr<DecodeOutputImage> decodeOutputImage, const CropResizePara cropResizePara, std::shared_ptr<CropResizeOutputImage> cropResizeOutputImage) { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "CropResize process start !"); ConstructImageConfigure(decodeOutputImage, imageConfigure, cropResizePara.inputFormat, cropResizePara.outputFormat); std::shared_ptr<VpcUserRoiConfigure> lastRoi; // record the last roi configuration for (int i = 0; i < cropResizePara.cropAreaArray.size(); i++) { std::shared_ptr<VpcUserRoiConfigure> roiConfigure(new VpcUserRoiConfigure); roiConfigure->next = nullptr; VpcUserRoiInputConfigure *inputConfigure = &roiConfigure->inputConfigure; ConstructRoiInputConfigure(cropResizePara.cropAreaArray[i], inputConfigure); // set roi configuration VpcUserRoiOutputConfigure *outputConfigure = &roiConfigure->outputConfigure; CropResizePara outputCropResizePara; outputCropResizePara.cropAreaArray.push_back(cropResizePara.cropAreaArray[i]); outputCropResizePara.resizeFactorW = cropResizePara.resizeFactorW; outputCropResizePara.resizeFactorH = cropResizePara.resizeFactorH; outputCropResizePara.outputFormat = cropResizePara.outputFormat; outputCropResizePara.inputFormat = INPUT_YUV400; //not use, init 0 ConstructRoiOutputConfigure(decodeOutputImage, outputConfigure, outputCropResizePara, cropResizeOutputImage); imageConfigure->roiConfigure = roiConfigure.get(); // if it is the first one, set it to imageConfigure if (i == 0) { imageConfigure->roiConfigure = roiConfigure.get(); lastRoi = roiConfigure; } else { lastRoi->next = roiConfigure.get(); lastRoi = roiConfigure; } IDVPPAPI *pidvppapi = nullptr; int ret = CreateDvppApi(pidvppapi); if (ret != 0) { while (imageConfigure->roiConfigure != nullptr) { imageConfigure->roiConfigure = imageConfigure->roiConfigure->next; } return HIAI_ERROR; } // control msg dvppapi_ctl_msg dvppApiCtlMsg; dvppApiCtlMsg.in = static_cast<void *>(imageConfigure.get()); dvppApiCtlMsg.in_size = sizeof(VpcUserImageConfigure); // resize the yuv ret = DvppCtl(pidvppapi, DVPP_CTL_VPC_PROC, &dvppApiCtlMsg); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "call vpc dvppctl process faild!\n"); ret = DestroyDvppApi(pidvppapi); return HIAI_ERROR; } else { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "call vpc dvppctl process success!\n"); } } return HIAI_OK; } /** * @brief get mul crop or resize area according to the specify rol number or col number. It is only used for testing * @param [in] : outWidth, the width of image * @param [in] : outHeight, the height of image * @return : vector<CropArea>, the array of crop resize. the size is equal to rolNum*colNum */ vector<CropArea> CropResize::GetMulCropArea(uint32_t outWidth, uint32_t outHeight, uint32_t rolNum, uint32_t colNum) { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "get MulCropArea process start !"); uint32_t outWidthAligned = ALIGN_UP(outWidth, WIDTH_ALIGNED); uint32_t outHeightAligned = ALIGN_UP(outHeight, HEIGHT_ALIGNED); vector<CropArea> cropAreaArray; if ((rolNum <= 0) || (colNum <= 0)) { return cropAreaArray; } // calculate the crop size // Leave 16 pixels on the right for 16 alignment uint32_t blockWidth = outWidthAligned / rolNum; uint32_t blockHeigth = outHeightAligned / colNum; // crop area para uint32_t cropWidth = (uint32_t)blockWidth * CROP_BLOCK_FACTOR; uint32_t cropHeigth = (uint32_t)blockHeigth * CROP_BLOCK_FACTOR; // there is a gap between crop areas, the width of gap is equal to a half of the difference value of // blockWidth and cropWidth, So as the height of it uint32_t widthStart = GAP_FACTOR * (blockWidth - cropWidth); uint32_t heigthStart = GAP_FACTOR * (blockHeigth - cropHeigth); for (int i = 0; i < rolNum; i++) { for (int j = 0; j < colNum; j++) { CropArea cropArea; cropArea.cropLeftOffset = ALIGN_UP(widthStart + i * blockWidth, WIDTH_ALIGNED); cropArea.cropRightOffset = CHECK_ODD(cropArea.cropLeftOffset + cropWidth - 1); cropArea.cropUpOffset = CHECK_EVEN(heigthStart + j * blockHeigth); cropArea.cropDownOffset = CHECK_ODD(cropArea.cropUpOffset + cropHeigth - 1); cropArea.outputLeftOffset = ALIGN_UP(widthStart + i * blockWidth, WIDTH_ALIGNED); cropArea.outputRightOffset = CHECK_ODD(cropArea.outputLeftOffset + cropWidth - 1); cropArea.outputUpOffset = CHECK_EVEN(heigthStart + j * blockHeigth); cropArea.outputDownOffset = CHECK_ODD(cropArea.outputUpOffset + cropHeigth - 1); cropAreaArray.push_back(cropArea); } } HIAI_ENGINE_LOG(HIAI_IDE_INFO, "get multicropArea process end !"); return cropAreaArray; } /** * @brief get one crop or reszie area according to image width and image height. It is only used for testing * @param [in] : outWidth, the width of image * @param [in] : outHeight, the height of image * @return : vector<CropArea>, the array of crop resize. the size is equal to 1 */ vector<CropArea> CropResize::GetSingleArea(uint32_t outWidth, uint32_t outHeight) { uint32_t singleRow = 1; uint32_t singleCol = 1; return this->GetMulCropArea(outWidth, outHeight, singleRow, singleCol); } /** * @brief get one resize area according to image width and image height. It is only used for testing * @param [in] : outWidth, the width of image * @param [in] : outHeight, the height of image * @return : vector<CropArea>, the array of crop resize. the size is equal to 1 */ vector<CropArea> CropResize::GetResizeArea(uint32_t outWidth, uint32_t outHeight) { return this->GetSingleArea(outWidth, outHeight); } /** * @brief get one crop area according to image width and image height. It is only used for testing * @param [in] : outWidth, the width of image * @param [in] : outHeight, the height of image * @return : vector<CropArea>, the array of crop resize. the size is equal to 1 */ vector<CropArea> CropResize::GetCropArea(uint32_t outWidth, uint32_t outHeight) { return this->GetSingleArea(outWidth, outHeight); } /** * @brief calculate the buffer size of yuv output, according to resize scale * @param [in] : decodeOutputImage, the width of image * @param [in] : resizeFactorW, the resize scale of width * @param [in] : resizeFactorH, the resize scale of height * @return : uint32_t, the yuv buffer size */ uint32_t CropResize::GetYuvOutputBufferSize(const std::shared_ptr<DecodeOutputImage> decodeOutputImage, const float resizeFactorW, const float resizeFactorH) { uint32_t outWidth = (uint32_t)decodeOutputImage->imgWidth * resizeFactorW; uint32_t outHeight = (uint32_t)decodeOutputImage->imgHeight * resizeFactorH; uint32_t outWidthAligned = ALIGN_UP(outWidth, WIDTH_ALIGNED); uint32_t outHeightAligned = ALIGN_UP(outHeight, HEIGHT_ALIGNED); return outWidthAligned * outHeightAligned * YUV_FACTOR / YUV_DIVISOR; } void CropResize::CbFreeJpeg() { jpegdOutData.cbFree(); jpegdOutData.yuvData = nullptr; } void CropResize::CbFreePng() { HIAI_DVPP_DFree(outputPngData.address); outputPngData.address = nullptr; } CropResize::~CropResize() { }
46.232218
135
0.686547
huaweiatlasTest
bf8a4cd23f903f7c681349a6193653539c9d956c
575
cpp
C++
tests/numbers-set1-regressions.cpp
davidhofman/dg
cf304a691f7063f638bd4edb66f2d8e65ccad2ec
[ "MIT" ]
1
2020-01-24T20:08:33.000Z
2020-01-24T20:08:33.000Z
tests/numbers-set1-regressions.cpp
davidhofman/dg
cf304a691f7063f638bd4edb66f2d8e65ccad2ec
[ "MIT" ]
null
null
null
tests/numbers-set1-regressions.cpp
davidhofman/dg
cf304a691f7063f638bd4edb66f2d8e65ccad2ec
[ "MIT" ]
null
null
null
#include <fstream> #include <iterator> #include <string> #include <vector> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); void runOnInput(const std::string& file) { std::ifstream input(file, std::ios::binary); if (!input.is_open()) abort(); std::vector<unsigned char> data( (std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>()); input.close(); LLVMFuzzerTestOneInput(data.data(), data.size()); } int main(void) { runOnInput("regressions-bin/numbers-set-regression.bin"); }
22.115385
72
0.667826
davidhofman
bf907e9f5e5f84062729562f279fa88c83c05377
4,232
cpp
C++
src/game/game_state_phase1.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/game/game_state_phase1.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/game/game_state_phase1.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
namespace Phase1 { Logic::EntityID player_id; Physics::Body bordere_rect_container[4]; f32 progess; f32 saddness; f32 saddness_target; Vec4 START_COLOR = V4(0.1, 0.05, 0.05, 1.0); Vec4 END_COLOR = V4(0.3, 0.3, 0.3, 1.0); void setup(); void enter(); void update(f32 now, f32 delta); void draw(); void exit(); Mixer::AudioID tickID; void setup() {} Logic::LogicID leave_id; void enter() { current_exit(); Logic::update_callback(update_id, update, 0.0, Logic::FOREVER); Logic::update_callback(draw_id, draw, 0.0, Logic::FOREVER); current_exit = exit; enemy_spawner.set_phase(1); enemy_spawner.set_paused(false); cog_spawner.set_phase(11); cog_spawner.set_paused(false); cog_spawner.spawn_cog(V2(0.6, 0)); progess = 0; saddness_target = 1.0; saddness = saddness_target; auto leave = []() { if (progess >= 1.0) { LOG("cut"); Logic::update_callback(update_id, empty_func, 0.0, Logic::FOREVER); Logic::update_callback(draw_id, empty_func, 0.0, Logic::FOREVER); transitioning = true; Cutscene::enter(1); } }; leave_id = Logic::add_callback(Logic::POST_DRAW, leave, 0.0, Logic::FOREVER); PlayerPhase1 player; player.init(); player_id = Logic::add_entity(player); init_hit_particles(); tickID = Mixer::play_sound(2, ASSET_METRONOME_2, 1.0, Mixer::AUDIO_DEFAULT_GAIN, Mixer::AUDIO_DEFAULT_VARIANCE, Mixer::AUDIO_DEFAULT_VARIANCE, true); transitioning = false; } void update(f32 delta, f32 now) { if (transitioning) return; hitEnemy.update(delta); enemy_spawner.update(delta); cog_spawner.update(delta); PlayerPhase1 *player = (PlayerPhase1 *) Logic::fetch_entity(player_id); for (s32 i = cog_spawner.entities.size() - 1; i >= 0; i--) { GameEntity *cog = Logic::fetch_entity<GameEntity>(cog_spawner.entities[i]); if (Physics::check_overlap(&cog->body, &player->body)) { cog->hp = 0; pick_up_compliment(); // TODO: Fix this later progess = CLAMP(0, 1.0, progess + 0.2); saddness_target -= 0.2; } } for (s32 i = enemy_spawner.entities.size() - 1; i >= 0; i--) { GameEntity *enemy = Logic::fetch_entity<GameEntity>(enemy_spawner.entities[i]); Physics::Overlap overlap = Physics::check_overlap(&enemy->body, &player->body); if (overlap) { player->body.velocity += overlap.normal * 0.1; enemy->body.velocity -= overlap.normal * 0.1; hitEnemy.position = (player->body.position + enemy->body.position)/2; for (int i = 0; i < 300; i++) { hitEnemy.spawn(); } // TODO(ed): Which channel AssetID alts[] = { ASSET_SPACESUIT_HIT_1, ASSET_SPACESUIT_HIT_2, ASSET_SPACESUIT_HIT_3, ASSET_SPACESUIT_HIT_4, }; Mixer::play_sound(6, alts[random_int() % LEN(alts)]); saddness_target += 0.2; progess = CLAMP(0, 1.0, progess - 0.2); } } saddness_target = CLAMP(0, 1.0, saddness_target); Vec2 target = -player->body.position; Vec2 curr = Renderer::get_camera()->position; Renderer::get_camera()->position = LERP(curr, 2 * length(target - curr) * delta, target); } void draw() { if (transitioning) return; // Draw background Vec4 tint = LERP(START_COLOR, progess, END_COLOR); draw_sprite(0, -Renderer::get_camera(0)->position, 2, 0, Sprites::BACKGROUND, tint); saddness = LERP(saddness, Logic::delta() * 2, saddness_target); Renderer::vignette_strength = (saddness * saddness) * 4.5; Renderer::vignette_radius = (saddness * saddness) * 0.5; hitEnemy.draw(); stars.draw(); // Physics::Overlap curr_overlap = // Physics::check_overlap(&player1.player_body, &temp_rect); // Physics::solve(curr_overlap); // Physics::debug_draw_body(&temp_rect); } void exit() { Logic::remove_callback(leave_id); Logic::remove_entity(player_id); enemy_spawner.clear(); cog_spawner.clear(); Mixer::stop_sound(tickID); } }; // namespace Phase1
30.666667
153
0.615312
FredTheDino
bf95036bb06e29cfa2fd68d72ecebe00fe1ebe46
3,032
hpp
C++
include/rectojump/game/main_menu/background_main_menu.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/game/main_menu/background_main_menu.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/game/main_menu/background_main_menu.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
// // Copyright (c) 2013-2021 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #define RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/star5.hpp> #include <rectojump/game/components/triangles4.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <mlk/time/simple_timer.h> #include <mlk/tools/random_utl.h> namespace rj { template <typename Main_Menu> class background_main_menu { Main_Menu& m_mainmenu; background_manager<typename Main_Menu::gh_type>& m_backgroundmgr; const sf::Color m_fillcolor{settings::get_color_light()}; mlk::tm::simple_timer m_timer{300}; bool m_use_effects{settings::get_main_menu_effects()}; public: background_main_menu(Main_Menu& mm) : m_mainmenu{mm}, m_backgroundmgr{mm.gamehandler().backgroundmgr()} { this->init(); } void update(dur duration) { this->update_bg_objs(duration); } void update_bg_objs(dur duration) noexcept { if(!m_use_effects) return; if(m_timer.timed_out()) { auto size{settings::get_window_size<vec2f>()}; auto pos_x{mlk::rnd(0.f, size.x)}; auto length{mlk::rnd(30.f, 60.f)}; auto rotatestep{mlk::rnd(-0.1f, 0.5f)}; vec2f movestep{mlk::rnd(-0.3f, 0.5f), mlk::rnd(0.05f, 0.5f)}; auto object_type{mlk::rnd(0, 1)}; if(object_type) { auto ptr{ m_backgroundmgr.template create_object_for_state<star5>( state::main_menu, vec2f{pos_x, 0.f}, vec2f{0.f, length}, 5000, rotatestep, movestep)}; ptr->render_object().setFillColor( {m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); } else { auto ptr{m_backgroundmgr .template create_object_for_state<triangles4>( state::main_menu, vec2f{pos_x, 0.f}, vec2f{15.5f, 30.f}, 5000, rotatestep, movestep)}; ptr->render_object().setFillColor( {m_fillcolor.r, m_fillcolor.g, m_fillcolor.b, 100}); } m_timer.restart(static_cast<mlk::ullong>( mlk::rnd<mlk::ullong>(70, 100) / duration)); } } void render() {} private: void init() { auto window_size{settings::get_window_size<vec2f>()}; // nova if(m_use_effects) { auto nova{m_backgroundmgr .template create_object_for_state<triangles4>( state::main_menu, vec2f{window_size.x / 2.f, window_size.y / 2.f}, vec2f{window_size.y / 3.f, window_size.x}, 0, 0.1f, vec2f{0.f, 0.f})}; nova->render_object().setFillColor(to_rgb("#bdbdbd", 100)); } // timer m_timer.run(); // set the background m_backgroundmgr.set_bg_shape( state::main_menu, {settings::get_window_size<vec2f>(), to_rgb("#373737"), to_rgb("#373737")}); } }; } #endif// RJ_GAME_MAIN_MENU_BACKGROUND_MAIN_MENU_HPP
27.816514
70
0.681728
Malekblubb
bf98fc7753949724cf8bfd66501702e6b1e1e137
710
cpp
C++
OpenGL_Triangle/src/TextureLoader.cpp
HeyIAmDave/OpenGL-Moving-Triangle
b820bdacc7bc8ff2ce8f0398663753b9761c1f4b
[ "MIT", "BSD-3-Clause" ]
null
null
null
OpenGL_Triangle/src/TextureLoader.cpp
HeyIAmDave/OpenGL-Moving-Triangle
b820bdacc7bc8ff2ce8f0398663753b9761c1f4b
[ "MIT", "BSD-3-Clause" ]
null
null
null
OpenGL_Triangle/src/TextureLoader.cpp
HeyIAmDave/OpenGL-Moving-Triangle
b820bdacc7bc8ff2ce8f0398663753b9761c1f4b
[ "MIT", "BSD-3-Clause" ]
1
2021-09-12T16:18:47.000Z
2021-09-12T16:18:47.000Z
#include "TextureLoader.h" #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> TextureLoader::TextureLoader() { } Texture & TextureLoader::Load(const std::string & filePath) { if (m_textures.find(filePath) == m_textures.end()) { int w, h; unsigned char* data = stbi_load(("./data/" + filePath).c_str(), &w, &h, 0, 4); if (data == NULL) printf("Error: failed to load texture: %s\n", filePath.c_str()); std::shared_ptr<Texture> texture = std::make_shared<Texture>(); texture->Init(data, w, h); stbi_image_free(data); m_textures[filePath] = texture; } return *m_textures[filePath]; } void TextureLoader::CleanUp() { for (auto& texture : m_textures) texture.second->CleanUp(); }
21.515152
80
0.68169
HeyIAmDave
bcc62a9abe019a1a84db55076b145ba228cb17f3
36,947
cpp
C++
DecompressLogo/DecompressLogo.cpp
clandrew/nhl94e
65faad66965f65f0f3a5080f9a38f5458b978849
[ "MIT" ]
2
2021-11-10T15:36:56.000Z
2021-11-10T16:16:40.000Z
DecompressLogo/DecompressLogo.cpp
clandrew/nhl94e
65faad66965f65f0f3a5080f9a38f5458b978849
[ "MIT" ]
null
null
null
DecompressLogo/DecompressLogo.cpp
clandrew/nhl94e
65faad66965f65f0f3a5080f9a38f5458b978849
[ "MIT" ]
null
null
null
// DecompressLogo.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <iomanip> #include <vector> #include <assert.h> std::vector<unsigned char> romData; std::vector<unsigned char> out; // Bootstrap // 1. Break-on-write 7FA671 // 2. Step in to the first jump- 80BDE1 // Snapshot is at // $80/BDC5 7C C8 BD JMP ($BDC8,x)[$80:BDE1] A:CE14 X:0010 Y:00CE P:envmXdizc // Initial values unsigned char decompressedValueDictionary_7E0500[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x1F, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x20, 0x40, 0x40, 0x40, 0x40, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFE, 0xFE, 0xFE, 0xFE, 0x06, 0x06, 0x0C, 0x0C, 0x0F, 0x0F, 0x18, 0x18, 0x30, 0x30, 0x3F, 0x3F, 0x60, 0x60, 0x70, 0x70, 0x7F, 0x7F, 0xB2, 0xB2, 0xF8, 0xF8, 0xFC, 0xFC, 0x05, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x11, 0x14, 0x1C, 0x1E, 0x21, 0x24, 0x28, 0x2F, 0x38, 0x3C, 0x78, 0x7E, 0x8F, 0x90, 0x9F, 0xA0, 0xB0, 0xBF, 0xDF, 0xEF, 0xF7, 0xF9, 0xFB, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x12, 0x12, 0x0C, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10 }; unsigned char array_7E0600[] = { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x12, 0x12, 0x0C, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x0D, 0x00, 0x0C, 0x00, 0x1E, 0x00 }; struct Regs { unsigned short A; unsigned short X; unsigned short Y; } regs; struct Wram { std::vector<unsigned char> Data; Wram() { unsigned char dataAt_7FA671_Write[] = { 0xCA, 0xFD, 0x0A, 0x00, 0x3B, 0x00, 0xCA, 0x8E, 0x00, 0x01, 0x10, 0x00, 0x9B, 0xCD, 0x81, 0x00, 0x00, 0x78, 0x7F, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x9E, 0x00, 0xCA, 0x00, 0x9E, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD2, 0x00, 0x00, 0x00, 0x03, 0x00, 0xF0, 0xFF, 0x00, 0x01, 0xF0, 0xFF, 0xE0, 0x00, 0xC9, 0xB4, 0x9B, 0x00, 0x00, 0x00, 0x40, 0x01, 0x40, 0x01, 0xD3, 0x16, 0x00, 0x00, 0xEC, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x4F, 0xC2, 0x89, 0xBC, 0x9B, 0x00, 0x10, 0x00, 0x24, 0x00, 0x50, 0xC2, 0x90, 0x00, 0x61, 0x00, 0x00, 0x00, 0x61, 0x00, 0xDF, 0x09, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x14, 0xCE, 0x00, 0x0D, 0x00, 0x08, 0x00, 0xB2, 0x07, 0x00, 0x10, 0xFF, 0x00, 0x0B, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x06, 0x00, 0x00, 0x00, 0x00, 0xBC, 0x34, 0x7E, 0x00, 0xD8, 0xE4, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6A, 0x00, 0x20, 0x00, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x3D, 0x03, 0x00, 0x00, 0x5D, 0x01, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x7C, 0xEE, 0x9A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x90, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x80, 0x02, 0x03, 0x04, 0x07, 0x08, 0x10, 0x1F, 0x20, 0x40, 0xC0, 0xE0, 0xF0, 0xFE, 0x06, 0x0C, 0x0F, 0x18, 0x30, 0x3F, 0x60, 0x70, 0x7F, 0xB2, 0xF8, 0xFC, 0x05, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x11, 0x14, 0x1C, 0x1E, 0x21, 0x24, 0x28, 0x2F, 0x38, 0x3C, 0x78, 0x7E, 0x8F, 0x90, 0x9F, 0xA0, 0xB0, 0xBF, 0xDF, 0xEF, 0xF7, 0xF9, 0xFB, 0xFD, 0x12, 0x13, 0x15, 0x16, 0x17, 0x19, 0x1A, 0x1B, 0x1D, 0x22, 0x23, 0x25, 0x26, 0x2C, 0x31, 0x37, 0x3E, 0x41, 0x42, 0x43, 0x44, 0x47, 0x48, 0x4F, 0x50, 0x5F, 0x61, 0x6F, 0x7C, 0x81, 0x82, 0x83, 0x84, 0x86, 0x87, 0x88, 0x8C, 0x98, 0xAF, 0xB8, 0xC1, 0xC2, 0xC4, 0xC8, 0xCF, 0xD0, 0xD8, 0xE2, 0xE3, 0xE7, 0xE8, 0xF1, 0xF2, 0xF3, 0xF4, 0xF6, 0xFA, 0x27, 0x29, 0x2A, 0x2B, 0x2D, 0x2E, 0x33, 0x34, 0x35, 0x36, 0x39, 0x3B, 0x3D, 0x46, 0x4C, 0x4E, 0x58, 0x5C, 0x5E, 0x62, 0x63, 0x64, 0x66, 0x67, 0x68, 0x6A, 0x6C, 0x6E, 0x72, 0x73, 0x74, 0x76, 0x77, 0x79, 0x7B, 0x7D, 0x89, 0x8D, 0x8E, 0x91, 0x92, 0x9C, 0x9E, 0xA1, 0xA4, 0xAA, 0xB6, 0xB7, 0xBC, 0xBE, 0xC3, 0xC6, 0xC7, 0xCC, 0xD3, 0xD5, 0xD7, 0xDB, 0xDC, 0xDE, 0xE1, 0xE4, 0xE6, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xF5, 0x32, 0x3A, 0x45, 0x49, 0x4B, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x59, 0x5A, 0x5B, 0x65, 0x6B, 0x6D, 0x71, 0x75, 0x7A, 0x85, 0x8A, 0x8B, 0x93, 0x94, 0x95, 0x97, 0x99, 0x9A, 0x9B, 0x9D, 0xA3, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAB, 0xAC, 0xAE, 0xB1, 0xB3, 0xB4, 0xB9, 0xBA, 0xBB, 0xBD, 0xC5, 0xC9, 0xCB, 0xCD, 0xCE, 0xD1, 0xD4, 0xD6, 0xD9, 0xDA, 0xDD, 0xE5, 0xE9, 0x4A, 0x4D, 0x5D, 0x69, 0x96, 0xA2, 0xAD, 0xB5, 0xCA, 0xD2, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0x80, 0x06, 0x00, 0x00, 0x01, 0x0C, 0xC8, 0x8E, 0x40, 0x00, 0x00, 0x7A, 0x01, 0x38, 0xC9, 0x8E, 0x40, 0x00, 0x20, 0x7A, 0x01, 0x14, 0xCF, 0x8E, 0x40, 0x00, 0x40, 0x7A, 0x01, 0x64, 0xCA, 0x8E, 0x40, 0x00, 0x00, 0x7B, 0xFB, 0x06, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x1E, 0xFB, 0x10, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x1E, 0xFB, 0x1A, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x1F, 0xFB, 0x24, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x1F, 0xFB, 0x2E, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x20, 0xFB, 0x38, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x20, 0xFB, 0x42, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x21, 0xFB, 0x4C, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x21, 0xFB, 0x56, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x22, 0xFB, 0x60, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x22, 0xFB, 0x6A, 0x00, 0x7F, 0x0A, 0x00, 0x3C, 0x23, 0xFB, 0x74, 0x00, 0x7F, 0x0A, 0x00, 0xBC, 0x23, 0x01, 0x43, 0x68, 0x7F, 0x80, 0x01, 0x20, 0x62, 0x01, 0xC3, 0x69, 0x7F, 0x40, 0x01, 0x20, 0x63, 0xFA, 0x00, 0x00, 0x7F, 0x00, 0x10, 0x00, 0x20, 0xFA, 0x00, 0x10, 0x7F, 0xC0, 0x02, 0x00, 0x30, 0xFB, 0x06, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1E, 0xFB, 0x12, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1E, 0xFB, 0x1E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1F, 0xFB, 0x2A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1F, 0xFB, 0x36, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x20, 0xFB, 0x42, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x20, 0xFB, 0x4E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x21, 0xFB, 0x5A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x21, 0xFB, 0x66, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x22, 0xFB, 0x72, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x22, 0xFB, 0x7E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x23, 0xFB, 0x8A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x23, 0xFB, 0x06, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x1F, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0xC0, 0x04, 0x00, 0x00, 0x01, 0xC8, 0x6B, 0x7F, 0x20, 0x09, 0x00, 0x64, 0x01, 0xE8, 0x74, 0x7F, 0x00, 0x01, 0x00, 0x69, 0xFB, 0x06, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1E, 0xFB, 0x12, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1E, 0xFB, 0x1E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1F, 0xFB, 0x2A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1F, 0xFB, 0x36, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x20, 0xFB, 0x42, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x20, 0xFB, 0x4E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x21, 0xFB, 0x5A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x21, 0xFB, 0x66, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x22, 0xFB, 0x72, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x22, 0xFB, 0x7E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x23, 0xFB, 0x8A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x23, 0xFB, 0x06, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x1F, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0x40, 0x06, 0x00, 0x00, 0x01, 0x2F, 0x76, 0x7F, 0xC0, 0x01, 0x00, 0x6A, 0x01, 0xEF, 0x77, 0x7F, 0xC0, 0x01, 0x00, 0x6B, 0xFB, 0x06, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1E, 0xFB, 0x12, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1E, 0xFB, 0x1E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x1F, 0xFB, 0x2A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x1F, 0xFB, 0x36, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x20, 0xFB, 0x42, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x20, 0xFB, 0x4E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x21, 0xFB, 0x5A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x21, 0xFB, 0x66, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x22, 0xFB, 0x72, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x22, 0xFB, 0x7E, 0x40, 0x7F, 0x0C, 0x00, 0x3C, 0x23, 0xFB, 0x8A, 0x40, 0x7F, 0x0C, 0x00, 0xBC, 0x23, 0xFB, 0x06, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x1F, 0xFB, 0x0E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x1F, 0xFB, 0x16, 0xA0, 0x7F, 0x08, 0x00, 0x3E, 0x20, 0xFB, 0x1E, 0xA0, 0x7F, 0x08, 0x00, 0xBE, 0x20, 0xFA, 0x00, 0xA0, 0x7F, 0x80, 0x06, 0x00, 0x00, 0x01, 0xD4, 0xC8, 0x8E, 0x40, 0x00, 0x00, 0x7A, 0x01, 0x38, 0xC9, 0x8E, 0x40, 0x00, 0x20, 0x7A, 0x01, 0xB0, 0xCE, 0x8E, 0x40, 0x00, 0x40, 0x7A, 0x01, 0xC8, 0xCA, 0x8E, 0x40, 0x00, 0x60, 0x7A, 0x01, 0x00, 0xCA, 0x8E, 0x40, 0x00, 0x80, 0x7A, 0x01, 0xBC, 0xCC, 0x8E, 0x40, 0x00, 0xA0, 0x7A, 0x01, 0xA8, 0xC7, 0x8E, 0x40, 0x00, 0xC0, 0x7A, 0x01, 0x84, 0xCD, 0x8E, 0x40, 0x00, 0xE0, 0x7A, 0x01, 0x14, 0xCF, 0x8E, 0x40, 0x00, 0x00, 0x7B, 0x01, 0x0C, 0xC8, 0x8E, 0x40, 0x00, 0x20, 0x7B, 0x01, 0x08, 0xD1, 0x8E, 0x40, 0x00, 0x40, 0x7B, 0x01, 0x58, 0xCC, 0x8E, 0x40, 0x00, 0x60, 0x7B, 0x01, 0x70, 0xC8, 0x8E, 0x40, 0x00, 0x80, 0x7B, 0x01, 0x64, 0xCA, 0x8E, 0x40, 0x00, 0xA0, 0x7B, 0x01, 0xF4, 0xCB, 0x8E, 0x40, 0x00, 0xC0, 0x7B, 0x01, 0x4C, 0xCE, 0x8E, 0x40, 0x00, 0xE0, 0x7B, 0x01, 0x20, 0xCD, 0x8E, 0x40, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x1F, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x20, 0x40, 0x40, 0x40, 0x40, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFE, 0xFE, 0xFE, 0xFE, 0x06, 0x06, 0x0C, 0x0C, 0x0F, 0x0F, 0x18, 0x18, 0x30, 0x30, 0x3F, 0x3F, 0x60, 0x60, 0x70, 0x70, 0x7F, 0x7F, 0xB2, 0xB2, 0xF8, 0xF8, 0xFC, 0xFC, 0x05, 0x09, 0x0A, 0x0B, 0x0D, 0x0E, 0x11, 0x14, 0x1C, 0x1E, 0x21, 0x24, 0x28, 0x2F, 0x38, 0x3C, 0x78, 0x7E, 0x8F, 0x90, 0x9F, 0xA0, 0xB0, 0xBF, 0xDF, 0xEF, 0xF7, 0xF9, 0xFB, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x12, 0x12, 0x0C, 0x0C, 0x0C, 0x0C, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x0D, 0x00, 0x0C, 0x00, 0x1E, 0x00, 0x39, 0x00, 0x45, 0x00, 0x3D, 0x00, 0x0A, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x08, 0x00, 0x14, 0x00, 0x39, 0x00, 0x8F, 0x00, 0x59, 0x01, 0x26, 0x03, 0x05, 0x07, 0x00, 0x0F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x50, 0x00, 0x60, 0x00, 0x94, 0x00, 0xAC, 0x00, 0xCA, 0x80, 0xE6, 0xC0, 0xF7, 0x60, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDD, 0xBF, 0x8F, 0x00, 0x78, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x7C, 0xEE, 0x9A, 0x00, 0x00, 0x00, 0x9C, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x0F, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x99, 0x9C, 0x19, 0x80, 0x80, 0x4E, 0x85, 0x00, 0x00, 0xBD, 0xF6, 0xAD, 0x45, 0x41, 0x43, 0x44, 0x53, 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x24, 0x00, 0x21, 0x20, 0x23, 0x3C, 0x00, 0x31, 0x25, 0x03, 0x00, 0x00, 0x60, 0x00, 0x00, 0xA0, 0x01, 0x0F, 0x00, 0x30, 0x24, 0x10, 0x22, 0x00, 0x00, 0x02, 0x00, 0xA4, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0xC2, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x25, 0x41, 0x00, 0x50, 0x00, 0x00, 0x69, 0x00, 0x68, 0x00, 0x00, 0x0E, 0x0E, 0x00, 0x00, 0x4F, 0xC2, 0xA5, 0xC3, 0xB7, 0xC4, 0x3C, 0xC5, 0xD5, 0xC5, 0x49, 0xC6, 0x17, 0xCA, 0x39, 0xCE, 0x4F, 0xD0, 0xC3, 0xD3, 0x29, 0xDC, 0xAC, 0xDC, 0x65, 0xDE, 0x15, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0xC2, 0x92, 0xC3, 0x98, 0xC4, 0x28, 0xC5, 0xC2, 0xC5, 0x26, 0xC6, 0xF4, 0xC9, 0x16, 0xCE, 0x40, 0xD0, 0xB6, 0xD3, 0x16, 0xDC, 0x94, 0xDC, 0x4E, 0xDE, 0x06, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x45, 0x00, 0x2D, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x89, 0xBC, 0x59, 0xBC, 0xF9, 0xB5, 0x09, 0xB8, 0x59, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, 0xB5, 0x00, 0x00, 0x39, 0xBB, 0xF9, 0xBB, 0x29, 0xBC, 0xC9, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x50, 0x5C, 0x36, 0x40, 0x43, 0x01, 0x01, 0x01, 0x7F, 0x01, 0x45, 0x7F, 0x31, 0x61, 0x00, 0x00, 0x00, 0x4F, 0x5C, 0x42, 0x61, 0x59, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x4C, 0x40, 0x61, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; for (int i = 0; i < _countof(dataAt_7FA671_Write); ++i) { Data.push_back(dataAt_7FA671_Write[i]); } } unsigned char& Key_Byte_6C() { return Data[0x6C]; } void ShiftLeft_Key_6C() { Data[0x6C] *= 2; } unsigned short GetShort_6C() { return GetShort(0x6C); } void SetShort_6C(unsigned short val) { SetShort(0x6C, val); } void SetLowByteOfShort(int addr, unsigned short val) { unsigned char ch0 = val & 0xFF; Data[addr] = ch0; } void SetShort(int addr, unsigned short val) { unsigned char ch0 = val & 0xFF; unsigned char ch1 = val >> 8; Data[addr] = ch0; Data[addr+1] = ch1; } unsigned char& LastWrittenValue_08() { return Data[0x08]; } unsigned char& ArrayIndex_6D() { return Data[0x6D]; } unsigned short GetByte(int addr) { unsigned char ch0 = Data[addr]; return ch0; } void GetLowByteOfShort(int addr, unsigned short* result) { unsigned char ch0 = Data[addr]; *result &= 0xFF00; *result |= ch0; } unsigned short GetShort(int addr) { unsigned char ch0 = Data[addr]; unsigned char ch1 = Data[addr+1]; unsigned short r = 0; r |= (ch1 << 8); r |= ch0; return r; } int GetLongPointer_0C() { unsigned char ch0 = Data[0xC]; unsigned char ch1 = Data[0xD]; int addr = 0x810000; addr |= (ch1 << 8); addr |= ch0; return addr; } void IncrementPointer_0C() { unsigned char& ch0 = Data[0xC]; ch0++; if (ch0 != 0) return; unsigned char& ch1 = Data[0xD]; assert(ch1 < 0xFF); ch1++; } } wram; int jumpElements_BCF9[] = { 0, 0, 0, 0, 0, 0, 0x80BEAE, 0, 0, 0, 0, 0, 0, 0, 0x80BD70 }; int jumpElements_BD2D[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80BEF2, 0, 0x80BF44 }; int jumpElements_BD7A[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0x80BEF3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80BD8E }; int jumpElements_BDC8[] = { 0x80BE04, 0x0, 0x80BE53, 0x0, 0x80BEA3, 0x0, 0x80BEF4, 0x0, 0x80BF46, 0x0, 0x80BD0D, 0x0, 0x80BD59, 0x0, 0x80BDA6, 0x0, 0x80BDE1, 0x0, 0x80BDDC }; int jumpElements_BE67[] = { 0x80BEA5, 0x0, 0x80BEF6, 0x0, 0x80BF48, 0x0, 0x80BD0F, 0x0, 0x80BD5B, 0x0, 0x80BDA8, 0x0, 0x80BDF6, 0x0, 0x80BE45, 0x0, 0x80BE80 }; int jumpElements_BEB8[] = { 0x80BEF7, 0x0, 0x80BF49, 0x0, 0x80BD10, 0x0, 0x80BD5C, 0x0, 0x80BDA9, 0x0, 0x80BDF7, 0x0, 0x80BE46, 0x0, 0x80BE96, 0x0, 0x80BED1, 0x0, 0x80BECC }; int jumpElements_BF0A[] = { 0, 0, 0x80BD11 }; int jumpElements_BF5D[] = { 0x80BD12, 0x0, 0x80BD5E, 0x0, 0x80BDAB, 0x0, 0x80BDF9, 0x0, 0x80BE48, 0x0, 0x80BE98, 0x0, 0x80BEE9, 0x0, 0x80BF3B, 0x0, 0x80BF76, 0x0, 0x80BF71 }; int jumpValue = 0; int previousJumpValue = 0; int ROMAddressToFileOffset(int romAddress) { assert(romAddress >= 0x800000); // Lower ones haven't been tested int offsetWithinSection = romAddress % 0x8000; int section = (romAddress - 0x800000) >> 16; int offset = section * 0x8000 + offsetWithinSection; return offset; } int FileOffsetToROMAddress(int fileOffset) { int section = fileOffset / 0x8000; int offsetWithinSection = fileOffset % 0x8000; int addr = 0x800000 + (section * 0x10000) + 0x8000 + offsetWithinSection; return addr; } unsigned short GetROMDataShort(int ptr) { unsigned char data0 = romData[ROMAddressToFileOffset(ptr)]; unsigned char data1 = romData[ROMAddressToFileOffset(ptr+1)]; return (data1 << 8) | data0; } void SetJumpValue(int newValue) { previousJumpValue = jumpValue; jumpValue = newValue; } void Impl_BC02() { assert(false); // incomplete impl regs.A = wram.GetShort(0x75); wram.SetShort(0x0, regs.A); } void Impl_BD11() { regs.A *= 4; unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.X = decompressedValueDictionary_7E0500[regs.Y]; out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); unsigned short x = wram.GetShort(0x600 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; SetJumpValue(jumpElements_BD2D[regs.X]); } void Impl_BD5E() { regs.A *= 2; unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.A *= 2; unsigned short x = wram.GetShort(0x500 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; unsigned char decompressed = x & 0xFF; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); x = wram.GetShort(0x600 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; SetJumpValue(jumpElements_BD7A[regs.X]); } void Impl_BD70() { wram.SetLowByteOfShort(0x6C, regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); regs.X = array_7E0600[regs.Y]; SetJumpValue(jumpElements_BD7A[regs.X]); } void Impl_BD8E() { regs.X = 0xE; SetJumpValue(0x80C17C); } void Impl_BDA6(int multiplier) { regs.A *= multiplier; // Set 8-bit acc for just this part unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.A *= 4; unsigned short x = wram.GetShort(0x500 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; unsigned char decompressed = x & 0xFF; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); x = wram.GetShort(0x600 + regs.Y); x &= 0xFF; regs.X &= 0xFF00; regs.X |= x; SetJumpValue(jumpElements_BDC8[regs.X]); } void Impl_BDE1() { regs.X = 0x0C; wram.Data[0x6A] = 0; regs.A = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF; regs.A *= 2; regs.A *= 2; regs.A |= wram.GetShort(0x6B); wram.SetShort(0x6B, regs.A); regs.A = wram.GetShort_6C(); SetJumpValue(0x80BFDD); } void Impl_BE0D() { // C153 // BE0D jump wram.SetShort_6C(regs.A); regs.Y = wram.GetShort(0x6D); regs.Y &= 0xFF; regs.X = wram.GetShort(0x600 + regs.Y); regs.X &= 0xFF; // This is in 8-bit index mode assert(regs.X == 2); SetJumpValue(0x80BEA4); } void Impl_BE53() { regs.A *= 4; regs.X = wram.GetShort(0x500 + regs.Y); out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); wram.GetLowByteOfShort(0x600 + regs.Y, &regs.X); SetJumpValue(jumpElements_BE67[regs.X]); } void Impl_BE96(int multiplier) { regs.A *= multiplier; unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A &= 0xFF00; regs.A |= low; wram.IncrementPointer_0C(); regs.A *= 32; wram.GetLowByteOfShort(0x500 + regs.Y, &regs.X); out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); wram.GetLowByteOfShort(0x600 + regs.Y, &regs.X); SetJumpValue(jumpElements_BEB8[regs.X]); } void Impl_BEA4() { // Jump to ($BE17, x) meaning we look at address 80BE17+2 which contains short address BEA4 // Jump to BEA4 regs.A *= 4; assert(regs.Y == 0x29); regs.X = wram.GetShort(0x500 + regs.Y); out.push_back(regs.X); wram.LastWrittenValue_08() = regs.X; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); wram.GetLowByteOfShort(0x600 + regs.Y, &regs.X); SetJumpValue(jumpElements_BEB8[regs.X]); } void Impl_BEAE() // Could merge with last part of Impl_BEA4 { wram.SetShort_6C(regs.A); regs.Y = wram.GetShort(0x6D); regs.Y &= 0xFF; regs.X = wram.GetShort(0x600 + regs.Y); regs.X &= 0xFF; // This is in 8-bit index mode SetJumpValue(jumpElements_BEB8[regs.X]); } void Impl_BEB5() { regs.X = 0x6; SetJumpValue(0x80C17C); } void Impl_BECC() { regs.X = 0x6; SetJumpValue(0x80C17C); } void Impl_BEF2(int multiplier) { regs.A *= multiplier; unsigned char decompressed = decompressedValueDictionary_7E0500[regs.Y]; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); unsigned short x = wram.GetShort(0x600 + regs.Y); unsigned char xLow = x & 0xFF; regs.X &= 0xFF00; regs.X |= xLow; SetJumpValue(jumpElements_BF0A[regs.X]); } void Impl_BF44(int multiplier) { regs.A *= multiplier; unsigned char decompressed = decompressedValueDictionary_7E0500[regs.Y]; out.push_back(decompressed); wram.LastWrittenValue_08() = decompressed; wram.SetShort_6C(regs.A); wram.GetLowByteOfShort(0x6D, &regs.Y); unsigned short x = wram.GetShort(0x600 + regs.Y); unsigned char xLow = x & 0xFF; regs.X &= 0xFF00; regs.X |= xLow; SetJumpValue(jumpElements_BF5D[regs.X]); } void Impl_BFDD() { unsigned short val0750 = wram.GetShort(0x750); if (val0750 == 0xE680) { // BF8F regs.A /= 128; unsigned short val0730 = wram.GetShort(0x730); regs.A -= val0730; regs.Y = regs.A; regs.A = wram.GetByte(0x100 + regs.Y); regs.Y = 1; unsigned char val73 = wram.GetByte(0x73); if (val73 == 0) { // BFC2 // untested assert(false); } else { // BFA6 // Jumped right to C0E8 // WriteImpl unsigned char b = regs.A & 0xFF; out.push_back(b); wram.LastWrittenValue_08() = b; wram.IncrementPointer_0C(); regs.A = wram.GetShort(0x6B); assert(regs.X == 0xC); SetJumpValue(0x80C10E); } } else { // Fall thru to BFE2 assert(false); // untested } } void Fn_C2DC() { regs.A = wram.GetShort_6C(); regs.Y = wram.GetShort(0x74); // Dunno what this is do { regs.A *= 2; regs.X -= 2; if (regs.X == 0) { unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A = regs.A & 0xFF00; regs.A = regs.A | low; wram.IncrementPointer_0C(); regs.X = 16; } regs.Y--; } while (regs.Y > 0); } unsigned short RotateLeft(unsigned short v, bool& carry) { bool high = v >= 0x8000; v = v << 1; if (carry) { v |= 1; } carry = high; return v; } void Fn_C232() { // Postconditions: Result1_08 contains the repeated value and Result0_A contains the repeat count. wram.SetShort(0x6F, 0); regs.A = wram.GetShort_6C(); bool carry = regs.A > 0x7FFF; regs.A = regs.A * 2; regs.X-=2; if (regs.X == 0) { // goto C250 assert(false); } else { if (!carry) // went to C277 { regs.Y = 2; bool carry = regs.A > 0x7FFF; regs.A = regs.A * 2; regs.X -= 2; if (regs.X == 0) { // goto C2A2 assert(false); } regs.Y++; if (!carry) { // goto c279 assert(false); } else { wram.SetShort(0x14, regs.Y); while (1) // C283 { carry = regs.A > 0x7FFF; regs.A = regs.A * 2; unsigned short val1 = wram.GetShort(0x6f); unsigned short val2 = RotateLeft(val1, carry); wram.SetShort(0x6F, val2); regs.X -= 2; if (regs.X == 0) { // C2AE unsigned char low = GetROMDataShort(wram.GetLongPointer_0C()); regs.A = regs.A & 0xFF00; regs.A = regs.A | low; wram.IncrementPointer_0C(); regs.X = 0x10; } regs.Y--; // C28A if (regs.Y != 0) { // Continue in loop } else { // C28D wram.SetShort_6C(regs.A); regs.Y = regs.X; regs.A = wram.GetShort(0x14); regs.A = regs.A & 0xFF; regs.A *= 2; regs.X = regs.A; int loadAddress = 0x80C2B6 + regs.A; regs.A = GetROMDataShort(loadAddress); regs.X = regs.Y; regs.A += wram.GetShort(0x6F); wram.SetShort(0x6F, regs.A); return; } } } } else { // fell thru to C23D assert(false); } } } void Impl_C10E() { // takes an acc parameter regs.A *= 2; regs.Y--; if (regs.Y == 0) { SetJumpValue(0x80BE0D); } else { assert(false); // untested } } void Impl_C17C() { wram.GetLowByteOfShort(0x74, &regs.Y); Fn_C2DC(); wram.SetShort_6C(regs.A); Fn_C232(); unsigned char repeatingValue = wram.LastWrittenValue_08(); int repeatCount = regs.A; if (repeatCount == 0) { SetJumpValue(0x80C195); return; } for (int i = 0; i < repeatCount; ++i) { out.push_back(repeatingValue); } regs.A = wram.GetShort_6C(); SetJumpValue(jumpElements_BCF9[regs.X]); } int main() { FILE* file{}; fopen_s(&file, "E:\\Emulation\\SNES\\Images\\Test\\nhl94.sfc", "rb"); fseek(file, 0, SEEK_END); long length = ftell(file); romData.resize(length); fseek(file, 0, SEEK_SET); fread(romData.data(), 1, length, file); fclose(file); // Initial values SetJumpValue(0x80BDE1); regs.A = 0xCE14; regs.X = 0X10; regs.Y = 0xCE; for (int i = 0; i < 37; ++i) { switch (jumpValue) { case 0x80BD11: Impl_BD11(); break; case 0x80BD5E: Impl_BD5E(); break; case 0x80BD70: Impl_BD70(); break; case 0x80BD8E: Impl_BD8E(); break; case 0x80BDA6: Impl_BDA6(64); break; case 0x80BDA7: Impl_BDA6(32); break; case 0x80BDA8: Impl_BDA6(16); break; case 0x80BDA9: Impl_BDA6(8); break; case 0x80BDAA: Impl_BDA6(4); break; case 0x80BDAB: Impl_BDA6(2); break; case 0x80BDAC: Impl_BDA6(1); break; case 0x80BDE1: Impl_BDE1(); break; case 0x80BE0D: Impl_BE0D(); break; case 0x80BE53: Impl_BE53(); break; case 0x80BE98: Impl_BE96(2); break; case 0x80BEA4: Impl_BEA4(); break; case 0x80BEAE: Impl_BEAE(); break; case 0x80BEB5: Impl_BEB5(); break; case 0x80BECC: Impl_BECC(); break; case 0x80BEF2: Impl_BEF2(64); break; case 0x80BEF3: Impl_BEF2(32); break; case 0x80BF44: Impl_BF44(128); break; case 0x80BF45: Impl_BF44(64); break; case 0x80BF46: Impl_BF44(32); break; case 0x80BF47: Impl_BF44(16); break; case 0x80BF48: Impl_BF44(8); break; case 0x80BF49: Impl_BF44(4); break; case 0x80BF4A: Impl_BF44(2); break; case 0x80BF4B: Impl_BF44(1); break; case 0x80BFDD: Impl_BFDD(); break; case 0x80C10E: Impl_C10E(); break; case 0x80C17C: Impl_C17C(); break; default: assert(false); } } unsigned char expected[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x07, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x01, 0x07, 0x03, 0x0F, 0x07 }; for (int i = 0; i < out.size(); ++i) { int val = out[i]; std::cout << std::hex << std::setw(2) << val << " "; if (i % 16 == 15) { std::cout << "\n"; } } } // SEP #$20 - Use 8-bit accumulator mode // REP #$20 - Use 16-bit accumulator mode // SEP #$10 - Use 8-bit indexing mode // REP #$10 - Use 16-bit indexing mode
48.614474
13,873
0.598235
clandrew
bccad925333905252f09ea9d654acc9f88ac598b
4,090
cpp
C++
code archive/CF/1079G.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/CF/1079G.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/CF/1079G.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
//{ #include<bits/stdc++.h> using namespace std; typedef int ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define REP1(i,n) for(ll i=1;i<=n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #define IOS() #else #define debug(...) #define pary(...) #define endl '\n' #define IOS() ios_base::sync_with_stdio(0);cin.tie(0); #endif // brian //} const ll MAXn=2e5+5,MAXlg=__lg(MAXn)+2; const ll MOD=1000000007; const ll INF=ll(1e9); struct node{ ll l,r; node *lc,*rc; ll dtl,dtr; void pull(){ dtl = min(lc->dtl,rc->dtl); dtr = max(lc->dtr,rc->dtr); } void insl(ll x,ll k) { if(l == r-1)dtl = min(dtl,k); else { if(x < (l+r)/2)lc->insl(x,k); else rc->insl(x,k); pull(); } } void insr(ll x,ll k) { if(l == r-1)dtr = max(dtr,k); else { if(x < (l+r)/2)lc->insr(x,k); else rc->insr(x,k); pull(); } } ll qrl(ll li,ll ri) { if(li >= r || ri <= l)return INF; else if(li <= l && ri >= r)return dtl; else return min(lc->qrl(li,ri),rc->qrl(li,ri)); } ll qrr(ll li,ll ri) { if(li >= r || ri <= l)return -1; else if(li <= l && ri >= r)return dtr; else return max(lc->qrr(li,ri),rc->qrr(li,ri)); } void clr() { dtl = INF,dtr = -1; if(l == r-1)return; if(lc->dtl != INF || lc->dtr != -1)lc->clr(); if(rc->dtl != INF || rc->dtr != -1)rc->clr(); } }; node *build(ll l,ll r) { if(l == r-1)return new node{l,r,0,0,INF,-1}; else return new node{l,r,build(l,(l+r)/2),build((l+r)/2,r),INF,-1}; } ll d[MAXn]; ll l[MAXn][MAXlg],r[MAXn][MAXlg],nl[MAXn],nr[MAXn],ct[MAXn]; node *rt; int main() { IOS(); ll n,nn; cin>>n; nn = 2 * n; if(n == 1) { cout<<0<<endl; return 0; } rt = build(0,nn); REP(i,n)cin>>d[i]; REP(i,n)d[n + i] = d[i]; REP(i,nn)l[i][0] = max(0,i - d[i]),r[i][0] = min(nn-1,i + d[i]); for(int i = 0; i < nn;i ++)nl[i] = nr[i] = i,ct[i] = 0; REP1(i,MAXlg-1) { //rt->clr(); REP(j,nn) { rt->insl(j,l[j][i-1]),rt->insr(j,r[j][i-1]); } REP(j,nn) { l[j][i] = rt->qrl(l[j][i-1],r[j][i-1]+1); r[j][i] = rt->qrr(l[j][i-1],r[j][i-1]+1); } } for(int i = MAXlg-1;i > 0;i--) { rt->clr(); REP(j,nn) { rt->insl(j,l[j][i-1]),rt->insr(j,r[j][i-1]); } for(int j = 0; j < nn;j ++) { ll tmpl = rt->qrl(nl[j],nr[j]+1); ll tmpr = rt->qrr(nl[j],nr[j]+1); if(tmpr - tmpl + 1 < n) { nl[j] = tmpl, nr[j] = tmpr; ct[j] += (1<<(i-1)); } } } for(int j = 0; j < n;j ++)cout<<min(ct[j],ct[j+n])+1<<" "; }
25.5625
129
0.476528
brianbbsu
bccbb768c15017dd2a04701b65a8bfead74a8802
12,924
hpp
C++
Engine/Code/Engine/Core/App.hpp
cugone/Abrams2019
0b94c43275069275bbbeadfa773c336fa1947882
[ "MIT" ]
1
2020-07-14T06:58:50.000Z
2020-07-14T06:58:50.000Z
Engine/Code/Engine/Core/App.hpp
cugone/Abrams2019
0b94c43275069275bbbeadfa773c336fa1947882
[ "MIT" ]
1
2020-04-06T06:52:11.000Z
2020-04-06T06:52:19.000Z
Engine/Code/Engine/Core/App.hpp
cugone/Abrams2019
0b94c43275069275bbbeadfa773c336fa1947882
[ "MIT" ]
2
2019-05-01T21:49:33.000Z
2021-04-01T08:22:21.000Z
#pragma once #include "Engine/Audio/AudioSystem.hpp" #include "Engine/Core/Config.hpp" #include "Engine/Core/Console.hpp" #include "Engine/Core/EngineConfig.hpp" #include "Engine/Core/EngineCommon.hpp" #include "Engine/Core/EngineSubsystem.hpp" #include "Engine/Core/FileLogger.hpp" #include "Engine/Core/JobSystem.hpp" #include "Engine/Core/KeyValueParser.hpp" #include "Engine/Core/StringUtils.hpp" #include "Engine/Core/TimeUtils.hpp" #include "Engine/Input/InputSystem.hpp" #include "Engine/Physics/PhysicsSystem.hpp" #include "Engine/Profiling/AllocationTracker.hpp" #include "Engine/Renderer/Renderer.hpp" #include "Engine/Renderer/Window.hpp" #include "Engine/Services/IAudioService.hpp" #include "Engine/Services/IAppService.hpp" #include "Engine/Services/IConfigService.hpp" #include "Engine/Services/IFileLoggerService.hpp" #include "Engine/Services/IInputService.hpp" #include "Engine/Services/IJobSystemService.hpp" #include "Engine/Services/IRendererService.hpp" #include "Engine/Services/IPhysicsService.hpp" #include "Engine/Services/ServiceLocator.hpp" #include "Engine/System/System.hpp" #include "Engine/UI/UISystem.hpp" #include "Engine/Game/GameBase.hpp" #include <algorithm> #include <condition_variable> #include <iomanip> #include <memory> template<typename T> class App : public EngineSubsystem, public IAppService { public: App() noexcept = default; explicit App(const std::string& title, const std::string& cmdString); App(const App& other) = default; App(App&& other) = default; App& operator=(const App& other) = default; App& operator=(App&& other) = default; using GameType = T; static_assert(std::is_base_of_v<std::remove_cv_t<std::remove_reference_t<std::remove_pointer_t<GameBase>>>, std::remove_cv_t<std::remove_reference_t<std::remove_pointer_t<GameType>>>>); virtual ~App() noexcept; static void CreateApp(const std::string& title, const std::string& cmdString) noexcept; static void DestroyApp() noexcept; void InitializeService() override; void RunFrame() override; bool IsQuitting() const override; void SetIsQuitting(bool value) override; bool HasFocus() const override; bool LostFocus() const override; bool GainedFocus() const override; protected: private: void RunMessagePump() const; void SetupEngineSystemPointers(); void SetupEngineSystemChainOfResponsibility(); void Initialize() noexcept override; void BeginFrame() noexcept override; void Update(TimeUtils::FPSeconds deltaSeconds) noexcept override; void Render() const noexcept override; void EndFrame() noexcept override; bool ProcessSystemMessage(const EngineMessage& msg) noexcept override; void LogSystemDescription() const; bool _isQuitting = false; bool _current_focus = false; bool _previous_focus = false; std::string _title{"UNTITLED GAME"}; std::unique_ptr<JobSystem> _theJobSystem{}; std::unique_ptr<FileLogger> _theFileLogger{}; std::unique_ptr<Config> _theConfig{}; std::unique_ptr<Renderer> _theRenderer{}; std::unique_ptr<Console> _theConsole{}; std::unique_ptr<PhysicsSystem> _thePhysicsSystem{}; std::unique_ptr<InputSystem> _theInputSystem{}; std::unique_ptr<UISystem> _theUI{}; std::unique_ptr<AudioSystem> _theAudioSystem{}; std::unique_ptr<GameType> _theGame{}; static inline std::unique_ptr<App<GameType>> _theApp{}; static inline NullAppService _nullApp{}; }; namespace detail { bool CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); EngineMessage GetEngineMessageFromWindowsParams(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); } template<typename T> /*static*/ void App<T>::CreateApp(const std::string& title, const std::string& cmdString) noexcept { if(_theApp) { return; } _theApp = std::make_unique<App<T>>(title, cmdString); ServiceLocator::provide(*static_cast<IAppService*>(_theApp.get())); } template<typename T> /*static*/ void App<T>::DestroyApp() noexcept { if(!_theApp) { return; } _theApp.reset(nullptr); } template<typename T> App<T>::App(const std::string& title, const std::string& cmdString) : EngineSubsystem() , _title{title} , _theConfig{std::make_unique<Config>(KeyValueParser{cmdString})} { SetupEngineSystemPointers(); SetupEngineSystemChainOfResponsibility(); LogSystemDescription(); } template<typename T> App<T>::~App() noexcept { if(g_theApp<T>) { g_theSubsystemHead = g_theApp<T>; } } template<typename T> void App<T>::SetupEngineSystemPointers() { ServiceLocator::provide(*static_cast<IConfigService*>(_theConfig.get())); _theJobSystem = std::make_unique<JobSystem>(-1, static_cast<std::size_t>(JobType::Max), new std::condition_variable); ServiceLocator::provide(*static_cast<IJobSystemService*>(_theJobSystem.get())); _theFileLogger = std::make_unique<FileLogger>("game"); ServiceLocator::provide(*static_cast<IFileLoggerService*>(_theFileLogger.get())); _thePhysicsSystem = std::make_unique<PhysicsSystem>(); ServiceLocator::provide(*static_cast<IPhysicsService*>(_thePhysicsSystem.get())); _theRenderer = std::make_unique<Renderer>(); ServiceLocator::provide(*static_cast<IRendererService*>(_theRenderer.get())); _theInputSystem = std::make_unique<InputSystem>(); ServiceLocator::provide(*static_cast<IInputService*>(_theInputSystem.get())); _theAudioSystem = std::make_unique<AudioSystem>(); ServiceLocator::provide(*static_cast<IAudioService*>(_theAudioSystem.get())); _theUI = std::make_unique<UISystem>(); _theConsole = std::make_unique<Console>(); _theGame = std::make_unique<GameType>(); g_theJobSystem = _theJobSystem.get(); g_theFileLogger = _theFileLogger.get(); g_theConfig = _theConfig.get(); g_theRenderer = _theRenderer.get(); g_theUISystem = _theUI.get(); g_theConsole = _theConsole.get(); g_thePhysicsSystem = _thePhysicsSystem.get(); g_theInputSystem = _theInputSystem.get(); g_theAudioSystem = _theAudioSystem.get(); g_theGame = _theGame.get(); g_theApp<T> = this; } template<typename T> void App<T>::SetupEngineSystemChainOfResponsibility() { g_theConsole->SetNextHandler(g_theUISystem); g_theUISystem->SetNextHandler(g_theInputSystem); g_theInputSystem->SetNextHandler(g_thePhysicsSystem); g_thePhysicsSystem->SetNextHandler(g_theRenderer); g_theRenderer->SetNextHandler(g_theApp<T>); g_theApp<T>->SetNextHandler(nullptr); g_theSubsystemHead = g_theConsole; } template<typename T> void App<T>::Initialize() noexcept { auto& settings = g_theGame->GetSettings(); bool vsync = settings.DefaultVsyncEnabled(); if(g_theConfig->HasKey("vsync")) { g_theConfig->GetValue(std::string{"vsync"}, vsync); } else { g_theConfig->SetValue(std::string{"vsync"}, vsync); } settings.SetVsyncEnabled(vsync); int width = settings.DefaultWindowWidth(); int height = settings.DefaultWindowHeight(); if(g_theConfig->HasKey("width")) { g_theConfig->GetValue(std::string{"width"}, width); } else { g_theConfig->SetValue(std::string{"width"}, width); } if(g_theConfig->HasKey("height")) { g_theConfig->GetValue(std::string{"height"}, height); } else { g_theConfig->SetValue(std::string{"height"}, height); } settings.SetWindowResolution(IntVector2{width, height}); g_theRenderer->Initialize(); g_theRenderer->SetVSync(vsync); auto* output = g_theRenderer->GetOutput(); output->SetTitle(_title); output->GetWindow()->custom_message_handler = detail::WindowProc; g_theUISystem->Initialize(); g_theInputSystem->Initialize(); g_theConsole->Initialize(); g_theAudioSystem->Initialize(); g_thePhysicsSystem->Initialize(); g_theGame->Initialize(); } template<typename T> void App<T>::InitializeService() { Initialize(); } template<typename T> void App<T>::BeginFrame() noexcept { g_theJobSystem->BeginFrame(); g_theUISystem->BeginFrame(); g_theInputSystem->BeginFrame(); g_theConsole->BeginFrame(); g_theAudioSystem->BeginFrame(); g_thePhysicsSystem->BeginFrame(); g_theGame->BeginFrame(); g_theRenderer->BeginFrame(); } template<typename T> void App<T>::Update(TimeUtils::FPSeconds deltaSeconds) noexcept { g_theUISystem->Update(deltaSeconds); g_theInputSystem->Update(deltaSeconds); g_theConsole->Update(deltaSeconds); g_theAudioSystem->Update(deltaSeconds); g_thePhysicsSystem->Update(deltaSeconds); g_theGame->Update(deltaSeconds); g_theRenderer->Update(deltaSeconds); } template<typename T> void App<T>::Render() const noexcept { g_theGame->Render(); g_theUISystem->Render(); g_theConsole->Render(); g_theAudioSystem->Render(); g_theInputSystem->Render(); g_thePhysicsSystem->Render(); g_theRenderer->Render(); } template<typename T> void App<T>::EndFrame() noexcept { g_theUISystem->EndFrame(); g_theGame->EndFrame(); g_theConsole->EndFrame(); g_theAudioSystem->EndFrame(); g_theInputSystem->EndFrame(); g_thePhysicsSystem->EndFrame(); g_theRenderer->EndFrame(); } template<typename T> bool App<T>::ProcessSystemMessage(const EngineMessage& msg) noexcept { switch(msg.wmMessageCode) { case WindowsSystemMessage::Window_Close: { SetIsQuitting(true); return true; } case WindowsSystemMessage::Window_Quit: { SetIsQuitting(true); return true; } case WindowsSystemMessage::Window_Destroy: { ::PostQuitMessage(0); return true; } case WindowsSystemMessage::Window_ActivateApp: { WPARAM wp = msg.wparam; bool losing_focus = wp == FALSE; bool gaining_focus = wp == TRUE; if(losing_focus) { _current_focus = false; _previous_focus = true; } if(gaining_focus) { _current_focus = true; _previous_focus = false; } return true; } case WindowsSystemMessage::Keyboard_Activate: { WPARAM wp = msg.wparam; auto active_type = LOWORD(wp); switch(active_type) { case WA_ACTIVE: /* FALLTHROUGH */ case WA_CLICKACTIVE: _current_focus = true; _previous_focus = false; return true; case WA_INACTIVE: _current_focus = false; _previous_focus = true; return true; default: return false; } } //case WindowsSystemMessage::Window_Size: //{ // LPARAM lp = msg.lparam; // const auto w = HIWORD(lp); // const auto h = LOWORD(lp); // g_theRenderer->ResizeBuffers(); // return true; //} default: return false; } } template<typename T> bool App<T>::IsQuitting() const { return _isQuitting; } template<typename T> void App<T>::SetIsQuitting(bool value) { _isQuitting = value; } template<typename T> void App<T>::RunFrame() { using namespace TimeUtils; RunMessagePump(); BeginFrame(); static FPSeconds previousFrameTime = TimeUtils::GetCurrentTimeElapsed(); FPSeconds currentFrameTime = TimeUtils::GetCurrentTimeElapsed(); FPSeconds deltaSeconds = (currentFrameTime - previousFrameTime); previousFrameTime = currentFrameTime; #ifdef DEBUG_BUILD deltaSeconds = (std::min)(FPSeconds{FPFrames{1}}, deltaSeconds); #endif Update(deltaSeconds); Render(); EndFrame(); AllocationTracker::tick(); } template<typename T> void App<T>::LogSystemDescription() const { const auto section_break_field_width = std::size_t{80u}; const auto system = System::GetSystemDesc(); std::ostringstream ss; ss << std::right << std::setfill('-') << std::setw(section_break_field_width) << '\n'; ss << StringUtils::to_string(system); ss << std::right << std::setfill('-') << std::setw(section_break_field_width) << '\n'; g_theFileLogger->LogAndFlush(ss.str()); } template<typename T> bool App<T>::HasFocus() const { return _current_focus; } template<typename T> bool App<T>::LostFocus() const { return _previous_focus && !_current_focus; } template<typename T> bool App<T>::GainedFocus() const { return !_previous_focus && _current_focus; } template<typename T> void App<T>::RunMessagePump() const { MSG msg{}; for(;;) { const BOOL hasMsg = ::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE); if(!hasMsg) { break; } if(!::TranslateAcceleratorA(reinterpret_cast<HWND>(g_theRenderer->GetOutput()->GetWindow()->GetWindowHandle()), reinterpret_cast<HACCEL>(g_theConsole->GetAcceleratorTable()), &msg)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } } }
30.553191
191
0.692587
cugone
bccbcfe71904fbe1fb6874b5f9cccc537f7c6b8a
189
hpp
C++
CSGOSimple/features/nosmoke.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
null
null
null
CSGOSimple/features/nosmoke.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
1
2022-03-07T21:32:36.000Z
2022-03-07T21:32:36.000Z
CSGOSimple/features/nosmoke.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
null
null
null
#pragma once #include "../Singleton.hpp" #include "../options.hpp" #include "../valve_sdk/csgostructs.hpp" class NoSmoke : public Singleton<NoSmoke> { public: void RemoveSmoke(); };
14.538462
41
0.693122
alerion921
bccc0128518c88978b4044c4442b8713be10a5fc
884
cpp
C++
src/Process/TextureGL.cpp
ThiagoLuizNunes/CG-TerrorProject
ec373bdadb1340703a5c5881d900c7648842864a
[ "MIT" ]
2
2017-12-17T05:02:58.000Z
2019-04-17T20:59:42.000Z
src/Process/TextureGL.cpp
ThiagoLuizNunes/TerrorOnTheHouse
ec373bdadb1340703a5c5881d900c7648842864a
[ "MIT" ]
1
2017-08-04T19:39:23.000Z
2017-08-21T04:12:13.000Z
src/Process/TextureGL.cpp
ThiagoLuizNunes/CG-TerrorProject
ec373bdadb1340703a5c5881d900c7648842864a
[ "MIT" ]
null
null
null
#include "TextureGL.hpp" TextureGL::TextureGL(int w, int h, int ch ,unsigned char* img) { this->width = w; this->height = h; this->channels = ch; this->data = img; } TextureGL::~TextureGL() {} int TextureGL::getWidth(void){ return this->width; } int TextureGL::getHeight(void){ return this->height; } int TextureGL::getChannels(void){ return this->channels; } unsigned char* TextureGL::getData(void){ return this->data; } GLint TextureGL::getTextureID(void) { return this->texture_id; } void TextureGL::setTextureID(GLint id) { this->texture_id = id; } void TextureGL::printAtt(void) { std::clog << "SOIL texture loading with succes!" << std::endl; std::clog << " Image width........ : " << this->width << std::endl; std::clog << " Image height....... : " << this->height << std::endl; std::clog << " Image channels..... : " << this->channels << std::endl; }
25.257143
74
0.647059
ThiagoLuizNunes
bccc1ec4583973230aedc0a4efa5a5436107fd8e
7,337
cpp
C++
old/dpd_cpp/micelle.cpp
brix4dayz/dpd_cpp
6156b9011f7fa529972620a9e949f1ff858f3a28
[ "MIT" ]
null
null
null
old/dpd_cpp/micelle.cpp
brix4dayz/dpd_cpp
6156b9011f7fa529972620a9e949f1ff858f3a28
[ "MIT" ]
7
2015-11-23T19:17:06.000Z
2016-03-02T20:55:29.000Z
old/dpd_cpp/micelle.cpp
brix4dayz/dpd_cpp
6156b9011f7fa529972620a9e949f1ff858f3a28
[ "MIT" ]
null
null
null
#include "micelle.h" Micelle::Micelle( DPDFrame<CopolymerChain>* frame ) { this->frame = frame; this->aggreg_num = 0; this->com = new PosVect(); } Micelle::Micelle(): Micelle( NULL ) {} void Micelle::unlink() { this->frame = NULL; for ( auto core = std::begin( this->coreList ); core != std::end( this->coreList ); core++ ) { *core = NULL; } } Micelle::~Micelle() { delete this->com; for ( auto core = std::begin( this->coreList ); core != std::end( this->coreList ); core++ ) { delete *core; } this->unlink(); } void Micelle::addCore( HydrophobicCore* core ) { if ( !core->grouped ) { core->grouped = true; core->micelle = this; this->coreList.push_back( core ); } } void Micelle::printMicelleCore( FILE* stream ) { for ( auto core = std::begin( this->coreList ) ; core != std::end( this->coreList ) ; core++ ) { ( *core )->printCore( stream ); } } TriblockMicelle::TriblockMicelle() : Micelle() {} TriblockMicelle::TriblockMicelle( DPDFrame<CopolymerChain>* frame ): Micelle( frame ) {} void TriblockMicelle::addChain( PECTriblock* chain ) { this->chainList.push_back( chain ); chain->micelle = this; } void TriblockMicelle::deriveChainList() { PECTriblock* chain; HydrophobicCore* c1; HydrophobicCore* c2; for ( auto core = std::begin( this->coreList ) ; core != std::end( this->coreList ) ; core++ ) { for ( auto bin = std::begin( ( *core )->binList ) ; bin != std::end( ( *core )->binList ) ; bin++ ) { for ( auto tail = std::begin( ( *bin )->tailList ) ; tail != std::end( ( *bin )->tailList ) ; tail++ ) { chain = ( PECTriblock* ) ( *tail )->chain; if ( chain && !chain->micelle ) { this->addChain( chain ); c1 = chain->tail1->getCore(); c2 = chain->tail2->getCore(); if ( c1 ) c1->aggregation_num++; if ( c2 && c1 != c2 ) c2->aggregation_num++; } } } } //if ( this->chainList.size() != this->aggreg_num ) //printf( "Error in deriving chain in micelle.\n" ); } void TriblockMicelle::printMicelle( FILE* stream ) { for ( auto chain = std::begin( this->chainList ) ; chain != std::end( this->chainList ) ; chain++ ) { ( *chain )->printChain( stream ); } } // Multiple base beads?? Randomly chosen??? void TriblockMicelle::pbcCorrectMicelle( idx* box_length, const float& pbc_correction_factor ) { /*Bead* baseBeads[ 3 ]; baseBeads[ 0 ] = this->chainList.at( 0 )->tail1->beadList[ 0 ]; PECTriblock* triblock = this->chainList.at( this->chainList.size() - 1 ); baseBeads[ 1 ] = triblock->tail2->beadList[ triblock->tail_length - 1 ]; int randChain = rand() % this->chainList.size(); triblock = this->chainList.at( randChain ); int randBead = rand() % triblock->tail_length; baseBeads[ 2 ] = triblock->tail1->beadList[ randBead ]; baseBeads[ 1 ]->pbcCorrectBeadInChain( baseBeads[ 0 ], box_length ); baseBeads[ 2 ]->pbcCorrectBeadInChain( baseBeads[ 1 ], box_length ); baseBeads[ 2 ]->pbcCorrectBeadInChain( baseBeads[ 0 ], box_length ); */ Bead* baseBead = this->chainList.at( 0 )->tail1->beadList[ 0 ]; PECTriblock* triblock = NULL; for ( auto chain = std::begin( this->chainList ) ; chain != std::end( this->chainList ) ; chain++ ) { triblock = ( *chain ); /*for ( int i = 0 ; i < 3; i++ ) { triblock->tail1->beadList[ 0 ]->pbcCorrectBeadInChain( baseBeads[ i ], box_length ); }*/ triblock->tail1->beadList[ 0 ]->pbcCorrectBeadInChain( baseBead, box_length, pbc_correction_factor ); for ( idx i = 0 ; i < triblock->pec_block->length ; i ++ ) { ( triblock->pec_block->getBead( i ) )->pbcCorrectBeadInChain( triblock->tail1->beadList[ 0 ], box_length, pbc_correction_factor ); } for ( idx i = 0 ; i < triblock->tail1->length ; i++ ) { ( triblock->tail1->getBead( i ) )->pbcCorrectBeadInChain( triblock->tail1->beadList[ 0 ], box_length, pbc_correction_factor ); ( triblock->tail2->getBead( i ) )->pbcCorrectBeadInChain( triblock->tail1->beadList[ 0 ], box_length, pbc_correction_factor ); } } } // Needs to be reviewed before I write tests, not a crucical function though void TriblockMicelle::calcCenterOfMass( idx* box_length, const float& pbc_correction_factor ) { this->com->reset(); this->pbcCorrectMicelle( box_length, pbc_correction_factor ); PECTriblock* triblock = NULL; Bead *current = NULL; for ( auto chain = std::begin( this->chainList ) ; chain != std::end( this->chainList ) ; chain++ ) { triblock = ( *chain ); for ( idx i = 0 ; i < triblock->pec_block->length ; i ++ ) { current = ( triblock->pec_block->getBead( i ) ); this->com->addCoords( current->r ); } for ( idx i = 0 ; i < triblock->tail1->length ; i++ ) { current = ( triblock->tail1->getBead( i ) ); this->com->addCoords( current->r ); current = ( triblock->tail2->getBead( i ) ); this->com->addCoords( current->r ); } } int ttlBeads = this->aggreg_num * triblock->chain_length; this->com->divideCoords( &ttlBeads ); } void TriblockMicelle::unlink() { for ( auto chain = std::begin( this->chainList ); chain != std::end( this->chainList ); chain++ ) { *chain = NULL; } } TriblockMicelle::~TriblockMicelle() { this->unlink(); } #if defined( TESTING ) #include <iostream> int main() { const float pbc_correction_factor = 0.5f; std::ifstream infile( "bin_test.txt" ); idx box_length = 36; // Make two triblocks from file std::cout << "Chain1: " << std::endl; PECTriblock* chain1 = new PECTriblock( 50, 4, 58, &infile, &box_length, pbc_correction_factor ); chain1->printChain( stdout ); std::cout << ( short ) chain1->chain_length << std::endl; std::cout << "Chain2: " << std::endl; PECTriblock* chain2 = new PECTriblock( 50, 4, 58, &infile, &box_length, pbc_correction_factor ); chain2->printChain( stdout ); std::cout << ( short ) chain2->chain_length << std::endl; // Initialize two bins Bin* b1 = new Bin(); Bin* b2 = new Bin(); b1->init( NULL, 2, 0, 0, 0 ); b2->init( NULL, 2, 0, 1, 0 ); //Add tails b1->addTail( chain1->tail1 ); b1->addTail( chain1->tail2 ); b2->addTail( chain2->tail1 ); b2->addTail( chain2->tail2 ); // Make core and add bins HydrophobicCore* core1 = new HydrophobicCore(); HydrophobicCore* core2 = new HydrophobicCore(); core1->addBin( b1 ); core2->addBin( b2 ); // Test core functionality TriblockMicelle* micelle = new TriblockMicelle(); micelle->addCore( core1 ); micelle->addCore( core2 ); std::cout << "MicelleCore: " << std::endl; micelle->printMicelleCore( stdout ); if ( core1->micelle != micelle || core2->micelle != micelle ) std::cout << "Fail" << std::endl; // Test chain functionality micelle->deriveChainList(); if ( chain1->micelle != micelle || chain2->micelle != micelle ) std::cout << "Fail" << std::endl; std::cout << "Micelle: " << std::endl; micelle->printMicelle( stdout ); // Only test so far for pbcCorrectMicelle micelle->pbcCorrectMicelle( &box_length, pbc_correction_factor ); std::cout << "Micelle (corrected): " << std::endl; micelle->printMicelle( stdout ); // Test calcCenterOfMass // but its not that important of a function delete chain1; delete chain2; delete b1; delete b2; delete micelle; return 0; } #endif
30.570833
136
0.628867
brix4dayz
bccd4fe8c4ee4756a993d42341f2d3f2055306c8
3,200
hpp
C++
rds/src/simulation_marr.hpp
epfl-lasa/rds
574b3881dbaf4fdcd785dd96ba4c451928454b40
[ "MIT" ]
12
2020-08-18T09:01:50.000Z
2022-03-17T19:53:30.000Z
rds/src/simulation_marr.hpp
epfl-lasa/rds
574b3881dbaf4fdcd785dd96ba4c451928454b40
[ "MIT" ]
null
null
null
rds/src/simulation_marr.hpp
epfl-lasa/rds
574b3881dbaf4fdcd785dd96ba4c451928454b40
[ "MIT" ]
1
2021-08-25T13:12:55.000Z
2021-08-25T13:12:55.000Z
#ifndef SIMULATION_MARR_HPP #define SIMULATION_MARR_HPP // simulation MARR (multiple agents reactive robot) #include "geometry.hpp" #include "rds_4_agent.hpp" #include <RVO.h> // external official RVO2 library #include <vector> //struct StateMARR //{ // StateMARR(RVO::Simulator& rvo_sim) : rvo_sim(rvo_sim) { } //private: // RVO::Simulator& rvo_sim; //}; /* d v_orca /dt = f(x, v_orca) d x_rds /dt = g(x, v_orca) */ struct AgentMARR { AgentMARR(int id, const Geometry2D::Vec2& position, double orientation, double radius, double v_max) : m_id(id), m_position(position), m_orientation(orientation), m_radius(radius), m_v_max(v_max) { } virtual ~AgentMARR() { } virtual void computeVelocity(double time, const std::vector<AgentMARR*>& agents, const AgentMARR* robot) = 0; void stepEuler(double dt) { m_position += dt*m_cartesian_velocity; m_orientation += dt*m_angular_velocity; }; int getID() { return m_id; } void getPosition(Geometry2D::Vec2* result) { *result = m_position; } double getOrientation() { return m_orientation; } void getCartesianVelocity(Geometry2D::Vec2* result) { *result = m_cartesian_velocity; } double getAngularVelocity() { return m_angular_velocity; } virtual void getPositionAndPreferredVelocity(double time, const Geometry2D::Vec2& client_position, Geometry2D::Vec2* position_result, Geometry2D::Vec2* velocity_result) const = 0; int m_id; Geometry2D::Vec2 m_position, m_cartesian_velocity; double m_orientation, m_angular_velocity, m_radius, m_v_max; }; //struct RobotMARR //{ // void stepEuler(double dt) = 0; //}; struct SimulationMARR { SimulationMARR() : m_time(0.0), m_robot(0) { } void stepEuler(double dt); std::vector<AgentMARR*> m_agents; AgentMARR* m_robot; double m_time; RVO::RVOSimulator m_reference_rvo_simulator; }; typedef void (*IndexedVectorField)(int index, double time, const Geometry2D::Vec2& position, const AgentMARR* a, Geometry2D::Vec2* velocity_result); struct RVOAgentMARR : public AgentMARR { RVOAgentMARR(int id, const Geometry2D::Vec2& position, double orientation, double radius, double v_max, IndexedVectorField motion_law) : AgentMARR(id, position, orientation, radius, v_max), m_tau(1.f), m_delta(0.05f), m_motion_law(motion_law) { } virtual void computeVelocity(double time, const std::vector<AgentMARR*>& agents, const AgentMARR* robot); virtual void getPositionAndPreferredVelocity(double time, const Geometry2D::Vec2& client_position, Geometry2D::Vec2* position_result, Geometry2D::Vec2* velocity_result) const; RVO::RVOSimulator m_rvo_simulator; float m_tau, m_delta; IndexedVectorField m_motion_law; }; struct RDSAgentMARR : public AgentMARR { RDSAgentMARR(int id, const Geometry2D::Vec2& position, double orientation, double radius, double v_max) : AgentMARR(id, position, orientation, radius, v_max) { } virtual void computeVelocity(double time, const std::vector<AgentMARR*>& agents, const AgentMARR* robot); virtual void getPositionAndPreferredVelocity(double time, const Geometry2D::Vec2& client_position, Geometry2D::Vec2* position_result, Geometry2D::Vec2* velocity_result) const; }; //struct RobotMARR //{ // void stepEuler(double dt) = 0; //}; #endif
29.906542
135
0.756875
epfl-lasa
bccf11d17f62a85a9166f4894ffa358e13b755b9
10,126
cpp
C++
MadLibs.cpp
quorten/madlibs-hist
1b217cca5001b27aba29f914dea234f1c757287b
[ "Unlicense" ]
null
null
null
MadLibs.cpp
quorten/madlibs-hist
1b217cca5001b27aba29f914dea234f1c757287b
[ "Unlicense" ]
null
null
null
MadLibs.cpp
quorten/madlibs-hist
1b217cca5001b27aba29f914dea234f1c757287b
[ "Unlicense" ]
null
null
null
//A simple Mad Libs game which loads a random story from a file. //Later a configuration pannel may be added. #ifdef MSVC #include <io.h> #else #include <dirent.h> //POSIX compliant code #endif #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> /*#include <sys/stat.h> #include <sys/types.h>*/ using namespace std; struct CacheInfoExtra { char* storyTitle; unsigned storyAddr; unsigned storySize; }; struct CacheInfo { unsigned numStories; CacheInfoExtra* cheExtra; }; struct MadLibsStory { string titleForPrev; //When allowed to pick a story vector<string> storyFragments; vector<string> customWords; vector<unsigned> wordRefs; }; inline bool FindFiles(vector<string>& files); void AskQuestion(string qBegin, string& wordDesc); void FormatCustomWord(string& wordDesc); int main(int argc, char* argv[]) { //First find all the story files in the directory vector<string> files; if (!FindFiles(files)) { cout << "ERROR: Could not find any story files.\n"; return 1; } //Check if the story info cache is up to date /*stat* s = new stat[]; stat("strche.dat", &s); if (s.st_mtime) printf("is directory\n");*/ //Read the cache file CacheInfo* cacheInfo = new CacheInfo[files.size()]; FILE* fp = fopen("strche.dat", "rb"); for (unsigned i = 0; i < files.size(); i++) { fread(&cacheInfo[i].numStories, sizeof(cacheInfo[i].numStories), 1, fp); } //Prepare psudorandom number table srand(time(NULL)); //Compute that: unsigned totNumStories = 0; for (unsigned i = 0; i < files.size(); i++) totNumStories += cacheInfo[i].numStories; //Pick a story unsigned story; if (argc > 1) story = atoi(argv[1]); else story = rand() % totNumStories; //Reformat and store file to parse unsigned prevStories = 0; unsigned fileID; //Which story file? for (unsigned i = 0; i < files.size(); i++) { if (story < cacheInfo[i].numStories + prevStories) { story -= prevStories; fileID = i; break; } prevStories += cacheInfo[i].numStories; } //We're done with cacheInfo free(cacheInfo); //Read the whole file into memory //We have to parse the file to find out how many stories it has since it does not //have a table of contents. fp = fopen(files[fileID].c_str(), "rb"); fseek(fp, 0, SEEK_END); unsigned fileSize = ftell(fp); fseek(fp, 0, SEEK_SET); char* buffer = new char[fileSize]; fread(buffer, fileSize, 1, fp); fclose(fp); //Since we read the whole file this way, we will have to properly format newlines. string fileContents; for (unsigned i = 0; i < fileSize; i++) { if (buffer[i] != '\r') fileContents.push_back(buffer[i]); else { if (buffer[i+1] == '\n') //CR+LF i++; fileContents.push_back('\n'); } } delete []buffer; //Parse the file //We have to format three arrays: story fragments, custom words, and word references //Story fragments and word references are interleaved to create the story vector<MadLibsStory> stories; unsigned curWordRef = 0; bool inTitle = true; //The first line should be a title { //Allocate memory for the first story MadLibsStory temp; temp.storyFragments.push_back(string("")); stories.push_back(temp); } for (unsigned i = 0; i < fileContents.size(); i++) { if (fileContents[i] != '(') { for (; i < fileContents.size() && fileContents[i] != '('; i++) { //Check for end tag const string endTag("\n\nEND STORY"); bool foundEndTag = true; for (unsigned j = i, k = 0; j < i + endTag.size(); j++, k++) { if (j == fileContents.size()) { //The end of file came early foundEndTag = false; break; } if (fileContents[j] != endTag[k]) { foundEndTag = false; break; } } if (foundEndTag == true) { i += 11; if (i == fileContents.size()) goto storyEnd; else if (fileContents[i] != '\n') break; //if (fileContents[i] != '\n') i++; //Skip double newline { //Allocate memory for the next story MadLibsStory temp; temp.storyFragments.push_back(string("")); stories.push_back(temp); } //Reset proper variables curWordRef = 0; inTitle = true; goto storyEnd; } //Do the normal story fragment copy stories.back().storyFragments.back().push_back(fileContents[i]); if (inTitle == true) { if (fileContents[i] != '\n') stories.back().titleForPrev.push_back(fileContents[i]); else { inTitle = false; //if (fileContents[i+1] != '\n') //Then we should tell the user about this //We might temporarily fix it too } } } i--; storyEnd: ; } else { i++; if (fileContents[i] == '(') { //These parentheses are meant for the story content for (; i < fileContents.size() && fileContents[i] == '('; i++) stories.back().storyFragments.back().push_back(fileContents[i]); i--; } else { //We found a custom word stories.back().customWords.push_back(string("")); //Save the custom word temporarily for (; i < fileContents.size() && fileContents[i] != ')'; i++) stories.back().customWords.back().push_back(fileContents[i]); //Search for a match with this custom word and previous custom words bool foundReuse = false; for (unsigned i = 0; i < stories.back().customWords.size() - 1; i++) { if (stories.back().customWords.back() == stories.back().customWords[i]) { //We have a match. Fill in the proper word reference stories.back().wordRefs.push_back(i); //Delete reused word stories.back().customWords.pop_back(); foundReuse = true; break; } } if (foundReuse == false) { //No match found. Store reference and keep stored word stories.back().wordRefs.push_back(curWordRef); curWordRef++; } stories.back().storyFragments.push_back(string("")); } if (inTitle == true) { stories.back().titleForPrev.push_back('?'); } } } if (inTitle == true) { //We have a newline at the end of the file, but of course no story stories.pop_back(); } //Ask the words FormatCustomWord(stories[story].customWords.front()); bool sayAnotherNext = false; for (unsigned i = 0; i < stories[story].customWords.size(); i++) { if (sayAnotherNext == true) //This flag is set at the end of the loop { sayAnotherNext = false; //If the next type of word is the same type, then set the //flag so next time we say "Type another ..." if (i < stories[story].customWords.size() - 1) FormatCustomWord(stories[story].customWords[i+1]); if (i < stories[story].customWords.size() - 1 && stories[story].customWords[i] == stories[story].customWords[i+1]) sayAnotherNext = true; //Now we can change the word when we ask the question AskQuestion(string("Type another "), stories[story].customWords[i]); } else { //If the next type of word is the same type, then set the //flag so next time we say "Type another ..." if (i < stories[story].customWords.size() - 1) FormatCustomWord(stories[story].customWords[i+1]); if (i < stories[story].customWords.size() - 1 && stories[story].customWords[i] == stories[story].customWords[i+1]) sayAnotherNext = true; //If the first letter of the word is a vowel (a, e, i, o, u, not //including y), then say "Type an ..." const string accptdVowls("aeiou"); bool useAn = false; for (unsigned j = 0; j < 5; j++) { if (stories[story].customWords[i][0] == accptdVowls[j]) { useAn = true; break; } } if (useAn == true) AskQuestion(string("Type an "), stories[story].customWords[i]); //Otherwise, just say "Type a ..." else AskQuestion(string("Type a "), stories[story].customWords[i]); //cout << "Type a " << stories[story].customWords[i] << ":\n"; } } //Display the story cout << endl; for (unsigned i = 0; i < stories[story].storyFragments.size() - 1; i++) cout << stories[story].storyFragments[i] << stories[story].customWords[stories[story].wordRefs[i]]; cout << stories[story].storyFragments.back() << endl; return 0; } inline bool FindFiles(vector<string>& files) { #ifdef MSVC _finddata_t findData; intptr_t findHandle; findHandle = _findfirst("*.mlb", &findData); if (findHandle == -1) return false; files.push_back(string(findData.name)); while (_findnext(findHandle, &findData) == 0) { files.push_back(string(findData.name)); } _findclose(findHandle); sort(files.begin(), files.end()); return true; #else DIR *d = opendir("."); if (d == NULL) return false; struct dirent *de; while (de = readdir(d)) { files.push_back(string(de->d_name)); if (files.back().find(".mlb") != files.back().size() - 4) files.pop_back(); } closedir(d); if (files.size() > 0) { sort(files.begin(), files.end()); return true; } else return false; #endif } void AskQuestion(string qBegin, string& wordDesc) { string answer; cout << qBegin << wordDesc << ": "; getline(cin, answer, '\n'); wordDesc = answer; } //Erases the numeric ID from the custom word description void FormatCustomWord(string& wordDesc) { //NOTE: Here we consider it pointless to have only a //number for the word description. unsigned numBegin; bool inNumber = true; for (numBegin = wordDesc.size() - 1; numBegin > 0 && inNumber == true; numBegin--) { const string numbers("0123456789"); inNumber = false; for (unsigned j = 0; j < 10; j++) { if (numbers[j] == wordDesc[numBegin]) inNumber = true; } } numBegin += 2; //Undo the extra numBegin-- and... //Don't erase the last letter of the description wordDesc.erase(numBegin); }
26.301299
118
0.613767
quorten
bcd5e56e3950bb5a15fd853fdc9f0eef5676b254
1,414
hpp
C++
src/mge/behaviours/AbstractBehaviour.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
src/mge/behaviours/AbstractBehaviour.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
src/mge/behaviours/AbstractBehaviour.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
#ifndef ABSTRACTBEHAVIOUR_H #define ABSTRACTBEHAVIOUR_H #include "Physics/RigidBody.h" class GameObject; /** * An AbstractBehaviour allows you to attach reusable behaviours to GameObjects (Steering, rotating, billboarding, etc). * A Behaviour is set on a GameObject, which in turn passes in a reference to itself through the setOwner method. * This way we can enforce that a Behaviour can never have an owner different from the object it has been attached to. * * The concept is similar to MonoBehaviours in Unity. */ class AbstractBehaviour { public: AbstractBehaviour(); virtual ~AbstractBehaviour() = 0; //we would like to have this private and only accessible by GameObject, but this //doesnt work out for the CompositeBehaviour, we would have to declare both of them //as friends, tying this class to one of its subclasses, so design decision: //this is kept public but should not be used directly. virtual void setOwner (GameObject* pGameObject); //behaviour should be able to update itself every step and MUST be implemented virtual void update(float pStep) = 0; protected: //reference back its owner GameObject* _owner; private: //disallow copy and assignment AbstractBehaviour(const AbstractBehaviour&); AbstractBehaviour& operator=(const AbstractBehaviour&); }; #endif // ABSTRACTBEHAVIOUR_H
31.422222
120
0.730552
mtesseracttech
bcd8f37017ce4bf5caf3939556e80374a792fc27
13,273
cpp
C++
library/ltbl/LightDirectionEmission.cpp
NeroGames/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
26
2020-09-02T18:14:36.000Z
2022-02-08T18:28:36.000Z
library/ltbl/LightDirectionEmission.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
14
2020-08-30T01:37:04.000Z
2021-07-19T20:47:29.000Z
library/ltbl/LightDirectionEmission.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
6
2020-09-02T18:14:57.000Z
2021-12-31T00:32:09.000Z
#include <ltbl/LightDirectionEmission.hpp> namespace ltbl { LightDirectionEmission::LightDirectionEmission() : BaseLight() , mShape() , mCastDirection(0.f, 1.f) , mCastAngle(90.f) , mSourceRadius(5.0f) , mSourceDistance(100.0f) { } void LightDirectionEmission::setColor(const sf::Color& color) { mShape.setFillColor(color); } const sf::Color& LightDirectionEmission::getColor() const { return mShape.getFillColor(); } void LightDirectionEmission::render(const sf::View& view, sf::RenderTexture& lightTempTexture, sf::RenderTexture& antumbraTempTexture, sf::Shader& unshadowShader, const std::vector<priv::QuadtreeOccupant*>& shapes, float shadowExtension) { lightTempTexture.setView(view); lightTempTexture.clear(sf::Color::White); // Mask off light shape (over-masking - mask too much, reveal penumbra/antumbra afterwards) unsigned int shapesCount = shapes.size(); for (unsigned int i = 0; i < shapesCount; ++i) { LightShape* pLightShape = static_cast<LightShape*>(shapes[i]); if (pLightShape != nullptr && pLightShape->isTurnedOn()) { // Get boundaries std::vector<priv::Penumbra> penumbras; std::vector<int> innerBoundaryIndices; std::vector<int> outerBoundaryIndices; std::vector<sf::Vector2f> innerBoundaryVectors; std::vector<sf::Vector2f> outerBoundaryVectors; getPenumbrasDirection(penumbras, innerBoundaryIndices, innerBoundaryVectors, outerBoundaryIndices, outerBoundaryVectors, *pLightShape); if (innerBoundaryIndices.size() != 2 || outerBoundaryIndices.size() != 2) { continue; } antumbraTempTexture.clear(sf::Color::White); antumbraTempTexture.setView(view); float maxDist = 0.0f; for (unsigned j = 0; j < pLightShape->getPointCount(); j++) { maxDist = std::max(maxDist, priv::vectorMagnitude(view.getCenter() - pLightShape->getTransform().transformPoint(pLightShape->getPoint(j)))); } float totalShadowExtension = shadowExtension + maxDist; sf::ConvexShape maskShape; maskShape.setPointCount(4); maskShape.setPoint(0, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[0]))); maskShape.setPoint(1, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[1]))); maskShape.setPoint(2, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[1])) + priv::vectorNormalize(innerBoundaryVectors[1]) * totalShadowExtension); maskShape.setPoint(3, pLightShape->getTransform().transformPoint(pLightShape->getPoint(innerBoundaryIndices[0])) + priv::vectorNormalize(innerBoundaryVectors[0]) * totalShadowExtension); maskShape.setFillColor(sf::Color::Black); antumbraTempTexture.draw(maskShape); unmaskWithPenumbras(antumbraTempTexture, sf::BlendAdd, unshadowShader, penumbras, totalShadowExtension); antumbraTempTexture.display(); lightTempTexture.setView(lightTempTexture.getDefaultView()); lightTempTexture.draw(sf::Sprite(antumbraTempTexture.getTexture()), sf::BlendMultiply); lightTempTexture.setView(view); } } for (unsigned int i = 0; i < shapesCount; i++) { LightShape* pLightShape = static_cast<LightShape*>(shapes[i]); if (pLightShape->renderLightOver() && pLightShape->isTurnedOn()) { pLightShape->setColor(sf::Color::White); lightTempTexture.draw(*pLightShape); } } lightTempTexture.setView(lightTempTexture.getDefaultView()); mShape.setSize(lightTempTexture.getView().getSize()); lightTempTexture.draw(mShape, sf::BlendMultiply); lightTempTexture.display(); } void LightDirectionEmission::setCastDirection(const sf::Vector2f& castDirection) { mCastDirection = priv::vectorNormalize(castDirection); mCastAngle = priv::_radToDeg * std::atan2(mCastDirection.y, mCastDirection.x); } const sf::Vector2f& LightDirectionEmission::getCastDirection() const { return mCastDirection; } void LightDirectionEmission::setCastAngle(float angle) { mCastAngle = angle; float radAngle = angle * priv::_degToRad; mCastDirection.x = std::cos(radAngle); mCastDirection.y = std::sin(radAngle); } float LightDirectionEmission::getCastAngle() const { return mCastAngle; } void LightDirectionEmission::setSourceRadius(float radius) { mSourceRadius = radius; } float LightDirectionEmission::getSourceRadius() const { return mSourceRadius; } void LightDirectionEmission::setSourceDistance(float distance) { mSourceDistance = distance; } float LightDirectionEmission::getSourceDistance() const { return mSourceDistance; } void LightDirectionEmission::getPenumbrasDirection(std::vector<priv::Penumbra>& penumbras, std::vector<int>& innerBoundaryIndices, std::vector<sf::Vector2f>& innerBoundaryVectors, std::vector<int>& outerBoundaryIndices, std::vector<sf::Vector2f>& outerBoundaryVectors, const LightShape& shape) { const int numPoints = shape.getPointCount(); innerBoundaryIndices.reserve(2); innerBoundaryVectors.reserve(2); penumbras.reserve(2); std::vector<bool> bothEdgesBoundaryWindings; bothEdgesBoundaryWindings.reserve(2); // Calculate front and back facing sides std::vector<bool> facingFrontBothEdges; facingFrontBothEdges.reserve(numPoints); std::vector<bool> facingFrontOneEdge; facingFrontOneEdge.reserve(numPoints); for (int i = 0; i < numPoints; i++) { sf::Vector2f point = shape.getTransform().transformPoint(shape.getPoint(i)); sf::Vector2f nextPoint = shape.getTransform().transformPoint(shape.getPoint((i < numPoints - 1) ? i + 1 : 0)); sf::Vector2f perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; sf::Vector2f firstEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); sf::Vector2f secondEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); sf::Vector2f firstNextEdgeRay = nextPoint - (point - mCastDirection * mSourceDistance - perpendicularOffset); sf::Vector2f secondNextEdgeRay = nextPoint - (point - mCastDirection * mSourceDistance + perpendicularOffset); sf::Vector2f pointToNextPoint = nextPoint - point; sf::Vector2f normal = priv::vectorNormalize(sf::Vector2f(-pointToNextPoint.y, pointToNextPoint.x)); // Front facing, mark it facingFrontBothEdges.push_back((priv::vectorDot(firstEdgeRay, normal) > 0.0f && priv::vectorDot(secondEdgeRay, normal) > 0.0f) || (priv::vectorDot(firstNextEdgeRay, normal) > 0.0f && priv::vectorDot(secondNextEdgeRay, normal) > 0.0f)); facingFrontOneEdge.push_back((priv::vectorDot(firstEdgeRay, normal) > 0.0f || priv::vectorDot(secondEdgeRay, normal) > 0.0f) || priv::vectorDot(firstNextEdgeRay, normal) > 0.0f || priv::vectorDot(secondNextEdgeRay, normal) > 0.0f); } // Go through front/back facing list. Where the facing direction switches, there is a boundary for (int i = 1; i < numPoints; i++) { if (facingFrontBothEdges[i] != facingFrontBothEdges[i - 1]) { innerBoundaryIndices.push_back(i); bothEdgesBoundaryWindings.push_back(facingFrontBothEdges[i]); } } // Check looping indices separately if (facingFrontBothEdges[0] != facingFrontBothEdges[numPoints - 1]) { innerBoundaryIndices.push_back(0); bothEdgesBoundaryWindings.push_back(facingFrontBothEdges[0]); } // Go through front/back facing list. Where the facing direction switches, there is a boundary for (int i = 1; i < numPoints; i++) { if (facingFrontOneEdge[i] != facingFrontOneEdge[i - 1]) { outerBoundaryIndices.push_back(i); } } // Check looping indices separately if (facingFrontOneEdge[0] != facingFrontOneEdge[numPoints - 1]) { outerBoundaryIndices.push_back(0); } for (unsigned bi = 0; bi < innerBoundaryIndices.size(); bi++) { int penumbraIndex = innerBoundaryIndices[bi]; bool winding = bothEdgesBoundaryWindings[bi]; sf::Vector2f point = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex)); sf::Vector2f perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; sf::Vector2f firstEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); sf::Vector2f secondEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); // Add boundary vector innerBoundaryVectors.push_back(winding ? secondEdgeRay : firstEdgeRay); sf::Vector2f outerBoundaryVector = winding ? firstEdgeRay : secondEdgeRay; outerBoundaryVectors.push_back(outerBoundaryVector); // Add penumbras bool hasPrevPenumbra = false; sf::Vector2f prevPenumbraLightEdgeVector; float prevBrightness = 1.0f; while (penumbraIndex != -1) { sf::Vector2f nextPoint; int nextPointIndex; if (penumbraIndex < numPoints - 1) { nextPointIndex = penumbraIndex + 1; nextPoint = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex + 1)); } else { nextPointIndex = 0; nextPoint = shape.getTransform().transformPoint(shape.getPoint(0)); } sf::Vector2f pointToNextPoint = nextPoint - point; sf::Vector2f prevPoint; int prevPointIndex; if (penumbraIndex > 0) { prevPointIndex = penumbraIndex - 1; prevPoint = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex - 1)); } else { prevPointIndex = numPoints - 1; prevPoint = shape.getTransform().transformPoint(shape.getPoint(numPoints - 1)); } sf::Vector2f pointToPrevPoint = prevPoint - point; priv::Penumbra penumbra; penumbra._source = point; if (!winding) { penumbra._lightEdge = (hasPrevPenumbra) ? prevPenumbraLightEdgeVector : innerBoundaryVectors.back(); penumbra._darkEdge = outerBoundaryVector; penumbra._lightBrightness = prevBrightness; // Next point, check for intersection float intersectionAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(pointToNextPoint))); float penumbraAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(penumbra._darkEdge))); if (intersectionAngle < penumbraAngle) { prevBrightness = penumbra._darkBrightness = intersectionAngle / penumbraAngle; assert(prevBrightness >= 0.0f && prevBrightness <= 1.0f); penumbra._darkEdge = pointToNextPoint; penumbraIndex = nextPointIndex; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = true; prevPenumbraLightEdgeVector = penumbra._darkEdge; point = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex)); perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; firstEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); secondEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); outerBoundaryVector = secondEdgeRay; } else { penumbra._darkBrightness = 0.0f; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = false; penumbraIndex = -1; } } else // Winding = true { penumbra._lightEdge = (hasPrevPenumbra) ? prevPenumbraLightEdgeVector : innerBoundaryVectors.back(); penumbra._darkEdge = outerBoundaryVector; penumbra._lightBrightness = prevBrightness; // Next point, check for intersection float intersectionAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(pointToPrevPoint))); float penumbraAngle = std::acos(priv::vectorDot(priv::vectorNormalize(penumbra._lightEdge), priv::vectorNormalize(penumbra._darkEdge))); if (intersectionAngle < penumbraAngle) { prevBrightness = penumbra._darkBrightness = intersectionAngle / penumbraAngle; assert(prevBrightness >= 0.0f && prevBrightness <= 1.0f); penumbra._darkEdge = pointToPrevPoint; penumbraIndex = prevPointIndex; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = true; prevPenumbraLightEdgeVector = penumbra._darkEdge; point = shape.getTransform().transformPoint(shape.getPoint(penumbraIndex)); perpendicularOffset = priv::vectorNormalize({ -mCastDirection.y, mCastDirection.x }) * mSourceRadius; firstEdgeRay = point - (point - mCastDirection * mSourceDistance + perpendicularOffset); secondEdgeRay = point - (point - mCastDirection * mSourceDistance - perpendicularOffset); outerBoundaryVector = firstEdgeRay; } else { penumbra._darkBrightness = 0.0f; if (hasPrevPenumbra) { std::swap(penumbra._darkBrightness, penumbras.back()._darkBrightness); std::swap(penumbra._lightBrightness, penumbras.back()._lightBrightness); } hasPrevPenumbra = false; penumbraIndex = -1; } } penumbras.push_back(penumbra); } } } } // namespace ltbl
36.265027
293
0.736533
NeroGames
bcd971f123367cb08b61f06a14ece77ff5adea14
7,716
cpp
C++
src/Game.cpp
johnhues/ae-asteroids
6d47c1e794b060718b21230ab59b04e62633f8fb
[ "MIT" ]
null
null
null
src/Game.cpp
johnhues/ae-asteroids
6d47c1e794b060718b21230ab59b04e62633f8fb
[ "MIT" ]
null
null
null
src/Game.cpp
johnhues/ae-asteroids
6d47c1e794b060718b21230ab59b04e62633f8fb
[ "MIT" ]
null
null
null
#include "Game.h" #include "Components.h" ae::DebugLines*& GetDebugLines() { static ae::DebugLines* g_debugLines = nullptr; return g_debugLines; } void Game::Initialize() { window.Initialize( 800, 600, false, true ); window.SetTitle( "AE-Asteroids" ); render.Initialize( &window ); debugLines.Initialize( 256 ); input.Initialize( &window ); #if _AE_WINDOWS_ const char* dataDir = "../data"; #elif _AE_APPLE_ const char* dataDir = "data"; #else const char* dataDir = ""; #endif file.Initialize( dataDir, "johnhues", "AE-Asteroids" ); timeStep.SetTimeStep( 1.0f / 60.0f ); GetDebugLines() = &debugLines; shader.Initialize( kVertShader, kFragShader, nullptr, 0 ); shader.SetDepthTest( true ); shader.SetDepthWrite( true ); level0.Initialize( &file, "level0.fbx" ); cubeModel.Initialize( &file, "cube.fbx" ); shipModel.Initialize( &file, "ship.fbx" ); asteroidModel.Initialize( kAsteroidVerts, kAsteroidIndices, countof(kAsteroidVerts), countof(kAsteroidIndices) ); } void Game::Terminate() { AE_INFO( "Terminate" ); //input.Terminate(); debugLines.Terminate(); render.Terminate(); window.Terminate(); } void Game::Load() { // Level { entt::entity entity = registry.create(); Level& level = registry.emplace< Level >( entity ); level.Clear(); level.AddMesh( &level0, ae::Matrix4::Identity() ); level.AddMesh( &cubeModel, ae::Matrix4::Translation( ae::Vec3( 3.0f, 3.0f, 0.0f ) ) * ae::Matrix4::Scaling( ae::Vec3( 3.0f ) ) ); } // Ship { entt::entity entity = registry.create(); registry.emplace< Transform >( entity ); registry.emplace< Collision >( entity ); Physics& physics = registry.emplace< Physics >( entity ); physics.moveDrag = 0.7f; physics.rotationDrag = 1.7f; physics.collisionRadius = 0.7f; Ship& ship = registry.emplace< Ship >( entity ); ship.local = true; ship.speed = 10.0f; ship.rotationSpeed = 5.0f; Team& team = registry.emplace< Team >( entity ); team.teamId = TeamId::Player; registry.emplace< Shooter >( entity ); Model& model = registry.emplace< Model >( entity ); model.mesh = &shipModel; model.shader = &shader; model.color = ae::Color::PicoBlue(); localShip = entity; } // Camera { entt::entity entity = registry.create(); Transform& transform = registry.emplace< Transform >( entity ); transform.SetPosition( ae::Vec3( 0, 0, 20.0f ) ); registry.emplace< Camera >( entity ); } // // Asteroids // for ( uint32_t i = 0; i < 8; i++ ) // { // entt::entity entity = registry.create(); // // Transform& transform = registry.emplace< Transform >( entity ); // transform.SetPosition( ae::Vec3( ae::Random( -1.0f, 1.0f ), ae::Random( -1.0f, 1.0f ), 0.0f ) ); // // registry.emplace< Collision >( entity ); // // float angle = ae::Random( 0.0f, ae::TWO_PI ); // float speed = ae::Random( 0.1f, 0.7f ); // Physics& physics = registry.emplace< Physics >( entity ); // physics.vel = ae::Vec3( cosf( angle ), sinf( angle ), 0.0f ) * speed; // // registry.emplace< Asteroid >( entity ); // // Model& model = registry.emplace< Model >( entity ); // model.mesh = &asteroidModel; // model.shader = &shader; // } // Turret { entt::entity entity = registry.create(); Transform& transform = registry.emplace< Transform >( entity ); transform.SetPosition( ae::Vec3( -4.0f, 4.0f, 0.0f ) ); registry.emplace< Collision >( entity ); Physics& physics = registry.emplace< Physics >( entity ); physics.rotationDrag = 1.7f; registry.emplace< Turret >( entity ); Team& team = registry.emplace< Team >( entity ); team.teamId = TeamId::Enemy; Shooter& shooter = registry.emplace< Shooter >( entity ); shooter.fireInterval = 0.4f; Model& model = registry.emplace< Model >( entity ); model.mesh = &shipModel; model.shader = &shader; model.color = ae::Color::PicoDarkPurple(); } } void Game::Run() { AE_INFO( "Run" ); while ( !input.quit ) //while ( !input.GetState()->exit ) { input.Pump(); // Update for( auto [ entity, ship, transform, physics ] : registry.view< Ship, Transform, Physics >().each() ) { ship.Update( this, entity, transform, physics ); } for( auto [ entity, turret ] : registry.view< Turret >().each() ) { turret.Update( this, entity ); } for( auto [ entity, asteroid, transform, physics ] : registry.view< Asteroid, Transform, Physics >().each() ) { asteroid.Update( this, transform, physics ); } for( auto [ entity, shooter ] : registry.view< Shooter >().each() ) { shooter.Update( this, entity ); } for( auto [ entity, projectile ] : registry.view< Projectile >().each() ) { projectile.Update( this, entity ); } for( auto [ entity, physics, transform ]: registry.view< Physics, Transform >().each() ) { physics.Update( this, transform ); } for( auto [ entity, level ]: registry.view< Level >().each() ) { for( auto [ entity, physics, transform ]: registry.view< Physics, Transform >().each() ) { if ( physics.collisionRadius ) { physics.hit = level.Test( &transform, &physics ); } } } for( auto [ entity, camera, transform ] : registry.view< Camera, Transform >().each() ) { camera.Update( this, transform ); } uint32_t pendingKillCount = m_pendingKill.Length(); for ( uint32_t i = 0; i < pendingKillCount; i++ ) { registry.destroy( m_pendingKill.GetKey( i ) ); } m_pendingKill.Clear(); // Render render.Activate(); render.Clear( ae::Color::PicoBlack() ); auto drawView = registry.view< const Transform, const Model >(); for( auto [ entity, transform, model ]: drawView.each() ) { model.Draw( this, transform ); } if ( Level* level = registry.try_get< Level >( this->level ) ) { level->Render( this ); } //debugLines.Render( worldToNdc ); debugLines.Clear(); render.Present(); timeStep.Wait(); } } bool Game::IsOnScreen( ae::Vec3 pos ) const { float halfWidth = render.GetAspectRatio(); float halfHeight = 1.0f; if ( -halfWidth < pos.x && pos.x < halfWidth && -halfHeight < pos.y && pos.y < halfHeight ) { return true; } else { return false; } } void Game::Kill( entt::entity entity ) { m_pendingKill.Set( entity, 0 ); } entt::entity Game::SpawnProjectile( entt::entity source, ae::Vec3 offset ) { const Transform& sourceTransform = registry.get< Transform >( source ); const Team& sourceTeam = registry.get< Team >( source ); const Physics* sourcePhysics = registry.try_get< Physics >( source ); entt::entity entity = registry.create(); Transform& transform = registry.emplace< Transform >( entity ); offset = ( sourceTransform.transform * ae::Vec4( offset, 0.0f ) ).GetXYZ(); transform.SetPosition( sourceTransform.GetPosition() + offset ); transform.transform.SetRotation( sourceTransform.transform.GetRotation() ); transform.transform.SetScale( ae::Vec3( 0.25f ) ); Physics& physics = registry.emplace< Physics >( entity ); if ( sourcePhysics ) { physics.vel += sourcePhysics->vel; } physics.vel += sourceTransform.GetForward() * 15.0f; physics.collisionRadius = 0.1f; Projectile& projectile = registry.emplace< Projectile >( entity ); projectile.killTime = ae::GetTime() + 2.0f; Team& team = registry.emplace< Team >( entity ); team.teamId = sourceTeam.teamId; Model& model = registry.emplace< Model >( entity ); model.mesh = &shipModel; model.shader = &shader; switch ( sourceTeam.teamId ) { case TeamId::None: model.color = ae::Color::Gray(); break; case TeamId::Player: model.color = ae::Color::PicoYellow(); break; case TeamId::Enemy: model.color = ae::Color::PicoRed(); break; default: AE_FAIL_MSG( "Invalid team" ); break; } return entity; }
26.424658
131
0.649171
johnhues
bcda1b04a810ad7ad4182e38ffe1f791e1979b1e
238
cpp
C++
AlgorithmCpp/Leetcode题解/L017.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
AlgorithmCpp/Leetcode题解/L017.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
AlgorithmCpp/Leetcode题解/L017.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
// 根据九宫格布局输出电话号码的可能组合 // 回溯法递归求解,接收两个参数:1.当前数字已经组成的对应字符串,2.剩余的数字字符串;返回条件:剩余的字符串为空,即所有的数字都匹配完;定义一个全局list存放可能的结果,当一个分支完整地遍历之后记录结果 #include<iostream> #include<vector> #include<map> using namespace std; int main() { return 0; }
14
105
0.752101
PusenYang
bcdc7c251189be4c60918394336cc2723cf445b1
11,044
cpp
C++
src/editor/properties/TextureProperty.cpp
CounterPillow/tungsten
2428201c44f2910d1984bd40f80b0c275848e9cf
[ "Apache-2.0", "Unlicense" ]
1
2017-11-09T18:53:56.000Z
2017-11-09T18:53:56.000Z
src/editor/properties/TextureProperty.cpp
CounterPillow/tungsten
2428201c44f2910d1984bd40f80b0c275848e9cf
[ "Apache-2.0", "Unlicense" ]
null
null
null
src/editor/properties/TextureProperty.cpp
CounterPillow/tungsten
2428201c44f2910d1984bd40f80b0c275848e9cf
[ "Apache-2.0", "Unlicense" ]
null
null
null
#include "TextureProperty.hpp" #include "PropertySheet.hpp" #include "ListProperty.hpp" #include "materials/ConstantTexture.hpp" #include "materials/CheckerTexture.hpp" #include "materials/BitmapTexture.hpp" #include "materials/BladeTexture.hpp" #include "materials/DiskTexture.hpp" #include "materials/IesTexture.hpp" #include "editor/ColorPickButton.hpp" #include "editor/TextureDisplay.hpp" #include "editor/QtUtils.hpp" #include "io/TextureCache.hpp" #include "io/FileUtils.hpp" #include "io/Scene.hpp" #include <QtGui> namespace Tungsten { TextureProperty::TextureProperty(QWidget *parent, PropertySheet &sheet, std::string name, std::shared_ptr<Texture> value, bool allowNone, Scene *scene, TexelConversion conversion, bool scalarGammaCorrect, std::function<bool(std::shared_ptr<Texture> &)> setter) : _parent(parent), _sheet(sheet), _allowNone(allowNone), _name(std::move(name)), _value(std::move(value)), _setter(std::move(setter)), _scene(scene), _conversion(conversion), _currentMode(textureToMode(_value.get())), _texturePage(nullptr), _scalarGammaCorrect(scalarGammaCorrect) { buildTextureHeader(&sheet); _pageRow = sheet.rowCount(); buildTexturePage(); } void TextureProperty::buildTextureHeader(PropertySheet *sheet) { _selectProperty = sheet->addListProperty(typeList(), modeToOption(_currentMode), _name, [this](const std::string &, int option) { changeMode(optionToMode(option)); buildTexturePage(); _setter(_value); return true; }); } TextureProperty::TextureMode TextureProperty::textureToMode(Texture *tex) const { if (ConstantTexture *c = dynamic_cast<ConstantTexture *>(tex)) { if (c->value().min() == c->value().max()) return TEXTURE_SCALAR; else return TEXTURE_RGB; } else if (dynamic_cast<IesTexture *>(tex)) { return TEXTURE_IES; } else if (dynamic_cast<BitmapTexture *>(tex)) { return TEXTURE_BITMAP; } else if (dynamic_cast<CheckerTexture *>(tex)) { return TEXTURE_CHECKER; } else if (dynamic_cast<DiskTexture *>(tex)) { return TEXTURE_DISK; } else if (dynamic_cast<BladeTexture *>(tex)) { return TEXTURE_BLADE; } return TEXTURE_NONE; } std::vector<std::string> TextureProperty::typeList() { std::vector<std::string> result; if (_allowNone) result.push_back("None"); result.push_back("Scalar"); result.push_back("RGB"); result.push_back("Bitmap"); result.push_back("Checker"); result.push_back("Disk"); result.push_back("Blade"); result.push_back("IES"); return std::move(result); } void TextureProperty::buildTexturePage() { if (_texturePage) _texturePage->deleteLater(); _texturePage = new QWidget(); PropertySheet *sheet = new PropertySheet(_texturePage); buildTexturePage(sheet); sheet->setMargin(0); _texturePage->setLayout(sheet); _sheet.addWidget(_texturePage, _pageRow, 1); } void TextureProperty::buildTexturePage(PropertySheet *sheet) { if (_currentMode == TEXTURE_SCALAR) buildTexturePage(sheet, dynamic_cast<ConstantTexture *>(_value.get())); if (_currentMode == TEXTURE_RGB) buildTexturePage(sheet, dynamic_cast<ConstantTexture *>(_value.get())); if (_currentMode == TEXTURE_BITMAP) buildTexturePage(sheet, dynamic_cast<BitmapTexture *>(_value.get())); if (_currentMode == TEXTURE_CHECKER) buildTexturePage(sheet, dynamic_cast<CheckerTexture *>(_value.get())); if (_currentMode == TEXTURE_DISK) buildTexturePage(sheet, dynamic_cast<DiskTexture *>(_value.get())); if (_currentMode == TEXTURE_BLADE) buildTexturePage(sheet, dynamic_cast<BladeTexture *>(_value.get())); if (_currentMode == TEXTURE_IES) buildTexturePage(sheet, dynamic_cast<IesTexture *>(_value.get())); } void TextureProperty::buildTexturePage(PropertySheet *sheet, ConstantTexture *tex) { if (_currentMode == TEXTURE_SCALAR) { sheet->addFloatProperty(toGamma(tex->average().x()), "Value", [this, tex](float f) { tex->setValue(toLinear(f)); _setter(_value); return true; }); } else { sheet->addVectorProperty(toGamma(tex->average()), "Value", false, [this, tex](Vec3f v) { tex->setValue(toLinear(v)); _setter(_value); return true; }); } } void TextureProperty::buildTexturePage(PropertySheet *sheet, BitmapTexture *tex) { _gammaCorrect = tex->gammaCorrect(); _linear = tex->linear(); _clamp = tex->clamp(); std::string path = (!tex->path() || tex->path()->empty()) ? "" : tex->path()->absolute().asString(); sheet->addPathProperty(path, "File", _scene->path().absolute().asString(), "Open bitmap...", "Image files (*.png *.jpg *.hdr *.pfm *.tga *.bmp *.psd *.gif *.pic *.jpeg" #if OPENEXR_AVAILABLE " *.exr" #endif ")", [this, tex](const std::string &path) { loadBitmap(_scene->fetchResource(path)); return true; }); sheet->addBoolProperty(tex->gammaCorrect(), "Gamma correct", [this, tex](bool b) { _gammaCorrect = b; updateBitmapFlags(); return true; }); sheet->addBoolProperty(tex->linear(), "Interpolate", [this, tex](bool b) { _linear = b; updateBitmapFlags(); return true; }); sheet->addBoolProperty(tex->clamp(), "Clamp UVs", [this, tex](bool b) { _clamp = b; updateBitmapFlags(); return true; }); buildTextureDisplay(sheet); } void TextureProperty::buildTexturePage(PropertySheet *sheet, CheckerTexture *tex) { sheet->addVectorProperty(tex->onColor(), "On Color", false, [this, tex](Vec3f v) { tex->setOnColor(v); updateTexture(); return true; }); sheet->addVectorProperty(tex->offColor(), "Off Color", false, [this, tex](Vec3f v) { tex->setOffColor(v); updateTexture(); return true; }); sheet->addIntProperty(tex->resU(), 1, 9999, "Width", [this, tex](int i) { tex->setResU(i); updateTexture(); return true; }); sheet->addIntProperty(tex->resV(), 1, 9999, "Height", [this, tex](int i) { tex->setResV(i); updateTexture(); return true; }); buildTextureDisplay(sheet); } void TextureProperty::buildTexturePage(PropertySheet *sheet, BladeTexture *tex) { sheet->addIntProperty(tex->numBlades(), 3, 999, "Number of Blades", [this, tex](int i) { tex->setNumBlades(i); updateTexture(); return true; }); sheet->addFloatProperty(Angle::radToDeg(tex->angle()), "Blade Angle", [this, tex](float f) { tex->setAngle(Angle::degToRad(f)); updateTexture(); return true; }); buildTextureDisplay(sheet); } void TextureProperty::buildTexturePage(PropertySheet *sheet, DiskTexture * /*tex*/) { buildTextureDisplay(sheet); } void TextureProperty::buildTexturePage(PropertySheet *sheet, IesTexture *tex) { _resolution = tex->resolution(); std::string path = (!tex->path() || tex->path()->empty()) ? "" : tex->path()->absolute().asString(); sheet->addPathProperty(path, "File", _scene->path().absolute().asString(), "Open IES profile...", "IES profiles (*.ies)", [this, tex](const std::string &path) { loadProfile(_scene->fetchResource(path)); return true; }); sheet->addIntProperty(tex->resolution(), 32, 8192, "Resolution", [this, tex](int value) { _resolution = value; updateProfileFlags(); return true; }); buildTextureDisplay(sheet); } void TextureProperty::buildTextureDisplay(PropertySheet *sheet) { _bitmapDisplay = new TextureDisplay(200, 200, _texturePage); _bitmapDisplay->changeTexture(_value.get()); sheet->addWidget(_bitmapDisplay, sheet->rowCount(), 0, 1, 2, Qt::AlignHCenter); } std::shared_ptr<Texture> TextureProperty::instantiateTexture(TextureMode mode) { switch (mode) { case TEXTURE_NONE: return nullptr; case TEXTURE_SCALAR: return std::make_shared<ConstantTexture>(); case TEXTURE_RGB: return std::make_shared<ConstantTexture>(); case TEXTURE_BITMAP: return std::make_shared<BitmapTexture>(); case TEXTURE_CHECKER: return std::make_shared<CheckerTexture>(); case TEXTURE_DISK: return std::make_shared<DiskTexture>(); case TEXTURE_BLADE: return std::make_shared<BladeTexture>(); case TEXTURE_IES: return std::make_shared<IesTexture>(); default: return nullptr; } } float TextureProperty::toLinear(float f) const { return _scalarGammaCorrect ? std::pow(f, 2.2f) : f; } Vec3f TextureProperty::toLinear(Vec3f v) const { return _scalarGammaCorrect ? std::pow(v, 2.2f) : v; } float TextureProperty::toGamma(float f) const { return _scalarGammaCorrect ? std::pow(f, 1.0f/2.2f) : f; } Vec3f TextureProperty::toGamma(Vec3f v) const { return _scalarGammaCorrect ? std::pow(v, 1.0f/2.2f) : v; } void TextureProperty::changeMode(TextureMode mode) { if (mode == TEXTURE_SCALAR && _currentMode == TEXTURE_RGB) { ConstantTexture *tex = dynamic_cast<ConstantTexture *>(_value.get()); tex->setValue(tex->value().x()); } else if (!(mode == TEXTURE_RGB && _currentMode == TEXTURE_SCALAR)) { _value = instantiateTexture(mode); if (mode == TEXTURE_BITMAP || mode == TEXTURE_IES) _value->loadResources(); } _setter(_value); _currentMode = mode; } int TextureProperty::modeToOption(TextureMode mode) { return static_cast<int>(mode) - (_allowNone ? 0 : 1); } TextureProperty::TextureMode TextureProperty::optionToMode(int option) { return static_cast<TextureMode>(_allowNone ? option : option + 1); } void TextureProperty::loadBitmap(PathPtr path) { std::shared_ptr<BitmapTexture> tex = _scene->textureCache()->fetchTexture( path, _conversion, _gammaCorrect, _linear, _clamp); tex->loadResources(); std::shared_ptr<Texture> base(tex); if (_setter(base)) { _value = std::move(base); buildTexturePage(); } } void TextureProperty::updateBitmapFlags() { loadBitmap(dynamic_cast<BitmapTexture *>(_value.get())->path()); } void TextureProperty::loadProfile(PathPtr path) { std::shared_ptr<IesTexture> tex = _scene->textureCache()->fetchIesTexture(std::move(path), _resolution); tex->loadResources(); std::shared_ptr<Texture> base(tex); if (_setter(base)) { _value = std::move(base); buildTexturePage(); } } void TextureProperty::updateProfileFlags() { loadProfile(dynamic_cast<IesTexture *>(_value.get())->path()); } void TextureProperty::updateTexture() { _setter(_value); _bitmapDisplay->changeTexture(_value.get()); } void TextureProperty::setVisible(bool visible) { _selectProperty->setVisible(visible); _texturePage->setVisible(visible); } }
31.464387
133
0.656465
CounterPillow
bce1fe7197d317fbf312a52f653dfad6f5e5b112
737
cpp
C++
codility/07_Brackets.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
codility/07_Brackets.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
codility/07_Brackets.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(string &S) { // write your code in C++11 (g++ 4.8.2) int N = S.size(); if (N == 0) return 1; if (N % 2 == 1) return 0; string stack; for (char c : S) { if (c == '(' || c == '[' || c == '{') { stack.push_back(c); } else { if (stack.empty()) return 0; if ((c == ')' && stack.back() != '(') || (c == ']' && stack.back() != '[') || (c == '}' && stack.back() != '{')) return 0; stack.pop_back(); } } return stack.empty() ? 1 : 0; }
27.296296
60
0.428765
longztian
bce3d1f9ce7a835ef9367f925e156817c9809789
4,644
hpp
C++
include/boost/hana/ext/std/ratio.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
2
2015-12-06T05:10:14.000Z
2021-09-05T21:48:27.000Z
include/boost/hana/ext/std/ratio.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
null
null
null
include/boost/hana/ext/std/ratio.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
1
2017-06-06T10:50:17.000Z
2017-06-06T10:50:17.000Z
/*! @file Adapts `std::ratio` for use with Hana. @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_EXT_STD_RATIO_HPP #define BOOST_HANA_EXT_STD_RATIO_HPP #include <boost/hana/bool.hpp> #include <boost/hana/concept/integral_constant.hpp> #include <boost/hana/core/when.hpp> #include <boost/hana/fwd/core/convert.hpp> #include <boost/hana/fwd/core/tag_of.hpp> #include <boost/hana/fwd/div.hpp> #include <boost/hana/fwd/equal.hpp> #include <boost/hana/fwd/less.hpp> #include <boost/hana/fwd/minus.hpp> #include <boost/hana/fwd/mod.hpp> #include <boost/hana/fwd/mult.hpp> #include <boost/hana/fwd/one.hpp> #include <boost/hana/fwd/plus.hpp> #include <boost/hana/fwd/zero.hpp> #include <cstdint> #include <ratio> #include <type_traits> namespace boost { namespace hana { namespace ext { namespace std { struct ratio_tag; }} template <std::intmax_t num, std::intmax_t den> struct tag_of<std::ratio<num, den>> { using type = ext::std::ratio_tag; }; ////////////////////////////////////////////////////////////////////////// // Conversion from IntegralConstants ////////////////////////////////////////////////////////////////////////// template <typename C> struct to_impl<ext::std::ratio_tag, C, when< hana::IntegralConstant<C>::value >> { template <typename N> static constexpr auto apply(N const&) { return std::ratio<N::value>{}; } }; ////////////////////////////////////////////////////////////////////////// // Comparable ////////////////////////////////////////////////////////////////////////// template <> struct equal_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr auto apply(R1 const&, R2 const&) { return hana::bool_c<std::ratio_equal<R1, R2>::value>; } }; ////////////////////////////////////////////////////////////////////////// // Orderable ////////////////////////////////////////////////////////////////////////// template <> struct less_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr auto apply(R1 const&, R2 const&) { return hana::bool_c<std::ratio_less<R1, R2>::value>; } }; ////////////////////////////////////////////////////////////////////////// // Monoid ////////////////////////////////////////////////////////////////////////// template <> struct plus_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_add<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; template <> struct zero_impl<ext::std::ratio_tag> { static constexpr std::ratio<0> apply() { return {}; } }; ////////////////////////////////////////////////////////////////////////// // Group ////////////////////////////////////////////////////////////////////////// template <> struct minus_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_subtract<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; ////////////////////////////////////////////////////////////////////////// // Ring ////////////////////////////////////////////////////////////////////////// template <> struct mult_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_multiply<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; template <> struct one_impl<ext::std::ratio_tag> { static constexpr std::ratio<1> apply() { return {}; } }; ////////////////////////////////////////////////////////////////////////// // EuclideanRing ////////////////////////////////////////////////////////////////////////// template <> struct div_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio_divide<R1, R2> apply(R1 const&, R2 const&) { return {}; } }; template <> struct mod_impl<ext::std::ratio_tag, ext::std::ratio_tag> { template <typename R1, typename R2> static constexpr std::ratio<0> apply(R1 const&, R2 const&) { return {}; } }; }} // end namespace boost::hana #endif // !BOOST_HANA_EXT_STD_RATIO_HPP
34.4
80
0.48385
qicosmos