hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
fdb5125236d3c10d247c2e357d5109271e5b1c68
1,334
hpp
C++
husky-sql/rexnode/aggregate_call.hpp
Alice3150/husky-sql
40dc95b5543c079bb4ab070fca2ac2a287514333
[ "Apache-2.0" ]
null
null
null
husky-sql/rexnode/aggregate_call.hpp
Alice3150/husky-sql
40dc95b5543c079bb4ab070fca2ac2a287514333
[ "Apache-2.0" ]
null
null
null
husky-sql/rexnode/aggregate_call.hpp
Alice3150/husky-sql
40dc95b5543c079bb4ab070fca2ac2a287514333
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <string> #include <memory> #include "husky-sql/rexnode/aggregators/abstract_aggregator.hpp" namespace husky { namespace sql { class AggregateCall { public: AggregateCall() { } ~AggregateCall() { } /* setters and getters*/ inline void set_arguments(const std::vector<int> & args) { arguments_ = args; } inline void set_function_name(const std::string & func_name) { function_name_ = func_name; } inline void set_aggregate_name(const std::string & agg_name) { aggregate_name_ = agg_name; } inline void set_datatype(const std::string & datatype) { datatype_ = datatype; } inline const std::vector<int> & get_arguments() const { return arguments_; } inline const std::string get_function_name() const { return function_name_; } inline const std::string get_aggregate_name() const { return aggregate_name_; } inline const std::string get_datatype() const { return datatype_; } inline int get_arguments_size() const { return arguments_.size(); } std::unique_ptr<AbstractAggregator> get_aggregator(); private: std::vector<int> arguments_; /* refers to input field index*/ std::string function_name_; std::string aggregate_name_; std::string datatype_; /* output datatype */ }; } // namespace sql } // namespace husky
34.205128
95
0.712894
[ "vector" ]
fdb5b851ded3189969fc4282a080f6bbeb4fddd3
75,857
cc
C++
tensorstore/array_test.cc
virenjain/tensorstore
a5c302615b831ad228be7cd82bb274606aeac404
[ "BSD-2-Clause" ]
2
2022-01-07T16:49:11.000Z
2022-01-07T16:49:12.000Z
tensorstore/array_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
null
null
null
tensorstore/array_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2020 The TensorStore Authors // // 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 "tensorstore/array.h" #include <random> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/random/bit_gen_ref.h" #include "absl/random/random.h" #include <nlohmann/json.hpp> #include "tensorstore/box.h" #include "tensorstore/index.h" #include "tensorstore/index_space/index_transform_testutil.h" #include "tensorstore/internal/data_type_random_generator.h" #include "tensorstore/internal/test_util.h" #include "tensorstore/serialization/batch.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/test_util.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" #include "tensorstore/util/str_cat.h" /// TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY behaves similarly to /// `EXPECT_DEBUG_DEATH` except that `stmt` is not executed when not in debug /// mode. /// /// This is useful in cases where `stmt` would result in undefined behavior when /// not in debug mode, e.g. because it is intended to `assert` statements /// designed to catch precondition violations. #ifdef NDEBUG #define TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY(stmt, pattern) #else #define TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY(stmt, pattern) \ EXPECT_DEATH(stmt, pattern) #endif namespace { using tensorstore::Array; using tensorstore::ArrayIterateResult; using tensorstore::ArrayOriginKind; using tensorstore::ArrayView; using tensorstore::BoxView; using tensorstore::BroadcastArray; using tensorstore::c_order; using tensorstore::container; using tensorstore::ContainerKind; using tensorstore::ContiguousLayoutOrder; using tensorstore::DimensionIndex; using tensorstore::dtype_v; using tensorstore::dynamic_rank; using tensorstore::ElementPointer; using tensorstore::fortran_order; using tensorstore::Index; using tensorstore::kInfIndex; using tensorstore::kInfSize; using tensorstore::MakeArray; using tensorstore::MakeArrayView; using tensorstore::MakeCopy; using tensorstore::MakeOffsetArray; using tensorstore::MakeScalarArrayView; using tensorstore::MatchesStatus; using tensorstore::offset_origin; using tensorstore::SharedArray; using tensorstore::SharedArrayView; using tensorstore::SharedSubArray; using tensorstore::span; using tensorstore::StaticCast; using tensorstore::StaticDataTypeCast; using tensorstore::StaticRankCast; using tensorstore::StrCat; using tensorstore::StridedLayout; using tensorstore::SubArray; using tensorstore::SubArrayStaticRank; using tensorstore::unchecked; using tensorstore::ValidateShapeBroadcast; using tensorstore::view; using tensorstore::zero_origin; using tensorstore::serialization::DecodeBatch; using tensorstore::serialization::EncodeBatch; using tensorstore::serialization::SerializationRoundTrip; using tensorstore::serialization::TestSerializationRoundTrip; using testing::ElementsAre; namespace array_metafunctions_tests { using tensorstore::IsArrayExplicitlyConvertible; static_assert(IsArrayExplicitlyConvertible<int, dynamic_rank, zero_origin, const int, 2, zero_origin>::value, ""); static_assert( IsArrayExplicitlyConvertible<const void, dynamic_rank, zero_origin, const int, 2, zero_origin>::value, ""); static_assert( IsArrayExplicitlyConvertible<const void, dynamic_rank, zero_origin, const int, 2, offset_origin>::value, ""); static_assert( !IsArrayExplicitlyConvertible<const void, dynamic_rank, offset_origin, const int, 2, zero_origin>::value, ""); static_assert( !IsArrayExplicitlyConvertible<const void, dynamic_rank, offset_origin, const void, dynamic_rank, zero_origin>::value, ""); static_assert(!IsArrayExplicitlyConvertible<const void, 2, zero_origin, const void, 3, zero_origin>::value, ""); static_assert(!IsArrayExplicitlyConvertible<const int, 2, zero_origin, const float, 2, zero_origin>::value, ""); } // namespace array_metafunctions_tests namespace subarray_ref_tests { static_assert(SubArrayStaticRank<dynamic_rank, span<const Index, 2>>::value == dynamic_rank, ""); static_assert(SubArrayStaticRank<5, span<const Index>>::value == dynamic_rank, ""); static_assert(SubArrayStaticRank<5, span<const Index, 3>>::value == 2, ""); } // namespace subarray_ref_tests namespace strided_array_size_tests { // Just a shared_ptr static_assert(sizeof(SharedArray<float, 0>) == sizeof(void*) * 2, ""); // shared_ptr + 2 Index values static_assert(sizeof(SharedArray<float, 1>) == (sizeof(void*) * 4), ""); // shared_ptr + DataType static_assert(sizeof(SharedArray<void, 0>) == (sizeof(void*) * 3), ""); // shared_ptr + DataType + 2 Index values static_assert(sizeof(SharedArray<void, 1>) == (sizeof(void*) * 5), ""); // shared_ptr + DataType + 1 DimensionIndex + 1 Index pointer static_assert(sizeof(SharedArray<void>) == (sizeof(void*) * 5), ""); // Just a raw pointer. static_assert(sizeof(ArrayView<float, 0>) == sizeof(void*), ""); // raw pointer + 2 Index pointers + 1 DimensionIndex static_assert(sizeof(ArrayView<float>) == sizeof(void*) * 4, ""); // raw pointer + DataType + 2 Index pointers + 1 DimensionIndex static_assert(sizeof(ArrayView<void>) == sizeof(void*) * 5, ""); // raw pointer + 2 Index pointers static_assert(sizeof(ArrayView<float, 1>) == sizeof(void*) * 3, ""); // raw pointer + DataType + 2 Index pointers static_assert(sizeof(ArrayView<void, 1>) == sizeof(void*) * 4, ""); // raw pointer + DataType static_assert(sizeof(ArrayView<void, 0>) == sizeof(void*) * 2, ""); } // namespace strided_array_size_tests namespace make_array_ref_tests { TEST(MakeArrayViewTest, Scalar) { int value = 3; auto result = MakeScalarArrayView(value); static_assert(std::is_same<decltype(result), ArrayView<int, 0>>::value, ""); EXPECT_EQ(&value, result.data()); } TEST(MakeArrayViewTest, Span) { std::vector<int> values{1, 2, 3}; auto result = MakeArrayView(values); static_assert(std::is_same<decltype(result), SharedArray<int, 1>>::value, ""); EXPECT_EQ(values.data(), result.data()); EXPECT_EQ(StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {3}), result.layout()); EXPECT_EQ(1, result(0)); EXPECT_EQ(2, result(1)); EXPECT_EQ(3, result(2)); } // Test calls to MakeArrayView with a braced list. static_assert(std::is_same<ArrayView<const int, 1>, decltype(MakeArrayView({1, 2, 3}))>::value, ""); static_assert( std::is_same<ArrayView<const int, 2>, decltype(MakeArrayView({{1, 2, 3}, {4, 5, 6}}))>::value, ""); static_assert( std::is_same<ArrayView<const int, 3>, decltype(MakeArrayView({{{1, 2, 3}}, {{4, 5, 6}}}))>::value, ""); static_assert( std::is_same<ArrayView<const int, 4>, decltype(MakeArrayView({{{{1, 2, 3}}, {{4, 5, 6}}}}))>::value, ""); static_assert(std::is_same<ArrayView<const int, 5>, decltype(MakeArrayView({{{{{1, 2, 3}}, {{4, 5, 6}}}}}))>::value, ""); static_assert(std::is_same<ArrayView<const int, 6>, decltype(MakeArrayView({{{{{{1, 2, 3}}, {{4, 5, 6}}}}}}))>::value, ""); TEST(MakeArrayViewTest, Rank1Array) { int values[] = {1, 2, 3}; const int cvalues[] = {1, 2, 3}; auto result = MakeArrayView(values); auto cresult = MakeArrayView(cvalues); static_assert(std::is_same<decltype(result), ArrayView<int, 1>>::value, ""); static_assert(std::is_same<decltype(cresult), ArrayView<const int, 1>>::value, ""); EXPECT_EQ(&values[0], result.data()); EXPECT_EQ(&cvalues[0], cresult.data()); auto layout = StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {3}); EXPECT_EQ(layout, result.layout()); EXPECT_EQ(layout, cresult.layout()); EXPECT_EQ(2, result(1)); } TEST(MakeArrayViewTest, Rank2Array) { int values[2][3] = {{1, 2, 3}, {4, 5, 6}}; const int cvalues[2][3] = {{1, 2, 3}, {4, 5, 6}}; auto result = MakeArrayView(values); auto cresult = MakeArrayView(cvalues); static_assert(std::is_same<decltype(result), ArrayView<int, 2>>::value, ""); static_assert(std::is_same<decltype(cresult), ArrayView<const int, 2>>::value, ""); EXPECT_EQ(&values[0][0], result.data()); EXPECT_EQ(&cvalues[0][0], cresult.data()); auto layout = StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {2, 3}); EXPECT_EQ(layout, result.layout()); EXPECT_EQ(layout, cresult.layout()); EXPECT_EQ(6, result(1, 2)); } TEST(MakeArrayViewTest, Rank3Array) { int values[1][2][3] = {{{1, 2, 3}, {4, 5, 6}}}; const int cvalues[1][2][3] = {{{1, 2, 3}, {4, 5, 6}}}; auto result = MakeArrayView(values); auto cresult = MakeArrayView(cvalues); static_assert(std::is_same<decltype(result), ArrayView<int, 3>>::value, ""); static_assert(std::is_same<decltype(cresult), ArrayView<const int, 3>>::value, ""); EXPECT_EQ(&values[0][0][0], result.data()); EXPECT_EQ(&cvalues[0][0][0], cresult.data()); auto layout = StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {1, 2, 3}); EXPECT_EQ(layout, result.layout()); EXPECT_EQ(layout, cresult.layout()); EXPECT_EQ(6, result(0, 1, 2)); } TEST(MakeArrayViewTest, Rank4Array) { int values[1][1][2][3] = {{{{1, 2, 3}, {4, 5, 6}}}}; const int cvalues[1][1][2][3] = {{{{1, 2, 3}, {4, 5, 6}}}}; auto result = MakeArrayView(values); auto cresult = MakeArrayView(cvalues); static_assert(std::is_same<decltype(result), ArrayView<int, 4>>::value, ""); static_assert(std::is_same<decltype(cresult), ArrayView<const int, 4>>::value, ""); EXPECT_EQ(&values[0][0][0][0], result.data()); auto layout = StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {1, 1, 2, 3}); EXPECT_EQ(layout, result.layout()); EXPECT_EQ(layout, cresult.layout()); EXPECT_EQ(6, result(0, 0, 1, 2)); } TEST(MakeArrayViewTest, Rank5Array) { int values[1][1][1][2][3] = {{{{{1, 2, 3}, {4, 5, 6}}}}}; const int cvalues[1][1][1][2][3] = {{{{{1, 2, 3}, {4, 5, 6}}}}}; auto result = MakeArrayView(values); auto cresult = MakeArrayView(cvalues); static_assert(std::is_same<decltype(result), ArrayView<int, 5>>::value, ""); static_assert(std::is_same<decltype(cresult), ArrayView<const int, 5>>::value, ""); EXPECT_EQ(&values[0][0][0][0][0], result.data()); auto layout = StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {1, 1, 1, 2, 3}); EXPECT_EQ(layout, result.layout()); EXPECT_EQ(layout, cresult.layout()); EXPECT_EQ(6, result(0, 0, 0, 1, 2)); } TEST(MakeArrayViewTest, Rank6Array) { int values[1][1][1][2][3][1] = {{{{{{1}, {2}, {3}}, {{4}, {5}, {6}}}}}}; const int cvalues[1][1][1][2][3][1] = { {{{{{1}, {2}, {3}}, {{4}, {5}, {6}}}}}}; auto result = MakeArrayView(values); auto cresult = MakeArrayView(cvalues); static_assert(std::is_same<decltype(result), ArrayView<int, 6>>::value, ""); static_assert(std::is_same<decltype(cresult), ArrayView<const int, 6>>::value, ""); EXPECT_EQ(&values[0][0][0][0][0][0], result.data()); EXPECT_EQ(&cvalues[0][0][0][0][0][0], cresult.data()); auto layout = StridedLayout(ContiguousLayoutOrder::c, sizeof(int), {1, 1, 1, 2, 3, 1}); EXPECT_EQ(layout, result.layout()); EXPECT_EQ(layout, cresult.layout()); EXPECT_EQ(6, result(0, 0, 0, 1, 2, 0)); } } // namespace make_array_ref_tests namespace array_conversion_tests { TEST(ArrayViewTest, ConstructDefault) { { ArrayView<int> p; EXPECT_EQ(0, p.rank()); EXPECT_EQ(nullptr, p.data()); } { ArrayView<void> p; EXPECT_EQ(0, p.rank()); EXPECT_EQ(nullptr, p.data()); EXPECT_FALSE(p.dtype().valid()); } } TEST(ArrayViewTest, ConstructAndAssign) { static_assert( !std::is_convertible<ArrayView<float>, ArrayView<float, 2>>::value, ""); static_assert( !std::is_convertible<ArrayView<float, 2>, ArrayView<int, 2>>::value, ""); static_assert(!std::is_constructible<ArrayView<float, 2>, ArrayView<const float, 2>>::value, ""); static_assert( !std::is_constructible<ArrayView<float, 2>, ArrayView<float, 3>>::value, ""); static_assert(!std::is_assignable<ArrayView<float, 2>, ArrayView<const float, 2>>::value, ""); static_assert( !std::is_assignable<ArrayView<float, 2>, ArrayView<float, 3>>::value, ""); static_assert( !std::is_assignable<ArrayView<float, 2>, ArrayView<int, 2>>::value, ""); static_assert( !std::is_convertible<ArrayView<void, 2>, ArrayView<float, 2>>::value, ""); float data[2][3] = {{1, 2, 3}, {4, 5, 6}}; ArrayView<float, 2> a = MakeArrayView(data); ArrayView<float> a1 = a; EXPECT_EQ(a.data(), a1.data()); EXPECT_EQ(a.layout(), a1.layout()); ArrayView<void> a2 = a1; EXPECT_EQ(a.data(), a2.data()); EXPECT_EQ(a.layout(), a2.layout()); EXPECT_EQ(dtype_v<float>, a2.dtype()); { auto a3 = StaticDataTypeCast<float>(a2).value(); static_assert(std::is_same<decltype(a3), ArrayView<float>>::value, ""); EXPECT_EQ(a.data(), a3.data()); EXPECT_EQ(a.layout(), a3.layout()); } { ArrayView<float, 2> a4 = StaticCast<ArrayView<float, 2>>(a2).value(); EXPECT_EQ(a.data(), a4.data()); EXPECT_EQ(a.layout(), a4.layout()); } { ArrayView<void, 2> a5(a.element_pointer(), a.layout()); EXPECT_EQ(a.data(), a5.data()); EXPECT_EQ(a.layout(), a5.layout()); EXPECT_EQ(dtype_v<float>, a5.dtype()); } { ArrayView<float, 2> a6; a6 = a; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } static_assert(!std::is_assignable<ArrayView<float, 2>, ArrayView<float>>(), ""); static_assert(!std::is_assignable<ArrayView<float, 2>, ArrayView<void>>(), ""); { ArrayView<float> a6; a6 = a; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } { ArrayView<float> a6; a6 = a1; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } static_assert(!std::is_assignable<ArrayView<float>, ArrayView<void>>(), ""); { ArrayView<const void, 2> a6; a6 = a; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } static_assert( !std::is_assignable<ArrayView<const void, 2>, ArrayView<float>>(), ""); static_assert( !std::is_assignable<ArrayView<const void, 2>, ArrayView<void>>(), ""); /// Test UnownedToShared array conversion. { SharedArray<void> a3_arr(UnownedToShared(a2)); EXPECT_EQ(a2.element_pointer(), a3_arr.element_pointer()); EXPECT_EQ(a2.layout(), a3_arr.layout()); auto a4_ref = StaticCast<ArrayView<float>>(a3_arr).value(); EXPECT_EQ(a2.element_pointer(), a4_ref.element_pointer()); EXPECT_EQ(a2.layout(), a4_ref.layout()); } } TEST(ArrayViewTest, StaticCast) { float data[2][3] = {{1, 2, 3}, {4, 5, 6}}; ArrayView<void> a2 = MakeArrayView(data); SharedArray<void> a3(UnownedToShared(a2)); EXPECT_THAT( (StaticCast<ArrayView<float, 3>>(a2)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot cast array with data type of float32 and rank of 2 " "to array with data type of float32 and rank of 3")); EXPECT_THAT( (StaticCast<ArrayView<void, 3>>(a2)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot cast array with data type of float32 and rank of 2 " "to array with dynamic data type and rank of 3")); EXPECT_THAT( (StaticCast<ArrayView<std::int32_t, 2>>(a2)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot cast array with data type of float32 and rank of 2 " "to array with data type of int32 and rank of 2")); EXPECT_THAT( (StaticCast<ArrayView<std::int32_t>>(a2)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot cast array with data type of float32 and rank of 2 " "to array with data type of int32 and dynamic rank")); EXPECT_THAT( (StaticCast<ArrayView<std::int32_t>>(a3)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot cast array with data type of float32 and rank of 2 " "to array with data type of int32 and dynamic rank")); } TEST(SharedArrayTest, ConstructAndAssign) { static_assert( !std::is_convertible<SharedArray<float>, SharedArray<float, 2>>::value, ""); static_assert(!std::is_convertible<const SharedArray<float>&, SharedArray<float, 2>>::value, ""); static_assert( !std::is_convertible<SharedArray<float, 2>, SharedArray<int, 2>>::value, ""); static_assert(!std::is_constructible<SharedArray<float, 2>, SharedArray<const float, 2>>::value, ""); static_assert( !std::is_constructible<SharedArray<float, 2>, const SharedArray<const float, 2>&>::value, ""); static_assert(!std::is_constructible<SharedArray<float, 2>, SharedArray<float, 3>>::value, ""); static_assert(!std::is_assignable<SharedArray<float, 2>, SharedArray<const float, 2>>::value, ""); static_assert( !std::is_assignable<SharedArray<float, 2>, SharedArray<float, 3>>::value, ""); static_assert( !std::is_assignable<SharedArray<float, 2>, SharedArray<int, 2>>::value, ""); static_assert(!std::is_assignable<SharedArray<float, 2>, const SharedArray<int, 2>&>::value, ""); static_assert( !std::is_convertible<SharedArray<void, 2>, SharedArray<float, 2>>::value, ""); static_assert( !std::is_convertible<SharedArray<void, 2>, SharedArray<float, 2>>::value, ""); float data[2][3] = {{1, 2, 3}, {4, 5, 6}}; ArrayView<float, 2> a_ref = MakeArrayView(data); SharedArray<float, 2> a(UnownedToShared(a_ref)); EXPECT_EQ(a_ref.data(), a.data()); EXPECT_EQ(a_ref.layout(), a.layout()); SharedArray<float> a1(a); EXPECT_EQ(a.data(), a1.data()); EXPECT_EQ(a.layout(), a1.layout()); SharedArray<void> a2 = a1; EXPECT_EQ(a.data(), a2.data()); EXPECT_EQ(a.layout(), a2.layout()); EXPECT_EQ(dtype_v<float>, a2.dtype()); { SharedArray<float> a3 = StaticDataTypeCast<float>(a2).value(); EXPECT_EQ(a.data(), a3.data()); EXPECT_EQ(a.layout(), a3.layout()); } { SharedArray<float, 2> a4 = StaticCast<SharedArray<float, 2>>(a2).value(); EXPECT_EQ(a.data(), a4.data()); EXPECT_EQ(a.layout(), a4.layout()); } { SharedArray<void, 2> a5(a.element_pointer(), a.layout()); EXPECT_EQ(a.data(), a5.data()); EXPECT_EQ(a.layout(), a5.layout()); EXPECT_EQ(dtype_v<float>, a5.dtype()); } { SharedArray<float, 2> a6; a6 = a; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } static_assert( !std::is_assignable<SharedArray<float, 2>, SharedArray<float>>(), ""); static_assert(!std::is_assignable<SharedArray<float, 2>, SharedArray<void>>(), ""); { SharedArray<float> a6; a6 = a; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } { SharedArray<float> a6; a6 = a1; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } static_assert(!std::is_assignable<SharedArray<float>, SharedArray<void>>(), ""); { SharedArray<const void, 2> a6; a6 = a; EXPECT_EQ(a.data(), a6.data()); EXPECT_EQ(a.layout(), a6.layout()); EXPECT_EQ(dtype_v<float>, a6.dtype()); } static_assert( !std::is_assignable<SharedArray<const void, 2>, SharedArray<void>>(), ""); static_assert( !std::is_assignable<SharedArray<const void, 2>, SharedArray<float>>(), ""); static_assert( !std::is_assignable<SharedArray<float, 2>, SharedArray<float>>(), ""); static_assert(!std::is_assignable<SharedArray<float, 2>, ArrayView<float>>(), ""); // Construct rank-0 array from just a pointer. { auto data = std::make_shared<float>(2.0f); SharedArray<float, 0> a7(data); EXPECT_EQ(data.get(), a7.data()); EXPECT_EQ(0, a7.rank()); EXPECT_EQ(2, a7()); } // Move construct and assign. { auto data = std::make_shared<float>(2.0f); SharedArray<float> a7( data, StridedLayout(ContiguousLayoutOrder::c, sizeof(float), {1})); const Index* shape_ptr = a7.shape().data(); const Index* byte_strides_ptr = a7.byte_strides().data(); EXPECT_EQ(2, data.use_count()); SharedArray<float> a8 = std::move(a7); EXPECT_EQ(nullptr, a7.data()); // NOLINT EXPECT_EQ(2, data.use_count()); EXPECT_EQ(data.get(), a8.data()); EXPECT_EQ(1, a8.rank()); EXPECT_EQ(shape_ptr, a8.shape().data()); EXPECT_EQ(byte_strides_ptr, a8.byte_strides().data()); SharedArray<void> a9 = std::move(a8); EXPECT_EQ(nullptr, a8.data()); // NOLINT EXPECT_EQ(2, data.use_count()); EXPECT_EQ(data.get(), a9.data()); EXPECT_EQ(1, a9.rank()); EXPECT_EQ(shape_ptr, a9.shape().data()); EXPECT_EQ(byte_strides_ptr, a9.byte_strides().data()); SharedArray<float> a10 = StaticDataTypeCast<float>(std::move(a9)).value(); // Ideally, this would move the shared_ptr to avoid atomic operations. // However, static_pointer_cast and the shared_ptr aliasing constructor does // not permit this. EXPECT_EQ(data.get(), a10.data()); EXPECT_EQ(1, a10.rank()); EXPECT_EQ(shape_ptr, a10.shape().data()); EXPECT_EQ(byte_strides_ptr, a10.byte_strides().data()); SharedArray<void> a11; a11 = std::move(a10); EXPECT_EQ(nullptr, a10.data()); // NOLINT EXPECT_EQ(data.get(), a11.data()); EXPECT_EQ(1, a11.rank()); EXPECT_EQ(shape_ptr, a11.shape().data()); EXPECT_EQ(byte_strides_ptr, a11.byte_strides().data()); SharedArray<const void> a12; a12 = std::move(a11); EXPECT_EQ(nullptr, a11.data()); // NOLINT EXPECT_EQ(data.get(), a12.data()); EXPECT_EQ(1, a12.rank()); EXPECT_EQ(shape_ptr, a12.shape().data()); EXPECT_EQ(byte_strides_ptr, a12.byte_strides().data()); } // Assign from SharedArrayView via UnownedToShared. { SharedArray<void> x; x = UnownedToShared(a_ref); EXPECT_EQ(a_ref.layout(), x.layout()); EXPECT_EQ(a_ref.element_pointer(), x.element_pointer()); ArrayView<const void> y; y = x; EXPECT_EQ(a_ref.layout(), y.layout()); EXPECT_EQ(a_ref.element_pointer(), y.element_pointer()); } } TEST(ArrayTest, SubArray) { auto array = MakeArray<int>({{1, 2, 3}, {4, 5, 6}}); EXPECT_THAT(array.shape(), ElementsAre(2, 3)); EXPECT_EQ(1, array.pointer().use_count()); auto sub_array = SubArray<container>(array, {1}); static_assert(std::is_same<decltype(sub_array), Array<int, 1>>::value, ""); EXPECT_THAT(sub_array.shape(), ElementsAre(3)); EXPECT_EQ(array.data() + 3, sub_array.data()); EXPECT_EQ(StridedLayout<1>({3}, {sizeof(int)}), sub_array.layout()); auto sub_array_view = SubArray<view>(array, {1}); static_assert( std::is_same<decltype(sub_array_view), ArrayView<int, 1>>::value, ""); EXPECT_EQ(array.data() + 3, sub_array_view.data()); EXPECT_EQ(StridedLayout<1>({3}, {sizeof(int)}), sub_array_view.layout()); } TEST(ArrayTest, SharedSubArray) { auto array = MakeArray<int>({{1, 2, 3}, {4, 5, 6}}); EXPECT_EQ(1, array.pointer().use_count()); auto sub_array = SharedSubArray<container>(array, {1}); static_assert(std::is_same<decltype(sub_array), SharedArray<int, 1>>::value, ""); EXPECT_EQ(2, array.pointer().use_count()); EXPECT_EQ(array.data() + 3, sub_array.data()); EXPECT_EQ(StridedLayout<1>({3}, {sizeof(int)}), sub_array.layout()); auto sub_array_view = SharedSubArray<view>(array, {1}); static_assert( std::is_same<decltype(sub_array_view), SharedArrayView<int, 1>>::value, ""); EXPECT_EQ(3, array.pointer().use_count()); EXPECT_EQ(array.data() + 3, sub_array_view.data()); EXPECT_EQ(StridedLayout<1>({3}, {sizeof(int)}), sub_array_view.layout()); } TEST(ArrayTest, DynamicCast) { int data[2][3] = {{1, 2, 3}, {4, 5, 6}}; ArrayView<int, 2> a_int_2 = MakeArrayView(data); auto a_int = StaticRankCast<dynamic_rank>(a_int_2).value(); EXPECT_EQ(a_int_2.layout(), a_int.layout()); EXPECT_EQ(a_int_2.element_pointer(), a_int.element_pointer()); static_assert(std::is_same<decltype(a_int), ArrayView<int>>::value, ""); StaticRankCast<dynamic_rank>(a_int).value(); /// If a conversion is done, StaticRankCast returns by value. However, for /// efficiency, a no-op StaticRankCast should just return an lvalue or rvalue /// reference to the argument. static_assert( std::is_same<decltype(StaticRankCast<dynamic_rank, unchecked>(a_int)), ArrayView<int>&>::value, ""); static_assert(std::is_same<decltype(StaticRankCast<dynamic_rank, unchecked>( std::declval<const ArrayView<int>&>())), const ArrayView<int>&>::value, ""); static_assert(std::is_same<decltype(StaticRankCast<dynamic_rank, unchecked>( std::declval<ArrayView<int>>())), ArrayView<int>&&>::value, ""); auto a_void_2 = StaticDataTypeCast<void>(a_int_2).value(); EXPECT_EQ(a_int_2.layout(), a_void_2.layout()); EXPECT_EQ(a_int_2.element_pointer(), a_void_2.element_pointer()); static_assert(std::is_same<decltype(a_void_2), ArrayView<void, 2>>::value, ""); StaticDataTypeCast<void>(a_void_2).value(); static_assert( std::is_same<decltype(StaticDataTypeCast<void, unchecked>(a_void_2)), ArrayView<void, 2>&>::value, ""); static_assert(std::is_same<decltype(StaticDataTypeCast<void, unchecked>( std::declval<const ArrayView<void, 2>&>())), const ArrayView<void, 2>&>::value, ""); static_assert(std::is_same<decltype(StaticDataTypeCast<void, unchecked>( std::declval<ArrayView<void, 2>>())), ArrayView<void, 2>&&>::value, ""); auto a_void = StaticCast<ArrayView<void>>(a_int_2).value(); EXPECT_EQ(a_int_2.layout(), a_void.layout()); EXPECT_EQ(a_int_2.element_pointer(), a_void.element_pointer()); static_assert(std::is_same<decltype(a_void), ArrayView<void>>::value, ""); StaticCast<ArrayView<void>>(a_void).value(); static_assert( std::is_same<decltype(StaticCast<ArrayView<void>, unchecked>(a_void)), ArrayView<void>&>::value, ""); static_assert(std::is_same<decltype(StaticCast<ArrayView<void>, unchecked>( std::declval<const ArrayView<void>&>())), const ArrayView<void>&>::value, ""); static_assert(std::is_same<decltype(StaticCast<ArrayView<void>, unchecked>( std::declval<ArrayView<void>>())), ArrayView<void>&&>::value, ""); auto b_int_2 = StaticCast<SharedArray<int, 2>>(UnownedToShared(a_void)).value(); EXPECT_EQ(a_int_2.layout(), b_int_2.layout()); EXPECT_EQ(a_int_2.element_pointer(), b_int_2.element_pointer()); static_assert(std::is_same<decltype(b_int_2), SharedArray<int, 2>>::value, ""); auto c_int_2 = StaticRankCast<2>(a_int).value(); EXPECT_EQ(a_int_2.layout(), c_int_2.layout()); EXPECT_EQ(a_int_2.element_pointer(), c_int_2.element_pointer()); static_assert(std::is_same<decltype(c_int_2), ArrayView<int, 2>>::value, ""); auto d_int_2 = StaticDataTypeCast<int>(a_void_2).value(); EXPECT_EQ(a_int_2.layout(), d_int_2.layout()); EXPECT_EQ(a_int_2.element_pointer(), d_int_2.element_pointer()); static_assert(std::is_same<decltype(d_int_2), ArrayView<int, 2>>::value, ""); } TEST(ArrayTest, OffsetOriginConstruct) { auto a = MakeOffsetArray<int>({7, 8}, {{1, 2, 3}, {4, 5, 6}}); EXPECT_THAT(a.origin(), ElementsAre(7, 8)); EXPECT_EQ(BoxView({7, 8}, {2, 3}), a.domain()); } TEST(ArrayTest, ZeroOriginToOffsetOrigin) { SharedArray<int, 2> a = MakeArray<int>({{1, 2}, {3, 4}}); SharedArray<int, 2, offset_origin> b(a); EXPECT_THAT(b.origin(), ElementsAre(0, 0)); EXPECT_EQ(a.domain(), b.domain()); EXPECT_EQ(a, b); } TEST(ArrayTest, ImplicitElementPointerConstruction) { int value = 5; // Test construction of dynamic_rank array with layout view from pointer. { ArrayView<void> a = &value; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test construction of dynamic_rank array with layout container from pointer. { tensorstore::Array<void> a = &value; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test construction of rank-0 array with layout view from pointer. { ArrayView<void, 0> a = &value; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test construction of rank-0 array with layout container from pointer. { tensorstore::Array<void, 0> a = &value; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test construction of rank-0 array from implicitly constructed // ElementPointer. { tensorstore::Array<void, 0> a = { {static_cast<void*>(&value), dtype_v<int>}}; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test construction of a rank-0 array from implicitly constructed // ElementPointer and explicit layout. { tensorstore::Array<void, 0> a = {{static_cast<void*>(&value), dtype_v<int>}, tensorstore::StridedLayout<0>()}; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test assignment of a rank-0 array from implicitly constructed // ElementPointer. { tensorstore::Array<void, 0> a; a = &value; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test assignment of a rank-0 array from implicitly constructed // ElementPointer. { tensorstore::Array<void, 0> a; a = &value; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } // Test assignment of a rank-0 array from implicitly constructed // ElementPointer and explicit layout. { tensorstore::Array<void, 0> a; a = {{static_cast<void*>(&value), dtype_v<int>}, tensorstore::StridedLayout<0>()}; EXPECT_EQ(&value, a.data()); EXPECT_EQ(0, a.rank()); } } TEST(ArrayTest, UnownedToSharedAliasing) { auto owned = std::make_shared<int>(); int value; tensorstore::Array<int> arr = &value; EXPECT_EQ(1, owned.use_count()); { auto alias_arr = UnownedToShared(owned, arr); static_assert( std::is_same_v<decltype(alias_arr), tensorstore::SharedArray<int>>); EXPECT_EQ(2, owned.use_count()); } EXPECT_EQ(1, owned.use_count()); } } // namespace array_conversion_tests namespace array_indexing_tests { TEST(ArrayTest, Indexing) { const Index two = 2; int data[2][3] = {{1, 2, 3}, {4, 5, 6}}; ArrayView<int, 2> a = MakeArrayView(data); EXPECT_EQ(1, a(0, 0)); EXPECT_EQ(6, a(1, 2)); EXPECT_EQ(6, a(1, two)); EXPECT_EQ(6, a({1, 2})); EXPECT_EQ(6, a(span({1, 2}))); EXPECT_EQ(MakeScalarArrayView<int>(6), a[1][2]); { auto a_sub = a[1]; static_assert(std::is_same<decltype(a_sub), ArrayView<int, 1>>::value, ""); EXPECT_EQ(&data[1][0], a_sub.data()); EXPECT_EQ(6, a_sub(2)); EXPECT_EQ(a.shape().data() + 1, a_sub.shape().data()); EXPECT_EQ(a.byte_strides().data() + 1, a_sub.byte_strides().data()); } { auto a_sub = a[span<const Index>({1, 2})]; static_assert(std::is_same<decltype(a_sub), ArrayView<int>>::value, ""); EXPECT_EQ(0, a_sub.rank()); EXPECT_EQ(&data[1][2], a_sub.data()); EXPECT_EQ(6, a_sub()); } { auto a_sub = a[{1, 2}]; static_assert(std::is_same<decltype(a_sub), ArrayView<int, 0>>::value, ""); EXPECT_EQ(0, a_sub.rank()); EXPECT_EQ(&data[1][2], a_sub.data()); EXPECT_EQ(6, a_sub()); } { ArrayView<int> a_d = a; auto a_sub = a_d[1]; static_assert(std::is_same<decltype(a_sub), ArrayView<int>>::value, ""); EXPECT_EQ(1, a_sub.rank()); EXPECT_EQ(&data[1][0], a_sub.data()); EXPECT_EQ(a_d.shape().data() + 1, a_sub.shape().data()); EXPECT_EQ(a_d.byte_strides().data() + 1, a_sub.byte_strides().data()); } } TEST(ArrayTest, OffsetOriginIndexing) { SharedArray<int, 2, offset_origin> a = MakeOffsetArray({7, 8}, {{1, 2, 3}, {4, 5, 6}}); EXPECT_EQ(1, a(7, 8)); EXPECT_EQ(5, a(8, 9)); auto a_sub = a[7]; EXPECT_THAT(a_sub.origin(), ElementsAre(8)); EXPECT_THAT(a_sub.shape(), ElementsAre(3)); EXPECT_EQ(3, a_sub(10)); } TEST(ArrayDeathTest, Indexing) { int data[2][3] = {{1, 2, 3}, {4, 5, 6}}; [[maybe_unused]] ArrayView<int, 2> a = MakeArrayView(data); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY(a(-1, 1), "Array index out of bounds"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY(a(2, 1), "Array index out of bounds"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( (ArrayView<int>(a)[0][0][0]), "Length of index vector is greater than rank of array"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( a(span<const Index>({1})), "Length of index vector must match rank of array"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( a(span<const Index>({1, 2, 3})), "Length of index vector must match rank of array"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( (a[span<const Index>({1, 2, 3})]), "Length of index vector is greater than rank of array"); } TEST(ArrayDeathTest, OffsetOriginIndexing) { int data[2][3] = {{1, 2, 3}, {4, 5, 6}}; SharedArray<int, 2, offset_origin> a = MakeOffsetArray({7, 8}, data); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY(a(0, 0), "Array index out of bounds"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY(a(7, 7), "Array index out of bounds"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( (ArrayView<int, dynamic_rank, offset_origin>(a)[7][8][0]), "Length of index vector is greater than rank of array"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( a(span<const Index>({1})), "Length of index vector must match rank of array"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( a(span<const Index>({1, 2, 3})), "Length of index vector must match rank of array"); TENSORSTORE_EXPECT_DEATH_DEBUG_ONLY( (a[span<const Index>({1, 2, 3})]), "Length of index vector is greater than rank of array"); } } // namespace array_indexing_tests namespace allocate_and_construct_shared_elements_test { TEST(AllocateAndConstructSharedElementsTest, StaticType) { auto result = tensorstore::internal::AllocateAndConstructSharedElements<float>(3); static_assert(std::is_same<decltype(result), tensorstore::SharedElementPointer<float>>::value, ""); EXPECT_NE(nullptr, result.data()); } TEST(AllocateAndConstructSharedElementsTest, DynamicType) { auto result = tensorstore::internal::AllocateAndConstructSharedElements( 3, tensorstore::default_init, dtype_v<float>); static_assert(std::is_same<decltype(result), tensorstore::SharedElementPointer<void>>::value, ""); EXPECT_EQ(dtype_v<float>, result.dtype()); EXPECT_NE(nullptr, result.data()); } } // namespace allocate_and_construct_shared_elements_test TEST(ToStringTest, Basic) { EXPECT_EQ("1", ToString(MakeScalarArrayView(1))); EXPECT_EQ("{1}", ToString(MakeArrayView({1}))); EXPECT_EQ("{1, 2, 3}", ToString(MakeArrayView({1, 2, 3}))); EXPECT_EQ("{{1, 2, 3}, {4, 5, 6}}", ToString(MakeArrayView({{1, 2, 3}, {4, 5, 6}}))); EXPECT_EQ("<null>", ToString(ArrayView<const void>())); // Printing of type-erased arrays. ArrayView<const void> void_array = MakeArrayView<int>({1, 2, 3}); EXPECT_EQ("{1, 2, 3}", ToString(void_array)); tensorstore::ArrayFormatOptions options; options.summary_threshold = 10; options.summary_edge_items = 2; EXPECT_EQ("{{1, 2, 3, 4}, {5, 6, 7, 8}}", ToString(MakeArrayView({{1, 2, 3, 4}, {5, 6, 7, 8}}), options)); EXPECT_EQ( "{{1, 2, 3, 4, 5}, {5, 6, 7, 8, 9}}", ToString(MakeArrayView({{1, 2, 3, 4, 5}, {5, 6, 7, 8, 9}}), options)); options.summary_threshold = 9; EXPECT_EQ( "{{1, 2, ..., 4, 5}, {5, 6, ..., 8, 9}}", ToString(MakeArrayView({{1, 2, 3, 4, 5}, {5, 6, 7, 8, 9}}), options)); std::ostringstream ostr; ostr << MakeScalarArrayView(3); EXPECT_EQ("3", ostr.str()); } TEST(ArrayTest, Compare) { EXPECT_TRUE(MakeArrayView({{1, 2, 3}, {4, 5, 6}}) == MakeArrayView({{1, 2, 3}, {4, 5, 6}})); EXPECT_FALSE(MakeArrayView({{1, 2, 3}, {4, 5, 6}}) != MakeArrayView({{1, 2, 3}, {4, 5, 6}})); EXPECT_TRUE(MakeArrayView({{1, 5, 3}, {4, 5, 6}}) != MakeArrayView({{1, 2, 3}, {4, 5, 6}})); EXPECT_FALSE(MakeArrayView({{1, 5, 3}, {4, 5, 6}}) == MakeArrayView({{1, 2, 3}, {4, 5, 6}})); EXPECT_FALSE(ArrayView<void>(MakeScalarArrayView(1.0)) == MakeScalarArrayView(1)); EXPECT_TRUE(ArrayView<void>(MakeScalarArrayView(1.0)) != MakeScalarArrayView(1)); EXPECT_TRUE(MakeArrayView({1}) != MakeArrayView({1, 2})); } TEST(ArrayTest, SameValue) { EXPECT_TRUE( AreArraysSameValueEqual(MakeArrayView<float>({{1, 2, 3}, {4, 5, 6}}), MakeArrayView<float>({{1, 2, 3}, {4, 5, 6}}))); EXPECT_TRUE( AreArraysSameValueEqual(MakeArrayView<float>({{NAN, 2, 3}, {4, 5, 6}}), MakeArrayView<float>({{NAN, 2, 3}, {4, 5, 6}}))); EXPECT_FALSE(AreArraysSameValueEqual( MakeArrayView<float>({{NAN, 2, +0.0}, {4, 5, 6}}), MakeArrayView<float>({{NAN, 2, -0.0}, {4, 5, 6}}))); } TEST(CopyArrayTest, ZeroOrigin) { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; auto arr_ref = MakeArrayView(arr); auto copy = MakeCopy(arr_ref); EXPECT_EQ(arr_ref, copy); InitializeArray(copy); EXPECT_EQ(MakeArrayView({{0, 0, 0}, {0, 0, 0}}), copy); } TEST(CopyArrayTest, OffsetOrigin) { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; auto source = MakeOffsetArray({7, 8}, arr); auto copy = MakeCopy(source); EXPECT_EQ(source, copy); } TEST(CopyConvertedArrayTest, Int32ToFloat32) { auto a = MakeArray<tensorstore::int32_t>({{1, 2, 3}, {4, 5, 6}}); auto b = tensorstore::AllocateArray<tensorstore::float32_t>({2, 3}); EXPECT_EQ(absl::OkStatus(), CopyConvertedArray(a, b)); EXPECT_EQ( b, MakeArray<tensorstore::float32_t>({{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}})); } TEST(CopyConvertedArrayTest, Int32ToUint32) { auto a = MakeArray<tensorstore::int32_t>({{1, 2, 3}, {4, 5, 6}}); auto b = tensorstore::AllocateArray<tensorstore::uint32_t>({2, 3}); EXPECT_EQ(absl::OkStatus(), CopyConvertedArray(a, b)); EXPECT_EQ(b, MakeArray<tensorstore::uint32_t>({{1, 2, 3}, {4, 5, 6}})); } TEST(CopyConvertedArrayTest, CopyError) { auto a = MakeArray<tensorstore::json_t>({3.0, "x"}); auto b = tensorstore::AllocateArray<tensorstore::float32_t>({2}); EXPECT_THAT( CopyConvertedArray(a, b), MatchesStatus( absl::StatusCode::kInvalidArgument, "Expected 64-bit floating-point number, but received: \"x\"")); } TEST(CopyConvertedArrayTest, InvalidDataType) { auto a = MakeArray<tensorstore::string_t>({"x", "y"}); auto b = tensorstore::AllocateArray<tensorstore::float32_t>({2}); EXPECT_THAT(CopyConvertedArray(a, b), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot convert string -> float32")); } TEST(MakeCopyTest, NoConversion) { const std::int32_t data[] = {1, 2, 3, 0, 4, 5, 6, 0}; tensorstore::Array<const std::int32_t, 3> array( data, tensorstore::StridedLayout<3>({2, 2, 3}, {0, 4 * 4, 4})); auto expected = MakeArray<const std::int32_t>( {{{1, 2, 3}, {4, 5, 6}}, {{1, 2, 3}, {4, 5, 6}}}); { // Default constraints (equivalent to {c_order, include_repeated_elements}) auto copy = MakeCopy(array); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(24, 12, 4)); } { auto copy = MakeCopy( array, {tensorstore::c_order, tensorstore::include_repeated_elements}); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(24, 12, 4)); } { auto copy = MakeCopy(array, {tensorstore::fortran_order, tensorstore::include_repeated_elements}); EXPECT_EQ(expected, copy); // Shape of allocated array is {2, 2, 3} EXPECT_THAT( copy.byte_strides(), ::testing::ElementsAre(sizeof(std::int32_t), sizeof(std::int32_t) * 2, sizeof(std::int32_t) * 2 * 2)); } { auto copy = MakeCopy( array, {tensorstore::c_order, tensorstore::skip_repeated_elements}); EXPECT_EQ(expected, copy); // Shape of allocated array is {1, 2, 3} EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(0, 3 * sizeof(std::int32_t), sizeof(std::int32_t))); } { auto copy = MakeCopy(array, {tensorstore::fortran_order, tensorstore::skip_repeated_elements}); EXPECT_EQ(expected, copy); // Shape of allocated array is {1, 2, 3} EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(0, sizeof(std::int32_t), sizeof(std::int32_t) * 2)); } { // Order is unspecified. `MakeCopy` determines order of dimensions (which // may match neither `c_order` nor `fortran_order`) that best matches the // input order. In this case the chosen order matches `c_order`. auto copy = MakeCopy(array, {tensorstore::skip_repeated_elements}); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(0, 12, 4)); } { auto copy = MakeCopy(array, {tensorstore::include_repeated_elements}); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(4, 24, 8)); } } TEST(MakeCopyTest, Conversion) { const std::int32_t data[] = {1, 2, 3, 0, 4, 5, 6, 0}; tensorstore::Array<const std::int32_t, 3> array( data, tensorstore::StridedLayout<3>({2, 2, 3}, {0, 4 * 4, 4})); auto expected = MakeArray<const float>({{{1, 2, 3}, {4, 5, 6}}, {{1, 2, 3}, {4, 5, 6}}}); EXPECT_THAT(MakeCopy<std::byte>(array), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot convert int32 -> byte")); { auto copy = MakeCopy<float>(array).value(); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(24, 12, 4)); } { auto copy = MakeCopy<float>(array, {tensorstore::fortran_order, tensorstore::skip_repeated_elements}) .value(); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(0, 4, 8)); } { auto copy = MakeCopy(array, {tensorstore::skip_repeated_elements}, tensorstore::DataType(dtype_v<float>)) .value(); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(0, 12, 4)); } { auto copy = MakeCopy<float>(array, {tensorstore::include_repeated_elements}) .value(); EXPECT_EQ(expected, copy); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(4, 24, 8)); } } template <tensorstore::ArrayOriginKind OriginKind> void TestAllocateArrayLike( ArrayView<const int, 2, OriginKind> source, ArrayView<const int, 3, OriginKind> source_repeated) { { auto copy = tensorstore::AllocateArrayLike<int>(source.layout(), ContiguousLayoutOrder::c); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(sizeof(int) * 3, sizeof(int))); EXPECT_EQ(source.domain(), copy.domain()); } { auto copy = tensorstore::AllocateArrayLike<int>( source.layout(), ContiguousLayoutOrder::fortran); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(sizeof(int), sizeof(int) * 2)); EXPECT_EQ(source.domain(), copy.domain()); } { auto copy = tensorstore::AllocateArrayLike<int>( source_repeated.layout(), {ContiguousLayoutOrder::c, tensorstore::include_repeated_elements}); EXPECT_THAT( copy.byte_strides(), ::testing::ElementsAre(sizeof(int) * 6, sizeof(int) * 3, sizeof(int))); EXPECT_EQ(source_repeated.domain(), copy.domain()); } { auto copy = tensorstore::AllocateArrayLike<int>( source_repeated.layout(), {ContiguousLayoutOrder::fortran, tensorstore::include_repeated_elements}); EXPECT_THAT( copy.byte_strides(), ::testing::ElementsAre(sizeof(int), sizeof(int) * 2, sizeof(int) * 4)); EXPECT_EQ(source_repeated.domain(), copy.domain()); } { auto copy = tensorstore::AllocateArrayLike<int>( source_repeated.layout(), {ContiguousLayoutOrder::c, tensorstore::skip_repeated_elements}); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(sizeof(int) * 3, 0, sizeof(int))); EXPECT_EQ(source_repeated.domain(), copy.domain()); } { auto copy = tensorstore::AllocateArrayLike<int>( source_repeated.layout(), {ContiguousLayoutOrder::fortran, tensorstore::skip_repeated_elements}); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(sizeof(int), 0, sizeof(int) * 2)); EXPECT_EQ(source_repeated.domain(), copy.domain()); } { auto copy = tensorstore::AllocateArrayLike<int>( source_repeated.layout(), tensorstore::skip_repeated_elements); EXPECT_THAT(copy.byte_strides(), ::testing::ElementsAre(sizeof(int) * 3, 0, sizeof(int))); EXPECT_EQ(source_repeated.domain(), copy.domain()); } } TEST(AllocateArrayLikeTest, ZeroOrigin) { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; auto source = MakeArray(arr); SharedArray<int, 3> source_repeated( source.element_pointer(), tensorstore::StridedLayoutView<3>({2, 2, 3}, {sizeof(int) * 3, 0, sizeof(int)})); TestAllocateArrayLike<zero_origin>(source, source_repeated); } TEST(AllocateArrayLikeTest, OffsetOrigin) { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; auto source = MakeOffsetArray({7, 8}, arr); SharedArray<int, 3, offset_origin> source_repeated( source.element_pointer(), tensorstore::StridedLayoutView<3, offset_origin>( {7, 9, 8}, {2, 2, 3}, {sizeof(int) * 3, 0, sizeof(int)})); TestAllocateArrayLike<offset_origin>(source, source_repeated); } TEST(AllocateArrayTest, Default) { SharedArray<int, 2> result = tensorstore::AllocateArray<int>( {2, 3u}, ContiguousLayoutOrder::c, tensorstore::value_init); EXPECT_THAT(result.shape(), testing::ElementsAreArray({2, 3})); EXPECT_THAT(result.byte_strides(), testing::ElementsAreArray({3 * sizeof(int), sizeof(int)})); result(1, 2) = 1; } TEST(AllocateArrayElementsLikeTest, ZeroOrigin) { StridedLayout<2, zero_origin> source_layout({2, 3}, {1, 10}); std::vector<Index> byte_strides(2); auto array_pointer = tensorstore::AllocateArrayElementsLike<int32_t>( source_layout, byte_strides.data(), tensorstore::skip_repeated_elements, tensorstore::value_init); ASSERT_THAT(byte_strides, testing::ElementsAre(4, 8)); for (Index i = 0; i < source_layout.num_elements(); ++i) { EXPECT_EQ(0, array_pointer.data()[i]); } } TEST(AllocateArrayElementsLikeTest, ZeroOriginSkipRepeatedElements) { StridedLayout<2, zero_origin> source_layout({2, 3}, {0, 10}); std::vector<Index> byte_strides(2); auto array_pointer = tensorstore::AllocateArrayElementsLike<int32_t>( source_layout, byte_strides.data(), tensorstore::skip_repeated_elements, tensorstore::value_init); ASSERT_THAT(byte_strides, testing::ElementsAre(0, 4)); for (Index i = 0; i < 3; ++i) { EXPECT_EQ(0, array_pointer.data()[i]); } } TEST(AllocateArrayElementsLikeTest, OffsetOrigin) { StridedLayout<2, offset_origin> source_layout({1, 2}, {2, 3}, {1, 10}); std::vector<Index> byte_strides(2); auto array_pointer = tensorstore::AllocateArrayElementsLike<int32_t>( source_layout, byte_strides.data(), tensorstore::skip_repeated_elements, tensorstore::value_init); ASSERT_THAT(byte_strides, testing::ElementsAre(4, 8)); for (Index i = 0; i < source_layout.num_elements(); ++i) { EXPECT_EQ(0, array_pointer.data()[1 + 4 + i]); } } TEST(AllocateArrayElementsLikeTest, OffsetOriginSkipRepeatedElements) { StridedLayout<2, offset_origin> source_layout({1, 2}, {2, 3}, {0, 10}); std::vector<Index> byte_strides(2); auto array_pointer = tensorstore::AllocateArrayElementsLike<int32_t>( source_layout, byte_strides.data(), tensorstore::skip_repeated_elements, tensorstore::value_init); EXPECT_THAT(byte_strides, testing::ElementsAre(0, 4)); for (Index i = 0; i < 3; ++i) { EXPECT_EQ(0, array_pointer.data()[2 + i]); } } TEST(IterateOverArrays, VoidReturn) { std::vector<std::pair<int, int>> values; EXPECT_EQ( (ArrayIterateResult{true, 4}), IterateOverArrays( [&](const int* a, const int* b) { values.emplace_back(*a, *b); }, /*constraints=*/ContiguousLayoutOrder::c, MakeArrayView({{1, 2}, {3, 4}}), MakeArrayView({{5, 6}, {7, 8}}))); const std::vector<std::pair<int, int>> expected_values{ {1, 5}, {2, 6}, {3, 7}, {4, 8}}; EXPECT_EQ(expected_values, values); } TEST(IterateOverArrays, VoidReturnStatus) { std::vector<std::pair<int, int>> values; absl::Status status; EXPECT_EQ( (ArrayIterateResult{true, 4}), IterateOverArrays( [&](const int* a, const int* b, absl::Status* status_ptr) { values.emplace_back(*a, *b); EXPECT_EQ(&status, status_ptr); }, &status, /*constraints=*/ContiguousLayoutOrder::c, MakeArrayView({{1, 2}, {3, 4}}), MakeArrayView({{5, 6}, {7, 8}}))); const std::vector<std::pair<int, int>> expected_values{ {1, 5}, {2, 6}, {3, 7}, {4, 8}}; EXPECT_EQ(expected_values, values); } TEST(IterateOverArrays, BoolReturnZeroElements) { EXPECT_EQ((ArrayIterateResult{true, 0}), IterateOverArrays([&](const int* a) -> bool { return false; }, /*constraints=*/{}, tensorstore::AllocateArray<int>({0}))); } TEST(IterateOverArrays, BoolTrueReturn) { std::vector<std::pair<int, int>> values; EXPECT_EQ( (ArrayIterateResult{true, 4}), IterateOverArrays( [&](const int* a, const int* b) -> bool { values.emplace_back(*a, *b); return true; }, /*constraints=*/ContiguousLayoutOrder::c, MakeArrayView({{1, 2}, {3, 4}}), MakeArrayView({{5, 6}, {7, 8}}))); const std::vector<std::pair<int, int>> expected_values{ {1, 5}, {2, 6}, {3, 7}, {4, 8}}; EXPECT_EQ(expected_values, values); } TEST(IterateOverArrays, BoolFalseReturn) { std::vector<std::pair<int, int>> values; EXPECT_EQ( (ArrayIterateResult{false, 1}), IterateOverArrays( [&](const int* a, const int* b) { values.emplace_back(*a, *b); return (*a != 2); }, /*constraints=*/ContiguousLayoutOrder::c, MakeArrayView({{1, 2}, {3, 4}}), MakeArrayView({{5, 6}, {7, 8}}))); const std::vector<std::pair<int, int>> expected_values{{1, 5}, {2, 6}}; EXPECT_EQ(expected_values, values); } TEST(SharedArrayTest, Example) { using tensorstore::CopyArray; using tensorstore::MakeArray; using tensorstore::SharedArray; ///! [SharedArray usage example] SharedArray<int, 2> x = MakeArray<int>({{1, 2, 3}, {4, 5, 6}}); SharedArray<int, 2> y = x; SharedArray<int, 2> z = MakeCopy(x); EXPECT_THAT(x.shape(), ::testing::ElementsAreArray({2, 3})); EXPECT_EQ("{{1, 2, 3}, {4, 5, 6}}", ToString(x)); EXPECT_EQ("{1, 2, 3}", ToString(x[0])); EXPECT_EQ(6, x(1, 2)); x(1, 2) = 7; x(0, 0) = 9; EXPECT_EQ("{{9, 2, 3}, {4, 5, 7}}", ToString(x)); EXPECT_EQ("{{9, 2, 3}, {4, 5, 7}}", ToString(y)); EXPECT_EQ("{{1, 2, 3}, {4, 5, 6}}", ToString(z)); ///! [SharedArray usage example] } TEST(ArrayViewTest, Example) { using tensorstore::AllocateArray; using tensorstore::ArrayView; using tensorstore::IterateOverArrays; using tensorstore::MakeArray; using tensorstore::SharedArray; ///! [ArrayView usage example] const auto compute_sum = [&](ArrayView<int> a, ArrayView<int> b) -> SharedArray<int> { auto c = AllocateArray<int>(a.shape()); IterateOverArrays( [&](const int* a_v, const int* b_v, int* c_v) { *c_v = *a_v + *b_v; }, /*constraints=*/{}, a, b, c); return c; }; SharedArray<int, 2> a = MakeArray<int>({{1, 2}, {3, 4}}); SharedArray<int, 2> b = MakeArray<int>({{5, 6}, {7, 9}}); EXPECT_EQ(MakeArray<int>({{6, 8}, {10, 13}}), compute_sum(a, b)); ///! [ArrayView usage example] } TEST(SharedArrayViewTest, Example) { using tensorstore::AllocateArray; using tensorstore::MakeArray; using tensorstore::SharedArray; using tensorstore::SharedArrayView; ///! [SharedArrayView usage example] const auto transpose = [&](SharedArrayView<int> x) -> SharedArray<int> { SharedArray<int> y(x); std::reverse(y.shape().begin(), y.shape().end()); std::reverse(y.byte_strides().begin(), y.byte_strides().end()); return y; }; SharedArray<int, 2> a = MakeArray<int>({{1, 2, 3}, {4, 5, 6}}); EXPECT_EQ(MakeArray<int>({{1, 4}, {2, 5}, {3, 6}}), transpose(a)); ///! [SharedArrayView usage example] } TEST(DynamicArrayCastTest, Example) { using tensorstore::AllocateArray; using tensorstore::MakeArray; using tensorstore::SharedArray; using tensorstore::SharedArrayView; ///! [DynamicArrayCast usage example] SharedArray<void> a(MakeArray<int>({1, 2, 3})); auto b = StaticCast<SharedArray<int, 1>>(a).value(); auto c = StaticCast<ArrayView<int, 1>>(a).value(); auto d = StaticCast<ArrayView<const int, 1>>(a).value(); ///! [DynamicArrayCast usage example] static_cast<void>(b); static_cast<void>(c); static_cast<void>(d); } TEST(DynamicElementCastTest, Example) { using tensorstore::AllocateArray; using tensorstore::MakeArray; using tensorstore::SharedArray; using tensorstore::SharedArrayView; ///! [DynamicElementCast usage example] SharedArray<void, 1> a = MakeArray<int>({1, 2, 3}); auto b = StaticDataTypeCast<int>(a); // Result<SharedArray<int, 1>> if (b) { // Conversion successful. } auto c = StaticDataTypeCast<const int>(a); // Result<SharedArray<const int, 1>> if (c) { // Conversion successful. } ///! [DynamicElementCast usage example] } TEST(DynamicRankCastTest, Example) { using tensorstore::AllocateArray; using tensorstore::MakeArray; using tensorstore::SharedArray; using tensorstore::SharedArrayView; ///! [DynamicRankCast usage example] SharedArray<int> a(MakeArray<int>({1, 2, 3})); auto b = StaticRankCast<1>(a); // Result<SharedArray<int, 1>> ///! [DynamicRankCast usage example] static_cast<void>(b); } TEST(SharedArrayTest, Domain) { SharedArray<int, 2> a = MakeArray<int>({{1, 2}, {3, 4}}); auto box = a.domain(); static_assert(std::is_same<decltype(box), tensorstore::BoxView<2>>::value, ""); EXPECT_THAT(box.shape(), ::testing::ElementsAre(2, 2)); EXPECT_THAT(box.origin(), ::testing::ElementsAre(0, 0)); static_assert(tensorstore::HasBoxDomain<SharedArray<int, 2>>::value, ""); EXPECT_EQ(box, GetBoxDomainOf(a)); } TEST(SharedArrayTest, AllocateArrayFromDomain) { auto array = tensorstore::AllocateArray<int>(BoxView({1, 2}, {3, 4}), ContiguousLayoutOrder::c, tensorstore::value_init); EXPECT_THAT(array.byte_strides(), ::testing::ElementsAre(4 * sizeof(int), sizeof(int))); array(3, 5) = 10; array(1, 2) = 5; EXPECT_EQ(BoxView({1, 2}, {3, 4}), array.domain()); EXPECT_EQ("{{5, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 10}} @ {1, 2}", ToString(array)); } template <ContainerKind SourceLayoutCKind, ContainerKind TargetLayoutCKind> void TestArrayOriginCastOffsetOriginToZeroOrigin() { auto source = MakeOffsetArray<int>({2, 3}, {{1, 2, 3}, {4, 5, 6}}); SharedArray<int, 2, offset_origin, SourceLayoutCKind> source_copy = source; auto result = tensorstore::ArrayOriginCast<zero_origin, TargetLayoutCKind>(source); static_assert(std::is_same<tensorstore::Result<tensorstore::SharedArray< int, 2, zero_origin, TargetLayoutCKind>>, decltype(result)>::value, ""); EXPECT_EQ(MakeArray<int>({{1, 2, 3}, {4, 5, 6}}), *result); } template <ArrayOriginKind TargetOriginKind, ContainerKind TargetLayoutCKind, typename ElementTag, DimensionIndex Rank, ArrayOriginKind OriginKind, ContainerKind SourceLayoutCKind> void TestArrayOriginCastImplicitCase( Array<ElementTag, Rank, OriginKind, SourceLayoutCKind> source) { auto result = tensorstore::ArrayOriginCast<TargetOriginKind, TargetLayoutCKind>(source); static_assert( std::is_same<tensorstore::Array<ElementTag, Rank, TargetOriginKind, TargetLayoutCKind>, decltype(result)>::value, ""); EXPECT_EQ(source, result); } TEST(ArrayOriginCastTest, OffsetOriginToZeroOriginSuccess) { TestArrayOriginCastOffsetOriginToZeroOrigin<container, container>(); TestArrayOriginCastOffsetOriginToZeroOrigin<container, view>(); TestArrayOriginCastOffsetOriginToZeroOrigin<view, container>(); TestArrayOriginCastOffsetOriginToZeroOrigin<view, view>(); } TEST(ArrayOriginCastTest, OffsetOriginToZeroOriginFailure) { int value = 1; Array<int, 1, offset_origin> array; array.element_pointer() = &value; array.byte_strides()[0] = 0; array.origin()[0] = -kInfIndex; array.shape()[0] = kInfSize; EXPECT_THAT(tensorstore::ArrayOriginCast<zero_origin>(array), MatchesStatus(absl::StatusCode::kInvalidArgument, StrCat("Cannot translate array with shape \\{", kInfSize, "\\} to have zero origin\\."))); } TEST(ArrayOriginCastTest, ImplicitCaseOffsetOriginSource) { SharedArray<int, 2, offset_origin> array = MakeOffsetArray<int>({2, 3}, {{1, 2, 3}, {3, 4, 5}}); TestArrayOriginCastImplicitCase<offset_origin, container>(array); TestArrayOriginCastImplicitCase<offset_origin, view>(array); const SharedArrayView<int, 2, offset_origin> array_view = array; TestArrayOriginCastImplicitCase<offset_origin, container>(array_view); TestArrayOriginCastImplicitCase<offset_origin, view>(array_view); } TEST(ArrayOriginCastTest, ImplicitCaseZeroOriginSource) { SharedArray<int, 2> array = MakeArray<int>({{1, 2, 3}, {3, 4, 5}}); TestArrayOriginCastImplicitCase<offset_origin, container>(array); TestArrayOriginCastImplicitCase<offset_origin, view>(array); TestArrayOriginCastImplicitCase<zero_origin, container>(array); TestArrayOriginCastImplicitCase<zero_origin, view>(array); SharedArrayView<int, 2> array_view = array; TestArrayOriginCastImplicitCase<offset_origin, container>(array_view); TestArrayOriginCastImplicitCase<offset_origin, view>(array_view); TestArrayOriginCastImplicitCase<zero_origin, container>(array_view); TestArrayOriginCastImplicitCase<zero_origin, view>(array_view); } TEST(ArrayTest, ConstructContiguousBracedList) { int data[6] = {1, 2, 3, 4, 5, 6}; // Defaults to `c_order`. Array<int, 2> array(data, {2, 3}); EXPECT_EQ(data, array.data()); EXPECT_EQ(array, MakeArray<int>({{1, 2, 3}, {4, 5, 6}})); // Explicit `c_order`. Array<int, 2> array_c_order(data, {2, 3}, c_order); EXPECT_EQ(data, array_c_order.data()); EXPECT_EQ(array_c_order, MakeArray<int>({{1, 2, 3}, {4, 5, 6}})); // Explicit `fortran_order`. Array<int, 2> array_f_order(data, {3, 2}, fortran_order); EXPECT_EQ(data, array_f_order.data()); EXPECT_EQ(array_f_order, MakeArray<int>({{1, 4}, {2, 5}, {3, 6}})); Array<int, 2, offset_origin> array_offset_origin(data, {2, 3}); EXPECT_EQ(data, array.data()); EXPECT_EQ(array_offset_origin, MakeArray<int>({{1, 2, 3}, {4, 5, 6}})); } TEST(ArrayTest, ConstructContiguousSpan) { int data[6] = {1, 2, 3, 4, 5, 6}; // Defaults to `c_order`. Array<int, 2> array(data, span<const Index, 2>({2, 3})); EXPECT_EQ(data, array.data()); EXPECT_EQ(array, MakeArray<int>({{1, 2, 3}, {4, 5, 6}})); // Explicit `c_order`. Array<int, 2> array_c_order(data, span<const Index, 2>({2, 3}), c_order); EXPECT_EQ(data, array_c_order.data()); EXPECT_EQ(array_c_order, MakeArray<int>({{1, 2, 3}, {4, 5, 6}})); // Explicit `fortran_order`. Array<int, 2> array_f_order(data, span<const Index, 2>({3, 2}), fortran_order); EXPECT_EQ(data, array_f_order.data()); EXPECT_EQ(array_f_order, MakeArray<int>({{1, 4}, {2, 5}, {3, 6}})); Array<int, 2, offset_origin> array_offset_origin( data, span<const Index, 2>({2, 3})); EXPECT_EQ(data, array.data()); EXPECT_EQ(array_offset_origin, MakeArray<int>({{1, 2, 3}, {4, 5, 6}})); } TEST(ArrayTest, ConstructContiguousBox) { int data[6] = {1, 2, 3, 4, 5, 6}; // Defaults to `c_order`. Array<int, 2, offset_origin> array(data, BoxView({1, 2}, {2, 3})); EXPECT_EQ(&data[0], array.byte_strided_origin_pointer()); EXPECT_EQ(array, MakeOffsetArray<int>({1, 2}, {{1, 2, 3}, {4, 5, 6}})); // Explicit `c_order`. Array<int, 2, offset_origin> array_c_order(data, BoxView({1, 2}, {2, 3}), c_order); EXPECT_EQ(&data[0], array_c_order.byte_strided_origin_pointer()); EXPECT_EQ(array_c_order, MakeOffsetArray<int>({1, 2}, {{1, 2, 3}, {4, 5, 6}})); // Explicit `fortran_order`. Array<int, 2, offset_origin> array_f_order(data, BoxView({1, 2}, {3, 2}), fortran_order); EXPECT_EQ(&data[0], array_f_order.byte_strided_origin_pointer()); EXPECT_EQ(array_f_order, MakeOffsetArray<int>({1, 2}, {{1, 4}, {2, 5}, {3, 6}})); } TEST(ArrayTest, DeductionGuides) { int value = 42; int* raw_p = &value; int data[] = {1, 2, 3, 4, 5, 6}; std::shared_ptr<int> shared_p = std::make_shared<int>(42); auto existing_array = MakeArray<int>({{1, 2, 3}, {4, 5, 6}}); ElementPointer<int> int_el_p = raw_p; ElementPointer<void> void_el_p = raw_p; ElementPointer<tensorstore::Shared<void>> shared_el_p = shared_p; StridedLayout<3, zero_origin> layout_3_zero; StridedLayout<3, offset_origin> layout_3_offset; StridedLayout<dynamic_rank, zero_origin> layout_dynamic_zero; StridedLayout<dynamic_rank, offset_origin> layout_dynamic_offset; { auto a = Array(raw_p); static_assert(std::is_same_v<decltype(a), Array<int, 0>>); EXPECT_EQ(a, tensorstore::MakeScalarArray<int>(42)); } { auto a = Array(shared_p); static_assert(std::is_same_v<decltype(a), SharedArray<int, 0>>); EXPECT_EQ(a, tensorstore::MakeScalarArray<int>(42)); } { auto a = Array(int_el_p); static_assert(std::is_same_v<decltype(a), Array<int, 0>>); EXPECT_EQ(a, tensorstore::MakeScalarArray<int>(42)); } { auto a = Array(void_el_p); static_assert(std::is_same_v<decltype(a), Array<void, 0>>); EXPECT_EQ(a, tensorstore::MakeScalarArray<int>(42)); } { auto a = Array(shared_el_p); static_assert(std::is_same_v<decltype(a), SharedArray<void, 0>>); EXPECT_EQ(a, tensorstore::MakeScalarArray<int>(42)); } { auto a = Array(raw_p, layout_3_zero); static_assert(std::is_same_v<decltype(a), Array<int, 3>>); } { auto a = Array(raw_p, layout_3_offset); static_assert(std::is_same_v<decltype(a), Array<int, 3, offset_origin>>); } { auto a = Array(shared_p, layout_3_zero); static_assert(std::is_same_v<decltype(a), SharedArray<int, 3>>); } { auto a = Array(shared_p, layout_dynamic_zero); static_assert(std::is_same_v<decltype(a), SharedArray<int>>); } { auto a = Array(shared_p, layout_dynamic_offset); static_assert( std::is_same_v<decltype(a), SharedArray<int, dynamic_rank, offset_origin>>); } { auto a = Array(void_el_p, layout_dynamic_offset); static_assert( std::is_same_v<decltype(a), Array<void, dynamic_rank, offset_origin>>); } { auto a = Array(data, {2, 3}); static_assert(std::is_same_v<decltype(a), Array<int, 2>>); EXPECT_EQ(existing_array, a); } { auto a = Array(data, {2, 3}, c_order); static_assert(std::is_same_v<decltype(a), Array<int, 2>>); EXPECT_EQ(existing_array, a); } } TEST(ValidateShapeBroadcastTest, Examples) { TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({5}), span<const Index>({4, 5}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({4, 1}), span<const Index>({4, 5}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1, 1, 5}), span<const Index>({4, 5}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1, 1, 5}), span<const Index>({4, 5}))); EXPECT_THAT(ValidateShapeBroadcast(span<const Index>({2, 5}), span<const Index>({4, 5})), MatchesStatus(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(ValidateShapeBroadcast(span<const Index>({2, 5}), span<const Index>({5, 5})), MatchesStatus(absl::StatusCode::kInvalidArgument)); } TEST(ValidateShapeBroadcastTest, Basic) { TENSORSTORE_EXPECT_OK( ValidateShapeBroadcast(span<const Index>(), span<const Index>())); TENSORSTORE_EXPECT_OK( ValidateShapeBroadcast(span<const Index>(), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({3, 4}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1, 3, 4}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1, 1, 3, 4}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1, 1, 1, 4}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1, 1, 3, 1}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({3, 1}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({4}), span<const Index>({3, 4}))); TENSORSTORE_EXPECT_OK(ValidateShapeBroadcast(span<const Index>({1}), span<const Index>({3, 4}))); EXPECT_THAT( ValidateShapeBroadcast(span<const Index>({5}), span<const Index>({3, 4})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot broadcast array of shape \\{5\\} to target shape " "\\{3, 4\\}")); } TEST(BroadcastStridedLayoutTest, Basic) { StridedLayout<1> source_layout({3}, {5}); StridedLayout<2> target_layout({4, 3}, {42, 42}); TENSORSTORE_ASSERT_OK( tensorstore::BroadcastStridedLayout(source_layout, target_layout.shape(), target_layout.byte_strides().data())); EXPECT_THAT(target_layout.byte_strides(), ::testing::ElementsAre(0, 5)); } TEST(BroadcastArrayTest, ZeroOrigin) { EXPECT_THAT( BroadcastArray(MakeArray<int>({1, 2, 3}), span<const Index>({2, 3})), MakeArray<int>({{1, 2, 3}, {1, 2, 3}})); EXPECT_THAT(BroadcastArray(MakeArray<int>({{1}, {2}, {3}}), span<const Index>({3, 2})), MakeArray<int>({{1, 1}, {2, 2}, {3, 3}})); EXPECT_THAT(BroadcastArray(MakeArray<int>({{1}, {2}, {3}}), span<const Index>({4, 2})), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot broadcast array of shape \\{3, 1\\} to target shape " "\\{4, 2\\}")); } TEST(BroadcastArrayTest, OffsetOrigin) { EXPECT_THAT(BroadcastArray(MakeOffsetArray<int>({3}, {1, 2, 3}), BoxView<>({1, 2}, {2, 3})), MakeOffsetArray<int>({1, 2}, {{1, 2, 3}, {1, 2, 3}})); EXPECT_THAT(BroadcastArray(MakeOffsetArray<int>({3, 4}, {{1}, {2}, {3}}), BoxView<>({1, 2}, {3, 2})), MakeOffsetArray<int>({1, 2}, {{1, 1}, {2, 2}, {3, 3}})); EXPECT_THAT(BroadcastArray(MakeOffsetArray<int>({3, 4}, {{1}, {2}, {3}}), BoxView<>({1, 2}, {4, 2})), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot broadcast array of shape \\{3, 1\\} to target shape " "\\{4, 2\\}")); } TEST(UnbroadcastArrayTest, Basic) { auto orig_array = MakeArray<int>({{{1, 2}}, {{3, 4}}, {{5, 6}}}); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto broadcast_array, BroadcastArray(orig_array, BoxView<>({1, 2, 3, 4}, {2, 3, 2, 2}))); auto unbroadcast_array = UnbroadcastArray(broadcast_array); auto unbroadcast_array2 = UnbroadcastArray(unbroadcast_array); EXPECT_EQ(orig_array, unbroadcast_array); EXPECT_EQ(orig_array.pointer(), unbroadcast_array.pointer()); EXPECT_EQ(orig_array.layout(), unbroadcast_array.layout()); EXPECT_EQ(orig_array, unbroadcast_array2); EXPECT_EQ(orig_array.pointer(), unbroadcast_array2.pointer()); EXPECT_EQ(orig_array.layout(), unbroadcast_array2.layout()); } TEST(UnbroadcastArrayTest, PreserveRank) { auto orig_array = MakeArray<int>({{{1, 2}}, {{3, 4}}, {{5, 6}}}); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto broadcast_array1, BroadcastArray(orig_array, BoxView<>({1, 3, 1, 2}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto broadcast_array2, BroadcastArray(orig_array, BoxView<>({1, 2, 3, 4}, {2, 3, 2, 2}))); auto unbroadcast_array2 = UnbroadcastArrayPreserveRank(broadcast_array2); EXPECT_EQ(unbroadcast_array2.pointer(), broadcast_array1.pointer()); EXPECT_EQ(unbroadcast_array2.layout(), broadcast_array1.layout()); } TEST(ArraySerializationTest, ZeroOrigin) { tensorstore::SharedArray<int, 2> array = tensorstore::MakeArray<int>({{1, 2, 3}, {4, 5, 6}}); TestSerializationRoundTrip(array); TestSerializationRoundTrip(tensorstore::SharedArray<void, 2>(array)); TestSerializationRoundTrip(tensorstore::SharedArray<int>(array)); TestSerializationRoundTrip(tensorstore::SharedArray<void>(array)); } TEST(ArraySerializationTest, OffsetOrigin) { tensorstore::SharedOffsetArray<int, 2> array = tensorstore::MakeOffsetArray<int>({7, 8}, {{1, 2, 3}, {4, 5, 6}}); TestSerializationRoundTrip(array); TestSerializationRoundTrip(tensorstore::SharedOffsetArray<void, 2>(array)); TestSerializationRoundTrip(tensorstore::SharedOffsetArray<int>(array)); TestSerializationRoundTrip(tensorstore::SharedOffsetArray<void>(array)); } // Tests that singleton dimensions (with zero stride) are correctly preserved. TEST(ArraySerializationTest, ZeroStrides) { int data[] = {1, 2, 3, 4, 5, 6}; tensorstore::SharedArray<int> array( std::shared_ptr<int>(std::shared_ptr<void>(), &data[0]), StridedLayout<>({kInfIndex + 1, 2, 3, kInfIndex + 1}, {0, 3 * sizeof(int), sizeof(int), 0})); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, SerializationRoundTrip(array)); ASSERT_EQ(array.layout(), copy.layout()); EXPECT_EQ(array, copy); } TEST(ArraySerializationTest, DataTypeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto encoded, EncodeBatch(MakeArray<int>({1, 2, 3}))); SharedArray<float> array; EXPECT_THAT( DecodeBatch(encoded, array), MatchesStatus(absl::StatusCode::kDataLoss, "Expected data type of float32 but received: int32; .*")); } TEST(ArraySerializationTest, RankMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto encoded, EncodeBatch(MakeArray<int>({1, 2, 3}))); SharedArray<int, 2> array; EXPECT_THAT(DecodeBatch(encoded, array), MatchesStatus(absl::StatusCode::kDataLoss, "Expected rank of 2 but received: 1; .*")); } class RandomDataSerializationTest : public ::testing::TestWithParam<tensorstore::DataType> {}; INSTANTIATE_TEST_SUITE_P(DataTypes, RandomDataSerializationTest, ::testing::ValuesIn(tensorstore::kDataTypes)); TEST_P(RandomDataSerializationTest, COrder) { auto dtype = GetParam(); for (int iteration = 0; iteration < 100; ++iteration) { std::minstd_rand gen{tensorstore::internal::GetRandomSeedForTest( "TENSORSTORE_ARRAY_SERIALIZATION_TEST_SEED")}; auto box = tensorstore::internal::MakeRandomBox(gen); auto array = tensorstore::internal::MakeRandomArray(gen, box, dtype, c_order); TestSerializationRoundTrip(array); tensorstore::serialization::TestSerializationRoundTripCorrupt(array); } } TEST_P(RandomDataSerializationTest, FOrder) { auto dtype = GetParam(); for (int iteration = 0; iteration < 100; ++iteration) { std::minstd_rand gen{tensorstore::internal::GetRandomSeedForTest( "TENSORSTORE_ARRAY_SERIALIZATION_TEST_SEED")}; auto box = tensorstore::internal::MakeRandomBox(gen); auto array = tensorstore::internal::MakeRandomArray(gen, box, dtype, fortran_order); TestSerializationRoundTrip(array); } } } // namespace
37.702286
80
0.6336
[ "shape", "vector" ]
fdb8cf34fba444878addf8f2cdd9150c91888969
5,637
cc
C++
debugd/src/debug_mode_tool.cc
doitmovin/chromiumos-platform2
6462aaf43072307b5a40eb045a89e473381b5fda
[ "BSD-3-Clause" ]
null
null
null
debugd/src/debug_mode_tool.cc
doitmovin/chromiumos-platform2
6462aaf43072307b5a40eb045a89e473381b5fda
[ "BSD-3-Clause" ]
null
null
null
debugd/src/debug_mode_tool.cc
doitmovin/chromiumos-platform2
6462aaf43072307b5a40eb045a89e473381b5fda
[ "BSD-3-Clause" ]
2
2021-01-26T12:37:19.000Z
2021-05-18T13:37:57.000Z
// Copyright (c) 2012 The Chromium OS 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 "debugd/src/debug_mode_tool.h" #include <chromeos/dbus/service_constants.h> #include <shill/dbus_proxies/org.chromium.flimflam.Manager.h> #include "dbus_proxies/org.freedesktop.DBus.Properties.h" #if USE_CELLULAR #include "dbus_proxies/org.freedesktop.ModemManager.h" #include "dbus_proxies/org.freedesktop.ModemManager1.h" #endif // USE_CELLULAR namespace debugd { namespace { const int kFlimflamLogLevelVerbose3 = -3; const int kFlimflamLogLevelInfo = 0; const char kSupplicantPath[] = "/fi/w1/wpa_supplicant1"; const char kSupplicantService[] = "fi.w1.wpa_supplicant1"; const char kSupplicantIface[] = "fi.w1.wpa_supplicant1"; } // namespace class ManagerProxy : public org::chromium::flimflam::Manager_proxy, public DBus::ObjectProxy { public: ManagerProxy(DBus::Connection* connection, const char* path, const char* service) : DBus::ObjectProxy(*connection, path, service) {} ~ManagerProxy() override = default; void PropertyChanged(const std::string&, const DBus::Variant&) override {} void StateChanged(const std::string&) override {} }; #if USE_CELLULAR namespace { const char kDBusListNames[] = "ListNames"; const char kModemManager[] = "ModemManager"; } // namespace class ModemManagerProxy : public org::freedesktop::ModemManager_proxy, public DBus::ObjectProxy { public: ModemManagerProxy(DBus::Connection* connection, const char* path, const char* service) : DBus::ObjectProxy(*connection, path, service) {} ~ModemManagerProxy() override = default; void DeviceAdded(const DBus::Path&) override {} void DeviceRemoved(const DBus::Path&) override {} }; class ModemManager1Proxy : public org::freedesktop::ModemManager1_proxy, public DBus::ObjectProxy { public: ModemManager1Proxy(DBus::Connection* connection, const char* path, const char* service) : DBus::ObjectProxy(*connection, path, service) {} ~ModemManager1Proxy() override = default; }; #endif // USE_CELLULAR class PropertiesProxy : public org::freedesktop::DBus::Properties_proxy, public DBus::ObjectProxy { public: PropertiesProxy(DBus::Connection* connection, const char* path, const char* service) : DBus::ObjectProxy(*connection, path, service) {} ~PropertiesProxy() override = default; }; DebugModeTool::DebugModeTool(DBus::Connection* connection) : connection_(connection) {} void DebugModeTool::SetDebugMode(const std::string& subsystem, DBus::Error*) { ManagerProxy flimflam(connection_, shill::kFlimflamServicePath, shill::kFlimflamServiceName); PropertiesProxy supplicant(connection_, kSupplicantPath, kSupplicantService); std::string flimflam_tags; DBus::Variant supplicant_value; std::string modemmanager_value = "info"; std::string supplicant_level = "info"; if (subsystem == "wifi") { flimflam_tags = "service+wifi+inet+device+manager"; supplicant_level = "msgdump"; } else if (subsystem == "wimax") { flimflam_tags = "service+wimax+device+manager"; } else if (subsystem == "cellular") { flimflam_tags = "service+cellular+modem+device+manager"; } else if (subsystem == "ethernet") { flimflam_tags = "service+ethernet+device+manager"; } else if (subsystem == "none") { flimflam_tags = ""; } flimflam.SetDebugTags(flimflam_tags); if (flimflam_tags.length()) { flimflam.SetDebugLevel(kFlimflamLogLevelVerbose3); } else { flimflam.SetDebugLevel(kFlimflamLogLevelInfo); } supplicant_value.writer().append_string(supplicant_level.c_str()); supplicant.Set(kSupplicantIface, "DebugLevel", supplicant_value); SetAllModemManagersLogging(modemmanager_value); } void DebugModeTool::GetAllModemManagers(std::vector<std::string>* managers) { #if USE_CELLULAR managers->clear(); DBus::CallMessage msg; DBus::MessageIter iter; msg.destination(dbus::kDBusInterface); msg.interface(dbus::kDBusInterface); msg.member(kDBusListNames); msg.path(dbus::kDBusServicePath); DBus::Message ret = connection_->send_blocking(msg, -1); iter = ret.reader(); iter = iter.recurse(); while (!iter.at_end()) { std::string name(iter.get_string()); if (name.find(kModemManager) != std::string::npos) managers->push_back(name); ++iter; } #endif // USE_CELLULAR } void DebugModeTool::SetAllModemManagersLogging(const std::string& level) { #if USE_CELLULAR std::vector<std::string> managers; GetAllModemManagers(&managers); for (size_t i = 0; i < managers.size(); ++i) { const std::string& manager = managers[i]; if (manager == cromo::kCromoServiceName) { ModemManagerProxy modemmanager(connection_, cromo::kCromoServicePath, cromo::kCromoServiceName); modemmanager.SetLogging(level == "err" ? "error" : level); } else if (manager == modemmanager::kModemManager1ServiceName) { ModemManager1Proxy modemmanager(connection_, modemmanager::kModemManager1ServicePath, modemmanager::kModemManager1ServiceName); modemmanager.SetLogging(level); } } #endif // USE_CELLULAR } } // namespace debugd
34.163636
79
0.674827
[ "vector" ]
fdb9b69d744f757fd09b740878006270bb630c7c
1,763
hpp
C++
samples/qt/photo-book/mainwindow.hpp
intel/umf
3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa
[ "Apache-2.0" ]
13
2018-01-23T22:05:21.000Z
2020-04-21T15:19:29.000Z
samples/qt/photo-book/mainwindow.hpp
intel/umf
3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa
[ "Apache-2.0" ]
10
2015-08-25T22:20:23.000Z
2016-06-08T10:13:26.000Z
samples/qt/photo-book/mainwindow.hpp
01org/vmf
3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa
[ "Apache-2.0" ]
10
2015-11-16T14:19:31.000Z
2016-08-18T21:44:07.000Z
#ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP #include <QMainWindow> #include <QGraphicsScene> #include <QGraphicsPixmapItem> #include <QTimer> #include <QLabel> #include "face_recognizer.hpp" #include "metadata_helper.hpp" #include "markup_model.hpp" #include "photo_book.hpp" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(const cv::String& cascadesPath, QWidget *parent = 0); ~MainWindow(); public Q_SLOTS: void openFile(); void showAboutInfo(); void sliderChanged(int value); void detectFaces(); void renewMarkup(); void commitMarkup(); void editUserData(); void associateRectangle(quint64 frameIndex, const FaceRect& r); void personChanged(int index); void onSceneSelection(); void addNewRegion(); void deleteRegion(); protected: void closeEvent(QCloseEvent *evt); private: void loadVideoData(); void loadVideoData(int frameNumber); void showFaceRectangels(MarkupModel::FrameIndex index); void scrollFrame(int delta); bool eventFilter(QObject *obj, QEvent *ev); void fillPeopleList(); void clearPersonInfo(); bool checkSave(); void clearWidgets(); void enableWidgets(bool bEnabled); private: Ui::MainWindow *ui; QGraphicsScene *scene; cv::VideoCapture capture; qint64 totalFrames; cv::Mat currentFrameImg; QTimer *timer; FaceRecognizer recognizer; std::vector<FaceRect> currentFaces; int videoWidth; int videoHeight; MetadataHelper metadataHelper; std::string currentFileName; MarkupModel markupModel; quint64 currentFrameNumber; bool disableRectAssociate; QLabel *lblFrameNumber; }; #endif // MAINWINDOW_HPP
22.896104
77
0.716393
[ "vector" ]
fdbc73751844247118a1864c16b44e6c9ab5a25d
23,406
cpp
C++
src/terrain.cpp
clayne/fo76utils
a004089445f92f0a16f627224ef5085395246f16
[ "MIT" ]
null
null
null
src/terrain.cpp
clayne/fo76utils
a004089445f92f0a16f627224ef5085395246f16
[ "MIT" ]
null
null
null
src/terrain.cpp
clayne/fo76utils
a004089445f92f0a16f627224ef5085395246f16
[ "MIT" ]
null
null
null
#include "common.hpp" #include "filebuf.hpp" #include <thread> static int landWidth = 0; static int landHeight = 0; static unsigned int renderWidth = 0; static unsigned int renderHeight = 0; static unsigned int imageWidth = 0; static unsigned int imageHeight = 0; static int renderMode = 0; // 0: SE, 1: SW, 2: NW, 3: NE, 4: 2D static int xOffset = 0; static int yOffset = 0; static int renderScale = 8; static unsigned int heightScale = 9728; static unsigned int waterLevel = 0; static unsigned int waterColor = 0x60004080U; static int lightOffsX = 256; static int lightOffsY = 256; static unsigned int textureWidth = 0; static unsigned int textureHeight = 0; static unsigned char textureScale = 0; static bool ltexRGBFormat = false; static unsigned long long ltexPalette[256]; static const unsigned char *hmapBuf = (unsigned char *) 0; static const unsigned char *ltexBuf = (unsigned char *) 0; static const unsigned char *wmapBuf = (unsigned char *) 0; static std::vector< unsigned short > zDiffColorMult; static std::vector< unsigned char > outBuf; static void loadLTexPalette(const char *fileName) { for (size_t i = 0; i < 256; i++) ltexPalette[i] = 0x0000010000100001ULL * (unsigned int) i; if (!fileName) return; FileBuffer inFile(fileName); unsigned long long tmp1 = 0x01; int tmp2 = -1; const unsigned char *p = inFile.getDataPtr(); size_t k = 0; for (size_t i = 0; i < inFile.size(); i++) { char c = char(p[i]); if (c >= '0' && c <= '9') { if (tmp2 < 0) tmp2 = 0; else tmp2 = tmp2 * 10; tmp2 = tmp2 + (c - '0'); } if ((i + 1) >= inFile.size()) c = '\n'; if (tmp2 >= 0 && !(c >= '0' && c <= '9')) { if (tmp1 < 0x1000000000000000ULL) tmp1 = (tmp1 << 20) | (unsigned int) tmp2; tmp2 = -1; } if (c == '\n') { if (tmp1 >= 0x1000000000000000ULL && k < 256) { ltexPalette[k] = tmp1 & 0x0FFFFFFFFFFFFFFFULL; k++; } tmp1 = 0x01; } } } static inline bool checkLandXY(int x, int y) { return ((unsigned int) x < (unsigned int) (landWidth << 8) && (unsigned int) y < (unsigned int) (landHeight << 8)); } static inline unsigned int getVertexHeight(int x, int y, const unsigned char *buf) { unsigned int w = (unsigned int) landWidth; unsigned int x0 = (unsigned int) x >> 8; unsigned int x1 = x0 + (unsigned int) ((x0 + 1) < w); unsigned int y0 = (unsigned int) y >> 8; unsigned int y1 = y0 + (unsigned int) ((y0 + 1) < (unsigned int) landHeight); unsigned int z0 = FileBuffer::readUInt16Fast(buf + ((y0 * w + x0) << 1)); unsigned int z1 = FileBuffer::readUInt16Fast(buf + ((y0 * w + x1) << 1)); unsigned int z2 = FileBuffer::readUInt16Fast(buf + ((y1 * w + x0) << 1)); unsigned int z3 = FileBuffer::readUInt16Fast(buf + ((y1 * w + x1) << 1)); unsigned int xf = x & 0xFF; z0 = (z0 * (256U - xf)) + (z1 * xf); z2 = (z2 * (256U - xf)) + (z3 * xf); unsigned int yf = y & 0xFF; // return 18-bit height return (((z0 * (256U - yf)) + (z2 * yf) + 8192U) >> 14); } static inline unsigned long long getLTexRGBPixel(unsigned int x, unsigned int y) { size_t offs = (y * textureWidth + x) * 3U; return ((unsigned long long) ltexBuf[offs] | ((unsigned long long) ltexBuf[offs + 1] << 20) | ((unsigned long long) ltexBuf[offs + 2] << 40)); } static inline unsigned long long getVertexColor(int x, int y) { if (!ltexBuf) return 0x0000FF000FF000FFULL; x = x << textureScale; y = y << textureScale; unsigned int x0 = (unsigned int) x >> 8; unsigned int x1 = x0 + (unsigned int) ((x0 + 1) < textureWidth); unsigned int y0 = (unsigned int) y >> 8; unsigned int y1 = y0 + (unsigned int) ((y0 + 1) < textureHeight); unsigned long long c0, c1, c2, c3; if (ltexRGBFormat) { c0 = getLTexRGBPixel(x0, y0); c1 = getLTexRGBPixel(x1, y0); c2 = getLTexRGBPixel(x0, y1); c3 = getLTexRGBPixel(x1, y1); } else { c0 = ltexPalette[ltexBuf[y0 * textureWidth + x0]]; c1 = ltexPalette[ltexBuf[y0 * textureWidth + x1]]; c2 = ltexPalette[ltexBuf[y1 * textureWidth + x0]]; c3 = ltexPalette[ltexBuf[y1 * textureWidth + x1]]; } unsigned int xf = x & 0xFF; c0 = ((c0 * (256U - xf)) + (c1 * xf) + 0x0000080000800008ULL) & 0x00FFF00FFF00FFF0ULL; c2 = ((c2 * (256U - xf)) + (c3 * xf) + 0x0000080000800008ULL) & 0x00FFF00FFF00FFF0ULL; unsigned int yf = y & 0xFF; return ((((c0 * (256U - yf)) + (c2 * yf) + 0x0080000800008000ULL) >> 16) & 0x0000FF000FF000FFULL); } static inline void renderPixels(unsigned long long *lineBufRGB, unsigned int y0, unsigned int y1, unsigned long long c) { unsigned char s = (unsigned char) (renderScale + 8); unsigned int f0 = (y0 >> (s - 8)) & 0xFF; y0 = y0 >> s; unsigned int f1 = (y1 >> (s - 8)) & 0xFF; y1 = y1 >> s; if (y0 == y1) { lineBufRGB[y0] = lineBufRGB[y0] + (c * (f1 - f0)); return; } lineBufRGB[y0] = lineBufRGB[y0] + (c * (256U - f0)); while (++y0 < y1) lineBufRGB[y0] = lineBufRGB[y0] + (c << 8); lineBufRGB[y0] = lineBufRGB[y0] + (c * f1); } void renderLine2D(unsigned long long *lineBufRGB, int x0, int y0) { unsigned int waterAlpha = (waterColor >> 24) << 1; unsigned long long waterRGB = ((unsigned long long) (waterColor & 0x00FF0000) << 24) | ((unsigned long long) (waterColor & 0x0000FF00) << 12) | (unsigned long long) (waterColor & 0x000000FF); waterRGB = waterRGB * ((waterAlpha * zDiffColorMult[65536] + 128U) >> 8) + 0x0000800008000080ULL; waterAlpha = 256 - waterAlpha; int d = (renderScale >= 7 ? 128 : (1 << renderScale)); for (int offs = 0; offs < int(renderHeight << 6); offs = offs + d, y0 = y0 - d) { unsigned int z = 0; unsigned int w = waterLevel; unsigned long long c = 0; if (checkLandXY(x0, y0)) { z = getVertexHeight(x0, y0, hmapBuf); if (wmapBuf) w = getVertexHeight(x0, y0, wmapBuf); c = getVertexColor(x0, y0); } int zDiff = 0; if (checkLandXY(x0 + lightOffsX, y0 + lightOffsY)) zDiff = int(getVertexHeight(x0 + lightOffsX, y0 + lightOffsY, hmapBuf)); zDiff = int(z) + 65536 - zDiff; zDiff = (zDiff >= 0 ? (zDiff <= 131071 ? zDiff : 131071) : 0); c = c * (unsigned int) zDiffColorMult[zDiff]; c = ((c + 0x0000800008000080ULL) >> 8) & 0x0003FF003FF003FFULL; if (z < w) { unsigned long long c2 = waterRGB; if (checkLandXY(x0 + lightOffsX, y0 + lightOffsY)) { zDiff = int(getVertexHeight(x0 + lightOffsX, y0 + lightOffsY, wmapBuf)); if (zDiff != int(w) && zDiff > int(waterLevel)) { zDiff = int(w) - zDiff; zDiff = (zDiff >= -65536 ? (zDiff <= 65535 ? zDiff : 65535) : -65536); c2 = (c2 >> 8) & 0x0003FF003FF003FFULL; c2 = c2 * (unsigned int) zDiffColorMult[zDiff + 196608]; c2 = c2 + 0x0000800008000080ULL; } } c = ((c * waterAlpha + c2) >> 8) & 0x0003FF003FF003FFULL; } renderPixels(lineBufRGB, (unsigned int) offs << 8, (unsigned int) (offs + d) << 8, c); } } void renderLineIsometric(unsigned long long *lineBufRGB, int x0, int y0) { unsigned int waterAlpha = (waterColor >> 24) << 1; unsigned long long waterRGB = ((unsigned long long) (waterColor & 0x00FF0000) << 24) | ((unsigned long long) (waterColor & 0x0000FF00) << 12) | (unsigned long long) (waterColor & 0x000000FF); waterRGB = waterRGB * ((waterAlpha * zDiffColorMult[65536] + 128U) >> 8) + 0x0000800008000080ULL; waterAlpha = 256 - waterAlpha; int d = 4730; if (renderScale < 7) d = ((d >> (6 - renderScale)) + 1) >> 1; int prvLineOffs = 0; bool wasLand = false; for (int offs = -(int((heightScale + 1) << 12)); prvLineOffs < int(renderHeight << 13); offs = offs + d) { int lineOffs = offs; int landOffs = int(((unsigned int) offs + 0x80000040U) >> 7) - 0x01000000; int x = x0 + (!((renderMode + 1) & 2) ? -landOffs : landOffs); int y = y0 + (!(renderMode & 2) ? -landOffs : landOffs); bool isLand = checkLandXY(x, y); unsigned int z = 0; unsigned int w = waterLevel; unsigned long long c = 0; if (!isLand) { if (!wasLand || w == 0) { prvLineOffs = (lineOffs > prvLineOffs ? lineOffs : prvLineOffs); wasLand = isLand; continue; } lineOffs += int((w * heightScale + 0x040000) >> 6); } else { z = getVertexHeight(x, y, hmapBuf); if (wmapBuf) w = getVertexHeight(x, y, wmapBuf); c = getVertexColor(x, y); lineOffs += int((z * heightScale + 0x040000) >> 6); if (!wasLand && lineOffs > d) prvLineOffs = lineOffs - d; } if (lineOffs <= prvLineOffs) { wasLand = isLand; continue; } int zDiff = 0; if (checkLandXY(x + lightOffsX, y + lightOffsY)) zDiff = int(getVertexHeight(x + lightOffsX, y + lightOffsY, hmapBuf)); zDiff = int(z) + 65536 - zDiff; zDiff = (zDiff >= 0 ? (zDiff <= 131071 ? zDiff : 131071) : 0); c = c * (unsigned int) zDiffColorMult[zDiff]; c = ((c + 0x0000800008000080ULL) >> 8) & 0x0003FF003FF003FFULL; if (z < w) { unsigned long long c2 = waterRGB; if (checkLandXY(x + lightOffsX, y + lightOffsY)) { zDiff = int(getVertexHeight(x + lightOffsX, y + lightOffsY, wmapBuf)); if (zDiff != int(w) && zDiff > int(waterLevel)) { zDiff = int(w) - zDiff; zDiff = (zDiff >= -65536 ? (zDiff <= 65535 ? zDiff : 65535) : -65536); c2 = (c2 >> 8) & 0x0003FF003FF003FFULL; c2 = c2 * (unsigned int) zDiffColorMult[zDiff + 196608]; c2 = c2 + 0x0000800008000080ULL; } } c = ((c * waterAlpha + c2) >> 8) & 0x0003FF003FF003FFULL; } if (lineOffs > int(renderHeight << 13)) lineOffs = int(renderHeight << 13); renderPixels(lineBufRGB, (unsigned int) prvLineOffs << 1, (unsigned int) lineOffs << 1, c); prvLineOffs = lineOffs; wasLand = isLand; } } void renderThread(size_t xMin, size_t xMax) { std::vector< unsigned long long > lineBufRGB(imageHeight + 1, 0); int x0 = xOffset * 256 + (landWidth << 7); int y0 = yOffset * 256 + (landHeight << 7); if (renderMode == 4) { int offs = (1 << renderScale) >> (textureScale + 2); x0 = x0 - int(renderWidth << 5) - offs; y0 = y0 + int(renderHeight << 5) + offs; } else { int w = int((renderWidth * 2365U + 64) >> 7); int h = int(renderHeight << 5); x0 = x0 + (!((renderMode + 1) & 2) ? h : -h) + (!(renderMode & 2) ? -w : w); y0 = y0 + (!(renderMode & 2) ? h : -h) + (!((renderMode + 1) & 2) ? w : -w); } for (size_t x = xMin; x < xMax; ) { for (size_t i = 0; i < 2; i++, x = x + size_t(1 << (renderScale - 1))) { if (renderMode == 4) { renderLine2D(&(lineBufRGB.front()), x0 + int(x), y0); } else { int offs = int(((unsigned int) x * 2365ULL + 2048U) >> 12); renderLineIsometric(&(lineBufRGB.front()), x0 + (!(renderMode & 2) ? offs : -offs), y0 + (!((renderMode + 1) & 2) ? -offs : offs)); } } for (size_t i = 0; i < imageHeight; i++) { unsigned long long c = lineBufRGB[i]; lineBufRGB[i] = 0; unsigned int r = (((unsigned int) (c >> 48) & 0x0FFF) + 1) >> 1; unsigned int g = (((unsigned int) (c >> 28) & 0x0FFF) + 1) >> 1; unsigned int b = (((unsigned int) (c >> 8) & 0x0FFF) + 1) >> 1; unsigned char *p = &(outBuf.front()) + (((imageHeight - (i + 1)) * imageWidth + ((x - 1) >> renderScale)) * 3); p[0] = (unsigned char) (b < 255 ? b : 255); p[1] = (unsigned char) (g < 255 ? g : 255); p[2] = (unsigned char) (r < 255 ? r : 255); } } } int main(int argc, char **argv) { int lightMultL = 88; int lightMultZ = 100; int lightPow = 35; int threadCnt = int(std::thread::hardware_concurrency()); threadCnt = (threadCnt > 1 ? (threadCnt < 256 ? threadCnt : 256) : 1); if (argc < 5) { std::fprintf(stderr, "Usage: %s HMAPFILE.DDS OUTFILE.DDS W H [OPTIONS...]\n", argv[0]); std::fprintf(stderr, "Options:\n"); std::fprintf(stderr, " -iso[_se|_sw|_nw|_ne] | -2d\n"); std::fprintf(stderr, " -ltex FILENAME\n"); std::fprintf(stderr, " -ltxpal FILENAME\n"); std::fprintf(stderr, " -lod INT (%d)\n", renderScale - 8); std::fprintf(stderr, " -xoffs INT (%d)\n", xOffset); std::fprintf(stderr, " -yoffs INT (%d)\n", yOffset); std::fprintf(stderr, " -zrange INT (ZMAX - ZMIN, multiplied by 4 for FO76) (%u)\n", heightScale << 4); std::fprintf(stderr, " -waterlevel UINT16 (%u)\n", waterLevel >> 2); std::fprintf(stderr, " -watercolor UINT32_A7R8G8B8 (0x%08X)\n", waterColor); std::fprintf(stderr, " -wmap FILENAME\n"); std::fprintf(stderr, " -light[_nw|_w|_sw|_s|_se|_e|_ne|_n] " "LMULTx100 ZMULTx100 POWx100 (%d %d %d)\n", lightMultL, lightMultZ, lightPow); std::fprintf(stderr, " -threads INT (%d)\n", threadCnt); return 1; } DDSInputFile *ltexFile = (DDSInputFile *) 0; DDSInputFile *wmapFile = (DDSInputFile *) 0; const char *ltexFileName = (char *) 0; const char *ltexPalFileName = (char *) 0; const char *wmapFileName = (char *) 0; try { imageWidth = (unsigned int) parseInteger(argv[3], 0, (char *) 0, 1, 32768); imageHeight = (unsigned int) parseInteger(argv[4], 0, (char *) 0, 1, 32768); unsigned int hdrBuf[11]; int pixelFormat = 0; DDSInputFile hmapFile(argv[1], landWidth, landHeight, pixelFormat, hdrBuf); if (pixelFormat != DDSInputFile::pixelFormatGRAY16) throw errorMessage("invalid height map file pixel format, must be L16"); // "FO", "LAND" if ((hdrBuf[0] & 0xFFFF) == 0x4F46 && hdrBuf[1] == 0x444E414C) { int zMin = uint32ToSigned(hdrBuf[4]); int zMax = uint32ToSigned(hdrBuf[7]); int cellSize = int(hdrBuf[9]); heightScale = (unsigned int) ((zMax - zMin) * cellSize + 256) >> 9; int wLvl = uint32ToSigned(hdrBuf[8]); if (wLvl > zMin) { waterLevel = (unsigned int) roundFloat(float(wLvl - zMin) * 262140.0f / float(zMax - zMin)); } } hmapBuf = hmapFile.getDataPtr(); for (int i = 5; i < argc; i++) { if (std::strcmp(argv[i], "-iso") == 0 || std::strcmp(argv[i], "-iso_se") == 0) { renderMode = 0; } else if (std::strcmp(argv[i], "-iso_sw") == 0) { renderMode = 1; } else if (std::strcmp(argv[i], "-iso_nw") == 0) { renderMode = 2; } else if (std::strcmp(argv[i], "-iso_ne") == 0) { renderMode = 3; } else if (std::strcmp(argv[i], "-2d") == 0) { renderMode = 4; } else if (std::strcmp(argv[i], "-ltex") == 0) { if (++i >= argc) throw errorMessage("missing file name"); ltexFileName = argv[i]; } else if (std::strcmp(argv[i], "-ltxpal") == 0) { if (++i >= argc) throw errorMessage("missing file name"); ltexPalFileName = argv[i]; } else if (std::strcmp(argv[i], "-lod") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); renderScale = int(parseInteger(argv[i], 0, (char *) 0, -5, 4)) + 8; } else if (std::strcmp(argv[i], "-xoffs") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); xOffset = int(parseInteger(argv[i], 0, "invalid X offset", 1 - landWidth, landWidth - 1)); } else if (std::strcmp(argv[i], "-yoffs") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); yOffset = int(parseInteger(argv[i], 0, "invalid Y offset", 1 - landHeight, landHeight - 1)); } else if (std::strcmp(argv[i], "-zrange") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); unsigned int tmp = (unsigned int) parseInteger(argv[i], 0, "invalid Z range", 0, 1000000); heightScale = (tmp + 8U) >> 4; } else if (std::strcmp(argv[i], "-waterlevel") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); waterLevel = (unsigned int) parseInteger(argv[i], 0, "invalid water level", 0, 65536) << 2; } else if (std::strcmp(argv[i], "-watercolor") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); waterColor = (unsigned int) parseInteger(argv[i], 0, "invalid water color", 0, 0x7FFFFFFF); } else if (std::strcmp(argv[i], "-wmap") == 0) { if (++i >= argc) throw errorMessage("missing file name"); wmapFileName = argv[i]; } else if (std::strncmp(argv[i], "-light", 6) == 0) { lightOffsX = 0; lightOffsY = 0; for (const char *p = argv[i] + 6; *p != '\0'; p++) { if (*p == 'N' || *p == 'n') lightOffsY = 256; else if (*p == 'W' || *p == 'w') lightOffsX = 256; else if (*p == 'S' || *p == 's') lightOffsY = -256; else if (*p == 'E' || *p == 'e') lightOffsX = -256; else if (*p != '_') throw errorMessage("invalid light direction"); } if (lightOffsX == 0 && lightOffsY == 0) { lightOffsX = 256; lightOffsY = 256; } if (++i >= argc) throw errorMessage("missing integer argument"); lightMultL = int(parseInteger(argv[i], 0, (char *) 0, 25, 400)); if (++i >= argc) throw errorMessage("missing integer argument"); lightMultZ = int(parseInteger(argv[i], 0, (char *) 0, -4096, 4096)); if (++i >= argc) throw errorMessage("missing integer argument"); lightPow = int(parseInteger(argv[i], 0, (char *) 0, 6, 100)); } else if (std::strcmp(argv[i], "-threads") == 0) { if (++i >= argc) throw errorMessage("missing integer argument"); threadCnt = int(parseInteger(argv[i], 0, "invalid thread count", 1, 64)); } else { throw errorMessage("invalid command line option: \"%s\"", argv[i]); } } if (ltexFileName) { int tmpWidth = 0; int tmpHeight = 0; int tmpPixelFormat = 0; ltexFile = new DDSInputFile(ltexFileName, tmpWidth, tmpHeight, tmpPixelFormat); textureScale = 0; while ((landWidth << textureScale) < tmpWidth && textureScale < 8) textureScale++; textureWidth = (unsigned int) landWidth << textureScale; textureHeight = (unsigned int) landHeight << textureScale; if (tmpWidth != int(textureWidth) || tmpHeight != int(textureHeight)) throw errorMessage("land texture dimensions do not match input file"); if (tmpPixelFormat == DDSInputFile::pixelFormatRGB24) { ltexRGBFormat = true; } else if (tmpPixelFormat == DDSInputFile::pixelFormatGRAY8 || tmpPixelFormat == (DDSInputFile::pixelFormatUnknown + 8)) { ltexRGBFormat = false; } else { throw errorMessage("invalid land texture file pixel format"); } ltexBuf = ltexFile->getDataPtr(); } loadLTexPalette(ltexPalFileName); if (wmapFileName) { int tmpWidth = 0; int tmpHeight = 0; int tmpPixelFormat = 0; wmapFile = new DDSInputFile(wmapFileName, tmpWidth, tmpHeight, tmpPixelFormat); if (tmpWidth != landWidth || tmpHeight != landHeight) { throw errorMessage("water height map dimensions " "do not match input file"); } if (tmpPixelFormat != DDSInputFile::pixelFormatGRAY16) throw errorMessage("invalid water height map file pixel format"); wmapBuf = wmapFile->getDataPtr(); } renderWidth = (imageWidth << renderScale) >> 6; renderHeight = (imageHeight << renderScale) >> 6; if (((renderWidth << 6) >> renderScale) != imageWidth || ((renderHeight << 6) >> renderScale) != imageHeight) { throw errorMessage("invalid output image dimensions"); } zDiffColorMult.resize(262144); for (int i = 0; i < 131072; i++) { double x = double(i - 65536) * double(lightMultZ * int(heightScale)); if (lightOffsX == 0 || lightOffsY == 0) x = x * (1.0 / 11863283.2); else x = x * (1.0 / 16777216.0); if (x < 0.0) x = (x * 2.0 - 1.0) / (x - 1.0); else x = 1.0 / (x + 1.0); x = std::pow(x, double(lightPow) / 100.0); int tmp = int(x * 256.0 * (double(lightMultL) / 100.0) + 0.5); zDiffColorMult[i] = (unsigned short) (tmp < 1023 ? tmp : 1023); tmp = int(x * 256.0 + 0.5); zDiffColorMult[i + 131072] = (unsigned short) (tmp < 1023 ? tmp : 1023); } outBuf.resize(size_t(imageWidth) * imageHeight * 3); if (threadCnt > int(imageWidth)) threadCnt = int(imageWidth); std::vector< std::thread * > threads(size_t(threadCnt), (std::thread *) 0); try { size_t prvX = 0; for (size_t i = 0; i < threads.size(); i++) { size_t x = ((i + 1) * imageWidth / threads.size()) << renderScale; threads[i] = new std::thread(renderThread, prvX, x); prvX = x; } } catch (...) { for (size_t i = 0; i < threads.size(); i++) { if (threads[i]) { threads[i]->join(); delete threads[i]; } } throw; } for (size_t i = 0; i < threads.size(); i++) { threads[i]->join(); delete threads[i]; } DDSOutputFile outFile(argv[2], int(imageWidth), int(imageHeight), DDSInputFile::pixelFormatRGB24, (unsigned int *) 0, 0); outFile.writeData(&(outBuf.front()), sizeof(unsigned char) * outBuf.size()); if (ltexFile) delete ltexFile; if (wmapFile) delete wmapFile; } catch (std::exception& e) { if (ltexFile) delete ltexFile; if (wmapFile) delete wmapFile; std::fprintf(stderr, "%s: %s\n", argv[0], e.what()); return 1; } return 0; }
34.62426
80
0.534521
[ "vector" ]
fdbe28df517b78062dc07d23f6a7d4e37e4efe4e
2,170
cc
C++
stapl_release/docs/tutorial_guide/ex_303.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/docs/tutorial_guide/ex_303.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/docs/tutorial_guide/ex_303.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <fstream> #include "ch3.hpp" typedef stapl::vector< ary_int_tp > vec_ary_int_tp; // ## 1 typedef stapl::vector_view<vec_ary_int_tp> vec_ary_int_vw_tp; typedef stapl::array< vec_int_tp > ary_vec_int_tp; // ## 2 typedef stapl::array_view<ary_vec_int_tp> ary_vec_int_vw_tp; size_t ex_303(size_t, stapl::stream<ifstream> &, stapl::stream<ofstream> &); stapl::exit_code stapl_main(int argc, char **argv) { stapl::stream<ifstream> zin; stapl::stream<ofstream> zout; zout.open("ex_303.out"); int model = 1; stapl::do_once( msg( zout, "Example 303" ) ); int result = ex_303(model, zin, zout); stapl::do_once( msg_val<int>( zout, "Result ", result ) ); return EXIT_SUCCESS; } struct ex_303_fill_wf { typedef void result_type; template <typename View1> result_type operator()(View1 const &vw1) { stapl::iota( vw1, 0 ); } }; struct ex_303_show_wf { private: stapl::stream<ofstream> m_zout; public: ex_303_show_wf(stapl::stream<ofstream> const& zout) : m_zout(zout) { } typedef void result_type; template <typename View1> result_type operator()(View1 const &vw1) { stapl::serial_io(put_val_wf(m_zout), vw1); stapl::do_once( msg( m_zout, "" ) ); } void define_type(stapl::typer& t) { t.member(m_zout); } }; size_t ex_303( size_t model, stapl::stream<ifstream> &zin, stapl::stream<ofstream> &zout) { size_t outer = 100 * model; size_t inner = 100 * model; ary_sz_tp len(outer); ary_sz_vw_tp len_vw(len); stapl::map_func(roll_wf(), len_vw, stapl::make_repeat_view(inner)); // ## 3 vec_ary_int_tp a(len_vw); vec_ary_int_vw_tp a_vw(a); ary_vec_int_tp b(len_vw); ary_vec_int_vw_tp b_vw(b); stapl::map_func(ex_303_fill_wf(), a_vw ); // ## 4 stapl::do_once( msg( zout, "a:" ) ); stapl::serial_io(ex_303_show_wf(zout), a_vw ); // ## 5 stapl::do_once( msg( zout, "\n" ) ); stapl::map_func(ex_303_fill_wf(), b_vw ); stapl::do_once( msg( zout, "b:" ) ); stapl::serial_io(ex_303_show_wf(zout), b_vw ); stapl::do_once( msg( zout, "\n" ) ); int res = stapl::map_reduce(nested_cksum_wf(), xor_un_wf(), a_vw); return res; }
26.144578
77
0.670507
[ "vector", "model" ]
fdc2d8a2ddff73e473a86d53289071d1a4d2bd59
28,258
cpp
C++
plugins/code/hevc_enc/beamr/src/hevc_enc_beamr_impl.cpp
DolbyLaboratories/dolby-encoding-engine
c44344319f7e1dcf9b5002ea7c13421f4e8d16a2
[ "BSD-3-Clause" ]
52
2018-02-26T11:12:22.000Z
2022-03-31T10:42:43.000Z
plugins/code/hevc_enc/beamr/src/hevc_enc_beamr_impl.cpp
DolbyLaboratories/dolby-encoding-engine
c44344319f7e1dcf9b5002ea7c13421f4e8d16a2
[ "BSD-3-Clause" ]
3
2017-12-12T18:46:45.000Z
2019-06-03T21:29:11.000Z
plugins/code/hevc_enc/beamr/src/hevc_enc_beamr_impl.cpp
DolbyLaboratories/dolby-encoding-engine
c44344319f7e1dcf9b5002ea7c13421f4e8d16a2
[ "BSD-3-Clause" ]
14
2018-01-26T15:08:39.000Z
2022-03-19T00:28:41.000Z
/* * BSD 3-Clause License * * Copyright (c) 2019, Dolby Laboratories * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hevc_enc_beamr_impl.h" #include "hevc_enc_beamr_utils.h" #include <algorithm> #include <cstdarg> #include <cstdio> #include <exception> #include <fstream> #include <map> void prologue(void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line) { Encoder* enc = static_cast<Encoder*>(ctx); if (enc->debugLevel > 1) { std::cerr << "(" << parent << "::" << line << ") "; std::cerr << "prologue: " << func << "(" << vaargs << ")" << std::endl; } } template <typename RetvalType> void epilogue(void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line, RetvalType) { Encoder* enc = static_cast<Encoder*>(ctx); if (enc->debugLevel > 1) { std::cerr << "(" << parent << "::" << line << ") "; std::cerr << "epilogue: " << func << "(" << vaargs << ")" << std::endl; } } template <typename RetvalType> void epilogueWithRetval( void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line, RetvalType retval) { Encoder* enc = static_cast<Encoder*>(ctx); if (enc->debugLevel > 1) { std::cerr << "(" << parent << "::" << line << ") "; std::cerr << "epilogue: " << func << "(" << vaargs << ") - returned " << retval << std::endl; } } template <> void epilogue(void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line, double retval) { epilogueWithRetval(ctx, func, vaargs, parent, line, retval); } template <> void epilogue(void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line, int retval) { epilogueWithRetval(ctx, func, vaargs, parent, line, retval); } template <> void epilogue(void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line, size_t retval) { epilogueWithRetval(ctx, func, vaargs, parent, line, retval); } template <> void epilogue(void* ctx, const char* func, const char* vaargs, const char* parent, unsigned int line, bool retval) { epilogueWithRetval(ctx, func, vaargs, parent, line, retval); } extern "C" { hevc_error_t VSSHSDKAPI cb_rec_send(void* ctx, const vh3_Picture* pic, vh3_RecPictureInfo info) { Encoder* enc = static_cast<Encoder*>(ctx); FUNCTION_P_RETVALA(enc, retval, enc->recSend, pic, info); return retval; } hevc_error_t VSSHSDKAPI cb_ms_send(void* ctx, const vh3_MediaSample* ms, vh3_NalInfo info) { Encoder* enc = static_cast<Encoder*>(ctx); FUNCTION_P_RETVALA(enc, retval, enc->msSend, ms, info); return retval; } hevc_error_t VSSHSDKAPI cb_notify(void* ctx, vh3_Notification a) { Encoder* enc = static_cast<Encoder*>(ctx); FUNCTION_P_RETVALA(enc, retval, enc->notify, a); return retval; } void cb_settings_change(void* ctx, const char* msg) { Encoder* enc = static_cast<Encoder*>(ctx); FUNCTION_P(enc, enc->settingsChange, msg); } } Encoder::Encoder() : hEnc(NULL) , cbTable({vh3_default_malloc, vh3_default_free, vh3_default_pic_alloc, vh3_default_pic_free, vh3_default_ms_alloc, vh3_default_ms_realloc, vh3_default_ms_free, cb_rec_send, cb_ms_send, cb_notify, this}) { } Encoder::~Encoder() { FUNCTIONV_T(close); if (outBuffer) delete[] outBuffer; } std::string Encoder::getVersion() { return version; } std::string Encoder::getMessage() { std::lock_guard<std::mutex> lck(dataLock); std::string msg; for (auto& x : pendingMsgs) { if (msg.size()) msg += "\n"; msg += x; } pendingMsgs.clear(); return msg; } void Encoder::checkPendingErrors() { std::string errMsg; { std::lock_guard<std::mutex> lck(dataLock); if (pendingErrors.size()) { for (auto& x : pendingErrors) { if (errMsg.size()) errMsg += "\n"; errMsg += x; } } } if (errMsg.size()) error("%s", errMsg.c_str()); } void Encoder::checkErrorCode(const hevc_error_t errCode) { if (errCode != HEVC_OK) { if (errCode > HEVC_OK) message("%s (%d)", hevc_error_text(errCode), (int)errCode); else error("%s (%d)", hevc_error_text(errCode), (int)errCode); } } static std::map<std::string, hevc_rate_control_types_e> multi_pass2int = { {"off", HEVC_RATE_CONTROL_VBR}, // VBR {"1st", HEVC_RATE_CONTROL_DUAL_PASS_0}, // dual pass - 1st pass {"nth", HEVC_RATE_CONTROL_DUAL_PASS_0}, // dual pass - 1st pass {"last", HEVC_RATE_CONTROL_DUAL_PASS_1}, // dual pass - 2nd pass }; static std::map<std::string, hevc_presets_e> preset2int = { {"insanely_slow", HEVC_PRESET_INSANELY_SLOW}, {"ultra_slow", HEVC_PRESET_ULTRA_SLOW}, {"very_slow", HEVC_PRESET_VERY_SLOW}, {"slower", HEVC_PRESET_SLOWER}, {"slow", HEVC_PRESET_SLOW}, {"medium", HEVC_PRESET_MEDIUM}, {"medium_plus", HEVC_PRESET_MEDIUM_PLUS}, {"fast", HEVC_PRESET_FAST}, {"faster", HEVC_PRESET_FASTER}, {"ultra_fast", HEVC_PRESET_ULTRA_FAST}, {"insanely_fast", HEVC_PRESET_INSANELY_FAST}, // Can be set, but not explicitly exposed in DEE interface {"broadcast", HEVC_PRESET_BROADCAST}, {"vod", HEVC_PRESET_VOD}, {"ultralow_bitrate", HEVC_PRESET_ULTRALOW_BITRATE}, }; uint16_t Encoder::presetValue(const std::string& str) { uint16_t value = 0; if (!preset2int.count(str)) error("Unknown preset - %s", str.c_str()); else value = (uint16_t)preset2int[str]; return value; } static std::map<std::string, hevc_modifiers_e> modifier2int = { {"low_delay", HEVC_MOD_LOW_DELAY}, {"tune_psnr", HEVC_MOD_TUNE_PSNR}, {"realtime", HEVC_MOD_REALTIME}, {"cinema", HEVC_MOD_CINEMA}, {"bluray", HEVC_MOD_BLURAY}, {"hdr10", HEVC_MOD_HDR10}, {"hlg", HEVC_MOD_HLG}, {"tune_vmaf", HEVC_MOD_TUNE_VMAF}, {"low_bitrate", HEVC_MOD_LOW_BITRATE}, }; uint32_t Encoder::modifierValue(const std::string& str) { uint32_t mask = 0; auto tokens = split(str, "+"); for (auto& x : tokens) { if (!modifier2int.count(x)) { error("Unknown modifier - %s", x.c_str()); continue; } mask |= modifier2int[x]; } return mask; } void Encoder::init(PluginCtrl& ctrl) { hevc_error_t errCode = HEVC_OK; debugLevel = ctrl.debug_level; int major, minor, rev, build; FUNCTION_T_RETVAL(errCode, hevc_get_version, 0, &major, &minor, &rev, &build); version += " v." + std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(rev) + "." + std::to_string(build); checkErrorCode(errCode); memset(&settings, 0, sizeof(settings)); settings.size = sizeof(settings); FUNCTION_T_RETVAL(errCode, hevce_default_settings, &settings); checkErrorCode(errCode); hevce_init_settings_t initSettings; memset(&initSettings, 0, sizeof(initSettings)); initSettings.size = sizeof(initSettings); if (ctrl.preset.size()) initSettings.preset = presetValue(ctrl.preset); if (ctrl.modifier.size()) initSettings.modifier = modifierValue(ctrl.modifier); initSettings.width = ctrl.width; initSettings.height = ctrl.height; FUNCTION_T_RETVAL(errCode, hevce_init_settings, &settings, &initSettings, 0); checkErrorCode(errCode); settings.stream[0].params.bit_depth_chroma = settings.input.bit_depth_chroma = ctrl.bit_depth; settings.stream[0].params.bit_depth_luma = settings.input.bit_depth_luma = ctrl.bit_depth; settings.input.colorspace = VH3_YUV_420; settings.input.chroma_bytes_per_pel = ctrl.bit_depth > 8 ? 2 : 1; settings.input.luma_bytes_per_pel = ctrl.bit_depth > 8 ? 2 : 1; settings.input.width = ctrl.width; settings.input.height = ctrl.height; auto fp = string2FramePeriod(ctrl.frame_rate); settings.gop.time_scale = fp.timeScale; settings.gop.num_units_in_tick = fp.numUnitsInTick; settings.stream[0].rc.type = (int8_t)multi_pass2int[ctrl.multi_pass]; settings.stream[0].rc.kbps = (int32_t)ctrl.data_rate; settings.stream[0].rc.max_kbps = (int32_t)ctrl.max_vbv_data_rate; settings.stream[0].rc.vbv_size = (uint32_t)ctrl.vbv_buffer_size; settings.stream[0].vui.video_signal_type_present_flag = 1; settings.stream[0].vui.video_full_range_flag = ctrl.range == "full" ? 1 : 0; settings.stream[0].vui.colour_description_present_flag = 1; settings.stream[0].vui.colour_primaries = (uint8_t)color_primaries2int(ctrl.color_primaries); settings.stream[0].vui.transfer_characteristics = (uint8_t)transfer_characteristics2int(ctrl.transfer_characteristics); settings.stream[0].vui.matrix_coeffs = (uint8_t)matrix_coefficients2int(ctrl.matrix_coefficients); settings.stream[0].vui.chroma_loc_info_present_flag = 1; settings.stream[0].vui.chroma_sample_loc_type_top_field = (uint8_t)ctrl.chromaloc; settings.stream[0].vui.chroma_sample_loc_type_bottom_field = (uint8_t)ctrl.chromaloc; settings.stream[0].sei.mastering_display_colour_volume_flag = (ctrl.mastering_display_sei_x1 >= 0 && ctrl.mastering_display_sei_y1 >= 0 && ctrl.mastering_display_sei_x2 >= 0 && ctrl.mastering_display_sei_y2 >= 0 && ctrl.mastering_display_sei_x3 >= 0 && ctrl.mastering_display_sei_y3 >= 0 && ctrl.mastering_display_sei_wx >= 0 && ctrl.mastering_display_sei_wy >= 0 && ctrl.mastering_display_sei_max_lum >= 0 && ctrl.mastering_display_sei_min_lum >= 0); if (settings.stream[0].sei.mastering_display_colour_volume_flag) { settings.stream[0].sei.mastering_display_colour_volume.display_primaries_x[0] = (uint16_t)ctrl.mastering_display_sei_x1; settings.stream[0].sei.mastering_display_colour_volume.display_primaries_y[0] = (uint16_t)ctrl.mastering_display_sei_y1; settings.stream[0].sei.mastering_display_colour_volume.display_primaries_x[1] = (uint16_t)ctrl.mastering_display_sei_x2; settings.stream[0].sei.mastering_display_colour_volume.display_primaries_y[1] = (uint16_t)ctrl.mastering_display_sei_y2; settings.stream[0].sei.mastering_display_colour_volume.display_primaries_x[2] = (uint16_t)ctrl.mastering_display_sei_x3; settings.stream[0].sei.mastering_display_colour_volume.display_primaries_y[2] = (uint16_t)ctrl.mastering_display_sei_y3; settings.stream[0].sei.mastering_display_colour_volume.white_point_x = (uint16_t)ctrl.mastering_display_sei_wx; settings.stream[0].sei.mastering_display_colour_volume.white_point_y = (uint16_t)ctrl.mastering_display_sei_wy; settings.stream[0].sei.mastering_display_colour_volume.max_display_mastering_luminance = (uint32_t)ctrl.mastering_display_sei_max_lum; settings.stream[0].sei.mastering_display_colour_volume.min_display_mastering_luminance = (uint32_t)ctrl.mastering_display_sei_min_lum; } settings.stream[0].sei.content_light_level_info_flag = (ctrl.light_level_max_content >= 0 && ctrl.light_level_max_frame_average >= 0); if (settings.stream[0].sei.content_light_level_info_flag) { settings.stream[0].sei.content_light_level_info.max_content_light_level = (uint16_t)ctrl.light_level_max_content; settings.stream[0].sei.content_light_level_info.max_pic_average_light_level = (uint16_t)ctrl.light_level_max_frame_average; } settings.gop.intra_period = ctrl.gop_intra_period; settings.gop.idr_period = ctrl.gop_idr_period; settings.gop.min_intra_period = ctrl.gop_min_intra_period; settings.gop.minigop_size = ctrl.gop_minigop_size; settings.gop.min_minigop_size = ctrl.gop_min_minigop_size; settings.gop.max_refs = ctrl.gop_max_refs; settings.me.scene_change = ctrl.me_scene_change; settings.stream[0].params.pps_cb_qp_offset = ctrl.pps_cb_qp_offset; settings.stream[0].params.pps_cr_qp_offset = ctrl.pps_cr_qp_offset; settings.stream[0].sei.pic_timing_flag = 1; settings.stream[0].vui.aspect_ratio_info_present_flag = 1; settings.stream[0].vui.aspect_ratio_idc = 1; // 1:1 (square) settings.gop.flags |= HEVC_GOP_ADD_AUD | HEVC_GOP_SPS_FOR_EACH_IDR; settings.gop.flags &= ~HEVC_GOP_NO_IDR_ON_SCENE_CHANGE; settings.stream[0].rc.flags |= HEVC_RC_FORCE_HRD_INFO; if (ctrl.uhd_bd) { message("Forcing UHD-BD/Dolby Vision profile 7 params."); settings.stream[0].modifier |= 0x20; settings.stream[0].params.general_profile_idc = 2; settings.stream[0].params.general_level_idc = 153; settings.stream[0].params.general_tier_flag = 1; for (int i = 0; i < VH3_MAX_T_LAYERS; i++) { settings.stream[0].params.layers[i].profile_idc = 2; settings.stream[0].params.layers[i].level_idc = 153; settings.stream[0].params.layers[i].tier_flag = 1; } } std::list<std::string> str; for (auto& tag : ctrl.param) { auto params = split(tag, ":"); for (auto& x : params) { auto kv = split(x, "="); if ("stats_file" == kv[0] || "dualpass-file" == kv[0]) { if (kv.size() > 1) ctrl.stats_file = kv[1]; continue; } str.push_back(x); } } if (str.size()) { std::vector<char*> argv; for (auto& x : str) argv.push_back((char*)x.c_str()); argv.push_back(nullptr); FUNCTION_T_RETVAL(errCode, hevce_read_cmd_line, &settings, argv.data()); checkErrorCode(errCode); str.clear(); } if (ctrl.native_config_file.size()) { std::string path = abspath(ctrl.native_config_file, ctrl.config_path); checkFileReadable(path); FUNCTION_T_RETVAL(errCode, hevce_read_config_file, &settings, path.c_str()); checkErrorCode(errCode); } dualPassFileName = ctrl.stats_file; check_settings_log_t log{cb_settings_change, this}; FUNCTION_T_RETVAL(errCode, hevce_check_settings, &settings, &log); checkErrorCode(errCode); FUNCTION_T_RETVAL(errCode, hevce_write_config_file, &settings, ctrl.temp_file[0].c_str()); checkErrorCode(errCode); FUNCTION_T_RETVAL(errCode, vh3_enc_open, &hEnc, &cbTable, &settings); checkErrorCode(errCode); opened = true; if (HEVC_RATE_CONTROL_DUAL_PASS_1 == settings.stream[0].rc.type && dualPassFileName.size()) { checkFileReadable(dualPassFileName); std::ifstream infile(dualPassFileName, std::ifstream::binary); dualPassBuffer.clear(); char c; while (infile.get(c)) dualPassBuffer.push_back(c); if (0 == dualPassBuffer.size()) error("Stats (dual-pass) file is empty."); FUNCTION_T_RETVAL(errCode, vh3_enc_setDualPassData, hEnc, dualPassBuffer.size(), (vh3_dualpass_data_t)dualPassBuffer.data(), 0); checkErrorCode(errCode); } if (ctrl.gop_structure_in_file.size()) { std::string path = abspath(ctrl.gop_structure_in_file, ctrl.config_path); checkFileReadable(path); gopStructureIn.open(path, std::ifstream::in); parseGopStructureFile(); } if (ctrl.gop_structure_out_file.size()) { std::string path = abspath(ctrl.gop_structure_out_file, ctrl.config_path); checkFileWritable(path); gopStructureOut.open(path, std::ofstream::out); } } static std::map<HevcEncFrameType, int> frameType2sliceType = { {HEVC_ENC_FRAME_TYPE_AUTO, (int)VH3_SLICE_AUTO}, {HEVC_ENC_FRAME_TYPE_IDR, (int)VH3_SLICE_I}, {HEVC_ENC_FRAME_TYPE_I, (int)VH3_SLICE_I}, {HEVC_ENC_FRAME_TYPE_P, (int)VH3_SLICE_P}, {HEVC_ENC_FRAME_TYPE_B, (int)VH3_SLICE_B}, {HEVC_ENC_FRAME_TYPE_BREF, (int)VH3_SLICE_B}}; void Encoder::feed(const HevcEncPicture* in) { checkPendingErrors(); if (in) { vh3_Picture* pic; FUNCTION_T_RETVAL(pic, cbTable.pic_alloc, cbTable.app_context, settings.input.width, settings.input.height, settings.input.luma_bytes_per_pel, settings.input.chroma_bytes_per_pel, settings.input.bit_depth_luma, settings.input.bit_depth_chroma, VH3_YUV_420, HEVC_PIC_FLAG_DEFAULT); if (pic == nullptr) error("pic is nullptr"); vh3_SrcPictureInfo picInfo; hevc_error_t errCode; FUNCTION_T_RETVAL(errCode, vh3_enc_initPictureInfo, &picInfo); checkErrorCode(errCode); picInfo.mediatime = frameIndex; pic->timestamp = frameIndex; picInfo.mod.slice_type = (int8_t)frameType2sliceType[in->frameType]; if (HEVC_ENC_FRAME_TYPE_IDR == in->frameType) picInfo.mod.idr_flag = 1; while (slices.size() && slices.front().index < (int64_t)frameIndex) { message("pop SliceInfo: %lld", slices.front().index); slices.pop_front(); } if (slices.size() && slices.front().index == (int64_t)frameIndex) { message("Force slice: %llu, %d, %d", frameIndex, (int)slices.front().type, (int)slices.front().idr_flag); picInfo.mod.slice_type = (int8_t)slices.front().type; picInfo.mod.idr_flag = slices.front().idr_flag; if (slices.size() == 1) { picInfo.mod.slice_type = (int8_t)VH3_SLICE_P; picInfo.mod.idr_flag = 0; } } FUNCTION_T(readFrame, in, pic); FUNCTION_T_RETVAL(errCode, vh3_enc_waitForCanSet, hEnc); checkErrorCode(errCode); FUNCTION_T_RETVAL(errCode, vh3_enc_setPicture, hEnc, pic, &picInfo); checkErrorCode(errCode); if (settings.mt.disable) { FUNCTION_T_RETVAL(errCode, vh3_encode, hEnc, nullptr); checkErrorCode(errCode); } if (debugLevel > 0) { std::lock_guard<std::mutex> lck(dataLock); message("Fed frame[" + std::to_string(frameIndex) + "]"); } frameIndex++; } } void Encoder::flush() { checkPendingErrors(); if (!flushing) { flushing = true; hevc_error_t errCode; FUNCTION_T_RETVAL(errCode, vh3_enc_flush, hEnc); checkErrorCode(errCode); if (settings.mt.disable) { FUNCTION_T_RETVAL(errCode, vh3_encode, hEnc, nullptr); checkErrorCode(errCode); } FUNCTION_T_RETVAL(errCode, vh3_enc_waitForEncode, hEnc); checkErrorCode(errCode); } } void Encoder::close() { if (opened) { std::lock_guard<std::mutex> lck(dataLock); FUNCTIONV_T(releaseNalUnits); hevc_error_t errCode; if (HEVC_RATE_CONTROL_DUAL_PASS_0 == settings.stream[0].rc.type && dualPassFileName.size()) { size_t sz; vh3_dualpass_data_t dpData; FUNCTION_T_RETVAL(errCode, vh3_enc_getDualPassData, hEnc, &sz, &dpData); checkErrorCode(errCode); std::ofstream outfile(dualPassFileName, std::ofstream::binary); if (!outfile.is_open()) error("Could not open stats (dual-pass) file for writing."); outfile.write((char*)dpData, sz); outfile.flush(); outfile.close(); } FUNCTION_T_RETVAL(errCode, vh3_enc_purge, hEnc); checkErrorCode(errCode); FUNCTION_T_RETVAL(errCode, vh3_enc_close, hEnc); checkErrorCode(errCode); opened = false; } if (gopStructureIn.is_open()) gopStructureIn.close(); if (gopStructureOut.is_open()) { reportSliceInfo(nullptr); gopStructureOut.close(); } } void Encoder::readFrame(const HevcEncPicture* in, vh3_Picture* pic) { uint8_t* picData{nullptr}; uint8_t* inData{nullptr}; uint32_t compStride{0}; uint16_t compWidth{0}; uint16_t compHeight{0}; for (uint8_t comp{0}; comp < 3; comp++) { if (comp == 0) { compStride = pic->stride[comp] * pic->luma_bytes_per_pel; compWidth = pic->width * pic->luma_bytes_per_pel; compHeight = pic->height; } else { compStride = pic->stride[comp] * pic->chroma_bytes_per_pel; compWidth = (pic->width >> 1) * pic->chroma_bytes_per_pel; compHeight = (pic->height >> 1); } picData = static_cast<uint8_t*>(pic->data[comp]); inData = static_cast<uint8_t*>(in->plane[comp]); for (uint16_t i = 0; i < compHeight; i++) { memcpy(picData, inData, compWidth); picData += compStride; inData += compWidth; } } } void Encoder::releaseNalUnits() { while (nalUnitsToRelease) { hevc_error_t errCode; FUNCTION_T_RETVAL(errCode, vh3_enc_releaseMediaSample, hEnc, qMS.front().ms); checkErrorCode(errCode); qMS.pop_front(); nalUnitsToRelease--; } } void Encoder::getNal(HevcEncOutput* out, uint64_t maxSize) { out->nalNum = 0; checkPendingErrors(); std::lock_guard<std::mutex> lck(dataLock); FUNCTIONV_T(releaseNalUnits); if (qMS.empty()) return; if (maxSize > outBufferSize) { if (outBuffer) delete[] outBuffer; outBuffer = new uint8_t[maxSize]; outBufferSize = maxSize; } uint8_t* curBufPos = outBuffer; uint64_t remainingBytes = maxSize; size_t nalIdx = 0; nal.clear(); while (remainingBytes && nalIdx < qMS.size()) { vh3_Nal u = qMS[nalIdx++]; auto ms = u.ms; if ((uint64_t)ms->used_size < remainingBytes) { HevcEncNal tmp; if (debugLevel > 0) message("ms->used_size: " + std::to_string(ms->used_size) + ", remainingBytes: " + std::to_string(remainingBytes)); FUNCTION_T(memcpy, curBufPos, ms->data, ms->used_size); tmp.payload = curBufPos; tmp.size = ms->used_size; tmp.type = (HevcEncNalType)u.info.type; curBufPos += ms->used_size; nal.push_back(tmp); nalUnitsToRelease++; remainingBytes -= (uint64_t)ms->used_size; } else { break; } } out->nal = nal.data(); out->nalNum = nal.size(); } void Encoder::parseGopStructureFile() { uint64_t lineNum = 0; std::string line; std::getline(gopStructureIn, line); // header lineNum++; while (std::getline(gopStructureIn, line)) { lineNum++; auto args = split(line, " "); if (args.size() > 1) { SliceInfo s; s.index = std::stoll(args[0]); s.type = (vh3_SliceType)std::stoul(args[1]); if (args.size() > 2) s.idr_flag = (int8_t)std::stoul(args[2]); if (s.index < 0) { message("gop_structure_in_file: Ignoring line %llu. Invalid 'index' value.", lineNum); continue; } if (s.type != VH3_SLICE_B && s.type != VH3_SLICE_P && s.type != VH3_SLICE_I && s.type != -1) { message("gop_structure_in_file: Ignoring line %llu. Invalid 'type' value.", lineNum); continue; } slices.push_back(s); } } auto comparator = [](const SliceInfo& a, const SliceInfo& b) { return a.index < b.index; }; std::sort(slices.begin(), slices.end(), comparator); } hevc_error_t Encoder::notify(vh3_Notification a) { if (VH3_MSG == a.type) { if ((int)a.data.msg.code < 0) { std::lock_guard<std::mutex> lck(dataLock); snprintf(stringBuffer, Encoder::MAX_STRING_SIZE, "%s (%d)", a.data.msg.text, (int)a.data.msg.code); pendingErrors.push_back(std::string(stringBuffer)); } else if (debugLevel > 0) { std::lock_guard<std::mutex> lck(dataLock); snprintf(stringBuffer, Encoder::MAX_STRING_SIZE, "%s (%d)", a.data.msg.text, (int)a.data.msg.code); message(std::string(stringBuffer)); } } return HEVC_OK; } void Encoder::reportSliceInfo(vh3_RecPictureInfo* info) { if (gopStructureOut.is_open()) { if (0 == recFrameIndex && gopSlices.empty()) gopStructureOut << "index type idr_flag" << std::endl; bool newGop = false; SliceInfo s; if (info) { s.index = info->stat.poc; s.type = info->stat.type; s.idr_flag = info->stat.idr_flag; for (auto& x : gopSlices) { if (x.index == s.index) { newGop = true; break; } } } if (!newGop && info) gopSlices.push_back(s); if (newGop || !info) { auto comparator = [](const SliceInfo& a, const SliceInfo& b) { return a.index < b.index; }; std::sort(gopSlices.begin(), gopSlices.end(), comparator); for (auto& x : gopSlices) { gopStructureOut << recFrameIndex++; gopStructureOut << " " << (int)x.type; gopStructureOut << " " << (int)x.idr_flag; gopStructureOut << std::endl; } gopSlices.clear(); if (info) gopSlices.push_back(s); } } } hevc_error_t Encoder::recSend(const vh3_Picture* pic, vh3_RecPictureInfo info) { reportSliceInfo(&info); hevc_error_t errCode; FUNCTION_T_RETVAL(errCode, vh3_enc_releasePicture, hEnc, pic); checkErrorCode(errCode); return HEVC_OK; } hevc_error_t Encoder::msSend(const vh3_MediaSample* ms, vh3_NalInfo info) { std::lock_guard<std::mutex> lck(dataLock); vh3_Nal u{info, ms}; qMS.emplace_back(u); return HEVC_OK; } void Encoder::settingsChange(const char* msg) { message(std::string(msg)); } void Encoder::message(const char* fmt, ...) { if (debugLevel > 0) { std::lock_guard<std::mutex> lck(dataLock); va_list args; va_start(args, fmt); memset(stringBuffer, 0, Encoder::MAX_STRING_SIZE); vsnprintf(stringBuffer, Encoder::MAX_STRING_SIZE - 1, fmt, args); va_end(args); pendingMsgs.push_back(std::string(stringBuffer)); } } void Encoder::message(const std::string& s) { if (debugLevel > 0) { pendingMsgs.push_back(s); } } void Encoder::error(const char* fmt, ...) { va_list args; va_start(args, fmt); memset(stringBuffer, 0, Encoder::MAX_STRING_SIZE); vsnprintf(stringBuffer, Encoder::MAX_STRING_SIZE - 1, fmt, args); va_end(args); throw std::runtime_error(stringBuffer); }
37.181579
131
0.643358
[ "vector" ]
fdc44858446d5931191d801b1cda231b98b07f5e
31,895
cpp
C++
services/WebPageUI/WebPageUI.cpp
knowac/tizen-browser-1.6.4
a37a3ea5b8c01d86bd3dac00d228800e5eed4619
[ "Apache-2.0" ]
1
2016-11-10T20:04:56.000Z
2016-11-10T20:04:56.000Z
services/WebPageUI/WebPageUI.cpp
knowac/tizen-browser-1.6.4
a37a3ea5b8c01d86bd3dac00d228800e5eed4619
[ "Apache-2.0" ]
null
null
null
services/WebPageUI/WebPageUI.cpp
knowac/tizen-browser-1.6.4
a37a3ea5b8c01d86bd3dac00d228800e5eed4619
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <Elementary.h> #include <memory> #include <boost/format.hpp> #include "app_i18n.h" #include "WebPageUI.h" #include "BrowserLogger.h" #include "ServiceManager.h" #include "BrowserAssert.h" #include "UrlHistoryList/UrlHistoryList.h" #include "WebPageUIStatesManager.h" #include <string> #include <app_control.h> namespace tizen_browser { namespace base_ui { EXPORT_SERVICE(WebPageUI, "org.tizen.browser.webpageui") #define MAX_SIGNAL_NAME 32 #define MAX_PROGRESS_LEVEL 20 #define PROGRESS_STEP 0.05 WebPageUI::WebPageUI() : m_parent(nullptr) , m_mainLayout(nullptr) #if DUMMY_BUTTON , m_dummy_button(nullptr) #endif , m_errorLayout(nullptr) , m_bookmarkManagerButton(nullptr) , m_statesMgr(std::make_shared<WebPageUIStatesManager>(WPUState::MAIN_WEB_PAGE)) , m_URIEntry(new URIEntry(m_statesMgr)) , m_editQuickAccessUI(std::make_shared<EditQuickAccessUI>()) , m_urlHistoryList(std::make_shared<UrlHistoryList>(getStatesMgr())) , m_webviewLocked(false) , m_WebPageUIvisible(false) #if PWA , m_pwaInfo(nullptr) #endif #if GESTURE , m_gestureLayer(nullptr) #endif , m_uriBarHidden(false) , m_fullscreen(false) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); } WebPageUI::~WebPageUI() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); #if DUMMY_BUTTON evas_object_smart_callback_del(m_dummy_button, "focused", _dummy_button_focused); evas_object_smart_callback_del(m_dummy_button, "unfocused", _dummy_button_unfocused); #endif } void WebPageUI::init(Evas_Object* parent) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); M_ASSERT(parent); m_parent = parent; m_editQuickAccessUI->init(parent); } Evas_Object* WebPageUI::getContent() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); M_ASSERT(m_parent); if (!m_mainLayout) { createLayout(); } return m_mainLayout; } UrlHistoryPtr WebPageUI::getUrlHistoryList() { return m_urlHistoryList; } void WebPageUI::updateEngineStateUI() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); auto state = getEngineState(); if (state) { switch (*state) { case basic_webengine::State::NORMAL: elm_object_signal_emit(m_mainLayout, "set_normal_mode", "ui"); break; case basic_webengine::State::SECRET: setButtonsDisabled(); elm_object_signal_emit(m_mainLayout, "set_secret_mode", "ui"); break; default: BROWSER_LOGE("[%s:%d] Unknown state!", __PRETTY_FUNCTION__, __LINE__); } m_bottomButtonBar->setButtonsColor(*state == basic_webengine::State::SECRET); m_rightButtonBar->setButtonsColor(*state == basic_webengine::State::SECRET); } else { BROWSER_LOGE("[%s:%d] Wrong state value!", __PRETTY_FUNCTION__, __LINE__); } } void WebPageUI::showUI() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); M_ASSERT(m_mainLayout); updateEngineStateUI(); evas_object_show(m_mainLayout); evas_object_show(elm_object_part_content_get(m_mainLayout, "web_view")); evas_object_show(m_URIEntry->getContent()); evas_object_show(elm_object_part_content_get(m_mainLayout, "bottom_toolbar")); evas_object_show(elm_object_part_content_get(m_mainLayout, "uri_bar_buttons_right")); if (m_statesMgr->equals(WPUState::QUICK_ACCESS)) { setQuickAccessView(); } m_WebPageUIvisible = true; elm_object_event_callback_add(m_bottomButtonBar->getContent(), _cb_down_pressed_on_urlbar, this); elm_object_event_callback_add(m_rightButtonBar->getContent(), _cb_down_pressed_on_urlbar, this); elm_object_event_callback_add(m_URIEntry->getContent(), _cb_down_pressed_on_urlbar, this); #if GESTURE elm_gesture_layer_cb_add(m_gestureLayer, ELM_GESTURE_N_LINES, ELM_GESTURE_STATE_MOVE, _gesture_move, this); elm_gesture_layer_line_min_length_set(m_gestureLayer, SWIPE_MOMENTUM_TRESHOLD); elm_gesture_layer_line_distance_tolerance_set(m_gestureLayer, SWIPE_MOMENTUM_TRESHOLD); #endif } void WebPageUI::hideUI() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); M_ASSERT(m_mainLayout); m_URIEntry->loadFinished(); evas_object_hide(m_mainLayout); if(m_statesMgr->equals(WPUState::QUICK_ACCESS)) hideQuickAccess(); evas_object_hide(elm_object_part_content_get(m_mainLayout, "web_view")); evas_object_hide(m_URIEntry->getContent()); evas_object_hide(elm_object_part_content_get(m_mainLayout, "bottom_toolbar")); evas_object_hide(elm_object_part_content_get(m_mainLayout, "uri_bar_buttons_right")); m_WebPageUIvisible = false; elm_object_event_callback_del(m_bottomButtonBar->getContent(), _cb_down_pressed_on_urlbar, this); elm_object_event_callback_del(m_rightButtonBar->getContent(), _cb_down_pressed_on_urlbar, this); elm_object_event_callback_del(m_URIEntry->getContent(), _cb_down_pressed_on_urlbar, this); #if GESTURE elm_gesture_layer_cb_del(m_gestureLayer, ELM_GESTURE_N_LINES, ELM_GESTURE_STATE_MOVE, _gesture_move, this); #endif hideFindOnPage(); } void WebPageUI::loadStarted() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); showProgressBar(); m_URIEntry->loadStarted(); elm_object_signal_emit(m_mainLayout, "shiftright_uri", "ui"); } void WebPageUI::progressChanged(double progress) { if (progress == 1.0) { hideProgressBar(); } else { int level = (int)(progress * MAX_PROGRESS_LEVEL); char signal_name[MAX_SIGNAL_NAME] = { 0 }; snprintf(signal_name, MAX_SIGNAL_NAME, "update,progress,%.02f,signal", ((double)level * PROGRESS_STEP)); elm_object_signal_emit(m_mainLayout, signal_name, ""); } } bool WebPageUI::stateEquals(WPUState state) const { return m_statesMgr->equals(state); } bool WebPageUI::stateEquals(std::initializer_list<WPUState> states) const { return m_statesMgr->equals(states); } void WebPageUI::loadFinished() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); m_URIEntry->loadFinished(); hideProgressBar(); m_URIEntry->updateSecureIcon(); #if DUMMY_BUTTON elm_object_focus_set(m_dummy_button, EINA_TRUE); #endif #if PWA getCountCheckSignal(); #endif } void WebPageUI::setMainContent(Evas_Object* content) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); M_ASSERT(content); hideWebView(); elm_object_part_content_set(m_mainLayout, "web_view", content); #if GESTURE elm_gesture_layer_attach(m_gestureLayer, content); #endif #if !DUMMY_BUTTON evas_object_smart_callback_add(content, "mouse,down", _content_clicked, this); #endif updateManualRotation(); evas_object_show(content); } void WebPageUI::switchViewToWebPage(Evas_Object* content, const std::string uri, bool loading) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if(m_statesMgr->equals(WPUState::QUICK_ACCESS)) { hideQuickAccess(); m_statesMgr->set(WPUState::MAIN_WEB_PAGE); } setMainContent(content); elm_object_signal_emit(m_mainLayout, "shiftright_uri", "ui"); #if DUMMY_BUTTON elm_object_signal_emit(m_mainLayout, "show,dummy_button", ""); #endif updateURIBar(uri, loading); } void WebPageUI::setQuickAccessView() { elm_object_signal_emit(m_mainLayout, "shiftback_uri", "ui"); hideProgressBar(); m_URIEntry->changeUri(""); m_URIEntry->showSecureIcon(false, false); setButtonsDisabled(); showQuickAccess(); } void WebPageUI::switchViewToQuickAccess(Evas_Object* content) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); m_statesMgr->set(WPUState::QUICK_ACCESS); setMainContent(content); setQuickAccessView(); #if DUMMY_BUTTON elm_object_signal_emit(m_mainLayout, "hide,dummy_button", ""); #endif } void WebPageUI::setMostVisitedSelectedItemsCountInEditMode(int count) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); m_editQuickAccessUI->setMVSelectedItems(count); } void WebPageUI::faviconClicked(void* data, Evas_Object*, const char*, const char*) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); WebPageUI* self = reinterpret_cast<WebPageUI*>(data); if(!self->stateEquals({ WPUState::QUICK_ACCESS, WPUState::MAIN_ERROR_PAGE })) { self->getURIEntry().clearFocus(); } } Eina_Bool WebPageUI::_cb_down_pressed_on_urlbar(void *data, Evas_Object */*obj*/, Evas_Object */*src*/, Evas_Callback_Type type, void *event_info) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); WebPageUI* self = reinterpret_cast<WebPageUI*>(data); if(type == EVAS_CALLBACK_KEY_DOWN) { Ecore_Event_Key *ev = static_cast<Ecore_Event_Key *>(event_info); const std::string keyName = ev->keyname; if(!keyName.compare("Down")){ self->lockWebview(); } } return EINA_FALSE; } void WebPageUI::setTabsNumber(int tabs) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (tabs == 0) { elm_object_part_text_set(m_bottomButtonBar->getContent(), "tabs_number", ""); } else { elm_object_part_text_set(m_bottomButtonBar->getContent(), "tabs_number", (boost::format("%1%") % tabs).str().c_str()); } } void WebPageUI::lockWebview() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if(isWebPageUIvisible()) { if(m_statesMgr->equals(WPUState::MAIN_WEB_PAGE)) { elm_object_focus_custom_chain_unset(m_mainLayout); elm_object_focus_custom_chain_append(m_mainLayout, elm_object_part_content_get(m_mainLayout, "web_view"), NULL); m_webviewLocked = true; } } } void WebPageUI::lockUrlHistoryList() { elm_object_focus_custom_chain_unset(m_mainLayout); elm_object_focus_custom_chain_append(m_mainLayout, getUrlHistoryList()->getLayout(), NULL); getUrlHistoryList()->listWidgetFocusedFromUri(); elm_object_focus_set(getUrlHistoryList()->getLayout(), EINA_TRUE); } void WebPageUI::unlockUrlHistoryList() { elm_object_focus_set(m_URIEntry->getEntryWidget(), EINA_TRUE); getUrlHistoryList()->onListWidgetFocusChange(false); } void WebPageUI::setFocusOnSuspend() { elm_object_focus_set(m_rightButtonBar->getButton("tab_button"), EINA_TRUE); } void WebPageUI::fullscreenModeSet(bool state) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); auto landscape = isLandscape(); auto findonpage = isFindOnPageVisible(); m_fullscreen = state; if (!state) { elm_object_signal_emit(m_mainLayout, "show_uri_bar", "ui"); if (findonpage && *findonpage) elm_object_signal_emit(m_mainLayout, "show_findonpage", "ui"); } else if (landscape && state) { (*landscape) ? elm_object_signal_emit(m_mainLayout, "hide_uri_bar_landscape", "ui") : elm_object_signal_emit(m_mainLayout, "hide_uri_bar_vertical", "ui"); if (findonpage && *findonpage) hideFindOnPage(); } showBottomBar(!state); } void WebPageUI::orientationChanged() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); auto landscape = isLandscape(); if (landscape) { if (*landscape) { elm_object_signal_emit(m_bottomButtonBar->getContent(), "landscape,mode", ""); if (m_uriBarHidden) elm_object_signal_emit(m_mainLayout, "hide_uri_bar_landscape", "ui"); } else { elm_object_signal_emit(m_bottomButtonBar->getContent(), "portrait,mode", ""); if (m_uriBarHidden) elm_object_signal_emit(m_mainLayout, "hide_uri_bar_vertical", "ui"); } } else BROWSER_LOGE("[%s:%d] Signal not found", __PRETTY_FUNCTION__, __LINE__); if (m_statesMgr->equals(WPUState::QUICK_ACCESS)) { qaOrientationChanged(); } } void WebPageUI::showContextMenu() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); boost::optional<Evas_Object*> window = getWindow(); if (window) { createContextMenu(*window); if (m_statesMgr->equals(WPUState::QUICK_ACCESS)) { //TODO: Add translation boost::optional<bool> isMostVisitedOpt(isMostVisited()); if (!isMostVisitedOpt || !(*isMostVisitedOpt)) elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_OPT_EDIT_QUICK_ACCESS_ABB"), nullptr, _cm_edit_qa_clicked, this); else elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_OPT_DELETE"), nullptr, _cm_delete_mv_clicked, this); } else if (m_statesMgr->equals(WPUState::MAIN_WEB_PAGE)) { elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_OPT_SHARE"), nullptr, _cm_share_clicked, this); elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_OPT_FIND_ON_PAGE"), nullptr, _cm_find_on_page_clicked, this); boost::optional<bool> bookmark = isBookmark(); if (bookmark) { //TODO: Add translation if (*bookmark) elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_OPT_REMOVE_FROM_BOOKMARKS_ABB"), nullptr, _cm_delete_bookmark_clicked, this); else elm_ctxpopup_item_append(m_ctxpopup, "Add to Bookmarks", nullptr, _cm_bookmark_flow_clicked, this); } else BROWSER_LOGE("[%s:%d] Signal not found", __PRETTY_FUNCTION__, __LINE__); boost::optional<bool> quickAccess = isQuickAccess(); if (quickAccess) { if (!*quickAccess) elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_OPT_ADD_TO_QUICK_ACCESS"), nullptr, _cm_add_to_qa_clicked, this); } else { BROWSER_LOGE("[%s:%d] Signal not found", __PRETTY_FUNCTION__, __LINE__); } if (!getDesktopMode()) elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_BODY_DESKTOP_VIEW"), nullptr, _cm_desktop_view_page_clicked, this); else elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_BODY_MOBILE_VIEW"), nullptr, _cm_mobile_view_page_clicked, this); } else { BROWSER_LOGW("[%s] State not handled, context menu not shown", __PRETTY_FUNCTION__); return; } elm_ctxpopup_item_append(m_ctxpopup, _("IDS_BR_BODY_SETTINGS"), nullptr, _cm_settings_clicked, this); #if PWA if (!m_statesMgr->equals(WPUState::QUICK_ACCESS)) elm_ctxpopup_item_append(m_ctxpopup, "Add to Homescreen", nullptr, _cm_add_to_hs_clicked, this); #endif alignContextMenu(*window); } else BROWSER_LOGE("[%s:%d] Signal not found", __PRETTY_FUNCTION__, __LINE__); } void WebPageUI::_cm_edit_qa_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->m_statesMgr->set(WPUState::EDIT_MODE); webPageUI->quickAccessEdit(); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_delete_mv_clicked(void *data, Evas_Object *, void *) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->m_statesMgr->set(WPUState::EDIT_MODE); webPageUI->deleteMostVisited(); } else { BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } } void WebPageUI::_cm_share_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); std::string uri = webPageUI->getURI(); webPageUI->launch_share(uri.c_str()); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_find_on_page_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->showFindOnPageUI(); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_delete_bookmark_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->deleteBookmark(); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_bookmark_flow_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->showBookmarkFlowUI(); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_add_to_qa_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); auto signal = webPageUI->getTitle(); if (signal) webPageUI->addToQuickAccess(webPageUI->getURI(), *signal); else BROWSER_LOGW("Signal does not exist!"); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_desktop_view_page_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->switchToDesktopMode(); webPageUI->setDesktopMode(true); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_mobile_view_page_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->switchToMobileMode(); webPageUI->setDesktopMode(false); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } void WebPageUI::_cm_settings_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); webPageUI->showSettingsUI(); } else BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } #if PWA void WebPageUI::_cm_add_to_hs_clicked(void* data, Evas_Object*, void* ) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); webPageUI->m_pwaInfo = std::make_shared<pwaInfo>(); _cm_dismissed(nullptr, webPageUI->m_ctxpopup, nullptr); // send request API. webPageUI->pwaRequestManifest(); } else { BROWSER_LOGW("[%s] data = nullptr", __PRETTY_FUNCTION__); } } #endif std::string WebPageUI::getURI() { auto retVal = requestCurrentPageForWebPageUI(); if(retVal && !(*retVal).empty()) { return *retVal; } else { return " "; } } void WebPageUI::createLayout() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); M_ASSERT(m_parent); // create web layout m_mainLayout = elm_layout_add(m_parent); evas_object_size_hint_weight_set(m_mainLayout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); elm_layout_file_set(m_mainLayout, edjePath("WebPageUI/WebPageUI.edj").c_str(), "main_layout"); createActions(); // bottom buttons m_bottomButtonBar = std::unique_ptr<ButtonBar>(new ButtonBar(m_mainLayout, "WebPageUI/BottomButtonBar.edj", "bottom_button_bar")); m_bottomButtonBar->addAction(m_back, "prev_button"); m_bottomButtonBar->addAction(m_forward, "next_button"); m_bottomButtonBar->addAction(m_homePage, "home_button"); m_bottomButtonBar->addAction(m_bookmarks, "bookmarks_button"); m_bottomButtonBar->addAction(m_tabs, "tabs_button"); // right buttons m_rightButtonBar = std::unique_ptr<ButtonBar>(new ButtonBar(m_mainLayout, "WebPageUI/RightButtonBar.edj", "right_button_bar")); m_rightButtonBar->addAction(m_addTab, "tab_button"); //URL bar (Evas Object is shipped by URIEntry object) m_URIEntry->init(m_mainLayout); elm_object_part_content_set(m_mainLayout, "uri_entry", m_URIEntry->getContent()); elm_object_part_content_set(m_mainLayout, "bottom_swallow", m_bottomButtonBar->getContent()); elm_object_part_content_set(m_mainLayout, "uri_bar_buttons_right", m_rightButtonBar->getContent()); elm_layout_signal_callback_add(m_URIEntry->getContent(), "slide_websearch", "elm", faviconClicked, this); // elm_theme_extension_add(nullptr, edjePath("WebPageUI/UrlHistoryList.edj").c_str()); // m_urlHistoryList->setMembers(m_mainLayout, m_URIEntry->getEntryWidget()); // elm_object_part_content_set(m_mainLayout, "url_history_list", m_urlHistoryList->getLayout()); connectActions(); #if GESTURE // will be attatch on every 'setMainContent' m_gestureLayer = elm_gesture_layer_add(m_mainLayout); #endif } #if DUMMY_BUTTON void WebPageUI::createDummyButton() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (!m_dummy_button) { M_ASSERT(m_mainLayout); m_dummy_button = elm_button_add(m_mainLayout); elm_object_style_set(m_dummy_button, "invisible_button"); evas_object_size_hint_align_set(m_dummy_button, EVAS_HINT_FILL, EVAS_HINT_FILL); evas_object_size_hint_weight_set(m_dummy_button, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); elm_object_focus_allow_set(m_dummy_button, EINA_TRUE); elm_object_focus_set(m_dummy_button, EINA_TRUE); evas_object_show(m_dummy_button); elm_object_part_content_set(m_mainLayout, "web_view_dummy_button", m_dummy_button); evas_object_smart_callback_add(m_dummy_button, "focused", _dummy_button_focused, this); evas_object_smart_callback_add(m_dummy_button, "unfocused", _dummy_button_unfocused, this); elm_atspi_accessible_role_set(m_dummy_button, ELM_ATSPI_ROLE_REDUNDANT_OBJECT); elm_atspi_accessible_can_highlight_set(m_dummy_button, EINA_FALSE); } } void WebPageUI::_dummy_button_focused(void *data, Evas_Object *, void *) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); webPageUI->focusWebView(); } } void WebPageUI::_dummy_button_unfocused(void *data, Evas_Object *, void *) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (data != nullptr) { WebPageUI* webPageUI = static_cast<WebPageUI*>(data); webPageUI->unfocusWebView(); } } #endif void WebPageUI::_bookmark_manager_clicked(void * data, Evas_Object *, void *) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); WebPageUI* webpageUI = static_cast<WebPageUI*>(data); webpageUI->bookmarkManagerClicked(); } void WebPageUI::setContentFocus() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (getURIEntry().hasFocus()) getURIEntry().clearFocus(); } void WebPageUI::showBottomBar(bool isShown) { BROWSER_LOGD("[%s:%d] %d", __PRETTY_FUNCTION__, __LINE__, isShown); if (m_fullscreen) { elm_object_signal_emit(m_mainLayout, "hide,bottom", ""); return; } if (isShown) elm_object_signal_emit(m_mainLayout, "show,bottom", ""); else elm_object_signal_emit(m_mainLayout, "hide,bottom", ""); } void WebPageUI::_content_clicked(void *data, Evas_Object *, void *) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); WebPageUI* webpageUI = static_cast<WebPageUI*>(data); webpageUI->setContentFocus(); } void WebPageUI::createActions() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); m_back = sharedAction(new Action(_("IDS_BR_BUTTON_BACK_ABB"))); m_back->setIcon("toolbar_prev"); m_forward = sharedAction(new Action(_("IDS_BR_SK_NEXT"))); m_forward->setIcon("toolbar_next"); m_addTab = sharedAction(new Action(_("IDS_BR_BUTTON_NEW_TAB_ABB2"))); m_addTab->setIcon("add_tab"); m_homePage = sharedAction(new Action("Home")); m_homePage->setIcon("toolbar_home"); m_bookmarks = sharedAction(new Action(_("IDS_BR_BODY_BOOKMARKS"))); m_bookmarks->setIcon("toolbar_bookmark"); m_tabs = sharedAction(new Action(_("IDS_BR_SK_TABS"))); m_tabs->setIcon("toolbar_tabs"); } void WebPageUI::connectActions() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); //bottom bar m_back->triggered.connect(boost::bind(&WebPageUI::backPageConnect, this)); m_forward->triggered.connect(boost::bind(&WebPageUI::forwardPageConnect, this)); m_tabs->triggered.connect(WebPageUI::showTabUI); m_bookmarks->triggered.connect(WebPageUI::showBookmarksUI); m_homePage->triggered.connect(WebPageUI::showHomePage); //right bar m_addTab->triggered.connect(boost::bind(&WebPageUI::addNewTabConnect, this)); } void WebPageUI::showProgressBar() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); elm_object_signal_emit(m_mainLayout, "show,progress,signal", ""); elm_object_signal_emit(m_mainLayout, "update,progress,0.00,signal", ""); } void WebPageUI::hideProgressBar() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); elm_object_signal_emit(m_mainLayout, "hide,progress,signal", ""); } void WebPageUI::hideFindOnPage() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); elm_object_signal_emit(m_mainLayout, "hide_findonpage", "ui"); } void WebPageUI::hideWebView() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); evas_object_hide(elm_object_part_content_unset(m_mainLayout, "web_view")); } void WebPageUI::setErrorButtons() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); m_forward->setEnabled(false); } void WebPageUI::setButtonsDisabled() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); m_forward->setEnabled(false); m_back->setEnabled(false); } void WebPageUI::updateURIBar(const std::string& uri, bool loading) { BROWSER_LOGD("[%s:%d] URI:%s", __PRETTY_FUNCTION__, __LINE__, uri.c_str()); m_URIEntry->setPageLoading(loading); m_URIEntry->changeUri(uri); hideProgressBar(); } std::string WebPageUI::edjePath(const std::string& file) { return std::string(EDJE_DIR) + file; } #if GESTURE Evas_Event_Flags WebPageUI::_gesture_move(void* data , void* event_info) { auto info = static_cast<Elm_Gesture_Line_Info*>(event_info); if (info->momentum.n == WebPageUI::SINGLE_FINGER) { if ((info->angle > 330 || info->angle < 30) && info->momentum.my < -WebPageUI::SWIPE_MOMENTUM_TRESHOLD) { // top direction auto self = static_cast<WebPageUI*>(data); self->gestureUp(); } else if (info->angle > 150 && info->angle < 210 && info->momentum.my > WebPageUI::SWIPE_MOMENTUM_TRESHOLD) { // bottom direction auto self = static_cast<WebPageUI*>(data); self->gestureDown(); } } return EVAS_EVENT_FLAG_NONE; } void WebPageUI::gestureUp() { if (!m_uriBarHidden) { m_uriBarHidden = true; BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); boost::optional<bool> landscape = isLandscape(); if (landscape) { if (*landscape) elm_object_signal_emit(m_mainLayout, "hide_uri_bar_landscape", "ui"); else elm_object_signal_emit(m_mainLayout, "hide_uri_bar_vertical", "ui"); } else BROWSER_LOGE("[%s:%d] Signal not found", __PRETTY_FUNCTION__, __LINE__); } } void WebPageUI::gestureDown() { if (m_uriBarHidden) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); elm_object_signal_emit(m_mainLayout, "show_uri_bar", "ui"); m_uriBarHidden = false; } } #endif void WebPageUI::mobileEntryFocused() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); elm_object_signal_emit(m_mainLayout, "enlarge_focused_uri", "ui"); } void WebPageUI::mobileEntryUnfocused() { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); elm_object_signal_emit(m_mainLayout, "decrease_unfocused_uri", "ui"); // delay hiding on one efl loop iteration to enable genlist item selected callback to come ecore_timer_add(0.0, _hideDelay, this); } Eina_Bool WebPageUI::_hideDelay(void *data) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); auto self = static_cast<WebPageUI*>(data); self->m_urlHistoryList->hideWidget(); return ECORE_CALLBACK_CANCEL; } #if PWA void WebPageUI::setDisplayMode(WebPageUI::WebDisplayMode mode) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); if (mode == WebDisplayMode::WebDisplayModeFullscreen) elm_object_signal_emit(m_mainLayout, "webview_fullscreen", "ui"); else if (mode == WebDisplayMode::WebDisplayModeStandalone) elm_object_signal_emit(m_mainLayout, "webview_fullscreen", "ui"); else if (mode == WebDisplayMode::WebDisplayModeMinimalUi) BROWSER_LOGD("Not implemented"); else if (mode == WebDisplayMode::WebDisplayModeBrowser) elm_object_signal_emit(m_mainLayout, "webview_default", "ui"); } #endif void WebPageUI:: launch_share(const char *uri) { BROWSER_LOGD("[%s:%d] ", __PRETTY_FUNCTION__, __LINE__); app_control_h app_control = NULL; if (app_control_create(&app_control) < 0) { BROWSER_LOGD("Fail to create app_control handle"); return ; } if (app_control_set_operation(app_control, APP_CONTROL_OPERATION_SHARE_TEXT) < 0) { BROWSER_LOGD("Fail to set app_control operation"); app_control_destroy(app_control); return ; } if (app_control_add_extra_data(app_control, APP_CONTROL_DATA_TEXT, uri) < 0) { BROWSER_LOGD("Fail to set extra data : APP_CONTROL_DATA_TEXT"); app_control_destroy(app_control); return ; } if (app_control_send_launch_request(app_control, NULL, NULL) < 0) { BROWSER_LOGD("Fail to launch app_control operation"); app_control_destroy(app_control); return ; } app_control_destroy(app_control); return ; } } // namespace tizen_browser } // namespace base_ui
34.555796
146
0.694435
[ "object" ]
fdc4626c50c3be840705e879405552463470df79
2,784
cc
C++
Dragon/src/operators/arithmetic/gram_matrix_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
212
2015-07-05T07:57:17.000Z
2022-02-27T01:55:35.000Z
Dragon/src/operators/arithmetic/gram_matrix_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
6
2016-07-07T14:31:56.000Z
2017-12-12T02:21:15.000Z
Dragon/src/operators/arithmetic/gram_matrix_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
71
2016-03-24T09:02:41.000Z
2021-06-03T01:52:41.000Z
#include "operators/arithmetic/gram_matrix_op.h" #include "core/workspace.h" #include "utils/math_functions.h" namespace dragon { template <class Context> template <typename T> void GramMatrixOp<Context>::RunWithType() { auto* Xdata = input(0).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, Context>(); for (int i = 0; i < outer_dim; i++) { math::Gemm<T, Context>(CblasNoTrans, CblasTrans, dim, dim, inner_dim, 1.0, Xdata, Xdata, 0.0, Ydata); Xdata += x_offset; Ydata += y_offset; } } template <class Context> void GramMatrixOp<Context>::RunOnDevice() { outer_dim = input(0).count(0, axis); dim = input(0).dim(axis); inner_dim = input(0).count(axis + 1); x_offset = dim * inner_dim, y_offset = dim * dim; output(0)->Reshape(vector<TIndex>({ outer_dim, dim, dim })); if (input(0).template IsType<float>()) RunWithType<float>(); #ifdef WITH_CUDA_FP16 else if (input(0).template IsType<float16>()) RunWithType<float16>(); #endif else LOG(FATAL) << "Unsupported input types."; } DEPLOY_CPU(GramMatrix); #ifdef WITH_CUDA DEPLOY_CUDA(GramMatrix); #endif OPERATOR_SCHEMA(GramMatrix).NumInputs(1).NumOutputs(1); template <class Context> template <typename T> void GramMatrixGradientOp<Context>::RunWithType() { auto* dYdata = input(-1).template data<T, Context>(); auto* Xdata = input(0).template data<T, Context>(); auto* dXdata = output(0)->template mutable_data<T, Context>(); for (int i = 0; i < outer_dim; i++) { math::Gemm<T, Context>(CblasNoTrans, CblasNoTrans, dim, inner_dim, dim, 2.0, dYdata, Xdata, 0.0, dXdata); dYdata += y_offset; dXdata += x_offset; } } template <class Context> void GramMatrixGradientOp<Context>::RunOnDevice() { outer_dim = input(0).count(0, axis); dim = input(0).dim(axis); inner_dim = input(0).count(axis + 1); x_offset = dim * inner_dim, y_offset = dim * dim; output(0)->ReshapeLike(input(0)); if (input(0).template IsType<float>()) RunWithType<float>(); #ifdef WITH_CUDA_FP16 else if (input(0).template IsType<float16>()) RunWithType<float16>(); #endif else LOG(FATAL) << "Unsupported input types."; } DEPLOY_CPU(GramMatrixGradient); #ifdef WITH_CUDA DEPLOY_CUDA(GramMatrixGradient); #endif OPERATOR_SCHEMA(GramMatrixGradient).NumInputs(2).NumOutputs(1); class GetGramMatrixGradient final : public GradientMakerBase { public: GRADIENT_MAKER_CTOR(GetGramMatrixGradient); vector<OperatorDef> MakeDefs() override{ return SingleDef(def.type() + "Gradient", "", vector<string> {I(0), GO(0)}, vector<string> {GI(0)}); } }; REGISTER_GRADIENT(GramMatrix, GetGramMatrixGradient); } // namespace dragon
32.752941
73
0.670259
[ "vector" ]
fdc9fa5aecacbafb3ba3c8474731551d0eb26f73
1,765
cpp
C++
ospray/geometry/Isosurfaces.cpp
TWITTM/ospray
7cc36c74df0dea59e18cd7eb15b23b712dfd8849
[ "Apache-2.0" ]
1
2020-05-30T02:39:22.000Z
2020-05-30T02:39:22.000Z
ospray/geometry/Isosurfaces.cpp
wzjj0525/ospray
7cc36c74df0dea59e18cd7eb15b23b712dfd8849
[ "Apache-2.0" ]
null
null
null
ospray/geometry/Isosurfaces.cpp
wzjj0525/ospray
7cc36c74df0dea59e18cd7eb15b23b712dfd8849
[ "Apache-2.0" ]
null
null
null
// Copyright 2009-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // ospray #include "Isosurfaces.h" #include "common/Data.h" #include "common/World.h" // openvkl #include "openvkl/openvkl.h" // ispc-generated files #include "Isosurfaces_ispc.h" namespace ospray { Isosurfaces::Isosurfaces() { ispcEquivalent = ispc::Isosurfaces_create(this); embreeGeometry = rtcNewGeometry(ispc_embreeDevice(), RTC_GEOMETRY_TYPE_USER); } Isosurfaces::~Isosurfaces() { if (valueSelector) { vklRelease(valueSelector); valueSelector = nullptr; } } std::string Isosurfaces::toString() const { return "ospray::Isosurfaces"; } void Isosurfaces::commit() { isovaluesData = getParamDataT<float>("isovalue", true, true); model = (VolumetricModel *)getParamObject("volume"); if (!model) { throw std::runtime_error( "the 'volume' parameter must be set for isosurfaces"); } if (!isovaluesData->compact()) { // get rid of stride auto data = new Data(OSP_FLOAT, vec3ui(isovaluesData->size(), 1, 1)); data->copy(*isovaluesData, vec3ui(0)); isovaluesData = &(data->as<float>()); data->refDec(); } if (valueSelector) { vklRelease(valueSelector); valueSelector = nullptr; } valueSelector = vklNewValueSelector(model->getVolume()->vklVolume); if (isovaluesData->size() > 0) { vklValueSelectorSetValues( valueSelector, isovaluesData->size(), isovaluesData->data()); } vklCommit(valueSelector); ispc::Isosurfaces_set(getIE(), embreeGeometry, isovaluesData->size(), isovaluesData->data(), model->getIE(), valueSelector); postCreationInfo(); } size_t Isosurfaces::numPrimitives() const { return isovaluesData->size(); } } // namespace ospray
21.26506
79
0.685552
[ "model" ]
fdd3be902b03f35729db142265076d59a49143fd
9,084
cpp
C++
dev/Code/Framework/AzCore/AzCore/Console/Console.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Framework/AzCore/AzCore/Console/Console.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Framework/AzCore/AzCore/Console/Console.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzCore/Console/Console.h> #include <AzCore/Console/ConsoleNotificationBus.h> #include <AzCore/StringFunc/StringFunc.h> #include <AzCore/Interface/Interface.h> #include <AzCore/IO/FileIO.h> namespace AZ { uint32_t CountMatchingPrefixes(const AZStd::string_view& string, const StringSet& stringSet) { uint32_t count = 0; for (AZStd::string_view iter : stringSet) { if (StringFunc::StartsWith(iter, string, false)) { ++count; } } return count; } Console::Console() : m_head(nullptr) { AZ::Interface<IConsole>::Register(this); } Console::~Console() { // Unlink everything first for (ConsoleFunctorBase* curr = m_head; curr != nullptr; curr = curr->m_next) { curr->Unlink(m_head); curr->m_console = nullptr; } // If we are shutting down, make sure that we mark the head as nullptr so that we don't try to unlink functors after the fact // It appears that things to not necessarily cleanly unlink in the client standalone exe on shutdown, so to prevent accessing memory that has been freed, we do this m_head = nullptr; AZ::Interface<IConsole>::Unregister(this); } bool Console::PerformCommand(const char* command, ConsoleFunctorFlags requiredSet, ConsoleFunctorFlags requiredClear) { static const char* separators = " \t\n\r"; AZStd::string trimmed = command; StringFunc::TrimWhiteSpace(trimmed, true, true); StringSet splitTokens; StringFunc::Tokenize(trimmed, splitTokens, " "); if (splitTokens.size() < 1) { return false; } const AZStd::string splitCommand = splitTokens.front(); splitTokens.erase(splitTokens.begin()); ConsoleFunctorFlags flags = ConsoleFunctorFlags::Null; if (DispatchCommand(splitCommand, splitTokens, requiredSet, requiredClear, flags)) { ConsoleNotificationBus::Broadcast(&ConsoleNotificationBus::Events::OnPerformCommand, splitCommand, flags); return true; } return false; } void Console::ExecuteCommandLine(const char* commandLine) { // We consume a leading space so values like guids don't get split by accident const AZStd::vector<AZStd::string_view> switches = { " -", " +" }; if (*commandLine == '\0') { return; } // Purposefully inject a space into the split string to match the switches above const AZStd::string commandline = AZStd::string(" ") + AZStd::string(commandLine); StringSet split; StringFunc::Tokenize(commandline, split, switches); for (AZStd::string& command : split) { const size_t delim = command.find_first_of('='); if (delim == AZStd::string::npos) { PerformCommand(command.c_str(), ConsoleFunctorFlags::Null, ConsoleFunctorFlags::Null); continue; } // Swap the '=' character for a space command[delim] = ' '; PerformCommand(command.c_str()); } } bool Console::HasCommand(const char* command) { return FindCommand(command) != nullptr; } ConsoleFunctorBase* Console::FindCommand(const char* command) { const size_t commandLength = strlen(command); for (ConsoleFunctorBase* curr = m_head; curr != nullptr; curr = curr->m_next) { if ((curr->GetFlags() & ConsoleFunctorFlags::IsInvisible) == ConsoleFunctorFlags::IsInvisible) { // Filter functors marked as invisible continue; } if (StringFunc::Equal(curr->GetName(), command, false, commandLength + 1)) // + 1 to include the NULL terminator { return curr; } } return nullptr; } AZStd::string Console::AutoCompleteCommand(const char* command) { const size_t commandLength = strlen(command); if (commandLength <= 0) { return command; } StringSet commandSubset; for (ConsoleFunctorBase* curr = m_head; curr != nullptr; curr = curr->m_next) { if ((curr->GetFlags() & ConsoleFunctorFlags::IsInvisible) == ConsoleFunctorFlags::IsInvisible) { // Filter functors marked as invisible continue; } if (StringFunc::Equal(curr->m_name, command, false, commandLength)) { AZ_TracePrintf("Az Console", "- %s : %s\n", curr->m_name, curr->m_desc); commandSubset.push_back(curr->m_name); } } AZStd::string largestSubstring = command; if ((!largestSubstring.empty()) && (!commandSubset.empty())) { const uint32_t totalCount = CountMatchingPrefixes(command, commandSubset); for (size_t i = largestSubstring.length(); i < commandSubset.front().length(); ++i) { const AZStd::string nextSubstring = largestSubstring + commandSubset.front()[i]; const uint32_t count = CountMatchingPrefixes(nextSubstring, commandSubset); if (count < totalCount) { break; } largestSubstring = nextSubstring; } } return largestSubstring; } void Console::VisitRegisteredFunctors(FunctorVisitorInterface& visitor) { for (ConsoleFunctorBase* curr = m_head; curr != nullptr; curr = curr->m_next) { visitor.Visit(curr); } } ConsoleFunctorBase*& Console::RetrieveHeadElement() { return m_head; } void Console::LinkDeferredFunctors(ConsoleFunctorBase*& deferredHead) { ConsoleFunctorBase* curr = deferredHead; while (curr != nullptr) { ConsoleFunctorBase* next = curr->m_next; curr->Unlink(deferredHead); curr->Link(m_head); curr->m_console = this; curr->m_isDeferred = false; curr = next; } deferredHead = nullptr; } bool Console::DispatchCommand(const AZStd::string& command, const StringSet& inputs, ConsoleFunctorFlags requiredSet, ConsoleFunctorFlags requiredClear, ConsoleFunctorFlags& outFlags) { const size_t commandLength = command.size(); bool result = false; for (ConsoleFunctorBase* curr = m_head; curr != nullptr; curr = curr->m_next) { if (StringFunc::Equal(curr->m_name, command.c_str(), false, commandLength + 1)) // + 1 to include the NULL terminator { result = true; if ((curr->GetFlags() & requiredSet) != requiredSet) { AZ_Warning("Az Console", false, "%s failed required set flag check\n", curr->m_name); continue; } if ((curr->GetFlags() & requiredClear) != ConsoleFunctorFlags::Null) { AZ_Warning("Az Console", false, "%s failed required clear flag check\n", curr->m_name); continue; } if ((curr->GetFlags() & ConsoleFunctorFlags::IsCheat) != ConsoleFunctorFlags::Null) { AZ_Warning("Az Console", false, "%s is marked as a cheat\n", curr->m_name); } if ((curr->GetFlags() & ConsoleFunctorFlags::IsDeprecated) != ConsoleFunctorFlags::Null) { AZ_Warning("Az Console", false, "%s is marked as deprecated\n", curr->m_name); } if ((curr->GetFlags() & ConsoleFunctorFlags::NeedsReload) != ConsoleFunctorFlags::Null) { AZ_Warning("Az Console", false, "Changes to %s will only take effect after level reload\n", curr->m_name); } // Letting this intentionally fall-through, since in editor we can register common variables multiple times (*curr)(inputs); outFlags = curr->GetFlags(); } } if (!result) { AZ_Warning("Az Console", false, "Command %s not found", command.c_str()); } return result; } }
31.324138
187
0.576398
[ "vector" ]
fdd4c3104b9fe47048c523e541a66b36de538c1e
3,343
hpp
C++
external/succinct/darray64.hpp
ZabalaMariano/PISA
344063799847e89f2f4bd7d75d606ccb95620d30
[ "Apache-2.0" ]
138
2015-01-03T23:21:53.000Z
2022-02-26T16:51:03.000Z
external/succinct/darray64.hpp
ZabalaMariano/PISA
344063799847e89f2f4bd7d75d606ccb95620d30
[ "Apache-2.0" ]
3
2015-03-04T11:14:32.000Z
2017-06-13T21:25:50.000Z
darray64.hpp
ot/succinct
669eebbdcaa0562028a22cb7c877e512e4f1210b
[ "Apache-2.0" ]
23
2015-02-04T01:58:41.000Z
2020-11-04T14:43:23.000Z
#pragma once #include "bit_vector.hpp" #include "broadword.hpp" namespace succinct { struct darray64 { struct builder { builder() : n_ones(0) {} void append1(size_t skip0 = 0) { bits.append_bits(0, skip0); bits.push_back(1); if (n_ones % block_size == 0) { block_inventory.push_back(bits.size() - 1); } if (n_ones % subblock_size == 0) { subblock_inventory.push_back(uint16_t(bits.size() - 1 - block_inventory[n_ones / block_size])); } n_ones += 1; } size_t n_ones; bit_vector_builder bits; std::vector<uint64_t> block_inventory; std::vector<uint16_t> subblock_inventory; }; darray64() : m_num_ones(0) {} darray64(builder* b) { m_num_ones = b->n_ones; bit_vector(&b->bits).swap(m_bits); m_block_inventory.steal(b->block_inventory); m_subblock_inventory.steal(b->subblock_inventory); } void swap(darray64& other) { std::swap(m_num_ones, other.m_num_ones); m_bits.swap(other.m_bits); m_block_inventory.swap(other.m_block_inventory); m_subblock_inventory.swap(other.m_subblock_inventory); } template <typename Visitor> void map(Visitor& visit) { visit (m_num_ones, "m_num_ones") (m_bits, "m_bits") (m_block_inventory, "m_block_inventory") (m_subblock_inventory, "m_subblock_inventory") ; } size_t num_ones() const { return m_num_ones; } bit_vector const& bits() const { return m_bits; } size_t select(size_t idx) const { assert(idx < num_ones()); size_t block = idx / block_size; size_t block_pos = m_block_inventory[block]; size_t subblock = idx / subblock_size; size_t start_pos = block_pos + m_subblock_inventory[subblock]; size_t reminder = idx % subblock_size; if (!reminder) { return start_pos; } else { size_t word_idx = start_pos / 64; size_t word_shift = start_pos % 64; uint64_t word = m_bits.data()[word_idx] & (uint64_t(-1) << word_shift); while (true) { size_t popcnt = broadword::popcount(word); if (reminder < popcnt) break; reminder -= popcnt; word = m_bits.data()[++word_idx]; } return 64 * word_idx + broadword::select_in_word(word, reminder); } } protected: static const size_t block_size = 1024; // 64 * block_size must fit in an uint16_t (64 is the max sparsity of bits) static const size_t subblock_size = 64; size_t m_num_ones; bit_vector m_bits; mapper::mappable_vector<uint64_t> m_block_inventory; mapper::mappable_vector<uint16_t> m_subblock_inventory; }; }
28.818966
122
0.514807
[ "vector" ]
fdd52a5fd3afcccf30f549c87abd3716a9e8d540
6,140
cxx
C++
StRoot/StEvent/StFmsPoint.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StEvent/StFmsPoint.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StEvent/StFmsPoint.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id: StFmsPoint.cxx,v 2.8 2017/11/20 20:01:49 smirnovd Exp $ * * Author: Thomas Burton, Yuxi Pan, 2014 *************************************************************************** * * Description: Implementation of StFmsPoint, the StEvent FMS * photon structure * *************************************************************************** * * $Log: StFmsPoint.cxx,v $ * Revision 2.8 2017/11/20 20:01:49 smirnovd * Remove StRoot/ from included header prefix * * Revision 2.7 2016/06/07 15:51:34 akio * Making code better based on Coverity reports * * Revision 2.6 2015/09/14 16:59:22 ullrich * Added comments and modified print out. * * Revision 2.5 2015/09/01 21:01:47 ullrich * Minor changes to format of print statments and \nchange to naming of data member. * * Revision 2.4 2015/09/01 18:29:01 ullrich * Changes due to adding StFpsSlat and interconnection between slats and points. * * Revision 2.3 2015/08/26 16:51:25 ullrich * Fixed bug in cluster() and added print out fct and operator. * * Revision 2.2 2015/08/19 19:22:34 ullrich * Major update (PID) by Akio. * * ***************************************************************************/ #include "StFmsPoint.h" #include "St_base/StMessMgr.h" #include "TMath.h" static const char rcsid[] = "$Id: StFmsPoint.cxx,v 2.8 2017/11/20 20:01:49 smirnovd Exp $"; StFmsPoint::StFmsPoint() : mDetectorId(0), mEnergy(-1.0), mX(-99.0), mY(-99.0), mId(-1), mParentClusterId(-1), mNParentClusterPhotons(-1), mCluster(0) { resetFps(); } StFmsPoint::~StFmsPoint() { /* no op */ } int StFmsPoint::fpsNCandidate(int layer) { if (layer>=1 && layer<=kFpsNLayer) { return mFpsNCandidate[layer-1]; } return 0; } float StFmsPoint::fpsMip(int layer, int candidate) { if(layer<1 || layer>kFpsNLayer) return -1; if(candidate>=0 && candidate<kFpsNCandidate) return mFpsMip[layer-1][candidate]; //return mip for a candidate if(candidate>=kFpsNCandidate && candidate<=kFpsNCandidate+2){ // candidate=kFpsNCandidate return 1+2 float sum=0.0; // candidate=kFpsNCandidate+1 return 1+2+3 for(int i=0; i<candidate-kFpsNCandidate+2; i++){ // candidate=kFpsNCandidate+2 return 1+2+3+4 if(i==0 && mFpsMip[layer-1][i]==-9.0) return -9.0; // if closest one has bad status, return bad. if(mFpsMip[layer-1][i]>0.0) sum+=mFpsMip[layer-1][i]; } return sum; } return -1; } int StFmsPoint::fpsSlatId(int layer, int candidate) { if (layer>=1 && layer<=kFpsNLayer && candidate>=0 && candidate<mFpsNCandidate[layer-1]){ return mFpsSlatId[layer-1][candidate]; } return -1; } float StFmsPoint::fpsDistance(int layer, int candidate) { if (layer>=1 && layer<=kFpsNLayer && candidate>=0 && candidate<mFpsNCandidate[layer-1]){ return mFpsDistance[layer-1][candidate]; } return 999.0; } void StFmsPoint::setFps(int layer, float mip, int slatid, float d) { if (layer>=1 && layer<=kFpsNLayer){ int n=mFpsNCandidate[layer-1]; if (n>=kFpsNCandidate) { LOG_WARN << Form("StFmsPoint::setFps() too many FPS slats associcated with a point in layer=%d (slatid=%d distance=%6.2f mip=%6.2f) n=%d/%d" ,layer,slatid,d,mip,n,kFpsNCandidate) <<endm; return; } mFpsMip[layer-1][n] = mip; mFpsSlatId[layer-1][n] = slatid; mFpsDistance[layer-1][n] = d; mFpsNCandidate[layer-1]++; } orderFpsCandidates(layer); } void StFmsPoint::resetFps() { mFpsPid = 0; for(int l=0; l<kFpsNLayer; l++){ mFpsNCandidate[l]=0; for(int c=0; c<kFpsNCandidate; c++){ mFpsMip[l][c] = -2.0; mFpsSlatId[l][c] = -1; mFpsDistance[l][c] = 999.0; } } } void StFmsPoint::orderFpsCandidates(int layer) { //order candidates by distance int l1=0, l2=kFpsNLayer; if(layer>0) {l1=layer-1; l2=layer;} for(int l=l1; l<l2; l++){ int n=mFpsNCandidate[l]; if(n<2) continue; int index[kFpsNCandidate]; TMath::Sort(n,mFpsDistance[l],index,false); //flase=increasing order for(int i=0; i<n-1; i++) { //swap contents based on index int j=index[i]; if(j!=i){ float mip = mFpsMip[l][i]; int slatid = mFpsSlatId[l][i]; float d = mFpsDistance[l][i]; mFpsMip[l][i] = mFpsMip[l][j]; mFpsSlatId[l][i] = mFpsSlatId[l][j]; mFpsDistance[l][i] = mFpsDistance[l][j]; mFpsMip[l][j] = mip; mFpsSlatId[l][j] = slatid; mFpsDistance[l][j] = d; for(int k=i+i; k<n; k++){ // swap index as well if(index[k]==i) { index[k]=j; index[i]=i; break; } } } } } } void StFmsPoint::print(int opt) { cout << Form("StFmsPoint: Id=%4d Det=%2d ParentId=%3d loc=%6.1f %6.1f xyz=%6.1f %6.1f %6.1f E=%7.2f ET=%6.2f FPS=", id(), detectorId(), parentClusterId(), x(), y(), XYZ().x(), XYZ().y(), XYZ().z(), energy(), fourMomentum().perp()); for(int i=1; i<=kFpsNLayer; i++) { //int mip=fpsMip(i,kFpsNCandidate); float mip=fpsMip(i,0); if(mip<0.0) {cout << "?";} else if(mip>9.0) {cout << "9";} else {cout << Form("%1d",int(mip+0.5));} } cout << Form(" PID=%2d(%s) ",fpsPid(),pidName(fpsPid())); for(int l=1; l<=kFpsNLayer; l++){ for(int j=0; j<fpsNCandidate(l); j++){ int slatid=fpsSlatId(l,j); int mip=int(fpsMip(l,j)+0.5); int slat=slatid%21+1; int layer=(slatid/21)%3+1; int quad=(slatid/21/3)+1; cout << Form(" Q%1dL%1dS%02d=%2d ",quad,layer,slat,mip); } } cout << endl; }
35.906433
152
0.528176
[ "3d" ]
fdddc3dde0a78e2ebea743aec564803147ab280c
8,277
cpp
C++
src/qt/stakereportdialog.cpp
Tillkoeln/WYTF
5092f9a457843a34903d51a289d8b6dcb97e6082
[ "MIT" ]
null
null
null
src/qt/stakereportdialog.cpp
Tillkoeln/WYTF
5092f9a457843a34903d51a289d8b6dcb97e6082
[ "MIT" ]
null
null
null
src/qt/stakereportdialog.cpp
Tillkoeln/WYTF
5092f9a457843a34903d51a289d8b6dcb97e6082
[ "MIT" ]
2
2020-11-19T10:27:53.000Z
2020-12-23T02:36:03.000Z
//***************************************************** // // Dialog which report the earning made with stake over time // Original coding by Remy5 // #include "stakereportdialog.h" #include "ui_stakereportdialog.h" #include "guiconstants.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "bitcoinrpc.h" #include "optionsmodel.h" #include "main.h" // for hashBestChain #include <QWidget> #include <QDateTime> #include <QTimer> #include <QClipboard> using namespace json_spirit; using namespace boost; using namespace std; struct StakePeriodRange_T { int64_t Start; int64_t End; int64_t Total; int Count; string Name; }; typedef vector<StakePeriodRange_T> vStakePeriodRange_T; extern vStakePeriodRange_T PrepareRangeForStakeReport(); extern int GetsStakeSubTotal(vStakePeriodRange_T& aRange); StakeReportDialog::StakeReportDialog(QWidget *parent) : QDialog(parent), ui(new Ui::StakeReportDialog) { ui->setupUi(this); QTableWidget *TableW = ui->StakeReportTable; alreadyConnected = false; // fill the table with clone of row 0 for(int y=TableW->rowCount(); --y >= 1;) for(int x=TableW->columnCount(); --x >= 0;) TableW->setItem(y, x, TableW->item(0, x)->clone()); TableW->horizontalHeader()->resizeSection(1,160); QApplication::processEvents(); updateStakeReportNow(); // 1st update } StakeReportDialog::~StakeReportDialog() { delete ui; } void StakeReportDialog::setModel(WalletModel *model) { this->ex_model = model; if(ex_model && ex_model->getOptionsModel() && !alreadyConnected) { alreadyConnected = true; connect(ex_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int))); connect(ui->button_Refresh, SIGNAL(clicked()), this, SLOT(updateStakeReportNow())); connect(ui->CopytoClipboard, SIGNAL(clicked()), this, SLOT(CopyAllToClipboard())); disablereportupdate = GetBoolArg("-disablereportupdate"); if (!disablereportupdate) { QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateStakeReportTimer())); connect(ex_model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64))); timer->start(MODEL_UPDATE_DELAY*5); } } } void StakeReportDialog::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64) { StakeReportDialog::updateStakeReportNow(); } void StakeReportDialog::updateDisplayUnit(int) { StakeReportDialog::updateStakeReportNow(); } void StakeReportDialog::updateStakeReportTimer() { static int lastBest = 0 ; if (lastBest != nBestHeight) { lastBest = nBestHeight; StakeReportDialog::updateStakeReport(false); } } void StakeReportDialog::showEvent( QShowEvent* event ) { QWidget::showEvent( event ); StakeReportDialog::updateStakeReportNow(); } // Extendable localtime format QString HalfDate(int64_t nTime, QString TimeMode="") { QDateTime OrigDate = QDateTime::fromTime_t((qint32)nTime); QString LocalDate = OrigDate.date().toString("yyyy-MM-dd"); if (TimeMode != "") LocalDate += " " + OrigDate.toString(TimeMode); return LocalDate; } // format Bitcoinvalue with all trailing zero QString Coin_0Pad(int nUnit, int64_t amount) { QString result = BitcoinUnits::format(nUnit, amount); int poin = result.indexOf(".") + 1; poin += BitcoinUnits::decimals(nUnit); return result.leftJustified(poin, '0'); } void StakeReportDialog::updateStakeReportNow() { updateStakeReport(true); } void StakeReportDialog::updateStakeReport(bool fImmediate=false) { static vStakePeriodRange_T aRange; int nItemCounted=0; if (fImmediate) nLastReportUpdate = 0; if (this->isHidden()) return; int64_t nTook = GetTimeMillis(); // Skip report recalc if not immediate or before 5 minutes from last if (GetTime() - nLastReportUpdate > 300) { QApplication::processEvents(); ui->TimeTook->setText(tr("Please wait...")); ui->TimeTook->repaint(); QApplication::processEvents(); aRange = PrepareRangeForStakeReport(); // get subtotal calc nItemCounted = GetsStakeSubTotal(aRange); nLastReportUpdate = GetTime(); nTook = GetTimeMillis() - nTook; } int64_t nTook2 = GetTimeMillis(); // actually update labels int nDisplayUnit = BitcoinUnits::BTC; if (ex_model && ex_model->getOptionsModel()) nDisplayUnit = ex_model->getOptionsModel()->getDisplayUnit(); ui->L_Coin->setText(BitcoinUnits::name(nDisplayUnit) + " " + tr("Total")); QTableWidget *TableW = ui->StakeReportTable; TableW->horizontalHeaderItem(1)->setText(BitcoinUnits::name(nDisplayUnit) + " " +tr("Total")); int i=30; TableW->setSortingEnabled(false); for(int y=0; y<i; y++) { TableW->item(y,0)->setText(HalfDate(aRange[y].Start)); TableW->item(y,1)->setText(Coin_0Pad(nDisplayUnit, aRange[y].Total)); TableW->item(y,2)->setText(QString::number(aRange[y].Count)); } TableW->setSortingEnabled(true); ui->Amount_24H->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(" CHIP")); ui->Stake_24H->setText(QString::number(aRange[i++].Count)); ui->Amount_7D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(" CHIP")); ui->Stake_7D->setText(QString::number(aRange[i++].Count)); ui->Amount_30D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(" CHIP")); ui->Stake_30D->setText(QString::number(aRange[i++].Count)); ui->Amount_365D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(" CHIP")); ui->Stake_365D->setText(QString::number(aRange[i++].Count)); ui->Amount_Last->setText(tr("Total: ") + Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(" CHIP")); ui->L_LastStakeTime->setText(tr("Latest stake date: ") + HalfDate(aRange[i].Start, "hh:mm")); ui->Stake_Counted->setText(tr("Stakes analysed: ") + QString::number(nItemCounted)); if (nItemCounted) ui->TimeTook->setText(tr("Last Recalc took ") + QString::number(nTook) + "ms"); ui->TimeTook_2->setText(tr("Refresh took ") + QString::number(GetTimeMillis() -nTook2) + "ms"); string sRefreshType = disablereportupdate ? "Manual refresh" : "Auto refresh"; string strCurr_block_info = strprintf("%s - %s : %6d @ %s\nhash %s\n", sRefreshType.c_str(), "Current Block", nBestHeight, HalfDate(pindexBest->GetBlockTime(), "hh:mm:ss").toStdString().c_str(), hashBestChain.GetHex().c_str()); ui->L_CurrentBlock->setText(strCurr_block_info.c_str() ); } QString GridGetLabelTextAt(QGridLayout * Grid, int row, int column, QString Empty = "") { if (Grid && Grid->itemAtPosition(row, column) && Grid->itemAtPosition(row, column)->widget()) return ((QLabel *) Grid->itemAtPosition(row, column)->widget())->text(); else return Empty; } void StakeReportDialog::CopyAllToClipboard() { QString Repo; Repo += " Staking Log\n"; Repo += " ---------------------\n"; QString RowForm = "%1 %2 %3\n"; for(int y=0; y<ui->gridLayout->rowCount(); y++) { if (y == 5) Repo += "\n"; // separator line else Repo += RowForm .arg(GridGetLabelTextAt(ui->gridLayout, y,0), -16) .arg(GridGetLabelTextAt(ui->gridLayout, y,1), 16) .arg(GridGetLabelTextAt(ui->gridLayout, y,2), 7); } Repo += "\n"; QTableWidget *TableW = ui->StakeReportTable; RowForm = "%1, %2, %3\n"; Repo += RowForm .arg(TableW->horizontalHeaderItem(0)->text(), -10) .arg(TableW->horizontalHeaderItem(1)->text(), 16) .arg(TableW->horizontalHeaderItem(2)->text(), 7); for(int y=0; y<30; y++) { Repo += RowForm .arg(TableW->item(y,0)->text(), -10) .arg(TableW->item(y,1)->text(), 16) .arg(TableW->item(y,2)->text(), 7); } Repo += "\n" + ui->L_CurrentBlock->text() + "\n"; QApplication::clipboard()->setText(Repo); }
29.455516
160
0.643228
[ "vector", "model" ]
fde099997247c62563205f9bd199c4c7744964fb
6,011
cpp
C++
tests/VPRiedel-test.cpp
troldal/PCProps
80b05ef5e79178a2f3cb3bbf3cf08ecad5e9b174
[ "MIT" ]
null
null
null
tests/VPRiedel-test.cpp
troldal/PCProps
80b05ef5e79178a2f3cb3bbf3cf08ecad5e9b174
[ "MIT" ]
null
null
null
tests/VPRiedel-test.cpp
troldal/PCProps
80b05ef5e79178a2f3cb3bbf3cf08ecad5e9b174
[ "MIT" ]
null
null
null
/* 8888888b. .d8888b. 8888888b. 888 Y88b d88P Y88b 888 Y88b 888 888 888 888 888 888 888 d88P 888 888 d88P 888d888 .d88b. 88888b. .d8888b 8888888P" 888 8888888P" 888P" d88""88b 888 "88b 88K 888 888 888 888 888 888 888 888 888 "Y8888b. 888 Y88b d88P 888 888 Y88..88P 888 d88P X88 888 "Y8888P" 888 888 "Y88P" 88888P" 88888P' 888 888 888 Copyright (c) 2020 Kenneth Troldal Balslev 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 <VaporPressure/VPRiedel.hpp> #include <catch.hpp> TEST_CASE("VPRiedel Test") { auto psat = PCProps::VaporPressure::VPRiedel {404.87, 632.35, 45.1911E5}; SECTION("Default Construction") { psat = PCProps::VaporPressure::VPRiedel {}; auto coeffs = psat.coefficients(); REQUIRE(coeffs[0] == Approx(0.0)); REQUIRE(coeffs[1] == Approx(0.0)); REQUIRE(coeffs[2] == Approx(0.0)); REQUIRE(coeffs[3] == Approx(0.0)); // This checks for NaN. If the value is NaN, any comparison (even with itself) will return false. REQUIRE(psat(300.0) != psat(300.0)); } SECTION("Object Construction") { auto coeffs = psat.coefficients(); REQUIRE(coeffs[0] == Approx(9.5814).epsilon(0.001)); REQUIRE(coeffs[1] == Approx(-9.8552).epsilon(0.001)); REQUIRE(coeffs[2] == Approx(-4.4729).epsilon(0.001)); REQUIRE(coeffs[3] == Approx(0.2738).epsilon(0.001)); REQUIRE(psat(300) == Approx(0.01755E5).epsilon(0.001)); REQUIRE(psat(350) == Approx(0.172E5).epsilon(0.001)); REQUIRE(psat(400) == Approx(0.886E5).epsilon(0.001)); REQUIRE(psat(450) == Approx(3.005E5).epsilon(0.001)); REQUIRE(psat(500) == Approx(7.74E5).epsilon(0.001)); REQUIRE(psat(550) == Approx(16.51E5).epsilon(0.001)); REQUIRE(psat(600) == Approx(31.20E5).epsilon(0.001)); psat = PCProps::VaporPressure::VPRiedel { 632.35, 45.1911E5, 9.5814, -9.8552, -4.4729, 0.2738 }; REQUIRE(coeffs[0] == Approx(9.5814).epsilon(0.001)); REQUIRE(coeffs[1] == Approx(-9.8552).epsilon(0.001)); REQUIRE(coeffs[2] == Approx(-4.4729).epsilon(0.001)); REQUIRE(coeffs[3] == Approx(0.2738).epsilon(0.001)); REQUIRE(psat(300) == Approx(0.01755E5).epsilon(0.001)); REQUIRE(psat(350) == Approx(0.172E5).epsilon(0.001)); REQUIRE(psat(400) == Approx(0.886E5).epsilon(0.001)); REQUIRE(psat(450) == Approx(3.005E5).epsilon(0.001)); REQUIRE(psat(500) == Approx(7.74E5).epsilon(0.001)); REQUIRE(psat(550) == Approx(16.51E5).epsilon(0.001)); REQUIRE(psat(600) == Approx(31.20E5).epsilon(0.001)); } SECTION("Object Copy Construction and Assignment") { auto psat2 {psat}; REQUIRE(psat2(300) == Approx(0.01755E5).epsilon(0.001)); REQUIRE(psat2(350) == Approx(0.172E5).epsilon(0.001)); REQUIRE(psat2(400) == Approx(0.886E5).epsilon(0.001)); REQUIRE(psat2(450) == Approx(3.005E5).epsilon(0.001)); REQUIRE(psat2(500) == Approx(7.74E5).epsilon(0.001)); REQUIRE(psat2(550) == Approx(16.51E5).epsilon(0.001)); REQUIRE(psat2(600) == Approx(31.20E5).epsilon(0.001)); auto psat3 = PCProps::VaporPressure::VPRiedel {}; psat3 = psat2; REQUIRE(psat3(300) == Approx(0.01755E5).epsilon(0.001)); REQUIRE(psat3(350) == Approx(0.172E5).epsilon(0.001)); REQUIRE(psat3(400) == Approx(0.886E5).epsilon(0.001)); REQUIRE(psat3(450) == Approx(3.005E5).epsilon(0.001)); REQUIRE(psat3(500) == Approx(7.74E5).epsilon(0.001)); REQUIRE(psat3(550) == Approx(16.51E5).epsilon(0.001)); REQUIRE(psat3(600) == Approx(31.20E5).epsilon(0.001)); } SECTION("Object Move Construction and Assignment") { auto psat2 {std::move(psat)}; REQUIRE(psat2(300) == Approx(0.01755E5).epsilon(0.001)); REQUIRE(psat2(350) == Approx(0.172E5).epsilon(0.001)); REQUIRE(psat2(400) == Approx(0.886E5).epsilon(0.001)); REQUIRE(psat2(450) == Approx(3.005E5).epsilon(0.001)); REQUIRE(psat2(500) == Approx(7.74E5).epsilon(0.001)); REQUIRE(psat2(550) == Approx(16.51E5).epsilon(0.001)); REQUIRE(psat2(600) == Approx(31.20E5).epsilon(0.001)); auto psat3 = PCProps::VaporPressure::VPRiedel {}; psat3 = std::move(psat2); REQUIRE(psat3(300) == Approx(0.01755E5).epsilon(0.001)); REQUIRE(psat3(350) == Approx(0.172E5).epsilon(0.001)); REQUIRE(psat3(400) == Approx(0.886E5).epsilon(0.001)); REQUIRE(psat3(450) == Approx(3.005E5).epsilon(0.001)); REQUIRE(psat3(500) == Approx(7.74E5).epsilon(0.001)); REQUIRE(psat3(550) == Approx(16.51E5).epsilon(0.001)); REQUIRE(psat3(600) == Approx(31.20E5).epsilon(0.001)); } }
43.244604
105
0.616536
[ "object" ]
fde535b5ca7cc680d03ba1adf6701f70f23b0374
7,883
hpp
C++
libqvr/rendercontext.hpp
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
[ "MIT" ]
2
2020-07-14T15:04:08.000Z
2022-03-05T12:21:25.000Z
libqvr/rendercontext.hpp
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
[ "MIT" ]
1
2022-03-08T17:40:42.000Z
2022-03-08T19:22:37.000Z
libqvr/rendercontext.hpp
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
[ "MIT" ]
null
null
null
/* * Copyright (C) 2016, 2017 Computer Graphics Group, University of Siegen * Written by Martin Lambers <martin.lambers@uni-siegen.de> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef QVR_RENDERCONTEXT_HPP #define QVR_RENDERCONTEXT_HPP #include <QRect> #include <QVector3D> #include <QMatrix4x4> #include <QQuaternion> #include "config.hpp" #include "frustum.hpp" class QDataStream; /*! * \brief Context for rendering a frame. * * A render context provides information about the views into the virtual world * that are required for one output frame in a given window. * * This information depends on the \a QVRWindow that the frame is produced for * and on the \a QVRObserver that observes this window. * * The render context is used in various places: * - In \a QVRApp::render(), it provides the information necessary for the * application to render a frame. * - In the event handling functions of \a QVRApp, it provides information about * the frame displayed in the window that generated the event. * - In the output plugin function \a QVROutputPlugin(), the context provides * information useful for a plugin to decide how to process the frame before * displaying it. */ class QVRRenderContext { private: int _processIndex; int _windowIndex; QRect _windowGeometry; QRect _screenGeometry; QVector3D _navigationPosition; QQuaternion _navigationOrientation; QVector3D _screenWall[3]; QVROutputMode _outputMode; int _viewCount; QVREye _eye[2]; QSize _textureSize[2]; QVector3D _trackingPosition[2]; QQuaternion _trackingOrientation[2]; QVRFrustum _frustum[2]; QMatrix4x4 _viewMatrix[2]; QMatrix4x4 _viewMatrixPure[2]; friend QDataStream &operator<<(QDataStream& ds, const QVRRenderContext& rc); friend QDataStream &operator>>(QDataStream& ds, QVRRenderContext& rc); // These functions are used internally by QVRWindow when computing the render context information. friend class QVRWindow; void setProcessIndex(int pi) { _processIndex = pi; } void setWindowIndex(int wi) { _windowIndex = wi; } void setWindowGeometry(const QRect& r) { _windowGeometry = r; } void setScreenGeometry(const QRect& r) { _screenGeometry = r; } void setNavigation(const QVector3D& p, const QQuaternion& r) { _navigationPosition = p; _navigationOrientation = r; } void setScreenWall(const QVector3D& bl, const QVector3D& br, const QVector3D& tl) { _screenWall[0] = bl; _screenWall[1]= br; _screenWall[2] = tl; } void setOutputConf(QVROutputMode om); void setTextureSize(int vp, const QSize& size) { _textureSize[vp] = size; } void setTracking(int vp, const QVector3D& p, const QQuaternion& r) { _trackingPosition[vp] = p; _trackingOrientation[vp] = r; } void setFrustum(int vp, const QVRFrustum f) { _frustum[vp] = f; } void setViewMatrix(int vp, const QMatrix4x4& vm) { _viewMatrix[vp] = vm; } void setViewMatrixPure(int vp, const QMatrix4x4& vmp) { _viewMatrixPure[vp] = vmp; } public: /*! \brief Constructor. */ QVRRenderContext(); /*! \brief Returns the index of the process that the window displaying the view belongs to. */ int processIndex() const { return _processIndex; } /*! \brief Returns the index of the window displaying the view, relative to the process it belongs to. */ int windowIndex() const { return _windowIndex; } /*! \brief Returns the pixel-based geometry of window on the Qt display screen (from \a QWindow::geometry()). */ const QRect& windowGeometry() const { return _windowGeometry; } /*! \brief Returns the pixel-based geometry of the Qt screen that the window is displayed on (from \a QScreen::geometry()). */ const QRect& screenGeometry() const { return _screenGeometry; } /*! \brief Returns the observer navigation position. */ const QVector3D& navigationPosition() const { return _navigationPosition; } /*! \brief Returns the observer navigation orientation. */ const QQuaternion& navigationOrientation() const { return _navigationOrientation; } /*! \brief Returns the observer navigation matrix. */ QMatrix4x4 navigationMatrix() const { QMatrix4x4 m; m.translate(navigationPosition()); m.rotate(navigationOrientation()); return m; } /*! \brief Returns the virtual world coordinates of the bottom left corner of the screen wall. */ QVector3D screenWallBottomLeft() const { return _screenWall[0]; } /*! \brief Returns the virtual world coordinates of the bottom right corner of the screen wall. */ QVector3D screenWallBottomRight() const { return _screenWall[1]; } /*! \brief Returns the virtual world coordinates of the top left corner of the screen wall. */ QVector3D screenWallTopLeft() const { return _screenWall[2]; } /*! \brief Returns the output mode of the window displaying the view. */ QVROutputMode outputMode() const { return _outputMode; } /*! \brief Returns the number of views necessary to produce the frame. */ int viewCount() const { return _viewCount; } /*! \brief Returns the eye for rendering \a view. */ QVREye eye(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _eye[view]; } /*! \brief Returns the texture size for rendering \a view. */ QSize textureSize(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _textureSize[view]; } /*! \brief Returns the observer tracking position for rendering \a view. */ const QVector3D& trackingPosition(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _trackingPosition[view]; } /*! \brief Returns the observer tracking orientation for rendering \a view. */ const QQuaternion& trackingOrientation(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _trackingOrientation[view]; } /*! \brief Returns the observer tracking matrix for rendering \a view. */ QMatrix4x4 trackingMatrix(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); QMatrix4x4 m; m.translate(trackingPosition(view)); m.rotate(trackingOrientation(view)); return m; } /*! \brief Returns the frustum for rendering \a view. */ const QVRFrustum& frustum(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _frustum[view]; } /*! \brief Returns the view matrix for rendering \a view. */ const QMatrix4x4& viewMatrix(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _viewMatrix[view]; } /*! \brief Returns the pure view matrix (i.e. in tracking space, without navigation) for rendering \a view. */ const QMatrix4x4& viewMatrixPure(int view) const { Q_ASSERT(view >= 0 && view < viewCount()); return _viewMatrixPure[view]; } }; QDataStream &operator<<(QDataStream& ds, const QVRRenderContext& rc); QDataStream &operator>>(QDataStream& ds, QVRRenderContext& rc); #endif
54.743056
190
0.724597
[ "geometry", "render" ]
fdeb690274ef7408514b88c8a5d02d03fdc6d2b6
1,033
cpp
C++
src/cmcandy/C_Language_Answers/_0738.cpp
ch98road/leetcode
a9b4be54a169b30f6711809b892dd1f79f2a17e7
[ "MIT" ]
null
null
null
src/cmcandy/C_Language_Answers/_0738.cpp
ch98road/leetcode
a9b4be54a169b30f6711809b892dd1f79f2a17e7
[ "MIT" ]
null
null
null
src/cmcandy/C_Language_Answers/_0738.cpp
ch98road/leetcode
a9b4be54a169b30f6711809b892dd1f79f2a17e7
[ "MIT" ]
1
2020-11-26T03:01:12.000Z
2020-11-26T03:01:12.000Z
#include <iostream> #include <vector> using namespace ::std; class Solution { public: int monotoneIncreasingDigits(int N) { vector<int> res; //1.高位先取,如果满足递增则一直去下去 //2.如果不满足,那么上一位-- // 3.如果上一位-- 后,依然满足递增,则后面全9即可 // 4.如果不满足,再上一位--,循环判断,直到最高位 string digit = to_string(N); int len = digit.size(); if (len < 2) return N; int i = 1; int flag = 0; while (i > 0 && i < len) { if (digit[i] >= digit[i - 1]) { //如果是调整过且符合要求,直接break if (flag == 1) break; //如果没调整,那就老老实实i++ i++; } else if (digit[i] < digit[i - 1]) { //上一位--,且调整标志置为1,一旦通过就通过 digit[--i]--; flag = 1; } } //剩下的位全部置为9即可 for (i; i < len - 1; i++) { digit[i + 1] = '9'; } return stoi(digit); } };
22.955556
45
0.384318
[ "vector" ]
fdf6a5d0a5a7a10a2f700a44e3290874eb935a56
2,844
cpp
C++
Arrangement_on_surface_2/examples/Arrangement_on_surface_2/polycurve_geodesic.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Arrangement_on_surface_2/examples/Arrangement_on_surface_2/polycurve_geodesic.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Arrangement_on_surface_2/examples/Arrangement_on_surface_2/polycurve_geodesic.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
//! \file examples/Arrangement_on_surface_2/polycurve_geodesic.cpp // Constructing an arrangement of polygeodesics. #include <vector> #include <list> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> #include <CGAL/Arr_geodesic_arc_on_sphere_traits_2.h> #include <CGAL/Arr_spherical_topology_traits_2.h> #include <CGAL/Arr_polyline_traits_2.h> #include <CGAL/Arrangement_on_surface_2.h> typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel; typedef CGAL::Arr_geodesic_arc_on_sphere_traits_2<Kernel> Segment_traits_2; typedef CGAL::Arr_polyline_traits_2<Segment_traits_2> Poly_traits_2; typedef Poly_traits_2::Point_2 Point_2; typedef Poly_traits_2::Curve_2 Poly_curve_2; typedef Poly_traits_2::X_monotone_curve_2 X_poly_curve_2; typedef CGAL::Arr_spherical_topology_traits_2<Poly_traits_2> Topol_poly_traits_2; typedef CGAL::Arrangement_on_surface_2<Poly_traits_2, Topol_poly_traits_2> Poly_arr; typedef Segment_traits_2::Curve_2 Seg_curve_2; typedef Segment_traits_2::X_monotone_curve_2 X_seg_curve_2; typedef CGAL::Arr_spherical_topology_traits_2<Segment_traits_2> Topol_segment_traits_2; typedef CGAL::Arrangement_on_surface_2<Segment_traits_2, Topol_segment_traits_2> Segment_arr; int main() { Segment_traits_2 seg_traits; Segment_traits_2::Construct_point_2 ctr_p = seg_traits.construct_point_2_object(); Segment_traits_2::Construct_x_monotone_curve_2 ctr_seg = seg_traits.construct_x_monotone_curve_2_object(); Point_2 p1 = ctr_p(0, 1, -1); Point_2 p2 = ctr_p(-11, 7, -7); Point_2 p3 = ctr_p(-1, 0, 0); Point_2 p4 = ctr_p(-11, 7, 7); Point_2 p5 = ctr_p(-1, 1, 1); Segment_arr seg_arr(&seg_traits); X_seg_curve_2 seg_cv1 = ctr_seg(p1, p2); X_seg_curve_2 seg_cv2 = ctr_seg(p2, p3); X_seg_curve_2 seg_cv3 = ctr_seg(p3, p4); X_seg_curve_2 seg_cv4 = ctr_seg(p4, p5); insert(seg_arr, seg_cv1); insert(seg_arr, seg_cv2); insert(seg_arr, seg_cv3); insert(seg_arr, seg_cv4); std::cout << "# seg. vertives: " << seg_arr.number_of_vertices() << std::endl; std::list<Point_2> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); points.push_back(p4); points.push_back(p5); Poly_traits_2 poly_traits; Poly_traits_2::Construct_x_monotone_curve_2 ctr = poly_traits.construct_x_monotone_curve_2_object(); Poly_arr poly_arr(&poly_traits); insert(poly_arr, ctr(seg_cv1)); insert(poly_arr, ctr(seg_cv2)); insert(poly_arr, ctr(seg_cv3)); insert(poly_arr, ctr(seg_cv4)); std::cout << "# poly vertives: " << poly_arr.number_of_vertices() << std::endl; return 0; }
37.421053
81
0.71308
[ "vector" ]
fdf7acb582feacdc244b6ec426bdf45b130c4e0d
4,884
cc
C++
chrome/browser/ui/tabs/tab_renderer_data.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/ui/tabs/tab_renderer_data.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/ui/tabs/tab_renderer_data.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/tabs/tab_renderer_data.h" #include "base/process/kill.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/tab_ui_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" #include "chrome/browser/ui/thumbnails/thumbnail_tab_helper.h" #include "chrome/common/webui_url_constants.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" namespace { bool ShouldThemifyFaviconForEntryUrl(const GURL& url) { // Themify favicon for the default NTP and incognito NTP. return url.SchemeIs(content::kChromeUIScheme) && (url.host_piece() == chrome::kChromeUINewTabPageHost || url.host_piece() == chrome::kChromeUINewTabHost); } bool ShouldThemifyFaviconForVisibleUrl(const GURL& visible_url) { return visible_url.SchemeIs(content::kChromeUIScheme) && visible_url.host_piece() != chrome::kChromeUIAppLauncherPageHost && visible_url.host_piece() != chrome::kChromeUIHelpHost && visible_url.host_piece() != chrome::kChromeUIVersionHost && visible_url.host_piece() != chrome::kChromeUINetExportHost && visible_url.host_piece() != chrome::kChromeUINewTabHost; } } // namespace // static TabRendererData TabRendererData::FromTabInModel(TabStripModel* model, int index) { content::WebContents* const contents = model->GetWebContentsAt(index); TabRendererData data; TabUIHelper* const tab_ui_helper = TabUIHelper::FromWebContents(contents); data.favicon = tab_ui_helper->GetFavicon().AsImageSkia(); ThumbnailTabHelper* const thumbnail_tab_helper = ThumbnailTabHelper::FromWebContents(contents); if (thumbnail_tab_helper) data.thumbnail = thumbnail_tab_helper->thumbnail(); data.network_state = TabNetworkStateForWebContents(contents); data.title = tab_ui_helper->GetTitle(); data.visible_url = contents->GetVisibleURL(); // Allow empty title for chrome-untrusted:// URLs. if (data.title.empty() && data.visible_url.SchemeIs(content::kChromeUIUntrustedScheme)) { data.should_render_empty_title = true; } data.last_committed_url = contents->GetLastCommittedURL(); data.crashed_status = contents->GetCrashedStatus(); data.incognito = contents->GetBrowserContext()->IsOffTheRecord(); data.pinned = model->IsTabPinned(index); data.show_icon = data.pinned || model->delegate()->ShouldDisplayFavicon(contents); data.blocked = model->IsTabBlocked(index); data.should_hide_throbber = tab_ui_helper->ShouldHideThrobber(); data.alert_state = chrome::GetTabAlertStatesForContents(contents); content::NavigationEntry* entry = contents->GetController().GetLastCommittedEntry(); data.should_themify_favicon = (entry && ShouldThemifyFaviconForEntryUrl(entry->GetURL())) || ShouldThemifyFaviconForVisibleUrl(contents->GetVisibleURL()); return data; } TabRendererData::TabRendererData() = default; TabRendererData::TabRendererData(const TabRendererData& other) = default; TabRendererData::TabRendererData(TabRendererData&& other) = default; TabRendererData& TabRendererData::operator=(const TabRendererData& other) = default; TabRendererData& TabRendererData::operator=(TabRendererData&& other) = default; TabRendererData::~TabRendererData() = default; bool TabRendererData::operator==(const TabRendererData& other) const { return favicon.BackedBySameObjectAs(other.favicon) && thumbnail == other.thumbnail && network_state == other.network_state && title == other.title && visible_url == other.visible_url && last_committed_url == other.last_committed_url && crashed_status == other.crashed_status && incognito == other.incognito && show_icon == other.show_icon && pinned == other.pinned && blocked == other.blocked && alert_state == other.alert_state && should_hide_throbber == other.should_hide_throbber; } bool TabRendererData::IsCrashed() const { return (crashed_status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED || #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) crashed_status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM || #endif crashed_status == base::TERMINATION_STATUS_PROCESS_CRASHED || crashed_status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION || crashed_status == base::TERMINATION_STATUS_LAUNCH_FAILED); }
43.607143
80
0.743243
[ "model" ]
fdfa343a87ed733aa544442c1a0a9dd621efd2bd
2,399
cc
C++
USACO/ZeroSum.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
USACO/ZeroSum.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
USACO/ZeroSum.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
/* ID: jeferso1 LANG: C++ TASK: zerosum */ #include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned long long uInt; typedef unsigned uint; vector<string> valid_str; int evaluate(const string arg) { int sum = 0; int curr_value = 0; stack<string> stk; for (int i = 0; i < (int) arg.size(); i++) { if (isdigit(arg[i])) { int curr_digit = arg[i] - '0'; curr_value = curr_value * 10 + curr_digit; } else if (arg[i] == ' ') { continue; } else { stk.push(to_string(curr_value)); stk.push(string(1, arg[i])); curr_value = 0; } } stk.push(to_string(curr_value)); if (stk.size() == 1) { return stoi(stk.top()); } while (!stk.empty()) { int val = stoi(stk.top()); stk.pop(); if (stk.empty()) { sum += val; } else { string operand = stk.top(); stk.pop(); ///cout << arg << " " << val << " " << operand << endl; if (operand == "+") { sum += val; } else { sum -= val; } } } return sum; } void rec(int curr_digit, string str, const int max_val) { if (curr_digit > max_val) { if (evaluate(str) == 0) { valid_str.push_back(str); } return; } if (curr_digit == 1) { rec(curr_digit + 1,str + "1", max_val); } else { rec(curr_digit + 1, str + "+" + to_string(curr_digit), max_val); rec(curr_digit + 1, str + "-" + to_string(curr_digit), max_val); rec(curr_digit + 1, str + " " + to_string(curr_digit), max_val); } } int main(void) { freopen("zerosum.in", "r", stdin); freopen("zerosum.out", "w", stdout); int N; cin >> N; rec(1, "", N); sort(valid_str.begin(), valid_str.end()); for (int i = 0; i < (int) valid_str.size(); i++) { cout << valid_str[i] << "\n"; } return 0; }
21.419643
72
0.4802
[ "vector" ]
fdfcb5a65cc13ba2062804cb1431d9ac936ec3f1
34,215
cpp
C++
source/kinect_client.cpp
0x0AF/rgbd-recon
0f0cd3a892aed0bde01874f4be767b36478d866c
[ "MIT" ]
1
2018-03-13T13:44:33.000Z
2018-03-13T13:44:33.000Z
source/kinect_client.cpp
0x0AF/rgbd-recon
0f0cd3a892aed0bde01874f4be767b36478d866c
[ "MIT" ]
null
null
null
source/kinect_client.cpp
0x0AF/rgbd-recon
0f0cd3a892aed0bde01874f4be767b36478d866c
[ "MIT" ]
null
null
null
#include <glbinding/gl/gl.h> using namespace gl; // load glbinding function type #include <glbinding/Function.h> // load meta info extension #include <glbinding/Meta.h> // load callback support #include <glbinding/callbacks.h> //dont load gl bindings from glfw #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <globjects/globjects.h> #include <globjects/Buffer.h> #include <globjects/Query.h> #include <globjects/base/File.h> #include <imgui.h> #include <imgui_impl_glfw_glb.h> #include <iostream> #include <cmath> #include <stdlib.h> #include <memory> #include <tuple> #include <CMDParser.h> #include <FeedbackReceiver.h> #include "configurator.hpp" #include "texture_blitter.hpp" #include <Point3.h> #include <BoundingBox.h> #include <PerspectiveCamera.h> #include <StereoCamera.h> #include <CameraNavigator.h> #include "CalibVolumes.hpp" #include <calibration_files.hpp> #include <NetKinectArray.h> #include <KinectCalibrationFile.h> #include "timer_database.hpp" #include "reconstruction.hpp" #include "recon_trigrid.hpp" #include "recon_points.hpp" #include "recon_calibs.hpp" #include "recon_integration.hpp" #include "recon_mvt.hpp" /// general setup std::string g_server_socket = "127.0.0.1:7000"; sys::FeedbackReceiver* g_fbr = 0; float g_clear_color[4] = {0.0,0.0,0.0,0.0}; unsigned g_stereo_mode = 0; float g_screenWidthReal = 1.28; float g_screenHeightReal = 0.72; unsigned g_screenWidth = 1280; unsigned g_screenHeight = 720; unsigned g_windowWidth = 1280; unsigned g_windowHeight = 720; unsigned g_left_pos_x = 0; unsigned g_left_pos_y = 0; unsigned g_right_pos_x = 0; unsigned g_right_pos_y = 0; float g_aspect = g_screenWidth * 1.0/g_screenHeight; bool g_play = true; bool g_draw_frustums= false; bool g_draw_grid = true; bool g_animate = false; int g_recon_mode = 1; bool g_bilateral = true; bool g_draw_calibvis= false; bool g_draw_textures= false; int g_texture_type = 0; int g_num_texture = 0; bool g_processed = true; bool g_refine = true; bool g_colorfill = true; bool g_bricking = true; bool g_skip_space = true; bool g_draw_bricks = false; bool g_watch_errors = true; int g_num_kinect = 1; float g_voxel_size = 0.01f; float g_brick_size = 0.1f; float g_tsdf_limit = 0.01f; float g_zoom = 0.5f; double g_time_prev = 0.0f; int g_min_voxels = 10; bool g_loaded_conf = false; unsigned g_time_limit = 1; std::string g_conf_file{}; gloost::BoundingBox g_bbox{}; std::vector<std::pair<int, int>> g_gui_texture_settings{}; gloost::PerspectiveCamera g_camera{50.0, g_aspect, 0.1, 200.0}; gloost::StereoCamera* g_stereo_camera; pmd::CameraNavigator g_navi{0.5f}; std::unique_ptr<kinect::NetKinectArray> g_nka; std::unique_ptr<kinect::CalibVolumes> g_cv; std::unique_ptr<kinect::CalibrationFiles> g_calib_files; GLFWwindow* g_window = nullptr; globjects::Buffer* g_buffer_shading; struct shading_data_t { int mode = 0; } g_shading_buffer_data; void init_stereo_camera(); void init_fbr(const char* client_socket); void init(std::vector<std::string> const& args); void init_config(std::vector<std::string> const& args); void load_config(std::string const&); void update_model_matrix(bool load_ident = true); void draw3d(); void watch_gl_errors(bool activate); void quit(int status); std::shared_ptr<kinect::ReconIntegration> g_recon_integration{}; std::vector<std::shared_ptr<kinect::Reconstruction>> g_recons;// 4 std::unique_ptr<kinect::ReconCalibs> g_calibvis;// 4 ////////////////////////////////////////////////////////////////////////////////////////// void init_stereo_camera(){ gloost::Matrix eye_matrix; eye_matrix.setIdentity(); eye_matrix.setTranslate(0.0,0.0,1.0); gloost::Matrix screen_matrix; screen_matrix.setIdentity(); g_stereo_camera = new gloost::StereoCamera(eye_matrix, 0.2, 20.0, 0.064 /*eyesep*/, screen_matrix, g_screenWidthReal, g_screenHeightReal); } std::ostream& operator<< (std::ostream& os, const glm::mat4& m){ os << "mat4[" << std::fixed << std::endl; os << " (" << m[0][0] << ", " << m[1][0] << ", " << m[2][0] << ", " << m[3][0] << ")," << std::endl; os << " (" << m[0][1] << ", " << m[1][1] << ", " << m[2][1] << ", " << m[3][1] << ")," << std::endl; os << " (" << m[0][2] << ", " << m[1][2] << ", " << m[2][2] << ", " << m[3][2] << ")," << std::endl; os << " (" << m[0][3] << ", " << m[1][3] << ", " << m[2][3] << ", " << m[3][3] << ") ]" << std::endl; return os; } gloost::Matrix glm2gloost(const glm::mat4 m){ gloost::Matrix tmp; tmp[0] = m[0][0]; tmp[1] = m[0][1]; tmp[2] = m[0][2]; tmp[3] = m[0][3]; tmp[4] = m[1][0]; tmp[5] = m[1][1]; tmp[6] = m[1][2]; tmp[7] = m[1][3]; tmp[8] = m[2][0]; tmp[9] = m[2][1]; tmp[10] = m[2][2]; tmp[11] = m[2][3]; tmp[12] = m[3][0]; tmp[13] = m[3][1]; tmp[14] = m[3][2]; tmp[15] = m[3][3]; return tmp; } void init_fbr(const char* client_socket){ sys::feedback initial_fb; initial_fb.cyclops_mat[3][0] = 0.0; initial_fb.cyclops_mat[3][1] = 0.0; initial_fb.cyclops_mat[3][2] = 1.0; initial_fb.recon_mode = 1; g_fbr = new sys::FeedbackReceiver(initial_fb, client_socket); } void init(std::vector<std::string> const& args){ std::string ext{args[0].substr(args[0].find_last_of(".") + 1)}; std::string file_name{}; if("ks" == ext) { file_name = args[0]; } else { throw std::invalid_argument{"No .ks file specified"}; } // read ks file std::vector<std::string> calib_filenames; gloost::Point3 bbox_min{-1.0f ,0.0f, -1.0f}; gloost::Point3 bbox_max{ 1.0f ,2.2f, 1.0f}; std::string resource_path = file_name.substr(0, file_name.find_last_of("/\\")) + '/'; std::cout << resource_path << std::endl; std::ifstream in(file_name); std::string token; while(in >> token){ if (token == "kinect") { in >> token; // detect absolute path if (token[0] == '/' || token[1] == ':') { calib_filenames.push_back(token); } else { calib_filenames.push_back(resource_path + token); } } else if (token == "bbx") { in >> bbox_min[0]; in >> bbox_min[1]; in >> bbox_min[2]; in >> bbox_max[0]; in >> bbox_max[1]; in >> bbox_max[2]; } } in.close(); // update bounding box dimensions with read values g_bbox.setPMin(bbox_min); g_bbox.setPMax(bbox_max); g_calib_files = std::unique_ptr<kinect::CalibrationFiles>{new kinect::CalibrationFiles(calib_filenames)}; g_cv = std::unique_ptr<kinect::CalibVolumes>{new kinect::CalibVolumes(calib_filenames, g_bbox)}; g_nka = std::unique_ptr<kinect::NetKinectArray>{new kinect::NetKinectArray(g_server_socket, g_calib_files.get(), g_cv.get())}; // binds to unit 1 to 3 g_nka->setStartTextureUnit(1); // bind calubration volumes from 4 - 13 g_cv->setStartTextureUnit(9); g_cv->loadInverseCalibs(resource_path); g_cv->setStartTextureUnitInv(30); g_recons.emplace_back(new kinect::ReconPoints(*g_calib_files, g_cv.get(), g_bbox)); g_recon_integration = std::make_shared<kinect::ReconIntegration>(*g_calib_files, g_cv.get(), g_bbox, g_tsdf_limit, g_voxel_size); g_recons.emplace_back(g_recon_integration); g_recons.emplace_back(new kinect::ReconTrigrid(*g_calib_files, g_cv.get(), g_bbox)); g_recons.emplace_back(new kinect::ReconMVT(*g_calib_files, g_cv.get(), g_bbox)); g_calibvis = std::unique_ptr<kinect::ReconCalibs>(new kinect::ReconCalibs(*g_calib_files, g_cv.get(), g_bbox)); // enable point scaling in vertex shader glEnable(GL_PROGRAM_POINT_SIZE); glEnable(GL_POINT_SPRITE); g_buffer_shading = new globjects::Buffer(); g_buffer_shading->ref(); g_buffer_shading->setData(sizeof(shading_data_t), &g_shading_buffer_data, GL_STATIC_DRAW); g_buffer_shading->bindBase(GL_UNIFORM_BUFFER, 1); // apply settings g_nka->useProcessedDepths(g_processed); g_nka->filterTextures(g_bilateral); g_nka->refineBoundary(g_refine); g_recon_integration->setTsdfLimit(g_tsdf_limit); g_recon_integration->setVoxelSize(g_voxel_size); g_recon_integration->setBrickSize(g_brick_size); g_recon_integration->setColorFilling(g_colorfill); g_recon_integration->setSpaceSkip(g_skip_space); g_recon_integration->setDrawBricks(g_draw_bricks); g_recon_integration->setUseBricks(g_bricking); } void init_config(std::vector<std::string> const& args) { // read config file if(args.size() > 1) { std::string ext = args[1].substr(args[1].find_last_of(".") + 1); if("conf" == ext) { load_config(args[1]); } else { throw std::invalid_argument{"No .conf file specified"}; } } } void load_config(std::string const& file_name) { configurator().read(file_name); configurator().print(); g_recon_mode = configurator().getUint("recon_mode"); g_screenWidth = configurator().getUint("screenWidth"); g_screenHeight = configurator().getUint("screenHeight"); g_play = configurator().getBool("play"); g_draw_grid = configurator().getBool("draw_grid"); g_animate = configurator().getBool("animate"); g_bilateral = configurator().getBool("bilateral"); g_processed = configurator().getBool("processed"); g_refine = configurator().getBool("refine"); g_colorfill = configurator().getBool("colorfill"); g_bricking = configurator().getBool("bricking"); g_skip_space = configurator().getBool("skip_space"); g_watch_errors = configurator().getBool("watch_errors"); g_voxel_size = configurator().getFloat("voxel_size"); g_brick_size = configurator().getFloat("brick_size"); g_tsdf_limit = configurator().getFloat("tsdf_limit"); g_zoom = configurator().getFloat("zoom"); g_time_limit = configurator().getUint("time_limit"); g_loaded_conf = true; g_conf_file = file_name; } ////////////////////////////////////////////////////////////////////////////////////////// /// logic void update_gui() { ImGui_ImplGlfwGLB_NewFrame(); // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" // { // static float f = 0.0f; // ImGui::Text("Hello, world!"); // ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // ImGui::ColorEdit3("clear color", (float*)&clear_color); // if (ImGui::Button("Another Window")) show_another_window ^= 1; // } // 2. Show another simple window, this time using an explicit Begin/End pair // if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Settings"); if (ImGui::Button("Show textures")) { g_gui_texture_settings.emplace_back(0, 0); } if (ImGui::Checkbox("Watch OpenGL errors", &g_watch_errors)) { watch_gl_errors(g_watch_errors); } ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); if (ImGui::CollapsingHeader("Reconstruction Mode",ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::RadioButton("Points", &g_recon_mode, 0); ImGui::RadioButton("Integration", &g_recon_mode, 1); ImGui::RadioButton("Trigrid", &g_recon_mode, 2); ImGui::RadioButton("Trigrid orig", &g_recon_mode, 3); } if (ImGui::CollapsingHeader("Visualisation")) { int prev = g_shading_buffer_data.mode; ImGui::RadioButton("Textured", &g_shading_buffer_data.mode, 0); ImGui::RadioButton("Shaded", &g_shading_buffer_data.mode, 1); ImGui::RadioButton("Normals", &g_shading_buffer_data.mode, 2); ImGui::RadioButton("Blending", &g_shading_buffer_data.mode, 3); if(prev != g_shading_buffer_data.mode) { g_buffer_shading->setSubData(0, sizeof(shading_data_t), &g_shading_buffer_data); } } if (ImGui::CollapsingHeader("Processing")) { if (ImGui::Checkbox("Morphological Filter", &g_processed)) { g_nka->useProcessedDepths(g_processed); g_recon_integration->integrate(); } if (ImGui::Checkbox("Bilateral Filter", &g_bilateral)) { g_nka->filterTextures(g_bilateral); g_recon_integration->integrate(); } if (ImGui::Checkbox("Boundary Refinement", &g_refine)) { g_nka->refineBoundary(g_refine); g_recon_integration->integrate(); } } if (ImGui::CollapsingHeader("Integration ")) { if (ImGui::DragFloat("TSDF Limit", &g_tsdf_limit, 0.001f, 0.001f, 0.03f, "%.3f")) { g_recon_integration->setTsdfLimit(g_tsdf_limit); } if (ImGui::DragFloat("Voxel Size", &g_voxel_size, 0.001f, 0.003f, 0.1f, "%.3f")) { g_recon_integration->setVoxelSize(g_voxel_size); g_brick_size = g_recon_integration->getBrickSize(); } if (ImGui::DragFloat("Brick Size", &g_brick_size, 0.01f, 0.1f, 1.0f, "%.3f")) { g_recon_integration->setBrickSize(g_brick_size); g_brick_size = g_recon_integration->getBrickSize(); } if (ImGui::DragInt("Min Brick Voxels", &g_min_voxels, 1, 0, 500, "%.0f")) { g_recon_integration->setMinVoxelsPerBrick(g_min_voxels); g_recon_integration->updateOccupiedBricks(); g_recon_integration->integrate(); } if (ImGui::Checkbox("Color hole filling", &g_colorfill)) { g_recon_integration->setColorFilling(g_colorfill); } if(g_recons[g_recon_mode].get() == g_recon_integration.get() &&g_bricking) { ImGui::Columns(2, NULL, false); if (ImGui::Checkbox("Volume Bricking", &g_bricking)) { g_recon_integration->setUseBricks(g_bricking); } ImGui::NextColumn(); ImGui::Text("%.3f %% occupied", g_recon_integration->occupiedRatio() * 100.0f); ImGui::Columns(1); if(g_bricking) { if (ImGui::Checkbox("Skip empty Spaces", &g_skip_space)) { g_recon_integration->setSpaceSkip(g_skip_space); } if (ImGui::Checkbox("Draw occupied bricks", &g_draw_bricks)) { g_recon_integration->setDrawBricks(g_draw_bricks); } } } else { if (ImGui::Checkbox("Volume Bricking", &g_bricking)) { g_recon_integration->setUseBricks(g_bricking); g_recon_integration->integrate(); } } if (ImGui::Checkbox("Draw TSDF", &g_draw_calibvis)) { // g_recon_integration->setDrawBricks(g_skip_space); } } if (ImGui::CollapsingHeader("Processing Performance")) { if (ImGui::TreeNode("Texture Processing")) { ImGui::SameLine(); ImGui::Text(" %.3f ms", TimerDatabase::instance().duration("1preprocess") / 1000000.0f); ImGui::Columns(2, NULL, false); ImGui::Text("Morphological Filtering"); ImGui::Text("Bilateral Filtering"); ImGui::Text("Boundary Refinement"); ImGui::Text("Normal Computation"); ImGui::Text("Quality Computation"); ImGui::NextColumn(); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("morph") / 1000000.0f); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("bilateral") / 1000000.0f); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("boundary") / 1000000.0f); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("normal") / 1000000.0f); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("quality") / 1000000.0f); ImGui::Columns(1); ImGui::TreePop(); } else { ImGui::SameLine(); ImGui::Text(" %.3f ms", TimerDatabase::instance().duration("1preprocess") / 1000000.0f); } if(g_recons[g_recon_mode].get() == g_recon_integration.get()) { std::uint64_t full = TimerDatabase::instance().duration("3recon") + TimerDatabase::instance().duration("2integrate"); if (ImGui::TreeNode("Reconstruction")) { ImGui::SameLine(); ImGui::Text(" %.3f ms", full / 1000000.0f); ImGui::Columns(2, NULL, false); ImGui::Text("Raymarching"); ImGui::Text("Integration"); ImGui::Text("Colorfilling"); if(g_skip_space) { ImGui::Text("Brickdrawing"); } ImGui::NextColumn(); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("draw") / 1000000.0f); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("2integrate") / 1000000.0f); ImGui::Text("%.3f ms", TimerDatabase::instance().duration("holefill") / 1000000.0f); if(g_skip_space) { ImGui::Text("%.3f ms", TimerDatabase::instance().duration("brickdraw") / 1000000.0f); } ImGui::Columns(1); ImGui::TreePop(); } else { ImGui::SameLine(); ImGui::Text(" %.3f ms", full / 1000000.0f); } } else { ImGui::Text(" Reconstruction"); ImGui::SameLine(); ImGui::Text(" %.3f ms", TimerDatabase::instance().duration("draw") / 1000000.0f); } } ImGui::End(); } for(unsigned i = 0; i < g_gui_texture_settings.size(); ++i) { auto& setting = g_gui_texture_settings[i]; ImGui::SetNextWindowSize(ImVec2(100,100), ImGuiSetCond_FirstUseEver); bool show_tex = true; if (!ImGui::Begin(std::string{"Textures " + std::to_string(i)}.c_str(), &show_tex)) { ImGui::End(); } else { if (ImGui::CollapsingHeader("Kinect", ImGuiTreeNodeFlags_DefaultOpen)) { static std::vector<const char*> listbox_items = {"1", "2", "3", "4"}; ImGui::ListBox("Number", &setting.second, listbox_items.data(), listbox_items.size(), listbox_items.size()); } if (ImGui::CollapsingHeader("Texture Type", ImGuiTreeNodeFlags_DefaultOpen)) { static std::vector<const char*> listbox_items = {"Color", "Depth", "Quality", "Normals", "Silhouette", "Orig Depth", "LAB colors"}; ImGui::ListBox("Type", &setting.first, listbox_items.data(), listbox_items.size(), listbox_items.size()); } TexInfo test = {g_nka->getStartTextureUnit() + setting.first, -setting.second - 1}; ImTextureID cont; std::memcpy(&cont, &test, sizeof(test)); glm::uvec2 res{g_nka->getDepthResolution()}; //float aspect = float(res.x) / res.y; // for rotated texture visualization float aspect = float(res.y) / res.x; float width = ImGui::GetWindowContentRegionWidth(); ImGui::Image(cont, ImVec2(width, width / aspect), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); ImGui::End(); } if (!show_tex) { g_gui_texture_settings.pop_back(); } } // ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); // ImGui::ShowTestWindow(); } void frameStep (){ glfwPollEvents(); update_gui(); draw3d(); if(2 != g_stereo_mode){ ImGui::Render(); } glfwSwapBuffers(g_window); } ////////////////////////////////////////////////////////////////////////////////////////// void update_model_matrix(bool load_ident) { gloost::Point3 speed(0.0,0.0,0.0); glm::fvec2 speed_button1(g_navi.getOffset(0)); glm::fvec2 speed_button2(g_navi.getOffset(1)); float fac = 0.005; speed[0] = speed_button1.x * fac; speed[1] = speed_button1.y * - 1.0 * fac; speed[2] = speed_button2.y * fac; gloost::Matrix camview(g_navi.get(speed)); camview.invert(); glMatrixMode(GL_MODELVIEW); if(load_ident){ glLoadIdentity(); } glMultMatrixf(camview.data()); static double curr_rot = 0.0; const double TAU = 2.0 * 180.0; if(g_animate){ curr_rot += ImGui::GetIO().DeltaTime * 10.0; if (curr_rot >= TAU) curr_rot = 0.0; } glRotatef(curr_rot, 0.0,1.0,0.0); g_navi.resetOffsets(); } void process_textures() { if(g_recon_integration.get() == g_recons.at(g_recon_mode).get()) { g_recon_integration->clearOccupiedBricks(); } g_nka->processTextures(); if(g_recon_integration.get() == g_recons.at(g_recon_mode).get()) { g_recon_integration->updateOccupiedBricks(); } } ////////////////////////////////////////////////////////////////////////////////////////// /// main loop function, render with 3D setup void draw3d(void) { bool update_textures = false; if (g_play) { update_textures = update_textures || g_nka->update(); } if (update_textures) { process_textures(); } // perform integration if(g_recon_integration.get() == g_recons.at(g_recon_mode).get()) { if(update_textures) { g_recon_integration->integrate(); } } glClearColor(g_clear_color[0],g_clear_color[1],g_clear_color[2],g_clear_color[3]); if(g_stereo_mode == 0){ // MONO glViewport(0,0,g_screenWidth, g_screenHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); g_camera.set(); update_model_matrix(); g_recons.at(g_recon_mode)->drawF(); } else if(g_stereo_mode == 1){ // ANAGLYPH STEREO glViewport(0,0,g_screenWidth, g_screenHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); g_stereo_camera->setLeft(); update_model_matrix(false); // g_recon_integration->setColorMaskMode(1); g_recons.at(g_recon_mode)->setColorMaskMode(1); g_recons.at(g_recon_mode)->drawF(); glClear(GL_DEPTH_BUFFER_BIT); g_stereo_camera->setRight(); update_model_matrix(false); // g_recon_integration->setColorMaskMode(2); g_recons.at(g_recon_mode)->setColorMaskMode(2); g_recons.at(g_recon_mode)->drawF(); } else if(g_stereo_mode == 2 && g_fbr){ // SIDE-BY-SIDE STEREO sys::feedback fb = g_fbr->get(); const gloost::Matrix cyclops_mat = glm2gloost(fb.cyclops_mat); const gloost::Matrix screen_mat = glm2gloost(fb.screen_mat); const gloost::Matrix model_mat = glm2gloost(fb.model_mat); g_recon_mode = fb.recon_mode; // currently only works without depth aware color filling if(1 == g_recon_mode){ g_recon_integration->setColorFilling(false); } glViewport(0,0,g_windowWidth, g_windowHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); g_stereo_camera->setCyclopsMatrix(cyclops_mat); g_stereo_camera->setScreenMatrix(screen_mat); glViewport(g_left_pos_x, g_left_pos_y, g_screenWidth, g_screenHeight); g_stereo_camera->setLeft(); glMatrixMode(GL_MODELVIEW); glMultMatrixf(model_mat.data()); // g_recon_integration->setViewportOffset((float) g_left_pos_x, (float) g_left_pos_y); g_recons.at(g_recon_mode)->setViewportOffset((float) g_left_pos_x, (float) g_left_pos_y); g_recons.at(g_recon_mode)->drawF(); glViewport(g_right_pos_x, g_right_pos_y, g_screenWidth, g_screenHeight); g_stereo_camera->setRight(); glMatrixMode(GL_MODELVIEW); glMultMatrixf(model_mat.data()); // g_recon_integration->setViewportOffset((float) g_right_pos_x, (float) g_right_pos_y); g_recons.at(g_recon_mode)->setViewportOffset((float) g_right_pos_x, (float) g_right_pos_y); g_recons.at(g_recon_mode)->drawF(); glViewport(0,0,g_screenWidth, g_screenHeight); } if(0 == g_stereo_mode){ if (g_draw_calibvis) { g_calibvis->draw(); } if(g_draw_frustums) { g_cv->drawFrustums(); } if(g_draw_bricks && g_recon_integration.get() != g_recons.at(g_recon_mode).get()) { g_recon_integration->drawOccupiedBricks(); } // draw black grid on floor for fancy look if(g_draw_grid) { // glPushAttrib(GL_ALL_ATTRIB_BITS); // glColor3f(1.0,1.0,1.0); // glBegin(GL_LINES); // const float lsize = 10.0f; // const float gstep = 0.5f; // for(float s = -lsize; s <= lsize; s += gstep){ // glVertex3f(s, 0.0, -lsize); // glVertex3f(s, 0.0, lsize); // glVertex3f(-lsize, 0.0, s); // glVertex3f( lsize, 0.0, s); // } // glEnd(); // glPopAttrib(); g_bbox.draw(); } if (g_draw_textures) { unsigned num = g_num_texture % 2; TextureBlitter::blit(15 + num, glm::fvec2{g_recon_integration->m_view_inpaint->resolution_full()} / 2.0f); } } glMemoryBarrier(GL_ALL_BARRIER_BITS); } //////////////////////////////////////////////////////////////////////////////// /// this function is triggered when the screen is resized void update_view(GLFWwindow* window, int width, int height){ g_screenWidth = width; g_screenHeight = height; g_aspect = g_screenWidth * 1.0/g_screenHeight; g_camera.setAspect(g_aspect); for (auto& recon : g_recons) { recon->resize(width, height); } g_navi.resize(width, height); } ////////////////////////////////////////////////////////////////////////////////////////// void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if(action != GLFW_RELEASE) return; switch (key){ /// press ESC or q to quit case GLFW_KEY_ESCAPE: case GLFW_KEY_Q: glfwSetWindowShouldClose(g_window, 1); break; case GLFW_KEY_F: g_draw_frustums = !g_draw_frustums; break; case GLFW_KEY_B: g_bilateral = !g_bilateral; g_nka->filterTextures(g_bilateral); break; case GLFW_KEY_D: g_processed = !g_processed; g_nka->useProcessedDepths(g_processed); break; case GLFW_KEY_N: g_refine = !g_refine; g_nka->refineBoundary(g_refine); break; case GLFW_KEY_G: g_draw_grid = !g_draw_grid; break; case GLFW_KEY_A: g_animate = !g_animate; break; case GLFW_KEY_O: g_draw_bricks = !g_draw_bricks; g_recon_integration->setDrawBricks(g_draw_bricks); break; case GLFW_KEY_Y: g_num_texture = (g_num_texture + 1) % g_calib_files->num(); break; case GLFW_KEY_U: g_texture_type = (g_texture_type + 1) % 7; break; case GLFW_KEY_T: g_draw_textures = !g_draw_textures; break; case GLFW_KEY_S: for (auto& recon : g_recons) { recon->reload(); } globjects::File::reloadAll(); process_textures(); g_recon_integration->integrate(); break; case GLFW_KEY_P: g_play = !g_play; break; case GLFW_KEY_1: g_shading_buffer_data.mode = (g_shading_buffer_data.mode + 1) % 4; g_buffer_shading->setSubData(0, sizeof(shading_data_t), &g_shading_buffer_data); break; case GLFW_KEY_V: g_draw_calibvis = !g_draw_calibvis; break; case GLFW_KEY_C: g_num_kinect = (g_num_kinect+ 1) % g_calib_files->num(); g_calibvis->setActiveKinect(g_num_kinect); break; case GLFW_KEY_PAGE_UP: g_recon_mode = (g_recon_mode + 1) % g_recons.size(); break; case GLFW_KEY_PAGE_DOWN: g_recon_mode = (g_recon_mode + g_recons.size() - 1) % g_recons.size(); break; default: break; } } ////////////////////////////////////////////////////////////////////////////////////////// void mouse_callback(GLFWwindow* window, double xpos, double ypos) { g_navi.motion(xpos, ypos); } ////////////////////////////////////////////////////////////////////////////////////////// void click_callback(GLFWwindow* window, int button, int action, int mods){ if(ImGui::GetIO().WantCaptureMouse) return; double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); int mouse_h = xpos; int mouse_v = ypos; g_navi.mouse(button, action, mouse_h, mouse_v); } //////////////////////////////////////////////////////////////////////////////// static void error_callback(int error, const char* description) { fprintf(stderr, "Error %d: %s\n", error, description); } void quit(int status) { if(g_loaded_conf) { time_t t = time(0); // get time now struct tm * now = localtime( & t ); std::stringstream file_name; file_name << g_conf_file.substr(0, g_conf_file.length() - 5) << "," << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << ',' << now->tm_hour << '-' << now->tm_min << ".csv"; TimerDatabase::instance().writeMean(file_name.str()); TimerDatabase::instance().writeMin(file_name.str()); TimerDatabase::instance().writeMax(file_name.str()); } //free globjects globjects::detachAllObjects(); ImGui_ImplGlfwGLB_Shutdown(); // free glfw resources glfwDestroyWindow(g_window); glfwTerminate(); if(g_stereo_mode > 0){ delete g_stereo_camera; } std::exit(status); } int main(int argc, char *argv[]) { CMDParser p("kinect_surface ..."); p.addOpt("s",2,"screensize", "set screen size in meter"); p.addOpt("d",2,"displaysize", "set display size in pixel"); p.addOpt("w",2,"windowsize", "set window size in pixel for stereomode side-by-side"); p.addOpt("l",2,"leftpos", "set the position of the left viewport (upper left corner) in pixel for stereomode side-by-side"); p.addOpt("r",2,"rightpos", "set the position of the right viewport (upper left corner) in pixel for stereomode side-by-side"); p.addOpt("m",1,"stereomode", "set stereo mode 0: none, 1: anaglyph, 2: side-by-side (default: 0)"); p.addOpt("c",4,"clearcolor", "set clear color (default: 0.0 0.0 0.0 0.0)"); p.addOpt("f",1,"feedbacksocket", "set socket for feedback receiver (e.g. 127.0.0.1:9000)"); p.addOpt("p",1,"serversocket", "set server socket for input stream : default " + g_server_socket); p.init(argc,argv); if(p.isOptSet("p")){ g_server_socket = p.getOptsString("p")[0]; } std::cout << "using server socket for input stream: " << g_server_socket << std::endl; if(p.isOptSet("s")){ g_screenWidthReal = p.getOptsFloat("s")[0]; g_screenHeightReal = p.getOptsFloat("s")[1]; } if(p.isOptSet("d")){ g_screenWidth = p.getOptsInt("d")[0]; g_screenHeight = p.getOptsInt("d")[1]; } if(p.isOptSet("w")){ g_windowWidth = p.getOptsInt("w")[0]; g_windowHeight = p.getOptsInt("w")[1]; } if(p.isOptSet("l")){ g_left_pos_x = p.getOptsInt("l")[0]; g_left_pos_y = p.getOptsInt("l")[1]; } if(p.isOptSet("r")){ g_right_pos_x = p.getOptsInt("r")[0]; g_right_pos_y = p.getOptsInt("r")[1]; } if(p.isOptSet("m")){ g_stereo_mode = p.getOptsInt("m")[0]; } if(p.isOptSet("c")){ g_clear_color[0] = p.getOptsFloat("c")[0]; g_clear_color[1] = p.getOptsFloat("c")[1]; g_clear_color[2] = p.getOptsFloat("c")[2]; g_clear_color[3] = p.getOptsFloat("c")[3]; } if(p.isOptSet("f")){ std::string client_socket = p.getOptsString("f")[0].c_str(); init_fbr(client_socket.c_str()); } if((1 == g_stereo_mode) || (2 == g_stereo_mode)){ init_stereo_camera(); } // load global variables init_config(p.getArgs()); // Setup window glfwSetErrorCallback(error_callback); if(!glfwInit()) { std::exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif if((0 == g_stereo_mode) || (1 == g_stereo_mode)){ g_window = glfwCreateWindow(g_screenWidth, g_screenHeight, "Kinect Reconstruction", NULL, NULL); } else if(2 == g_stereo_mode){ g_window = glfwCreateWindow(g_windowWidth, g_windowHeight, "Kinect Reconstruction", NULL, NULL); } if(!g_window) { glfwTerminate(); std::exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_window); // Setup ImGui binding ImGui_ImplGlfwGLB_Init(g_window, true); // disable vsync glfwSwapInterval(0); glfwSetKeyCallback(g_window, key_callback); glfwSetCursorPosCallback(g_window, mouse_callback); glfwSetMouseButtonCallback(g_window, click_callback); if(0 == g_stereo_mode){ glfwSetFramebufferSizeCallback(g_window, update_view); } // allow unlimited mouse movement // Initialize globjects (internally initializes glbinding, and registers the current context) globjects::init(); watch_gl_errors(g_watch_errors); // set some gl states glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // load and intialize objects init(p.getArgs()); // update_view(g_window, g_screenWidth, g_screenHeight); g_aspect = g_screenWidth * 1.0/g_screenHeight; g_camera.setAspect(g_aspect); g_navi.resize(g_screenWidth, g_screenHeight); g_navi.setZoom(g_zoom); for (auto& recon : g_recons) { recon->resize(g_screenWidth, g_screenHeight); } //start of rendering auto time_start = std::chrono::high_resolution_clock::now(); while (!glfwWindowShouldClose(g_window)) { frameStep(); // keep track fo time if config was loaded if(g_loaded_conf) { unsigned time_in_s = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - time_start).count(); if(time_in_s >= g_time_limit) { quit(EXIT_SUCCESS); } } } quit(EXIT_SUCCESS); } void watch_gl_errors(bool activate) { if(activate) { // add callback after each function call glbinding::setCallbackMaskExcept(glbinding::CallbackMask::After | glbinding::CallbackMask::ParametersAndReturnValue, {"glGetError", "glVertex3f", "glVertex2f", "glBegin", "glColor3f"}); glbinding::setAfterCallback( [](glbinding::FunctionCall const& call) { GLenum error = glGetError(); if (error != GL_NO_ERROR) { // print name std::cerr << "OpenGL Error: " << call.function->name() << "("; // parameters for (unsigned i = 0; i < call.parameters.size(); ++i) { std::cerr << call.parameters[i]->asString(); if (i < call.parameters.size() - 1) std::cerr << ", "; } std::cerr << ")"; // return value if(call.returnValue) { std::cerr << " -> " << call.returnValue->asString(); } // error std::cerr << " - " << glbinding::Meta::getString(error) << std::endl; throw std::exception{}; } } ); } else { glbinding::setCallbackMask(glbinding::CallbackMask::None); } }
32.585714
189
0.634809
[ "render", "vector", "3d" ]
fdfd954478533a946deea702af45c388b3ed62a6
26,636
cc
C++
src/nnet3/nnet-normalize-component.cc
LanceaKing/kaldi
eb205a83f08fb8056ba1deb03c505ec8b722d4d9
[ "Apache-2.0" ]
39
2021-06-16T11:38:57.000Z
2022-03-24T01:33:56.000Z
src/nnet3/nnet-normalize-component.cc
LanceaKing/kaldi
eb205a83f08fb8056ba1deb03c505ec8b722d4d9
[ "Apache-2.0" ]
8
2017-09-06T00:12:00.000Z
2019-03-22T08:03:19.000Z
src/nnet3/nnet-normalize-component.cc
LanceaKing/kaldi
eb205a83f08fb8056ba1deb03c505ec8b722d4d9
[ "Apache-2.0" ]
29
2020-01-03T22:28:27.000Z
2022-03-30T23:00:27.000Z
// nnet3/nnet-normalize-component.cc // Copyright 2015-2017 Johns Hopkins University (author: Daniel Povey) // 2015 Guoguo Chen // 2015 Daniel Galvez // See ../../COPYING for clarification regarding multiple authors // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <iterator> #include <sstream> #include <algorithm> #include <iomanip> #include "nnet3/nnet-normalize-component.h" #include "nnet3/nnet-parse.h" #include "cudamatrix/cu-math.h" namespace kaldi { namespace nnet3 { const BaseFloat NormalizeComponent::kSquaredNormFloor = pow(2.0, NormalizeComponent::kExpSquaredNormFloor); NormalizeComponent::NormalizeComponent(const NormalizeComponent &other): input_dim_(other.input_dim_), block_dim_(other.block_dim_), target_rms_(other.target_rms_), add_log_stddev_(other.add_log_stddev_) { } void NormalizeComponent::InitFromConfig(ConfigLine *cfl) { input_dim_ = 0; add_log_stddev_ = false; target_rms_ = 1.0; bool ok = cfl->GetValue("dim", &input_dim_) || cfl->GetValue("input-dim", &input_dim_); block_dim_ = input_dim_; cfl->GetValue("block-dim", &block_dim_); cfl->GetValue("target-rms", &target_rms_); cfl->GetValue("add-log-stddev", &add_log_stddev_); if (!ok || cfl->HasUnusedValues() || input_dim_ <= 0 || target_rms_ <= 0.0 || block_dim_ <= 0 || input_dim_ % block_dim_ != 0) KALDI_ERR << "Invalid initializer for layer of type " << Type() << ": \"" << cfl->WholeLine() << "\""; } void NormalizeComponent::Read(std::istream &is, bool binary) { std::string token; ReadToken(is, binary, &token); if (token == "<NormalizeComponent>") { ReadToken(is, binary, &token); } KALDI_ASSERT(token == "<Dim>" || token == "<InputDim>"); ReadBasicType(is, binary, &input_dim_); // Read dimension. ReadToken(is, binary, &token); if (token == "<BlockDim>") { ReadBasicType(is, binary, &block_dim_); ReadToken(is, binary, &token); } else { block_dim_ = input_dim_; } // read target_rms_ if it is available. if (token == "<TargetRms>") { ReadBasicType(is, binary, &target_rms_); ReadToken(is, binary, &token); } // Read add_log_stddev_ token, if it is available. if (token == "<AddLogStddev>") { ReadBasicType(is, binary, &add_log_stddev_); ReadToken(is, binary, &token); } else { add_log_stddev_ = false; } if (token == "<ValueAvg>") { // back-compatibility code. CuVector<double> temp; temp.Read(is, binary); ExpectToken(is, binary, "<DerivAvg>"); temp.Read(is, binary); ExpectToken(is, binary, "<Count>"); double count; ReadBasicType(is, binary, &count); ReadToken(is, binary, &token); } KALDI_ASSERT(token == "</NormalizeComponent>"); } void NormalizeComponent::Write(std::ostream &os, bool binary) const { WriteToken(os, binary, "<NormalizeComponent>"); WriteToken(os, binary, "<InputDim>"); WriteBasicType(os, binary, input_dim_); if (block_dim_ != input_dim_) { WriteToken(os, binary, "<BlockDim>"); WriteBasicType(os, binary, block_dim_); } WriteToken(os, binary, "<TargetRms>"); WriteBasicType(os, binary, target_rms_); WriteToken(os, binary, "<AddLogStddev>"); WriteBasicType(os, binary, add_log_stddev_); WriteToken(os, binary, "</NormalizeComponent>"); } std::string NormalizeComponent::Info() const { std::ostringstream stream; stream << Type() << ", input-dim=" << InputDim() << ", output-dim=" << OutputDim() << ", target-rms=" << target_rms_ << ", add-log-stddev=" << std::boolalpha << add_log_stddev_; if (block_dim_ != input_dim_) stream << ", block-dim=" << block_dim_; return stream.str(); } // The output y_i = scale * x_i, // and we want to RMS value of the y_i to equal target_rms, // so y^t y = D * target_rms^2 (if y is one row of the input). // we need to have scale = 1.0 / sqrt(x^t x / (D * target_rms^2)). // there is also flooring involved, to avoid division-by-zero // problems. It's important for the backprop, that the floor's // square root is exactly representable as float. // If add_log_stddev_ is true, log(max(epsi, sqrt(x^t x / D))) // is an extra dimension of the output. void* NormalizeComponent::Propagate(const ComponentPrecomputedIndexes *indexes, const CuMatrixBase<BaseFloat> &in, CuMatrixBase<BaseFloat> *out) const { KALDI_ASSERT(in.NumCols() == InputDim() && out->NumCols() == OutputDim() && in.NumRows() == out->NumRows()); if (block_dim_ != input_dim_) { int32 num_blocks = input_dim_ / block_dim_, new_num_rows = in.NumRows() * num_blocks, output_block_dim = block_dim_ + (add_log_stddev_ ? 1 : 0); KALDI_ASSERT(in.Stride() == in.NumCols() && out->Stride() == out->NumCols()); CuSubMatrix<BaseFloat> in_reshaped(in.Data(), new_num_rows, block_dim_, block_dim_), out_reshaped(out->Data(), new_num_rows, output_block_dim, output_block_dim); cu::NormalizePerRow(in_reshaped, target_rms_, add_log_stddev_, &out_reshaped); } else { cu::NormalizePerRow(in, target_rms_, add_log_stddev_, out); } return NULL; } /* A note on the derivative of NormalizeComponent... let both row_in and row_out be vectors of dimension D. Let p = row_in^T row_in / (D * target_rms^2), and let f = 1.0 / sqrt(max(kSquaredNormFloor, p)), and we compute row_out as: row_out = f row_in. Suppose we have a quantity deriv_out which is the derivative of the objective function w.r.t. row_out. We want to compute deriv_in which is the derivative of the objective function w.r.t. row_in. Let the objective function be F. One term is obvious: we have deriv_in = f deriv_out + .... next we have to take into account the derivative that gets back-propagated through f. Obviously, dF/df = deriv_out^T row_in. And df/dp = (p <= kSquaredNormFloor ? 0.0 : -0.5 p^{-1.5}) = (f == 1.0 / sqrt(kSquaredNormFloor) ? 0.0 : -0.5 f^3), and dp/d(row_in) = 2/(D * target_rms^2) row_in. [it's vector_valued]. So this term in dF/d(row_in) equals: dF/df df/dp dp/d(row_in) = 2/(D * target_rms^2) (f == 1.0 / sqrt(kSquaredNormFloor) ? 0.0 : -0.5 f^3) (deriv_out^T row_in) row_in So deriv_in = f deriv_out + (f == 1.0 ? 0.0 : -f^3 / (D * target_rms^2) ) (deriv_out^T row_in) row_in if add_log_stddev_ true, the deriv_in has another term as dF/dx_i = dF/df . df/dx_i => df/dx_i = x_i/(x^T x) */ void NormalizeComponent::Backprop(const std::string &debug_info, const ComponentPrecomputedIndexes *indexes, const CuMatrixBase<BaseFloat> &in_value, const CuMatrixBase<BaseFloat> &, // out_value const CuMatrixBase<BaseFloat> &out_deriv, void *memo, Component *to_update, CuMatrixBase<BaseFloat> *in_deriv) const { NVTX_RANGE("NormalizeComponent::Backprop"); if (!in_deriv) return; if (block_dim_ != input_dim_) { int32 num_blocks = input_dim_ / block_dim_, new_num_rows = in_value.NumRows() * num_blocks, output_block_dim = block_dim_ + (add_log_stddev_ ? 1 : 0); KALDI_ASSERT(in_value.Stride() == in_value.NumCols() && out_deriv.Stride() == out_deriv.NumCols() && in_deriv->Stride() == in_deriv->NumCols()); CuSubMatrix<BaseFloat> in_value_reshaped(in_value.Data(), new_num_rows, block_dim_, block_dim_), out_deriv_reshaped(out_deriv.Data(), new_num_rows, output_block_dim, output_block_dim), in_deriv_reshaped(in_deriv->Data(), new_num_rows, block_dim_, block_dim_); cu::DiffNormalizePerRow(in_value_reshaped, out_deriv_reshaped, target_rms_, add_log_stddev_, &in_deriv_reshaped); } else { cu::DiffNormalizePerRow(in_value, out_deriv, target_rms_, add_log_stddev_, in_deriv); } } void BatchNormComponent::ComputeDerived() { if (!test_mode_) { offset_.Resize(0); scale_.Resize(0); return; } if (count_ == 0.0) { KALDI_WARN << "Test-mode is set but there is no data count. " "Creating random counts. This is NOT A PROBLEM if the message " "appears in unit-tests or in compute_prob_*.0.log. If you see this " "elsewhere, something is very wrong."; count_ = 1.0; stats_sum_.SetRandn(); stats_sumsq_.SetRandn(); stats_sumsq_.AddVecVec(1.0, stats_sum_, stats_sum_, 1.0); } offset_.Resize(block_dim_); scale_.Resize(block_dim_); offset_.CopyFromVec(stats_sum_); offset_.Scale(-1.0 / count_); // now offset_ is -mean. scale_.CopyFromVec(stats_sumsq_); scale_.Scale(1.0 / count_); scale_.AddVecVec(-1.0, offset_, offset_, 1.0); // now scale_ is variance. // Mathematically the ApplyFloor statement should be a no-op; this is in case // of numerical roundoff. scale_.ApplyFloor(0.0); scale_.Add(epsilon_); BaseFloat power = -0.5; scale_.ApplyPow(power); // now scale_ = min(variance, epsilon)^power // next, multiply by the target RMS (normally 1.0). scale_.Scale(target_rms_); offset_.MulElements(scale_); // now offset_ is -(scale*mean). } void BatchNormComponent::SetTestMode(bool test_mode) { test_mode_ = test_mode; ComputeDerived(); } void BatchNormComponent::Check() const { KALDI_ASSERT(dim_ > 0 && block_dim_ > 0 && dim_ % block_dim_ == 0 && epsilon_ > 0.0 && target_rms_ > 0.0); } BatchNormComponent::BatchNormComponent(const BatchNormComponent &other): dim_(other.dim_), block_dim_(other.block_dim_), epsilon_(other.epsilon_), target_rms_(other.target_rms_), test_mode_(other.test_mode_), count_(other.count_), stats_sum_(other.stats_sum_), stats_sumsq_(other.stats_sumsq_) { ComputeDerived(); Check(); } std::string BatchNormComponent::Info() const { std::ostringstream stream; stream << Type() << ", dim=" << dim_ << ", block-dim=" << block_dim_ << ", epsilon=" << epsilon_ << ", target-rms=" << target_rms_ << ", count=" << count_ << ", test-mode=" << (test_mode_ ? "true" : "false"); if (count_ > 0) { Vector<BaseFloat> mean(stats_sum_), var(stats_sumsq_); mean.Scale(1.0 / count_); var.Scale(1.0 / count_); // subtract mean^2 from var. var.AddVecVec(-1.0, mean, mean, 1.0); var.ApplyFloor(0.0); var.ApplyPow(0.5); // make it the stddev. stream << ", data-mean=" << SummarizeVector(mean) << ", data-stddev=" << SummarizeVector(var); } return stream.str(); } void BatchNormComponent::InitFromConfig(ConfigLine *cfl) { dim_ = -1; block_dim_ = -1; epsilon_ = 1.0e-03; target_rms_ = 1.0; test_mode_ = false; bool ok = cfl->GetValue("dim", &dim_); cfl->GetValue("block-dim", &block_dim_); cfl->GetValue("epsilon", &epsilon_); cfl->GetValue("target-rms", &target_rms_); cfl->GetValue("test-mode", &test_mode_); if (!ok || dim_ <= 0) { KALDI_ERR << "BatchNormComponent must have 'dim' specified, and > 0"; } if (block_dim_ == -1) block_dim_ = dim_; if (!(block_dim_ > 0 && dim_ % block_dim_ == 0 && epsilon_ > 0 && target_rms_ > 0)) KALDI_ERR << "Invalid configuration in BatchNormComponent."; if (cfl->HasUnusedValues()) KALDI_ERR << "Could not process these elements in initializer: " << cfl->UnusedValues(); count_ = 0; stats_sum_.Resize(block_dim_); stats_sumsq_.Resize(block_dim_); if (test_mode_) { ComputeDerived(); } } /* BATCHNORM_MATH This comment describes the equations involved in batch normalization, and derives the forward and back-propagation. This is all dimension-by-dimension, so we just imagine the inputs are scalars x(i), for i=0 .. n-1. FORWARD PASS: Let 'power' be a constant, equal to -0.5 for regular batch-norm. To simplify the math we (conceptually, not physically) do the normalization in two stages: first mean, then variance, so we have x(i) -> y(i) -> z(i). The name 'rscale' means 'raw scale', meaning the scale before including target-rms. Later we'll define 'scale = target-rms * rscale', to make some of the actual computations slightly more efficient. Define: mean = 1/I * sum_i x(i) y(i) = x(i) - mean var = 1/I \sum_i y(i)^2 rscale = sqrt(var + epsilon)^power <---- For regular batchnorm, power == -0.5. z(i) = target-rms * rscale * y(i) Most of the rest of this comment derives how to compute the derivatives. If you just want the formulas, please skip to the string 'BACKWARD PASS' below. We'll use a notation where an apostrophe on something means (the derivative of the objective function w.r.t. that thing), so y'(i) is df/dy(i), and so on. We are given y'(i). Propagating the derivatives backward: rscale' = (sum_i y(i) z'(i)) * target-rms = (sum_i z(i) z'(i)) / rscale [ note: d(rscale)/d(var) = power * (var + epsilon)^{power - 1} = power * rscale^{(power-1)/power} ] var' = rscale' * power * rscale^{(power-1)/power} = power * (\sum_i z'(i) z(i)) * rscale^{(power-1)/power - 1} = power * (\sum_i z'(i) z(i)) * rscale^{-1/power} [note: the following formula is of the form "direct term" + "indirect term"] y'(i) = z'(i) * target-rms * rscale + 2/I y(i) var' Now, the above is inconvenient because it contains y(i) which is an intermediate quantity. We reformulate in terms of z(i), using y(i) = z(i) / (target-rms * rscale), so: defining var_deriv_mod = 2/I * var' / (target-rms * rscale) = 2/I * power/target-rms * (\sum_i z'(i) z(i)) * rscale^{-(1+power)/power} we have: y'(i) = z'(i) * target-rms * rscale + z(i) var_deriv_mod Now, mean' = \sum_i y'(i) = (target-rms * rscale * \sum_i z'(i)) + (var_deriv_mod \sum_i z(i)) [... and the 2nd term above is zero when summed over i, because \sum_i z(i) is zero, ...] = target-rms * rscale * \sum_i z(i) and: x'(i) = z'(i) * target-rms * rscale + z(i) var_deriv_mod - 1/I mean' = z'(i) * target-rms * rscale + z(i) var_deriv_mod - 1/I * target-rms * rscale * \sum_i z'(i) = target-rms * rscale * (z'(i) - 1/I * \sum_i z'(i)) + z(i) var_deriv_mod It will simplify the code if we define: scale = target-rms * rscale. This way, we can write as follows: BACKWARD PASS (recap): var_deriv_mod = 2 * power * target-rms^{1/power} * (1/I \sum_i z'(i) z(i)) * scale^{-(1+power)/power} .. which for power = -0.5, simplifies to: var_deriv_mod = -1.0 / (target-rms^2) * (1/I \sum_i z'(i) z(i)) * scale x'(i) = scale * (z'(i) - 1/I * \sum_i z'(i)) + z(i) var_deriv_mod */ void* BatchNormComponent::Propagate(const ComponentPrecomputedIndexes *indexes, const CuMatrixBase<BaseFloat> &in, CuMatrixBase<BaseFloat> *out) const { KALDI_ASSERT(SameDim(in, *out) && (in.NumCols() == dim_ || in.NumCols() == block_dim_)); if (in.NumCols() != block_dim_) { // if block_dim_ != dim_, we recurse; this helps keep the main code // simple. KALDI_ASSERT(in.Stride() == in.NumCols() && out->Stride() == out->NumCols()); int32 ratio = dim_ / block_dim_, orig_rows = in.NumRows(), orig_cols = in.NumCols(), new_rows = orig_rows * ratio, new_cols = orig_cols / ratio; CuSubMatrix<BaseFloat> in_reshaped(in.Data(), new_rows, new_cols, new_cols), out_reshaped(out->Data(), new_rows, new_cols, new_cols); return Propagate(indexes, in_reshaped, &out_reshaped); } // From this point, we can assume that the num-cols of 'in' and 'out' // equals block_dim_. if (!test_mode_) { // search in the comment above for FORWARD PASS to see what is being // implemented here. // if this takes too much time due to multiple different CUDA calls, // we'll consider making a single kernel for some of it. Memo *memo = new Memo; int32 num_frames = in.NumRows(), dim = block_dim_; memo->num_frames = num_frames; memo->mean_uvar_scale.Resize(5, dim); CuSubVector<BaseFloat> mean(memo->mean_uvar_scale, 0), uvar(memo->mean_uvar_scale, 1), scale(memo->mean_uvar_scale, 2); mean.AddRowSumMat(1.0 / num_frames, in, 0.0); uvar.AddDiagMat2(1.0 / num_frames, in, kTrans, 0.0); scale.CopyFromVec(uvar); // by applying this scale at this point, we save a multiply later on. BaseFloat var_scale = 1.0 / (target_rms_ * target_rms_); scale.AddVecVec(-var_scale, mean, mean, var_scale); // at this point, 'scale' contains just the variance (times target-rms^{-2}). scale.ApplyFloor(0.0); scale.Add(var_scale * epsilon_); // Now 'scale' contains the variance floored to zero and then with epsilon // added [both times 1/target-rms^2]. scale.ApplyPow(-0.5); // now 'scale' is the actual scale we'll use. // the next command will do no work if out == in, for in-place propagation. out->CopyFromMat(in); out->AddVecToRows(-1.0, mean, 1.0); out->MulColsVec(scale); return static_cast<void*>(memo); } else { if (offset_.Dim() != block_dim_) { if (count_ == 0) KALDI_ERR << "Test mode set in BatchNormComponent, but no stats."; else // why was ComputeDerived() not called? KALDI_ERR << "Code error in BatchNormComponent"; } out->CopyFromMat(in); out->MulColsVec(scale_); out->AddVecToRows(1.0, offset_, 1.0); return NULL; } } void BatchNormComponent::Backprop( const std::string &debug_info, const ComponentPrecomputedIndexes *indexes, const CuMatrixBase<BaseFloat> &in_value, // unused const CuMatrixBase<BaseFloat> &out_value, const CuMatrixBase<BaseFloat> &out_deriv, void *memo_in, Component *to_update, // unused CuMatrixBase<BaseFloat> *in_deriv) const { NVTX_RANGE("BatchNormComponent::Backprop"); KALDI_ASSERT(SameDim(out_value, out_deriv) && SameDim(out_value, *in_deriv) && (out_value.NumCols() == dim_ || out_value.NumCols() == block_dim_)); if (out_value.NumCols() != block_dim_) { // if block_dim_ != dim_, we recurse; this helps keep the main code // simple. KALDI_ASSERT(out_value.Stride() == out_value.NumCols() && out_deriv.Stride() == out_deriv.NumCols() && in_deriv->Stride() == in_deriv->NumCols()); int32 ratio = dim_ / block_dim_, orig_rows = out_value.NumRows(), orig_cols = out_value.NumCols(), new_rows = orig_rows * ratio, new_cols = orig_cols / ratio; CuSubMatrix<BaseFloat> out_value_reshaped(out_value.Data(), new_rows, new_cols, new_cols), out_deriv_reshaped(out_deriv.Data(), new_rows, new_cols, new_cols), in_deriv_reshaped(in_deriv->Data(), new_rows, new_cols, new_cols); // we'll never use in_value, so pass it in unchanged. Backprop(debug_info, indexes, in_value, out_value_reshaped, out_deriv_reshaped, memo_in, to_update, &in_deriv_reshaped); return; } Memo *memo = static_cast<Memo*>(memo_in); if (!test_mode_) { // search above for BACKWARD PASS for a comment describing the math. KALDI_ASSERT(memo != NULL && "memo not passed into backprop"); int32 num_frames = memo->num_frames; KALDI_ASSERT(out_value.NumRows() == num_frames); CuSubVector<BaseFloat> scale(memo->mean_uvar_scale, 2), var_deriv_mod(memo->mean_uvar_scale, 3), temp(memo->mean_uvar_scale, 4); // var_deriv_mod is going to contain: // 2 * power * target-rms^{1/power} * (1/I \sum_i z'(i) z(i)) * scale^{-(1+power)/power} // which for power = -0.5 simplifies to: // -1.0 / (target_rms * target_rms). // but for now we don't have the power of 'scale', we'll add that later. BaseFloat coeff = -1.0 / (target_rms_ * target_rms_ * num_frames); var_deriv_mod.AddDiagMatMat(coeff, out_value, kTrans, out_deriv, kNoTrans, 0.0); var_deriv_mod.MulElements(scale); temp.AddRowSumMat(-1.0 / num_frames, out_deriv, 0.0); // the following statement does no work if in_deriv and out_deriv are the // same matrix. in_deriv->CopyFromMat(out_deriv); in_deriv->AddVecToRows(1.0, temp); // At this point, *in_deriv contains // (z'(i) - 1/I * \sum_i z'(i)) in_deriv->MulColsVec(scale); // At this point, *in_deriv contains // scale * (z'(i) - 1/I * \sum_i z'(i)) in_deriv->AddMatDiagVec(1.0, out_value, kNoTrans, var_deriv_mod, 1.0); // At this point, *in_deriv contains what we described in the comment // starting BATCHNORM_MATH as: // x'(i) = scale * (z'(i) - 1/I * \sum_i z'(i)) + z(i) var_deriv_mod } else { KALDI_ASSERT(offset_.Dim() == block_dim_); // the next call does no work if they point to the same memory. in_deriv->CopyFromMat(out_deriv); in_deriv->MulColsVec(scale_); } } void BatchNormComponent::StoreStats( const CuMatrixBase<BaseFloat> &in_value, const CuMatrixBase<BaseFloat> &out_value, void *memo_in) { // in test mode this component does not store stats, it doesn't provide the // kStoresStats flag. KALDI_ASSERT(!test_mode_); KALDI_ASSERT(out_value.NumCols() == dim_ || out_value.NumCols() == block_dim_); if (out_value.NumCols() != block_dim_) { // if block_dim_ != dim_, we recurse; this helps keep the main code // simple. KALDI_ASSERT(out_value.Stride() == out_value.NumCols()); int32 ratio = dim_ / block_dim_, orig_rows = out_value.NumRows(), orig_cols = out_value.NumCols(), new_rows = orig_rows * ratio, new_cols = orig_cols / ratio; CuSubMatrix<BaseFloat> out_value_reshaped(out_value.Data(), new_rows, new_cols, new_cols); // we'll never use in_value, so just pass it in unchanged. StoreStats(in_value, out_value_reshaped, memo_in); return; } Memo *memo = static_cast<Memo*>(memo_in); KALDI_ASSERT(out_value.NumRows() == memo->num_frames); CuSubVector<BaseFloat> mean(memo->mean_uvar_scale, 0), uvar(memo->mean_uvar_scale, 1); KALDI_ASSERT(mean.Dim() == block_dim_ && memo->num_frames > 0); BaseFloat num_frames = memo->num_frames; if (stats_sum_.Dim() != block_dim_) { stats_sum_.Resize(block_dim_); stats_sumsq_.Resize(block_dim_); KALDI_ASSERT(count_ == 0); } count_ += num_frames; stats_sum_.AddVec(num_frames, mean, 1.0); stats_sumsq_.AddVec(num_frames, uvar, 1.0); } void BatchNormComponent::Read(std::istream &is, bool binary) { ExpectOneOrTwoTokens(is, binary, "<BatchNormComponent>", "<Dim>"); ReadBasicType(is, binary, &dim_); ExpectToken(is, binary, "<BlockDim>"); ReadBasicType(is, binary, &block_dim_); ExpectToken(is, binary, "<Epsilon>"); ReadBasicType(is, binary, &epsilon_); ExpectToken(is, binary, "<TargetRms>"); ReadBasicType(is, binary, &target_rms_); ExpectToken(is, binary, "<TestMode>"); ReadBasicType(is, binary, &test_mode_); ExpectToken(is, binary, "<Count>"); ReadBasicType(is, binary, &count_); ExpectToken(is, binary, "<StatsMean>"); stats_sum_.Read(is, binary); ExpectToken(is, binary, "<StatsVar>"); stats_sumsq_.Read(is, binary); stats_sumsq_.AddVecVec(1.0, stats_sum_, stats_sum_, 1.0); stats_sum_.Scale(count_); stats_sumsq_.Scale(count_); ExpectToken(is, binary, "</BatchNormComponent>"); ComputeDerived(); Check(); } void BatchNormComponent::Write(std::ostream &os, bool binary) const { Check(); WriteToken(os, binary, "<BatchNormComponent>"); WriteToken(os, binary, "<Dim>"); WriteBasicType(os, binary, dim_); WriteToken(os, binary, "<BlockDim>"); WriteBasicType(os, binary, block_dim_); WriteToken(os, binary, "<Epsilon>"); WriteBasicType(os, binary, epsilon_); WriteToken(os, binary, "<TargetRms>"); WriteBasicType(os, binary, target_rms_); WriteToken(os, binary, "<TestMode>"); WriteBasicType(os, binary, test_mode_); WriteToken(os, binary, "<Count>"); WriteBasicType(os, binary, count_); CuVector<BaseFloat> mean(stats_sum_), var(stats_sumsq_); if (count_ != 0) { mean.Scale(1.0 / count_); var.Scale(1.0 / count_); var.AddVecVec(-1.0, mean, mean, 1.0); } WriteToken(os, binary, "<StatsMean>"); mean.Write(os, binary); WriteToken(os, binary, "<StatsVar>"); var.Write(os, binary); WriteToken(os, binary, "</BatchNormComponent>"); } void BatchNormComponent::Scale(BaseFloat scale) { if (scale == 0) { count_ = 0.0; stats_sum_.SetZero(); stats_sumsq_.SetZero(); } else { count_ *= scale; stats_sum_.Scale(scale); stats_sumsq_.Scale(scale); } } void BatchNormComponent::Add(BaseFloat alpha, const Component &other_in) { const BatchNormComponent *other = dynamic_cast<const BatchNormComponent*>(&other_in); count_ += alpha * other->count_; stats_sum_.AddVec(alpha, other->stats_sum_); stats_sumsq_.AddVec(alpha, other->stats_sumsq_); // this operation might change offset_ and scale_, so we recompute them // in this instance (but not in Scale()). ComputeDerived(); } void BatchNormComponent::ZeroStats() { // We only zero the stats if we're not in test mode. In test mode, this would // be dangerous as the stats are the source for the transform, and zeroing // them and then calling ComputeDerived() again would remove the transform // parameters (offset_ and scale_). if (!test_mode_) { count_ = 0.0; stats_sum_.SetZero(); stats_sumsq_.SetZero(); } } } // namespace nnet3 } // namespace kaldi
38.998536
137
0.643077
[ "vector", "transform" ]
fdff233843220cdda444bca5ddc7207afc9c4f49
4,999
cpp
C++
src/Cube.cpp
THOSE-EYES/MeshEditor
6a58460a3ddfeba5d372aa92cd120b0c2a108c35
[ "Apache-2.0" ]
null
null
null
src/Cube.cpp
THOSE-EYES/MeshEditor
6a58460a3ddfeba5d372aa92cd120b0c2a108c35
[ "Apache-2.0" ]
null
null
null
src/Cube.cpp
THOSE-EYES/MeshEditor
6a58460a3ddfeba5d372aa92cd120b0c2a108c35
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Illia Shvarov * * 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 "Cube.hpp" const string Cube::getName() const{ string name = "Cube"; return name; } uint8_t Cube::execute(const map<string, string>& args) { // Parse the arguments parse(args); // Split the object STLParser parser = STLParser(); const Triangles* triangles = createTriangles(); parser.write(triangles, filepath); return 0; } uint8_t Cube::parse(const map<string, string>& args) { string key, value; // Temporary values of map iteration size_t position; // Temporary variable for storing a position inside of a string vector<size_t> positions; // Array of positions // Check arguments size if (args.size() < MIN_ARGS) std::exit(LESS_ARGS_ERR_CODE); for (pair<string, string> pair : args) { key = pair.first; value = pair.second; // If the argument is a length of the cube's side if (key == "L") { length = stoi(value); // terminate the execution, if the length is incorrect if (length <= 0) std::exit(INCORR_LENGTH_ERR_CODE); } // If the data is the origin coordinates else if (key == "origin") { position = value.find(","); positions = vector<size_t>(); // Fetching positions of commas while (position != string::npos) { // Save the current comma position positions.push_back(position); // Get the next comma position position = value.find(",", position + string(",").size()); } // Save the position of the origin origin.x = stod(value.substr(1, positions[0])); origin.y = stod(value.substr(positions[0] + 1, positions[1])); origin.z = stod(value.substr(positions[1] + 1, value.size() - 1)); } // Save the output file name else if (key == "filepath") { filepath = value; } } } const Triangles* Cube::createTriangles() { Triangles* triangles = new Triangles(); Vertex origin_vertex, f_common, s_common; Triangle triangle; // Calculate the vertexes of the cube and create triangles based on them (half of the cube) for (int counter = 0, second_counter = 1; counter < 3 && second_counter < 4; ++counter, ++second_counter) { // second counter is used to move common points (one is offset along the X axis, the other - along Y, one along Y, and so on) if (second_counter == 3) { second_counter = 0; } // Clear vertex temporary files f_common.position = { origin.x, origin.y, origin.z }; s_common.position = { origin.x, origin.y, origin.z }; origin_vertex.position = origin; // Offset two diagonal common points of a face f_common.position[counter] += length; s_common.position[second_counter] += length; // Write points to the triangle triangle.push_back(f_common); triangle.push_back(s_common); triangle.push_back(origin_vertex); // Write the triangle to the triangle vector triangles->push_back(triangle); //Offset Remaining Vertex (which is not shared) triangle[2].position[counter] += length; triangle[2].position[second_counter] += length; // Write the new triangle to the vector triangles->push_back(triangle); // Clear the temporary triangle triangle.clear(); } // Move the origin diagonally (to draw the second half of the cube) origin.x += length; origin.y += length; origin.z += length; //Просчитать точки куба и создать на их основе треугольники (вторая половина куба) for (int counter = 0, second_counter = 1; counter < 3 && second_counter < 4; ++counter, ++second_counter) { // second counter is used to move common points (one is offset along the X axis, the other - along Y, one along Y, and so on) if (second_counter == 3) { second_counter = 0; } // Clear vertex temporary files f_common.position = { origin.x, origin.y, origin.z }; s_common.position = { origin.x, origin.y, origin.z }; origin_vertex.position = origin; // Offset two diagonal common points of a face f_common.position[counter] -= length; s_common.position[second_counter] -= length; // Write points to the triangle triangle.push_back(f_common); triangle.push_back(s_common); triangle.push_back(origin_vertex); // Write the triangle to the triangle vector triangles->push_back(triangle); //Offset Remaining Vertex (which is not shared) triangle[2].position[counter] -= length; triangle[2].position[second_counter] -= length; // Write the new triangle to the vector triangles->push_back(triangle); // Clear the temporary triangle triangle.clear(); } return triangles; }
30.114458
127
0.69834
[ "object", "vector" ]
a902419b7208f1b21a1bd057bfa0e431044b3c5a
1,833
cpp
C++
tests/PassengerTest.cpp
jlcrodrigues/feup-aed
9586e984cd725292c7d76645b146ec969f788e19
[ "MIT" ]
7
2021-12-22T21:57:38.000Z
2022-01-05T18:08:17.000Z
tests/PassengerTest.cpp
jlcrodrigues/feup-aed
9586e984cd725292c7d76645b146ec969f788e19
[ "MIT" ]
null
null
null
tests/PassengerTest.cpp
jlcrodrigues/feup-aed
9586e984cd725292c7d76645b146ec969f788e19
[ "MIT" ]
1
2021-12-23T00:35:06.000Z
2021-12-23T00:35:06.000Z
/*#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../src/Airline/Airline.h" using testing::Eq; Flight getFlight() { Airport airport1; Airport airport2; return Flight(3, Date(11, 2, 2020), Date(16,0), Date(2,0), airport1, airport2, 100); } Plane getPlane() { return Plane("83598", "A310", 310); } TEST(passenger, buyTicket) { Plane plane = getPlane(); Flight flight = getFlight(); Flight flight_full(4, Date(4,4,2010), Date(3,20), Date(2,30), Airport(), Airport(), 1); Passenger pa = Passenger(12341234, "Carlos"); Passenger pa1 = Passenger(24525, "Manuel"); Passenger pa2 = Passenger(123412, "Maria"); Passenger pa3 = Passenger(324234, "Pedro"); vector<struct GroupMember> group = {{pa1, false}, {pa2, true}}; //Buying a single ticket pa.buyTicket(flight); EXPECT_EQ(flight.getOccupation(), 99); EXPECT_EQ(pa.getTickets().size(), 1); //Buying a ticket to a full flight pa.buyTicket(flight_full); EXPECT_FALSE(pa1.buyTicket(flight_full)); //Buying a group ticket pa1.buyTicket(flight, group); EXPECT_EQ(flight.getOccupation(), 97); EXPECT_EQ(pa1.getTickets().size(), 1); EXPECT_EQ(pa2.getTickets().size(), 1); //Buying 2 tickets to the same flight EXPECT_FALSE(pa.buyTicket(flight)); vector<struct GroupMember> group2 = {{pa3, false}, {pa, true}}; EXPECT_FALSE(pa3.buyTicket(flight, group2)); } TEST(passenger, checkIn) { Flight flight = getFlight(); Passenger pa1 = Passenger(23, "Maria"); Passenger pa2 = Passenger(234, "Carlos"); pa1.buyTicket(flight, true); pa2.buyTicket(flight, false); EXPECT_THROW(pa1.checkIn(flight), invalid_argument); //EXPECT_TRUE(pa1.checkIn(flight, 10)); not working atm //EXPECT_THROW(pa2.checkIn(flight, 10), invalid_argument); //EXPECT_TRUE(pa2.checkIn(flight)); } */
28.2
90
0.678123
[ "vector" ]
a906517dd616649a0b0ca1aecfba0e62b61bd45d
4,177
cc
C++
syzygy/block_graph/transforms/fuzzing_transform.cc
nzeh/syzygy
3573e3d458dbb4285753c28a7cb42ced739f9f55
[ "Apache-2.0" ]
343
2015-01-07T05:58:44.000Z
2022-03-15T14:55:21.000Z
syzygy/block_graph/transforms/fuzzing_transform.cc
nzeh/syzygy-nzeh
3757e53f850644721284073de318e218224dd411
[ "Apache-2.0" ]
61
2015-03-19T18:20:21.000Z
2019-10-23T12:58:23.000Z
syzygy/block_graph/transforms/fuzzing_transform.cc
nzeh/syzygy-nzeh
3757e53f850644721284073de318e218224dd411
[ "Apache-2.0" ]
66
2015-01-20T15:35:05.000Z
2021-11-25T16:49:41.000Z
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/block_graph/transforms/fuzzing_transform.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "syzygy/block_graph/basic_block_assembler.h" #include "syzygy/block_graph/block_builder.h" #include "syzygy/block_graph/block_util.h" #include "syzygy/block_graph/analysis/liveness_analysis.h" #include "syzygy/common/defs.h" namespace block_graph { namespace transforms { namespace { using block_graph::BasicBlock; using block_graph::BasicBlockAssembler; using block_graph::BasicCodeBlock; using block_graph::Instruction; using block_graph::Immediate; } // namespace const char LivenessFuzzingBasicBlockTransform::kTransformName[] = "LivenessFuzzingBasicBlockTransform"; const char FuzzingTransform::kTransformName[] = "FuzzingTransform"; bool LivenessFuzzingBasicBlockTransform::TransformBasicBlockSubGraph( const TransformPolicyInterface* policy, BlockGraph* block_graph, BasicBlockSubGraph* subgraph) { DCHECK(policy != NULL); DCHECK(block_graph != NULL); DCHECK(subgraph != NULL); // Perform the global liveness analysis. block_graph::analysis::LivenessAnalysis liveness; liveness.Analyze(subgraph); // Iterate through each basic block and instrument it. BasicBlockSubGraph::BBCollection::iterator bb_iter = subgraph->basic_blocks().begin(); for (; bb_iter != subgraph->basic_blocks().end(); ++bb_iter) { BasicCodeBlock* bb = BasicCodeBlock::Cast(*bb_iter); if (bb == NULL) continue; block_graph::analysis::LivenessAnalysis::State state; liveness.GetStateAtExitOf(bb, &state); BasicBlock::Instructions& instructions = bb->instructions(); if (instructions.empty()) continue; BasicBlock::Instructions::iterator instr_iter = instructions.end(); --instr_iter; while (true) { // Propagate liveness through the current instruction. Instruction instr = *instr_iter; liveness.PropagateBackward(instr, &state); // Rewrite dead registers. for (size_t i = 0; i < assm::kRegister32Count; ++i) { const assm::Register32& reg = assm::kRegisters32[i]; if (state.IsLive(reg)) continue; BasicBlockAssembler assembly(instr_iter, &instructions); // Write some garbage in the dead register. assembly.mov(reg, Immediate(0xCCCCCCCC)); --instr_iter; } if (!state.AreArithmeticFlagsLive()) { // Write some garbage to the flags register when they are not alive. BasicBlockAssembler assembly(instr_iter, &instructions); assembly.add(assm::ebp, Immediate(0, assm::kSize32Bit)); --instr_iter; } // Move to the previous instruction. if (instr_iter == instructions.begin()) break; --instr_iter; } } return true; } FuzzingTransform::FuzzingTransform() { } bool FuzzingTransform::OnBlock( const TransformPolicyInterface* policy, BlockGraph* block_graph, BlockGraph::Block* block) { DCHECK(policy != NULL); DCHECK(block_graph != NULL); DCHECK(block != NULL); // Use the policy to skip blocks that aren't eligible for basic block // decomposition. if (!policy->BlockIsSafeToBasicBlockDecompose(block)) return true; // Apply a basic block transform. LivenessFuzzingBasicBlockTransform liveness_transform; if (!ApplyBasicBlockSubGraphTransform( &liveness_transform, policy, block_graph, block, NULL)) { return false; } return true; } } // namespace transforms } // namespace block_graph
30.713235
76
0.717501
[ "transform" ]
a90b74e2e5f651c00c89e7939d12373425956e12
7,263
cpp
C++
compiler/v2/generics.cpp
uchan-nos/opela
bdc54486c419dd6ae569e398acb93ac96631b3d9
[ "MIT" ]
25
2020-08-28T16:31:35.000Z
2021-09-01T04:35:01.000Z
compiler/v2/generics.cpp
uchan-nos/opela
bdc54486c419dd6ae569e398acb93ac96631b3d9
[ "MIT" ]
3
2020-12-28T07:17:50.000Z
2021-01-27T01:53:20.000Z
compiler/v2/generics.cpp
uchan-nos/opela
bdc54486c419dd6ae569e398acb93ac96631b3d9
[ "MIT" ]
null
null
null
#include "generics.hpp" #include <cassert> #include <cstring> #include <functional> #include <iostream> #include <map> #include "ast.hpp" #include "magic_enum.hpp" #include "mangle.hpp" using namespace std; struct ConcContext { Source& src; TypeMap& gtype; Object* func; // 具体化を実行中の関数オブジェクト std::map<Object*, Object*>& new_lvars; }; namespace { Node* ConcretizeNode(ConcContext& ctx, Node* node) { if (node == nullptr) { return nullptr; } if (node->kind == Node::kType) { return NewNodeType(node->token, ConcretizeType(ctx.gtype, node->type)); } else if (node->kind == Node::kId) { auto dup = NewNode(Node::kId, node->token); if (auto p = get_if<Object*>(&node->value)) { Object* obj = *p; if (auto it = ctx.new_lvars.find(obj); it != ctx.new_lvars.end()) { dup->value = it->second; dup->type = it->second->type; } else { auto obj_dup = new Object{*obj}; dup->value = obj_dup; dup->type = obj_dup->type = ConcretizeType(ctx.gtype, obj->type); } } else { dup->type = ConcretizeType(ctx.gtype, node->type); } return dup; } auto lhs = ConcretizeNode(ctx, node->lhs); auto rhs = ConcretizeNode(ctx, node->rhs); auto cond = ConcretizeNode(ctx, node->cond); auto next = ConcretizeNode(ctx, node->next); if (lhs == node->lhs && rhs == node->rhs && cond == node->cond && next == node->next) { return node; } auto dup = NewNode(node->kind, node->token); dup->lhs = lhs; dup->rhs = rhs; dup->cond = cond; dup->next = next; dup->value = node->value; if (auto p = get_if<Object*>(&node->value)) { Object* obj = *p; get<Object*>(dup->value)->type = ConcretizeType(ctx.gtype, obj->type); } else if (auto p = get_if<TypedFunc*>(&node->value)) { TypedFunc* tf = *p; get<TypedFunc*>(dup->value)->func->type = ConcretizeType(ctx.gtype, tf->func->type); } switch (node->kind) { case Node::kAdd: case Node::kSub: case Node::kMul: case Node::kDiv: dup->type = MergeTypeBinOp(lhs->type, rhs->type); break; case Node::kEqu: case Node::kGT: dup->type = node->type; break; case Node::kBlock: break; case Node::kRet: dup->type = lhs->type; break; case Node::kIf: break; case Node::kAssign: dup->type = lhs->type; break; case Node::kCall: dup->type = lhs->type->base; break; case Node::kParam: dup->type = lhs->type; break; case Node::kSizeof: dup->type = node->type; break; case Node::kCast: dup->type = ConcretizeType(ctx.gtype, node->type); break; case Node::kDeref: dup->type = lhs->type->base; break; case Node::kSubscr: dup->type = lhs->type->base; break; case Node::kInc: case Node::kDec: dup->type = lhs->type; break; case Node::kArrow: if (auto p = GetPrimaryType(lhs->type); p->kind != Type::kPointer) { cerr << "lhs must be a pointer to a struct: " << p << endl; ErrorAt(ctx.src, *node->token); } else if (auto t = GetPrimaryType(p->base); t->kind != Type::kStruct) { cerr << "lhs must be a pointer to a struct: " << t << endl; ErrorAt(ctx.src, *node->token); } else { for (auto ft = t->next; ft; ft = ft->next) { if (get<Token*>(ft->value)->raw == node->rhs->token->raw) { dup->type = ft->base; break; } } if (dup->type == nullptr) { cerr << "no such member" << endl; ErrorAt(ctx.src, *node->rhs->token); } } break; case Node::kTList: break; default: cerr << "ConcretizeNode: not implemented" << endl; ErrorAt(ctx.src, *node->token); } return dup; } } // namespace using DoneKey = std::pair<Type*, TypeMap*>; struct LessDoneKey { bool operator()(const DoneKey& a, const DoneKey& b) const { if (a.first < b.first) { return true; } else if (a.first > b.first) { return false; } // a.first == b.first if (b.second == nullptr) { return false; } else if (a.second == nullptr) { return true; } // a.second != nullptr && b.second != nullptr return *a.second < *b.second; } }; using DoneMap = std::map<DoneKey, Type*, LessDoneKey>; Type* ConcretizeType(TypeMap* gtype, Type* type, DoneMap& done) { if (type == nullptr) { return nullptr; } else if (auto it = done.find({type, gtype}); it != done.end()) { return it->second; } if (type->kind == Type::kConcrete) { auto generic_t = GetUserBaseType(type->base); auto type_list = type->next; auto gtype_ = new TypeMap; auto gparam = generic_t->next; for (auto param = type_list; param; param = param->next) { string gname{get<Token*>(gparam->value)->raw}; gtype_->insert({gname, ConcretizeType(gtype, param->base, done)}); gparam = gparam->next; } return done[{type, gtype_}] = ConcretizeType(gtype_, generic_t->base, done); } if (type->kind == Type::kGParam) { if (gtype) { return done[{type, gtype}] = (*gtype)[string(get<Token*>(type->value)->raw)]; } return done[{type, gtype}] = type; } auto dup = NewType(type->kind); done[{type, gtype}] = dup; dup->base = ConcretizeType(gtype, type->base, done); dup->next = ConcretizeType(gtype, type->next, done); dup->value = type->value; return dup; } Type* ConcretizeType(TypeMap& gtype, Type* type) { DoneMap done; return ConcretizeType(&gtype, type, done); } Type* ConcretizeType(Type* type) { DoneMap done; return ConcretizeType(nullptr, type, done); } TypedFunc* NewTypedFunc(Object* gfunc, Node* type_list) { assert(type_list->kind == Node::kTList); auto cf = new TypedFunc{{}, gfunc}; auto gname = gfunc->def->rhs; // generic name list: T, S, ... for (auto tnode = type_list->lhs; tnode; tnode = tnode->next) { cf->gtype[string(gname->token->raw)] = tnode->type; gname = gname->next; } return cf; } Type* ConcretizeType(TypedFunc& f) { return ConcretizeType(f.gtype, f.func->type); } std::string Mangle(TypedFunc& f) { auto t = ConcretizeType(f); return Mangle(f.func->id->raw, t); } Node* ConcretizeDefFunc(Source& src, TypeMap& gtype, Node* def) { assert(def->kind == Node::kDefFunc); auto def_dup = NewNode(Node::kDefFunc, def->token); for (auto& [ gname, conc_t ] : gtype) { gtype[gname] = ConcretizeType(gtype, conc_t); } auto func = get<Object*>(def->value); Type* conc_func_t = ConcretizeType(gtype, func->type); auto obj_dup = NewFunc(func->id, def, func->linkage); obj_dup->locals = func->locals; map<Object*, Object*> new_lvars; for (size_t i = 0; i < func->locals.size(); ++i) { Object* lvar = func->locals[i]; auto t = ConcretizeType(gtype, lvar->type); if (t != lvar->type) { auto new_lvar = new Object{*lvar}; new_lvar->type = t; obj_dup->locals[i] = new_lvar; new_lvars[lvar] = new_lvar; } } obj_dup->type = conc_func_t; ConcContext ctx{src, gtype, obj_dup, new_lvars}; def_dup->lhs = ConcretizeNode(ctx, def->lhs); def_dup->rhs = ConcretizeNode(ctx, def->rhs); def_dup->cond = ConcretizeNode(ctx, def->cond); def_dup->value = obj_dup; obj_dup->mangled_name = MangleByDefNode(def_dup); return def_dup; }
26.125899
83
0.604709
[ "object" ]
a90d07b41b59957a5d5d987293bd2f498e533956
9,549
cpp
C++
shared/source/os_interface/linux/ioctl_helper_prelim.cpp
againull/compute-runtime
3ef1ab88a4d9fad5c72e343f349365817c54da17
[ "Intel", "MIT" ]
null
null
null
shared/source/os_interface/linux/ioctl_helper_prelim.cpp
againull/compute-runtime
3ef1ab88a4d9fad5c72e343f349365817c54da17
[ "Intel", "MIT" ]
null
null
null
shared/source/os_interface/linux/ioctl_helper_prelim.cpp
againull/compute-runtime
3ef1ab88a4d9fad5c72e343f349365817c54da17
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2021-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/debug_settings/debug_settings_manager.h" #include "shared/source/helpers/debug_helpers.h" #include "shared/source/os_interface/linux/cache_info.h" #include "shared/source/os_interface/linux/ioctl_helper.h" #include "third_party/uapi/prelim/drm/i915_drm.h" #include <algorithm> #include <cerrno> #include <cstring> #include <sys/ioctl.h> namespace NEO { uint32_t IoctlHelperPrelim20::createGemExt(Drm *drm, const std::vector<MemoryClassInstance> &memClassInstances, size_t allocSize, uint32_t &handle) { uint32_t regionsSize = static_cast<uint32_t>(memClassInstances.size()); std::vector<prelim_drm_i915_gem_memory_class_instance> regions(regionsSize); for (uint32_t i = 0; i < regionsSize; i++) { regions[i].memory_class = memClassInstances[i].memoryClass; regions[i].memory_instance = memClassInstances[i].memoryInstance; } prelim_drm_i915_gem_object_param regionParam{}; regionParam.size = regionsSize; regionParam.data = reinterpret_cast<uintptr_t>(regions.data()); regionParam.param = PRELIM_I915_OBJECT_PARAM | PRELIM_I915_PARAM_MEMORY_REGIONS; prelim_drm_i915_gem_create_ext_setparam setparamRegion{}; setparamRegion.base.name = PRELIM_I915_GEM_CREATE_EXT_SETPARAM; setparamRegion.param = regionParam; prelim_drm_i915_gem_create_ext createExt{}; createExt.size = allocSize; createExt.extensions = reinterpret_cast<uintptr_t>(&setparamRegion); printDebugString(DebugManager.flags.PrintBOCreateDestroyResult.get(), stdout, "Performing GEM_CREATE_EXT with { size: %lu, param: 0x%llX", allocSize, regionParam.param); if (DebugManager.flags.PrintBOCreateDestroyResult.get()) { for (uint32_t i = 0; i < regionsSize; i++) { auto region = regions[i]; printDebugString(DebugManager.flags.PrintBOCreateDestroyResult.get(), stdout, ", memory class: %d, memory instance: %d", region.memory_class, region.memory_instance); } printDebugString(DebugManager.flags.PrintBOCreateDestroyResult.get(), stdout, "%s", " }\n"); } auto ret = IoctlHelper::ioctl(drm, PRELIM_DRM_IOCTL_I915_GEM_CREATE_EXT, &createExt); printDebugString(DebugManager.flags.PrintBOCreateDestroyResult.get(), stdout, "GEM_CREATE_EXT has returned: %d BO-%u with size: %lu\n", ret, createExt.handle, createExt.size); handle = createExt.handle; return ret; } std::vector<MemoryRegion> IoctlHelperPrelim20::translateToMemoryRegions(const std::vector<uint8_t> &regionInfo) { auto *data = reinterpret_cast<const prelim_drm_i915_query_memory_regions *>(regionInfo.data()); auto memRegions = std::vector<MemoryRegion>(data->num_regions); for (uint32_t i = 0; i < data->num_regions; i++) { memRegions[i].probedSize = data->regions[i].probed_size; memRegions[i].unallocatedSize = data->regions[i].unallocated_size; memRegions[i].region.memoryClass = data->regions[i].region.memory_class; memRegions[i].region.memoryInstance = data->regions[i].region.memory_instance; } return memRegions; } CacheRegion IoctlHelperPrelim20::closAlloc(Drm *drm) { struct prelim_drm_i915_gem_clos_reserve clos = {}; int ret = IoctlHelper::ioctl(drm, PRELIM_DRM_IOCTL_I915_GEM_CLOS_RESERVE, &clos); if (ret != 0) { int err = errno; printDebugString(DebugManager.flags.PrintDebugMessages.get(), stderr, "ioctl(I915_GEM_CLOS_RESERVE) failed with %d. errno=%d(%s)\n", ret, err, strerror(err)); DEBUG_BREAK_IF(true); return CacheRegion::None; } return static_cast<CacheRegion>(clos.clos_index); } uint16_t IoctlHelperPrelim20::closAllocWays(Drm *drm, CacheRegion closIndex, uint16_t cacheLevel, uint16_t numWays) { struct prelim_drm_i915_gem_cache_reserve cache = {}; cache.clos_index = static_cast<uint16_t>(closIndex); cache.cache_level = cacheLevel; cache.num_ways = numWays; int ret = IoctlHelper::ioctl(drm, PRELIM_DRM_IOCTL_I915_GEM_CACHE_RESERVE, &cache); if (ret != 0) { int err = errno; PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "ioctl(I915_GEM_CACHE_RESERVE) failed with %d. errno=%d(%s)\n", ret, err, strerror(err)); return 0; } return cache.num_ways; } CacheRegion IoctlHelperPrelim20::closFree(Drm *drm, CacheRegion closIndex) { struct prelim_drm_i915_gem_clos_free clos = {}; clos.clos_index = static_cast<uint16_t>(closIndex); int ret = IoctlHelper::ioctl(drm, PRELIM_DRM_IOCTL_I915_GEM_CLOS_FREE, &clos); if (ret != 0) { int err = errno; printDebugString(DebugManager.flags.PrintDebugMessages.get(), stderr, "ioctl(I915_GEM_CLOS_FREE) failed with %d. errno=%d(%s)\n", ret, err, strerror(err)); DEBUG_BREAK_IF(true); return CacheRegion::None; } return closIndex; } int IoctlHelperPrelim20::waitUserFence(Drm *drm, uint32_t ctxId, uint64_t address, uint64_t value, uint32_t dataWidth, int64_t timeout, uint16_t flags) { prelim_drm_i915_gem_wait_user_fence wait = {}; wait.ctx_id = ctxId; wait.flags = flags; switch (dataWidth) { case 3u: wait.mask = PRELIM_I915_UFENCE_WAIT_U64; break; case 2u: wait.mask = PRELIM_I915_UFENCE_WAIT_U32; break; case 1u: wait.mask = PRELIM_I915_UFENCE_WAIT_U16; break; default: wait.mask = PRELIM_I915_UFENCE_WAIT_U8; break; } wait.op = PRELIM_I915_UFENCE_WAIT_GTE; wait.addr = address; wait.value = value; wait.timeout = timeout; return IoctlHelper::ioctl(drm, PRELIM_DRM_IOCTL_I915_GEM_WAIT_USER_FENCE, &wait); } uint32_t IoctlHelperPrelim20::getHwConfigIoctlVal() { return PRELIM_DRM_I915_QUERY_HWCONFIG_TABLE; } uint32_t IoctlHelperPrelim20::getAtomicAdvise(bool isNonAtomic) { return isNonAtomic ? PRELIM_I915_VM_ADVISE_ATOMIC_NONE : PRELIM_I915_VM_ADVISE_ATOMIC_SYSTEM; } uint32_t IoctlHelperPrelim20::getPreferredLocationAdvise() { return PRELIM_I915_VM_ADVISE_PREFERRED_LOCATION; } bool IoctlHelperPrelim20::setVmBoAdvise(Drm *drm, int32_t handle, uint32_t attribute, void *region) { prelim_drm_i915_gem_vm_advise vmAdvise{}; vmAdvise.handle = handle; vmAdvise.attribute = attribute; if (region != nullptr) { vmAdvise.region = *reinterpret_cast<prelim_drm_i915_gem_memory_class_instance *>(region); } int ret = IoctlHelper::ioctl(drm, PRELIM_DRM_IOCTL_I915_GEM_VM_ADVISE, &vmAdvise); if (ret != 0) { int err = errno; PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "ioctl(PRELIM_DRM_I915_GEM_VM_ADVISE) failed with %d. errno=%d(%s)\n", ret, err, strerror(err)); DEBUG_BREAK_IF(true); return false; } return true; } uint32_t IoctlHelperPrelim20::getDirectSubmissionFlag() { return PRELIM_I915_CONTEXT_CREATE_FLAGS_ULLS; } int32_t IoctlHelperPrelim20::getMemRegionsIoctlVal() { return PRELIM_DRM_I915_QUERY_MEMORY_REGIONS; } int32_t IoctlHelperPrelim20::getEngineInfoIoctlVal() { return PRELIM_DRM_I915_QUERY_ENGINE_INFO; } std::vector<EngineCapabilities> IoctlHelperPrelim20::translateToEngineCaps(const std::vector<uint8_t> &data) { auto engineInfo = reinterpret_cast<const prelim_drm_i915_query_engine_info *>(data.data()); std::vector<EngineCapabilities> engines; engines.reserve(engineInfo->num_engines); for (uint32_t i = 0; i < engineInfo->num_engines; i++) { EngineCapabilities engine{}; engine.capabilities = engineInfo->engines[i].capabilities; engine.engine.engineClass = engineInfo->engines[i].engine.engine_class; engine.engine.engineInstance = engineInfo->engines[i].engine.engine_instance; engines.push_back(engine); } return engines; } prelim_drm_i915_query_distance_info translateToi915(const DistanceInfo &distanceInfo) { prelim_drm_i915_query_distance_info dist{}; dist.engine.engine_class = distanceInfo.engine.engineClass; dist.engine.engine_instance = distanceInfo.engine.engineInstance; dist.region.memory_class = distanceInfo.region.memoryClass; dist.region.memory_instance = distanceInfo.region.memoryInstance; return dist; } uint32_t IoctlHelperPrelim20::queryDistances(Drm *drm, std::vector<drm_i915_query_item> &queryItems, std::vector<DistanceInfo> &distanceInfos) { std::vector<prelim_drm_i915_query_distance_info> i915Distances(distanceInfos.size()); std::transform(distanceInfos.begin(), distanceInfos.end(), i915Distances.begin(), translateToi915); for (auto i = 0u; i < i915Distances.size(); i++) { queryItems[i].query_id = PRELIM_DRM_I915_QUERY_DISTANCE_INFO; queryItems[i].length = sizeof(prelim_drm_i915_query_distance_info); queryItems[i].flags = 0u; queryItems[i].data_ptr = reinterpret_cast<__u64>(&i915Distances[i]); } drm_i915_query query{}; query.items_ptr = reinterpret_cast<__u64>(queryItems.data()); query.num_items = static_cast<uint32_t>(queryItems.size()); auto ret = IoctlHelper::ioctl(drm, DRM_IOCTL_I915_QUERY, &query); for (auto i = 0u; i < i915Distances.size(); i++) { distanceInfos[i].distance = i915Distances[i].distance; } return ret; } int32_t IoctlHelperPrelim20::getComputeEngineClass() { return PRELIM_I915_ENGINE_CLASS_COMPUTE; } } // namespace NEO
39.296296
179
0.725626
[ "vector", "transform" ]
a90e58b02df7bc6e4ec7f1f5837d6c5d0d6a8ac8
4,769
hpp
C++
Code/Rendering/VertexArray.hpp
Tigole/OpenGL-SandBox
652d07e7b5b3aff2600f61d4e5b7114a2ebf8b24
[ "MIT" ]
null
null
null
Code/Rendering/VertexArray.hpp
Tigole/OpenGL-SandBox
652d07e7b5b3aff2600f61d4e5b7114a2ebf8b24
[ "MIT" ]
null
null
null
Code/Rendering/VertexArray.hpp
Tigole/OpenGL-SandBox
652d07e7b5b3aff2600f61d4e5b7114a2ebf8b24
[ "MIT" ]
null
null
null
#ifndef _VERTEX_ARRAY_HPP #define _VERTEX_ARRAY_HPP 1 #include <cstdint> #include <vector> #include <initializer_list> #include <string> #include <map> #include <memory> #include "glm/glm.hpp" //#include "ResourceManager/Resource.hpp" #include "OpenGLTranslation.hpp" class Mesh; enum class ShaderDataType { None, vec3, vec4, mat3, mat4, vec2, }; std::istream& operator>>(std::istream& i, ShaderDataType& sdt); std::ostream& operator<<(std::ostream& o, ShaderDataType& sdt); int fn_ShaderDataType_To_Size(ShaderDataType type); int fn_ShaderDataType_To_Type(ShaderDataType type); struct VertexBufferLayoutElement { VertexBufferLayoutElement() : m_Name(), m_Type(ShaderDataType::None), m_Offset(0), m_Byte_Size(0), m_Nomalized(false) {} VertexBufferLayoutElement(const std::string& name, ShaderDataType type, bool normalized) : m_Name(name), m_Type(type), m_Offset(0), m_Byte_Size(fn_ShaderDataType_To_Size(type)), m_Nomalized(normalized) {} int mt_Get_Element_Count(void) const { switch(m_Type) { case ShaderDataType::mat3: return 3 * 3; case ShaderDataType::mat4: return 4 * 4; case ShaderDataType::vec3: return 3; case ShaderDataType::vec4: return 4; case ShaderDataType::vec2: return 2; } return 0; } std::string m_Name; ShaderDataType m_Type; int m_Offset; int m_Byte_Size; bool m_Nomalized; }; class VertexBufferLayout { public: VertexBufferLayout() : m_Elements() {} VertexBufferLayout(std::initializer_list<VertexBufferLayoutElement> elements) : m_Elements(elements) { mt_Setup(); } VertexBufferLayout(const std::vector<VertexBufferLayoutElement>& elements) : m_Elements(elements) { mt_Setup(); } void mt_Set_Elements(const std::vector<VertexBufferLayoutElement>& elements) { m_Elements = elements; mt_Setup(); } int mt_Get_Stride(void) const { return m_Stride; } const std::vector<VertexBufferLayoutElement>& mt_Get_Elements(void) const { return m_Elements; } std::vector<VertexBufferLayoutElement>::iterator begin() {return m_Elements.begin();} std::vector<VertexBufferLayoutElement>::iterator end() {return m_Elements.end();} private: void mt_Setup(void) { int l_Offset = 0; for (std::size_t ii = 0; ii < m_Elements.size(); ii++) { m_Elements[ii].m_Offset = l_Offset; l_Offset += m_Elements[ii].m_Byte_Size; } m_Stride = l_Offset; } int m_Stride; std::vector<VertexBufferLayoutElement> m_Elements; }; class IndexBuffer { public: IndexBuffer(const std::vector<uint32_t>& indices); ~IndexBuffer(); void mt_Bind(void); void mt_Unbind(void); uint32_t mt_Get_Indices_Count(void) const {return m_Indices_Count;} private: uint32_t m_Id; uint32_t m_Indices_Count; }; class VertexBuffer { public: VertexBuffer(const std::vector<float>& vertices, const VertexBufferLayout& layout); /// Add index buffer construction method VertexBuffer(const VertexBufferLayout& layout); ~VertexBuffer(); void mt_Bind(void); void mt_Unbind(void); const VertexBufferLayout& mt_Get_Layout(void) const { return m_Layout; } IndexBuffer* mt_Get_Index_Buffer(void) { return m_Index_Buffer.get(); } bool mt_Instanced(void) const { return m_Index_Buffer == nullptr; } void mt_Update_Data(const std::vector<float>& vertices, DrawingUsage usage); bool mt_Update_Data(const std::string& name, const void* data, std::size_t byte_count, DrawingUsage usage); private: uint32_t m_Id; VertexBufferLayout m_Layout; std::unique_ptr<IndexBuffer> m_Index_Buffer; }; struct VertexArray_CreationParams { Mesh* m_Mesh; }; class VertexArray { public: VertexArray(); VertexArray(const VertexArray& rhs) = delete; VertexArray& operator=(const VertexArray& rhs) = delete; ~VertexArray(); void mt_Add_Vertex_Buffer(VertexBuffer* buffer); void mt_Set_Index_Buffer(IndexBuffer* buffer); void mt_Bind(void) const; void mt_Unbind(void) const; bool mt_Update_Data(const std::string& name, const glm::mat4& matrix); bool mt_Update_Data(const std::string& name, const void* data, std::size_t byte_count, DrawingUsage usage); private: std::map<std::string, VertexBuffer*> m_String_Data_Map; std::vector<VertexBuffer*> m_Vertex_Buffers; IndexBuffer* m_Index_Buffer; uint32_t m_Id; uint32_t m_Attrib_Index; public: uint32_t mt_Indice_Count(void) const { return m_Index_Buffer->mt_Get_Indices_Count(); } }; #endif // _VERTEX_ARRAY_HPP
24.582474
129
0.687985
[ "mesh", "vector" ]
a910219ca340352c67e332be105855ace9b10fbb
2,409
cpp
C++
aws-cpp-sdk-opensearch/source/model/StorageType.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-opensearch/source/model/StorageType.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-opensearch/source/model/StorageType.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/opensearch/model/StorageType.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace OpenSearchService { namespace Model { StorageType::StorageType() : m_storageTypeNameHasBeenSet(false), m_storageSubTypeNameHasBeenSet(false), m_storageTypeLimitsHasBeenSet(false) { } StorageType::StorageType(JsonView jsonValue) : m_storageTypeNameHasBeenSet(false), m_storageSubTypeNameHasBeenSet(false), m_storageTypeLimitsHasBeenSet(false) { *this = jsonValue; } StorageType& StorageType::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("StorageTypeName")) { m_storageTypeName = jsonValue.GetString("StorageTypeName"); m_storageTypeNameHasBeenSet = true; } if(jsonValue.ValueExists("StorageSubTypeName")) { m_storageSubTypeName = jsonValue.GetString("StorageSubTypeName"); m_storageSubTypeNameHasBeenSet = true; } if(jsonValue.ValueExists("StorageTypeLimits")) { Array<JsonView> storageTypeLimitsJsonList = jsonValue.GetArray("StorageTypeLimits"); for(unsigned storageTypeLimitsIndex = 0; storageTypeLimitsIndex < storageTypeLimitsJsonList.GetLength(); ++storageTypeLimitsIndex) { m_storageTypeLimits.push_back(storageTypeLimitsJsonList[storageTypeLimitsIndex].AsObject()); } m_storageTypeLimitsHasBeenSet = true; } return *this; } JsonValue StorageType::Jsonize() const { JsonValue payload; if(m_storageTypeNameHasBeenSet) { payload.WithString("StorageTypeName", m_storageTypeName); } if(m_storageSubTypeNameHasBeenSet) { payload.WithString("StorageSubTypeName", m_storageSubTypeName); } if(m_storageTypeLimitsHasBeenSet) { Array<JsonValue> storageTypeLimitsJsonList(m_storageTypeLimits.size()); for(unsigned storageTypeLimitsIndex = 0; storageTypeLimitsIndex < storageTypeLimitsJsonList.GetLength(); ++storageTypeLimitsIndex) { storageTypeLimitsJsonList[storageTypeLimitsIndex].AsObject(m_storageTypeLimits[storageTypeLimitsIndex].Jsonize()); } payload.WithArray("StorageTypeLimits", std::move(storageTypeLimitsJsonList)); } return payload; } } // namespace Model } // namespace OpenSearchService } // namespace Aws
24.581633
134
0.764633
[ "model" ]
a9112ee9b512c0153d96fccbcf4177d961a23240
10,279
cc
C++
libconfig/lua/lua_config.cc
lynnlx/gear-lib
abf19104d0512eda0b1e5e49422169993e31f8b5
[ "MIT" ]
2
2019-02-26T11:02:20.000Z
2019-02-26T11:02:27.000Z
libconfig/lua/lua_config.cc
Yu-cz/gear-lib
c6902177457436f3c26902f071bd4015781aae66
[ "MIT" ]
null
null
null
libconfig/lua/lua_config.cc
Yu-cz/gear-lib
c6902177457436f3c26902f071bd4015781aae66
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright (C) 2014-2020 Zhifeng Gong <gozfree@163.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 <libmacro.h> #include "libconfig.h" #include "config_util.h" #include "luatables.h" #include <iostream> #include <cstdlib> #include <vector> #include <sstream> #include <stdarg.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace std; class LuaConfig: public LuaTable { public: static LuaConfig* create(const char *config) { LuaConfig *result = new LuaConfig(); if (result && !result->init(config)) { delete result; result = NULL; } return result; }; void destroy() { delete this; }; bool save() { std::string config_string = serialize(); if (config_string.length() <= 0) { return false; } int fd = open(filename.c_str(), O_WRONLY|O_TRUNC, 0666); if (fd < 0) { return false; } size_t written = 0; size_t total = config_string.length(); const char *str = config_string.c_str(); while (written < total) { ssize_t retval = write(fd, (void*)(str + written), (total - written)); if (retval > 0) { written += retval; } else if (retval <= 0) { printf("Failed to write file %s: %s", filename.c_str(), strerror(errno)); break; } } return (written == total); } public: virtual ~LuaConfig(){} private: LuaConfig(){}; bool init(const char *config) { *this = fromFile(config); return (luaRef != -1); }; LuaConfig& operator=(const LuaTable &table) { *((LuaTable*)this) = table; return *this; }; }; static int lua_load(struct config *c, const char *name) { LuaConfig *lt = LuaConfig::create(name); if (!lt) { printf("LuaConfig %s failed!\n", name); return -1; } c->priv = (void *)lt; strncpy(c->path, name, sizeof(c->path)); return 0; } static int lua_get_int(struct config *c, ...) { LuaConfig *lt = (LuaConfig *)c->priv; lt = lt; LuaTableNode *node; LuaTable tbl; int ret; struct int_charp *type_list = NULL; struct int_charp mix; int cnt = 0; va_list ap; va_start(ap, c); va_arg_type(ap, mix); while (mix.type != TYPE_EMPTY) {//last argument must be NULL cnt++; type_list = (struct int_charp *)realloc(type_list, cnt*sizeof(struct int_charp)); memcpy(&type_list[cnt-1], &mix, sizeof(mix)); va_arg_type(ap, mix); } va_end(ap); node = new LuaTableNode[cnt]; if (cnt > 0) { if (type_list[0].type == TYPE_INT) { node[0] = (*lt)[type_list[0].ival]; } else if (type_list[0].type == TYPE_CHARP) { node[0] = (*lt)[type_list[0].cval]; } } for (int i = 1; i < cnt; i++) { switch (type_list[i].type) { case TYPE_INT: node[i] = node[i-1][type_list[i].ival]; break; case TYPE_CHARP: node[i] = node[i-1][type_list[i].cval]; break; default: break; } } free(type_list); ret = node[cnt-1].getDefault<int>(0); delete []node; return ret; } static char *lua_get_string(struct config *c, ...) { LuaConfig *lt = (LuaConfig *)c->priv; lt = lt; LuaTableNode *node; LuaTable tbl; char *ret = NULL; struct int_charp *type_list = NULL; struct int_charp mix; int cnt = 0; va_list ap; va_start(ap, c); va_arg_type(ap, mix); while (mix.type != TYPE_EMPTY) {//last argument must be NULL cnt++; type_list = (struct int_charp *)realloc(type_list, cnt*sizeof(struct int_charp)); memcpy(&type_list[cnt-1], &mix, sizeof(mix)); va_arg_type(ap, mix); } va_end(ap); node = new LuaTableNode[cnt]; if (cnt > 0) { if (type_list[0].type == TYPE_INT) { node[0] = (*lt)[type_list[0].ival]; } else if (type_list[0].type == TYPE_CHARP) { node[0] = (*lt)[type_list[0].cval]; } } for (int i = 1; i < cnt; i++) { switch (type_list[i].type) { case TYPE_INT: node[i] = node[i-1][type_list[i].ival]; break; case TYPE_CHARP: node[i] = node[i-1][type_list[i].cval]; break; default: break; } } ret = (char *)node[cnt-1].getDefault<string>("").c_str(); free(type_list); delete []node; return ret; } static double lua_get_double(struct config *c, ...) { LuaConfig *lt = (LuaConfig *)c->priv; lt = lt; LuaTableNode *node; LuaTable tbl; double ret; struct int_charp *type_list = NULL; struct int_charp mix; int cnt = 0; va_list ap; va_start(ap, c); va_arg_type(ap, mix); while (mix.type != TYPE_EMPTY) {//last argument must be NULL cnt++; type_list = (struct int_charp *)realloc(type_list, cnt*sizeof(struct int_charp)); memcpy(&type_list[cnt-1], &mix, sizeof(mix)); va_arg_type(ap, mix); } va_end(ap); node = new LuaTableNode[cnt]; if (cnt > 0) { if (type_list[0].type == TYPE_INT) { node[0] = (*lt)[type_list[0].ival]; } else if (type_list[0].type == TYPE_CHARP) { node[0] = (*lt)[type_list[0].cval]; } } for (int i = 1; i < cnt; i++) { switch (type_list[i].type) { case TYPE_INT: node[i] = node[i-1][type_list[i].ival]; break; case TYPE_CHARP: node[i] = node[i-1][type_list[i].cval]; break; default: break; } } free(type_list); ret = node[cnt-1].getDefault<double>(0); delete []node; return ret; } static int lua_get_boolean(struct config *c, ...) { LuaConfig *lt = (LuaConfig *)c->priv; lt = lt; LuaTableNode *node; LuaTable tbl; int ret; struct int_charp *type_list = NULL; struct int_charp mix; int cnt = 0; va_list ap; va_start(ap, c); va_arg_type(ap, mix); while (mix.type != TYPE_EMPTY) {//last argument must be NULL cnt++; type_list = (struct int_charp *)realloc(type_list, cnt*sizeof(struct int_charp)); memcpy(&type_list[cnt-1], &mix, sizeof(mix)); va_arg_type(ap, mix); } va_end(ap); node = new LuaTableNode[cnt]; if (cnt > 0) { if (type_list[0].type == TYPE_INT) { node[0] = (*lt)[type_list[0].ival]; } else if (type_list[0].type == TYPE_CHARP) { node[0] = (*lt)[type_list[0].cval]; } } for (int i = 1; i < cnt; i++) { switch (type_list[i].type) { case TYPE_INT: node[i] = node[i-1][type_list[i].ival]; break; case TYPE_CHARP: node[i] = node[i-1][type_list[i].cval]; break; default: break; } } free(type_list); ret = node[cnt-1].getDefault<bool>(false); delete []node; return ret; } static int lua_get_length(struct config *c, ...) { LuaConfig *lt = (LuaConfig *)c->priv; lt = lt; LuaTableNode *node; LuaTable tbl; int ret; struct int_charp *type_list = NULL; struct int_charp mix; int cnt = 0; va_list ap; va_start(ap, c); va_arg_type(ap, mix); while (mix.type != TYPE_EMPTY) {//last argument must be NULL cnt++; type_list = (struct int_charp *)realloc(type_list, cnt*sizeof(struct int_charp)); memcpy(&type_list[cnt-1], &mix, sizeof(mix)); va_arg_type(ap, mix); } va_end(ap); node = new LuaTableNode[cnt]; if (cnt > 0) { if (type_list[0].type == TYPE_INT) { node[0] = (*lt)[type_list[0].ival]; } else if (type_list[0].type == TYPE_CHARP) { node[0] = (*lt)[type_list[0].cval]; } } for (int i = 1; i < cnt; i++) { switch (type_list[i].type) { case TYPE_INT: node[i] = node[i-1][type_list[i].ival]; break; case TYPE_CHARP: node[i] = node[i-1][type_list[i].cval]; break; default: break; } } free(type_list); ret = node[cnt-1].length(); delete []node; return ret; } static int lua_save(struct config *c) { LuaConfig *lt = (LuaConfig *)c->priv; return (lt->save()?0:-1); } static void lua_unload(struct config *c) { LuaConfig *lt = (LuaConfig *)c->priv; lt->destroy(); } struct config_ops lua_ops = { .load = lua_load, .set_string = NULL, .get_string = lua_get_string, .get_int = lua_get_int, .get_double = lua_get_double, .get_boolean = lua_get_boolean, .get_length = lua_get_length, .del = NULL, .dump = NULL, .save = lua_save, .unload = lua_unload, };
27.557641
89
0.550637
[ "vector" ]
a9176e180fb08a334644d1cda7e26331d7e28152
7,520
cpp
C++
media_driver/agnostic/common/heap_manager/heap_manager.cpp
xinfengz/media-driver
310104a4693c476a215de13e7e9fabdf2afbad0a
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2019-09-26T23:48:34.000Z
2019-09-26T23:48:34.000Z
media_driver/agnostic/common/heap_manager/heap_manager.cpp
xinfengz/media-driver
310104a4693c476a215de13e7e9fabdf2afbad0a
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2019-01-05T02:54:19.000Z
2019-01-05T02:54:19.000Z
media_driver/agnostic/common/heap_manager/heap_manager.cpp
xinfengz/media-driver
310104a4693c476a215de13e7e9fabdf2afbad0a
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2018-01-12T06:07:55.000Z
2018-01-12T06:07:55.000Z
/* * Copyright (c) 2017, Intel Corporation * * 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 heap_manager.cpp //! \brief Implements functionalities pertaining to the heap manager. //! #include "heap_manager.h" HeapManager::~HeapManager() { HEAP_FUNCTION_ENTER; m_currHeapId = 0; m_currHeapSize = 0; m_extendHeapSize = 0; m_osInterface = nullptr; } MOS_STATUS HeapManager::AcquireSpace( MemoryBlockManager::AcquireParams &params, std::vector<MemoryBlock> &blocks, uint32_t &spaceNeeded) { HEAP_FUNCTION_ENTER; // first time space is being acquired, allocate the first heap if (m_heapIds.empty()) { HEAP_CHK_STATUS(AllocateHeap(m_currHeapSize)); } if (m_behavior != Behavior::clientControlled) { if (params.m_staticBlock) { HEAP_ASSERTMESSAGE("Static blocks are only allowed when the client controls behavior"); return MOS_STATUS_INVALID_PARAMETER; } if (!m_blockManager.IsTrackerDataValid()) { HEAP_ASSERTMESSAGE("A tracker must be registered before acquiring space if client does not control behavior"); return MOS_STATUS_INVALID_PARAMETER; } } spaceNeeded = 0; if ((m_blockManager.AcquireSpace(params, blocks, spaceNeeded)) == MOS_STATUS_CLIENT_AR_NO_SPACE) { bool blocksUpdated = false; // no need to refresh the block states for every space acquisition // attempt for first AcquireSpace failure HEAP_CHK_STATUS(m_blockManager.RefreshBlockStates(blocksUpdated)); if (blocksUpdated) { if ((m_blockManager.AcquireSpace(params, blocks, spaceNeeded)) == MOS_STATUS_CLIENT_AR_NO_SPACE) { // if space may not be acquired after refreshing block states, execute behavior HEAP_CHK_STATUS(BehaveWhenNoSpace()); HEAP_CHK_STATUS(m_blockManager.AcquireSpace(params, blocks, spaceNeeded)); } } else { // if no blocks updated after refresh, execute behavior HEAP_CHK_STATUS(BehaveWhenNoSpace()); HEAP_CHK_STATUS(m_blockManager.AcquireSpace(params, blocks, spaceNeeded)); } } return MOS_STATUS_SUCCESS; } MOS_STATUS HeapManager::ClearSpace(MemoryBlock &block) { HEAP_FUNCTION_ENTER; if (m_behavior != clientControlled) { HEAP_ASSERTMESSAGE("Only client controlled behavior allows for clients to clear space"); return MOS_STATUS_INVALID_PARAMETER; } HEAP_CHK_STATUS(m_blockManager.ClearSpace(block)) return MOS_STATUS_SUCCESS; } MOS_STATUS HeapManager::RegisterTrackerResource(uint32_t *trackerData) { HEAP_FUNCTION_ENTER; return m_blockManager.RegisterTrackerResource(trackerData); } MOS_STATUS HeapManager::SetInitialHeapSize(uint32_t size) { HEAP_FUNCTION_ENTER; if (size == 0) { HEAP_ASSERTMESSAGE("0 is an invalid size for heap extension"); return MOS_STATUS_INVALID_PARAMETER; } m_currHeapSize = MOS_ALIGN_CEIL(size, m_heapAlignment); return MOS_STATUS_SUCCESS; } MOS_STATUS HeapManager::SetExtendHeapSize(uint32_t size) { HEAP_FUNCTION_ENTER; if (size == 0) { HEAP_ASSERTMESSAGE("0 is an invalid size for heap extension"); return MOS_STATUS_INVALID_PARAMETER; } if (m_behavior == Behavior::wait) { HEAP_ASSERTMESSAGE("The heap may not be extended in the case of wait behavior"); return MOS_STATUS_INVALID_PARAMETER; } m_extendHeapSize = MOS_ALIGN_CEIL(size, m_heapAlignment); return MOS_STATUS_SUCCESS; } MOS_STATUS HeapManager::RegisterOsInterface(PMOS_INTERFACE osInterface) { HEAP_FUNCTION_ENTER; HEAP_CHK_NULL(osInterface); m_osInterface = osInterface; HEAP_CHK_STATUS(m_blockManager.RegisterOsInterface(m_osInterface)); return MOS_STATUS_SUCCESS; } uint32_t HeapManager::GetTotalSize() { HEAP_FUNCTION_ENTER; uint32_t totalSize = m_blockManager.GetSize(); // Since allocation is delayed to when space is acquired, it is possible // for manager to be in a valid state if a size of 0 is returned. if (totalSize == 0 && m_currHeapId == Heap::m_invalidId) { totalSize = m_currHeapSize; } return totalSize; } MOS_STATUS HeapManager::AllocateHeap(uint32_t size) { HEAP_FUNCTION_ENTER; HEAP_CHK_NULL(m_osInterface); if (size == 0) { HEAP_ASSERTMESSAGE("0 is an invalid size for heap allocation"); return MOS_STATUS_INVALID_PARAMETER; } ++m_currHeapId; m_heapIds.push_back(m_currHeapId); HEAP_CHK_STATUS(m_blockManager.RegisterHeap(m_currHeapId, size)); return MOS_STATUS_SUCCESS; } void HeapManager::FreeHeap() { // Free oldest heap auto heapId = m_heapIds.front(); m_heapIds.pop_front(); m_blockManager.UnregisterHeap(heapId); } MOS_STATUS HeapManager::Wait() { HEAP_FUNCTION_ENTER_VERBOSE; bool blocksUpdated = false; for (auto waitMs = m_waitTimeout; waitMs > 0; waitMs -= m_waitIncrement) { MOS_Sleep(m_waitIncrement); HEAP_CHK_STATUS(m_blockManager.RefreshBlockStates(blocksUpdated)); if (blocksUpdated) { break; } } return (blocksUpdated) ? MOS_STATUS_SUCCESS : MOS_STATUS_CLIENT_AR_NO_SPACE; } MOS_STATUS HeapManager::BehaveWhenNoSpace() { HEAP_FUNCTION_ENTER_VERBOSE; switch (m_behavior) { case wait: HEAP_CHK_STATUS(Wait()); break; case extend: m_currHeapSize += m_extendHeapSize; HEAP_CHK_STATUS(AllocateHeap(m_currHeapSize)); break; case destructiveExtend: FreeHeap(); m_currHeapSize += m_extendHeapSize; HEAP_CHK_STATUS(AllocateHeap(m_currHeapSize)); break; case waitAndExtend: if (Wait() == MOS_STATUS_CLIENT_AR_NO_SPACE) { m_currHeapSize += m_extendHeapSize; HEAP_CHK_STATUS(AllocateHeap(m_currHeapSize)); } break; case clientControlled: // heap manager gives control back to the client return MOS_STATUS_CLIENT_AR_NO_SPACE; default: HEAP_ASSERTMESSAGE("The requested behavior is not yet implemented"); return MOS_STATUS_UNIMPLEMENTED; } return MOS_STATUS_SUCCESS; }
29.034749
122
0.68391
[ "vector" ]
a91ac2dfe0802de7dee5ead9ca22633687385e26
11,982
cpp
C++
xcode/strands/strands/width.cpp
DarisaLLC/ridge_strands
50766c05a40c41f7934e7fef73ae1114fccbe9dc
[ "MIT" ]
3
2021-08-30T10:54:17.000Z
2021-12-24T03:39:28.000Z
xcode/strands/strands/width.cpp
DarisaLLC/ridge_strands
50766c05a40c41f7934e7fef73ae1114fccbe9dc
[ "MIT" ]
1
2021-09-10T06:11:05.000Z
2021-09-10T06:11:05.000Z
xcode/strands/strands/width.cpp
DarisaLLC/ridge_strands
50766c05a40c41f7934e7fef73ae1114fccbe9dc
[ "MIT" ]
1
2021-08-30T10:57:48.000Z
2021-08-30T10:57:48.000Z
#include "link.h" #include "utils.hpp" using namespace std; /* * Extract the line width by using a facet model line detector on an image of * the absolute value of the gradient. */ void link::compute_line_width(std::vector<float>& dx, std::vector<float>& dy, bool correct_pos, std::vector<contour>& contours){ auto width = m_width; auto height = m_height; int i, j, k; int r, c, l; int x, y, dir; float length; contour cont; int num_points, max_num_points; float d, dr, dc, drr, drc, dcc; float i1, i2, i3, i4, i5, i6, i7, i8, i9; float t1, t2, t3, t4, t5, t6; float a, b, t = 0; int num = 0; float nx, ny; float n1, n2; float p1, p2; float val; float px, py; max_num_points = 0; for (auto i = 0; i < contours.size(); i++) { num_points = contours[i].num; if (num_points > max_num_points) max_num_points = num_points; } std::vector<float> width_l(max_num_points); std::vector<float> width_r(max_num_points); std::vector<float> grad_l(max_num_points); std::vector<float> grad_r(max_num_points); std::vector<float> pos_x(max_num_points); std::vector<float> pos_y(max_num_points); std::vector<float> correct(max_num_points); std::vector<float> contrast(max_num_points); std::vector<float> asymm(max_num_points); std::vector<float> grad(width * height); length = 2.5f * sigma(); #if 0 max_line = (int)Math.ceil(length * 3); line = new Offset[max_line]; for (int o = 0; o < line.length; o++) { line[o] = new Offset(); } #endif /* Compute the gradient image. */ for (r = 0; r < height; r++) { for (c = 0; c < width; c++) { l = LCOR(r, c, width); grad[l] = (float)sqrt(dx[l] * dx[l] + dy[l] * dy[l]); } } for (i = 0; i < contours.size(); i++) { cont = contours[i]; num_points = cont.num; for (j = 0; j < num_points; j++) { px = cont.row[j]; py = cont.col[j]; pos_x[j] = px; pos_y[j] = py; r = (int)floor(px + 0.5); c = (int)floor(py + 0.5); nx = cos(cont.angle[j]); ny = sin(cont.angle[j]); /* Compute the search line. */ std::vector<offset> line; bresenham(nx, ny, 0.0, 0.0, length, line); auto num_line = line.size(); width_r[j] = width_l[j] = 0; /* Look on both sides of the line. */ for (dir = -1; dir <= 1; dir += 2) { for (k = 0; k < num_line; k++) { x = BR(r + dir * line[k].x()); y = BC(c + dir * line[k].y()); i1 = grad[LCOR(BR(x - 1), BC(y - 1), width)]; i2 = grad[LCOR(BR(x - 1), y, width)]; i3 = grad[LCOR(BR(x - 1), BC(y + 1), width)]; i4 = grad[LCOR(x, BC(y - 1), width)]; i5 = grad[LCOR(x, y, width)]; i6 = grad[LCOR(x, BC(y + 1), width)]; i7 = grad[LCOR(BR(x + 1), BC(y - 1), width)]; i8 = grad[LCOR(BR(x + 1), y, width)]; i9 = grad[LCOR(BR(x + 1), BC(y + 1), width)]; t1 = i1 + i2 + i3; t2 = i4 + i5 + i6; t3 = i7 + i8 + i9; t4 = i1 + i4 + i7; t5 = i2 + i5 + i8; t6 = i3 + i6 + i9; dr = (t3 - t1) / 6; dc = (t6 - t4) / 6; drr = (t1 - 2 * t2 + t3) / 6; dcc = (t4 - 2 * t5 + t6) / 6; drc = (i1 - i3 - i7 + i9) / 4; std::vector<std::vector<float>> eigenvalvect = compute_eigenvals(2 * drr, drc, 2 * dcc); val = -eigenvalvect[0][0]; if (val > 0.0) { n1 = eigenvalvect[1][0]; // igenvector coordinate y n2 = eigenvalvect[1][1]; // eigenvector coordinate x a = 2.0 * (drr * n1 * n1 + drc * n1 * n2 + dcc * n2 * n2); b = dr * n1 + dc * n2; if (a == 0.0) continue; t = (-1) * b / a; p1 = t * n1; p2 = t * n2; if (abs(p1) <= 0.5 && abs(p2) <= 0.5) { /* * Project the maximum point position perpendicularly onto the search line. */ a = 1; b = nx * (px - (r + dir * line[k].x() + p1)) + ny * (py - (c + dir * line[k].y() + p2)); if (a == 0.0) continue; t = (-1) * b / a; d = (-i1 + 2 * i2 - i3 + 2 * i4 + 5 * i5 + 2 * i6 - i7 + 2 * i8 - i9) / 9; if (dir == 1) { grad_r[j] = d + p1 * dr + p2 * dc + p1 * p1 * drr + p1 * p2 * drc + p2 * p2 * dcc; width_r[j] = abs(t); } else { grad_l[j] = d + p1 * dr + p2 * dc + p1 * p1 * drr + p1 * p2 * drc + p2 * p2 * dcc; width_l[j] = abs(t); } break; } } } } } // fix_locations(width_l, width_r, grad_l, grad_r, pos_x, pos_y, correct, contrast, asymm, sigma, mode, // correct_pos, cont); } } /* * Fill gaps in the arrays master, slave1, and slave2, i.e., points where * master=0, by interpolation (interior points) or extrapolation (end points). * The array master will usually be the width of the line, while slave1 and * slave2 will be values that depend on master[i] being 0, e.g., the gradient at * each line point. The arrays slave1 and slave2 can be NULL. */ void link::fill_gaps(std::vector<float>& master, std::vector<float>& slave1, std::vector<float>& slave2, contour& cont){ int i, j, k, s, e; int num_points; float m_s, m_e, s1_s, s1_e, s2_s, s2_e, d_r, d_c, arc_len, len; num_points = cont.num; for (i = 0; i < num_points; i++) { if (master[i] == 0) { for (j = i + 1; j < num_points; j++) { if (master[j] > 0) break; } m_s = 0; m_e = 0; s1_s = 0; s1_e = 0; s2_s = 0; s2_e = 0; if (i > 0 && j < num_points - 1) { s = i; e = j - 1; m_s = master[(s - 1)]; m_e = master[(e + 1)]; if (!slave1.empty()) { s1_s = slave1[(s - 1)]; s1_e = slave1[(e + 1)]; } if (!slave2.empty()) { s2_s = slave2[(s - 1)]; s2_e = slave2[(e + 1)]; } } else if (i > 0) { s = i; e = num_points - 2; m_s = master[(s - 1)]; m_e = master[(s - 1)]; master[(e + 1)] = m_e; if (!slave1.empty()) { s1_s = slave1[(s - 1)]; s1_e = slave1[(s - 1)]; slave1[(e + 1)] = s1_e; } if (!slave2.empty()) { s2_s = slave2[(s - 1)]; s2_e = slave2[(s - 1)]; slave2[(e + 1)] = s2_e; } } else if (j < num_points - 1) { s = 1; e = j - 1; m_s = master[(e + 1)]; m_e = master[(e + 1)]; master[(s - 1)] = m_s; if (!slave1.empty()) { s1_s = slave1[(e + 1)]; s1_e = slave1[(e + 1)]; slave1[(s - 1)] = s1_s; } if (!slave2.empty()) { s2_s = slave2[(e + 1)]; s2_e = slave2[(e + 1)]; slave2[(s - 1)] = s2_s; } } else { s = 1; e = num_points - 2; m_s = master[(s - 1)]; m_e = master[(e + 1)]; if (!slave1.empty()) { s1_s = slave1[(s - 1)]; s1_e = slave1[(e + 1)]; } if (!slave2.empty()) { s2_s = slave2[(s - 1)]; s2_e = slave2[(e + 1)]; } } arc_len = 0; for (k = s; k <= e + 1; k++) { d_r = cont.row[k] - cont.row[(k - 1)]; d_c = cont.col[k] - cont.col[(k - 1)]; arc_len += sqrt(d_r * d_r + d_c * d_c); } len = 0; for (k = s; k <= e; k++) { d_r = cont.row[k] - cont.row[(k - 1)]; d_c = cont.col[k] - cont.col[(k - 1)]; len += sqrt(d_r * d_r + d_c * d_c); master[k] = (arc_len - len) / arc_len * m_s + len / arc_len * m_e; if (!slave1.empty()) slave1[k] = (arc_len - len) / arc_len * s1_s + len / arc_len * s1_e; if (!slave2.empty()) slave2[k] = (arc_len - len) / arc_len * s2_s + len / arc_len * s2_e; } i = j; } } } /* * Correct the extracted line positions and widths. The algorithm first closes * gaps in the extracted data width_l, width_r, grad_l, and grad_r to provide * meaningful input over the whole line. Then the correction is calculated. * After this, gaps that have been introduced by the width correction are again * closed. Finally, the position correction is applied if correct_pos is set. * The results are returned in width_l, width_r, and cont. */ void link::fix_locations(std::vector<float>& width_l, std::vector<float>& width_r, std::vector<float>& grad_l, std::vector<float>& grad_r, std::vector<float>& pos_x, std::vector<float>& pos_y, std::vector<float>& correction, std::vector<float>& contr, std::vector<float>& asymm, bool correct_pos, contour& cont) { #if 0 int i; int num_points; double px, py; double nx, ny; double w_est, r_est; MutableDouble w_real, h_real, corr; w_real = new MutableDouble(); h_real = new MutableDouble(); corr = new MutableDouble(); MutableDouble w_strong = new MutableDouble(); MutableDouble w_weak = new MutableDouble(); double correct, asymmetry, response, width, contrast; bool weak_is_r; bool correct_start, correct_end; Convol convol = new Convol(); fill_gaps(width_l, grad_l, null, cont); fill_gaps(width_r, grad_r, null, cont); num_points = cont.num; /* Calculate true line width, asymmetry, and position correction. */ if (correct_pos) { /* * Do not correct the position of a junction point if its width is found by * interpolation, i.e., if the position could be corrected differently for each * junction point, thereby destroying the junction. */ correct_start = ((cont.cont_class == contour_class::cont_no_junc || cont.cont_class == contour_class::cont_end_junc || cont.cont_class == contour_class::cont_closed) && (width_r[0] > 0 && width_l[0] > 0)); correct_end = ((cont.cont_class == contour_class::cont_no_junc || cont.cont_class == contour_class::cont_start_junc || cont.cont_class == contour_class::cont_closed) && (width_r[(num_points - 1)] > 0 && width_l[(num_points - 1)] > 0)); /* * Calculate the true width and assymetry, and its corresponding correction for * each line point. */ for (i = 0; i < num_points; i++) { if (width_r[i] > 0 && width_l[i] > 0) { w_est = (width_r[i] + width_l[i]) * LINE_WIDTH_COMPENSATION; if (grad_r[i] <= grad_l[i]) { r_est = grad_r[i] / grad_l[i]; weak_is_r = true; } else { r_est = grad_l[i] / grad_r[i]; weak_is_r = false; } Correct.line_corrections(sigma, w_est, r_est, w_real, h_real, corr, w_strong, w_weak); w_real.setValue(w_real.getValue() / LINE_WIDTH_COMPENSATION); corr.setValue(corr.getValue() / LINE_WIDTH_COMPENSATION); width_r[i] = w_real.getValue(); width_l[i] = w_real.getValue(); if (weak_is_r) { asymm[i] = h_real.getValue(); correction[i] = -corr.getValue(); } else { asymm[i] = -h_real.getValue(); correction[i] = corr.getValue(); } } } fill_gaps(width_l, correction, asymm, cont); for (i = 0; i < num_points; i++) width_r[i] = width_l[i]; /* Adapt the correction for junction points if necessary. */ if (!correct_start) correction[0] = 0; if (!correct_end) correction[(num_points - 1)] = 0; for (i = 0; i < num_points; i++) { px = pos_x[i]; py = pos_y[i]; nx = Math.cos(cont.angle[i]); ny = Math.sin(cont.angle[i]); px = px + correction[i] * nx; py = py + correction[i] * ny; pos_x[i] = px; pos_y[i] = py; } } /* Update the position of a line and add the extracted width. */ cont.width_l = new float[num_points]; cont.width_r = new float[num_points]; for (i = 0; i < num_points; i++) { cont.width_l[i] = (float)width_l[i]; cont.width_r[i] = (float)width_r[i]; cont.row[i] = (float)pos_x[i]; cont.col[i] = (float)pos_y[i]; } /* Now calculate the true contrast. */ if (correct_pos) { cont.asymmetry = new float[num_points]; cont.intensity = new float[num_points]; for (i = 0; i < num_points; i++) { response = cont.response[i]; asymmetry = Math.abs(asymm[i]); correct = Math.abs(correction[i]); width = cont.width_l[i]; if (width < MIN_LINE_WIDTH) contrast = 0; else contrast = (response / Math.abs(convol.phi2(correct + width, sigma) + (asymmetry - 1) * convol.phi2(correct - width, sigma))); if (contrast > MAX_CONTRAST) contrast = 0; contr[i] = contrast; } fill_gaps(contr, null, null, cont); for (i = 0; i < num_points; i++) { cont.asymmetry[i] = (float)asymm[i]; if (mode == MODE_LIGHT) cont.intensity[i] = (float)contr[i]; else cont.intensity[i] = (float)-contr[i]; } } #endif }
29.153285
165
0.565098
[ "vector", "model" ]
a91c5dfc8d59167ce2eef8635417882750ec9557
3,795
cc
C++
onnxruntime/core/providers/dnnl/subgraph/dnnl_batchnorm.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
6,036
2019-05-07T06:03:57.000Z
2022-03-31T17:59:54.000Z
onnxruntime/core/providers/dnnl/subgraph/dnnl_batchnorm.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
5,730
2019-05-06T23:04:55.000Z
2022-03-31T23:55:56.000Z
onnxruntime/core/providers/dnnl/subgraph/dnnl_batchnorm.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
1,566
2019-05-07T01:30:07.000Z
2022-03-31T17:06:50.000Z
// Copyright(C) 2021 Intel Corporation // Licensed under the MIT License #include "dnnl_batchnorm.h" #include "dnnl_subgraph.h" #include "dnnl_subgraph_primitive.h" namespace onnxruntime { namespace ort_dnnl { DnnlBatchNorm::DnnlBatchNorm() {} void DnnlBatchNorm::CreatePrimitive(DnnlSubgraphPrimitive& sp, DnnlNode& node) { using namespace dnnl; // get the engine, currently only support either single gpu or single cpu device auto dnnl_engine = sp.GetEngine(); auto epsilon = ReadEpsilon(node); auto batchnorm_src_mem = sp.GetMemory(node.Input(IN_X)); auto src_md = batchnorm_src_mem.get_desc(); auto batchnorm_scale_mem = sp.GetMemory(node.Input(IN_SCALE)); auto scale_md = batchnorm_scale_mem.get_desc(); auto scale_dims = scale_md.dims(); auto batchnorm_bias_mem = sp.GetMemory(node.Input(IN_B)); auto bias_md = batchnorm_bias_mem.get_desc(); auto batchnorm_mean_mem = sp.GetMemory(node.Input(IN_MEAN)); auto mean_md = batchnorm_mean_mem.get_desc(); auto batchnorm_var_mem = sp.GetMemory(node.Input(IN_VAR)); auto var_md = batchnorm_var_mem.get_desc(); std::vector<memory::desc> src_mds; src_mds.push_back(scale_md); src_mds.push_back(bias_md); const int axis = 0; //To make the inputs compatible with OneDNN, we need to concatenate scale and bias into a single tensor of length 2XC //Then, we create the batchnorm pd and feed in the inputs. auto concat_pd = dnnl::concat::primitive_desc(axis, src_mds, dnnl_engine); //If using GPU this will move the memory from the CPU to the GPU. batchnorm_scale_mem = sp.GetMemoryAndReshape(node.Input(IN_SCALE), concat_pd.src_desc(), dnnl_engine); batchnorm_bias_mem = sp.GetMemoryAndReshape(node.Input(IN_B), concat_pd.src_desc(), dnnl_engine); batchnorm_mean_mem = sp.GetMemoryAndReshape(node.Input(IN_MEAN), mean_md, dnnl_engine); batchnorm_var_mem = sp.GetMemoryAndReshape(node.Input(IN_VAR), var_md, dnnl_engine); auto batchnorm_scale_shift_mem = dnnl::memory(concat_pd.dst_desc(), dnnl_engine); auto batchnorm_desc = dnnl::batch_normalization_forward::desc(dnnl::prop_kind::forward_inference, src_md, epsilon, dnnl::normalization_flags::use_scale_shift | dnnl::normalization_flags::use_global_stats); auto batchnorm_pd = dnnl::batch_normalization_forward::primitive_desc(batchnorm_desc, dnnl_engine); // If using GPU this will move the memory from the CPU to the GPU. batchnorm_src_mem = sp.GetMemoryAndReshape(node.Input(IN_X), batchnorm_pd.src_desc(), dnnl_engine); auto batchnorm_dst_mem = dnnl::memory(batchnorm_pd.dst_desc(), dnnl_engine); auto concat_op = dnnl::concat(concat_pd); sp.AddPrimitive(concat_op, {{DNNL_ARG_MULTIPLE_SRC, batchnorm_scale_mem}, {DNNL_ARG_MULTIPLE_SRC+1, batchnorm_bias_mem}, {DNNL_ARG_DST, batchnorm_scale_shift_mem}}); auto batchnorm_op = dnnl::batch_normalization_forward(batchnorm_pd); sp.AddPrimitive(batchnorm_op, {{DNNL_ARG_SRC, batchnorm_src_mem}, {DNNL_ARG_MEAN, batchnorm_mean_mem}, {DNNL_ARG_VARIANCE, batchnorm_var_mem}, {DNNL_ARG_SCALE_SHIFT, batchnorm_scale_shift_mem}, {DNNL_ARG_DST, batchnorm_dst_mem}}); sp.SetMemory(node.Output(OUT_Y), batchnorm_dst_mem); } float DnnlBatchNorm::ReadEpsilon(DnnlNode& node) { auto attr = node.Attributes().find("epsilon"); float epsilon = 1e-05f; //Default value according to ONNX spec if (attr != node.Attributes().end() && attr->second().type() == ::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_FLOAT) { epsilon = attr->second().f(); } return epsilon; } } // namespace ort_dnnl } // namespace onnxruntime
40.806452
119
0.730171
[ "vector" ]
a91d1292ff0ad83d7112f2ba3014aff34edf586a
28,718
cc
C++
wrappers/7.0.0/vtkDendrogramItemWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkDendrogramItemWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkDendrogramItemWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkContextItemWrap.h" #include "vtkDendrogramItemWrap.h" #include "vtkObjectWrap.h" #include "vtkTreeWrap.h" #include "vtkContext2DWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkDendrogramItemWrap::ptpl; VtkDendrogramItemWrap::VtkDendrogramItemWrap() { } VtkDendrogramItemWrap::VtkDendrogramItemWrap(vtkSmartPointer<vtkDendrogramItem> _native) { native = _native; } VtkDendrogramItemWrap::~VtkDendrogramItemWrap() { } void VtkDendrogramItemWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkDendrogramItem").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("DendrogramItem").ToLocalChecked(), ConstructorGetter); } void VtkDendrogramItemWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkDendrogramItemWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkContextItemWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkContextItemWrap::ptpl)); tpl->SetClassName(Nan::New("VtkDendrogramItemWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "CollapseToNumberOfLeafNodes", CollapseToNumberOfLeafNodes); Nan::SetPrototypeMethod(tpl, "collapseToNumberOfLeafNodes", CollapseToNumberOfLeafNodes); Nan::SetPrototypeMethod(tpl, "ComputeLabelWidth", ComputeLabelWidth); Nan::SetPrototypeMethod(tpl, "computeLabelWidth", ComputeLabelWidth); Nan::SetPrototypeMethod(tpl, "DisplayNumberOfCollapsedLeafNodesOff", DisplayNumberOfCollapsedLeafNodesOff); Nan::SetPrototypeMethod(tpl, "displayNumberOfCollapsedLeafNodesOff", DisplayNumberOfCollapsedLeafNodesOff); Nan::SetPrototypeMethod(tpl, "DisplayNumberOfCollapsedLeafNodesOn", DisplayNumberOfCollapsedLeafNodesOn); Nan::SetPrototypeMethod(tpl, "displayNumberOfCollapsedLeafNodesOn", DisplayNumberOfCollapsedLeafNodesOn); Nan::SetPrototypeMethod(tpl, "DrawLabelsOff", DrawLabelsOff); Nan::SetPrototypeMethod(tpl, "drawLabelsOff", DrawLabelsOff); Nan::SetPrototypeMethod(tpl, "DrawLabelsOn", DrawLabelsOn); Nan::SetPrototypeMethod(tpl, "drawLabelsOn", DrawLabelsOn); Nan::SetPrototypeMethod(tpl, "ExtendLeafNodesOff", ExtendLeafNodesOff); Nan::SetPrototypeMethod(tpl, "extendLeafNodesOff", ExtendLeafNodesOff); Nan::SetPrototypeMethod(tpl, "ExtendLeafNodesOn", ExtendLeafNodesOn); Nan::SetPrototypeMethod(tpl, "extendLeafNodesOn", ExtendLeafNodesOn); Nan::SetPrototypeMethod(tpl, "GetAngleForOrientation", GetAngleForOrientation); Nan::SetPrototypeMethod(tpl, "getAngleForOrientation", GetAngleForOrientation); Nan::SetPrototypeMethod(tpl, "GetBounds", GetBounds); Nan::SetPrototypeMethod(tpl, "getBounds", GetBounds); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetDisplayNumberOfCollapsedLeafNodes", GetDisplayNumberOfCollapsedLeafNodes); Nan::SetPrototypeMethod(tpl, "getDisplayNumberOfCollapsedLeafNodes", GetDisplayNumberOfCollapsedLeafNodes); Nan::SetPrototypeMethod(tpl, "GetDrawLabels", GetDrawLabels); Nan::SetPrototypeMethod(tpl, "getDrawLabels", GetDrawLabels); Nan::SetPrototypeMethod(tpl, "GetExtendLeafNodes", GetExtendLeafNodes); Nan::SetPrototypeMethod(tpl, "getExtendLeafNodes", GetExtendLeafNodes); Nan::SetPrototypeMethod(tpl, "GetLabelWidth", GetLabelWidth); Nan::SetPrototypeMethod(tpl, "getLabelWidth", GetLabelWidth); Nan::SetPrototypeMethod(tpl, "GetLeafSpacing", GetLeafSpacing); Nan::SetPrototypeMethod(tpl, "getLeafSpacing", GetLeafSpacing); Nan::SetPrototypeMethod(tpl, "GetLineWidth", GetLineWidth); Nan::SetPrototypeMethod(tpl, "getLineWidth", GetLineWidth); Nan::SetPrototypeMethod(tpl, "GetOrientation", GetOrientation); Nan::SetPrototypeMethod(tpl, "getOrientation", GetOrientation); Nan::SetPrototypeMethod(tpl, "GetPosition", GetPosition); Nan::SetPrototypeMethod(tpl, "getPosition", GetPosition); Nan::SetPrototypeMethod(tpl, "GetPrunedTree", GetPrunedTree); Nan::SetPrototypeMethod(tpl, "getPrunedTree", GetPrunedTree); Nan::SetPrototypeMethod(tpl, "GetTextAngleForOrientation", GetTextAngleForOrientation); Nan::SetPrototypeMethod(tpl, "getTextAngleForOrientation", GetTextAngleForOrientation); Nan::SetPrototypeMethod(tpl, "GetTree", GetTree); Nan::SetPrototypeMethod(tpl, "getTree", GetTree); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "Paint", Paint); Nan::SetPrototypeMethod(tpl, "paint", Paint); Nan::SetPrototypeMethod(tpl, "PrepareToPaint", PrepareToPaint); Nan::SetPrototypeMethod(tpl, "prepareToPaint", PrepareToPaint); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetColorArray", SetColorArray); Nan::SetPrototypeMethod(tpl, "setColorArray", SetColorArray); Nan::SetPrototypeMethod(tpl, "SetDisplayNumberOfCollapsedLeafNodes", SetDisplayNumberOfCollapsedLeafNodes); Nan::SetPrototypeMethod(tpl, "setDisplayNumberOfCollapsedLeafNodes", SetDisplayNumberOfCollapsedLeafNodes); Nan::SetPrototypeMethod(tpl, "SetDrawLabels", SetDrawLabels); Nan::SetPrototypeMethod(tpl, "setDrawLabels", SetDrawLabels); Nan::SetPrototypeMethod(tpl, "SetExtendLeafNodes", SetExtendLeafNodes); Nan::SetPrototypeMethod(tpl, "setExtendLeafNodes", SetExtendLeafNodes); Nan::SetPrototypeMethod(tpl, "SetLeafSpacing", SetLeafSpacing); Nan::SetPrototypeMethod(tpl, "setLeafSpacing", SetLeafSpacing); Nan::SetPrototypeMethod(tpl, "SetLineWidth", SetLineWidth); Nan::SetPrototypeMethod(tpl, "setLineWidth", SetLineWidth); Nan::SetPrototypeMethod(tpl, "SetOrientation", SetOrientation); Nan::SetPrototypeMethod(tpl, "setOrientation", SetOrientation); Nan::SetPrototypeMethod(tpl, "SetPosition", SetPosition); Nan::SetPrototypeMethod(tpl, "setPosition", SetPosition); Nan::SetPrototypeMethod(tpl, "SetTree", SetTree); Nan::SetPrototypeMethod(tpl, "setTree", SetTree); #ifdef VTK_NODE_PLUS_VTKDENDROGRAMITEMWRAP_INITPTPL VTK_NODE_PLUS_VTKDENDROGRAMITEMWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkDendrogramItemWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkDendrogramItem> native = vtkSmartPointer<vtkDendrogramItem>::New(); VtkDendrogramItemWrap* obj = new VtkDendrogramItemWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkDendrogramItemWrap::CollapseToNumberOfLeafNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsUint32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->CollapseToNumberOfLeafNodes( info[0]->Uint32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::ComputeLabelWidth(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContext2DWrap::ptpl))->HasInstance(info[0])) { VtkContext2DWrap *a0 = ObjectWrap::Unwrap<VtkContext2DWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->ComputeLabelWidth( (vtkContext2D *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::DisplayNumberOfCollapsedLeafNodesOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DisplayNumberOfCollapsedLeafNodesOff(); } void VtkDendrogramItemWrap::DisplayNumberOfCollapsedLeafNodesOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DisplayNumberOfCollapsedLeafNodesOn(); } void VtkDendrogramItemWrap::DrawLabelsOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DrawLabelsOff(); } void VtkDendrogramItemWrap::DrawLabelsOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DrawLabelsOn(); } void VtkDendrogramItemWrap::ExtendLeafNodesOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ExtendLeafNodesOff(); } void VtkDendrogramItemWrap::ExtendLeafNodesOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ExtendLeafNodesOn(); } void VtkDendrogramItemWrap::GetAngleForOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { double r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetAngleForOrientation( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::GetBounds(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetBounds( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[4]; if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 4; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetBounds( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkDendrogramItemWrap::GetDisplayNumberOfCollapsedLeafNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDisplayNumberOfCollapsedLeafNodes(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetDrawLabels(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDrawLabels(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetExtendLeafNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetExtendLeafNodes(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetLabelWidth(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); float r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLabelWidth(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetLeafSpacing(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLeafSpacing(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetLineWidth(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); float r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLineWidth(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOrientation(); info.GetReturnValue().Set(Nan::New(r)); } void VtkDendrogramItemWrap::GetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); float const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetPosition(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 2 * sizeof(float)); Local<v8::Float32Array> at = v8::Float32Array::New(ab, 0, 2); memcpy(ab->GetContents().Data(), r, 2 * sizeof(float)); info.GetReturnValue().Set(at); } void VtkDendrogramItemWrap::GetPrunedTree(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); vtkTree * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetPrunedTree(); VtkTreeWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkTreeWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkTreeWrap *w = new VtkTreeWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkDendrogramItemWrap::GetTextAngleForOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { double r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTextAngleForOrientation( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::GetTree(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); vtkTree * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTree(); VtkTreeWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkTreeWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkTreeWrap *w = new VtkTreeWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkDendrogramItemWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); vtkDendrogramItem * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkDendrogramItemWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDendrogramItemWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDendrogramItemWrap *w = new VtkDendrogramItemWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkDendrogramItemWrap::Paint(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContext2DWrap::ptpl))->HasInstance(info[0])) { VtkContext2DWrap *a0 = ObjectWrap::Unwrap<VtkContext2DWrap>(info[0]->ToObject()); bool r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->Paint( (vtkContext2D *) a0->native.GetPointer() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::PrepareToPaint(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContext2DWrap::ptpl))->HasInstance(info[0])) { VtkContext2DWrap *a0 = ObjectWrap::Unwrap<VtkContext2DWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->PrepareToPaint( (vtkContext2D *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkDendrogramItem * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkDendrogramItemWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDendrogramItemWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDendrogramItemWrap *w = new VtkDendrogramItemWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetColorArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColorArray( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetDisplayNumberOfCollapsedLeafNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetDisplayNumberOfCollapsedLeafNodes( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetDrawLabels(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetDrawLabels( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetExtendLeafNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetExtendLeafNodes( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetLeafSpacing(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetLeafSpacing( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetLineWidth(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetLineWidth( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOrientation( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat32Array()) { v8::Local<v8::Float32Array>a0(v8::Local<v8::Float32Array>::Cast(info[0]->ToObject())); if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPosition( (float *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); float b0[2]; if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 2; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPosition( b0 ); return; } else if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() > 1 && info[1]->IsNumber()) { if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetPosition( info[0]->NumberValue(), info[1]->NumberValue() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkDendrogramItemWrap::SetTree(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkDendrogramItemWrap *wrapper = ObjectWrap::Unwrap<VtkDendrogramItemWrap>(info.Holder()); vtkDendrogramItem *native = (vtkDendrogramItem *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTreeWrap::ptpl))->HasInstance(info[0])) { VtkTreeWrap *a0 = ObjectWrap::Unwrap<VtkTreeWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTree( (vtkTree *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); }
31.215217
114
0.723658
[ "object" ]
a91db0920d33815d20e0fff3df2cc78981387eba
1,506
cpp
C++
contests/codechef/cookoff126b/Prime_Tuples.cpp
Mukul-dhiman/competitive_practice
3ffa5ee05fa0ba6e7a8c7b35bbe16a82f925c23c
[ "MIT" ]
1
2021-01-30T18:32:56.000Z
2021-01-30T18:32:56.000Z
contests/codechef/cookoff126b/Prime_Tuples.cpp
Mukul-dhiman/compitative_practice
3ffa5ee05fa0ba6e7a8c7b35bbe16a82f925c23c
[ "MIT" ]
1
2021-01-30T21:54:21.000Z
2021-01-30T21:54:21.000Z
contests/codechef/cookoff126b/Prime_Tuples.cpp
Mukul-dhiman/compitative_practice
3ffa5ee05fa0ba6e7a8c7b35bbe16a82f925c23c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; #define FAST_IO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define endl "\n" #define pb push_back #define loop(i,n) for(int i=0;i<n;i++) #define iloop(a,i,n) for(int i=a;i<=n;i++) #define bug(i) cout<<"debug at:"<<__LINE__<<" "<<i<<endl #define out(i) cout<<i<<endl #define mod 1000000007 //10e9+7 int ans[1000001]={0}; void SieveOfEratosthenes(int n){ bool prime[n + 1]; memset(prime, true, sizeof(prime)); vector<int> primev; for (int p = 2; p * p <= n; p++){ if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for(int i=2;i<=n;i++){ if(prime[i]){ primev.pb(i); } } // cout<<primev.size()<<endl; int sz=primev.size(); for(int i=0;i<sz;i++){ if(primev[i]+2<=n){ if(prime[primev[i]+2]){ ans[primev[i]+2]+=1; } } } for(int i=1;i<=n;i++){ ans[i]+=ans[i-1]; } } void pre(){ FAST_IO; //code for pre celculations SieveOfEratosthenes(1000000); } void solve(){ int n; cin>>n; out(ans[n]); return; } void test(){ int t; cin>>t; iloop(1,i,t){ // cout<<"Case #"<<i<<": "; solve(); } return; } int main(){ // std::cout << std::fixed; // std::cout << std::setprecision(10); pre(); test(); // solve(); return 0; }
21.211268
78
0.492032
[ "vector" ]
a91dcaf0f3ca585a8382639cd8c2b2a90663e6b9
688
cpp
C++
cpp/tests/LetterCombinationsOfAPhoneNumberTest.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
4
2018-03-05T02:27:16.000Z
2021-03-15T14:19:44.000Z
cpp/tests/LetterCombinationsOfAPhoneNumberTest.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
null
null
null
cpp/tests/LetterCombinationsOfAPhoneNumberTest.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
2
2018-07-22T10:32:10.000Z
2018-10-20T03:14:28.000Z
#include "LetterCombinationsOfAPhoneNumber.h" #include "gtest/gtest.h" using namespace lcpp; TEST(LetterCombinationsOfAPhoneNumber, Solution17_1) { auto S17_1 = Solution17_1(); std::string Digits1 = "23"; std::vector<std::string> const Expected1{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}; EXPECT_EQ(Expected1, S17_1.letterCombinations(Digits1)); std::string Digits2; std::vector<std::string> const Expected2; EXPECT_EQ(Expected2, S17_1.letterCombinations(Digits2)); std::string Digits3 = "2"; std::vector<std::string> const Expected3{"a", "b", "c"}; EXPECT_EQ(Expected3, S17_1.letterCombinations(Digits3)); }
32.761905
72
0.664244
[ "vector" ]
a91f6534ffa1f8022e2005cc83255d306adf77c1
3,775
cc
C++
lite/tests/kernels/softmax_compute_test.cc
jameswu2014/Paddle-Lite
827e349ac8eb769a873fe9b3aa961af8b8b20a96
[ "Apache-2.0" ]
1
2020-03-09T03:51:31.000Z
2020-03-09T03:51:31.000Z
lite/tests/kernels/softmax_compute_test.cc
jameswu2014/Paddle-Lite
827e349ac8eb769a873fe9b3aa961af8b8b20a96
[ "Apache-2.0" ]
null
null
null
lite/tests/kernels/softmax_compute_test.cc
jameswu2014/Paddle-Lite
827e349ac8eb769a873fe9b3aa961af8b8b20a96
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include "lite/api/paddle_use_kernels.h" #include "lite/api/paddle_use_ops.h" #include "lite/core/arena/framework.h" #include "lite/tests/utils/fill_data.h" namespace paddle { namespace lite { class SoftmaxComputeTest : public arena::TestCase { protected: // common attributes for this op. std::string op_type_ = "softmax"; DDim x_dims_{{1, 2, 3, 4}}; std::string x_ = "x"; std::string out_ = "out"; int axis_ = 1; public: SoftmaxComputeTest(const Place& place, const std::string& alias, DDim x_dims, int axis) : TestCase(place, alias), x_dims_(x_dims), axis_(axis) {} void RunBaseline(Scope* scope) override { auto x = scope->FindTensor(x_); auto out = scope->NewTensor(out_); CHECK(out); out->Resize(x_dims_); auto x_data = x->data<float>(); auto out_data = out->mutable_data<float>(); auto x_rank = x_dims_.size(); if (axis_ < 0) { axis_ += x_rank; } int axis_size = x_dims_[axis_]; int outer_num = x_dims_.Slice(0, axis_).production(); int inner_num = x_dims_.Slice(axis_ + 1, x_rank).production(); int compute_size = outer_num * inner_num; for (int i = 0; i < compute_size; i++) { int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int start = idx_outer * inner_num + idx_inner; int offset; offset = start; float max_data = std::numeric_limits<float>::lowest(); for (int j = 0; j < axis_size; j++) { max_data = x_data[offset] > max_data ? x_data[offset] : max_data; offset += inner_num; } offset = start; float sum_data = 0.f; for (int j = 0; j < axis_size; j++) { out_data[offset] = exp(x_data[offset] - max_data); sum_data += out_data[offset]; offset += inner_num; } offset = start; for (int j = 0; j < axis_size; j++) { out_data[offset] /= sum_data; offset += inner_num; } } } void PrepareOpDesc(cpp::OpDesc* op_desc) { op_desc->SetType(op_type_); op_desc->SetInput("X", {x_}); op_desc->SetOutput("Out", {out_}); op_desc->SetAttr("axis", axis_); } void PrepareData() override { std::vector<float> x(x_dims_.production()); fill_data_rand(x.data(), -1.f, 1.f, x_dims_.production()); SetCommonTensor(x_, x_dims_, x.data()); } }; TEST(Softmax, precision) { LOG(INFO) << "test softmax op"; float abs_error = 2e-5; Place place; #if defined(LITE_WITH_NPU) place = TARGET(kNPU); abs_error = 4e-3; // Using fp16 in NPU #elif defined(LITE_WITH_XPU) place = TARGET(kXPU); #else return; #endif for (auto x_dims : std::vector<std::vector<int64_t>>{{1, 2, 3, 4}, {2, 3, 4}, {3, 4}}) { for (auto axis : {-1, 0, 1, 2, 3}) { if (axis >= x_dims.size()) continue; std::unique_ptr<arena::TestCase> tester( new SoftmaxComputeTest(place, "def", DDim(x_dims), axis)); arena::Arena arena(std::move(tester), place, abs_error); arena.TestPrecision(); } } } } // namespace lite } // namespace paddle
29.960317
76
0.624371
[ "vector" ]
a92f816cded4b57f893efdd5990f2a3bfb4fe181
1,572
cc
C++
examples/pxScene2d/external/spark-webgl/src/nexus/gles2nexusimpl.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
46
2017-09-07T14:59:22.000Z
2020-10-31T20:34:12.000Z
examples/pxScene2d/external/spark-webgl/src/nexus/gles2nexusimpl.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/spark-webgl/src/nexus/gles2nexusimpl.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
#include <cstring> #include <vector> #include <iostream> #include <cstdlib> #include "../gles2impl.h" #include "Nexus.h" using namespace std; namespace gles2impl { BCMNexus::EGLTarget *eglTarget; string init(int width, int height, bool fullscreen, std::string title) { cout << "initializing BCM NEXUS & EGL" << endl; eglTarget = new BCMNexus::EGLTarget(BCMNexus::Backend::getInstance(), width, height, fullscreen, title); std::string result = eglTarget->constructTarget(); // This comment is taken from webkit // EGL registers atexit handlers to cleanup its global display list. // Since the global EGLTarget instance is created before, // when the EGLTarget destructor is called, EGL has already removed the // display from the list, causing eglTerminate() to crash. So, here we register // our own atexit handler, after EGL has been initialized and after the global // instance has been created to ensure we call eglTerminate() before the other // EGL atexit handlers and the EGLTarget destructor. std::atexit(cleanup); return result; } void nextFrame(bool swapBuffers) { if ((eglTarget != nullptr) && swapBuffers == true) { eglTarget->swapBuffer(); } } void cleanup() { cout << "Destroy EGL target" << endl; if (eglTarget != nullptr) { eglTarget->destroyTarget(); delete eglTarget; eglTarget = nullptr; } } } // end namespace gles2impl
30.230769
112
0.636132
[ "vector" ]
a93313b0c3fa753e69e7e994565385e20941047e
8,860
cpp
C++
nntrainer/src/layer.cpp
kparichay/nntrainer
79e37918a3ced623346e285993d6714cb5d1e14b
[ "Apache-2.0" ]
null
null
null
nntrainer/src/layer.cpp
kparichay/nntrainer
79e37918a3ced623346e285993d6714cb5d1e14b
[ "Apache-2.0" ]
null
null
null
nntrainer/src/layer.cpp
kparichay/nntrainer
79e37918a3ced623346e285993d6714cb5d1e14b
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2019 Samsung Electronics Co., Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * @file layer.cpp * @date 04 December 2019 * @brief This is Layers Classes for Neural Network * @see https://github.com/nnstreamer/nntrainer * @author Jijoong Moon <jijoong.moon@samsung.com> * @bug No known bugs except for NYI items * */ #include <layer.h> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <parse_util.h> #include <util_func.h> namespace nntrainer { int Layer::setActivation(ActiType acti) { int status = ML_ERROR_NONE; if (acti == ACT_UNKNOWN) { ml_loge("Error:have to specify activation function"); return ML_ERROR_INVALID_PARAMETER; } activation_type = acti; return status; } int Layer::setOptimizer(Optimizer &opt) { this->opt.setType(opt.getType()); this->opt.setOptParam(opt.getOptParam()); return this->opt.initialize(params, param_size, true); } int Layer::checkValidation() { int status = ML_ERROR_NONE; if (type == LAYER_UNKNOWN) { ml_loge("Error: Layer type is unknown"); return ML_ERROR_INVALID_PARAMETER; } if (activation_type == ACT_UNKNOWN) { ml_loge("Error: Have to set activation for this layer"); return ML_ERROR_INVALID_PARAMETER; } return status; } void Layer::copy(std::shared_ptr<Layer> l) { setParamSize(l->param_size); for (unsigned int i = 0; i < l->param_size; ++i) { paramsAt(i) = l->paramsAt(i); } } void Layer::read(std::ifstream &file) { for (unsigned int i = 0; i < param_size; ++i) { paramsAt(i).weight.read(file); } } void Layer::save(std::ofstream &file) { for (unsigned int i = 0; i < param_size; ++i) { paramsAt(i).weight.save(file); } } Tensor Layer::initializeWeight(const TensorDim &w_dim, WeightInitializer initializer, int &status) { Tensor w = Tensor(w_dim); if (initializer == WEIGHT_UNKNOWN) { ml_logw("Warning: Weight Initalization Type is not set. " "WEIGHT_XAVIER_NORMAL is used by default"); initializer = WEIGHT_XAVIER_NORMAL; } switch (initializer) { case WEIGHT_ZEROS: w.setZero(); break; case WEIGHT_ONES: w.setValue(1.0f); break; case WEIGHT_LECUN_NORMAL: w.setRandNormal(0.0f, sqrt(1.0f / w_dim.height())); break; case WEIGHT_XAVIER_NORMAL: w.setRandNormal(0.0f, sqrt(2.0f / (w_dim.width() + w_dim.height()))); break; case WEIGHT_HE_NORMAL: w.setRandNormal(0.0f, sqrt(2.0f / (w_dim.height()))); break; case WEIGHT_LECUN_UNIFORM: w.setRandUniform(-1.0f * sqrt(1.0f / w_dim.height()), sqrt(1.0f / w_dim.height())); break; case WEIGHT_XAVIER_UNIFORM: w.setRandUniform(-1.0f * sqrt(6.0f / (w_dim.height() + w_dim.width())), sqrt(6.0 / (w_dim.height() + w_dim.width()))); break; case WEIGHT_HE_UNIFORM: w.setRandUniform(-1.0f * sqrt(6.0f / (w_dim.height())), sqrt(6.0 / (w_dim.height()))); break; default: break; } return w; } int Layer::setProperty(std::vector<std::string> values) { int status = ML_ERROR_NONE; for (unsigned int i = 0; i < values.size(); ++i) { std::string key; std::string value; status = getKeyValue(values[i], key, value); NN_RETURN_STATUS(); unsigned int type = parseLayerProperty(key); if (value.empty()) { return ML_ERROR_INVALID_PARAMETER; } try { /// @note this calls derived setProperty if available setProperty(static_cast<PropertyType>(type), value); } catch (...) { return ML_ERROR_INVALID_PARAMETER; } } return status; } void Layer::setProperty(const PropertyType type, const std::string &value) { int status = ML_ERROR_NONE; switch (type) { case PropertyType::name: if (!value.empty()) { status = setName(value); throw_status(status); } break; case PropertyType::input_shape: if (!value.empty()) { unsigned int cache_batch_size = 1; /** cache original value of batch size */ if (input_dim.batch()) { cache_batch_size = input_dim.batch(); input_dim.batch(1); } status = input_dim.setTensorDim(value.c_str()); if (input_dim.batch() > 1) { ml_logw("Batch size set with input dimension %d is ignored." "Set batchsize property for the model to update batchsize.", input_dim.batch()); } /** set back to cache value of dimension */ input_dim.batch(cache_batch_size); throw_status(status); } break; case PropertyType::batch_size: if (!value.empty()) { unsigned int batch_size; status = setUint(batch_size, value); throw_status(status); input_dim.batch(batch_size); } break; case PropertyType::activation: if (!value.empty()) { status = setActivation((ActiType)parseType(value, TOKEN_ACTI)); throw_status(status); } break; case PropertyType::flatten: if (!value.empty()) { status = setBoolean(flatten, value); throw_status(status); } break; case PropertyType::weight_regularizer: if (!value.empty()) { weight_regularizer.type = (WeightRegularizerType)parseType(value, TOKEN_WEIGHT_REGULARIZER); if (weight_regularizer.type == WeightRegularizerType::unknown) { throw std::invalid_argument("[Layer] Unknown Weight decay"); } } break; case PropertyType::weight_regularizer_constant: if (!value.empty()) { status = setFloat(weight_regularizer.constant, value); throw_status(status); } break; case PropertyType::weight_initializer: if (!value.empty()) { weight_initializer = (WeightInitializer)parseType(value, TOKEN_WEIGHT_INIT); } break; case PropertyType::bias_initializer: if (!value.empty()) { bias_initializer = (WeightInitializer)parseType(value, TOKEN_WEIGHT_INIT); } break; default: std::string msg = "[Layer] Unknown Layer Property Key for value " + std::string(value); throw exception::not_supported(msg); } } int Layer::setName(std::string name) { if (name.empty()) return ML_ERROR_INVALID_PARAMETER; this->name = name; return ML_ERROR_NONE; } template <typename T> void Layer::printIfValid(std::ostream &out, const PropertyType type, const T target) { try { setProperty(type); } catch (exception::not_supported &e) { return; } out << propToStr(static_cast<unsigned int>(type)) << ": " << target << std::endl; } void Layer::printShapeInfo(std::ostream &out) { out << "input " << input_dim; for (unsigned int i = 0; i < param_size; i++) out << "inner" << i << " " << paramsAt(i).weight.getDim(); out << "output " << output_dim; } void Layer::printPropertiesMeta(std::ostream &out) { printIfValid(out, PropertyType::activation, activation_type); printIfValid(out, PropertyType::flatten, flatten); } void Layer::printProperties(std::ostream &out) { out << "Trainable: " << trainable << std::endl; printIfValid(out, PropertyType::weight_regularizer, static_cast<int>(weight_regularizer.type)); printIfValid(out, PropertyType::weight_regularizer_constant, weight_regularizer.constant); } void Layer::printMetric(std::ostream &out) { if (loss > 0) { out << "Weight regularization loss: " << loss; } } void Layer::print(std::ostream &out, unsigned int flags) { if (flags & PRINT_INST_INFO) { out << "==================="; printInstance(out, this); out << "Layer Type: " << type << std::endl; } if (flags & PRINT_SHAPE_INFO) { out << "======shape information: " << std::endl; printShapeInfo(out); } if (flags & PRINT_PROP_META) { out << "======meta properties: " << std::endl; printPropertiesMeta(out); } if (flags & PRINT_PROP) { out << "======properties: " << std::endl; printProperties(out); } if (flags & PRINT_WEIGHTS) { out << "======weights: " << std::endl; for (unsigned int i = 0; i < param_size; ++i) { out << '[' << paramsAt(i).name << ']' << std::endl; out << paramsAt(i).weight; } } if (flags & PRINT_METRIC) { out << "======metrics: " << std::endl; printMetric(out); } }; } /* namespace nntrainer */
27.515528
80
0.638262
[ "shape", "vector", "model" ]
a933f4ccf0516a7172815adcf2cd05d81320b73e
378
cpp
C++
JeffGCPPNow2019/04_takeView.cpp
tlanc007/CPP20_Ranges
e931ecf14904f74e3baac91dfbd09766c74cf7b9
[ "MIT" ]
null
null
null
JeffGCPPNow2019/04_takeView.cpp
tlanc007/CPP20_Ranges
e931ecf14904f74e3baac91dfbd09766c74cf7b9
[ "MIT" ]
null
null
null
JeffGCPPNow2019/04_takeView.cpp
tlanc007/CPP20_Ranges
e931ecf14904f74e3baac91dfbd09766c74cf7b9
[ "MIT" ]
null
null
null
/* 04_takeView.cpp */ #include <iostream> #include <ranges> #include <vector> #include "rangeNamespace.hpp" namespace view = std::view; int main () { std::vector<int> vi {0,1,2,3,4,5}; //not sure this notation is C++20 //rng::take_view tvi(vi, 5); auto tvi {view::take (vi, 5) }; for (int i : tvi) { std::cout << i << " "; } std::cout << '\n'; }
15.75
48
0.560847
[ "vector" ]
a9349b40f218d03d06a126de9f97cf2022f0035c
1,654
cxx
C++
examples/rootexample.cxx
maxisacson/DataStore
de057b48c98d66c73a510a0d8f2c31347408e445
[ "MIT" ]
null
null
null
examples/rootexample.cxx
maxisacson/DataStore
de057b48c98d66c73a510a0d8f2c31347408e445
[ "MIT" ]
null
null
null
examples/rootexample.cxx
maxisacson/DataStore
de057b48c98d66c73a510a0d8f2c31347408e445
[ "MIT" ]
null
null
null
#include "DataStore.h" #include <TFile.h> #include <TTree.h> #include <TH1.h> #include <vector> int main() { TFile* f = TFile::Open("tree.root"); TFile* out = TFile::Open("out.root", "RECREATE"); TH1D * h = new TH1D("gaus", "gaussian", 50, -5, 5); TH1D * m = new TH1D("gaus_m", "gaussian(80, 2)", 50, 70, 90); TTree * tree = (TTree*)f->Get("tree"); /** * add desired variables to the store */ ds::DataStore store; store.add<float>("gaus"); store.add<std::vector<float> >("m"); /** * get references to the objects in the store. Note the use of the ptr 'addr_v' * to make root accept the address. When pointing branches to vectors root needs * the address to the pointer to the vector. */ float& x = store.retrieve<float>("gaus"); std::vector<float>& v = store.retrieve<std::vector<float> >("m"); std::vector<float>* addr_v = &v; /** * set the branch addresses */ tree->SetBranchAddress("gauss", &x); tree->SetBranchAddress("m", &addr_v); /** * get new references to the objects, just to illustrate that the objects are * actually updated in the store. */ float& y = store.retrieve<float>("gaus"); std::vector<float>& v_m = store.retrieve<std::vector<float> >("m"); /** * loop over the entries in the tree */ long n = tree->GetEntries(); for (int i = 0; i < n; i++) { /** * get entry #i */ tree->GetEntry(i); /** * fill our histograms */ h->Fill(y); for (unsigned int j = 0; j < v_m.size(); j++) { m->Fill(v_m[j]); } } /** * write and close */ out->Write(); out->Close(); f->Close(); return 0; }
23.295775
82
0.579202
[ "vector" ]
a93d2753598fedf307fa0e84dd69171a7fb372fd
2,894
cpp
C++
Samples/WebService/Sources/Main.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Samples/WebService/Sources/Main.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Samples/WebService/Sources/Main.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Int.h" #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Containers/Sequence.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Module.h" #include "Stroika/Foundation/Execution/SignalHandlers.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "WSImpl.h" #include "WebServer.h" #include "AppVersion.h" using namespace std; using namespace Stroika::Foundation; using Characters::String; using Containers::Sequence; using namespace StroikaSample::WebServices; int main (int argc, const char* argv[]) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())}; Execution::SignalHandlerRegistry::SafeSignalsManager safeSignals; #if qPlatform_POSIX Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif uint16_t portNumber = 8080; Time::DurationSecondsType quitAfter = numeric_limits<Time::DurationSecondsType>::max (); Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end (); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"port")) { ++argi; if (argi != args.end ()) { portNumber = Characters::String2Int<uint16_t> (*argi); } else { cerr << "Expected arg to -port" << endl; return EXIT_FAILURE; } } else if (Execution::MatchesCommandLineArgument (*argi, L"quit-after")) { ++argi; if (argi != args.end ()) { quitAfter = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -quit-after" << endl; return EXIT_FAILURE; } } } try { WebServer myWebServer{portNumber, make_shared<WSImpl> ()}; // listen and dispatch while this object exists Execution::WaitableEvent{}.Wait (quitAfter); // wait forever - til user hits ctrl-c } catch (const Execution::TimeOutException&) { cerr << "Timed out - so - terminating..." << endl; return EXIT_FAILURE; } catch (...) { cerr << "Error encountered: " << Characters::ToString (current_exception ()).AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
36.632911
202
0.641672
[ "object", "vector" ]
a944a351625b371965d4bdbdfa00b275dd16611c
6,264
cpp
C++
Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Atom/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.h> #include <Atom/RPI.Edit/Material/MaterialTypeSourceData.h> #include <Atom/RPI.Edit/Common/AssetUtils.h> #include <Atom/RPI.Edit/Common/JsonFileLoadContext.h> #include <Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h> #include <AzCore/Serialization/Json/JsonUtils.h> #include <AzCore/Serialization/Json/BaseJsonSerializer.h> #include <AzCore/Serialization/Json/JsonSerializationResult.h> #include <AzCore/Serialization/Json/JsonSerialization.h> #include <AzCore/Serialization/Json/StackedString.h> namespace AZ { namespace RPI { namespace { constexpr const char TypeField[] = "type"; constexpr const char ArgsField[] = "args"; } AZ_CLASS_ALLOCATOR_IMPL(JsonMaterialFunctorSourceDataSerializer, SystemAllocator, 0); JsonSerializationResult::Result JsonMaterialFunctorSourceDataSerializer::Load(void* outputValue, const Uuid& outputValueTypeId, const rapidjson::Value& inputValue, JsonDeserializerContext& context) { namespace JSR = JsonSerializationResult; AZ_Assert(azrtti_typeid<MaterialFunctorSourceDataHolder>() == outputValueTypeId, "Unable to deserialize material functor to json because the provided type is %s", outputValueTypeId.ToString<AZStd::string>().c_str()); AZ_UNUSED(outputValueTypeId); MaterialFunctorSourceDataHolder* functorHolder = reinterpret_cast<MaterialFunctorSourceDataHolder*>(outputValue); AZ_Assert(functorHolder, "Output value for JsonMaterialFunctorSourceDataSerializer can't be null."); JSR::ResultCode result(JSR::Tasks::ReadField); if (!inputValue.IsObject()) { return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Unsupported, "Material functor data must be a JSON object."); } Uuid functorTypeId = 0; if (!inputValue.HasMember(TypeField)) { return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Unsupported, "Functor type name is not specified."); } // Load the name first and find the type. AZStd::string functorName; result.Combine(ContinueLoadingFromJsonObjectField(&functorName, azrtti_typeid<AZStd::string>(), inputValue, TypeField, context)); functorTypeId = MaterialFunctorSourceDataRegistration::Get()->FindMaterialFunctorTypeIdByName(functorName); if (functorTypeId == 0) { return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Unsupported, "Functor type name is not registered."); } // Create the actual source data of the functor. const SerializeContext::ClassData* actualClassData = context.GetSerializeContext()->FindClassData(functorTypeId); if (actualClassData) { void* instance = actualClassData->m_factory->Create(actualClassData->m_name); if (inputValue.HasMember(ArgsField)) { result.Combine(ContinueLoading(instance, functorTypeId, inputValue[ArgsField], context)); } else { result.Combine(JSR::ResultCode(JSR::Tasks::ReadField, JSR::Outcomes::DefaultsUsed)); } functorHolder->m_actualSourceData = reinterpret_cast<MaterialFunctorSourceData*>(instance); } else { return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Unsupported, "Class data is not registered in the SerializeContext."); } return context.Report(result, "Successfully processed MaterialFunctorSourceData."); } JsonSerializationResult::Result JsonMaterialFunctorSourceDataSerializer::Store(rapidjson::Value& outputValue, const void* inputValue, [[maybe_unused]] const void* defaultValue, const Uuid& valueTypeId, JsonSerializerContext& context) { namespace JSR = JsonSerializationResult; AZ_Assert(azrtti_typeid<MaterialFunctorSourceDataHolder>() == valueTypeId, "Unable to serialize material functor to json because the provided type is %s", valueTypeId.ToString<AZStd::string>().c_str()); AZ_UNUSED(valueTypeId); JSR::ResultCode result(JSR::Tasks::WriteValue); outputValue.SetObject(); const MaterialFunctorSourceDataHolder* functorHolder = reinterpret_cast<const MaterialFunctorSourceDataHolder*>(inputValue); if (!functorHolder->m_actualSourceData) { return context.Report(JSR::Tasks::WriteValue, JSR::Outcomes::Unsupported, "No actual functor source data lives in this holder."); } Uuid functorTypeId = functorHolder->m_actualSourceData->RTTI_GetType(); AZStd::string functorName = MaterialFunctorSourceDataRegistration::Get()->FindMaterialFunctorNameByTypeId(functorTypeId); if (functorName.empty()) { return context.Report(JSR::Tasks::WriteValue, JSR::Outcomes::Unsupported, "Functor name is not registered."); } const AZStd::string emptyString; result.Combine(ContinueStoringToJsonObjectField(outputValue, TypeField, &functorName, &emptyString, azrtti_typeid<AZStd::string>(), context)); result.Combine(ContinueStoringToJsonObjectField(outputValue, ArgsField, functorHolder->m_actualSourceData.get(), nullptr, functorTypeId, context)); return context.Report(result, "Successfully processed MaterialFunctorSourceData."); } BaseJsonSerializer::OperationFlags JsonMaterialFunctorSourceDataSerializer::GetOperationsFlags() const { return OperationFlags::ManualDefault; } } // namespace RPI } // namespace AZ
47.097744
159
0.668423
[ "object", "3d" ]
a9479f36b4fe6b3383f8c2cb8cacc679fe3e0965
2,109
cpp
C++
src/tests/functional/plugin/cpu/shared_tests_instances/single_layer_tests/experimental_detectron_topkrois.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
1
2021-10-21T03:04:16.000Z
2021-10-21T03:04:16.000Z
src/tests/functional/plugin/cpu/shared_tests_instances/single_layer_tests/experimental_detectron_topkrois.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
58
2020-11-06T12:13:45.000Z
2022-03-28T13:20:11.000Z
src/tests/functional/plugin/cpu/shared_tests_instances/single_layer_tests/experimental_detectron_topkrois.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2
2019-09-20T01:33:37.000Z
2019-09-20T08:42:11.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include "single_layer_tests/experimental_detectron_topkrois.hpp" using namespace ov::test; using namespace ov::test::subgraph; namespace { std::vector<int64_t> maxRois { 1000, 1500, 2000, 2500 }; const std::vector<std::vector<InputShape>> staticInputShape = { static_shapes_to_test_representation({{3000, 4}, {3000}}), static_shapes_to_test_representation({{4200, 4}, {4200}}), static_shapes_to_test_representation({{4500, 4}, {4500}}) }; INSTANTIATE_TEST_SUITE_P(smoke_ExperimentalDetectronTopKROIs_static, ExperimentalDetectronTopKROIsLayerTest, ::testing::Combine( ::testing::ValuesIn(staticInputShape), ::testing::ValuesIn(maxRois), ::testing::Values(ElementType::f32), ::testing::Values(CommonTestUtils::DEVICE_CPU)), ExperimentalDetectronTopKROIsLayerTest::getTestCaseName); const std::vector<std::vector<InputShape>> dynamicInputShape = { { { {{-1, 4}, {{5000, 4}, {4000, 4}, {3500, 4}}}, {{-1}, {{5000}, {4000}, {3500}}} } }, { { {{{1000, 5000}, 4}, {{5000, 4}, {3000, 4}, {2500, 4}}}, {{{1000, 5000}}, {{5000}, {3000}, {2500}}} } } }; INSTANTIATE_TEST_SUITE_P(smoke_ExperimentalROI_dynamic, ExperimentalDetectronTopKROIsLayerTest, ::testing::Combine( ::testing::ValuesIn(dynamicInputShape), ::testing::ValuesIn(maxRois), ::testing::Values(ElementType::f32), ::testing::Values(CommonTestUtils::DEVICE_CPU)), ExperimentalDetectronTopKROIsLayerTest::getTestCaseName); } // namespace
37.660714
108
0.526316
[ "vector" ]
a948f0901d5a61742c4de90134b4c90a99a28f48
2,781
cc
C++
SimPPS/PPSPixelDigiProducer/plugins/RPixDetDigitizer.cc
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
6
2017-09-08T14:12:56.000Z
2022-03-09T23:57:01.000Z
SimPPS/PPSPixelDigiProducer/plugins/RPixDetDigitizer.cc
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
545
2017-09-19T17:10:19.000Z
2022-03-07T16:55:27.000Z
SimPPS/PPSPixelDigiProducer/plugins/RPixDetDigitizer.cc
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
14
2017-10-04T09:47:21.000Z
2019-10-23T18:04:45.000Z
#include <vector> #include <iostream> #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "SimPPS/PPSPixelDigiProducer/interface/RPixDetDigitizer.h" #include "Geometry/VeryForwardGeometry/interface/CTPPSPixelTopology.h" RPixDetDigitizer::RPixDetDigitizer(const edm::ParameterSet &params, CLHEP::HepRandomEngine &eng, uint32_t det_id, const edm::EventSetup &iSetup) : det_id_(det_id) { verbosity_ = params.getParameter<int>("RPixVerbosity"); numPixels = CTPPSPixelTopology().detPixelNo(); theNoiseInElectrons = params.getParameter<double>("RPixEquivalentNoiseCharge"); thePixelThresholdInE = params.getParameter<double>("RPixDummyROCThreshold"); noNoise = params.getParameter<bool>("RPixNoNoise"); links_persistence_ = params.getParameter<bool>("CTPPSPixelDigiSimHitRelationsPersistence"); theRPixPileUpSignals = std::make_unique<RPixPileUpSignals>(params, det_id_); theRPixDummyROCSimulator = std::make_unique<RPixDummyROCSimulator>(params, det_id_); theRPixHitChargeConverter = std::make_unique<RPixHitChargeConverter>(params, eng, det_id_); } RPixDetDigitizer::~RPixDetDigitizer() {} void RPixDetDigitizer::run(const std::vector<PSimHit> &input, const std::vector<int> &input_links, std::vector<CTPPSPixelDigi> &output_digi, std::vector<std::vector<std::pair<int, double> > > &output_digi_links, const CTPPSPixelGainCalibrations *pcalibrations) { if (verbosity_) edm::LogInfo("RPixDetDigitizer") << det_id_ << " received input.size()=" << input.size(); theRPixPileUpSignals->reset(); bool links_persistence_checked = links_persistence_ && input_links.size() == input.size(); int input_size = input.size(); for (int i = 0; i < input_size; ++i) { std::map<unsigned short, double> the_pixel_charge_map; the_pixel_charge_map = theRPixHitChargeConverter->processHit(input[i]); if (verbosity_) edm::LogInfo("RPixDetDigitizer") << det_id_ << " returned hits=" << the_pixel_charge_map.size(); if (links_persistence_checked) theRPixPileUpSignals->add(the_pixel_charge_map, input_links[i]); else theRPixPileUpSignals->add(the_pixel_charge_map, 0); } const std::map<unsigned short, double> &theSignal = theRPixPileUpSignals->dumpSignal(); std::map<unsigned short, std::vector<std::pair<int, double> > > &theSignalProvenance = theRPixPileUpSignals->dumpLinks(); std::map<unsigned short, double> afterNoise; afterNoise = theSignal; theRPixDummyROCSimulator->ConvertChargeToHits( afterNoise, theSignalProvenance, output_digi, output_digi_links, pcalibrations); }
49.660714
102
0.7073
[ "geometry", "vector" ]
a94aaee2120d050b4a92b0a7de007f6c54c15916
6,440
cpp
C++
src/components/config.cpp
maciekMerkury/polybar-dwm-module
012a8638c384da7f774d1604ee739c01f83113e2
[ "MIT" ]
102
2020-07-24T03:33:01.000Z
2022-03-29T01:21:47.000Z
src/components/config.cpp
maciekMerkury/polybar-dwm-module
012a8638c384da7f774d1604ee739c01f83113e2
[ "MIT" ]
35
2020-07-17T05:46:16.000Z
2022-03-21T08:56:00.000Z
src/components/config.cpp
maciekMerkury/polybar-dwm-module
012a8638c384da7f774d1604ee739c01f83113e2
[ "MIT" ]
19
2020-07-24T08:36:15.000Z
2021-12-19T18:46:47.000Z
#include "components/config.hpp" #include <climits> #include <fstream> #include "cairo/utils.hpp" #include "utils/color.hpp" #include "utils/env.hpp" #include "utils/factory.hpp" #include "utils/string.hpp" POLYBAR_NS namespace chrono = std::chrono; /** * Create instance */ config::make_type config::make(string path, string bar) { return *factory_util::singleton<std::remove_reference_t<config::make_type>>(logger::make(), move(path), move(bar)); } /** * Get path of loaded file */ const string& config::filepath() const { return m_file; } /** * Get the section name of the bar in use */ string config::section() const { return "bar/" + m_barname; } void config::use_xrm() { #if WITH_XRM /* * Initialize the xresource manager if there are any xrdb refs * present in the configuration */ if (!m_xrm) { m_log.info("Enabling xresource manager"); m_xrm.reset(new xresource_manager{connection::make()}); } #endif } void config::set_sections(sectionmap_t sections) { m_sections = move(sections); copy_inherited(); } void config::set_included(file_list included) { m_included = move(included); } /** * Print a deprecation warning if the given parameter is set */ void config::warn_deprecated(const string& section, const string& key, string replacement) const { try { auto value = get<string>(section, key); m_log.warn( "The config parameter `%s.%s` is deprecated, use `%s.%s` instead.", section, key, section, move(replacement)); } catch (const key_error& err) { } } /** * Look for sections set up to inherit from a base section * and copy the missing parameters * * Multiple sections can be specified, separated by a space. * * [sub/section] * inherit = section1 section2 */ void config::copy_inherited() { for (auto&& section : m_sections) { std::vector<string> inherit_sections; // Collect all sections to be inherited for (auto&& param : section.second) { string key_name = param.first; if (key_name == "inherit") { auto inherit = param.second; inherit = dereference<string>(section.first, key_name, inherit, inherit); std::vector<string> sections = string_util::split(std::move(inherit), ' '); inherit_sections.insert(inherit_sections.end(), sections.begin(), sections.end()); } else if (key_name.find("inherit") == 0) { // Legacy support for keys that just start with 'inherit' m_log.warn( "\"%s.%s\": Using anything other than 'inherit' for inheriting section keys is deprecated. " "The 'inherit' key supports multiple section names separated by a space.", section.first, key_name); auto inherit = param.second; inherit = dereference<string>(section.first, key_name, inherit, inherit); if (inherit.empty() || m_sections.find(inherit) == m_sections.end()) { throw value_error( "Invalid section \"" + inherit + "\" defined for \"" + section.first + "." + key_name + "\""); } inherit_sections.push_back(std::move(inherit)); } } for (const auto& base_name : inherit_sections) { const auto base_section = m_sections.find(base_name); if (base_section == m_sections.end()) { throw value_error("Invalid section \"" + base_name + "\" defined for \"" + section.first + ".inherit\""); } m_log.trace("config: Inheriting keys from \"%s\" in \"%s\"", base_name, section.first); /* * Iterate the base and copy the parameters that haven't been defined * yet. */ for (auto&& base_param : base_section->second) { section.second.emplace(base_param.first, base_param.second); } } } } template <> string config::convert(string&& value) const { return forward<string>(value); } template <> const char* config::convert(string&& value) const { return value.c_str(); } template <> char config::convert(string&& value) const { return value.c_str()[0]; } template <> int config::convert(string&& value) const { return std::strtol(value.c_str(), nullptr, 10); } template <> short config::convert(string&& value) const { return static_cast<short>(std::strtol(value.c_str(), nullptr, 10)); } template <> bool config::convert(string&& value) const { string lower{string_util::lower(forward<string>(value))}; return (lower == "true" || lower == "yes" || lower == "on" || lower == "1"); } template <> float config::convert(string&& value) const { return std::strtof(value.c_str(), nullptr); } template <> double config::convert(string&& value) const { return std::strtod(value.c_str(), nullptr); } template <> long config::convert(string&& value) const { return std::strtol(value.c_str(), nullptr, 10); } template <> long long config::convert(string&& value) const { return std::strtoll(value.c_str(), nullptr, 10); } template <> unsigned char config::convert(string&& value) const { return std::strtoul(value.c_str(), nullptr, 10); } template <> unsigned short config::convert(string&& value) const { return std::strtoul(value.c_str(), nullptr, 10); } template <> unsigned int config::convert(string&& value) const { return std::strtoul(value.c_str(), nullptr, 10); } template <> unsigned long config::convert(string&& value) const { unsigned long v{std::strtoul(value.c_str(), nullptr, 10)}; return v < ULONG_MAX ? v : 0UL; } template <> unsigned long long config::convert(string&& value) const { unsigned long long v{std::strtoull(value.c_str(), nullptr, 10)}; return v < ULLONG_MAX ? v : 0ULL; } template <> chrono::seconds config::convert(string&& value) const { return chrono::seconds{convert<chrono::seconds::rep>(forward<string>(value))}; } template <> chrono::milliseconds config::convert(string&& value) const { return chrono::milliseconds{convert<chrono::milliseconds::rep>(forward<string>(value))}; } template <> chrono::duration<double> config::convert(string&& value) const { return chrono::duration<double>{convert<double>(forward<string>(value))}; } template <> rgba config::convert(string&& value) const { rgba ret{value}; if (!ret.has_color()) { throw value_error("\"" + value + "\" is an invalid color value."); } return ret; } template <> cairo_operator_t config::convert(string&& value) const { return cairo::utils::str2operator(forward<string>(value), CAIRO_OPERATOR_OVER); } POLYBAR_NS_END
26.502058
118
0.665994
[ "vector" ]
a94b67292e1ececa308956c4c5b66c122712dae8
1,335
cpp
C++
Data Structure/Parentheses-balance/c++-solution/balance.cpp
me-shaon/coding-interview-prep
cbfe358030fd48406d914f9c1f7c9d418ab925c7
[ "MIT" ]
1
2021-06-03T08:26:52.000Z
2021-06-03T08:26:52.000Z
Data Structure/Parentheses-balance/c++-solution/balance.cpp
me-shaon/coding-interview-prep
cbfe358030fd48406d914f9c1f7c9d418ab925c7
[ "MIT" ]
null
null
null
Data Structure/Parentheses-balance/c++-solution/balance.cpp
me-shaon/coding-interview-prep
cbfe358030fd48406d914f9c1f7c9d418ab925c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cstring> #include <stack> #include <iomanip> using namespace std; bool isOpen(char c) { if(c == '(' || c == '{' || c == '[') return true; return false; } bool isBalanced(char popped, char now) { if(popped == '(' && now ==')') return true; if(popped == '[' && now ==']') return true; if(popped == '{' && now =='}') return true; return false; } bool checkBalance(string expression) { stack<char> s; bool balanced = true; for(int i = 0; i < expression.length(); i++) { char now = expression[i]; if(isOpen(now)) s.push(now); else { //If a closing symbol appears first of an expression or previous pairs already matched it will see the stack empty if(!s.empty() && isBalanced(s.top(), now)) { s.pop(); } else { balanced = false; break; } } } return (balanced && s.empty()); //if the stack is empty then all openingSymbols matches with closingSymbols } int main() { std::cout << std::boolalpha; cout<<checkBalance("([)]")<<endl; cout<<checkBalance("{{([][])}()}")<<endl; cout<<checkBalance("}()")<<endl; }
21.532258
126
0.501124
[ "vector" ]
a95597d909477764ac8d157c8ed9eb514e27261f
11,164
hpp
C++
include/checked_mutex.hpp
alishewn/yamc
f4ed5182c04c674c0e19992410578b327d768831
[ "MIT" ]
101
2017-01-19T10:38:06.000Z
2021-12-16T22:29:45.000Z
include/checked_mutex.hpp
alishewn/yamc
f4ed5182c04c674c0e19992410578b327d768831
[ "MIT" ]
25
2017-01-18T09:22:15.000Z
2022-03-30T12:50:32.000Z
include/checked_mutex.hpp
alishewn/yamc
f4ed5182c04c674c0e19992410578b327d768831
[ "MIT" ]
15
2017-10-28T03:54:42.000Z
2022-03-28T20:39:12.000Z
/* * checked_mutex.hpp * * MIT License * * Copyright (c) 2017 yohhoy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef YAMC_CHECKED_MUTEX_HPP_ #define YAMC_CHECKED_MUTEX_HPP_ #include <cassert> #include <cstdlib> #include <chrono> #include <condition_variable> #include <mutex> #include <system_error> #include <thread> #include "yamc_lock_validator.hpp" // call std::abort() when requirements violation #ifndef YAMC_CHECKED_CALL_ABORT #define YAMC_CHECKED_CALL_ABORT 0 #endif // default deadlock detection mode #ifndef YAMC_CHECKED_DETECT_DEADLOCK #define YAMC_CHECKED_DETECT_DEADLOCK 1 #endif namespace yamc { /* * strict requirements checking mutex for debug * * - yamc::checked::mutex * - yamc::checked::timed_mutex * - yamc::checked::recursive_mutex * - yamc::checked::recursive_timed_mutex */ namespace checked { namespace detail { #if YAMC_CHECKED_DETECT_DEADLOCK using validator = yamc::validator::deadlock; #else using validator = yamc::validator::null; #endif class mutex_base { protected: std::thread::id owner_; std::condition_variable cv_; std::mutex mtx_; void dtor_precondition(const char* emsg) { std::lock_guard<decltype(mtx_)> lk(mtx_); if (owner_ != std::thread::id()) { // object liveness #if YAMC_CHECKED_CALL_ABORT std::abort(); (void)emsg; // suppress "unused variable" warning #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } } void lock() { const auto tid = std::this_thread::get_id(); std::unique_lock<decltype(mtx_)> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "recursive lock"); #endif } while (owner_ != std::thread::id()) { if (!validator::enqueue(reinterpret_cast<uintptr_t>(this), tid, false)) { // deadlock detection #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "deadlock"); #endif } cv_.wait(lk); validator::dequeue(reinterpret_cast<uintptr_t>(this), tid); } owner_ = tid; validator::locked(reinterpret_cast<uintptr_t>(this), tid, false); } bool try_lock() { const auto tid = std::this_thread::get_id(); std::lock_guard<decltype(mtx_)> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "recursive try_lock"); #endif } if (owner_ != std::thread::id()) { return false; } owner_ = tid; validator::locked(reinterpret_cast<uintptr_t>(this), tid, false); return true; } void unlock() { const auto tid = std::this_thread::get_id(); std::lock_guard<decltype(mtx_)> lk(mtx_); if (owner_ != tid) { // owner thread #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::operation_not_permitted), "invalid unlock"); #endif } owner_ = std::thread::id(); validator::unlocked(reinterpret_cast<uintptr_t>(this), tid, false); cv_.notify_all(); } }; class recursive_mutex_base { protected: std::size_t ncount_ = 0; std::thread::id owner_; std::condition_variable cv_; std::mutex mtx_; void dtor_precondition(const char* emsg) { std::lock_guard<decltype(mtx_)> lk(mtx_); if (ncount_ != 0 || owner_ != std::thread::id()) { // object liveness #if YAMC_CHECKED_CALL_ABORT std::abort(); (void)emsg; // suppress "unused variable" warning #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } } void lock() { const auto tid = std::this_thread::get_id(); std::unique_lock<decltype(mtx_)> lk(mtx_); if (owner_ == tid) { ++ncount_; return; } while (ncount_ != 0) { if (!validator::enqueue(reinterpret_cast<uintptr_t>(this), tid, false)) { // deadlock detection #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), "deadlock"); #endif } cv_.wait(lk); validator::dequeue(reinterpret_cast<uintptr_t>(this), tid); } assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; validator::locked(reinterpret_cast<uintptr_t>(this), tid, false); } bool try_lock() { const auto tid = std::this_thread::get_id(); std::lock_guard<decltype(mtx_)> lk(mtx_); if (owner_ == tid) { ++ncount_; return true; } if (ncount_ == 0) { assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; validator::locked(reinterpret_cast<uintptr_t>(this), tid, false); return true; } return false; } void unlock() { const auto tid = std::this_thread::get_id(); std::lock_guard<decltype(mtx_)> lk(mtx_); if (owner_ != tid) { // owner thread #if YAMC_CHECKED_CALL_ABORT std::abort(); #else throw std::system_error(std::make_error_code(std::errc::operation_not_permitted), "invalid unlock"); #endif } assert(0 < ncount_); if (--ncount_ == 0) { owner_ = std::thread::id(); validator::unlocked(reinterpret_cast<uintptr_t>(this), tid, false); cv_.notify_all(); } } }; } // namespace detail class mutex : private detail::mutex_base { using base = detail::mutex_base; public: mutex() { detail::validator::ctor(reinterpret_cast<uintptr_t>(this)); } ~mutex() noexcept(false) { detail::validator::dtor(reinterpret_cast<uintptr_t>(this)); dtor_precondition("abandoned mutex"); } mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; }; class timed_mutex : private detail::mutex_base { using base = detail::mutex_base; template<typename Clock, typename Duration> bool do_try_lockwait(const std::chrono::time_point<Clock, Duration>& tp, const char* emsg) { const auto tid = std::this_thread::get_id(); std::unique_lock<decltype(mtx_)> lk(mtx_); if (owner_ == tid) { // non-recursive semantics #if YAMC_CHECKED_CALL_ABORT std::abort(); (void)emsg; // suppress "unused variable" warning #else throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur), emsg); #endif } while (owner_ != std::thread::id()) { if (cv_.wait_until(lk, tp) == std::cv_status::timeout) { if (owner_ == std::thread::id()) // re-check predicate break; return false; } } owner_ = tid; detail::validator::locked(reinterpret_cast<uintptr_t>(this), tid, false); return true; } public: timed_mutex() { detail::validator::ctor(reinterpret_cast<uintptr_t>(this)); } ~timed_mutex() noexcept(false) { detail::validator::dtor(reinterpret_cast<uintptr_t>(this)); dtor_precondition("abandoned timed_mutex"); } timed_mutex(const timed_mutex&) = delete; timed_mutex& operator=(const timed_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; template<typename Rep, typename Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { const auto tp = std::chrono::steady_clock::now() + duration; return do_try_lockwait(tp, "recursive try_lock_for"); } template<typename Clock, typename Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& tp) { return do_try_lockwait(tp, "recursive try_lock_until"); } }; class recursive_mutex : private detail::recursive_mutex_base { using base = detail::recursive_mutex_base; public: recursive_mutex() { detail::validator::ctor(reinterpret_cast<uintptr_t>(this)); } ~recursive_mutex() noexcept(false) { detail::validator::dtor(reinterpret_cast<uintptr_t>(this)); dtor_precondition("abandoned recursive_mutex"); } recursive_mutex(const recursive_mutex&) = delete; recursive_mutex& operator=(const recursive_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; }; class recursive_timed_mutex : private detail::recursive_mutex_base { using base = detail::recursive_mutex_base; template<typename Clock, typename Duration> bool do_try_lockwait(const std::chrono::time_point<Clock, Duration>& tp) { const auto tid = std::this_thread::get_id(); std::unique_lock<decltype(mtx_)> lk(mtx_); if (owner_ == tid) { ++ncount_; return true; } while (ncount_ != 0) { if (cv_.wait_until(lk, tp) == std::cv_status::timeout) { if (ncount_ == 0) // re-check predicate break; return false; } } assert(owner_ == std::thread::id()); ncount_ = 1; owner_ = tid; detail::validator::locked(reinterpret_cast<uintptr_t>(this), tid, false); return true; } public: recursive_timed_mutex() { detail::validator::ctor(reinterpret_cast<uintptr_t>(this)); } ~recursive_timed_mutex() noexcept(false) { detail::validator::dtor(reinterpret_cast<uintptr_t>(this)); dtor_precondition("abandoned recursive_timed_mutex"); } recursive_timed_mutex(const recursive_timed_mutex&) = delete; recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete; using base::lock; using base::try_lock; using base::unlock; template<typename Rep, typename Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { const auto tp = std::chrono::steady_clock::now() + duration; return do_try_lockwait(tp); } template<typename Clock, typename Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& tp) { return do_try_lockwait(tp); } }; } // namespace checked } // namespace yamc #endif
26.517815
116
0.678699
[ "object" ]
a9566bd6dee3c4c868315077b2bbd0819730b459
3,107
hh
C++
C/Cpp_include/c4Observer.hh
mhocouchbase/couchbase-lite-core
8a527a066b703c8865b4e61cbd9e3d41d81ba5ef
[ "Apache-2.0" ]
null
null
null
C/Cpp_include/c4Observer.hh
mhocouchbase/couchbase-lite-core
8a527a066b703c8865b4e61cbd9e3d41d81ba5ef
[ "Apache-2.0" ]
null
null
null
C/Cpp_include/c4Observer.hh
mhocouchbase/couchbase-lite-core
8a527a066b703c8865b4e61cbd9e3d41d81ba5ef
[ "Apache-2.0" ]
null
null
null
// // c4Observer.hh // // Copyright 2021-Present Couchbase, Inc. // // Use of this software is governed by the Business Source License included // in the file licenses/BSL-Couchbase.txt. As of the Change Date specified // in that file, in accordance with the Business Source License, use of this // software will be governed by the Apache License, Version 2.0, included in // the file licenses/APL2.txt. // #pragma once #include "c4Base.hh" #include "c4Collection.hh" #include "c4DocumentTypes.h" #include <memory> C4_ASSUME_NONNULL_BEGIN // ************************************************************************ // This header is part of the LiteCore C++ API. // If you use this API, you must _statically_ link LiteCore; // the dynamic library only exports the C API. // ************************************************************************ /** A registration for callbacks whenever any document in a database changes. The registration lasts until this object is destructed. */ struct C4CollectionObserver : public fleece::InstanceCounted, C4Base { using Callback = C4Collection::CollectionObserverCallback; static std::unique_ptr<C4CollectionObserver> create(C4Collection*, Callback); #ifndef C4_STRICT_COLLECTION_API static std::unique_ptr<C4CollectionObserver> create(C4Database*, Callback); #endif virtual ~C4CollectionObserver() =default; /// Metadata of a change recorded by C4CollectionObserver. (Equivalent to C4CollectionChange.) struct Change { alloc_slice docID; ///< Document ID alloc_slice revID; ///< Revision ID C4SequenceNumber sequence; ///< Sequence number, or 0 if this was a purge uint32_t bodySize; ///< (Approximate) size of revision body C4RevisionFlags flags; ///< Revision flags }; /** Retrieves changes, in chronological order. You do not have to fetch changes immediately during the callback, but can wait for a convenient time, for instance scheduling a task on a thread/queue/event-loop. \note The usual way to use this method is to allocate a reasonably sized buffer, maybe 100 changes, and keep calling getChanges passing in the entire buffer, until it returns 0 to indicate no more changes. */ virtual uint32_t getChanges(Change outChanges[C4NONNULL], uint32_t maxChanges, bool *outExternal) =0; }; /** A registration for callbacks whenever a specific document in a collection changes. The registration lasts until this object is destructed. */ struct C4DocumentObserver : public fleece::InstanceCounted, C4Base { using Callback = C4Collection::DocumentObserverCallback; static std::unique_ptr<C4DocumentObserver> create(C4Collection*, slice docID, Callback); virtual ~C4DocumentObserver() =default; protected: C4DocumentObserver() =default; }; C4_ASSUME_NONNULL_END
39.833333
98
0.64757
[ "object" ]
a95694e077a536e50b12720f79abed350d42f5fe
7,613
cpp
C++
src/cold.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
1
2018-09-16T03:17:50.000Z
2018-09-16T03:17:50.000Z
src/cold.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
src/cold.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
#include "system.h" int obj_data :: vs_cold( ) { int save = 100; int i; for( i = 0; i < MAX_MATERIAL; i++ ) if( is_set( &pIndexData->materials, i ) ) save = min( save, material_table[i].save_cold ); if( pIndexData->item_type != ITEM_ARMOR || pIndexData->item_type != ITEM_WEAPON || pIndexData->item_type != ITEM_SHIELD ) return save; return save+value[0]*(100-save)/(value[0]+2); } bool affected_flames( char_data* ch ) { if( !is_set( ch->affected_by, AFF_FLAME_SHIELD ) && !is_set( ch->affected_by, AFF_FIRE_SHIELD ) && !is_set( ch->affected_by, AFF_FIERY_SHIELD ) && !is_set( ch->affected_by, AFF_INFERNO_SHIELD ) ) return FALSE; return TRUE; } /* * COLD SPELLS */ bool spell_resist_cold( char_data* ch, char_data* victim, void*, int level, int duration ) { spell_affect( ch, victim, level, duration, SPELL_RESIST_COLD, AFF_RESIST_COLD ); return TRUE; } bool spell_chilling_touch( char_data* ch, char_data* victim, void* vo, int level, int duration ) { obj_data* obj = (obj_data*) vo; int save; /* Quaff/Drinking */ if( ch == NULL && obj == NULL ) { fsend( victim, "You feel incredible pain, as your insides unnaturally freeze from the liquid you consumed. Luckily the pain does not last for long." ); fsend_seen( victim, "%s turns blue in coloration, and spasms in pain - %s does not survive long.", victim, victim->He_She( ) ); death_message( victim ); death( victim, NULL, "freezing to death" ); return TRUE; } /* Fill */ if( ch == NULL ) { if( obj->metal( ) || is_set( &obj->materials, MAT_STONE ) ) return FALSE; fsend( victim, "The freezing cold liquid solidifies %s, which you quickly drop and it shatters on impact." ); fsend( *victim->array, "%s quickly drops %s, which shatters on impact.", victim, obj ); obj->Extract( obj->selected ); return TRUE; } /* Dip */ if( duration == -3 ) { save = obj->vs_cold( ); if( number_range( 0, 99 ) > save ) { if( number_range( 0, 99 ) > save ) { send( *ch->array, "%s shatters from the contact with the freezing cold.\r\n", obj ); obj->Extract( 1 ); return TRUE; } send( ch, "%s is partially destroyed by the cold.\r\n", obj ); } return TRUE; } /* Throw-Cast */ damage_element( victim, ch, spell_damage( SPELL_CHILLING_TOUCH, level ), "*the touch of ice", ATT_COLD ); return TRUE; } bool spell_freeze( char_data* ch, char_data* victim, void*, int level, int ) { damage_cold( victim, ch, spell_damage( SPELL_FREEZE, level ), "*the sphere of cold" ); return TRUE; } bool spell_ice_storm( char_data* ch, char_data* victim, void*, int level, int ) { damage_cold( victim, ch, spell_damage( SPELL_ICE_STORM, level ), "*the icy blast" ); return TRUE; } bool spell_ice_lance( char_data* ch, char_data* victim, void*, int level, int ) { damage_cold( victim, ch, spell_damage( SPELL_ICE_LANCE, level ), "*the frigid pierce" ); return TRUE; } bool spell_hoar_frost( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "hoar frost" ) ) return TRUE; if( affected_flames( victim ) ) { send( victim, "The hoar frost fails to form around you.\r\n" ); send_seen( victim, "The flames protecting %s prevent the formation of hoar frost.\r\n", victim ); return TRUE; } if( is_submerged( victim ) ) { send( ch, "The hoar frost encases you in a solid block of ice.\r\n" ); send_seen( ch, "The water around %s turns to an encasing solid ice.\r\n", victim ); damage_cold( ch, NULL, spell_damage( SPELL_HOAR_FROST, 0, 0 ), "The encasing ice" ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_HOAR_FROST, AFF_HOAR_FROST ); return TRUE; } bool spell_frost_shield( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "frost shield" ) ) return TRUE; if( affected_flames( victim ) ) { send( victim, "The frost fails to form around you.\r\n" ); send_seen( victim, "The flames protecting %s prevent the formation of frost.\r\n", victim ); return TRUE; } if( is_submerged( victim ) ) { send( ch, "The frost shield encases you in a solid block of ice.\r\n" ); send_seen( ch, "The water around %s turns to an encasing solid ice.\r\n", victim ); damage_cold( ch, NULL, spell_damage( SPELL_FROST_SHIELD, 0, 0 ), "The encasing ice" ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_FROST_SHIELD, AFF_FROST_SHIELD ); return TRUE; } bool spell_hoar_shield( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "hoar shield" ) ) return TRUE; if( affected_flames( victim ) ) { send( victim, "The hoar is prevented from forming by the flames protecting you.\r\n" ); send_seen( victim, "The flames protecting %s prevents the formation of the hoar.\r\n", victim ); return TRUE; } if( is_submerged( victim ) ) { send( ch, "The hoar shield encases you in a solid block of ice.\r\n" ); send_seen( ch, "The water around %s turns to an encasing solid ice.\r\n", victim ); damage_cold( ch, NULL, spell_damage( SPELL_FROST_SHIELD, 0, 0 ), "The encasing ice" ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_HOAR_SHIELD, AFF_HOAR_SHIELD ); return TRUE; } bool spell_absolute_zero( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "absolute zero" ) ) return TRUE; if( affected_flames( victim ) ) { send( victim, "The absolute freezing is prevented from forming by the flames protecting you.\r\n" ); send_seen( victim, "The flames protecting %s prevent the forming of the absolute freezing.\r\n", victim ); return TRUE; } if( is_submerged( victim ) ) { send( ch, "The shield of absolute zero encases you in a solid block of ice.\r\n" ); send_seen( ch, "The water around %s turns to an encasing solid ice.\r\n", victim ); damage_cold( ch, NULL, spell_damage( SPELL_ABSOLUTE_ZERO, 0, 0 ), "The encasing ice" ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_ABSOLUTE_ZERO, AFF_ABSOLUTE_ZERO ); return TRUE; } bool spell_solid( char_data* ch, char_data* victim, void*, int level, int duration ) { damage_element( victim, ch, spell_damage( SPELL_SOLID, level ), "*the encasing ice", ATT_COLD ); if( victim->hit >= 0 ) spell_affect( ch, victim, level, duration, SPELL_SOLID, AFF_SLOW ); return TRUE; } /* * Druid Cold Spells */ bool spell_winters_gale( char_data* ch, char_data* victim, void*, int level, int ) { ch->move -= spell_damage( SPELL_WINTERS_GALE, level ); ch->move = max( 0, ch->move ); damage_element( victim, ch, spell_damage( SPELL_WINTERS_GALE, level ), "*The howling ice and wind", ATT_COLD ); return TRUE; } bool spell_winters_touch( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_WINTERS_TOUCH, level ), "*The winters first frost", ATT_COLD ); return TRUE; } bool spell_hail_stones( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_HAIL_STONES, level ), "*The frosty hail stones", ATT_COLD ); return TRUE; } bool spell_breath_serpent( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_BREATH_SERPENT, level ), "*The ice serpents breath", ATT_COLD ); return TRUE; }
30.090909
156
0.665703
[ "solid" ]
a95c70a74434d7a11a7d855b2d7a6b6b93f943c4
2,164
cpp
C++
benchmark/askit_release/rkdtsrc/parallelIO/test_display_file.cpp
maumueller/rehashing
38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad
[ "MIT" ]
20
2019-05-14T20:08:08.000Z
2021-09-22T20:48:29.000Z
benchmark/askit_release/rkdtsrc/parallelIO/test_display_file.cpp
maumueller/rehashing
38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad
[ "MIT" ]
2
2020-10-06T09:47:52.000Z
2020-10-09T04:27:39.000Z
benchmark/askit_release/rkdtsrc/parallelIO/test_display_file.cpp
maumueller/rehashing
38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad
[ "MIT" ]
2
2019-08-11T22:29:45.000Z
2020-10-08T20:02:46.000Z
#include <mpi.h> #include <iostream> #include <fstream> #include <cctype> #include <omp.h> #include <string> #include <climits> #include "CmdLine.h" #include "parallelIO.h" #include "generator.h" using namespace Torch; using namespace std; void printpbyp(double *arr, int numof_points, int dim, MPI_Comm comm) { int rank, size; MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank); long dummy_n = numof_points; long offset; MPI_Scan(&dummy_n, &offset, 1, MPI_LONG, MPI_SUM, comm); offset -= dummy_n; for(int r = 0; r < size; r++) { if(rank == r) { for(int i = 0; i < numof_points; i++) { cout<<"(rank "<<rank<<") "<<offset+i<<": "; for(int j = 0; j < dim; j++) cout<<arr[i*dim+j]<<" "; cout<<endl; } } cout.flush(); MPI_Barrier(comm); } } int main(int argc, char **argv) { // command lines CmdLine cmd; const char *pchHelp = "General info."; cmd.addInfo(pchHelp); char *ptrInputFile = NULL; cmd.addSCmdOption("-file", &ptrInputFile, "data.bx", "file"); long numof_points; cmd.addLCmdOption("-n", &numof_points, 1000, "number of points per rank"); int dim; cmd.addICmdOption("-d", &dim, 1, "dim"); bool isBinary; cmd.addBCmdOption("-binary", &isBinary, false, "use binary file"); cmd.read(argc,argv); // program start int rank, size; MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); if(isBinary) { vector<double> arr; int dummy_numof_points; knn::mpi_binread(ptrInputFile, numof_points, dim, dummy_numof_points, arr, comm); if(rank == 0) cout<<"data read: "<<endl; printpbyp(&(arr[0]), dummy_numof_points, dim, comm); if(rank == 0) cout<<endl; } else { vector<double> arr; knn::mpi_dlmread(ptrInputFile, numof_points, dim, arr, comm, false); if(rank == 0) cout<<"data read: "<<endl; printpbyp(&(arr[0]), numof_points, dim, comm); if(rank == 0) cout<<endl; } MPI_Finalize(); return 0; }
23.268817
89
0.5878
[ "vector" ]
a96a133e1ffa0e0abbe87a648913948f555228a5
636
hpp
C++
Sniper.hpp
talcome/WarGame
1af9cba399cae255d95618814881f06021f5a239
[ "MIT" ]
null
null
null
Sniper.hpp
talcome/WarGame
1af9cba399cae255d95618814881f06021f5a239
[ "MIT" ]
null
null
null
Sniper.hpp
talcome/WarGame
1af9cba399cae255d95618814881f06021f5a239
[ "MIT" ]
null
null
null
#pragma once #include "Soldier.hpp" namespace WarGame { class Sniper : public Soldier { public: explicit Sniper(uint playerID): Soldier(playerID,100,100,50){} Sniper(uint playerID, uint currHealth,uint maxHealth,uint damage):Soldier(playerID,currHealth,maxHealth,damage){} ~Sniper() override= default; std::pair<int,int> getEnemyLoc(std::vector<std::vector<Soldier*>> &board) override ; void attack(std::vector<std::vector<Soldier *>> &board, std::pair<int, int> source) override; void heal() override; }; } // end namespace WarGame
31.8
125
0.632075
[ "vector" ]
a96c28ed36ad060357584abf1cddf773a449c3ca
2,609
cpp
C++
exercises/Perception-Driven_Manipulation/ros2/template_ws/src/pick_and_place_application/src/tasks/detect_box_pick.cpp
DaveBGld/industrial_training
e3cbc892971b995625102d549846f4fc6c783df8
[ "Apache-2.0" ]
324
2015-01-31T07:35:37.000Z
2022-03-27T09:30:14.000Z
exercises/Perception-Driven_Manipulation/ros2/template_ws/src/pick_and_place_application/src/tasks/detect_box_pick.cpp
AhmedMounir/industrial_training
e6761c7bee65d3802fee6cf7c99e3113d3dc1af2
[ "Apache-2.0" ]
226
2015-01-20T17:15:56.000Z
2022-01-19T04:55:23.000Z
exercises/Perception-Driven_Manipulation/ros2/template_ws/src/pick_and_place_application/src/tasks/detect_box_pick.cpp
AhmedMounir/industrial_training
e6761c7bee65d3802fee6cf7c99e3113d3dc1af2
[ "Apache-2.0" ]
219
2015-03-29T03:05:11.000Z
2022-03-23T11:12:43.000Z
#include <pick_and_place_application/pick_and_place.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> /* DETECTING BOX PICK POSE Goal: - Get the box location in the world frame by calling the target recognition service. - Return the box pose. */ geometry_msgs::msg::Pose pick_and_place_application::PickAndPlaceApp::detectBox() { using RequestType = pick_and_place_msgs::srv::GetTargetPose::Request; using ResponseType = pick_and_place_msgs::srv::GetTargetPose::Response; RCLCPP_ERROR_STREAM(node->get_logger(),"detectBox is not implemented yet. Aborting."); exit(1); // creating shape for recognition shape_msgs::msg::SolidPrimitive shape; shape.type = shape_msgs::msg::SolidPrimitive::BOX; shape.dimensions.resize(3); shape.dimensions[0] = cfg.BOX_SIZE.getX(); shape.dimensions[1] = cfg.BOX_SIZE.getY(); shape.dimensions[2] = cfg.BOX_SIZE.getZ(); // creating request object RequestType::SharedPtr req = std::make_shared<RequestType>(); req->shape = shape; req->world_frame_id = cfg.WORLD_FRAME_ID; req->ar_tag_frame_id = cfg.AR_TAG_FRAME_ID; /* Fill Code: * Goal: * - Call target recognition service and save the result. * Hint: * - use the service client to send the request object to the service server */ geometry_msgs::msg::Pose box_pose; // send request asynchronously std::shared_future<ResponseType::SharedPtr> response_fut; // UNCOMMENT AND COMPLETE: response_fut = target_recognition_client->...; // now wait for result using the "wait_for" method of the future object std::future_status st = response_fut.wait_for(rclcpp::Duration::from_seconds(20.0).to_chrono<std::chrono::seconds>()); if (st == std::future_status ::ready) { ResponseType::SharedPtr response = response_fut.get(); if (response->succeeded) { // save target pose into the box pose variable box_pose = response->target_pose; RCLCPP_INFO_STREAM(node->get_logger(), "target recognition succeeded"); } else { RCLCPP_ERROR_STREAM(node->get_logger(), "Target recognition failed"); throw std::runtime_error("Service call failure"); } } else { RCLCPP_ERROR_STREAM(node->get_logger(), "Service call for target recognition failed with response timed out"); throw std::runtime_error("Service call failure"); } // updating box marker for visualization in rviz cfg.MARKER_MESSAGE.header.frame_id = cfg.WORLD_FRAME_ID; cfg.MARKER_MESSAGE.pose = box_pose; cfg.MARKER_MESSAGE.pose.position.z = box_pose.position.z - 0.5f * cfg.BOX_SIZE.z(); showBox(true); return box_pose; }
35.256757
120
0.725949
[ "object", "shape" ]
a96ce884255c63811ced8d745bf0038f6c6aecf8
18,416
cpp
C++
src/mongo/db/repl/tenant_migration_donor_op_observer.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/repl/tenant_migration_donor_op_observer.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/repl/tenant_migration_donor_op_observer.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2020-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/catalog_raii.h" #include "mongo/db/repl/tenant_migration_access_blocker_util.h" #include "mongo/db/repl/tenant_migration_donor_op_observer.h" #include "mongo/db/repl/tenant_migration_state_machine_gen.h" namespace mongo { namespace repl { namespace { MONGO_FAIL_POINT_DEFINE(donorOpObserverFailAfterOnInsert); MONGO_FAIL_POINT_DEFINE(donorOpObserverFailAfterOnUpdate); const auto tenantIdToDeleteDecoration = OperationContext::declareDecoration<boost::optional<std::string>>(); const auto migrationIdToDeleteDecoration = OperationContext::declareDecoration<boost::optional<UUID>>(); /** * Initializes the TenantMigrationDonorAccessBlocker for the tenant migration denoted by the given * state doc. */ void onTransitionToAbortingIndexBuilds(OperationContext* opCtx, const TenantMigrationDonorDocument& donorStateDoc) { invariant(donorStateDoc.getState() == TenantMigrationDonorStateEnum::kAbortingIndexBuilds); if (donorStateDoc.getProtocol().value_or(MigrationProtocolEnum::kMultitenantMigrations) == MigrationProtocolEnum::kMultitenantMigrations) { auto mtab = std::make_shared<TenantMigrationDonorAccessBlocker>( opCtx->getServiceContext(), donorStateDoc.getId(), donorStateDoc.getTenantId().toString(), MigrationProtocolEnum::kMultitenantMigrations, donorStateDoc.getRecipientConnectionString().toString()); TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .add(donorStateDoc.getTenantId(), mtab); if (opCtx->writesAreReplicated()) { // onRollback is not registered on secondaries since secondaries should not fail to // apply the write. opCtx->recoveryUnit()->onRollback([opCtx, donorStateDoc] { TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .remove(donorStateDoc.getTenantId(), TenantMigrationAccessBlocker::BlockerType::kDonor); }); } } else { tassert(6448702, "Bad protocol", donorStateDoc.getProtocol() == MigrationProtocolEnum::kShardMerge); auto mtab = std::make_shared<TenantMigrationDonorAccessBlocker>( opCtx->getServiceContext(), donorStateDoc.getId(), donorStateDoc.getTenantId().toString(), MigrationProtocolEnum::kShardMerge, donorStateDoc.getRecipientConnectionString().toString()); TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .addShardMergeDonorAccessBlocker(mtab); if (opCtx->writesAreReplicated()) { // onRollback is not registered on secondaries since secondaries should not fail to // apply the write. opCtx->recoveryUnit()->onRollback([opCtx, donorStateDoc] { TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .removeShardMergeDonorAccessBlocker(donorStateDoc.getId()); }); } } } /** * Transitions the TenantMigrationDonorAccessBlocker to the blocking state. */ void onTransitionToBlocking(OperationContext* opCtx, const TenantMigrationDonorDocument& donorStateDoc) { invariant(donorStateDoc.getState() == TenantMigrationDonorStateEnum::kBlocking); invariant(donorStateDoc.getBlockTimestamp()); auto mtab = tenant_migration_access_blocker::getTenantMigrationDonorAccessBlocker( opCtx->getServiceContext(), donorStateDoc.getTenantId()); invariant(mtab); if (!opCtx->writesAreReplicated()) { // A primary calls startBlockingWrites on the TenantMigrationDonorAccessBlocker before // reserving the OpTime for the "start blocking" write, so only secondaries call // startBlockingWrites on the TenantMigrationDonorAccessBlocker in the op observer. mtab->startBlockingWrites(); } // Both primaries and secondaries call startBlockingReadsAfter in the op observer, since // startBlockingReadsAfter just needs to be called before the "start blocking" write's oplog // hole is filled. mtab->startBlockingReadsAfter(donorStateDoc.getBlockTimestamp().get()); } /** * Transitions the TenantMigrationDonorAccessBlocker to the committed state. */ void onTransitionToCommitted(OperationContext* opCtx, const TenantMigrationDonorDocument& donorStateDoc) { invariant(donorStateDoc.getState() == TenantMigrationDonorStateEnum::kCommitted); invariant(donorStateDoc.getCommitOrAbortOpTime()); auto mtab = tenant_migration_access_blocker::getTenantMigrationDonorAccessBlocker( opCtx->getServiceContext(), donorStateDoc.getTenantId()); invariant(mtab); mtab->setCommitOpTime(opCtx, donorStateDoc.getCommitOrAbortOpTime().get()); } /** * Transitions the TenantMigrationDonorAccessBlocker to the aborted state. */ void onTransitionToAborted(OperationContext* opCtx, const TenantMigrationDonorDocument& donorStateDoc) { invariant(donorStateDoc.getState() == TenantMigrationDonorStateEnum::kAborted); invariant(donorStateDoc.getCommitOrAbortOpTime()); auto mtab = tenant_migration_access_blocker::getTenantMigrationDonorAccessBlocker( opCtx->getServiceContext(), donorStateDoc.getTenantId()); invariant(mtab); mtab->setAbortOpTime(opCtx, donorStateDoc.getCommitOrAbortOpTime().get()); } /** * Used to update the TenantMigrationDonorAccessBlocker for the migration denoted by the donor's * state doc once the write for updating the doc is committed. */ class TenantMigrationDonorCommitOrAbortHandler final : public RecoveryUnit::Change { public: TenantMigrationDonorCommitOrAbortHandler(OperationContext* opCtx, const TenantMigrationDonorDocument donorStateDoc) : _opCtx(opCtx), _donorStateDoc(std::move(donorStateDoc)) {} void commit(boost::optional<Timestamp>) override { if (_donorStateDoc.getExpireAt()) { auto mtab = tenant_migration_access_blocker::getTenantMigrationDonorAccessBlocker( _opCtx->getServiceContext(), _donorStateDoc.getTenantId()); if (!mtab) { // The state doc and TenantMigrationDonorAccessBlocker for this migration were // removed immediately after expireAt was set. This is unlikely to occur in // production where the garbage collection delay should be sufficiently large. return; } if (!_opCtx->writesAreReplicated()) { // Setting expireAt implies that the TenantMigrationDonorAccessBlocker for this // migration will be removed shortly after this. However, a lagged secondary // might not manage to advance its majority commit point past the migration // commit or abort opTime and consequently transition out of the blocking state // before the TenantMigrationDonorAccessBlocker is removed. When this occurs, // blocked reads or writes will be left waiting for the migration decision // indefinitely. To avoid that, notify the TenantMigrationDonorAccessBlocker // here that the commit or abort opTime has been majority committed (guaranteed // to be true since by design the donor never marks its state doc as garbage // collectable before the migration decision is majority committed). mtab->onMajorityCommitPointUpdate(_donorStateDoc.getCommitOrAbortOpTime().get()); } if (_donorStateDoc.getState() == TenantMigrationDonorStateEnum::kAborted) { invariant(mtab->inStateAborted()); // The migration durably aborted and is now marked as garbage collectable, // remove its TenantMigrationDonorAccessBlocker right away to allow back-to-back // migration retries. if (_donorStateDoc.getProtocol().value_or( MigrationProtocolEnum::kMultitenantMigrations) == MigrationProtocolEnum::kMultitenantMigrations) { TenantMigrationAccessBlockerRegistry::get(_opCtx->getServiceContext()) .remove(_donorStateDoc.getTenantId(), TenantMigrationAccessBlocker::BlockerType::kDonor); } else { tassert(6448701, "Bad protocol", _donorStateDoc.getProtocol() == MigrationProtocolEnum::kShardMerge); TenantMigrationAccessBlockerRegistry::get(_opCtx->getServiceContext()) .removeShardMergeDonorAccessBlocker(_donorStateDoc.getId()); } } return; } switch (_donorStateDoc.getState()) { case TenantMigrationDonorStateEnum::kCommitted: onTransitionToCommitted(_opCtx, _donorStateDoc); break; case TenantMigrationDonorStateEnum::kAborted: onTransitionToAborted(_opCtx, _donorStateDoc); break; default: MONGO_UNREACHABLE; } } void rollback() override {} private: OperationContext* _opCtx; const TenantMigrationDonorDocument _donorStateDoc; }; } // namespace void TenantMigrationDonorOpObserver::onInserts(OperationContext* opCtx, const NamespaceString& nss, const UUID& uuid, std::vector<InsertStatement>::const_iterator first, std::vector<InsertStatement>::const_iterator last, bool fromMigrate) { if (nss == NamespaceString::kTenantMigrationDonorsNamespace && !tenant_migration_access_blocker::inRecoveryMode(opCtx)) { for (auto it = first; it != last; it++) { auto donorStateDoc = tenant_migration_access_blocker::parseDonorStateDocument(it->doc); switch (donorStateDoc.getState()) { case TenantMigrationDonorStateEnum::kAbortingIndexBuilds: onTransitionToAbortingIndexBuilds(opCtx, donorStateDoc); break; case TenantMigrationDonorStateEnum::kDataSync: case TenantMigrationDonorStateEnum::kBlocking: case TenantMigrationDonorStateEnum::kCommitted: case TenantMigrationDonorStateEnum::kAborted: uasserted(ErrorCodes::IllegalOperation, "cannot insert a donor's state doc with 'state' other than 'aborting " "index builds'"); break; default: MONGO_UNREACHABLE; } } if (MONGO_unlikely(donorOpObserverFailAfterOnInsert.shouldFail())) { uasserted(ErrorCodes::InternalError, "fail donor's state doc insert"); } } } void TenantMigrationDonorOpObserver::onUpdate(OperationContext* opCtx, const OplogUpdateEntryArgs& args) { if (args.nss == NamespaceString::kTenantMigrationDonorsNamespace && !tenant_migration_access_blocker::inRecoveryMode(opCtx)) { auto donorStateDoc = tenant_migration_access_blocker::parseDonorStateDocument(args.updateArgs->updatedDoc); switch (donorStateDoc.getState()) { case TenantMigrationDonorStateEnum::kDataSync: break; case TenantMigrationDonorStateEnum::kBlocking: onTransitionToBlocking(opCtx, donorStateDoc); break; case TenantMigrationDonorStateEnum::kCommitted: case TenantMigrationDonorStateEnum::kAborted: opCtx->recoveryUnit()->registerChange( std::make_unique<TenantMigrationDonorCommitOrAbortHandler>(opCtx, donorStateDoc)); break; default: MONGO_UNREACHABLE; } if (MONGO_unlikely(donorOpObserverFailAfterOnUpdate.shouldFail())) { uasserted(ErrorCodes::InternalError, "fail donor's state doc update"); } } } void TenantMigrationDonorOpObserver::aboutToDelete(OperationContext* opCtx, NamespaceString const& nss, const UUID& uuid, BSONObj const& doc) { if (nss == NamespaceString::kTenantMigrationDonorsNamespace && !tenant_migration_access_blocker::inRecoveryMode(opCtx)) { auto donorStateDoc = tenant_migration_access_blocker::parseDonorStateDocument(doc); uassert(ErrorCodes::IllegalOperation, str::stream() << "cannot delete a donor's state document " << doc << " since it has not been marked as garbage collectable", donorStateDoc.getExpireAt()); // To support back-to-back migration retries, when a migration is aborted, we remove its // TenantMigrationDonorAccessBlocker as soon as its donor state doc is marked as garbage // collectable. So onDelete should skip removing the TenantMigrationDonorAccessBlocker for // aborted migrations. if (donorStateDoc.getProtocol().value_or(MigrationProtocolEnum::kMultitenantMigrations) == MigrationProtocolEnum::kMultitenantMigrations) { tenantIdToDeleteDecoration(opCtx) = donorStateDoc.getState() == TenantMigrationDonorStateEnum::kAborted ? boost::none : boost::make_optional(donorStateDoc.getTenantId().toString()); } else { tassert(6448700, "Bad protocol", donorStateDoc.getProtocol() == MigrationProtocolEnum::kShardMerge); migrationIdToDeleteDecoration(opCtx) = donorStateDoc.getState() == TenantMigrationDonorStateEnum::kAborted ? boost::none : boost::make_optional(donorStateDoc.getId()); } } } void TenantMigrationDonorOpObserver::onDelete(OperationContext* opCtx, const NamespaceString& nss, const UUID& uuid, StmtId stmtId, const OplogDeleteEntryArgs& args) { if (nss == NamespaceString::kTenantMigrationDonorsNamespace && !tenant_migration_access_blocker::inRecoveryMode(opCtx)) { if (tenantIdToDeleteDecoration(opCtx)) { opCtx->recoveryUnit()->onCommit([opCtx](boost::optional<Timestamp>) { TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .remove(tenantIdToDeleteDecoration(opCtx).get(), TenantMigrationAccessBlocker::BlockerType::kDonor); }); } if (migrationIdToDeleteDecoration(opCtx)) { opCtx->recoveryUnit()->onCommit([opCtx](boost::optional<Timestamp>) { TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .removeShardMergeDonorAccessBlocker(migrationIdToDeleteDecoration(opCtx).get()); }); } } } repl::OpTime TenantMigrationDonorOpObserver::onDropCollection(OperationContext* opCtx, const NamespaceString& collectionName, const UUID& uuid, std::uint64_t numRecords, const CollectionDropType dropType) { if (collectionName == NamespaceString::kTenantMigrationDonorsNamespace) { opCtx->recoveryUnit()->onCommit([opCtx](boost::optional<Timestamp>) { TenantMigrationAccessBlockerRegistry::get(opCtx->getServiceContext()) .removeAll(TenantMigrationAccessBlocker::BlockerType::kDonor); }); } return {}; } void TenantMigrationDonorOpObserver::onMajorityCommitPointUpdate( ServiceContext* service, const repl::OpTime& newCommitPoint) { TenantMigrationAccessBlockerRegistry::get(service).onMajorityCommitPointUpdate(newCommitPoint); } } // namespace repl } // namespace mongo
48.719577
100
0.641887
[ "vector" ]
a977125c4a4921e869197359339ce2d52c9aa2b1
18,372
cpp
C++
intel_extension_for_pytorch/csrc/aten/cpu/PixelShuffle.cpp
Peach-He/intel-extension-for-pytorch
d3d4d2bc5e8637e251f49d70ae9982c4a1e65935
[ "Apache-2.0" ]
null
null
null
intel_extension_for_pytorch/csrc/aten/cpu/PixelShuffle.cpp
Peach-He/intel-extension-for-pytorch
d3d4d2bc5e8637e251f49d70ae9982c4a1e65935
[ "Apache-2.0" ]
null
null
null
intel_extension_for_pytorch/csrc/aten/cpu/PixelShuffle.cpp
Peach-He/intel-extension-for-pytorch
d3d4d2bc5e8637e251f49d70ae9982c4a1e65935
[ "Apache-2.0" ]
null
null
null
#include <ATen/NativeFunctions.h> #include <c10/util/Exception.h> #include <ATen/ATen.h> #include <ATen/Dispatch.h> #include <ATen/Parallel.h> #include <ATen/native/DispatchStub.h> #include <ATen/native/cpu/utils.h> #include <algorithm> #include <numeric> #include <vector> #include "PixelShuffle.h" #include "csrc/autocast/autocast_mode.h" #include "csrc/autocast/autocast_verbose.h" #include "csrc/utils/library.h" namespace torch_ipex { namespace cpu { template <typename scalar_t> void cpu_pixel_shuffle( at::Tensor& output, const at::Tensor& input, int64_t upscale_factor) { auto input_data = input.data_ptr<scalar_t>(); auto output_data = output.data_ptr<scalar_t>(); // [(B1...Bn), C, H, W] => [N, C, H, W] int64_t channels = input.size(-3); int64_t height = input.size(-2); int64_t width = input.size(-1); int64_t sub_channels = channels / (upscale_factor * upscale_factor); int64_t numel = input.numel(); int64_t nbatch = numel / (channels * height * width); int64_t S = upscale_factor; // input strides int64_t stride_n = channels * height * width; int64_t stride_c = S * S * height * width; int64_t stride_s1 = S * height * width; int64_t stride_s2 = height * width; int64_t stride_h = width; int64_t stride_w = 1; // input tensor shape of [n, c, s1, s2, h, w] // output tensor shape of [n, c, h, s1, w, s2] at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { int64_t n{0}, c{0}, h{0}, s1{0}, w{0}, s2{0}; at::native::data_index_init( begin, n, nbatch, c, sub_channels, h, height, s1, S, w, width, s2, S); for (int64_t i = begin; i < end; i++) { int64_t input_offset = n * stride_n + c * stride_c + s1 * stride_s1 + s2 * stride_s2 + h * stride_h + w * stride_w; output_data[i] = input_data[input_offset]; at::native::data_index_step( n, nbatch, c, sub_channels, h, height, s1, S, w, width, s2, S); } }); } template <typename scalar_t> void cpu_pixel_shuffle_channels_last( at::Tensor& output, const at::Tensor& input, int64_t upscale_factor) { TORCH_CHECK( input.ndimension() == 4, "pixel shuffle with channels last format supports tensors with 4 dims"); auto input_data = input.data_ptr<scalar_t>(); auto output_data = output.data_ptr<scalar_t>(); int64_t nbatch = input.size(0); int64_t channels = input.size(1); int64_t height = input.size(2); int64_t width = input.size(3); int64_t sub_channels = channels / (upscale_factor * upscale_factor); int64_t numel = input.numel(); int64_t S = upscale_factor; // input strides int64_t stride_n = height * width * channels; int64_t stride_h = width * channels; int64_t stride_w = channels; int64_t stride_c = S * S; int64_t stride_s1 = S; int64_t stride_s2 = 1; // input tensor shape of [n, h, w, c, s1, s2] // output tensor shape of [n, h, s1, w, s2, c] at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { int64_t n{0}, h{0}, s1{0}, w{0}, s2{0}, c{0}; at::native::data_index_init( begin, n, nbatch, h, height, s1, S, w, width, s2, S, c, sub_channels); for (int64_t i = begin; i < end; i++) { int64_t input_offset = n * stride_n + h * stride_h + w * stride_w + c * stride_c + s1 * stride_s1 + s2 * stride_s2; output_data[i] = input_data[input_offset]; at::native::data_index_step( n, nbatch, h, height, s1, S, w, width, s2, S, c, sub_channels); } }); } template <typename scalar_t> void cpu_pixel_shuffle_backward( at::Tensor& grad_input, const at::Tensor& grad_output, int64_t upscale_factor) { auto grad_input_data = grad_input.data_ptr<scalar_t>(); auto grad_output_data = grad_output.data_ptr<scalar_t>(); // [(B1...Bn), C, H, W] => [N, C, H, W] int64_t channels = grad_input.size(-3); int64_t height = grad_input.size(-2); int64_t width = grad_input.size(-1); int64_t sub_channels = channels / (upscale_factor * upscale_factor); int64_t numel = grad_input.numel(); int64_t nbatch = numel / (channels * height * width); int64_t S = upscale_factor; // grad_output strides int64_t stride_n = channels * height * width; int64_t stride_c = height * S * width * S; int64_t stride_h = S * width * S; int64_t stride_s1 = width * S; int64_t stride_w = S; int64_t stride_s2 = 1; // grad_output tensor shape of [n, c, h, s1, w, s2] // grad_input tensor shape of [n, c, s1, s2, h, w] at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { int64_t n{0}, c{0}, s1{0}, s2{0}, h{0}, w{0}; at::native::data_index_init( begin, n, nbatch, c, sub_channels, s1, S, s2, S, h, height, w, width); for (int64_t i = begin; i < end; i++) { int64_t output_offset = n * stride_n + c * stride_c + h * stride_h + s1 * stride_s1 + w * stride_w + s2 * stride_s2; grad_input_data[i] = grad_output_data[output_offset]; at::native::data_index_step( n, nbatch, c, sub_channels, s1, S, s2, S, h, height, w, width); } }); } template <typename scalar_t> void cpu_pixel_shuffle_backward_channels_last( at::Tensor& grad_input, const at::Tensor& grad_output, int64_t upscale_factor) { TORCH_CHECK( grad_output.ndimension() == 4, "pixel shuffle with channels last format supports tensors with 4 dims"); auto grad_input_data = grad_input.data_ptr<scalar_t>(); auto grad_output_data = grad_output.data_ptr<scalar_t>(); int64_t nbatch = grad_input.size(0); int64_t channels = grad_input.size(1); int64_t height = grad_input.size(2); int64_t width = grad_input.size(3); int64_t sub_channels = channels / (upscale_factor * upscale_factor); int64_t numel = grad_input.numel(); int64_t S = upscale_factor; // grad_output strides int64_t stride_n = height * width * channels; int64_t stride_h = S * width * S * sub_channels; int64_t stride_s1 = width * S * sub_channels; int64_t stride_w = S * sub_channels; int64_t stride_s2 = sub_channels; int64_t stride_c = 1; // grad_output tensor shape of [n, h, s1, w, s2, c] // grad_input tensor shape of [n, h, w, c, s1, s2] at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { int64_t n{0}, h{0}, w{0}, c{0}, s1{0}, s2{0}; at::native::data_index_init( begin, n, nbatch, h, height, w, width, c, sub_channels, s1, S, s2, S); for (int64_t i = begin; i < end; i++) { int64_t output_offset = n * stride_n + h * stride_h + s1 * stride_s1 + w * stride_w + s2 * stride_s2 + c * stride_c; grad_input_data[i] = grad_output_data[output_offset]; at::native::data_index_step( n, nbatch, h, height, w, width, c, sub_channels, s1, S, s2, S); } }); } void pixel_shuffle_kernel( at::Tensor& output, const at::Tensor& input, int64_t upscale_factor) { switch (input.suggest_memory_format()) { case at::MemoryFormat::Contiguous: { AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "pixel_shuffle", [&] { cpu_pixel_shuffle<scalar_t>(output, input, upscale_factor); }); break; } case at::MemoryFormat::ChannelsLast: { AT_DISPATCH_FLOATING_TYPES( input.scalar_type(), "pixel_shuffle_channels_last", [&] { cpu_pixel_shuffle_channels_last<scalar_t>( output, input, upscale_factor); }); break; } default: TORCH_CHECK( false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); } } void pixel_shuffle_backward_kernel( at::Tensor& grad_input, const at::Tensor& grad_output, int64_t upscale_factor) { switch (grad_output.suggest_memory_format()) { case at::MemoryFormat::Contiguous: { AT_DISPATCH_FLOATING_TYPES( grad_output.scalar_type(), "pixel_shuffle_backward", [&] { cpu_pixel_shuffle_backward<scalar_t>( grad_input, grad_output, upscale_factor); }); break; } case at::MemoryFormat::ChannelsLast: { AT_DISPATCH_FLOATING_TYPES( grad_output.scalar_type(), "pixel_shuffle_backward_channels_last", [&] { cpu_pixel_shuffle_backward_channels_last<scalar_t>( grad_input, grad_output, upscale_factor); }); break; } default: TORCH_CHECK( false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); } } void pixel_unshuffle_kernel( at::Tensor& output, const at::Tensor& input, int64_t downscale_factor) { switch (input.suggest_memory_format()) { case at::MemoryFormat::Contiguous: { // input tensor shape of [N, C, Hr, Wr] // output tensor shape of [N, Crr, H, W] AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "pixel_unshuffle", [&] { cpu_pixel_shuffle_backward<scalar_t>(output, input, downscale_factor); }); break; } case at::MemoryFormat::ChannelsLast: { // input tensor shape of [N, Hr, Wr, C] // output tensor shape of [N, H, W, Crr] AT_DISPATCH_FLOATING_TYPES( input.scalar_type(), "pixel_unshuffle_channels_last", [&] { cpu_pixel_shuffle_backward_channels_last<scalar_t>( output, input, downscale_factor); }); break; } default: TORCH_CHECK( false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); } } void pixel_unshuffle_backward_kernel( at::Tensor& grad_input, const at::Tensor& grad_output, int64_t downscale_factor) { switch (grad_output.suggest_memory_format()) { case at::MemoryFormat::Contiguous: { // grad_output tensor shape of [N, Crr, H, W] // grad_input tensor shape of [N, C, Hr, Wr] AT_DISPATCH_FLOATING_TYPES( grad_output.scalar_type(), "pixel_unshuffle_backward", [&] { cpu_pixel_shuffle<scalar_t>( grad_input, grad_output, downscale_factor); }); break; } case at::MemoryFormat::ChannelsLast: { // grad_output tensor shape of [N, H, W, Crr] // grad_input tensor shape of [N, Hr, Wr, C] AT_DISPATCH_FLOATING_TYPES( grad_output.scalar_type(), "pixel_unshuffle_backward_channels_last", [&] { cpu_pixel_shuffle_channels_last<scalar_t>( grad_input, grad_output, downscale_factor); }); break; } default: TORCH_CHECK( false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); } } at::Tensor pixel_shuffle_cpu(const at::Tensor& self, int64_t upscale_factor) { // Format: (B1, ..., Bn), C, H, W std::vector<int64_t> output_sizes( self.sizes().begin(), self.sizes().end() - 3); output_sizes.insert( output_sizes.end(), {self.size(-3) / upscale_factor / upscale_factor, self.size(-2) * upscale_factor, self.size(-1) * upscale_factor}); auto output = at::empty({0}, self.options()); auto memory_format = self.suggest_memory_format(); output.resize_(output_sizes, memory_format); auto input = self.contiguous(memory_format); pixel_shuffle_kernel(output, input, upscale_factor); return output; } at::Tensor pixel_shuffle_backward_cpu( const at::Tensor& grad_output, at::IntArrayRef input_sizes, int64_t upscale_factor) { auto grad_input = at::empty({0}, grad_output.options()); auto memory_format = grad_output.suggest_memory_format(); grad_input.resize_(input_sizes, memory_format); auto grad_output_ = grad_output.contiguous(memory_format); pixel_shuffle_backward_kernel(grad_input, grad_output_, upscale_factor); return grad_input; } at::Tensor pixel_unshuffle_cpu( const at::Tensor& self, int64_t downscale_factor) { // Format: (B1, ..., Bn), C, H, W std::vector<int64_t> output_sizes( self.sizes().begin(), self.sizes().end() - 3); output_sizes.insert( output_sizes.end(), {self.size(-3) * downscale_factor * downscale_factor, self.size(-2) / downscale_factor, self.size(-1) / downscale_factor}); auto output = at::empty({0}, self.options()); auto memory_format = self.suggest_memory_format(); output.resize_(output_sizes, memory_format); auto input = self.contiguous(memory_format); pixel_unshuffle_kernel(output, input, downscale_factor); return output; } at::Tensor pixel_unshuffle_backward_cpu( const at::Tensor& grad_output, at::IntArrayRef input_sizes, int64_t downscale_factor) { auto grad_input = at::empty({0}, grad_output.options()); auto memory_format = grad_output.suggest_memory_format(); grad_input.resize_(input_sizes, memory_format); auto grad_output_ = grad_output.contiguous(memory_format); pixel_unshuffle_backward_kernel(grad_input, grad_output_, downscale_factor); return grad_input; } at::Tensor pixel_shuffle(const at::Tensor& self, int64_t upscale_factor) { #if defined(IPEX_DISP_OP) printf("torch_ipex::pixel_shuffle\n"); #endif #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("torch_ipex::pixel_shuffle", std::vector<c10::IValue>({})); #endif TORCH_CHECK( self.dim() >= 3, "pixel_shuffle expects input to have at least 3 dimensions, but " "got input with ", self.dim(), " dimension(s)"); TORCH_CHECK( upscale_factor > 0, "pixel_shuffle expects a positive upscale_factor, but got ", upscale_factor); int64_t c = self.size(-3); int64_t upscale_factor_squared = upscale_factor * upscale_factor; TORCH_CHECK( c % upscale_factor_squared == 0, "pixel_shuffle expects its input's 'channel' dimension to be " "divisible by the square of " "upscale_factor, but input.size(-3)=", c, " is not divisible by ", upscale_factor_squared); // NOTE: The original PR registers the math_pixel_shuffle as an // operator, and then this operator will be dispatched to // native_pixel_shuffle. After that, the native_pixel_shuffle will be // dispatched to pixel_shuffle_cpu for cpu device and to math_pixel_shuffle // for other devices. if (at::GradMode::is_enabled()) return PixelShuffleOp::apply(self, upscale_factor); return PixelShuffleOp::_forward(self, upscale_factor); } at::Tensor pixel_unshuffle(const at::Tensor& self, int64_t downscale_factor) { #if defined(IPEX_DISP_OP) printf("torch_ipex::pixel_unshuffle\n"); #endif #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("torch_ipex::pixel_unshuffle", std::vector<c10::IValue>({})); #endif TORCH_CHECK( self.dim() >= 3, "pixel_unshuffle expects input to have at least 3 dimensions, " "but got input with ", self.dim(), " dimension(s)"); TORCH_CHECK( downscale_factor > 0, "pixel_unshuffle expects a positive downscale_factor, but got ", downscale_factor); int64_t h = self.size(-2); int64_t w = self.size(-1); TORCH_CHECK( h % downscale_factor == 0, "pixel_unshuffle expects height to be divisible by " "downscale_factor, but input.size(-2)=", h, " is not divisible by ", downscale_factor); TORCH_CHECK( w % downscale_factor == 0, "pixel_unshuffle expects width to be divisible by " "downscale_factor, but input.size(-1)=", w, " is not divisible by ", downscale_factor); if (at::GradMode::is_enabled()) return PixelUnshuffleOp::apply(self, downscale_factor); return PixelUnshuffleOp::_forward(self, downscale_factor); } at::Tensor PixelShuffleOp::_forward( const at::Tensor& self, int64_t upscale_factor) { #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("PixelShuffleOp::_forward", std::vector<c10::IValue>({})); #endif return pixel_shuffle_cpu(self, upscale_factor); } at::Tensor PixelShuffleOp::forward( torch::autograd::AutogradContext* ctx, const at::Tensor& self, int64_t upscale_factor) { #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("PixelShuffleOp::forward", std::vector<c10::IValue>({})); #endif at::AutoNonVariableTypeMode g; ctx->saved_data["upscale_factor"] = upscale_factor; ctx->saved_data["input_sizes"] = self.sizes(); return _forward(self, upscale_factor); } torch::autograd::tensor_list PixelShuffleOp::backward( torch::autograd::AutogradContext* ctx, torch::autograd::tensor_list grad_outputs) { #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("PixelShuffleOp::backward", std::vector<c10::IValue>({})); #endif at::Tensor grad_output = grad_outputs[0]; int64_t upscale_factor = ctx->saved_data["upscale_factor"].toInt(); auto input_sizes = ctx->saved_data["input_sizes"].toIntList().vec(); return { pixel_shuffle_backward_cpu(grad_output, input_sizes, upscale_factor), at::Tensor()}; } at::Tensor PixelUnshuffleOp::_forward( const at::Tensor& self, int64_t downscale_factor) { #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("PixelUnshuffleOp::_forward", std::vector<c10::IValue>({})); #endif return pixel_unshuffle_cpu(self, downscale_factor); } at::Tensor PixelUnshuffleOp::forward( torch::autograd::AutogradContext* ctx, const at::Tensor& self, int64_t downscale_factor) { #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("PixelUnshuffleOp::forward", std::vector<c10::IValue>({})); #endif at::AutoNonVariableTypeMode g; ctx->saved_data["downscale_factor"] = downscale_factor; ctx->saved_data["input_sizes"] = self.sizes(); return _forward(self, downscale_factor); } torch::autograd::tensor_list PixelUnshuffleOp::backward( torch::autograd::AutogradContext* ctx, torch::autograd::tensor_list grad_outputs) { #if defined(IPEX_PROFILE_OP) RECORD_FUNCTION("PixelUnshuffleOp::backward", std::vector<c10::IValue>({})); #endif at::Tensor grad_output = grad_outputs[0]; int64_t downscale_factor = ctx->saved_data["downscale_factor"].toInt(); auto input_sizes = ctx->saved_data["input_sizes"].toIntList().vec(); return { pixel_unshuffle_backward_cpu(grad_output, input_sizes, downscale_factor), at::Tensor()}; } IPEX_TORCH_LIBRARY_IMPL(aten, CPU, m) { m.impl( TORCH_SELECTIVE_NAME("aten::pixel_shuffle"), TORCH_FN((&torch_ipex::cpu::pixel_shuffle))); m.impl( TORCH_SELECTIVE_NAME("aten::pixel_unshuffle"), TORCH_FN((&torch_ipex::cpu::pixel_unshuffle))); } } // namespace cpu } // namespace torch_ipex
33.896679
79
0.671511
[ "shape", "vector" ]
a97a4b2062ede8e6d996c6495912b87ce2e5d532
6,296
cpp
C++
probot_anno_demo/src/probot_sync_demo.cpp
ps-micro/PROBOT_Anno
9ead90472c454405a65b28f0ca191b447e3e09ab
[ "Apache-2.0" ]
71
2019-04-16T09:22:26.000Z
2022-03-14T06:16:26.000Z
probot_anno_demo/src/probot_sync_demo.cpp
ps-micro/probot_ros
9ead90472c454405a65b28f0ca191b447e3e09ab
[ "Apache-2.0" ]
7
2020-01-14T16:57:59.000Z
2022-02-07T11:51:51.000Z
probot_anno_demo/src/probot_sync_demo.cpp
ps-micro/probot_ros
9ead90472c454405a65b28f0ca191b447e3e09ab
[ "Apache-2.0" ]
26
2019-04-16T08:48:21.000Z
2021-11-26T06:59:03.000Z
/*********************************************************************** Copyright 2019 Wuhan PS-Micro Technology Co., Itd. 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 <ros/ros.h> #include <moveit/move_group_interface/move_group_interface.h> #include <probot_msgs/SetOutputIO.h> #include <probot_msgs/ProbotStatus.h> bool startFlag_ = false; void probotStatusCallback(const probot_msgs::ProbotStatus::ConstPtr& msg) { if(msg->inputIOs[0] == 1) startFlag_ = true; else startFlag_ = false; } int main(int argc, char **argv) { ros::init(argc, argv, "probot_sync_demo"); ros::AsyncSpinner spinner(1); spinner.start(); moveit::planning_interface::MoveGroupInterface arm("manipulator"); arm.setGoalJointTolerance(0.001); arm.setMaxAccelerationScalingFactor(1); arm.setMaxVelocityScalingFactor(1); //获取终端link的名称 std::string end_effector_link = arm.getEndEffectorLink(); ros::NodeHandle n; ros::Publisher ioPub = n.advertise<probot_msgs::SetOutputIO>("probot_set_output_io", 1); ros::Subscriber sub = n.subscribe("probot_status", 1, probotStatusCallback); // 控制机械臂先回到初始化位置 arm.setNamedTarget("home"); arm.move(); sleep(1); ROS_INFO("Start Sync Demo!"); while(startFlag_ != true) usleep(1000); while(ros::ok()) { ROS_INFO("Wait Start Flag!"); probot_msgs::SetOutputIO ioOutput1; ioOutput1.mask = 1; ioOutput1.status = 1; ioPub.publish(ioOutput1); while(startFlag_ != true) usleep(1000); std::vector<double> A = {1.57, 0.000, 0.000, 0.000, 0.000, 0.000}; std::vector<double> B = {1.57, 0.000, 1.000, 0.000, 0.000, 0.000}; std::vector<double> C = {-1.000, 0.000, 1.000, 0.000, 0.000, 0.000}; std::vector<double> D = {-1.000, 0.000, 1.000, 0.000, 1.000, 0.000}; arm.setJointValueTarget(A); arm.move(); arm.setJointValueTarget(B); arm.move(); arm.setJointValueTarget(C); arm.move(); arm.setJointValueTarget(D); arm.move(); arm.setNamedTarget("home"); arm.move(); std::vector<double> position1_up = {0.25105589628219604, -0.3714791238307953, -0.5240143537521362, -3.899861258105375e-05, 0.8954282999038696, 0.2508518099784851}; std::vector<double> position1_down = {0.25105589628219604, -0.9745101928710938, -0.4310262203216553, -0.0001481490326113999, 1.4054712057113647, 0.25096750259399414}; std::vector<double> position2_up = {-0.5309033393859863, -0.37207022309303284, -0.524405837059021, 0.00010066419781651348, 0.896560549736023, 0.2511337101459503}; std::vector<double> position2_down = {-0.5309033393859863, -0.9512181878089905, -0.44115084409713745, 0.00035425653913989663, 1.3924535512924194, 0.2508637011051178}; arm.setJointValueTarget(position1_up); arm.move(); arm.setJointValueTarget(position1_down); arm.move(); arm.setJointValueTarget(position1_up); arm.move(); arm.setJointValueTarget(position2_up); arm.move(); arm.setJointValueTarget(position2_down); arm.move(); arm.setJointValueTarget(position2_up); arm.move(); arm.setNamedTarget("home"); arm.move(); // 获取当前位姿数据最为机械臂运动的起始位姿 geometry_msgs::Pose start_pose = arm.getCurrentPose(end_effector_link).pose; std::vector<geometry_msgs::Pose> waypoints; //将初始位姿加入路点列表 waypoints.push_back(start_pose); start_pose.position.z -= 0.2; waypoints.push_back(start_pose); start_pose.position.x += 0.1; waypoints.push_back(start_pose); start_pose.position.y += 0.1; waypoints.push_back(start_pose); start_pose.position.x -= 0.1; start_pose.position.y -= 0.1; waypoints.push_back(start_pose); // 笛卡尔空间下的路径规划 moveit_msgs::RobotTrajectory trajectory; const double jump_threshold = 0.0; const double eef_step = 0.01; double fraction = 0.0; int maxtries = 100; //最大尝试规划次数 int attempts = 0; //已经尝试规划次数 while(fraction < 1.0 && attempts < maxtries) { fraction = arm.computeCartesianPath(waypoints, eef_step, jump_threshold, trajectory); attempts++; if(attempts % 10 == 0) ROS_INFO("Still trying after %d attempts...", attempts); } if(fraction == 1) { ROS_INFO("Path computed successfully. Moving the arm."); // 生成机械臂的运动规划数据 moveit::planning_interface::MoveGroupInterface::Plan plan; plan.trajectory_ = trajectory; // 执行运动 arm.execute(plan); sleep(1); } else { ROS_INFO("Path planning failed with only %0.6f success after %d attempts.", fraction, maxtries); } std::vector<double> lastPoint1 = {-0.012496701441705227, -0.41917115449905396, -0.19433578848838806, 0.018087295815348625, 2.2288901805877686, -0.013513846322894096}; std::vector<double> lastPoint2 = {-0.012496701441705227, -0.2822195291519165, -0.05068935826420784, 0.030009545385837555, 1.9483672380447388, 2.1740968227386475}; arm.setJointValueTarget(lastPoint1); arm.move(); arm.setJointValueTarget(lastPoint2); arm.move(); ioOutput1.mask = 1; ioOutput1.status = 0; ioPub.publish(ioOutput1); // 控制机械臂先回到初始化位置 arm.setNamedTarget("home"); arm.move(); sleep(1); } // 控制机械臂先回到初始化位置 arm.setNamedTarget("home"); arm.move(); sleep(1); ros::shutdown(); return 0; }
31.959391
174
0.62913
[ "vector" ]
a97dc7c28eb4863faffa7267cd478b0ce23c4269
142,266
cpp
C++
gecode/flatzinc/parser.tab.cpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
gecode/flatzinc/parser.tab.cpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
gecode/flatzinc/parser.tab.cpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
/* A Bison parser, made by GNU Bison 2.7. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc. 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.7" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Copy the first part of user declarations. */ /* Line 371 of yacc.c */ #line 40 "gecode/flatzinc/parser.yxx" #define YYPARSE_PARAM parm #define YYLEX_PARAM static_cast<ParserState*>(parm)->yyscanner #include <gecode/flatzinc.hh> #include <gecode/flatzinc/parser.hh> #include <iostream> #include <fstream> #ifdef HAVE_MMAP #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #endif using namespace std; int yyparse(void*); int yylex(YYSTYPE*, void* scanner); int yylex_init (void** scanner); int yylex_destroy (void* scanner); int yyget_lineno (void* scanner); void yyset_extra (void* user_defined ,void* yyscanner ); extern int yydebug; using namespace Gecode; using namespace Gecode::FlatZinc; void yyerror(void* parm, const char *str) { ParserState* pp = static_cast<ParserState*>(parm); pp->err << "Error: " << str << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; } void yyassert(ParserState* pp, bool cond, const char* str) { if (!cond) { pp->err << "Error: " << str << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; } } /* * The symbol tables * */ AST::Node* getArrayElement(ParserState* pp, string id, int offset, bool annotation) { if (offset > 0) { SymbolEntry e; if (pp->symbols.get(id,e)) { switch (e.t) { case ST_INTVARARRAY: if (offset > pp->arrays[e.i]) goto error; { std::string n; if (annotation) { std::ostringstream oss; oss << id << "[" << offset << "]"; n = oss.str(); } return new AST::IntVar(pp->arrays[e.i+offset],n); } case ST_BOOLVARARRAY: if (offset > pp->arrays[e.i]) goto error; { std::string n; if (annotation) { std::ostringstream oss; oss << id << "[" << offset << "]"; n = oss.str(); } return new AST::BoolVar(pp->arrays[e.i+offset],n); } case ST_SETVARARRAY: if (offset > pp->arrays[e.i]) goto error; { std::string n; if (annotation) { std::ostringstream oss; oss << id << "[" << offset << "]"; n = oss.str(); } return new AST::SetVar(pp->arrays[e.i+offset],n); } case ST_FLOATVARARRAY: if (offset > pp->arrays[e.i]) goto error; { std::string n; if (annotation) { std::ostringstream oss; oss << id << "[" << offset << "]"; n = oss.str(); } return new AST::FloatVar(pp->arrays[e.i+offset],n); } case ST_INTVALARRAY: if (offset > pp->arrays[e.i]) goto error; return new AST::IntLit(pp->arrays[e.i+offset]); case ST_SETVALARRAY: if (offset > pp->arrays[e.i]) goto error; return new AST::SetLit(pp->setvals[pp->arrays[e.i+1]+offset-1]); case ST_FLOATVALARRAY: if (offset > pp->arrays[e.i]) goto error; return new AST::FloatLit(pp->floatvals[pp->arrays[e.i+1]+offset-1]); default: break; } } } error: pp->err << "Error: array access to " << id << " invalid" << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; return new AST::IntVar(0); // keep things consistent } AST::Node* getVarRefArg(ParserState* pp, string id, bool annotation = false) { SymbolEntry e; string n; if (annotation) n = id; if (pp->symbols.get(id, e)) { switch (e.t) { case ST_INTVAR: return new AST::IntVar(e.i,n); case ST_BOOLVAR: return new AST::BoolVar(e.i,n); case ST_SETVAR: return new AST::SetVar(e.i,n); case ST_FLOATVAR: return new AST::FloatVar(e.i,n); default: break; } } if (annotation) return new AST::Atom(id); pp->err << "Error: undefined variable " << id << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; return new AST::IntVar(0); // keep things consistent } void addDomainConstraint(ParserState* pp, std::string id, AST::Node* var, Option<AST::SetLit* >& dom) { if (!dom()) return; AST::Array* args = new AST::Array(2); args->a[0] = var; args->a[1] = dom.some(); pp->domainConstraints.push_back(new ConExpr(id, args)); } void addDomainConstraint(ParserState* pp, AST::Node* var, Option<std::pair<double,double>* > dom) { if (!dom()) return; { AST::Array* args = new AST::Array(2); args->a[0] = new AST::FloatLit(dom.some()->first); args->a[1] = var; pp->domainConstraints.push_back(new ConExpr("float_le", args)); } { AST::Array* args = new AST::Array(2); AST::FloatVar* fv = static_cast<AST::FloatVar*>(var); args->a[0] = new AST::FloatVar(fv->i,fv->n); args->a[1] = new AST::FloatLit(dom.some()->second); pp->domainConstraints.push_back(new ConExpr("float_le", args)); } delete dom.some(); } /* * Initialize the root gecode space * */ void initfg(ParserState* pp) { if (!pp->hadError) pp->fg->init(pp->intvars.size(), pp->boolvars.size(), pp->setvars.size(), pp->floatvars.size()); for (unsigned int i=0; i<pp->intvars.size(); i++) { if (!pp->hadError) { try { pp->fg->newIntVar(static_cast<IntVarSpec*>(pp->intvars[i].second)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } if (pp->intvars[i].first[0] != '[') { delete pp->intvars[i].second; pp->intvars[i].second = NULL; } } for (unsigned int i=0; i<pp->boolvars.size(); i++) { if (!pp->hadError) { try { pp->fg->newBoolVar( static_cast<BoolVarSpec*>(pp->boolvars[i].second)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } if (pp->boolvars[i].first[0] != '[') { delete pp->boolvars[i].second; pp->boolvars[i].second = NULL; } } for (unsigned int i=0; i<pp->setvars.size(); i++) { if (!pp->hadError) { try { pp->fg->newSetVar(static_cast<SetVarSpec*>(pp->setvars[i].second)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } if (pp->setvars[i].first[0] != '[') { delete pp->setvars[i].second; pp->setvars[i].second = NULL; } } for (unsigned int i=0; i<pp->floatvars.size(); i++) { if (!pp->hadError) { try { pp->fg->newFloatVar( static_cast<FloatVarSpec*>(pp->floatvars[i].second)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } if (pp->floatvars[i].first[0] != '[') { delete pp->floatvars[i].second; pp->floatvars[i].second = NULL; } } for (unsigned int i=pp->domainConstraints.size(); i--;) { if (!pp->hadError) { try { assert(pp->domainConstraints[i]->args->a.size() == 2); pp->fg->postConstraint(*pp->domainConstraints[i], NULL); delete pp->domainConstraints[i]; } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } } } void fillPrinter(ParserState& pp, Gecode::FlatZinc::Printer& p) { p.init(pp.getOutput()); } AST::Node* arrayOutput(AST::Call* ann) { AST::Array* a = NULL; if (ann->args->isArray()) { a = ann->args->getArray(); } else { a = new AST::Array(ann->args); } std::ostringstream oss; oss << "array" << a->a.size() << "d("; for (unsigned int i=0; i<a->a.size(); i++) { AST::SetLit* s = a->a[i]->getSet(); if (s->empty()) oss << "{}, "; else if (s->interval) oss << s->min << ".." << s->max << ", "; else { oss << "{"; for (unsigned int j=0; j<s->s.size(); j++) { oss << s->s[j]; if (j<s->s.size()-1) oss << ","; } oss << "}, "; } } if (!ann->args->isArray()) { a->a[0] = NULL; delete a; } return new AST::String(oss.str()); } /* * The main program * */ namespace Gecode { namespace FlatZinc { FlatZincSpace* parse(const std::string& filename, Printer& p, std::ostream& err, FlatZincSpace* fzs) { #ifdef HAVE_MMAP int fd; char* data; struct stat sbuf; fd = open(filename.c_str(), O_RDONLY); if (fd == -1) { err << "Cannot open file " << filename << endl; return NULL; } if (stat(filename.c_str(), &sbuf) == -1) { err << "Cannot stat file " << filename << endl; return NULL; } data = (char*)mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd,0); if (data == (caddr_t)(-1)) { err << "Cannot mmap file " << filename << endl; return NULL; } if (fzs == NULL) { fzs = new FlatZincSpace(); } ParserState pp(data, sbuf.st_size, err, fzs); #else std::ifstream file; file.open(filename.c_str()); if (!file.is_open()) { err << "Cannot open file " << filename << endl; return NULL; } std::string s = string(istreambuf_iterator<char>(file), istreambuf_iterator<char>()); if (fzs == NULL) { fzs = new FlatZincSpace(); } ParserState pp(s, err, fzs); #endif yylex_init(&pp.yyscanner); yyset_extra(&pp, pp.yyscanner); // yydebug = 1; yyparse(&pp); fillPrinter(pp, p); if (pp.yyscanner) yylex_destroy(pp.yyscanner); return pp.hadError ? NULL : pp.fg; } FlatZincSpace* parse(std::istream& is, Printer& p, std::ostream& err, FlatZincSpace* fzs) { std::string s = string(istreambuf_iterator<char>(is), istreambuf_iterator<char>()); if (fzs == NULL) { fzs = new FlatZincSpace(); } ParserState pp(s, err, fzs); yylex_init(&pp.yyscanner); yyset_extra(&pp, pp.yyscanner); // yydebug = 1; yyparse(&pp); fillPrinter(pp, p); if (pp.yyscanner) yylex_destroy(pp.yyscanner); return pp.hadError ? NULL : pp.fg; } }} /* Line 371 of yacc.c */ #line 455 "gecode/flatzinc/parser.tab.cpp" # ifndef YY_NULL # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULL nullptr # else # define YY_NULL 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* In a future release of Bison, this section will be replaced by #include "parser.tab.hpp". */ #ifndef YY_YY_GECODE_FLATZINC_PARSER_TAB_HPP_INCLUDED # define YY_YY_GECODE_FLATZINC_PARSER_TAB_HPP_INCLUDED /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 1 #endif #if YYDEBUG extern int yydebug; #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { FZ_INT_LIT = 258, FZ_BOOL_LIT = 259, FZ_FLOAT_LIT = 260, FZ_ID = 261, FZ_U_ID = 262, FZ_STRING_LIT = 263, FZ_VAR = 264, FZ_PAR = 265, FZ_ANNOTATION = 266, FZ_ANY = 267, FZ_ARRAY = 268, FZ_BOOL = 269, FZ_CASE = 270, FZ_COLONCOLON = 271, FZ_CONSTRAINT = 272, FZ_DEFAULT = 273, FZ_DOTDOT = 274, FZ_ELSE = 275, FZ_ELSEIF = 276, FZ_ENDIF = 277, FZ_ENUM = 278, FZ_FLOAT = 279, FZ_FUNCTION = 280, FZ_IF = 281, FZ_INCLUDE = 282, FZ_INT = 283, FZ_LET = 284, FZ_MAXIMIZE = 285, FZ_MINIMIZE = 286, FZ_OF = 287, FZ_SATISFY = 288, FZ_OUTPUT = 289, FZ_PREDICATE = 290, FZ_RECORD = 291, FZ_SET = 292, FZ_SHOW = 293, FZ_SHOWCOND = 294, FZ_SOLVE = 295, FZ_STRING = 296, FZ_TEST = 297, FZ_THEN = 298, FZ_TUPLE = 299, FZ_TYPE = 300, FZ_VARIANT_RECORD = 301, FZ_WHERE = 302 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 387 of yacc.c */ #line 427 "gecode/flatzinc/parser.yxx" int iValue; char* sValue; bool bValue; double dValue; std::vector<int>* setValue; Gecode::FlatZinc::AST::SetLit* setLit; std::vector<double>* floatSetValue; std::vector<Gecode::FlatZinc::AST::SetLit>* setValueList; Gecode::FlatZinc::Option<Gecode::FlatZinc::AST::SetLit* > oSet; Gecode::FlatZinc::Option<std::pair<double,double>* > oPFloat; Gecode::FlatZinc::VarSpec* varSpec; Gecode::FlatZinc::Option<Gecode::FlatZinc::AST::Node*> oArg; std::vector<Gecode::FlatZinc::VarSpec*>* varSpecVec; Gecode::FlatZinc::Option<std::vector<Gecode::FlatZinc::VarSpec*>* > oVarSpecVec; Gecode::FlatZinc::AST::Node* arg; Gecode::FlatZinc::AST::Array* argVec; /* Line 387 of yacc.c */ #line 561 "gecode/flatzinc/parser.tab.cpp" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void *parm); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ #endif /* !YY_YY_GECODE_FLATZINC_PARSER_TAB_HPP_INCLUDED */ /* Copy the second part of user declarations. */ /* Line 390 of yacc.c */ #line 588 "gecode/flatzinc/parser.tab.cpp" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(N) (N) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (YYID (0)) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 7 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 346 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 58 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 68 /* YYNRULES -- Number of rules. */ #define YYNRULES 159 /* YYNRULES -- Number of states. */ #define YYNSTATES 344 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 302 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 49, 50, 2, 2, 51, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 52, 48, 2, 55, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 53, 2, 54, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 56, 2, 57, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 9, 10, 12, 15, 19, 20, 22, 25, 29, 30, 32, 35, 39, 45, 46, 49, 51, 55, 59, 66, 74, 77, 79, 81, 85, 87, 89, 91, 95, 97, 101, 103, 105, 112, 119, 126, 135, 142, 149, 156, 165, 179, 193, 207, 223, 239, 255, 271, 289, 291, 293, 298, 299, 302, 304, 308, 309, 311, 315, 317, 319, 324, 325, 328, 330, 334, 338, 340, 342, 347, 348, 351, 353, 357, 361, 363, 365, 370, 371, 374, 376, 380, 384, 385, 388, 389, 392, 393, 396, 397, 400, 407, 411, 416, 418, 422, 426, 428, 433, 435, 439, 443, 447, 448, 451, 453, 457, 458, 461, 463, 467, 468, 471, 473, 477, 478, 481, 483, 487, 489, 493, 495, 499, 500, 503, 505, 507, 509, 511, 513, 518, 519, 522, 524, 528, 530, 535, 537, 539, 540, 542, 545, 549, 554, 556, 558, 562, 564, 569, 570, 572, 574, 576, 578, 580, 582, 587 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 59, 0, -1, 60, 62, 64, 98, 48, -1, -1, 61, -1, 66, 48, -1, 61, 66, 48, -1, -1, 63, -1, 75, 48, -1, 63, 75, 48, -1, -1, 65, -1, 97, 48, -1, 65, 97, 48, -1, 35, 6, 49, 67, 50, -1, -1, 68, 79, -1, 69, -1, 68, 51, 69, -1, 70, 52, 6, -1, 13, 53, 72, 54, 32, 71, -1, 13, 53, 72, 54, 32, 9, 71, -1, 9, 71, -1, 71, -1, 99, -1, 37, 32, 99, -1, 14, -1, 24, -1, 73, -1, 72, 51, 73, -1, 28, -1, 3, 19, 3, -1, 6, -1, 7, -1, 9, 99, 52, 74, 119, 113, -1, 9, 100, 52, 74, 119, 113, -1, 9, 101, 52, 74, 119, 113, -1, 9, 37, 32, 99, 52, 74, 119, 113, -1, 28, 52, 74, 119, 55, 114, -1, 24, 52, 74, 119, 55, 114, -1, 14, 52, 74, 119, 55, 114, -1, 37, 32, 28, 52, 74, 119, 55, 114, -1, 13, 53, 3, 19, 3, 54, 32, 9, 99, 52, 74, 119, 93, -1, 13, 53, 3, 19, 3, 54, 32, 9, 100, 52, 74, 119, 94, -1, 13, 53, 3, 19, 3, 54, 32, 9, 101, 52, 74, 119, 95, -1, 13, 53, 3, 19, 3, 54, 32, 9, 37, 32, 99, 52, 74, 119, 96, -1, 13, 53, 3, 19, 3, 54, 32, 28, 52, 74, 119, 55, 53, 103, 54, -1, 13, 53, 3, 19, 3, 54, 32, 14, 52, 74, 119, 55, 53, 105, 54, -1, 13, 53, 3, 19, 3, 54, 32, 24, 52, 74, 119, 55, 53, 107, 54, -1, 13, 53, 3, 19, 3, 54, 32, 37, 32, 28, 52, 74, 119, 55, 53, 109, 54, -1, 3, -1, 74, -1, 74, 53, 3, 54, -1, -1, 78, 79, -1, 76, -1, 78, 51, 76, -1, -1, 51, -1, 53, 77, 54, -1, 5, -1, 74, -1, 74, 53, 3, 54, -1, -1, 83, 79, -1, 81, -1, 83, 51, 81, -1, 53, 82, 54, -1, 4, -1, 74, -1, 74, 53, 3, 54, -1, -1, 87, 79, -1, 85, -1, 87, 51, 85, -1, 53, 86, 54, -1, 102, -1, 74, -1, 74, 53, 3, 54, -1, -1, 91, 79, -1, 89, -1, 91, 51, 89, -1, 53, 90, 54, -1, -1, 55, 80, -1, -1, 55, 88, -1, -1, 55, 84, -1, -1, 55, 92, -1, 17, 6, 49, 111, 50, 119, -1, 40, 119, 33, -1, 40, 119, 118, 117, -1, 28, -1, 56, 103, 57, -1, 3, 19, 3, -1, 14, -1, 56, 106, 79, 57, -1, 24, -1, 5, 19, 5, -1, 56, 103, 57, -1, 3, 19, 3, -1, -1, 104, 79, -1, 3, -1, 104, 51, 3, -1, -1, 106, 79, -1, 4, -1, 106, 51, 4, -1, -1, 108, 79, -1, 5, -1, 108, 51, 5, -1, -1, 110, 79, -1, 102, -1, 110, 51, 102, -1, 112, -1, 111, 51, 112, -1, 114, -1, 53, 115, 54, -1, -1, 55, 114, -1, 4, -1, 3, -1, 5, -1, 102, -1, 74, -1, 74, 53, 114, 54, -1, -1, 116, 79, -1, 114, -1, 116, 51, 114, -1, 74, -1, 74, 53, 3, 54, -1, 31, -1, 30, -1, -1, 120, -1, 16, 121, -1, 120, 16, 121, -1, 6, 49, 122, 50, -1, 123, -1, 121, -1, 122, 51, 121, -1, 125, -1, 53, 122, 124, 54, -1, -1, 51, -1, 4, -1, 3, -1, 5, -1, 102, -1, 74, -1, 74, 53, 125, 54, -1, 8, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 529, 529, 531, 533, 536, 537, 541, 542, 546, 547, 549, 551, 554, 555, 562, 565, 567, 570, 571, 574, 578, 579, 580, 581, 584, 586, 588, 589, 592, 593, 596, 597, 603, 603, 606, 639, 672, 712, 746, 755, 765, 774, 786, 851, 909, 979, 1042, 1063, 1083, 1103, 1126, 1130, 1145, 1169, 1170, 1174, 1176, 1179, 1179, 1181, 1185, 1187, 1202, 1225, 1226, 1230, 1232, 1236, 1240, 1242, 1257, 1280, 1281, 1285, 1287, 1290, 1293, 1295, 1310, 1333, 1334, 1338, 1340, 1343, 1348, 1349, 1354, 1355, 1360, 1361, 1366, 1367, 1371, 1385, 1398, 1422, 1424, 1426, 1432, 1434, 1447, 1449, 1458, 1460, 1467, 1468, 1472, 1474, 1479, 1480, 1484, 1486, 1491, 1492, 1496, 1498, 1503, 1504, 1508, 1510, 1518, 1520, 1524, 1526, 1531, 1532, 1536, 1538, 1540, 1542, 1544, 1640, 1655, 1656, 1660, 1662, 1670, 1687, 1713, 1714, 1722, 1723, 1727, 1729, 1733, 1737, 1741, 1743, 1747, 1749, 1752, 1752, 1755, 1757, 1759, 1761, 1763, 1869, 1880 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 1 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "FZ_INT_LIT", "FZ_BOOL_LIT", "FZ_FLOAT_LIT", "FZ_ID", "FZ_U_ID", "FZ_STRING_LIT", "FZ_VAR", "FZ_PAR", "FZ_ANNOTATION", "FZ_ANY", "FZ_ARRAY", "FZ_BOOL", "FZ_CASE", "FZ_COLONCOLON", "FZ_CONSTRAINT", "FZ_DEFAULT", "FZ_DOTDOT", "FZ_ELSE", "FZ_ELSEIF", "FZ_ENDIF", "FZ_ENUM", "FZ_FLOAT", "FZ_FUNCTION", "FZ_IF", "FZ_INCLUDE", "FZ_INT", "FZ_LET", "FZ_MAXIMIZE", "FZ_MINIMIZE", "FZ_OF", "FZ_SATISFY", "FZ_OUTPUT", "FZ_PREDICATE", "FZ_RECORD", "FZ_SET", "FZ_SHOW", "FZ_SHOWCOND", "FZ_SOLVE", "FZ_STRING", "FZ_TEST", "FZ_THEN", "FZ_TUPLE", "FZ_TYPE", "FZ_VARIANT_RECORD", "FZ_WHERE", "';'", "'('", "')'", "','", "':'", "'['", "']'", "'='", "'{'", "'}'", "$accept", "model", "preddecl_items", "preddecl_items_head", "vardecl_items", "vardecl_items_head", "constraint_items", "constraint_items_head", "preddecl_item", "pred_arg_list", "pred_arg_list_head", "pred_arg", "pred_arg_type", "pred_arg_simple_type", "pred_array_init", "pred_array_init_arg", "var_par_id", "vardecl_item", "int_init", "int_init_list", "int_init_list_head", "list_tail", "int_var_array_literal", "float_init", "float_init_list", "float_init_list_head", "float_var_array_literal", "bool_init", "bool_init_list", "bool_init_list_head", "bool_var_array_literal", "set_init", "set_init_list", "set_init_list_head", "set_var_array_literal", "vardecl_int_var_array_init", "vardecl_bool_var_array_init", "vardecl_float_var_array_init", "vardecl_set_var_array_init", "constraint_item", "solve_item", "int_ti_expr_tail", "bool_ti_expr_tail", "float_ti_expr_tail", "set_literal", "int_list", "int_list_head", "bool_list", "bool_list_head", "float_list", "float_list_head", "set_literal_list", "set_literal_list_head", "flat_expr_list", "flat_expr", "non_array_expr_opt", "non_array_expr", "non_array_expr_list", "non_array_expr_list_head", "solve_expr", "minmax", "annotations", "annotations_head", "annotation", "annotation_list", "annotation_expr", "annotation_list_tail", "ann_non_array_expr", YY_NULL }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 59, 40, 41, 44, 58, 91, 93, 61, 123, 125 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 58, 59, 60, 60, 61, 61, 62, 62, 63, 63, 64, 64, 65, 65, 66, 67, 67, 68, 68, 69, 70, 70, 70, 70, 71, 71, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 76, 76, 76, 77, 77, 78, 78, 79, 79, 80, 81, 81, 81, 82, 82, 83, 83, 84, 85, 85, 85, 86, 86, 87, 87, 88, 89, 89, 89, 90, 90, 91, 91, 92, 93, 93, 94, 94, 95, 95, 96, 96, 97, 98, 98, 99, 99, 99, 100, 100, 101, 101, 102, 102, 103, 103, 104, 104, 105, 105, 106, 106, 107, 107, 108, 108, 109, 109, 110, 110, 111, 111, 112, 112, 113, 113, 114, 114, 114, 114, 114, 114, 115, 115, 116, 116, 117, 117, 118, 118, 119, 119, 120, 120, 121, 121, 122, 122, 123, 123, 124, 124, 125, 125, 125, 125, 125, 125, 125 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 5, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 5, 0, 2, 1, 3, 3, 6, 7, 2, 1, 1, 3, 1, 1, 1, 3, 1, 3, 1, 1, 6, 6, 6, 8, 6, 6, 6, 8, 13, 13, 13, 15, 15, 15, 15, 17, 1, 1, 4, 0, 2, 1, 3, 0, 1, 3, 1, 1, 4, 0, 2, 1, 3, 3, 1, 1, 4, 0, 2, 1, 3, 3, 1, 1, 4, 0, 2, 1, 3, 3, 0, 2, 0, 2, 0, 2, 0, 2, 6, 3, 4, 1, 3, 3, 1, 4, 1, 3, 3, 3, 0, 2, 1, 3, 0, 2, 1, 3, 0, 2, 1, 3, 0, 2, 1, 3, 1, 3, 1, 3, 0, 2, 1, 1, 1, 1, 1, 4, 0, 2, 1, 3, 1, 4, 1, 1, 0, 1, 2, 3, 4, 1, 1, 3, 1, 4, 0, 1, 1, 1, 1, 1, 1, 4, 1 }; /* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM. Performed when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 3, 0, 0, 7, 4, 0, 0, 1, 0, 0, 0, 0, 0, 0, 11, 8, 0, 0, 5, 16, 0, 0, 99, 101, 96, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 9, 6, 0, 0, 27, 28, 0, 105, 0, 58, 18, 0, 24, 25, 0, 0, 0, 107, 111, 0, 58, 58, 0, 0, 0, 0, 33, 34, 141, 141, 141, 0, 0, 141, 0, 0, 13, 10, 23, 0, 0, 15, 59, 17, 0, 98, 102, 0, 97, 59, 106, 59, 0, 141, 141, 141, 0, 0, 0, 142, 0, 0, 0, 0, 0, 2, 14, 0, 31, 0, 29, 26, 19, 20, 0, 108, 112, 100, 125, 125, 125, 0, 154, 153, 155, 33, 159, 0, 105, 157, 156, 143, 146, 149, 0, 0, 0, 0, 141, 128, 127, 129, 133, 131, 130, 0, 121, 123, 140, 139, 94, 0, 0, 0, 0, 141, 0, 35, 36, 37, 0, 0, 0, 147, 151, 0, 0, 41, 144, 40, 39, 0, 135, 0, 58, 0, 141, 0, 137, 95, 32, 30, 0, 125, 126, 0, 104, 0, 152, 0, 103, 0, 0, 124, 59, 134, 0, 93, 122, 0, 0, 21, 38, 0, 0, 0, 0, 0, 145, 0, 148, 150, 158, 42, 136, 132, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 0, 0, 0, 141, 141, 141, 0, 0, 141, 141, 141, 0, 0, 0, 0, 0, 85, 87, 89, 0, 0, 0, 141, 141, 0, 43, 0, 44, 0, 45, 109, 113, 105, 0, 91, 54, 86, 72, 88, 64, 90, 0, 58, 115, 0, 58, 0, 0, 0, 46, 51, 52, 56, 0, 58, 69, 70, 74, 0, 58, 61, 62, 66, 0, 58, 48, 110, 49, 59, 114, 47, 117, 80, 92, 0, 60, 59, 55, 0, 76, 59, 73, 0, 68, 59, 65, 116, 0, 119, 0, 58, 78, 82, 0, 58, 77, 0, 57, 0, 75, 0, 67, 50, 59, 118, 0, 84, 59, 81, 53, 71, 63, 120, 0, 83, 79 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 2, 3, 4, 14, 15, 36, 37, 5, 48, 49, 50, 51, 52, 109, 110, 143, 16, 280, 281, 282, 83, 264, 290, 291, 292, 268, 285, 286, 287, 266, 320, 321, 322, 301, 253, 255, 257, 277, 38, 74, 53, 28, 29, 144, 59, 60, 269, 61, 272, 273, 317, 318, 145, 146, 157, 147, 173, 174, 179, 151, 98, 99, 163, 164, 132, 189, 133 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -123 static const yytype_int16 yypact[] = { -23, 21, 57, 209, -23, -7, 13, -123, 102, 7, 16, 43, 50, 38, 82, 209, 33, 58, -123, 45, 99, 109, -123, -123, -123, 95, 48, 77, 89, 90, 130, 49, 49, 49, 116, 150, 119, 82, 115, 120, -123, -123, 159, 117, -123, -123, 137, 168, 124, 125, -123, 128, -123, -123, 174, 176, 47, -123, -123, 127, 134, 138, 49, 49, 49, 171, -123, -123, 178, 178, 178, 153, 170, 178, 169, 179, -123, -123, -123, 10, 47, -123, 45, -123, 220, -123, -123, 177, -123, 225, -123, 227, 181, 178, 178, 178, 236, 81, 185, 226, 188, 189, 49, 87, 79, -123, -123, 228, -123, -5, -123, -123, -123, -123, 49, -123, -123, -123, 193, 193, 193, 195, 231, -123, -123, 202, -123, 81, 168, 199, -123, -123, -123, -123, 148, 81, 148, 148, 178, 231, -123, -123, 148, 200, -123, 64, -123, -123, -123, -123, -123, 49, 251, 10, 223, 178, 148, -123, -123, -123, 224, 254, 81, -123, 207, 203, 11, -123, -123, -123, -123, 204, -123, 208, 212, 148, 178, 87, 211, -123, -123, -123, 158, 193, -123, 151, -123, 73, 81, 213, -123, 214, 148, -123, 148, -123, 216, -123, -123, 263, 159, -123, -123, 108, 219, 222, 230, 240, -123, 81, -123, -123, -123, -123, -123, -123, 221, -123, 244, 232, 233, 234, 49, 49, 49, 250, -123, 47, 49, 49, 49, 178, 178, 178, 235, 237, 178, 178, 178, 238, 239, 241, 49, 49, 242, 243, 245, 246, 248, 249, 178, 178, 252, -123, 253, -123, 255, -123, 275, 278, 168, 256, 257, 18, -123, 143, -123, 29, -123, 259, 138, -123, 260, 229, 261, 264, 265, -123, -123, 266, -123, 262, 258, -123, 267, -123, 268, 270, -123, 271, -123, 269, 274, -123, -123, -123, 283, -123, -123, 41, 23, -123, 287, -123, 18, -123, 288, -123, 143, -123, 289, -123, 29, -123, -123, 231, -123, 272, 276, 277, -123, 279, 280, -123, 281, -123, 282, -123, 284, -123, -123, 41, -123, 292, -123, 23, -123, -123, -123, -123, -123, 285, -123, -123 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -123, -123, -123, -123, -123, -123, -123, -123, 299, -123, -123, 247, -123, -34, -123, 154, -31, 295, 24, -123, -123, -57, -123, 20, -123, -123, -123, 26, -123, -123, -123, 2, -123, -123, -123, -123, -123, -123, -123, 303, -123, -3, 139, 140, -90, -122, -123, -123, 83, -123, -123, -123, -123, -123, 167, -109, -114, -123, -123, -123, -123, -30, -123, -88, 183, -123, -123, 180 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint16 yytable[] = { 68, 69, 70, 90, 92, 27, 165, 130, 78, 131, 158, 159, 1, 107, 122, 123, 124, 66, 67, 126, 167, 278, 169, 170, 66, 67, 315, 6, 172, 66, 67, 93, 94, 95, 288, 66, 67, 130, 108, 100, 101, 18, 184, 104, 315, 130, 153, 168, 20, 154, 20, 57, 58, 87, 42, 66, 67, 7, 43, 44, 30, 196, 19, 118, 119, 120, 129, 128, 31, 45, 34, 138, 130, 24, 202, 24, 130, 111, 213, 128, 214, 40, 46, 155, 122, 123, 124, 125, 67, 126, 139, 140, 141, 66, 67, 32, 129, 128, 130, 35, 210, 47, 33, 47, 129, 20, 41, 21, 171, 148, 149, 20, 150, 21, 176, 177, 22, 195, 54, 130, 178, 210, 22, 208, 209, 183, 23, 56, 55, 62, 24, 129, 23, 65, 127, 129, 24, 128, 274, 25, 142, 63, 64, 128, 71, 218, 197, 283, 201, 66, 67, 139, 140, 141, 66, 67, 72, 129, 26, 73, 203, 20, 20, 76, 26, 204, 217, 200, 77, 80, 79, 57, 44, 44, 81, 205, 82, 85, 129, 206, 84, 86, 45, 45, 88, 89, 24, 24, 207, 91, 96, 231, 232, 233, 97, 46, 46, 236, 237, 238, 219, 239, 240, 241, 128, 102, 244, 245, 246, 316, 323, 250, 251, 294, 47, 47, 297, 105, 8, 103, 261, 262, 9, 10, 235, 305, 113, 106, 115, 114, 309, 116, 279, 11, 284, 313, 289, 12, 117, 121, 134, 340, 135, 136, 137, 323, 13, 152, 156, 160, 161, 162, 166, 175, 180, 182, 185, 186, 188, 192, 190, 332, 193, 194, 199, 336, 216, 211, 212, 319, 215, 222, 225, 279, 223, 226, 227, 284, 234, 58, 296, 289, 224, 271, 228, 229, 230, 242, 314, 243, 324, 326, 328, 247, 248, 341, 249, 252, 254, 258, 256, 259, 260, 17, 319, 263, 265, 181, 267, 304, 39, 275, 276, 293, 295, 298, 303, 299, 300, 302, 306, 308, 307, 311, 310, 312, 330, 331, 325, 112, 333, 335, 329, 334, 327, 337, 338, 342, 339, 343, 75, 270, 220, 221, 198, 187, 191 }; #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-123))) #define yytable_value_is_error(Yytable_value) \ YYID (0) static const yytype_uint16 yycheck[] = { 31, 32, 33, 60, 61, 8, 128, 97, 42, 97, 119, 120, 35, 3, 3, 4, 5, 6, 7, 8, 134, 3, 136, 137, 6, 7, 3, 6, 142, 6, 7, 62, 63, 64, 5, 6, 7, 127, 28, 69, 70, 48, 156, 73, 3, 135, 51, 135, 3, 54, 3, 3, 4, 56, 9, 6, 7, 0, 13, 14, 53, 175, 49, 93, 94, 95, 97, 56, 52, 24, 32, 102, 162, 28, 183, 28, 166, 80, 192, 56, 194, 48, 37, 114, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 52, 127, 56, 188, 17, 188, 56, 52, 56, 135, 3, 48, 5, 138, 30, 31, 3, 33, 5, 50, 51, 14, 174, 19, 209, 151, 209, 14, 50, 51, 155, 24, 32, 19, 52, 28, 162, 24, 3, 53, 166, 28, 56, 260, 37, 53, 52, 52, 56, 28, 37, 176, 4, 182, 6, 7, 3, 4, 5, 6, 7, 6, 188, 56, 40, 9, 3, 3, 48, 56, 14, 200, 9, 48, 32, 53, 3, 14, 14, 50, 24, 51, 3, 209, 28, 52, 5, 24, 24, 57, 51, 28, 28, 37, 51, 19, 222, 223, 224, 16, 37, 37, 228, 229, 230, 203, 231, 232, 233, 56, 52, 236, 237, 238, 299, 300, 242, 243, 270, 56, 56, 273, 48, 9, 49, 250, 251, 13, 14, 227, 282, 6, 48, 3, 52, 287, 4, 263, 24, 265, 292, 267, 28, 57, 3, 55, 331, 16, 55, 55, 335, 37, 19, 55, 54, 19, 49, 53, 53, 3, 32, 32, 3, 51, 55, 57, 318, 54, 51, 53, 322, 3, 54, 54, 300, 54, 52, 32, 304, 52, 54, 32, 308, 28, 4, 51, 312, 52, 5, 52, 52, 52, 52, 5, 52, 3, 3, 3, 55, 55, 3, 55, 55, 55, 53, 55, 53, 53, 4, 335, 53, 53, 153, 53, 51, 15, 55, 55, 54, 54, 54, 54, 53, 53, 53, 53, 51, 54, 54, 53, 51, 54, 51, 304, 82, 53, 51, 312, 54, 308, 54, 54, 335, 54, 54, 37, 258, 203, 203, 177, 162, 166 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 35, 59, 60, 61, 66, 6, 0, 9, 13, 14, 24, 28, 37, 62, 63, 75, 66, 48, 49, 3, 5, 14, 24, 28, 37, 56, 99, 100, 101, 53, 52, 52, 52, 32, 17, 64, 65, 97, 75, 48, 48, 9, 13, 14, 24, 37, 56, 67, 68, 69, 70, 71, 99, 19, 19, 32, 3, 4, 103, 104, 106, 52, 52, 52, 3, 6, 7, 74, 74, 74, 28, 6, 40, 98, 97, 48, 48, 71, 53, 32, 50, 51, 79, 52, 3, 5, 99, 57, 51, 79, 51, 79, 74, 74, 74, 19, 16, 119, 120, 119, 119, 52, 49, 119, 48, 48, 3, 28, 72, 73, 99, 69, 6, 52, 3, 4, 57, 119, 119, 119, 3, 3, 4, 5, 6, 8, 53, 56, 74, 102, 121, 123, 125, 55, 16, 55, 55, 74, 3, 4, 5, 53, 74, 102, 111, 112, 114, 30, 31, 33, 118, 19, 51, 54, 74, 55, 113, 113, 113, 54, 19, 49, 121, 122, 103, 53, 114, 121, 114, 114, 119, 114, 115, 116, 53, 50, 51, 74, 117, 3, 73, 32, 119, 114, 32, 3, 122, 51, 124, 57, 125, 55, 54, 51, 79, 114, 119, 112, 53, 9, 71, 113, 9, 14, 24, 28, 37, 50, 51, 121, 54, 54, 114, 114, 54, 3, 71, 37, 99, 100, 101, 52, 52, 52, 32, 54, 32, 52, 52, 52, 74, 74, 74, 28, 99, 74, 74, 74, 119, 119, 119, 52, 52, 119, 119, 119, 55, 55, 55, 74, 74, 55, 93, 55, 94, 55, 95, 53, 53, 53, 119, 119, 53, 80, 53, 88, 53, 84, 105, 106, 5, 107, 108, 103, 55, 55, 96, 3, 74, 76, 77, 78, 4, 74, 85, 86, 87, 5, 74, 81, 82, 83, 54, 79, 54, 51, 79, 54, 53, 53, 92, 53, 54, 51, 79, 53, 54, 51, 79, 53, 54, 51, 79, 5, 3, 102, 109, 110, 74, 89, 90, 91, 102, 3, 76, 3, 85, 3, 81, 54, 51, 79, 53, 54, 51, 79, 54, 54, 54, 102, 3, 89, 54 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. However, YYFAIL appears to be in use. Nevertheless, it is formally deprecated in Bison 2.4.2's NEWS entry, where a plan to phase it out is discussed. */ #define YYFAIL goto yyerrlab #if defined YYFAIL /* This is here to suppress warnings from the GCC cpp's -Wunused-macros. Normally we don't worry about that warning, but some users do, and we want to make it easy for users to remove YYFAIL uses, which will produce warnings from Bison 2.5. */ #endif #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (parm, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, YYLEX_PARAM) #else # define YYLEX yylex (&yylval) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, parm); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void *parm) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, parm) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; void *parm; #endif { FILE *yyo = yyoutput; YYUSE (yyo); if (!yyvaluep) return; YYUSE (parm); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void *parm) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, parm) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; void *parm; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep, parm); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule, void *parm) #else static void yy_reduce_print (yyvsp, yyrule, parm) YYSTYPE *yyvsp; int yyrule; void *parm; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , parm); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule, parm); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULL, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULL; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - Assume YYFAIL is not used. It's too flawed to consider. See <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html> for details. YYERROR is fine as it does not invoke this function. - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULL, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *parm) #else static void yydestruct (yymsg, yytype, yyvaluep, parm) const char *yymsg; int yytype; YYSTYPE *yyvaluep; void *parm; #endif { YYUSE (yyvaluep); YYUSE (parm); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *parm) #else int yyparse (parm) void *parm; #endif #endif { /* The lookahead symbol. */ int yychar; #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ static YYSTYPE yyval_default; # define YY_INITIAL_VALUE(Value) = Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif /* The semantic value of the lookahead symbol. */ YYSTYPE yylval YY_INITIAL_VALUE(yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 7: /* Line 1792 of yacc.c */ #line 541 "gecode/flatzinc/parser.yxx" { initfg(static_cast<ParserState*>(parm)); } break; case 8: /* Line 1792 of yacc.c */ #line 543 "gecode/flatzinc/parser.yxx" { initfg(static_cast<ParserState*>(parm)); } break; case 15: /* Line 1792 of yacc.c */ #line 563 "gecode/flatzinc/parser.yxx" { free((yyvsp[(2) - (5)].sValue)); } break; case 20: /* Line 1792 of yacc.c */ #line 575 "gecode/flatzinc/parser.yxx" { free((yyvsp[(3) - (3)].sValue)); } break; case 25: /* Line 1792 of yacc.c */ #line 585 "gecode/flatzinc/parser.yxx" { if ((yyvsp[(1) - (1)].oSet)()) delete (yyvsp[(1) - (1)].oSet).some(); } break; case 26: /* Line 1792 of yacc.c */ #line 587 "gecode/flatzinc/parser.yxx" { if ((yyvsp[(3) - (3)].oSet)()) delete (yyvsp[(3) - (3)].oSet).some(); } break; case 35: /* Line 1792 of yacc.c */ #line 607 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); bool print = (yyvsp[(5) - (6)].argVec)->hasAtom("output_var"); bool introduced = (yyvsp[(5) - (6)].argVec)->hasAtom("var_is_introduced"); bool funcDep = (yyvsp[(5) - (6)].argVec)->hasAtom("is_defined_var"); yyassert(pp, pp->symbols.put((yyvsp[(4) - (6)].sValue), se_iv(pp->intvars.size())), "Duplicate symbol"); if (print) { pp->output(std::string((yyvsp[(4) - (6)].sValue)), new AST::IntVar(pp->intvars.size())); } if ((yyvsp[(6) - (6)].oArg)()) { AST::Node* arg = (yyvsp[(6) - (6)].oArg).some(); if (arg->isInt()) { pp->intvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new IntVarSpec(arg->getInt(),introduced,funcDep))); } else if (arg->isIntVar()) { pp->intvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new IntVarSpec(Alias(arg->getIntVar()),introduced,funcDep))); } else { yyassert(pp, false, "Invalid var int initializer"); } if (!pp->hadError) addDomainConstraint(pp, "int_in", new AST::IntVar(pp->intvars.size()-1), (yyvsp[(2) - (6)].oSet)); delete arg; } else { pp->intvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new IntVarSpec((yyvsp[(2) - (6)].oSet),introduced,funcDep))); } delete (yyvsp[(5) - (6)].argVec); free((yyvsp[(4) - (6)].sValue)); } break; case 36: /* Line 1792 of yacc.c */ #line 640 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); bool print = (yyvsp[(5) - (6)].argVec)->hasAtom("output_var"); bool introduced = (yyvsp[(5) - (6)].argVec)->hasAtom("var_is_introduced"); bool funcDep = (yyvsp[(5) - (6)].argVec)->hasAtom("is_defined_var"); yyassert(pp, pp->symbols.put((yyvsp[(4) - (6)].sValue), se_bv(pp->boolvars.size())), "Duplicate symbol"); if (print) { pp->output(std::string((yyvsp[(4) - (6)].sValue)), new AST::BoolVar(pp->boolvars.size())); } if ((yyvsp[(6) - (6)].oArg)()) { AST::Node* arg = (yyvsp[(6) - (6)].oArg).some(); if (arg->isBool()) { pp->boolvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new BoolVarSpec(arg->getBool(),introduced,funcDep))); } else if (arg->isBoolVar()) { pp->boolvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new BoolVarSpec(Alias(arg->getBoolVar()),introduced,funcDep))); } else { yyassert(pp, false, "Invalid var bool initializer"); } if (!pp->hadError) addDomainConstraint(pp, "int_in", new AST::BoolVar(pp->boolvars.size()-1), (yyvsp[(2) - (6)].oSet)); delete arg; } else { pp->boolvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new BoolVarSpec((yyvsp[(2) - (6)].oSet),introduced,funcDep))); } delete (yyvsp[(5) - (6)].argVec); free((yyvsp[(4) - (6)].sValue)); } break; case 37: /* Line 1792 of yacc.c */ #line 673 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); bool print = (yyvsp[(5) - (6)].argVec)->hasAtom("output_var"); bool introduced = (yyvsp[(5) - (6)].argVec)->hasAtom("var_is_introduced"); bool funcDep = (yyvsp[(5) - (6)].argVec)->hasAtom("is_defined_var"); yyassert(pp, pp->symbols.put((yyvsp[(4) - (6)].sValue), se_fv(pp->floatvars.size())), "Duplicate symbol"); if (print) { pp->output(std::string((yyvsp[(4) - (6)].sValue)), new AST::FloatVar(pp->floatvars.size())); } if ((yyvsp[(6) - (6)].oArg)()) { AST::Node* arg = (yyvsp[(6) - (6)].oArg).some(); if (arg->isFloat()) { pp->floatvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new FloatVarSpec(arg->getFloat(),introduced,funcDep))); } else if (arg->isFloatVar()) { pp->floatvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new FloatVarSpec( Alias(arg->getFloatVar()),introduced,funcDep))); } else { yyassert(pp, false, "Invalid var float initializer"); } if (!pp->hadError && (yyvsp[(2) - (6)].oPFloat)()) { AST::FloatVar* fv = new AST::FloatVar(pp->floatvars.size()-1); addDomainConstraint(pp, fv, (yyvsp[(2) - (6)].oPFloat)); } delete arg; } else { Option<std::pair<double,double> > dom = (yyvsp[(2) - (6)].oPFloat)() ? Option<std::pair<double,double> >::some(*(yyvsp[(2) - (6)].oPFloat).some()) : Option<std::pair<double,double> >::none(); if ((yyvsp[(2) - (6)].oPFloat)()) delete (yyvsp[(2) - (6)].oPFloat).some(); pp->floatvars.push_back(varspec((yyvsp[(4) - (6)].sValue), new FloatVarSpec(dom,introduced,funcDep))); } delete (yyvsp[(5) - (6)].argVec); free((yyvsp[(4) - (6)].sValue)); } break; case 38: /* Line 1792 of yacc.c */ #line 713 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); bool print = (yyvsp[(7) - (8)].argVec)->hasAtom("output_var"); bool introduced = (yyvsp[(7) - (8)].argVec)->hasAtom("var_is_introduced"); bool funcDep = (yyvsp[(7) - (8)].argVec)->hasAtom("is_defined_var"); yyassert(pp, pp->symbols.put((yyvsp[(6) - (8)].sValue), se_sv(pp->setvars.size())), "Duplicate symbol"); if (print) { pp->output(std::string((yyvsp[(6) - (8)].sValue)), new AST::SetVar(pp->setvars.size())); } if ((yyvsp[(8) - (8)].oArg)()) { AST::Node* arg = (yyvsp[(8) - (8)].oArg).some(); if (arg->isSet()) { pp->setvars.push_back(varspec((yyvsp[(6) - (8)].sValue), new SetVarSpec(arg->getSet(),introduced,funcDep))); } else if (arg->isSetVar()) { pp->setvars.push_back(varspec((yyvsp[(6) - (8)].sValue), new SetVarSpec(Alias(arg->getSetVar()),introduced,funcDep))); delete arg; } else { yyassert(pp, false, "Invalid var set initializer"); delete arg; } if (!pp->hadError) addDomainConstraint(pp, "set_subset", new AST::SetVar(pp->setvars.size()-1), (yyvsp[(4) - (8)].oSet)); } else { pp->setvars.push_back(varspec((yyvsp[(6) - (8)].sValue), new SetVarSpec((yyvsp[(4) - (8)].oSet),introduced,funcDep))); } delete (yyvsp[(7) - (8)].argVec); free((yyvsp[(6) - (8)].sValue)); } break; case 39: /* Line 1792 of yacc.c */ #line 747 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(6) - (6)].arg)->isInt(), "Invalid int initializer"); yyassert(pp, pp->symbols.put((yyvsp[(3) - (6)].sValue), se_i((yyvsp[(6) - (6)].arg)->getInt())), "Duplicate symbol"); delete (yyvsp[(4) - (6)].argVec); free((yyvsp[(3) - (6)].sValue)); } break; case 40: /* Line 1792 of yacc.c */ #line 756 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(6) - (6)].arg)->isFloat(), "Invalid float initializer"); pp->floatvals.push_back((yyvsp[(6) - (6)].arg)->getFloat()); yyassert(pp, pp->symbols.put((yyvsp[(3) - (6)].sValue), se_f(pp->floatvals.size()-1)), "Duplicate symbol"); delete (yyvsp[(4) - (6)].argVec); free((yyvsp[(3) - (6)].sValue)); } break; case 41: /* Line 1792 of yacc.c */ #line 766 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(6) - (6)].arg)->isBool(), "Invalid bool initializer"); yyassert(pp, pp->symbols.put((yyvsp[(3) - (6)].sValue), se_b((yyvsp[(6) - (6)].arg)->getBool())), "Duplicate symbol"); delete (yyvsp[(4) - (6)].argVec); free((yyvsp[(3) - (6)].sValue)); } break; case 42: /* Line 1792 of yacc.c */ #line 775 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(8) - (8)].arg)->isSet(), "Invalid set initializer"); AST::SetLit* set = (yyvsp[(8) - (8)].arg)->getSet(); pp->setvals.push_back(*set); yyassert(pp, pp->symbols.put((yyvsp[(5) - (8)].sValue), se_s(pp->setvals.size()-1)), "Duplicate symbol"); delete set; delete (yyvsp[(6) - (8)].argVec); free((yyvsp[(5) - (8)].sValue)); } break; case 43: /* Line 1792 of yacc.c */ #line 788 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(3) - (13)].iValue)==1, "Arrays must start at 1"); if (!pp->hadError) { bool print = (yyvsp[(12) - (13)].argVec)->hasCall("output_array"); vector<int> vars((yyvsp[(5) - (13)].iValue)); if (!pp->hadError) { if ((yyvsp[(13) - (13)].oVarSpecVec)()) { vector<VarSpec*>* vsv = (yyvsp[(13) - (13)].oVarSpecVec).some(); yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[(5) - (13)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) { IntVarSpec* ivsv = static_cast<IntVarSpec*>((*vsv)[i]); if (ivsv->alias) { vars[i] = ivsv->i; } else { vars[i] = pp->intvars.size(); pp->intvars.push_back(varspec((yyvsp[(11) - (13)].sValue), ivsv)); } if (!pp->hadError && (yyvsp[(9) - (13)].oSet)()) { Option<AST::SetLit*> opt = Option<AST::SetLit*>::some(new AST::SetLit(*(yyvsp[(9) - (13)].oSet).some())); addDomainConstraint(pp, "int_in", new AST::IntVar(vars[i]), opt); } } } delete vsv; } else { if ((yyvsp[(5) - (13)].iValue)>0) { IntVarSpec* ispec = new IntVarSpec((yyvsp[(9) - (13)].oSet),false,false); string arrayname = "["; arrayname += (yyvsp[(11) - (13)].sValue); for (int i=0; i<(yyvsp[(5) - (13)].iValue)-1; i++) { vars[i] = pp->intvars.size(); pp->intvars.push_back(varspec(arrayname, ispec)); } vars[(yyvsp[(5) - (13)].iValue)-1] = pp->intvars.size(); pp->intvars.push_back(varspec((yyvsp[(11) - (13)].sValue), ispec)); } } } if (print) { AST::Array* a = new AST::Array(); a->a.push_back(arrayOutput((yyvsp[(12) - (13)].argVec)->getCall("output_array"))); AST::Array* output = new AST::Array(); for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) output->a.push_back(new AST::IntVar(vars[i])); a->a.push_back(output); a->a.push_back(new AST::String(")")); pp->output(std::string((yyvsp[(11) - (13)].sValue)), a); } int iva = pp->arrays.size(); pp->arrays.push_back(vars.size()); for (unsigned int i=0; i<vars.size(); i++) pp->arrays.push_back(vars[i]); yyassert(pp, pp->symbols.put((yyvsp[(11) - (13)].sValue), se_iva(iva)), "Duplicate symbol"); } delete (yyvsp[(12) - (13)].argVec); free((yyvsp[(11) - (13)].sValue)); } break; case 44: /* Line 1792 of yacc.c */ #line 853 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); bool print = (yyvsp[(12) - (13)].argVec)->hasCall("output_array"); yyassert(pp, (yyvsp[(3) - (13)].iValue)==1, "Arrays must start at 1"); if (!pp->hadError) { vector<int> vars((yyvsp[(5) - (13)].iValue)); if ((yyvsp[(13) - (13)].oVarSpecVec)()) { vector<VarSpec*>* vsv = (yyvsp[(13) - (13)].oVarSpecVec).some(); yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[(5) - (13)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) { BoolVarSpec* bvsv = static_cast<BoolVarSpec*>((*vsv)[i]); if (bvsv->alias) vars[i] = bvsv->i; else { vars[i] = pp->boolvars.size(); pp->boolvars.push_back(varspec((yyvsp[(11) - (13)].sValue), (*vsv)[i])); } if (!pp->hadError && (yyvsp[(9) - (13)].oSet)()) { Option<AST::SetLit*> opt = Option<AST::SetLit*>::some(new AST::SetLit(*(yyvsp[(9) - (13)].oSet).some())); addDomainConstraint(pp, "int_in", new AST::BoolVar(vars[i]), opt); } } } delete vsv; } else { for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) { vars[i] = pp->boolvars.size(); pp->boolvars.push_back(varspec((yyvsp[(11) - (13)].sValue), new BoolVarSpec((yyvsp[(9) - (13)].oSet),false,false))); } } if (print) { AST::Array* a = new AST::Array(); a->a.push_back(arrayOutput((yyvsp[(12) - (13)].argVec)->getCall("output_array"))); AST::Array* output = new AST::Array(); for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) output->a.push_back(new AST::BoolVar(vars[i])); a->a.push_back(output); a->a.push_back(new AST::String(")")); pp->output(std::string((yyvsp[(11) - (13)].sValue)), a); } int bva = pp->arrays.size(); pp->arrays.push_back(vars.size()); for (unsigned int i=0; i<vars.size(); i++) pp->arrays.push_back(vars[i]); yyassert(pp, pp->symbols.put((yyvsp[(11) - (13)].sValue), se_bva(bva)), "Duplicate symbol"); } delete (yyvsp[(12) - (13)].argVec); free((yyvsp[(11) - (13)].sValue)); } break; case 45: /* Line 1792 of yacc.c */ #line 912 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(3) - (13)].iValue)==1, "Arrays must start at 1"); if (!pp->hadError) { bool print = (yyvsp[(12) - (13)].argVec)->hasCall("output_array"); vector<int> vars((yyvsp[(5) - (13)].iValue)); if (!pp->hadError) { if ((yyvsp[(13) - (13)].oVarSpecVec)()) { vector<VarSpec*>* vsv = (yyvsp[(13) - (13)].oVarSpecVec).some(); yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[(5) - (13)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) { FloatVarSpec* ivsv = static_cast<FloatVarSpec*>((*vsv)[i]); if (ivsv->alias) { vars[i] = ivsv->i; } else { vars[i] = pp->floatvars.size(); pp->floatvars.push_back(varspec((yyvsp[(11) - (13)].sValue), ivsv)); } if (!pp->hadError && (yyvsp[(9) - (13)].oPFloat)()) { Option<std::pair<double,double>*> opt = Option<std::pair<double,double>*>::some( new std::pair<double,double>(*(yyvsp[(9) - (13)].oPFloat).some())); addDomainConstraint(pp, new AST::FloatVar(vars[i]), opt); } } } delete vsv; } else { if ((yyvsp[(5) - (13)].iValue)>0) { Option<std::pair<double,double> > dom = (yyvsp[(9) - (13)].oPFloat)() ? Option<std::pair<double,double> >::some(*(yyvsp[(9) - (13)].oPFloat).some()) : Option<std::pair<double,double> >::none(); FloatVarSpec* ispec = new FloatVarSpec(dom,false,false); string arrayname = "["; arrayname += (yyvsp[(11) - (13)].sValue); for (int i=0; i<(yyvsp[(5) - (13)].iValue)-1; i++) { vars[i] = pp->floatvars.size(); pp->floatvars.push_back(varspec(arrayname, ispec)); } vars[(yyvsp[(5) - (13)].iValue)-1] = pp->floatvars.size(); pp->floatvars.push_back(varspec((yyvsp[(11) - (13)].sValue), ispec)); } } } if (print) { AST::Array* a = new AST::Array(); a->a.push_back(arrayOutput((yyvsp[(12) - (13)].argVec)->getCall("output_array"))); AST::Array* output = new AST::Array(); for (int i=0; i<(yyvsp[(5) - (13)].iValue); i++) output->a.push_back(new AST::FloatVar(vars[i])); a->a.push_back(output); a->a.push_back(new AST::String(")")); pp->output(std::string((yyvsp[(11) - (13)].sValue)), a); } int fva = pp->arrays.size(); pp->arrays.push_back(vars.size()); for (unsigned int i=0; i<vars.size(); i++) pp->arrays.push_back(vars[i]); yyassert(pp, pp->symbols.put((yyvsp[(11) - (13)].sValue), se_fva(fva)), "Duplicate symbol"); } if ((yyvsp[(9) - (13)].oPFloat)()) delete (yyvsp[(9) - (13)].oPFloat).some(); delete (yyvsp[(12) - (13)].argVec); free((yyvsp[(11) - (13)].sValue)); } break; case 46: /* Line 1792 of yacc.c */ #line 981 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); bool print = (yyvsp[(14) - (15)].argVec)->hasCall("output_array"); yyassert(pp, (yyvsp[(3) - (15)].iValue)==1, "Arrays must start at 1"); if (!pp->hadError) { vector<int> vars((yyvsp[(5) - (15)].iValue)); if ((yyvsp[(15) - (15)].oVarSpecVec)()) { vector<VarSpec*>* vsv = (yyvsp[(15) - (15)].oVarSpecVec).some(); yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[(5) - (15)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { for (int i=0; i<(yyvsp[(5) - (15)].iValue); i++) { SetVarSpec* svsv = static_cast<SetVarSpec*>((*vsv)[i]); if (svsv->alias) vars[i] = svsv->i; else { vars[i] = pp->setvars.size(); pp->setvars.push_back(varspec((yyvsp[(13) - (15)].sValue), (*vsv)[i])); } if (!pp->hadError && (yyvsp[(11) - (15)].oSet)()) { Option<AST::SetLit*> opt = Option<AST::SetLit*>::some(new AST::SetLit(*(yyvsp[(11) - (15)].oSet).some())); addDomainConstraint(pp, "set_subset", new AST::SetVar(vars[i]), opt); } } } delete vsv; } else { if ((yyvsp[(5) - (15)].iValue)>0) { SetVarSpec* ispec = new SetVarSpec((yyvsp[(11) - (15)].oSet),false,false); string arrayname = "["; arrayname += (yyvsp[(13) - (15)].sValue); for (int i=0; i<(yyvsp[(5) - (15)].iValue)-1; i++) { vars[i] = pp->setvars.size(); pp->setvars.push_back(varspec(arrayname, ispec)); } vars[(yyvsp[(5) - (15)].iValue)-1] = pp->setvars.size(); pp->setvars.push_back(varspec((yyvsp[(13) - (15)].sValue), ispec)); } } if (print) { AST::Array* a = new AST::Array(); a->a.push_back(arrayOutput((yyvsp[(14) - (15)].argVec)->getCall("output_array"))); AST::Array* output = new AST::Array(); for (int i=0; i<(yyvsp[(5) - (15)].iValue); i++) output->a.push_back(new AST::SetVar(vars[i])); a->a.push_back(output); a->a.push_back(new AST::String(")")); pp->output(std::string((yyvsp[(13) - (15)].sValue)), a); } int sva = pp->arrays.size(); pp->arrays.push_back(vars.size()); for (unsigned int i=0; i<vars.size(); i++) pp->arrays.push_back(vars[i]); yyassert(pp, pp->symbols.put((yyvsp[(13) - (15)].sValue), se_sva(sva)), "Duplicate symbol"); } delete (yyvsp[(14) - (15)].argVec); free((yyvsp[(13) - (15)].sValue)); } break; case 47: /* Line 1792 of yacc.c */ #line 1044 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(3) - (15)].iValue)==1, "Arrays must start at 1"); yyassert(pp, (yyvsp[(14) - (15)].setValue)->size() == static_cast<unsigned int>((yyvsp[(5) - (15)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { int ia = pp->arrays.size(); pp->arrays.push_back((yyvsp[(14) - (15)].setValue)->size()); for (unsigned int i=0; i<(yyvsp[(14) - (15)].setValue)->size(); i++) pp->arrays.push_back((*(yyvsp[(14) - (15)].setValue))[i]); yyassert(pp, pp->symbols.put((yyvsp[(10) - (15)].sValue), se_ia(ia)), "Duplicate symbol"); } delete (yyvsp[(14) - (15)].setValue); free((yyvsp[(10) - (15)].sValue)); delete (yyvsp[(11) - (15)].argVec); } break; case 48: /* Line 1792 of yacc.c */ #line 1065 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(3) - (15)].iValue)==1, "Arrays must start at 1"); yyassert(pp, (yyvsp[(14) - (15)].setValue)->size() == static_cast<unsigned int>((yyvsp[(5) - (15)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { int ia = pp->arrays.size(); pp->arrays.push_back((yyvsp[(14) - (15)].setValue)->size()); for (unsigned int i=0; i<(yyvsp[(14) - (15)].setValue)->size(); i++) pp->arrays.push_back((*(yyvsp[(14) - (15)].setValue))[i]); yyassert(pp, pp->symbols.put((yyvsp[(10) - (15)].sValue), se_ba(ia)), "Duplicate symbol"); } delete (yyvsp[(14) - (15)].setValue); free((yyvsp[(10) - (15)].sValue)); delete (yyvsp[(11) - (15)].argVec); } break; case 49: /* Line 1792 of yacc.c */ #line 1085 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(3) - (15)].iValue)==1, "Arrays must start at 1"); yyassert(pp, (yyvsp[(14) - (15)].floatSetValue)->size() == static_cast<unsigned int>((yyvsp[(5) - (15)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { int fa = pp->arrays.size(); pp->arrays.push_back((yyvsp[(14) - (15)].floatSetValue)->size()); pp->arrays.push_back(pp->floatvals.size()); for (unsigned int i=0; i<(yyvsp[(14) - (15)].floatSetValue)->size(); i++) pp->floatvals.push_back((*(yyvsp[(14) - (15)].floatSetValue))[i]); yyassert(pp, pp->symbols.put((yyvsp[(10) - (15)].sValue), se_fa(fa)), "Duplicate symbol"); } delete (yyvsp[(14) - (15)].floatSetValue); delete (yyvsp[(11) - (15)].argVec); free((yyvsp[(10) - (15)].sValue)); } break; case 50: /* Line 1792 of yacc.c */ #line 1105 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); yyassert(pp, (yyvsp[(3) - (17)].iValue)==1, "Arrays must start at 1"); yyassert(pp, (yyvsp[(16) - (17)].setValueList)->size() == static_cast<unsigned int>((yyvsp[(5) - (17)].iValue)), "Initializer size does not match array dimension"); if (!pp->hadError) { int sa = pp->arrays.size(); pp->arrays.push_back((yyvsp[(16) - (17)].setValueList)->size()); pp->arrays.push_back(pp->setvals.size()); for (unsigned int i=0; i<(yyvsp[(16) - (17)].setValueList)->size(); i++) pp->setvals.push_back((*(yyvsp[(16) - (17)].setValueList))[i]); yyassert(pp, pp->symbols.put((yyvsp[(12) - (17)].sValue), se_sa(sa)), "Duplicate symbol"); } delete (yyvsp[(16) - (17)].setValueList); delete (yyvsp[(13) - (17)].argVec); free((yyvsp[(12) - (17)].sValue)); } break; case 51: /* Line 1792 of yacc.c */ #line 1127 "gecode/flatzinc/parser.yxx" { (yyval.varSpec) = new IntVarSpec((yyvsp[(1) - (1)].iValue),false,false); } break; case 52: /* Line 1792 of yacc.c */ #line 1131 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (1)].sValue), e) && e.t == ST_INTVAR) (yyval.varSpec) = new IntVarSpec(Alias(e.i),false,false); else { pp->err << "Error: undefined identifier " << (yyvsp[(1) - (1)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new IntVarSpec(0,false,false); // keep things consistent } free((yyvsp[(1) - (1)].sValue)); } break; case 53: /* Line 1792 of yacc.c */ #line 1146 "gecode/flatzinc/parser.yxx" { vector<int> v; SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (4)].sValue), e) && e.t == ST_INTVARARRAY) { yyassert(pp,(yyvsp[(3) - (4)].iValue) > 0 && (yyvsp[(3) - (4)].iValue) <= pp->arrays[e.i], "array access out of bounds"); if (!pp->hadError) (yyval.varSpec) = new IntVarSpec(Alias(pp->arrays[e.i+(yyvsp[(3) - (4)].iValue)]),false,false); else (yyval.varSpec) = new IntVarSpec(0,false,false); // keep things consistent } else { pp->err << "Error: undefined array identifier " << (yyvsp[(1) - (4)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new IntVarSpec(0,false,false); // keep things consistent } free((yyvsp[(1) - (4)].sValue)); } break; case 54: /* Line 1792 of yacc.c */ #line 1169 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(0); } break; case 55: /* Line 1792 of yacc.c */ #line 1171 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (2)].varSpecVec); } break; case 56: /* Line 1792 of yacc.c */ #line 1175 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(1); (*(yyval.varSpecVec))[0] = (yyvsp[(1) - (1)].varSpec); } break; case 57: /* Line 1792 of yacc.c */ #line 1177 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (3)].varSpecVec); (yyval.varSpecVec)->push_back((yyvsp[(3) - (3)].varSpec)); } break; case 60: /* Line 1792 of yacc.c */ #line 1182 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(2) - (3)].varSpecVec); } break; case 61: /* Line 1792 of yacc.c */ #line 1186 "gecode/flatzinc/parser.yxx" { (yyval.varSpec) = new FloatVarSpec((yyvsp[(1) - (1)].dValue),false,false); } break; case 62: /* Line 1792 of yacc.c */ #line 1188 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (1)].sValue), e) && e.t == ST_FLOATVAR) (yyval.varSpec) = new FloatVarSpec(Alias(e.i),false,false); else { pp->err << "Error: undefined identifier " << (yyvsp[(1) - (1)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new FloatVarSpec(0.0,false,false); } free((yyvsp[(1) - (1)].sValue)); } break; case 63: /* Line 1792 of yacc.c */ #line 1203 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (4)].sValue), e) && e.t == ST_FLOATVARARRAY) { yyassert(pp,(yyvsp[(3) - (4)].iValue) > 0 && (yyvsp[(3) - (4)].iValue) <= pp->arrays[e.i], "array access out of bounds"); if (!pp->hadError) (yyval.varSpec) = new FloatVarSpec(Alias(pp->arrays[e.i+(yyvsp[(3) - (4)].iValue)]),false,false); else (yyval.varSpec) = new FloatVarSpec(0.0,false,false); } else { pp->err << "Error: undefined array identifier " << (yyvsp[(1) - (4)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new FloatVarSpec(0.0,false,false); } free((yyvsp[(1) - (4)].sValue)); } break; case 64: /* Line 1792 of yacc.c */ #line 1225 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(0); } break; case 65: /* Line 1792 of yacc.c */ #line 1227 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (2)].varSpecVec); } break; case 66: /* Line 1792 of yacc.c */ #line 1231 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(1); (*(yyval.varSpecVec))[0] = (yyvsp[(1) - (1)].varSpec); } break; case 67: /* Line 1792 of yacc.c */ #line 1233 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (3)].varSpecVec); (yyval.varSpecVec)->push_back((yyvsp[(3) - (3)].varSpec)); } break; case 68: /* Line 1792 of yacc.c */ #line 1237 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(2) - (3)].varSpecVec); } break; case 69: /* Line 1792 of yacc.c */ #line 1241 "gecode/flatzinc/parser.yxx" { (yyval.varSpec) = new BoolVarSpec((yyvsp[(1) - (1)].iValue),false,false); } break; case 70: /* Line 1792 of yacc.c */ #line 1243 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (1)].sValue), e) && e.t == ST_BOOLVAR) (yyval.varSpec) = new BoolVarSpec(Alias(e.i),false,false); else { pp->err << "Error: undefined identifier " << (yyvsp[(1) - (1)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new BoolVarSpec(false,false,false); } free((yyvsp[(1) - (1)].sValue)); } break; case 71: /* Line 1792 of yacc.c */ #line 1258 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (4)].sValue), e) && e.t == ST_BOOLVARARRAY) { yyassert(pp,(yyvsp[(3) - (4)].iValue) > 0 && (yyvsp[(3) - (4)].iValue) <= pp->arrays[e.i], "array access out of bounds"); if (!pp->hadError) (yyval.varSpec) = new BoolVarSpec(Alias(pp->arrays[e.i+(yyvsp[(3) - (4)].iValue)]),false,false); else (yyval.varSpec) = new BoolVarSpec(false,false,false); } else { pp->err << "Error: undefined array identifier " << (yyvsp[(1) - (4)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new BoolVarSpec(false,false,false); } free((yyvsp[(1) - (4)].sValue)); } break; case 72: /* Line 1792 of yacc.c */ #line 1280 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(0); } break; case 73: /* Line 1792 of yacc.c */ #line 1282 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (2)].varSpecVec); } break; case 74: /* Line 1792 of yacc.c */ #line 1286 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(1); (*(yyval.varSpecVec))[0] = (yyvsp[(1) - (1)].varSpec); } break; case 75: /* Line 1792 of yacc.c */ #line 1288 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (3)].varSpecVec); (yyval.varSpecVec)->push_back((yyvsp[(3) - (3)].varSpec)); } break; case 76: /* Line 1792 of yacc.c */ #line 1290 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(2) - (3)].varSpecVec); } break; case 77: /* Line 1792 of yacc.c */ #line 1294 "gecode/flatzinc/parser.yxx" { (yyval.varSpec) = new SetVarSpec((yyvsp[(1) - (1)].setLit),false,false); } break; case 78: /* Line 1792 of yacc.c */ #line 1296 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); SymbolEntry e; if (pp->symbols.get((yyvsp[(1) - (1)].sValue), e) && e.t == ST_SETVAR) (yyval.varSpec) = new SetVarSpec(Alias(e.i),false,false); else { pp->err << "Error: undefined identifier " << (yyvsp[(1) - (1)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new SetVarSpec(Alias(0),false,false); } free((yyvsp[(1) - (1)].sValue)); } break; case 79: /* Line 1792 of yacc.c */ #line 1311 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState* pp = static_cast<ParserState*>(parm); if (pp->symbols.get((yyvsp[(1) - (4)].sValue), e) && e.t == ST_SETVARARRAY) { yyassert(pp,(yyvsp[(3) - (4)].iValue) > 0 && (yyvsp[(3) - (4)].iValue) <= pp->arrays[e.i], "array access out of bounds"); if (!pp->hadError) (yyval.varSpec) = new SetVarSpec(Alias(pp->arrays[e.i+(yyvsp[(3) - (4)].iValue)]),false,false); else (yyval.varSpec) = new SetVarSpec(Alias(0),false,false); } else { pp->err << "Error: undefined array identifier " << (yyvsp[(1) - (4)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.varSpec) = new SetVarSpec(Alias(0),false,false); } free((yyvsp[(1) - (4)].sValue)); } break; case 80: /* Line 1792 of yacc.c */ #line 1333 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(0); } break; case 81: /* Line 1792 of yacc.c */ #line 1335 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (2)].varSpecVec); } break; case 82: /* Line 1792 of yacc.c */ #line 1339 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = new vector<VarSpec*>(1); (*(yyval.varSpecVec))[0] = (yyvsp[(1) - (1)].varSpec); } break; case 83: /* Line 1792 of yacc.c */ #line 1341 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(1) - (3)].varSpecVec); (yyval.varSpecVec)->push_back((yyvsp[(3) - (3)].varSpec)); } break; case 84: /* Line 1792 of yacc.c */ #line 1344 "gecode/flatzinc/parser.yxx" { (yyval.varSpecVec) = (yyvsp[(2) - (3)].varSpecVec); } break; case 85: /* Line 1792 of yacc.c */ #line 1348 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none(); } break; case 86: /* Line 1792 of yacc.c */ #line 1350 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[(2) - (2)].varSpecVec)); } break; case 87: /* Line 1792 of yacc.c */ #line 1354 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none(); } break; case 88: /* Line 1792 of yacc.c */ #line 1356 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[(2) - (2)].varSpecVec)); } break; case 89: /* Line 1792 of yacc.c */ #line 1360 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none(); } break; case 90: /* Line 1792 of yacc.c */ #line 1362 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[(2) - (2)].varSpecVec)); } break; case 91: /* Line 1792 of yacc.c */ #line 1366 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none(); } break; case 92: /* Line 1792 of yacc.c */ #line 1368 "gecode/flatzinc/parser.yxx" { (yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[(2) - (2)].varSpecVec)); } break; case 93: /* Line 1792 of yacc.c */ #line 1372 "gecode/flatzinc/parser.yxx" { ParserState *pp = static_cast<ParserState*>(parm); if (!pp->hadError) { ConExpr c((yyvsp[(2) - (6)].sValue), (yyvsp[(4) - (6)].argVec)); try { pp->fg->postConstraint(c, (yyvsp[(6) - (6)].argVec)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } delete (yyvsp[(6) - (6)].argVec); free((yyvsp[(2) - (6)].sValue)); } break; case 94: /* Line 1792 of yacc.c */ #line 1386 "gecode/flatzinc/parser.yxx" { ParserState *pp = static_cast<ParserState*>(parm); if (!pp->hadError) { try { pp->fg->solve((yyvsp[(2) - (3)].argVec)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } else { delete (yyvsp[(2) - (3)].argVec); } } break; case 95: /* Line 1792 of yacc.c */ #line 1399 "gecode/flatzinc/parser.yxx" { ParserState *pp = static_cast<ParserState*>(parm); if (!pp->hadError) { try { int v = (yyvsp[(4) - (4)].iValue) < 0 ? (-(yyvsp[(4) - (4)].iValue)-1) : (yyvsp[(4) - (4)].iValue); bool vi = (yyvsp[(4) - (4)].iValue) >= 0; if ((yyvsp[(3) - (4)].bValue)) pp->fg->minimize(v,vi,(yyvsp[(2) - (4)].argVec)); else pp->fg->maximize(v,vi,(yyvsp[(2) - (4)].argVec)); } catch (Gecode::FlatZinc::Error& e) { yyerror(pp, e.toString().c_str()); } } else { delete (yyvsp[(2) - (4)].argVec); } } break; case 96: /* Line 1792 of yacc.c */ #line 1423 "gecode/flatzinc/parser.yxx" { (yyval.oSet) = Option<AST::SetLit* >::none(); } break; case 97: /* Line 1792 of yacc.c */ #line 1425 "gecode/flatzinc/parser.yxx" { (yyval.oSet) = Option<AST::SetLit* >::some(new AST::SetLit(*(yyvsp[(2) - (3)].setValue))); } break; case 98: /* Line 1792 of yacc.c */ #line 1427 "gecode/flatzinc/parser.yxx" { (yyval.oSet) = Option<AST::SetLit* >::some(new AST::SetLit((yyvsp[(1) - (3)].iValue), (yyvsp[(3) - (3)].iValue))); } break; case 99: /* Line 1792 of yacc.c */ #line 1433 "gecode/flatzinc/parser.yxx" { (yyval.oSet) = Option<AST::SetLit* >::none(); } break; case 100: /* Line 1792 of yacc.c */ #line 1435 "gecode/flatzinc/parser.yxx" { bool haveTrue = false; bool haveFalse = false; for (int i=(yyvsp[(2) - (4)].setValue)->size(); i--;) { haveTrue |= ((*(yyvsp[(2) - (4)].setValue))[i] == 1); haveFalse |= ((*(yyvsp[(2) - (4)].setValue))[i] == 0); } delete (yyvsp[(2) - (4)].setValue); (yyval.oSet) = Option<AST::SetLit* >::some( new AST::SetLit(!haveFalse,haveTrue)); } break; case 101: /* Line 1792 of yacc.c */ #line 1448 "gecode/flatzinc/parser.yxx" { (yyval.oPFloat) = Option<std::pair<double,double>* >::none(); } break; case 102: /* Line 1792 of yacc.c */ #line 1450 "gecode/flatzinc/parser.yxx" { std::pair<double,double>* dom = new std::pair<double,double>((yyvsp[(1) - (3)].dValue),(yyvsp[(3) - (3)].dValue)); (yyval.oPFloat) = Option<std::pair<double,double>* >::some(dom); } break; case 103: /* Line 1792 of yacc.c */ #line 1459 "gecode/flatzinc/parser.yxx" { (yyval.setLit) = new AST::SetLit(*(yyvsp[(2) - (3)].setValue)); } break; case 104: /* Line 1792 of yacc.c */ #line 1461 "gecode/flatzinc/parser.yxx" { (yyval.setLit) = new AST::SetLit((yyvsp[(1) - (3)].iValue), (yyvsp[(3) - (3)].iValue)); } break; case 105: /* Line 1792 of yacc.c */ #line 1467 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = new vector<int>(0); } break; case 106: /* Line 1792 of yacc.c */ #line 1469 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = (yyvsp[(1) - (2)].setValue); } break; case 107: /* Line 1792 of yacc.c */ #line 1473 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = new vector<int>(1); (*(yyval.setValue))[0] = (yyvsp[(1) - (1)].iValue); } break; case 108: /* Line 1792 of yacc.c */ #line 1475 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = (yyvsp[(1) - (3)].setValue); (yyval.setValue)->push_back((yyvsp[(3) - (3)].iValue)); } break; case 109: /* Line 1792 of yacc.c */ #line 1479 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = new vector<int>(0); } break; case 110: /* Line 1792 of yacc.c */ #line 1481 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = (yyvsp[(1) - (2)].setValue); } break; case 111: /* Line 1792 of yacc.c */ #line 1485 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = new vector<int>(1); (*(yyval.setValue))[0] = (yyvsp[(1) - (1)].iValue); } break; case 112: /* Line 1792 of yacc.c */ #line 1487 "gecode/flatzinc/parser.yxx" { (yyval.setValue) = (yyvsp[(1) - (3)].setValue); (yyval.setValue)->push_back((yyvsp[(3) - (3)].iValue)); } break; case 113: /* Line 1792 of yacc.c */ #line 1491 "gecode/flatzinc/parser.yxx" { (yyval.floatSetValue) = new vector<double>(0); } break; case 114: /* Line 1792 of yacc.c */ #line 1493 "gecode/flatzinc/parser.yxx" { (yyval.floatSetValue) = (yyvsp[(1) - (2)].floatSetValue); } break; case 115: /* Line 1792 of yacc.c */ #line 1497 "gecode/flatzinc/parser.yxx" { (yyval.floatSetValue) = new vector<double>(1); (*(yyval.floatSetValue))[0] = (yyvsp[(1) - (1)].dValue); } break; case 116: /* Line 1792 of yacc.c */ #line 1499 "gecode/flatzinc/parser.yxx" { (yyval.floatSetValue) = (yyvsp[(1) - (3)].floatSetValue); (yyval.floatSetValue)->push_back((yyvsp[(3) - (3)].dValue)); } break; case 117: /* Line 1792 of yacc.c */ #line 1503 "gecode/flatzinc/parser.yxx" { (yyval.setValueList) = new vector<AST::SetLit>(0); } break; case 118: /* Line 1792 of yacc.c */ #line 1505 "gecode/flatzinc/parser.yxx" { (yyval.setValueList) = (yyvsp[(1) - (2)].setValueList); } break; case 119: /* Line 1792 of yacc.c */ #line 1509 "gecode/flatzinc/parser.yxx" { (yyval.setValueList) = new vector<AST::SetLit>(1); (*(yyval.setValueList))[0] = *(yyvsp[(1) - (1)].setLit); delete (yyvsp[(1) - (1)].setLit); } break; case 120: /* Line 1792 of yacc.c */ #line 1511 "gecode/flatzinc/parser.yxx" { (yyval.setValueList) = (yyvsp[(1) - (3)].setValueList); (yyval.setValueList)->push_back(*(yyvsp[(3) - (3)].setLit)); delete (yyvsp[(3) - (3)].setLit); } break; case 121: /* Line 1792 of yacc.c */ #line 1519 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = new AST::Array((yyvsp[(1) - (1)].arg)); } break; case 122: /* Line 1792 of yacc.c */ #line 1521 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = (yyvsp[(1) - (3)].argVec); (yyval.argVec)->append((yyvsp[(3) - (3)].arg)); } break; case 123: /* Line 1792 of yacc.c */ #line 1525 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(1) - (1)].arg); } break; case 124: /* Line 1792 of yacc.c */ #line 1527 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(2) - (3)].argVec); } break; case 125: /* Line 1792 of yacc.c */ #line 1531 "gecode/flatzinc/parser.yxx" { (yyval.oArg) = Option<AST::Node*>::none(); } break; case 126: /* Line 1792 of yacc.c */ #line 1533 "gecode/flatzinc/parser.yxx" { (yyval.oArg) = Option<AST::Node*>::some((yyvsp[(2) - (2)].arg)); } break; case 127: /* Line 1792 of yacc.c */ #line 1537 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::BoolLit((yyvsp[(1) - (1)].iValue)); } break; case 128: /* Line 1792 of yacc.c */ #line 1539 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::IntLit((yyvsp[(1) - (1)].iValue)); } break; case 129: /* Line 1792 of yacc.c */ #line 1541 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::FloatLit((yyvsp[(1) - (1)].dValue)); } break; case 130: /* Line 1792 of yacc.c */ #line 1543 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(1) - (1)].setLit); } break; case 131: /* Line 1792 of yacc.c */ #line 1545 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); SymbolEntry e; if (pp->symbols.get((yyvsp[(1) - (1)].sValue), e)) { switch (e.t) { case ST_INTVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::IntVar(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_BOOLVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::BoolVar(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_FLOATVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::FloatVar(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_SETVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::SetVar(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_INTVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::IntLit(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_BOOLVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::BoolLit(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_SETVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); int idx = pp->arrays[e.i+1]; for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::SetLit(pp->setvals[idx+i]); (yyval.arg) = v; } break; case ST_FLOATVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); int idx = pp->arrays[e.i+1]; for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::FloatLit(pp->floatvals[idx+i]); (yyval.arg) = v; } break; case ST_INT: (yyval.arg) = new AST::IntLit(e.i); break; case ST_BOOL: (yyval.arg) = new AST::BoolLit(e.i); break; case ST_FLOAT: (yyval.arg) = new AST::FloatLit(pp->floatvals[e.i]); break; case ST_SET: (yyval.arg) = new AST::SetLit(pp->setvals[e.i]); break; default: (yyval.arg) = getVarRefArg(pp,(yyvsp[(1) - (1)].sValue)); } } else { pp->err << "Error: undefined identifier " << (yyvsp[(1) - (1)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; (yyval.arg) = NULL; } free((yyvsp[(1) - (1)].sValue)); } break; case 132: /* Line 1792 of yacc.c */ #line 1641 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); int i = -1; yyassert(pp, (yyvsp[(3) - (4)].arg)->isInt(i), "Non-integer array index"); if (!pp->hadError) (yyval.arg) = getArrayElement(static_cast<ParserState*>(parm),(yyvsp[(1) - (4)].sValue),i,false); else (yyval.arg) = new AST::IntLit(0); // keep things consistent delete (yyvsp[(3) - (4)].arg); free((yyvsp[(1) - (4)].sValue)); } break; case 133: /* Line 1792 of yacc.c */ #line 1655 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = new AST::Array(0); } break; case 134: /* Line 1792 of yacc.c */ #line 1657 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = (yyvsp[(1) - (2)].argVec); } break; case 135: /* Line 1792 of yacc.c */ #line 1661 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = new AST::Array((yyvsp[(1) - (1)].arg)); } break; case 136: /* Line 1792 of yacc.c */ #line 1663 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = (yyvsp[(1) - (3)].argVec); (yyval.argVec)->append((yyvsp[(3) - (3)].arg)); } break; case 137: /* Line 1792 of yacc.c */ #line 1671 "gecode/flatzinc/parser.yxx" { ParserState *pp = static_cast<ParserState*>(parm); SymbolEntry e; bool haveSym = pp->symbols.get((yyvsp[(1) - (1)].sValue),e); if (haveSym && e.t == ST_INTVAR) { (yyval.iValue) = e.i; } else if (haveSym && e.t == ST_FLOATVAR) { (yyval.iValue) = -e.i-1; } else { pp->err << "Error: unknown int or float variable " << (yyvsp[(1) - (1)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; } free((yyvsp[(1) - (1)].sValue)); } break; case 138: /* Line 1792 of yacc.c */ #line 1688 "gecode/flatzinc/parser.yxx" { SymbolEntry e; ParserState *pp = static_cast<ParserState*>(parm); if ( (!pp->symbols.get((yyvsp[(1) - (4)].sValue), e)) || (e.t != ST_INTVARARRAY && e.t != ST_FLOATVARARRAY)) { pp->err << "Error: unknown int or float variable array " << (yyvsp[(1) - (4)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; } if ((yyvsp[(3) - (4)].iValue) == 0 || (yyvsp[(3) - (4)].iValue) > pp->arrays[e.i]) { pp->err << "Error: array index out of bounds for array " << (yyvsp[(1) - (4)].sValue) << " in line no. " << yyget_lineno(pp->yyscanner) << std::endl; pp->hadError = true; } else { if (e.t == ST_INTVARARRAY) (yyval.iValue) = pp->arrays[e.i+(yyvsp[(3) - (4)].iValue)]; else (yyval.iValue) = -pp->arrays[e.i+(yyvsp[(3) - (4)].iValue)]-1; } free((yyvsp[(1) - (4)].sValue)); } break; case 141: /* Line 1792 of yacc.c */ #line 1722 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = NULL; } break; case 142: /* Line 1792 of yacc.c */ #line 1724 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = (yyvsp[(1) - (1)].argVec); } break; case 143: /* Line 1792 of yacc.c */ #line 1728 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = new AST::Array((yyvsp[(2) - (2)].arg)); } break; case 144: /* Line 1792 of yacc.c */ #line 1730 "gecode/flatzinc/parser.yxx" { (yyval.argVec) = (yyvsp[(1) - (3)].argVec); (yyval.argVec)->append((yyvsp[(3) - (3)].arg)); } break; case 145: /* Line 1792 of yacc.c */ #line 1734 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::Call((yyvsp[(1) - (4)].sValue), AST::extractSingleton((yyvsp[(3) - (4)].arg))); free((yyvsp[(1) - (4)].sValue)); } break; case 146: /* Line 1792 of yacc.c */ #line 1738 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(1) - (1)].arg); } break; case 147: /* Line 1792 of yacc.c */ #line 1742 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::Array((yyvsp[(1) - (1)].arg)); } break; case 148: /* Line 1792 of yacc.c */ #line 1744 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(1) - (3)].arg); (yyval.arg)->append((yyvsp[(3) - (3)].arg)); } break; case 149: /* Line 1792 of yacc.c */ #line 1748 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(1) - (1)].arg); } break; case 150: /* Line 1792 of yacc.c */ #line 1750 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(2) - (4)].arg); } break; case 153: /* Line 1792 of yacc.c */ #line 1756 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::BoolLit((yyvsp[(1) - (1)].iValue)); } break; case 154: /* Line 1792 of yacc.c */ #line 1758 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::IntLit((yyvsp[(1) - (1)].iValue)); } break; case 155: /* Line 1792 of yacc.c */ #line 1760 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::FloatLit((yyvsp[(1) - (1)].dValue)); } break; case 156: /* Line 1792 of yacc.c */ #line 1762 "gecode/flatzinc/parser.yxx" { (yyval.arg) = (yyvsp[(1) - (1)].setLit); } break; case 157: /* Line 1792 of yacc.c */ #line 1764 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); SymbolEntry e; bool gotSymbol = false; if (pp->symbols.get((yyvsp[(1) - (1)].sValue), e)) { gotSymbol = true; switch (e.t) { case ST_INTVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) { std::ostringstream oss; oss << (yyvsp[(1) - (1)].sValue) << "["<<(i+1)<<"]"; v->a[i] = new AST::IntVar(pp->arrays[e.i+i+1], oss.str()); } (yyval.arg) = v; } break; case ST_BOOLVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) { std::ostringstream oss; oss << (yyvsp[(1) - (1)].sValue) << "["<<(i+1)<<"]"; v->a[i] = new AST::BoolVar(pp->arrays[e.i+i+1], oss.str()); } (yyval.arg) = v; } break; case ST_FLOATVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) { std::ostringstream oss; oss << (yyvsp[(1) - (1)].sValue) << "["<<(i+1)<<"]"; v->a[i] = new AST::FloatVar(pp->arrays[e.i+i+1], oss.str()); } (yyval.arg) = v; } break; case ST_SETVARARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) { std::ostringstream oss; oss << (yyvsp[(1) - (1)].sValue) << "["<<(i+1)<<"]"; v->a[i] = new AST::SetVar(pp->arrays[e.i+i+1], oss.str()); } (yyval.arg) = v; } break; case ST_INTVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::IntLit(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_BOOLVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::BoolLit(pp->arrays[e.i+i+1]); (yyval.arg) = v; } break; case ST_SETVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); int idx = pp->arrays[e.i+1]; for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::SetLit(pp->setvals[idx+i]); (yyval.arg) = v; } break; case ST_FLOATVALARRAY: { AST::Array *v = new AST::Array(pp->arrays[e.i]); int idx = pp->arrays[e.i+1]; for (int i=pp->arrays[e.i]; i--;) v->a[i] = new AST::FloatLit(pp->floatvals[idx+i]); (yyval.arg) = v; } break; case ST_INT: (yyval.arg) = new AST::IntLit(e.i); break; case ST_BOOL: (yyval.arg) = new AST::BoolLit(e.i); break; case ST_FLOAT: (yyval.arg) = new AST::FloatLit(pp->floatvals[e.i]); break; case ST_SET: (yyval.arg) = new AST::SetLit(pp->setvals[e.i]); break; default: gotSymbol = false; } } if (!gotSymbol) (yyval.arg) = getVarRefArg(pp,(yyvsp[(1) - (1)].sValue),true); free((yyvsp[(1) - (1)].sValue)); } break; case 158: /* Line 1792 of yacc.c */ #line 1870 "gecode/flatzinc/parser.yxx" { ParserState* pp = static_cast<ParserState*>(parm); int i = -1; yyassert(pp, (yyvsp[(3) - (4)].arg)->isInt(i), "Non-integer array index"); if (!pp->hadError) (yyval.arg) = getArrayElement(static_cast<ParserState*>(parm),(yyvsp[(1) - (4)].sValue),i,true); else (yyval.arg) = new AST::IntLit(0); // keep things consistent free((yyvsp[(1) - (4)].sValue)); } break; case 159: /* Line 1792 of yacc.c */ #line 1881 "gecode/flatzinc/parser.yxx" { (yyval.arg) = new AST::String((yyvsp[(1) - (1)].sValue)); free((yyvsp[(1) - (1)].sValue)); } break; /* Line 1792 of yacc.c */ #line 3784 "gecode/flatzinc/parser.tab.cpp" default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (parm, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (parm, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, parm); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, parm); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (parm, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, parm); } /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, parm); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); }
35.442451
158
0.507999
[ "vector", "model" ]
a97de92f88ea94fb019cc7c746e05e0d1534660e
6,675
cpp
C++
Modules/planning/local_planner/src/apf.cpp
w407022008/Prometheus
385694ef6c692237cd3e71208973f30fd1a67e1e
[ "BSD-3-Clause" ]
null
null
null
Modules/planning/local_planner/src/apf.cpp
w407022008/Prometheus
385694ef6c692237cd3e71208973f30fd1a67e1e
[ "BSD-3-Clause" ]
null
null
null
Modules/planning/local_planner/src/apf.cpp
w407022008/Prometheus
385694ef6c692237cd3e71208973f30fd1a67e1e
[ "BSD-3-Clause" ]
null
null
null
#include "apf.h" #include "math.h" namespace Local_Planning { Eigen::Vector3d last_desired_vel; auto min=[](double v1, double v2)->double { return v1<v2 ? v1 : v2; }; auto max=[](double v1, double v2)->double { return v1<v2 ? v1 : v2; }; auto sign=[](double v)->double { return v<0.0? -1.0:1.0; }; void APF::init(ros::NodeHandle& nh) { has_local_map_ = false; nh.param("local_planner/inflate_distance", inflate_distance, 0.20); // 最小障碍物距离 nh.param("local_planner/sensor_max_range", sensor_max_range, 2.5); // 感知障碍物距离 nh.param("local_planner/max_planning_vel", max_planning_vel, 0.5); // 最大飞行速度 nh.param("apf/k_push", k_push, 0.8); // 推力增益 nh.param("apf/k_att", k_att, 0.4); // 引力增益 nh.param("apf/max_att_dist", max_att_dist, 5.0); // 最大吸引距离 nh.param("local_planner/ground_height", ground_height, 0.1); // 地面高度 nh.param("apf/ground_safe_height", ground_safe_height, 0.2); // 地面安全距离 nh.param("local_plannerapf/safe_distance", safe_distance, 0.15); // 安全停止距离 // TRUE代表2D平面规划及搜索,FALSE代表3D nh.param("local_planner/is_2D", is_2D, true); sensor_max_range = max(sensor_max_range,3*inflate_distance); } void APF::set_local_map(sensor_msgs::PointCloud2ConstPtr &local_map_ptr) { local_map_ptr_ = local_map_ptr; pcl::fromROSMsg(*local_map_ptr, latest_local_pcl_); has_local_map_=true; } void APF::set_local_map_pcl(pcl::PointCloud<pcl::PointXYZ>::Ptr &pcl_ptr) { latest_local_pcl_ = *pcl_ptr; has_local_map_=true; } void APF::set_odom(nav_msgs::Odometry cur_odom) { cur_odom_ = cur_odom; has_odom_=true; } int APF::compute_force(Eigen::Vector3d &goal, Eigen::Vector3d &desired_vel) { // 0 for not init; 1for safe; 2 for dangerous int local_planner_state=0; int safe_cnt=0; if(!has_local_map_|| !has_odom_) return 0; if ((int)latest_local_pcl_.points.size() == 0) return 0; if (isnan(goal(0)) || isnan(goal(1)) || isnan(goal(2))) return 0; // 当前状态 Eigen::Vector3d current_pos; current_pos[0] = cur_odom_.pose.pose.position.x; current_pos[1] = cur_odom_.pose.pose.position.y; current_pos[2] = cur_odom_.pose.pose.position.z; Eigen::Vector3d current_vel; current_vel[0] = cur_odom_.twist.twist.linear.x; current_vel[1] = cur_odom_.twist.twist.linear.y; current_vel[2] = cur_odom_.twist.twist.linear.z; float current_vel_norm = current_vel.norm(); ros::Time begin_collision = ros::Time::now(); // 引力 Eigen::Vector3d uav2goal = goal - current_pos; double dist_att = uav2goal.norm(); if(dist_att > max_att_dist) { uav2goal = max_att_dist * uav2goal/dist_att ; } // 计算吸引力 attractive_force = k_att * uav2goal; // 排斥力 double uav_height = cur_odom_.pose.pose.position.z; repulsive_force = Eigen::Vector3d(0.0, 0.0, 0.0); guide_force = Eigen::Vector3d(0.0, 0.0, 0.0); int count; double max_guide_force = 0.0; Eigen::Vector3d p3d; vector<Eigen::Vector3d> obstacles; // 根据局部点云计算排斥力(是否可以考虑对点云进行降采样?) for (size_t i = 0; i < latest_local_pcl_.points.size(); ++i) { p3d(0) = latest_local_pcl_.points[i].x; p3d(1) = latest_local_pcl_.points[i].y; p3d(2) = latest_local_pcl_.points[i].z; // World-ENU frame Eigen::Vector3d uav2obs = p3d - current_pos; // 低速悬浮时不考虑 if(current_vel_norm<0.3) continue; // 不考虑地面上的点的排斥力 if(fabs(p3d(2))<ground_height) continue; // 超出感知范围,则不考虑该点的排斥力 double dist_push = (uav2obs).norm(); obs_angle = acos(uav2obs.dot(current_vel) / uav2obs.norm() / current_vel_norm); if(isnan(dist_push) || (dist_push > min(3*inflate_distance,sensor_max_range) && obs_angle > M_PI/6)){ continue; } // 如果当前的观测点中,包含小于安全停止距离的点,进行计数 if(dist_push < safe_distance+inflate_distance) { safe_cnt++; desired_vel += 1000 * (-uav2obs)/dist_push; if(is_2D) { desired_vel[2] = 0.0; } if(safe_cnt>3) { desired_vel /= safe_cnt; return 2; //成功规划,但是飞机不安全 } }else if(dist_push < 3*inflate_distance){ double push_gain = k_push * (1/(dist_push - inflate_distance) - 1/(2*inflate_distance)); repulsive_force += push_gain * (-uav2obs)/dist_push; count ++; } if (obs_angle < M_PI/6){ double force = cos(obs_angle) * min(3,1/(max(inflate_distance,dist_push) - inflate_distance + 1e-6) - 1/(sensor_max_range-inflate_distance)); guide_force += current_vel.cross((-uav2obs).cross(current_vel)) / pow(current_vel_norm,2) / dist_push * force; // or / pow(dist_push,2) if (max_guide_force<force) max_guide_force = force; } obstacles.push_back(p3d); } // 平均排斥力 if(count != 0) { repulsive_force=repulsive_force/count; //obstacles.size(); } if(count==int(obstacles.size())) { guide_force=Eigen::Vector3d(0.0,0.0,0.0); }else{ double guide_force_norm = guide_force.norm(); if(guide_force_norm<1e-6) guide_force += uav2goal; guide_force = max_guide_force*guide_force/guide_force.norm(); } // 地面排斥力 if (current_pos[2] <2*ground_safe_height) repulsive_force += Eigen::Vector3d(0.0, 0.0, 1.0) * k_push * (1/max(max(ground_safe_height,current_pos[2]) - ground_safe_height, 1e-6) - 1/(ground_safe_height)); if(dist_att<1.0) { repulsive_force *= pow(dist_att,2); // to gaurantee to reach the goal. guide_force *= pow(dist_att,2); // to gaurantee to reach the goal. } // 合力 desired_vel = 0.3*repulsive_force + 0.4*attractive_force + 0.3*guide_force; // ENU frame if(is_2D) desired_vel[2] = 0.0; if(max_planning_vel<desired_vel.norm()) desired_vel = desired_vel/desired_vel.norm()*max_planning_vel; desired_vel = 0.5*last_desired_vel + 0.5*desired_vel; last_desired_vel = desired_vel; cout << "guide_force: " << max_guide_force << endl; cout << "repulsive_force: " << repulsive_force.norm() << endl; cout << "attractive_force: " << attractive_force.norm() << endl; cout << "desired_vel: " << desired_vel.norm() << endl; cout << " " << endl; local_planner_state =1; //成功规划, 安全 static int exec_num=0; exec_num++; // 此处改为根据循环时间计算的数值 if(exec_num == 100) { printf("APF calculate take %f [s].\n", (ros::Time::now()-begin_collision).toSec()); exec_num=0; } return local_planner_state; } }
29.799107
163
0.628315
[ "vector" ]
a9817d102765ee93df8694386b2cd0ae160ed19d
1,144
cpp
C++
src/generator.cpp
Joklost/geo
8bf792dfbd6e0be7ac6c24996e5219da374fec98
[ "MIT" ]
1
2019-03-22T12:24:45.000Z
2019-03-22T12:24:45.000Z
src/generator.cpp
Joklost/geo
8bf792dfbd6e0be7ac6c24996e5219da374fec98
[ "MIT" ]
null
null
null
src/generator.cpp
Joklost/geo
8bf792dfbd6e0be7ac6c24996e5219da374fec98
[ "MIT" ]
null
null
null
#include <iomanip> #include <geo/generator.h> #include <geo/geo.h> std::vector<std::string> grid(geo::Location &point, unsigned long len, double gap, double time_end, double time_gap) { if (time_end <= time_gap && time_end <= 0.0 && time_gap <= 0.0) { throw std::runtime_error("time_end and time_gap must be greater than 0"); } std::vector<std::string> lines{}; auto time = 0.0; while (time <= time_end) { auto p = point; auto l = p; auto id = 1; for (auto i = 0; i < len; i++) { std::ostringstream l1{}; l1 << id++ << "," << std::fixed << p.latitude << "," << p.longitude << "," << time; lines.push_back(l1.str()); p = geo::move_location(p, gap, 0); for (auto j = 1; j < len; j++) { l = geo::move_location(l, gap, 90); std::ostringstream l2{}; l2 << id++ << "," << std::fixed << l.latitude << "," << l.longitude << "," << time; lines.push_back(l2.str()); } l = p; } time += time_gap; } return lines; }
28.6
118
0.479895
[ "vector" ]
a983d7db9e7292389523d4ee6f0782e4b0f371f0
30,699
cc
C++
execution/src/windows/execution.cc
lucywyman/leatherman
0d79e5a012c9451700bbe64e28849f8b5dc8629c
[ "Apache-2.0" ]
55
2015-08-27T13:17:42.000Z
2022-02-07T15:19:59.000Z
execution/src/windows/execution.cc
lucywyman/leatherman
0d79e5a012c9451700bbe64e28849f8b5dc8629c
[ "Apache-2.0" ]
236
2015-02-23T23:50:10.000Z
2021-09-01T18:09:12.000Z
execution/src/windows/execution.cc
lucywyman/leatherman
0d79e5a012c9451700bbe64e28849f8b5dc8629c
[ "Apache-2.0" ]
88
2015-02-23T22:40:27.000Z
2022-02-07T15:19:59.000Z
#include <leatherman/execution/execution.hpp> #include <leatherman/util/environment.hpp> #include <leatherman/util/scope_exit.hpp> #include <leatherman/util/windows/scoped_handle.hpp> #include <leatherman/util/scoped_env.hpp> #include <leatherman/windows/system_error.hpp> #include <leatherman/windows/windows.hpp> #include <leatherman/logging/logging.hpp> #include <leatherman/locale/locale.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/nowide/convert.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <cstdlib> #include <cstdio> #include <sstream> #include <cstring> #include <random> // Mark string for translation (alias for leatherman::locale::format) using leatherman::locale::_; using namespace std; using namespace leatherman::windows; using namespace leatherman::logging; using namespace leatherman::util; using namespace leatherman::util::windows; using namespace boost::filesystem; using namespace boost::algorithm; namespace leatherman { namespace execution { void log_execution(string const& file, vector<string> const* arguments); const char *const command_shell = "cmd.exe"; const char *const command_args = "/c"; struct extpath_helper { vector<string> const& ext_paths() const { return _extpaths; } bool contains(const string & ext) const { return binary_search(_extpaths.begin(), _extpaths.end(), to_lower_copy(ext)); } private: // Use sorted, lower-case operations to ignore case and use binary search. vector<string> _extpaths = {".bat", ".cmd", ".com", ".exe"};; }; static bool is_executable(path const& p, extpath_helper const* helper = nullptr) { // If there's an error accessing file status, we assume is_executable // is false and return. The reason for failure doesn't matter to us. boost::system::error_code ec; bool isfile = is_regular_file(p, ec); if (ec) { LOG_TRACE("error reading status of path {1}: {2} ({3})", p, ec.message(), ec.value()); } if (helper) { // Checking extensions aren't needed if we explicitly specified it. // If helper was passed, then we haven't and should check the ext. isfile &= helper->contains(p.extension().string()); } return isfile; } string which(string const& file, vector<string> const& directories, bool expand) { // On Windows is not supported to turn off command expansion by setting expand to false if (!expand) { LOG_ERROR("Unsupported argument on Windows expand with value false"); throw std::invalid_argument("Unsupported argument on Windows"); } // On Windows, everything has execute permission; Ruby determined // executability based on extension {com, exe, bat, cmd}. We'll do the // same check here using extpath_helper. static extpath_helper helper; // If the file is already absolute, return it if it's executable. path p = file; if (p.is_absolute()) { return is_executable(p, &helper) ? p.string() : string(); } // On Windows, treat 'echo' as a command that can be found if (file == "echo") { return "echo"; } // Otherwise, check for an executable file under the given search paths for (auto const& dir : directories) { path p = path(dir) / file; if (!p.has_extension()) { path pext = p; for (auto const&ext : helper.ext_paths()) { pext.replace_extension(ext); if (is_executable(pext)) { return pext.string(); } } } if (is_executable(p, &helper)) { return p.string(); } } return {}; } // Create a pipe, throwing if there's an error. Returns {read, write} handles. // Always creates overlapped pipes. static tuple<scoped_handle, scoped_handle> CreatePipeThrow() { static LONG counter = 0; static boost::uuids::random_generator rand_uuid; SECURITY_ATTRIBUTES attributes = {}; attributes.nLength = sizeof(SECURITY_ATTRIBUTES); attributes.bInheritHandle = TRUE; attributes.lpSecurityDescriptor = NULL; // Format a name for the pipe. Use the thread id to ensure no two threads try to use the same // pipe, and a counter to generate multiple pipes for the same process invocation. // A scenario exists using timeouts where we could release the invoking end of a named pipe // but the other end doesn't release. Then the invoking thread shuts down and another with // the same thread id is started and reconnects to the existing named pipe. Use the process // id and a random UUID to make that highly unlikely. wstring name = boost::nowide::widen(_("\\\\.\\Pipe\\leatherman.{1}.{2}.{3}.{4}", GetCurrentProcessId(), GetCurrentThreadId(), InterlockedIncrement(&counter), to_string(rand_uuid()))); // Create the read pipe scoped_handle read_handle(CreateNamedPipeW( name.c_str(), PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_WAIT, 1, 4096, 4096, 0, &attributes)); if (read_handle == INVALID_HANDLE_VALUE) { LOG_ERROR("failed to create read pipe: {1}.", windows::system_error()); throw execution_exception(_("failed to create read pipe.")); } // Open the write pipe scoped_handle write_handle(CreateFileW( name.c_str(), GENERIC_WRITE, 0, &attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (write_handle == INVALID_HANDLE_VALUE) { LOG_ERROR("failed to create write pipe: {1}.", windows::system_error()); throw execution_exception(_("failed to create write pipe.")); } return make_tuple(move(read_handle), move(write_handle)); } // Source: http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx static string ArgvToCommandLine(vector<string> const& arguments, bool preserve = false) { // Unless we're told otherwise, don't quote unless we actually need to do so - hopefully avoid problems if // programs won't parse quotes properly. string commandline; for (auto const& arg : arguments) { if (arg.empty()) { continue; } else if (preserve || arg.find_first_of(" \t\n\v\"") == arg.npos) { commandline += arg; } else { commandline += '"'; for (auto it = arg.begin(); ; ++it) { unsigned num_back_slashes = 0; while (it != arg.end() && *it == '\\') { ++it; ++num_back_slashes; } if (it == arg.end()) { // Escape all backslashes, but let the terminating double quotation mark we add below be // interpreted as a metacharacter. commandline.append(num_back_slashes * 2, '\\'); break; } else if (*it == '"') { // Escape all backslashes and the following double quotation mark. commandline.append(num_back_slashes * 2 + 1, '\\'); commandline.push_back(*it); } else { // Backslashes aren't special here. commandline.append(num_back_slashes, '\\'); commandline.push_back(*it); } } commandline += '"'; } commandline += ' '; } // Strip the trailing space. boost::trim_right(commandline); return commandline; } // Represents information about a pipe struct pipe { // cppcheck-suppress passedByValue pipe(string pipe_name, scoped_handle pipe_handle, function<bool(string const&)> cb) : name(move(pipe_name)), handle(move(pipe_handle)), overlapped{}, pending(false), read(true), callback(move(cb)) { init(); } // cppcheck-suppress passedByValue pipe(string pipe_name, scoped_handle pipe_handle, string buf) : name(move(pipe_name)), handle(move(pipe_handle)), overlapped{}, pending(false), read(false), buffer(move(buf)) { init(); } const string name; scoped_handle handle; OVERLAPPED overlapped; scoped_handle event; bool pending; bool read; string buffer; function<bool(string const&)> callback; private: void init() { if (handle != INVALID_HANDLE_VALUE) { event = scoped_handle(CreateEvent(nullptr, TRUE, FALSE, nullptr)); if (!event) { LOG_ERROR("failed to create {1} read event: {2}.", name, windows::system_error()); throw execution_exception(_("failed to create read event.")); } overlapped.hEvent = event; } } }; static void rw_from_child(DWORD child, array<pipe, 3>& pipes, uint32_t timeout, HANDLE timer, bool convert_newlines) { vector<HANDLE> wait_handles; while (true) { // Process all pipes for (auto& pipe : pipes) { // If the handle is closed or is pending, skip if (pipe.handle == INVALID_HANDLE_VALUE || pipe.pending) { continue; } // Process the pipe until pending while (true) { // Before doing anything, check to see if there's been a timeout // This is done pre-emptively in case ReadFile never returns ERROR_IO_PENDING if (timeout && WaitForSingleObject(timer, 0) == WAIT_OBJECT_0) { throw timeout_exception(_("command timed out after {1} seconds.", timeout), static_cast<size_t>(child)); } if (pipe.read) { // Read the data pipe.buffer.resize(4096); } DWORD count = 0; auto success = pipe.read ? ReadFile(pipe.handle, &pipe.buffer[0], pipe.buffer.size(), &count, &pipe.overlapped) : WriteFile(pipe.handle, pipe.buffer.c_str(), pipe.buffer.size(), &count, &pipe.overlapped); if (!success) { // Treat broken pipes as closed pipes if (GetLastError() == ERROR_BROKEN_PIPE) { pipe.handle = {}; break; } // Check to see if it's a pending operation if (GetLastError() == ERROR_IO_PENDING) { pipe.pending = true; break; } LOG_ERROR("{1} pipe i/o failed: {2}.", pipe.name, windows::system_error()); throw execution_exception(_("child i/o failed.")); } // Check for closed pipe if (count == 0) { pipe.handle = {}; break; } if (pipe.read) { // Read completed immediately, process the data pipe.buffer.resize(count); if (convert_newlines) { pipe.buffer.erase( std::remove(pipe.buffer.begin(), pipe.buffer.end(), '\r'), pipe.buffer.end()); } if (!pipe.callback(pipe.buffer)) { // Callback signaled that we're done return; } } else { // Register written data pipe.buffer.erase(0, count); } } } // All pipes should be pending now wait_handles.clear(); for (auto const& pipe : pipes) { if (pipe.handle == INVALID_HANDLE_VALUE || !pipe.pending) { continue; } wait_handles.push_back(pipe.event); } // If no wait handles, then we're done processing if (wait_handles.empty()) { return; } if (timeout) { wait_handles.push_back(timer); } // Wait for data (and, optionally, timeout) auto result = WaitForMultipleObjects(wait_handles.size(), wait_handles.data(), FALSE, INFINITE); if (result >= (WAIT_OBJECT_0 + wait_handles.size())) { LOG_ERROR("failed to wait for child process i/o: {1}.", windows::system_error()); throw execution_exception(_("failed to wait for child process i/o.")); } // Check for timeout DWORD index = result - WAIT_OBJECT_0; if (timeout && wait_handles[index] == timer) { throw timeout_exception(_("command timed out after {1} seconds.", timeout), static_cast<size_t>(child)); } // Find the pipe for the event that was signalled for (auto& pipe : pipes) { if (pipe.handle == INVALID_HANDLE_VALUE || !pipe.pending || pipe.event != wait_handles[index]) { continue; } // Pipe is no longer pending pipe.pending = false; // Get the overlapped result and process it DWORD count = 0; if (!GetOverlappedResult(pipe.handle, &pipe.overlapped, &count, FALSE)) { if (GetLastError() != ERROR_BROKEN_PIPE) { LOG_ERROR("asynchronous i/o on {1} failed: {2}.", pipe.name, windows::system_error()); throw execution_exception(_("asynchronous i/o failed.")); } // Treat a broken pipe as nothing left to read count = 0; } // Check for closed pipe if (count == 0) { pipe.handle = {}; break; } if (pipe.read) { // Read completed, process the data pipe.buffer.resize(count); if (convert_newlines) { pipe.buffer.erase( std::remove(pipe.buffer.begin(), pipe.buffer.end(), '\r'), pipe.buffer.end()); } if (!pipe.callback(pipe.buffer)) { // Callback signaled that we're done return; } } else { // Register written data pipe.buffer.erase(0, count); } break; } } } result execute( string const& file, vector<string> const* arguments, string const* input, map<string, string> const* environment, function<void(size_t)> const& pid_callback, function<bool(string&)> const& stdout_callback, function<bool(string&)> const& stderr_callback, option_set<execution_options> const& options, uint32_t timeout) { // Since we use a job object in the windows world, we want to // be sure we're not in a job object, or at least able to // break our processes out if we are in one. BOOL in_job; bool use_job_object = true; if (!IsProcessInJob(GetCurrentProcess(), nullptr, &in_job)) { throw execution_exception(_("could not determine if the parent process is running in a job object")); } if (in_job) { JOBOBJECT_BASIC_LIMIT_INFORMATION limits; if (!QueryInformationJobObject(nullptr, JobObjectBasicLimitInformation, &limits, sizeof(limits), nullptr) || !(limits.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)) { // short-circuits if QueryInformationJobObject fails use_job_object = false; } } // Search for the executable string executable = which(file); log_execution(executable.empty() ? file : executable, arguments); if (executable.empty()) { LOG_DEBUG("{1} was not found on the PATH.", file); if (options[execution_options::throw_on_nonzero_exit]) { throw child_exit_exception(_("child process returned non-zero exit status."), 127, {}, {}); } return {false, "", "", 127, 0}; } // Setup the execution environment vector<wchar_t> modified_environ; vector<scoped_env> scoped_environ; if (options[execution_options::merge_environment]) { // Modify the existing environment, then restore it after. There's no way to modify environment variables // after the child has started. An alternative would be to use GetEnvironmentStrings and add/modify the block, // but searching for and modifying existing environment strings to update would be cumbersome in that form. // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms682009(v=vs.85).aspx if (!options[execution_options::inherit_locale]) { // Unless inherit_locale is specified, override with a C locale to ensure consistent behavior from // command-line tools. if (!environment || environment->count("LC_ALL") == 0) { scoped_environ.emplace_back("LC_ALL", "C"); } if (!environment || environment->count("LANG") == 0) { scoped_environ.emplace_back("LANG", "C"); } } if (environment) { for (auto const& kv : *environment) { // Use scoped_env to save the old state and restore it on return. LOG_DEBUG("child environment {1}={2}", kv.first, kv.second); scoped_environ.emplace_back(kv.first, kv.second); } } } else { // We aren't inheriting the environment, so create an environment block instead of changing existing env. // Environment variables must be sorted alphabetically and case-insensitive, // so copy them all into the same map with case-insensitive key compare: // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682009(v=vs.85).aspx map<string, string, bool(*)(string const&, string const&)> sortedEnvironment( [](string const& a, string const& b) { return ilexicographical_compare(a, b); }); if (environment) { sortedEnvironment.insert(environment->begin(), environment->end()); } // Insert LANG and LC_ALL if they aren't already present. Emplace ensures this behavior. string locale_env; if (options[execution_options::inherit_locale] && environment::get("LC_ALL", locale_env)) { sortedEnvironment.emplace("LC_ALL", locale_env); } else if (!options[execution_options::inherit_locale]) { sortedEnvironment.emplace("LC_ALL", "C"); } if (options[execution_options::inherit_locale] && environment::get("LANG", locale_env)) { sortedEnvironment.emplace("LANG", locale_env); } else if (!options[execution_options::inherit_locale]) { sortedEnvironment.emplace("LANG", "C"); } // An environment block is a NULL-terminated list of NULL-terminated strings. for (auto const& variable : sortedEnvironment) { LOG_DEBUG("child environment {1}={2}", variable.first, variable.second); string var = variable.first + "=" + variable.second; for (auto c : boost::nowide::widen(var)) { modified_environ.push_back(c); } modified_environ.push_back(L'\0'); } modified_environ.push_back(L'\0'); if (sortedEnvironment.empty()) { // The environment block is terminated by two nulls, so if the environment is // empty add a second one. modified_environ.push_back(L'\0'); } } // Execute the command, reading the results into a buffer until there's no more to read. // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx // for details on redirecting input/output. scoped_handle stdInRd, stdInWr; tie(stdInRd, stdInWr) = CreatePipeThrow(); if (!SetHandleInformation(stdInWr, HANDLE_FLAG_INHERIT, 0)) { throw execution_exception(_("pipe could not be modified")); } scoped_handle stdOutRd, stdOutWr; tie(stdOutRd, stdOutWr) = CreatePipeThrow(); if (!SetHandleInformation(stdOutRd, HANDLE_FLAG_INHERIT, 0)) { throw execution_exception(_("pipe could not be modified")); } scoped_handle stdErrRd, stdErrWr; if (!options[execution_options::redirect_stderr_to_stdout]) { // If redirecting to null, open the "NUL" device and inherit the handle if (options[execution_options::redirect_stderr_to_null]) { SECURITY_ATTRIBUTES attributes = {}; attributes.nLength = sizeof(SECURITY_ATTRIBUTES); attributes.bInheritHandle = TRUE; stdErrWr = scoped_handle(CreateFileW(L"nul", GENERIC_WRITE, FILE_SHARE_WRITE, &attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (stdErrWr == INVALID_HANDLE_VALUE) { throw execution_exception(_("cannot open NUL device for redirecting stderr.")); } } else { // Otherwise, we're reading from stderr, so create a pipe tie(stdErrRd, stdErrWr) = CreatePipeThrow(); if (!SetHandleInformation(stdErrRd, HANDLE_FLAG_INHERIT, 0)) { throw execution_exception(_("pipe could not be modified")); } } } // Execute the command with arguments. Prefix arguments with the executable, or quoted arguments won't work. auto commandLine = arguments ? boost::nowide::widen(ArgvToCommandLine({ executable }) + " " + ArgvToCommandLine(*arguments, options[execution_options::preserve_arguments])) : L""; STARTUPINFO startupInfo = {}; startupInfo.cb = sizeof(startupInfo); startupInfo.dwFlags |= STARTF_USESTDHANDLES; startupInfo.hStdInput = stdInRd; startupInfo.hStdOutput = stdOutWr; // Set up stderr redirection to out or the pipe (which may be INVALID_HANDLE_VALUE, i.e. "null") if (options[execution_options::redirect_stderr_to_stdout]) { startupInfo.hStdError = stdOutWr; } else { startupInfo.hStdError = stdErrWr; } PROCESS_INFORMATION procInfo = {}; // Set up flags for CreateProcess based on whether the create_detached_process // option was set and the parent process is running in a Job object. auto creation_flags = CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; if (use_job_object) { creation_flags |= CREATE_BREAKAWAY_FROM_JOB; } if (options[execution_options::create_detached_process]) { creation_flags |= CREATE_NEW_PROCESS_GROUP; } if (!CreateProcessW( boost::nowide::widen(executable).c_str(), &commandLine[0], /* Pass a modifiable string buffer; the contents may be modified */ NULL, /* Don't allow child process to inherit process handle */ NULL, /* Don't allow child process to inherit thread handle */ TRUE, /* Inherit handles from the calling process for communication */ creation_flags, options[execution_options::merge_environment] ? NULL : modified_environ.data(), NULL, /* Use existing current directory */ &startupInfo, /* STARTUPINFO for child process */ &procInfo)) { /* PROCESS_INFORMATION pointer for output */ LOG_ERROR("failed to create process: {1}.", windows::system_error()); throw execution_exception(_("failed to create child process.")); } // Release unused pipes, to avoid any races in process completion. if (!input) { stdInWr.release(); } stdInRd.release(); stdOutWr.release(); stdErrWr.release(); scoped_handle hProcess(procInfo.hProcess); scoped_handle hThread(procInfo.hThread); // Use a Job Object to group any child processes spawned by the CreateProcess invocation, so we can // easily stop them in case of a timeout. bool create_job_object = use_job_object && !options[execution_options::create_detached_process]; scoped_handle hJob; if (create_job_object) { hJob = scoped_handle(CreateJobObjectW(nullptr, nullptr)); if (hJob == NULL) { LOG_ERROR("failed to create job object: {1}.", windows::system_error()); throw execution_exception(_("failed to create job object.")); } else if (!AssignProcessToJobObject(hJob, hProcess)) { LOG_ERROR("failed to associate process with job object: {1}.", windows::system_error()); throw execution_exception(_("failed to associate process with job object.")); } } bool terminate = true; scope_exit reaper([&]() { if (terminate) { // Terminate the process on an exception if (create_job_object) { if (!TerminateJobObject(hJob, -1)) { LOG_ERROR("failed to terminate process: {1}.", windows::system_error()); } } else { LOG_WARNING("could not terminate process {1} because a job object could not be used.", procInfo.dwProcessId); } } }); // Create a waitable timer if given a timeout scoped_handle timer; if (timeout) { timer = scoped_handle(CreateWaitableTimer(nullptr, TRUE, nullptr)); if (!timer) { LOG_ERROR("failed to create waitable timer: {1}.", windows::system_error()); throw execution_exception(_("failed to create waitable timer.")); } // "timeout" in X intervals in the future (1 interval = 100 ns) // The negative value indicates relative to the current time LARGE_INTEGER future; future.QuadPart = timeout * -10000000ll; if (!SetWaitableTimer(timer, &future, 0, nullptr, nullptr, FALSE)) { LOG_ERROR("failed to set waitable timer: {1}.", windows::system_error()); throw execution_exception(_("failed to set waitable timer.")); } } // Execute the PID callback if (pid_callback) { pid_callback(procInfo.dwProcessId); } string output, error; tie(output, error) = process_streams(options[execution_options::trim_output], stdout_callback, stderr_callback, [&](function<bool(string const&)> const& process_stdout, function<bool(string const&)> const& process_stderr) { // Read the child output array<pipe, 3> pipes = { { input ? pipe("stdin", move(stdInWr), *input) : pipe("stdin", {}, ""), pipe("stdout", move(stdOutRd), process_stdout), pipe("stderr", move(stdErrRd), process_stderr) } }; rw_from_child(procInfo.dwProcessId, pipes, timeout, timer, options[execution_options::convert_newlines]); }); HANDLE handles[2] = { hProcess, timer }; auto wait_result = WaitForMultipleObjects(timeout ? 2 : 1, handles, FALSE, INFINITE); if (wait_result == WAIT_OBJECT_0) { // Process has terminated terminate = false; } else if (wait_result == WAIT_OBJECT_0 + 1) { // Timeout while waiting on the process to complete throw timeout_exception(_("command timed out after {1} seconds.", timeout), static_cast<size_t>(procInfo.dwProcessId)); } else { LOG_ERROR("failed to wait for child process to terminate: {1}.", windows::system_error()); throw execution_exception(_("failed to wait for child process to terminate.")); } // Now check the process return status. DWORD exit_code; if (!GetExitCodeProcess(hProcess, &exit_code)) { throw execution_exception(_("error retrieving exit code of completed process")); } LOG_DEBUG("process exited with exit code {1}.", exit_code); if (exit_code != 0 && options[execution_options::throw_on_nonzero_exit]) { throw child_exit_exception(_("child process returned non-zero exit status."), exit_code, output, error); } return {exit_code == 0, move(output), move(error), static_cast<int>(exit_code), static_cast<size_t>(procInfo.dwProcessId)}; } }} // namespace leatherman::execution
43.606534
231
0.55764
[ "object", "vector" ]
a98a7c78338149bb8066f7ac9fc3ed34bebb1f45
13,707
hpp
C++
src/xapp-asn/e2ap/e2ap_subscription_request.hpp
zeinabshahbazi2020/hwx
308a28051f95dd66fba5ee09565f46eb821e605b
[ "Apache-2.0" ]
2
2020-10-14T00:21:43.000Z
2021-07-19T21:33:21.000Z
src/xapp-asn/e2ap/e2ap_subscription_request.hpp
zeinabshahbazi2020/hwx
308a28051f95dd66fba5ee09565f46eb821e605b
[ "Apache-2.0" ]
null
null
null
src/xapp-asn/e2ap/e2ap_subscription_request.hpp
zeinabshahbazi2020/hwx
308a28051f95dd66fba5ee09565f46eb821e605b
[ "Apache-2.0" ]
5
2021-07-07T06:42:49.000Z
2022-02-14T23:33:26.000Z
/* ================================================================================== Copyright (c) 2019-2020 AT&T Intellectual Property. 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. ================================================================================== */ /* * e2ap_subscription_request.hpp * * Created on: Jun 30, 2020 * Author: Shraboni Jana */ #ifndef XAPP_ASN_REFACTOR_E2AP_SUBSCRIPTION_HPP_ #define XAPP_ASN_REFACTOR_E2AP_SUBSCRIPTION_HPP_ #include <E2AP-PDU.h> #include <InitiatingMessage.h> #include <ProtocolIE-Field.h> #include <RICsubscriptionRequest.h> #include <ProtocolIE-SingleContainer.h> #include <RICactions-ToBeSetup-List.h> #include <RICsubsequentAction.h> #include <vector> #include "e2ap_action.hpp" /* RICsubscriptionRequest-IEs E2AP-PROTOCOL-IES ::= { { ID id-RICrequestID CRITICALITY reject TYPE RICrequestID PRESENCE mandatory}| { ID id-RANfunctionID CRITICALITY reject TYPE RANfunctionID PRESENCE mandatory}| { ID id-RICsubscriptionDetails CRITICALITY reject TYPE RICsubscriptionDetails PRESENCE mandatory}, ... } RICrequestID ::= SEQUENCE { ricRequestorID INTEGER (0..65535), ricInstanceID INTEGER (0..65535), ... } RICsubscriptionDetails ::= SEQUENCE { ricEventTriggerDefinition RICeventTriggerDefinition, ricAction-ToBeSetup-List RICactions-ToBeSetup-List, ... } */ template <typename E2SMEventTriggerDefinition, typename E2SMActionDefinition> class E2APSubscriptionRequest { public: class SubscriptionRequestIEs{ private: long int ricRequestorID, ricInstanceID, ranFunctionID; size_t ricEventTriggerDefinition_size = IE_SIZE; unsigned char ricEventTriggerDefinition[IE_SIZE]; int ricAction_ToBeSetup_List_Count; std::vector<typename E2APAction<E2SMActionDefinition>::ActionIEs> *ricAction_ToBeSetup_List; public: SubscriptionRequestIEs(void):ricRequestorID(0), ricInstanceID(0), ranFunctionID(0), ricAction_ToBeSetup_List(0), ricAction_ToBeSetup_List_Count(0){}; SubscriptionRequestIEs& set_ricRequestorID(long int req_id){ricRequestorID = req_id; return *this;}; SubscriptionRequestIEs& set_ricInstanceID(long int inst_id){ricInstanceID = inst_id; return *this;}; SubscriptionRequestIEs& set_ranFunctionID(long int func_id){ranFunctionID = func_id; return *this;}; SubscriptionRequestIEs& set_ricEventTriggerDefinition(E2SMEventTriggerDefinition &eventObj) { bool res = eventObj.encode(&(this->ricEventTriggerDefinition)[0],&ricEventTriggerDefinition_size); if(!res){ mdclog_write(MDCLOG_ERR, "Failed to encode: %s","RIC Event Trigger Definition"); mdclog_write(MDCLOG_ERR, "Error during encode: %s",eventObj.get_error()); } else { mdclog_write(MDCLOG_INFO, "Successfully encoded: %s of size: %d","RIC Event Trigger Definition",ricEventTriggerDefinition_size); } return *this; }; SubscriptionRequestIEs& set_ricAction_ToBeSetup_List(E2APAction<E2SMActionDefinition> &actionObj) { ricAction_ToBeSetup_List = actionObj.get_list(); ricAction_ToBeSetup_List_Count = actionObj.get_list_count(); return *this; }; long int get_ricRequestorID(){return this->ricRequestorID;}; long int get_ricInstanceID(){return this->ricInstanceID;}; long int get_ranFunctionID(){return this->ranFunctionID;}; unsigned char* get_ricEventTriggerDefinition(){return this->ricEventTriggerDefinition;}; size_t get_ricEventTriggerDefinitionSize(){return this->ricEventTriggerDefinition_size;}; std::vector<typename E2APAction<E2SMActionDefinition>::ActionIEs>* get_ricAction_ToBeSetup_List(){ return this->ricAction_ToBeSetup_List;}; int get_ricAction_ToBeSetup_List_Count(){return this->ricAction_ToBeSetup_List_Count;}; }; E2APSubscriptionRequest(SubscriptionRequestIEs&); ~E2APSubscriptionRequest(); bool encode(unsigned char *, size_t * ); std::string get_error (void) const {return _error_string ;}; void add(SubscriptionRequestIEs &ies){_requestIEs = ies;}; SubscriptionRequestIEs& getIEs(){ return *_requestIEs.get();}; private: InitiatingMessage_t *initMsg; E2AP_PDU_t * e2ap_pdu_obj; RICsubscriptionRequest_IEs_t * IE_array; RICaction_ToBeSetup_ItemIEs_t * action_array; unsigned int action_array_size; std::unique_ptr<SubscriptionRequestIEs> _requestIEs; std::string _error_string; char _errbuf[128]; size_t _errbuf_len = 128; bool setfields(InitiatingMessage_t *); }; template <typename T1,typename T2> E2APSubscriptionRequest<T1,T2>::E2APSubscriptionRequest(SubscriptionRequestIEs &subRequestObj){ _requestIEs = std::make_unique<SubscriptionRequestIEs>(); *_requestIEs = subRequestObj; e2ap_pdu_obj = 0; e2ap_pdu_obj = (E2AP_PDU_t * )calloc(1, sizeof(E2AP_PDU_t)); assert(e2ap_pdu_obj != 0); initMsg = 0; initMsg = (InitiatingMessage_t * )calloc(1, sizeof(InitiatingMessage_t)); assert(initMsg != 0); IE_array = 0; if(RIC_SUB_REQUEST_IES_COUNT == 0) { mdclog_write(MDCLOG_ERR, "E2AP Subscription Request IEs = 0."); } IE_array = (RICsubscriptionRequest_IEs_t *)calloc(RIC_SUB_REQUEST_IES_COUNT, sizeof(RICsubscriptionRequest_IEs_t)); assert(IE_array != 0); action_array_size = subRequestObj.get_ricAction_ToBeSetup_List_Count(); action_array = 0; action_array = (RICaction_ToBeSetup_ItemIEs_t *)calloc(action_array_size, sizeof(RICaction_ToBeSetup_ItemIEs_t)); assert(action_array != 0); e2ap_pdu_obj->choice.initiatingMessage = initMsg; e2ap_pdu_obj->present = E2AP_PDU_PR_initiatingMessage; }; // Clear assigned protocolIE list from RIC indication IE container template <typename T1, typename T2> E2APSubscriptionRequest<T1,T2>::~E2APSubscriptionRequest(void){ mdclog_write(MDCLOG_DEBUG, "Freeing subscription request memory");; RICsubscriptionDetails_t * ricsubscription_ie = &(IE_array[2].value.choice.RICsubscriptionDetails); for(int i = 0; i < ricsubscription_ie->ricAction_ToBeSetup_List.list.size; i++){ ricsubscription_ie->ricAction_ToBeSetup_List.list.array[i] = 0; } // clear action list if (ricsubscription_ie->ricAction_ToBeSetup_List.list.size > 0){ free(ricsubscription_ie->ricAction_ToBeSetup_List.list.array); ricsubscription_ie->ricAction_ToBeSetup_List.list.size = 0; ricsubscription_ie->ricAction_ToBeSetup_List.list.count = 0; ricsubscription_ie->ricAction_ToBeSetup_List.list.array = 0; } // clear subsequent action array for (unsigned int i = 0; i < action_array_size; i++){ free(action_array[i].value.choice.RICaction_ToBeSetup_Item.ricSubsequentAction ); } free(action_array); RICsubscriptionRequest_t * subscription_request = &(initMsg->value.choice.RICsubscriptionRequest); for(int i = 0; i < subscription_request->protocolIEs.list.size; i++){ subscription_request->protocolIEs.list.array[i] = 0; } if( subscription_request->protocolIEs.list.size > 0){ free( subscription_request->protocolIEs.list.array); subscription_request->protocolIEs.list.array = 0; subscription_request->protocolIEs.list.size = 0; subscription_request->protocolIEs.list.count = 0; } free(IE_array); free(initMsg); e2ap_pdu_obj->choice.initiatingMessage = 0; ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, e2ap_pdu_obj); mdclog_write(MDCLOG_DEBUG, "Freed subscription request memory "); }; template <typename T1, typename T2> bool E2APSubscriptionRequest<T1,T2>::encode(unsigned char *buf, size_t *size){ bool res; initMsg->procedureCode = ProcedureCode_id_RICsubscription; initMsg->criticality = Criticality_ignore; initMsg->value.present = InitiatingMessage__value_PR_RICsubscriptionRequest; res = setfields(initMsg); if (!res){ return false; } int ret_constr = asn_check_constraints(&asn_DEF_E2AP_PDU, (void *) e2ap_pdu_obj, _errbuf, &_errbuf_len); if(ret_constr){ _error_string.assign(_errbuf, _errbuf_len); _error_string = "Constraints failed for encoding subscription request. Reason = " + _error_string; return false; } asn_enc_rval_t retval = asn_encode_to_buffer(0, ATS_ALIGNED_BASIC_PER, &asn_DEF_E2AP_PDU, e2ap_pdu_obj, buf, *size); if(retval.encoded == -1){ _error_string.assign(strerror(errno)); _error_string = "Error encoding Subscription Request. Reason = " + _error_string; return false; } else { if(*size < retval.encoded){ std::stringstream ss; ss <<"Error encoding Subscription Request . Reason = encoded pdu size " << retval.encoded << " exceeds buffer size " << *size << std::endl; _error_string = ss.str(); retval.encoded = -1; return false; } } *size = retval.encoded; xer_fprint(stdout, &asn_DEF_E2AP_PDU, e2ap_pdu_obj); return true; } template <typename T1, typename T2> bool E2APSubscriptionRequest<T1,T2>::setfields( InitiatingMessage_t * init_msg){ int ie_index; int result = 0; if (init_msg == 0){ _error_string = "Error. Invalid reference when getting fields from subscription request"; return false; } RICsubscriptionRequest_t * ric_subscription = &(init_msg->value.choice.RICsubscriptionRequest); ric_subscription->protocolIEs.list.count = 0; ie_index = 0; RICsubscriptionRequest_IEs_t *ies_ricreq = &IE_array[ie_index]; ies_ricreq->criticality = Criticality_reject; ies_ricreq->id = ProtocolIE_ID_id_RICrequestID; ies_ricreq->value.present = RICsubscriptionRequest_IEs__value_PR_RICrequestID; RICrequestID_t *ricrequest_ie = &ies_ricreq->value.choice.RICrequestID; ricrequest_ie->ricRequestorID = this->getIEs().get_ricRequestorID(); result = ASN_SEQUENCE_ADD(&(ric_subscription->protocolIEs), &IE_array[ie_index]); assert(result == 0); ie_index++; RICsubscriptionRequest_IEs_t *ies_ranfunc = &IE_array[ie_index]; ies_ranfunc->criticality = Criticality_reject; ies_ranfunc->id = ProtocolIE_ID_id_RANfunctionID; ies_ranfunc->value.present = RICsubscriptionRequest_IEs__value_PR_RANfunctionID; RANfunctionID_t *ranfunction_ie = &ies_ranfunc->value.choice.RANfunctionID; *ranfunction_ie = this->getIEs().get_ranFunctionID(); result = ASN_SEQUENCE_ADD(&(ric_subscription->protocolIEs), &IE_array[ie_index]); assert(result == 0); ie_index++; RICsubscriptionRequest_IEs_t *ies_actid = &IE_array[ie_index]; ies_actid->criticality = Criticality_reject; ies_actid->id = ProtocolIE_ID_id_RICsubscriptionDetails; ies_actid->value.present = RICsubscriptionRequest_IEs__value_PR_RICsubscriptionDetails; RICsubscriptionDetails_t *ricsubscription_ie = &ies_actid->value.choice.RICsubscriptionDetails; ricsubscription_ie->ricEventTriggerDefinition.buf = (uint8_t *) this->getIEs().get_ricEventTriggerDefinition(); ricsubscription_ie->ricEventTriggerDefinition.size = this->getIEs().get_ricEventTriggerDefinitionSize(); std::vector<typename E2APAction<T2>::ActionIEs> *ref_action_array = this->getIEs().get_ricAction_ToBeSetup_List(); // reset the list count on ricAction_ToBeSetup_List; ricsubscription_ie->ricAction_ToBeSetup_List.list.count = 0; for(unsigned int i = 0; i < ref_action_array->size(); i ++){ action_array[i].criticality = Criticality_ignore; action_array[i].id = ProtocolIE_ID_id_RICaction_ToBeSetup_Item ; action_array[i].value.present = RICaction_ToBeSetup_ItemIEs__value_PR_RICaction_ToBeSetup_Item; action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionID = (*ref_action_array)[i].get_ricActionID(); action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionType = (*ref_action_array)[i].get_ricActionType(); if((*ref_action_array)[i].get_is_ricSubsequentAction()){ action_array[i].value.choice.RICaction_ToBeSetup_Item.ricSubsequentAction = (RICsubsequentAction_t *)calloc(1, sizeof(RICsubsequentAction_t)); action_array[i].value.choice.RICaction_ToBeSetup_Item.ricSubsequentAction->ricSubsequentActionType = (*ref_action_array)[i].get_ricSubsequentActionType(); action_array[i].value.choice.RICaction_ToBeSetup_Item.ricSubsequentAction->ricTimeToWait = (*ref_action_array)[i].get_ricTimeToWait(); } if((*ref_action_array)[i].get_is_ricActionDefinition()){ action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionDefinition = (RICactionDefinition_t*)calloc(1, sizeof(RICactionDefinition_t)); auto actionSize = (*ref_action_array)[i].get_ricActionDefinition_size(); action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionDefinition->size = actionSize; action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionDefinition->buf = (uint8_t *)calloc(1,actionSize); memcpy(action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionDefinition->buf, (uint8_t*)(*ref_action_array)[i].get_ricActionDefinition(), actionSize); action_array[i].value.choice.RICaction_ToBeSetup_Item.ricActionDefinition->size = actionSize; } result = ASN_SEQUENCE_ADD(&ricsubscription_ie->ricAction_ToBeSetup_List, &(action_array[i])); if (result == -1){ _error_string = "Error : Unable to assign memory to add Action item to set up list"; return false; } } result = ASN_SEQUENCE_ADD(&(ric_subscription->protocolIEs), &IE_array[ie_index]); assert(result == 0); return true; }; #endif /* XAPP_ASN_REFACTOR_E2AP_SUBSCRIPTION_HPP_ */
38.830028
164
0.758518
[ "vector" ]
a98e14074be268ff9e4d24847d8ea06aed468aeb
3,821
cpp
C++
src/Scene/Scene.cpp
moneil113/RayTrace
0fd1264b6da395c038b1235485b210c0d8d4655f
[ "MIT" ]
null
null
null
src/Scene/Scene.cpp
moneil113/RayTrace
0fd1264b6da395c038b1235485b210c0d8d4655f
[ "MIT" ]
null
null
null
src/Scene/Scene.cpp
moneil113/RayTrace
0fd1264b6da395c038b1235485b210c0d8d4655f
[ "MIT" ]
null
null
null
#include <iostream> #include "Scene.h" #include "Ray.h" #define EPSILON 0.001f using namespace std; Scene::Scene() : renderer(this) { } void Scene::print() { cout << camera.to_string(); cout << "\n---\n\n"; cout << lights.size() << " light(s)\n"; for (size_t i = 0; i < lights.size(); i++) { cout << "\n"; cout << "Light[" << i << "]:\n"; cout << lights.at(i).to_string(); } cout << "\n---\n\n"; cout << geometry.size() << " object(s)\n"; for (size_t i = 0; i < geometry.size(); i++) { cout << "\n"; cout << "Object[" << i << "]:\n"; cout << geometry.at(i)->to_string(); } } void Scene::setCamera(Camera newCam) { camera = newCam; } void Scene::setImageSize(const int width, const int height) { camera.setImageSize(width, height); renderer.setImageSize(width, height); } void Scene::setBRDF(const int type) { renderer.setBRDF(type); } void Scene::setSuperSamples(const int n) { renderer.setSuperSamples(n); } void Scene::setFresnel() { renderer.setFresnel(); } void Scene::useSDS() { rootNode = make_shared<BVHNode>(); rootNode->build(geometry); } void Scene::useGlobalIllumination() { renderer.useGlobalIllumination(); } void Scene::setGISamples(const int n) { renderer.setGISamples(n); } void Scene::setGIBounces(const int n) { renderer.setGIBounces(n); } void Scene::setGIRatio(const int n) { renderer.setGIRatio(n); } void Scene::setNumThreads(const int n) { renderer.setNumThreads(n); } void Scene::addLight(Light l) { lights.push_back(l); } void Scene::addGeometry(std::shared_ptr<Geometry> g) { geometry.push_back(g); } std::shared_ptr<Geometry> Scene::firstHitVector(const Ray &r, floatOptional &t) { t = {false, INFINITY}; floatOptional temp; shared_ptr<Geometry> objectHit; for (int i = 0; i < geometry.size(); i++) { temp = geometry[i]->intersect(r); if (temp.valid && temp.value > 0.001f && temp.value < t.value) { t = temp; objectHit = geometry[i]; } } if (t.valid) { return objectHit; } else { return NULL; } } std::shared_ptr<Geometry> Scene::firstHitBVH(const Ray &r, floatOptional &t) { return rootNode->firstHit(r, t); } std::shared_ptr<Geometry> Scene::firstHit(Ray r, floatOptional &t) { if (rootNode) { return firstHitBVH(r, t); } else { return firstHitVector(r, t); } } void Scene::render(std::string outputFile) { renderer.renderScene(outputFile); } void Scene::pixelTest(int x, int y) { cout << "Pixel: [" << x << ", " << y << "] "; cout << "Ray: " << camera.rayToPixel(x, y).to_string() << '\n'; } void Scene::firstHitTest(int x, int y) { pixelTest(x, y); floatOptional t; Ray r = camera.rayToPixel(x, y); std::shared_ptr<Geometry> objectHit = firstHit(r, t); if (t.valid) { cout << setprecision(4); cout << "T = " << t.value << "\n"; cout << "Object Type: " << objectHit->type() << '\n'; Eigen::Vector3f color = objectHit->color(); cout << "Color: "; cout << color.x() << " " << color.y() << " " << color.z() << "\n"; } else { cout << "No Hit" << '\n'; } } void Scene::pixelColorTest(int x, int y) { pixelTest(x, y); floatOptional t; Ray r = camera.rayToPixel(x, y); std::shared_ptr<Geometry> objectHit = firstHit(r, t); if (t.valid) { cout << setprecision(4); cout << "T = " << t.value << "\n"; cout << "Object Type: " << objectHit->type() << '\n'; renderer.pixelColorTest(x, y); } else { cout << "No Hit" << '\n'; } } void Scene::printRaysTest(int x, int y) { renderer.printRaysTest(x, y); }
21.227778
81
0.563465
[ "geometry", "render", "object" ]
8178e47d893dd9ab413fd1b990162db8ba061a10
24,143
cpp
C++
copasi/sbml/unittests/test000095.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/sbml/unittests/test000095.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/sbml/unittests/test000095.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "test000095.h" #include <sstream> #include "utilities.hpp" #include "copasi/CopasiDataModel/CDataModel.h" #include "copasi/model/CModel.h" #include "copasi/model/CModelValue.h" #include "copasi/model/CEvent.h" #include "sbml/math/ASTNode.h" #include "sbml/SBMLDocument.h" #include "sbml/Model.h" #include "sbml/Compartment.h" #include "sbml/Parameter.h" #include "sbml/Event.h" #include "sbml/Trigger.h" #include "sbml/Delay.h" #include "sbml/EventAssignment.h" #include "copasi/core/CRootContainer.h" CDataModel* test000095::pCOPASIDATAMODEL = NULL; void test000095::setUp() { // Create the root container. CRootContainer::init(0, NULL, false); // Create the global data model. pCOPASIDATAMODEL = CRootContainer::addDatamodel(); } void test000095::tearDown() { CRootContainer::destroy(); } void test000095::test_import_l3_event_1() { CDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING1)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getCompartments().size() == 0); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 0); CPPUNIT_ASSERT(pModel->getModelValues().size() == 1); const CModelValue* pModelValue = pModel->getModelValues()[0]; CPPUNIT_ASSERT(pModelValue != NULL); CPPUNIT_ASSERT(pModel->getEvents().size() == 1); const CEvent* pEvent = pModel->getEvents()[0]; CPPUNIT_ASSERT(pEvent != NULL); // check the trigger expression const CExpression* pExpr = pEvent->getTriggerExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::LOGICAL); CPPUNIT_ASSERT(pNode->subType() == CEvaluationNode::SubType::GT); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::OBJECT); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCommonName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); CObjectInterface::ContainerList listOfContainers; listOfContainers.push_back(pModel); const CDataObject* pObject = CObjectInterface::DataModel(pCOPASIDATAMODEL->getObjectFromCN(listOfContainers, objectCN)); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->hasFlag(CDataObject::Reference) == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Time")); CPPUNIT_ASSERT(pObject->getObjectParent() == pModel); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getSibling()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 2.0) / 2.0) < 1e-6); // check that there is a delay CPPUNIT_ASSERT(pEvent->getAssignments().size() == 1); // check the event assignment std::string key = pEvent->getAssignments()[0]->getTargetKey(); CPPUNIT_ASSERT(key == pModelValue->getKey()); pExpr = pEvent->getAssignments()[0]->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT((fabs(pNumberNode->getValue() - 8.0) / 8.0) < 1e-9); // check that the message stack contains a warning about event priorities // MCSBML + 98 CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 97) == false); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 98) == true); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 99) == false); } void test000095::test_import_l3_event_2() { CDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING2)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getCompartments().size() == 0); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 0); CPPUNIT_ASSERT(pModel->getModelValues().size() == 1); const CModelValue* pModelValue = pModel->getModelValues()[0]; CPPUNIT_ASSERT(pModelValue != NULL); CPPUNIT_ASSERT(pModel->getEvents().size() == 1); const CEvent* pEvent = pModel->getEvents()[0]; CPPUNIT_ASSERT(pEvent != NULL); // check the trigger expression const CExpression* pExpr = pEvent->getTriggerExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::LOGICAL); CPPUNIT_ASSERT(pNode->subType() == CEvaluationNode::SubType::GT); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::OBJECT); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCommonName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); CObjectInterface::ContainerList listOfContainers; listOfContainers.push_back(pModel); const CDataObject* pObject = CObjectInterface::DataModel(pCOPASIDATAMODEL->getObjectFromCN(listOfContainers, objectCN)); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->hasFlag(CDataObject::Reference) == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Time")); CPPUNIT_ASSERT(pObject->getObjectParent() == pModel); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getSibling()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 2.0) / 2.0) < 1e-6); // check that there is a delay CPPUNIT_ASSERT(pEvent->getAssignments().size() == 1); // check the event assignment std::string key = pEvent->getAssignments()[0]->getTargetKey(); CPPUNIT_ASSERT(key == pModelValue->getKey()); pExpr = pEvent->getAssignments()[0]->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT((fabs(pNumberNode->getValue() - 8.0) / 8.0) < 1e-9); // check that the message stack contains a warning about initial values for triggers // MCSBML + 97 CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 97) == true); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 98) == false); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 99) == false); } void test000095::test_import_l3_event_3() { CDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING3)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getCompartments().size() == 0); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 0); CPPUNIT_ASSERT(pModel->getModelValues().size() == 1); const CModelValue* pModelValue = pModel->getModelValues()[0]; CPPUNIT_ASSERT(pModelValue != NULL); CPPUNIT_ASSERT(pModel->getEvents().size() == 1); const CEvent* pEvent = pModel->getEvents()[0]; CPPUNIT_ASSERT(pEvent != NULL); // check the trigger expression const CExpression* pExpr = pEvent->getTriggerExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::LOGICAL); CPPUNIT_ASSERT(pNode->subType() == CEvaluationNode::SubType::GT); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::OBJECT); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCommonName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); CObjectInterface::ContainerList listOfContainers; listOfContainers.push_back(pModel); const CDataObject* pObject = CObjectInterface::DataModel(pCOPASIDATAMODEL->getObjectFromCN(listOfContainers, objectCN)); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->hasFlag(CDataObject::Reference) == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Time")); CPPUNIT_ASSERT(pObject->getObjectParent() == pModel); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getSibling()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 2.0) / 2.0) < 1e-6); // check that there is a delay CPPUNIT_ASSERT(pEvent->getAssignments().size() == 1); // check the event assignment std::string key = pEvent->getAssignments()[0]->getTargetKey(); CPPUNIT_ASSERT(key == pModelValue->getKey()); pExpr = pEvent->getAssignments()[0]->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT((fabs(pNumberNode->getValue() - 8.0) / 8.0) < 1e-9); // check that the message stack contains a warning about event priorities // MCSBML + 98 // check that the message stack contains a warning about initial values for triggers // MCSBML + 97 CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 97) == true); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 98) == true); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 99) == false); } void test000095::test_import_l3_event_4() { CDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING4)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getCompartments().size() == 0); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 0); CPPUNIT_ASSERT(pModel->getModelValues().size() == 1); const CModelValue* pModelValue = pModel->getModelValues()[0]; CPPUNIT_ASSERT(pModelValue != NULL); CPPUNIT_ASSERT(pModel->getEvents().size() == 1); const CEvent* pEvent = pModel->getEvents()[0]; CPPUNIT_ASSERT(pEvent != NULL); // check the trigger expression const CExpression* pExpr = pEvent->getTriggerExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::LOGICAL); CPPUNIT_ASSERT(pNode->subType() == CEvaluationNode::SubType::GT); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::OBJECT); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCommonName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); CObjectInterface::ContainerList listOfContainers; listOfContainers.push_back(pModel); const CDataObject* pObject = CObjectInterface::DataModel(pCOPASIDATAMODEL->getObjectFromCN(listOfContainers, objectCN)); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->hasFlag(CDataObject::Reference) == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Time")); CPPUNIT_ASSERT(pObject->getObjectParent() == pModel); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getSibling()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 2.0) / 2.0) < 1e-6); // check that there is a delay CPPUNIT_ASSERT(pEvent->getAssignments().size() == 1); // check the event assignment std::string key = pEvent->getAssignments()[0]->getTargetKey(); CPPUNIT_ASSERT(key == pModelValue->getKey()); pExpr = pEvent->getAssignments()[0]->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT((fabs(pNumberNode->getValue() - 8.0) / 8.0) < 1e-9); // check that the message stack contains a warning about non-persistent triggers // MCSBML + 99 CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 97) == false); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 98) == false); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 99) == true); } void test000095::test_import_l3_event_5() { CDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING5)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getCompartments().size() == 0); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 0); CPPUNIT_ASSERT(pModel->getModelValues().size() == 1); const CModelValue* pModelValue = pModel->getModelValues()[0]; CPPUNIT_ASSERT(pModelValue != NULL); CPPUNIT_ASSERT(pModel->getEvents().size() == 1); const CEvent* pEvent = pModel->getEvents()[0]; CPPUNIT_ASSERT(pEvent != NULL); // check the trigger expression const CExpression* pExpr = pEvent->getTriggerExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::LOGICAL); CPPUNIT_ASSERT(pNode->subType() == CEvaluationNode::SubType::GT); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::OBJECT); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCommonName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); CObjectInterface::ContainerList listOfContainers; listOfContainers.push_back(pModel); const CDataObject* pObject = CObjectInterface::DataModel(pCOPASIDATAMODEL->getObjectFromCN(listOfContainers, objectCN)); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->hasFlag(CDataObject::Reference) == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Time")); CPPUNIT_ASSERT(pObject->getObjectParent() == pModel); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getSibling()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 2.0) / 2.0) < 1e-6); // check that there is a delay CPPUNIT_ASSERT(pEvent->getAssignments().size() == 1); // check the event assignment std::string key = pEvent->getAssignments()[0]->getTargetKey(); CPPUNIT_ASSERT(key == pModelValue->getKey()); pExpr = pEvent->getAssignments()[0]->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(pNode->mainType() == CEvaluationNode::MainType::NUMBER); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pNode); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT((fabs(pNumberNode->getValue() - 8.0) / 8.0) < 1e-9); // check that there is no MCSBML + 97, MCSBML + 98 or MCSBML + 99 error message CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 97) == false); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 98) == false); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 99) == false); } const char* test000095::MODEL_STRING1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">" " <model id=\"Model_1\" name=\"New Model\">" " <notes>" " <body xmlns=\"http://www.w3.org/1999/xhtml\">" " <p>L3V1 model with event priority.</p>" " </body>" " </notes>" " <listOfParameters>" " <parameter id=\"parameter_1\" name=\"K\" value=\"0\" constant=\"false\"/>" " </listOfParameters>" " <listOfEvents>" " <event>" " <trigger initialValue=\"true\" persistent=\"true\">" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <apply>" " <gt/>" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/time\"> time </csymbol>" " <cn> 2.0 </cn>" " </apply>" " </math>" " </trigger>" " <priority>" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 2.0 </cn>" " </math>" " </priority>" " <listOfEventAssignments>" " <eventAssignment variable=\"parameter_1\">" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 8.0 </cn>" " </math>" " </eventAssignment>" " </listOfEventAssignments>" " </event>" " </listOfEvents>" " </model>" "</sbml>" ; const char* test000095::MODEL_STRING2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">" " <model id=\"Model_1\" name=\"New Model\">" " <notes>" " <body xmlns=\"http://www.w3.org/1999/xhtml\">" " <p>L3V1 model with event priority.</p>" " </body>" " </notes>" " <listOfParameters>" " <parameter id=\"parameter_1\" name=\"K\" value=\"0\" constant=\"false\"/>" " </listOfParameters>" " <listOfEvents>" " <event>" " <trigger initialValue=\"false\" persistent=\"true\" >" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <apply>" " <gt/>" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/time\"> time </csymbol>" " <cn> 2.0 </cn>" " </apply>" " </math>" " </trigger>" " <listOfEventAssignments>" " <eventAssignment variable=\"parameter_1\">" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 8.0 </cn>" " </math>" " </eventAssignment>" " </listOfEventAssignments>" " </event>" " </listOfEvents>" " </model>" "</sbml>" ; const char* test000095::MODEL_STRING3 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">" " <model id=\"Model_1\" name=\"New Model\">" " <notes>" " <body xmlns=\"http://www.w3.org/1999/xhtml\">" " <p>L3V1 model with event priority.</p>" " </body>" " </notes>" " <listOfParameters>" " <parameter id=\"parameter_1\" name=\"K\" value=\"0\" constant=\"false\"/>" " </listOfParameters>" " <listOfEvents>" " <event>" " <trigger initialValue=\"false\" persistent=\"true\" >" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <apply>" " <gt/>" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/time\"> time </csymbol>" " <cn> 2.0 </cn>" " </apply>" " </math>" " </trigger>" " <priority>" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 2.0 </cn>" " </math>" " </priority>" " <listOfEventAssignments>" " <eventAssignment variable=\"parameter_1\">" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 8.0 </cn>" " </math>" " </eventAssignment>" " </listOfEventAssignments>" " </event>" " </listOfEvents>" " </model>" "</sbml>" ; const char* test000095::MODEL_STRING4 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">" " <model id=\"Model_1\" name=\"New Model\">" " <notes>" " <body xmlns=\"http://www.w3.org/1999/xhtml\">" " <p>L3V1 model with event priority.</p>" " </body>" " </notes>" " <listOfParameters>" " <parameter id=\"parameter_1\" name=\"K\" value=\"0\" constant=\"false\"/>" " </listOfParameters>" " <listOfEvents>" " <event>" " <trigger initialValue=\"true\" persistent=\"false\" >" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <apply>" " <gt/>" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/time\"> time </csymbol>" " <cn> 2.0 </cn>" " </apply>" " </math>" " </trigger>" " <listOfEventAssignments>" " <eventAssignment variable=\"parameter_1\">" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 8.0 </cn>" " </math>" " </eventAssignment>" " </listOfEventAssignments>" " </event>" " </listOfEvents>" " </model>" "</sbml>" ; const char* test000095::MODEL_STRING5 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">" " <model id=\"Model_1\" name=\"New Model\">" " <notes>" " <body xmlns=\"http://www.w3.org/1999/xhtml\">" " <p>L3V1 model with event priority.</p>" " </body>" " </notes>" " <listOfParameters>" " <parameter id=\"parameter_1\" name=\"K\" value=\"0\" constant=\"false\"/>" " </listOfParameters>" " <listOfEvents>" " <event>" " <trigger initialValue=\"true\" persistent=\"true\" >" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <apply>" " <gt/>" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/time\"> time </csymbol>" " <cn> 2.0 </cn>" " </apply>" " </math>" " </trigger>" " <listOfEventAssignments>" " <eventAssignment variable=\"parameter_1\">" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">" " <cn> 8.0 </cn>" " </math>" " </eventAssignment>" " </listOfEventAssignments>" " </event>" " </listOfEvents>" " </model>" "</sbml>" ;
43.344704
122
0.666653
[ "object", "model" ]
81794cfe3397c04b00dcc2386240c27ec1b27a71
42,770
cpp
C++
legion/engine/core/data/loaders/gltfmeshloader.cpp
Legion-Engine/Legion-Engine
a2b898e1cc763b82953c6990dde0b379491a30d0
[ "MIT" ]
258
2020-10-22T07:09:57.000Z
2021-09-09T05:47:09.000Z
legion/engine/core/data/loaders/gltfmeshloader.cpp
Legion-Engine/Legion-Engine
a2b898e1cc763b82953c6990dde0b379491a30d0
[ "MIT" ]
51
2020-11-17T13:02:10.000Z
2021-09-07T18:19:39.000Z
legion/engine/core/data/loaders/gltfmeshloader.cpp
Legion-Engine/Legion-Engine
a2b898e1cc763b82953c6990dde0b379491a30d0
[ "MIT" ]
13
2020-12-08T08:06:48.000Z
2021-09-09T05:47:19.000Z
#if !defined(DOXY_EXCLUDE) #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYGLTF_USE_CPP14 #include <tinygltf/tiny_gltf.h> #endif #include <core/data/loaders/gltfmeshloader.hpp> namespace legion::core { namespace detail { static assets::asset<image> loadGLTFImage(const tinygltf::Image& img) { std::string name = img.name + img.uri; const auto hash = nameHash(name); auto handle = assets::get<image>(hash); if (handle) return handle; byte* imgData = new byte[img.image.size()]; // faux_gltf_image_loader will delete upon destruction. memcpy(imgData, img.image.data(), img.image.size()); return assets::AssetCache<image>::createAsLoader<GltfFauxImageLoader>(hash, img.name, "", // Image constructor parameters. math::ivec2(img.width, img.height), img.pixel_type == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE ? channel_format::eight_bit : img.pixel_type == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT ? channel_format::sixteen_bit : channel_format::float_hdr, img.component == 1 ? image_components::grey : img.component == 2 ? image_components::grey_alpha : img.component == 3 ? image_components::rgb : image_components::rgba, data_view<byte>{ imgData, img.image.size(), 0 }); } /** * @brief Function to copy tinygltf buffer data into the correct mesh data vector * * @param buffer - The tinygltf::Buffer buffer containing the data * @param bufferView - the tinygltf::BufferView containing information about data size and offset * @param data - std::Vector<T> where the buffer is going to be copied into. The vector will be resized to vector.size()+(tinygltf data size) */ template<typename T> static void handleGltfBuffer(const tinygltf::Model& model, const tinygltf::Accessor& accessor, std::vector<T>& data) { const tinygltf::BufferView& bufferView = model.bufferViews.at(static_cast<size_type>(accessor.bufferView)); const tinygltf::Buffer& buffer = model.buffers.at(static_cast<size_type>(bufferView.buffer)); const size_type bufferStart = bufferView.byteOffset + accessor.byteOffset; const size_type stride = static_cast<size_type>(accessor.ByteStride(bufferView)); const size_type bufferEnd = bufferStart + accessor.count * stride; const size_type dataStart = data.size(); data.reserve(dataStart + accessor.count); for (size_t i = bufferStart; i < bufferEnd; i += stride) data.push_back(*reinterpret_cast<const T*>(&buffer.data[i])); if (accessor.sparse.isSparse) { const auto& sparse = accessor.sparse; const auto& indices = sparse.indices; const auto& values = sparse.values; const auto& indexView = model.bufferViews.at(static_cast<size_type>(indices.bufferView)); const auto& indexBuffer = model.buffers.at(static_cast<size_type>(indexView.buffer)); const size_type indexStart = indexView.byteOffset + static_cast<size_type>(indices.byteOffset); const size_type indexStride = (indexView.byteStride == 0 ? sizeof(uint16) : indexView.byteStride); const auto& valueView = model.bufferViews.at(static_cast<size_type>(values.bufferView)); const auto& valueBuffer = model.buffers.at(static_cast<size_type>(valueView.buffer)); const size_type valueStart = valueView.byteOffset + static_cast<size_type>(values.byteOffset); const size_type valueStride = (valueView.byteStride == 0 ? sizeof(T) : valueView.byteStride); size_type indexPos = indexStart; size_type valuePos = valueStart; for (int i = 0; i < sparse.count; i++) { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); data.at(dataStart + *idx) = *reinterpret_cast<const T*>(&valueBuffer.data[valuePos]); indexPos += indexStride; valuePos += valueStride; } } } static void handleGltfBuffer(const tinygltf::Model& model, const tinygltf::Accessor& accessor, std::vector<math::vec3>& data, const math::mat4 transform, bool normal = false) { const tinygltf::BufferView& bufferView = model.bufferViews.at(static_cast<size_type>(accessor.bufferView)); const tinygltf::Buffer& buffer = model.buffers.at(static_cast<size_type>(bufferView.buffer)); const size_type bufferStart = bufferView.byteOffset + accessor.byteOffset; const size_type stride = static_cast<size_type>(accessor.ByteStride(bufferView)); const size_type bufferEnd = bufferStart + accessor.count * stride; const size_type dataStart = data.size(); data.reserve(dataStart + accessor.count); if (normal) { for (size_t i = bufferStart; i < bufferEnd; i += stride) { const float* x = reinterpret_cast<const float*>(&buffer.data[i]); const float* y = reinterpret_cast<const float*>(&buffer.data[i + sizeof(float)]); const float* z = reinterpret_cast<const float*>(&buffer.data[i + 2 * sizeof(float)]); data.push_back(math::normalize((transform * math::vec4(*x, *y, *z, 0)).xyz())); } } else { for (size_t i = bufferStart; i < bufferEnd; i += stride) { const float* x = reinterpret_cast<const float*>(&buffer.data[i]); const float* y = reinterpret_cast<const float*>(&buffer.data[i + sizeof(float)]); const float* z = reinterpret_cast<const float*>(&buffer.data[i + 2 * sizeof(float)]); data.push_back((transform * math::vec4(*x, *y, *z, 1)).xyz()); } } if (accessor.sparse.isSparse) { const auto& sparse = accessor.sparse; const auto& indices = sparse.indices; const auto& values = sparse.values; const auto& indexView = model.bufferViews.at(static_cast<size_type>(indices.bufferView)); const auto& indexBuffer = model.buffers.at(static_cast<size_type>(indexView.buffer)); const size_type indexStart = indexView.byteOffset + static_cast<size_type>(indices.byteOffset); const size_type indexStride = (indexView.byteStride == 0 ? sizeof(uint16) : indexView.byteStride); const auto& valueView = model.bufferViews.at(static_cast<size_type>(values.bufferView)); const auto& valueBuffer = model.buffers.at(static_cast<size_type>(valueView.buffer)); const size_type valueStart = valueView.byteOffset + static_cast<size_type>(values.byteOffset); const size_type valueStride = (valueView.byteStride == 0 ? 3 * sizeof(float) : valueView.byteStride); size_type indexPos = indexStart; size_type valuePos = valueStart; if (normal) { for (int i = 0; i < sparse.count; i++) { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); const float* x = reinterpret_cast<const float*>(&valueBuffer.data[valuePos]); const float* y = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + sizeof(float)]); const float* z = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + 2 * sizeof(float)]); data.at(dataStart + *idx) = math::normalize((transform * math::vec4(*x, *y, *z, 0)).xyz()); indexPos += indexStride; valuePos += valueStride; } } else { for (int i = 0; i < sparse.count; i++) { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); const float* x = reinterpret_cast<const float*>(&valueBuffer.data[valuePos]); const float* y = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + sizeof(float)]); const float* z = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + 2 * sizeof(float)]); data.at(dataStart + *idx) = (transform * math::vec4(*x, *y, *z, 1)).xyz(); indexPos += indexStride; valuePos += valueStride; } } } } /** * @brief Function to handle vertex color of tinygltf * * @param buffer - tinygltf::Buffer containing the mesh data * @param bufferView - tinygltf::BufferView containing information about the buffer (data size/data offset) * @param accessorType - tinygltf accessorType, Vertex color is expected to come in vec3 or vec4 - will be handled by the function * @param componentType - tinygltf componentType, Vertex color is expected to come in float, unsigned byte or unsigned short - will be handled by the function * @param data - std::vector<color> the destination of the data copy. The vector will be resized to vector.size()+(tinygltf vertex color size) */ static common::result<void, void> handleGltfVertexColor(const tinygltf::Model& model, const tinygltf::Accessor& accessor, int accessorType, int componentType, std::vector<math::color>& data) { const tinygltf::BufferView& bufferView = model.bufferViews.at(static_cast<size_type>(accessor.bufferView)); const tinygltf::Buffer& buffer = model.buffers.at(static_cast<size_type>(bufferView.buffer)); const size_type bufferStart = bufferView.byteOffset + accessor.byteOffset; const size_type stride = static_cast<size_type>(accessor.ByteStride(bufferView)); const size_type bufferEnd = bufferStart + accessor.count * stride; const size_type dataStart = data.size(); data.reserve(dataStart + accessor.count); std::vector<std::string> warnings; //colors in glft are in vec3/vec4 float/unsigned byte/unsigned short for (size_type i = bufferStart; i < bufferEnd; i += stride) { if (accessorType == TINYGLTF_TYPE_VEC3) { // Copy the vertex colors into the vector, keeping in my mind that the vertex color data is only r,g,b switch (componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { // Vertex colors in unsigned byte const float r = static_cast<float>(buffer.data[i]) / 255.f; const float g = static_cast<float>(buffer.data[i + sizeof(byte)]) / 255.f; const float b = static_cast<float>(buffer.data[i + 2 * sizeof(byte)]) / 255.f; data.emplace_back(r, g, b); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { // Vertex colors in unsigned short // Currently not supported warnings.emplace_back("Vert colors for UNSIGNED SHORT not implemented"); } break; case TINYGLTF_COMPONENT_TYPE_FLOAT: { // Vertex colors in float const float* r = reinterpret_cast<const float*>(&buffer.data[i]); const float* g = reinterpret_cast<const float*>(&buffer.data[i + sizeof(float)]); const float* b = reinterpret_cast<const float*>(&buffer.data[i + 2 * sizeof(float)]); data.emplace_back(*r, *g, *b); } break; default: warnings.emplace_back("Vert colors were not stored as UNSIGNED BYTE/SHORT or float, skipping"); } } else if (accessorType == TINYGLTF_TYPE_VEC4) { // Copy the vertex colors into the vector, keeping in my mind that the vertex color data is r,g,b,a switch (componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { // Vertex colors in unsigned byte const float r = static_cast<float>(buffer.data[i]) / 255.f; const float g = static_cast<float>(buffer.data[i + sizeof(byte)]) / 255.f; const float b = static_cast<float>(buffer.data[i + 2 * sizeof(byte)]) / 255.f; const float a = static_cast<float>(buffer.data[i + 3 * sizeof(byte)]) / 255.f; data.emplace_back(r, g, b, a); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { // Vertex colors in unsigned short // Currently not supported warnings.emplace_back("Vert colors for UNSIGNED SHORT not implemented"); } break; case TINYGLTF_COMPONENT_TYPE_FLOAT: { // Vertex colors in float const float* r = reinterpret_cast<const float*>(&buffer.data[i]); const float* g = reinterpret_cast<const float*>(&buffer.data[i + sizeof(float)]); const float* b = reinterpret_cast<const float*>(&buffer.data[i + 2 * sizeof(float)]); const float* a = reinterpret_cast<const float*>(&buffer.data[i + 3 * sizeof(float)]); data.emplace_back(*r, *g, *b, *a); } break; default: warnings.emplace_back("Vert colors were not stored as UNSIGNED BYTE/SHORT or float, skipping"); } } else warnings.emplace_back("Vert colors were not vec3 or vec4, skipping colors"); } if (accessor.sparse.isSparse) { const auto& sparse = accessor.sparse; const auto& indices = sparse.indices; const auto& values = sparse.values; const auto& indexView = model.bufferViews.at(static_cast<size_type>(indices.bufferView)); const auto& indexBuffer = model.buffers.at(static_cast<size_type>(indexView.buffer)); const size_type indexStart = indexView.byteOffset + static_cast<size_type>(indices.byteOffset); const size_type indexStride = (indexView.byteStride == 0 ? sizeof(uint16) : indexView.byteStride); const auto& valueView = model.bufferViews.at(static_cast<size_type>(values.bufferView)); const auto& valueBuffer = model.buffers.at(static_cast<size_type>(valueView.buffer)); const size_type valueStart = valueView.byteOffset + static_cast<size_type>(values.byteOffset); const size_type valueStride = (valueView.byteStride == 0 ? sizeof(uint16) : valueView.byteStride); size_type indexPos = indexStart; size_type valuePos = valueStart; for (int i = 0; i < sparse.count; i++) { if (accessorType == TINYGLTF_TYPE_VEC3) { switch (componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); const float r = static_cast<float>(valueBuffer.data[valuePos]) / 255.f; const float g = static_cast<float>(valueBuffer.data[valuePos + sizeof(byte)]) / 255.f; const float b = static_cast<float>(valueBuffer.data[valuePos + 2 * sizeof(byte)]) / 255.f; data.at(dataStart + *idx) = math::color(r, g, b); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { } break; case TINYGLTF_COMPONENT_TYPE_FLOAT: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); const float* r = reinterpret_cast<const float*>(&valueBuffer.data[valuePos]); const float* g = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + sizeof(float)]); const float* b = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + 2 * sizeof(float)]); data.at(dataStart + *idx) = math::color(*r, *g, *b); } break; } } else if (accessorType == TINYGLTF_TYPE_VEC4) { switch (componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); const float r = static_cast<float>(valueBuffer.data[valuePos]) / 255.f; const float g = static_cast<float>(valueBuffer.data[valuePos + sizeof(byte)]) / 255.f; const float b = static_cast<float>(valueBuffer.data[valuePos + 2 * sizeof(byte)]) / 255.f; const float a = static_cast<float>(valueBuffer.data[valuePos + 3 * sizeof(byte)]) / 255.f; data.at(dataStart + *idx) = math::color(r, g, b, a); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { } break; case TINYGLTF_COMPONENT_TYPE_FLOAT: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); const float* r = reinterpret_cast<const float*>(&valueBuffer.data[valuePos]); const float* g = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + sizeof(float)]); const float* b = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + 2 * sizeof(float)]); const float* a = reinterpret_cast<const float*>(&valueBuffer.data[valuePos + 3 * sizeof(float)]); data.at(dataStart + *idx) = math::color(*r, *g, *b, *a); } break; } } indexPos += indexStride; valuePos += valueStride; } } return { common::success, warnings }; } /** * @brief Function to copy tinygltf indices data into std::vector * * @param buffer - The tinygltf::Buffer containting mesh data * @param bufferView - the tinygltf::BufferView containting data about the buffer (data size/data offset) * @param offset - The mesh Indices offset. ( e.g. For the first submesh 0, for the second submesh submesh[0].indices.size() ) * @param data - The std::vector to copy the indices data into */ static common::result<void, void> handleGltfIndices(const tinygltf::Model& model, const tinygltf::Accessor& accessor, size_type offset, std::vector<uint>& data) { const tinygltf::BufferView& bufferView = model.bufferViews.at(static_cast<size_type>(accessor.bufferView)); const tinygltf::Buffer& buffer = model.buffers.at(static_cast<size_type>(bufferView.buffer)); const size_type bufferStart = bufferView.byteOffset + accessor.byteOffset; const size_type stride = static_cast<size_type>(accessor.ByteStride(bufferView)); const size_type bufferEnd = bufferStart + accessor.count * stride; const size_type dataStart = data.size(); data.reserve(dataStart + accessor.count); std::vector<std::string> warnings; switch (accessor.componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { for (size_type i = bufferStart; i < bufferEnd; i += stride) data.push_back(static_cast<uint>(buffer.data[i] + offset)); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { for (size_type i = bufferStart; i < bufferEnd; i += stride) data.push_back(static_cast<uint>(*reinterpret_cast<const uint16*>(&buffer.data[i]) + offset)); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: { for (size_type i = bufferStart; i < bufferEnd; i += stride) data.push_back(*reinterpret_cast<const uint*>(&buffer.data[i]) + static_cast<uint>(offset)); } break; default: warnings.push_back("Index component type not supported."); } if (accessor.sparse.isSparse) { const auto& sparse = accessor.sparse; const auto& indices = sparse.indices; const auto& values = sparse.values; const auto& indexView = model.bufferViews.at(static_cast<size_type>(indices.bufferView)); const auto& indexBuffer = model.buffers.at(static_cast<size_type>(indexView.buffer)); const size_type indexStart = indexView.byteOffset + static_cast<size_type>(indices.byteOffset); const size_type indexStride = (indexView.byteStride == 0 ? sizeof(uint16) : indexView.byteStride); const auto& valueView = model.bufferViews.at(static_cast<size_type>(values.bufferView)); const auto& valueBuffer = model.buffers.at(static_cast<size_type>(valueView.buffer)); const size_type valueStart = valueView.byteOffset + static_cast<size_type>(values.byteOffset); const size_type valueStride = (valueView.byteStride == 0 ? sizeof(uint16) : valueView.byteStride); size_type indexPos = indexStart; size_type valuePos = valueStart; for (int i = 0; i < sparse.count; i++) { switch (accessor.componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); data.at(dataStart + *idx) = static_cast<uint>(valueBuffer.data[valuePos] + offset); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); data.at(dataStart + *idx) = static_cast<uint>(*reinterpret_cast<const uint16*>(&valueBuffer.data[valuePos]) + offset); } break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: { const uint16* idx = reinterpret_cast<const uint16*>(&indexBuffer.data[indexPos]); data.at(dataStart + *idx) = *reinterpret_cast<const uint*>(&valueBuffer.data[valuePos]) + static_cast<uint>(offset); } break; } indexPos += indexStride; valuePos += valueStride; } } return { common::success, warnings }; } static math::mat4 getGltfNodeTransform(const tinygltf::Node& node) { if (node.matrix.size() == 16u) { // Use matrix attribute return math::mat4( -static_cast<float>(node.matrix[0]), -static_cast<float>(node.matrix[1]), -static_cast<float>(node.matrix[2]), -static_cast<float>(node.matrix[3]), static_cast<float>(node.matrix[4]), static_cast<float>(node.matrix[5]), static_cast<float>(node.matrix[6]), static_cast<float>(node.matrix[7]), static_cast<float>(node.matrix[8]), static_cast<float>(node.matrix[9]), static_cast<float>(node.matrix[10]), static_cast<float>(node.matrix[11]), static_cast<float>(node.matrix[12]), static_cast<float>(node.matrix[13]), static_cast<float>(node.matrix[14]), static_cast<float>(node.matrix[15])); } else { math::vec3 pos{ 0.f, 0.f, 0.f }; math::quat rot{ 1.f, 0.f, 0.f, 0.f }; math::vec3 scale{ 1.f, 1.f, 1.f }; // Assume Trans x Rotate x Scale order if (node.scale.size() == 3) scale = math::vec3(static_cast<float>(node.scale[0]), static_cast<float>(node.scale[1]), static_cast<float>(node.scale[2])); if (node.rotation.size() == 4) rot = math::quat(static_cast<float>(node.rotation[3]), static_cast<float>(node.rotation[0]), static_cast<float>(node.rotation[1]), static_cast<float>(node.rotation[2])); if (node.translation.size() == 3) pos = math::vec3(static_cast<float>(node.translation[0]), static_cast<float>(node.translation[1]), static_cast<float>(node.translation[2])); auto result = math::compose(scale, rot, pos); result[0] = -result[0]; return result; } } static common::result<void, void> handleGltfMesh(mesh& meshData, const tinygltf::Model& model, const tinygltf::Mesh& mesh, const math::mat4& transform) { std::vector<std::string> warnings; size_type primitiveIndex = 0; for (auto primitive : mesh.primitives) { sub_mesh m; m.name = mesh.name; m.indexOffset = meshData.indices.size(); m.materialIndex = primitive.material; // Loop through all primitives in the mesh // Primitives can be vertex position, normal, texcoord (uv) and vertex colors const size_type vertexOffset = meshData.vertices.size(); for (auto& attrib : primitive.attributes) { // Loop through the attributes of the primitive // Depending on the attribute the data is copied into a different std::vector in meshData const tinygltf::Accessor& accessor = model.accessors.at(static_cast<size_type>(attrib.second)); if (attrib.first.compare("POSITION") == 0) { // Position data detail::handleGltfBuffer(model, accessor, meshData.vertices, transform); } else if (attrib.first.compare("NORMAL") == 0) { // Normal data detail::handleGltfBuffer(model, accessor, meshData.normals, transform, true); } else if (attrib.first.compare("TEXCOORD_0") == 0) { // UV data detail::handleGltfBuffer(model, accessor, meshData.uvs); } else if (attrib.first.compare("COLOR_0") == 0) { // Vertex color data auto result = detail::handleGltfVertexColor(model, accessor, accessor.type, accessor.componentType, meshData.colors); warnings.insert(warnings.end(), result.warnings().begin(), result.warnings().end()); } else { warnings.push_back("More data to be found in gltf. Data can be accesed through: " + attrib.first); } } const size_type smallestBufferSize = std::min(meshData.normals.size(), std::min(meshData.uvs.size(), meshData.colors.size())); const size_type vertexCount = meshData.vertices.size(); meshData.normals.reserve(vertexCount); meshData.uvs.reserve(vertexCount); meshData.colors.reserve(vertexCount); for (size_type i = smallestBufferSize; i < vertexCount; ++i) { if (meshData.normals.size() == i) meshData.normals.push_back(math::vec3::up); if (meshData.uvs.size() == i) meshData.uvs.push_back(math::vec2(0, 0)); if (meshData.colors.size() == i) meshData.colors.push_back(core::math::colors::white); } // Find the indices of our mesh and copy them into meshData.indices const size_type index = static_cast<size_type>(primitive.indices); if (index > model.accessors.size()) { warnings.push_back("Invalid index accessor index in primitive: " + std::to_string(primitiveIndex)); return { common::error, warnings }; } if (primitive.indices >= 0) { const tinygltf::Accessor& indexAccessor = model.accessors.at(index); auto result = detail::handleGltfIndices(model, indexAccessor, vertexOffset, meshData.indices); warnings.insert(warnings.end(), result.warnings().begin(), result.warnings().end()); } else { for (uint i = static_cast<uint>(vertexOffset); i < meshData.vertices.size(); i++) meshData.indices.push_back(i); } primitiveIndex++; // Calculate size of submesh m.indexCount = meshData.indices.size() - m.indexOffset; meshData.submeshes.push_back(m); } return { common::success, warnings }; } static common::result<void, void> handleGltfNode(mesh& meshData, const tinygltf::Model& model, const tinygltf::Node& node, const math::mat4& parentTransf) { std::vector<std::string> warnings; const math::mat4 rhToLhMat{ -1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }; const auto transf = parentTransf * detail::getGltfNodeTransform(node) * rhToLhMat; const size_type meshIdx = static_cast<size_type>(node.mesh); if (node.mesh >= 0 && meshIdx < model.meshes.size()) { auto result = handleGltfMesh(meshData, model, model.meshes[meshIdx], transf); warnings.insert(warnings.end(), result.warnings().begin(), result.warnings().end()); } for (auto& nodeIdx : node.children) { const size_type idx = static_cast<size_type>(nodeIdx); if (nodeIdx < 0 && idx >= model.nodes.size()) { warnings.emplace_back("invalid node in GLTF"); continue; } auto result = handleGltfNode(meshData, model, model.nodes[idx], transf); warnings.insert(warnings.end(), result.warnings().begin(), result.warnings().end()); } return { common::success, warnings }; } } using base = assets::AssetLoader<mesh>; using asset_ptr = base::asset_ptr; using import_cfg = base::import_cfg; using progress_type = base::progress_type; common::result<asset_ptr> GltfMeshLoader::loadImpl(id_type nameHash, const fs::view& file, progress_type* progress) { namespace tg = tinygltf; tg::Model model; tg::TinyGLTF loader; std::string err; std::string warn; std::string baseDir = ""; std::vector<std::string> warnings; auto contextPath = file.parent().get_virtual_path(); filesystem::navigator navigator(contextPath); auto solution = navigator.find_solution(); if (solution.has_error()) warnings.push_back(std::string("Invalid gltf context path, ") + solution.error().what()); else { auto s = solution.value(); if (s.size() != 1) warnings.emplace_back("Invalid gltf context path, fs::view was not fully local"); else { filesystem::basic_resolver* resolver = dynamic_cast<filesystem::basic_resolver*>(s[0].first); if (!resolver) warnings.emplace_back("Invalid gltf context path, fs::view was not local"); else { resolver->set_target(s[0].second); if (!resolver->is_valid_path()) warnings.emplace_back("Invalid gltf context path"); else baseDir = resolver->get_absolute_path(); } } } auto result = file.get(); warnings.insert(warnings.end(), result.warnings().begin(), result.warnings().end()); if (!result) return { legion_exception_msg(result.error().what()), warnings }; auto extension = file.get_extension(); if (!extension) return { legion_exception_msg(extension.error().what()), warnings }; if (progress) progress->advance_progress(5.f); if (extension.value() == ".gltf") { auto text = result->to_string(); if (!loader.LoadASCIIFromString(&model, &err, &warn, text.c_str(), static_cast<uint>(text.size()), baseDir)) { auto parserWarnings = common::split_string_at<'\n'>(warn); warnings.insert(warnings.end(), parserWarnings.begin(), parserWarnings.end()); return { legion_exception_msg("Failed to parse GLTF: " + err), warnings }; } } else if (extension.value() == ".glb") { if (!loader.LoadBinaryFromMemory(&model, &err, &warn, result->data(), static_cast<uint>(result->size()), baseDir)) { auto parserWarnings = common::split_string_at<'\n'>(warn); warnings.insert(warnings.end(), parserWarnings.begin(), parserWarnings.end()); return { legion_exception_msg("Failed to parse GLTF: " + err), warnings }; } } else return { legion_exception_msg("File was not recognised as a gltf file."), warnings }; if (progress) progress->advance_progress(55.f); if (!err.empty()) { auto parserErrors = common::split_string_at<'\n'>(err); warnings.insert(warnings.end(), parserErrors.begin(), parserErrors.end()); } if (!warn.empty()) { auto parserWarnings = common::split_string_at<'\n'>(warn); warnings.insert(warnings.end(), parserWarnings.begin(), parserWarnings.end()); } core::mesh meshData; const float percentagePerMat = 25.f / static_cast<float>(model.materials.size()); std::unordered_map<std::string, std::pair<bool, size_type>> materialNames; for (auto& srcMat : model.materials) { auto& material = meshData.materials.emplace_back(); auto& pbrData = srcMat.pbrMetallicRoughness; material.name = srcMat.name; if (materialNames.count(material.name)) materialNames.at(material.name).first = true; else materialNames.emplace(material.name, std::make_pair<bool, size_type>(false, 0u)); material.opaque = srcMat.alphaMode != "BLEND"; material.alphaCutoff = static_cast<float>(srcMat.alphaCutoff); material.doubleSided = srcMat.doubleSided; material.albedoValue = math::color( static_cast<float>(pbrData.baseColorFactor[0]), static_cast<float>(pbrData.baseColorFactor[1]), static_cast<float>(pbrData.baseColorFactor[2]), static_cast<float>(pbrData.baseColorFactor[3])); if (pbrData.baseColorTexture.index >= 0) material.albedoMap = detail::loadGLTFImage( model.images[ static_cast<size_type>(model.textures[ static_cast<size_type>(pbrData.baseColorTexture.index) ].source) ]); material.metallicValue = static_cast<float>(pbrData.metallicFactor); material.roughnessValue = static_cast<float>(pbrData.roughnessFactor); if (pbrData.metallicRoughnessTexture.index >= 0) material.metallicRoughnessMap = detail::loadGLTFImage( model.images[ static_cast<size_type>(model.textures[ static_cast<size_type>(pbrData.metallicRoughnessTexture.index) ].source) ]); material.emissiveValue = math::color( static_cast<float>(srcMat.emissiveFactor[0]), static_cast<float>(srcMat.emissiveFactor[1]), static_cast<float>(srcMat.emissiveFactor[2])); if (srcMat.emissiveTexture.index >= 0) material.emissiveMap = detail::loadGLTFImage( model.images[ static_cast<size_type>(model.textures[ static_cast<size_type>(srcMat.emissiveTexture.index) ].source) ]); if (srcMat.normalTexture.index >= 0) material.normalMap = detail::loadGLTFImage( model.images[ static_cast<size_type>(model.textures[ static_cast<size_type>(srcMat.normalTexture.index) ].source) ]); if (srcMat.occlusionTexture.index >= 0) material.aoMap = detail::loadGLTFImage( model.images[ static_cast<size_type>(model.textures[ static_cast<size_type>(srcMat.occlusionTexture.index) ].source) ]); material.heightMap = assets::invalid_asset<image>; if (progress) progress->advance_progress(percentagePerMat); } if (!materialNames.empty()) { for (auto& mat : meshData.materials) { auto& [duplicate, count] = materialNames.at(mat.name); if (duplicate) { mat.name += std::to_string(count++); } } } if (!model.scenes.size()) { return { legion_exception_msg("GLTF model contained 0 scenes"), warnings }; } const size_type sceneToLoad = model.defaultScene < 0 ? 0 : static_cast<size_type>(model.defaultScene); const float percentagePerNode = 10.f / static_cast<float>(model.scenes[sceneToLoad].nodes.size()); const math::mat4 rootMat{ -1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }; for (auto& nodeIdx : model.scenes[sceneToLoad].nodes) { if (nodeIdx < 0) continue; const size_type idx = static_cast<size_type>(nodeIdx); detail::handleGltfNode(meshData, model, model.nodes[idx], rootMat); if (progress) progress->advance_progress(percentagePerNode); } for (auto& uv : meshData.uvs) uv.y = 1.f-uv.y; // Because we only flip one axis we also need to flip the triangle rotation. for (size_type i = 0; i < meshData.indices.size(); i += 3) { uint i1 = meshData.indices[i + 1]; uint i2 = meshData.indices[i + 2]; meshData.indices[i + 1] = i2; meshData.indices[i + 2] = i1; } mesh::calculate_tangents(&meshData); return { create(nameHash, meshData), warnings }; } bool GltfMeshLoader::canLoad(const fs::view& file) { auto result = file.get_extension(); if (!result) return false; return result.value() == ".gltf" || result.value() == ".glb"; } common::result<asset_ptr> GltfMeshLoader::load(id_type nameHash, const fs::view& file, L_MAYBEUNUSED const import_cfg& settings) { OPTICK_EVENT(); return loadImpl(nameHash, file, nullptr); } common::result<asset_ptr> GltfMeshLoader::loadAsync(id_type nameHash, const fs::view& file, L_MAYBEUNUSED const import_cfg& settings, progress_type& progress) { OPTICK_EVENT(); return loadImpl(nameHash, file, &progress); } }
48.437146
217
0.542296
[ "mesh", "vector", "model", "transform" ]
8183d20ca6de6f6095898f5aa6085a27fec53eeb
3,798
cpp
C++
plugins/mesh/src/AbstractMeshDataSource.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
null
null
null
plugins/mesh/src/AbstractMeshDataSource.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
null
null
null
plugins/mesh/src/AbstractMeshDataSource.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
null
null
null
#include "mesh/AbstractMeshDataSource.h" megamol::mesh::AbstractMeshDataSource::AbstractMeshDataSource() : core::Module() , m_mesh_access_collection({nullptr, {}}) , m_mesh_lhs_slot("meshes", "The slot publishing the loaded data") , m_mesh_rhs_slot("chainMeshes", "The slot for chaining mesh data sources") { this->m_mesh_lhs_slot.SetCallback(CallMesh::ClassName(), "GetData", &AbstractMeshDataSource::getMeshDataCallback); this->m_mesh_lhs_slot.SetCallback( CallMesh::ClassName(), "GetMetaData", &AbstractMeshDataSource::getMeshMetaDataCallback); this->MakeSlotAvailable(&this->m_mesh_lhs_slot); this->m_mesh_rhs_slot.SetCompatibleCall<CallMeshDescription>(); this->MakeSlotAvailable(&this->m_mesh_rhs_slot); } megamol::mesh::AbstractMeshDataSource::~AbstractMeshDataSource() { this->Release(); } bool megamol::mesh::AbstractMeshDataSource::create(void) { // default empty collection m_mesh_access_collection.first = std::make_shared<MeshDataAccessCollection>(); return true; } bool megamol::mesh::AbstractMeshDataSource::getMeshMetaDataCallback(core::Call& caller) { CallMesh* lhs_mesh_call = dynamic_cast<CallMesh*>(&caller); CallMesh* rhs_mesh_call = m_mesh_rhs_slot.CallAs<CallMesh>(); if (lhs_mesh_call == NULL) return false; auto lhs_meta_data = lhs_mesh_call->getMetaData(); unsigned int frame_cnt = 1; auto bbox = lhs_meta_data.m_bboxs.BoundingBox(); auto cbbox = lhs_meta_data.m_bboxs.ClipBox(); if (rhs_mesh_call != NULL) { auto rhs_meta_data = rhs_mesh_call->getMetaData(); rhs_meta_data.m_frame_ID = lhs_meta_data.m_frame_ID; rhs_mesh_call->setMetaData(rhs_meta_data); if (!(*rhs_mesh_call)(1)) return false; rhs_meta_data = rhs_mesh_call->getMetaData(); frame_cnt = std::max(rhs_meta_data.m_frame_cnt, frame_cnt); bbox.Union(rhs_meta_data.m_bboxs.BoundingBox()); cbbox.Union(rhs_meta_data.m_bboxs.ClipBox()); } lhs_meta_data.m_frame_cnt = frame_cnt; lhs_meta_data.m_bboxs.SetBoundingBox(bbox); lhs_meta_data.m_bboxs.SetClipBox(cbbox); lhs_mesh_call->setMetaData(lhs_meta_data); return true; } void megamol::mesh::AbstractMeshDataSource::release() {} void megamol::mesh::AbstractMeshDataSource::syncMeshAccessCollection(CallMesh* lhs_call, CallMesh* rhs_call) { if (lhs_call->getData() == nullptr) { // no incoming mesh -> use your own mesh access collection, i.e. share to left lhs_call->setData(m_mesh_access_collection.first, lhs_call->version()); } else { // incoming material -> use it, copy material from last used collection if needed if (lhs_call->getData() != m_mesh_access_collection.first) { std::pair<std::shared_ptr<MeshDataAccessCollection>, std::vector<std::string>> mesh_access_collection = { lhs_call->getData(), {}}; for (auto const& identifier : m_mesh_access_collection.second) { MeshDataAccessCollection::Mesh mesh = m_mesh_access_collection.first->accessMesh(identifier); mesh_access_collection.first->addMesh(identifier, mesh.attributes, mesh.indices, mesh.primitive_type); m_mesh_access_collection.first->deleteMesh(identifier); } m_mesh_access_collection = mesh_access_collection; } } if (rhs_call != nullptr) { rhs_call->setData(m_mesh_access_collection.first, rhs_call->version()); } } void megamol::mesh::AbstractMeshDataSource::clearMeshAccessCollection() { for (auto& identifier : m_mesh_access_collection.second) { m_mesh_access_collection.first->deleteMesh(identifier); } m_mesh_access_collection.second.clear(); }
38.755102
118
0.705898
[ "mesh", "vector" ]
81848866937f0ee2b5d646b4303085d0915a9bc4
1,894
cpp
C++
Contests/USACO Solutions/2014-15/Open 2015 Gold/15 Open G2.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
1,760
2017-05-21T21:07:06.000Z
2022-03-29T13:15:08.000Z
Contests/USACO Solutions/2014-15/Open 2015 Gold/15 Open G2.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
12
2018-01-24T02:41:53.000Z
2022-03-17T13:09:26.000Z
Contests/USACO Solutions/2014-15/Open 2015 Gold/15 Open G2.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
473
2017-07-06T04:53:41.000Z
2022-03-28T13:03:28.000Z
// #include<iostream> #include<fstream> #include<set> #include<map> #include<unordered_map> #include<cmath> #include<cstring> #include<string> #include<bitset> #include<algorithm> #include<vector> #include <bits/stdc++.h> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pi; //typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; #define FOR(i, a, b) for (int i=a; i<b; i++) #define F0R(i, a) for (int i=0; i<a; i++) #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound const int MOD = 1000000007; double PI = 4*atan(1); int N, dp[500][500], dp1[500][500]; char grid[500][500]; int main() { ifstream cin ("palpath.in"); ofstream cout ("palpath.out"); cin >> N; if (N == 1) { cout << 1; return 0; } F0R(i,N) F0R(j,N) cin >> grid[i][j]; F0R(i,N-1) { F0R(j,i+1) F0R(k,i+1) { pi a = {j,i-j}, b = {N-1-k,N-1-i+k}; if (a.f>b.f || a.s>b.s) continue; if (grid[a.f][a.s] == grid[b.f][b.s] && i>0) { if (j) { if (k) dp1[j][k] = (dp1[j][k]+dp[j-1][k-1]) % MOD; dp1[j][k] = (dp1[j][k]+dp[j-1][k]) % MOD; } if (k) dp1[j][k] = (dp1[j][k]+dp[j][k-1]) % MOD; dp1[j][k] = (dp1[j][k]+dp[j][k]) % MOD; } else if (grid[a.f][a.s] == grid[b.f][b.s] && i == 0) dp1[j][k] = 1; } F0R(j,i+1) F0R(k,i+1) { dp[j][k] = dp1[j][k]; dp1[j][k] = 0; } } int ans = 0; F0R(i,N) { ans = (ans+dp[i][N-1-i]) % MOD; if (N-2-i >= 0) ans = (ans+dp[i][N-1-i-1]) % MOD; if (i) { ans = (ans+dp[i-1][N-1-i]) % MOD; if (N-2-i >= 0) ans = (ans+dp[i-1][N-1-i-1]) % MOD; } } cout << ans; }
24.282051
99
0.528511
[ "vector" ]
81851dc168264c183c90328dc91c4d654aaed98a
6,887
cpp
C++
benchmarks/static_rtree.cpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
1
2016-11-29T15:02:40.000Z
2016-11-29T15:02:40.000Z
benchmarks/static_rtree.cpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
1
2019-02-04T18:10:57.000Z
2019-02-04T18:10:57.000Z
benchmarks/static_rtree.cpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../data_structures/original_edge_data.hpp" #include "../data_structures/query_node.hpp" #include "../data_structures/shared_memory_vector_wrapper.hpp" #include "../data_structures/static_rtree.hpp" #include "../data_structures/edge_based_node.hpp" #include <osrm/coordinate.hpp> #include <random> // Choosen by a fair W20 dice roll (this value is completely arbitrary) constexpr unsigned RANDOM_SEED = 13; constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION; constexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION; constexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION; constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION; using RTreeLeaf = EdgeBasedNode; using FixedPointCoordinateListPtr = std::shared_ptr<std::vector<FixedPointCoordinate>>; using BenchStaticRTree = StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, false>::vector, false>; FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes_file) { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); QueryNode current_node; unsigned coordinate_count = 0; nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned)); auto coords = std::make_shared<std::vector<FixedPointCoordinate>>(coordinate_count); for (unsigned i = 0; i < coordinate_count; ++i) { nodes_input_stream.read((char *)&current_node, sizeof(QueryNode)); coords->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon); BOOST_ASSERT((std::abs(coords->at(i).lat) >> 30) == 0); BOOST_ASSERT((std::abs(coords->at(i).lon) >> 30) == 0); } nodes_input_stream.close(); return coords; } void Benchmark(BenchStaticRTree &rtree, unsigned num_queries) { std::mt19937 mt_rand(RANDOM_SEED); std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT); std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON); std::vector<FixedPointCoordinate> queries; for (unsigned i = 0; i < num_queries; i++) { queries.emplace_back(FixedPointCoordinate(lat_udist(mt_rand), lon_udist(mt_rand))); } { const unsigned num_results = 5; std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results << " phantom nodes" << "\n"; TIMER_START(query_phantom); std::vector<PhantomNode> phantom_node_vector; for (const auto &q : queries) { phantom_node_vector.clear(); rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 3, num_results); phantom_node_vector.clear(); rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 17, num_results); } TIMER_STOP(query_phantom); std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries << " queries." << "\n"; std::cout << TIMER_MSEC(query_phantom) / ((double)num_queries) << " msec/query." << "\n"; std::cout << "#### LocateClosestEndPointForCoordinate" << "\n"; } TIMER_START(query_endpoint); FixedPointCoordinate result; for (const auto &q : queries) { rtree.LocateClosestEndPointForCoordinate(q, result, 3); } TIMER_STOP(query_endpoint); std::cout << "Took " << TIMER_MSEC(query_endpoint) << " msec for " << num_queries << " queries." << "\n"; std::cout << TIMER_MSEC(query_endpoint) / ((double)num_queries) << " msec/query." << "\n"; std::cout << "#### FindPhantomNodeForCoordinate" << "\n"; TIMER_START(query_node); for (const auto &q : queries) { PhantomNode phantom; rtree.FindPhantomNodeForCoordinate(q, phantom, 3); } TIMER_STOP(query_node); std::cout << "Took " << TIMER_MSEC(query_node) << " msec for " << num_queries << " queries." << "\n"; std::cout << TIMER_MSEC(query_node) / ((double)num_queries) << " msec/query." << "\n"; { const unsigned num_results = 1; std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results << " phantom nodes" << "\n"; TIMER_START(query_phantom); std::vector<PhantomNode> phantom_node_vector; for (const auto &q : queries) { phantom_node_vector.clear(); rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 3, num_results); phantom_node_vector.clear(); rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 17, num_results); } TIMER_STOP(query_phantom); std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries << " queries." << "\n"; std::cout << TIMER_MSEC(query_phantom) / ((double)num_queries) << " msec/query." << "\n"; std::cout << "#### LocateClosestEndPointForCoordinate" << "\n"; } } int main(int argc, char **argv) { if (argc < 4) { std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes" << "\n"; return 1; } const char *ramPath = argv[1]; const char *filePath = argv[2]; const char *nodesPath = argv[3]; auto coords = LoadCoordinates(nodesPath); BenchStaticRTree rtree(ramPath, filePath, coords); Benchmark(rtree, 10000); return 0; }
37.429348
100
0.664876
[ "vector" ]
8185dff41b990b5a98fa3b79d83e94bbdbe27d84
27,268
cpp
C++
external/SoWin/src/Inventor/Win/viewers/FullViewer.cpp
skrat/ifcplusplus
1e65d8e0d5e3365d4d1da399081ffaa78fd8a486
[ "MIT" ]
7
2018-03-07T06:51:41.000Z
2020-05-22T08:32:54.000Z
external/SoWin/src/Inventor/Win/viewers/FullViewer.cpp
skrat/ifcplusplus
1e65d8e0d5e3365d4d1da399081ffaa78fd8a486
[ "MIT" ]
1
2019-03-06T08:59:24.000Z
2019-03-06T08:59:24.000Z
external/SoWin/src/Inventor/Win/viewers/FullViewer.cpp
skrat/ifcplusplus
1e65d8e0d5e3365d4d1da399081ffaa78fd8a486
[ "MIT" ]
8
2018-05-02T20:16:07.000Z
2021-06-10T03:06:04.000Z
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ // ************************************************************************ // Class is documented in common/viewers/SoGuiFullViewer.cpp.in. // ************************************************************************* #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/nodes/SoOrthographicCamera.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/threads/SbStorage.h> #include <sowindefs.h> #include <Inventor/Win/Win32API.h> #include <Inventor/Win/SoWin.h> #include <Inventor/Win/widgets/SoWinBitmapButton.h> #include <Inventor/Win/widgets/WinNativePopupMenu.h> #include <Inventor/Win/viewers/SoWinFullViewer.h> #include <Inventor/Win/viewers/SoWinFullViewerP.h> #include <float.h> // FLT_MAX // Button icons. #include <Inventor/Win/common/pixmaps/pick.xpm> #include <Inventor/Win/common/pixmaps/view.xpm> #include <Inventor/Win/common/pixmaps/home.xpm> #include <Inventor/Win/common/pixmaps/set_home.xpm> #include <Inventor/Win/common/pixmaps/view_all.xpm> #include <Inventor/Win/common/pixmaps/seek.xpm> static const int DECORATION_SIZE = 30; static const int DECORATION_BUFFER = 5; #define PRIVATE(o) (o->pimpl) #define PUBLIC(o) (o->pub) // ************************************************************************* SOWIN_OBJECT_ABSTRACT_SOURCE(SoWinFullViewer); // ************************************************************************* static void hookhandle_constructor(void * closure) { HHOOK * hookhandle = (HHOOK *) closure; *hookhandle = NULL; } static void hookhandle_destructor(void *) { } SoWinFullViewer::SoWinFullViewer(HWND parent, const char * name, SbBool embedded, BuildFlag flag, SoWinViewer::Type type, SbBool build) : inherited(parent, name, embedded, type, FALSE) { SoWinFullViewerP::nrinstances++; this->pimpl = new SoWinFullViewerP(this); if (SoWinFullViewerP::hookhandle == NULL) { SoWinFullViewerP::hookhandle = new SbStorage(sizeof(HHOOK), hookhandle_constructor, hookhandle_destructor); } HHOOK * hookhandle = (HHOOK *) SoWinFullViewerP::hookhandle->get(); if (!(*hookhandle)) { *hookhandle = Win32::SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)SoWinFullViewerP::systemEventHook, NULL, GetCurrentThreadId()); } if (SoWinFullViewerP::parentHWNDmappings == NULL) { SoWinFullViewerP::parentHWNDmappings = new SbDict; } PRIVATE(this)->viewerwidget = NULL; PRIVATE(this)->renderareawidget = NULL; PRIVATE(this)->menuenabled = (flag & SoWinFullViewer::BUILD_POPUP) ? TRUE : FALSE; PRIVATE(this)->decorations = (flag & SoWinFullViewer::BUILD_DECORATION) ? TRUE : FALSE; this->prefmenu = NULL; PRIVATE(this)->leftthumbwheel = NULL; PRIVATE(this)->bottomthumbwheel = NULL; PRIVATE(this)->rightthumbwheel = NULL; this->leftWheel = NULL; this->bottomWheel = NULL; this->rightWheel = NULL; this->rightWheelStr = NULL; // Let these be bogus until we actually set up the wheels. this->leftWheelVal = FLT_MAX; this->bottomWheelVal = FLT_MAX; this->rightWheelVal = FLT_MAX; if (build) { this->setClassName("SoWinFullViewer"); this->setBaseWidget(this->buildWidget(this->getParentWidget())); } /* FIXME: We should use the actual size of the parent window instead of hardcoding the size here, at least if the size of the parent window is reasonable. See also SoWinExaminerViewerP::constructor(). 2004-01-08 thammer. */ this->setSize(SbVec2s(500, 420)); if (! this->isViewing()) this->setViewing(TRUE); } SoWinFullViewer::~SoWinFullViewer() { (void)SoWinFullViewerP::parentHWNDmappings->remove((SbDict::Key)this->getParentWidget()); SoWinFullViewerP::nrinstances--; if (SoWinFullViewerP::nrinstances == 0) { // Parent HWND -> SoWinFullViewer dict. delete SoWinFullViewerP::parentHWNDmappings; SoWinFullViewerP::parentHWNDmappings = NULL; HHOOK * hookhandle = (HHOOK *) SoWinFullViewerP::hookhandle->get(); if (*hookhandle) { Win32::UnhookWindowsHookEx(*hookhandle); } delete SoWinFullViewerP::hookhandle; SoWinFullViewerP::hookhandle = NULL; } delete this->prefmenu; delete PRIVATE(this); } void SoWinFullViewer::setDecoration(SbBool enable) { #if SOWIN_DEBUG if ((enable && this->isDecoration()) || (! enable && ! this->isDecoration())) { SoDebugError::postWarning("SoWinFullViewer::setDecoration", "decorations already turned %s", enable ? "on" : "off"); return; } #endif // SOWIN_DEBUG PRIVATE(this)->decorations = enable; PRIVATE(this)->showDecorationWidgets(enable); // reposition all widgets RECT rect; Win32::GetClientRect(this->getParentWidget(), & rect); PRIVATE(this)->layoutWidgets(rect.right, rect.bottom); if (enable) { rect.right -= DECORATION_SIZE * 2; rect.bottom -= DECORATION_SIZE; } SoWinRenderArea::sizeChanged(SbVec2s((short)rect.right, (short)rect.bottom)); Win32::InvalidateRect(this->getParentWidget(), NULL, TRUE); } SbBool SoWinFullViewer::isDecoration(void) const { return PRIVATE(this)->decorations; } void SoWinFullViewer::setPopupMenuEnabled(SbBool enable) { #if SOWIN_DEBUG if ((enable && this->isPopupMenuEnabled()) || (! enable && ! this->isPopupMenuEnabled())) { SoDebugError::postWarning("SoWinFullViewer::setPopupMenuEnabled", "popup menu already turned %s", enable ? "on" : "off"); return; } #endif // SOWIN_DEBUG PRIVATE(this)->menuenabled = enable; } SbBool SoWinFullViewer::isPopupMenuEnabled(void) const { return PRIVATE(this)->menuenabled; } HWND SoWinFullViewer::getAppPushButtonParent(void) const { return PRIVATE(this)->viewerwidget; } void SoWinFullViewer::addAppPushButton(HWND newButton) { PRIVATE(this)->lefttrimbuttons.append(newButton); } void SoWinFullViewer::insertAppPushButton(HWND newButton, int index) { PRIVATE(this)->lefttrimbuttons.insert(newButton, index); } void SoWinFullViewer::removeAppPushButton(HWND oldButton) { int index = PRIVATE(this)->lefttrimbuttons.find(oldButton); PRIVATE(this)->lefttrimbuttons.remove(index); } int SoWinFullViewer::findAppPushButton(HWND oldButton) const { return PRIVATE(this)->lefttrimbuttons.find(oldButton); } int SoWinFullViewer::lengthAppPushButton(void) const { return PRIVATE(this)->lefttrimbuttons.getLength(); } HWND SoWinFullViewer::getRenderAreaWidget(void) const { return PRIVATE(this)->renderareawidget; } // Doc in superclass. void SoWinFullViewer::setComponentCursor(const SoWinCursor & cursor) { // Overridden to apply the new cursor only for the rendering canvas // widget. Otherwise, the default SoWinComponent setComponentCursor() // method will set the cursor for the top-most parent widget, which // makes it affect all sub-widgets, like the decorations stuff. PRIVATE(this)->cursor = cursor; SoWinComponent::setWidgetCursor(this->getRenderAreaWidget(), cursor); } // Documented in superclass. void SoWinFullViewer::setViewing(SbBool enable) { if ((enable && this->isViewing()) || (! enable && ! this->isViewing())) { #if SOWIN_DEBUG SoDebugError::postWarning("SoWinFullViewer::setViewing", "view mode already %s", enable ? "on" : "off"); #endif // SOWIN_DEBUG return; } inherited::setViewing(enable); if (PRIVATE(this)->viewerButton(SoWinFullViewerP::VIEWERBUTTON_VIEW) != NULL) { PRIVATE(this)->viewerButton(SoWinFullViewerP::VIEWERBUTTON_VIEW)->setPressedState(enable); PRIVATE(this)->viewerButton(SoWinFullViewerP::VIEWERBUTTON_PICK)->setPressedState(enable ? FALSE : TRUE); PRIVATE(this)->viewerButton(SoWinFullViewerP::VIEWERBUTTON_SEEK)->setEnabled(enable); } } /////////////////////////////////////////////////////////////////// // // (protected) // // // Documented in superclass. HWND SoWinFullViewer::buildWidget(HWND parent) { // This method will always be called with a parent. assert(IsWindow(parent)); SoWinFullViewerP::parentHWNDmappings->enter((SbDict::Key)parent, this); PRIVATE(this)->viewerwidget = parent; PRIVATE(this)->renderareawidget = inherited::buildWidget(parent); assert(IsWindow(PRIVATE(this)->renderareawidget)); // Change default cursor from pointer arrow, to *no* default // cursor. This must be done for the SetCursor()-call in // SoWinFullViewerP::systemEventHook() to work even when the canvas // has not grabbed the mouse. // (void)Win32::SetClassLongPtr(this->getGLWidget(), GCLP_HCURSOR, 0); if (PRIVATE(this)->menuenabled) { this->buildPopupMenu(); } if (PRIVATE(this)->decorations) { this->buildDecoration(parent); } return PRIVATE(this)->renderareawidget; } // doc in super void SoWinFullViewer::sizeChanged(const SbVec2s & size) { if (! IsWindow(this->getBaseWidget())) return; if (PRIVATE(this)->decorations) { SoWinRenderArea::sizeChanged(SbVec2s(size[0] - (2 * DECORATION_SIZE), size[1] - DECORATION_SIZE)); } else { SoWinRenderArea::sizeChanged(size); } PRIVATE(this)->layoutWidgets(size[0], size[1]); Win32::InvalidateRect(this->getParentWidget(), NULL, TRUE); } void SoWinFullViewer::buildDecoration(HWND parent) { this->leftWheel = PRIVATE(this)->buildLeftWheel(parent); this->bottomWheel = PRIVATE(this)->buildBottomWheel(parent); this->rightWheel = PRIVATE(this)->buildRightWheel(parent); (void)this->buildViewerButtons(parent); } HWND SoWinFullViewer::buildViewerButtons(HWND parent) { this->createViewerButtons(parent, & PRIVATE(this)->righttrimbuttons); // Now position the buttons. RECT rect; Win32::GetClientRect(parent, &rect); const int x = rect.right - DECORATION_SIZE; for (int i=0; i < PRIVATE(this)->righttrimbuttons.getLength(); i++) { SoWinBitmapButton * b = (SoWinBitmapButton *) PRIVATE(this)->righttrimbuttons[i]; b->move(x, i * DECORATION_SIZE, DECORATION_SIZE, DECORATION_SIZE); } return parent; } void SoWinFullViewer::buildPopupMenu(void) { this->prefmenu = PRIVATE(this)->setupStandardPopupMenu(); } void SoWinFullViewer::openPopupMenu(const SbVec2s position) { assert(this->prefmenu != NULL); PRIVATE(this)->prepareMenu(this->prefmenu); RECT clientrect; Win32::GetClientRect(PRIVATE(this)->renderareawidget, &clientrect); this->prefmenu->popUp(PRIVATE(this)->renderareawidget, position[0], clientrect.bottom - position[1]); } void SoWinFullViewer::setLeftWheelString(const char * const name) { if (PRIVATE(this)->leftthumbwheel) PRIVATE(this)->leftthumbwheel->setLabelText(name); } void SoWinFullViewer::setBottomWheelString(const char * const name) { if (PRIVATE(this)->bottomthumbwheel) PRIVATE(this)->bottomthumbwheel->setLabelText(name); } const char * SoWinFullViewer::getRightWheelString() const { return this->rightWheelStr; } void SoWinFullViewer::setRightWheelString(const char * const string) { if (this->rightWheelStr) delete [] this->rightWheelStr; this->rightWheelStr = NULL; if (string) this->rightWheelStr = strcpy(new char [strlen(string)+1], string); if (PRIVATE(this)->rightthumbwheel) { PRIVATE(this)->rightthumbwheel->setLabelText(string); } } // ************************************************************************* #ifndef DOXYGEN_SKIP_THIS int SoWinFullViewerP::nrinstances = 0; SbStorage * SoWinFullViewerP::hookhandle = NULL; SbDict * SoWinFullViewerP::parentHWNDmappings = NULL; HWND SoWinFullViewerP::buildLeftWheel(HWND parent) { // Create coords are not needed - the widget is moved into place // by layoutWidgets this->leftthumbwheel = new SoWinThumbWheel(SoWinThumbWheel::Vertical, parent, 0, 0, 0, "RotX"); PUBLIC(this)->leftWheelVal = this->leftthumbwheel->value(); this->leftthumbwheel->setCallback(this->leftWheelCB, this); this->leftthumbwheel->setRangeBoundaryHandling(SoWinThumbWheel::ACCUMULATE); this->leftthumbwheel->setLabelOffset(0, ((DECORATION_SIZE - this->leftthumbwheel->sizeHint().cx) / 2) + DECORATION_BUFFER + 1); return this->leftthumbwheel->getWidget(); } HWND SoWinFullViewerP::buildBottomWheel(HWND parent) { // Create coords are not needed - the widget is moved into place // by layoutWidgets this->bottomthumbwheel = new SoWinThumbWheel(SoWinThumbWheel::Horizontal, parent, 1, 0, 0, "RotY"); PUBLIC(this)->bottomWheelVal = this->bottomthumbwheel->value(); this->bottomthumbwheel->setCallback(this->bottomWheelCB, this); this->bottomthumbwheel->setRangeBoundaryHandling(SoWinThumbWheel::ACCUMULATE); this->bottomthumbwheel->setLabelOffset(-4, 0); return this->bottomthumbwheel->getWidget(); } HWND SoWinFullViewerP::buildRightWheel(HWND parent) { // Create coords are not needed - the widget is moved into place // by layoutWidgets this->rightthumbwheel = new SoWinThumbWheel(SoWinThumbWheel::Vertical, parent, 2, 0, 0, "Dolly"); PUBLIC(this)->setRightWheelString("Dolly"); PUBLIC(this)->rightWheelVal = this->rightthumbwheel->value(); this->rightthumbwheel->setCallback(this->rightWheelCB, this); this->rightthumbwheel->setRangeBoundaryHandling(SoWinThumbWheel::ACCUMULATE); this->rightthumbwheel->setLabelOffset(- (this->bottomthumbwheel->getLabelSize().cx - this->rightthumbwheel->sizeHint().cx), ((DECORATION_SIZE - this->leftthumbwheel->sizeHint().cx) / 2) + DECORATION_BUFFER + 1); return this->rightthumbwheel->getWidget(); } void SoWinFullViewerP::seekbuttonProc(SoWinBitmapButton * b, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; that->seekbuttonClicked(); } void SoWinFullViewerP::seekbuttonClicked(void) { PUBLIC(this)->setSeekMode(PUBLIC(this)->isSeekMode() ? FALSE : TRUE); } void SoWinFullViewerP::leftWheelCB(SoWinThumbWheel::Interaction type, float val, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; if (type == SoWinThumbWheel::START) { PUBLIC(that)->leftWheelStart(); } else if (type == SoWinThumbWheel::END) { PUBLIC(that)->leftWheelFinish(); } else { PUBLIC(that)->leftWheelMotion(val); } } void SoWinFullViewerP::bottomWheelCB(SoWinThumbWheel::Interaction type, float val, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; if (type == SoWinThumbWheel::START) { PUBLIC(that)->bottomWheelStart(); } else if (type == SoWinThumbWheel::END) { PUBLIC(that)->bottomWheelFinish(); } else { PUBLIC(that)->bottomWheelMotion(val); } } void SoWinFullViewerP::rightWheelCB(SoWinThumbWheel::Interaction type, float val, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; if (type == SoWinThumbWheel::START) { PUBLIC(that)->rightWheelStart(); } else if (type == SoWinThumbWheel::END) { PUBLIC(that)->rightWheelFinish(); } else { PUBLIC(that)->rightWheelMotion(val); } } void SoWinFullViewerP::interactbuttonProc(SoWinBitmapButton * b, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; that->viewerButton(SoWinFullViewerP::VIEWERBUTTON_PICK)->setPressedState(TRUE); that->viewerButton(SoWinFullViewerP::VIEWERBUTTON_VIEW)->setPressedState(FALSE); if (PUBLIC(that)->isViewing()) { PUBLIC(that)->setViewing(FALSE); } } void SoWinFullViewerP::examinebuttonProc(SoWinBitmapButton * b, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; that->viewerButton(SoWinFullViewerP::VIEWERBUTTON_VIEW)->setPressedState(TRUE); that->viewerButton(SoWinFullViewerP::VIEWERBUTTON_PICK)->setPressedState(FALSE); if (!PUBLIC(that)->isViewing()) { PUBLIC(that)->setViewing(TRUE); } } void SoWinFullViewerP::homebuttonProc(SoWinBitmapButton * b, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; PUBLIC(that)->resetToHomePosition(); } void SoWinFullViewerP::sethomebuttonProc(SoWinBitmapButton * b, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; PUBLIC(that)->saveHomePosition(); } void SoWinFullViewerP::viewallbuttonProc(SoWinBitmapButton * b, void * userdata) { SoWinFullViewerP * that = (SoWinFullViewerP *)userdata; PUBLIC(that)->viewAll(); } int SoWinFullViewerP::layoutWidgets(int cx, int cy) { int x, y, width, height, bottom, right, top; const int numViewerButtons = this->righttrimbuttons.getLength(); const int numAppButtons = this->lefttrimbuttons.getLength(); HWND renderArea = PUBLIC(this)->getBaseWidget(); UINT flags = SWP_NOSIZE | SWP_NOZORDER | SWP_NOREDRAW; // RenderArea assert(IsWindow(renderArea)); if (this->decorations) { Win32::SetWindowPos(renderArea, NULL, DECORATION_SIZE, 0, 0, 0, flags); } else { Win32::SetWindowPos(renderArea, NULL, 0, 0, 0, 0, flags); return 0; } // Viewer buttons int i; for(i = 0; i < numViewerButtons; i++) this->viewerButton(i)->move(cx - DECORATION_SIZE, DECORATION_SIZE * i); // App buttons for(i = 0; i < numAppButtons; i++) { Win32::MoveWindow(this->appButton(i), 0, DECORATION_SIZE * i, DECORATION_SIZE, DECORATION_SIZE, TRUE); } // Wheels bottom = (cy - (DECORATION_SIZE + DECORATION_BUFFER)); right = (cx - ((this->rightthumbwheel ? this->rightthumbwheel->getLabelSize().cx : 0) + 8)); // Left wheel if (this->leftthumbwheel) { x = (DECORATION_SIZE / 2) - (this->leftthumbwheel->sizeHint().cx / 2) - 1; width = this->leftthumbwheel->sizeHint().cx; top = numAppButtons * DECORATION_SIZE + DECORATION_BUFFER; // if area is large enough for full height if ((bottom - top) > this->leftthumbwheel->sizeHint().cy) { height = this->leftthumbwheel->sizeHint().cy; y = bottom - height; } // else we must use all available space else { y = top; height = bottom - top; } this->leftthumbwheel->move(x, y, width, height); } // Bottom wheel if (this->bottomthumbwheel) { x += this->leftthumbwheel->getLabelSize().cx + this->bottomthumbwheel->getLabelSize().cx + 8; y = (cy - DECORATION_SIZE) + ((DECORATION_SIZE / 2) - (this->bottomthumbwheel->sizeHint().cy / 2) + 1); height = this->bottomthumbwheel->sizeHint().cy; if (right < (x + this->bottomthumbwheel->sizeHint().cx)) { width = right - x; } else { width = this->bottomthumbwheel->sizeHint().cx; } this->bottomthumbwheel->move(x, y, width, height); } // Right wheel if (this->rightthumbwheel) { width = this->rightthumbwheel->sizeHint().cx; x = (cx - DECORATION_SIZE) + ((DECORATION_SIZE / 2) - (width / 2) + 1); top = numViewerButtons * DECORATION_SIZE + DECORATION_BUFFER; // if area is large enough for original height if ((bottom - top) > this->rightthumbwheel->sizeHint().cy) { height = this->rightthumbwheel->sizeHint().cy; y = bottom - height; } // else we must use all available space else { y = top; height = bottom - top; } this->rightthumbwheel->move(x, y, width, height); } return 0; } void SoWinFullViewerP::showDecorationWidgets(SbBool enable) { const int numViewerButtons = this->righttrimbuttons.getLength(); const int numAppButtons = this->lefttrimbuttons.getLength(); // Viewer buttons int i; for(i = 0; i < numViewerButtons; i++) { (void)ShowWindow(this->viewerButton(i)->getWidget(), (enable ? SW_SHOW : SW_HIDE)); } // App buttons for(i = 0; i < numAppButtons; i++) { (void)ShowWindow(this->appButton(i), (enable ? SW_SHOW : SW_HIDE)); } // Thumbwheels if (enable) { this->leftthumbwheel->show(); this->bottomthumbwheel->show(); this->rightthumbwheel->show(); } else { this->leftthumbwheel->hide(); this->bottomthumbwheel->hide(); this->rightthumbwheel->hide(); } } LRESULT CALLBACK SoWinFullViewerP::systemEventHook(int code, WPARAM wparam, LPARAM lparam) { // FIXME: if I'm not mistaken, this message hook catches ~ all // messages in our process, for _all_ windows / widgets. This is // superbly inefficient, and should be cleaned up. 20030424 mortene. CWPSTRUCT * msg = (CWPSTRUCT *)lparam; void * comp; SbBool found = SoWinFullViewerP::parentHWNDmappings->find((SbDict::Key)msg->hwnd, comp); if (found) { SoWinFullViewer * object = (SoWinFullViewer *)comp; // According to MSVC++ Win32 API doc on CallWndProc(), if code<0 // we should not do any processing -- just pass message along to // next hook. if (code >= 0) { // FIXME: if code==HC_ACTION the Win32 API doc says we _must_ // process the message. Weird. Try to find out what that really // means. 20011126 mortene. switch (msg->message) { case WM_SETCURSOR: SoWinComponent::setWidgetCursor(object->getRenderAreaWidget(), PRIVATE(object)->cursor); break; case WM_LBUTTONDOWN: case WM_SETFOCUS: if ( object->isStealFocus() ) (void)Win32::SetFocus(object->getGLWidget()); break; } } } HHOOK * hookhandle = (HHOOK *) SoWinFullViewerP::hookhandle->get(); return CallNextHookEx(*hookhandle, code, wparam, lparam); } // ************************************************************************* void SoWinFullViewer::createViewerButtons(HWND parent, SbPList * buttonlist) { SoWinBitmapButton * button = new SoWinBitmapButton(parent, 24, "pick", NULL); button->addBitmap(pick_xpm); button->setBitmap(0); // use first (and only) bitmap button->registerClickedProc(SoWinFullViewerP::interactbuttonProc, PRIVATE(this)); buttonlist->append(button); button->setPressedState(this->isViewing() ? FALSE : TRUE); button = new SoWinBitmapButton(parent, 24, "view", NULL); button->addBitmap(view_xpm); button->setBitmap(0); // use first (and only) bitmap button->registerClickedProc(SoWinFullViewerP::examinebuttonProc, PRIVATE(this)); buttonlist->append(button); button->setPressedState(this->isViewing()); button = new SoWinBitmapButton(parent, 24, "home", NULL); button->addBitmap(home_xpm); button->setBitmap(0); // use first (and only) bitmap button->registerClickedProc(SoWinFullViewerP::homebuttonProc, PRIVATE(this)); buttonlist->append(button); button = new SoWinBitmapButton(parent, 24, "set_home", NULL); button->addBitmap(set_home_xpm); button->setBitmap(0); button->registerClickedProc(SoWinFullViewerP::sethomebuttonProc, PRIVATE(this)); buttonlist->append(button); button = new SoWinBitmapButton(parent, 24, "view_all", NULL); button->addBitmap(view_all_xpm); button->setBitmap(0); // use first (and only) bitmap button->registerClickedProc(SoWinFullViewerP::viewallbuttonProc, PRIVATE(this)); buttonlist->append(button); button = new SoWinBitmapButton(parent, 24, "seek", NULL); button->addBitmap(seek_xpm); button->setBitmap(0); // use first (and only) bitmap button->registerClickedProc(SoWinFullViewerP::seekbuttonProc, PRIVATE(this)); buttonlist->append(button); } // FIXME: the build*Trim() functions are present and working in the // other So* toolkits, but are unimplemented missing in SoWin. Why? // 20020111 mortene. HWND SoWinFullViewer::buildLeftTrim(HWND parent) { return NULL; } HWND SoWinFullViewer::buildBottomTrim(HWND parent) { return NULL; } HWND SoWinFullViewer::buildRightTrim(HWND parent) { return NULL; } // ************************************************************************* SoWinFullViewerP::SoWinFullViewerP(SoWinFullViewer * publ) : SoGuiFullViewerP(publ) { } SoWinFullViewerP::~SoWinFullViewerP() { const int len = this->righttrimbuttons.getLength(); for (int i = 0; i < len; i++) { delete (SoWinBitmapButton *)this->righttrimbuttons[i]; } if (this->leftthumbwheel) delete this->leftthumbwheel; if (this->rightthumbwheel) delete this->rightthumbwheel; if (this->bottomthumbwheel) delete this->bottomthumbwheel; } SoWinBitmapButton * SoWinFullViewerP::viewerButton(int idx) { if (this->righttrimbuttons.getLength() <= idx) { return NULL; } return (SoWinBitmapButton *)this->righttrimbuttons[idx]; } HWND SoWinFullViewerP::appButton(int idx) { if (this->lefttrimbuttons.getLength() <= idx) { return NULL; } return (HWND)this->lefttrimbuttons[idx]; } void SoWinFullViewerP::setThumbWheelValue(void * wheel, float val) { SoWinThumbWheel * twheel = SoWinThumbWheel::getWheelFromHWND((HWND)wheel); assert(twheel != NULL); twheel->setValue(val); } #endif // !DOXYGEN_SKIP_THIS // *************************************************************************
30.09713
125
0.665102
[ "object" ]
8187b8dcaf4279814c9b1c9d025567e8222fba33
2,576
cpp
C++
android/android_9/frameworks/ml/nn/driver/sample/SampleDriverAll.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/ml/nn/driver/sample/SampleDriverAll.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/ml/nn/driver/sample/SampleDriverAll.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "SampleDriverAll" #include "SampleDriver.h" #include "HalInterfaces.h" #include "Utils.h" #include "ValidateHal.h" #include <android-base/logging.h> #include <hidl/LegacySupport.h> #include <thread> namespace android { namespace nn { namespace sample_driver { class SampleDriverAll : public SampleDriver { public: SampleDriverAll() : SampleDriver("sample-all") {} Return<void> getCapabilities_1_1(getCapabilities_1_1_cb cb) override; Return<void> getSupportedOperations_1_1(const V1_1::Model& model, getSupportedOperations_1_1_cb cb) override; }; Return<void> SampleDriverAll::getCapabilities_1_1(getCapabilities_1_1_cb cb) { android::nn::initVLogMask(); VLOG(DRIVER) << "getCapabilities()"; Capabilities capabilities = {.float32Performance = {.execTime = 1.1f, .powerUsage = 1.1f}, .quantized8Performance = {.execTime = 1.1f, .powerUsage = 1.1f}, .relaxedFloat32toFloat16Performance = {.execTime = 1.1f, .powerUsage = 1.1f}}; cb(ErrorStatus::NONE, capabilities); return Void(); } Return<void> SampleDriverAll::getSupportedOperations_1_1(const V1_1::Model& model, getSupportedOperations_1_1_cb cb) { VLOG(DRIVER) << "getSupportedOperations()"; if (validateModel(model)) { const size_t count = model.operations.size(); std::vector<bool> supported(count, true); cb(ErrorStatus::NONE, supported); } else { std::vector<bool> supported; cb(ErrorStatus::INVALID_ARGUMENT, supported); } return Void(); } } // namespace sample_driver } // namespace nn } // namespace android using android::nn::sample_driver::SampleDriverAll; using android::sp; int main() { sp<SampleDriverAll> driver(new SampleDriverAll()); return driver->run(); }
33.454545
97
0.665761
[ "vector", "model" ]
818839ed8ca40e3e23c54c3e41e05b257a0598b4
3,994
cc
C++
src/tasks/client-integrity-task.cc
muflihun/residue
4fb7506b72335bd931e1d6364d1d2690b5b0fcb5
[ "Apache-2.0" ]
18
2017-02-11T22:10:13.000Z
2018-10-07T00:46:45.000Z
src/tasks/client-integrity-task.cc
amrayn/residue
4fb7506b72335bd931e1d6364d1d2690b5b0fcb5
[ "Apache-2.0" ]
46
2017-03-21T06:22:44.000Z
2018-09-24T05:00:02.000Z
src/tasks/client-integrity-task.cc
amrayn/residue
4fb7506b72335bd931e1d6364d1d2690b5b0fcb5
[ "Apache-2.0" ]
5
2020-11-06T10:50:39.000Z
2021-11-06T01:47:18.000Z
// // client-integrity-task.cc // Residue // // Copyright 2017-present Amrayn Web Services // https://amrayn.com // // Author: @abumusamq // // 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 "tasks/client-integrity-task.h" #include <vector> #include "core/client.h" #include "core/configuration.h" #include "core/registry.h" #include "logging/log.h" using namespace residue; ClientIntegrityTask::ClientIntegrityTask(Registry* registry, unsigned int interval) : Task("ClientIntegrityTask", registry, interval) { } void ClientIntegrityTask::performCleanup(const std::string& clientId) { auto iter = m_registry->clients().find(clientId); if (iter == m_registry->clients().end()) { // This is possible in case of "unknown" return; } Client* client = &(iter->second); if (!client->isAlive()) { // Do not use m_registry.removeClient, instead, // manually remove as we need to manually increment // iterator as erase invalidates it std::lock_guard<std::recursive_mutex> lock(m_registry->mutex()); m_registry->clients().erase(iter); } else { if (!client->backupKey().empty()) { RVLOG(RV_WARNING) << "Removing backup key for [" << client->id() << "]"; client->setBackupKey(""); } } } void ClientIntegrityTask::execute() { auto* list = &(m_registry->clients()); for (auto clientIter = list->begin(); clientIter != list->end();) { Client* client = &(clientIter->second); if (!client->isAlive()) { std::lock_guard<std::mutex> pausedClientsLock(m_mutex); auto pos = m_pausedClients.find(client->id()); if (pos == m_pausedClients.end()) { // here we check for unmanaged clients // we may be removing a "paused" unmanaged client // as m_pausedClients for unmanaged client will be "unknown" if (!client->isManaged() && m_pausedClients.find(Configuration::UNMANAGED_CLIENT_ID) != m_pausedClients.end()) { // yes we are surely removing a paused unmanaged client // that we shouldn't do RLOG(INFO) << "Unmanaged client [" << client->id() << "] expired - Paused removal"; ++clientIter; // skip and move on } else { RLOG(INFO) << "Client [" << client->id() << "] expired"; // Do not use m_registry.removeClient, instead, // manually remove as we need to manually increment // iterator as erase invalidates it std::lock_guard<std::recursive_mutex> lock(m_registry->mutex()); m_registry->clients().erase(clientIter++); } } else { RLOG(INFO) << "Client [" << client->id() << "] expired - Paused removal"; ++clientIter; // skip and move on } } else { if (!client->backupKey().empty()) { RVLOG(RV_WARNING) << "Removing backup key for [" << client->id() << "]"; client->setBackupKey(""); } ++clientIter; } } if (!m_registry->configuration()->hasFlag(Configuration::Flag::REQUIRES_TIMESTAMP)) { RLOG(WARNING) << "You have disabled 'requires_timestamp'. Your server is prone to replay attack."; } }
37.679245
128
0.585628
[ "vector" ]
818cdcb64b2fb72af2e3239951f7fb52fdc20eeb
5,098
hpp
C++
openstudiocore/src/model/CoilCoolingLowTempRadiantVarFlow_Impl.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/model/CoilCoolingLowTempRadiantVarFlow_Impl.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/model/CoilCoolingLowTempRadiantVarFlow_Impl.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_COILCOOLINGLOWTEMPRADIANTVARFLOW_IMPL_HPP #define MODEL_COILCOOLINGLOWTEMPRADIANTVARFLOW_IMPL_HPP #include <model/ModelAPI.hpp> #include <model/StraightComponent_Impl.hpp> namespace openstudio { namespace model { class Schedule; namespace detail { /** CoilCoolingLowTempRadiantVarFlow_Impl is a StraightComponent_Impl that is the implementation class for CoilCoolingLowTempRadiantVarFlow.*/ class MODEL_API CoilCoolingLowTempRadiantVarFlow_Impl : public StraightComponent_Impl { Q_OBJECT public: /** @name Constructors and Destructors */ //@{ CoilCoolingLowTempRadiantVarFlow_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); CoilCoolingLowTempRadiantVarFlow_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); CoilCoolingLowTempRadiantVarFlow_Impl(const CoilCoolingLowTempRadiantVarFlow_Impl& other, Model_Impl* model, bool keepHandle); virtual ~CoilCoolingLowTempRadiantVarFlow_Impl() {} //@} /** @name Virtual Methods */ //@{ virtual const std::vector<std::string>& outputVariableNames() const; virtual IddObjectType iddObjectType() const; virtual std::vector<ScheduleTypeKey> getScheduleTypeKeys(const Schedule& schedule) const; virtual unsigned inletPort(); virtual unsigned outletPort(); virtual boost::optional<ZoneHVACComponent> containingZoneHVACComponent() const; //@} /** @name Getters */ //@{ boost::optional<double> maximumColdWaterFlow() const; bool isMaximumColdWaterFlowDefaulted() const; bool isMaximumColdWaterFlowAutosized() const; double coolingControlThrottlingRange() const; bool isCoolingControlThrottlingRangeDefaulted() const; boost::optional<Schedule> coolingControlTemperatureSchedule() const; std::string condensationControlType() const; bool isCondensationControlTypeDefaulted() const; double condensationControlDewpointOffset() const; bool isCondensationControlDewpointOffsetDefaulted() const; //@} /** @name Setters */ //@{ bool setMaximumColdWaterFlow(boost::optional<double> maximumColdWaterFlow); void resetMaximumColdWaterFlow(); void autosizeMaximumColdWaterFlow(); bool setCoolingControlThrottlingRange(double coolingControlThrottlingRange); void resetCoolingControlThrottlingRange(); bool setCoolingControlTemperatureSchedule(Schedule& schedule); void resetCoolingControlTemperatureSchedule(); bool setCondensationControlType(std::string condensationControlType); void resetCondensationControlType(); void setCondensationControlDewpointOffset(double condensationControlDewpointOffset); void resetCondensationControlDewpointOffset(); //@} /** @name Other */ //@{ bool addToNode(Node & node); //@} protected: private: REGISTER_LOGGER("openstudio.model.CoilCoolingLowTempRadiantVarFlow"); std::vector<std::string> condensationControlTypeValues() const; //boost::optional<ModelObject> coolingWaterInletNodeAsModelObject() const; //boost::optional<ModelObject> coolingWaterOutletNodeAsModelObject() const; boost::optional<ModelObject> coolingControlTemperatureScheduleAsModelObject() const; //bool setCoolingWaterInletNodeAsModelObject(const boost::optional<ModelObject>& modelObject); //bool setCoolingWaterOutletNodeAsModelObject(const boost::optional<ModelObject>& modelObject); bool setCoolingControlTemperatureScheduleAsModelObject(const boost::optional<ModelObject>& modelObject); }; } // detail } // model } // openstudio #endif // MODEL_COILCOOLINGLOWTEMPRADIANTVARFLOW_IMPL_HPP
33.761589
143
0.681248
[ "vector", "model" ]
819119c0d9442bfda5189057ed206382a88c6d22
1,806
cpp
C++
figures/src/PCP/Curvature/Curvature.cpp
STORM-IRIT/algebraic-shape-operator
8de592549562cf8cff51044a459ce64a75176e42
[ "MIT" ]
4
2021-07-29T18:19:36.000Z
2022-02-12T12:42:52.000Z
figures/src/PCP/Curvature/Curvature.cpp
STORM-IRIT/algebraic-shape-operator
8de592549562cf8cff51044a459ce64a75176e42
[ "MIT" ]
2
2021-07-12T08:51:46.000Z
2021-07-14T09:38:17.000Z
figures/src/PCP/Curvature/Curvature.cpp
STORM-IRIT/algebraic-shape-operator
8de592549562cf8cff51044a459ce64a75176e42
[ "MIT" ]
4
2021-07-12T08:52:53.000Z
2021-09-17T11:40:21.000Z
#include <PCP/Curvature/Curvature.h> #include <PCP/Curvature/GlobalEstimationData.h> #include <PCP/Geometry/Geometry.h> #include <PCP/Common/Progress.h> #include <PCP/Common/Macro.h> namespace pcp { // --------> Name ori. H N k k_si. dir MethodProperties CurvatureComputer_PSS ::method_properties() const {return {"PSS", false, true, true, true, true, true };} MethodProperties CurvatureComputer_OJets ::method_properties() const {return {"OJets", false, true, true, true, true, true };} MethodProperties CurvatureComputer_WJets ::method_properties() const {return {"WJets", false, true, true, true, true, true };} MethodProperties CurvatureComputer_Barycenter::method_properties() const {return {"Barycenter", false, true, false, false, false, false};} MethodProperties CurvatureComputer_PCAPlane ::method_properties() const {return {"PCAPlane", false, true, true, false, false, true };} MethodProperties CurvatureComputer_APSS ::method_properties() const {return {"APSS", true, true, true, false, false, false};} MethodProperties CurvatureComputer_ASO ::method_properties() const {return {"ASO", true, true, true, true, true, true };} void GlobalCurvatureComputer::compute(const Geometry& points, Scalar r, GlobalEstimationData& estimations, bool b) { estimations.resize(points.size()); auto prog = Progress(points.size(), b); #pragma omp parallel for for(int i=0; i<points.size(); ++i) { estimations[i] = m_computer->compute(points, i, r); ++prog; } } } // namespace pcp
47.526316
138
0.612957
[ "geometry" ]
8191e6d0fa08b5076e95dbac34b48860592c52a5
65,305
cpp
C++
lib/src/mask/mergerMask.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
lib/src/mask/mergerMask.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
lib/src/mask/mergerMask.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "mergerMask.hpp" #include "seamFinder.hpp" #include "core/controllerInputFrames.hpp" #include "core1/bounds.hpp" #include "core1/imageMapping.hpp" #include "core1/imageMerger.hpp" #include "core1/panoRemapper.hpp" #include "core1/inputsMap.hpp" #include "core1/imageMerger.hpp" #include "core1/textureTarget.hpp" #include "gpu/allocator.hpp" #include "gpu/core1/strip.hpp" #include "gpu/core1/transform.hpp" #include "gpu/core1/voronoi.hpp" #include "gpu/uniqueBuffer.hpp" #include "gpu/stream.hpp" #include "gpu/memcpy.hpp" #include "gpu/image/sampling.hpp" #include "gpu/image/blur.hpp" #include "util/registeredAlgo.hpp" #include "util/compressionUtils.hpp" #include "util/imageProcessingGPUUtils.hpp" #include <unordered_set> #include <vector> //#define MERGERMASK_SETUP_DISTORTIONMAP //#define MERGERMASK_SETUP_MAPPEDRECT //#define MERGERMASK_SETUP_FRAMES //#define MERGERMASK_GET_MERGERMASKS //#define MERGERMASK_GET_MERGERMASKS_FULL //#define MERGERMASK_GET_MERGERMASKS_FINAL //#define MERGERMASK_INPUT_SPACE //#define MERGERMASK_SEAM_INPUT //#define MERGERMASK_SEAM_OPTIMIZATION //#define MERGERMASK_SEAM_MASK #if defined(MERGERMASK_SETUP_MAPPEDRECT) || defined(MERGERMASK_SEAM_OPTIMIZATION) || defined(MERGERMASK_SEAM_MASK) || \ defined(MERGERMASK_SEAM_INPUT) || defined(MERGERMASK_GET_MERGERMASKS_FINAL) || defined(MERGERMASK_INPUT_SPACE) #ifdef NDEBUG #error "This is not supposed to be included in non-debug mode." #endif #include "backend/cuda/deviceBuffer.hpp" #include "backend/cuda/deviceStream.hpp" #endif #if defined(MERGERMASK_GET_MERGERMASKS_FULL) || defined(MERGERMASK_SETUP_FRAMES) || \ defined(MERGERMASK_SETUP_DISTORTIONMAP) || defined(MERGERMASK_GET_MERGERMASKS) || \ defined(MERGERMASK_SEAM_OPTIMIZATION) || defined(MERGERMASK_SEAM_MASK) || defined(MERGERMASK_SEAM_INPUT) || \ defined(MERGERMASK_GET_MERGERMASKS_FINAL) || defined(MERGERMASK_INPUT_SPACE) #ifdef NDEBUG #error "This is not supposed to be included in non-debug mode." #endif #include "util/pngutil.hpp" #include "util/pnm.hpp" #include "util/debugUtils.hpp" #include "util/opticalFlowUtils.hpp" #endif namespace VideoStitch { namespace MergerMask { Potential<MergerMask> MergerMask::create(const std::map<readerid_t, Input::VideoReader*>& readers, const Core::PanoDefinition& pano, const Core::StereoRigDefinition* rigDef, const MergerMaskConfig& config, const MergerMaskProgress& progress) { std::unique_ptr<MergerMask> mergerMask; mergerMask.reset(new MergerMask(pano, rigDef, config, progress)); FAIL_RETURN(mergerMask->setup(readers)); return mergerMask.release(); } MergerMask::MergerMask(const Core::PanoDefinition& pano, const Core::StereoRigDefinition* rigDef, const MergerMaskConfig& config, const MergerMaskProgress& progress) : pano(pano), rigDef(rigDef), mergerMaskConfig(config), // downsamplingLevelCount(getDownLevel(pano, (int)config.getSizeThreshold())), downsamplingLevelCount(0), progress(progress) {} MergerMask::~MergerMask() { for (size_t i = 0; i < imageMappings.size(); i++) { delete imageMappings[(int)i]; } imageMappings.clear(); for (size_t i = 0; i < transforms.size(); i++) { delete transforms[(int)i]; } transforms.clear(); for (size_t i = 0; i < distortionMaps.size(); i++) { distortionMaps[(int)i].release(); } for (size_t i = 0; i < originalDistortionMaps.size(); i++) { originalDistortionMaps[(int)i].release(); } distortionMaps.clear(); originalDistortionMaps.clear(); } int MergerMask::getDownSize(const int size) const { int level = downsamplingLevelCount; int downSize = size; while (level > 0) { downSize = (downSize + 1) / 2; level--; } return downSize; } int MergerMask::getDownCoord(const int coord) const { int level = downsamplingLevelCount; float downCoord = (float)coord; while (level > 0) { downCoord = (downCoord + 1.0f) / 2.0f; level--; } return (int)downCoord; } int MergerMask::getDownLevel(const Core::PanoDefinition& pano, const int sizeThreshold) { int width = (int)pano.getWidth(); int height = (int)pano.getHeight(); int level = 0; while (width > sizeThreshold || height > sizeThreshold) { width = (width + 1) / 2; height = (height + 1) / 2; level++; } return level; } Status MergerMask::setupMappings(const std::map<readerid_t, Input::VideoReader*>& readers) { // Prepare input maps GPU::Stream stream = GPU::Stream::getDefault(); std::unique_ptr<Core::InputsMap> inputsMap; Potential<Core::InputsMap> potInputsMap = Core::InputsMap::create(pano); FAIL_RETURN(potInputsMap.status()); inputsMap = std::unique_ptr<Core::InputsMap>(potInputsMap.release()); FAIL_RETURN(inputsMap->compute(readers, pano, rigDef, LeftEye, false)); // Create the mappers. imageMappings.clear(); for (auto reader : readers) { imageMappings[reader.second->id] = new Core::ImageMapping(reader.second->id); } // Prepare mappings auto tmpDevBuffer = GPU::Buffer<uint32_t>::allocate(size_t(std::max(pano.getWidth(), pano.getHeight())), "Input Bounding boxes"); FAIL_RETURN(tmpDevBuffer.status()); auto tmpHostBuffer = GPU::HostBuffer<uint32_t>::allocate((unsigned)std::max(pano.getWidth(), pano.getHeight()), "Input Bounding boxes"); FAIL_RETURN(tmpHostBuffer.status()); FAIL_RETURN(computeHBounds(Core::EQUIRECTANGULAR, pano.getWidth(), pano.getHeight(), imageMappings, rigDef, LeftEye, inputsMap->getMask(), tmpHostBuffer.value(), tmpDevBuffer.value(), stream, true)); FAIL_RETURN(computeVBounds(Core::EQUIRECTANGULAR, pano.getWidth(), pano.getHeight(), imageMappings, inputsMap->getMask(), tmpHostBuffer.value(), tmpDevBuffer.value(), stream)); int devWidth = (int)pano.getWidth(); int devHeight = (int)pano.getHeight(); // Duplicate the original inputs map FAIL_RETURN(inputsMapOriginalBuffer.alloc(devWidth * devHeight, "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(inputsMapOriginalBuffer.borrow(), inputsMap->getMask(), devWidth * devHeight * sizeof(uint32_t))); #ifdef MERGERMASK_GET_MERGERMASKS_FULL { std::stringstream ss; ss.str(""); ss << "input-full-index.png"; Debug::dumpRGBAIndexDeviceBuffer<uint32_t>(ss.str().c_str(), inputsMapOriginalBuffer.borrow_const(), devWidth, devHeight); for (int i = 0; i < pano.numInputs(); i++) { std::stringstream ss; ss.str(""); ss << "input-full-index" << i << ".png"; Debug::dumpRGBAIndexDeviceBuffer<uint32_t>(ss.str().c_str(), inputsMapOriginalBuffer.borrow_const(), devWidth, devHeight, i); } } #endif // Generate the down-sampled inputs map FAIL_RETURN(Util::ImageProcessingGPU::downSampleImages<uint32_t>(downsamplingLevelCount, devWidth, devHeight, inputsMap->getMask(), stream, true)); FAIL_RETURN(inputsMapBuffer.alloc(devWidth * devHeight, "Merger Mask")); FAIL_RETURN( GPU::memcpyBlocking(inputsMapBuffer.borrow(), inputsMap->getMask(), devWidth * devHeight * sizeof(uint32_t))); FAIL_RETURN(tmpHostBuffer.value().release()); FAIL_RETURN(tmpDevBuffer.value().release()); return Status::OK(); } Status MergerMask::setupTransform(const std::map<readerid_t, Input::VideoReader*>& readers) { // Prepare transform for (auto reader : readers) { const Core::InputDefinition& inputDef = pano.getInput(reader.second->id); Core::Transform* transform = Core::Transform::create(inputDef); if (!transform) { return {Origin::Stitcher, ErrType::SetupFailure, "Cannot create v1 transformation for input " + std::to_string(reader.second->id)}; } transforms[reader.second->id] = transform; } return Status::OK(); } Status MergerMask::setupDistortionMap() { // Prepare distortion maps GPU::Stream stream = GPU::Stream::getDefault(); for (auto transform : transforms) { Core::ImageMapping* mapping = imageMappings[transform.first]; auto potDevOut = GPU::uniqueBuffer<unsigned char>(mapping->getOutputRect(Core::EQUIRECTANGULAR).getArea(), "Merger Mask Algorithm"); FAIL_RETURN(potDevOut.status()); const Core::InputDefinition& im = pano.getInput(transform.first); FAIL_RETURN(transform.second->mapDistortion(0, potDevOut.borrow(), mapping->getOutputRect(Core::EQUIRECTANGULAR), pano, im, stream)); int devWidth = (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getWidth(); int devHeight = (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getHeight(); FAIL_RETURN(updateDistortionFromMask((int)transform.first, make_int2(devWidth, devHeight), make_int2((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).left(), (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).top()), potDevOut.borrow(), make_int2((int)pano.getWidth(), (int)pano.getHeight()), inputsMapOriginalBuffer.borrow_const(), stream)); #ifdef MERGERMASK_SETUP_DISTORTIONMAP { std::stringstream ss; ss.str(""); ss << "distortion-ori" << i << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), potDevOut.borrow_const(), mapping->getOutputRect().getWidth(), mapping->getOutputRect().getHeight()); } #endif // Down-sampling the image to the appropriate level auto originalCacheBuffer = GPU::uniqueBuffer<unsigned char>(devWidth * devHeight, "Merger Mask Algorithm"); FAIL_RETURN(originalCacheBuffer.status()); FAIL_RETURN(GPU::memcpyBlocking<unsigned char>(originalCacheBuffer.borrow(), potDevOut.borrow_const(), devWidth * devHeight * sizeof(unsigned char))); FAIL_RETURN(Util::ImageProcessingGPU::downSampleImages<unsigned char>(downsamplingLevelCount, devWidth, devHeight, potDevOut.borrow(), stream, false)); // Put the down-sampled image into the cached map auto cacheBuffer = GPU::uniqueBuffer<unsigned char>(devWidth * devHeight, "Merger Mask Algorithm"); FAIL_RETURN(cacheBuffer.status()); FAIL_RETURN(GPU::memcpyBlocking<unsigned char>(cacheBuffer.borrow(), potDevOut.borrow().as_const(), devWidth * devHeight * sizeof(unsigned char))); FAIL_RETURN(transformDistortion(make_int2(devWidth, devHeight), cacheBuffer.borrow(), stream)); #ifdef MERGERMASK_SETUP_DISTORTIONMAP { std::stringstream ss; ss.str(""); ss << "distortion-" << i << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), cacheBuffer.borrow().as_const(), devWidth, devHeight); } #endif distortionMaps[transform.first] = cacheBuffer.releaseOwnership(); originalDistortionMaps[transform.first] = originalCacheBuffer.releaseOwnership(); } return Status::OK(); } Status MergerMask::setupMappedRect() { // Precompute data for the low res cachedMappedRects.clear(); std::vector<int2> rectOffset; std::vector<int2> rectSize; std::vector<uint32_t> frameOffsets; int offset = 0; // Precompute data for the original res cachedOriginalMappedRects.clear(); std::vector<int2> originalRectOffset; std::vector<int2> originalRectSize; std::vector<uint32_t> originalFrameOffsets; int originalOffset = 0; for (auto transform : transforms) { Core::ImageMapping* mapping = imageMappings[transform.first]; // Data for the original res cachedOriginalMappedRects.push_back(mapping->getOutputRect(Core::EQUIRECTANGULAR)); originalRectOffset.push_back(make_int2((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).left(), (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).top())); originalRectSize.push_back(make_int2((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getWidth(), (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getHeight())); originalFrameOffsets.push_back(originalOffset); originalOffset += (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getArea(); // Data for the low res int devWidth = (int)getDownSize((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getWidth()); int devHeight = (int)getDownSize((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getHeight()); int devLeft = (int)getDownCoord((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).left()); int devTop = (int)getDownCoord((int)mapping->getOutputRect(Core::EQUIRECTANGULAR).top()); cachedMappedRects.push_back( Core::Rect::fromInclusiveTopLeftBottomRight(devTop, devLeft, devTop + devHeight - 1, devLeft + devWidth - 1)); rectOffset.push_back(make_int2(devLeft, devTop)); rectSize.push_back(make_int2(devWidth, devHeight)); frameOffsets.push_back(offset); offset += devWidth * devHeight; } // For the original images FAIL_RETURN(originalMappedRectOffset.alloc(pano.numInputs(), "Merger Mask")); FAIL_RETURN(originalMappedRectSize.alloc(pano.numInputs(), "Merger Mask")); FAIL_RETURN(originalMappedOffset.alloc(pano.numInputs(), "Merger Mask")); FAIL_RETURN( GPU::memcpyBlocking(originalMappedRectOffset.borrow(), &originalRectOffset[0], transforms.size() * sizeof(int2))); FAIL_RETURN( GPU::memcpyBlocking(originalMappedRectSize.borrow(), &originalRectSize[0], transforms.size() * sizeof(int2))); FAIL_RETURN(GPU::memcpyBlocking(originalMappedOffset.borrow(), &originalFrameOffsets[0], transforms.size() * sizeof(uint32_t))); // For the resize caches FAIL_RETURN(mappedRectOffset.alloc(pano.numInputs(), "Merger Mask")); FAIL_RETURN(mappedRectSize.alloc(pano.numInputs(), "Merger Mask")); FAIL_RETURN(mappedOffset.alloc(pano.numInputs(), "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(mappedRectOffset.borrow(), &rectOffset[0], transforms.size() * sizeof(int2))); FAIL_RETURN(GPU::memcpyBlocking(mappedRectSize.borrow(), &rectSize[0], transforms.size() * sizeof(int2))); FAIL_RETURN(GPU::memcpyBlocking(mappedOffset.borrow(), &frameOffsets[0], transforms.size() * sizeof(uint32_t))); #ifdef MERGERMASK_SETUP_MAPPEDRECT std::vector<int2> debugRectOffset(transforms.size()); std::vector<int2> debugRectSize(transforms.size()); std::vector<uint32_t> debugFrameOffsets(transforms.size()); cudaMemcpy(&debugRectOffset[0], mappedRectOffset.borrow_const().get(), transforms.size() * sizeof(int2), cudaMemcpyDeviceToHost); cudaMemcpy(&debugRectSize[0], mappedRectSize.borrow_const().get(), transforms.size() * sizeof(int2), cudaMemcpyDeviceToHost); cudaMemcpy(&debugFrameOffsets[0], mappedOffset.borrow_const().get(), transforms.size() * sizeof(uint32_t), cudaMemcpyDeviceToHost); #endif return Status::OK(); } Status MergerMask::setup(const std::map<readerid_t, Input::VideoReader*>& readers) { FAIL_RETURN(setupMappings(readers)); FAIL_RETURN(setupTransform(readers)); FAIL_RETURN(setupMappedRect()); FAIL_RETURN(setupDistortionMap()); FAIL_RETURN(setupOverlappingPair()); FAIL_RETURN(setupFrames()); FAIL_RETURN(progress.add("coarseMask_setup", "Setup blending mask")); return Status::OK(); } Status MergerMask::retrieveImages(const std::vector<unsigned int>& frames, FrameBuffers& frameBuffers, const Core::PanoDefinition& pano) { frameBuffers.clear(); auto container = Core::ControllerInputFrames<PixelFormat::RGBA, uint32_t>::create(&pano); FAIL_RETURN(container.status()); for (auto& numFrame : frames) { FAIL_RETURN(container->seek((int)numFrame)); std::map<readerid_t, PotentialValue<GPU::HostBuffer<uint32_t>>> loadedFrames; container->load(loadedFrames); for (auto& loadedFrame : loadedFrames) { readerid_t inputid = loadedFrame.first; if (inputid > (int)pano.numInputs()) { continue; } auto potLoadedFrame = loadedFrame.second; FAIL_RETURN(potLoadedFrame.status()); GPU::HostBuffer<uint32_t> frame = potLoadedFrame.value(); /* Get the size of the current image */ const Core::InputDefinition& idef = pano.getInput(inputid); const int width = (int)idef.getWidth(); const int height = (int)idef.getHeight(); const size_t frameSize = (size_t)(width * height * sizeof(uint32_t)); std::pair<size_t, size_t> id = std::make_pair(inputid, numFrame); auto frameBuffer = GPU::uniqueBuffer<uint32_t>(width * height, "Merger Mask Algorithm"); FAIL_RETURN(frameBuffer.status()); FAIL_RETURN(GPU::memcpyBlocking(frameBuffer.borrow(), frame.hostPtr(), frameSize)); frameBuffers[id] = frameBuffer.releaseValue(); } } return Status::OK(); } Status MergerMask::setupFrames() { const std::vector<unsigned int> frames = mergerMaskConfig.getFrames(); FrameBuffers frameBuffers; FAIL_RETURN(retrieveImages(mergerMaskConfig.getFrames(), frameBuffers, pano)); #ifdef MERGERMASK_SETUP_FRAMES for (FrameBuffers::iterator it = frameBuffers.begin(); it != frameBuffers.end(); ++it) { const int frameid = it->first.first; const int camid = it->first.second; const Core::InputDefinition& idef = pano.getInput(camid); const int width = (int)idef.getWidth(); const int height = (int)idef.getHeight(); std::stringstream ss; ss << "inputImage-" << frameid << " " << camid << ".png"; Debug::dumpRGBADeviceBuffer(ss.str().c_str(), (it->second).borrow_const(), width, height); } #endif // Find the total number of element needed for a certain time frame int totalElementCount = 0; for (size_t i = 0; i < cachedMappedRects.size(); i++) { totalElementCount += (int)cachedMappedRects[i].getArea(); } const int width = getDownSize((int)pano.getWidth()); const int height = getDownSize((int)pano.getHeight()); FAIL_RETURN(work1.alloc(pano.getWidth() * pano.getHeight(), "Merger Mask")); FAIL_RETURN(work2.alloc(pano.getWidth() * pano.getHeight(), "Merger Mask")); FAIL_RETURN(workMask.alloc(pano.getWidth() * pano.getHeight(), "Merger Mask")); FAIL_RETURN(workCost.alloc(width * height, "Merger Mask")); // Allocate temporal memory for processing the mapped buffer auto potDevOut = GPU::uniqueBuffer<uint32_t>(pano.getWidth() * pano.getHeight(), "Merger Mask Algorithm"); FAIL_RETURN(potDevOut.status()); cachedMappedFrames.clear(); const int camCount = (int)pano.numInputs(); GPU::Stream stream = GPU::Stream::getDefault(); // For all frameid and camid, do the mapping for (size_t j = 0; j < frames.size(); j++) { auto cacheBuffer = GPU::uniqueBuffer<uint32_t>(totalElementCount, "Merger Mask"); FAIL_RETURN(cacheBuffer.status()); cachedMappedFrames.push_back(cacheBuffer.releaseValue()); int elementOffset = 0; for (int i = 0; i < camCount; i++) { Core::Transform* transform = transforms[i]; Core::ImageMapping* mapping = imageMappings[i]; const Core::InputDefinition& im = pano.getInput(i); const std::pair<size_t, size_t> inPair = std::make_pair(i, frames[j]); FrameBuffers::const_iterator it = frameBuffers.find(inPair); if (it != frameBuffers.end()) { const GPU::Buffer<const uint32_t> inputBuffer = it->second.borrow_const(); auto surface = Core::OffscreenAllocator::createSourceSurface(im.getWidth(), im.getHeight(), "Merger Mask"); FAIL_RETURN(GPU::memcpyAsync(*surface->pimpl->surface, inputBuffer, stream)); // Map the input to the output space transform->mapBuffer(frames[j], potDevOut.borrow(), *surface->pimpl->surface, nullptr, mapping->getOutputRect(Core::EQUIRECTANGULAR), pano, im, *surface->pimpl->surface, stream); // Down-sampling the image to the appropriate level int devWidth = (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getWidth(); int devHeight = (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getHeight(); #ifdef MERGERMASK_SETUP_FRAMES { std::stringstream ss; ss << "oriwarped-" << i << " " << frames[j] << ".png"; Debug::dumpRGB210DeviceBuffer(ss.str().c_str(), devOut.borrow_const(), devWidth, devHeight); } #endif Util::ImageProcessingGPU::downSampleImages(downsamplingLevelCount, devWidth, devHeight, potDevOut.borrow(), stream, false); // Put the down-sampled image into the cached map #ifdef MERGERMASK_SETUP_FRAMES { std::stringstream ss; ss << "warped-rgb210-" << i << " " << frames[j] << ".png"; Debug::dumpRGB210DeviceBuffer(ss.str().c_str(), devOut.borrow_const(), devWidth, devHeight); } #endif // Convert from rgb to lab GPU::Buffer<uint32_t> subBuffer = cachedMappedFrames.back().borrow().createSubBuffer(elementOffset); FAIL_RETURN(Util::ImageProcessingGPU::convertRGB210ToRGBandGradient( make_int2(devWidth, devHeight), potDevOut.borrow_const(), subBuffer, stream)); #ifdef MERGERMASK_SETUP_FRAMES { std::stringstream ss; ss << "warped-rgb-" << i << " " << frames[j] << ".png"; Debug::dumpRGBADeviceBuffer(ss.str().c_str(), devOut.borrow_const(), devWidth, devHeight); } #endif FAIL_RETURN(Util::ImageProcessingGPU::convertRGBandGradientToNormalizedLABandGradient( make_int2(devWidth, devHeight), subBuffer, stream)); #ifdef MERGERMASK_SETUP_FRAMES { std::stringstream ss; ss << "warped-" << i << " " << frames[j] << ".png"; Debug::dumpRGB210DeviceBuffer(ss.str().c_str(), subBuffer.as_const(), devWidth, devHeight); } { std::stringstream ss; ss << "gradient-" << i << " " << frames[j] << ".png"; GPU::UniqueBuffer<unsigned char> gradientBuffer; FAIL_RETURN(gradientBuffer.alloc(devWidth * devHeight, "Merger Mask")); FAIL_RETURN( extractChannel(make_int2(devWidth, devHeight), subBuffer.as_const(), 3, gradientBuffer.borrow(), stream)); Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), gradientBuffer.borrow_const(), devWidth, devHeight); } #endif elementOffset += (int)cachedMappedRects[i].getArea(); } } } return Status::OK(); } Status MergerMask::setupOverlappingPair() { // Prepare overlapping pair GPU::Stream stream = GPU::Stream::getDefault(); const GPU::Buffer<const uint32_t> mappingMask = inputsMapBuffer.borrow_const(); // Copy data from GPU to CPU PotentialValue<GPU::HostBuffer<uint32_t>> potHostBuffer = GPU::HostBuffer<uint32_t>::allocate(mappingMask.numElements(), "Mask Merger Graph"); FAIL_RETURN(potHostBuffer.status()); GPU::HostBuffer<uint32_t> mask = potHostBuffer.value(); FAIL_RETURN(GPU::memcpyBlocking(mask, mappingMask)); // Find the overlapping bit set std::unordered_set<uint32_t> overlappingValueSet; const uint32_t* maskPtr = mask.hostPtr(); for (size_t i = 0; i < mappingMask.numElements(); i++) { if (maskPtr[i] > 0) { if (overlappingValueSet.find(maskPtr[i]) == overlappingValueSet.end()) { overlappingValueSet.insert(maskPtr[i]); } } } // Find all pair mapping for (readerid_t i = 0; i < pano.numInputs(); i++) { isOverlapping.push_back(std::vector<int>(pano.numInputs(), 0)); } for (auto i = overlappingValueSet.begin(); i != overlappingValueSet.end(); i++) { uint32_t v = *i; std::vector<int> indices; // Find the set of indices int t = 0; while (v > 0) { if ((v & 1) > 0) { indices.push_back(t); } t++; v = v >> 1; } for (size_t i = 0; i < indices.size(); i++) for (size_t j = i + 1; j < indices.size(); j++) { isOverlapping[indices[i]][indices[j]]++; isOverlapping[indices[j]][indices[i]]++; } } mask.release(); return Status::OK(); } // Step (3c) Status MergerMask::getBlendingCost(const std::vector<int>& normalizedMaxOverlappingWidths, const int2& size, const std::vector<size_t>& allCam, const GPU::Buffer<const unsigned char>& inputDistortionBuffer, const GPU::Buffer<const uint32_t>& inputNonOverlappingIndexBuffer, GPU::Buffer<unsigned char> nextDistortionBuffer, GPU::Buffer<uint32_t> nextNonOverlappingIndexBuffer, GPU::Buffer<uint32_t> nextInputIndexBuffer, float& blendingCost) { GPU::Stream stream = GPU::Stream::getDefault(); const std::vector<unsigned int> frames = mergerMaskConfig.getFrames(); FAIL_RETURN(updateInputIndexByDistortionMap((int)allCam.back(), size, inputNonOverlappingIndexBuffer, inputDistortionBuffer, nextNonOverlappingIndexBuffer, nextDistortionBuffer, stream)); #ifdef MERGERMASK_GET_MERGERMASKS { std::stringstream ss; ss.str(""); ss << "trial-distortion-"; for (int i = 0; i < allCam.size(); i++) { ss << allCam[i] << "-"; } ss << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), nextDistortionBuffer.as_const(), size.x, size.y); } #endif // To make sure the overlapping area is small (for efficiency), reduce the new area's mask to less than a threshold // - (C3) Make sure that the overlapping width of image pairs is less than a certain threshold FAIL_RETURN(updateOverlappingMap(normalizedMaxOverlappingWidths, size, allCam, nextNonOverlappingIndexBuffer, nextInputIndexBuffer, stream)); // Thirdly, compute the image difference cost metric // Iterate over all frames const int kernelSize = mergerMaskConfig.getKernelSize(); // First, initialize the distortion cost FAIL_RETURN(GPU::memsetToZeroBlocking(workCost.borrow(), sizeof(float) * size.x * size.y)); // Now iterate over all frames and start accumulating the cost into buffers GPU::UniqueBuffer<uint32_t> debugBuffer0, debugBuffer1; FAIL_RETURN(debugBuffer0.alloc(size.x * size.y, "Merger Mask")); FAIL_RETURN(debugBuffer1.alloc(size.x * size.y, "Merger Mask")); for (size_t i = 0; i < frames.size(); i++) { FAIL_RETURN(updateStitchingCost(size, kernelSize, nextInputIndexBuffer.as_const(), mappedOffset.borrow_const(), mappedRectOffset.borrow_const(), mappedRectSize.borrow_const(), cachedMappedFrames[i].borrow_const(), workCost.borrow(), debugBuffer0.borrow(), debugBuffer1.borrow(), stream)); } #ifdef MERGERMASK_GET_MERGERMASKS { std::stringstream ss; /*ss.str(""); ss << "cost-map-"; for (int i = 0; i < prevCam.size(); i++) { ss << prevCam[i] << "-"; } ss << camId << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linearFloat>(ss.str().c_str(), workCost.borrow_const(), size.x, size.y); */ ss.str(""); ss << "cost-debug-map-zero-"; for (int i = 0; i < allCam.size(); i++) { ss << allCam[i] << "-"; } ss << ".png"; Debug::dumpRGBADeviceBuffer(ss.str().c_str(), debugBuffer0.borrow(), size.x, size.y); ss.str(""); ss << "cost-debug-map-one-"; for (int i = 0; i < allCam.size(); i++) { ss << allCam[i] << "-"; } ss << ".png"; Debug::dumpRGBAIndexDeviceBuffer<uint32_t>(ss.str().c_str(), debugBuffer1.borrow(), size.x, size.y); ss.str(""); ss << "cost-overlapping-mask-final-"; for (int i = 0; i < allCam.size(); i++) { ss << allCam[i] << "-"; } ss << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), nextInputIndexBuffer.as_const(), size.x, size.y); } #endif // Calculate cost now float output, mask; FAIL_RETURN( Util::ImageProcessingGPU::calculateSum(size.x * size.y, workCost.borrow_const(), 256, stream, output, mask)); float cost = mask > 0 ? output / mask : 1; float maskRatio = mask / float(size.x * size.y); float preferBiggerMaskCost = expf(-maskRatio * maskRatio * 100); blendingCost = cost + 0.05f * preferBiggerMaskCost; return Status::OK(); } Status MergerMask::updateOverlappingMap(const std::vector<int>& normalizedMaxOverlappingWidths, const int2& size, const std::vector<size_t>& allCam, const GPU::Buffer<const uint32_t>& inputNonOverlappingIndexBuffer, GPU::Buffer<uint32_t> inputIndexBuffer, GPU::Stream stream, const bool original) { assert(normalizedMaxOverlappingWidths.size() == allCam.size()); assert(allCam.size() > 1); // Get all frame index as max value size_t maxCam = allCam[0]; for (size_t i = 1; i < allCam.size(); i++) { if (allCam[i] > maxCam) { maxCam = allCam[i]; } } std::vector<char> camIndex(maxCam + 1, 0); for (size_t i = 0; i < allCam.size(); i++) { camIndex[(int)allCam[i]] = (char)i; } GPU::UniqueBuffer<char> camIndexBuffer; FAIL_RETURN(camIndexBuffer.alloc(maxCam, "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(camIndexBuffer.borrow(), &camIndex[0])); // Initialize the index buffer from the non-overlapping FAIL_RETURN( GPU::memcpyBlocking(inputIndexBuffer, inputNonOverlappingIndexBuffer, size.x * size.y * sizeof(uint32_t))); // Set up a mask for all camera previous to the current one to calculate the distance transform function for (size_t i = 0; i < allCam.size(); i++) { if (normalizedMaxOverlappingWidths[i] > 0) { // Compute the distance map for the current camera, make sure that it will have overlapping // area that is larger than a predefined threshold const int upSize = int(float(size.x) * float(normalizedMaxOverlappingWidths[i]) / float(getDownSize(size.x))); const int maxOverlappingWidth = original ? upSize : normalizedMaxOverlappingWidths[i]; FAIL_RETURN(Core::computeEuclideanDistanceMap(workMask.borrow(), inputIndexBuffer, work1.borrow(), work2.borrow(), size.x, size.y, 1 << allCam[i], true, (float)maxOverlappingWidth, 1, stream)); } else { FAIL_RETURN(GPU::memsetToZeroBlocking(workMask.borrow(), size.x * size.y)); } #ifdef MERGERMASK_GET_MERGERMASKS_FINAL if (original) { std::stringstream ss; ss.str(""); ss << "work-mask-"; for (int j = 0; j <= i; j++) { ss << allCam[j] << "-"; } ss << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), workMask.borrow_const(), size.x, size.y); } #endif const int2 camSize = original ? make_int2((int)cachedOriginalMappedRects[allCam[i]].getWidth(), (int)cachedOriginalMappedRects[allCam[i]].getHeight()) : make_int2((int)cachedMappedRects[allCam[i]].getWidth(), (int)cachedMappedRects[allCam[i]].getHeight()); const int2 camOffset = original ? make_int2((int)cachedOriginalMappedRects[allCam[i]].left(), (int)cachedOriginalMappedRects[allCam[i]].top()) : make_int2((int)cachedMappedRects[allCam[i]].left(), (int)cachedMappedRects[allCam[i]].top()); FAIL_RETURN( updateIndexMask((int)allCam[i], original ? 10000 : 2, camIndexBuffer.borrow_const(), camSize, camOffset, original ? originalDistortionMaps[(int)allCam[(int)i]] : distortionMaps[(int)allCam[(int)i]], size, inputIndexBuffer, workMask.borrow(), original ? inputsMapOriginalBuffer.borrow_const() : inputsMapBuffer.borrow_const(), stream)); #ifdef MERGERMASK_GET_MERGERMASKS_FINAL if (original) { { std::stringstream ss; ss.str(""); ss << "index-buffer-final-"; for (int j = 0; j <= i; j++) { ss << allCam[j] << "-"; } ss << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputIndexBuffer.as_const(), size.x, size.y); } /*{ std::stringstream ss; ss.str(""); ss << "distortion-buffer-final-"; for (int j = 0; j <= i; j++) { ss << allCam[j] << "-"; } ss << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), originalDistortionMaps[allCam[i]].as_const(), size.x, size.y); }*/ } #endif } return Status::OK(); } Status MergerMask::releaseMergerMaskMemory() { for (size_t i = 0; i < distortionMaps.size(); i++) { distortionMaps[(int)i].release(); } for (size_t i = 0; i < originalDistortionMaps.size(); i++) { originalDistortionMaps[(int)i].release(); } distortionMaps.clear(); originalDistortionMaps.clear(); workCost.releaseOwnership().release(); inputsMapBuffer.releaseOwnership().release(); inputsMapOriginalBuffer.releaseOwnership().release(); cachedMappedFrames.clear(); return Status::OK(); } Status MergerMask::getMergerMasks(GPU::Buffer<uint32_t> inputIndexPixelBuffer, std::vector<size_t>& masksOrder) { const bool useBlendingOrder = mergerMaskConfig.useBlendingOrder(); const int width = (int)getDownSize((int)pano.getWidth()); const int height = (int)getDownSize((int)pano.getHeight()); const int camCount = (int)pano.numInputs(); GPU::UniqueBuffer<unsigned char> inputDistortionBuffer; FAIL_RETURN(inputDistortionBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<unsigned char> nextDistortionBuffer; FAIL_RETURN(nextDistortionBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<unsigned char> bestDistortionBuffer; FAIL_RETURN(bestDistortionBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> inputNonOverlappingIndexBuffer; FAIL_RETURN(inputNonOverlappingIndexBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> nextNonOverlappingIndexBuffer; FAIL_RETURN(nextNonOverlappingIndexBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> bestNonOverlappingIndexBuffer; FAIL_RETURN(bestNonOverlappingIndexBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> inputIndexBuffer; FAIL_RETURN(inputIndexBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> nextInputIndexBuffer; FAIL_RETURN(nextInputIndexBuffer.alloc(width * height, "Merger Mask")); GPU::Stream stream = GPU::Stream::getDefault(); std::vector<size_t> bestCamOrder; float bestFinalCost = -1; std::vector<int> bestWidths; std::vector<int> normalizedMaxOverlappingWidths; if (mergerMaskConfig.getMaxOverlappingWidth() < -1) { normalizedMaxOverlappingWidths.push_back(-1); for (int i = 100; i <= 200; i += 50) { normalizedMaxOverlappingWidths.push_back(i); } } else { normalizedMaxOverlappingWidths.push_back(mergerMaskConfig.getMaxOverlappingWidth()); } // Try it heuristically // For the first image, just try all of them for (int i0 = 0; i0 < camCount; i0++) { // Do put all image into frame std::vector<bool> processedCam(camCount, false); std::vector<size_t> camOrder; std::vector<int> widths; widths.push_back(-1); float finalCost = 0; processedCam[i0] = true; camOrder.push_back(i0); // Initialize the first map FAIL_RETURN(initializeMasks(make_int2(width, height), i0, inputNonOverlappingIndexBuffer.borrow(), inputDistortionBuffer.borrow(), stream)); #ifdef MERGERMASK_GET_MERGERMASKS { std::stringstream ss; ss.str(""); ss << "trial-distortion-" << i0 << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), inputDistortionBuffer.borrow().as_const(), width, height); } #endif for (int t = 1; t < camCount; t++) { FAIL_RETURN(progress.add("coarseMask_lowRes", "Optimizing for the coarse masks")); // Find camera at position [t] float bestCost = 0; int bestNextCam = -1; std::vector<int> bestNextWidths; // Check whether there is at least one overlapping bool atLeastOneOverlapping = false; for (size_t i = 0; i < camOrder.size(); i++) { for (int j = 0; j < camCount; j++) if (!processedCam[j] && isOverlapping[j][camOrder[i]]) { atLeastOneOverlapping = true; break; } } for (int iNext = 0; iNext < camCount; iNext++) if (!processedCam[iNext]) { if (!useBlendingOrder) { iNext = t; atLeastOneOverlapping = false; } if (atLeastOneOverlapping) { bool isOverlapped = false; for (size_t i = 0; i < camOrder.size(); i++) { if (isOverlapping[iNext][camOrder[i]]) { isOverlapped = true; break; } } if (!isOverlapped) { continue; } } for (size_t k = 0; k < normalizedMaxOverlappingWidths.size(); k++) { std::vector<int> trialWidths = widths; trialWidths.push_back(normalizedMaxOverlappingWidths[k]); std::vector<size_t> allCam = camOrder; allCam.push_back(iNext); // Compute the cost of current configuration float cost = 100000000; FAIL_RETURN(getBlendingCost(trialWidths, make_int2(width, height), allCam, inputDistortionBuffer.borrow_const(), inputNonOverlappingIndexBuffer.borrow_const(), nextDistortionBuffer.borrow(), nextNonOverlappingIndexBuffer.borrow(), nextInputIndexBuffer.borrow(), cost)); if (cost < bestCost || bestNextCam == -1) { bestCost = cost; bestNextCam = iNext; bestNextWidths = trialWidths; FAIL_RETURN(GPU::memcpyBlocking(bestNonOverlappingIndexBuffer.borrow(), nextNonOverlappingIndexBuffer.borrow_const(), width * height * sizeof(uint32_t))); FAIL_RETURN(GPU::memcpyBlocking(bestDistortionBuffer.borrow(), nextDistortionBuffer.borrow_const(), width * height * sizeof(unsigned char))); } } if (!useBlendingOrder) { break; } } // Perform the greedy step here // From all the trial in this step, pick the one that have the smallest cost and use it for the next iteration if (bestNextCam >= 0) { camOrder.push_back(bestNextCam); widths = bestNextWidths; finalCost = bestCost; processedCam[bestNextCam] = true; FAIL_RETURN(GPU::memcpyBlocking(inputNonOverlappingIndexBuffer.borrow(), bestNonOverlappingIndexBuffer.borrow_const(), width * height * sizeof(uint32_t))); FAIL_RETURN(GPU::memcpyBlocking(inputDistortionBuffer.borrow(), bestDistortionBuffer.borrow_const(), width * height * sizeof(unsigned char))); } else { finalCost = -1; break; } } // Find the best results from all initial camera if (camOrder.size() == (size_t)camCount) { if ((finalCost > 0) && (finalCost < bestFinalCost || bestFinalCost < 0)) { bestFinalCost = finalCost; bestCamOrder = camOrder; bestWidths = widths; } } if (!useBlendingOrder) { break; } } // Found the best order, now re-run the process in full resolution to generate the final map masksOrder = bestCamOrder; FAIL_RETURN(getOriginalMaskFromOrder(bestWidths, masksOrder, inputIndexPixelBuffer)); if (mergerMaskConfig.useSeam()) { // Release all that are not needed FAIL_RETURN(releaseMergerMaskMemory()); FAIL_RETURN(performSeamOptimization(masksOrder, inputIndexPixelBuffer)); } return Status::OK(); } Status MergerMask::getOriginalMaskFromOrder(const std::vector<int>& normalizedOverlappingWidths, const std::vector<size_t>& maskOrder, GPU::Buffer<uint32_t> inputIndexPixelBuffer) { const int width = (int)pano.getWidth(); const int height = (int)pano.getHeight(); GPU::Stream stream = GPU::Stream::getDefault(); GPU::UniqueBuffer<unsigned char> inputDistortionBuffer; FAIL_RETURN(inputDistortionBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<unsigned char> nextDistortionBuffer; FAIL_RETURN(nextDistortionBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> inputNonOverlappingIndexBuffer; FAIL_RETURN(inputNonOverlappingIndexBuffer.alloc(width * height, "Merger Mask")); GPU::UniqueBuffer<uint32_t> nextNonOverlappingIndexBuffer; FAIL_RETURN(nextNonOverlappingIndexBuffer.alloc(width * height, "Merger Mask")); const int2 size = make_int2(width, height); FAIL_RETURN(initializeMasks(size, (int)maskOrder[0], inputNonOverlappingIndexBuffer.borrow(), inputDistortionBuffer.borrow(), stream, true)); for (size_t i = 1; i < maskOrder.size(); i++) { FAIL_RETURN(updateInputIndexByDistortionMap( (int)maskOrder[i], size, inputNonOverlappingIndexBuffer.borrow_const(), inputDistortionBuffer.borrow_const(), nextNonOverlappingIndexBuffer.borrow(), nextDistortionBuffer.borrow(), stream, true)); FAIL_RETURN(GPU::memcpyBlocking(inputNonOverlappingIndexBuffer.borrow(), nextNonOverlappingIndexBuffer.borrow_const(), width * height * sizeof(uint32_t))); FAIL_RETURN(GPU::memcpyBlocking(inputDistortionBuffer.borrow(), nextDistortionBuffer.borrow_const(), width * height * sizeof(unsigned char))); } #ifdef MERGERMASK_GET_MERGERMASKS_FULL { std::stringstream ss; ss.str(""); ss << "final-non-overlapping-result-"; for (int i = 0; i < normalizedOverlappingWidths.size(); i++) ss << normalizedOverlappingWidths[i] << " "; ss << "cam"; for (int i = 0; i < maskOrder.size(); i++) { ss << maskOrder[i] << "-"; } ss << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputNonOverlappingIndexBuffer.borrow_const(), size.x, size.y); } { std::stringstream ss; ss.str(""); ss << "final-distortion-map-"; for (int i = 0; i < normalizedOverlappingWidths.size(); i++) ss << normalizedOverlappingWidths[i] << " "; ss << "cam"; for (int i = 0; i < maskOrder.size(); i++) { ss << maskOrder[i] << "-"; } ss << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), inputDistortionBuffer.borrow_const(), size.x, size.y); } #endif FAIL_RETURN(updateOverlappingMap(normalizedOverlappingWidths, size, maskOrder, nextNonOverlappingIndexBuffer.borrow_const(), inputIndexPixelBuffer, stream, true)); #ifdef MERGERMASK_GET_MERGERMASKS_FULL { std::stringstream ss; ss.str(""); ss << "final-full-result-"; for (int i = 0; i < normalizedOverlappingWidths.size(); i++) ss << normalizedOverlappingWidths[i] << " "; ss << "cam"; for (int i = 0; i < maskOrder.size(); i++) { ss << maskOrder[i] << "-"; } ss << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputIndexPixelBuffer.as_const(), size.x, size.y); } { std::stringstream ss; ss.str(""); ss << "input-full-index.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputsMapOriginalBuffer.borrow_const(), size.x, size.y); } #endif FAIL_RETURN(progress.add("coarseMask_fulRes", "Coarse masks done")); return Status::OK(); } Status MergerMask::performSeamOptimization(const std::vector<size_t>& maskOrder, GPU::Buffer<uint32_t> inputIndexBuffer) { // Copy input index buffer to a temporal buffer GPU::UniqueBuffer<uint32_t> tmpInputIndexBuffer; FAIL_RETURN(tmpInputIndexBuffer.alloc(inputIndexBuffer.numElements(), "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(tmpInputIndexBuffer.borrow(), inputIndexBuffer)); const int width = (int)pano.getWidth(); const int height = (int)pano.getHeight(); const int2 size = make_int2(width, height); #ifdef MERGERMASK_SEAM_MASK { std::stringstream ss; ss.str(""); ss << "before-seam-mask" << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputIndexBuffer.as_const(), size.x, size.y); } #endif GPU::UniqueBuffer<uint32_t> indexBuffer0; GPU::UniqueBuffer<uint32_t> indexBuffer1; FAIL_RETURN(indexBuffer0.alloc(inputIndexBuffer.numElements(), "Merger Mask")); FAIL_RETURN(indexBuffer1.alloc(inputIndexBuffer.numElements(), "Merger Mask")); GPU::Stream stream = GPU::Stream::getDefault(); std::vector<unsigned int> frames = {mergerMaskConfig.getFrames()[0]}; // Retrieve the first image from the selected set of frames FrameBuffers frameBuffers; FAIL_MSG(retrieveImages(frames, frameBuffers, pano), "Run out of memory while trying to read input frames for seam optimization"); int totalSize = 0; for (auto mapping : imageMappings) { totalSize += (int)mapping.second->getOutputRect(Core::EQUIRECTANGULAR).getArea(); } auto potMappedFrames = GPU::uniqueBuffer<uint32_t>(totalSize, "Merger Mask"); FAIL_RETURN(potMappedFrames.status()); // Transforms image from the input to the output space, store them in the mappedFrames int offset = 0; for (auto transformIterator : transforms) { const videoreaderid_t i = transformIterator.first; Core::Transform* transform = transformIterator.second; Core::ImageMapping* mapping = imageMappings[i]; const Core::InputDefinition& im = pano.getInput(i); const std::pair<size_t, size_t> inPair = std::make_pair(i, frames[0]); FrameBuffers::const_iterator it = frameBuffers.find(inPair); if (it != frameBuffers.end()) { const GPU::Buffer<const uint32_t> inputBuffer = it->second.borrow_const(); auto surface = Core::OffscreenAllocator::createSourceSurface(im.getWidth(), im.getHeight(), "Merger Mask"); FAIL_RETURN(GPU::memcpyAsync(*surface->pimpl->surface, inputBuffer, stream)); auto potDevOut = GPU::uniqueBuffer<uint32_t>(mapping->getOutputRect(Core::EQUIRECTANGULAR).getArea(), "Merger Mask"); FAIL_RETURN(potDevOut.status()); // Map the input to the output space FAIL_RETURN(transform->mapBuffer(frames[0], potDevOut.borrow(), *surface->pimpl->surface, nullptr, mapping->getOutputRect(Core::EQUIRECTANGULAR), pano, im, *surface->pimpl->surface, stream)); // Down-sampling the image to the appropriate level int devWidth = (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getWidth(); int devHeight = (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getHeight(); #ifdef MERGERMASK_SEAM_INPUT { std::stringstream ss; ss << "oriwarped-" << i << ".png"; Debug::dumpRGB210DeviceBuffer(ss.str().c_str(), devOut.borrow_const(), devWidth, devHeight); } #endif // Convert from rgb to lab GPU::Buffer<uint32_t> subBuffer = potMappedFrames.borrow().createSubBuffer(offset); FAIL_RETURN(Util::ImageProcessingGPU::convertRGB210ToRGBandGradient(make_int2(devWidth, devHeight), potDevOut.borrow_const(), subBuffer, stream)); #ifdef MERGERMASK_SEAM_INPUT { std::stringstream ss; ss << "warped-rgb-" << i << ".png"; Debug::dumpRGBADeviceBuffer(ss.str().c_str(), devOut.borrow_const(), devWidth, devHeight); } #endif FAIL_RETURN(Util::ImageProcessingGPU::convertRGBandGradientToNormalizedLABandGradient( make_int2(devWidth, devHeight), subBuffer, stream)); #ifdef MERGERMASK_SEAM_INPUT { std::stringstream ss; ss << "warped-" << i << ".png"; Debug::dumpRGB210DeviceBuffer(ss.str().c_str(), subBuffer.as_const(), devWidth, devHeight); } { std::stringstream ss; ss << "gradient-" << i << ".png"; GPU::UniqueBuffer<unsigned char> gradientBuffer; FAIL_RETURN(gradientBuffer.alloc(devWidth * devHeight, "Merger Mask")); FAIL_RETURN( extractChannel(make_int2(devWidth, devHeight), subBuffer.as_const(), 3, gradientBuffer.borrow(), stream)); Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), gradientBuffer.borrow_const(), devWidth, devHeight); } #endif } offset += (int)mapping->getOutputRect(Core::EQUIRECTANGULAR).getArea(); } FAIL_RETURN(progress.add("seam_setup", "Setup seam computation")); GPU::UniqueBuffer<uint32_t> input0Buffer; GPU::UniqueBuffer<uint32_t> input1Buffer; FAIL_RETURN(input0Buffer.alloc(size.x * size.y, "Merger Mask")); FAIL_RETURN(input1Buffer.alloc(size.x * size.y, "Merger Mask")); const int seamFeatheringSize = mergerMaskConfig.getSeamFeatheringSize(); Core::Rect rect = Core::Rect::fromInclusiveTopLeftBottomRight(0, 0, size.y - 1, size.x - 1); uint32_t prevIds = 1 << maskOrder[0]; for (size_t i = 1; i < maskOrder.size(); i++) { // Optimize for the seam using the first image only, more will likely cause more harm than good const uint32_t currentId = 1 << maskOrder[i]; std::vector<unsigned char> prevCams; for (size_t j = 0; j < i; j++) { prevCams.push_back((unsigned char)maskOrder[j]); } GPU::UniqueBuffer<unsigned char> prevCamsBuffer; FAIL_RETURN(prevCamsBuffer.alloc(prevCams.size(), "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(prevCamsBuffer.borrow(), &prevCams[0])); std::vector<unsigned char> currentCam = {(unsigned char)maskOrder[i]}; GPU::UniqueBuffer<unsigned char> currentCamBuffer; FAIL_RETURN(currentCamBuffer.alloc(currentCam.size(), "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(currentCamBuffer.borrow(), &currentCam[0])); FAIL_RETURN(lookupColorBufferFromInputIndex( (int)rect.getWidth(), prevCamsBuffer.borrow_const(), originalMappedRectOffset.borrow_const(), originalMappedRectSize.borrow_const(), originalMappedOffset.borrow_const(), potMappedFrames.borrow_const(), size, inputIndexBuffer, input0Buffer.borrow(), stream)); FAIL_RETURN(lookupColorBufferFromInputIndex( (int)rect.getWidth(), currentCamBuffer.borrow_const(), originalMappedRectOffset.borrow_const(), originalMappedRectSize.borrow_const(), originalMappedOffset.borrow_const(), potMappedFrames.borrow_const(), size, inputIndexBuffer, input1Buffer.borrow(), stream)); auto potSeamFinder = SeamFinder::create(2, 1, (int)pano.getWidth(), rect, input0Buffer.borrow_const(), rect, input1Buffer.borrow_const(), stream, workMask, work1, work2); FAIL_MSG(potSeamFinder.status(), "Failed to initialize seam computation"); std::unique_ptr<SeamFinder> seamFinder(potSeamFinder.release()); FAIL_MSG(seamFinder->findSeam(), "Failed to find seam"); #ifdef MERGERMASK_SEAM_OPTIMIZATION // Convert input buffers into rgb for dumping { VideoStitch::MergerMask::MergerMask::convertNormalizedLABandGradientToRGBA(size, input0Buffer.borrow(), stream); VideoStitch::MergerMask::MergerMask::convertNormalizedLABandGradientToRGBA(size, input1Buffer.borrow(), stream); } { std::stringstream ss; ss << "ori-" << i << "-0.png"; Debug::dumpRGBADeviceBuffer(ss.str().c_str(), input0Buffer.borrow_const(), size.x, size.y); } { std::stringstream ss; ss << "ori-" << i << "-1.png"; work1 Debug::dumpRGBADeviceBuffer(ss.str().c_str(), input1Buffer.borrow_const(), size.x, size.y); } { std::stringstream ss; ss << "output-image" << i << "-with-seam.png"; seamFinder.saveSeamImage(ss.str(), 2); } { std::stringstream ss; ss << "output-map-" << i << "-0.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), seamFinder.getOutputsMap().as_const(), size.x, size.y); } #endif // If there is no overlapping, just continue the process if (seamFinder->seamFound()) { FAIL_RETURN( updateIndexMaskAfterSeam(prevIds, currentId, size, seamFinder->getOutputsMap(), inputIndexBuffer, stream)); #ifdef MERGERMASK_SEAM_OPTIMIZATION { { std::stringstream ss; ss << "after-seam-" << i << "-index-map.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputIndexBuffer.as_const(), size.x, size.y); } } #endif } prevIds += currentId; FAIL_RETURN(progress.add("seam_fulRes", "Perform seam optimization")); } #ifdef MERGERMASK_SEAM_MASK { std::stringstream ss; ss.str(""); ss << "final-seam-mask-no-feathering" << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputIndexBuffer.as_const(), size.x, size.y); } #endif if (seamFeatheringSize > 0) { // Now perform feathering around borders GPU::UniqueBuffer<uint32_t> seamWithFeatheringBuffer; FAIL_RETURN(seamWithFeatheringBuffer.alloc(size.x * size.y, "Merger Mask")); FAIL_RETURN(GPU::memcpyBlocking(seamWithFeatheringBuffer.borrow(), inputIndexBuffer)); for (size_t i = 0; i < maskOrder.size(); i++) { // Compute the distance map for the current camera, make sure that it will have overlapping // area that is larger than a predefined threshold FAIL_RETURN(Core::computeEuclideanDistanceMap(workMask.borrow(), inputIndexBuffer, work1.borrow(), work2.borrow(), size.x, size.y, 1 << maskOrder[i], true, (float)seamFeatheringSize, 1, stream)); #ifdef MERGERMASK_SEAM_OPTIMIZATION { std::stringstream ss; ss.str(""); ss << "work-mask-" << i << ".png"; Debug::dumpMonochromeDeviceBuffer<Debug::linear>(ss.str().c_str(), workMask.borrow_const(), size.x, size.y); } #endif FAIL_RETURN(updateSeamMask((int)maskOrder[i], size, tmpInputIndexBuffer.borrow_const(), workMask.borrow_const(), seamWithFeatheringBuffer.borrow(), stream)); #ifdef MERGERMASK_SEAM_OPTIMIZATION { std::stringstream ss; ss.str(""); ss << "index-buffer-final-" << i << ".png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), seamWithFeatheringBuffer.borrow_const(), size.x, size.y); } #endif } FAIL_RETURN(GPU::memcpyBlocking(inputIndexBuffer, seamWithFeatheringBuffer.borrow_const())); #ifdef MERGERMASK_SEAM_MASK { std::stringstream ss; ss.str(""); ss << "final-seam-mask.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputIndexBuffer.as_const(), size.x, size.y); } #endif } #ifdef MERGERMASK_SEAM_MASK { std::stringstream ss; ss.str(""); ss << "input-original-mask.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), inputsMapOriginalBuffer.borrow_const(), size.x, size.y); } #endif FAIL_RETURN(progress.add("seam_updateMask", "Update seam mask")); return Status::OK(); } Status MergerMask::transformMasksFromOutputToEncodedInputSpace( const Core::PanoDefinition& pano, const std::map<readerid_t, Input::VideoReader*>& readers, const GPU::Buffer<const uint32_t>& maskOutputSpaces, std::map<videoreaderid_t, std::string>& maskInputSpaces) { // Prepare transform std::map<videoreaderid_t, std::unique_ptr<Core::Transform>> transforms; for (auto reader : readers) { const Core::InputDefinition& inputDef = pano.getInput(reader.second->id); Core::Transform* transform = Core::Transform::create(inputDef); if (!transform) { return {Origin::Stitcher, ErrType::SetupFailure, "Cannot create v1 transformation for input " + std::to_string(reader.second->id)}; } transforms[reader.second->id] = std::unique_ptr<Core::Transform>(transform); } GPU::Stream stream = GPU::Stream::getDefault(); Core::Rect outputBounds = Core::Rect::fromInclusiveTopLeftBottomRight(0, 0, pano.getHeight() - 1, pano.getWidth() - 1); const int inputScaleFactor = pano.getBlendingMaskInputScaleFactor(); maskInputSpaces.clear(); #ifdef MERGERMASK_INPUT_SPACE { std::stringstream ss; ss << "inputsMap-result.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), maskOutputSpaces.as_const(), outputBounds.getWidth(), outputBounds.getHeight()); } #endif for (auto& transform : transforms) { const videoreaderid_t imId = transform.first; // Find the precomputed coordinate to map pixels from the output to the input space const Core::InputDefinition& inputDef = pano.getInput(imId); GPU::UniqueBuffer<float2> devCoord; FAIL_RETURN(devCoord.alloc(inputDef.getWidth() * inputDef.getHeight() * inputScaleFactor * inputScaleFactor, "Merger Mask")); FAIL_RETURN(transform.second->mapCoordInput(0, inputScaleFactor, devCoord.borrow(), pano, inputDef, stream)); #ifdef MERGERMASK_INPUT_SPACE { std::stringstream ss; ss << "inputsMap-inputcoord-" << imId << ".png"; GPU::UniqueBuffer<uint32_t> dst; FAIL_RETURN( dst.alloc(inputDef.getWidth() * inputDef.getHeight() * inputScaleFactor * inputScaleFactor, "Merger Mask")); Util::OpticalFlow::convertFlowToRGBA( make_int2((int)inputDef.getWidth() * inputScaleFactor, (int)inputDef.getHeight() * inputScaleFactor), devCoord.borrow_const(), make_int2((int)pano.getWidth(), (int)pano.getHeight()), dst.borrow(), stream); Debug::dumpRGBADeviceBuffer(ss.str().c_str(), dst.borrow_const(), inputDef.getWidth() * inputScaleFactor, inputDef.getHeight() * inputScaleFactor); } #endif GPU::UniqueBuffer<unsigned char> inputMask; FAIL_RETURN(inputMask.alloc(inputDef.getWidth() * inputDef.getHeight() * inputScaleFactor * inputScaleFactor, "Merger Mask")); GPU::UniqueBuffer<unsigned char> tmp; FAIL_RETURN( tmp.alloc(inputDef.getWidth() * inputDef.getHeight() * inputScaleFactor * inputScaleFactor, "Merger Mask")); FAIL_RETURN(GPU::memsetToZeroBlocking(inputMask.borrow(), inputMask.borrow().byteSize())); // Accumulate the pixels FAIL_RETURN(getInputMaskFromOutputIndices( imId, inputScaleFactor, make_int2((int)outputBounds.getWidth(), (int)outputBounds.getHeight()), maskOutputSpaces, make_int2((int)inputDef.getWidth(), (int)inputDef.getHeight()), devCoord.borrow(), inputMask.borrow(), stream)); // Perform gaussian filter on the mask to remove spiky edges. // This step will improve polyline compression rate dramatically. FAIL_RETURN(Image::gaussianBlur2D(inputMask.borrow(), tmp.borrow(), (int)inputDef.getWidth() * inputScaleFactor, (int)inputDef.getHeight() * inputScaleFactor, 1, 6, 0, 16, stream)); FAIL_RETURN(Util::ImageProcessingGPU::thresholdingBuffer<unsigned char>( make_int2((int)inputDef.getWidth() * inputScaleFactor, (int)inputDef.getHeight() * inputScaleFactor), 0, 0, 255, inputMask.borrow(), stream)); std::vector<unsigned char> masks(inputDef.getWidth() * inputDef.getHeight() * inputScaleFactor * inputScaleFactor); FAIL_RETURN( GPU::memcpyBlocking<unsigned char>(&masks[0], inputMask.borrow_const(), masks.size() * sizeof(unsigned char))); #ifdef MERGERMASK_INPUT_SPACE { std::stringstream ss; ss << "inputsMap-mask-" << imId << ".png"; Debug::dumpRGBAIndexDeviceBuffer<unsigned char>(ss.str().c_str(), masks, inputDef.getWidth() * inputScaleFactor, inputDef.getHeight() * inputScaleFactor); } #endif std::string maskInputSpace; FAIL_RETURN(Util::Compression::polylineEncodeBinaryMask((int)inputDef.getWidth() * inputScaleFactor, (int)inputDef.getHeight() * inputScaleFactor, masks, maskInputSpace)); maskInputSpaces[imId] = maskInputSpace; } #ifdef MERGERMASK_INPUT_SPACE { GPU::UniqueBuffer<uint32_t> reconstructMaskOutput; FAIL_RETURN(reconstructMaskOutput.alloc(pano.getWidth() * pano.getHeight(), "Merger Mask")); FAIL_RETURN( transformMasksFromEncodedInputToOutputSpace(pano, readers, maskInputSpaces, reconstructMaskOutput.borrow())); std::stringstream ss; ss << "inputsMap-reconstruction.png"; Debug::dumpRGBAIndexDeviceBuffer(ss.str().c_str(), reconstructMaskOutput.borrow_const(), pano.getWidth(), pano.getHeight()); } #endif return Status::OK(); } Status MergerMask::transformMasksFromEncodedInputToOutputSpace( const Core::PanoDefinition& pano, const std::map<readerid_t, Input::VideoReader*>& readers, const std::map<videoreaderid_t, std::string>& maskInputSpaces, GPU::Buffer<uint32_t> maskOutputSpaces) { // Prepare transform std::map<videoreaderid_t, std::unique_ptr<Core::Transform>> transforms; for (auto reader : readers) { const Core::InputDefinition& inputDef = pano.getInput(reader.second->id); Core::Transform* transform = Core::Transform::create(inputDef); if (!transform) { return {Origin::Stitcher, ErrType::SetupFailure, "Cannot create v1 transformation for input " + std::to_string(reader.second->id)}; } transforms[reader.second->id] = std::unique_ptr<Core::Transform>(transform); } const int inputScaleFactor = pano.getBlendingMaskInputScaleFactor(); GPU::Stream stream = GPU::Stream::getDefault(); Core::Rect outputBounds = Core::Rect::fromInclusiveTopLeftBottomRight(0, 0, pano.getHeight() - 1, pano.getWidth() - 1); auto tex = Core::OffscreenAllocator::createCoordSurface(outputBounds.getWidth(), outputBounds.getHeight(), "Merger Mask"); if (!tex.ok()) { return tex.status(); } std::unique_ptr<Core::SourceSurface> devCoord(tex.release()); FAIL_RETURN(GPU::memsetToZeroBlocking<uint32_t>(maskOutputSpaces, maskOutputSpaces.byteSize())); for (auto& transform : transforms) { const videoreaderid_t imId = transform.first; const Core::InputDefinition& inputDef = pano.getInput(imId); FAIL_RETURN( transform.second->mapBufferCoord(0, *devCoord.get()->pimpl->surface, outputBounds, pano, inputDef, stream)); GPU::UniqueBuffer<unsigned char> inputMask; FAIL_RETURN(inputMask.alloc(inputDef.getWidth() * inputDef.getHeight() * inputScaleFactor * inputScaleFactor, "Merger Mask")); std::vector<unsigned char> masks; auto it = maskInputSpaces.find(imId); if (it == maskInputSpaces.end()) { return {Origin::BlendingMaskAlgorithm, ErrType::ImplementationError, "Data was not found"}; } FAIL_RETURN(Util::Compression::polylineDecodeBinaryMask( (int)inputDef.getWidth() * inputScaleFactor, (int)inputDef.getHeight() * inputScaleFactor, it->second, masks)); FAIL_RETURN( GPU::memcpyBlocking<unsigned char>(inputMask.borrow(), &masks[0], masks.size() * sizeof(unsigned char))); FAIL_RETURN(getOutputIndicesFromInputMask( imId, inputScaleFactor, make_int2((int)inputDef.getWidth(), (int)inputDef.getHeight()), inputMask.borrow_const(), make_int2((int)outputBounds.getWidth(), (int)outputBounds.getHeight()), *devCoord.get()->pimpl->surface, maskOutputSpaces, stream)); } return Status::OK(); } } // namespace MergerMask } // namespace VideoStitch
44.095206
120
0.654498
[ "vector", "transform" ]
8195566daea870c14dd4ef90e28e02ee5c6e8f80
14,001
hpp
C++
Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.hpp
luzpaz/DiligentCore
3eaf45aa4785bf566b307613c56b41d67799c5e7
[ "Apache-2.0" ]
null
null
null
Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.hpp
luzpaz/DiligentCore
3eaf45aa4785bf566b307613c56b41d67799c5e7
[ "Apache-2.0" ]
null
null
null
Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.hpp
luzpaz/DiligentCore
3eaf45aa4785bf566b307613c56b41d67799c5e7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2021 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once /// \file /// Declaration of Diligent::ShaderResourceCacheVk class // Shader resource cache stores Vk resources in a continuous chunk of memory: // // |Vulkan Descriptor Set| // A ___________________________________________________________ // m_pMemory | | m_pResources, m_NumResources == m | // | m_DescriptorSetAllocation| | | // V | | V // | DescriptorSet[0] | .... | DescriptorSet[Ns-1] | Res[0] | ... | Res[n-1] | .... | Res[0] | ... | Res[m-1] | // | | A \ // | | | \ // | |________________________________________________| \RefCntAutoPtr // | m_pResources, m_NumResources == n \_________ // | | Object | // | m_DescriptorSetAllocation --------- // V // |Vulkan Descriptor Set| // // Ns = m_NumSets // // // Descriptor set for static and mutable resources is assigned during cache initialization // Descriptor set for dynamic resources is assigned at every draw call #include <vector> #include <memory> #include "DescriptorPoolManager.hpp" #include "SPIRVShaderResources.hpp" #include "BufferVkImpl.hpp" #include "ShaderResourceCacheCommon.hpp" #include "PipelineResourceAttribsVk.hpp" #include "VulkanUtilities/VulkanLogicalDevice.hpp" namespace Diligent { class DeviceContextVkImpl; // sizeof(ShaderResourceCacheVk) == 24 (x64, msvc, Release) class ShaderResourceCacheVk { public: explicit ShaderResourceCacheVk(ResourceCacheContentType ContentType) noexcept : m_TotalResources{0}, m_ContentType{static_cast<Uint32>(ContentType)} { VERIFY_EXPR(GetContentType() == ContentType); } // clang-format off ShaderResourceCacheVk (const ShaderResourceCacheVk&) = delete; ShaderResourceCacheVk (ShaderResourceCacheVk&&) = delete; ShaderResourceCacheVk& operator = (const ShaderResourceCacheVk&) = delete; ShaderResourceCacheVk& operator = (ShaderResourceCacheVk&&) = delete; // clang-format on ~ShaderResourceCacheVk(); static size_t GetRequiredMemorySize(Uint32 NumSets, const Uint32* SetSizes); void InitializeSets(IMemoryAllocator& MemAllocator, Uint32 NumSets, const Uint32* SetSizes); void InitializeResources(Uint32 Set, Uint32 Offset, Uint32 ArraySize, DescriptorType Type, bool HasImmutableSampler); // sizeof(Resource) == 16 (x64, msvc, Release) struct Resource { explicit Resource(DescriptorType _Type, bool _HasImmutableSampler) noexcept : Type{_Type}, HasImmutableSampler{_HasImmutableSampler} { VERIFY(Type == DescriptorType::CombinedImageSampler || Type == DescriptorType::Sampler || !HasImmutableSampler, "Immutable sampler can only be assigned to a combined image sampler or a separate sampler"); } // clang-format off Resource (const Resource&) = delete; Resource (Resource&&) = delete; Resource& operator = (const Resource&) = delete; Resource& operator = (Resource&&) = delete; /* 0 */ const DescriptorType Type; /* 1 */ const bool HasImmutableSampler; /*2-7*/ // Unused /* 8 */ RefCntAutoPtr<IDeviceObject> pObject; VkDescriptorBufferInfo GetUniformBufferDescriptorWriteInfo() const; VkDescriptorBufferInfo GetStorageBufferDescriptorWriteInfo() const; VkDescriptorImageInfo GetImageDescriptorWriteInfo () const; VkBufferView GetBufferViewWriteInfo () const; VkDescriptorImageInfo GetSamplerDescriptorWriteInfo() const; VkDescriptorImageInfo GetInputAttachmentDescriptorWriteInfo() const; VkWriteDescriptorSetAccelerationStructureKHR GetAccelerationStructureWriteInfo() const; // clang-format on bool IsNull() const { return pObject == nullptr; } }; // sizeof(DescriptorSet) == 48 (x64, msvc, Release) class DescriptorSet { public: // clang-format off DescriptorSet(Uint32 NumResources, Resource *pResources) : m_NumResources {NumResources}, m_pResources {pResources } {} DescriptorSet (const DescriptorSet&) = delete; DescriptorSet (DescriptorSet&&) = delete; DescriptorSet& operator = (const DescriptorSet&) = delete; DescriptorSet& operator = (DescriptorSet&&) = delete; // clang-format on const Resource& GetResource(Uint32 CacheOffset) const { VERIFY(CacheOffset < m_NumResources, "Offset ", CacheOffset, " is out of range"); return m_pResources[CacheOffset]; } Uint32 GetSize() const { return m_NumResources; } VkDescriptorSet GetVkDescriptorSet() const { return m_DescriptorSetAllocation.GetVkDescriptorSet(); } // clang-format off /* 0 */ const Uint32 m_NumResources = 0; private: friend ShaderResourceCacheVk; Resource& GetResource(Uint32 CacheOffset) { VERIFY(CacheOffset < m_NumResources, "Offset ", CacheOffset, " is out of range"); return m_pResources[CacheOffset]; } /* 8 */ Resource* const m_pResources = nullptr; /*16 */ DescriptorSetAllocation m_DescriptorSetAllocation; /*48 */ // End of structure // clang-format on }; const DescriptorSet& GetDescriptorSet(Uint32 Index) const { VERIFY_EXPR(Index < m_NumSets); return reinterpret_cast<const DescriptorSet*>(m_pMemory.get())[Index]; } void AssignDescriptorSetAllocation(Uint32 SetIndex, DescriptorSetAllocation&& Allocation) { auto& DescrSet = GetDescriptorSet(SetIndex); VERIFY(DescrSet.GetSize() > 0, "Descriptor set is empty"); VERIFY(!DescrSet.m_DescriptorSetAllocation, "Descriptor set alloction has already been initialized"); DescrSet.m_DescriptorSetAllocation = std::move(Allocation); } // Sets the resource at the given descriptor set index and offset const Resource& SetResource(const VulkanUtilities::VulkanLogicalDevice* pLogicalDevice, Uint32 SetIndex, Uint32 Offset, Uint32 BindingIndex, Uint32 ArrayIndex, RefCntAutoPtr<IDeviceObject>&& pObject); const Resource& ResetResource(Uint32 SetIndex, Uint32 Offset) { return SetResource(nullptr, SetIndex, Offset, ~0u, ~0u, RefCntAutoPtr<IDeviceObject>{}); } Uint32 GetNumDescriptorSets() const { return m_NumSets; } Uint32 GetNumDynamicBuffers() const { return m_NumDynamicBuffers; } ResourceCacheContentType GetContentType() const { return static_cast<ResourceCacheContentType>(m_ContentType); } #ifdef DILIGENT_DEBUG // Only for debug purposes: indicates what types of resources are stored in the cache void DbgVerifyResourceInitialization() const; void DbgVerifyDynamicBuffersCounter() const; #endif template <bool VerifyOnly> void TransitionResources(DeviceContextVkImpl* pCtxVkImpl); __forceinline Uint32 GetDynamicBufferOffsets(Uint32 CtxId, DeviceContextVkImpl* pCtxVkImpl, std::vector<uint32_t>& Offsets) const; private: Resource* GetFirstResourcePtr() { return reinterpret_cast<Resource*>(reinterpret_cast<DescriptorSet*>(m_pMemory.get()) + m_NumSets); } const Resource* GetFirstResourcePtr() const { return reinterpret_cast<const Resource*>(reinterpret_cast<const DescriptorSet*>(m_pMemory.get()) + m_NumSets); } DescriptorSet& GetDescriptorSet(Uint32 Index) { VERIFY_EXPR(Index < m_NumSets); return reinterpret_cast<DescriptorSet*>(m_pMemory.get())[Index]; } std::unique_ptr<void, STDDeleter<void, IMemoryAllocator>> m_pMemory; Uint16 m_NumSets = 0; // Total actual number of dynamic buffers (that were created with USAGE_DYNAMIC) bound in the resource cache // regardless of the variable type. Note this variable is not equal to dynamic offsets count, which is constant. Uint16 m_NumDynamicBuffers = 0; Uint32 m_TotalResources : 31; // Indicates what types of resources are stored in the cache const Uint32 m_ContentType : 1; #ifdef DILIGENT_DEBUG // Debug array that stores flags indicating if resources in the cache have been initialized std::vector<std::vector<bool>> m_DbgInitializedResources; #endif }; __forceinline Uint32 ShaderResourceCacheVk::GetDynamicBufferOffsets(Uint32 CtxId, DeviceContextVkImpl* pCtxVkImpl, std::vector<uint32_t>& Offsets) const { // If any of the sets being bound include dynamic uniform or storage buffers, then // pDynamicOffsets includes one element for each array element in each dynamic descriptor // type binding in each set. Values are taken from pDynamicOffsets in an order such that // all entries for set N come before set N+1; within a set, entries are ordered by the binding // numbers (unclear if this is SPIRV binding or VkDescriptorSetLayoutBinding number) in the // descriptor set layouts; and within a binding array, elements are in order. (13.2.5) // In each descriptor set, all uniform buffers with dynamic offsets (DescriptorType::UniformBufferDynamic) // for every shader stage come first, followed by all storage buffers with dynamic offsets // (DescriptorType::StorageBufferDynamic and DescriptorType::StorageBufferDynamic_ReadOnly) for every shader stage, // followed by all other resources. Uint32 OffsetInd = 0; for (Uint32 set = 0; set < m_NumSets; ++set) { const auto& DescrSet = GetDescriptorSet(set); const auto SetSize = DescrSet.GetSize(); Uint32 res = 0; while (res < SetSize) { const auto& Res = DescrSet.GetResource(res); if (Res.Type == DescriptorType::UniformBufferDynamic) { const auto* pBufferVk = Res.pObject.RawPtr<const BufferVkImpl>(); const auto Offset = pBufferVk != nullptr ? pBufferVk->GetDynamicOffset(CtxId, pCtxVkImpl) : 0; Offsets[OffsetInd++] = Offset; ++res; } else break; } while (res < SetSize) { const auto& Res = DescrSet.GetResource(res); if (Res.Type == DescriptorType::StorageBufferDynamic || Res.Type == DescriptorType::StorageBufferDynamic_ReadOnly) { const auto* pBufferVkView = Res.pObject.RawPtr<const BufferViewVkImpl>(); const auto* pBufferVk = pBufferVkView != nullptr ? pBufferVkView->GetBuffer<const BufferVkImpl>() : nullptr; const auto Offset = pBufferVk != nullptr ? pBufferVk->GetDynamicOffset(CtxId, pCtxVkImpl) : 0; Offsets[OffsetInd++] = Offset; ++res; } else break; } #ifdef DILIGENT_DEBUG for (; res < SetSize; ++res) { const auto& Res = DescrSet.GetResource(res); VERIFY((Res.Type != DescriptorType::UniformBufferDynamic && Res.Type != DescriptorType::StorageBufferDynamic && Res.Type != DescriptorType::StorageBufferDynamic_ReadOnly), "All dynamic uniform and storage buffers are expected to go first in the beginning of each descriptor set"); } #endif } return OffsetInd; } } // namespace Diligent
43.616822
137
0.620956
[ "object", "vector" ]
8197322cb55ab8abf8fdf510ddb63eeb7393b3f9
750
cpp
C++
libs/core/render/test/src/gl/unit_test_core_render_gl_primitive_topology.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/test/src/gl/unit_test_core_render_gl_primitive_topology.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/test/src/gl/unit_test_core_render_gl_primitive_topology.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file unit_test_core_render_gl_primitive_topology.cpp * * @brief PrimitiveTopology のテスト * * @author myoukaku */ #include <bksge/core/render/gl/detail/primitive_topology.hpp> #include <bksge/core/render/primitive_topology.hpp> #include <bksge/core/render/config.hpp> #include <gtest/gtest.h> GTEST_TEST(Render_GlTest, GlPrimitiveTopologyTest) { #if BKSGE_CORE_RENDER_HAS_GL_RENDERER EXPECT_EQ((GLenum)GL_POINTS, bksge::render::gl::PrimitiveTopology(bksge::PrimitiveTopology::kPoints)); EXPECT_EQ((GLenum)GL_LINES, bksge::render::gl::PrimitiveTopology(bksge::PrimitiveTopology::kLines)); EXPECT_EQ((GLenum)GL_TRIANGLES, bksge::render::gl::PrimitiveTopology(bksge::PrimitiveTopology::kTriangles)); #endif }
34.090909
110
0.762667
[ "render" ]
819987800810710eeab49ad19487e1040e665956
6,814
hpp
C++
irobot_create_common/irobot_create_nodes/include/irobot_create_nodes/motion_control/wall_follow_states.hpp
roni-kreinin/create3_sim
637f02b9f7ddcc28de35e5e003c998290a51fccd
[ "BSD-3-Clause" ]
14
2021-10-21T10:43:09.000Z
2022-03-22T13:30:44.000Z
irobot_create_common/irobot_create_nodes/include/irobot_create_nodes/motion_control/wall_follow_states.hpp
roni-kreinin/create3_sim
637f02b9f7ddcc28de35e5e003c998290a51fccd
[ "BSD-3-Clause" ]
49
2021-10-20T19:00:08.000Z
2022-03-28T11:12:51.000Z
irobot_create_common/irobot_create_nodes/include/irobot_create_nodes/motion_control/wall_follow_states.hpp
roni-kreinin/create3_sim
637f02b9f7ddcc28de35e5e003c998290a51fccd
[ "BSD-3-Clause" ]
10
2021-10-20T16:26:15.000Z
2022-03-21T00:35:24.000Z
// Copyright 2021 iRobot Corporation. All Rights Reserved. // @author Justin Kearns (jkearns@irobot.com) #ifndef IROBOT_CREATE_NODES__MOTION_CONTROL__WALL_FOLLOW_STATES_HPP_ #define IROBOT_CREATE_NODES__MOTION_CONTROL__WALL_FOLLOW_STATES_HPP_ #include <irobot_create_msgs/action/wall_follow.hpp> #include <irobot_create_msgs/msg/ir_intensity_vector.hpp> #include <tf2/utils.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <atomic> #include <memory> #include <string> #include <vector> namespace irobot_create_nodes { struct WFVelocityCommand { double translate; double rotate; }; enum class WallFollowStateID { NONE, SPIRAL, ALIGNED_SERVO, OBSTACLE_IN_FRONT, }; /// \brief Base Class for Wall Follow States in State Machine class WallFollowState { public: virtual bool get_next_velocity( const tf2::Transform & robot_pose, const irobot_create_msgs::msg::IrIntensityVector & ir_intensity, const std::vector<std::string> & active_hazard_frames, WFVelocityCommand & vel_cmd) = 0; virtual WallFollowStateID get_id() = 0; virtual bool is_engaged() = 0; }; /// \brief Execute Spiral Pattern increasing in size to engage wall class SpiralToEngageWall : public WallFollowState { public: SpiralToEngageWall(const tf2::Transform & robot_pose, int8_t follow_side) : start_orientation_{tf2::getYaw(robot_pose.getRotation())}, follow_side_{follow_side} {} bool get_next_velocity( const tf2::Transform & robot_pose, const irobot_create_msgs::msg::IrIntensityVector & ir_intensity, const std::vector<std::string> & active_hazard_frames, WFVelocityCommand & vel_cmd) override; WallFollowStateID get_id() override {return WallFollowStateID::SPIRAL;} bool is_engaged() override {return found_obstruction_;} private: const double start_orientation_; const int8_t follow_side_; std::atomic<bool> found_obstruction_ {false}; const double spiral_trans_vel_ {0.15}; const double spiral_start_rot_vel_ {M_PI / 4.0}; const double converged_angle_threshold_ {M_PI / 60.0}; unsigned int spiral_rot_divisor_ {1}; bool check_orientation_converge_ {false}; }; /// \brief Servo off of side IR sensor to maintain desired value class AlignedIRServo : public WallFollowState { public: AlignedIRServo(const rclcpp::Time start_time, int8_t follow_side) : last_seen_obs_time_{start_time}, follow_side_{follow_side}, follow_frame_{follow_side == irobot_create_msgs::action::WallFollow::Goal::FOLLOW_LEFT ? "ir_intensity_side_left" : "ir_intensity_right"} {} bool get_next_velocity( const tf2::Transform & robot_pose, const irobot_create_msgs::msg::IrIntensityVector & ir_intensity, const std::vector<std::string> & active_hazard_frames, WFVelocityCommand & vel_cmd) override; WallFollowStateID get_id() override {return WallFollowStateID::ALIGNED_SERVO;} bool is_engaged() override {return found_obstruction_;} private: rclcpp::Time last_seen_obs_time_; const int8_t follow_side_; const std::string follow_frame_; std::atomic<bool> found_obstruction_ {false}; const double align_trans_vel_ {0.15}; const int16_t min_sees_wall_ir_intensity_ {50}; const int16_t sees_wall_desired_ir_intensity_ {700}; const double ir_diff_to_rotate_scale_ {0.001}; const double max_rotate_ {M_PI / 8.0}; const rclcpp::Duration drive_after_lost_time_ {std::chrono::seconds(1)}; }; /// \brief Rotate away from obstacle in front of robot class ObstacleInFront : public WallFollowState { public: ObstacleInFront(const tf2::Transform & robot_pose, int8_t follow_side) : start_pose_angle_{tf2::getYaw(robot_pose.getRotation())}, start_pose_position_{robot_pose.getOrigin()}, follow_side_{follow_side}, side_ir_frames_{(follow_side == irobot_create_msgs::action::WallFollow::Goal::FOLLOW_LEFT) ? std::vector<std::string>({"ir_intensity_side_left"}) : std::vector<std::string>({"ir_intensity_right"})}, front_side_ir_frames_{(follow_side == irobot_create_msgs::action::WallFollow::Goal::FOLLOW_LEFT) ? std::vector<std::string>({"ir_intensity_front_left", "ir_intensity_left"}) : std::vector<std::string>({"ir_intensity_front_right"})}, opposite_ir_frames_{(follow_side == irobot_create_msgs::action::WallFollow::Goal::FOLLOW_LEFT) ? std::vector<std::string>({"ir_intensity_front_right"}) : std::vector<std::string>({"ir_intensity_front_left", "ir_intensity_left"})} {} bool get_next_velocity( const tf2::Transform & robot_pose, const irobot_create_msgs::msg::IrIntensityVector & ir_intensity, const std::vector<std::string> & active_hazard_frames, WFVelocityCommand & vel_cmd) override; WallFollowStateID get_id() override {return WallFollowStateID::OBSTACLE_IN_FRONT;} bool is_engaged() override {return aligned_;} private: double start_pose_angle_; tf2::Vector3 start_pose_position_; const int8_t follow_side_; std::atomic<bool> aligned_ {false}; const double backup_translate_ {-0.1}; const double backup_rotate_ {-0.1}; // When multiplied by RIGHT (-1) this will turn positive const double rotate_in_place_ {-M_PI / 8.0}; // When multiplied by RIGHT this will turn positive const double upcoming_translate_ {0.05}; const double upcoming_rotate_ {-M_PI / 4.0}; const std::vector<std::string> front_ir_frames_ {"ir_intensity_front_center_left", "ir_intensity_front_center_right", "ir_intensity_front_left"}; const std::vector<std::string> side_ir_frames_; const std::vector<std::string> front_side_ir_frames_; const std::vector<std::string> opposite_ir_frames_; const int16_t min_sees_wall_front_ir_intensity_ {20}; const int16_t min_sees_wall_side_ir_intensity_ {20}; const double min_linear_traversal_ {0.2}; const double min_angular_traversal_ {M_PI / 8.0}; }; /// \brief Manage state machine for transition between wall follow behaviors class WallFollowStateManager : public WallFollowState { public: explicit WallFollowStateManager(const rclcpp::Logger & logger) : logger_{logger} {} void initialize(int8_t follow_side); bool get_next_velocity( const tf2::Transform & robot_pose, const irobot_create_msgs::msg::IrIntensityVector & ir_intensity, const std::vector<std::string> & active_hazard_frames, WFVelocityCommand & vel_cmd) override; WallFollowStateID get_id() override {return WallFollowStateID::NONE;} bool is_engaged() override {return wall_engaged_;} private: const std::string odom_frame_ {"odom"}; std::string base_frame_ {"base_link"}; rclcpp::Logger logger_; std::atomic<int8_t> follow_side_{0}; std::atomic<bool> wall_engaged_{false}; std::shared_ptr<WallFollowState> current_follow_mode_ {nullptr}; }; } // namespace irobot_create_nodes #endif // IROBOT_CREATE_NODES__MOTION_CONTROL__WALL_FOLLOW_STATES_HPP_
37.646409
100
0.76695
[ "vector", "transform" ]
81a59f01fcaaaf3bdda3f8c187ee2461a112c63b
3,018
cpp
C++
graph-source-code/510-C/9707144.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/510-C/9707144.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/510-C/9707144.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #include<stdio.h> #include<iostream> #include<sstream> #include<queue> #include<math.h> #include<stdlib.h> #include<stack> #include<string.h> #include<string> #include<map> #include<algorithm> #include<time.h> #include<set> #include<vector> #include<numeric> #include<iomanip> #include<bitset> using namespace std; #define All(a) a.begin(), a.end() #define _2d(a,row,col,type) type**a=new type*[row]; for (int i=0;i<row;i++) a[i]=new type[col]; #define rep(i,n) for(int i=0;i<int(n);i++) #define repd(i,n) for(int i=n-1;i>=0;i--) #define repi(i,a,n) for(int i=int(a);i<int(n);i++) #define clr(a, n) memset(a, n, sizeof(a)); #define scn(a,n) rep(i,n) cin>>a[i]; #define scn2(a,row,col) rep(i,row) rep(j,col) cin>>a[i][j]; #define prn(a,n) rep(i,n-1) cout<<a[i]<<" "; cout<<a[n-1]<<endl; #define prn2(a,row,col) rep(i,row){rep(j,col-1) cout<<a[i][j]<<" "; cout<<a[i][col-1]<<endl;} #define dri(x) scanf("%d",&(x)) #define drii(x,y) scanf("%d%d",&(x),&(y)) #define drl(x) scanf("%I64d",&(x)) #define drll(x,y) scanf("%I64d%I64d",&(x),&(y)) #define mp(a, b) make_pair(a, b) #define Odd(x) x%2!=0 #define Even(x) x%2==0 #define Pi 3.14 #define INF 2000000000 // 2 billion typedef long long ll; typedef unsigned long ul; typedef unsigned long long ull; typedef long double ld; typedef vector<int> vi; typedef vector<long> vl; typedef vector<ll> vll; typedef vector<double> vd; typedef vector<string> vs; typedef pair<int, int> pii; typedef pair<int, string> is; typedef vector<pii> vii; #define FilesX #define TimeX /*---------------------------*/ vector<vi > adj(26); int vis[26]; vi topo; bool dfs1(int i){ vis[i] = 1; rep(j, adj[i].size()){ if (vis[adj[i][j]] == 1) return true; if (vis[adj[i][j]] == 2) continue; if (dfs1(adj[i][j])) return true; } vis[i] = 2; return false; } void dfs(int i){ vis[i] = true; rep(j, adj[i].size()) if (!vis[adj[i][j]]) dfs(adj[i][j]); topo.push_back(i); } void solution(){ int n; cin>>n; vs a(n); rep(i, n) cin>>a[i]; rep(i, n-1){ rep(j, min(a[i].length(), a[i+1].length())) if (a[i][j] != a[i+1][j]){ adj[a[i][j] - 'a'].push_back(a[i+1][j] - 'a'); break; } } rep(i, n-1){ repi(j, i+1, n){ if (a[i].length() > a[j].length() && a[i].substr(0, a[j].length()) == a[j]){ cout<<"Impossible"; return; } } } rep(i, 26){ clr(vis, false); if (dfs1(i)) {cout<<"Impossible"; return;} } clr(vis, false); rep(i, 26){ if (!vis[i]) dfs(i); } reverse(All(topo)); rep(i, topo.size()) cout<<char(topo[i] + 'a'); cout<<endl; } /*---------------------------*/ int main(){ #ifdef Files freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif double beg=clock(); ios::sync_with_stdio(false); solution(); #ifdef Time cout << endl; double end=clock(); printf("*** Total time = %.3f sec ***", (end - beg) / CLOCKS_PER_SEC); #endif return 0; }
22.522388
96
0.560968
[ "vector" ]
81a5fb238062efa3e0dbc76c8805e8cb40a5eb1e
748
cc
C++
cinn/hlir/framework/scope.cc
edithgogo/CINN
bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292
[ "Apache-2.0" ]
1
2019-10-23T09:16:23.000Z
2019-10-23T09:16:23.000Z
cinn/hlir/framework/scope.cc
edithgogo/CINN
bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292
[ "Apache-2.0" ]
null
null
null
cinn/hlir/framework/scope.cc
edithgogo/CINN
bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292
[ "Apache-2.0" ]
null
null
null
#include "cinn/hlir/framework/scope.h" #include "cinn/common/common.h" namespace cinn { namespace hlir { namespace framework { Variable* Scope::FindVar(const std::string& name) const { auto it = data_.find(name); if (it != data_.end()) return it->second.get(); return nullptr; } Tensor Scope::GetTensor(const std::string& name) const { CheckVarNameValid(name); auto* var = FindVar(name); CHECK(var) << "No variable called [" << name << "] found"; return std::get<Tensor>(*var); } std::vector<std::string_view> Scope::var_names() const { std::vector<std::string_view> names; for (auto& item : data_) { names.push_back(item.first); } return names; } } // namespace framework } // namespace hlir } // namespace cinn
22.666667
60
0.671123
[ "vector" ]
81ab0f65977c40fc4c6971c0b684ef7e4c3118b9
1,466
hh
C++
src/FreeflyCam.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/FreeflyCam.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/FreeflyCam.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <typed-geometry/types/pos.hh> #include <typed-geometry/types/quat.hh> #include <typed-geometry/types/vec.hh> namespace gamedev { // simple camera state struct FreeflyCamState { tg::pos3 position = tg::pos3(0); tg::vec3 forward = tg::vec3(0, 0, 1); void moveRelative(tg::vec3 distance, bool freeFlyEnabled); void mouselook(float dx, float dy); void setFocus(tg::pos3 focus, tg::vec3 global_offset); }; // smoothed camera, has a physical (current) and target state struct FreeflyCam { // current state FreeflyCamState physical; // state toward which this interpolates FreeflyCamState target; float sensitivityRotation = 70.f; float sensitivityPosition = 25.f; // interpolates physical state towards target based on delta time and sensitivities // returns true if changes to physical were made bool interpolateToTarget(float dt); }; // Smoothed lerp alpha, framerate-correct inline float smoothLerpAlpha(float smoothing, float dt) { return 1 - std::pow(smoothing, dt); } // Exponential decay alpha, framerate-correct damp / lerp inline float exponentialDecayAlpha(float lambda, float dt) { return 1 - std::exp(-lambda * dt); } // alpha based on the halftime between current and target state inline float halftimeLerpAlpha(float halftime, float dt) { return 1 - std::pow(.5f, dt / halftime); } tg::quat forwardToRotation(tg::vec3 fwd, tg::vec3 up = {0, 1, 0}); }
29.32
101
0.72101
[ "geometry" ]
81b799ede6fffc96667904c24b1a307e38788868
7,768
cpp
C++
clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
nickbabcock/EECS381StyleCheck
271a15140229e5dbc1798328edfe6ca8c632a7be
[ "MIT" ]
3
2018-03-22T05:23:45.000Z
2018-09-11T17:19:08.000Z
clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
nickbabcock/EECS381StyleCheck
271a15140229e5dbc1798328edfe6ca8c632a7be
[ "MIT" ]
null
null
null
clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
nickbabcock/EECS381StyleCheck
271a15140229e5dbc1798328edfe6ca8c632a7be
[ "MIT" ]
null
null
null
//===--- DanglingHandleCheck.cpp - clang-tidy------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DanglingHandleCheck.h" #include "../utils/Matchers.h" #include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" using namespace clang::ast_matchers; using namespace clang::tidy::matchers; namespace clang { namespace tidy { namespace bugprone { namespace { ast_matchers::internal::BindableMatcher<Stmt> handleFrom(const ast_matchers::internal::Matcher<RecordDecl> &IsAHandle, const ast_matchers::internal::Matcher<Expr> &Arg) { return expr( anyOf(cxxConstructExpr(hasDeclaration(cxxMethodDecl(ofClass(IsAHandle))), hasArgument(0, Arg)), cxxMemberCallExpr(hasType(cxxRecordDecl(IsAHandle)), callee(memberExpr(member(cxxConversionDecl()))), on(Arg)))); } ast_matchers::internal::Matcher<Stmt> handleFromTemporaryValue( const ast_matchers::internal::Matcher<RecordDecl> &IsAHandle) { // If a ternary operator returns a temporary value, then both branches hold a // temporary value. If one of them is not a temporary then it must be copied // into one to satisfy the type of the operator. const auto TemporaryTernary = conditionalOperator(hasTrueExpression(cxxBindTemporaryExpr()), hasFalseExpression(cxxBindTemporaryExpr())); return handleFrom(IsAHandle, anyOf(cxxBindTemporaryExpr(), TemporaryTernary)); } ast_matchers::internal::Matcher<RecordDecl> isASequence() { return hasAnyName("::std::deque", "::std::forward_list", "::std::list", "::std::vector"); } ast_matchers::internal::Matcher<RecordDecl> isASet() { return hasAnyName("::std::set", "::std::multiset", "::std::unordered_set", "::std::unordered_multiset"); } ast_matchers::internal::Matcher<RecordDecl> isAMap() { return hasAnyName("::std::map", "::std::multimap", "::std::unordered_map", "::std::unordered_multimap"); } ast_matchers::internal::BindableMatcher<Stmt> makeContainerMatcher( const ast_matchers::internal::Matcher<RecordDecl> &IsAHandle) { // This matcher could be expanded to detect: // - Constructors: eg. vector<string_view>(3, string("A")); // - emplace*(): This requires a different logic to determine that // the conversion will happen inside the container. // - map's insert: This requires detecting that the pair conversion triggers // the bug. A little more complicated than what we have now. return callExpr( hasAnyArgument( ignoringParenImpCasts(handleFromTemporaryValue(IsAHandle))), anyOf( // For sequences: assign, push_back, resize. cxxMemberCallExpr( callee(functionDecl(hasAnyName("assign", "push_back", "resize"))), on(expr(hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(recordDecl(isASequence())))))))), // For sequences and sets: insert. cxxMemberCallExpr(callee(functionDecl(hasName("insert"))), on(expr(hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(recordDecl( anyOf(isASequence(), isASet()))))))))), // For maps: operator[]. cxxOperatorCallExpr(callee(cxxMethodDecl(ofClass(isAMap()))), hasOverloadedOperatorName("[]")))); } } // anonymous namespace DanglingHandleCheck::DanglingHandleCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), HandleClasses(utils::options::parseStringList(Options.get( "HandleClasses", "std::basic_string_view;std::experimental::basic_string_view"))), IsAHandle(cxxRecordDecl(hasAnyName(std::vector<StringRef>( HandleClasses.begin(), HandleClasses.end()))) .bind("handle")) {} void DanglingHandleCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "HandleClasses", utils::options::serializeStringList(HandleClasses)); } void DanglingHandleCheck::registerMatchersForVariables(MatchFinder *Finder) { const auto ConvertedHandle = handleFromTemporaryValue(IsAHandle); // Find 'Handle foo(ReturnsAValue());' Finder->addMatcher( varDecl(hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(cxxRecordDecl(IsAHandle))))), hasInitializer( exprWithCleanups(has(ignoringParenImpCasts(ConvertedHandle))) .bind("bad_stmt"))), this); // Find 'Handle foo = ReturnsAValue();' Finder->addMatcher( varDecl( hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(cxxRecordDecl(IsAHandle))))), unless(parmVarDecl()), hasInitializer(exprWithCleanups(has(ignoringParenImpCasts(handleFrom( IsAHandle, ConvertedHandle)))) .bind("bad_stmt"))), this); // Find 'foo = ReturnsAValue(); // foo is Handle' Finder->addMatcher( cxxOperatorCallExpr(callee(cxxMethodDecl(ofClass(IsAHandle))), hasOverloadedOperatorName("="), hasArgument(1, ConvertedHandle)) .bind("bad_stmt"), this); // Container insertions that will dangle. Finder->addMatcher(makeContainerMatcher(IsAHandle).bind("bad_stmt"), this); } void DanglingHandleCheck::registerMatchersForReturn(MatchFinder *Finder) { // Return a local. Finder->addMatcher( returnStmt( // The AST contains two constructor calls: // 1. Value to Handle conversion. // 2. Handle copy construction. // We have to match both. has(ignoringImplicit(handleFrom( IsAHandle, handleFrom(IsAHandle, declRefExpr(to(varDecl( // Is function scope ... hasAutomaticStorageDuration(), // ... and it is a local array or Value. anyOf(hasType(arrayType()), hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(recordDecl( unless(IsAHandle)))))))))))))), // Temporary fix for false positives inside lambdas. unless(hasAncestor(lambdaExpr()))) .bind("bad_stmt"), this); // Return a temporary. Finder->addMatcher( returnStmt( has(ignoringParenImpCasts(exprWithCleanups(has(ignoringParenImpCasts( handleFrom(IsAHandle, handleFromTemporaryValue(IsAHandle)))))))) .bind("bad_stmt"), this); } void DanglingHandleCheck::registerMatchers(MatchFinder *Finder) { registerMatchersForVariables(Finder); registerMatchersForReturn(Finder); } void DanglingHandleCheck::check(const MatchFinder::MatchResult &Result) { auto *Handle = Result.Nodes.getNodeAs<CXXRecordDecl>("handle"); diag(Result.Nodes.getNodeAs<Stmt>("bad_stmt")->getBeginLoc(), "%0 outlives its value") << Handle->getQualifiedNameAsString(); } } // namespace bugprone } // namespace tidy } // namespace clang
41.100529
80
0.617147
[ "vector" ]
81be1cf06b2a6868ebf9f7dc993176a4cf26fdfa
573
cpp
C++
leetcode/1461. Check If a String Contains All Binary Codes of Size K/s1.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
1
2021-02-11T01:23:10.000Z
2021-02-11T01:23:10.000Z
leetcode/1461. Check If a String Contains All Binary Codes of Size K/s1.cpp
AnupSadhukhan/LeetCode
725c22ec2f11f5232fd7ab6d63ab4fcd800f201b
[ "Fair" ]
null
null
null
leetcode/1461. Check If a String Contains All Binary Codes of Size K/s1.cpp
AnupSadhukhan/LeetCode
725c22ec2f11f5232fd7ab6d63ab4fcd800f201b
[ "Fair" ]
1
2021-03-25T17:11:14.000Z
2021-03-25T17:11:14.000Z
// OJ: https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ // Author: github.com/lzl124631x // Time: O(N + min(N, 2^K))) // Space: O(2^K) class Solution { public: bool hasAllCodes(string s, int k) { vector<bool> v(1 << k); int n = 0, mask = (1 << k) - 1; for (int i = 0; i < s.size(); ++i) { n = (n << 1) & mask | (s[i] - '0'); if (i >= k - 1) v[n] = true; } for (int i = 0; i < (1 << k); ++i) { if (!v[i]) return false; } return true; } };
30.157895
91
0.448517
[ "vector" ]
81c0a474d7003f6ed075d152f298b8924096f3d0
33,795
cpp
C++
test/unittests/lib/parser/test_ParserNumericInstr.cpp
WasmVM/wass
e35962e1637a1445ab8ad97e5a06ee4d59b49fd7
[ "BSD-3-Clause" ]
null
null
null
test/unittests/lib/parser/test_ParserNumericInstr.cpp
WasmVM/wass
e35962e1637a1445ab8ad97e5a06ee4d59b49fd7
[ "BSD-3-Clause" ]
null
null
null
test/unittests/lib/parser/test_ParserNumericInstr.cpp
WasmVM/wass
e35962e1637a1445ab8ad97e5a06ee4d59b49fd7
[ "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <variant> #include <vector> #include <Error.hpp> #include <parser/ParserContext.hpp> #include <parser/ParserNumericInstr.hpp> #include <structure/BaseInstr.hpp> #include <Helper.hpp> TEST(unittest_ParserNumericInstr, i32_clz){ std::vector<char> data(create_char_vector("i32.clz")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32ClzInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_ctz){ std::vector<char> data(create_char_vector("i32.ctz")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32CtzInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_add){ std::vector<char> data(create_char_vector("i32.add")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32AddInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_sub){ std::vector<char> data(create_char_vector("i32.sub")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32SubInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_mul){ std::vector<char> data(create_char_vector("i32.mul")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32MulInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_div_s){ std::vector<char> data(create_char_vector("i32.div_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32DivSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_div_u){ std::vector<char> data(create_char_vector("i32.div_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32DivUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_rem_s){ std::vector<char> data(create_char_vector("i32.rem_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32RemSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_rem_u){ std::vector<char> data(create_char_vector("i32.rem_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32RemUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_and){ std::vector<char> data(create_char_vector("i32.and")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32AndInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_or){ std::vector<char> data(create_char_vector("i32.or")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32OrInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_xor){ std::vector<char> data(create_char_vector("i32.xor")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32XorInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_shl){ std::vector<char> data(create_char_vector("i32.shl")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32ShlInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_shr_s){ std::vector<char> data(create_char_vector("i32.shr_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32ShrSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_shr_u){ std::vector<char> data(create_char_vector("i32.shr_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32ShrUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_rotl){ std::vector<char> data(create_char_vector("i32.rotl")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32RotlInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_rotr){ std::vector<char> data(create_char_vector("i32.rotr")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32RotrInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_clz){ std::vector<char> data(create_char_vector("i64.clz")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ClzInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_ctz){ std::vector<char> data(create_char_vector("i64.ctz")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64CtzInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_add){ std::vector<char> data(create_char_vector("i64.add")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64AddInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_sub){ std::vector<char> data(create_char_vector("i64.sub")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64SubInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_mul){ std::vector<char> data(create_char_vector("i64.mul")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64MulInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_div_s){ std::vector<char> data(create_char_vector("i64.div_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64DivSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_div_u){ std::vector<char> data(create_char_vector("i64.div_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64DivUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_rem_s){ std::vector<char> data(create_char_vector("i64.rem_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64RemSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_rem_u){ std::vector<char> data(create_char_vector("i64.rem_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64RemUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_and){ std::vector<char> data(create_char_vector("i64.and")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64AndInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_or){ std::vector<char> data(create_char_vector("i64.or")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64OrInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_xor){ std::vector<char> data(create_char_vector("i64.xor")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64XorInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_shl){ std::vector<char> data(create_char_vector("i64.shl")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ShlInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_shr_s){ std::vector<char> data(create_char_vector("i64.shr_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ShrSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_shr_u){ std::vector<char> data(create_char_vector("i64.shr_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ShrUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_rotl){ std::vector<char> data(create_char_vector("i64.rotl")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64RotlInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_rotr){ std::vector<char> data(create_char_vector("i64.rotr")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64RotrInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_abs){ std::vector<char> data(create_char_vector("f32.abs")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32AbsInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_neg){ std::vector<char> data(create_char_vector("f32.neg")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32NegInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_ceil){ std::vector<char> data(create_char_vector("f32.ceil")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32CeilInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_floor){ std::vector<char> data(create_char_vector("f32.floor")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32FloorInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_trunc){ std::vector<char> data(create_char_vector("f32.trunc")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32TruncInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_nearest){ std::vector<char> data(create_char_vector("f32.nearest")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32NearestInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_sqrt){ std::vector<char> data(create_char_vector("f32.sqrt")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32SqrtInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_add){ std::vector<char> data(create_char_vector("f32.add")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32AddInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_sub){ std::vector<char> data(create_char_vector("f32.sub")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32SubInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_mul){ std::vector<char> data(create_char_vector("f32.mul")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32MulInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_div){ std::vector<char> data(create_char_vector("f32.div")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32DivInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_min){ std::vector<char> data(create_char_vector("f32.min")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32MinInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_max){ std::vector<char> data(create_char_vector("f32.max")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32MaxInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_copysign){ std::vector<char> data(create_char_vector("f32.copysign")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32CopysignInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_abs){ std::vector<char> data(create_char_vector("f64.abs")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64AbsInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_neg){ std::vector<char> data(create_char_vector("f64.neg")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64NegInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_ceil){ std::vector<char> data(create_char_vector("f64.ceil")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64CeilInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_floor){ std::vector<char> data(create_char_vector("f64.floor")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64FloorInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_trunc){ std::vector<char> data(create_char_vector("f64.trunc")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64TruncInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_nearest){ std::vector<char> data(create_char_vector("f64.nearest")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64NearestInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_sqrt){ std::vector<char> data(create_char_vector("f64.sqrt")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64SqrtInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_add){ std::vector<char> data(create_char_vector("f64.add")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64AddInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_sub){ std::vector<char> data(create_char_vector("f64.sub")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64SubInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_mul){ std::vector<char> data(create_char_vector("f64.mul")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64MulInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_div){ std::vector<char> data(create_char_vector("f64.div")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64DivInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_min){ std::vector<char> data(create_char_vector("f64.min")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64MinInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_max){ std::vector<char> data(create_char_vector("f64.max")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64MaxInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_copysign){ std::vector<char> data(create_char_vector("f64.copysign")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64CopysignInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_eqz){ std::vector<char> data(create_char_vector("i32.eqz")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32EqzInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_eq){ std::vector<char> data(create_char_vector("i32.eq")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32EqInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_ne){ std::vector<char> data(create_char_vector("i32.ne")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32NeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_lt_s){ std::vector<char> data(create_char_vector("i32.lt_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32LtSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_lt_u){ std::vector<char> data(create_char_vector("i32.lt_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32LtUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_gt_s){ std::vector<char> data(create_char_vector("i32.gt_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32GtSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_gt_u){ std::vector<char> data(create_char_vector("i32.gt_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32GtUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_le_s){ std::vector<char> data(create_char_vector("i32.le_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32LeSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_le_u){ std::vector<char> data(create_char_vector("i32.le_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32LeUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_ge_s){ std::vector<char> data(create_char_vector("i32.ge_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32GeSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_ge_u){ std::vector<char> data(create_char_vector("i32.ge_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32GeUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_eqz){ std::vector<char> data(create_char_vector("i64.eqz")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64EqzInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_eq){ std::vector<char> data(create_char_vector("i64.eq")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64EqInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_ne){ std::vector<char> data(create_char_vector("i64.ne")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64NeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_lt_s){ std::vector<char> data(create_char_vector("i64.lt_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64LtSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_lt_u){ std::vector<char> data(create_char_vector("i64.lt_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64LtUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_gt_s){ std::vector<char> data(create_char_vector("i64.gt_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64GtSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_gt_u){ std::vector<char> data(create_char_vector("i64.gt_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64GtUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_le_s){ std::vector<char> data(create_char_vector("i64.le_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64LeSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_le_u){ std::vector<char> data(create_char_vector("i64.le_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64LeUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_ge_s){ std::vector<char> data(create_char_vector("i64.ge_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64GeSInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_ge_u){ std::vector<char> data(create_char_vector("i64.ge_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64GeUInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_eq){ std::vector<char> data(create_char_vector("f32.eq")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32EqInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_ne){ std::vector<char> data(create_char_vector("f32.ne")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32NeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_lt){ std::vector<char> data(create_char_vector("f32.lt")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32LtInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_gt){ std::vector<char> data(create_char_vector("f32.gt")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32GtInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_le){ std::vector<char> data(create_char_vector("f32.le")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32LeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_ge){ std::vector<char> data(create_char_vector("f32.ge")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32GeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_eq){ std::vector<char> data(create_char_vector("f64.eq")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64EqInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_ne){ std::vector<char> data(create_char_vector("f64.ne")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64NeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_lt){ std::vector<char> data(create_char_vector("f64.lt")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64LtInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_gt){ std::vector<char> data(create_char_vector("f64.gt")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64GtInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_le){ std::vector<char> data(create_char_vector("f64.le")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64LeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_ge){ std::vector<char> data(create_char_vector("f64.ge")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64GeInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_wrap_i64){ std::vector<char> data(create_char_vector("i32.wrap_i64")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32WrapI64Instr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_trunc_f32_s){ std::vector<char> data(create_char_vector("i32.trunc_f32_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32TruncF32SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_trunc_f32_u){ std::vector<char> data(create_char_vector("i32.trunc_f32_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32TruncF32UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_trunc_f64_s){ std::vector<char> data(create_char_vector("i32.trunc_f64_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32TruncF64SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_trunc_f64_u){ std::vector<char> data(create_char_vector("i32.trunc_f64_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32TruncF64UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_trunc_f32_s){ std::vector<char> data(create_char_vector("i64.trunc_f32_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64TruncF32SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_trunc_f32_u){ std::vector<char> data(create_char_vector("i64.trunc_f32_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64TruncF32UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_trunc_f64_s){ std::vector<char> data(create_char_vector("i64.trunc_f64_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64TruncF64SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_trunc_f64_u){ std::vector<char> data(create_char_vector("i64.trunc_f64_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64TruncF64UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_extend_i32_s){ std::vector<char> data(create_char_vector("i64.extend_i32_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ExtendI32SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_extend_i32_u){ std::vector<char> data(create_char_vector("i64.extend_i32_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ExtendI32UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_convert_i32_s){ std::vector<char> data(create_char_vector("f32.convert_i32_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32ConvertI32SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_convert_i32_u){ std::vector<char> data(create_char_vector("f32.convert_i32_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32ConvertI32UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_convert_i64_s){ std::vector<char> data(create_char_vector("f32.convert_i64_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32ConvertI64SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_convert_i64_u){ std::vector<char> data(create_char_vector("f32.convert_i64_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32ConvertI64UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_convert_i32_s){ std::vector<char> data(create_char_vector("f64.convert_i32_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64ConvertI32SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_convert_i32_u){ std::vector<char> data(create_char_vector("f64.convert_i32_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64ConvertI32UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_convert_i64_s){ std::vector<char> data(create_char_vector("f64.convert_i64_s")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64ConvertI64SInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_convert_i64_u){ std::vector<char> data(create_char_vector("f64.convert_i64_u")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64ConvertI64UInstr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_demote_f64){ std::vector<char> data(create_char_vector("f32.demote_f64")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32DemoteF64Instr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_promote_f32){ std::vector<char> data(create_char_vector("f64.promote_f32")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64PromoteF32Instr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i32_reinterpret_f32){ std::vector<char> data(create_char_vector("i32.reinterpret_f32")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I32ReinterpretF32Instr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, i64_reinterpret_f64){ std::vector<char> data(create_char_vector("i64.reinterpret_f64")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<I64ReinterpretF64Instr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f32_reinterpret_i32){ std::vector<char> data(create_char_vector("f32.reinterpret_i32")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F32ReinterpretI32Instr>(&result), nullptr); } TEST(unittest_ParserNumericInstr, f64_reinterpret_i64){ std::vector<char> data(create_char_vector("f64.reinterpret_i64")); ParserContext context(data); ParserNumericInstr result(context); EXPECT_EQ(context.cursor, data.end()); EXPECT_NE(std::get_if<F64ReinterpretI64Instr>(&result), nullptr); }
34.590583
68
0.762213
[ "vector" ]
81c1d1a7af1ebe0df5711cf0153195eefd47d8c4
6,944
cc
C++
unix/iumlapi/src/Entity.cc
skind30/iuml-dumper
258bf82f3d00f502e52fdee325f06a8637bc9842
[ "Apache-2.0" ]
null
null
null
unix/iumlapi/src/Entity.cc
skind30/iuml-dumper
258bf82f3d00f502e52fdee325f06a8637bc9842
[ "Apache-2.0" ]
null
null
null
unix/iumlapi/src/Entity.cc
skind30/iuml-dumper
258bf82f3d00f502e52fdee325f06a8637bc9842
[ "Apache-2.0" ]
4
2019-03-20T15:13:23.000Z
2020-09-03T20:46:04.000Z
// // Filename : Entity.cc // // UK Crown Copyright (c) 2005. All Rights Reserved // #include "iumlapi/iUMLAPI.hh" #include "iumlapi/Entity.hh" #include <algorithm> iUMLAPI::Entity::Entity() : valid(false) { } iUMLAPI::Entity::Entity(const API_ENTITY& other) : valid(true) { iUMLAPI::copy_of_entity(other,entity); } iUMLAPI::Entity::Entity(const Entity& other) { if ( other.valid ) { iUMLAPI::copy_of_entity(other.entity,entity); valid = true; } else { valid = false; } } iUMLAPI::Entity& iUMLAPI::Entity::operator= ( const API_ENTITY& other ) { if ( valid && ! iUMLAPI::same_entity(other,entity) ) { iUMLAPI::release_entity(entity); } iUMLAPI::copy_of_entity(other,entity); valid = true; return *this; } iUMLAPI::Entity& iUMLAPI::Entity::operator= ( const Entity& other ) { if ( other.valid ) { if ( valid && ! iUMLAPI::same_entity(other.entity,entity) ) { iUMLAPI::release_entity(entity); } iUMLAPI::copy_of_entity(other.entity,entity); valid = true; } else { if ( valid ) { iUMLAPI::release_entity(entity); valid = false; } } return *this; } iUMLAPI::Entity::~Entity() { if ( valid ) { try { iUMLAPI::release_entity(entity); } catch(...) { std::cerr << "Exception thrown in release." << std::endl; } } } API_ATTR_TYPE iUMLAPI::Entity::getAttributeType ( const std::string& name, UMLDomain domain ) const { setUMLDomain(domain); if ( !valid ) { throw iUMLAPI::Error("getAttributeType","Invalid entity"); } API_ATTRIBUTE value; iUMLAPI::read_attribute(entity,name,value); API_ATTR_TYPE result = value.attr_type; iUMLAPI::release_attribute(value); return result; } iUMLAPI::Entity::Attribute iUMLAPI::Entity::getAttribute ( const std::string& name, UMLDomain domain ) const { setUMLDomain(domain); if ( !valid ) { throw iUMLAPI::Error("getAttribute","Invalid entity"); } API_ATTRIBUTE value; iUMLAPI::read_attribute(entity,name,value); Attribute result(value); iUMLAPI::release_attribute(value); return result; } void iUMLAPI::Entity::setAttribute ( const std::string& name, const Attribute& value, UMLDomain domain ) { setUMLDomain(domain); if ( !valid ) { throw iUMLAPI::Error("setAttribute","Invalid entity"); } iUMLAPI::update_attribute(entity,name,value); } std::vector<iUMLAPI::Entity> iUMLAPI::Entity::navigate ( const std::string& relationship, UMLDomain domain ) const { if (valid) { std::string::size_type commaPos = relationship.find(','); std::string firstHop = (commaPos==std::string::npos)?relationship:relationship.substr(0,commaPos); std::string toNavigate = (commaPos==std::string::npos)?"":relationship.substr(commaPos+1); setUMLDomain(domain); API_ENTITY_LIST* list = 0; iUMLAPI::read_relationship(entity,firstHop,list); std::vector<Entity> result; API_ENTITY_LIST* element = list; while ( element ) { if ( toNavigate == "" ) { result.push_back(element->entity); } else { std::vector<Entity> children = Entity(element->entity).navigate(toNavigate,domain); std::copy(children.begin(),children.end(),std::back_inserter(result)); } element = element->next_entity; } if (list) iUMLAPI::release_entity_list(list); return result; } else { return std::vector<Entity>(); } } iUMLAPI::Entity iUMLAPI::Entity::navigateOne ( const std::string& relationship, UMLDomain domain ) const { if (valid) { setUMLDomain(domain); API_ENTITY_LIST* list = 0; iUMLAPI::read_relationship(entity,relationship,list); if ( list ) { Entity result(list->entity); iUMLAPI::release_entity_list(list); return result; } else return Entity(); } else { return Entity(); } } void iUMLAPI::Entity::acquireTopLevelLock() { API_ENTITY editable; iUMLAPI::acquire_top_level_lock(entity,editable); iUMLAPI::release_entity(entity); entity = editable; } void iUMLAPI::Entity::acquireAnalysisAreaLock() { API_ENTITY editable; iUMLAPI::acquire_analysis_area_lock(entity,editable); iUMLAPI::release_entity(entity); entity = editable; } void iUMLAPI::Entity::acquireProjectVersionLock() { API_ENTITY editable; iUMLAPI::acquire_project_version_lock(entity,editable); iUMLAPI::release_entity(entity); entity = editable; } iUMLAPI::Entity::UMLDomain iUMLAPI::Entity::currentDomain = None; void iUMLAPI::Entity::setUMLDomain ( UMLDomain newDomain ) { if ( newDomain != currentDomain ) { switch ( newDomain ) { case ATT: iUMLAPI::set_domain("ATT"); break; case BS: iUMLAPI::set_domain("BS"); break; case ORG: iUMLAPI::set_domain("ORG"); break; case TAGS: iUMLAPI::set_domain("TAGS"); break; case XUML: iUMLAPI::set_domain("XUML"); break; case DM: iUMLAPI::set_domain("DM"); break; case DS: iUMLAPI::set_domain("DS"); break; case REQ: iUMLAPI::set_domain("REQ"); break; case SQ: iUMLAPI::set_domain("SQ"); break; case UC: iUMLAPI::set_domain("UC"); break; default: break; } currentDomain = newDomain; } } iUMLAPI::Entity::Attribute::Attribute ( const API_ATTRIBUTE& attribute ) : type(attribute.attr_type) { switch ( type ) { case API_INTEGER: longVal = attribute.attr_value.v_int; break; case API_BOOLEAN: boolVal = attribute.attr_value.v_bool; break; case API_STRING: stringVal = attribute.attr_value.v_str; break; } } iUMLAPI::Entity::Attribute::Attribute ( const std::string& value ) : type(API_STRING), stringVal(value) { } iUMLAPI::Entity::Attribute::Attribute ( bool value ) : type(API_BOOLEAN), boolVal(value) { } iUMLAPI::Entity::Attribute::Attribute ( long value ) : type(API_INTEGER), longVal(value) { } bool iUMLAPI::Entity::Attribute::getBool() const { if ( type != API_BOOLEAN ){std::cerr << "Cast error: Expected " << API_BOOLEAN << " got " << type << std::endl; throw std::bad_cast(); } return boolVal; } long iUMLAPI::Entity::Attribute::getLong() const { if ( type != API_INTEGER ) {std::cerr << "Cast error: Expected " << API_INTEGER << " got " << type << std::endl; throw std::bad_cast(); } return longVal; } const std::string& iUMLAPI::Entity::Attribute::getString() const { if ( type != API_STRING ) {std::cerr << "Cast error: Expected " << API_STRING << " got " << type << std::endl; throw std::bad_cast(); } return stringVal; } iUMLAPI::Entity::Attribute::operator API_ATTRIBUTE() const { API_ATTRIBUTE result; result.attr_type = type; switch ( type ) { case API_INTEGER: result.attr_value.v_int = longVal; break; case API_BOOLEAN: result.attr_value.v_bool = boolVal; break; case API_STRING: result.attr_value.v_str = const_cast<char*>(stringVal.c_str()); break; } return result; }
25.623616
223
0.660426
[ "vector" ]
81c42a64e0ea3e05738df2c0ee42310d7cc4d06e
1,814
cpp
C++
Problems/Hackerrank/minimumBribes2.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
1
2021-07-08T01:02:06.000Z
2021-07-08T01:02:06.000Z
Problems/Hackerrank/minimumBribes2.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
Problems/Hackerrank/minimumBribes2.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
/****************************************************************************** Problem: Array - Minimum Bribes (HR) *******************************************************************************/ #include <iostream> #include <vector> #include <cmath> void minimumBribes(std::vector<int> q) { const int bribeLimit = 2; int swapCount = 0; int bribeCount = 0; // optimization - flag to check if any swaps were made: // -- if true: it's still unordered, keep the loop running // -- if false: it's already sorted, no need to keep checking, break out: bool swapped = false; // check if there any element which exceeded the bribe limit: // num. of bribes = element currently in the pos.- original holder of that pos. for (size_t i{0}; i < q.size(); i++) { bribeCount = q.at(i) - (i + 1); // in case bribe limit was exceeded: if (bribeCount > bribeLimit) { std::cout << "Too chaotic" << "\n"; return; } } // perform a bubble sort and check how many swaps were done by sorting // the array and counting how many swaps were needed to sort it: for (size_t i{0}; i < q.size(); i++) { for (size_t j{0}; j < q.size() - i - 1; j++) { if (q.at(j) > q.at(j + 1)) { int temp = q.at(j); q.at(j) = q.at(j + 1); q.at(j + 1) = temp; swapCount++; swapped = true; } } if (swapped == false) break; swapped = true; } std::cout << swapCount << "\n"; } int main() { std::vector<int> q1{2, 1, 5, 3, 4}; std::vector<int> q2{5, 1, 2, 3, 7, 8, 6, 4}; std::vector<int> q3{1, 2, 5, 3, 7, 8, 6, 4}; minimumBribes(q1); std::cout << "-----" << "\n"; minimumBribes(q2); std::cout << "-----" << "\n"; minimumBribes(q3); return 0; }
25.194444
81
0.491731
[ "vector" ]
81c68eb2e9e387fefcb226e0f76796c8deca7809
3,070
cpp
C++
Modules/M2aiaSignalProcessing/Testing/m2CalibrationTest.cpp
ivowolf/M2aia
03cfe3495bc706cbb0b00a2916b8f0a3cb398e25
[ "BSD-3-Clause" ]
7
2021-07-22T06:52:01.000Z
2022-02-17T12:53:31.000Z
Modules/M2aiaSignalProcessing/Testing/m2CalibrationTest.cpp
ivowolf/M2aia
03cfe3495bc706cbb0b00a2916b8f0a3cb398e25
[ "BSD-3-Clause" ]
4
2021-07-25T22:29:33.000Z
2022-02-22T13:21:30.000Z
Modules/M2aiaSignalProcessing/Testing/m2CalibrationTest.cpp
ivowolf/M2aia
03cfe3495bc706cbb0b00a2916b8f0a3cb398e25
[ "BSD-3-Clause" ]
2
2021-06-23T11:53:11.000Z
2021-07-22T06:14:24.000Z
/*=================================================================== MSI applications for interactive analysis in MITK (M2aia) Copyright (c) Jonas Cordes All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt for details. ===================================================================*/ #include "mitkIOUtil.h" #include <algorithm> #include <m2Normalization.h> #include <m2TestingConfig.h> #include <mitkTestFixture.h> #include <mitkTestingMacros.h> #include <numeric> #include <random> //#include <boost/algorithm/string.hpp> class m2CalibrationTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(m2CalibrationTestSuite); MITK_TEST(ApplyTIC_RandomGaussianSignal_shouldReturnTrue); CPPUNIT_TEST_SUITE_END(); /* Signal was generated once using the following procedure ----- const double mean = 1.0; const double stddev = 0.33; std::default_random_engine generator; generator.seed(142191); std::normal_distribution<double> dist(mean, stddev); std::vector<double> signal; auto it = std::inserter(signal, std::begin(signal)); for (int i = 0; i < 1000; ++i) it = dist(generator); ----- */ private: std::vector<double> ReadDoubleVector(const std::string &fileNameInM2aiaDir, char delim = '\n') { std::vector<double> signal; std::ifstream f(GetTestDataFilePath(fileNameInM2aiaDir, M2AIA_DATA_DIR)); std::string line; while (std::getline(f, line, delim)) { signal.push_back(std::stod(line)); } return signal; } template <class T> void WriteVector( const std::vector<T> & vec, const std::string &fileNameInM2aiaDir, char delim = '\n', std::function<double(T &)> &func = [](T &t) { return t; }) { std::ofstream f(GetTestDataFilePath(fileNameInM2aiaDir, M2AIA_DATA_DIR)); for (int i = 0; i < vec.size(); i++) { f << std::setprecision(128) << vec[i]; if (i < vec.size() - 1) f << delim; } } public: void ApplyTIC_RandomGaussianSignal_shouldReturnTrue() { /*{ std::ofstream f(GetTestDataFilePath("quadratic.data", M2AIA_DATA_DIR)); for (int i = 0; i < 1000; i++) { f << std::setprecision(128) << -0.00012 * i * i + 0.32 * i + 800; if (i < 1000 - 1) f << "\n"; } }*/ std::vector<double> signal = ReadDoubleVector("signal.data"); std::vector<double> mzs = ReadDoubleVector("quadratic.data"); std::vector<double> expected = ReadDoubleVector("quadratic_tic_calibration.result"); std::vector<double> result(signal.size()); double tic = m2::Signal::TotalIonCurrent(std::begin(mzs), std::end(mzs), std::begin(signal)); MITK_INFO << tic; std::transform(std::begin(signal), std::end(signal), std::begin(result), [&tic](const auto &v) { return v / tic; }); CPPUNIT_ASSERT(std::equal(std::begin(result), std::end(result), std::begin(expected))); } }; MITK_TEST_SUITE_REGISTRATION(m2Calibration)
28.962264
135
0.634853
[ "vector", "transform" ]
81c798c51e5bbecb3ceb20cb83cb49d8bf57a843
4,612
hpp
C++
benchmark/benchmark.hpp
bysoul/viper
79ebf6e9248b6734244fb9b52d4cafaf703611b2
[ "BSD-2-Clause" ]
48
2021-04-28T11:39:40.000Z
2022-03-19T06:10:59.000Z
benchmark/benchmark.hpp
bysoul/viper
79ebf6e9248b6734244fb9b52d4cafaf703611b2
[ "BSD-2-Clause" ]
12
2021-04-28T18:21:43.000Z
2022-03-07T12:50:19.000Z
benchmark/benchmark.hpp
bysoul/viper
79ebf6e9248b6734244fb9b52d4cafaf703611b2
[ "BSD-2-Clause" ]
16
2021-05-25T22:32:32.000Z
2022-03-30T10:48:34.000Z
#pragma once #include <stdint.h> #include <chrono> #include <iomanip> #include <benchmark/benchmark.h> namespace viper::kv_bm { static constexpr double SCALE_FACTOR = 1; static constexpr uint64_t NUM_BASE_PREFILLS = 100'000'000; static constexpr uint64_t NUM_BASE_OPS = 50'000'000; static constexpr uint64_t NUM_OPS = NUM_BASE_OPS * SCALE_FACTOR; static constexpr uint64_t NUM_PREFILLS = NUM_BASE_PREFILLS * SCALE_FACTOR; static constexpr uint64_t NUM_INSERTS = NUM_OPS; static constexpr uint64_t NUM_UPDATES = NUM_OPS; static constexpr uint64_t NUM_FINDS = NUM_OPS; static constexpr uint64_t NUM_DELETES = NUM_OPS; static constexpr uint64_t MAX_DATA_SIZE = NUM_PREFILLS + NUM_INSERTS; static constexpr uint64_t NUM_REPETITIONS = 1; static constexpr uint64_t NUM_MAX_THREADS = 36; static constexpr uint64_t NUM_UTIL_THREADS = 36; static constexpr benchmark::TimeUnit BM_TIME_UNIT = benchmark::TimeUnit::kMicrosecond; template <typename T, size_t N> struct BMRecord { static_assert(N > 0, "N needs to be greater than 0"); static constexpr size_t total_size = N * sizeof(T); BMRecord() {} static BMRecord max_value() { return BMRecord(std::numeric_limits<uint64_t>::max()); } BMRecord(uint64_t x) { data.fill(static_cast<T>(x)); } BMRecord(uint32_t x) { data.fill(static_cast<T>(x)); } inline bool operator==(const BMRecord& other) const { return data == other.data; } inline bool operator!=(const BMRecord& other) const { return data != other.data; } bool operator<(const BMRecord &rhs) const { return get_key() < rhs.get_key(); } bool operator>(const BMRecord &rhs) const { return rhs < *this; } bool operator<=(const BMRecord &rhs) const { return !(rhs < *this); } bool operator>=(const BMRecord &rhs) const { return !(*this < rhs); } BMRecord<T, N>& from_str(const std::string& bytes) { assert(bytes.size() == total_size); const char* raw = static_cast<const char*>(bytes.data()); char* raw_data = static_cast<char*>(static_cast<void*>(data.data())); std::copy(raw, raw + total_size, raw_data); return *this; } uint64_t get_key() const { return *(uint64_t*) data.data(); } void update_value() { data[0]++; } std::array<T, N> data; }; using Offset = uint64_t; using KeyType8 = BMRecord<uint32_t, 2>; using KeyType16 = BMRecord<uint32_t, 4>; using KeyType32 = BMRecord<uint32_t, 8>; using KeyType100 = BMRecord<uint32_t, 25>; using ValueType8 = KeyType8; using ValueType100 = KeyType100; using ValueType200 = BMRecord<uint32_t, 50>; using ValueType500 = BMRecord<uint32_t, 125>; using ValueType900 = BMRecord<uint32_t, 225>; #if defined(NVRAM01) static constexpr size_t CPU_AFFINITY_OFFSET = 36; static constexpr char VIPER_POOL_FILE[] = "/dev/dax1.1"; static constexpr char DB_PMEM_DIR[] = "/mnt/pmem2/viper"; static constexpr char DB_FILE_DIR[] = "/scratch/lawrence.benson/viper-dev/data/"; static constexpr char RESULT_FILE_DIR[] = "/scratch/lawrence.benson/viper-dev/results/"; static constexpr char CONFIG_DIR[] = "/scratch/lawrence.benson/viper-dev/benchmark/config/"; #elif defined(NVRAM02) static constexpr char VIPER_POOL_FILE[] = "/dev/dax0.0"; static constexpr char DB_PMEM_DIR[] = "/mnt/nvram-viper"; static constexpr char DB_FILE_DIR[] = "/scratch/viper"; static constexpr char RESULT_FILE_DIR[] = "/hpi/fs00/home/lawrence.benson/clion/viper/results/"; static constexpr char CONFIG_DIR[] = "/hpi/fs00/home/lawrence.benson/clion/viper/benchmark/config/"; static constexpr size_t CPU_AFFINITY_OFFSET = 0; #else static constexpr char VIPER_POOL_FILE[] = "/dev/dax0.0"; static constexpr char DB_PMEM_DIR[] = "/mnt/pmem/"; static constexpr char DB_FILE_DIR[] = "/home/user/data/"; static constexpr char RESULT_FILE_DIR[] = "/home/user/viper/results/"; static constexpr char CONFIG_DIR[] = "/home/user/viper/benchmark/config/"; static constexpr size_t CPU_AFFINITY_OFFSET = 0; // 0 or #logical-cpu-per-socket //static_assert(false, "Need to set these variables for unknown host."); #endif static constexpr uint64_t ONE_GB = (1024ul*1024*1024) * 1; // 1GB static constexpr uint64_t BM_POOL_SIZE = ONE_GB; std::string get_time_string(); std::string get_output_file(const std::string& bm_name); int bm_main(std::vector<std::string> args); } // namespace viper::kv_bm template <typename T, size_t N> std::ostream& operator<<(std::ostream& s, const viper::kv_bm::BMRecord<T, N>& rec) { s << "BMRecord[s" << N << ", data=" << rec.data[0] << "]"; return s; }
34.41791
100
0.709237
[ "vector" ]
81c906d6bbbe24d96fd61234c0bdffe2cb189ca8
5,837
cpp
C++
fboss/agent/packet/test/EthHdrTest.cpp
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
834
2015-03-10T18:12:28.000Z
2022-03-31T20:16:17.000Z
fboss/agent/packet/test/EthHdrTest.cpp
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
82
2015-04-07T08:48:29.000Z
2022-03-11T21:56:58.000Z
fboss/agent/packet/test/EthHdrTest.cpp
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
296
2015-03-11T03:45:37.000Z
2022-03-14T22:54:22.000Z
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/packet/EthHdr.h" /* * References: * https://code.google.com/p/googletest/wiki/Primer * https://code.google.com/p/googletest/wiki/AdvancedGuide */ #include <gtest/gtest.h> #include <folly/MacAddress.h> #include <folly/io/Cursor.h> #include "fboss/agent/hw/mock/MockRxPacket.h" using namespace facebook::fboss; using folly::MacAddress; using folly::io::Cursor; using std::vector; TEST(EthHdrTest, default_constructor) { EthHdr ethHdr; EXPECT_EQ(MacAddress(), ethHdr.dstAddr); EXPECT_EQ(MacAddress(), ethHdr.srcAddr); EXPECT_EQ(vector<VlanTag>(), ethHdr.vlanTags); EXPECT_EQ(0, ethHdr.etherType); } TEST(EthHdrTest, copy_constructor) { MacAddress dstAddr("ff:ff:ff:ff:ff:ff"); MacAddress srcAddr("10:dd:b1:bb:5a:ef"); vector<VlanTag> vlanTags; vlanTags.push_back(VlanTag(0x81000001)); vlanTags.push_back(VlanTag(0x88A80002)); vlanTags.push_back(VlanTag(0x88A80003)); uint16_t etherType = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV4); EthHdr lhs(dstAddr, srcAddr, vlanTags, etherType); EthHdr rhs(lhs); EXPECT_EQ(lhs, rhs); } TEST(EthHdrTest, parameterized_data_constructor) { MacAddress dstAddr("ff:ff:ff:ff:ff:ff"); MacAddress srcAddr("10:dd:b1:bb:5a:ef"); vector<VlanTag> vlanTags; vlanTags.push_back(VlanTag(0x81000001)); vlanTags.push_back(VlanTag(0x88A80002)); vlanTags.push_back(VlanTag(0x88A80003)); uint16_t etherType = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV6); EthHdr ethHdr(dstAddr, srcAddr, vlanTags, etherType); EXPECT_EQ(dstAddr, ethHdr.dstAddr); EXPECT_EQ(srcAddr, ethHdr.srcAddr); EXPECT_EQ(vlanTags, ethHdr.vlanTags); EXPECT_EQ(etherType, ethHdr.etherType); } TEST(EthHdrTest, cursor_data_constructor) { MacAddress dstAddr("ff:ff:ff:ff:ff:ff"); MacAddress srcAddr("10:dd:b1:bb:5a:ef"); vector<VlanTag> vlanTags; vlanTags.push_back(VlanTag(0x81000001)); vlanTags.push_back(VlanTag(0x88A80002)); vlanTags.push_back(VlanTag(0x88A80003)); uint16_t etherType = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV6); auto pkt = MockRxPacket::fromHex( // Ethernet Header "ff ff ff ff ff ff" // Destination MAC Address "10 dd b1 bb 5a ef" // Source MAC Address "81 00 00 01" // VLAN: 1 "88 A8 00 02" // VLAN: 2 "88 A8 00 03" // VLAN: 3 "86 DD" // EtherType: IPv6 ); Cursor cursor(pkt->buf()); EthHdr ethHdr(cursor); EXPECT_EQ(dstAddr, ethHdr.dstAddr); EXPECT_EQ(srcAddr, ethHdr.srcAddr); EXPECT_EQ(vlanTags, ethHdr.vlanTags); EXPECT_EQ(etherType, ethHdr.etherType); } TEST(EthHdrTest, cursor_data_constructor_too_small_0) { auto pkt = MockRxPacket::fromHex( // Ethernet Header "ff ff ff ff ff ff" // Destination MAC Address "10 dd b1 bb 5a ef" // Source MAC Address "86 " // OOPS! One octet too small! ); Cursor cursor(pkt->buf()); EXPECT_THROW({ EthHdr ethHdr(cursor); }, HdrParseError); } TEST(EthHdrTest, cursor_data_constructor_too_small_1) { auto pkt = MockRxPacket::fromHex( // Ethernet Header "ff ff ff ff ff ff" // Destination MAC Address "10 dd b1 bb 5a ef" // Source MAC Address "81 00 00 01" // VLAN: 1 "88 A8 00 02" // VLAN: 2 "88 A8 00 03" // VLAN: 3 "86 " // OOPS! One octet too small! ); Cursor cursor(pkt->buf()); EXPECT_THROW({ EthHdr ethHdr(cursor); }, HdrParseError); } TEST(EthHdrTest, assignment_operator) { MacAddress dstAddr("ff:ff:ff:ff:ff:ff"); MacAddress srcAddr("10:dd:b1:bb:5a:ef"); vector<VlanTag> vlanTags; vlanTags.push_back(VlanTag(0x81000001)); vlanTags.push_back(VlanTag(0x88A80002)); vlanTags.push_back(VlanTag(0x88A80003)); uint16_t etherType = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV4); EthHdr lhs(dstAddr, srcAddr, vlanTags, etherType); EthHdr rhs = lhs; EXPECT_EQ(lhs, rhs); } TEST(EthHdrTest, equality_operator) { MacAddress dstAddr("ff:ff:ff:ff:ff:ff"); MacAddress srcAddr("10:dd:b1:bb:5a:ef"); vector<VlanTag> vlanTags; vlanTags.push_back(VlanTag(0x81000001)); vlanTags.push_back(VlanTag(0x88A80002)); vlanTags.push_back(VlanTag(0x88A80003)); uint16_t etherType = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV4); EthHdr lhs(dstAddr, srcAddr, vlanTags, etherType); EthHdr rhs(dstAddr, srcAddr, vlanTags, etherType); EXPECT_EQ(lhs, rhs); } TEST(EthHdrTest, inequality_operator) { MacAddress dstAddr("ff:ff:ff:ff:ff:ff"); MacAddress srcAddr("10:dd:b1:bb:5a:ef"); vector<VlanTag> vlanTags; vlanTags.push_back(VlanTag(0x81000001)); vlanTags.push_back(VlanTag(0x88A80002)); vlanTags.push_back(VlanTag(0x88A80003)); uint16_t etherType1 = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV4); uint16_t etherType2 = static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_IPV6); EthHdr lhs(dstAddr, srcAddr, vlanTags, etherType1); EthHdr rhs(dstAddr, srcAddr, vlanTags, etherType2); EXPECT_NE(lhs, rhs); } TEST(EthHdrTest, vlan_tag) { // Vlan id has bits in both octets set. // Drop eligibility is 0 VlanTag vlan1(2050, static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_VLAN), 0, 4); EXPECT_EQ(vlan1.vid(), 2050); EXPECT_EQ(vlan1.tpid(), static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_VLAN)); EXPECT_EQ(vlan1.dei(), 0); EXPECT_EQ(vlan1.pcp(), 4); // Vlan id has set bits in only one octets // Drop eligibility is 1 VlanTag vlan2(50, static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_QINQ), 1, 0); EXPECT_EQ(vlan2.vid(), 50); EXPECT_EQ(vlan2.tpid(), static_cast<uint16_t>(ETHERTYPE::ETHERTYPE_QINQ)); EXPECT_EQ(vlan2.dei(), 1); EXPECT_EQ(vlan2.pcp(), 0); }
33.936047
79
0.716978
[ "vector" ]
81d1e46927b2ddf8db25084bbc4376123706191b
13,055
cxx
C++
Dockerized/rdpstack/cmake-3.17.2/Source/cmGeneratorExpression.cxx
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
3
2021-10-14T07:40:15.000Z
2022-02-27T09:20:33.000Z
Dockerized/rdpstack/cmake-3.17.2/Source/cmGeneratorExpression.cxx
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
null
null
null
Dockerized/rdpstack/cmake-3.17.2/Source/cmGeneratorExpression.cxx
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
2
2021-10-21T06:12:36.000Z
2022-03-07T15:52:28.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmGeneratorExpression.h" #include <cassert> #include <memory> #include <utility> #include "cmsys/RegularExpression.hxx" #include "cmGeneratorExpressionContext.h" #include "cmGeneratorExpressionDAGChecker.h" #include "cmGeneratorExpressionEvaluator.h" #include "cmGeneratorExpressionLexer.h" #include "cmGeneratorExpressionParser.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmGeneratorExpression::cmGeneratorExpression(cmListFileBacktrace backtrace) : Backtrace(std::move(backtrace)) { } cmCompiledGeneratorExpression::~cmCompiledGeneratorExpression() = default; cmGeneratorExpression::~cmGeneratorExpression() = default; std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( std::string input) const { return std::unique_ptr<cmCompiledGeneratorExpression>( new cmCompiledGeneratorExpression(this->Backtrace, std::move(input))); } std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( const char* input) const { return this->Parse(std::string(input ? input : "")); } std::string cmGeneratorExpression::Evaluate( std::string input, cmLocalGenerator* lg, const std::string& config, cmGeneratorTarget const* headTarget, cmGeneratorExpressionDAGChecker* dagChecker, cmGeneratorTarget const* currentTarget, std::string const& language) { if (Find(input) != std::string::npos) { cmCompiledGeneratorExpression cge(cmListFileBacktrace(), std::move(input)); return cge.Evaluate(lg, config, headTarget, dagChecker, currentTarget, language); } return input; } std::string cmGeneratorExpression::Evaluate( const char* input, cmLocalGenerator* lg, const std::string& config, cmGeneratorTarget const* headTarget, cmGeneratorExpressionDAGChecker* dagChecker, cmGeneratorTarget const* currentTarget, std::string const& language) { return input ? Evaluate(std::string(input), lg, config, headTarget, dagChecker, currentTarget, language) : ""; } const std::string& cmCompiledGeneratorExpression::Evaluate( cmLocalGenerator* lg, const std::string& config, const cmGeneratorTarget* headTarget, cmGeneratorExpressionDAGChecker* dagChecker, const cmGeneratorTarget* currentTarget, std::string const& language) const { cmGeneratorExpressionContext context( lg, config, this->Quiet, headTarget, currentTarget ? currentTarget : headTarget, this->EvaluateForBuildsystem, this->Backtrace, language); return this->EvaluateWithContext(context, dagChecker); } const std::string& cmCompiledGeneratorExpression::EvaluateWithContext( cmGeneratorExpressionContext& context, cmGeneratorExpressionDAGChecker* dagChecker) const { if (!this->NeedsEvaluation) { return this->Input; } this->Output.clear(); for (const auto& it : this->Evaluators) { this->Output += it->Evaluate(&context, dagChecker); this->SeenTargetProperties.insert(context.SeenTargetProperties.cbegin(), context.SeenTargetProperties.cend()); if (context.HadError) { this->Output.clear(); break; } } this->MaxLanguageStandard = context.MaxLanguageStandard; if (!context.HadError) { this->HadContextSensitiveCondition = context.HadContextSensitiveCondition; this->HadHeadSensitiveCondition = context.HadHeadSensitiveCondition; this->SourceSensitiveTargets = context.SourceSensitiveTargets; } this->DependTargets = context.DependTargets; this->AllTargetsSeen = context.AllTargets; return this->Output; } cmCompiledGeneratorExpression::cmCompiledGeneratorExpression( cmListFileBacktrace backtrace, std::string input) : Backtrace(std::move(backtrace)) , Input(std::move(input)) , EvaluateForBuildsystem(false) , Quiet(false) , HadContextSensitiveCondition(false) , HadHeadSensitiveCondition(false) { cmGeneratorExpressionLexer l; std::vector<cmGeneratorExpressionToken> tokens = l.Tokenize(this->Input); this->NeedsEvaluation = l.GetSawGeneratorExpression(); if (this->NeedsEvaluation) { cmGeneratorExpressionParser p(tokens); p.Parse(this->Evaluators); } } std::string cmGeneratorExpression::StripEmptyListElements( const std::string& input) { if (input.find(';') == std::string::npos) { return input; } std::string result; result.reserve(input.size()); const char* c = input.c_str(); const char* last = c; bool skipSemiColons = true; for (; *c; ++c) { if (*c == ';') { if (skipSemiColons) { result.append(last, c - last); last = c + 1; } skipSemiColons = true; } else { skipSemiColons = false; } } result.append(last); if (!result.empty() && *(result.end() - 1) == ';') { result.resize(result.size() - 1); } return result; } static std::string stripAllGeneratorExpressions(const std::string& input) { std::string result; std::string::size_type pos = 0; std::string::size_type lastPos = pos; int nestingLevel = 0; while ((pos = input.find("$<", lastPos)) != std::string::npos) { result += input.substr(lastPos, pos - lastPos); pos += 2; nestingLevel = 1; const char* c = input.c_str() + pos; const char* const cStart = c; for (; *c; ++c) { if (cmGeneratorExpression::StartsWithGeneratorExpression(c)) { ++nestingLevel; ++c; continue; } if (c[0] == '>') { --nestingLevel; if (nestingLevel == 0) { break; } } } const std::string::size_type traversed = (c - cStart) + 1; if (!*c) { result += "$<" + input.substr(pos, traversed); } pos += traversed; lastPos = pos; } if (nestingLevel == 0) { result += input.substr(lastPos); } return cmGeneratorExpression::StripEmptyListElements(result); } static void prefixItems(const std::string& content, std::string& result, const std::string& prefix) { std::vector<std::string> entries; cmGeneratorExpression::Split(content, entries); const char* sep = ""; for (std::string const& e : entries) { result += sep; sep = ";"; if (!cmSystemTools::FileIsFullPath(e) && cmGeneratorExpression::Find(e) != 0) { result += prefix; } result += e; } } static std::string stripExportInterface( const std::string& input, cmGeneratorExpression::PreprocessContext context, bool resolveRelative) { std::string result; int nestingLevel = 0; std::string::size_type pos = 0; std::string::size_type lastPos = pos; while (true) { std::string::size_type bPos = input.find("$<BUILD_INTERFACE:", lastPos); std::string::size_type iPos = input.find("$<INSTALL_INTERFACE:", lastPos); if (bPos == std::string::npos && iPos == std::string::npos) { break; } if (bPos == std::string::npos) { pos = iPos; } else if (iPos == std::string::npos) { pos = bPos; } else { pos = (bPos < iPos) ? bPos : iPos; } result += input.substr(lastPos, pos - lastPos); const bool gotInstallInterface = input[pos + 2] == 'I'; pos += gotInstallInterface ? sizeof("$<INSTALL_INTERFACE:") - 1 : sizeof("$<BUILD_INTERFACE:") - 1; nestingLevel = 1; const char* c = input.c_str() + pos; const char* const cStart = c; for (; *c; ++c) { if (cmGeneratorExpression::StartsWithGeneratorExpression(c)) { ++nestingLevel; ++c; continue; } if (c[0] == '>') { --nestingLevel; if (nestingLevel != 0) { continue; } if (context == cmGeneratorExpression::BuildInterface && !gotInstallInterface) { result += input.substr(pos, c - cStart); } else if (context == cmGeneratorExpression::InstallInterface && gotInstallInterface) { const std::string content = input.substr(pos, c - cStart); if (resolveRelative) { prefixItems(content, result, "${_IMPORT_PREFIX}/"); } else { result += content; } } break; } } const std::string::size_type traversed = (c - cStart) + 1; if (!*c) { result += std::string(gotInstallInterface ? "$<INSTALL_INTERFACE:" : "$<BUILD_INTERFACE:") + input.substr(pos, traversed); } pos += traversed; lastPos = pos; } if (nestingLevel == 0) { result += input.substr(lastPos); } return cmGeneratorExpression::StripEmptyListElements(result); } void cmGeneratorExpression::Split(const std::string& input, std::vector<std::string>& output) { std::string::size_type pos = 0; std::string::size_type lastPos = pos; while ((pos = input.find("$<", lastPos)) != std::string::npos) { std::string part = input.substr(lastPos, pos - lastPos); std::string preGenex; if (!part.empty()) { std::string::size_type startPos = input.rfind(';', pos); if (startPos == std::string::npos) { preGenex = part; part.clear(); } else if (startPos != pos - 1 && startPos >= lastPos) { part = input.substr(lastPos, startPos - lastPos); preGenex = input.substr(startPos + 1, pos - startPos - 1); } if (!part.empty()) { cmExpandList(part, output); } } pos += 2; int nestingLevel = 1; const char* c = input.c_str() + pos; const char* const cStart = c; for (; *c; ++c) { if (cmGeneratorExpression::StartsWithGeneratorExpression(c)) { ++nestingLevel; ++c; continue; } if (c[0] == '>') { --nestingLevel; if (nestingLevel == 0) { break; } } } for (; *c; ++c) { // Capture the part after the genex and before the next ';' if (c[0] == ';') { --c; break; } } const std::string::size_type traversed = (c - cStart) + 1; output.push_back(preGenex + "$<" + input.substr(pos, traversed)); pos += traversed; lastPos = pos; } if (lastPos < input.size()) { cmExpandList(input.substr(lastPos), output); } } std::string cmGeneratorExpression::Preprocess(const std::string& input, PreprocessContext context, bool resolveRelative) { if (context == StripAllGeneratorExpressions) { return stripAllGeneratorExpressions(input); } if (context == BuildInterface || context == InstallInterface) { return stripExportInterface(input, context, resolveRelative); } assert(false && "cmGeneratorExpression::Preprocess called with invalid args"); return std::string(); } std::string::size_type cmGeneratorExpression::Find(const std::string& input) { const std::string::size_type openpos = input.find("$<"); if (openpos != std::string::npos && input.find('>', openpos) != std::string::npos) { return openpos; } return std::string::npos; } bool cmGeneratorExpression::IsValidTargetName(const std::string& input) { // The ':' is supported to allow use with IMPORTED targets. At least // Qt 4 and 5 IMPORTED targets use ':' as the namespace delimiter. static cmsys::RegularExpression targetNameValidator("^[A-Za-z0-9_.:+-]+$"); return targetNameValidator.find(input); } void cmGeneratorExpression::ReplaceInstallPrefix( std::string& input, const std::string& replacement) { std::string::size_type pos = 0; std::string::size_type lastPos = pos; while ((pos = input.find("$<INSTALL_PREFIX>", lastPos)) != std::string::npos) { std::string::size_type endPos = pos + sizeof("$<INSTALL_PREFIX>") - 1; input.replace(pos, endPos - pos, replacement); lastPos = endPos; } } void cmCompiledGeneratorExpression::GetMaxLanguageStandard( const cmGeneratorTarget* tgt, std::map<std::string, std::string>& mapping) { auto it = this->MaxLanguageStandard.find(tgt); if (it != this->MaxLanguageStandard.end()) { mapping = it->second; } } const std::string& cmGeneratorExpressionInterpreter::Evaluate( std::string expression, const std::string& property) { this->CompiledGeneratorExpression = this->GeneratorExpression.Parse(std::move(expression)); // Specify COMPILE_OPTIONS to DAGchecker, same semantic as COMPILE_FLAGS cmGeneratorExpressionDAGChecker dagChecker( this->HeadTarget, property == "COMPILE_FLAGS" ? "COMPILE_OPTIONS" : property, nullptr, nullptr); return this->CompiledGeneratorExpression->Evaluate( this->LocalGenerator, this->Config, this->HeadTarget, &dagChecker, nullptr, this->Language); } const std::string& cmGeneratorExpressionInterpreter::Evaluate( const char* expression, const std::string& property) { return this->Evaluate(std::string(expression ? expression : ""), property); }
30.431235
79
0.647415
[ "vector" ]
81dd7b3d21119ba77bb5fc907c02713f83a3b88b
4,709
cc
C++
components/subresource_filter/core/common/test_ruleset_creator.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
components/subresource_filter/core/common/test_ruleset_creator.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/subresource_filter/core/common/test_ruleset_creator.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 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 "components/subresource_filter/core/common/test_ruleset_creator.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "components/subresource_filter/core/common/indexed_ruleset.h" #include "components/subresource_filter/core/common/proto/rules.pb.h" #include "components/subresource_filter/core/common/unindexed_ruleset.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h" namespace subresource_filter { namespace { // The methods below assume that char and uint8_t are interchangeable. static_assert(CHAR_BIT == 8, "Assumed char was 8 bits."); proto::UrlRule CreateSuffixRule(base::StringPiece suffix) { proto::UrlRule rule; rule.set_semantics(proto::RULE_SEMANTICS_BLACKLIST); rule.set_source_type(proto::SOURCE_TYPE_ANY); rule.set_element_types(proto::ELEMENT_TYPE_ALL); rule.set_url_pattern_type(proto::URL_PATTERN_TYPE_SUBSTRING); rule.set_anchor_left(proto::ANCHOR_TYPE_NONE); rule.set_anchor_right(proto::ANCHOR_TYPE_BOUNDARY); rule.set_url_pattern(suffix.as_string()); return rule; } std::vector<uint8_t> SerializeUnindexedRulesetWithSingleRule( const proto::UrlRule& rule) { std::string ruleset_contents; google::protobuf::io::StringOutputStream output(&ruleset_contents); UnindexedRulesetWriter ruleset_writer(&output); ruleset_writer.AddUrlRule(rule); ruleset_writer.Finish(); auto data = reinterpret_cast<const uint8_t*>(ruleset_contents.data()); return std::vector<uint8_t>(data, data + ruleset_contents.size()); } std::vector<uint8_t> SerializeIndexedRulesetWithSingleRule( const proto::UrlRule& rule) { RulesetIndexer indexer; EXPECT_TRUE(indexer.AddUrlRule(rule)); indexer.Finish(); return std::vector<uint8_t>(indexer.data(), indexer.data() + indexer.size()); } } // namespace namespace testing { // TestRuleset ----------------------------------------------------------------- TestRuleset::TestRuleset() = default; TestRuleset::~TestRuleset() = default; // static base::File TestRuleset::Open(const TestRuleset& ruleset) { base::File file; file.Initialize(ruleset.path, base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_SHARE_DELETE); return file; } // TestRulesetPair ------------------------------------------------------------- TestRulesetPair::TestRulesetPair() = default; TestRulesetPair::~TestRulesetPair() = default; // TestRulesetCreator ---------------------------------------------------------- TestRulesetCreator::TestRulesetCreator() = default; TestRulesetCreator::~TestRulesetCreator() = default; void TestRulesetCreator::CreateRulesetToDisallowURLsWithPathSuffix( base::StringPiece suffix, TestRulesetPair* test_ruleset_pair) { DCHECK(test_ruleset_pair); proto::UrlRule suffix_rule = CreateSuffixRule(suffix); ASSERT_NO_FATAL_FAILURE(CreateTestRulesetFromContents( SerializeUnindexedRulesetWithSingleRule(suffix_rule), &test_ruleset_pair->unindexed)); ASSERT_NO_FATAL_FAILURE(CreateTestRulesetFromContents( SerializeIndexedRulesetWithSingleRule(suffix_rule), &test_ruleset_pair->indexed)); } void TestRulesetCreator::CreateUnindexedRulesetToDisallowURLsWithPathSuffix( base::StringPiece suffix, TestRuleset* test_unindexed_ruleset) { DCHECK(test_unindexed_ruleset); proto::UrlRule suffix_rule = CreateSuffixRule(suffix); ASSERT_NO_FATAL_FAILURE(CreateTestRulesetFromContents( SerializeUnindexedRulesetWithSingleRule(suffix_rule), test_unindexed_ruleset)); } void TestRulesetCreator::GetUniqueTemporaryPath(base::FilePath* path) { DCHECK(path); ASSERT_TRUE(scoped_temp_dir_.IsValid() || scoped_temp_dir_.CreateUniqueTempDir()); *path = scoped_temp_dir_.GetPath().AppendASCII( base::IntToString(next_unique_file_suffix++)); } void TestRulesetCreator::CreateTestRulesetFromContents( std::vector<uint8_t> ruleset_contents, TestRuleset* ruleset) { DCHECK(ruleset); ruleset->contents = std::move(ruleset_contents); ASSERT_NO_FATAL_FAILURE(GetUniqueTemporaryPath(&ruleset->path)); int ruleset_size_as_int = base::checked_cast<int>(ruleset->contents.size()); int num_bytes_written = base::WriteFile( ruleset->path, reinterpret_cast<const char*>(ruleset->contents.data()), ruleset_size_as_int); ASSERT_EQ(ruleset_size_as_int, num_bytes_written); } } // namespace testing } // namespace subresource_filter
36.503876
83
0.745594
[ "vector" ]
81df5a98fa8f06f5f1c16418da54f3041f9932a3
4,556
cpp
C++
GLCompute/WinThread/julia.cpp
Ginkgo-Biloba/Cpp-Repo2
400bf3a179bb3ce58c809a90e8053fa09eb85dbd
[ "Apache-2.0" ]
null
null
null
GLCompute/WinThread/julia.cpp
Ginkgo-Biloba/Cpp-Repo2
400bf3a179bb3ce58c809a90e8053fa09eb85dbd
[ "Apache-2.0" ]
null
null
null
GLCompute/WinThread/julia.cpp
Ginkgo-Biloba/Cpp-Repo2
400bf3a179bb3ce58c809a90e8053fa09eb85dbd
[ "Apache-2.0" ]
null
null
null
#define WIN32_LEAN_AND_MEAN #define NOCOMM #define NOMINMAX #include <Windows.h> #include <opencv2/highgui.hpp> using namespace cv; using std::vector; int ijulia = 1; inline int atomic_load(int* ptr) { return _InterlockedOr( reinterpret_cast<long volatile*>(ptr), 0); } inline int atomic_fetch_add(int* ptr, int val) { return _InterlockedExchangeAdd( reinterpret_cast<long volatile*>(ptr), val); } struct Julia { enum { ndiv = 16, size = 540, iter = 256, }; Mat image; int current; float radius, ppi; Complexf org; Complexf c; vector<Vec3f> colormap; Julia() { image.create(size, size, CV_32FC3); current = 0; org.re = org.im = 0; c = Complexf(-1.F, -0.F); radius = 1.5F; ppi = radius * 2.F / size; colormap.resize(256); for (int i = 0; i < 256; ++i) { float n = 4.F * i / 256; float r = min(max(min(n - 1.5F, -n + 4.5F), 0.F), 1.F); float g = min(max(min(n - 0.5F, -n + 3.5F), 0.F), 1.F); float b = min(max(min(n + 0.5F, -n + 2.5F), 0.F), 1.F); colormap[255 - i] = Vec3f(b, g, r); } } void do_julia(int h, int hend) { for (; h < hend; ++h) { Vec3f* ptr = image.ptr<Vec3f>(h); float im = org.im + (h - size / 2) * ppi; for (int w = 0; w < size; ++w) { Complexf z(org.re + (w - size / 2) * ppi, im); int i = 0; do { if (z.re * z.re + z.im * z.im > 4.F) break; z = z * z + c; ++i; } while (i < iter); ptr[w] = colormap[i]; } } } void mandelbrot(int h, int hend) { for (; h < hend; ++h) { Vec3f* ptr = image.ptr<Vec3f>(h); float im = org.im + (h - size / 2) * ppi; for (int w = 0; w < size; ++w) { Complexf zc(org.re + (w - size / 2) * ppi, im); Complexf z; int i = 0; for (; i < iter; ++i) { float x = z.re * z.re; float y = z.im * z.im; if (x + y > 1024.F) break; z.im = z.re * z.im * 2.F + zc.im; z.re = x - y + zc.re; } ptr[w] = colormap[i]; } } } int run() { int sumt = 0, task, hbeg, hend; for (;;) { task = atomic_load(&current); task = max((size - task) / ndiv, 1); hbeg = atomic_fetch_add(&current, task); if (hbeg >= size) break; hend = min(hbeg + task, static_cast<int>(size)); sumt += (hend - hbeg); if (ijulia) do_julia(hbeg, hend); else mandelbrot(hbeg, hend); } return sumt; } }; static VOID CALLBACK Julia_Func(PTP_CALLBACK_INSTANCE, PVOID vp_job, PTP_WORK) { Julia* job = static_cast<Julia*>(vp_job); if (atomic_load(&(job->current)) < job->size) job->run(); } int main() { TP_POOL* pool = CreateThreadpool(NULL); if (pool == NULL) { printf("CreateThreadpool LastError: %u\n", GetLastError()); return 1; } TP_CALLBACK_ENVIRON env; InitializeThreadpoolEnvironment(&env); SetThreadpoolCallbackPool(&env, pool); TP_CLEANUP_GROUP* clup = CreateThreadpoolCleanupGroup(); if (clup == NULL) { printf("CreateThreadpoolCleanupGroup LastError: %u\n", GetLastError()); return 2; } SetThreadpoolCallbackCleanupGroup(&env, clup, NULL); SYSTEM_INFO sys; GetSystemInfo(&sys); SetThreadpoolThreadMinimum(pool, 1); SetThreadpoolThreadMaximum(pool, sys.dwNumberOfProcessors * 2); Julia ju; Complexf juc(-0.8F, 0.156F); Complexf jmd(0.27322626F, 0.595153338F); float cdir = -0.002F, coff = 0.F; float rad = 2.F, ratio = 0.95F; char const* wd = "Julia"; int64_t ticksum = 0; int step = 0; namedWindow(wd); while (tolower(waitKey(20)) != 'q') { ju.current = 0; if (ijulia) { ju.c = juc + coff; coff += cdir; if (fabs(coff) > 0.1F) cdir = -cdir; } else { rad *= ratio; if ((rad < FLT_EPSILON) || (rad > 2.1F)) ratio = 1.F / ratio; ju.org = jmd; ju.ppi = rad * 2.F / ju.size; } int64_t tick0 = getTickCount(); TP_WORK* work = CreateThreadpoolWork(Julia_Func, &ju, &env); if (!work) { printf("CreateThreadpoolWork LastError %u\n", GetLastError()); break; } for (DWORD i = sys.dwNumberOfProcessors; i > 1; --i) SubmitThreadpoolWork(work); ju.run(); WaitForThreadpoolWorkCallbacks(work, FALSE); CloseThreadpoolWork(work); int64_t tick1 = getTickCount(); ticksum += tick1 - tick0; if (((++step) & 31) == 0) { if (ijulia) printf("c = (%f, %f)", ju.c.re, ju.c.im); else printf("rad = %.9f", rad); printf(", %fms\n", 1e3 * ticksum / getTickFrequency()); ticksum = 0; } imshow(wd, ju.image); } CloseThreadpoolCleanupGroupMembers(clup, FALSE, NULL); CloseThreadpoolCleanupGroup(clup); DestroyThreadpoolEnvironment(&env); CloseThreadpool(pool); }
20.522523
78
0.589772
[ "vector" ]
81df96c2004a5a8a1b3ce69008bd01ab70a3a3fb
3,092
hpp
C++
remodet_repository_LEE/include/caffe/mask/anno_image_loader.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_LEE/include/caffe/mask/anno_image_loader.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_LEE/include/caffe/mask/anno_image_loader.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#ifndef CAFFE_MASK_ANNO_IMAGE_LOADER_H #define CAFFE_MASK_ANNO_IMAGE_LOADER_H #include <vector> #include <string> #include <opencv/cv.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "caffe/tracker/bounding_box.hpp" #include "glog/logging.h" #include "caffe/caffe.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/common.hpp" #include "caffe/pose/pose_image_loader.hpp" using namespace cv; namespace caffe { /** * 实例(person)的数据结构 */ template <typename Dtype> struct Instance { // minibatch内部的编号 int bindex; // 类别号:0 int cid; // 类下的实例号 int pid; // 该对象是否是diff? bool is_diff; // 该对象是否是crowd? bool iscrowd; // 该对象的Box BoundingBox<Dtype> bbox; // 该对象是否有mask? bool mask_included; // 该对象的Mask图片的位置 string mask_path; // 该对象是否有关节点? bool kps_included; // 该对象的可见关节点数量 int num_kps; // 该对象的关节点数据 Joints joint; // TorsoAndHead BBox BoundingBox<Dtype> THbbox; }; /** * 一张图片的标注数据 * 包含: * 1.图片路径 * 2.图片数据集 * 3.图片尺寸 * 4.有效的实例数 * 5.实例的数据结构集合 */ template <typename Dtype> struct AnnoData { // 图片路径 string img_path; // 数据集 string dataset; // 图片尺寸 int img_width; int img_height; // 实例数 int num_person; // 实例数据结构集合 vector<Instance<Dtype> > instances; }; /** * 图片标注集合 */ template <typename Dtype> class AnnoImageLoader { public: AnnoImageLoader() {} /** * 加载图片 * @param image_num [图片id] * @param image [图片cv::Mat] */ void LoadImage(const int image_num, cv::Mat* image); /** * 加载标注信息 * @param image_num [图片id] * @param image [返回图片cv::Mat] * @param anno [标注] */ void LoadAnnotation(const int image_num, cv::Mat* image, AnnoData<Dtype>* anno); // 显示图片 void ShowImages(); // 显示图片和标记 void ShowAnnotations(); // 随机显示图片和标记 void ShowAnnotationsRand(); // 保存至输出目录 void Saving(const std::string& output_folder); // 获取标注 std::vector<AnnoData<Dtype> > get_annotations() const { return annotations_; } // 获取第三方的样本数据 void merge_from(const AnnoImageLoader<Dtype>* dst); // 图片size int size() const { return annotations_.size(); } protected: /** * 绘制标注 * @param image_num [id] * @param dst_image [返回的图片cv::Mat] */ void drawAnnotations(const int image_num, cv::Mat* dst_image); /** * 绘制box * @param anno [标注信息] * @param image_out [绘制的cv::Mat] */ void drawbox(const AnnoData<Dtype>& anno, cv::Mat* image_out); /** * 绘制kps * @param anno [标注信息] * @param image_out [绘制的cv::Mat] */ void drawkps(const AnnoData<Dtype>& anno, cv::Mat* image_out); /** * 绘制mask * @param anno [标注信息] * @param image_out [绘制的cv::Mat] */ void drawmask(const AnnoData<Dtype>& anno, cv::Mat* image_out); /** * 绘制mask * @param mask [mask图像] * @param image [绘制的cv::Mat] * @param r [绘制颜色R] * @param g [绘制颜色G] * @param b [绘制颜色B] */ void drawmask(const cv::Mat& mask, cv::Mat* image, int r, int g, int b); /** * 所有标注信息集合 */ std::vector<AnnoData<Dtype> > annotations_; }; } #endif
18.739394
80
0.628396
[ "vector" ]
81e0ce1c70dabc8af66a2320a67038aaaec4ab94
7,274
cpp
C++
Editor/Widgets/ShaderEditor.cpp
nexovec/SpartanEngine
6ae79b820b831774c5e94eb9e42d51c4a5cdd464
[ "MIT" ]
278
2016-06-19T16:48:31.000Z
2019-04-10T05:52:47.000Z
Editor/Widgets/ShaderEditor.cpp
RocketManNum1/SpartanEngine
4e218b2cccfe15371b473e19cecadc3cf43493c5
[ "MIT" ]
22
2016-09-11T20:57:56.000Z
2019-04-04T00:10:58.000Z
Editor/Widgets/ShaderEditor.cpp
RocketManNum1/SpartanEngine
4e218b2cccfe15371b473e19cecadc3cf43493c5
[ "MIT" ]
31
2016-08-09T13:15:51.000Z
2019-03-27T13:25:07.000Z
/* Copyright(c) 2016-2022 Panos Karabelas 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 "ShaderEditor.h" #include "Rendering/Renderer.h" #include "../ImGuiExtension.h" #include <fstream> #include "RHI/RHI_Shader.h" //================================ //= NAMESPACES ========= using namespace std; using namespace Spartan; //====================== static const float k_vertical_split_percentage = 0.7f; static const float k_horizontal_split_offset_from_bottom = 81.0f; ShaderEditor::ShaderEditor(Editor* editor) : Widget(editor) { m_title = "Shader Editor"; m_flags |= ImGuiWindowFlags_NoScrollbar; m_visible = false; m_size_initial = ImVec2(1366, 1000); m_text_editor = make_unique<Widget_TextEditor>(); m_renderer = m_context->GetSubsystem<Renderer>(); m_position = k_widget_position_screen_center; m_alpha = 1.0f; } void ShaderEditor::TickVisible() { // Source ShowShaderSource(); // Shader list ImGui::SameLine(); ShowShaderList(); // Controls ShowControls(); } void ShaderEditor::ShowShaderSource() { if (ImGui::BeginChild("##shader_editor_source", ImVec2(ImGui::GetContentRegionMax().x * k_vertical_split_percentage, ImGui::GetContentRegionMax().y - k_horizontal_split_offset_from_bottom), true, ImGuiWindowFlags_NoScrollbar)) { // Title ImGui::Text(m_shader ? m_shader_name.c_str() : "Select a shader"); // Content if (m_shader) { // Shader source if (ImGui::BeginTabBar("##shader_editor_tab_bar", ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown)) { const std::vector<std::string>& names = m_shader->GetNames(); const std::vector<std::string>& sources = m_shader->GetSources(); for (uint32_t i = 0; i < static_cast<uint32_t>(names.size()); i++) { if (ImGui::BeginTabItem(names[i].c_str())) { // Set text if (m_index_displayed != i) { m_text_editor->SetText(sources[i]); m_index_displayed = i; } // Render m_text_editor->Render("##shader_text_editor", ImVec2(0.0f, 0.0f), true); // Update shader if (m_text_editor->IsTextChanged()) { m_shader->SetSource(i, m_text_editor->GetText()); } ImGui::EndTabItem(); } } ImGui::EndTabBar(); } } } ImGui::EndChild(); } void ShaderEditor::ShowShaderList() { GetShaderInstances(); if (ImGui::BeginChild("##shader_editor_list", ImVec2(0.0f, ImGui::GetContentRegionMax().y - k_horizontal_split_offset_from_bottom), true, ImGuiWindowFlags_HorizontalScrollbar)) { // Title ImGui::Text("Shaders"); for (RHI_Shader* shader : m_shaders) { // Get name string name = shader->GetObjectName(); // Append stage if (shader->GetShaderStage() == RHI_Shader_Vertex) { name += "_Vertex"; } else if (shader->GetShaderStage() == RHI_Shader_Pixel) { name += "_Pixel"; } else if (shader->GetShaderStage() == RHI_Shader_Compute) { name += "_Compute"; } else { name += "_Unknown"; } // Append defines for (const auto& define : shader->GetDefines()) { if (define.second != "0") { name += "_" + define.first; } } if (ImGuiEx::Button(name.c_str()) || m_first_run) { m_shader = shader; m_shader_name = name; m_index_displayed = -1; m_first_run = false; // Reload in case it has been modified m_shader->LoadSource(m_shader->GetFilePath()); } } } ImGui::EndChild(); } void ShaderEditor::ShowControls() { if (ImGui::BeginChild("##shader_editor_controls", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoScrollbar)) { // Compile button if (ImGuiEx::Button("Compile")) { if (m_index_displayed != -1) { static const std::vector<std::string>& file_paths = m_shader->GetFilePaths(); static const std::vector<std::string>& sources = m_shader->GetSources(); // Save all files for (uint32_t i = 0; i < static_cast<uint32_t>(file_paths.size()); i++) { ofstream out(file_paths[i]); out << sources[i]; out.flush(); out.close(); } // Compile synchronously to make it obvious when the first rendered frame (with your changes) shows up bool async = false; m_shader->Compile(m_shader->GetShaderStage(), m_shader->GetFilePath(), async); } } // Opacity slider ImGui::SameLine(); ImGui::PushItemWidth(200.0f); ImGui::SliderFloat("Opacity", &m_alpha, 0.1f, 1.0f, "%.1f"); ImGui::PopItemWidth(); } ImGui::EndChild(); } void ShaderEditor::GetShaderInstances() { unordered_map<Renderer::Shader, shared_ptr<RHI_Shader>> shaders = m_renderer->GetShaders(); m_shaders.clear(); for (const auto& it : shaders) { if (it.second->IsCompiled()) { m_shaders.emplace_back(it.second.get()); } } // Order them alphabetically sort(m_shaders.begin(), m_shaders.end(), [](RHI_Shader* a, RHI_Shader* b) { return a->GetObjectName() < b->GetObjectName(); }); }
33.520737
230
0.551828
[ "render", "vector" ]
81e3b72827cc661913ccb6274605d8048c590632
11,116
cpp
C++
src/core/qgsmaprenderercustompainterjob.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/core/qgsmaprenderercustompainterjob.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/core/qgsmaprenderercustompainterjob.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsmaprenderercustompainterjob.cpp -------------------------------------- Date : December 2013 Copyright : (C) 2013 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************************************** * * * 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 "qgsmaprenderercustompainterjob.h" #include "qgsfeedback.h" #include "qgslabelingengine.h" #include "qgslogger.h" #include "qgsproject.h" #include "qgsmaplayerrenderer.h" #include "qgsvectorlayer.h" #include "qgsrenderer.h" #include "qgsmaplayerlistutils.h" #include <QtConcurrentRun> QgsMapRendererCustomPainterJob::QgsMapRendererCustomPainterJob( const QgsMapSettings &settings, QPainter *painter ) : QgsMapRendererJob( settings ) , mPainter( painter ) , mActive( false ) , mRenderSynchronously( false ) { QgsDebugMsgLevel( QStringLiteral( "QPAINTER construct" ), 5 ); } QgsMapRendererCustomPainterJob::~QgsMapRendererCustomPainterJob() { QgsDebugMsgLevel( QStringLiteral( "QPAINTER destruct" ), 5 ); Q_ASSERT( !mFutureWatcher.isRunning() ); //cancel(); } void QgsMapRendererCustomPainterJob::start() { if ( isActive() ) return; mRenderingStart.start(); mActive = true; mErrors.clear(); QgsDebugMsgLevel( QStringLiteral( "QPAINTER run!" ), 5 ); QgsDebugMsgLevel( QStringLiteral( "Preparing list of layer jobs for rendering" ), 5 ); QTime prepareTime; prepareTime.start(); // clear the background mPainter->fillRect( 0, 0, mSettings.deviceOutputSize().width(), mSettings.deviceOutputSize().height(), mSettings.backgroundColor() ); mPainter->setRenderHint( QPainter::Antialiasing, mSettings.testFlag( QgsMapSettings::Antialiasing ) ); #ifndef QT_NO_DEBUG QPaintDevice *paintDevice = mPainter->device(); QString errMsg = QStringLiteral( "pre-set DPI not equal to painter's DPI (%1 vs %2)" ) .arg( paintDevice->logicalDpiX() ) .arg( mSettings.outputDpi() * mSettings.devicePixelRatio() ); Q_ASSERT_X( qgsDoubleNear( paintDevice->logicalDpiX(), mSettings.outputDpi() * mSettings.devicePixelRatio() ), "Job::startRender()", errMsg.toLatin1().data() ); #endif mLabelingEngineV2.reset(); if ( mSettings.testFlag( QgsMapSettings::DrawLabeling ) ) { mLabelingEngineV2.reset( new QgsLabelingEngine() ); mLabelingEngineV2->setMapSettings( mSettings ); } bool canUseLabelCache = prepareLabelCache(); mLayerJobs = prepareJobs( mPainter, mLabelingEngineV2.get() ); mLabelJob = prepareLabelingJob( mPainter, mLabelingEngineV2.get(), canUseLabelCache ); QgsDebugMsgLevel( "Rendering prepared in (seconds): " + QString( "%1" ).arg( prepareTime.elapsed() / 1000.0 ), 4 ); if ( mRenderSynchronously ) { // do the rendering right now! doRender(); return; } // now we are ready to start rendering! connect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsMapRendererCustomPainterJob::futureFinished ); mFuture = QtConcurrent::run( staticRender, this ); mFutureWatcher.setFuture( mFuture ); } void QgsMapRendererCustomPainterJob::cancel() { if ( !isActive() ) { QgsDebugMsgLevel( QStringLiteral( "QPAINTER not running!" ), 4 ); return; } QgsDebugMsgLevel( QStringLiteral( "QPAINTER canceling" ), 5 ); disconnect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsMapRendererCustomPainterJob::futureFinished ); cancelWithoutBlocking(); QTime t; t.start(); mFutureWatcher.waitForFinished(); QgsDebugMsgLevel( QStringLiteral( "QPAINER cancel waited %1 ms" ).arg( t.elapsed() / 1000.0 ), 5 ); futureFinished(); QgsDebugMsgLevel( QStringLiteral( "QPAINTER canceled" ), 5 ); } void QgsMapRendererCustomPainterJob::cancelWithoutBlocking() { if ( !isActive() ) { QgsDebugMsg( QStringLiteral( "QPAINTER not running!" ) ); return; } mLabelJob.context.setRenderingStopped( true ); for ( LayerRenderJobs::iterator it = mLayerJobs.begin(); it != mLayerJobs.end(); ++it ) { it->context.setRenderingStopped( true ); if ( it->renderer && it->renderer->feedback() ) it->renderer->feedback()->cancel(); } } void QgsMapRendererCustomPainterJob::waitForFinished() { if ( !isActive() ) return; disconnect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsMapRendererCustomPainterJob::futureFinished ); QTime t; t.start(); mFutureWatcher.waitForFinished(); QgsDebugMsgLevel( QStringLiteral( "waitForFinished: %1 ms" ).arg( t.elapsed() / 1000.0 ), 4 ); futureFinished(); } bool QgsMapRendererCustomPainterJob::isActive() const { return mActive; } bool QgsMapRendererCustomPainterJob::usedCachedLabels() const { return mLabelJob.cached; } QgsLabelingResults *QgsMapRendererCustomPainterJob::takeLabelingResults() { if ( mLabelingEngineV2 ) return mLabelingEngineV2->takeResults(); else return nullptr; } void QgsMapRendererCustomPainterJob::waitForFinishedWithEventLoop( QEventLoop::ProcessEventsFlags flags ) { QEventLoop loop; connect( &mFutureWatcher, &QFutureWatcher<void>::finished, &loop, &QEventLoop::quit ); loop.exec( flags ); } void QgsMapRendererCustomPainterJob::renderSynchronously() { mRenderSynchronously = true; start(); futureFinished(); mRenderSynchronously = false; } void QgsMapRendererCustomPainterJob::futureFinished() { mActive = false; mRenderingTime = mRenderingStart.elapsed(); QgsDebugMsgLevel( QStringLiteral( "QPAINTER futureFinished" ), 5 ); logRenderingTime( mLayerJobs, mLabelJob ); // final cleanup cleanupJobs( mLayerJobs ); cleanupLabelJob( mLabelJob ); emit finished(); } void QgsMapRendererCustomPainterJob::staticRender( QgsMapRendererCustomPainterJob *self ) { try { self->doRender(); } catch ( QgsException &e ) { Q_UNUSED( e ); QgsDebugMsg( "Caught unhandled QgsException: " + e.what() ); } catch ( std::exception &e ) { Q_UNUSED( e ); QgsDebugMsg( "Caught unhandled std::exception: " + QString::fromLatin1( e.what() ) ); } catch ( ... ) { QgsDebugMsg( QStringLiteral( "Caught unhandled unknown exception" ) ); } } void QgsMapRendererCustomPainterJob::doRender() { QgsDebugMsgLevel( QStringLiteral( "Starting to render layer stack." ), 5 ); QTime renderTime; renderTime.start(); for ( LayerRenderJobs::iterator it = mLayerJobs.begin(); it != mLayerJobs.end(); ++it ) { LayerRenderJob &job = *it; if ( job.context.renderingStopped() ) break; if ( job.context.useAdvancedEffects() ) { // Set the QPainter composition mode so that this layer is rendered using // the desired blending mode mPainter->setCompositionMode( job.blendMode ); } if ( !job.cached ) { QTime layerTime; layerTime.start(); if ( job.img ) { job.img->fill( 0 ); job.imageInitialized = true; } job.renderer->render(); job.renderingTime += layerTime.elapsed(); } if ( job.img ) { // If we flattened this layer for alternate blend modes, composite it now mPainter->setOpacity( job.opacity ); mPainter->drawImage( 0, 0, *job.img ); mPainter->setOpacity( 1.0 ); } } QgsDebugMsgLevel( QStringLiteral( "Done rendering map layers" ), 5 ); if ( mSettings.testFlag( QgsMapSettings::DrawLabeling ) && !mLabelJob.context.renderingStopped() ) { if ( !mLabelJob.cached ) { QTime labelTime; labelTime.start(); if ( mLabelJob.img ) { QPainter painter; mLabelJob.img->fill( 0 ); painter.begin( mLabelJob.img ); mLabelJob.context.setPainter( &painter ); drawLabeling( mLabelJob.context, mLabelingEngineV2.get(), &painter ); painter.end(); } else { drawLabeling( mLabelJob.context, mLabelingEngineV2.get(), mPainter ); } mLabelJob.complete = true; mLabelJob.renderingTime = labelTime.elapsed(); mLabelJob.participatingLayers = _qgis_listRawToQPointer( mLabelingEngineV2->participatingLayers() ); } } if ( mLabelJob.img && mLabelJob.complete ) { mPainter->setCompositionMode( QPainter::CompositionMode_SourceOver ); mPainter->setOpacity( 1.0 ); mPainter->drawImage( 0, 0, *mLabelJob.img ); } QgsDebugMsgLevel( "Rendering completed in (seconds): " + QString( "%1" ).arg( renderTime.elapsed() / 1000.0 ), 2 ); } void QgsMapRendererJob::drawLabeling( QgsRenderContext &renderContext, QgsLabelingEngine *labelingEngine2, QPainter *painter ) { QgsDebugMsgLevel( QStringLiteral( "Draw labeling start" ), 5 ); QTime t; t.start(); // Reset the composition mode before rendering the labels painter->setCompositionMode( QPainter::CompositionMode_SourceOver ); renderContext.setPainter( painter ); if ( labelingEngine2 ) { test:: Performance performance; bool myinitial = true; unordered_map<int, int> my_solution_prev; labelingEngine2->run( renderContext,performance, myinitial, my_solution_prev); } QgsDebugMsg( QStringLiteral( "Draw labeling took (seconds): %1" ).arg( t.elapsed() / 1000. ) ); } void QgsMapRendererJob::drawLabeling( const QgsMapSettings &settings, QgsRenderContext &renderContext, QgsLabelingEngine *labelingEngine2, QPainter *painter ) { Q_UNUSED( settings ); drawLabeling( renderContext, labelingEngine2, painter ); } bool QgsMapRendererJob::needTemporaryImage( QgsMapLayer *ml ) { switch ( ml->type() ) { case QgsMapLayerType::VectorLayer: { QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( ml ); if ( vl->renderer() && vl->renderer()->forceRasterRender() ) { //raster rendering is forced for this layer return true; } if ( mSettings.testFlag( QgsMapSettings::UseAdvancedEffects ) && ( ( vl->blendMode() != QPainter::CompositionMode_SourceOver ) || ( vl->featureBlendMode() != QPainter::CompositionMode_SourceOver ) || ( !qgsDoubleNear( vl->opacity(), 1.0 ) ) ) ) { //layer properties require rasterization return true; } break; } case QgsMapLayerType::RasterLayer: { // preview of intermediate raster rendering results requires a temporary output image if ( mSettings.testFlag( QgsMapSettings::RenderPartialOutput ) ) return true; break; } case QgsMapLayerType::MeshLayer: case QgsMapLayerType::PluginLayer: break; } return false; }
28.575835
158
0.657431
[ "render" ]
81e53c22334312fb00961f2cf3c2d20a462a2380
7,220
cc
C++
native/utils/encoder.posix.cc
async3619/merry-go-round
e4a15f4af0be5bd52b5392704d02902d1eaa070a
[ "MIT" ]
1
2019-04-30T19:20:12.000Z
2019-04-30T19:20:12.000Z
native/utils/encoder.posix.cc
async3619/merry-go-round
e4a15f4af0be5bd52b5392704d02902d1eaa070a
[ "MIT" ]
3
2021-05-08T11:23:42.000Z
2022-01-22T04:18:28.000Z
native/utils/encoder.posix.cc
async3619/merry-go-round
e4a15f4af0be5bd52b5392704d02902d1eaa070a
[ "MIT" ]
null
null
null
#include "../includes.hpp" #if !defined(_MERRY_GO_ROUND_USE_WIN32) && defined(_MERRY_GO_ROUND_USE_POSIX) # include <codecvt> # include <locale> template <typename char_t> struct string_helper {}; template <> struct string_helper<char> { static size_t strlen(const char* string) { return std::strlen(string); } }; template <> struct string_helper<wchar_t> { static size_t strlen(const wchar_t* string) { return std::wcslen(string); } }; template <typename data_t> struct global_buffer_t { private: static Watcher watch; static data_t* buffer; static std::size_t length; public: static data_t* allocate(std::size_t length) { if (length < global_buffer_t::length) { std::memset(global_buffer_t::buffer, 0, sizeof(data_t) * global_buffer_t::length); return global_buffer_t::buffer; } std::size_t nearestLength = 1; while (length >= nearestLength) { nearestLength *= 2; } void* data = global_buffer_t::buffer; if (global_buffer_t::buffer) { delete[] global_buffer_t::buffer; } // I used unmanaged one (malloc) here because it'll be DESTRUCTED when node.js instance is about to close. // because watcher is defined as *static* variable. and static variable destructing is called lately than // callback registered by `napi_add_env_cleanup_hook`. global_buffer_t::buffer = static_cast<data_t*>(malloc(nearestLength * sizeof(size_t))); global_buffer_t::length = nearestLength; std::memset(global_buffer_t::buffer, 0, sizeof(data_t) * global_buffer_t::length); return global_buffer_t::buffer; } }; template <> char* global_buffer_t<char>::buffer = nullptr; template <> std::size_t global_buffer_t<char>::length = 0; template <> Watcher global_buffer_t<char>::watch([]() { delete[] global_buffer_t<char>::buffer; }); template <> wchar_t* global_buffer_t<wchar_t>::buffer = nullptr; template <> std::size_t global_buffer_t<wchar_t>::length = 0; template <> Watcher global_buffer_t<wchar_t>::watch([]() { delete[] global_buffer_t<wchar_t>::buffer; }); // // string types (char*) of this project will be two possibilities. UTF-8 or Latin1 (multibyte-based string). // In majority of compilers nowadays will treat normal string literal as UTF-8 but we still don't know whether if // given char* is UTF-8 or Lain1. so we're going to consider multibyte string is just multibyte string. even if it's not. // // but if we wanted to wide string or UTF-8 as multibyte, we would convert it to UTF-8 instead of multibyte. // because they're same actually. // // and we'll treat wide character (wchar_t) as UTF-16 because the only usage of wide character encoding is for TagLib // library which uses wchar_t to store UTF-16 string. // // utility wrapper to adapt locale-bound facets for wstring/wbuffer convert template<class Facet> struct deletable_facet : Facet { template<class ...Args> deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {} ~deletable_facet() {} }; TEMPLACE_SPECIALIZE unmanaged_multibyte_to_utf8_t::result_t unmanaged_multibyte_to_utf8_t::convert(const input_t* input) { // // I found that TagLib handles all string data as UTF-8 even if they're encoded as Latin1. // so I'll do basic copy operation for this function. // // UTF-8 -> UTF-8 std::string latin1String = input; char* result = global_buffer_t<char>::allocate(latin1String.size() + 1); memcpy(result, latin1String.c_str(), sizeof(char) * latin1String.size()); return result; } TEMPLACE_SPECIALIZE unmanaged_multibyte_to_wide_t::result_t unmanaged_multibyte_to_wide_t::convert(const input_t* input) { // Latin1 -> UTF-8 std::string u8string = unmanaged_multibyte_to_utf8_t::convert(input); std::cout << "Latin1 -> UTF-8: " << input << " -> " << u8string << std::endl; // UTF-8 -> UTF-16 std::wstring_convert<deletable_facet<std::codecvt<char16_t, char, std::mbstate_t>>, char16_t> conv16; std::u16string u16 = conv16.from_bytes(u8string); std::cout << "UTF-8 -> UTF-16: " << u8string << std::endl; // we shouldn't memcpy on here because value of `sizeof(wchar_t)` is compiler-dependent. auto* buffer = global_buffer_t<unmanaged_wide_to_utf8_t::input_t>::allocate(u16.size() + 1); for (std::size_t i = 0, j = u16.size(); i < j; ++i) { buffer[i] = u16[i]; } return buffer; } TEMPLACE_SPECIALIZE unmanaged_wide_to_utf8_t::result_t unmanaged_wide_to_utf8_t::convert(const input_t* input) { // UTF-16 -> UTF-8 std::wstring wideString = input; std::string utf8String = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>{}.to_bytes(wideString); char* result = global_buffer_t<char>::allocate(utf8String.size() + 1); memcpy(result, utf8String.c_str(), sizeof(char) * utf8String.size()); return result; } TEMPLACE_SPECIALIZE unmanaged_wide_to_multibyte_t::result_t unmanaged_wide_to_multibyte_t::convert(const input_t* input) { // UTF-16 -> UTF-8 return unmanaged_wide_to_utf8_t::convert(input); } TEMPLACE_SPECIALIZE unmanaged_utf8_to_wide_t::result_t unmanaged_utf8_to_wide_t::convert(const input_t* input) { // UTF-8 -> UTF-16 std::wstring wideString = std::wstring_convert<std::codecvt_utf8<wchar_t>>{}.from_bytes(input); wchar_t* result = global_buffer_t<wchar_t>::allocate(wideString.size() + 1); memcpy(result, wideString.c_str(), sizeof(wchar_t) * wideString.size()); return result; } TEMPLACE_SPECIALIZE unmanaged_utf8_to_multibyte_t::result_t unmanaged_utf8_to_multibyte_t::convert(const input_t* input) { // UTF-8 -> UTF-8 std::string utf8String = input; char* result = global_buffer_t<char>::allocate(utf8String.size() + 1); memcpy(result, utf8String.c_str(), sizeof(char) * utf8String.size()); return result; } #define IMPL_CODE_CVT_MANAGED(x) TEMPLACE_SPECIALIZE x::result_t x::convert(const input_t* input) { return x::inverse_t::convert(input); } IMPL_CODE_CVT_MANAGED(multibyte_to_wide_t); IMPL_CODE_CVT_MANAGED(multibyte_to_utf8_t); IMPL_CODE_CVT_MANAGED(wide_to_multibyte_t); IMPL_CODE_CVT_MANAGED(wide_to_utf8_t); IMPL_CODE_CVT_MANAGED(utf8_to_wide_t); IMPL_CODE_CVT_MANAGED(utf8_to_multibyte_t); template <> utf8_t::elem_t* code_cvt_helper::toUtf8<TagLib::String>(const TagLib::String& ref) { // check if given string object is unicode. // if it's already a unicode string, that means it has own utf-8/16 string. // (which is at least wchar_t on windows) bool isUnicode = !(ref.isAscii() || ref.isLatin1()); char* result = nullptr; // call most suitable code converter. if (isUnicode) { result = unmanaged_wide_to_utf8_t::convert(ref.toCWString()); } else { result = unmanaged_multibyte_to_utf8_t::convert(ref.toCString()); } return result; } template <> utf8_t::elem_t* code_cvt_helper::toUtf8<TagLib::String>(TagLib::String&& ref) { return code_cvt_helper::toUtf8<TagLib::String>(ref); } template <> utf8_t::elem_t* code_cvt_helper::toUtf8<std::string>(std::string&& ref) { return unmanaged_multibyte_to_utf8_t::convert(ref.c_str()); } #endif
36.464646
138
0.709418
[ "object" ]
81e5538107c21e98e58b525a43c5780dcb96a5ca
11,008
cpp
C++
src/threepp/math/Vector3.cpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
src/threepp/math/Vector3.cpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
src/threepp/math/Vector3.cpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
#include "threepp/math/Vector3.hpp" #include "threepp/math/Matrix3.hpp" #include "threepp/math/Matrix4.hpp" #include "threepp/math/Quaternion.hpp" #include "threepp/math/Spherical.hpp" #include "threepp/math/MathUtils.hpp" #include "threepp/cameras/Camera.hpp" #include <algorithm> #include <cmath> #include <stdexcept> using namespace threepp; const Vector3 Vector3::X = Vector3{1, 0, 0}; const Vector3 Vector3::Y = Vector3{0, 1, 0}; const Vector3 Vector3::Z = Vector3{0, 0, 1}; const Vector3 Vector3::ONES = Vector3{1, 1, 1}; const Vector3 Vector3::ZEROS = Vector3{0, 0, 0}; Vector3::Vector3(float x, float y, float z) : x(x), y(y), z(z) {} Vector3 &Vector3::set(float x, float y, float z) { this->x = x; this->y = y; this->z = z; return *this; } Vector3 &Vector3::setScalar(float value) { this->x = value; this->y = value; this->z = value; return *this; } Vector3 &Vector3::setX(float value) { this->x = value; return *this; } Vector3 &Vector3::setY(float value) { y = value; return *this; } Vector3 &Vector3::setZ(float value) { z = value; return *this; } float &Vector3::operator[](unsigned int index) { switch (index) { case 0: return x; case 1: return y; case 2: return z; default: throw std::runtime_error("index out of bound: " + std::to_string(index)); } } Vector3 &Vector3::copy(const Vector3 &v) { this->x = v.x; this->y = v.y; this->z = v.z; return *this; } Vector3 &Vector3::add(const Vector3 &v) { this->x += v.x; this->y += v.y; this->z += v.z; return *this; } Vector3 &Vector3::addScalar(float s) { this->x += s; this->y += s; this->z += s; return *this; } Vector3 &Vector3::addVectors(const Vector3 &a, const Vector3 &b) { this->x = a.x + b.x; this->y = a.y + b.y; this->z = a.z + b.z; return *this; } Vector3 &Vector3::addScaledVector(const Vector3 &v, float s) { this->x += v.x * s; this->y += v.y * s; this->z += v.z * s; return *this; } Vector3 &Vector3::sub(const Vector3 &v) { this->x -= v.x; this->y -= v.y; this->z -= v.z; return *this; } Vector3 &Vector3::subScalar(float s) { this->x -= s; this->y -= s; this->z -= s; return *this; } Vector3 &Vector3::subVectors(const Vector3 &a, const Vector3 &b) { this->x = a.x - b.x; this->y = a.y - b.y; this->z = a.z - b.z; return *this; } Vector3 &Vector3::multiply(const Vector3 &v) { this->x *= v.x; this->y *= v.y; this->z *= v.z; return *this; } Vector3 &Vector3::multiplyScalar(float scalar) { this->x *= scalar; this->y *= scalar; this->z *= scalar; return *this; } Vector3 &Vector3::multiplyVectors(const Vector3 &a, const Vector3 &b) { this->x = a.x * b.x; this->y = a.y * b.y; this->z = a.z * b.z; return *this; } Vector3 &Vector3::applyMatrix3(const Matrix3 &m) { const auto x_ = this->x, y_ = this->y, z_ = this->z; const auto &e = m.elements; this->x = e[0] * x_ + e[3] * y_ + e[6] * z_; this->y = e[1] * x_ + e[4] * y_ + e[7] * z_; this->z = e[2] * x_ + e[5] * y_ + e[8] * z_; return *this; } Vector3 &Vector3::applyNormalMatrix(const Matrix3 &m) { return applyMatrix3(m).normalize(); } Vector3 &Vector3::applyMatrix4(const Matrix4 &m) { const auto x_ = this->x, y_ = this->y, z_ = this->z; const auto &e = m.elements; const auto w = 1.0f / (e[3] * x + e[7] * y + e[11] * z + e[15]); this->x = (e[0] * x_ + e[4] * y_ + e[8] * z_ + e[12]) * w; this->y = (e[1] * x_ + e[5] * y_ + e[9] * z_ + e[13]) * w; this->z = (e[2] * x_ + e[6] * y_ + e[10] * z_ + e[14]) * w; return *this; } Vector3 &Vector3::applyQuaternion(const Quaternion &q) { const auto x = this->x, y = this->y, z = this->z; const auto qx = q.x(), qy = q.y(), qz = q.z(), qw = q.w(); // calculate quat * vector const auto ix = qw * x + qy * z - qz * y; const auto iy = qw * y + qz * x - qx * z; const auto iz = qw * z + qx * y - qy * x; const auto iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat this->x = ix * qw + iw * -qx + iy * -qz - iz * -qy; this->y = iy * qw + iw * -qy + iz * -qx - ix * -qz; this->z = iz * qw + iw * -qz + ix * -qy - iy * -qx; return *this; } Vector3 &Vector3::project(const Camera &camera) { return this->applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); } Vector3 &Vector3::unproject(const Camera &camera) { return this->applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(*camera.matrixWorld); } Vector3 &Vector3::transformDirection(const Matrix4 &m) { // input: THREE.Matrix4 affine matrix // vector interpreted as a direction const auto x = this->x, y = this->y, z = this->z; const auto &e = m.elements; this->x = e[0] * x + e[4] * y + e[8] * z; this->y = e[1] * x + e[5] * y + e[9] * z; this->z = e[2] * x + e[6] * y + e[10] * z; return this->normalize(); } Vector3 &Vector3::divide(const Vector3 &v) { this->x /= v.x; this->y /= v.y; this->z /= v.z; return *this; } Vector3 &Vector3::divideScalar(const float &v) { this->x /= v; this->y /= v; this->z /= v; return *this; } Vector3 &Vector3::min(const Vector3 &v) { this->x = std::min(this->x, v.x); this->y = std::min(this->y, v.y); this->z = std::min(this->z, v.z); return *this; } Vector3 &Vector3::max(const Vector3 &v) { this->x = std::max(this->x, v.x); this->y = std::max(this->y, v.y); this->z = std::max(this->z, v.z); return *this; } Vector3 &Vector3::clamp(const Vector3 &min, const Vector3 &max) { // assumes min < max, componentwise this->x = std::max(min.x, std::min(max.x, this->x)); this->y = std::max(min.y, std::min(max.y, this->y)); this->z = std::max(min.z, std::min(max.z, this->z)); return *this; } Vector3 &Vector3::floor() { this->x = std::floor(this->x); this->y = std::floor(this->y); this->z = std::floor(this->z); return *this; } Vector3 &Vector3::ceil() { this->x = std::ceil(this->x); this->y = std::ceil(this->y); this->z = std::ceil(this->z); return *this; } Vector3 &Vector3::round() { this->x = std::round(this->x); this->y = std::round(this->y); this->z = std::round(this->z); return *this; } Vector3 &Vector3::roundToZero() { this->x = (x < 0) ? std::ceil(this->x) : std::floor(this->x); this->y = (y < 0) ? std::ceil(this->y) : std::floor(this->y); this->z = (z < 0) ? std::ceil(this->z) : std::floor(this->z); return *this; } Vector3 &Vector3::negate() { x = -x; y = -y; z = -z; return *this; } float Vector3::dot(const Vector3 &v) const { return x * v.x + y * v.y + z * v.z; } float Vector3::lengthSq() const { return x * x + y * y + z * z; } float Vector3::length() const { return std::sqrt(x * x + y * y + z * z); } float Vector3::manhattanLength() const { return std::abs(x) + std::abs(y) + std::abs(z); } Vector3 &Vector3::normalize() { auto l = length(); this->divideScalar(std::isnan(l) ? 1 : l); return *this; } Vector3 &Vector3::setLength(float length) { return normalize().multiplyScalar(length); } Vector3 &Vector3::lerp(const Vector3 &v, float alpha) { this->x += (v.x - x) * alpha; this->y += (v.y - y) * alpha; this->z += (v.z - z) * alpha; return *this; } Vector3 &Vector3::lerpVectors(const Vector3 &v1, const Vector3 &v2, float alpha) { this->x = v1.x + (v2.x - v1.x) * alpha; this->y = v1.y + (v2.y - v1.y) * alpha; this->z = v1.z + (v2.z - v1.z) * alpha; return *this; } Vector3 &Vector3::cross(const Vector3 &v) { return crossVectors(*this, v); } Vector3 &Vector3::crossVectors(const Vector3 &a, const Vector3 &b) { const auto ax = a.x, ay = a.y, az = a.z; const auto bx = b.x, by = b.y, bz = b.z; this->x = ay * bz - az * by; this->y = az * bx - ax * bz; this->z = ax * by - ay * bx; return *this; } Vector3 &Vector3::projectOnVector(const Vector3 &v) { const auto denominator = v.lengthSq(); if (denominator == 0) return this->set(0, 0, 0); const auto scalar = v.dot(*this) / denominator; return this->copy(v).multiplyScalar(scalar); } Vector3 &Vector3::projectOnPlane(const Vector3 &planeNormal) { Vector3 _vector; _vector.copy(*this).projectOnVector(planeNormal); return this->sub(_vector); } Vector3 &Vector3::reflect(const Vector3 &normal) { // reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length Vector3 _vector; return this->sub(_vector.copy(normal).multiplyScalar(2 * this->dot(normal))); } float Vector3::angleTo(const Vector3 &v) const { const auto denominator = std::sqrt(lengthSq() * v.lengthSq()); if (denominator == 0) return math::PI / 2; const auto theta = dot(v) / denominator; // clamp, to handle numerical problems return std::acos(std::clamp(theta, -1.0f, 1.0f)); } float Vector3::distanceTo(const Vector3 &v) const { return std::sqrt(distanceToSquared(v)); } float Vector3::distanceToSquared(const Vector3 &v) const { const auto dx = this->x - v.x, dy = this->y - v.y, dz = this->z - v.z; return dx * dx + dy * dy + dz * dz; } float Vector3::manhattanDistanceTo(const Vector3 &v) const { return std::abs(this->x - v.x) + std::abs(this->y - v.y) + std::abs(this->z - v.z); } Vector3 &Vector3::setFromSpherical(const Spherical &s) { return this->setFromSphericalCoords(s.radius, s.phi, s.theta); } Vector3 &Vector3::setFromSphericalCoords(float radius, float phi, float theta) { const auto sinPhiRadius = std::sin(phi) * radius; this->x = sinPhiRadius * std::sin(theta); this->y = std::cos(phi) * radius; this->z = sinPhiRadius * std::cos(theta); return *this; } Vector3 &Vector3::setFromMatrixPosition(const Matrix4 &m) { const auto &e = m.elements; this->x = e[12]; this->y = e[13]; this->z = e[14]; return *this; } Vector3 &Vector3::setFromMatrixScale(const Matrix4 &m) { const auto sx = this->setFromMatrixColumn(m, 0).length(); const auto sy = this->setFromMatrixColumn(m, 1).length(); const auto sz = this->setFromMatrixColumn(m, 2).length(); this->x = sx; this->y = sy; this->z = sz; return *this; } Vector3 &Vector3::setFromMatrixColumn(const Matrix4 &m, unsigned int index) { return this->fromArray(m.elements, index * 4); } Vector3 &Vector3::setFromMatrix3Column(const Matrix3 &m, unsigned int index) { return this->fromArray(m.elements, index * 3); } Vector3 Vector3::clone() const { return Vector3{x,y,z}; } bool Vector3::equals(const Vector3 &v) const { return ((v.x == this->x) && (v.y == this->y) && (v.z == this->z)); }
20.730697
96
0.572674
[ "vector" ]
81e6e3fc25189ac6a1dd03056dbd873c1a2a0582
4,149
hpp
C++
inference-engine/src/mkldnn_plugin/quantizer.hpp
tdp2110/dldt
87f321c5365ed813e849ea0ed987354ef2c39743
[ "Apache-2.0" ]
null
null
null
inference-engine/src/mkldnn_plugin/quantizer.hpp
tdp2110/dldt
87f321c5365ed813e849ea0ed987354ef2c39743
[ "Apache-2.0" ]
null
null
null
inference-engine/src/mkldnn_plugin/quantizer.hpp
tdp2110/dldt
87f321c5365ed813e849ea0ed987354ef2c39743
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <string> #include <map> #include <vector> #include <ie_icnn_network.hpp> #include <cpp/ie_cnn_network.h> namespace InferenceEngine { namespace details { /** * @brief Quantization layer details and basic operations on them. */ class QuantizationDetails { public: QuantizationDetails(); QuantizationDetails(const QuantizationDetails& quantizationDetails); QuantizationDetails( const size_t levels, const std::vector<float>& inputLowValues, const std::vector<float>& inputHighValues, const std::vector<float>& outputLowValues, const std::vector<float>& outputHighValues); static QuantizationDetails getDetails(const CNNLayerPtr quantize); bool hasNegativeOutput() const; float maxOutput(const size_t channel) const; float maxInput(const size_t channel) const; size_t inputChannels() const; size_t outputChannels() const; const size_t levels; const std::vector<float> inputLowValues; const std::vector<float> inputHighValues; const std::vector<float> outputLowValues; const std::vector<float> outputHighValues; private: static void validate(const CNNLayerPtr& constantLayer); static std::vector<float> getBlobValue(const CNNLayerPtr& constantLayer); }; /** * @brief Quantization class to quantize ICNNNetwork. */ class Quantizer { public: enum QuantizationPrecision { NONE = 0, FP32 = 1, INT8 = 2 }; /** * Check if network can be quantized or not. * @return true if network can be quantized or false if not */ static bool isNetworkSupported(const ICNNNetwork& network); /** * Quantize network. * @param dotFilePath dot file path for exploration proposals. Empty string is default value. * @param irFilePath model file path after weights quantization for exploration proposals. Empty string is default value. */ void quantize( ICNNNetwork& network, const QuantizationPrecision precision = QuantizationPrecision::INT8, const bool transformQuantizeOnDataPath = true, const std::string& dotFilePath = "", const std::string& irFilePath = ""); /** * Handle Quantize layers on weights path. */ void transformQuantizeOnWeightsPath( ICNNNetwork& network, const std::string& irFilePath = ""); private: void transformQuantizeOnWeightsPath(ICNNNetwork& network, CNNLayerPtr layer); /** * Calculate layer properties to infer laer in low precision. * @param network which contains layer * @param quantize Quantize layer * @param layer layer for quantization * @param mode quantization mode * @param quantizationDetails map with quantization details * @param transformQuantizeOnDataPath boolean flag to transform Quantize layers on data path or not */ static void quantizeConvolutionOrFullyConnected( ICNNNetwork& network, CNNLayerPtr& quantize, CNNLayerPtr& layer, QuantizationPrecision mode, std::map<std::string, const QuantizationDetails>& quantizationDetails, const bool transformQuantizeOnDataPath = true); /** * Extract and quantize weights. */ static Blob::Ptr quantizeWeights(const CNNLayerPtr quantize); static int getMaxSignValue(const size_t quantizationLevels); static int getMaxUnsignValue(const size_t quantizationLevels); static void definesExecutionPrecision( ICNNNetwork& net, const std::map<std::string, const QuantizationDetails>& quantizationDetailsMap); static void propagateScaleFactors(ICNNNetwork& net); static Blob::Ptr calculateScale(const QuantizationDetails& quantizationDetails, const size_t channels); static void ScaleDataToInt( const float* srcData, size_t srcSize, Blob::Ptr int8blob, const std::vector<float>& scales); }; typedef std::shared_ptr<Quantizer> QuantizerPtr; } // namespace details } // namespace InferenceEngine
31.195489
125
0.706435
[ "vector", "model", "transform" ]
81ee227025dbba34cf743184af8f5edaec143a96
35,377
cxx
C++
Podd/THaOutput.cxx
johnaldhino/analyzer
24ced3b45aa91515fb1b9185fd2c2e90d22729a9
[ "BSD-3-Clause" ]
null
null
null
Podd/THaOutput.cxx
johnaldhino/analyzer
24ced3b45aa91515fb1b9185fd2c2e90d22729a9
[ "BSD-3-Clause" ]
null
null
null
Podd/THaOutput.cxx
johnaldhino/analyzer
24ced3b45aa91515fb1b9185fd2c2e90d22729a9
[ "BSD-3-Clause" ]
null
null
null
//*-- Author : Robert Michaels 05/08/2002 ////////////////////////////////////////////////////////////////////////// // // THaOutput // // Defines the tree and histogram output for THaAnalyzer. // This class reads a file 'output.def' (an example is in /examples) // to define which global variables, including arrays, and formulas // (THaFormula's), and histograms go to the ROOT output. // // author: R. Michaels Sept 2002 // // ////////////////////////////////////////////////////////////////////////// #include "THaOutput.h" #include "TROOT.h" #include "THaVform.h" #include "THaVhist.h" #include "THaVarList.h" #include "THaVar.h" #include "THaTextvars.h" #include "THaGlobals.h" #include "TH1.h" #include "TTree.h" #include "TFile.h" #include "TRegexp.h" #include "TError.h" #include "TString.h" #include "THaEvData.h" #include "THaEpicsEvtHandler.h" #include "THaString.h" #include "FileInclude.h" #include <algorithm> #include <fstream> #include <cstring> #include <iostream> #include <sstream> #include <utility> //#include <iterator> #include "THaBenchmark.h" using namespace std; using namespace THaString; using namespace Podd; Int_t THaOutput::fgVerbose = 1; //FIXME: these should be member variables static Bool_t fgDoBench = false; static THaBenchmark fgBench; static const char comment('#'); //_____________________________________________________________________________ class THaEpicsKey { // Utility class used by THaOutput to store a list of // 'keys' to access EPICS data 'string=num' assignments public: explicit THaEpicsKey(string nm) : fName(std::move(nm)) { fAssign.clear(); } void AddAssign(const string& input) { // Add optional assignments. The input must // be of the form "epicsvar=number" // epicsvar can be a string with spaces if // and only if its enclosed in single spaces. // E.g. "Yes=1" "No=2", "'RF On'", etc typedef map<string, double>::value_type valType; string::size_type pos; string sdata,temp1,temp2; sdata = findQuotes(input); pos = sdata.find('='); if (pos != string::npos) { temp1.assign(sdata.substr(0,pos)); temp2.assign(sdata.substr(pos+1,sdata.length())); // In case someone used "==" instead of "=" if (temp2.find('=') != string::npos) temp2.assign (sdata.substr(pos+2,sdata.length())); if (strlen(temp2.c_str()) > 0) { double tdat = atof(temp2.c_str()); fAssign.insert(valType(temp1,tdat)); } else { // In case of "epicsvar=" fAssign.insert(valType(temp1,0)); } } }; static string findQuotes(const string& input) { string result,temp1; string::size_type pos1,pos2; result = input; pos1 = input.find('\''); if (pos1 != string::npos) { temp1.assign(input.substr(pos1+1,input.length())); pos2 = temp1.find('\''); if (pos2 != string::npos) { result.assign(temp1.substr(0,pos2)); result += temp1.substr(pos2+1,temp1.length()); } } return result; }; Bool_t IsString() { return !fAssign.empty(); }; Double_t Eval(const string& input) { if (fAssign.empty()) return 0; for (auto & pm : fAssign) { if (input == pm.first) { return pm.second; } } return 0; }; Double_t Eval(const TString& input) { return Eval(string(input.Data())); } const string& GetName() { return fName; }; private: string fName; map<string,Double_t> fAssign; }; //_____________________________________________________________________________ //_____________________________________________________________________________ THaOdata::THaOdata( const THaOdata& other ) : tree(other.tree), name(other.name), nsize(other.nsize) { data = new Double_t[nsize]; ndata = other.ndata; memcpy( data, other.data, nsize*sizeof(Double_t)); } //_____________________________________________________________________________ THaOdata& THaOdata::operator=(const THaOdata& rhs ) { if( this != &rhs ) { tree = rhs.tree; name = rhs.name; if( nsize < rhs.nsize ) { nsize = rhs.nsize; delete [] data; data = new Double_t[nsize]; } ndata = rhs.ndata; memcpy( data, rhs.data, nsize*sizeof(Double_t)); } return *this; } //_____________________________________________________________________________ void THaOdata::AddBranches( TTree* _tree, string _name ) { name = std::move(_name); tree = _tree; string sname = "Ndata." + name; string leaf = sname; tree->Branch(sname.c_str(),&ndata,(leaf+"/I").c_str()); // FIXME: defined this way, ROOT always thinks we are variable-size leaf = name + "[" + leaf + "]/D"; tree->Branch(name.c_str(),data,leaf.c_str()); } //_____________________________________________________________________________ Bool_t THaOdata::Resize(Int_t i) { static const Int_t MAX = 1<<16; if( i > MAX ) return true; Int_t newsize = nsize; while ( i >= newsize ) { newsize *= 2; } auto tmp = new Double_t[newsize]; memcpy( tmp, data, nsize*sizeof(Double_t) ); delete [] data; data = tmp; nsize = newsize; if( tree ) tree->SetBranchAddress( name.c_str(), data ); return false; } //_____________________________________________________________________________ THaOutput::THaOutput() : fNvar(0), fVar(nullptr), fEpicsVar(nullptr), fTree(nullptr), fEpicsTree(nullptr), fInit(false), fExtra(nullptr), fEpicsHandler(nullptr), nx(0), ny(0), iscut(0), xlo(0), xhi(0), ylo(0), yhi(0), fOpenEpics(false), fFirstEpics(false), fIsScalar(false) { // Constructor } //_____________________________________________________________________________ THaOutput::~THaOutput() { // Destructor delete fExtra; fExtra = nullptr; // Delete Trees and histograms only if ROOT system is initialized. // ROOT will report being uninitialized if we're called from the TSystem // destructor, at which point the trees already have been deleted. // FIXME: Trees would also be deleted if deleting the output file, right? // Can we use this here? if( TROOT::Initialized() ) { delete fTree; delete fEpicsTree; } delete [] fVar; delete [] fEpicsVar; for (auto & od : fOdata) delete od; for (auto & form : fFormulas) delete form; for (auto & cut : fCuts) delete cut; for (auto & histo : fHistos) delete histo; for (auto & ek : fEpicsKey) delete ek; } //_____________________________________________________________________________ Int_t THaOutput::Init( const char* filename ) { // Initialize output system. Required before anything can happen. // // Only re-attach to variables and re-compile cuts and formulas // upon re-initialization (eg: continuing analysis with another file) if( fInit ) { cout << "\nTHaOutput::Init: Info: THaOutput cannot be completely" << " re-initialized. Keeping existing definitions." << endl; cout << "Global Variables are being re-attached and formula/cuts" << " are being re-compiled." << endl; // Assign pointers and recompile stuff reliant on pointers. if ( Attach() ) return -4; Print(); return 1; } if( !gHaVars ) return -2; if( fgDoBench ) fgBench.Begin("Init"); fTree = new TTree("T","Hall A Analyzer Output DST"); fTree->SetAutoSave(200000000); fOpenEpics = false; fFirstEpics = true; Int_t err = LoadFile( filename ); if( fgDoBench && err != 0 ) fgBench.Stop("Init"); if( err == -1 ) { return 0; // No error if file not found, but please } // read the instructions. else if( err != 0 ) { delete fTree; fTree = nullptr; return -3; } fNvar = fVarnames.size(); // this gets reassigned below fArrayNames.clear(); fVNames.clear(); THaVar *pvar; for (Int_t ivar = 0; ivar < fNvar; ivar++) { pvar = gHaVars->Find(fVarnames[ivar].c_str()); if (pvar) { if (pvar->IsArray()) { fArrayNames.push_back(fVarnames[ivar]); fOdata.push_back(new THaOdata()); } else { fVNames.push_back(fVarnames[ivar]); } } else { cout << "\nTHaOutput::Init: WARNING: Global variable "; cout << fVarnames[ivar] << " does not exist. "<< endl; cout << "There is probably a typo error... "<<endl; } } Int_t k = 0; for (auto inam = fFormnames.begin(); inam != fFormnames.end(); ++inam, ++k) { string tinfo = Form("f%d",k); // FIXME: avoid duplicate formulas auto pform = new THaVform("formula",inam->c_str(),fFormdef[k].c_str()); Int_t status = pform->Init(); if ( status != 0) { cout << "THaOutput::Init: WARNING: Error in formula "; cout << *inam << endl; cout << "There is probably a typo error... " << endl; pform->ErrPrint(status); delete pform; --k; continue; } pform->SetOutput(fTree); fFormulas.push_back(pform); if( fgVerbose > 2 ) pform->LongPrint(); // for debug // Add variables (i.e. those var's used by the formula) to tree. // Reason is that TTree::Draw() may otherwise fail with ERROR 26 vector<string> avar = pform->GetVars(); for(auto & str : avar) { string svar = StripBracket(str); pvar = gHaVars->Find(svar.c_str()); if (pvar) { if (pvar->IsArray()) { auto found = find(fArrayNames.begin(), fArrayNames.end(), svar); if( found == fArrayNames.end() ) { fArrayNames.push_back(svar); fOdata.push_back(new THaOdata()); } } else { auto found = find(fVNames.begin(), fVNames.end(), svar); if( found == fVNames.end() ) fVNames.push_back(svar); } } } } k = 0; for( auto iodat = fOdata.begin(); iodat != fOdata.end(); ++iodat, ++k ) (*iodat)->AddBranches(fTree, fArrayNames[k]); fNvar = fVNames.size(); fVar = new Double_t[fNvar]; for (k = 0; k < fNvar; ++k) { string tinfo = fVNames[k] + "/D"; fTree->Branch(fVNames[k].c_str(), &fVar[k], tinfo.c_str(), kNbout); } k = 0; for( auto inam = fCutnames.begin(); inam != fCutnames.end(); ++inam, ++k ) { // FIXME: avoid duplicate cuts auto pcut = new THaVform("cut", inam->c_str(), fCutdef[k].c_str()); Int_t status = pcut->Init(); if ( status != 0 ) { cout << "THaOutput::Init: WARNING: Error in formula "; cout << *inam << endl; cout << "There is probably a typo error... " << endl; pcut->ErrPrint(status); delete pcut; --k; continue; } pcut->SetOutput(fTree); fCuts.push_back(pcut); if( fgVerbose>2 ) pcut->LongPrint(); // for debug } for( auto pVhist : fHistos ) { // After initializing formulas and cuts, must sort through // histograms and potentially reassign variables. // A histogram variable or cut is either a string (which can // encode a formula) or an externally defined THaVform. sfvarx = pVhist->GetVarX(); sfvary = pVhist->GetVarY(); for( auto pVform : fFormulas ) { string stemp(pVform->GetName()); if (CmpNoCase(sfvarx,stemp) == 0) { pVhist->SetX(pVform); } if (CmpNoCase(sfvary,stemp) == 0) { pVhist->SetY(pVform); } } if (pVhist->HasCut()) { scut = pVhist->GetCutStr(); for( auto pcut : fCuts ) { string stemp(pcut->GetName()); if (CmpNoCase(scut,stemp) == 0) { pVhist->SetCut(pcut); } } } pVhist->Init(); } if (!fEpicsKey.empty()) { vector<THaEpicsKey*>::size_type siz = fEpicsKey.size(); fEpicsVar = new Double_t[siz+1]; UInt_t i = 0; for (auto it = fEpicsKey.begin(); it != fEpicsKey.end(); ++it, ++i) { fEpicsVar[i] = -1e32; string epicsbr = CleanEpicsName((*it)->GetName()); string tinfo = epicsbr + "/D"; fTree->Branch(epicsbr.c_str(), &fEpicsVar[i], tinfo.c_str(), kNbout); fEpicsTree->Branch(epicsbr.c_str(), &fEpicsVar[i], tinfo.c_str(), kNbout); } fEpicsVar[siz] = -1e32; fEpicsTree->Branch("timestamp",&fEpicsVar[siz],"timestamp/D", kNbout); } Print(); fInit = true; if( fgDoBench ) fgBench.Stop("Init"); if( fgDoBench ) fgBench.Begin("Attach"); Int_t st = Attach(); if( fgDoBench ) fgBench.Stop("Attach"); if ( st ) return -4; return 0; } void THaOutput::BuildList( const vector<string>& vdata) { // Build list of EPICS variables and // SCALER variables to add to output. if (vdata.empty()) return; if (CmpNoCase(vdata[0],"begin") == 0) { if (vdata.size() < 2) return; if (CmpNoCase(vdata[1],"epics") == 0) fOpenEpics = true; } if (CmpNoCase(vdata[0],"end") == 0) { if (vdata.size() < 2) return; if (CmpNoCase(vdata[1],"epics") == 0) fOpenEpics = false; } if (fOpenEpics) { if (fFirstEpics) { if (!fEpicsTree) fEpicsTree = new TTree("E","Hall A Epics Data"); fFirstEpics = false; return; } else { fEpicsKey.push_back(new THaEpicsKey(vdata[0])); if (vdata.size() > 1) { vector<string> esdata = reQuote(vdata); for (int k = 1; k < (int)esdata.size(); k++) { fEpicsKey[fEpicsKey.size()-1]->AddAssign(esdata[k]); } } } } else { fFirstEpics = true; } } //_____________________________________________________________________________ Int_t THaOutput::Attach() { // Get the pointers for the global variables // Also, sets the size of the fVariables and fArrays vectors // according to the size of the related names array if( !gHaVars ) return -2; THaVar *pvar; Int_t NAry = fArrayNames.size(); Int_t NVar = fVNames.size(); fVariables.resize(NVar); fArrays.resize(NAry); // simple variable-type names for (Int_t ivar = 0; ivar < NVar; ivar++) { pvar = gHaVars->Find(fVNames[ivar].c_str()); if (pvar) { if ( !pvar->IsArray() ) { fVariables[ivar] = pvar; } else { cout << "\tTHaOutput::Attach: ERROR: Global variable " << fVNames[ivar] << " changed from simple to array!! Leaving empty space for variable" << endl; fVariables[ivar] = nullptr; } } else { cout << "\nTHaOutput::Attach: WARNING: Global variable "; cout << fVarnames[ivar] << " NO LONGER exists (it did before). "<< endl; cout << "This is not supposed to happen... "<<endl; } } // arrays for (Int_t ivar = 0; ivar < NAry; ivar++) { pvar = gHaVars->Find(fArrayNames[ivar].c_str()); if (pvar) { if ( pvar->IsArray() ) { fArrays[ivar] = pvar; } else { cout << "\tTHaOutput::Attach: ERROR: Global variable " << fVNames[ivar] << " changed from ARRAY to Simple!! Leaving empty space for variable" << endl; fArrays[ivar] = nullptr; } } else { cout << "\nTHaOutput::Attach: WARNING: Global variable "; cout << fVarnames[ivar] << " NO LONGER exists (it did before). "<< endl; cout << "This is not supposed to happen... "<<endl; } } // Reattach formulas, cuts, histos for (auto & form : fFormulas) { form->ReAttach(); } for (auto & cut : fCuts) { cut->ReAttach(); } for (auto & hist : fHistos) { hist->ReAttach(); } return 0; } //_____________________________________________________________________________ Int_t THaOutput::ProcEpics(THaEvData *evdata, THaEpicsEvtHandler *epicshandle) { // Process the EPICS data, this fills the trees. if ( !epicshandle ) return 0; if ( !epicshandle->IsMyEvent(evdata->GetEvType()) || fEpicsKey.empty() || !fEpicsTree ) return 0; if( fgDoBench ) fgBench.Begin("EPICS"); fEpicsVar[fEpicsKey.size()] = -1e32; for (size_t i = 0; i < fEpicsKey.size(); i++) { if (epicshandle->IsLoaded(fEpicsKey[i]->GetName().c_str())) { // cout << "EPICS name "<<fEpicsKey[i]->GetName()<<" val "<< epicshandle->GetString(fEpicsKey[i]->GetName().c_str())<<endl; if (fEpicsKey[i]->IsString()) { fEpicsVar[i] = fEpicsKey[i]->Eval( epicshandle->GetString( fEpicsKey[i]->GetName().c_str())); } else { fEpicsVar[i] = epicshandle->GetData( fEpicsKey[i]->GetName().c_str()); } // fill time stamp (once is ok since this is an EPICS event) fEpicsVar[fEpicsKey.size()] = epicshandle->GetTime( fEpicsKey[i]->GetName().c_str()); } else { fEpicsVar[i] = -1e32; // data not yet found } } if (fEpicsTree) fEpicsTree->Fill(); if( fgDoBench ) fgBench.Stop("EPICS"); return 1; } //_____________________________________________________________________________ Int_t THaOutput::Process() { // Process the variables, formulas, and histograms. // This is called by THaAnalyzer. if( fgDoBench ) fgBench.Begin("Formulas"); for (auto & form : fFormulas) if (form) form->Process(); if( fgDoBench ) fgBench.Stop("Formulas"); if( fgDoBench ) fgBench.Begin("Cuts"); for (auto & cut : fCuts) if (cut) cut->Process(); if( fgDoBench ) fgBench.Stop("Cuts"); if( fgDoBench ) fgBench.Begin("Variables"); THaVar *pvar; for (Int_t ivar = 0; ivar < fNvar; ivar++) { pvar = fVariables[ivar]; if (pvar) fVar[ivar] = pvar->GetValue(); } Int_t k = 0; for (auto it = fOdata.begin(); it != fOdata.end(); ++it, ++k) { THaOdata* pdat(*it); pdat->Clear(); pvar = fArrays[k]; if ( pvar == nullptr ) continue; // Fill array in reverse order so that fOdata[k] gets resized just once Int_t i = pvar->GetLen(); bool first = true; while( i-- > 0 ) { // FIXME: for better efficiency, should use pointer to data and // Fill(int n,double* data) method in case of a contiguous array if (pdat->Fill(i,pvar->GetValue(i)) != 1) { if( fgVerbose>0 && first ) { cerr << "THaOutput::ERROR: storing too much variable sized data: " << pvar->GetName() <<" "<<pvar->GetLen()<<endl; first = false; } } } } if( fgDoBench ) fgBench.Stop("Variables"); if( fgDoBench ) fgBench.Begin("Histos"); for (auto & hist : fHistos) hist->Process(); if( fgDoBench ) fgBench.Stop("Histos"); if( fgDoBench ) fgBench.Begin("TreeFill"); if (fTree) fTree->Fill(); if( fgDoBench ) fgBench.Stop("TreeFill"); return 0; } //_____________________________________________________________________________ Int_t THaOutput::End() { if( fgDoBench ) fgBench.Begin("End"); if (fTree) fTree->Write(); if (fEpicsTree) fEpicsTree->Write(); for (auto & hist : fHistos) hist->End(); if( fgDoBench ) fgBench.Stop("End"); if( fgDoBench ) { cout << "Output timing summary:" << endl; fgBench.Print("Init"); fgBench.Print("Attach"); fgBench.Print("Variables"); fgBench.Print("Formulas"); fgBench.Print("Cuts"); fgBench.Print("Histos"); fgBench.Print("TreeFill"); fgBench.Print("EPICS"); fgBench.Print("End"); } return 0; } //_____________________________________________________________________________ Int_t THaOutput::LoadFile( const char* filename ) { // Process the file that defines the output const char* const here = "THaOutput::LoadFile"; if( !filename || !*filename || strspn(filename," ") == strlen(filename) ) { ::Error( here, "invalid file name, no output definition loaded" ); return -2; } string loadfile(filename); ifstream odef(loadfile.c_str()); if ( !odef ) { ErrFile(-1, loadfile); return -1; } string::size_type pos; vector<string> strvect; string sline; while (getline(odef,sline)) { // #include if( sline.substr(0,kIncTag.length()) == kIncTag && sline.length() > kIncTag.length() ) { string incfilename; if( GetIncludeFileName(sline,incfilename) != 0 ) { ostringstream ostr; ostr << "Error in #include specification: " << sline; ::Error( here, "%s", ostr.str().c_str() ); return -3; } if( CheckIncludeFilePath(incfilename) != 0 ) { ostringstream ostr; ostr << "Error opening include file: " << sline; ::Error( here, "%s", ostr.str().c_str() ); return -3; } if( incfilename == filename ) { // File including itself? // FIXME: does not catch including the same file via full pathname or similar ostringstream ostr; ostr << "File cannot include itself: " << sline; ::Error( here, "%s", ostr.str().c_str() ); return -3; } Int_t ret = LoadFile( incfilename.c_str() ); if( ret != 0 ) return ret; continue; } // Blank line or comment line? if( sline.empty() || (pos = sline.find_first_not_of(kWhiteSpace)) == string::npos || sline[pos] == comment ) continue; // Get rid of trailing comments if( (pos = sline.find(comment)) != string::npos ) sline.erase(pos); // Substitute text variables vector<string> lines( 1, sline ); if( gHaTextvars->Substitute(lines) ) continue; for( auto& str : lines ) { // Split the line into tokens separated by whitespace strvect = Split(str); bool special_before = (fOpenEpics); BuildList(strvect); bool special_now = (fOpenEpics); if( special_before || special_now ) continue; // strvect already processed if (strvect.size() < 2) { ErrFile(0, str); continue; } fIsScalar = false; // this may be set true by svPrefix string svkey = svPrefix(strvect[0]); Int_t ikey = FindKey(svkey); string sname = StripBracket(strvect[1]); switch (ikey) { case kVar: fVarnames.push_back(sname); break; case kForm: if (strvect.size() < 3) { ErrFile(ikey, str); continue; } fFormnames.push_back(sname); fFormdef.push_back(strvect[2]); break; case kCut: if (strvect.size() < 3) { ErrFile(ikey, str); continue; } fCutnames.push_back(sname); fCutdef.push_back(strvect[2]); break; case kH1f: case kH1d: case kH2f: case kH2d: if( ChkHistTitle(ikey, str) != 1) { ErrFile(ikey, str); continue; } fHistos.push_back(new THaVhist(svkey,sname,stitle)); // Tentatively assign variables and cuts as strings. // Later will check if they are actually THaVform's. fHistos.back()->SetX(nx, xlo, xhi, sfvarx); if (ikey == kH2f || ikey == kH2d) { fHistos.back()->SetY(ny, ylo, yhi, sfvary); } if (iscut != fgNocut) fHistos.back()->SetCut(scut); // If we know now that its a scalar, inform the histogram to remain that way // and over-ride its internal rules for self-determining if its a vector. if (fIsScalar) fHistos.back()->SetScalarTrue(); break; case kBlock: // Do not strip brackets for block regexps: use strvect[1] not sname if( BuildBlock(strvect[1]) == 0 ) { cout << "\nTHaOutput::Init: WARNING: Block "; cout << strvect[1] << " does not match any variables. " << endl; cout << "There is probably a typo error... "<<endl; } break; case kBegin: case kEnd: break; default: cout << "Warning: keyword "<<svkey<<" undefined "<<endl; } } } // sort thru fVarnames, removing identical entries if( fVarnames.size() > 1 ) { sort(fVarnames.begin(),fVarnames.end()); auto Vi = fVarnames.begin(); while ( (Vi+1)!=fVarnames.end() ) { if ( *Vi == *(Vi+1) ) { fVarnames.erase(Vi+1); } else { ++Vi; } } } return 0; } //_____________________________________________________________________________s string THaOutput::svPrefix(string& histtype) { // If the arg is a string for a histogram type, we strip the initial // "s" or "v". If the first character is "s" we set fIsScalar true. const int ldebug=0; fIsScalar = false; string sresult = histtype; if (ldebug) cout << "svPrefix histogram type = "<<histtype<<" histtype length "<<histtype.length()<<endl; // For histograms `histtype' is of the form "XthNY" // with X="s" or "v" and N=1 or 2, Y = "f" or "d" // For example, "sth1f". Note it always has length 5 if (histtype.length() != 5) return sresult; string sfirst = histtype.substr(0,1); if (ldebug) cout << "sfirst = "<<sfirst<<endl; if(CmpNoCase(sfirst,"s")==0) fIsScalar = true; sresult=histtype.substr(1); // Needs to be a histogram, not something else like block if( (CmpNoCase(sresult,"th1f")!=0) && (CmpNoCase(sresult,"th2f")!=0) && (CmpNoCase(sresult,"th1d")!=0) && (CmpNoCase(sresult,"th2d")!=0) ) return histtype; // return original if (ldebug) { cout << "result "<<sresult<< endl; if (fIsScalar) cout << "fScalar is TRUE"<<endl; } return sresult; } //_____________________________________________________________________________ Int_t THaOutput::FindKey(const string& key) const { // Return integer flag corresponding to // case-insensitive keyword "key" if it exists // Map of keywords to internal logical type numbers struct KeyMap { const char* name; EId keyval; }; static const KeyMap keymap[] = { { "variable", kVar }, { "formula", kForm }, { "cut", kCut }, { "th1f", kH1f }, { "th1d", kH1d }, { "th2f", kH2f }, { "th2d", kH2d }, { "block", kBlock }, { "begin", kBegin }, { "end", kEnd }, { nullptr } }; if( const KeyMap* it = keymap ) { while( it->name ) { if( CmpNoCase( key, it->name ) == 0 ) return it->keyval; it++; } } return -1; } //_____________________________________________________________________________ string THaOutput::StripBracket(const string& var) const { // If the string contains "[anything]", we strip // it away. In practice this should not be fatal // because your variable will still show up in the tree. string::size_type pos1,pos2; string open_brack("["); string close_brack("]"); string result; pos1 = var.find(open_brack,0); pos2 = var.find(close_brack,0); if ((pos1 != string::npos) && (pos2 != string::npos)) { result = var.substr(0,pos1); result += var.substr(pos2+1,var.length()); // cout << "THaOutput:WARNING:: Stripping away"; // cout << "unwanted brackets from "<<var<<endl; } else { result = var; } return result; } //_____________________________________________________________________________ vector<string> THaOutput::reQuote(const vector<string>& input) const { // Specialist private function needed by EPICs line parser: // The problem is that the line was split by white space, so // a line like "'RF On'=42" must be repackaged into // one string, i.e. "'RF" and "On'=42" put back together. vector<string> result; result.clear(); int first_quote = 1; int to_add = 0; string temp1,temp2,temp3; string::size_type pos1,pos2; for( const auto& str : input ) { temp1 = str; pos1 = temp1.find('\''); if (pos1 != string::npos) { if (first_quote) { temp2.assign(temp1.substr(pos1,temp1.length())); // But there might be a 2nd "'" with no spaces // like "'Yes'" (silly, but understandable & allowed) temp3.assign(temp1.substr(pos1+1,temp1.length())); pos2 = temp3.find('\''); if (pos2 != string::npos) { temp1.assign(temp3.substr(0,pos2)); temp2.assign(temp3.substr (pos2+1,temp3.length())); temp3 = temp1+temp2; result.push_back(temp3); continue; } first_quote = 0; to_add = 1; } else { temp2 += " "; temp2 += temp1; result.push_back(temp2); temp2.clear(); first_quote = 1; to_add = 0; } } else { if (to_add) { temp2 += " "; temp2 += temp1; } else { result.push_back(temp1); } } } return result; } //_____________________________________________________________________________ string THaOutput::CleanEpicsName(const string& input) const { // To clean up EPICS variable names that contain // bad characters like ":" and arithmetic operations // that confuse TTree::Draw(). // Replace all 'badchar' with 'goodchar' static const char badchar[]=":+-*/="; static const string goodchar = "_"; int numbad = sizeof(badchar)/sizeof(char) - 1; string output = input; for (int i = 0; i < numbad; i++) { string sbad(&badchar[i]); sbad.erase(1,sbad.size()); string::size_type pos = input.find(sbad,0); while (pos != string::npos) { output.replace(pos,1,goodchar); pos = input.find(sbad,pos+1); } } return output; } //_____________________________________________________________________________ void THaOutput::ErrFile(Int_t iden, const string& sline) const { // Print error messages about the output definition file. if (iden == -1) { cerr << "<THaOutput::LoadFile> WARNING: file " << sline; cerr << " does not exist." << endl; cerr << "See $ANALYZER/examples/output.def for an example.\n"; cerr << "Output will only contain event objects " "(this may be all you want).\n"; return; } if (fOpenEpics) return; // No error cerr << "THaOutput::ERROR: Syntax error in output definition file."<<endl; cerr << "The offending line is :\n"<<sline<<endl<<endl; switch (iden) { case kVar: cerr << "For variables, the syntax is: "<<endl; cerr << " variable variable-name"<<endl; cerr << "Example: "<<endl; cerr << " variable R.vdc.v2.nclust"<<endl; break; case kCut: case kForm: cerr << "For formulas or cuts, the syntax is: "<<endl; cerr << " formula(or cut) formula-name formula-expression"<<endl; cerr << "Example: "<<endl; cerr << " formula targetX 1.464*B.bpm4b.x-0.464*B.bpm4a.x"<<endl; break; case kH1f: case kH1d: cerr << "For 1D histograms, the syntax is: "<<endl; cerr << " TH1F(or TH1D) name 'title' "; cerr << "variable nbin xlo xhi [cut-expr]"<<endl; cerr << "Example: "<<endl; cerr << " TH1F tgtx 'target X' targetX 100 -2 2"<<endl; cerr << "(Title in single quotes. Variable can be a formula)"<<endl; cerr << "optionally can impose THaCut expression 'cut-expr'"<<endl; break; case kH2f: case kH2d: cerr << "For 2D histograms, the syntax is: "<<endl; cerr << " TH2F(or TH2D) name 'title' varx vary"; cerr << " nbinx xlo xhi nbiny ylo yhi [cut-expr]"<<endl; cerr << "Example: "<<endl; cerr << " TH2F t12 't1 vs t2' D.timeroc1 D.timeroc2"; cerr << " 100 0 20000 100 0 35000"<<endl; cerr << "(Title in single quotes. Variable can be a formula)"<<endl; cerr << "optionally can impose THaCut expression 'cut-expr'"<<endl; break; default: cerr << "Illegal line: " << sline << endl; cerr << "See the documentation or ask Bob Michaels"<<endl; break; } } //_____________________________________________________________________________ void THaOutput::Print() const { // Printout the definitions. Amount printed depends on verbosity // level, set with SetVerbosity(). if( fgVerbose > 0 ) { if( fVarnames.empty() && fFormulas.empty() && fCuts.empty() && fHistos.empty() ) { ::Warning("THaOutput", "no output defined"); } else { cout << endl << "THaOutput definitions: " << endl; if( !fVarnames.empty() ) { cout << "=== Number of variables "<<fVarnames.size()<<endl; if( fgVerbose > 1 ) { cout << endl; UInt_t i = 0; for (auto ivar = fVarnames.begin(); ivar != fVarnames.end(); i++, ivar++ ) { cout << "Variable # "<<i<<" = "<<(*ivar)<<endl; } } } if( !fFormulas.empty() ) { cout << "=== Number of formulas "<<fFormulas.size()<<endl; if( fgVerbose > 1 ) { cout << endl; UInt_t i = 0; for (auto iform = fFormulas.begin(); iform != fFormulas.end(); i++, iform++ ) { cout << "Formula # "<<i<<endl; if( fgVerbose>2 ) (*iform)->LongPrint(); else (*iform)->ShortPrint(); } } } if( !fCuts.empty() ) { cout << "=== Number of cuts "<<fCuts.size()<<endl; if( fgVerbose > 1 ) { cout << endl; UInt_t i = 0; for (auto icut = fCuts.begin(); icut != fCuts.end(); i++, icut++ ) { cout << "Cut # "<<i<<endl; if( fgVerbose>2 ) (*icut)->LongPrint(); else (*icut)->ShortPrint(); } } } if( !fHistos.empty() ) { cout << "=== Number of histograms "<<fHistos.size()<<endl; if( fgVerbose > 1 ) { cout << endl; UInt_t i = 0; for (auto ihist = fHistos.begin(); ihist != fHistos.end(); i++, ihist++) { cout << "Histogram # "<<i<<endl; (*ihist)->Print(); } } } cout << endl; } } } //_____________________________________________________________________________ Int_t THaOutput::ChkHistTitle(Int_t iden, const string& sline) { // Parse the string that defines the histogram. // The title must be enclosed in single quotes (e.g. 'my title'). // Ret value 'result' means: -1 == error, 1 == everything ok. Int_t result = -1; stitle = ""; sfvarx = ""; sfvary = ""; iscut = fgNocut; scut = ""; nx = 0; ny = 0; xlo = 0; xhi = 0; ylo = 0; yhi = 0; string::size_type pos1 = sline.find_first_of('\''); string::size_type pos2 = sline.find_last_of('\''); if (pos1 != string::npos && pos2 > pos1) { stitle = sline.substr(pos1+1,pos2-pos1-1); } string ctemp = sline.substr(pos2+1,sline.size()-pos2); vector<string> stemp = Split(ctemp); if (stemp.size() > 1) { sfvarx = stemp[0]; Int_t ssize = stemp.size(); if (ssize == 4 || ssize == 5) { sscanf(stemp[1].c_str(),"%8d",&nx); sscanf(stemp[2].c_str(),"%16f",&xlo); sscanf(stemp[3].c_str(),"%16f",&xhi); if (ssize == 5) { iscut = 1; scut = stemp[4]; } result = 1; } if (ssize == 8 || ssize == 9) { sfvary = stemp[1]; sscanf(stemp[2].c_str(),"%8d",&nx); sscanf(stemp[3].c_str(),"%16f",&xlo); sscanf(stemp[4].c_str(),"%16f",&xhi); sscanf(stemp[5].c_str(),"%8d",&ny); sscanf(stemp[6].c_str(),"%16f",&ylo); sscanf(stemp[7].c_str(),"%16f",&yhi); if (ssize == 9) { iscut = 1; scut = stemp[8]; } result = 2; } } if (result != 1 && result != 2) return -1; if ((iden == kH1f || iden == kH1d) && result == 1) return 1; // ok if ((iden == kH2f || iden == kH2d) && result == 2) return 1; // ok return -1; } //_____________________________________________________________________________ Int_t THaOutput::BuildBlock(const string& blockn) { // From the block name, identify and save a specific grouping // of global variables by adding them to the fVarnames list. // // For efficiency, at the end of building the list we should // ensure that variables are listed only once. // // Eventually, we can have some specially named blocks, // but for now we simply will use pattern matching, such that // block L.* // would save all variables from the left spectrometer. TRegexp re(blockn.c_str(),true); TIter next(gHaVars); TObject *obj; Int_t nvars=0; while ((obj = next())) { TString s = obj->GetName(); if ( s.Index(re) != kNPOS ) { fVarnames.emplace_back(s.Data()); nvars++; } } return nvars; } //_____________________________________________________________________________ void THaOutput::SetVerbosity( Int_t level ) { // Set verbosity level for debug messages fgVerbose = level; } //_____________________________________________________________________________ //ClassImp(THaOdata) ClassImp(THaOutput)
30.366524
137
0.613365
[ "vector" ]
81f1ad4e2dd0083dd320de131f536bfce2c7ac69
6,202
cpp
C++
modules/gapi/test/internal/gapi_int_gmetaarg_test.cpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
modules/gapi/test/internal/gapi_int_gmetaarg_test.cpp
yusufm423/opencv
6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
modules/gapi/test/internal/gapi_int_gmetaarg_test.cpp
yusufm423/opencv
6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #include "../test_precomp.hpp" #include "api/gcomputation_priv.hpp" namespace opencv_test { TEST(GMetaArg, Traits_Is_Positive) { using namespace cv::detail; static_assert(is_meta_descr<cv::GScalarDesc>::value, "GScalarDesc is a meta description type"); static_assert(is_meta_descr<cv::GMatDesc>::value, "GMatDesc is a meta description type"); } TEST(GMetaArg, Traits_Is_Negative) { using namespace cv::detail; static_assert(!is_meta_descr<cv::GCompileArgs>::value, "GCompileArgs is NOT a meta description type"); static_assert(!is_meta_descr<int>::value, "int is NOT a meta description type"); static_assert(!is_meta_descr<std::string>::value, "str::string is NOT a meta description type"); } TEST(GMetaArg, Traits_Are_EntireList_Positive) { using namespace cv::detail; static_assert(are_meta_descrs<cv::GScalarDesc>::value, "GScalarDesc is a meta description type"); static_assert(are_meta_descrs<cv::GMatDesc>::value, "GMatDesc is a meta description type"); static_assert(are_meta_descrs<cv::GMatDesc, cv::GScalarDesc>::value, "Both GMatDesc and GScalarDesc are meta types"); } TEST(GMetaArg, Traits_Are_EntireList_Negative) { using namespace cv::detail; static_assert(!are_meta_descrs<cv::GCompileArgs>::value, "GCompileArgs is NOT among meta types"); static_assert(!are_meta_descrs<int, std::string>::value, "Both int and std::string is NOT among meta types"); static_assert(!are_meta_descrs<cv::GMatDesc, cv::GScalarDesc, int>::value, "List of type is not valid for meta as there\'s int"); static_assert(!are_meta_descrs<cv::GMatDesc, cv::GScalarDesc, cv::GCompileArgs>::value, "List of type is not valid for meta as there\'s GCompileArgs"); } TEST(GMetaArg, Traits_Are_ButLast_Positive) { using namespace cv::detail; static_assert(are_meta_descrs_but_last<cv::GScalarDesc, int>::value, "List is valid (int is omitted)"); static_assert(are_meta_descrs_but_last<cv::GMatDesc, cv::GScalarDesc, cv::GCompileArgs>::value, "List is valid (GCompileArgs are omitted)"); } TEST(GMetaArg, Traits_Are_ButLast_Negative) { using namespace cv::detail; static_assert(!are_meta_descrs_but_last<int, std::string>::value, "Both int is NOT among meta types (std::string is omitted)"); static_assert(!are_meta_descrs_but_last<cv::GMatDesc, cv::GScalarDesc, int, int>::value, "List of type is not valid for meta as there\'s two ints"); static_assert(!are_meta_descrs_but_last<cv::GMatDesc, cv::GScalarDesc, cv::GCompileArgs, float>::value, "List of type is not valid for meta as there\'s GCompileArgs"); } TEST(GMetaArg, Can_Get_Metas_From_Input_Run_Args) { cv::Mat m(3, 3, CV_8UC3); cv::Scalar s; std::vector<int> v; GMatDesc m_desc; GMetaArgs meta_args = descr_of(cv::gin(m, s, v)); EXPECT_EQ(meta_args.size(), 3u); EXPECT_NO_THROW(m_desc = util::get<cv::GMatDesc>(meta_args[0])); EXPECT_NO_THROW(util::get<cv::GScalarDesc>(meta_args[1])); EXPECT_NO_THROW(util::get<cv::GArrayDesc>(meta_args[2])); EXPECT_EQ(CV_8U, m_desc.depth); EXPECT_EQ(3, m_desc.chan); EXPECT_EQ(cv::gapi::own::Size(3, 3), m_desc.size); } TEST(GMetaArg, Can_Get_Metas_From_Output_Run_Args) { cv::Mat m(3, 3, CV_8UC3); cv::Scalar s; std::vector<int> v; GMatDesc m_desc; GRunArgsP out_run_args = cv::gout(m, s, v); GMetaArg m_meta = descr_of(out_run_args[0]); GMetaArg s_meta = descr_of(out_run_args[1]); GMetaArg v_meta = descr_of(out_run_args[2]); EXPECT_NO_THROW(m_desc = util::get<cv::GMatDesc>(m_meta)); EXPECT_NO_THROW(util::get<cv::GScalarDesc>(s_meta)); EXPECT_NO_THROW(util::get<cv::GArrayDesc>(v_meta)); EXPECT_EQ(CV_8U, m_desc.depth); EXPECT_EQ(3, m_desc.chan); EXPECT_EQ(cv::Size(3, 3), m_desc.size); } TEST(GMetaArg, Can_Describe_RunArg) { cv::Mat m(3, 3, CV_8UC3); cv::UMat um(3, 3, CV_8UC3); cv::Scalar s; constexpr int w = 3, h = 3, c = 3; uchar data[w*h*c]; cv::gapi::own::Mat om(h, w, CV_8UC3, data); cv::Scalar os; std::vector<int> v; GMetaArgs metas = {GMetaArg(descr_of(m)), GMetaArg(descr_of(um)), GMetaArg(descr_of(s)), GMetaArg(descr_of(om)), GMetaArg(descr_of(os)), GMetaArg(descr_of(v))}; auto in_run_args = cv::gin(m, um, s, om, os, v); for (int i = 0; i < 3; i++) { EXPECT_TRUE(can_describe(metas[i], in_run_args[i])); } } TEST(GMetaArg, Can_Describe_RunArgs) { cv::Mat m(3, 3, CV_8UC3); cv::Scalar s; std::vector<int> v; GMetaArgs metas0 = {GMetaArg(descr_of(m)), GMetaArg(descr_of(s)), GMetaArg(descr_of(v))}; auto in_run_args0 = cv::gin(m, s, v); EXPECT_TRUE(can_describe(metas0, in_run_args0)); auto in_run_args01 = cv::gin(m, s); EXPECT_FALSE(can_describe(metas0, in_run_args01)); } TEST(GMetaArg, Can_Describe_RunArgP) { cv::Mat m(3, 3, CV_8UC3); cv::UMat um(3, 3, CV_8UC3); cv::Scalar s; constexpr int w = 3, h = 3, c = 3; uchar data[w*h*c]; cv::gapi::own::Mat om(h, w, CV_8UC3, data); cv::Scalar os; std::vector<int> v; GMetaArgs metas = {GMetaArg(descr_of(m)), GMetaArg(descr_of(um)), GMetaArg(descr_of(s)), GMetaArg(descr_of(om)), GMetaArg(descr_of(os)), GMetaArg(descr_of(v))}; auto out_run_args = cv::gout(m, um, s, om, os, v); for (int i = 0; i < 3; i++) { EXPECT_TRUE(can_describe(metas[i], out_run_args[i])); } } } // namespace opencv_test
30.70297
107
0.631893
[ "vector" ]
81f30463c4fcc545d2fa7482f76732c91b0cd75a
13,263
hpp
C++
openstudiocore/src/model/Surface_Impl.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/Surface_Impl.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/Surface_Impl.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_SURFACE_IMPL_HPP #define MODEL_SURFACE_IMPL_HPP #include <model/ModelAPI.hpp> #include <model/PlanarSurface_Impl.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/adapted/boost_tuple.hpp> namespace openstudio { namespace model { class Space; class SubSurface; class Surface; namespace detail { /** Surface_Impl is a PlanarSurface_Impl that is the implementation class for Surface.*/ class MODEL_API Surface_Impl : public PlanarSurface_Impl { Q_OBJECT; Q_PROPERTY(std::string constructionType READ constructionType WRITE setConstructionType); Q_PROPERTY(std::string surfaceType READ surfaceType WRITE setSurfaceType); Q_PROPERTY(std::vector<std::string> surfaceTypeValues READ surfaceTypeValues); Q_PROPERTY(std::string outsideBoundaryCondition READ outsideBoundaryCondition WRITE setOutsideBoundaryCondition); Q_PROPERTY(std::vector<std::string> outsideBoundaryConditionValues READ outsideBoundaryConditionValues); Q_PROPERTY(std::string sunExposure READ sunExposure WRITE setSunExposure RESET resetSunExposure); Q_PROPERTY(std::vector<std::string> sunExposureValues READ sunExposureValues); Q_PROPERTY(bool isSunExposureDefaulted READ isSunExposureDefaulted); Q_PROPERTY(std::string windExposure READ windExposure WRITE setWindExposure RESET resetWindExposure); Q_PROPERTY(std::vector<std::string> windExposureValues READ windExposureValues); Q_PROPERTY(bool isWindExposureDefaulted READ isWindExposureDefaulted); Q_PROPERTY(boost::optional<double> viewFactortoGround READ viewFactortoGround WRITE setViewFactortoGround RESET resetViewFactortoGround); Q_PROPERTY(bool isViewFactortoGroundDefaulted READ isViewFactortoGroundDefaulted); Q_PROPERTY(bool isViewFactortoGroundAutocalculated READ isViewFactortoGroundAutocalculated); Q_PROPERTY(boost::optional<double> numberofVertices READ numberofVertices WRITE setNumberofVertices RESET resetNumberofVertices); Q_PROPERTY(bool isNumberofVerticesDefaulted READ isNumberofVerticesDefaulted); Q_PROPERTY(bool isNumberofVerticesAutocalculated READ isNumberofVerticesAutocalculated); Q_PROPERTY(bool isPartOfEnvelope READ isPartOfEnvelope); Q_PROPERTY(boost::optional<openstudio::model::ModelObject> space READ spaceAsModelObject WRITE setSpaceAsModelObject); Q_PROPERTY(std::vector<openstudio::model::ModelObject> subSurfaces READ subSurfacesAsModelObjects); Q_PROPERTY(boost::optional<openstudio::model::ModelObject> adjacentSurface READ adjacentSurfaceAsModelObject WRITE setAdjacentSurfaceAsModelObject RESET resetAdjacentSurface); public: /** @name Constructors and Destructors */ //@{ Surface_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); Surface_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); Surface_Impl(const Surface_Impl& other, Model_Impl* model, bool keepHandle); virtual ~Surface_Impl(); //@} // return the parent object in the hierarchy virtual boost::optional<ParentObject> parent() const; /// set the parent, child may have to call methods on the parent virtual bool setParent(ParentObject& newParent); // return any children objects in the hierarchy virtual std::vector<ModelObject> children() const; /// remove self and all children objects recursively virtual std::vector<IdfObject> remove(); /// get a vector of allowable children types virtual std::vector<IddObjectType> allowableChildTypes() const; virtual const std::vector<std::string>& outputVariableNames() const; virtual IddObjectType iddObjectType() const; /// should subtract this surface from parent's gross area for net area virtual bool subtractFromGrossArea() const; /// get the construction object /// if the planar surface is paired with an adjacent planar surface, attempts to resolve any surface matching conflict virtual boost::optional<ConstructionBase> construction() const; /// get the construction object and the search distance that was needed to find the construction /// does not consider adjacent planar surfaces virtual boost::optional<std::pair<ConstructionBase, int> > constructionWithSearchDistance() const; /// Returns true if the construction is not directly referenced by this surface . virtual bool isConstructionDefaulted() const; virtual bool setVertices(const std::vector<Point3d>& vertices); /// set the construction object virtual bool setConstruction(const ConstructionBase& construction); /// Resets the construction object. virtual void resetConstruction(); /// Returns the containing PlanarSurfaceGroup if available. virtual boost::optional<PlanarSurfaceGroup> planarSurfaceGroup() const; /// Returns the containing Space if available. virtual boost::optional<Space> space() const; /** Get the u-factor of this surface. Includes film coefficients. */ virtual boost::optional<double> uFactor() const; /** Get the conductance of this surface. Does not include film coefficients. */ virtual boost::optional<double> thermalConductance() const; /** Set the u-factor of this surface in W/m^2*K, if possible. value should already include appropriate * film coefficients. By default, assumes still air indoors and 15 mph outdoor air speed. */ virtual bool setUFactor(double value); /** Set the conductance of this surface in W/m^2*K, if possible. value should not include any film * coefficients. */ virtual bool setThermalConductance(double value); /** @name Getters */ //@{ std::string surfaceType() const; std::vector<std::string> surfaceTypeValues() const; std::string outsideBoundaryCondition() const; std::vector<std::string> outsideBoundaryConditionValues() const; bool isGroundSurface() const; std::string sunExposure() const; std::vector<std::string> sunExposureValues() const; bool isSunExposureDefaulted() const; std::string windExposure() const; std::vector<std::string> windExposureValues() const; bool isWindExposureDefaulted() const; boost::optional<double> viewFactortoGround() const; bool isViewFactortoGroundDefaulted() const; bool isViewFactortoGroundAutocalculated() const; boost::optional<double> numberofVertices() const; bool isNumberofVerticesDefaulted() const; bool isNumberofVerticesAutocalculated() const; //@} /** @name Setters */ //@{ bool setSurfaceType(std::string surfaceType); bool setSurfaceType(std::string surfaceType, bool driverMethod); bool setOutsideBoundaryCondition(std::string outsideBoundaryCondition); bool setOutsideBoundaryCondition(std::string outsideBoundaryCondition, bool driverMethod); bool setSunExposure(std::string sunExposure); bool setSunExposure(std::string sunExposure, bool driverMethod); void resetSunExposure(); bool setWindExposure(std::string windExposure); bool setWindExposure(std::string windExposure, bool driverMethod); void resetWindExposure(); bool setViewFactortoGround(boost::optional<double> viewFactortoGround); bool setViewFactortoGround(double viewFactortoGround); void resetViewFactortoGround(); void autocalculateViewFactortoGround(); bool setNumberofVertices(boost::optional<double> numberofVertices); bool setNumberofVertices(double numberofVertices); void resetNumberofVertices(); void autocalculateNumberofVertices(); //@} /// Returns all child \link SubSurface SubSurfaces \endlink. std::vector<SubSurface> subSurfaces() const; /// Sets the parent Space. bool setSpace(const Space& space); /** Returns the adjacent Surface, if it exists. */ boost::optional<Surface> adjacentSurface() const; /** Sets the adjacent Surface. */ bool setAdjacentSurface(Surface& surface); /** Resets the adjacent Surface. */ void resetAdjacentSurface(); /** Intersect with other Surface in other Space. * Returns false if either surface has child windows. * Returns false if either surface has an adjacent surface. * Returns false if surfaces are not on the same plane with opposing outward normals. * If the surfaces are the same, returns true but no new geometry is created. * Returns true if an intersection occurred. Does not set surface adjacency. */ bool intersect(Surface& otherSurface); /** Creates an adjacent Surface in another Space, also create adjacent SubSurface objects if needed. Returns the new Surface if created. */ boost::optional<Surface> createAdjacentSurface(const Space& otherSpace); /** Returns true if the Surface is part of the building envelope. */ bool isPartOfEnvelope() const; /** Assign default surface type based on vertices. */ void assignDefaultSurfaceType(); void assignDefaultSurfaceType(bool driverMethod); /** Assign default boundary condition. */ void assignDefaultBoundaryCondition(); void assignDefaultBoundaryCondition(bool driverMethod); /** Assign default sun exposure. */ void assignDefaultSunExposure(); void assignDefaultSunExposure(bool driverMethod); /** Assign default wind exposure. */ void assignDefaultWindExposure(); void assignDefaultWindExposure(bool driverMethod); /** Returns the ConstructionBase.standardsInformation().constructionType(). Method provided * so constructionType can be Attribute on the Surface. */ std::string constructionType() const; /** Set the ConstructionBase.standardsInformation().constructionType(). Method provided so * constructionType can be Attribute on the Surface. */ bool setConstructionType(const std::string& type); /** Get the default film thermal resistance (m^2*K/W) for this surface. Assumes still indoor * air, and 15 mph wind outside. */ double filmResistance() const; /** Get the window to wall ratio for this surface. Calculated as sum(surface.windows.netArea)/surface.grossArea if this surface is a wall, returns 0 if this surface is not a wall. */ double windowToWallRatio() const; /** Sets the window to wall ratio for this surface. Returns false if the surface is not a wall, if the surface is not rectangular in face coordinates, if requested ratio is too large (window area ~= surface area) or too small (min dimension of window < 1 foot), or if the window clips any remaining sub surfaces. Otherwise, removes all existing windows and adds new window to meet requested ratio.*/ boost::optional<SubSurface> setWindowToWallRatio(double wwr); /** Same as setWindowToWallRatio but with extra parameters desiredHeightOffset and heightOffsetFromFloor. If heightOffsetFromFloor is true then desiredHeightOffset is the desired sill height, otherwise it is the offset from the ceiling. */ boost::optional<SubSurface> setWindowToWallRatio(double wwr, double desiredHeightOffset, bool heightOffsetFromFloor); protected: private: friend class openstudio::model::Surface; REGISTER_LOGGER("openstudio.model.Surface"); std::vector<ModelObject> subSurfacesAsModelObjects() const; boost::optional<ModelObject> adjacentSurfaceAsModelObject() const; bool setSpaceAsModelObject(const boost::optional<ModelObject>& modelObject); bool setAdjacentSurfaceAsModelObject(const boost::optional<ModelObject>& modelObject); // helper function to get a boost polygon point from a Point3d boost::tuple<double, double> point3dToTuple(const Point3d& point3d, std::vector<Point3d>& allPoints, double tol) const; }; } // detail } // model } // openstudio #endif // MODEL_SURFACE_IMPL_HPP
41.576803
180
0.721707
[ "geometry", "object", "vector", "model" ]
81f5b89621be186129c392c206d60c25b3c8a599
13,654
cpp
C++
src/analyses/escape_analysis.cpp
muralitaws/cbmc
5d1fe3858726692e4abef75828dd88de074be133
[ "BSD-4-Clause" ]
null
null
null
src/analyses/escape_analysis.cpp
muralitaws/cbmc
5d1fe3858726692e4abef75828dd88de074be133
[ "BSD-4-Clause" ]
null
null
null
src/analyses/escape_analysis.cpp
muralitaws/cbmc
5d1fe3858726692e4abef75828dd88de074be133
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Field-insensitive, location-sensitive escape analysis Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ /// \file /// Field-insensitive, location-sensitive escape analysis #include "escape_analysis.h" #include <util/cprover_prefix.h> #include <util/pointer_expr.h> #include <util/simplify_expr.h> bool escape_domaint::is_tracked(const symbol_exprt &symbol) { const irep_idt &identifier=symbol.get_identifier(); if( identifier == CPROVER_PREFIX "memory_leak" || identifier == CPROVER_PREFIX "malloc_object" || identifier == CPROVER_PREFIX "dead_object" || identifier == CPROVER_PREFIX "deallocated") { return false; } return true; } irep_idt escape_domaint::get_function(const exprt &lhs) { if(lhs.id()==ID_address_of) return get_function(to_address_of_expr(lhs).object()); else if(lhs.id()==ID_typecast) return get_function(to_typecast_expr(lhs).op()); else if(lhs.id()==ID_symbol) { irep_idt identifier=to_symbol_expr(lhs).get_identifier(); return identifier; } return irep_idt(); } void escape_domaint::assign_lhs_cleanup( const exprt &lhs, const std::set<irep_idt> &cleanup_functions) { if(lhs.id()==ID_symbol) { const symbol_exprt &symbol_expr=to_symbol_expr(lhs); if(is_tracked(symbol_expr)) { irep_idt identifier=symbol_expr.get_identifier(); if(cleanup_functions.empty()) cleanup_map.erase(identifier); else cleanup_map[identifier].cleanup_functions=cleanup_functions; } } } void escape_domaint::assign_lhs_aliases( const exprt &lhs, const std::set<irep_idt> &alias_set) { if(lhs.id()==ID_symbol) { const symbol_exprt &symbol_expr=to_symbol_expr(lhs); if(is_tracked(symbol_expr)) { irep_idt identifier=symbol_expr.get_identifier(); aliases.isolate(identifier); for(const auto &alias : alias_set) { aliases.make_union(identifier, alias); } } } } void escape_domaint::get_rhs_cleanup( const exprt &rhs, std::set<irep_idt> &cleanup_functions) { if(rhs.id()==ID_symbol) { const symbol_exprt &symbol_expr=to_symbol_expr(rhs); if(is_tracked(symbol_expr)) { irep_idt identifier=symbol_expr.get_identifier(); const escape_domaint::cleanup_mapt::const_iterator m_it= cleanup_map.find(identifier); if(m_it!=cleanup_map.end()) cleanup_functions.insert(m_it->second.cleanup_functions.begin(), m_it->second.cleanup_functions.end()); } } else if(rhs.id()==ID_if) { get_rhs_cleanup(to_if_expr(rhs).true_case(), cleanup_functions); get_rhs_cleanup(to_if_expr(rhs).false_case(), cleanup_functions); } else if(rhs.id()==ID_typecast) { get_rhs_cleanup(to_typecast_expr(rhs).op(), cleanup_functions); } } void escape_domaint::get_rhs_aliases( const exprt &rhs, std::set<irep_idt> &alias_set) { if(rhs.id()==ID_symbol) { const symbol_exprt &symbol_expr=to_symbol_expr(rhs); if(is_tracked(symbol_expr)) { irep_idt identifier=symbol_expr.get_identifier(); alias_set.insert(identifier); for(const auto &alias : aliases) if(aliases.same_set(alias, identifier)) alias_set.insert(alias); } } else if(rhs.id()==ID_if) { get_rhs_aliases(to_if_expr(rhs).true_case(), alias_set); get_rhs_aliases(to_if_expr(rhs).false_case(), alias_set); } else if(rhs.id()==ID_typecast) { get_rhs_aliases(to_typecast_expr(rhs).op(), alias_set); } else if(rhs.id()==ID_address_of) { get_rhs_aliases_address_of(to_address_of_expr(rhs).op(), alias_set); } } void escape_domaint::get_rhs_aliases_address_of( const exprt &rhs, std::set<irep_idt> &alias_set) { if(rhs.id()==ID_symbol) { irep_idt identifier=to_symbol_expr(rhs).get_identifier(); alias_set.insert("&"+id2string(identifier)); } else if(rhs.id()==ID_if) { get_rhs_aliases_address_of(to_if_expr(rhs).true_case(), alias_set); get_rhs_aliases_address_of(to_if_expr(rhs).false_case(), alias_set); } else if(rhs.id()==ID_dereference) { } } void escape_domaint::transform( const irep_idt &function_from, trace_ptrt trace_from, const irep_idt &function_to, trace_ptrt trace_to, ai_baset &ai, const namespacet &ns) { locationt from{trace_from->current_location()}; if(has_values.is_false()) return; // upcast of ai // escape_analysist &ea= // static_cast<escape_analysist &>(ai); const goto_programt::instructiont &instruction=*from; switch(instruction.type) { case ASSIGN: { const code_assignt &code_assign=to_code_assign(instruction.code); std::set<irep_idt> cleanup_functions; get_rhs_cleanup(code_assign.rhs(), cleanup_functions); assign_lhs_cleanup(code_assign.lhs(), cleanup_functions); std::set<irep_idt> rhs_aliases; get_rhs_aliases(code_assign.rhs(), rhs_aliases); assign_lhs_aliases(code_assign.lhs(), rhs_aliases); } break; case DECL: { const code_declt &code_decl=to_code_decl(instruction.code); aliases.isolate(code_decl.get_identifier()); assign_lhs_cleanup(code_decl.symbol(), std::set<irep_idt>()); } break; case DEAD: { const code_deadt &code_dead=to_code_dead(instruction.code); aliases.isolate(code_dead.get_identifier()); assign_lhs_cleanup(code_dead.symbol(), std::set<irep_idt>()); } break; case FUNCTION_CALL: { const code_function_callt &code_function_call= to_code_function_call(instruction.code); const exprt &function=code_function_call.function(); if(function.id()==ID_symbol) { const irep_idt &identifier=to_symbol_expr(function).get_identifier(); if(identifier == CPROVER_PREFIX "cleanup") { if(code_function_call.arguments().size()==2) { exprt lhs=code_function_call.arguments()[0]; irep_idt cleanup_function= get_function(code_function_call.arguments()[1]); if(!cleanup_function.empty()) { // may alias other stuff std::set<irep_idt> lhs_set; get_rhs_aliases(lhs, lhs_set); for(const auto &l : lhs_set) { cleanup_map[l].cleanup_functions.insert(cleanup_function); } } } } } } break; case END_FUNCTION: // This is the edge to the call site. break; case GOTO: // Ignoring the guard is a valid over-approximation break; case CATCH: case THROW: DATA_INVARIANT(false, "Exceptions must be removed before analysis"); break; case RETURN: DATA_INVARIANT(false, "Returns must be removed before analysis"); break; case ATOMIC_BEGIN: // Ignoring is a valid over-approximation case ATOMIC_END: // Ignoring is a valid over-approximation case LOCATION: // No action required case START_THREAD: // Require a concurrent analysis at higher level case END_THREAD: // Require a concurrent analysis at higher level case ASSERT: // No action required case ASSUME: // Ignoring is a valid over-approximation case SKIP: // No action required break; case OTHER: #if 0 DATA_INVARIANT(false, "Unclear what is a safe over-approximation of OTHER"); #endif break; case INCOMPLETE_GOTO: case NO_INSTRUCTION_TYPE: DATA_INVARIANT(false, "Only complete instructions can be analyzed"); break; } } void escape_domaint::output( std::ostream &out, const ai_baset &, const namespacet &) const { if(has_values.is_known()) { out << has_values.to_string() << '\n'; return; } for(const auto &cleanup : cleanup_map) { out << cleanup.first << ':'; for(const auto &id : cleanup.second.cleanup_functions) out << ' ' << id; out << '\n'; } for(aliasest::const_iterator a_it1=aliases.begin(); a_it1!=aliases.end(); a_it1++) { bool first=true; for(aliasest::const_iterator a_it2=aliases.begin(); a_it2!=aliases.end(); a_it2++) { if(aliases.is_root(a_it1) && a_it1!=a_it2 && aliases.same_set(a_it1, a_it2)) { if(first) { out << "Aliases: " << *a_it1; first=false; } out << ' ' << *a_it2; } } if(!first) out << '\n'; } } bool escape_domaint::merge( const escape_domaint &b, locationt, locationt) { bool changed=has_values.is_false(); has_values=tvt::unknown(); for(const auto &cleanup : b.cleanup_map) { const std::set<irep_idt> &b_cleanup=cleanup.second.cleanup_functions; std::set<irep_idt> &a_cleanup=cleanup_map[cleanup.first].cleanup_functions; auto old_size=a_cleanup.size(); a_cleanup.insert(b_cleanup.begin(), b_cleanup.end()); if(a_cleanup.size()!=old_size) changed=true; } // kill empty ones for(cleanup_mapt::iterator a_it=cleanup_map.begin(); a_it!=cleanup_map.end(); ) // no a_it++ { if(a_it->second.cleanup_functions.empty()) a_it=cleanup_map.erase(a_it); else a_it++; } // do union for(aliasest::const_iterator it=b.aliases.begin(); it!=b.aliases.end(); it++) { irep_idt b_root=b.aliases.find(it); if(!aliases.same_set(*it, b_root)) { aliases.make_union(*it, b_root); changed=true; } } // isolate non-tracked ones #if 0 for(aliasest::const_iterator it=aliases.begin(); it!=aliases.end(); it++) { if(cleanup_map.find(*it)==cleanup_map.end()) aliases.isolate(it); } #endif return changed; } void escape_domaint::check_lhs( const exprt &lhs, std::set<irep_idt> &cleanup_functions) const { if(lhs.id()==ID_symbol) { const irep_idt &identifier=to_symbol_expr(lhs).get_identifier(); // pointer with cleanup function? const escape_domaint::cleanup_mapt::const_iterator m_it= cleanup_map.find(identifier); if(m_it!=cleanup_map.end()) { // count the aliases std::size_t count=0; for(const auto &alias : aliases) { if(alias!=identifier && aliases.same_set(alias, identifier)) count+=1; } // There is an alias? Then we are still ok. if(count==0) { cleanup_functions.insert( m_it->second.cleanup_functions.begin(), m_it->second.cleanup_functions.end()); } } } } void escape_analysist::insert_cleanup( goto_functionst::goto_functiont &goto_function, goto_programt::targett location, const exprt &lhs, const std::set<irep_idt> &cleanup_functions, bool is_object, const namespacet &ns) { source_locationt source_location=location->source_location; for(const auto &cleanup : cleanup_functions) { symbol_exprt function=ns.lookup(cleanup).symbol_expr(); const code_typet &function_type=to_code_type(function.type()); goto_function.body.insert_before_swap(location); code_function_callt code(function); code.function().add_source_location()=source_location; if(function_type.parameters().size()==1) { typet param_type=function_type.parameters().front().type(); exprt arg=lhs; if(is_object) arg=address_of_exprt(arg); arg = typecast_exprt::conditional_cast(arg, param_type); code.arguments().push_back(arg); } *location = goto_programt::make_function_call(code, source_location); } } void escape_analysist::instrument( goto_modelt &goto_model) { const namespacet ns(goto_model.symbol_table); for(auto &gf_entry : goto_model.goto_functions.function_map) { Forall_goto_program_instructions(i_it, gf_entry.second.body) { get_state(i_it); const goto_programt::instructiont &instruction=*i_it; if(instruction.type == ASSIGN) { const code_assignt &code_assign = to_code_assign(instruction.code); std::set<irep_idt> cleanup_functions; operator[](i_it).check_lhs(code_assign.lhs(), cleanup_functions); insert_cleanup( gf_entry.second, i_it, code_assign.lhs(), cleanup_functions, false, ns); } else if(instruction.type == DEAD) { const code_deadt &code_dead = to_code_dead(instruction.code); std::set<irep_idt> cleanup_functions1; const escape_domaint &d = operator[](i_it); const escape_domaint::cleanup_mapt::const_iterator m_it = d.cleanup_map.find("&" + id2string(code_dead.get_identifier())); // does it have a cleanup function for the object? if(m_it != d.cleanup_map.end()) { cleanup_functions1.insert( m_it->second.cleanup_functions.begin(), m_it->second.cleanup_functions.end()); } std::set<irep_idt> cleanup_functions2; d.check_lhs(code_dead.symbol(), cleanup_functions2); insert_cleanup( gf_entry.second, i_it, code_dead.symbol(), cleanup_functions1, true, ns); insert_cleanup( gf_entry.second, i_it, code_dead.symbol(), cleanup_functions2, false, ns); for(const auto &c : cleanup_functions1) { (void)c; i_it++; } for(const auto &c : cleanup_functions2) { (void)c; i_it++; } } } } }
25.238447
80
0.641863
[ "object", "transform" ]